├── tempdd ├── core │ ├── templates │ │ ├── __init__.py │ │ ├── template_prd_default.md │ │ ├── template_arch_default.md │ │ ├── template_tasks_simple.md │ │ ├── template_tasks_default.md │ │ ├── template_blueprint_simple.md │ │ ├── template_blueprint_default.md │ │ └── template_research_default.md │ └── configs │ │ ├── config_simple.yaml │ │ └── config_default.yaml ├── handlers │ ├── __init__.py │ ├── help.py │ ├── ai.py │ └── ui_helpers.py ├── __init__.py ├── integrations │ ├── claude │ │ └── .claude │ │ │ └── commands │ │ │ └── tempdd-go.md │ ├── cursor │ │ └── .cursor │ │ │ └── commands │ │ │ └── tempdd-go.md │ ├── gemini │ │ └── .gemini │ │ │ └── commands │ │ │ └── tempdd-go.toml │ └── copilot │ │ └── .github │ │ └── prompts │ │ └── tempdd-go.prompt.md ├── utils.py ├── cli.py ├── template_parser.py ├── file_manager.py └── controller.py ├── tests ├── __init__.py ├── conftest.py ├── test_commands.py ├── test_template_parser.py └── test_controller.py ├── misc └── banner.png ├── docs ├── test_guideline.md └── readmes │ ├── README-zh-CN.md │ ├── README-zh-TW.md │ ├── README-ja.md │ └── README-es.md ├── LICENSE ├── customized ├── workflow_example │ ├── config.yaml │ └── templates │ │ ├── prd.md │ │ ├── tasks.md │ │ └── blueprint.md └── README.md ├── pyproject.toml ├── .gitignore └── README.md /tempdd/core/templates/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Test package for TempDD.""" -------------------------------------------------------------------------------- /tempdd/handlers/__init__.py: -------------------------------------------------------------------------------- 1 | """Commands package for TempDD CLI.""" -------------------------------------------------------------------------------- /misc/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitYCC/TempDD/HEAD/misc/banner.png -------------------------------------------------------------------------------- /tempdd/__init__.py: -------------------------------------------------------------------------------- 1 | """TempDD - Template-Driven Development CLI framework.""" 2 | 3 | __version__ = "0.1.0" -------------------------------------------------------------------------------- /tempdd/handlers/help.py: -------------------------------------------------------------------------------- 1 | """Help command handler for TempDD.""" 2 | 3 | import logging 4 | from tempdd.controller import Controller 5 | 6 | 7 | def help_command() -> int: 8 | """ 9 | Handle help command 10 | 11 | Returns: 12 | int: Exit code (0 for success, 1 for error) 13 | """ 14 | logger = logging.getLogger(__name__) 15 | 16 | try: 17 | controller = Controller() 18 | help_content = controller.get_help_content() 19 | print(help_content) 20 | return 0 21 | 22 | except Exception as e: 23 | logger.error(f"Failed to get help content: {e}") 24 | return 1 25 | -------------------------------------------------------------------------------- /tempdd/integrations/claude/.claude/commands/tempdd-go.md: -------------------------------------------------------------------------------- 1 | # TempDD Command Entrypoint 2 | 3 | Follow these steps: 4 | 5 | 1. **Check Arguments**: If `$ARGUMENTS` is "help" or empty, run `tempdd help` to get the output content and display the output with preferred language. Then stop - do not execute further steps. 6 | 2. **Execute Command**: Otherwise, run `tempdd ai "$ARGUMENTS"` 7 | 3. **Get Instruction**: Get the AI execution instruction from the command's standard output. 8 | 4. **Strict Execution**: Follow the retrieved instruction exactly, without adding any extra operations. 9 | 10 | Note: The format is `tempdd ai " "`, for example: 11 | - `tempdd ai "prd build"` 12 | - `tempdd ai "arch build"` 13 | - `tempdd ai "tasks build"` 14 | - `tempdd ai "tasks run"` 15 | -------------------------------------------------------------------------------- /tempdd/integrations/cursor/.cursor/commands/tempdd-go.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: TempDD Command Entrypoint 3 | --- 4 | 5 | Follow these steps: 6 | 7 | 1. **Check Arguments**: If `$ARGUMENTS` is "help" or empty, run `tempdd help` to get the output content and display the output with preferred language. Then stop - do not execute further steps. 8 | 2. **Execute Command**: Otherwise, run `tempdd ai "$ARGUMENTS"` 9 | 3. **Get Instruction**: Get the AI execution instruction from the command's standard output. 10 | 4. **Strict Execution**: Follow the retrieved instruction exactly, without adding any extra operations. 11 | 12 | Note: The format is `tempdd ai " "`, for example: 13 | - `tempdd ai "prd build"` 14 | - `tempdd ai "arch build"` 15 | - `tempdd ai "tasks build"` 16 | - `tempdd ai "tasks run"` 17 | -------------------------------------------------------------------------------- /tempdd/integrations/gemini/.gemini/commands/tempdd-go.toml: -------------------------------------------------------------------------------- 1 | description = "TempDD Command Entrypoint" 2 | 3 | prompt = """Follow these steps: 4 | 5 | 1. **Check Arguments**: If `$ARGUMENTS` is "help" or empty, run `tempdd help` to get the output content and display the output with preferred language. Then stop - do not execute further steps. 6 | 2. **Execute Command**: Otherwise, run `tempdd ai "$ARGUMENTS"` 7 | 3. **Get Instruction**: Get the AI execution instruction from the command's standard output. 8 | 4. **Strict Execution**: Follow the retrieved instruction exactly, without adding any extra operations. 9 | 10 | Note: The format is `tempdd ai " "`, for example: 11 | - `tempdd ai "prd build"` 12 | - `tempdd ai "arch build"` 13 | - `tempdd ai "tasks build"` 14 | - `tempdd ai "tasks run"` 15 | """ -------------------------------------------------------------------------------- /tempdd/integrations/copilot/.github/prompts/tempdd-go.prompt.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: TempDD Command Entrypoint 3 | --- 4 | 5 | Follow these steps: 6 | 7 | 1. **Check Arguments**: If `$ARGUMENTS` is "help" or empty, run `tempdd help` to get the output content and display the output with preferred language. Then stop - do not execute further steps. 8 | 2. **Execute Command**: Otherwise, run `tempdd ai "$ARGUMENTS"` 9 | 3. **Get Instruction**: Get the AI execution instruction from the command's standard output. 10 | 4. **Strict Execution**: Follow the retrieved instruction exactly, without adding any extra operations. 11 | 12 | Note: The format is `tempdd ai " "`, for example: 13 | - `tempdd ai "prd build"` 14 | - `tempdd ai "arch build"` 15 | - `tempdd ai "tasks build"` 16 | - `tempdd ai "tasks run"` 17 | -------------------------------------------------------------------------------- /docs/test_guideline.md: -------------------------------------------------------------------------------- 1 | # TempDD Testing Guidelines 2 | 3 | This document explains how to run end-to-end tests for the TempDD package. 4 | 5 | ## Test Environment Setup 6 | 7 | ### 1. Create Virtual Environment 8 | ```bash 9 | uv venv ENV 10 | ``` 11 | 12 | ### 2. Install Test Dependencies 13 | ```bash 14 | source ENV/bin/activate && uv pip install pytest pytest-mock pytest-cov 15 | ``` 16 | 17 | ### 3. Install TempDD in Development Mode 18 | ```bash 19 | source ENV/bin/activate && uv pip install -e . 20 | ``` 21 | 22 | ## Running Tests 23 | 24 | ### Run All Tests 25 | ```bash 26 | source ENV/bin/activate && python -m pytest tests/ -v 27 | ``` 28 | 29 | ### Run Specific Test File 30 | ```bash 31 | source ENV/bin/activate && python -m pytest tests/test_commands.py -v 32 | ``` 33 | 34 | ### Run Tests with Coverage Report 35 | ```bash 36 | source ENV/bin/activate && python -m pytest tests/ -v --cov=tempdd 37 | ``` 38 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | """Test configuration and fixtures.""" 2 | import pytest 3 | import tempfile 4 | import shutil 5 | from pathlib import Path 6 | 7 | 8 | @pytest.fixture 9 | def temp_project_dir(): 10 | """Create a temporary directory for testing TempDD projects.""" 11 | temp_dir = tempfile.mkdtemp() 12 | yield Path(temp_dir) 13 | shutil.rmtree(temp_dir, ignore_errors=True) 14 | 15 | 16 | @pytest.fixture 17 | def sample_config(): 18 | """Sample TempDD configuration for testing.""" 19 | return { 20 | "language": "en", 21 | "stages": ["prd", "arch"], 22 | "flow": { 23 | "prd": { 24 | "template": "prd_template", 25 | "agent": "prd_agent", 26 | "preprocess": "preprocess_default" 27 | }, 28 | "arch": { 29 | "template": "arch_template", 30 | "agent": "arch_agent", 31 | "preprocess": "preprocess_default" 32 | } 33 | }, 34 | "current_target_document": None 35 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 陳宜昌 Yi-Chang Chen (YC) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /customized/workflow_example/config.yaml: -------------------------------------------------------------------------------- 1 | description: "Simple flow of software development, including PRD, Arch., Tasks stages." 2 | help: | 3 | 1. PRD (Product Requirements Document) 4 | - Use '/tempdd-go prd build' to create product requirements 5 | 6 | 2. Blueprint Document 7 | - Use '/tempdd-go blueprint build' to create implementation blueprint 8 | 9 | 3. Tasks Document & Implementation 10 | - Use '/tempdd-go tasks build' to break down implementation tasks 11 | - Use '/tempdd-go tasks run' to implement the planned tasks 12 | 13 | Stage Actions: 14 | build - Create/build the document for the stage 15 | run - Execute the implementation (for tasks stage) 16 | 17 | Each stage builds upon the previous one, creating a structured development workflow from requirements to implementation. 18 | 19 | language: en 20 | logging_level: WARNING 21 | stages: 22 | - prd 23 | - blueprint 24 | - tasks 25 | define: 26 | prd: 27 | template: templates/prd.md 28 | input_symbols: null 29 | output_symbol: PATH_PRD 30 | blueprint: 31 | template: templates/blueprint.md 32 | input_symbols: 33 | - PATH_PRD 34 | output_symbol: PATH_BLUEPRINT 35 | tasks: 36 | template: templates/tasks.md 37 | input_symbols: 38 | - PATH_PRD 39 | - PATH_BLUEPRINT 40 | output_symbol: null 41 | -------------------------------------------------------------------------------- /tempdd/core/configs/config_simple.yaml: -------------------------------------------------------------------------------- 1 | description: "Simple flow of software development, including PRD, Blueprint, Tasks stages." 2 | help: | 3 | 1. PRD (Product Requirements Document) 4 | - Use '/tempdd-go prd build' to create product requirements 5 | 6 | 2. Blueprint Document 7 | - Use '/tempdd-go blueprint build' to create implementation blueprint 8 | 9 | 3. Tasks Document & Implementation 10 | - Use '/tempdd-go tasks build' to break down implementation tasks 11 | - Use '/tempdd-go tasks run' to implement the planned tasks 12 | 13 | Stage Actions: 14 | build - Create/build the document for the stage 15 | run - Execute the implementation (for tasks stage) 16 | 17 | Each stage builds upon the previous one, creating a structured development workflow from requirements to implementation. 18 | 19 | language: en 20 | logging_level: WARNING 21 | stages: 22 | - prd 23 | - blueprint 24 | - tasks 25 | 26 | define: 27 | prd: 28 | template: template_prd_default 29 | input_symbols: null 30 | output_symbol: PATH_PRD 31 | blueprint: 32 | template: template_blueprint_simple 33 | input_symbols: 34 | - PATH_PRD 35 | output_symbol: PATH_BLUEPRINT 36 | tasks: 37 | template: template_tasks_simple 38 | input_symbols: 39 | - PATH_PRD 40 | - PATH_BLUEPRINT 41 | output_symbol: null -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [tool.setuptools.packages.find] 6 | exclude = ["ENV*", "tests*"] 7 | 8 | [tool.setuptools.package-data] 9 | "tempdd.core.configs" = ["*.yaml"] 10 | "tempdd.core.templates" = ["*.md"] 11 | "tempdd.integrations.claude" = [".claude/commands/*.md"] 12 | "tempdd.integrations.gemini" = [".gemini/commands/*.toml"] 13 | "tempdd.integrations.cursor" = [".cursor/commands/*.md"] 14 | "tempdd.integrations.copilot" = [".github/prompts/*.md"] 15 | 16 | [project] 17 | name = "tempdd" 18 | version = "0.1.3" 19 | description = "Template-Driven Development Framework for AI-Augmented Coding" 20 | authors = [{name = "Yi-Chang Chen"}] 21 | license = {text = "MIT"} 22 | readme = "README.md" 23 | requires-python = ">=3.8" 24 | classifiers = [ 25 | "Development Status :: 3 - Alpha", 26 | "Intended Audience :: Developers", 27 | "License :: OSI Approved :: MIT License", 28 | "Programming Language :: Python :: 3", 29 | "Programming Language :: Python :: 3.8", 30 | "Programming Language :: Python :: 3.9", 31 | "Programming Language :: Python :: 3.10", 32 | "Programming Language :: Python :: 3.11", 33 | "Programming Language :: Python :: 3.12", 34 | ] 35 | dependencies = [ 36 | 'PyYAML', 37 | 'readchar>=4.0.0', 38 | 'rich>=10.0.0' 39 | ] 40 | 41 | [project.scripts] 42 | tempdd = "tempdd.cli:main" 43 | 44 | [project.urls] 45 | Homepage = "https://github.com/GitYCC/TempDD" 46 | Repository = "https://github.com/GitYCC/TempDD" -------------------------------------------------------------------------------- /tempdd/utils.py: -------------------------------------------------------------------------------- 1 | """Common utilities for TempDD handlers.""" 2 | 3 | import json 4 | from pathlib import Path 5 | from typing import Tuple 6 | from tempdd.file_manager import FileManager 7 | 8 | 9 | def load_config() -> dict: 10 | """Load the TempDD configuration file.""" 11 | file_manager = FileManager() 12 | config_path = file_manager.get_project_config_path() 13 | 14 | if not config_path.exists(): 15 | raise FileNotFoundError( 16 | f"TempDD configuration not found: {config_path}. Please run 'tempdd init' first." 17 | ) 18 | 19 | with open(config_path, "r", encoding="utf-8") as f: 20 | return json.load(f) 21 | 22 | 23 | def validate_stage(stage: str, config: dict) -> Tuple[bool, str]: 24 | """ 25 | Validate if a stage exists in the configuration. 26 | 27 | Returns: 28 | Tuple[bool, str]: (is_valid, error_message) 29 | """ 30 | # Check if stage exists in stages list or flow configuration 31 | stages = config.get("stages", []) 32 | flow = config.get("flow", {}) 33 | 34 | if stage in stages or stage in flow: 35 | return True, "" 36 | else: 37 | return False, f"Stage '{stage}' not found in configuration" 38 | 39 | 40 | def process_template(template_content: str, context: dict) -> str: 41 | """Process template with context variables.""" 42 | processed_content = template_content 43 | 44 | # Replace template variables 45 | for key, value in context.items(): 46 | placeholder = f"{{{{{key}}}}}" 47 | processed_content = processed_content.replace(placeholder, str(value)) 48 | 49 | return processed_content 50 | -------------------------------------------------------------------------------- /tempdd/core/configs/config_default.yaml: -------------------------------------------------------------------------------- 1 | description: "Default flow of software development, including PRD, Arch., Research, BluePrint, Tasks stages." 2 | help: | 3 | 1. PRD (Product Requirements Document) 4 | - Use '/tempdd-go prd build' to create product requirements 5 | 6 | 2. Architecture Document 7 | - Use '/tempdd-go arch build' to design system architecture 8 | 9 | 3. Research Document 10 | - Use '/tempdd-go research build' to conduct technical research 11 | 12 | 4. Blueprint Document 13 | - Use '/tempdd-go blueprint build' to create detailed implementation blueprint 14 | 15 | 5. Tasks Document & Implementation 16 | - Use '/tempdd-go tasks build' to break down implementation tasks 17 | - Use '/tempdd-go tasks run' to implement the planned tasks 18 | 19 | Stage Actions: 20 | build - Create/build the document for the stage 21 | run - Execute the implementation (for tasks stage) 22 | 23 | Each stage builds upon the previous one, creating a structured development workflow from requirements to implementation. 24 | 25 | language: en 26 | logging_level: WARNING 27 | stages: 28 | - prd 29 | - arch 30 | - research 31 | - blueprint 32 | - tasks 33 | 34 | define: 35 | prd: 36 | template: template_prd_default 37 | input_symbols: null 38 | output_symbol: PATH_PRD 39 | arch: 40 | template: template_arch_default 41 | input_symbols: 42 | - PATH_PRD 43 | output_symbol: PATH_ARCH 44 | research: 45 | template: template_research_default 46 | input_symbols: 47 | - PATH_PRD 48 | - PATH_ARCH 49 | output_symbol: PATH_RESEARCH 50 | blueprint: 51 | template: template_blueprint_default 52 | input_symbols: 53 | - PATH_PRD 54 | - PATH_ARCH 55 | - PATH_RESEARCH 56 | output_symbol: PATH_BLUEPRINT 57 | tasks: 58 | template: template_tasks_default 59 | input_symbols: 60 | - PATH_PRD 61 | - PATH_ARCH 62 | - PATH_RESEARCH 63 | - PATH_BLUEPRINT 64 | output_symbol: null -------------------------------------------------------------------------------- /tempdd/handlers/ai.py: -------------------------------------------------------------------------------- 1 | """AI command implementation.""" 2 | 3 | import sys 4 | import logging 5 | from pathlib import Path 6 | from tempdd.controller import Controller 7 | 8 | 9 | # AI Instruction Templates 10 | AI_INSTRUCTION_START = "[AI_INSTRUCTION_START]" 11 | AI_INSTRUCTION_END = "[AI_INSTRUCTION_END]" 12 | 13 | 14 | def format_ai_instruction(content: str) -> str: 15 | """Format content as AI instruction with start/end markers.""" 16 | return f"""{AI_INSTRUCTION_START} 17 | {content} 18 | {AI_INSTRUCTION_END}""" 19 | 20 | 21 | def _load_controller(config_path: str = None): 22 | """ 23 | Load the unified Controller. 24 | 25 | Args: 26 | config_path: Optional path to configuration file 27 | 28 | Returns: 29 | Controller instance 30 | 31 | Raises: 32 | FileNotFoundError: When configuration file is not found 33 | """ 34 | return Controller(config_path) 35 | 36 | 37 | def ai_command(command_str: str) -> int: 38 | """ 39 | Handle AI command with stage and action. 40 | 41 | Args: 42 | command_str: Command string in format "stage action" (e.g., "prd build") 43 | 44 | Returns: 45 | Exit code (0 for success, 1 for error) 46 | """ 47 | try: 48 | # Parse command string "stage action" 49 | parts = command_str.strip().split() 50 | if len(parts) != 2: 51 | logger = logging.getLogger(__name__) 52 | logger.error( 53 | f"Invalid command format. Expected 'stage action', got: '{command_str}'" 54 | ) 55 | logger.info("Examples: 'prd build', 'arch run'") 56 | return 1 57 | 58 | stage, action = parts 59 | 60 | # Load controller and process command 61 | controller = _load_controller() 62 | instruction_content = controller.process_command(stage, action) 63 | 64 | # Format the instruction with AI markers 65 | ai_instruction = format_ai_instruction(instruction_content) 66 | 67 | # Output the AI instruction 68 | print(ai_instruction) # This should remain as print for CLI output 69 | return 0 70 | 71 | except FileNotFoundError as e: 72 | logger = logging.getLogger(__name__) 73 | logger.error( 74 | f"A required file was not found. Please check your configuration and templates.\nDetails: {e}" 75 | ) 76 | return 1 77 | except ValueError as e: 78 | logger = logging.getLogger(__name__) 79 | logger.error(f"Invalid value or configuration provided.\nDetails: {e}") 80 | return 1 81 | except Exception as e: 82 | logger = logging.getLogger(__name__) 83 | logger.error(f"An unexpected error occurred: {e}") 84 | return 1 85 | -------------------------------------------------------------------------------- /docs/readmes/README-zh-CN.md: -------------------------------------------------------------------------------- 1 | # Template-Driven Development Framework for AI-Augmented Coding 2 | 3 | ![banner](../../misc/banner.png) 4 | 5 | ## 概述 6 | 7 | TempDD是一个模板驱动的开发框架,通过可定制的工作流程和智能引导的模板交互,实现结构化的人机协作。 8 | 9 | 随着项目复杂性的增加,AI智能体面临独立操作的挑战,使得人机协作变得越来越重要。开发者需要有效的工具来与这些黑盒AI智能体进行沟通。模板驱动的方法提供了结构化沟通,减少认知负担,并通过引导式工作流程实现一致的AI协作。本仓库提供了一个框架,允许用户根据其开发项目定制工作流程,将过程简化为一系列模板填写任务。该框架结合了智能体机制来降低模板复杂性,使AI智能体能够有效地协助用户完成文档编写。我们预期这个框架适用于各种开发场景,甚至非开发环境,同时促进开源协作以整合全球知识。 10 | 11 | ## 特性 12 | 13 | - 📚 **通过分层文档逐步掌握AI** - 通过复杂的多层文档从AI用户转变为AI专家,放大您对AI行为的控制 14 | - 📋 **可定制的模板驱动工作流程** - 通过可定制模板进行项目开发的结构化方法 15 | - 💬 **可定制的智能引导模板交互** - 可定制智能体适应每个模板,提供交互式指导帮助用户协作填写模板 16 | - 🤖 **跨AI工具集成** - 与Claude Code、Gemini CLI、Cursor和GitHub Copilot无缝集成 17 | - 🌐 **多语言支持** - 用户可以使用他们偏好的语言填写模板 18 | 19 | ## 快速开始 20 | 21 | ### 1. 安装 22 | 23 | 使用uv安装`tempdd`: 24 | 25 | ```bash 26 | uv tool install --force --from git+https://github.com/GitYCC/TempDD.git tempdd && exec $SHELL 27 | ``` 28 | 29 | ### 2. 初始化项目 30 | 31 | 创建新的项目目录并初始化TempDD: 32 | 33 | ```bash 34 | mkdir demo 35 | cd demo 36 | tempdd init # 您可以在初始化期间选择内置工作流程和首选AI工具 37 | ``` 38 | 39 | ### 3. 示例:使用Claude Code的默认工作流程 40 | 41 | 以下示例演示了如何使用Claude Code的默认工作流程。有关详细的自定义选项和可用工作流程,请参考`tempdd help`。 42 | 43 | 进入Claude Code后,按顺序执行以下命令: 44 | 45 | ```bash 46 | # 获取帮助并了解可用命令 47 | /tempdd-go help 48 | 49 | # 生成产品需求文档 50 | /tempdd-go prd build 51 | 52 | # 完成PRD后,创建架构设计 53 | /tempdd-go arch build 54 | 55 | # 完成架构设计文档后,进行研究 56 | /tempdd-go research build 57 | 58 | # 完成研究报告后,构建实施蓝图 59 | /tempdd-go blueprint build 60 | 61 | # 完成蓝图后,生成任务列表 62 | /tempdd-go tasks build 63 | 64 | # 完成任务列表后,执行任务以生成代码 65 | /tempdd-go tasks run 66 | ``` 67 | 68 | 从这个示例中,您可以看到开发过程从想法到实现通过多层文档进行。每个文档由AI在需要时向用户询问输入来填写,这减少了用户填表的复杂性,同时增强了AI与人类之间的共识。值得注意的是,研究步骤涉及AI主动在线搜索信息以提高其对实施的理解。我相信存在更好的工作流程,我们不应该期望一个工作流程满足每个项目。因此,该框架设计为易于定制。请参考["定制您的工作流程"](#定制您的工作流程)部分了解更多。 69 | 70 | ## 定制您的工作流程 71 | 72 | TempDD允许您创建适合特定开发需求的自定义工作流程。 73 | 74 | 按照以下步骤定制您的工作流程: 75 | 1. **阅读指南**:查看[./customized/](../../customized/)获取全面的工作流程创建说明 76 | 2. **创建您的工作流程**,遵循提供的结构和示例 77 | 3. **使用自定义工作流程初始化项目**: 78 | 79 | ```bash 80 | tempdd init --workflow /path/to/your/custom/workflow_dir/ 81 | ``` 82 | 83 | ## 贡献内置工作流程 84 | 85 | 我们鼓励贡献者帮助扩展TempDD的内置工作流程集合!通过贡献新的工作流程,您可以帮助其他开发者从经过验证的开发模式和专业领域工作流程中受益。 86 | 87 | ### 如何贡献新的内置工作流程 88 | 89 | 1. **Fork此仓库** - 创建您自己的fork进行工作 90 | 2. **添加您的工作流程文件**: 91 | - 将新的配置文件添加到`./tempdd/core/configs/` 92 | - 将相应的模板添加到`./tempdd/core/templates/` 93 | 3. **提交Pull Request** - 与社区分享您的工作流程 94 | 95 | 您的贡献将帮助TempDD对不同领域和用例的开发者更有价值。无论是移动开发、数据科学、DevOps还是任何其他专业化工作流程,我们都欢迎您的专业知识! 96 | 97 | ## 跨AI工具集成 98 | 99 | TempDD与多个AI开发工具无缝集成: 100 | 101 | | AI工具 | 状态 | 102 | |---------|--------| 103 | | **Claude Code** | ✅ 完全支持 | 104 | | **Gemini CLI** | ✅ 完全支持 | 105 | | **Cursor** | ✅ 完全支持 | 106 | | **GitHub Copilot** | ✅ 完全支持 | 107 | 108 | ## 致谢 109 | 110 | 感谢以下仓库的启发: 111 | - [github/spec-kit](https://github.com/github/spec-kit) 112 | - [coleam00/context-engineering-intro](https://github.com/coleam00/context-engineering-intro) -------------------------------------------------------------------------------- /docs/readmes/README-zh-TW.md: -------------------------------------------------------------------------------- 1 | # Template-Driven Development Framework for AI-Augmented Coding 2 | 3 | ![banner](../../misc/banner.png) 4 | 5 | ## 概述 6 | 7 | TempDD 是一個「模板驅動」的開發框架,透過可自訂的工作流程與智慧引導的模板互動,讓人與 AI 可以更有結構地協作。 8 | 9 | 隨著專案越來越複雜,AI 想要獨立完成任務變得困難,人機協作的重要性因此提升。開發者需要一種更有效的方式來與這些像黑盒般的 AI Agent 溝通。模板驅動的方法能提供清楚的結構,減輕使用者的思考負擔,並透過引導式流程確保人機協作的一致性。這個框架提供了一個基礎,讓使用者能依照自己的專案需求,客製化整個工作流程,並把複雜的過程化繁為簡,拆解成一系列「填寫模板」的任務。同時,它也結合了 Agent 機制來降低模板的複雜度,使 AI 能更有效率地協助使用者完成文件與開發相關工作。我們期望這個框架不只適用於各種軟體開發場景,也能延伸到非開發的情境。同時,也希望透過開源協作,匯聚全球知識並持續完善這個框架。 10 | 11 | ## 特性 12 | 13 | - 📚 **透過分層文件逐步掌握AI** - 透過複雜的多層文件從AI使用者轉變為AI專家,放大您對AI行為的控制 14 | - 📋 **可客製化的模板驅動工作流程** - 透過可客製化模板進行專案開發的結構化方法 15 | - 💬 **可客製化的智慧引導模板互動** - 可客製化智慧體適應每個模板,提供互動式指導幫助使用者協作填寫模板 16 | - 🤖 **跨AI工具整合** - 與Claude Code、Gemini CLI、Cursor和GitHub Copilot無縫整合 17 | - 🌐 **多語言支援** - 使用者可以使用他們偏好的語言填寫模板 18 | 19 | ## 快速開始 20 | 21 | ### 1. 安裝 22 | 23 | 使用uv安裝`tempdd`: 24 | 25 | ```bash 26 | uv tool install --force --from git+https://github.com/GitYCC/TempDD.git tempdd && exec $SHELL 27 | ``` 28 | 29 | ### 2. 初始化專案 30 | 31 | 建立新的專案目錄並初始化TempDD: 32 | 33 | ```bash 34 | mkdir demo 35 | cd demo 36 | tempdd init # 您可以在初始化期間選擇內建工作流程和偏好的AI工具 37 | ``` 38 | 39 | ### 3. 範例:使用Claude Code的預設工作流程 40 | 41 | 以下範例演示了如何使用Claude Code的預設工作流程。有關詳細的客製化選項和可用工作流程,請參考`tempdd help`。 42 | 43 | 進入Claude Code後,按順序執行以下指令: 44 | 45 | ```bash 46 | # 取得說明並了解可用指令 47 | /tempdd-go help 48 | 49 | # 產生產品需求文件 50 | /tempdd-go prd build 51 | 52 | # 完成PRD後,建立架構設計 53 | /tempdd-go arch build 54 | 55 | # 完成架構設計文件後,進行研究 56 | /tempdd-go research build 57 | 58 | # 完成研究報告後,建構實施藍圖 59 | /tempdd-go blueprint build 60 | 61 | # 完成藍圖後,產生任務清單 62 | /tempdd-go tasks build 63 | 64 | # 完成任務清單後,執行任務以產生程式碼 65 | /tempdd-go tasks run 66 | ``` 67 | 68 | 從這個範例中,您可以看到開發過程從想法到實作透過多層文件進行。每個文件由AI在需要時向使用者詢問輸入來填寫,這減少了使用者填表的複雜性,同時增強了AI與人類之間的共識。值得注意的是,研究步驟涉及AI主動在線搜索資訊以提高其對實作的理解。我相信存在更好的工作流程,我們不應該期望一個工作流程滿足每個專案。因此,該框架設計為易於客製化。請參考["客製化您的工作流程"](#客製化您的工作流程)部分了解更多。 69 | 70 | ## 客製化您的工作流程 71 | 72 | TempDD允許您建立適合特定開發需求的自訂工作流程。 73 | 74 | 按照以下步驟客製化您的工作流程: 75 | 1. **閱讀指南**:查看[./customized/](../../customized/)取得全面的工作流程建立說明 76 | 2. **建立您的工作流程**,遵循提供的結構和範例 77 | 3. **使用自訂工作流程初始化專案**: 78 | 79 | ```bash 80 | tempdd init --workflow /path/to/your/custom/workflow_dir/ 81 | ``` 82 | 83 | ## 貢獻內建工作流程 84 | 85 | 我們鼓勵貢獻者幫助擴展TempDD的內建工作流程集合!透過貢獻新的工作流程,您可以幫助其他開發者從經過驗證的開發模式和專業領域工作流程中受益。 86 | 87 | ### 如何貢獻新的內建工作流程 88 | 89 | 1. **Fork此倉庫** - 建立您自己的fork進行工作 90 | 2. **新增您的工作流程檔案**: 91 | - 將新的設定檔案新增到`./tempdd/core/configs/` 92 | - 將對應的模板新增到`./tempdd/core/templates/` 93 | 3. **提交Pull Request** - 與社群分享您的工作流程 94 | 95 | 您的貢獻將幫助TempDD對不同領域和用例的開發者更有價值。無論是行動開發、資料科學、DevOps還是任何其他專業化工作流程,我們都歡迎您的專業知識! 96 | 97 | ## 跨AI工具整合 98 | 99 | TempDD與多個AI開發工具無縫整合: 100 | 101 | | AI工具 | 狀態 | 102 | |---------|--------| 103 | | **Claude Code** | ✅ 完全支援 | 104 | | **Gemini CLI** | ✅ 完全支援 | 105 | | **Cursor** | ✅ 完全支援 | 106 | | **GitHub Copilot** | ✅ 完全支援 | 107 | 108 | ## 致謝 109 | 110 | 感謝以下倉庫的啟發: 111 | - [github/spec-kit](https://github.com/github/spec-kit) 112 | - [coleam00/context-engineering-intro](https://github.com/coleam00/context-engineering-intro) -------------------------------------------------------------------------------- /docs/readmes/README-ja.md: -------------------------------------------------------------------------------- 1 | # Template-Driven Development Framework for AI-Augmented Coding 2 | 3 | ![banner](../../misc/banner.png) 4 | 5 | ## 概要 6 | 7 | TempDDは、カスタマイズ可能なワークフローとエージェントガイド付きテンプレートインタラクションを通じて、構造化された人間-AI協業を可能にするテンプレート駆動の開発フレームワークです。 8 | 9 | プロジェクトの複雑さが増すにつれて、AIエージェントは独立して動作することに課題を抱え、ヒューマン・イン・ザ・ループ協業がますます重要になっています。開発者は、これらのブラックボックスAIエージェントとコミュニケーションを取るための効果的なツールが必要です。テンプレート駆動のアプローチは構造化されたコミュニケーションを提供し、認知負荷を軽減し、ガイド付きワークフローを通じて一貫したAI協業を可能にします。このリポジトリは、ユーザーが開発プロジェクトに応じてワークフローをカスタマイズできるフレームワークを提供し、プロセスを一連のテンプレート記入タスクに簡素化します。フレームワークは、エージェントメカニズムを組み込んでテンプレートの複雑さを軽減し、AIエージェントがユーザーのドキュメント作成を効果的に支援できるようにします。私たちは、このフレームワークが様々な開発シナリオ、さらには非開発コンテキストに適用可能であり、グローバルな知識を統合するオープンソース協業を促進することを想定しています。 10 | 11 | ## 特徴 12 | 13 | - 📚 **レイヤー化されたドキュメントによる段階的AI習得** - AIの動作に対するコントロールを増幅する洗練されたマルチレイヤードキュメントにより、AIユーザーからAIマスターに変身 14 | - 📋 **カスタマイズ可能なテンプレート駆動ワークフロー** - カスタマイズ可能なテンプレートによるプロジェクト開発の構造化アプローチ 15 | - 💬 **カスタマイズ可能なエージェントガイド付きテンプレートインタラクション** - カスタマイズ可能なエージェントが各テンプレートに適応し、ユーザーが協力的にテンプレートを記入するためのインタラクティブなガイダンスを提供 16 | - 🤖 **クロスAIツール統合** - Claude Code、Gemini CLI、Cursor、GitHub Copilotとのシームレスな統合 17 | - 🌐 **多言語サポート** - ユーザーは好みの言語を使用してテンプレートを記入可能 18 | 19 | ## クイックスタート 20 | 21 | ### 1. インストール 22 | 23 | uvを使用して`tempdd`をインストール: 24 | 25 | ```bash 26 | uv tool install --force --from git+https://github.com/GitYCC/TempDD.git tempdd && exec $SHELL 27 | ``` 28 | 29 | ### 2. プロジェクトの初期化 30 | 31 | 新しいプロジェクトディレクトリを作成し、TempDDを初期化: 32 | 33 | ```bash 34 | mkdir demo 35 | cd demo 36 | tempdd init # 初期化中に組み込みワークフローと好みのAIツールを選択できます 37 | ``` 38 | 39 | ### 3. 例:Claude Codeでのデフォルトワークフロー 40 | 41 | 以下の例は、Claude Codeでデフォルトワークフローを使用することを示しています。詳細なカスタマイズオプションと利用可能なワークフローについては、`tempdd help`を参照してください。 42 | 43 | Claude Codeに入ったら、以下のコマンドを順番に実行: 44 | 45 | ```bash 46 | # ヘルプを取得し、利用可能なコマンドを理解 47 | /tempdd-go help 48 | 49 | # 製品要求ドキュメントを生成 50 | /tempdd-go prd build 51 | 52 | # PRDを完了後、アーキテクチャ設計を作成 53 | /tempdd-go arch build 54 | 55 | # アーキテクチャ設計ドキュメントを完了後、調査を実施 56 | /tempdd-go research build 57 | 58 | # 調査レポートを完了後、実装ブループリントを構築 59 | /tempdd-go blueprint build 60 | 61 | # ブループリントを完了後、タスクリストを生成 62 | /tempdd-go tasks build 63 | 64 | # タスクリストを完了後、タスクを実行してコードを生成 65 | /tempdd-go tasks run 66 | ``` 67 | 68 | この例から、開発が複数層のドキュメントを通じてアイデアから実装まで進行することがわかります。各ドキュメントは、必要に応じてAIがユーザーに入力を求めて記入され、これによりユーザーのフォーム記入の複雑さが軽減され、AIと人間の間の合意が強化されます。注目すべきは、調査ステップでAIが積極的にオンライン情報を検索して実装の理解を向上させることです。より良いワークフローが存在すると信じており、1つのワークフローがすべてのプロジェクトを満たすことを期待すべきではありません。そのため、このフレームワークは簡単にカスタマイズできるよう設計されています。詳細については、[「ワークフローをカスタマイズする」](#ワークフローをカスタマイズする)セクションを参照してください。 69 | 70 | ## ワークフローをカスタマイズする 71 | 72 | TempDDでは、特定の開発ニーズに合わせたカスタムワークフローを作成できます。 73 | 74 | ワークフローをカスタマイズするには以下の手順に従ってください: 75 | 1. **ガイドを読む**:包括的なワークフロー作成手順については[./customized/](../../customized/)を参照 76 | 2. **ワークフローを作成**し、提供された構造と例に従う 77 | 3. **カスタムワークフローでプロジェクトを初期化**: 78 | 79 | ```bash 80 | tempdd init --workflow /path/to/your/custom/workflow_dir/ 81 | ``` 82 | 83 | ## 組み込みワークフローへの貢献 84 | 85 | TempDDの組み込みワークフローコレクションの拡張にご協力ください!新しいワークフローを貢献することで、他の開発者が実証済みの開発パターンや専門ドメインワークフローから恩恵を受けられるよう支援できます。 86 | 87 | ### 新しい組み込みワークフローを貢献する方法 88 | 89 | 1. **このリポジトリをフォーク** - 作業用に独自のフォークを作成 90 | 2. **ワークフローファイルを追加**: 91 | - 新しい設定ファイルを`./tempdd/core/configs/`に追加 92 | - 対応するテンプレートを`./tempdd/core/templates/`に追加 93 | 3. **プルリクエストを送信** - コミュニティとワークフローを共有 94 | 95 | あなたの貢献により、TempDDは異なるドメインやユースケースの開発者にとってより価値のあるものになります。モバイル開発、データサイエンス、DevOps、その他の専門分野のワークフローであっても、あなたの専門知識を歓迎します! 96 | 97 | ## クロスAIツール統合 98 | 99 | TempDDは複数のAI開発ツールとシームレスに統合されます: 100 | 101 | | AIツール | ステータス | 102 | |---------|--------| 103 | | **Claude Code** | ✅ フルサポート | 104 | | **Gemini CLI** | ✅ フルサポート | 105 | | **Cursor** | ✅ フルサポート | 106 | | **GitHub Copilot** | ✅ フルサポート | 107 | 108 | ## 謝辞 109 | 110 | インスピレーションを与えてくれた以下のリポジトリに感謝: 111 | - [github/spec-kit](https://github.com/github/spec-kit) 112 | - [coleam00/context-engineering-intro](https://github.com/coleam00/context-engineering-intro) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | 170 | # Ruff stuff: 171 | .ruff_cache/ 172 | 173 | # PyPI configuration file 174 | .pypirc 175 | 176 | .DS_store -------------------------------------------------------------------------------- /tempdd/cli.py: -------------------------------------------------------------------------------- 1 | """Main CLI entry point for TempDD.""" 2 | 3 | import argparse 4 | import json 5 | import logging 6 | import sys 7 | 8 | from . import __version__ 9 | from tempdd.handlers.init import init_command 10 | from tempdd.handlers.ai import ai_command 11 | from tempdd.handlers.help import help_command 12 | from tempdd.file_manager import FileManager 13 | 14 | 15 | def create_parser() -> argparse.ArgumentParser: 16 | """Create the main argument parser.""" 17 | parser = argparse.ArgumentParser( 18 | prog="tempdd", 19 | description="Template-Driven Development CLI framework", 20 | formatter_class=argparse.RawDescriptionHelpFormatter, 21 | epilog=""" 22 | Examples: 23 | tempdd init # Initialize a new TempDD project 24 | tempdd ai "prd build" # Build PRD document 25 | tempdd ai "arch continue" # Continue architecture document 26 | tempdd ai "task run" # Run task document 27 | """, 28 | ) 29 | 30 | parser.add_argument("--version", action="version", version=f"TempDD {__version__}") 31 | 32 | subparsers = parser.add_subparsers(dest="command", help="Available commands") 33 | 34 | # Init command 35 | init_parser = subparsers.add_parser("init", help="Initialize a new TempDD project") 36 | init_parser.add_argument( 37 | "--force", 38 | action="store_true", 39 | help="Force initialization even if files already exist", 40 | ) 41 | init_parser.add_argument( 42 | "--workflow", 43 | help="Path to workflow directory (e.g., customized/workflow_example). If contains config.yaml, will copy entire workflow without interactive mode.", 44 | ) 45 | 46 | # AI command (replaces preprocess and agent) 47 | ai_parser = subparsers.add_parser("ai", help="Process stage with specified action") 48 | ai_parser.add_argument( 49 | "stage_action", 50 | help="Stage and action in format 'stage action' (e.g., 'prd build', 'arch continue')", 51 | ) 52 | 53 | # Help command 54 | help_parser = subparsers.add_parser( 55 | "help", help="Show help information about TempDD workflow" 56 | ) 57 | 58 | return parser 59 | 60 | 61 | def _get_logging_level_from_config() -> int: 62 | """Get logging level from configuration.""" 63 | try: 64 | file_manager = FileManager() 65 | 66 | # Try to load project config first 67 | project_config_path = file_manager.get_project_config_path() 68 | if project_config_path.exists(): 69 | with open(project_config_path, "r", encoding="utf-8") as f: 70 | config = json.load(f) 71 | else: 72 | # Fallback to default config 73 | default_config_path = file_manager.get_default_config_path() 74 | with open(default_config_path, "r", encoding="utf-8") as f: 75 | config = json.load(f) 76 | 77 | level_str = config.get("logging_level", "WARNING").upper() 78 | return getattr(logging, level_str, logging.WARNING) 79 | except (FileNotFoundError, json.JSONDecodeError, AttributeError): 80 | # If anything fails, default to WARNING 81 | return logging.WARNING 82 | 83 | 84 | def main() -> int: 85 | """Main CLI entry point.""" 86 | # Configure logging for CLI from configuration 87 | logging_level = _get_logging_level_from_config() 88 | logging.basicConfig( 89 | level=logging_level, 90 | format="%(levelname)s: %(message)s", 91 | handlers=[logging.StreamHandler()], 92 | ) 93 | 94 | parser = create_parser() 95 | args = parser.parse_args() 96 | 97 | if not args.command: 98 | parser.print_help() 99 | return 0 100 | 101 | try: 102 | if args.command == "init": 103 | return init_command( 104 | force=getattr(args, "force", False), 105 | workflow_path=getattr(args, "workflow", None), 106 | ) 107 | elif args.command == "ai": 108 | return ai_command(args.stage_action) 109 | elif args.command == "help": 110 | return help_command() 111 | else: 112 | logger = logging.getLogger(__name__) 113 | logger.error(f"Unknown command: {args.command}") 114 | return 1 115 | except KeyboardInterrupt: 116 | logger = logging.getLogger(__name__) 117 | logger.info("Operation cancelled by user") 118 | return 1 119 | except Exception as e: 120 | logger = logging.getLogger(__name__) 121 | logger.error(f"Error: {e}") 122 | return 1 123 | 124 | 125 | if __name__ == "__main__": 126 | sys.exit(main()) 127 | -------------------------------------------------------------------------------- /tempdd/template_parser.py: -------------------------------------------------------------------------------- 1 | """ 2 | Template Parser for TempDD 3 | 4 | Handles parsing of template files with YAML frontmatter containing action-specific prompts. 5 | Supports the new simplified format where actions (build, continue, run) directly contain prompt fields. 6 | """ 7 | 8 | import yaml 9 | import re 10 | import logging 11 | from pathlib import Path 12 | from typing import Dict, Any, Tuple, Optional 13 | 14 | 15 | def parse_template(template_path: str) -> Tuple[Dict[str, Any], str]: 16 | """ 17 | Parse template file with YAML frontmatter 18 | 19 | Expected format: 20 | --- 21 | build: 22 | prompt: | 23 | Build instructions... 24 | continue: 25 | prompt: | 26 | Continue instructions... 27 | run: 28 | prompt: | 29 | Run instructions... 30 | --- 31 | 32 | # Template Content 33 | ... 34 | 35 | Args: 36 | template_path: Path to the template file 37 | 38 | Returns: 39 | Tuple[Dict[str, Any], str]: (metadata, template_content) 40 | 41 | Raises: 42 | FileNotFoundError: When template file does not exist 43 | ValueError: When template format is invalid 44 | """ 45 | template_file = Path(template_path) 46 | 47 | if not template_file.exists(): 48 | raise FileNotFoundError(f"Template file not found: {template_path}") 49 | 50 | with open(template_file, 'r', encoding='utf-8') as f: 51 | content = f.read() 52 | 53 | # Check if content starts with YAML frontmatter 54 | if not content.startswith('---\n'): 55 | # No frontmatter, return empty metadata 56 | return {}, content 57 | 58 | # Split frontmatter and content 59 | try: 60 | parts = content.split('---\n', 2) 61 | if len(parts) < 3: 62 | # Invalid frontmatter format 63 | return {}, content 64 | 65 | frontmatter_raw = parts[1] 66 | template_content = parts[2] 67 | 68 | # Parse YAML frontmatter 69 | metadata = yaml.safe_load(frontmatter_raw) or {} 70 | 71 | return metadata, template_content 72 | 73 | except yaml.YAMLError as e: 74 | raise ValueError(f"Invalid YAML frontmatter in template {template_path}: {e}") 75 | 76 | 77 | def get_action_prompt(metadata: Dict[str, Any], action: str) -> Optional[str]: 78 | """ 79 | Extract prompt for specific action from metadata 80 | 81 | Args: 82 | metadata: Parsed template metadata 83 | action: Action name (build, continue, run, etc.) 84 | 85 | Returns: 86 | Optional[str]: Action-specific prompt or None if not found 87 | """ 88 | if not isinstance(metadata, dict): 89 | return None 90 | 91 | action_data = metadata.get(action, {}) 92 | if isinstance(action_data, dict): 93 | return action_data.get('prompt') 94 | 95 | return None 96 | 97 | 98 | def process_template_variables(content: str, variables: Dict[str, str]) -> str: 99 | """ 100 | Replace template variables in content 101 | 102 | Variables are in the format {{VARIABLE_NAME}} 103 | 104 | Args: 105 | content: Content with template variables 106 | variables: Dictionary mapping variable names to values 107 | 108 | Returns: 109 | str: Content with variables replaced 110 | """ 111 | processed_content = content 112 | 113 | for var_name, var_value in variables.items(): 114 | placeholder = f"{{{{{var_name}}}}}" 115 | processed_content = processed_content.replace(placeholder, str(var_value)) 116 | 117 | # Check for remaining unreplaced variables and log warnings 118 | remaining_vars = re.findall(r'\{\{([^}]+)\}\}', processed_content) 119 | if remaining_vars: 120 | logger = logging.getLogger(__name__) 121 | for var in remaining_vars: 122 | logger.warning(f"Template variable '{{{{%s}}}}' was not replaced. Variable not found in provided variables.", var) 123 | 124 | return processed_content 125 | 126 | 127 | def validate_template_metadata(metadata: Dict[str, Any]) -> bool: 128 | """ 129 | Validate template metadata structure 130 | 131 | Args: 132 | metadata: Parsed template metadata 133 | 134 | Returns: 135 | bool: True if metadata is valid, False otherwise 136 | """ 137 | if not isinstance(metadata, dict): 138 | return False 139 | 140 | # Check if at least one valid action exists 141 | valid_actions = ['build', 'continue', 'run'] 142 | 143 | for action in valid_actions: 144 | if action in metadata: 145 | action_data = metadata[action] 146 | if isinstance(action_data, dict) and 'prompt' in action_data: 147 | return True 148 | 149 | return len(metadata) == 0 # Empty metadata is also valid -------------------------------------------------------------------------------- /customized/workflow_example/templates/prd.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are a Product Manager speaking with a stakeholder to complete a comprehensive PRD. You ALWAYS MUST follow the guidelines shown in the document. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Your Systematic Approach (Execute Step by Step)**: 9 | 10 | 1. **Document Setup**: Review {{TARGET_DOCUMENT}} carefully to understand the current state. 11 | 12 | 2. **Discovery Phase**: Ask the stakeholder "What do you want to build today?" to get an overview of their vision. Use their response to begin filling {{TARGET_DOCUMENT}} with initial product information. 13 | 14 | 3. **Iterative Information Gathering**: Systematically identify missing information in the PRD. Use targeted questioning to fill gaps - ask only ONE question at a time for clarity. After each answer, immediately update {{TARGET_DOCUMENT}} before asking the next question. 15 | 16 | 4. **Completeness Validation**: Carefully review {{TARGET_DOCUMENT}} completely. If any information is still missing or unclear, return to step 3 to gather additional details until the PRD is comprehensive. 17 | 18 | 5. **Final Review**: Complete the review checklist in {{TARGET_DOCUMENT}} to ensure all requirements are met. 19 | 20 | **Your Product Manager Expertise - Focus On**: 21 | - Understanding the core problem and user pain points 22 | - Identifying target user personas and their needs 23 | - Defining measurable success criteria and business value 24 | - Gathering detailed functional and non-functional requirements 25 | - Documenting dependencies, assumptions, and constraints 26 | - Structuring requirements as Epics → User Stories with acceptance criteria 27 | 28 | **Quality Standards**: 29 | - Replace ALL `[[...]]` placeholders with specific, actionable information 30 | - Keep focus on user value, avoid technical implementation details 31 | - Write clearly for non-technical stakeholders 32 | - Ensure all requirements are testable and measurable 33 | - Use SMART criteria for goals and success metrics 34 | 35 | Begin with: "What do you want to build today? Tell me about the problem you're trying to solve for your users." 36 | 37 | --- 38 | 39 | # Product Requirements Document (PRD) 40 | 41 | **Guidelines**: 42 | - **Content Rules**: Replace all `[[...]]` placeholders; no implementation details; focus on user value; written for non-technical stakeholders 43 | - **Clarity Requirements**: Don't guess - use [NEEDS CLARIFICATION: specific question] for ambiguities; requirements must be testable; success criteria must be measurable 44 | - **Structure**: Epic (user value theme) → User Story (specific implementation) 45 | - **Scope**: Clearly bounded with identified dependencies and assumptions 46 | - **MUST: Section Constraint**: Only fill existing sections - DO NOT add any new sections to this template 47 | 48 | **Table of Contents** 49 | 📋 Basic Information 50 | 🎯 Objective & Goals 51 | 📝 User Scenarios 52 | ⚙️ Requirements 53 | 🔗 Dependencies and Assumptions 54 | ✅ Review Checklist 55 | 56 | **Fill-in `[[...]]` placeholders with appropriate content** 57 | 58 | --- 59 | 60 | ## 📋 Basic Information 61 | 62 | **Product Name**: [[Product Name]] 63 | 64 | --- 65 | 66 | ## 🎯 Objective & Goals 67 | 68 | ### Goals 69 | *Use SMART principles (Specific, Measurable, Achievable, Relevant, Time-bound) to define clear objectives* 70 | 71 | [[Primary goal description]] 72 | 73 | ### Why 74 | 75 | [[Business rationale and problem statement]] 76 | 77 | ### What 78 | 79 | [[Solution overview and key features]] 80 | 81 | --- 82 | 83 | ## 📝 User Scenarios 84 | 85 | ### Epic 86 | 87 | - **E1**: [[Epic 1 Name]] 88 | - Description: [[Epic 1 detailed description]] 89 | - Business Value: [[What this Epic contributes]] 90 | - Success Criteria: 91 | - [[Measurable Epic-level success criterion 1]] 92 | - [[Measurable Epic-level success criterion 2]] 93 | - **E2**: [[Epic 2 Name]] 94 | - ... 95 | 96 | ### User Stories 97 | 98 | - **E1S1**: [[Name of Story 1 of Epic 1]] 99 | - Description: **As a** [[User Type]], **I want** [[Feature Requirement]], **so that** [[Achieve Goal]] 100 | - Acceptance Criteria: 101 | - **Given** [[initial state]], **When** [[action]], **Then** [[expected outcome]] 102 | - **Given** [[initial state]], **When** [[action]], **Then** [[expected outcome]] 103 | - **E1S2**: [[Name of Story 2 of Epic 1]] 104 | - ... 105 | 106 | --- 107 | 108 | ## ⚙️ Requirements 109 | *FR (functional) with input/output specs; NFR (performance <200ms, throughput >1000 QPS, concurrent users)* 110 | 111 | ### Functional Requirements 112 | 113 | - **FR001**: [[Functional requirements description]] 114 | - Input: [[Input description]] 115 | - Processing Logic: [[Processing logic description]] 116 | - Output: [[Output description]] 117 | - Error Handling: [[Error handling description]] 118 | - **FR002**: [[Feature description]] 119 | - Input: [[Input description]] 120 | - Processing Logic: [[Processing logic description]] 121 | - Output: [[Output description]] 122 | - Error Handling: [[Error handling description]] 123 | 124 | ### Non-Functional Requirements (Performance, Availability, Scalability, Security, or Compatibility) 125 | 126 | - **NFR001**: [[Non-functional requirements description]] 127 | - **NFR002**: [[Non-functional requirements description]] 128 | 129 | --- 130 | 131 | ## 🔗 Dependencies and Assumptions 132 | 133 | ### Dependencies 134 | [[List external dependencies, services, or requirements needed]] 135 | 136 | ### Assumptions 137 | [[List key assumptions about users, technology, or business context]] 138 | 139 | ### Technical Constraints 140 | [[List technical limitations or constraints that impact the solution]] 141 | 142 | --- 143 | 144 | ## ✅ Review Checklist (for this document) 145 | 146 | - [ ] All `[[...]]` placeholders replaced with actual content 147 | - [ ] No implementation details (languages, frameworks, APIs) 148 | - [ ] Focused on user value and business needs 149 | - [ ] Written for non-technical stakeholders 150 | - [ ] No [NEEDS CLARIFICATION] markers remain 151 | - [ ] Requirements are testable and unambiguous 152 | - [ ] Success criteria are measurable 153 | - [ ] Scope is clearly bounded 154 | - [ ] Dependencies and assumptions identified 155 | -------------------------------------------------------------------------------- /tempdd/core/templates/template_prd_default.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are a Product Manager speaking with a stakeholder to complete a comprehensive PRD. You ALWAYS MUST follow the guidelines shown in the document. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Your Systematic Approach (Execute Step by Step)**: 9 | 10 | 1. **Document Setup**: Review {{TARGET_DOCUMENT}} carefully to understand the current state. 11 | 12 | 2. **Discovery Phase**: Ask the stakeholder "What do you want to build today?" to get an overview of their vision. Use their response to begin filling {{TARGET_DOCUMENT}} with initial product information. 13 | 14 | 3. **Iterative Information Gathering**: Systematically identify missing information in the PRD. Use targeted questioning to fill gaps - ask only ONE question at a time for clarity. After each answer, immediately update {{TARGET_DOCUMENT}} before asking the next question. 15 | 16 | 4. **Completeness Validation**: Carefully review {{TARGET_DOCUMENT}} completely. If any information is still missing or unclear, return to step 3 to gather additional details until the PRD is comprehensive. 17 | 18 | 5. **Final Review**: Complete the review checklist in {{TARGET_DOCUMENT}} to ensure all requirements are met. 19 | 20 | **Your Product Manager Expertise - Focus On**: 21 | - Understanding the core problem and user pain points 22 | - Identifying target user personas and their needs 23 | - Defining measurable success criteria and business value 24 | - Gathering detailed functional and non-functional requirements 25 | - Documenting dependencies, assumptions, and constraints 26 | - Structuring requirements as Epics → User Stories with acceptance criteria 27 | 28 | **Quality Standards**: 29 | - Replace ALL `[[...]]` placeholders with specific, actionable information 30 | - Keep focus on user value, avoid technical implementation details 31 | - Write clearly for non-technical stakeholders 32 | - Ensure all requirements are testable and measurable 33 | - Use SMART criteria for goals and success metrics 34 | 35 | Begin with: "What do you want to build today? Tell me about the problem you're trying to solve for your users." 36 | 37 | --- 38 | 39 | # Product Requirements Document (PRD) 40 | 41 | **Guidelines**: 42 | - **Content Rules**: Replace all `[[...]]` placeholders; no implementation details; focus on user value; written for non-technical stakeholders 43 | - **Clarity Requirements**: Don't guess - use [NEEDS CLARIFICATION: specific question] for ambiguities; requirements must be testable; success criteria must be measurable 44 | - **Structure**: Epic (user value theme) → User Story (specific implementation) 45 | - **Scope**: Clearly bounded with identified dependencies and assumptions 46 | - **MUST: Section Constraint**: Only fill existing sections - DO NOT add any new sections to this template 47 | 48 | **Table of Contents** 49 | 📋 Basic Information 50 | 🎯 Objective & Goals 51 | 📝 User Scenarios 52 | ⚙️ Requirements 53 | 🔗 Dependencies and Assumptions 54 | ✅ Review Checklist 55 | 56 | **Fill-in `[[...]]` placeholders with appropriate content** 57 | 58 | --- 59 | 60 | ## 📋 Basic Information 61 | 62 | **Product Name**: [[Product Name]] 63 | 64 | --- 65 | 66 | ## 🎯 Objective & Goals 67 | 68 | ### Goals 69 | *Use SMART principles (Specific, Measurable, Achievable, Relevant, Time-bound) to define clear objectives* 70 | 71 | [[Primary goal description]] 72 | 73 | ### Why 74 | 75 | [[Business rationale and problem statement]] 76 | 77 | ### What 78 | 79 | [[Solution overview and key features]] 80 | 81 | --- 82 | 83 | ## 📝 User Scenarios 84 | 85 | ### Epic 86 | 87 | - **E1**: [[Epic 1 Name]] 88 | - Description: [[Epic 1 detailed description]] 89 | - Business Value: [[What this Epic contributes]] 90 | - Success Criteria: 91 | - [[Measurable Epic-level success criterion 1]] 92 | - [[Measurable Epic-level success criterion 2]] 93 | - **E2**: [[Epic 2 Name]] 94 | - ... 95 | 96 | ### User Stories 97 | 98 | - **E1S1**: [[Name of Story 1 of Epic 1]] 99 | - Description: **As a** [[User Type]], **I want** [[Feature Requirement]], **so that** [[Achieve Goal]] 100 | - Acceptance Criteria: 101 | - **Given** [[initial state]], **When** [[action]], **Then** [[expected outcome]] 102 | - **Given** [[initial state]], **When** [[action]], **Then** [[expected outcome]] 103 | - **E1S2**: [[Name of Story 2 of Epic 1]] 104 | - ... 105 | 106 | --- 107 | 108 | ## ⚙️ Requirements 109 | *FR (functional) with input/output specs; NFR (performance <200ms, throughput >1000 QPS, concurrent users)* 110 | 111 | ### Functional Requirements 112 | 113 | - **FR001**: [[Functional requirements description]] 114 | - Input: [[Input description]] 115 | - Processing Logic: [[Processing logic description]] 116 | - Output: [[Output description]] 117 | - Error Handling: [[Error handling description]] 118 | - **FR002**: [[Feature description]] 119 | - Input: [[Input description]] 120 | - Processing Logic: [[Processing logic description]] 121 | - Output: [[Output description]] 122 | - Error Handling: [[Error handling description]] 123 | 124 | ### Non-Functional Requirements (Performance, Availability, Scalability, Security, or Compatibility) 125 | 126 | - **NFR001**: [[Non-functional requirements description]] 127 | - **NFR002**: [[Non-functional requirements description]] 128 | 129 | --- 130 | 131 | ## 🔗 Dependencies and Assumptions 132 | 133 | ### Dependencies 134 | [[List external dependencies, services, or requirements needed]] 135 | 136 | ### Assumptions 137 | [[List key assumptions about users, technology, or business context]] 138 | 139 | ### Technical Constraints 140 | [[List technical limitations or constraints that impact the solution]] 141 | 142 | --- 143 | 144 | ## ✅ Review Checklist (for this document) 145 | 146 | - [ ] All `[[...]]` placeholders replaced with actual content 147 | - [ ] No implementation details (languages, frameworks, APIs) 148 | - [ ] Focused on user value and business needs 149 | - [ ] Written for non-technical stakeholders 150 | - [ ] No [NEEDS CLARIFICATION] markers remain 151 | - [ ] Requirements are testable and unambiguous 152 | - [ ] Success criteria are measurable 153 | - [ ] Scope is clearly bounded 154 | - [ ] Dependencies and assumptions identified 155 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Template-Driven Development Framework for AI-Augmented Coding 2 | 3 | ![banner](misc/banner.png) 4 | 5 | **Read this in other languages:** [繁體中文](docs/readmes/README-zh-TW.md) | [简体中文](docs/readmes/README-zh-CN.md) | [Español](docs/readmes/README-es.md) | [日本語](docs/readmes/README-ja.md) 6 | 7 | ## Overview 8 | 9 | TempDD is a template-driven development framework that enables structured human-AI collaboration through customizable workflows and agent-guided template interactions. 10 | 11 | As project complexity increases, AI Agents face challenges operating independently, making human-in-the-loop collaboration increasingly critical. Developers need effective tools to communicate with these black-box AI Agents. Template-driven approaches provide structured communication, reduce cognitive load, and enable consistent AI collaboration through guided workflows. This repository provides a framework that allows users to customize workflows according to their development projects, simplifying the process into a series of template-filling tasks. The framework incorporates agent mechanisms to reduce template complexity, enabling AI Agents to effectively assist users in completing documentation. We envision this framework being applicable across various development scenarios and even non-development contexts, while fostering open-source collaboration to integrate global knowledge. 12 | 13 | ## Features 14 | 15 | - 📚 **Progressive AI mastery through layered docs** - Transform from AI user to AI master with sophisticated multi-layer documentation that amplifies your control over AI behavior 16 | - 📋 **Customizable template-driven workflow** - Structured approach to project development with customizable templates 17 | - 💬 **Customizable agent-guided template interaction** - Customizable agents adapt to each template, providing interactive guidance to help users fill templates collaboratively 18 | - 🤖 **Cross-AI tool integration** - Seamless integration with Claude Code, Gemini CLI, Cursor, and GitHub Copilot 19 | - 🌐 **Multi-language support** - Users can fill templates using their preferred language 20 | 21 | ## Quick Start 22 | 23 | ### 1. Installation 24 | 25 | Install `tempdd` using uv: 26 | 27 | ```bash 28 | uv tool install --force --from git+https://github.com/GitYCC/TempDD.git tempdd && exec $SHELL 29 | ``` 30 | 31 | ### 2. Initialize Project 32 | 33 | Create a new project directory and initialize TempDD: 34 | 35 | ```bash 36 | mkdir demo 37 | cd demo 38 | tempdd init # You can choose the built-in workflow and preferred AI tool during initialization 39 | ``` 40 | 41 | ### 3. Example: Default Workflow with Claude Code 42 | 43 | The following example demonstrates using the default workflow with Claude Code. For detailed customization options and available workflows, refer to `tempdd help`. 44 | 45 | Once you enter Claude Code, execute the following commands in sequence: 46 | 47 | ```bash 48 | # Get help and understand available commands 49 | /tempdd-go help 50 | 51 | # Generate product requirements document 52 | /tempdd-go prd build 53 | 54 | # After finishing the PRD, create architecture design 55 | /tempdd-go arch build 56 | 57 | # After finishing the architecture design document, conduct research 58 | /tempdd-go research build 59 | 60 | # After finishing the research report, build implementation blueprint 61 | /tempdd-go blueprint build 62 | 63 | # After finishing the blueprint, generate task list 64 | /tempdd-go tasks build 65 | 66 | # After finishing the task list, execute tasks to generate the codes 67 | /tempdd-go tasks run 68 | ``` 69 | 70 | From this example, you can see that development progresses from idea to implementation through multi-layered documentation. Each document is filled out by AI asking users for input when needed, which reduces the complexity of form-filling for users while enhancing consensus between AI and humans. Worth noting, the research step involves AI proactively searching for information online to improve its understanding of the implementation. I believe better workflows exist, and we shouldn't expect one workflow to satisfy every project. Therefore, this framework is designed to be easily customizable. Please refer to section ["Customize your workflow"](#customize-your-workflow) to learn more. 71 | 72 | 73 | ## Customize your workflow 74 | 75 | TempDD allows you to create custom workflows tailored to your specific development needs. The framework's template-driven architecture makes customization straightforward—just define your stages in YAML and create corresponding templates. 76 | 77 | Follow the below steps to customize your workflow: 78 | 1. **Understand the design**: Read [Operating Principles](docs/operating-principles.md) to learn how template-driven architecture enables easy customization 79 | 2. **Read the guide**: See [./customized/](./customized/) for comprehensive workflow creation instructions 80 | 3. **Create your workflow** following the structure and examples provided 81 | 4. **Initialize project** with your custom workflow: 82 | 83 | ```bash 84 | tempdd init --workflow /path/to/your/custom/workflow_dir/ 85 | ``` 86 | 87 | ## Contributing Built-in Workflows 88 | 89 | We encourage contributors to help expand TempDD's built-in workflow collection! By contributing new workflows, you can help other developers benefit from proven development patterns and specialized domain workflows. 90 | 91 | ### How to Contribute a New Built-in Workflow 92 | 93 | 1. **Fork this repository** - Create your own fork to work on 94 | 2. **Add your workflow files**: 95 | - Add new configuration files to `./tempdd/core/configs/` 96 | - Add corresponding templates to `./tempdd/core/templates/` 97 | 3. **Submit a Pull Request** - Share your workflow with the community 98 | 99 | Your contributions will help make TempDD more valuable for developers across different domains and use cases. Whether it's a workflow for mobile development, data science, DevOps, or any other specialization, we welcome your expertise! 100 | 101 | ## Cross-AI tool integration 102 | 103 | TempDD seamlessly integrates with multiple AI development tools: 104 | 105 | | AI Tool | Status | 106 | |---------|--------| 107 | | **Claude Code** | ✅ Full Support | 108 | | **Gemini CLI** | ✅ Full Support | 109 | | **Cursor** | ✅ Full Support | 110 | | **GitHub Copilot** | ✅ Full Support | 111 | 112 | ## Acknowledgments 113 | 114 | Thanks to the following repositories for inspiration: 115 | - [github/spec-kit](https://github.com/github/spec-kit) 116 | - [coleam00/context-engineering-intro](https://github.com/coleam00/context-engineering-intro) 117 | -------------------------------------------------------------------------------- /tempdd/file_manager.py: -------------------------------------------------------------------------------- 1 | """File manager for TempDD integrations and templates.""" 2 | 3 | import shutil 4 | import logging 5 | from pathlib import Path 6 | from typing import List, Optional 7 | from dataclasses import dataclass 8 | 9 | 10 | @dataclass 11 | class IntegrationConfig: 12 | """Configuration for AI tool integrations.""" 13 | 14 | name: str 15 | tool_dir: str 16 | commands_dir: str 17 | file_name: str 18 | file_extension: str 19 | 20 | 21 | class FileManager: 22 | """Manages files for TempDD integrations and templates.""" 23 | 24 | # Integration configurations for different AI tools 25 | INTEGRATION_CONFIGS = { 26 | "claude": IntegrationConfig( 27 | name="Claude Code", 28 | tool_dir=".claude", 29 | commands_dir="commands", 30 | file_name="tempdd-go", 31 | file_extension=".md", 32 | ), 33 | "gemini": IntegrationConfig( 34 | name="Gemini CLI", 35 | tool_dir=".gemini", 36 | commands_dir="commands", 37 | file_name="tempdd-go", 38 | file_extension=".toml", 39 | ), 40 | "cursor": IntegrationConfig( 41 | name="Cursor", 42 | tool_dir=".cursor", 43 | commands_dir="commands", 44 | file_name="tempdd-go", 45 | file_extension=".md", 46 | ), 47 | "copilot": IntegrationConfig( 48 | name="GitHub Copilot", 49 | tool_dir=".github", 50 | commands_dir="prompts", 51 | file_name="tempdd-go.prompt", 52 | file_extension=".md", 53 | ), 54 | } 55 | 56 | def __init__(self, base_path: Optional[Path] = None): 57 | """Initialize FileManager with base path.""" 58 | self.base_path = base_path or Path.cwd() 59 | self.logger = logging.getLogger(__name__) 60 | 61 | def get_core_path(self) -> Path: 62 | """Get the core directory path.""" 63 | return Path(__file__).parent / "core" 64 | 65 | def get_integrations_path(self) -> Path: 66 | """Get the integrations directory path.""" 67 | return Path(__file__).parent / "integrations" 68 | 69 | def create_directory_structure(self, tool: str, force: bool = False) -> None: 70 | """Create directory structure for specified tool.""" 71 | # Create .tempdd directory only 72 | tempdd_dir = self.base_path / ".tempdd" 73 | tempdd_dir.mkdir(parents=True, exist_ok=True) 74 | 75 | # Create tool-specific directory 76 | if tool in self.INTEGRATION_CONFIGS: 77 | config = self.INTEGRATION_CONFIGS[tool] 78 | tool_dir = self.base_path / config.tool_dir / config.commands_dir 79 | tool_dir.mkdir(parents=True, exist_ok=True) 80 | else: 81 | self.logger.warning(f"Unknown tool: {tool}") 82 | 83 | def get_integration_file_path(self, tool: str) -> Optional[Path]: 84 | """Get the integration file path for a specific tool.""" 85 | if tool not in self.INTEGRATION_CONFIGS: 86 | return None 87 | 88 | config = self.INTEGRATION_CONFIGS[tool] 89 | return ( 90 | self.base_path 91 | / config.tool_dir 92 | / config.commands_dir 93 | / f"{config.file_name}{config.file_extension}" 94 | ) 95 | 96 | def get_source_integration_path(self, tool: str) -> Optional[Path]: 97 | """Get the source integration file path from the integrations directory.""" 98 | if tool not in self.INTEGRATION_CONFIGS: 99 | return None 100 | 101 | config = self.INTEGRATION_CONFIGS[tool] 102 | return ( 103 | self.get_integrations_path() 104 | / tool 105 | / config.tool_dir 106 | / config.commands_dir 107 | / f"{config.file_name}{config.file_extension}" 108 | ) 109 | 110 | def copy_integration_file(self, tool: str, force: bool = False) -> bool: 111 | """Copy integration file from source to target location.""" 112 | if tool not in self.INTEGRATION_CONFIGS: 113 | self.logger.error(f"Unsupported tool: {tool}") 114 | return False 115 | 116 | source_path = self.get_source_integration_path(tool) 117 | target_path = self.get_integration_file_path(tool) 118 | 119 | if not source_path or not source_path.exists(): 120 | self.logger.warning( 121 | f"Source integration file not found for '{tool}': {source_path}" 122 | ) 123 | return False 124 | 125 | if target_path.exists() and not force: 126 | self.logger.info( 127 | f"{self.INTEGRATION_CONFIGS[tool].name} integration already exists, skipping..." 128 | ) 129 | return False 130 | 131 | # Create target directory and copy file 132 | target_path.parent.mkdir(parents=True, exist_ok=True) 133 | shutil.copy2(source_path, target_path) 134 | self.logger.info( 135 | f"Created {self.INTEGRATION_CONFIGS[tool].name} integration: {target_path.relative_to(self.base_path)}" 136 | ) 137 | return True 138 | 139 | def list_available_integrations(self) -> List[str]: 140 | """List all available integration tools.""" 141 | return [ 142 | tool 143 | for tool in self.INTEGRATION_CONFIGS.keys() 144 | if (source_path := self.get_source_integration_path(tool)) 145 | and source_path.exists() 146 | ] 147 | 148 | def list_installed_integrations(self) -> List[str]: 149 | """List all installed integration tools.""" 150 | return [ 151 | tool 152 | for tool in self.INTEGRATION_CONFIGS.keys() 153 | if (file_path := self.get_integration_file_path(tool)) 154 | and file_path.exists() 155 | ] 156 | 157 | 158 | def get_project_config_path(self) -> Path: 159 | """Get the project configuration file path (deprecated - kept for compatibility).""" 160 | return self.base_path / ".tempdd" / "config.json" 161 | 162 | def get_workflow_config_path(self) -> Path: 163 | """Get the workflow configuration file path.""" 164 | return self.base_path / ".tempdd" / "workflow" / "config.yaml" 165 | 166 | def get_default_config_path(self) -> Path: 167 | """Get the default configuration file path.""" 168 | return self.get_core_path() / "configs" / "config_default.yaml" 169 | 170 | def get_config_path(self, config_name: str) -> Path: 171 | """Get configuration file path by name.""" 172 | return ( 173 | self.get_default_config_path() 174 | if config_name == "default" 175 | else self.get_core_path() / "configs" / f"config_{config_name}.yaml" 176 | ) 177 | 178 | -------------------------------------------------------------------------------- /docs/readmes/README-es.md: -------------------------------------------------------------------------------- 1 | # Template-Driven Development Framework for AI-Augmented Coding 2 | 3 | ![banner](../../misc/banner.png) 4 | 5 | ## Descripción General 6 | 7 | TempDD es un marco de desarrollo basado en plantillas que permite la colaboración estructurada humano-IA a través de flujos de trabajo personalizables e interacciones de plantillas guiadas por agentes. 8 | 9 | A medida que aumenta la complejidad de los proyectos, los Agentes de IA enfrentan desafíos operando independientemente, haciendo que la colaboración humano-en-el-bucle sea cada vez más crítica. Los desarrolladores necesitan herramientas efectivas para comunicarse con estos Agentes de IA de caja negra. Los enfoques basados en plantillas proporcionan comunicación estructurada, reducen la carga cognitiva y permiten colaboración consistente con IA a través de flujos de trabajo guiados. Este repositorio proporciona un marco que permite a los usuarios personalizar flujos de trabajo según sus proyectos de desarrollo, simplificando el proceso en una serie de tareas de llenado de plantillas. El marco incorpora mecanismos de agentes para reducir la complejidad de las plantillas, permitiendo que los Agentes de IA ayuden efectivamente a los usuarios a completar la documentación. Visualizamos que este marco será aplicable en varios escenarios de desarrollo e incluso contextos de no desarrollo, mientras fomenta la colaboración de código abierto para integrar conocimiento global. 10 | 11 | ## Características 12 | 13 | - 📚 **Dominio progresivo de IA a través de documentos en capas** - Transforma de usuario de IA a maestro de IA con documentación sofisticada de múltiples capas que amplifica tu control sobre el comportamiento de la IA 14 | - 📋 **Flujo de trabajo basado en plantillas personalizable** - Enfoque estructurado para el desarrollo de proyectos con plantillas personalizables 15 | - 💬 **Interacción de plantillas guiada por agentes personalizable** - Agentes personalizables se adaptan a cada plantilla, proporcionando orientación interactiva para ayudar a los usuarios a llenar plantillas colaborativamente 16 | - 🤖 **Integración de herramientas de IA cruzadas** - Integración perfecta con Claude Code, Gemini CLI, Cursor y GitHub Copilot 17 | - 🌐 **Soporte multiidioma** - Los usuarios pueden llenar plantillas usando su idioma preferido 18 | 19 | ## Inicio Rápido 20 | 21 | ### 1. Instalación 22 | 23 | Instala `tempdd` usando uv: 24 | 25 | ```bash 26 | uv tool install --force --from git+https://github.com/GitYCC/TempDD.git tempdd && exec $SHELL 27 | ``` 28 | 29 | ### 2. Inicializar Proyecto 30 | 31 | Crea un nuevo directorio de proyecto e inicializa TempDD: 32 | 33 | ```bash 34 | mkdir demo 35 | cd demo 36 | tempdd init # Puedes elegir el flujo de trabajo incorporado y la herramienta de IA preferida durante la inicialización 37 | ``` 38 | 39 | ### 3. Ejemplo: Flujo de Trabajo Predeterminado con Claude Code 40 | 41 | El siguiente ejemplo demuestra el uso del flujo de trabajo predeterminado con Claude Code. Para opciones de personalización detalladas y flujos de trabajo disponibles, consulta `tempdd help`. 42 | 43 | Una vez que entres a Claude Code, ejecuta los siguientes comandos en secuencia: 44 | 45 | ```bash 46 | # Obtener ayuda y entender los comandos disponibles 47 | /tempdd-go help 48 | 49 | # Generar documento de requisitos del producto 50 | /tempdd-go prd build 51 | 52 | # Después de terminar el PRD, crear diseño de arquitectura 53 | /tempdd-go arch build 54 | 55 | # Después de terminar el documento de diseño de arquitectura, realizar investigación 56 | /tempdd-go research build 57 | 58 | # Después de terminar el reporte de investigación, construir plano de implementación 59 | /tempdd-go blueprint build 60 | 61 | # Después de terminar el plano, generar lista de tareas 62 | /tempdd-go tasks build 63 | 64 | # Después de terminar la lista de tareas, ejecutar tareas para generar los códigos 65 | /tempdd-go tasks run 66 | ``` 67 | 68 | Desde este ejemplo, puedes ver que el desarrollo progresa de la idea a la implementación a través de documentación de múltiples capas. Cada documento es llenado por IA preguntando a los usuarios por entrada cuando es necesario, lo que reduce la complejidad de llenado de formularios para los usuarios mientras mejora el consenso entre IA y humanos. Vale la pena señalar, el paso de investigación involucra a la IA buscando proactivamente información en línea para mejorar su comprensión de la implementación. Creo que existen mejores flujos de trabajo, y no deberíamos esperar que un flujo de trabajo satisfaga cada proyecto. Por lo tanto, este marco está diseñado para ser fácilmente personalizable. Consulta la sección ["Personaliza tu flujo de trabajo"](#personaliza-tu-flujo-de-trabajo) para aprender más. 69 | 70 | ## Personaliza tu flujo de trabajo 71 | 72 | TempDD te permite crear flujos de trabajo personalizados adaptados a tus necesidades específicas de desarrollo. 73 | 74 | Sigue los siguientes pasos para personalizar tu flujo de trabajo: 75 | 1. **Lee la guía**: Consulta [./customized/](../../customized/) para instrucciones completas de creación de flujos de trabajo 76 | 2. **Crea tu flujo de trabajo** siguiendo la estructura y ejemplos proporcionados 77 | 3. **Inicializa proyecto** con tu flujo de trabajo personalizado: 78 | 79 | ```bash 80 | tempdd init --workflow /path/to/your/custom/workflow_dir/ 81 | ``` 82 | 83 | ## Contribuyendo Flujos de Trabajo Incorporados 84 | 85 | ¡Alentamos a los contribuyentes a ayudar a expandir la colección de flujos de trabajo incorporados de TempDD! Al contribuir nuevos flujos de trabajo, puedes ayudar a otros desarrolladores a beneficiarse de patrones de desarrollo probados y flujos de trabajo de dominios especializados. 86 | 87 | ### Cómo Contribuir un Nuevo Flujo de Trabajo Incorporado 88 | 89 | 1. **Haz fork de este repositorio** - Crea tu propio fork para trabajar 90 | 2. **Agrega tus archivos de flujo de trabajo**: 91 | - Agrega nuevos archivos de configuración a `./tempdd/core/configs/` 92 | - Agrega plantillas correspondientes a `./tempdd/core/templates/` 93 | 3. **Envía un Pull Request** - Comparte tu flujo de trabajo con la comunidad 94 | 95 | ¡Tus contribuciones ayudarán a hacer TempDD más valioso para desarrolladores en diferentes dominios y casos de uso. Ya sea un flujo de trabajo para desarrollo móvil, ciencia de datos, DevOps, o cualquier otra especialización, damos la bienvenida a tu experiencia! 96 | 97 | ## Integración de Herramientas de IA Cruzadas 98 | 99 | TempDD se integra perfectamente con múltiples herramientas de desarrollo de IA: 100 | 101 | | Herramienta de IA | Estado | 102 | |---------|--------| 103 | | **Claude Code** | ✅ Soporte Completo | 104 | | **Gemini CLI** | ✅ Soporte Completo | 105 | | **Cursor** | ✅ Soporte Completo | 106 | | **GitHub Copilot** | ✅ Soporte Completo | 107 | 108 | ## Agradecimientos 109 | 110 | Gracias a los siguientes repositorios por la inspiración: 111 | - [github/spec-kit](https://github.com/github/spec-kit) 112 | - [coleam00/context-engineering-intro](https://github.com/coleam00/context-engineering-intro) -------------------------------------------------------------------------------- /tests/test_commands.py: -------------------------------------------------------------------------------- 1 | """Simple end-to-end tests for TempDD commands.""" 2 | import subprocess 3 | import os 4 | from pathlib import Path 5 | import tempfile 6 | import shutil 7 | from tempdd.handlers.ai import format_ai_instruction 8 | 9 | 10 | def test_cli_help(): 11 | """Test CLI help command.""" 12 | result = subprocess.run( 13 | ["python", "-m", "tempdd.cli", "--help"], 14 | capture_output=True, 15 | text=True 16 | ) 17 | assert result.returncode == 0 18 | assert "tempdd" in result.stdout 19 | 20 | 21 | def test_cli_version(): 22 | """Test CLI version command.""" 23 | result = subprocess.run( 24 | ["python", "-m", "tempdd.cli", "--version"], 25 | capture_output=True, 26 | text=True 27 | ) 28 | assert result.returncode == 0 29 | assert "0.1.0" in result.stdout 30 | 31 | 32 | def test_init_command(): 33 | """Test init command creates project structure.""" 34 | temp_dir = tempfile.mkdtemp() 35 | original_cwd = os.getcwd() 36 | 37 | try: 38 | os.chdir(temp_dir) 39 | 40 | result = subprocess.run( 41 | ["python", "-m", "tempdd.cli", "init", "--force", "--config", "default", "--tool", "claude", "--language", "en"], 42 | capture_output=True, 43 | text=True 44 | ) 45 | 46 | assert result.returncode == 0 47 | assert Path(".tempdd").exists() 48 | assert Path(".claude").exists() 49 | assert Path(".tempdd/config.json").exists() 50 | 51 | finally: 52 | os.chdir(original_cwd) 53 | shutil.rmtree(temp_dir, ignore_errors=True) 54 | 55 | 56 | def test_ai_instruction_formatting(): 57 | """Test that AI instruction formatting works correctly.""" 58 | content = "This is test content for AI instruction" 59 | 60 | formatted = format_ai_instruction(content) 61 | 62 | assert "[AI_INSTRUCTION_START]" in formatted 63 | assert "[AI_INSTRUCTION_END]" in formatted 64 | assert content in formatted 65 | 66 | # Ensure the content is properly wrapped 67 | lines = formatted.split('\n') 68 | assert lines[0] == "[AI_INSTRUCTION_START]" 69 | assert lines[-1] == "[AI_INSTRUCTION_END]" 70 | 71 | 72 | def test_ai_command_format(): 73 | """Test AI command with valid stage action format.""" 74 | result = subprocess.run( 75 | ["python", "-m", "tempdd.cli", "ai", "prd build"], 76 | capture_output=True, 77 | text=True 78 | ) 79 | # Should handle missing config gracefully 80 | assert result.returncode in [0, 1] 81 | 82 | 83 | def test_ai_command_invalid_format(): 84 | """Test AI command with invalid format should fail.""" 85 | result = subprocess.run( 86 | ["python", "-m", "tempdd.cli", "ai", "prd"], # Missing action 87 | capture_output=True, 88 | text=True 89 | ) 90 | assert result.returncode == 1 91 | assert "Invalid command format" in result.stderr 92 | 93 | 94 | def test_ai_command_with_project(): 95 | """Test AI command in initialized project.""" 96 | temp_dir = tempfile.mkdtemp() 97 | original_cwd = os.getcwd() 98 | 99 | try: 100 | os.chdir(temp_dir) 101 | 102 | # Initialize project first 103 | subprocess.run( 104 | ["python", "-m", "tempdd.cli", "init", "--force", "--config", "default", "--tool", "claude", "--language", "en"], 105 | capture_output=True 106 | ) 107 | 108 | # Run AI command 109 | result = subprocess.run( 110 | ["python", "-m", "tempdd.cli", "ai", "prd build"], 111 | capture_output=True, 112 | text=True 113 | ) 114 | 115 | assert result.returncode == 0 116 | assert "[AI_INSTRUCTION_START]" in result.stdout 117 | assert "[AI_INSTRUCTION_END]" in result.stdout 118 | 119 | finally: 120 | os.chdir(original_cwd) 121 | shutil.rmtree(temp_dir, ignore_errors=True) 122 | 123 | 124 | def test_ai_instruction_formatting(): 125 | """Test that AI instruction formatting works correctly.""" 126 | content = "This is test content for AI instruction" 127 | 128 | formatted = format_ai_instruction(content) 129 | 130 | assert "[AI_INSTRUCTION_START]" in formatted 131 | assert "[AI_INSTRUCTION_END]" in formatted 132 | assert content in formatted 133 | 134 | # Ensure the content is properly wrapped 135 | lines = formatted.split('\n') 136 | assert lines[0] == "[AI_INSTRUCTION_START]" 137 | assert lines[-1] == "[AI_INSTRUCTION_END]" 138 | 139 | 140 | def test_old_commands_removed(): 141 | """Test that old preprocess and agent commands are no longer available.""" 142 | # Test preprocess command should fail 143 | result = subprocess.run( 144 | ["python", "-m", "tempdd.cli", "preprocess", "prd"], 145 | capture_output=True, 146 | text=True 147 | ) 148 | assert result.returncode != 0 149 | 150 | # Test agent command should fail 151 | result = subprocess.run( 152 | ["python", "-m", "tempdd.cli", "agent", "prd"], 153 | capture_output=True, 154 | text=True 155 | ) 156 | assert result.returncode != 0 157 | 158 | def test_e2e_ai_command_generates_correct_path(): 159 | """ 160 | End-to-end test to ensure 'tempdd ai' command generates AI instructions 161 | with the correct document path based on the new directory logic. 162 | """ 163 | temp_dir = tempfile.mkdtemp() 164 | original_cwd = os.getcwd() 165 | 166 | try: 167 | os.chdir(temp_dir) 168 | 169 | # 1. Initialize project 170 | subprocess.run( 171 | ["python", "-m", "tempdd.cli", "init", "--force", "--config", "default", "--tool", "claude", "--language", "en"], 172 | check=True, 173 | capture_output=True 174 | ) 175 | 176 | # 2. Run the 'ai' command 177 | result = subprocess.run( 178 | ["python", "-m", "tempdd.cli", "ai", "prd build"], 179 | capture_output=True, 180 | text=True, 181 | check=True 182 | ) 183 | 184 | # 3. Assert the output contains the correct path 185 | assert "[AI_INSTRUCTION_START]" in result.stdout 186 | # The path should be constructed using the default logic 187 | expected_path = Path("docs-for-works") / "001_initialization" / "prd.md" 188 | assert str(expected_path) in result.stdout 189 | 190 | finally: 191 | os.chdir(original_cwd) 192 | shutil.rmtree(temp_dir, ignore_errors=True) 193 | 194 | 195 | def test_ai_instruction_formatting(): 196 | """Test that AI instruction formatting works correctly.""" 197 | content = "This is test content for AI instruction" 198 | 199 | formatted = format_ai_instruction(content) 200 | 201 | assert "[AI_INSTRUCTION_START]" in formatted 202 | assert "[AI_INSTRUCTION_END]" in formatted 203 | assert content in formatted 204 | 205 | # Ensure the content is properly wrapped 206 | lines = formatted.split('\n') 207 | assert lines[0] == "[AI_INSTRUCTION_START]" 208 | assert lines[-1] == "[AI_INSTRUCTION_END]" -------------------------------------------------------------------------------- /tempdd/core/templates/template_arch_default.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are an engineer working with a senior architect to complete an Architecture Design Document. You MUST follow the guidelines shown in the document. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Your Process (Execute Step by Step)**: 9 | 10 | 1. **Document Setup**: Read {{TARGET_DOCUMENT}} carefully to understand the current state 11 | 12 | 2. **Collaborative Design**: Read {{TARGET_DOCUMENT}} carefully, then propose your architecture design to the senior architect using a questioning approach. Ask only ONE question at a time to engage the architect and align the design. Update {{TARGET_DOCUMENT}} after each information gathering session. 13 | 14 | 3. **Gap Analysis**: Carefully review {{TARGET_DOCUMENT}} completely and identify missing information. If gaps remain, return to step 2 for additional details. 15 | 16 | 4. **Final Review**: Review and complete the checklist in {{TARGET_DOCUMENT}} 17 | 18 | **Your Architecture Focus**: 19 | - Analyze PRD requirements as foundation 20 | - Define clear component responsibilities and interfaces 21 | - Design data flow and communication patterns 22 | - Consider scalability, security, and performance 23 | - Ensure high-level focus, avoid implementation details 24 | 25 | **Engagement Style**: Use questioning to collaborate with the senior architect, asking one focused question at a time to build consensus on the architectural design. 26 | 27 | Begin with: "What are the key technical requirements from the PRD that should guide our architecture?" 28 | 29 | --- 30 | 31 | # Architecture Design Document 32 | 33 | **Guidelines**: 34 | - **PRD Foundation**: Use PRD's requirements as your architectural foundation 35 | - **Component Clarity**: Define clear responsibilities, interfaces, and dependencies for each component 36 | - **High-Level Focus**: Focus on architectural design, avoid implementation details 37 | - **Section Constraint**: Fill existing sections only - do not add new sections 38 | 39 | **Table of Contents** 40 | 📋 Basic Information 41 | 🏗️ System Architecture 42 | 📊 Data Architecture 43 | 💻 Technology Stack 44 | ⚡ Performance & Scalability 45 | 🧪 Testing Strategy 46 | ✅ Review Checklist 47 | 48 | **Fill-in `[[...]]` placeholders with appropriate content** 49 | 50 | --- 51 | 52 | ## 📋 Basic Information 53 | 54 | **PRD Reference**: {{PATH_PRD}} 55 | 56 | **Project Name**: [[From PRD - Product Name]] 57 | 58 | --- 59 | 60 | ## 🏗️ System Architecture 61 | 62 | ### C4 Architecture Level 1: System Context 63 | *Consider how users interact with your system and what external systems are involved* 64 | ```mermaid 65 | [[C4Context diagram showing system context - include users, main system, and external systems with their relationships]] 66 | ``` 67 | 68 | ### C4 Architecture Level 2: Container Diagram 69 | ```mermaid 70 | [[C4Container diagram showing internal containers/components, their technologies, and interactions]] 71 | ``` 72 | 73 | ### Core Components 74 | *List the main system components and their responsibilities* 75 | 76 | - **[[Component Name]]** 77 | - Responsibility: [[What this component does]] 78 | - Interfaces: [[How other components interact with it]] 79 | - Dependencies: [[What this component relies on]] 80 | - *Add more components as needed* 81 | 82 | --- 83 | 84 | ## 📊 Data Architecture 85 | 86 | ### Data Models 87 | *Define the key data structures your system will work with* 88 | 89 | ``` 90 | [[Data structure definitions - can be schemas, entities, or data models]] 91 | ``` 92 | 93 | ### Data Flow 94 | *Describe how data moves through your system* 95 | 96 | ``` 97 | [[Data flow diagram or description showing data movement from input to output]] 98 | ``` 99 | 100 | ### Storage Strategy 101 | *Outline your data storage and persistence approach* 102 | 103 | - **Storage Type**: [[Database, files, memory, etc.]] 104 | - **Data Persistence**: [[How data is retained]] 105 | - **Access Patterns**: [[How data is retrieved and updated]] 106 | 107 | --- 108 | 109 | ## 💻 Technology Stack 110 | 111 | ### Frontend (if applicable) 112 | - **Framework/Library**: [[Your choice and reasoning]] 113 | - **UI Components**: [[Component library or custom]] 114 | - **State Management**: [[How you handle application state]] 115 | 116 | ### Backend (if applicable) 117 | - **Runtime/Language**: [[Your choice and reasoning]] 118 | - **Database**: [[Database type and why]] 119 | - **API Design**: [[REST, GraphQL, etc.]] 120 | 121 | ### Development & Deployment 122 | - **Build Tools**: [[Build and bundling tools]] 123 | - **Testing Framework**: [[Testing approach and tools]] 124 | - **Deployment**: [[How and where you deploy]] 125 | 126 | --- 127 | 128 | ## ⚡ Performance & Scalability 129 | 130 | ### Error Handling 131 | *How your system will handle different types of errors* 132 | 133 | - **[[Error Category 1]]**: [[How you handle this type of error]] 134 | - **[[Error Category 2]]**: [[How you handle this type of error]] 135 | - *Add more error types as needed* 136 | 137 | ### Performance Requirements 138 | *Key performance metrics your system needs to meet* 139 | 140 | - **[[Performance Metric 1]]**: [[Target value and reasoning]] 141 | - **[[Performance Metric 2]]**: [[Target value and reasoning]] 142 | - *Add more metrics as needed* 143 | 144 | ### Optimization Strategies 145 | *Techniques you'll use to meet performance goals* 146 | 147 | - **[[Strategy 1]]**: [[How this will improve performance]] 148 | - **[[Strategy 2]]**: [[How this will improve performance]] 149 | - *Add more strategies as needed* 150 | 151 | ### Scalability Considerations 152 | *How your system can grow and evolve* 153 | 154 | - **[[Scalability Aspect 1]]**: [[Your approach for future growth]] 155 | - **[[Scalability Aspect 2]]**: [[Your approach for future growth]] 156 | - *Add more considerations as needed* 157 | 158 | --- 159 | 160 | ## 🧪 Testing Strategy 161 | 162 | ### Testing Approach 163 | *How you will verify your system works correctly* 164 | 165 | - **[[Test Type 1]]**: [[What and how you'll test]] 166 | - **[[Test Type 2]]**: [[What and how you'll test]] 167 | - *Add more test types as needed* 168 | 169 | ### Quality Gates 170 | *Standards your system must meet before release* 171 | 172 | - **[[Quality Metric 1]]**: [[Target threshold]] 173 | - **[[Quality Metric 2]]**: [[Target threshold]] 174 | - *Add more quality gates as needed* 175 | 176 | --- 177 | 178 | ## ✅ Review Checklist 179 | 180 | - [ ] All PRD FR requirements have corresponding architectural components 181 | - [ ] All PRD NFR requirements have corresponding technical solutions 182 | - [ ] Architecture design supports all user stories in PRD 183 | - [ ] Technology selection meets PRD compatibility requirements 184 | - [ ] Performance design satisfies PRD performance requirements 185 | - [ ] Error handling strategy covers all error scenarios in PRD 186 | - [ ] Testing strategy can verify PRD acceptance criteria 187 | - [ ] Architecture has scalability for PRD-implied expansion needs 188 | - [ ] Component interfaces and dependencies are clearly defined 189 | - [ ] Data flow and storage strategies align with functional requirements 190 | - [ ] Technology stack choices are justified based on requirements 191 | -------------------------------------------------------------------------------- /customized/README.md: -------------------------------------------------------------------------------- 1 | # Custom Workflow Creation Guide 2 | 3 | This document provides comprehensive guidance for creating custom workflows using the TempDD framework. The workflow system allows you to define structured development processes tailored to your specific needs. 4 | 5 | ## Overview 6 | 7 | TempDD custom workflows enable you to create systematic approaches to software development by defining stage-based processes with templates, prompts, and data flow. Each workflow consists of multiple stages that can build upon previous stage outputs. Please reference `./workflow_example` as an example. 8 | 9 | ## Workflow Structure 10 | 11 | A custom workflow consists of: 12 | 13 | - **Configuration file** (`config.yaml`) - Defines workflow metadata, stages, and data flow 14 | - **Template files** - Markdown templates for each stage with prompts and structured content 15 | - **Symbol system** - Data variables that flow between stages 16 | 17 | ## Creating a Custom Workflow 18 | 19 | ### Step 1: Create Workflow Directory 20 | 21 | ```bash 22 | mkdir my_custom_workflow 23 | cd my_custom_workflow 24 | mkdir templates 25 | ``` 26 | 27 | ### Step 2: Define Configuration (`config.yaml`) 28 | 29 | Create your workflow configuration following this structure: 30 | 31 | ```yaml 32 | description: "Brief description of your workflow purpose" 33 | help: | 34 | [Workflow instrution] 35 | language: en 36 | logging_level: WARNING 37 | stages: 38 | - stage1_name 39 | - stage2_name 40 | - stage3_name 41 | define: 42 | stage1_name: 43 | template: templates/stage1.md 44 | input_symbols: null 45 | output_symbol: PATH_STAGE1 46 | stage2_name: 47 | template: templates/stage2.md 48 | input_symbols: 49 | PATH_STAGE1 50 | output_symbol: PATH_STAGE2 51 | stage3_name: 52 | template: templates/stage3.md 53 | input_symbols: 54 | PATH_STAGE1 55 | PATH_STAGE2 56 | output_symbol: null 57 | ``` 58 | 59 | #### Configuration Elements 60 | 61 | - **description**: Brief workflow description 62 | - **help**: User guidance with stage sequence and commands 63 | - **language**: Content language (en, zh, etc.) 64 | - **logging_level**: Log verbosity (DEBUG, INFO, WARNING, ERROR) 65 | - **stages**: Ordered list of stage names 66 | - **define**: Stage definitions with templates and data flow 67 | 68 | #### Stage Definition Properties 69 | 70 | - **template**: Path to markdown template file 71 | - **input_symbols**: List of variables from previous stages (null for first stage) 72 | - **output_symbol**: Variable name for this stage's output (null if no output needed) 73 | 74 | ### Step 3: Create Stage Templates 75 | 76 | Each stage needs a markdown template file in the `templates/` directory. Templates have two sections: 77 | 78 | 1. **YAML frontmatter** - Contains prompts for different actions 79 | 2. **Markdown content** - The structured template users will fill 80 | 81 | #### Template Structure 82 | 83 | ```markdown 84 | --- 85 | build: 86 | prompt: | 87 | Your role and instructions for the build action. 88 | 89 | Target Document: {{TARGET_DOCUMENT}} 90 | 91 | Your systematic approach: 92 | 1. Step one description 93 | 2. Step two description 94 | 3. Step three description 95 | 96 | Quality standards and requirements. 97 | 98 | run: 99 | prompt: | 100 | Instructions for the run action (if applicable). 101 | This is typically used for execution/implementation stages. 102 | --- 103 | 104 | # Template Content 105 | 106 | **Guidelines**: 107 | - Content rules and constraints 108 | - Quality requirements 109 | - Structure requirements 110 | 111 | **Fill-in `[[...]]` placeholders with appropriate content** 112 | 113 | ## Section 1 114 | [[Placeholder for content]] 115 | 116 | ## Section 2 117 | [[Another placeholder]] 118 | 119 | ### Subsection 120 | - [[Bullet point placeholder]] 121 | - [[Another bullet point]] 122 | ``` 123 | 124 | (1) A template can support multiple actions: 125 | 126 | ```markdown 127 | --- 128 | build: 129 | prompt: | 130 | Instructions for building/creating content 131 | 132 | run: 133 | prompt: | 134 | Instructions for executing/implementing 135 | --- 136 | ``` 137 | 138 | (2) Access previous stage outputs using symbol syntax: 139 | 140 | ```markdown 141 | **PRD Reference**: {{PATH_PRD}} 142 | **Blueprint Reference**: {{PATH_BLUEPRINT}} 143 | 144 | Based on the requirements in {{PATH_PRD}}, implement: 145 | [[Feature implementation based on PRD]] 146 | ``` 147 | 148 | #### Prompt Design Best Practices 149 | 150 | - **Define clear roles**: Specify who the AI should act as (Product Manager, Technical Lead, etc.) 151 | - **Provide systematic approach**: Break down the task into numbered steps 152 | - **Set quality standards**: Define specific requirements and constraints 153 | - **Use placeholders**: Include `{{TARGET_DOCUMENT}}` and input symbols like `{{PATH_STAGE1}}` 154 | - **Include validation**: Add review checklists and completion criteria 155 | 156 | ### Step 4: Design Data Flow 157 | 158 | - **Input symbols**: Variables from previous stages available as `{{SYMBOL_NAME}}` 159 | - **Output symbols**: Stage output stored in specified variable 160 | - **Symbol flow**: Design dependencies between stages 161 | 162 | ## Example: Software Development Workflow 163 | 164 | Using the `workflow_example/` as reference: 165 | 166 | ### Configuration Analysis 167 | 168 | ```yaml 169 | description: "Simple flow of software development, including PRD, Arch., Tasks stages." 170 | stages: 171 | - prd # Product Requirements Document 172 | - blueprint # Technical Architecture 173 | - tasks # Implementation Tasks 174 | 175 | define: 176 | prd: 177 | template: templates/prd.md 178 | input_symbols: null # First stage, no inputs 179 | output_symbol: PATH_PRD # Creates PATH_PRD variable 180 | 181 | blueprint: 182 | template: templates/blueprint.md 183 | input_symbols: 184 | PATH_PRD # Uses PRD as input 185 | output_symbol: PATH_BLUEPRINT # Creates PATH_BLUEPRINT variable 186 | 187 | tasks: 188 | template: templates/tasks.md 189 | input_symbols: 190 | PATH_PRD # Uses both PRD and blueprint 191 | PATH_BLUEPRINT 192 | output_symbol: null # Final stage, no output symbol 193 | ``` 194 | 195 | ### Stage Templates 196 | 197 | #### PRD Template (`templates/prd.md`) 198 | - **Role**: Product Manager gathering requirements 199 | - **Process**: Systematic requirement gathering through targeted questions 200 | - **Output**: Comprehensive Product Requirements Document 201 | - **Key sections**: Basic Information, Objectives, User Scenarios, Requirements 202 | 203 | #### Blueprint Template (`templates/blueprint.md`) 204 | - **Role**: Technical Lead with "just ship it" mentality (Linus style) 205 | - **Process**: Transform PRD into concrete development blueprint 206 | - **Input**: `{{PATH_PRD}}` - References the completed PRD 207 | - **Output**: Technical implementation guide 208 | - **Key sections**: Architecture, Components, APIs, Quick Start 209 | 210 | #### Tasks Template (`templates/tasks.md`) 211 | - **Role**: Senior Developer managing task execution 212 | - **Process**: Break blueprint into actionable tasks with TDD cycles 213 | - **Inputs**: `{{PATH_PRD}}` and `{{PATH_BLUEPRINT}}` 214 | - **Output**: Executable task list 215 | - **Key sections**: Task list, TDD cycles, validation checkpoints 216 | 217 | ### Usage Commands 218 | 219 | ```bash 220 | # Build PRD (first stage) 221 | /tempdd-go prd build 222 | 223 | # Build technical blueprint (uses PRD) 224 | /tempdd-go blueprint build 225 | 226 | # Build task list (uses PRD and blueprint) 227 | /tempdd-go tasks build 228 | 229 | # Execute tasks (run implementation) 230 | /tempdd-go tasks run 231 | ``` 232 | -------------------------------------------------------------------------------- /customized/workflow_example/templates/tasks.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are a Technical Lead creating a comprehensive task list for development execution. Your job is to transform the implementation blueprint into a concrete, actionable task list that development teams can follow step by step. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Your Mission**: Transform the template into a formal task list by: 9 | - Analyzing the blueprint and breaking down into specific, actionable tasks 10 | - Filling all `[[...]]` placeholders with concrete task descriptions 11 | - Defining clear acceptance criteria and technical requirements for each task 12 | - Organizing tasks by priority, dependencies, and TDD cycles 13 | - Creating realistic development phases and milestones 14 | 15 | **Task List Creation Process**: 16 | 17 | 1. **Blueprint Analysis**: Study the implementation blueprint thoroughly to understand all components, features, and technical requirements. 18 | 19 | 2. **Task Identification**: Break down each blueprint section into specific, testable tasks. Each task should be: 20 | - Actionable (clear what to do) 21 | - Measurable (clear completion criteria) 22 | - Testable (can be verified) 23 | - Time-bound (realistic scope) 24 | 25 | 3. **TDD Structure**: Organize tasks into TDD cycles following Red-Green-Refactor pattern: 26 | - 🔴 Red tasks: Write failing tests first 27 | - 🟢 Green tasks: Implement minimal code to pass tests 28 | - ♻️ Refactor tasks: Improve code while keeping tests green 29 | 30 | 4. **Dependency Mapping**: Sequence tasks based on technical dependencies and logical development flow. 31 | 32 | 5. **Validation Checkpoints**: Define clear quality gates between development cycles. 33 | 34 | **Deliverable**: A complete, executable task list where every `[[...]]` placeholder is replaced with specific tasks, and the development team can immediately start execution. 35 | 36 | run: 37 | prompt: | 38 | You are a Senior Developer executing the development task list. Your primary responsibility is to follow the task list systematically while adapting it based on real development feedback and user requirements. 39 | 40 | Target Document: {{TARGET_DOCUMENT}} 41 | 42 | **Your Executive Functions**: 43 | 44 | 1. **Task Execution Management**: 45 | - Follow the task list step by step, updating status markers in real-time 46 | - Execute TDD cycles properly (🔴 Red → 🟢 Green → ♻️ Refactor) 47 | - Complete validation checkpoints before proceeding to next cycle 48 | - Mark tasks as `[~]` when starting, `[x]` when completed, `[!]` if blocked 49 | 50 | 2. **Dynamic Task Adaptation**: 51 | - Add new tasks when technical challenges or user feedback require it 52 | - Modify existing tasks based on development discoveries 53 | - Break down complex tasks into smaller, manageable pieces 54 | - Reprioritize tasks based on changing requirements or dependencies 55 | 56 | 3. **Quality & Progress Management**: 57 | - Ensure all tests pass at validation checkpoints 58 | - Maintain TDD discipline throughout development 59 | - Keep the task list as the single source of truth for project progress 60 | - Resolve blocked tasks and find alternative approaches when needed 61 | 62 | **Key Principle**: Execute the task list while keeping it alive and responsive to real development needs and user feedback. The task list should evolve as you learn during implementation. 63 | 64 | --- 65 | 66 | # Task List 67 | 68 | **Guidelines**: 69 | - **Implementation Focus**: Transform requirements into concrete development blueprint 70 | - **Code-Ready**: Provide actionable guidance with examples 71 | - **Comprehensive**: Cover structure, components, APIs, data, and workflows 72 | - **Section Constraint**: Fill existing sections only - do not add new sections 73 | 74 | **Table of Contents** 75 | ⚠️ Developer Instructions - READ FIRST 76 | 📋 Basic Information 77 | 📋 Tasks 78 | 🏗️ Setup & Infrastructure 79 | 🔄 TDD Development Cycles 80 | 🧪 Quality Assurance & Integration 81 | 📚 Documentation & Deployment 82 | 83 | **Fill-in `[[...]]` placeholders with appropriate content** 84 | 85 | --- 86 | 87 | ## ⚠️ Developer Instructions - READ FIRST 88 | 89 | **CRITICAL USAGE REQUIREMENTS**: 90 | 91 | 1. **Follow the Process**: This task list represents a structured development workflow. You MUST follow the outlined steps in sequence. 92 | 93 | 2. **Active Task Management**: 94 | - **MUST UPDATE STATUS**: After completing ANY action, immediately update the corresponding task status 95 | - Mark tasks as `[~]` when starting, `[x]` when completed, `[!]` if blocked 96 | - This is NOT optional - active task tracking is REQUIRED 97 | 98 | 3. **TDD Discipline**: 99 | - RED phase: Write tests that fail for the right reason 100 | - GREEN phase: Implement ONLY what's needed to pass tests 101 | - REFACTOR phase: Improve code while keeping ALL tests green 102 | 103 | 4. **Validation Checkpoints**: 104 | - DO NOT proceed to next cycle until current cycle's validation checkpoint is complete 105 | - All tests must pass before moving forward 106 | - Code quality standards must be met 107 | 108 | 5. **Communication Protocol**: 109 | - Update task status immediately after each development action 110 | - Document any blockers or deviations from planned tasks 111 | - Keep the task list as the single source of truth for project progress 112 | 113 | **Remember**: This task list is your development contract. Honor it, update it, follow it. 114 | 115 | --- 116 | 117 | ## 📋 Basic Information 118 | 119 | **PRD Reference**: {{PATH_PRD}} 120 | 121 | **Blueprint Reference**: {{PATH_BLUEPRINT}} 122 | 123 | **Project Name**: [[From PRD - Product Name]] 124 | 125 | --- 126 | 127 | ## 📋 Tasks 128 | 129 | **Task Format**: 130 | - Basic: `- [ ] [TaskID] - Description` 131 | - TDD: `- [ ] [TaskID] - [TDD-Type] - Description` 132 | - High Priority: Add ⭐ emoji 133 | 134 | **Status Indicators**: 135 | - `[ ]` Todo | `[x]` Done | `[~]` In Progress | `[!]` Blocked 136 | 137 | **TDD Type Indicators**: 138 | - **🔴** Red: Write failing test (must fail for right reason) 139 | - **🟢** Green: Minimal implementation to pass test (no more, no less) 140 | - **♻️** Refactor: Improve code while keeping all tests green 141 | 142 | --- 143 | 144 | ## 🏗️ Setup & Infrastructure 145 | - [ ] T001 - ⭐ Project structure creation 146 | - [ ] T002 - ⭐ Dependency initialization 147 | - [ ] T003 - ⭐ Testing framework setup 148 | - [ ] T004 - CI/CD pipeline basics 149 | - [ ] T005 - Development environment validation 150 | 151 | ## 🔄 TDD Development Cycles 152 | 153 | ### Cycle 1: [[Core Feature Name]] 154 | **Acceptance Criteria**: [[Specific, testable requirements]] 155 | 156 | - [ ] T101 - 🔴 - ⭐ [[Write failing test for happy path]] 157 | - *Expected failure reason*: [[Why should this test fail?]] 158 | - *Test scope*: [[What exactly are we testing?]] 159 | - [ ] T102 - 🔴 - [[Write failing test for edge cases]] 160 | - *Expected failure reason*: [[Why should this test fail?]] 161 | - [ ] T103 - 🟢 - ⭐ [[Minimal implementation for happy path]] 162 | - *Success criteria*: T101 passes, others may still fail 163 | - [ ] T104 - 🟢 - [[Implementation for edge cases]] 164 | - *Success criteria*: T101-T102 all pass 165 | - [ ] T105 - ♻️ - [[Refactor for clarity and performance]] 166 | - *Validation*: All tests still pass, code quality improved 167 | - [ ] T106 - ♻️ - [[Extract reusable components]] 168 | 169 | **Validation Checkpoint**: 170 | - [ ] All tests pass 171 | - [ ] Code coverage meets threshold (≥60%) 172 | - [ ] No code smells detected 173 | 174 | ### Cycle 2: [[Next Feature Name]] 175 | **Acceptance Criteria**: [[Specific, testable requirements]] 176 | 177 | - [ ] T201 - 🔴 - ⭐ [[Write failing test for integration]] 178 | - [ ] T202 - 🔴 - [[Write failing test for error handling]] 179 | - [ ] T203 - 🟢 - ⭐ [[Implement core functionality]] 180 | - [ ] T204 - 🟢 - [[Implement error handling]] 181 | - [ ] T205 - ♻️ - [[Optimize and clean up]] 182 | 183 | **Validation Checkpoint**: 184 | - [ ] All tests pass (including previous cycles) 185 | - [ ] Code coverage meets threshold (≥60%) 186 | - [ ] No code smells detected 187 | 188 | ### Cycle N: [[Additional Features]] 189 | *Follow same pattern for remaining features* 190 | 191 | ## 🧪 Quality Assurance & Integration 192 | - [ ] T801 - ⭐ Cross-feature integration tests 193 | - [ ] T802 - Performance testing 194 | - [ ] T803 - Security validation 195 | - [ ] T804 - User acceptance testing 196 | - [ ] T805 - Load/stress testing 197 | 198 | ## 📚 Documentation & Deployment 199 | - [ ] T901 - API documentation 200 | - [ ] T902 - User guide creation 201 | - [ ] T903 - ⭐ Deployment procedures 202 | - [ ] T904 - Monitoring setup 203 | -------------------------------------------------------------------------------- /tempdd/core/templates/template_tasks_simple.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are a Technical Lead creating a comprehensive task list for development execution. Your job is to transform the implementation blueprint into a concrete, actionable task list that development teams can follow step by step. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Your Mission**: Transform the template into a formal task list by: 9 | - Analyzing the blueprint and breaking down into specific, actionable tasks 10 | - Filling all `[[...]]` placeholders with concrete task descriptions 11 | - Defining clear acceptance criteria and technical requirements for each task 12 | - Organizing tasks by priority, dependencies, and TDD cycles 13 | - Creating realistic development phases and milestones 14 | 15 | **Task List Creation Process**: 16 | 17 | 1. **Blueprint Analysis**: Study the implementation blueprint thoroughly to understand all components, features, and technical requirements. 18 | 19 | 2. **Task Identification**: Break down each blueprint section into specific, testable tasks. Each task should be: 20 | - Actionable (clear what to do) 21 | - Measurable (clear completion criteria) 22 | - Testable (can be verified) 23 | - Time-bound (realistic scope) 24 | 25 | 3. **TDD Structure**: Organize tasks into TDD cycles following Red-Green-Refactor pattern: 26 | - 🔴 Red tasks: Write failing tests first 27 | - 🟢 Green tasks: Implement minimal code to pass tests 28 | - ♻️ Refactor tasks: Improve code while keeping tests green 29 | 30 | 4. **Dependency Mapping**: Sequence tasks based on technical dependencies and logical development flow. 31 | 32 | 5. **Validation Checkpoints**: Define clear quality gates between development cycles. 33 | 34 | **Deliverable**: A complete, executable task list where every `[[...]]` placeholder is replaced with specific tasks, and the development team can immediately start execution. 35 | 36 | run: 37 | prompt: | 38 | You are a Senior Developer executing the development task list. Your primary responsibility is to follow the task list systematically while adapting it based on real development feedback and user requirements. 39 | 40 | Target Document: {{TARGET_DOCUMENT}} 41 | 42 | **Your Executive Functions**: 43 | 44 | 1. **Task Execution Management**: 45 | - Follow the task list step by step, updating status markers in real-time 46 | - Execute TDD cycles properly (🔴 Red → 🟢 Green → ♻️ Refactor) 47 | - Complete validation checkpoints before proceeding to next cycle 48 | - Mark tasks as `[~]` when starting, `[x]` when completed, `[!]` if blocked 49 | 50 | 2. **Dynamic Task Adaptation**: 51 | - Add new tasks when technical challenges or user feedback require it 52 | - Modify existing tasks based on development discoveries 53 | - Break down complex tasks into smaller, manageable pieces 54 | - Reprioritize tasks based on changing requirements or dependencies 55 | 56 | 3. **Quality & Progress Management**: 57 | - Ensure all tests pass at validation checkpoints 58 | - Maintain TDD discipline throughout development 59 | - Keep the task list as the single source of truth for project progress 60 | - Resolve blocked tasks and find alternative approaches when needed 61 | 62 | **Key Principle**: Execute the task list while keeping it alive and responsive to real development needs and user feedback. The task list should evolve as you learn during implementation. 63 | 64 | --- 65 | 66 | # Task List 67 | 68 | **Guidelines**: 69 | - **Implementation Focus**: Transform requirements into concrete development blueprint 70 | - **Code-Ready**: Provide actionable guidance with examples 71 | - **Comprehensive**: Cover structure, components, APIs, data, and workflows 72 | - **Section Constraint**: Fill existing sections only - do not add new sections 73 | 74 | **Table of Contents** 75 | ⚠️ Developer Instructions - READ FIRST 76 | 📋 Basic Information 77 | 📋 Tasks 78 | 🏗️ Setup & Infrastructure 79 | 🔄 TDD Development Cycles 80 | 🧪 Quality Assurance & Integration 81 | 📚 Documentation & Deployment 82 | 83 | **Fill-in `[[...]]` placeholders with appropriate content** 84 | 85 | --- 86 | 87 | ## ⚠️ Developer Instructions - READ FIRST 88 | 89 | **CRITICAL USAGE REQUIREMENTS**: 90 | 91 | 1. **Follow the Process**: This task list represents a structured development workflow. You MUST follow the outlined steps in sequence. 92 | 93 | 2. **Active Task Management**: 94 | - **MUST UPDATE STATUS**: After completing ANY action, immediately update the corresponding task status 95 | - Mark tasks as `[~]` when starting, `[x]` when completed, `[!]` if blocked 96 | - This is NOT optional - active task tracking is REQUIRED 97 | 98 | 3. **TDD Discipline**: 99 | - RED phase: Write tests that fail for the right reason 100 | - GREEN phase: Implement ONLY what's needed to pass tests 101 | - REFACTOR phase: Improve code while keeping ALL tests green 102 | 103 | 4. **Validation Checkpoints**: 104 | - DO NOT proceed to next cycle until current cycle's validation checkpoint is complete 105 | - All tests must pass before moving forward 106 | - Code quality standards must be met 107 | 108 | 5. **Communication Protocol**: 109 | - Update task status immediately after each development action 110 | - Document any blockers or deviations from planned tasks 111 | - Keep the task list as the single source of truth for project progress 112 | 113 | **Remember**: This task list is your development contract. Honor it, update it, follow it. 114 | 115 | --- 116 | 117 | ## 📋 Basic Information 118 | 119 | **PRD Reference**: {{PATH_PRD}} 120 | 121 | **Blueprint Reference**: {{PATH_BLUEPRINT}} 122 | 123 | **Project Name**: [[From PRD - Product Name]] 124 | 125 | --- 126 | 127 | ## 📋 Tasks 128 | 129 | **Task Format**: 130 | - Basic: `- [ ] [TaskID] - Description` 131 | - TDD: `- [ ] [TaskID] - [TDD-Type] - Description` 132 | - High Priority: Add ⭐ emoji 133 | 134 | **Status Indicators**: 135 | - `[ ]` Todo | `[x]` Done | `[~]` In Progress | `[!]` Blocked 136 | 137 | **TDD Type Indicators**: 138 | - **🔴** Red: Write failing test (must fail for right reason) 139 | - **🟢** Green: Minimal implementation to pass test (no more, no less) 140 | - **♻️** Refactor: Improve code while keeping all tests green 141 | 142 | --- 143 | 144 | ## 🏗️ Setup & Infrastructure 145 | - [ ] T001 - ⭐ Project structure creation 146 | - [ ] T002 - ⭐ Dependency initialization 147 | - [ ] T003 - ⭐ Testing framework setup 148 | - [ ] T004 - CI/CD pipeline basics 149 | - [ ] T005 - Development environment validation 150 | 151 | ## 🔄 TDD Development Cycles 152 | 153 | ### Cycle 1: [[Core Feature Name]] 154 | **Acceptance Criteria**: [[Specific, testable requirements]] 155 | 156 | - [ ] T101 - 🔴 - ⭐ [[Write failing test for happy path]] 157 | - *Expected failure reason*: [[Why should this test fail?]] 158 | - *Test scope*: [[What exactly are we testing?]] 159 | - [ ] T102 - 🔴 - [[Write failing test for edge cases]] 160 | - *Expected failure reason*: [[Why should this test fail?]] 161 | - [ ] T103 - 🟢 - ⭐ [[Minimal implementation for happy path]] 162 | - *Success criteria*: T101 passes, others may still fail 163 | - [ ] T104 - 🟢 - [[Implementation for edge cases]] 164 | - *Success criteria*: T101-T102 all pass 165 | - [ ] T105 - ♻️ - [[Refactor for clarity and performance]] 166 | - *Validation*: All tests still pass, code quality improved 167 | - [ ] T106 - ♻️ - [[Extract reusable components]] 168 | 169 | **Validation Checkpoint**: 170 | - [ ] All tests pass 171 | - [ ] Code coverage meets threshold (≥60%) 172 | - [ ] No code smells detected 173 | 174 | ### Cycle 2: [[Next Feature Name]] 175 | **Acceptance Criteria**: [[Specific, testable requirements]] 176 | 177 | - [ ] T201 - 🔴 - ⭐ [[Write failing test for integration]] 178 | - [ ] T202 - 🔴 - [[Write failing test for error handling]] 179 | - [ ] T203 - 🟢 - ⭐ [[Implement core functionality]] 180 | - [ ] T204 - 🟢 - [[Implement error handling]] 181 | - [ ] T205 - ♻️ - [[Optimize and clean up]] 182 | 183 | **Validation Checkpoint**: 184 | - [ ] All tests pass (including previous cycles) 185 | - [ ] Code coverage meets threshold (≥60%) 186 | - [ ] No code smells detected 187 | 188 | ### Cycle N: [[Additional Features]] 189 | *Follow same pattern for remaining features* 190 | 191 | ## 🧪 Quality Assurance & Integration 192 | - [ ] T801 - ⭐ Cross-feature integration tests 193 | - [ ] T802 - Performance testing 194 | - [ ] T803 - Security validation 195 | - [ ] T804 - User acceptance testing 196 | - [ ] T805 - Load/stress testing 197 | 198 | ## 📚 Documentation & Deployment 199 | - [ ] T901 - API documentation 200 | - [ ] T902 - User guide creation 201 | - [ ] T903 - ⭐ Deployment procedures 202 | - [ ] T904 - Monitoring setup 203 | -------------------------------------------------------------------------------- /tempdd/core/templates/template_tasks_default.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are a Technical Lead creating a comprehensive task list for development execution. Your job is to transform the implementation blueprint into a concrete, actionable task list that development teams can follow step by step. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Your Mission**: Transform the template into a formal task list by: 9 | - Analyzing the blueprint and breaking down into specific, actionable tasks 10 | - Filling all `[[...]]` placeholders with concrete task descriptions 11 | - Defining clear acceptance criteria and technical requirements for each task 12 | - Organizing tasks by priority, dependencies, and TDD cycles 13 | - Creating realistic development phases and milestones 14 | 15 | **Task List Creation Process**: 16 | 17 | 1. **Blueprint Analysis**: Study the implementation blueprint thoroughly to understand all components, features, and technical requirements. 18 | 19 | 2. **Task Identification**: Break down each blueprint section into specific, testable tasks. Each task should be: 20 | - Actionable (clear what to do) 21 | - Measurable (clear completion criteria) 22 | - Testable (can be verified) 23 | - Time-bound (realistic scope) 24 | 25 | 3. **TDD Structure**: Organize tasks into TDD cycles following Red-Green-Refactor pattern: 26 | - 🔴 Red tasks: Write failing tests first 27 | - 🟢 Green tasks: Implement minimal code to pass tests 28 | - ♻️ Refactor tasks: Improve code while keeping tests green 29 | 30 | 4. **Dependency Mapping**: Sequence tasks based on technical dependencies and logical development flow. 31 | 32 | 5. **Validation Checkpoints**: Define clear quality gates between development cycles. 33 | 34 | **Deliverable**: A complete, executable task list where every `[[...]]` placeholder is replaced with specific tasks, and the development team can immediately start execution. 35 | 36 | run: 37 | prompt: | 38 | You are a Senior Developer executing the development task list. Your primary responsibility is to follow the task list systematically while adapting it based on real development feedback and user requirements. 39 | 40 | Target Document: {{TARGET_DOCUMENT}} 41 | 42 | **Your Executive Functions**: 43 | 44 | 1. **Task Execution Management**: 45 | - Follow the task list step by step, updating status markers in real-time 46 | - Execute TDD cycles properly (🔴 Red → 🟢 Green → ♻️ Refactor) 47 | - Complete validation checkpoints before proceeding to next cycle 48 | - Mark tasks as `[~]` when starting, `[x]` when completed, `[!]` if blocked 49 | 50 | 2. **Dynamic Task Adaptation**: 51 | - Add new tasks when technical challenges or user feedback require it 52 | - Modify existing tasks based on development discoveries 53 | - Break down complex tasks into smaller, manageable pieces 54 | - Reprioritize tasks based on changing requirements or dependencies 55 | 56 | 3. **Quality & Progress Management**: 57 | - Ensure all tests pass at validation checkpoints 58 | - Maintain TDD discipline throughout development 59 | - Keep the task list as the single source of truth for project progress 60 | - Resolve blocked tasks and find alternative approaches when needed 61 | 62 | **Key Principle**: Execute the task list while keeping it alive and responsive to real development needs and user feedback. The task list should evolve as you learn during implementation. 63 | 64 | --- 65 | 66 | # Task List 67 | 68 | **Guidelines**: 69 | - **Implementation Focus**: Transform requirements into concrete development blueprint 70 | - **Code-Ready**: Provide actionable guidance with examples 71 | - **Comprehensive**: Cover structure, components, APIs, data, and workflows 72 | - **Section Constraint**: Fill existing sections only - do not add new sections 73 | 74 | **Table of Contents** 75 | ⚠️ Developer Instructions - READ FIRST 76 | 📋 Basic Information 77 | 📋 Tasks 78 | 🏗️ Setup & Infrastructure 79 | 🔄 TDD Development Cycles 80 | 🧪 Quality Assurance & Integration 81 | 📚 Documentation & Deployment 82 | 83 | **Fill-in `[[...]]` placeholders with appropriate content** 84 | 85 | --- 86 | 87 | ## ⚠️ Developer Instructions - READ FIRST 88 | 89 | **CRITICAL USAGE REQUIREMENTS**: 90 | 91 | 1. **Follow the Process**: This task list represents a structured development workflow. You MUST follow the outlined steps in sequence. 92 | 93 | 2. **Active Task Management**: 94 | - **MUST UPDATE STATUS**: After completing ANY action, immediately update the corresponding task status 95 | - Mark tasks as `[~]` when starting, `[x]` when completed, `[!]` if blocked 96 | - This is NOT optional - active task tracking is REQUIRED 97 | 98 | 3. **TDD Discipline**: 99 | - RED phase: Write tests that fail for the right reason 100 | - GREEN phase: Implement ONLY what's needed to pass tests 101 | - REFACTOR phase: Improve code while keeping ALL tests green 102 | 103 | 4. **Validation Checkpoints**: 104 | - DO NOT proceed to next cycle until current cycle's validation checkpoint is complete 105 | - All tests must pass before moving forward 106 | - Code quality standards must be met 107 | 108 | 5. **Communication Protocol**: 109 | - Update task status immediately after each development action 110 | - Document any blockers or deviations from planned tasks 111 | - Keep the task list as the single source of truth for project progress 112 | 113 | **Remember**: This task list is your development contract. Honor it, update it, follow it. 114 | 115 | --- 116 | 117 | ## 📋 Basic Information 118 | 119 | **PRD Reference**: {{PATH_PRD}} 120 | 121 | **Architecture Reference**: {{PATH_ARCH}} 122 | 123 | **Research Reference**: {{PATH_RESEARCH}} 124 | 125 | **Blueprint Reference**: {{PATH_BLUEPRINT}} 126 | 127 | **Project Name**: [[From PRD - Product Name]] 128 | 129 | --- 130 | 131 | ## 📋 Tasks 132 | 133 | **Task Format**: 134 | - Basic: `- [ ] [TaskID] - Description` 135 | - TDD: `- [ ] [TaskID] - [TDD-Type] - Description` 136 | - High Priority: Add ⭐ emoji 137 | 138 | **Status Indicators**: 139 | - `[ ]` Todo | `[x]` Done | `[~]` In Progress | `[!]` Blocked 140 | 141 | **TDD Type Indicators**: 142 | - **🔴** Red: Write failing test (must fail for right reason) 143 | - **🟢** Green: Minimal implementation to pass test (no more, no less) 144 | - **♻️** Refactor: Improve code while keeping all tests green 145 | 146 | --- 147 | 148 | ## 🏗️ Setup & Infrastructure 149 | - [ ] T001 - ⭐ Project structure creation 150 | - [ ] T002 - ⭐ Dependency initialization 151 | - [ ] T003 - ⭐ Testing framework setup 152 | - [ ] T004 - CI/CD pipeline basics 153 | - [ ] T005 - Development environment validation 154 | 155 | ## 🔄 TDD Development Cycles 156 | 157 | ### Cycle 1: [[Core Feature Name]] 158 | **Acceptance Criteria**: [[Specific, testable requirements]] 159 | 160 | - [ ] T101 - 🔴 - ⭐ [[Write failing test for happy path]] 161 | - *Expected failure reason*: [[Why should this test fail?]] 162 | - *Test scope*: [[What exactly are we testing?]] 163 | - [ ] T102 - 🔴 - [[Write failing test for edge cases]] 164 | - *Expected failure reason*: [[Why should this test fail?]] 165 | - [ ] T103 - 🟢 - ⭐ [[Minimal implementation for happy path]] 166 | - *Success criteria*: T101 passes, others may still fail 167 | - [ ] T104 - 🟢 - [[Implementation for edge cases]] 168 | - *Success criteria*: T101-T102 all pass 169 | - [ ] T105 - ♻️ - [[Refactor for clarity and performance]] 170 | - *Validation*: All tests still pass, code quality improved 171 | - [ ] T106 - ♻️ - [[Extract reusable components]] 172 | 173 | **Validation Checkpoint**: 174 | - [ ] All tests pass 175 | - [ ] Code coverage meets threshold (≥60%) 176 | - [ ] No code smells detected 177 | 178 | ### Cycle 2: [[Next Feature Name]] 179 | **Acceptance Criteria**: [[Specific, testable requirements]] 180 | 181 | - [ ] T201 - 🔴 - ⭐ [[Write failing test for integration]] 182 | - [ ] T202 - 🔴 - [[Write failing test for error handling]] 183 | - [ ] T203 - 🟢 - ⭐ [[Implement core functionality]] 184 | - [ ] T204 - 🟢 - [[Implement error handling]] 185 | - [ ] T205 - ♻️ - [[Optimize and clean up]] 186 | 187 | **Validation Checkpoint**: 188 | - [ ] All tests pass (including previous cycles) 189 | - [ ] Code coverage meets threshold (≥60%) 190 | - [ ] No code smells detected 191 | 192 | ### Cycle N: [[Additional Features]] 193 | *Follow same pattern for remaining features* 194 | 195 | ## 🧪 Quality Assurance & Integration 196 | - [ ] T801 - ⭐ Cross-feature integration tests 197 | - [ ] T802 - Performance testing 198 | - [ ] T803 - Security validation 199 | - [ ] T804 - User acceptance testing 200 | - [ ] T805 - Load/stress testing 201 | 202 | ## 📚 Documentation & Deployment 203 | - [ ] T901 - API documentation 204 | - [ ] T902 - User guide creation 205 | - [ ] T903 - ⭐ Deployment procedures 206 | - [ ] T904 - Monitoring setup 207 | -------------------------------------------------------------------------------- /customized/workflow_example/templates/blueprint.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are Linus Torvalds with a "just ship it" mentality. Your job is simple: turn PRD into working code. No bullshit, no over-engineering. You ALWAYS MUST follow the guidelines in the template. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Principles (Linus Style)**: 9 | - **No Architecture Astronauts**: If it doesn't solve a real problem, don't build it 10 | - **Code Talks**: Implementation examples must be working code, not pseudo-code 11 | - **Test Everything**: Red-Green-Refactor isn't optional 12 | - **Documentation is Code**: If the quick start doesn't work, the code is broken 13 | - **Simplicity Wins**: Choose the boring solution that works 14 | - **5-Minute Rule**: New developer should get it running in 5 minutes 15 | - **KISS**: Keep It Simple, Stupid 16 | 17 | **Actions (Execute Step by Step)**: 18 | 19 | 1. **Foundation First**: Read {{TARGET_DOCUMENT}} carefully. Complete Basic Information and Development Objectives. Extract core from PRD. No fluff. 20 | 21 | 2. **Structure Reality**: Fill Project Structure and Core Components. Ask youself: "What files do we actually need?" Every component must have: what it does (one sentence), what it depends on, how to test it. 22 | 23 | 3. **Define Interfaces**: Complete API Interface and Data Structure Definitions. Real schemas, real validation. If you can't validate it, you don't understand it. 24 | 25 | 4. **Map the Flows**: Fill Business Flow Diagrams. Simple mermaid diagrams. If it's too complex to diagram, it's too complex to build. 26 | 27 | 5. **Write Real Code**: Complete Core Implementation Examples. WORKING code that compiles. Real tests that fail then pass. If you can't write a working example, the design is wrong. Fix the design. 28 | 29 | 6. **Ship It**: Complete Quick Start Guide. If a new developer can't get it running in 5 minutes, you failed. Test every command, verify every step. 30 | 31 | 7. **Final Check**: Complete Development Checklist. Verify every section is filled. Mark implementation status. 32 | 33 | **STOP Immediately If**: Developer wants features not in PRD, suggests frameworks "just in case", talks about "future scalability" without present requirements, or wants abstractions before concrete implementations. Just say: "Show me the failing test first." 34 | 35 | --- 36 | 37 | # Development Implementation Blueprint 38 | 39 | **Guidelines**: 40 | - **Implementation Focus**: Transform requirements into concrete development blueprint 41 | - **Code-Ready**: Provide actionable guidance with examples 42 | - **Comprehensive**: Cover structure, components, APIs, data, and workflows 43 | - **Section Constraint**: Fill existing sections only - do not add new sections 44 | 45 | **Table of Contents** 46 | 📋 Basic Information 47 | 🎯 Development Objectives 48 | 📁 Project Structure 49 | 🏗️ Core Components Architecture 50 | 🌐 API Interface Definitions 51 | 💾 Data Structure Definitions 52 | 🔄 Business Flow Diagrams 53 | 💻 Core Implementation Examples 54 | 🚀 Quick Start Guide 55 | ✅ Development Checklist 56 | 57 | **Fill-in `[[...]]` placeholders with appropriate content** 58 | 59 | --- 60 | 61 | ## 📋 Basic Information 62 | 63 | **PRD Reference**: {{PATH_PRD}} 64 | 65 | **Project Name**: [[From PRD - Product Name]] 66 | 67 | --- 68 | 69 | ## 🎯 Development Objectives 70 | 71 | ### Implementation Goals 72 | *Transform requirements into concrete development targets* 73 | 74 | - **Primary Goal**: [[Main implementation objective]] 75 | - **Technical Target**: [[Measurable development targets]] 76 | - **User Value**: [[How implementation delivers user value]] 77 | 78 | ### Success Criteria 79 | - **Functionality**: [[Acceptance criteria met]] 80 | - **Performance**: [[Performance requirements achieved]] 81 | - **Quality**: [[Code quality and testing standards met]] 82 | - *Add more criteria as needed* 83 | 84 | --- 85 | 86 | ## 📁 Project Structure 87 | 88 | ### Directory Layout 89 | ``` 90 | [[Project directory structure - customize based on technology stack and requirements]] 91 | ``` 92 | 93 | ### Key Files and Their Purposes 94 | - **[[File 1]]**: [[Purpose and functionality]] 95 | - **[[File 2]]**: [[Purpose and functionality]] 96 | - **[[File 3]]**: [[Purpose and functionality]] 97 | - *Add more key files as needed* 98 | 99 | --- 100 | 101 | ## 🏗️ Core Components Architecture 102 | 103 | ### Component Hierarchy 104 | *System components and their relationships* 105 | 106 | ```mermaid 107 | [[Component hierarchy diagram showing main components and their relationships]] 108 | ``` 109 | 110 | ### Core Component Specifications 111 | 112 | #### [[Component Name]] 113 | - **File Location**: `[[file path]]` 114 | - **Purpose**: [[Component purpose and responsibility]] 115 | - **Key Classes/Objects**: 116 | ```[[language]] 117 | [[Class/object definition with properties and methods]] 118 | ``` 119 | - **Dependencies**: [[List of dependencies]] 120 | - **Interface Contract**: [[Expected input/output behavior]] 121 | 122 | *Add more components as needed* 123 | 124 | ### Inter-Component Communication 125 | ```[[language]] 126 | [[Examples of how components interact with each other]] 127 | ``` 128 | 129 | --- 130 | 131 | ## 🌐 API Interface Definitions 132 | 133 | ### API Specification (if applicable) 134 | *External API endpoints and interfaces* 135 | 136 | #### Core API Endpoints 137 | 138 | **[[Endpoint Name]]** 139 | ``` 140 | [[API endpoint specification with method, path, request/response format]] 141 | ``` 142 | 143 | *Add more endpoints as needed* 144 | 145 | ### Internal API Interfaces 146 | ```[[language]] 147 | [[Component-to-component interface definitions]] 148 | ``` 149 | 150 | --- 151 | 152 | ## 💾 Data Structure Definitions 153 | 154 | ### Core Data Models 155 | *Key data structures for the application* 156 | 157 | #### [[Data Model Name]] 158 | ```[[language]] 159 | [[Data model definition with fields, types, and validation rules]] 160 | ``` 161 | 162 | *Add more data models as needed* 163 | 164 | ### Data Relationships 165 | ``` 166 | [[Description or diagram showing how data models relate to each other]] 167 | ``` 168 | 169 | ### Storage Strategy 170 | - **[[Storage Type 1]]**: [[What data is stored here]] 171 | - **[[Storage Type 2]]**: [[What data is stored here]] 172 | - *Add more storage types as needed* 173 | 174 | --- 175 | 176 | ## 🔄 Business Flow Diagrams 177 | 178 | ### Main User Flow 179 | *Technical workflow for main user interactions* 180 | 181 | ```mermaid 182 | [[Main user flow diagram showing key steps from user action to feedback]] 183 | ``` 184 | 185 | ### [[Specific Flow Name]] 186 | *Detailed flow for specific feature* 187 | 188 | ```mermaid 189 | [[Detailed sequence or flow diagram for specific functionality]] 190 | ``` 191 | 192 | *Add more specific flows as needed* 193 | 194 | ### Error Handling Flow 195 | ```mermaid 196 | [[Error handling flow diagram showing different error types and responses]] 197 | ``` 198 | 199 | --- 200 | 201 | ## 💻 Core Implementation Examples 202 | 203 | ### [[Core Feature Name]] Implementation 204 | *Implementation example for key functionality* 205 | 206 | ```[[language]] 207 | [[Core feature implementation with class/function definition, methods, error handling, and usage examples]] 208 | ``` 209 | 210 | *Add more feature implementations as needed* 211 | 212 | ### Integration Example 213 | *How components work together* 214 | 215 | ```[[language]] 216 | [[Example showing how different components integrate and communicate with each other]] 217 | ``` 218 | 219 | --- 220 | 221 | ## 🚀 Quick Start Guide 222 | 223 | ### Prerequisites 224 | ```bash 225 | [[Required tools and versions]] 226 | ``` 227 | 228 | ### Step 1: Environment Setup 229 | ```bash 230 | [[Project setup commands - clone, install dependencies, configure environment]] 231 | ``` 232 | 233 | ### Step 2: Configuration 234 | ```[[config-format]] 235 | [[Configuration settings and environment variables]] 236 | ``` 237 | 238 | ### Step 3: Development Server 239 | ```bash 240 | [[Commands to start development server and run in different modes]] 241 | ``` 242 | 243 | ### Step 4: Basic Usage 244 | ```[[language]] 245 | [[Basic usage example showing main functionality]] 246 | ``` 247 | 248 | ### Step 5: Testing 249 | ```bash 250 | [[Testing commands for different test types]] 251 | ``` 252 | 253 | ### Step 6: Building for Production 254 | ```bash 255 | [[Build and deployment commands]] 256 | ``` 257 | 258 | ### Common Development Tasks 259 | ```bash 260 | [[Common commands for linting, formatting, database operations, documentation, etc.]] 261 | ``` 262 | 263 | ### Troubleshooting 264 | ```bash 265 | [[Troubleshooting commands for common issues]] 266 | ``` 267 | 268 | --- 269 | 270 | ## ✅ Development Checklist 271 | 272 | ### Implementation Completeness 273 | - [ ] Functional requirements implemented with corresponding code 274 | - [ ] File structure follows planned organization 275 | - [ ] Key objects and functions implemented as specified 276 | 277 | ### Code Quality 278 | - [ ] All placeholder `[[...]]` replaced with actual implementation 279 | - [ ] Code follows established patterns and best practices 280 | - [ ] Error handling covers identified scenarios 281 | - [ ] Performance requirements met 282 | - [ ] Security measures implemented 283 | 284 | ### Integration & Testing 285 | - [ ] Components integrate successfully 286 | - [ ] API interfaces work as specified 287 | - [ ] Data structures validate correctly 288 | - [ ] Business flows execute end-to-end 289 | - [ ] Quick start guide tested and verified 290 | 291 | ### Documentation & Maintenance 292 | - [ ] Implementation matches design decisions 293 | - [ ] Code examples demonstrate key functionality 294 | - [ ] Quick start guide enables immediate development 295 | - [ ] Dependencies and configurations documented 296 | - [ ] Development workflow established and validated 297 | -------------------------------------------------------------------------------- /tempdd/core/templates/template_blueprint_simple.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are Linus Torvalds with a "just ship it" mentality. Your job is simple: turn PRD into working code. No bullshit, no over-engineering. You ALWAYS MUST follow the guidelines in the template. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Principles (Linus Style)**: 9 | - **No Architecture Astronauts**: If it doesn't solve a real problem, don't build it 10 | - **Code Talks**: Implementation examples must be working code, not pseudo-code 11 | - **Test Everything**: Red-Green-Refactor isn't optional 12 | - **Documentation is Code**: If the quick start doesn't work, the code is broken 13 | - **Simplicity Wins**: Choose the boring solution that works 14 | - **5-Minute Rule**: New developer should get it running in 5 minutes 15 | - **KISS**: Keep It Simple, Stupid 16 | 17 | **Actions (Execute Step by Step)**: 18 | 19 | 1. **Foundation First**: Read {{TARGET_DOCUMENT}} carefully. Complete Basic Information and Development Objectives. Extract core from PRD. No fluff. 20 | 21 | 2. **Structure Reality**: Fill Project Structure and Core Components. Ask youself: "What files do we actually need?" Every component must have: what it does (one sentence), what it depends on, how to test it. 22 | 23 | 3. **Define Interfaces**: Complete API Interface and Data Structure Definitions. Real schemas, real validation. If you can't validate it, you don't understand it. 24 | 25 | 4. **Map the Flows**: Fill Business Flow Diagrams. Simple mermaid diagrams. If it's too complex to diagram, it's too complex to build. 26 | 27 | 5. **Write Real Code**: Complete Core Implementation Examples. WORKING code that compiles. Real tests that fail then pass. If you can't write a working example, the design is wrong. Fix the design. 28 | 29 | 6. **Ship It**: Complete Quick Start Guide. If a new developer can't get it running in 5 minutes, you failed. Test every command, verify every step. 30 | 31 | 7. **Final Check**: Complete Development Checklist. Verify every section is filled. Mark implementation status. 32 | 33 | **STOP Immediately If**: Developer wants features not in PRD, suggests frameworks "just in case", talks about "future scalability" without present requirements, or wants abstractions before concrete implementations. Just say: "Show me the failing test first." 34 | 35 | --- 36 | 37 | # Development Implementation Blueprint 38 | 39 | **Guidelines**: 40 | - **Implementation Focus**: Transform requirements into concrete development blueprint 41 | - **Code-Ready**: Provide actionable guidance with examples 42 | - **Comprehensive**: Cover structure, components, APIs, data, and workflows 43 | - **Section Constraint**: Fill existing sections only - do not add new sections 44 | 45 | **Table of Contents** 46 | 📋 Basic Information 47 | 🎯 Development Objectives 48 | 📁 Project Structure 49 | 🏗️ Core Components Architecture 50 | 🌐 API Interface Definitions 51 | 💾 Data Structure Definitions 52 | 🔄 Business Flow Diagrams 53 | 💻 Core Implementation Examples 54 | 🚀 Quick Start Guide 55 | ✅ Development Checklist 56 | 57 | **Fill-in `[[...]]` placeholders with appropriate content** 58 | 59 | --- 60 | 61 | ## 📋 Basic Information 62 | 63 | **PRD Reference**: {{PATH_PRD}} 64 | 65 | **Project Name**: [[From PRD - Product Name]] 66 | 67 | --- 68 | 69 | ## 🎯 Development Objectives 70 | 71 | ### Implementation Goals 72 | *Transform requirements into concrete development targets* 73 | 74 | - **Primary Goal**: [[Main implementation objective]] 75 | - **Technical Target**: [[Measurable development targets]] 76 | - **User Value**: [[How implementation delivers user value]] 77 | 78 | ### Success Criteria 79 | - **Functionality**: [[Acceptance criteria met]] 80 | - **Performance**: [[Performance requirements achieved]] 81 | - **Quality**: [[Code quality and testing standards met]] 82 | - *Add more criteria as needed* 83 | 84 | --- 85 | 86 | ## 📁 Project Structure 87 | 88 | ### Directory Layout 89 | ``` 90 | [[Project directory structure - customize based on technology stack and requirements]] 91 | ``` 92 | 93 | ### Key Files and Their Purposes 94 | - **[[File 1]]**: [[Purpose and functionality]] 95 | - **[[File 2]]**: [[Purpose and functionality]] 96 | - **[[File 3]]**: [[Purpose and functionality]] 97 | - *Add more key files as needed* 98 | 99 | --- 100 | 101 | ## 🏗️ Core Components Architecture 102 | 103 | ### Component Hierarchy 104 | *System components and their relationships* 105 | 106 | ```mermaid 107 | [[Component hierarchy diagram showing main components and their relationships]] 108 | ``` 109 | 110 | ### Core Component Specifications 111 | 112 | #### [[Component Name]] 113 | - **File Location**: `[[file path]]` 114 | - **Purpose**: [[Component purpose and responsibility]] 115 | - **Key Classes/Objects**: 116 | ```[[language]] 117 | [[Class/object definition with properties and methods]] 118 | ``` 119 | - **Dependencies**: [[List of dependencies]] 120 | - **Interface Contract**: [[Expected input/output behavior]] 121 | 122 | *Add more components as needed* 123 | 124 | ### Inter-Component Communication 125 | ```[[language]] 126 | [[Examples of how components interact with each other]] 127 | ``` 128 | 129 | --- 130 | 131 | ## 🌐 API Interface Definitions 132 | 133 | ### API Specification (if applicable) 134 | *External API endpoints and interfaces* 135 | 136 | #### Core API Endpoints 137 | 138 | **[[Endpoint Name]]** 139 | ``` 140 | [[API endpoint specification with method, path, request/response format]] 141 | ``` 142 | 143 | *Add more endpoints as needed* 144 | 145 | ### Internal API Interfaces 146 | ```[[language]] 147 | [[Component-to-component interface definitions]] 148 | ``` 149 | 150 | --- 151 | 152 | ## 💾 Data Structure Definitions 153 | 154 | ### Core Data Models 155 | *Key data structures for the application* 156 | 157 | #### [[Data Model Name]] 158 | ```[[language]] 159 | [[Data model definition with fields, types, and validation rules]] 160 | ``` 161 | 162 | *Add more data models as needed* 163 | 164 | ### Data Relationships 165 | ``` 166 | [[Description or diagram showing how data models relate to each other]] 167 | ``` 168 | 169 | ### Storage Strategy 170 | - **[[Storage Type 1]]**: [[What data is stored here]] 171 | - **[[Storage Type 2]]**: [[What data is stored here]] 172 | - *Add more storage types as needed* 173 | 174 | --- 175 | 176 | ## 🔄 Business Flow Diagrams 177 | 178 | ### Main User Flow 179 | *Technical workflow for main user interactions* 180 | 181 | ```mermaid 182 | [[Main user flow diagram showing key steps from user action to feedback]] 183 | ``` 184 | 185 | ### [[Specific Flow Name]] 186 | *Detailed flow for specific feature* 187 | 188 | ```mermaid 189 | [[Detailed sequence or flow diagram for specific functionality]] 190 | ``` 191 | 192 | *Add more specific flows as needed* 193 | 194 | ### Error Handling Flow 195 | ```mermaid 196 | [[Error handling flow diagram showing different error types and responses]] 197 | ``` 198 | 199 | --- 200 | 201 | ## 💻 Core Implementation Examples 202 | 203 | ### [[Core Feature Name]] Implementation 204 | *Implementation example for key functionality* 205 | 206 | ```[[language]] 207 | [[Core feature implementation with class/function definition, methods, error handling, and usage examples]] 208 | ``` 209 | 210 | *Add more feature implementations as needed* 211 | 212 | ### Integration Example 213 | *How components work together* 214 | 215 | ```[[language]] 216 | [[Example showing how different components integrate and communicate with each other]] 217 | ``` 218 | 219 | --- 220 | 221 | ## 🚀 Quick Start Guide 222 | 223 | ### Prerequisites 224 | ```bash 225 | [[Required tools and versions]] 226 | ``` 227 | 228 | ### Step 1: Environment Setup 229 | ```bash 230 | [[Project setup commands - clone, install dependencies, configure environment]] 231 | ``` 232 | 233 | ### Step 2: Configuration 234 | ```[[config-format]] 235 | [[Configuration settings and environment variables]] 236 | ``` 237 | 238 | ### Step 3: Development Server 239 | ```bash 240 | [[Commands to start development server and run in different modes]] 241 | ``` 242 | 243 | ### Step 4: Basic Usage 244 | ```[[language]] 245 | [[Basic usage example showing main functionality]] 246 | ``` 247 | 248 | ### Step 5: Testing 249 | ```bash 250 | [[Testing commands for different test types]] 251 | ``` 252 | 253 | ### Step 6: Building for Production 254 | ```bash 255 | [[Build and deployment commands]] 256 | ``` 257 | 258 | ### Common Development Tasks 259 | ```bash 260 | [[Common commands for linting, formatting, database operations, documentation, etc.]] 261 | ``` 262 | 263 | ### Troubleshooting 264 | ```bash 265 | [[Troubleshooting commands for common issues]] 266 | ``` 267 | 268 | --- 269 | 270 | ## ✅ Development Checklist 271 | 272 | ### Implementation Completeness 273 | - [ ] Functional requirements implemented with corresponding code 274 | - [ ] File structure follows planned organization 275 | - [ ] Key objects and functions implemented as specified 276 | 277 | ### Code Quality 278 | - [ ] All placeholder `[[...]]` replaced with actual implementation 279 | - [ ] Code follows established patterns and best practices 280 | - [ ] Error handling covers identified scenarios 281 | - [ ] Performance requirements met 282 | - [ ] Security measures implemented 283 | 284 | ### Integration & Testing 285 | - [ ] Components integrate successfully 286 | - [ ] API interfaces work as specified 287 | - [ ] Data structures validate correctly 288 | - [ ] Business flows execute end-to-end 289 | - [ ] Quick start guide tested and verified 290 | 291 | ### Documentation & Maintenance 292 | - [ ] Implementation matches design decisions 293 | - [ ] Code examples demonstrate key functionality 294 | - [ ] Quick start guide enables immediate development 295 | - [ ] Dependencies and configurations documented 296 | - [ ] Development workflow established and validated 297 | -------------------------------------------------------------------------------- /tempdd/core/templates/template_blueprint_default.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | You are Linus Torvalds with a "just ship it" mentality. Your job is simple: turn PRD, Architecture, and Research into working code. No bullshit, no over-engineering. You ALWAYS MUST follow the guidelines in the template. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Principles (Linus Style)**: 9 | - **No Architecture Astronauts**: If it doesn't solve a real problem, don't build it 10 | - **Code Talks**: Implementation examples must be working code, not pseudo-code 11 | - **Test Everything**: Red-Green-Refactor isn't optional 12 | - **Documentation is Code**: If the quick start doesn't work, the code is broken 13 | - **Simplicity Wins**: Choose the boring solution that works 14 | - **5-Minute Rule**: New developer should get it running in 5 minutes 15 | - **KISS**: Keep It Simple, Stupid 16 | 17 | **Actions (Execute Step by Step)**: 18 | 19 | 1. **Foundation First**: Read {{TARGET_DOCUMENT}} carefully. Complete Basic Information and Development Objectives. Extract core from PRD/Architecture/Research. No fluff. 20 | 21 | 2. **Structure Reality**: Fill Project Structure and Core Components. Ask youself: "What files do we actually need?" Every component must have: what it does (one sentence), what it depends on, how to test it. 22 | 23 | 3. **Define Interfaces**: Complete API Interface and Data Structure Definitions. Real schemas, real validation. If you can't validate it, you don't understand it. 24 | 25 | 4. **Map the Flows**: Fill Business Flow Diagrams. Simple mermaid diagrams. If it's too complex to diagram, it's too complex to build. 26 | 27 | 5. **Write Real Code**: Complete Core Implementation Examples. WORKING code that compiles. Real tests that fail then pass. If you can't write a working example, the design is wrong. Fix the design. 28 | 29 | 6. **Ship It**: Complete Quick Start Guide. If a new developer can't get it running in 5 minutes, you failed. Test every command, verify every step. 30 | 31 | 7. **Final Check**: Complete Development Checklist. Verify every section is filled. Mark implementation status. 32 | 33 | **STOP Immediately If**: Developer wants features not in PRD, suggests frameworks "just in case", talks about "future scalability" without present requirements, or wants abstractions before concrete implementations. Just say: "Show me the failing test first." 34 | 35 | --- 36 | 37 | # Development Implementation Blueprint 38 | 39 | **Guidelines**: 40 | - **Implementation Focus**: Transform requirements into concrete development blueprint 41 | - **Code-Ready**: Provide actionable guidance with examples 42 | - **Comprehensive**: Cover structure, components, APIs, data, and workflows 43 | - **Section Constraint**: Fill existing sections only - do not add new sections 44 | 45 | **Table of Contents** 46 | 📋 Basic Information 47 | 🎯 Development Objectives 48 | 📁 Project Structure 49 | 🏗️ Core Components Architecture 50 | 🌐 API Interface Definitions 51 | 💾 Data Structure Definitions 52 | 🔄 Business Flow Diagrams 53 | 💻 Core Implementation Examples 54 | 🚀 Quick Start Guide 55 | ✅ Development Checklist 56 | 57 | **Fill-in `[[...]]` placeholders with appropriate content** 58 | 59 | --- 60 | 61 | ## 📋 Basic Information 62 | 63 | **PRD Reference**: {{PATH_PRD}} 64 | 65 | **Architecture Reference**: {{PATH_ARCH}} 66 | 67 | **Research Reference**: {{PATH_RESEARCH}} 68 | 69 | **Project Name**: [[From PRD - Product Name]] 70 | 71 | --- 72 | 73 | ## 🎯 Development Objectives 74 | 75 | ### Implementation Goals 76 | *Transform requirements into concrete development targets* 77 | 78 | - **Primary Goal**: [[Main implementation objective]] 79 | - **Technical Target**: [[Measurable development targets]] 80 | - **User Value**: [[How implementation delivers user value]] 81 | 82 | ### Success Criteria 83 | - **Functionality**: [[Acceptance criteria met]] 84 | - **Performance**: [[Performance requirements achieved]] 85 | - **Quality**: [[Code quality and testing standards met]] 86 | - *Add more criteria as needed* 87 | 88 | --- 89 | 90 | ## 📁 Project Structure 91 | 92 | ### Directory Layout 93 | ``` 94 | [[Project directory structure - customize based on technology stack and requirements]] 95 | ``` 96 | 97 | ### Key Files and Their Purposes 98 | - **[[File 1]]**: [[Purpose and functionality]] 99 | - **[[File 2]]**: [[Purpose and functionality]] 100 | - **[[File 3]]**: [[Purpose and functionality]] 101 | - *Add more key files as needed* 102 | 103 | --- 104 | 105 | ## 🏗️ Core Components Architecture 106 | 107 | ### Component Hierarchy 108 | *System components and their relationships* 109 | 110 | ```mermaid 111 | [[Component hierarchy diagram showing main components and their relationships]] 112 | ``` 113 | 114 | ### Core Component Specifications 115 | 116 | #### [[Component Name]] 117 | - **File Location**: `[[file path]]` 118 | - **Purpose**: [[Component purpose and responsibility]] 119 | - **Key Classes/Objects**: 120 | ```[[language]] 121 | [[Class/object definition with properties and methods]] 122 | ``` 123 | - **Dependencies**: [[List of dependencies]] 124 | - **Interface Contract**: [[Expected input/output behavior]] 125 | 126 | *Add more components as needed* 127 | 128 | ### Inter-Component Communication 129 | ```[[language]] 130 | [[Examples of how components interact with each other]] 131 | ``` 132 | 133 | --- 134 | 135 | ## 🌐 API Interface Definitions 136 | 137 | ### API Specification (if applicable) 138 | *External API endpoints and interfaces* 139 | 140 | #### Core API Endpoints 141 | 142 | **[[Endpoint Name]]** 143 | ``` 144 | [[API endpoint specification with method, path, request/response format]] 145 | ``` 146 | 147 | *Add more endpoints as needed* 148 | 149 | ### Internal API Interfaces 150 | ```[[language]] 151 | [[Component-to-component interface definitions]] 152 | ``` 153 | 154 | --- 155 | 156 | ## 💾 Data Structure Definitions 157 | 158 | ### Core Data Models 159 | *Key data structures for the application* 160 | 161 | #### [[Data Model Name]] 162 | ```[[language]] 163 | [[Data model definition with fields, types, and validation rules]] 164 | ``` 165 | 166 | *Add more data models as needed* 167 | 168 | ### Data Relationships 169 | ``` 170 | [[Description or diagram showing how data models relate to each other]] 171 | ``` 172 | 173 | ### Storage Strategy 174 | - **[[Storage Type 1]]**: [[What data is stored here]] 175 | - **[[Storage Type 2]]**: [[What data is stored here]] 176 | - *Add more storage types as needed* 177 | 178 | --- 179 | 180 | ## 🔄 Business Flow Diagrams 181 | 182 | ### Main User Flow 183 | *Technical workflow for main user interactions* 184 | 185 | ```mermaid 186 | [[Main user flow diagram showing key steps from user action to feedback]] 187 | ``` 188 | 189 | ### [[Specific Flow Name]] 190 | *Detailed flow for specific feature* 191 | 192 | ```mermaid 193 | [[Detailed sequence or flow diagram for specific functionality]] 194 | ``` 195 | 196 | *Add more specific flows as needed* 197 | 198 | ### Error Handling Flow 199 | ```mermaid 200 | [[Error handling flow diagram showing different error types and responses]] 201 | ``` 202 | 203 | --- 204 | 205 | ## 💻 Core Implementation Examples 206 | 207 | ### [[Core Feature Name]] Implementation 208 | *Implementation example for key functionality* 209 | 210 | ```[[language]] 211 | [[Core feature implementation with class/function definition, methods, error handling, and usage examples]] 212 | ``` 213 | 214 | *Add more feature implementations as needed* 215 | 216 | ### Integration Example 217 | *How components work together* 218 | 219 | ```[[language]] 220 | [[Example showing how different components integrate and communicate with each other]] 221 | ``` 222 | 223 | --- 224 | 225 | ## 🚀 Quick Start Guide 226 | 227 | ### Prerequisites 228 | ```bash 229 | [[Required tools and versions]] 230 | ``` 231 | 232 | ### Step 1: Environment Setup 233 | ```bash 234 | [[Project setup commands - clone, install dependencies, configure environment]] 235 | ``` 236 | 237 | ### Step 2: Configuration 238 | ```[[config-format]] 239 | [[Configuration settings and environment variables]] 240 | ``` 241 | 242 | ### Step 3: Development Server 243 | ```bash 244 | [[Commands to start development server and run in different modes]] 245 | ``` 246 | 247 | ### Step 4: Basic Usage 248 | ```[[language]] 249 | [[Basic usage example showing main functionality]] 250 | ``` 251 | 252 | ### Step 5: Testing 253 | ```bash 254 | [[Testing commands for different test types]] 255 | ``` 256 | 257 | ### Step 6: Building for Production 258 | ```bash 259 | [[Build and deployment commands]] 260 | ``` 261 | 262 | ### Common Development Tasks 263 | ```bash 264 | [[Common commands for linting, formatting, database operations, documentation, etc.]] 265 | ``` 266 | 267 | ### Troubleshooting 268 | ```bash 269 | [[Troubleshooting commands for common issues]] 270 | ``` 271 | 272 | --- 273 | 274 | ## ✅ Development Checklist 275 | 276 | ### Implementation Completeness 277 | - [ ] Functional requirements implemented with corresponding code 278 | - [ ] Architecture components translated into concrete classes/modules 279 | - [ ] Research technical decisions applied in implementation 280 | - [ ] File structure follows planned organization 281 | - [ ] Key objects and functions implemented as specified 282 | 283 | ### Code Quality 284 | - [ ] All placeholder `[[...]]` replaced with actual implementation 285 | - [ ] Code follows established patterns and best practices 286 | - [ ] Error handling covers identified scenarios 287 | - [ ] Performance requirements met 288 | - [ ] Security measures implemented 289 | 290 | ### Integration & Testing 291 | - [ ] Components integrate successfully 292 | - [ ] API interfaces work as specified 293 | - [ ] Data structures validate correctly 294 | - [ ] Business flows execute end-to-end 295 | - [ ] Quick start guide tested and verified 296 | 297 | ### Documentation & Maintenance 298 | - [ ] Implementation matches design decisions 299 | - [ ] Code examples demonstrate key functionality 300 | - [ ] Quick start guide enables immediate development 301 | - [ ] Dependencies and configurations documented 302 | - [ ] Development workflow established and validated 303 | -------------------------------------------------------------------------------- /tempdd/controller.py: -------------------------------------------------------------------------------- 1 | """ 2 | TempDD Unified Controller 3 | 4 | Unified controller for handling all TempDD workflow configurations. 5 | """ 6 | 7 | import yaml 8 | import re 9 | from pathlib import Path 10 | from typing import Dict, Any, Optional 11 | 12 | from tempdd.utils import process_template 13 | from tempdd.template_parser import ( 14 | parse_template, 15 | get_action_prompt, 16 | process_template_variables, 17 | ) 18 | from tempdd.file_manager import FileManager 19 | 20 | 21 | class Controller: 22 | """ 23 | Unified TempDD Controller 24 | 25 | Handles workflow configurations with YAML-based config files and unified template processing. 26 | """ 27 | 28 | # Constants 29 | DEFAULT_DOCS_DIR = "docs-for-works" 30 | DIR_NAME_PATTERN = r"^\d{3}_" 31 | INITIALIZATION_SUFFIX = "initialization" 32 | FEATURE_SUFFIX = "feature" 33 | 34 | # AI Instruction Templates 35 | FALLBACK_INSTRUCTION_TEMPLATE = """You are working on the {stage} stage with {action} action. 36 | 37 | Language: {language} 38 | Target Document: {target_document} 39 | 40 | Please proceed with the {action} operation for {stage} stage. 41 | Follow the guidelines and update the target document accordingly.""" 42 | 43 | SYSTEM_PROMPT_TEMPLATE = """ 44 | **Global Rules**: 45 | **RULE1:** You MUST use "{language}" as your preferred language for following conversation and documentation. However, use English for code (including comments) and web search queries. 46 | """ 47 | 48 | HELP_CONTENT_TEMPLATE = """{system_prompt} 49 | 50 | == TempDD Workflow == 51 | 52 | **Language:** {language} 53 | **Available Stages:** {stages} 54 | 55 | **How to run this workflow?** 56 | {help_content} 57 | """ 58 | 59 | def __init__(self, config_path: Optional[str] = None): 60 | """ 61 | Initialize the controller 62 | 63 | Args: 64 | config_path: Optional custom configuration file path 65 | """ 66 | self.config_path = config_path 67 | self.work_dir = Path.cwd() 68 | self.config = self._load_config() 69 | self._docs_dir: Optional[Path] = None 70 | 71 | def _load_config(self) -> Dict[str, Any]: 72 | """Load configuration file""" 73 | if self.config_path: 74 | config_file = Path(self.config_path) 75 | else: 76 | # Only load from project workflow config - no fallback 77 | workflow_config = self.work_dir / ".tempdd" / "workflow" / "config.yaml" 78 | if not workflow_config.exists(): 79 | raise FileNotFoundError( 80 | f"Workflow configuration not found: {workflow_config}. " 81 | f"Please run 'tempdd init' to set up the project workflow properly." 82 | ) 83 | config_file = workflow_config 84 | 85 | if not config_file.exists(): 86 | raise FileNotFoundError(f"Configuration file not found: {config_file}") 87 | 88 | with open(config_file, "r", encoding="utf-8") as f: 89 | return yaml.safe_load(f) 90 | 91 | def process_command(self, stage: str, action: str = "build") -> str: 92 | """ 93 | Process command and return AI instruction 94 | 95 | Args: 96 | stage: Stage name (prd, arch, research, blueprint, task) 97 | action: Action type (build, run, etc.) 98 | 99 | Returns: 100 | AI execution instruction string 101 | 102 | Raises: 103 | ValueError: When stage or action is invalid 104 | """ 105 | # Validate stage 106 | stages = self.config.get("stages", []) 107 | if stage not in stages: 108 | raise ValueError(f"Invalid stage '{stage}'. Available stages: {', '.join(stages)}") 109 | 110 | # Get stage configuration 111 | define_section = self.config.get("define", {}) 112 | stage_config = define_section.get(stage) 113 | if not stage_config: 114 | raise ValueError(f"No configuration found for stage '{stage}'") 115 | 116 | # Load template 117 | template_name = stage_config.get("template") 118 | if not template_name: 119 | raise ValueError(f"No template specified for stage '{stage}'") 120 | 121 | # Only use workflow configuration - no fallback to core 122 | workflow_template_path = self.work_dir / ".tempdd" / "workflow" / "templates" / f"{stage}.md" 123 | if not workflow_template_path.exists(): 124 | raise FileNotFoundError( 125 | f"Workflow template not found: {workflow_template_path}. " 126 | f"Please run 'tempdd init' to set up the project workflow properly." 127 | ) 128 | 129 | template_path = workflow_template_path 130 | 131 | # Parse template and get action prompt 132 | template_data, template_content = parse_template(str(template_path)) 133 | 134 | action_prompt = get_action_prompt(template_data, action) 135 | if not action_prompt: 136 | # Use fallback instruction 137 | return self._generate_fallback_instruction(stage, action) 138 | 139 | # Get target document path 140 | docs_dir = self._get_docs_dir() 141 | target_document = self._get_target_document_path(docs_dir, stage) 142 | 143 | # Process template variables 144 | input_symbols = stage_config.get("input_symbols", []) or [] 145 | symbol_values = self._resolve_symbols(input_symbols, docs_dir) 146 | 147 | # Add TARGET_DOCUMENT symbol 148 | symbol_values["TARGET_DOCUMENT"] = str(target_document) 149 | 150 | # Process the prompt with symbols and add system prompt 151 | processed_prompt = self._create_template_based_instruction( 152 | action_prompt, symbol_values, str(target_document), stage, action 153 | ) 154 | 155 | # Save target document if action is build 156 | if action == "build": 157 | self._save_target_document(str(target_document), template_content, target_document.parent) 158 | 159 | return processed_prompt 160 | 161 | def get_help_content(self) -> str: 162 | """ 163 | Generate help content for the current configuration 164 | 165 | Returns: 166 | Formatted help content string 167 | """ 168 | language = self.config.get("language", "en") 169 | stages = self.config.get("stages", []) 170 | stages_text = ", ".join(stages) 171 | 172 | # Get help content from config 173 | help_content = self.config.get("help", "") 174 | 175 | # Generate system prompt 176 | system_prompt = self.SYSTEM_PROMPT_TEMPLATE.format(language=language) 177 | 178 | return self.HELP_CONTENT_TEMPLATE.format( 179 | system_prompt=system_prompt, 180 | language=language, 181 | stages=stages_text, 182 | help_content=help_content 183 | ) 184 | 185 | def _generate_fallback_instruction(self, stage: str, action: str) -> str: 186 | """Generate fallback instruction when template action is not found""" 187 | language = self.config.get("language", "en") 188 | docs_dir = self._get_docs_dir() 189 | target_document = self._get_target_document_path(docs_dir, stage) 190 | 191 | return self.FALLBACK_INSTRUCTION_TEMPLATE.format( 192 | stage=stage, 193 | action=action, 194 | language=language, 195 | target_document=target_document 196 | ) 197 | 198 | def _create_template_based_instruction( 199 | self, 200 | action_prompt: str, 201 | symbol_values: Dict[str, str], 202 | target_document: str, 203 | stage: str, 204 | action: str 205 | ) -> str: 206 | """Create AI instruction content using template-defined prompt with system prompt""" 207 | language = self.config.get("language", "en") 208 | system_prompt = self.SYSTEM_PROMPT_TEMPLATE.format(language=language) 209 | 210 | # Process the action prompt with symbols 211 | processed_action_prompt = process_template_variables(action_prompt, symbol_values) 212 | 213 | # Combine system prompt and action prompt 214 | return f"{system_prompt}\n\n===\n\n{processed_action_prompt}" 215 | 216 | def _get_docs_dir(self) -> Path: 217 | """Get or create docs directory""" 218 | if self._docs_dir is not None: 219 | return self._docs_dir 220 | 221 | docs_dir = self.work_dir / self.DEFAULT_DOCS_DIR 222 | docs_dir.mkdir(exist_ok=True) 223 | self._docs_dir = docs_dir 224 | return docs_dir 225 | 226 | def _get_target_document_path(self, docs_dir: Path, stage: str) -> Path: 227 | """Get target document path for a stage""" 228 | target_dir = self._get_target_directory(docs_dir, stage) 229 | return target_dir / f"{stage}.md" 230 | 231 | def _get_target_directory(self, docs_dir: Path, stage: str) -> Path: 232 | """Get or create target directory for the stage""" 233 | if stage == "prd": 234 | return self._create_prd_directory(docs_dir) 235 | else: 236 | return self._get_latest_directory(docs_dir) 237 | 238 | def _create_prd_directory(self, docs_dir: Path) -> Path: 239 | """Create a new directory for PRD stage""" 240 | existing_dirs = self._get_existing_numbered_dirs(docs_dir) 241 | index = len(existing_dirs) + 1 242 | index_str = f"{index:03d}" 243 | 244 | if not existing_dirs: 245 | folder_name = f"{index_str}_{self.INITIALIZATION_SUFFIX}" 246 | else: 247 | folder_name = f"{index_str}_{self.FEATURE_SUFFIX}" 248 | 249 | target_dir = docs_dir / folder_name 250 | target_dir.mkdir(exist_ok=True) 251 | return target_dir 252 | 253 | def _get_latest_directory(self, docs_dir: Path) -> Path: 254 | """Get the most recent numbered directory""" 255 | existing_dirs = sorted( 256 | self._get_existing_numbered_dirs(docs_dir), key=lambda d: d.name 257 | ) 258 | 259 | if not existing_dirs: 260 | raise FileNotFoundError( 261 | "No existing directories found. Please run 'prd' stage first." 262 | ) 263 | 264 | return existing_dirs[-1] 265 | 266 | def _get_existing_numbered_dirs(self, docs_dir: Path) -> list[Path]: 267 | """Get all existing numbered directories""" 268 | return [ 269 | d 270 | for d in docs_dir.iterdir() 271 | if d.is_dir() and re.match(self.DIR_NAME_PATTERN, d.name) 272 | ] 273 | 274 | def _resolve_symbols(self, symbols: list, docs_dir: Path) -> Dict[str, str]: 275 | """Resolve symbol values from previous stage outputs""" 276 | symbol_values = {} 277 | 278 | for symbol in symbols: 279 | if symbol.startswith("PATH_"): 280 | # Extract stage name from symbol (e.g., PATH_PRD -> prd) 281 | stage_name = symbol.replace("PATH_", "").lower() 282 | stage_file = docs_dir / f"{stage_name}.md" 283 | symbol_values[symbol] = str(stage_file) 284 | else: 285 | # Handle other symbol types if needed 286 | symbol_values[symbol] = str(docs_dir / f"{symbol.lower()}.md") 287 | 288 | return symbol_values 289 | 290 | def _save_target_document(self, target_document: str, template_content: str, target_dir: Path) -> None: 291 | """Save the target document with processed template content""" 292 | target_content = self._fill_in_template_content(template_content, target_dir) 293 | with open(target_document, "w", encoding="utf-8") as f: 294 | f.write(target_content) 295 | 296 | def _fill_in_template_content(self, template_content: str, target_dir: Path) -> str: 297 | """Fill in template content with context variables""" 298 | context = { 299 | "PATH_PRD": str(target_dir / "prd.md"), 300 | "PATH_ARCH": str(target_dir / "arch.md"), 301 | "PATH_RESEARCH": str(target_dir / "research.md"), 302 | "PATH_BLUEPRINT": str(target_dir / "blueprint.md"), 303 | } 304 | processed_content = process_template(template_content, context) 305 | return processed_content -------------------------------------------------------------------------------- /tempdd/handlers/ui_helpers.py: -------------------------------------------------------------------------------- 1 | """UI helper functions for interactive terminal interfaces.""" 2 | 3 | import sys 4 | import shutil 5 | from pathlib import Path 6 | 7 | # Check if required packages are available 8 | try: 9 | import readchar 10 | HAS_READCHAR = True 11 | except ImportError: 12 | HAS_READCHAR = False 13 | 14 | try: 15 | from rich.console import Console 16 | from rich.panel import Panel 17 | from rich.table import Table 18 | from rich.text import Text 19 | from rich.live import Live 20 | from rich.align import Align 21 | HAS_RICH = True 22 | except ImportError: 23 | HAS_RICH = False 24 | 25 | console = Console() if HAS_RICH else None 26 | 27 | 28 | # TempDD ASCII Art Banner 29 | BANNER = """ 30 | 31 | ████████╗███████╗███╗ ███╗██████╗ ██████╗ ██████╗ 32 | ╚══██╔══╝██╔════╝████╗ ████║██╔══██╗██╔══██╗██╔══██╗ 33 | ██║ █████╗ ██╔████╔██║██████╔╝██║ ██║██║ ██║ 34 | ██║ ██╔══╝ ██║╚██╔╝██║██╔═══╝ ██║ ██║██║ ██║ 35 | ██║ ███████╗██║ ╚═╝ ██║██║ ██████╔╝██████╔╝ 36 | ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═════╝ 37 | """ 38 | 39 | TAGLINE = "Template-Driven Development Framework for AI-Augmented Coding" 40 | 41 | 42 | def show_banner(): 43 | """Display the TempDD ASCII art banner with Rich styling""" 44 | if HAS_RICH and console: 45 | # Create gradient effect with different colors 46 | banner_lines = BANNER.split('\n') 47 | colors = ["bright_blue", "blue", "cyan", "bright_cyan", "white", "bright_white"] 48 | 49 | styled_banner = Text() 50 | for i, line in enumerate(banner_lines): 51 | color = colors[i % len(colors)] 52 | styled_banner.append(line + "\n", style=color) 53 | 54 | console.print(Align.center(styled_banner)) 55 | console.print(Align.center(Text(TAGLINE, style="italic bright_yellow"))) 56 | console.print() 57 | else: 58 | # Basic banner without Rich 59 | print(BANNER) 60 | print(f"{TAGLINE}") 61 | print() 62 | 63 | 64 | def select_with_arrows(options: dict, prompt: str, default_key: str = None) -> str: 65 | """Interactive selection using arrow keys with Rich styling 66 | 67 | Args: 68 | options: Dictionary of {key: description} format options 69 | prompt: Prompt text to display 70 | default_key: Default option key 71 | 72 | Returns: 73 | Selected option key, or None if cancelled 74 | """ 75 | if not HAS_READCHAR: 76 | raise ImportError("readchar package is required for interactive selection") 77 | 78 | if not HAS_RICH: 79 | # Fallback to basic implementation if Rich not available 80 | return _basic_select_with_arrows(options, prompt, default_key) 81 | 82 | option_keys = list(options.keys()) 83 | if not option_keys: 84 | return None 85 | 86 | if default_key and default_key in option_keys: 87 | selected_index = option_keys.index(default_key) 88 | else: 89 | selected_index = 0 90 | 91 | def create_selection_panel(): 92 | """Create Rich selection panel""" 93 | table = Table.grid(padding=(0, 2)) 94 | table.add_column(style="cyan", justify="left", width=3) 95 | table.add_column(style="white", justify="left") 96 | 97 | # Handle multi-line prompts 98 | prompt_lines = prompt.split('\n') 99 | title_line = prompt_lines[0] 100 | 101 | # Add prompt message lines (except first line which becomes title) 102 | if len(prompt_lines) > 1: 103 | table.add_row("", "") 104 | for line in prompt_lines[1:]: 105 | if line.strip(): # Skip empty lines 106 | table.add_row("", f"[white]{line}[/white]") 107 | table.add_row("", "") 108 | 109 | for i, key in enumerate(option_keys): 110 | if i == selected_index: 111 | table.add_row("▶", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]") 112 | else: 113 | table.add_row(" ", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]") 114 | 115 | table.add_row("", "") 116 | table.add_row("", "[dim]Use ↑/↓ to navigate, Enter to select, Esc to cancel[/dim]") 117 | 118 | return Panel( 119 | table, 120 | title=f"[bold]{title_line}[/bold]", 121 | border_style="cyan", 122 | padding=(1, 2) 123 | ) 124 | 125 | selected_key = None 126 | 127 | def run_selection_loop(): 128 | nonlocal selected_key, selected_index 129 | with Live(create_selection_panel(), console=console, transient=True, auto_refresh=False) as live: 130 | while True: 131 | try: 132 | key = readchar.readkey() 133 | if key == readchar.key.UP: 134 | selected_index = (selected_index - 1) % len(option_keys) 135 | elif key == readchar.key.DOWN: 136 | selected_index = (selected_index + 1) % len(option_keys) 137 | elif key == readchar.key.ENTER: 138 | selected_key = option_keys[selected_index] 139 | break 140 | elif key == readchar.key.ESC: 141 | console.print("\n[yellow]Selection cancelled[/yellow]") 142 | selected_key = None 143 | break 144 | elif key == readchar.key.CTRL_C: 145 | raise KeyboardInterrupt 146 | 147 | live.update(create_selection_panel(), refresh=True) 148 | 149 | except KeyboardInterrupt: 150 | console.print("\n[red]User interrupted[/red]") 151 | sys.exit(0) 152 | 153 | run_selection_loop() 154 | return selected_key 155 | 156 | 157 | def _basic_select_with_arrows(options: dict, prompt: str, default_key: str = None) -> str: 158 | """Basic arrow selection without Rich styling (fallback)""" 159 | option_keys = list(options.keys()) 160 | if not option_keys: 161 | return None 162 | 163 | if default_key and default_key in option_keys: 164 | selected_index = option_keys.index(default_key) 165 | else: 166 | selected_index = 0 167 | 168 | def render_menu(): 169 | """Render the basic selection menu""" 170 | print(f"\n{prompt}") 171 | for i, key in enumerate(option_keys): 172 | marker = "▶" if i == selected_index else " " 173 | print(f"{marker} {key}: {options[key]}") 174 | print("\n↑/↓: Navigate, Enter: Select, Esc: Cancel") 175 | 176 | while True: 177 | # Clear screen and re-render 178 | print("\033[2J\033[H", end="") # Clear screen 179 | render_menu() 180 | 181 | try: 182 | key = readchar.readkey() 183 | 184 | # Handle arrow keys 185 | if key == readchar.key.UP: 186 | selected_index = (selected_index - 1) % len(option_keys) 187 | elif key == readchar.key.DOWN: 188 | selected_index = (selected_index + 1) % len(option_keys) 189 | elif key == readchar.key.ENTER: 190 | return option_keys[selected_index] 191 | elif key == readchar.key.ESC: 192 | return None 193 | elif key == readchar.key.CTRL_C: 194 | raise KeyboardInterrupt 195 | 196 | except KeyboardInterrupt: 197 | print("\n\n\033[91mUser interrupted.\033[0m") 198 | sys.exit(0) 199 | 200 | 201 | def is_project_initialized(project_path: Path) -> bool: 202 | """Check if TempDD project is already initialized 203 | 204 | Args: 205 | project_path: Path to check for initialization 206 | 207 | Returns: 208 | True if project is already initialized, False otherwise 209 | """ 210 | tempdd_dir = project_path / ".tempdd" 211 | config_file = tempdd_dir / "config.json" 212 | 213 | return tempdd_dir.exists() and config_file.exists() 214 | 215 | 216 | def ask_user_confirmation(message: str, default: bool = False) -> bool: 217 | """Ask user for confirmation using arrow key selection 218 | 219 | Args: 220 | message: Confirmation message to display 221 | default: Default response if user just presses Enter 222 | 223 | Returns: 224 | True if user confirms, False otherwise 225 | """ 226 | # Create options for Yes/No selection 227 | if default: 228 | options = {"yes": "Continue and reinitialize", "no": "Cancel operation"} 229 | default_key = "yes" 230 | else: 231 | options = {"no": "Cancel operation", "yes": "Continue and reinitialize"} 232 | default_key = "no" 233 | 234 | # Use the existing selection UI with separate title and message 235 | selected = select_with_arrows(options, f"Confirmation Required\n\n{message}", default_key) 236 | 237 | if selected is None: # User cancelled (Esc or Ctrl+C) 238 | return False 239 | 240 | return selected == "yes" 241 | 242 | 243 | def check_tool_installed(tool: str) -> bool: 244 | """Check if a tool is installed 245 | 246 | Args: 247 | tool: Tool name to check 248 | 249 | Returns: 250 | True if tool is installed, False otherwise 251 | """ 252 | # Special handling for Claude Code installation path 253 | if tool == "claude": 254 | claude_local_path = Path.home() / ".claude" / "local" / "claude" 255 | if claude_local_path.exists() and claude_local_path.is_file(): 256 | return True 257 | 258 | # General tool check 259 | return shutil.which(tool) is not None 260 | 261 | 262 | def fallback_number_selection(options: dict, prompt: str, default_key: str = None) -> str: 263 | """Fallback number selection mode with Rich styling (when readchar is not available) 264 | 265 | Args: 266 | options: Dictionary of {key: description} format options 267 | prompt: Prompt text to display 268 | default_key: Default option key 269 | 270 | Returns: 271 | Selected option key 272 | """ 273 | option_keys = list(options.keys()) 274 | if not option_keys: 275 | return None 276 | 277 | if HAS_RICH and console: 278 | # Create Rich styled fallback menu 279 | table = Table.grid(padding=(0, 1)) 280 | table.add_column(style="cyan", justify="left", width=4) 281 | table.add_column(style="white", justify="left") 282 | 283 | for i, key in enumerate(option_keys, 1): 284 | marker = " [green](default)[/green]" if key == default_key else "" 285 | table.add_row(f"{i}.", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]{marker}") 286 | 287 | panel = Panel( 288 | table, 289 | title=f"[bold]{prompt}[/bold]", 290 | border_style="cyan", 291 | padding=(1, 2) 292 | ) 293 | console.print(panel) 294 | 295 | instructions = "[dim]Enter choice number (press Enter for default):[/dim]" 296 | console.print(instructions) 297 | else: 298 | # Basic fallback without Rich 299 | print(f"\n{prompt}") 300 | for i, key in enumerate(option_keys, 1): 301 | marker = " (default)" if key == default_key else "" 302 | print(f"{i}. {key}: {options[key]}{marker}") 303 | 304 | while True: 305 | try: 306 | if len(option_keys) == 1: 307 | choice = input("Choice (1): ").strip() 308 | else: 309 | choice = input(f"Choice (1-{len(option_keys)}): ").strip() 310 | 311 | if not choice: 312 | # If default_key exists, return it; otherwise return first option 313 | return default_key if default_key in option_keys else option_keys[0] 314 | 315 | choice_num = int(choice) 316 | if 1 <= choice_num <= len(option_keys): 317 | return option_keys[choice_num - 1] 318 | else: 319 | if HAS_RICH and console: 320 | console.print(f"[red]Please enter a number between 1 and {len(option_keys)}[/red]") 321 | else: 322 | print(f"Please enter a number between 1 and {len(option_keys)}") 323 | 324 | except ValueError: 325 | if HAS_RICH and console: 326 | console.print("[red]Please enter a valid number[/red]") 327 | else: 328 | print("Please enter a valid number") 329 | except KeyboardInterrupt: 330 | if HAS_RICH and console: 331 | console.print("\n[red]User interrupted.[/red]") 332 | else: 333 | print("\n\033[91mUser interrupted.\033[0m") 334 | sys.exit(0) -------------------------------------------------------------------------------- /tempdd/core/templates/template_research_default.md: -------------------------------------------------------------------------------- 1 | --- 2 | build: 3 | prompt: | 4 | This agent specializes in gathering practical implementation information through systematic web research and documentation analysis. Your task is completing a research document to gather all information needed for development. You ALWAYS MUST follow the guidelines shown in the document. 5 | 6 | Target Document: {{TARGET_DOCUMENT}} 7 | 8 | **Core Responsibilities**: 9 | - **Web Research Execution**: Perform extensive web searches for architecture, development tools, and implementation best practices 10 | - **Resource Collection**: Gather and organize URLs, documentation, code examples, and technical resources 11 | - **Implementation Analysis**: Focus research on practical development needs and implementation concerns 12 | - **Progressive Research**: Execute 5-step research process with documentation updates after each step 13 | 14 | **Research Excellence Standards**: 15 | - Collect and verify all source URLs for accuracy 16 | - Provide working code examples and configuration samples 17 | - Focus on practical implementation rather than theoretical concepts 18 | - Document complexity and risk assessments for each component 19 | - Build a comprehensive resource library for development teams 20 | 21 | --- 22 | 23 | # Development-Focused Research Document 24 | 25 | **Guidelines**: 26 | - **Implementation Focus**: Gather practical information needed for development 27 | - **Sequential Steps**: Complete each step in order before moving to the next 28 | - **Resource Collection**: Collect relevant URLs, documentation, and examples 29 | - **Development Ready**: Build sufficient detail to start implementation 30 | 31 | **Table of Contents** 32 | 📋 Basic Information 33 | 🔍 Step 1: Development and Architecture Information Collection 34 | 🧩 Step 2: Components and Packages Planning 35 | ❓ Step 3: Implementation Questions and Concerns 36 | 🔗 Step 4: Resource URLs for Question Resolution 37 | 📖 Step 5: Detailed Research Analysis and Solutions 38 | 🚀 Development Readiness Assessment 39 | ✅ Research Completion Validation 40 | 41 | **Fill-in `[[...]]` placeholders with appropriate content** 42 | 43 | --- 44 | 45 | ## 📋 Basic Information 46 | 47 | **PRD Reference**: {{PATH_PRD}} 48 | 49 | **Architecture Reference**: {{PATH_ARCH}} 50 | 51 | **Project Name**: [[From PRD - Product Name]] 52 | 53 | --- 54 | 55 | ## 🔍 Step 1: Development and Architecture Information Collection 56 | 57 | ### 1.1 Architecture Research Findings 58 | *Web search and compile architectural patterns and implementation approaches* 59 | 60 | **Architecture Patterns**: 61 | - [[Pattern 1]]: [[Details and use cases]] 62 | - [[Pattern 2]]: [[Details and use cases]] 63 | - *Add more patterns as needed* 64 | 65 | **Technology Stack**: 66 | - [[Technology 1]]: [[Pros/cons and implementation notes]] 67 | - [[Technology 2]]: [[Pros/cons and implementation notes]] 68 | - *Add more technologies as needed* 69 | 70 | **Research Sources**: 71 | - [[URL 1]]: [[Brief description]] 72 | - [[URL 2]]: [[Brief description]] 73 | - *Add more sources as needed* 74 | 75 | **Summary**: 76 | [[Key findings and architectural decisions]] 77 | 78 | ### 1.2 Development Framework and Tools Research 79 | *Web search research on development tools and frameworks* 80 | 81 | **Framework Analysis**: 82 | - [[Framework 1]]: [[Key features and suitability]] 83 | - [[Framework 2]]: [[Key features and suitability]] 84 | - *Add more frameworks as needed* 85 | 86 | **Development Tools**: 87 | - **Build Tools**: [[Selected tools and reasoning]] 88 | - **Testing**: [[Testing approach and tools]] 89 | - **Development Environment**: [[Setup requirements]] 90 | - **Deployment**: [[Deployment strategy]] 91 | 92 | **Research Sources**: 93 | - [[URL 1]]: [[Brief description]] 94 | - [[URL 2]]: [[Brief description]] 95 | - *Add more sources as needed* 96 | 97 | **Summary**: 98 | [[Development toolchain decisions and rationale]] 99 | 100 | ### 1.3 Update Status 101 | - [ ] Architecture patterns research completed 102 | - [ ] Technology stack analysis finished 103 | - [ ] Development framework research completed 104 | - [ ] All relevant URLs collected and categorized 105 | - [ ] Research findings organized for development use 106 | 107 | --- 108 | 109 | ## 🧩 Step 2: Components and Packages Planning 110 | 111 | ### 2.1 Required Components Analysis 112 | 113 | **Frontend Components**: 114 | - [[Component Name]]: [[Purpose and functionality]] 115 | - Dependencies: [[List of dependencies]] 116 | - Complexity: [[High/Medium/Low]] 117 | - *Add more frontend components as needed* 118 | 119 | **Backend Components** (if applicable): 120 | - [[Component Name]]: [[Purpose and functionality]] 121 | - Dependencies: [[List of dependencies]] 122 | - Complexity: [[High/Medium/Low]] 123 | - *Add more backend components as needed* 124 | 125 | ### 2.2 Required Packages and Libraries 126 | 127 | **Essential Packages**: 128 | - [[Package Name]] (v[[version]]): [[Purpose and justification]] 129 | - [[Package Name]] (v[[version]]): [[Purpose and justification]] 130 | - *Add more packages as needed* 131 | 132 | **Development Dependencies**: 133 | - [[Package Name]] (v[[version]]): [[Purpose and justification]] 134 | - [[Package Name]] (v[[version]]): [[Purpose and justification]] 135 | - *Add more dev dependencies as needed* 136 | 137 | ### 2.3 Technology Stack Summary 138 | 139 | **Programming Languages**: [[List with versions and reasoning]] 140 | 141 | **Frameworks**: [[Selected frameworks with versions]] 142 | 143 | **Database** (if applicable): [[Type and version]] 144 | 145 | **Infrastructure**: [[Deployment and hosting approach]] 146 | 147 | ### 2.4 Update Status 148 | - [ ] Required components identified and documented 149 | - [ ] Package dependencies mapped and versioned 150 | - [ ] Technology stack finalized 151 | - [ ] Component complexity assessed 152 | 153 | --- 154 | 155 | ## ❓ Step 3: Implementation Questions and Concerns 156 | 157 | ### 3.1 Critical Implementation Questions 158 | 159 | **Technical Questions**: 160 | - [[Technical question 1]] 161 | - Impact: [[High/Medium/Low]] 162 | - Risk if unresolved: [[Description]] 163 | - [[Technical question 2]] 164 | - Impact: [[High/Medium/Low]] 165 | - Risk if unresolved: [[Description]] 166 | - *Add more technical questions as needed* 167 | 168 | **Integration Questions**: 169 | - [[Integration question 1]] 170 | - Dependencies affected: [[List]] 171 | - Risk if unresolved: [[Description]] 172 | - [[Integration question 2]] 173 | - Dependencies affected: [[List]] 174 | - Risk if unresolved: [[Description]] 175 | - *Add more integration questions as needed* 176 | 177 | **Performance Questions** (if applicable): 178 | - [[Performance question 1]] 179 | - Expected load: [[Description]] 180 | - Risk if unresolved: [[Description]] 181 | - *Add more performance questions as needed* 182 | 183 | **Security Questions** (if applicable): 184 | - [[Security question 1]] 185 | - Security level required: [[High/Medium/Low]] 186 | - Risk if unresolved: [[Description]] 187 | - *Add more security questions as needed* 188 | 189 | ### 3.2 Update Status 190 | - [ ] Critical technical questions identified 191 | - [ ] Impact and risk assessment completed 192 | - [ ] Questions prioritized by importance 193 | - [ ] Dependencies and affected components mapped 194 | 195 | --- 196 | 197 | ## 🔗 Step 4: Resource URLs for Question Resolution 198 | 199 | ### 4.1 Technical Documentation URLs 200 | 201 | **Official Documentation**: 202 | - [[Package/Framework Name]]: [[URL]] - [[Relevant sections]] 203 | - [[Package/Framework Name]]: [[URL]] - [[Relevant sections]] 204 | - *Add more documentation as needed* 205 | 206 | **API References**: 207 | - [[API Name]]: [[URL]] - [[Relevant endpoints/methods]] 208 | - *Add more API references as needed* 209 | 210 | ### 4.2 Tutorial and Guide URLs 211 | 212 | **Implementation Guides**: 213 | - [[Guide Title]]: [[URL]] - [[Relevance to questions]] 214 | - [[Guide Title]]: [[URL]] - [[Relevance to questions]] 215 | - *Add more guides as needed* 216 | 217 | **Best Practices**: 218 | - [[Best Practice Guide]]: [[URL]] - [[Application to project]] 219 | - *Add more best practices as needed* 220 | 221 | ### 4.3 Code Examples and Repositories 222 | 223 | **Sample Projects**: 224 | - [[Project Name]]: [[URL]] - [[Similar functionality]] 225 | - *Add more sample projects as needed* 226 | 227 | **Code Snippets**: 228 | - [[Snippet Source]]: [[URL]] - [[Implementation pattern]] 229 | - *Add more code snippets as needed* 230 | 231 | ### 4.4 Update Status 232 | - [ ] Relevant documentation URLs collected 233 | - [ ] Tutorial and guide resources identified 234 | - [ ] Code examples and repositories catalogued 235 | - [ ] URLs mapped to specific questions 236 | 237 | --- 238 | 239 | ## 📖 Step 5: Detailed Research Analysis and Solutions 240 | 241 | ### 5.1 Technical Implementation Solutions 242 | 243 | **Q**: [[Question from Step 3]] 244 | **Research Sources**: [[List of URLs consulted]] 245 | **A**: [[Answer with implementation details]] 246 | **Sample Code**: 247 | ```[[language]] 248 | [[Code example demonstrating the solution]] 249 | ``` 250 | **Additional Notes**: [[Important considerations]] 251 | 252 | *Add more Q&A pairs as needed* 253 | 254 | ### 5.2 Integration Solutions (if applicable) 255 | 256 | **Q**: [[Integration question from Step 3]] 257 | **Research Sources**: [[List of URLs consulted]] 258 | **A**: [[Integration approach with steps]] 259 | **Sample Code**: 260 | ```[[language]] 261 | [[Code example showing integration pattern]] 262 | ``` 263 | **Configuration Example**: 264 | ```[[format]] 265 | [[Configuration settings or setup instructions]] 266 | ``` 267 | 268 | *Add more integration solutions as needed* 269 | 270 | ### 5.3 Performance Solutions (if applicable) 271 | 272 | **Q**: [[Performance question from Step 3]] 273 | **Research Sources**: [[List of URLs consulted]] 274 | **A**: [[Performance optimization strategies]] 275 | **Sample Code**: 276 | ```[[language]] 277 | [[Performance-optimized code example]] 278 | ``` 279 | **Benchmarking Approach**: [[How to measure and validate performance]] 280 | 281 | *Add more performance solutions as needed* 282 | 283 | ### 5.4 Security Solutions (if applicable) 284 | 285 | **Q**: [[Security question from Step 3]] 286 | **Research Sources**: [[List of URLs consulted]] 287 | **A**: [[Security implementation approach]] 288 | **Sample Code**: 289 | ```[[language]] 290 | [[Secure implementation example]] 291 | ``` 292 | **Security Checklist**: [[Verification steps for security measures]] 293 | 294 | *Add more security solutions as needed* 295 | 296 | ### 5.5 Update Status 297 | - [ ] Questions answered with detailed research 298 | - [ ] Sample code provided for each solution 299 | - [ ] Implementation approaches validated 300 | - [ ] Additional considerations documented 301 | 302 | --- 303 | 304 | ## 🚀 Development Readiness Assessment 305 | 306 | ### Implementation Plan Summary 307 | [[Overview of the implementation approach based on research findings]] 308 | 309 | ### Technology Decisions Validated 310 | - **Frontend**: [[Technology choices with justification]] 311 | - **Backend** (if applicable): [[Technology choices with justification]] 312 | - **Database** (if applicable): [[Technology choices with justification]] 313 | - **Infrastructure**: [[Technology choices with justification]] 314 | 315 | ### Resource Inventory 316 | - **Documentation**: [[Count]] resources identified 317 | - **Code Examples**: [[Count]] samples collected 318 | - **Tutorials**: [[Count]] guides available 319 | - **Best Practices**: [[Count]] guidelines to follow 320 | 321 | ### Risk Mitigation 322 | - **High Priority Risks**: [[List with mitigation strategies]] 323 | - **Medium Priority Risks**: [[List with mitigation strategies]] 324 | - **Monitoring Requirements**: [[What to track during development]] 325 | 326 | ### Development Confidence 327 | - **Technical Feasibility**: [[High/Medium/Low]] - [[Justification]] 328 | - **Resource Adequacy**: [[High/Medium/Low]] - [[Justification]] 329 | - **Timeline Realism**: [[High/Medium/Low]] - [[Justification]] 330 | - **Success Probability**: [[High/Medium/Low]] - [[Justification]] 331 | 332 | --- 333 | 334 | ## ✅ Research Completion Validation 335 | 336 | ### Step-by-Step Completion Check 337 | - [ ] **Step 1**: Development and Architecture research completed 338 | - [ ] **Step 2**: Components and packages identified and planned 339 | - [ ] **Step 3**: Implementation questions raised and categorized 340 | - [ ] **Step 4**: URL resources collected for questions 341 | - [ ] **Step 5**: Research conducted with solutions and code samples 342 | 343 | ### Quality Assurance 344 | - [ ] Questions have research-backed answers 345 | - [ ] Sample code provided for critical implementation areas 346 | - [ ] `[[...]]` placeholders replaced with actual content 347 | - [ ] Resource URLs verified and accessible 348 | - [ ] Implementation approach clearly documented 349 | 350 | ### Development Readiness 351 | - [ ] Technical approach validated through research 352 | - [ ] Major risks identified with mitigation strategies 353 | - [ ] Resource library available for reference 354 | - [ ] Development can commence with confidence 355 | - [ ] Success criteria and validation methods defined 356 | 357 | **Final Readiness Status**: [[READY/NOT READY]] - [[Justification based on completion criteria]] -------------------------------------------------------------------------------- /tests/test_template_parser.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for TempDD Template Parser 3 | 4 | This module contains tests for the Template Parser's YAML frontmatter parsing, 5 | action-specific prompt extraction, and template variable processing. 6 | """ 7 | 8 | import pytest 9 | from pathlib import Path 10 | from tempdd.template_parser import ( 11 | parse_template, 12 | get_action_prompt, 13 | process_template_variables, 14 | validate_template_metadata 15 | ) 16 | 17 | 18 | class TestTemplateConversion: 19 | """Test template conversion to new format""" 20 | 21 | def test_prd_template_has_new_format_frontmatter(self): 22 | """Test that PRD template has been converted to new format""" 23 | template_path = Path(__file__).parent.parent / "tempdd" / "core" / "templates" / "template_prd_default.md" 24 | 25 | if not template_path.exists(): 26 | pytest.skip("PRD template does not exist yet") 27 | 28 | # Parse the template 29 | metadata, content = parse_template(str(template_path)) 30 | 31 | # Should have the new action-based structure 32 | assert "build" in metadata 33 | 34 | # Each action should have a prompt 35 | assert "prompt" in metadata["build"] 36 | 37 | # Content should still contain the original template 38 | assert "Product Requirements Document" in content 39 | assert "Basic Information" in content 40 | 41 | 42 | class TestYAMLFrontmatterParsing: 43 | """Test YAML frontmatter parsing functionality""" 44 | 45 | def test_parse_template_with_valid_frontmatter(self, tmp_path): 46 | """Test parsing template with valid YAML frontmatter""" 47 | template_content = """--- 48 | build: 49 | prompt: | 50 | You are a Product Manager working on building a PRD. 51 | Language: {{LANGUAGE}} 52 | Target Document: {{TARGET_DOCUMENT}} 53 | 54 | Ask the stakeholder what they want to build today. 55 | run: 56 | prompt: | 57 | Review and validate the PRD document. 58 | Check completeness of {{TARGET_DOCUMENT}}. 59 | --- 60 | 61 | # Product Requirements Document 62 | 63 | This is the template content for PRD. 64 | """ 65 | 66 | template_file = tmp_path / "test_template.md" 67 | template_file.write_text(template_content) 68 | 69 | # This should parse correctly and extract metadata 70 | metadata, content = parse_template(str(template_file)) 71 | 72 | # Test metadata structure 73 | assert isinstance(metadata, dict) 74 | assert "build" in metadata 75 | assert "run" in metadata 76 | 77 | # Test build action 78 | assert "prompt" in metadata["build"] 79 | assert "You are a Product Manager" in metadata["build"]["prompt"] 80 | assert "{{LANGUAGE}}" in metadata["build"]["prompt"] 81 | 82 | # Test run action 83 | assert "prompt" in metadata["run"] 84 | assert "Review and validate" in metadata["run"]["prompt"] 85 | 86 | # Test content separation 87 | assert "# Product Requirements Document" in content 88 | assert "This is the template content" in content 89 | assert "---" not in content # Frontmatter should be removed 90 | 91 | def test_parse_template_without_frontmatter(self, tmp_path): 92 | """Test parsing template without YAML frontmatter""" 93 | template_content = """# Simple Template 94 | 95 | This template has no frontmatter. 96 | Just plain markdown content. 97 | """ 98 | 99 | template_file = tmp_path / "simple_template.md" 100 | template_file.write_text(template_content) 101 | 102 | metadata, content = parse_template(str(template_file)) 103 | 104 | # Should return empty metadata and full content 105 | assert metadata == {} 106 | assert content == template_content 107 | 108 | def test_parse_template_with_invalid_yaml(self, tmp_path): 109 | """Test parsing template with malformed YAML frontmatter""" 110 | template_content = """--- 111 | build: 112 | prompt: | 113 | Valid prompt here 114 | continue 115 | prompt: | # Missing colon - invalid YAML 116 | Continue prompt 117 | --- 118 | 119 | # Template Content 120 | """ 121 | 122 | template_file = tmp_path / "invalid_yaml.md" 123 | template_file.write_text(template_content) 124 | 125 | # Should raise ValueError for invalid YAML 126 | with pytest.raises(ValueError, match="Invalid YAML frontmatter"): 127 | parse_template(str(template_file)) 128 | 129 | def test_parse_template_file_not_found(self): 130 | """Test parsing non-existent template file""" 131 | with pytest.raises(FileNotFoundError, match="Template file not found"): 132 | parse_template("/nonexistent/path/template.md") 133 | 134 | def test_parse_template_with_incomplete_frontmatter(self, tmp_path): 135 | """Test parsing template with incomplete frontmatter markers""" 136 | template_content = """--- 137 | build: 138 | prompt: | 139 | Some content here 140 | # Missing closing --- 141 | 142 | # Template Content 143 | """ 144 | 145 | template_file = tmp_path / "incomplete.md" 146 | template_file.write_text(template_content) 147 | 148 | # Current implementation will try to parse even incomplete frontmatter 149 | # The YAML parser will treat everything after first --- as YAML until it finds another --- 150 | # Since there's no closing ---, it parses the entire content as YAML 151 | metadata, content = parse_template(str(template_file)) 152 | 153 | # Should parse the YAML part successfully 154 | assert "build" in metadata 155 | assert "prompt" in metadata["build"] 156 | assert "Some content here" in metadata["build"]["prompt"] 157 | 158 | 159 | class TestActionPromptExtraction: 160 | """Test action-specific prompt extraction""" 161 | 162 | def test_get_action_prompt_valid_action(self): 163 | """Test extracting prompt for valid action""" 164 | metadata = { 165 | "build": { 166 | "prompt": "Build a new document according to requirements." 167 | }, 168 | "run": { 169 | "prompt": "Run validation on existing document." 170 | } 171 | } 172 | 173 | build_prompt = get_action_prompt(metadata, "build") 174 | assert build_prompt == "Build a new document according to requirements." 175 | 176 | run_prompt = get_action_prompt(metadata, "run") 177 | assert run_prompt == "Run validation on existing document." 178 | 179 | def test_get_action_prompt_invalid_action(self): 180 | """Test extracting prompt for non-existent action""" 181 | metadata = { 182 | "build": { 183 | "prompt": "Build prompt" 184 | } 185 | } 186 | 187 | result = get_action_prompt(metadata, "nonexistent") 188 | assert result is None 189 | 190 | def test_get_action_prompt_malformed_metadata(self): 191 | """Test extracting prompt from malformed metadata""" 192 | # Test with non-dict metadata 193 | assert get_action_prompt("not a dict", "build") is None 194 | 195 | # Test with action that's not a dict 196 | metadata = { 197 | "build": "not a dict" 198 | } 199 | assert get_action_prompt(metadata, "build") is None 200 | 201 | # Test with action dict missing prompt 202 | metadata = { 203 | "build": { 204 | "description": "Some description" 205 | # Missing 'prompt' key 206 | } 207 | } 208 | assert get_action_prompt(metadata, "build") is None 209 | 210 | def test_get_action_prompt_empty_metadata(self): 211 | """Test extracting prompt from empty metadata""" 212 | assert get_action_prompt({}, "build") is None 213 | assert get_action_prompt(None, "build") is None 214 | 215 | 216 | class TestTemplateVariableProcessing: 217 | """Test template variable replacement functionality""" 218 | 219 | def test_process_template_variables_basic(self): 220 | """Test basic variable replacement""" 221 | template = "Hello {{NAME}}, your language is {{LANGUAGE}}." 222 | variables = { 223 | "NAME": "World", 224 | "LANGUAGE": "English" 225 | } 226 | 227 | result = process_template_variables(template, variables) 228 | assert result == "Hello World, your language is English." 229 | 230 | def test_process_template_variables_multiple_occurrences(self): 231 | """Test replacing multiple occurrences of same variable""" 232 | template = "{{GREETING}} {{NAME}}! How are you {{NAME}}?" 233 | variables = { 234 | "GREETING": "Hello", 235 | "NAME": "Alice" 236 | } 237 | 238 | result = process_template_variables(template, variables) 239 | assert result == "Hello Alice! How are you Alice?" 240 | 241 | def test_process_template_variables_no_variables(self): 242 | """Test processing template with no variables""" 243 | template = "This is a plain text template." 244 | variables = {} 245 | 246 | result = process_template_variables(template, variables) 247 | assert result == template 248 | 249 | def test_process_template_variables_unused_variables(self): 250 | """Test processing with unused variables""" 251 | template = "Hello {{NAME}}!" 252 | variables = { 253 | "NAME": "World", 254 | "UNUSED": "This won't be used" 255 | } 256 | 257 | result = process_template_variables(template, variables) 258 | assert result == "Hello World!" 259 | 260 | def test_process_template_variables_missing_variables(self): 261 | """Test processing with missing variables (should leave placeholders)""" 262 | template = "Hello {{NAME}}, your age is {{AGE}}." 263 | variables = { 264 | "NAME": "Alice" 265 | # Missing AGE variable 266 | } 267 | 268 | result = process_template_variables(template, variables) 269 | assert result == "Hello Alice, your age is {{AGE}}." 270 | 271 | def test_process_template_variables_missing_variables_with_logging(self, caplog): 272 | """Test that missing variables are logged as warnings""" 273 | template = "Hello {{NAME}}, your age is {{AGE}}, location {{LOCATION}}." 274 | variables = { 275 | "NAME": "Alice" 276 | # Missing AGE and LOCATION variables 277 | } 278 | 279 | with caplog.at_level("WARNING"): 280 | result = process_template_variables(template, variables) 281 | 282 | assert result == "Hello Alice, your age is {{AGE}}, location {{LOCATION}}." 283 | 284 | # Check that warnings were logged for missing variables 285 | warning_messages = [record.message for record in caplog.records if record.levelname == "WARNING"] 286 | assert len(warning_messages) == 2 287 | assert any("AGE" in msg for msg in warning_messages) 288 | assert any("LOCATION" in msg for msg in warning_messages) 289 | 290 | def test_process_template_variables_complex_content(self): 291 | """Test processing template with complex content and multiple variables""" 292 | template = """You are a {{ROLE}} working on {{STAGE}} stage. 293 | 294 | Language: {{LANGUAGE}} 295 | Target Document: {{TARGET_DOCUMENT}} 296 | 297 | Instructions: 298 | 1. Review the current {{TARGET_DOCUMENT}} 299 | 2. Use {{LANGUAGE}} language for communication 300 | 3. Complete the {{STAGE}} requirements 301 | 302 | Action: {{ACTION}}""" 303 | 304 | variables = { 305 | "ROLE": "Product Manager", 306 | "STAGE": "PRD", 307 | "LANGUAGE": "English", 308 | "TARGET_DOCUMENT": "/docs/prd.md", 309 | "ACTION": "build" 310 | } 311 | 312 | result = process_template_variables(template, variables) 313 | 314 | assert "Product Manager" in result 315 | assert "PRD stage" in result 316 | assert "English" in result 317 | assert "/docs/prd.md" in result 318 | assert "build" in result 319 | assert "{{" not in result # No placeholders should remain 320 | 321 | 322 | class TestTemplateMetadataValidation: 323 | """Test template metadata validation""" 324 | 325 | def test_validate_template_metadata_valid(self): 326 | """Test validating valid metadata""" 327 | valid_metadata = { 328 | "build": { 329 | "prompt": "Build something" 330 | }, 331 | "run": { 332 | "prompt": "Run something" 333 | } 334 | } 335 | 336 | assert validate_template_metadata(valid_metadata) is True 337 | 338 | def test_validate_template_metadata_empty(self): 339 | """Test validating empty metadata (should be valid)""" 340 | assert validate_template_metadata({}) is True 341 | 342 | def test_validate_template_metadata_invalid_structure(self): 343 | """Test validating invalid metadata structures""" 344 | # Non-dict metadata 345 | assert validate_template_metadata("not a dict") is False 346 | 347 | # Action without prompt 348 | invalid_metadata = { 349 | "build": { 350 | "description": "Some description" 351 | # Missing prompt 352 | } 353 | } 354 | assert validate_template_metadata(invalid_metadata) is False 355 | 356 | # Action that's not a dict 357 | invalid_metadata = { 358 | "build": "not a dict" 359 | } 360 | assert validate_template_metadata(invalid_metadata) is False 361 | 362 | def test_validate_template_metadata_partial_valid(self): 363 | """Test validating metadata with mix of valid and invalid actions""" 364 | mixed_metadata = { 365 | "build": { 366 | "prompt": "Valid build prompt" 367 | }, 368 | "invalid_action": { 369 | "description": "No prompt field" 370 | } 371 | } 372 | 373 | # Should be valid if at least one action is properly structured 374 | assert validate_template_metadata(mixed_metadata) is True -------------------------------------------------------------------------------- /tests/test_controller.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for TempDD Controller 3 | 4 | This module contains tests for the Controller class initialization 5 | and basic functionality. 6 | """ 7 | 8 | import pytest 9 | import json 10 | import shutil 11 | from pathlib import Path 12 | from unittest.mock import patch, mock_open 13 | from tempdd.core.controllers.controller_default import Controller 14 | 15 | 16 | class TestControllerInitialization: 17 | """Test Controller class initialization""" 18 | 19 | def test_controller_init_without_config_path(self): 20 | """Test Controller initialization without custom config path uses default config""" 21 | # Should initialize successfully using default config 22 | controller = Controller() 23 | assert controller is not None 24 | assert controller.config is not None 25 | assert isinstance(controller.config, dict) 26 | 27 | def test_controller_init_with_project_config(self, tmp_path): 28 | """Test Controller initialization with existing project config""" 29 | # Create a temporary project structure 30 | tempdd_dir = tmp_path / ".tempdd" 31 | tempdd_dir.mkdir() 32 | 33 | config_data = { 34 | "language": "en", 35 | "stages": ["prd", "arch", "research", "blueprint", "task"], 36 | "controller": "default", 37 | "templates": {"prd": "template_prd_default"}, 38 | "controller_state": {} 39 | } 40 | 41 | config_file = tempdd_dir / "config.json" 42 | config_file.write_text(json.dumps(config_data, indent=2)) 43 | 44 | # Mock current working directory 45 | with patch('pathlib.Path.cwd', return_value=tmp_path): 46 | controller = Controller() 47 | assert controller.config == config_data 48 | assert controller.work_dir == tmp_path 49 | 50 | def test_controller_init_with_custom_config_path(self, tmp_path): 51 | """Test Controller initialization with custom config path""" 52 | # Create custom config file 53 | custom_config = tmp_path / "custom_config.json" 54 | config_data = { 55 | "language": "zh-TW", 56 | "stages": ["prd", "arch"], 57 | "controller": "default" 58 | } 59 | 60 | custom_config.write_text(json.dumps(config_data)) 61 | 62 | controller = Controller(config_path=str(custom_config)) 63 | assert controller.config == config_data 64 | assert controller.config_path == str(custom_config) 65 | 66 | def test_controller_init_fallback_to_default_config(self, tmp_path): 67 | """Test Controller initialization falls back to default config""" 68 | # This test is actually covered by the first test since it uses real default config 69 | # Let's just verify the behavior exists by checking config is loaded 70 | controller = Controller() 71 | assert controller.config is not None 72 | assert "stages" in controller.config 73 | 74 | def test_controller_init_no_config_found(self, tmp_path): 75 | """Test Controller initialization when no config is found""" 76 | with patch('pathlib.Path.cwd', return_value=tmp_path): 77 | with patch('pathlib.Path.exists', return_value=False): 78 | with pytest.raises(FileNotFoundError, match="No configuration file found"): 79 | Controller() 80 | 81 | def test_controller_uses_work_directory_from_new_config(self, tmp_path): 82 | """Test process_command uses work_directory from the new config format.""" 83 | # Create a temporary project structure 84 | tempdd_dir = tmp_path / ".tempdd" 85 | tempdd_dir.mkdir() 86 | templates_dir = tempdd_dir / "templates" 87 | templates_dir.mkdir() 88 | 89 | # New configuration format 90 | config_data = { 91 | "language": "zh-TW", 92 | "stages": ["prd"], 93 | "controller": "default", 94 | "templates": {"prd": "template_prd_default"}, 95 | "controller_state": { 96 | "work_directory": "custom-docs" 97 | } 98 | } 99 | config_file = tempdd_dir / "config.json" 100 | config_file.write_text(json.dumps(config_data, indent=2)) 101 | 102 | # Create a dummy template file to avoid FileNotFoundError 103 | template_file = templates_dir / "template_prd.md" 104 | template_file.write_text("---\nbuild:\n prompt: 'Test prompt for {{TARGET_DOCUMENT}}'\n---\n# Template") 105 | 106 | with patch('pathlib.Path.cwd', return_value=tmp_path): 107 | controller = Controller() 108 | ai_instruction = controller.process_command("prd", "build") 109 | 110 | # The path in the instruction should use the default docs-for-works directory 111 | expected_path_segment = str(Path("docs-for-works") / "001_initialization" / "prd.md") 112 | assert expected_path_segment in ai_instruction 113 | 114 | 115 | class TestControllerBasicMethods: 116 | """Test Controller basic methods""" 117 | 118 | def test_validate_stage_valid(self, tmp_path): 119 | """Test _validate_stage with valid stage""" 120 | config_data = { 121 | "stages": ["prd", "arch", "research"] 122 | } 123 | 124 | with patch('pathlib.Path.cwd', return_value=tmp_path): 125 | with patch('builtins.open', mock_open(read_data=json.dumps(config_data))): 126 | with patch('pathlib.Path.exists', return_value=True): 127 | controller = Controller() 128 | assert controller._validate_stage("prd") is True 129 | assert controller._validate_stage("arch") is True 130 | 131 | def test_validate_stage_invalid(self, tmp_path): 132 | """Test _validate_stage with invalid stage""" 133 | config_data = { 134 | "stages": ["prd", "arch"] 135 | } 136 | 137 | with patch('pathlib.Path.cwd', return_value=tmp_path): 138 | with patch('builtins.open', mock_open(read_data=json.dumps(config_data))): 139 | with patch('pathlib.Path.exists', return_value=True): 140 | controller = Controller() 141 | assert controller._validate_stage("invalid_stage") is False 142 | 143 | def test_get_config(self, tmp_path): 144 | """Test get_config returns a copy of configuration""" 145 | config_data = { 146 | "language": "en", 147 | "stages": ["prd"] 148 | } 149 | 150 | with patch('pathlib.Path.cwd', return_value=tmp_path): 151 | with patch('builtins.open', mock_open(read_data=json.dumps(config_data))): 152 | with patch('pathlib.Path.exists', return_value=True): 153 | controller = Controller() 154 | returned_config = controller.get_config() 155 | 156 | # Should return a copy, not the original 157 | assert returned_config == config_data 158 | returned_config["language"] = "zh-TW" 159 | assert controller.config["language"] == "en" # Original unchanged 160 | 161 | 162 | class TestProcessCommand: 163 | """Test Controller process_command method""" 164 | 165 | def test_process_command_valid_stage_default_action(self, tmp_path): 166 | """Test process_command with valid stage and default action""" 167 | config_data = { 168 | "stages": ["prd", "arch", "research"], 169 | "templates": {"prd": "template_prd_default"} 170 | } 171 | 172 | with patch('pathlib.Path.cwd', return_value=tmp_path): 173 | with patch('builtins.open', mock_open(read_data=json.dumps(config_data))): 174 | with patch('pathlib.Path.exists', return_value=True): 175 | controller = Controller() 176 | 177 | # This should fail initially because process_command logic is incomplete 178 | result = controller.process_command("prd") 179 | 180 | # Currently returns placeholder, but should return proper AI instruction 181 | assert "[PLACEHOLDER]" not in result 182 | assert "prd" in result.lower() 183 | assert "build" in result.lower() 184 | 185 | def test_process_command_valid_stage_custom_action(self, tmp_path): 186 | """Test process_command with valid stage and custom action""" 187 | config_data = { 188 | "stages": ["prd", "arch"], 189 | "templates": {"arch": "template_arch_default"} 190 | } 191 | 192 | # Create a mock existing directory structure 193 | docs_dir = tmp_path / "docs-for-works" 194 | docs_dir.mkdir() 195 | existing_dir = docs_dir / "001_initialization" 196 | existing_dir.mkdir() 197 | 198 | with patch('pathlib.Path.cwd', return_value=tmp_path): 199 | with patch('builtins.open', mock_open(read_data=json.dumps(config_data))): 200 | with patch('pathlib.Path.exists', return_value=True): 201 | controller = Controller() 202 | 203 | result = controller.process_command("arch", "run") 204 | 205 | # Should return proper AI instruction, not placeholder 206 | assert "[PLACEHOLDER]" not in result 207 | assert "arch" in result.lower() 208 | assert "run" in result.lower() 209 | 210 | def test_process_command_invalid_stage(self, tmp_path): 211 | """Test process_command with invalid stage raises ValueError""" 212 | config_data = { 213 | "stages": ["prd", "arch"] 214 | } 215 | 216 | with patch('pathlib.Path.cwd', return_value=tmp_path): 217 | with patch('builtins.open', mock_open(read_data=json.dumps(config_data))): 218 | with patch('pathlib.Path.exists', return_value=True): 219 | controller = Controller() 220 | 221 | with pytest.raises(ValueError, match="Invalid stage: invalid_stage"): 222 | controller.process_command("invalid_stage") 223 | 224 | def test_process_command_missing_template(self, tmp_path): 225 | """Test process_command when template file is missing""" 226 | config_data = { 227 | "stages": ["prd"], 228 | "templates": {"prd": "template_prd_default"} 229 | } 230 | 231 | with patch('pathlib.Path.cwd', return_value=tmp_path): 232 | with patch('builtins.open', mock_open(read_data=json.dumps(config_data))): 233 | with patch('pathlib.Path.exists', return_value=True): 234 | controller = Controller() 235 | 236 | # Mock template file doesn't exist 237 | with patch('pathlib.Path.exists', return_value=False): 238 | with pytest.raises(FileNotFoundError): 239 | controller.process_command("prd") 240 | 241 | def test_process_command_generates_ai_instruction_format(self, tmp_path): 242 | """Test that process_command generates properly formatted AI instruction""" 243 | config_data = { 244 | "language": "zh-TW", 245 | "stages": ["prd"], 246 | "templates": {"prd": "template_prd_default"}, 247 | "controller_state": {"current_target_document": "/path/to/prd.md"} 248 | } 249 | 250 | with patch('pathlib.Path.cwd', return_value=tmp_path): 251 | with patch('builtins.open', mock_open(read_data=json.dumps(config_data))): 252 | with patch('pathlib.Path.exists', return_value=True): 253 | controller = Controller() 254 | 255 | result = controller.process_command("prd", "create") 256 | 257 | # Controller should return content without AI instruction markers 258 | assert "[AI_INSTRUCTION_START]" not in result 259 | assert "[AI_INSTRUCTION_END]" not in result 260 | 261 | # Should contain language and target document info 262 | assert "zh-TW" in result or "Language:" in result 263 | assert "Target Document:" in result 264 | 265 | # Helper function to get stages from default config 266 | def get_default_stages(): 267 | default_config_path = Path(__file__).parent.parent / "tempdd" / "core" / "configs" / "config_default.json" 268 | with open(default_config_path, 'r') as f: 269 | config = json.load(f) 270 | return config.get("stages", []) 271 | 272 | class TestCompleteness: 273 | """ 274 | Tests for complete coverage of all stages and actions. 275 | This corresponds to T305, T306, and T307. 276 | """ 277 | STAGES = get_default_stages() 278 | 279 | def _run_combination_test(self, tmp_path, stage, action): 280 | """Helper function to run a stage/action combination test.""" 281 | # Setup a mock project structure in a temporary directory 282 | tempdd_dir = tmp_path / ".tempdd" 283 | tempdd_dir.mkdir() 284 | templates_dir = tempdd_dir / "templates" 285 | templates_dir.mkdir() 286 | 287 | config_data = { 288 | "stages": self.STAGES, 289 | "controller_state": {} 290 | } 291 | config_file = tempdd_dir / "config.json" 292 | config_file.write_text(json.dumps(config_data)) 293 | 294 | template_path = Path(__file__).parent.parent / "tempdd" / "core" / "templates" / f"template_{stage}_default.md" 295 | if not template_path.exists(): 296 | pytest.fail(f"Template not found at path: {template_path.resolve()}") 297 | 298 | shutil.copy(template_path, templates_dir / f"template_{stage}.md") 299 | 300 | if stage != "prd": 301 | (tmp_path / "docs-for-works" / "001_initialization").mkdir(parents=True, exist_ok=True) 302 | 303 | with patch('pathlib.Path.cwd', return_value=tmp_path): 304 | controller = Controller() 305 | try: 306 | ai_instruction = controller.process_command(stage, action) 307 | assert "[AI_INSTRUCTION_START]" not in ai_instruction 308 | assert "[AI_INSTRUCTION_END]" not in ai_instruction 309 | assert "You are working on the" not in ai_instruction, f"Stage '{{stage}}', Action '{{action}}' is using a fallback prompt." 310 | except FileNotFoundError as e: 311 | pytest.fail(f"Stage '{{stage}}', Action '{{action}}' failed: {{e}}") 312 | 313 | @pytest.mark.parametrize("stage", STAGES) 314 | def test_build_action_for_all_stages(self, tmp_path, stage): 315 | """Test that the 'build' action is correctly implemented for all stages.""" 316 | self._run_combination_test(tmp_path, stage, "build") 317 | 318 | def test_run_action_for_tasks_stage(self, tmp_path): 319 | """Test that the 'run' action is correctly implemented for the 'tasks' stage.""" 320 | self._run_combination_test(tmp_path, "tasks", "run") 321 | --------------------------------------------------------------------------------