{"id":32122492,"url":"https://github.com/promptdriven/pdd","last_synced_at":"2026-06-06T08:00:34.682Z","repository":{"id":295191008,"uuid":"988545824","full_name":"promptdriven/pdd","owner":"promptdriven","description":" Prompt Driven Development (PDD): The Last Programming Language™. Prompt files are source; code is generated output.","archived":false,"fork":false,"pushed_at":"2026-06-03T06:07:26.000Z","size":815481,"stargazers_count":735,"open_issues_count":278,"forks_count":63,"subscribers_count":3,"default_branch":"main","last_synced_at":"2026-06-03T07:28:30.338Z","etag":null,"topics":["ai","cli","code","developer-tools","development","methodology","prompt","prompt-engineering","prompt-toolkit","prompts","prompts-template"],"latest_commit_sha":null,"homepage":"https://promptdriven.ai","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/promptdriven.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2025-05-22T17:52:24.000Z","updated_at":"2026-06-03T04:33:33.000Z","dependencies_parsed_at":null,"dependency_job_id":"2e96167e-d8d3-4820-b116-62a2cd537cf4","html_url":"https://github.com/promptdriven/pdd","commit_stats":null,"previous_names":["promptdriven/pdd"],"tags_count":158,"template":false,"template_full_name":null,"purl":"pkg:github/promptdriven/pdd","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/promptdriven%2Fpdd","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/promptdriven%2Fpdd/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/promptdriven%2Fpdd/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/promptdriven%2Fpdd/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/promptdriven","download_url":"https://codeload.github.com/promptdriven/pdd/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/promptdriven%2Fpdd/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33973868,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-06T02:00:07.033Z","response_time":107,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","cli","code","developer-tools","development","methodology","prompt","prompt-engineering","prompt-toolkit","prompts","prompts-template"],"created_at":"2025-10-20T20:51:04.611Z","updated_at":"2026-06-06T08:00:34.672Z","avatar_url":"https://github.com/promptdriven.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PDD: The Last Programming Language™\n\n![PyPI version](https://img.shields.io/pypi/v/pdd-cli.svg) [![Discord](https://img.shields.io/badge/Discord-join%20chat-7289DA.svg?logo=discord\u0026logoColor=white)](https://discord.gg/Yp4RTh8bG7)\n\n## Introduction\n\nPDD (Prompt-Driven Development) is a prompt-native programming system. `.prompt`\nfiles are the human-authored source language; Python, TypeScript, Go, and other\ntraditional languages are generated artifacts.\n\nPDD is the last programming language in this specific sense: developers author\ndurable intent, constraints, examples, and tests, then compile that source into\nwhatever implementation language the project needs. Code remains real and\nreviewable, but it is no longer the primary source of truth.\n\n**Getting started is simple:**\n\n```bash\n# Install and run\nuv tool install pdd-cli\npdd setup\npdd connect\n```\n\nThis launches a web interface at `localhost:9876` where you can:\n- Implement GitHub issues automatically\n- Generate and test code from prompts\n- Manage your PDD projects visually\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"docs/videos/handpaint_demo.gif\" alt=\"PDD Handpaint Demo\" /\u003e\n\u003c/p\u003e\n\nFor CLI users, PDD also offers powerful **agentic commands** that implement GitHub issues automatically:\n- `pdd change \u003cissue-url\u003e` - Implement feature requests (13-step workflow)\n- `pdd bug \u003cissue-url\u003e` - Create failing tests for bugs\n- `pdd fix \u003cissue-url\u003e` - Fix the failing tests\n- `pdd split \u003ctarget-file\u003e` - Diagnose and split large dev units (15-step workflow with intent classification, diagnosis, phase extraction, per-child verify gate, and repair)\n- `pdd generate \u003cissue-url\u003e` - Generate architecture.json from a PRD issue (11-step workflow)\n- `pdd test \u003cissue-url\u003e` - Generate UI tests from issue descriptions (18-step workflow with exploratory testing, contract validation, accessibility audits)\n\nFor prompt-based workflows, the **`sync`** command automates the complete development cycle with intelligent decision-making, real-time visual feedback, and sophisticated state management.\n\n## Whitepaper\n\nFor the positioning essay behind this shift, read [The Last Programming Language](docs/the-last-programming-language.md).\n\nFor a detailed explanation of the concepts, architecture, and benefits of Prompt-Driven Development, please refer to our full whitepaper. This document provides an in-depth look at the PDD philosophy, its advantages over traditional development, and includes benchmarks and case studies.\n\n[Read the Full Whitepaper with Benchmarks](docs/whitepaper_with_benchmarks/whitepaper_w_benchmarks.md)\n\nFor a case study on specification drift in AI-assisted coding workflows, read [Why AI Code Falls Apart](docs/whitepaper_specification_drift/whitepaper.md).\n\nAlso see the Prompt‑Driven Development Doctrine for core principles and practices: [docs/prompt-driven-development-doctrine.md](docs/prompt-driven-development-doctrine.md)\n\nFor pre-merge prompt and user-story quality (vague terms, vocabulary, optional LLM review), see [docs/prompt_lint.md](docs/prompt_lint.md).\n\nFor deterministic contract-section lint (`\u003ccontract_rules\u003e`, `\u003ccoverage\u003e`, waivers, story `## Covers`), see [docs/contract_check.md](docs/contract_check.md).\n\nFor a rule-to-story/test coverage matrix (`pdd checkup coverage`), see [docs/coverage_contracts.md](docs/coverage_contracts.md).\n## Installation\n\n### Prerequisites for macOS\n\nOn macOS, you'll need to install some prerequisites before installing PDD:\n\n1. **Install Xcode Command Line Tools** (required for Python compilation):\n   ```bash\n   xcode-select --install\n   ```\n\n2. **Install Homebrew** (recommended package manager for macOS):\n   ```bash\n   /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"\n   ```\n   \n   After installation, add Homebrew to your PATH:\n   ```bash\n   echo 'eval \"$(/opt/homebrew/bin/brew shellenv)\"' \u003e\u003e ~/.zprofile \u0026\u0026 eval \"$(/opt/homebrew/bin/brew shellenv)\"\n   ```\n\n3. **Install Python** (if not already installed):\n   ```bash\n   # Check if Python is installed\n   python3 --version\n   \n   # If Python is not found, install it via Homebrew\n   brew install python\n   ```\n   \n   **Note**: Recent versions of macOS no longer ship with Python pre-installed. PDD requires Python 3.8 or higher. The `brew install python` command installs the latest Python 3 version.\n\n### Recommended Method: uv\n\nWe recommend installing PDD using the [uv package manager](https://github.com/astral-sh/uv) for better dependency management and automatic environment configuration:\n\n```bash\n# Install uv if you haven't already \ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Install PDD using uv tool install\nuv tool install pdd-cli\n```\n\nThis installation method ensures:\n- Faster installations with optimized dependency resolution\n- Automatic environment setup without manual configuration\n- Proper handling of the PDD_PATH environment variable\n- Better isolation from other Python packages\n\nThe PDD CLI will be available immediately after installation without requiring any additional environment configuration.\n\nVerify installation:\n```bash\npdd --version\n```\n\nWith the CLI on your `PATH`, continue with:\n```bash\npdd setup\n```\nThe command detects agentic CLI tools, scans for API keys, configures models, and seeds local configuration files.\nIf you postpone this step, the CLI detects the missing setup artifacts the first time you run another command and shows a reminder banner so you can complete it later (the banner is suppressed once `~/.pdd/api-env` exists or when your project already provides credentials via `.env` or `.pdd/`).\n\n### Alternative: pip Installation\n\nIf you prefer using pip, you can install PDD with:\n```bash\npip install pdd-cli\n```\n\n\n## Advanced Installation Options\n\n### Virtual Environment Installation\n```bash\n# Create virtual environment\npython -m venv pdd-env\n\n# Activate environment\n# On Windows:\npdd-env\\Scripts\\activate\n# On Unix/MacOS:\nsource pdd-env/bin/activate\n\n# Install PDD\npip install pdd-cli\n```\n\n\n\n## Getting Started\n\n### Option 1: Web Interface (Recommended)\n\nThe easiest way to use PDD is through the web interface:\n\n```bash\n# 1. Install PDD\ncurl -LsSf https://astral.sh/uv/install.sh | sh\nuv tool install pdd-cli\n\n# 2. Run setup (API keys, shell completion)\npdd setup\n\n# 3. Launch the web interface\npdd connect\n```\n\nThis opens a browser-based interface where you can:\n- **Run Commands**: Execute `pdd change`, `pdd bug`, `pdd fix`, `pdd sync` etc. visually\n- **Browse Files**: View and edit prompts, code, and tests in your project\n- **Remote Access**: Access your session from any browser via PDD Cloud (use `--local-only` to disable)\n\n### Option 2: Issue-Driven CLI\n\nFor CLI enthusiasts, implement GitHub issues directly:\n\n**Prerequisites:**\n1. **GitHub CLI** - Required for issue access:\n   ```bash\n   brew install gh \u0026\u0026 gh auth login\n   ```\n\n2. **One Agentic CLI** - Required to run the workflows (install at least one):\n   - **Claude Code**: `npm install -g @anthropic-ai/claude-code` (uses your stored Claude Max/Pro OAuth login if you've run `claude auth login`, otherwise falls back to `ANTHROPIC_API_KEY`; pdd auto-prefers OAuth — set `PDD_KEEP_ANTHROPIC_API_KEY=1` to force API-key billing)\n   - **Antigravity CLI (`agy`, preferred)**: install via `curl -fsSL https://antigravity.google/cli/install.sh | bash` (uses Antigravity OAuth or keyring-backed Google subscription sign-in if present, otherwise `ANTIGRAVITY_API_KEY`/`GOOGLE_API_KEY`, Vertex AI env auth, or PDD's compatibility bridge from `GEMINI_API_KEY`). Set `PDD_AGENTIC_PROVIDER=antigravity` to pin the Antigravity binary, or `PDD_GOOGLE_CLI=agy|gemini|auto` to control binary selection (`auto` prefers `agy` when credentialed, but keeps legacy `gemini` for legacy-OAuth-only setups).\n   - **Gemini CLI (legacy, rollback)**: `npm install -g @google/gemini-cli` (uses `~/.gemini` OAuth credentials if present, otherwise `GOOGLE_API_KEY` or `GEMINI_API_KEY`). Google announced consumer-tier Gemini CLI cutoff on **2026-06-18**; set `PDD_GOOGLE_CLI=gemini` only when you intentionally need the old binary.\n   - **Codex CLI**: `npm install -g @openai/codex` (uses `~/.codex/auth.json` ChatGPT login if present, otherwise `OPENAI_API_KEY`)\n   - **OpenCode CLI**: `npm install -g opencode-ai` (uses OpenCode provider auth from `opencode auth login`, `~/.config/opencode/opencode.json`, project `opencode.json`, or provider env vars; set `OPENCODE_MODEL=provider/model`)\n\n**Usage:**\n```bash\n# Implement a feature request\npdd change https://github.com/owner/repo/issues/123\n\n# Or fix a bug\npdd bug https://github.com/owner/repo/issues/456\npdd fix https://github.com/owner/repo/issues/456\n```\n\n### Option 3: Manual Prompt Workflow\n\nFor learning PDD fundamentals or working with existing prompt files:\n\n```bash\ncd your-project\npdd sync module_name  # Full automated workflow\n```\n\nSee the [Hello Example](#-quickstart-hello-example) below for a step-by-step introduction.\n\n---\n\n## 🚀 Quickstart (Hello Example)\n\nIf you want to understand PDD fundamentals, follow this manual example to see it in action.\n\n1. **Install prerequisites** (macOS/Linux):\n   ```bash\n   xcode-select --install      # macOS only\n   curl -LsSf https://astral.sh/uv/install.sh | sh\n   uv tool install pdd-cli\n   pdd --version\n   ```\n\n2. **Clone repo**\n\n   ```bash\n     # Clone the repository (if not already done)\n    git clone https://github.com/promptdriven/pdd.git\n    cd pdd/examples/hello\n   ```\n\n3. **Set one API key** (choose your provider):\n   ```bash\n   export GEMINI_API_KEY=\"your-gemini-key\"\n   # OR\n   export OPENAI_API_KEY=\"your-openai-key\"\n   ```\n\n### Post-Installation Setup (Required first step after installation)\n\nRun the comprehensive setup wizard:\n```bash\npdd setup\n```\n\nThe setup wizard runs these steps:\n  1.  Detects agentic CLI tools (Claude, Gemini/Antigravity, Codex, OpenCode) and offers installation and credential configuration if needed. Credentials can be environment-variable API keys, stored OAuth/subscription/config credentials such as Claude Max/Pro, Google Gemini/Antigravity login, Vertex AI env auth, Codex ChatGPT login, or OpenCode provider auth/config.\n  2. Scans for API keys across `.env`, `~/.pdd/api-env.*`, and the shell environment. If no API key is found but a selected CLI already has a stored OAuth/subscription/config credential, setup skips the API-key prompt for the agentic workflow and explains which direct prompt/LiteLLM commands still need API keys.\n  3. Configures models from a reference CSV `data/llm_model.csv` of top ranked models across all LiteLLM-supported providers based on your available API keys\n  4. If you have credentials for **more than one** provider, asks which provider(s) `pdd --local` should use, then removes the unselected providers' PDD-managed rows from `~/.pdd/llm_model.csv` (rows you hand-edited or added yourself are preserved — see below)\n  5. Optionally creates a `.pddrc` project config\n  6. Tests a model from your selected provider with a real LLM call\n  7. Prints a structured summary (CLIs, keys, models, test result)\n\nThe wizard can be re-run at any time to update keys, add providers, or reconfigure settings.\n\n#### Choosing your local provider\n\n`pdd --local` selects a model from `~/.pdd/llm_model.csv` by cost/ranking, so if\nthe file lists several providers it can route to one you didn't intend — for\nexample a free GitHub Copilot login outranking a `GEMINI_API_KEY` you set on\npurpose. To prevent that, when setup ends up with more than one usable provider\n— which includes always-available device-login providers like GitHub Copilot,\nso the prompt can appear even if you only set a single API key — it asks you to\npick which provider(s) to keep, then removes the unselected providers'\nPDD-managed rows (rows you hand-edited or added yourself are preserved):\n\n- **Default selection** excludes device-login providers (e.g. GitHub Copilot,\n  which needs no API key) so a free login never silently outranks a key you\n  configured. Select them explicitly to keep them.\n- **Local models** (Ollama, LM Studio) and any **hand-edited/custom rows** for\n  providers you don't configure are never offered for removal and are left\n  untouched.\n- Before removing any rows, setup **lists exactly what will be removed and asks\n  you to confirm**, and snapshots the previous file to\n  `~/.pdd/llm_model.csv.backup.\u003ctimestamp\u003e` so the change is always reversible.\n- Your choice is saved to `~/.pdd/setup_preferences.json`. Re-running setup\n  re-uses it without re-asking and without re-adding the providers you dropped\n  (so a later run stays quiet — no repeated prompt, no Copilot churn). It only\n  adds new models for the providers you already chose.\n\nTo use a different provider later, delete `~/.pdd/setup_preferences.json` and\nre-run `pdd setup` to pick a new selection (or edit `~/.pdd/llm_model.csv`\ndirectly). Adding a provider through the setup options menu also updates your\nsaved selection.\n\n\u003e **Important:** After setup completes, source the API environment file so your keys take effect in the current terminal session:\n\u003e ```bash\n\u003e source ~/.pdd/api-env.zsh   # or api-env.bash, depending on your shell\n\u003e ```\n\u003e New terminal windows will load keys automatically.\n\nIf you skip this step, the first regular pdd command you run will detect the missing setup files and print a reminder banner so you can finish onboarding later.\n\n5. **Run Hello**:\n   ```bash\n   cd ../hello\n   pdd --force generate hello_python.prompt\n   python3 hello.py\n   ```\n\n    ✅ Expected output:\n    ```\n    hello\n    ```\n\n\n\n## Cloud vs Local Execution\n\nPDD commands can be run either in the cloud or locally. By default, all commands run in the cloud mode, which provides several advantages:\n\n- No need to manage API keys locally\n- Access to more powerful models\n- Shared examples and improvements across the PDD community\n- Automatic updates and improvements\n- Better cost optimization\n\n### Cloud Authentication\n\nWhen running in cloud mode (default), PDD uses GitHub Single Sign-On (SSO) for authentication. On first use, you'll be prompted to authenticate:\n\n1. PDD will open your default browser to the GitHub login page\n2. Log in with your GitHub account\n3. Authorize PDD Cloud to access your GitHub profile\n4. Once authenticated, you can return to your terminal to continue using PDD\n\nThe authentication token is securely stored locally and automatically refreshed as needed.\n\n### Local Mode Requirements\n\nWhen running in local mode with the `--local` flag, you'll need to set up API keys for the language models:\n\n```bash\n# For OpenAI\nexport OPENAI_API_KEY=your_api_key_here\n\n# For Anthropic\nexport ANTHROPIC_API_KEY=your_api_key_here\n\n# For other supported providers (LiteLLM supports multiple LLM providers)\nexport PROVIDER_API_KEY=your_api_key_here\n```\n\nSome local-mode providers do not use API keys. GitHub Copilot models\nauthenticate through LiteLLM's OAuth device flow; run `pdd setup`, then choose\n**Add a provider** from the options menu and pick GitHub Copilot to complete\nthat device login. (The provider-selection prompt described above only decides\nwhich already-configured providers `pdd --local` uses — it does not perform the\nOAuth login.)\n\nAdd these to your `.bashrc`, `.zshrc`, or equivalent for persistence.\n\nPDD's local mode uses LiteLLM (version 1.75.5 or higher) for interacting with language models, providing:\n\n- Support for multiple model providers (OpenAI, Anthropic, Google/Vertex AI, and more)\n- Automatic model selection based on strength settings\n- Response caching for improved performance\n- Smart token usage tracking and cost estimation\n- Interactive API key acquisition when keys are missing\n\nWhen keys are missing, PDD will prompt for them interactively and securely store them in your local `.env` file.\n\n### Local Model Configuration\n\nPDD uses a CSV file to configure model selection and capabilities. This configuration is loaded from:\n\n1. User-specific configuration: `~/.pdd/llm_model.csv` (takes precedence if it exists)\n2. Project-specific configuration: `\u003cPROJECT_ROOT\u003e/.pdd/llm_model.csv`\n3. Package default: Bundled with PDD installation (fallback when no local configurations exist)\n\nThe CSV includes columns for:\n- `provider`: The LLM provider (e.g., \"openai\", \"anthropic\", \"google\")\n- `model`: The LiteLLM model identifier (e.g., \"gpt-4\", \"claude-3-opus-20240229\")\n- `input`/`output`: Costs per million tokens\n- `coding_arena_elo`: Raw Arena/static ELO metadata\n- `model_rank_score`: Primary selection rank. DeepSWE rows use a high solve-rate band; Arena/static rows fall back to raw ELO.\n- `model_rank_source`: Source of `model_rank_score` (for example `deepswe-solve-rate`, `arena-elo-fallback`, or `static`)\n- `api_key`: The environment variable name for required authentication, or\n  blank for local and device-flow providers such as Ollama, LM Studio, and\n  GitHub Copilot\n- `structured_output`: Whether the model supports structured JSON output\n- `reasoning_type`: Support for reasoning capabilities (\"none\", \"budget\", \"effort\", or \"adaptive\")\n\nFor a concrete, up-to-date reference of supported models and example rows, see the bundled CSV in this repository: [pdd/data/llm_model.csv](pdd/data/llm_model.csv).\n\nFor proper model identifiers to use in your custom configuration, refer to the [LiteLLM Model List](https://docs.litellm.ai/docs/providers) documentation. LiteLLM typically uses model identifiers in the format `provider/model_name` (e.g., \"openai/gpt-4\", \"anthropic/claude-3-opus-20240229\").\n\n## Troubleshooting Common Installation Issues\n\n1. **Command not found**\n   ```bash\n   # Add to PATH if needed\n   export PATH=\"$HOME/.local/bin:$PATH\"\n   ```\n\n2. **Permission errors**\n   ```bash\n   # Install with user permissions\n   pip install --user pdd-cli\n   ```\n\n3. **macOS-specific issues**\n   - **Xcode Command Line Tools not found**: Run `xcode-select --install` to install the required development tools\n   - **Homebrew not found**: Install Homebrew using the command in the prerequisites section above\n   - **Python not found or wrong version**: Install Python 3 via Homebrew: `brew install python`\n   - **Permission denied during compilation**: Ensure Xcode Command Line Tools are properly installed and you have write permissions to the installation directory\n   - **uv installation fails**: Try installing uv through Homebrew: `brew install uv`\n   - **Python version conflicts**: If you have multiple Python versions, ensure `python3` points to Python 3.8+: `which python3 \u0026\u0026 python3 --version`\n\n## Version\n\nTo check your installed version, run:\n```\npdd --version\n```\nPDD includes an auto-update feature to ensure you always have access to the latest features and security patches. You can control this behavior using an environment variable (see \"Auto-Update Control\" section below).\n\n## Supported Programming Languages\n\nPDD supports a wide range of programming languages, including but not limited to:\n- Python\n- JavaScript\n- TypeScript\n- Java\n- C++\n- Ruby\n- Go\n\nThe specific language is often determined by the prompt file's naming convention or specified in the command options.\n\n## Prompt File Naming Convention\n\nPrompt files in PDD commonly follow one of these formats:\n```\n\u003cbasename\u003e_\u003clanguage\u003e.prompt\n```\nor, for architecture-driven projects with nested output paths:\n```\n\u003cpath/to/output_stem\u003e_\u003cLanguage\u003e.prompt\n```\nWhere:\n- `\u003cbasename\u003e` is the base name of the file or project in legacy flat layouts\n- `\u003cpath/to/output_stem\u003e` mirrors the output filepath without its extension in architecture-driven layouts\n- `\u003clanguage\u003e` / `\u003cLanguage\u003e` is the programming language or prompt context suffix used by the project\n\nExamples:\n- `factorial_calculator_python.prompt` (basename: factorial_calculator, language: python)\n- `responsive_layout_css.prompt` (basename: responsive_layout, language: css)\n- `data_processing_pipeline_python.prompt` (basename: data_processing_pipeline, language: python)\n- `src/models/user_Python.prompt` → generates `src/models/user.py`\n- `app/api/orders/route_TypeScript.prompt` → generates `app/api/orders/route.ts`\n\nPDD supports both conventions. Legacy hand-written prompts are often flat, while prompts generated from `architecture.json` typically mirror the target filepath directory structure.\n\n## Prompt-Driven Development Philosophy\n\n### Core Concepts\n\nPrompt-Driven Development (PDD) inverts traditional software development by treating prompts as the primary artifact - not code. This paradigm shift has profound implications:\n\n1. **Prompts as Source of Truth**: \n   In traditional development, source code is the ground truth that defines system behavior. In PDD, the prompts are authoritative, with code being a generated artifact.\n\n2. **Natural Language Over Code**:\n   Prompts are written primarily in natural language, making them more accessible to non-programmers and clearer in expressing intent.\n\n3. **Regenerative Development**:\n   When changes are needed, you modify the prompt and regenerate code, rather than directly editing the code. This maintains the conceptual integrity between requirements and implementation.\n\n4. **Intent Preservation**:\n   Prompts capture the \"why\" behind code in addition to the \"what\" - preserving design rationale in a way that comments often fail to do.\n\n### Mental Model\n\nTo work effectively with PDD, adopt these mental shifts:\n\n1. **Prompt-First Thinking**:\n   Always start by defining what you want in a prompt before generating any code.\n\n2. **Bidirectional Flow**:\n   - Prompt → Code: The primary direction (generation)\n   - Code → Prompt: Secondary but crucial (keeping prompts in sync with code changes)\n\n3. **Modular Prompts**:\n   Just as you modularize code, you should modularize prompts into self-contained units that can be composed.\n\n4. **Integration via Examples**:\n   Modules integrate through their examples, which serve as interfaces, allowing for token-efficient references.\n\n### PDD Workflows: Conceptual Understanding\n\nEach workflow in PDD addresses a fundamental development need:\n\n1. **Initial Development Workflow**\n   - **Purpose**: Creating functionality from scratch\n   - **Conceptual Flow**: Define dependencies → Generate implementation → Create interfaces → Ensure runtime functionality → Verify correctness\n   \n   This workflow embodies the prompt-to-code pipeline, moving from concept to tested implementation.\n\n2. **Code-to-Prompt Update Workflow**\n   - **Purpose**: Maintaining prompt as source of truth when code changes\n   - **Conceptual Flow**: Sync code changes to prompt → Identify impacts → Propagate changes\n   \n   This workflow ensures the information flow from code back to prompts, preserving prompts as the source of truth.\n\n3. **Debugging Workflows**\n   - **Purpose**: Resolving different types of issues\n   - **Conceptual Types**:\n     - **Context Issues**: Addressing misunderstandings in prompt interpretation\n     - **Runtime Issues**: Fixing execution failures\n     - **Logical Issues**: Correcting incorrect behavior\n     - **Traceability Issues**: Connecting code problems back to prompt sections\n   \n   These workflows recognize that different errors require different resolution approaches.\n\n4. **Refactoring Workflow**\n   - **Purpose**: Improving prompt organization and reusability\n   - **Conceptual Flow**: Extract functionality → Ensure dependencies → Create interfaces\n   \n   This workflow parallels code refactoring but operates at the prompt level.\n\n5. **Multi-Prompt Architecture Workflow**\n   - **Purpose**: Coordinating systems with multiple prompts\n   - **Conceptual Flow**: Detect conflicts → Resolve incompatibilities → Regenerate code → Update interfaces → Verify system\n   \n   This workflow addresses the complexity of managing multiple interdependent prompts.\n\n6. **Enhancement Phase**: Use Feature Enhancement when adding capabilities to existing modules.\n\n### Workflow Selection Principles\n\nThe choice of workflow should be guided by your current development phase:\n\n1. **Creation Phase**: Use Initial Development when building new functionality.\n\n2. **Maintenance Phase**: Use Code-to-Prompt Update when existing code changes.\n\n3. **Problem-Solving Phase**: Choose the appropriate Debugging workflow based on the issue type:\n   - Preprocess → Generate for prompt interpretation issues\n   - Crash for runtime errors\n   - Bug → Fix for logical errors\n   - Trace for locating problematic prompt sections\n\n4. **Restructuring Phase**: Use Refactoring when prompts grow too large or complex.\n\n5. **System Design Phase**: Use Multi-Prompt Architecture when coordinating multiple components.\n\n6. **Enhancement Phase**: Use Feature Enhancement when adding capabilities to existing modules.\n\n### PDD Design Patterns\n\nEffective PDD employs these recurring patterns:\n\n1. **Dependency Injection via Auto-deps**:\n   Automatically including relevant dependencies in prompts.\n\n2. **Interface Extraction via Example**:\n   Creating minimal reference implementations for reuse.\n\n3. **Bidirectional Traceability**:\n   Maintaining connections between prompt sections and generated code.\n\n4. **Test-Driven Prompt Fixing**:\n   Using tests to guide prompt improvements when fixing issues.\n\n5. **Hierarchical Prompt Organization**:\n   Structuring prompts from high-level architecture to detailed implementations.\n\n## Basic Usage\n\n```\npdd [GLOBAL OPTIONS] COMMAND [OPTIONS] [ARGS]...\n```\n\n## Command Overview\n\nHere is a brief overview of the main commands provided by PDD. Click the command name to jump to its detailed section:\n\n### Command Relationships\n\nThe following diagram shows how PDD commands interact:\n\n```mermaid\ngraph TB\n    subgraph Entry Points\n        connect[\"pdd connect (Web UI - Recommended)\"]\n        cli[\"Direct CLI\"]\n        ghapp[\"GitHub App\"]\n    end\n\n    gen_url[\"pdd generate \u0026lt;url\u0026gt;\"]\n\n    subgraph sync workflow\n        sync[\"pdd sync\"]\n        s_deps[\"auto-deps\"]\n        s_gen[\"generate\"]\n        s_example[\"example\"]\n        s_crash[\"crash\"]\n        s_verify[\"verify\"]\n        s_test[\"test\"]\n        s_fix[\"fix\"]\n        s_update[\"update\"]\n    end\n\n    checkup[\"pdd checkup \u0026lt;url\u0026gt;\"]\n    test_url[\"pdd test \u0026lt;url\u0026gt;\"]\n    bug_url[\"pdd bug \u0026lt;url\u0026gt;\"]\n    fix_url[\"pdd fix \u0026lt;url\u0026gt;\"]\n    change[\"pdd change \u0026lt;url\u0026gt;\"]\n    sync_url[\"pdd sync \u0026lt;url\u0026gt;\"]\n\n    connect --\u003e gen_url\n    cli --\u003e gen_url\n    ghapp --\u003e gen_url\n    gen_url --\u003e sync\n    sync --\u003e s_deps\n    s_deps --\u003e s_gen\n    s_gen --\u003e s_example\n    s_example --\u003e s_crash\n    s_crash --\u003e s_verify\n    s_verify --\u003e s_test\n    s_test --\u003e s_fix\n    s_fix --\u003e s_update\n    sync --\u003e checkup\n    checkup --\u003e test_url\n    checkup --\u003e bug_url\n    checkup --\u003e change\n    test_url --\u003e fix_url\n    bug_url --\u003e fix_url\n    change --\u003e sync_url\n    sync_url -.-\u003e sync\n```\n\n**Key concepts:**\n- **Entry points**: `pdd connect` (web UI), direct CLI, or the GitHub App\n- **Start**: `pdd generate \u003curl\u003e` scaffolds architecture, prompts, and `.pddrc` from a PRD GitHub issue\n- **Core loop**: `pdd sync` runs the full auto-deps → generate → example → crash → verify → test → fix → update cycle for each module\n- **Health check**: `pdd checkup \u003curl\u003e` identifies what needs attention next; `pdd checkup --pr ...` reviews an existing PR on its own merits (add `--issue ...` to also verify it resolves a specific issue)\n- **Defect path**: `test \u003curl\u003e` or `bug \u003curl\u003e` surfaces failing tests → `fix \u003curl\u003e` resolves them\n- **Feature path**: `change \u003curl\u003e` implements the feature → `sync \u003curl\u003e` re-runs sync across affected modules. Auth caveat: `sync \u003curl\u003e` still runs a LiteLLM-backed generate phase, so OAuth-only CLI setup is not enough; configure an API key first.\n\n### Getting Started\n- **[`connect`](#18-connect)**: **[RECOMMENDED]** Launch web interface for visual PDD interaction\n- **[`setup`](#post-installation-setup-required-first-step-after-installation)**: Configure API keys and shell completion\n\n### Agentic Commands (Issue-Driven)\n- **[`change`](#8-change)**: Implement feature requests from GitHub issues (13-step workflow)\n- **[`bug`](#14-bug)**: Analyze bugs and create failing tests from GitHub issues\n- **[`checkup`](#17-checkup)**: Run automated project health checks from GitHub issues, or review/verify existing PRs (optionally against a source issue)\n- **[`fix`](#6-fix)**: Fix failing tests (supports issue-driven and manual modes)\n- **[`sync`](#1-sync)**: Multi-module parallel sync from a GitHub issue (when passed a URL instead of basename). This mode still requires API-key-backed LiteLLM for its generate phase; stored CLI OAuth alone is not sufficient.\n- **[`test`](#4-test)**: Generate UI tests from GitHub issues (18-step workflow in agentic mode)\n\n### Core Commands (Prompt-Based)\n- **[`sync`](#1-sync)**: **[PRIMARY FOR PROMPT WORKFLOWS]** Automated prompt-to-code cycle\n- **[`generate`](#2-generate)**: Creates runnable code from a prompt file; supports parameterized prompts via `-e/--env`\n- **[`example`](#3-example)**: Generates a compact example showing how to use functionality defined in a prompt\n- **[`test`](#4-test)**: Generates or enhances unit tests for a code file and its prompt\n- **[`update`](#9-update)**: Updates the original prompt file based on modified code\n- **[`verify`](#16-verify)**: Verifies functional correctness by running a program and judging output against intent\n- **[`crash`](#12-crash)**: Fixes errors in a code module and its calling program that caused a crash\n\n### Prompt Management\n- **[`preprocess`](#5-preprocess)**: Preprocesses prompt files, handling includes, comments, and other directives\n- **[`replay`](#5a-replay)**: Reconstructs and audits expanded prompt context from a snapshot-enabled run artifact\n- **[`split`](#7-split)**: Splits large prompt files into smaller, more manageable ones\n- **[`extracts prune`](#21-extracts)**: Garbage-collect orphaned extracts cache entries\n- **[`auto-deps`](#15-auto-deps)**: Analyzes and inserts needed dependencies into a prompt file\n- **[`sync-architecture`](#1a-sync-architecture)**: Updates `architecture.json` from prompt metadata tags\n- **[`detect`](#10-detect)**: Analyzes prompts to determine which ones need changes based on a description\n- **[`conflicts`](#11-conflicts)**: Finds and suggests resolutions for conflicts between two prompt files\n- **[`trace`](#13-trace)**: Finds the corresponding line number in a prompt file for a given code line\n\n### Utility Commands\n- **[`auth`](#19-auth)**: Manages authentication with PDD Cloud\n- **[`sessions`](#20-pdd-sessions---manage-remote-sessions)**: Manage remote sessions for `connect`\n\n### User Story Prompt Tests\nPDD can validate prompt changes against user stories stored as Markdown files. This uses `detect` under the hood: a story **passes** when `detect` returns no required prompt changes.\n\nDefaults:\n- Stories live in `user_stories/` and match `story__*.md`.\n- Prompts are loaded from `prompts/` (excluding `*_llm.prompt` by default).\n\nOverrides:\n- `PDD_USER_STORIES_DIR` sets the stories directory.\n- `PDD_PROMPTS_DIR` sets the prompts directory.\n\nCommands:\n- `pdd detect --stories` runs the validation suite.\n- `pdd change` runs story validation after prompt modifications and fails if any story fails.\n- `pdd fix user_stories/story__*.md` applies a single story to prompts and re-validates it.\n- `pdd test --issue \u003curl|number|issue.md\u003e \u003cprompt_1.prompt\u003e [prompt_2.prompt ...]` generates a `story__*.md` file from the issue text and links those prompts.\n- `pdd test user_stories/story__*.md` updates prompt links for an existing story file.\n\nStory prompt linkage:\n- Stories may include optional metadata to scope validation to a subset of prompts:\n  `\u003c!-- pdd-story-prompts: prompts/a_python.prompt, prompts/b_python.prompt --\u003e`\n- If metadata is missing, `pdd detect --stories` validates against the full prompt set.\n- `pdd test --issue ... \u003c*.prompt\u003e` links the prompt files passed on the command line directly in story metadata; it does not run `detect_change` during story authoring.\n- In `--stories` mode, existing story metadata scopes validation; when metadata is missing, validation falls back to the full prompt set.\n\nTemplate:\n- See `user_stories/story__template.md` for a starter format.\n\nContract coverage:\n- User stories are **example-level coverage** for named contract rules in prompts.\n  Document rule IDs under each story's `## Covers` section (for example `R1` or\n  `prompts/module_python.prompt#R2`). See `docs/coverage_contracts.md` and\n  `docs/contract_check.md`.\n\n## Global Options\n\nThese options can be used with any command:\n\n- `--force`: Skip all interactive prompts (file overwrites, API key requests). Useful for CI/automation.\n- `--strength FLOAT`: Set the strength of the AI model (0.0 to 1.0, default is 0.5).\n  - 0.0: Cheapest available model\n  - 0.5: Default base model\n  - 1.0: Most powerful model (highest DeepSWE-first rank score)\n- `--time FLOAT`: Controls the reasoning allocation for LLM models supporting reasoning capabilities (0.0 to 1.0, default is 0.25).\n  - For models with specific reasoning token limits (e.g., 64k), a value of `1.0` utilizes the maximum available tokens.\n  - For models with discrete effort levels, `1.0` corresponds to the highest effort level.\n  - Values between 0.0 and 1.0 scale the allocation proportionally.\n- `--temperature FLOAT`: Set the temperature of the AI model (default is 0.0).\n- `--verbose`: Increase output verbosity for more detailed information. Includes token count and context window usage for each LLM call.\n- `--quiet`: Decrease output verbosity for minimal information.\n- `--output-cost PATH_TO_CSV_FILE`: Enable cost tracking and output a CSV file with usage details.\n- `--review-examples`: Review and optionally exclude few-shot examples before command execution.\n- `--local`: Run commands locally instead of in the cloud.\n- `--core-dump`: Capture a debug bundle for this run so it can be replayed and analyzed later.\n- `report-core`: Report a bug by creating a GitHub issue with the core dump file.\n- `--context CONTEXT_NAME`: Override automatic context detection and use the specified context from `.pddrc`.\n- `--list-contexts`: List all available contexts defined in `.pddrc` and exit.\n- `--compress-examples`: Automatically apply `mode=\"interface\"` to example includes (legacy; prefer `--context-compression examples`).\n- `--compress-test-context`: Compress test includes to failing tests only (legacy; prefer `--context-compression test`).\n- `--context-compression {off,test,examples,contracts,all}`: Set context compression for this CLI invocation (default: `off`). Must appear **before** the subcommand (e.g. `pdd --context-compression test generate ...`). `sync` and `fix` also accept the same flags after their subcommand.\n- `--compression-fallback {full,error}`: When compression or slicing fails, use full content (`full`, default) or abort (`error`). Global placement is the same as `--context-compression`.\n\n### Core Dump Debug Bundles\n\nIf something goes wrong and you want the PDD team to be able to reproduce it, you can run any command with a core dump enabled:\n\n```bash\npdd --core-dump sync factorial_calculator\npdd --core-dump crash prompts/calc_python.prompt src/calc.py examples/run_calc.py crash_errors.log\n```\n\nWhen `--core-dump` is set, PDD:\n\n- Captures the full CLI command and arguments\n- Records relevant logs and internal trace information for that run\n- Bundles the prompt(s), generated code, and key metadata needed to replay the issue\n\nAt the end of the run, PDD prints the path to the core dump bundle.  \nAttach that bundle when you open a GitHub issue or send a bug report so maintainers can quickly reproduce and diagnose your problem.\n\n#### `report-core` Command\n\nThe `report-core` command helps you report a bug by creating a GitHub issue with the core dump file. It simplifies the reporting process by automatically collecting relevant files and information.\n\n**Usage:**\n```bash\npdd report-core [OPTIONS] [CORE_FILE]\n```\n\n**Arguments:**\n- `CORE_FILE`: The path to the core dump file (e.g., `.pdd/core_dumps/pdd-core-....json`). If omitted, the most recent core dump is used.\n\n**Options:**\n- `--api`: Create the issue directly via the GitHub API instead of opening a browser. This enables automatic Gist creation for attached files.\n- `--repo OWNER/REPO`: Override the target repository (default: `promptdriven/pdd`).\n- `--description`, `-d TEXT`: A short description of what went wrong.\n\n**Authentication:**\n\nTo use the `--api` flag, you need to be authenticated with GitHub. PDD checks for credentials in the following order:\n\n1.  **GitHub CLI**: `gh auth token` (recommended)\n2.  **Environment Variables**: `GITHUB_TOKEN` or `GH_TOKEN`\n3.  **Legacy**: `PDD_GITHUB_TOKEN`\n\n**File Tracking \u0026 Gists:**\n\nWhen using `--api`, PDD will:\n1.  Collect all relevant files (prompts, code, tests, configs, meta files).\n2.  Create a **private GitHub Gist** containing these files.\n3.  Link the Gist in the created issue.\n\nThis ensures that all necessary context is available for debugging while keeping the issue body clean. If you don't use `--api`, files will be truncated to fit within the URL length limits of the browser-based submission.\n\n---\n\n### Context Selection Flags\n\n- `--list-contexts` reads the nearest `.pddrc` (searching upward from the current directory), prints the available contexts one per line, and exits immediately with status 0. No auto‑update checks or subcommands run when this flag is present.\n- `--context CONTEXT_NAME` is validated early against the same `.pddrc` source of truth. If the name is unknown, the CLI raises a `UsageError` and exits with code 2 before running auto‑update or subcommands.\n- Precedence for configuration is: CLI options \u003e `.pddrc` context \u003e environment variables \u003e defaults. See Configuration for details.\n\n## Auto-Update Control\n\nPDD automatically updates itself to ensure you have the latest features and security patches. However, you can control this behavior using the `PDD_AUTO_UPDATE` environment variable:\n\n```bash\n# Disable auto-updates\nexport PDD_AUTO_UPDATE=false\n\n# Enable auto-updates (default behavior)\nexport PDD_AUTO_UPDATE=true\n```\n\nFor persistent settings, add this environment variable to your shell's configuration file (e.g., `.bashrc` or `.zshrc`).\n\nThis is particularly useful in:\n- Production environments where version stability is crucial\n- CI/CD pipelines where consistent behavior is required\n- Version-sensitive projects that require specific PDD versions\n\n## AI Model Information\n\nPDD uses a large language model to generate and manipulate code. The `--strength` and `--temperature` options allow you to control the model's output:\n\n- Strength: Determines how powerful/expensive a model should be used. Higher values (closer to 1.0) result in high performance models with better capabilities (selected by `model_rank_score`, where DeepSWE is primary and Arena/static ELO is fallback), while lower values (closer to 0.0) select more cost-effective models.\n- Temperature: Controls the randomness of the output. Higher values increase diversity but may lead to less coherent results, while lower values produce more focused and deterministic outputs.\n- Time: (Optional, controlled by `--time FLOAT`) For models supporting reasoning, this scales the allocated reasoning resources (e.g., tokens or effort level) between minimum (0.0) and maximum (1.0), with a default of 0.25.\n\nWhen running in local mode, PDD uses LiteLLM to select and interact with language models based on a configuration file that includes:\n- Input and output costs per million tokens\n- Primary `model_rank_score` values for selection and raw Arena/static `coding_arena_elo` metadata\n- Required API key environment variables\n- Structured output capability flags\n- Reasoning capabilities (budget-based, effort-based, or adaptive)\n\n## Output Cost Tracking\n\nPDD includes a feature for tracking and reporting the cost of operations. When enabled, it generates a CSV file with usage details for each command execution.\n\n### Usage\n\nTo enable cost tracking, use the `--output-cost` option with any command:\n\n```\npdd --output-cost PATH_TO_CSV_FILE [COMMAND] [OPTIONS] [ARGS]...\n```\n\nThe `PATH_TO_CSV_FILE` should be the desired location and filename for the CSV output.\n\n### Cost Calculation and Presentation\n\nPDD calculates costs based on the AI model usage for each operation. Costs are presented in USD (United States Dollars) and are calculated using the following factors:\n\n1. Model strength: Higher strength settings generally result in higher costs.\n2. Input size: Larger inputs (e.g., longer prompts or code files) typically incur higher costs.\n3. Operation complexity: Some operations (like `fix` and `crash` with multiple iterations) may be more costly than simpler operations.\n\nThe exact cost per operation is determined by the LiteLLM integration using the provider's current pricing model. PDD uses an internal pricing table that is regularly updated to reflect the most current rates.\n\n### CSV Output\n\nThe generated CSV file includes the following columns:\n- timestamp: The date and time of the command execution\n- model: The AI model used for the operation\n- command: The PDD command that was executed\n- cost: The estimated cost of the operation in USD (e.g., 0.05 for 5 cents). This will be zero for local models or operations that do not use a LLM.\n- input_files: A list of input files involved in the operation\n- output_files: A list of output files generated or modified by the operation\n- attempted_models: Semicolon-delimited audit log of every model PDD attempted for the command, across all LLM calls the command made (e.g. `generate` runs code-generation followed by postprocess code extraction — both contribute). When PDD's default model fails and the run falls back to another provider (for example Vertex AI → DeepSeek), each attempted model appears here so users can see the full fallback history rather than only the final successful model. The `model` column above names the model that actually produced the command's output; `attempted_models` is the complete record of what was tried. For commands that catch a substep failure and recover with a different model, the list may contain entries that came AFTER the model named in `model` — those represent attempts that were tried but didn't produce the final output. For a single-attempt successful command this column contains just the successful model. Semicolons inside model names are sanitized to preserve the delimiter. **Ordering:** sequential (single-thread) command paths produce a list in wall-clock attempt order; concurrent paths (e.g. `auto-deps --concurrency \u003e 1`, which fans summarization across worker threads) sort their per-file contributions by file-submission index — a deterministic alternative to wall-clock ordering, which would otherwise depend on thread-scheduler timing.\n\nThis comprehensive output allows for detailed tracking of not only the cost and type of operations but also the specific files involved in each PDD command execution.\n\n### Environment Variable\n\nYou can set a default location for the cost output CSV file using the environment variable:\n\n- **`PDD_OUTPUT_COST_PATH`**: Default path for the cost tracking CSV file.\n\nIf this environment variable is set, the CSV file will be saved to the specified path by default, unless overridden by the `--output-cost` option. For example, if `PDD_OUTPUT_COST_PATH=/path/to/cost/reports/`, the CSV file will be saved in that directory with a default filename.\n\n### Cost Budgeting\n\nFor commands that support it (like the `fix` command), you can set a maximum budget using the `--budget` option. This helps prevent unexpected high costs, especially for operations that might involve multiple AI model calls.\n\nExample:\n```\npdd [GLOBAL OPTIONS] fix --budget 5.0 [OTHER OPTIONS] [ARGS]...\n```\nThis sets a maximum budget of $5.00 for the fix operation.\n\n## Commands\n\nHere are the main commands provided by PDD:\n\n### 1. sync\n\n**[PRIMARY COMMAND]** Automatically execute the complete PDD workflow loop. With a basename, it syncs one module. With no argument, it runs Tier 1 project-wide sync by scanning `architecture.json` for modules whose prompt fingerprints changed or whose code outputs are missing, then runs those modules in dependency order. With a GitHub issue URL, it runs multi-module issue sync, but the generate phase still calls LiteLLM and requires an API key; stored Claude/Gemini/Antigravity/Codex OAuth or OpenCode provider auth alone is not sufficient for this mode.\n\n```bash\n# Project-wide architecture sync (no argument)\npdd [GLOBAL OPTIONS] sync [OPTIONS]\n\n# Single-module sync\npdd [GLOBAL OPTIONS] sync [OPTIONS] BASENAME\n\n# Multi-module sync from a GitHub issue (requires API-key-backed LiteLLM)\npdd [GLOBAL OPTIONS] sync [OPTIONS] GITHUB_ISSUE_URL\n```\n\nImportant: Sync frequently overwrites generated files to keep outputs up to date. In most real runs, include the global `--force` flag to allow overwrites without interactive confirmation:\n\n```\npdd --force sync BASENAME\n```\n\n```bash\n# Single-module sync with replayable context snapshots\npdd --force sync --snapshot-context factorial_calculator\n```\n\nSnapshot-enabled runs write the canonical run manifest to `.pdd/evidence/runs/\u003crun_id\u003e.json` and replayable context artifacts to the sibling directory `.pdd/evidence/runs/\u003crun_id\u003e/`. Snapshot redaction runs before hashing and storage for known token, key, authorization header, URL credential, and secret-assignment patterns; raw environment dumps and bearer/API tokens must not be persisted. Commit only policy-approved snapshot files.\n\nArguments:\n- No argument: Scan `architecture.json` and sync all modules that need deterministic Tier 1 prompt-to-code updates.\n- `architecture.json` as a positional value is not a global-sync alias in v1; use no-argument `pdd sync` for project-wide Tier 1 sync.\n- `BASENAME`: The base name for the prompt file (e.g., \"factorial_calculator\" for \"factorial_calculator_python.prompt\")\n- `GITHUB_ISSUE_URL`: A GitHub issue URL for issue-driven multi-module sync. This path is not OAuth-only friendly because its generate phase uses LiteLLM; configure an API key even if your agentic CLI has a stored OAuth login.\n\nOptions:\n- `--max-attempts INT`: Maximum number of fix attempts in any iterative loop (default is 3)\n- `--model NAME`: Override the base model for this sync run (sets PDD_MODEL_DEFAULT for the invocation, e.g. `chatgpt/gpt-5.3-codex`). Restored after the run. Affects the local llm_invoke route; for a `chatgpt/*` subscription model on a cloud-enabled install, also pass `--local`.\n- `--budget FLOAT`: Maximum total cost allowed for the entire sync process (default is $20.0)\n- `--skip-verify`: Skip the functional verification step\n- `--skip-tests`: Skip unit test generation and fixing\n- `--target-coverage FLOAT`: Desired code coverage percentage (default is 90.0)\n- `--compress`: Use AST-based compression for Python few-shot examples (strips docstrings and logic-external comments). Helps fit more context into limited LLM windows without losing executable logic.\n- `--dry-run`: Display real-time sync analysis instead of running sync operations. For no-argument project-wide sync, this prints the dependency-ordered module list and estimated cost without executing any module syncs, plus a single compact roll-up of modules outside the Tier 1 (`generate` / `auto-deps`) scope — bucketed by reason (e.g. `Out of Tier 1 scope: 42 example, 31 test, 18 verify, 12 update, 74 no-prompt fixture`) instead of one warning line per skipped entry. When zero modules are stale, the `0 stale module(s)` fragment is rendered in green so the success signal is visually unambiguous. Actionable architecture-graph warnings (ambiguous or unresolved cross-arch dependencies) are still printed individually in yellow. For single-module sync, it performs the same state analysis as a normal sync run but without acquiring exclusive locks or executing operations. Passing the top-level `pdd --verbose` flag (see above) restores the legacy per-module enumeration after the compact roll-up — one yellow warning line per module outside the Tier 1 scope — for debugging.\n- `--snapshot-context`: Capture the fully expanded prompt context used for generation, including nondeterministic `\u003cshell\u003e`, `\u003cweb\u003e`, and `\u003cinclude ... query=\"...\"\u003e` outputs. The run manifest is `.pdd/evidence/runs/\u003crun_id\u003e.json`; snapshot artifacts are in `.pdd/evidence/runs/\u003crun_id\u003e/`. Replay can later reconstruct the same prompt/context from the recorded run artifact.\n- `--compressed-context / --no-compressed-context`: Enable or disable compressed sync context for generation and repair phases. This option is tri-state internally: omitting it lets `.pddrc` `defaults.compressed_context` apply, `--compressed-context` forces it on, and `--no-compressed-context` forces it off. When enabled, sync builds bounded phase packages from the prompt, existing tests, examples when present, contract sections, and recent repair evidence, then passes those packages to generate, verify, test, and fix attempts. The sync result records whether compression was used and whether any agentic fallback was needed.\n- `--one-session / --no-one-session`: Run sync in a single agentic session instead of separate sessions for each step. Cannot be combined with `--skip-tests` or `--skip-verify`.\n- `--no-steer`: Disable interactive steering of sync operations.\n- `--steer-timeout FLOAT`: Timeout in seconds for steering prompts (default: 8.0).\n- `--compress-examples`: Automatically apply `mode=\"interface\"` to example files in the `\u003cinclude\u003e` graph for this sync operation.\n- `--compress-test-context`: Use AST-based slicing to include only failing tests and fixtures in the fix/test context.\n- `--context-compression {off,test,examples,contracts,all}`: Set a global compression mode for this sync operation (default: `off`). `test` and `examples` mirror the legacy flags; `contracts` extracts contract rules and metadata from prompts and documentation; `all` enables all compression modes.\n- `--compression-fallback {full,error}`: Strategy for when a file cannot be compressed (default: `full`).\n- `--durable`: Issue-sync only. Run each module in an isolated git worktree under `.pdd/worktrees/sync-issue-\u003cN\u003e-\u003cmodule\u003e/` and checkpoint successful module output to a dedicated durable branch worktree under `.pdd/worktrees/durable-issue-\u003cN\u003e/`. Default issue-sync behavior (shared parallel worktree) is unchanged unless this flag is passed.\n- `--durable-branch TEXT`: Durable mode only. Override the durable checkpoint branch name. Default is `sync/issue-\u003cN\u003e` derived from the GitHub issue. Refused if it resolves to `main`, `master`, or the repository default branch.\n- `--no-resume`: Durable mode only. Ignore existing `PDD-Sync-Checkpoint-V1` commit trailers on the durable branch and re-run every selected module. By default, durable sync reads checkpoint trailers (`PDD-Sync-Checkpoint-V1: issue=\u003cN\u003e module=\u003cbasename\u003e`) and skips modules already checkpointed for the same issue, which is what makes a cloud rerun safely resume completed work after a partial failure.\n- `--durable-max-parallel INT`: Durable mode only. Cap how many module worktrees run concurrently. Defaults to the standard runner concurrency. A total budget still forces sequential execution.\n\n**Durable Issue Sync** (`--durable`):\n\nStandard issue sync runs all modules in one shared worktree. If the worker exits before every module completes (timeout, crash, ephemeral cloud checkout deletion), the work that already succeeded is lost and a rerun starts over from the original branch state. Durable mode is the opt-in fix: each module runs in its own git worktree, and on success its diff is applied to a separate durable branch worktree as a checkpoint commit carrying a `PDD-Sync-Checkpoint-V1: issue=\u003cN\u003e module=\u003cbasename\u003e` trailer. Independent modules still run in parallel (capped by `--durable-max-parallel`); the serialization guarantee is narrower — a module is only marked successful, and its dependents only become eligible to schedule, after its checkpoint commit has been pushed. Any rerun then reads the trailers and skips modules already checkpointed for the same issue. Failed module worktrees are left in place for inspection; successful ones are cleaned up after their checkpoint pushes. Durable sync requires a git repository with an `origin` remote and refuses to operate on `main`, `master`, or the repository default branch. Module-scoped `.pdd/meta/\u003cmodule\u003e_*.json` is included in checkpoints; secrets, lock files, cost CSVs, `.pdd/worktrees/`, and `.pdd/agentic_sync_state.json` are not.\n\n```bash\n# Cloud-friendly issue sync: resumable across reruns\npdd --force sync --durable https://github.com/myorg/myrepo/issues/1328\n\n# Rerun every module fresh on the same durable branch (ignores existing trailers)\npdd --force sync --durable --no-resume \\\n  https://github.com/myorg/myrepo/issues/1328\n```\n\nThe dedicated durable-branch worktree path is keyed on the issue number (`.pdd/worktrees/durable-issue-\u003cN\u003e/`), not the branch name. A given issue's first durable run claims that path for whichever branch it picked (default `sync/issue-\u003cN\u003e` or an explicit `--durable-branch`). To switch a later run for the **same issue** to a different durable branch, remove the existing worktree first (`git worktree remove .pdd/worktrees/durable-issue-\u003cN\u003e`) before re-invoking with the new `--durable-branch`. Different issue numbers do not collide.\n\n**Real-time Progress Animation**:\nThe sync command provides live visual feedback showing:\n- Current operation being executed (auto-deps, generate, example, crash, verify, test, fix, update)\n- File status indicators with color coding:\n  - Green: File exists and up-to-date\n  - Yellow: File being processed\n  - Red: File has errors or missing\n  - Blue: File analysis in progress\n- Running cost totals and time elapsed\n- Progress through the workflow steps\n\n**Language Detection**:\nThe sync command automatically detects the programming language by scanning for existing development prompt files for the requested basename. In classic layouts this is typically `{basename}_{language}.prompt`; in architecture-driven layouts it can also resolve nested prompt paths whose filenames mirror the target output path. For example:\n- `factorial_calculator_python.prompt` → generates `factorial_calculator.py`\n- `factorial_calculator_typescript.prompt` → generates `factorial_calculator.ts`\n- `factorial_calculator_javascript.prompt` → generates `factorial_calculator.js`\n- `src/models/user_Python.prompt` → generates `src/models/user.py`\n\nIf multiple development language prompt files exist for the same basename, sync will process all of them.\n\n**Language Filtering**: The sync command only processes development languages (python, javascript, typescript, java, cpp, etc.) and excludes runtime languages (LLM). Files ending in `_llm.prompt` are used for internal processing only and cannot form valid development units since they lack associated code, examples, and tests required for the sync workflow.\n\n**Advanced Configuration Integration**:\n- **Automatic Context Detection**: Detects project structure and applies appropriate settings from `.pddrc`\n- **Configuration Hierarchy**: CLI options \u003e .pddrc context \u003e environment variables \u003e defaults\n- **Multi-language Support**: Automatically processes all language variants of a basename\n- **Intelligent Path Resolution**: Uses sophisticated directory management for complex project structures\n- **Architecture-Aware Outputs**: When `architecture.json` provides an explicit `filepath` for a prompt entry, sync honors it according to whether that `filepath` includes a directory component:\n  - If `filepath` includes a directory (e.g. `backend/api/widget.py`), that explicit directory structure wins and is preserved as-is — `.pddrc` output paths are not applied to it.\n  - If `filepath` is a bare filename at the project root (e.g. `widget.py`), the filename is preserved but its parent directory is taken from `.pddrc` `generate_output_path`. This makes the code path resolve consistently with `example_output_path` and `test_output_path`, which are always sourced from `.pddrc` defaults (Issue #1201). When no `generate_output_path` is configured, the bare filename resolves at the project root as before.\n- Context-specific settings include output paths, default language, model parameters, coverage targets, and budgets\n\n**Workflow Logic**:\n\nThe sync command automatically detects what files exist and executes the appropriate workflow:\n\n1. **auto-deps**: Find and inject relevant dependencies into the prompt — both code examples and documentation files (schema docs, API docs, etc.). Removes redundant inline content that duplicates included documents.\n2. **generate**: Create or update the code module from the prompt. When compressed context is enabled, this phase receives a generated phase package containing compressed prompt/test/example/contract context instead of the raw boolean option value or repeatedly expanded full context. After generation an **architecture conformance gate** validates the output against both `architecture.json` and the prompt's `\u003cpdd-interface\u003e` block:\n    - Each declared symbol must exist in the generated code (architecture.json symbol-existence check).\n    - For interface entries that declare a paren-list `signature` (`module`, `cli`, and `command` types), each declared parameter name must appear in the matching function/method signature (dotted names like `ContentSelector.select` are resolved through the class body; variadic `*args`/`**kwargs` do not satisfy a declared named parameter).\n    - **Signature drift** is checked per parameter: annotation drift fires only when both sides specify and differ (conservative — gradually-typed code does not churn), while default drift fires whenever the prompt declares a default and the generated code drops or changes it (strict — a missing default is a runtime contract break for callers omitting the optional kwarg).\n    - **Public-surface regression gate**: when a module already has a generated code file in the working tree (i.e., not a first-time generation), the gate ALSO snapshots the pre-generation public surface and rejects a generation that removes, renames, or changes the callable signature of any public symbol. For Python the snapshot covers top-level functions, classes, `class.method` symbols (including nested classes), module-level constants (`PUBLIC_FLAG = ...`, including bound `AnnAssign` like `PUBLIC_FLAG: bool = True`), and re-exported imports (`import git` exposes `git`; `from .helpers import load` exposes `load`). `from __future__ import …` directives and bare type-only annotations are not part of the surface. Intentional removals/signature changes must be scoped, e.g. `BREAKING-CHANGE: remove calculate_sha256` or `BREAKING-CHANGE: change signature calculate`; listing a top-level class (`BREAKING-CHANGE: remove Service`) implicitly authorizes removing every `Service.method` / `Service.Inner.method` descendant captured in the snapshot. A bare `BREAKING-CHANGE:` does not disable the gate. First-time generation (no prior code file) is exempt. Set `PDD_SKIP_PUBLIC_SURFACE_GATE=1` to disable only this gate, or `PDD_SKIP_CONFORMANCE=1` to skip all conformance gates.\n    - **Test-churn gate**: if `pdd sync` is about to overwrite an existing test file through the code-generation writer, `cmd_test_main`, or one-session agentic sync, and the unified-diff churn ratio between the pre-sync and proposed test file exceeds `PDD_TEST_CHURN_THRESHOLD` (default `0.40`, i.e., 40%), the gate fails fast with `TestChurnError` so a small prompt change cannot land a thousand-line test rewrite that drops broad existing coverage. Pure additive test growth is allowed, first-time test generation is exempt, and intentional rewrites require an explicit marker such as `BREAKING-CHANGE: rewrite tests`. Set `PDD_SKIP_TEST_CHURN_GATE=1` to disable only this gate.\n    - **Empty-generation guard**: when the LLM provider returns an empty (or whitespace-only) body and the output path already has non-empty existing content, the writer refuses to truncate the file. Python public modules / test files trip `PublicSurfaceRegressionError` / `TestChurnError` through the normal gates; non-Python artifacts (JSON, YAML, prompts, etc.) raise a `click.UsageError(\"Refusing to overwrite ...\")` instead. Set `PDD_ALLOW_EMPTY_GENERATION=1` for the rare case where empty output is intentional.\n    - On failure, sync retries the generation step up to `MAX_CONFORMANCE_ATTEMPTS` with a `PDD_REPAIR_DIRECTIVE` that names the function to fix and the parameters/annotations/defaults to add or restore. Public-surface and test-churn failures use the same repair loop **only on the generate and one-session paths**; surface regressions detected after a crash/fix/verify write are hard failures (no retry) because each of those operations already runs its own internal fix loop and a second outer retry would compound retries (`N × M`) without converging. `.pddrc` context/strength are pinned across the entire retry sequence so a retry never silently switches model or context. The retry stops early when the missing-symbol/signature set repeats across attempts, and the final failure is surfaced as a structured `=== architecture conformance failure ===`, `=== public surface regression ===`, or `=== test churn threshold exceeded ===` block listing the offending symbols / churn ratio plus a `Reproduce locally: pdd sync \u003cbasename\u003e` line.\n3. **example**: Generate usage example if it doesn't exist or is outdated\n4. **crash**: Fix any runtime errors to make code executable\n5. **verify**: Run functional verification against prompt intent (unless --skip-verify). When compressed context is enabled, verification receives its own phase-aware compressed context package built from the same bounded prompt/test/example/contract evidence.\n6. **test**: Generate comprehensive unit tests if they don't exist (unless --skip-tests). Auth modules get auth-specific test patterns (mock OAuth servers, JWT fixtures, token lifecycle testing)\n7. **fix**: Resolve any bugs found by unit tests (unless --skip-tests). Because `--skip-tests` skips both unit test generation (step 6) and fixing, the fix step is skipped along with the test step. When the requested operation is an isolated code repair or generation replay, sync consumes existing examples if present but must not detour into unrelated example generation just to construct repair context.\n8. **update**: Back-propagate any learnings to the prompt file\n\n**One-Session Mode** (`--one-session`):\n\nBy default, sync runs each step (example, crash-fix, verify, test, fix) as a separate LLM session. One-session mode runs all these steps in a single agentic session. This results in faster and cheaper sync runs.\n\nOne-session mode is enabled by default for agentic sync (GitHub issue URLs) and disabled by default for single-module sync. Use `--one-session` or `--no-one-session` to override.\n\n```bash\n# Project-wide sync dry run\npdd sync --dry-run\n\n# Single-module sync with one-session mode\npdd sync --one-session factorial_calculator\n\n# Agentic sync (one-session is the default)\npdd sync https://github.com/myorg/myrepo/issues/100\npdd sync calculator --model chatgpt/gpt-5.3-codex  # force a model on the local route; for chatgpt/* on a cloud-enabled install add --local\npdd sync calculator --local --model chatgpt/gpt-5.3-codex  # local route: required for a chatgpt/* subscription model when PDD Cloud is configured\n\n# Disable one-session for agentic sync\npdd sync --no-one-session https://github.com/myorg/myrepo/issues/100\n```\n\n**Advanced Decision Making**:\n- **Fingerprint-based Change Detection**: Uses content hashes and timestamps to precisely detect what changed\n- **LLM-powered Conflict Resolution**: For complex scenarios with multiple file changes, uses AI to determine the best approach\n- **Persistent State Tracking**: Maintains sync history and learns from previous operations\n- **Smart Lock Management**: Prevents concurrent sync operations with automatic stale lock cleanup\n- Detects which files already exist and are up-to-date\n- Skips unnecessary steps (e.g., won't regenerate code if prompt hasn't changed)\n- Uses git integration to detect changes and determine incremental vs full regeneration\n- Accumulates tests over time rather than replacing them (in a single test file per target)\n- Automatically handles dependencies between steps\n- **Compressed Context Telemetry**: Sync results and logs record whether compressed context was requested, the effective value after CLI and `.pddrc` resolution, whether it was actually applied for each phase, the source inputs used to build it, and whether the run fell back to agentic repair. This makes replay and benchmark comparisons distinguish normal sync from compressed-context sync.\n\n**Robust State Management**:\n- **Fingerprint Files**: Maintains `.pdd/meta/{basename}_{language}.json` with operation history\n- **Run Reports**: Tracks test results, coverage, and execution status  \n- **Lock Management**: Prevents race conditions with file-descriptor based locking\n- **Git Integration**: Leverages version control for change detection and rollback safety\n\n**The `.pdd` Directory**:\nPDD uses a `.pdd` directory in your project root to store various metadata and configuration files:\n- `.pdd/meta/` - Contains fingerprint files, run reports, and sync logs\n- `.pdd/locks/` - Stores lock files to prevent concurrent operations\n- `.pdd/llm_model.csv` - Project-specific LLM model configuration (optional)\n- `.pdd/worktrees/` - Transient git worktrees used by `pdd sync --durable` (per-module execution sandboxes and the dedicated durable-branch worktree). Local scratch state, not project state.\n\nThis directory should typically be added to version control (except for `.pdd/locks/` and `.pdd/worktrees/`), as it contains important project state information.\n\n**Environment Variables**:\nAll existing PDD output path environment variables are respected, allowing the sync command to save files in the appropriate locations for your project structure.\n\n**Sync State Analysis**:\nThe sync command maintains detailed decision-making logs which you can view using the `--dry-run` option:\n\n```bash\n# View current sync state analysis (non-blocking)\npdd sync --dry-run calculator\n\n# View detailed LLM reasoning for complex scenarios\npdd --verbose sync --dry-run calculator\n```\n\n**Analysis Contents Include**:\n- Current file state and fingerprint comparisons\n- Real-time decision reasoning (heuristic-based vs LLM-powered analysis)\n- Operation recommendations with confidence levels\n- Estimated costs for recommended operations\n- Lock status and potential conflicts\n- State management details\n\nThe `--dry-run` option performs live analysis of the current project state, making it safe to run even when another sync operation is in progress. This differs from viewing historical logs - it shows what sync would decide to do right now based on current file states.\n\nUse `--verbose` with `--dry-run` to see detailed LLM reasoning for complex multi-file change scenarios and advanced state analysis.\n\n**When to use**: This is the recommended starting point for most PDD workflows. Use sync when you want to ensure all artifacts (code, examples, tests) are up-to-date and synchronized with your prompt files. The command embodies the PDD philosophy by treating the workflow as a batch process that developers can launch and return to later, freeing them from constant supervision.\n\nExamples:\n```bash\n# Complete workflow with progress animation and intelligent decision-making\npdd --force sync factorial_calculator\n\n# Advanced sync with higher budget, custom coverage, and full visual feedback\npdd --force sync --budget 15.0 --target-coverage 95.0 data_processor\n\n# Quick sync with animation showing real-time status updates\npdd --force sync --skip-verify --budget 5.0 web_scraper\n\n# Multi-language sync with fingerprint-based change detection\npdd --force sync multi_language_module\n\n# View comprehensive sync analysis with decision analysis\npdd sync --dry-run factorial_calculator\n\n# View detailed sync analysis with LLM reasoning for complex conflict resolution\npdd --verbose sync --dry-run factorial_calculator\n\n# Monitor what sync would do without executing (with state analysis)\npdd sync --dry-run calculator\n\n# Context-aware examples with automatic configuration detection\ncd backend \u0026\u0026 pdd --force sync calculator     # Uses backend context settings with animation\ncd frontend \u0026\u0026 pdd --force sync dashboard     # Uses frontend context with real-time feedback\npdd --context backend --force sync calculator # Explicit context override with visual progress\n```\n\n**Agentic Multi-Module Sync (GitHub Issue Mode)**:\n\nWhen a GitHub issue URL is passed instead of a basename, sync enters agentic mode:\n1. **Module Identification**: Fetches the issue content and uses an LLM to identify which modules need syncing\n2. **Dependency Validation**: Validates architecture.json dependencies and applies corrections if needed\n3. **Parallel Execution**: Dispatches parallel sync via `AsyncSyncRunner` with dependency-aware scheduling (max 4 concurrent workers)\n4. **Live Progress**: Posts and updates a GitHub comment with real-time module sync status\n\n```bash\n# Sync modules identified from a GitHub issue (parallel, dependency-aware)\npdd sync https://github.com/myorg/myrepo/issues/100\n\n# Extend the per-module timeout for a very large module\npdd sync --timeout-adder 600 https://github.com/myorg/myrepo/issues/100\n```\n\nOptions (agentic mode):\n- `--timeout-adder FLOAT`: Add seconds to the per-module timeout (default: 0.0).\n- `--no-github-state`: Disable GitHub state persistence, use local-only\n\n**Cross-Machine Resume**: Workflow state is stored in a hidden GitHub comment, enabling resume from any machine. Use `--no-github-state` to disable.\n\n### 1a. sync-architecture\n\nSync `architecture.json` from prompt metadata tags (`\u003cpdd-reason\u003e`, `\u003cpdd-interface\u003e`, and `\u003cpdd-dependency\u003e`). This is useful after editing prompt metadata directly, or after backfilling prompt tags, so the architecture graph and command metadata stay aligned with the prompts.\n\n```bash\n# Preview architecture updates for all prompts\npdd sync-architecture --dry-run\n\n# Update architecture.json from all prompt metadata tags\npdd sync-architecture\n\n# Update architecture.json from specific prompt entries\npdd sync-architecture commands/maintenance_python.prompt\n```\n\nArguments:\n- No argument: Scan all prompt files known to the current project.\n- `FILENAMES`: Optional prompt filenames as they appear in `architecture.json` or under the configured prompts directory.\n\nOptions:\n- `--dry-run`: Report which architecture entries would change without writing `architecture.json`.\n\nThe command prints updated prompt entries and validation errors or warnings. It exits non-zero when validation fails, even if it was able to write requested metadata updates before validation.\n\n\u003e Note: Validation is repo-wide and runs even when you target a single prompt. If your `architecture.json` already has unrelated missing-dependency errors elsewhere, the exit code stays non-zero on `--dry-run` even for an otherwise-clean target prompt. Fix the repo-wide errors (or scope your check) before relying on the exit code in scripts.\n\n### 2. generate\n\nCreate runnable code from a prompt file. This command produces the full implementation code that fulfills all requirements in the prompt. When changes are detected between the current prompt and its last committed version, it can automatically perform incremental updates rather than full regeneration.\n\n```bash\n# Basic usage\npdd [GLOBAL OPTIONS] generate [OPTIONS] PROMPT_FILE\n```\n\nArguments:\n- `PROMPT_FILE`: The filename of the prompt file used to generate the code.\n\nOptions:\n- `--output LOCATION`: Specify where to save the generated code. Supports `${VAR}`/`$VAR` expansion from `-e/--env`. The default file name is `\u003cbasename\u003e.\u003clanguage_file_extension\u003e`. If an environment variable `PDD_GENERATE_OUTPUT_PATH` is set, the file will be saved in that path unless overridden by this option.\n- `--original-prompt FILENAME`: The original prompt file used to generate the existing code. If not specified, the command automatically uses the last committed version of the prompt file from git.\n- `--incremental`: For prompt-to-code generation, force incremental patching when an output location is specified and the file exists. To run the experimental PRD-to-architecture workflow, combine it with `--experimental-prd`.\n- `--experimental-prd`: Explicitly opt in to experimental Incremental PRD Mode for PRD-like files (`.md`, `.markdown`, `.txt`, `.rst`, `.adoc`) or GitHub issue URLs. Requires `--incremental`.\n- `--unit-test FILENAME`: Path to a unit test file. If provided, automatic test discovery is disabled and only the content of this file is included in the prompt, instructing the model to generate code that passes the specified tests.\n- `--exclude-tests`: Do not automatically include test files found in the default tests directory.\n- Context compression: use global `--context-compression` / `--compression-fallback` before `generate` (see [Global Options](#global-options)); `generate` does not accept these flags after the subcommand.\n- `--snapshot-context`: Capture the expanded prompt and dynamic context outputs used for this generation. The run manifest is `.pdd/evidence/runs/\u003crun_id\u003e.json`; snapshot artifacts are in `.pdd/evidence/runs/\u003crun_id\u003e/`. This is recommended when a prompt uses `\u003cshell\u003e`, `\u003cweb\u003e`, or `\u003cinclude ... query=\"...\"\u003e` for contract-relevant context.\n\n**Parameter Variables (-e/--env)**:\nPass key=value pairs to parameterize a prompt so one prompt can generate multiple variants (e.g., multiple files) by invoking `generate` repeatedly with different values.\n\n- Syntax: `-e KEY=VALUE` or `--env KEY=VALUE` (repeatable).\n- Docker-style env fallback: `-e KEY` reads `VALUE` from the current process environment variable `KEY`.\n- Scope: Applies to `generate`.\n- Precedence: Values passed with `-e/--env` override same‑named OS environment variables during template expansion for this command.\n\n**Templating**:\nPrompt files and `--output` values may reference variables using `$VAR` or `${VAR}`. Only variables explicitly provided via `-e/--env` (or via env fallback with `-e KEY`) are substituted; all other dollar-prefixed text is left unchanged. No escaping is required for ordinary `$` usage.\n\n- In prompt content: `$VAR` and `${VAR}` are replaced only when `VAR` was provided.\n- In output path: When using `--output`, PDD also expands `$VAR`/`${VAR}` using the same variable set.\n- Unknowns: Placeholders without a provided value are left unchanged. If you pass `-e KEY` (no value) and `KEY` exists in the OS environment, that environment value is used.\n\nExamples:\n```\n# Basic parameterized generation (Python module)\npdd generate -e MODULE=orders --output 'src/${MODULE}.py' prompts/module_python.prompt\n\n# Generate multiple files from the same prompt\npdd generate -e MODULE=orders   --output 'src/${MODULE}.py' prompts/module_python.prompt\npdd generate -e MODULE=payments --output 'src/${MODULE}.py' prompts/module_python.prompt\npdd generate -e MODULE=customers --output 'src/${MODULE}.py' prompts/module_python.prompt\n\n# Multiple variables\npdd generate -e MODULE=orders -e PACKAGE=core --output 'src/${PACKAGE}/${MODULE}.py' prompts/module_python.prompt\n\n# Docker-style env fallback (reads MODULE from your shell env)\nexport MODULE=orders\npdd generate -e MODULE --output 'src/${MODULE}.py' prompts/module_python.prompt\n```\n\n```bash\npdd generate prompts/refund_python.prompt --output src/refund.py --snapshot-context\n```\n\nShell quoting options:\n- Quote `KEY=VALUE` if the value contains spaces or shell-special characters: `-e \"DISPLAY_NAME=Order Processor\"`.\n- PDD-side expansion (portable): prevent shell expansion and let PDD expand using `-e/--env` — e.g., `--output 'src/${MODULE}.py'`.\n- Shell-side expansion (familiar): set an env var and let the shell expand `--output`, while still passing `-e KEY` so prompts get the same value — e.g.,\n  - `export MODULE=orders \u0026\u0026 pdd generate -e MODULE --output \"src/$MODULE.py\" prompts/module_python.prompt`\n  - Or inline for POSIX shells: `MODULE=orders pdd generate -e MODULE --output \"src/$MODULE.py\" prompts/module_python.prompt`\n  - Note: PowerShell/Windows shells differ; PDD-side expansion is more portable across shells.\n\n**Git Integration**:\n- When the command detects changes between the current prompt and its last committed version, it automatically considers incremental generation if the output file exists.\n- If incremental generation is performed, both the current prompt and code files are staged with `git add` (if not already committed/added) to ensure you can roll back if needed.\n- Full regeneration always happens for new files (when there's no existing output file to update) or when the existing output file is deleted.\n\n**When to use**: Choose this command when implementing new functionality from scratch or updating existing code based on prompt changes. The command will automatically detect changes and determine whether to use incremental patching or full regeneration based on the significance of the changes.\n\nExamples:\n```\n# Basic generation with automatic git-based change detection\n# (incremental if output file exists, full generation if it doesn't)\npdd [GLOBAL OPTIONS] generate --output src/calculator.py calculator_python.prompt \n\n# Force incremental patching (requires output file to exist)\npdd [GLOBAL OPTIONS] generate --incremental --output src/calculator.py calculator_python.prompt\n\n# Force full regeneration (just delete the output file first)\nrm src/calculator.py  # Delete the file\npdd [GLOBAL OPTIONS] generate --output src/calculator.py calculator_python.prompt\n\n# Specify a different original prompt (bypassing git detection)\npdd [GLOBAL OPTIONS] generate --output src/calculator.py  --original-prompt old_calculator_python.prompt calculator_python.prompt\n```\n\n**Agentic Architecture Mode:**\n\nWhen the positional argument is a GitHub issue URL instead of a prompt file, `generate` enters agentic architecture mode. The issue body serves as the PRD (Product Requirements Document), and an 11-step agentic workflow generates `architecture.json`, `.pddrc`, and prompt files automatically.\n\n```bash\npdd generate https://github.com/owner/repo/issues/42\n```\n\nThe 11-step workflow:\n\n**Analysis \u0026 Generation (Steps 1-8):**\n1. **Analyze PRD**: Extract features, tech stack, and requirements from the issue content\n2. **Deep Analysis**: Feature decomposition, module boundaries, shared concerns\n3. **Research**: Web search for tech stack documentation and best practices\n4. **Design**: Module breakdown with dependency graph and priority ordering (auth modules are separated into dedicated concerns with low priority numbers)\n5. **Research Dependencies**: Find relevant API docs and code examples per module\n6. **Generate**: Produce complete `architecture.json` and scaffolding files\n7. **Generate .pddrc**: Create project configuration with context-specific paths\n8. **Generate Prompts**: Create prompt files for each module in `architecture.json`\n\n**Validation (Steps 9-11):**\n9. **Completeness Validation**: Verify all modules have prompts and dependencies\n10. **Sync Validation**: Run `pdd sync --dry-run` on each module to catch prompt-discovery and output path issues, including architecture-driven nested paths\n11. **Dependency Validation**: Preprocess prompts to verify `\u003cinclude\u003e` tags resolve under the same rules used at runtime, and reject fabricated example-file include paths\n\nEach validation step retries up to 3 times with automatic fixes before proceeding.\n\n**Options:**\n- `--skip-prompts`: Skip prompt file generation (steps 8-11), only generate `architecture.json` and `.pddrc`\n- `--project-root \u003cpath\u003e`: Explicit project-root override. Use the given path as the resolved project root instead of walking up from cwd. Useful when the cwd is a self-contained pdd project nested inside an unrelated outer git repo.\n\n**Project Root Detection:**\n\n`pdd generate \u003cissue-url\u003e` (and `pdd generate --incremental --experimental-prd`) resolves the project root by walking up from cwd. Tier A, Tier B, and Tier C are all project boundaries — the nearest boundary found while walking upward wins. This lets a nested PDD marker beat an enclosing outer `.git`, but prevents an enclosing outer PDD marker from overriding a nearer inner git repository:\n\n1. **Tier A (PDD-explicit)**: a directory containing `.pddrc` or a `.pdd/` directory.\n2. **Tier B (PDD-conventional)**: a directory containing `sources/` plus PRD/spec markdown (`prd*.md`, `spec*.md`, or `*_prd.md`/`*_spec.md`).\n3. **Tier C (git)**: a directory containing `.git`.\n\n`Path.home()` (the user's `$HOME`) is skipped for the PDD-marker check — `~/.pdd` and `~/.pddrc` are user-global config (created by `pdd setup`), not project markers. So a normal repo under `$HOME` without its own marker still falls through to its enclosing `.git` rather than resolving to `$HOME`.\n\nA self-contained pdd project nested inside an unrelated outer git repo is correctly identified as its own project root. A separate git repository nested inside an outer PDD project is also correctly identified as its own root. When the resolved project root is a strict descendant of the enclosing git toplevel, the remote-vs-issue mismatch warning is suppressed (it would be a false positive). Pass `--project-root \u003cpath\u003e` to bypass marker-based discovery entirely; this is most useful for CI scripts and unusual layouts where automatic detection cannot infer the right root, since marker-based detection already handles the nested-project case.\n\nPrerequisites:\n- `gh` CLI must be installed and authenticated\n- The issue must contain a PRD describing the project scope\n\n**Workflow Resumption**: Re-running `pdd generate \u003cissue-url\u003e` resumes from the last completed step. State is persisted to GitHub issue comments for cross-machine resume.\n\n**Hard Stops**: The workflow stops if the PRD content is insufficient, the tech stack is ambiguous, or clarification is needed. Address the issue and re-run.\n\nExample:\n```bash\npdd generate https://github.com/myorg/myrepo/issues/42\n# Generates: architecture.json, architecture_diagram.html, .pddrc, prompts/*.prompt\n\n# Skip prompt generation (faster, just architecture)\npdd generate --skip-prompts https://github.com/myorg/myrepo/issues/42\n# Generates: architecture.json, architecture_diagram.html, .pddrc\n```\n\n**Experimental Incremental PRD Mode (`--incremental --experimental-prd` with a PRD file or issue URL):**\n\nAfter the initial architecture has been generated, `pdd generate --incremental --experimental-prd \u003cprd_file_or_issue_url\u003e` produces a targeted, validated patch instead of regenerating from scratch. The flow diffs the PRD against a hash/provenance record in `.pdd/meta/prd_hashes.json` plus an ignored local raw-baseline cache in `.pdd/cache/prd_snapshots/`, asks the LLM for a structured `ArchitecturePatch` (add/remove/modify modules + dependency updates), validates it deterministically (rejecting unknown modules, dangling dependencies, removals that leave dependents, unsupported fields, path traversal, and dependency cycles), and on success applies it atomically with `.bak` backups, propagates Requirements changes into affected prompts via `detect_change` + `change`, and generates new prompt files for added modules. Tracked metadata never stores raw PRD text, GitHub issue bodies, or issue comments; the command also writes `.pdd/cache/.gitignore` so raw baselines stay local even in projects without a root ignore rule.\n\n```bash\n# Diff PRD vs last fingerprint, patch architecture.json + prompts\npdd generate --incremental --experimental-prd docs/prd.md\n\n# Same, sourced from a GitHub issue\npdd generate --incremental --experimental-prd https://github.com/owner/repo/issues/42\n\n# Preview without writing — dry-run is safe (no files modified)\npdd generate --incremental --experimental-prd --dry-run docs/prd.md\n\n# Suppress GitHub issue status comments during agentic runs\npdd generate --incremental --experimental-prd --no-github-state docs/prd.md\n\n# Patch a subproject architecture/prompts directory\npdd generate --incremental --experimental-prd --output-dir service docs/prd.md\n```\n\nThis mode is never selected by suffix alone: `--experimental-prd` is required. `--incremental` with a `.prompt` file remains the legacy code-patching mode (see \"Force incremental patching\" example above), and `.md`/`.markdown`/`.txt`/`.rst`/`.adoc` inputs also stay in legacy code generation when options such as `--output`, `--original-prompt`, `--template`, or `--unit-test` are present. Re-running with no PRD changes is a free no-op (\"No PRD changes detected\"). On invalid LLM patches the orchestrator retries up to 3 times with concrete validation feedback before failing without writes.\n\n**Current limitations (this experimental mode is intentionally narrower than `pdd generate \u003cissue-url\u003e`):**\n\n- **Starter prompts for new modules.** When the LLM patch adds a new module, this command generates a lightweight starter prompt (PDD metadata tags, architecture-target-relative `\u003cinclude\u003e` per dependency, Role / Requirements / Interface Specification / Dependencies skeleton) — not the richer artifacts produced by the full agentic Step 9 prompt-generation flow. If you used `--output-dir service` or an issue-derived target directory, run follow-up sync from that target directory (`cd service \u0026\u0026 pdd sync`) because generated includes resolve there. Run `pdd sync` from the repo root only for root-level architectures.\n- **Hidden/config file targets are blocked.** Incremental mode refuses LLM-proposed `filepath` values with hidden path components or secret-like names such as `.env`, `.github/...`, private keys, credentials, and secrets files. Use full agentic generation or a manual architecture edit for legitimate hidden/config-file modules.\n- **No shared-context-doc merge.** Step 8.5's merge across `data_dictionary.yaml` / `api_contracts.yaml` / `integration_points.yaml` is **not** invoked. Update those files manually if the PRD change affects them.\n- **No `pdd sync --dry-run` validation.** New or modified modules are not validated against the wider sync pipeline before this command writes; run `pdd sync` after the experimental PRD update to catch any downstream issues.\n\nThese are tracked as follow-ups under #859. The architecture-side propagation (patch validation, transactional commit with rollback, concurrent-modification guard, `\u003cpdd-*\u003e` tag preservation, Requirements updates via `detect_change` + `change`) is fully implemented and live-verified.\n\n#### Prompt Templates\n\nTemplates are reusable prompt files that generate a specific artifact (code, JSON, tests, etc.). Templates carry human/CLI metadata in YAML front matter (parsed by the CLI and not sent to the LLM), while the body stays concise and model‑focused.\n\n- Front matter (human/CLI):\n  - name, description, version, tags, language, output\n  - variables: schema for `-e/--env` (required/optional, type, examples)\n  - usage: copyable `pdd generate` commands\n  - discover (optional): CLI‑executed file discovery (root, patterns, exclude, caps)\n  - output_schema (optional): JSON shape used by the CLI for validation and by `pdd templates show`\n- Prompt body (LLM):\n  - Includes to hydrate context: `\u003cinclude\u003e${VAR}\u003c/include\u003e`, `\u003cinclude-many\u003e${LIST}\u003c/include-many\u003e`\n  - Crisp instructions and an explicit output contract; no human usage notes or discovery logic\n\nQuick examples (templates)\n\n```\n# Minimal (PRD required)\npdd generate -e PRD_FILE=docs/specs.md --output architecture.json \\\n  pdd/templates/architecture/architecture_json.prompt\n\n# With extra context\npdd generate -e PRD_FILE=docs/specs.md -e TECH_STACK_FILE=docs/tech_stack.md \\\n  -e DOC_FILES='docs/ux.md,docs/components.md' \\\n  -e INCLUDE_FILES='src/app.py,src/api.py,frontend/app/layout.tsx' \\\n  --output architecture.json pdd/templates/architecture/architecture_json.prompt\n\n# Multiple variants\npdd generate -e PRD_FILE=docs/specs.md -e APP_NAME=Shop   --output apps/shop/architecture.json   pdd/templates/architecture/architecture_json.prompt\npdd generate -e PRD_FILE=docs/specs.md -e APP_NAME=Admin  --output apps/admin/architecture.json  pdd/templates/architecture/architecture_json.prompt\npdd generate -e PRD_FILE=docs/specs.md -e APP_NAME=Public --output apps/public/architecture.json pdd/templates/architecture/architecture_json.prompt\n\n# 4) Use variables in the output path\n# 5) Use shell env fallback for convenience\nexport APP=shop\npdd generate -e APP -e PRD_FILE=docs/specs.md --output 'apps/${APP}/architecture.json' pdd/templates/architecture/architecture_json.prompt\n```\n\nTips for authoring templates\n\n- Put human guidance in YAML front matter (variables with examples, usage, notes); keep the prompt body model‑focused.\n- Use `\u003cinclude\u003e`/`\u003cinclude-many\u003e` for curated context; prefer specs/configs over large code dumps.\n- Parameterized includes: pass file paths via `-e`, e.g. `\u003cinclude\u003e${PRD_FILE}\u003c/include\u003e`; the engine resolves includes after variable expansion.\n- If your template outputs a specific filename, show example commands with `--output`.\n\nBehavior notes\n\n- Variable expansion only applies to variables explicitly passed via `-e/--env` (or via the env fallback with `-e KEY`). Other `$NAME` occurrences remain unchanged.\n- `--output` also accepts `$VAR`/`${VAR}` from the same set of variables.\n- If you omit `--output`, PDD derives the filename from the prompt basename and detected language extension; set `PDD_GENERATE_OUTPUT_PATH` to direct outputs to a common directory.\n\nTemplates: Commands\n\n- Front matter is parsed (not sent to the LLM) and powers:\n  - Variables schema and validation\n  - Usage examples (rendered by `pdd templates show`)\n  - Optional `discover` settings (executed by the CLI with caps)\n  - Optional `output_schema` for validation\n- Commands:\n  - `pdd templates list [--json] [--filter tag=...]`\n  - `pdd templates show \u003cname\u003e`\n  - `pdd templates copy \u003cname\u003e --to prompts/`\n  - `pdd generate --template \u003cname\u003e [-e KEY=VALUE...] [--output PATH]`\n\n#### Built-In Templates\n\nPDD can distribute a curated set of popular templates as part of the package to help you get started quickly (e.g., frontend/Next.js, backend/Flask, data/ETL).\n\nWhere built-ins live (packaged)\n\n- Under the installed package at `pdd/templates/\u003ccategory\u003e/**/*.prompt` (plus optional README/index files). When installed from PyPI, these are included as package data.\n\nIncluded starter templates\n\n- `architecture/architecture_json.prompt`: Universal architecture generator (requires `-e PRD_FILE=...`; supports optional `TECH_STACK_FILE`, `DOC_FILES`, `INCLUDE_FILES`).\n\n**LLM Toggle Functionality:**\n\nAll templates support the `llm` parameter to control whether LLM generation runs:\n\n- **`llm=true`** (default): Full generation with LLM + post-processing\n- **`llm=false`**: Skip LLM generation, run only post-processing\n\n**Architecture JSON Template Features:**\n\nThe `architecture/architecture_json` template includes automatic **Mermaid diagram generation**:\n\n- **Post-processing**: Automatically converts the generated JSON into an interactive HTML Mermaid diagram\n- **Visualization**: Creates `architecture_diagram.html` with color-coded modules (frontend/backend/shared)\n- **Interactive**: Hover tooltips show module details, dependencies, and descriptions\n- **Self-contained**: HTML file works offline with embedded Mermaid library\n\n**Example Commands:**\n\n```bash\n# Full generation (LLM + post-processing + Mermaid HTML)\npdd generate --template architecture/architecture_json \\\n  -e PRD_FILE=docs/specs.md \\\n  -e APP_NAME=\"MyApp\" \\\n  --output architecture.json\n# Results in: architecture.json + architecture_diagram.html\n\n# Post-processing only (skip LLM, generate HTML from existing JSON)\npdd generate --template architecture/architecture_json \\\n  -e APP_NAME=\"MyApp\" \\\n  -e llm=false \\\n  --output architecture.json\n# Results in: architecture_diagram.html (from existing architecture.json)\n```\n\n**Context URLs (optional field):**\n\nArchitecture entries support an optional `context_urls` array that associates web documentation references with each module. When prompts are generated from the architecture (via `generate_prompt`), these URLs are emitted as `\u003cweb\u003e` tags in the Dependencies section, enabling the LLM to fetch relevant API documentation during code generation.\n\n```json\n{\n  \"filename\": \"orders_api_Python.prompt\",\n  \"dependencies\": [\"models_Python.prompt\"],\n  \"context_urls\": [\n    {\"url\": \"https://fastapi.tiangolo.com/tutorial/first-steps/\", \"purpose\": \"FastAPI routing patterns\"},\n    {\"url\": \"https://docs.pydantic.dev/latest/concepts/models/\", \"purpose\": \"Pydantic model validation\"}\n  ],\n  ...\n}\n```\n\nThe `context_urls` field is populated automatically by the agentic architecture workflow (step 5: research dependencies) but can also be added manually to any architecture entry.\n\nFront Matter (YAML) metadata\n\n- Templates include YAML front matter with human-readable metadata:\n  - `name`, `description`, `version`, `tags`: docs and discovery\n  - `language`, `output`: defaults for `generate`\n  - `variables`: parameter schema for `-e/--env` (type, required, default)\n\nExample (architecture template):\n\n```\n---\nname: architecture/architecture_json\ndescription: Unified architecture template for multiple stacks\nversion: 1.0.0\ntags: [architecture, template, json]\nlanguage: json\noutput: architecture.json\nvariables:\n  TECH_STACK:\n    required: false\n    type: string\n    description: Target tech stack for interface shaping and conventions.\n    examples: [nextjs, python, fastapi, flask, django, node, go]\n  API_STYLE:\n    required: false\n    type: string\n    description: API style for backends.\n    examples: [rest, graphql]\n  APP_NAME:\n    required: false\n    type: string\n    description: Optional app name for context.\n    example: Shop\n  PRD_FILE:\n    required: true\n    type: path\n    description: Primary product requirements document (PRD) describing scope and goals.\n    example_paths: [PRD.md, docs/specs.md, docs/product/prd.md]\n    example_content: |\n      Title: Order Management MVP\n      Goals: Enable customers to create and track orders end-to-end.\n      Key Features:\n        - Create Order: id, user_id, items[], total, status\n        - View Order: details page with status timeline\n        - List Orders: filter by status, date, user\n      Non-Functional Requirements:\n        - P95 latency \u003c 300ms for read endpoints\n        - Error rate \u003c 0.1%\n  TECH_STACK_FILE:\n    required: false\n    type: path\n    description: Tech stack overview (languages, frameworks, infrastructure, and tools).\n    example_paths: [docs/tech_stack.md, docs/architecture/stack.md]\n    example_content: |\n      Backend: Python (FastAPI), Postgres (SQLAlchemy), PyTest\n      Frontend: Next.js (TypeScript), shadcn/ui, Tailwind CSS\n      API: REST\n      Auth: Firebase Auth (GitHub Device Flow), JWT for API\n      Infra: Vercel (frontend), Cloud Run (backend), Cloud SQL (Postgres)\n      Observability: OpenTelemetry traces, Cloud Logging\n  DOC_FILES:\n    required: false\n    type: list\n    description: Additional documentation files (comma/newline-separated).\n    example_paths: [docs/ux.md, docs/components.md]\n    example_content: |\n      Design overview, patterns and constraints\n  INCLUDE_FILES:\n    required: false\n    type: list\n    description: Specific source files to include (comma/newline-separated).\n    example_paths: [src/app.py, src/api.py, frontend/app/layout.tsx, frontend/app/page.tsx]\n  usage:\n    generate:\n      - name: Minimal (PRD only)\n        command: pdd generate -e PRD_FILE=docs/specs.md --output architecture.json pdd/templates/architecture/architecture_json.prompt\n      - name: With tech stack overview\n        command: pdd generate -e PRD_FILE=docs/specs.md -e TECH_STACK_FILE=docs/tech_stack.md --output architecture.json pdd/templates/architecture/architecture_json.prompt\n  discover:\n    enabled: false\n    max_per_pattern: 5\n    max_total: 10\n---\n```\n\nNotes\n\n- YAML front matter is parsed and not sent to the LLM. Use `pdd templates show` to view variables, usage, discover, and output schema. Pass variables via `-e` at the CLI.\n\nTemplate Variables (reference)\n\n- Architecture (`architecture/architecture_json.prompt`)\n  - `PRD_FILE` (path, required): Primary spec/PRD file path\n  - `TECH_STACK_FILE` (path, optional): Tech stack overview file (includes API style; e.g., docs/tech_stack.md)\n  - `APP_NAME` (string, optional): App name for context\n  - `DOC_FILES` (list, optional): Comma/newline-separated list of additional doc paths\n  - `INCLUDE_FILES` (list, optional): Comma/newline-separated list of source files to include\n  - `SCAN_PATTERNS` (list, optional): Discovery patterns defined in front matter `discover` and executed by the CLI\n  - `SCAN_ROOT` (path, optional): Discovery root defined in front matter `discover`\n\nNotes\n\n- These variables are declared in YAML front matter at the top of each template for clarity and future CLI discovery. Until the CLI parses front matter, pass values via `-e` as shown in examples.\n\nCopy-and-generate\n\n- Copy the desired template(s) into your project’s `prompts/` folder, then use `pdd generate` as usual. This keeps prompts versioned with your repo so you can edit and evolve them.\n- Quick copy (Python one‑liner; run from your project root):\n\n```\npython - \u003c\u003c'PY'\nfrom importlib.resources import files\nimport shutil, os\n\ndst_dir = 'prompts/architecture'\nsrc_dir = files('pdd').joinpath('templates/architecture')\nos.makedirs(dst_dir, exist_ok=True)\n\nfor p in src_dir.rglob('*.prompt'):\n    shutil.copy(p, dst_dir)\nprint(f'Copied built-in templates from {src_dir} -\u003e {dst_dir}')\nPY\n\n# Then generate from the copied prompt(s)\npdd generate --output architecture.json prompts/architecture/architecture_json.prompt\n```\n\nUnified template examples\n\n```\n# Frontend (Next.js) — interface.page.route and component props\npdd generate \\\n  -e APP_NAME=Shop \\\n  # (routes are inferred from PRD/tech stack/files)\n  -e PRD_FILE=docs/specs.md \\\n  -e DOC_FILES='docs/ux.md,docs/components.md' \\\n  -e TECH_STACK_FILE=docs/tech_stack.md \\\n  # discovery, if needed, is configured in template YAML and executed by the CLI\n  --output architecture.json \\\n  pdd/templates/architecture/architecture_json.prompt\n\n# Backend (Python) — interface.module.functions or interface.api.endpoints\npdd generate \\\n  -e PRD_FILE=docs/backend-spec.md \\\n  -e TECH_STACK_FILE=docs/tech_stack.md \\\n  -e INCLUDE_FILES='src/app.py,src/api.py,pyproject.toml' \\\n  --output architecture.json \\\n  pdd/templates/architecture/architecture_json.prompt\n```\n\n**Interface Schema**\n\n- Core keys (every item):\n  - `reason`, `description`, `dependencies`, `priority`, `filename`, optional `tags`.\n- Interface object (typed, include only what applies):\n  - `type`: `component` | `page` | `module` | `api` | `graphql` | `cli` | `job` | `message` | `config`\n  - `component`: `props[]`, optional `emits[]`, `context[]`\n  - `page`: `route`, optional `params[]`, `layout`, and `dataSources[]` where each entry is an object with required `kind` (e.g., `api`, `query`) and `source` (URL or identifier), plus optional `method`, `description`, `auth`, `inputs[]`, `outputs[]`, `refreshInterval`, `notes`\n  - `module`: `functions[]` with `name`, `signature`, optional `returns`, `errors`, `sideEffects`\n  - `api`: `endpoints[]` with `method`, `path`, optional `auth`, `requestSchema`, `responseSchema`, `errors`\n  - `graphql`: optional `sdl`, or `operations` with `queries[]`, `mutations[]`, `subscriptions[]`\n  - `cli`: `commands[]` with `name`, optional `args[]`, `flags[]`, `exitCodes[]`; optional `io` (`stdin`, `stdout`)\n  - `job`: `trigger` (cron/event), optional `inputs[]`, `outputs[]`, `retryPolicy`\n  - `message`: `topics[]` with `name`, `directi","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpromptdriven%2Fpdd","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpromptdriven%2Fpdd","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpromptdriven%2Fpdd/lists"}