An open API service indexing awesome lists of open source software.

https://github.com/promptdriven/pdd

Prompt Driven Development (PDD): The Last Programming Language™. Prompt files are source; code is generated output.
https://github.com/promptdriven/pdd

ai cli code developer-tools development methodology prompt prompt-engineering prompt-toolkit prompts prompts-template

Last synced: 1 day ago
JSON representation

Prompt Driven Development (PDD): The Last Programming Language™. Prompt files are source; code is generated output.

Awesome Lists containing this project

README

          

# PDD: The Last Programming Language™

![PyPI version](https://img.shields.io/pypi/v/pdd-cli.svg) [![Discord](https://img.shields.io/badge/Discord-join%20chat-7289DA.svg?logo=discord&logoColor=white)](https://discord.gg/Yp4RTh8bG7)

## Introduction

PDD (Prompt-Driven Development) is a prompt-native programming system. `.prompt`
files are the human-authored source language; Python, TypeScript, Go, and other
traditional languages are generated artifacts.

PDD is the last programming language in this specific sense: developers author
durable intent, constraints, examples, and tests, then compile that source into
whatever implementation language the project needs. Code remains real and
reviewable, but it is no longer the primary source of truth.

**Getting started is simple:**

```bash
# Install and run
uv tool install pdd-cli
pdd setup
pdd connect
```

This launches a web interface at `localhost:9876` where you can:
- Implement GitHub issues automatically
- Generate and test code from prompts
- Manage your PDD projects visually


PDD Handpaint Demo

For CLI users, PDD also offers powerful **agentic commands** that implement GitHub issues automatically:
- `pdd change ` - Implement feature requests (13-step workflow)
- `pdd bug ` - Create failing tests for bugs
- `pdd fix ` - Fix the failing tests
- `pdd split ` - Diagnose and split large dev units (15-step workflow with intent classification, diagnosis, phase extraction, per-child verify gate, and repair)
- `pdd generate ` - Generate architecture.json from a PRD issue (11-step workflow)
- `pdd test ` - Generate UI tests from issue descriptions (18-step workflow with exploratory testing, contract validation, accessibility audits)

For prompt-based workflows, the **`sync`** command automates the complete development cycle with intelligent decision-making, real-time visual feedback, and sophisticated state management.

## Whitepaper

For the positioning essay behind this shift, read [The Last Programming Language](docs/the-last-programming-language.md).

For 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.

[Read the Full Whitepaper with Benchmarks](docs/whitepaper_with_benchmarks/whitepaper_w_benchmarks.md)

For a case study on specification drift in AI-assisted coding workflows, read [Why AI Code Falls Apart](docs/whitepaper_specification_drift/whitepaper.md).

Also see the Prompt‑Driven Development Doctrine for core principles and practices: [docs/prompt-driven-development-doctrine.md](docs/prompt-driven-development-doctrine.md)

For pre-merge prompt and user-story quality (vague terms, vocabulary, optional LLM review), see [docs/prompt_lint.md](docs/prompt_lint.md).

## Installation

### Prerequisites for macOS

On macOS, you'll need to install some prerequisites before installing PDD:

1. **Install Xcode Command Line Tools** (required for Python compilation):
```bash
xcode-select --install
```

2. **Install Homebrew** (recommended package manager for macOS):
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```

After installation, add Homebrew to your PATH:
```bash
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile && eval "$(/opt/homebrew/bin/brew shellenv)"
```

3. **Install Python** (if not already installed):
```bash
# Check if Python is installed
python3 --version

# If Python is not found, install it via Homebrew
brew install python
```

**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.

### Recommended Method: uv

We recommend installing PDD using the [uv package manager](https://github.com/astral-sh/uv) for better dependency management and automatic environment configuration:

```bash
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install PDD using uv tool install
uv tool install pdd-cli
```

This installation method ensures:
- Faster installations with optimized dependency resolution
- Automatic environment setup without manual configuration
- Proper handling of the PDD_PATH environment variable
- Better isolation from other Python packages

The PDD CLI will be available immediately after installation without requiring any additional environment configuration.

Verify installation:
```bash
pdd --version
```

With the CLI on your `PATH`, continue with:
```bash
pdd setup
```
The command detects agentic CLI tools, scans for API keys, configures models, and seeds local configuration files.
If 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/`).

### Alternative: pip Installation

If you prefer using pip, you can install PDD with:
```bash
pip install pdd-cli
```

## Advanced Installation Options

### Virtual Environment Installation
```bash
# Create virtual environment
python -m venv pdd-env

# Activate environment
# On Windows:
pdd-env\Scripts\activate
# On Unix/MacOS:
source pdd-env/bin/activate

# Install PDD
pip install pdd-cli
```

## Getting Started

### Option 1: Web Interface (Recommended)

The easiest way to use PDD is through the web interface:

```bash
# 1. Install PDD
curl -LsSf https://astral.sh/uv/install.sh | sh
uv tool install pdd-cli

# 2. Run setup (API keys, shell completion)
pdd setup

# 3. Launch the web interface
pdd connect
```

This opens a browser-based interface where you can:
- **Run Commands**: Execute `pdd change`, `pdd bug`, `pdd fix`, `pdd sync` etc. visually
- **Browse Files**: View and edit prompts, code, and tests in your project
- **Remote Access**: Access your session from any browser via PDD Cloud (use `--local-only` to disable)

### Option 2: Issue-Driven CLI

For CLI enthusiasts, implement GitHub issues directly:

**Prerequisites:**
1. **GitHub CLI** - Required for issue access:
```bash
brew install gh && gh auth login
```

2. **One Agentic CLI** - Required to run the workflows (install at least one):
- **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)
- **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).
- **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.
- **Codex CLI**: `npm install -g @openai/codex` (uses `~/.codex/auth.json` ChatGPT login if present, otherwise `OPENAI_API_KEY`)
- **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`)

**Usage:**
```bash
# Implement a feature request
pdd change https://github.com/owner/repo/issues/123

# Or fix a bug
pdd bug https://github.com/owner/repo/issues/456
pdd fix https://github.com/owner/repo/issues/456
```

### Option 3: Manual Prompt Workflow

For learning PDD fundamentals or working with existing prompt files:

```bash
cd your-project
pdd sync module_name # Full automated workflow
```

See the [Hello Example](#-quickstart-hello-example) below for a step-by-step introduction.

---

## 🚀 Quickstart (Hello Example)

If you want to understand PDD fundamentals, follow this manual example to see it in action.

1. **Install prerequisites** (macOS/Linux):
```bash
xcode-select --install # macOS only
curl -LsSf https://astral.sh/uv/install.sh | sh
uv tool install pdd-cli
pdd --version
```

2. **Clone repo**

```bash
# Clone the repository (if not already done)
git clone https://github.com/promptdriven/pdd.git
cd pdd/examples/hello
```

3. **Set one API key** (choose your provider):
```bash
export GEMINI_API_KEY="your-gemini-key"
# OR
export OPENAI_API_KEY="your-openai-key"
```

### Post-Installation Setup (Required first step after installation)

Run the comprehensive setup wizard:
```bash
pdd setup
```

The setup wizard runs these steps:
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.
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.
3. Configures models from a reference CSV `data/llm_model.csv` of top models (ELO ≥ 1300) across all LiteLLM-supported providers based on your available API keys
4. Optionally creates a `.pddrc` project config
5. Tests the first available model with a real LLM call
6. Prints a structured summary (CLIs, keys, models, test result)

The wizard can be re-run at any time to update keys, add providers, or reconfigure settings.

> **Important:** After setup completes, source the API environment file so your keys take effect in the current terminal session:
> ```bash
> source ~/.pdd/api-env.zsh # or api-env.bash, depending on your shell
> ```
> New terminal windows will load keys automatically.

If 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.

5. **Run Hello**:
```bash
cd ../hello
pdd --force generate hello_python.prompt
python3 hello.py
```

✅ Expected output:
```
hello
```

## Cloud vs Local Execution

PDD commands can be run either in the cloud or locally. By default, all commands run in the cloud mode, which provides several advantages:

- No need to manage API keys locally
- Access to more powerful models
- Shared examples and improvements across the PDD community
- Automatic updates and improvements
- Better cost optimization

### Cloud Authentication

When running in cloud mode (default), PDD uses GitHub Single Sign-On (SSO) for authentication. On first use, you'll be prompted to authenticate:

1. PDD will open your default browser to the GitHub login page
2. Log in with your GitHub account
3. Authorize PDD Cloud to access your GitHub profile
4. Once authenticated, you can return to your terminal to continue using PDD

The authentication token is securely stored locally and automatically refreshed as needed.

### Local Mode Requirements

When running in local mode with the `--local` flag, you'll need to set up API keys for the language models:

```bash
# For OpenAI
export OPENAI_API_KEY=your_api_key_here

# For Anthropic
export ANTHROPIC_API_KEY=your_api_key_here

# For other supported providers (LiteLLM supports multiple LLM providers)
export PROVIDER_API_KEY=your_api_key_here
```

Some local-mode providers do not use API keys. GitHub Copilot models
authenticate through LiteLLM's OAuth device flow; run `pdd setup` and choose
the provider to complete that login.

Add these to your `.bashrc`, `.zshrc`, or equivalent for persistence.

PDD's local mode uses LiteLLM (version 1.75.5 or higher) for interacting with language models, providing:

- Support for multiple model providers (OpenAI, Anthropic, Google/Vertex AI, and more)
- Automatic model selection based on strength settings
- Response caching for improved performance
- Smart token usage tracking and cost estimation
- Interactive API key acquisition when keys are missing

When keys are missing, PDD will prompt for them interactively and securely store them in your local `.env` file.

### Local Model Configuration

PDD uses a CSV file to configure model selection and capabilities. This configuration is loaded from:

1. User-specific configuration: `~/.pdd/llm_model.csv` (takes precedence if it exists)
2. Project-specific configuration: `/.pdd/llm_model.csv`
3. Package default: Bundled with PDD installation (fallback when no local configurations exist)

The CSV includes columns for:
- `provider`: The LLM provider (e.g., "openai", "anthropic", "google")
- `model`: The LiteLLM model identifier (e.g., "gpt-4", "claude-3-opus-20240229")
- `input`/`output`: Costs per million tokens
- `coding_arena_elo`: ELO rating for coding ability
- `api_key`: The environment variable name for required authentication, or
blank for local and device-flow providers such as Ollama, LM Studio, and
GitHub Copilot
- `structured_output`: Whether the model supports structured JSON output
- `reasoning_type`: Support for reasoning capabilities ("none", "budget", or "effort")

For 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).

For 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").

## Troubleshooting Common Installation Issues

1. **Command not found**
```bash
# Add to PATH if needed
export PATH="$HOME/.local/bin:$PATH"
```

2. **Permission errors**
```bash
# Install with user permissions
pip install --user pdd-cli
```

3. **macOS-specific issues**
- **Xcode Command Line Tools not found**: Run `xcode-select --install` to install the required development tools
- **Homebrew not found**: Install Homebrew using the command in the prerequisites section above
- **Python not found or wrong version**: Install Python 3 via Homebrew: `brew install python`
- **Permission denied during compilation**: Ensure Xcode Command Line Tools are properly installed and you have write permissions to the installation directory
- **uv installation fails**: Try installing uv through Homebrew: `brew install uv`
- **Python version conflicts**: If you have multiple Python versions, ensure `python3` points to Python 3.8+: `which python3 && python3 --version`

## Version

To check your installed version, run:
```
pdd --version
```
PDD 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).

## Supported Programming Languages

PDD supports a wide range of programming languages, including but not limited to:
- Python
- JavaScript
- TypeScript
- Java
- C++
- Ruby
- Go

The specific language is often determined by the prompt file's naming convention or specified in the command options.

## Prompt File Naming Convention

Prompt files in PDD commonly follow one of these formats:
```
_.prompt
```
or, for architecture-driven projects with nested output paths:
```
_.prompt
```
Where:
- `` is the base name of the file or project in legacy flat layouts
- `` mirrors the output filepath without its extension in architecture-driven layouts
- `` / `` is the programming language or prompt context suffix used by the project

Examples:
- `factorial_calculator_python.prompt` (basename: factorial_calculator, language: python)
- `responsive_layout_css.prompt` (basename: responsive_layout, language: css)
- `data_processing_pipeline_python.prompt` (basename: data_processing_pipeline, language: python)
- `src/models/user_Python.prompt` → generates `src/models/user.py`
- `app/api/orders/route_TypeScript.prompt` → generates `app/api/orders/route.ts`

PDD supports both conventions. Legacy hand-written prompts are often flat, while prompts generated from `architecture.json` typically mirror the target filepath directory structure.

## Prompt-Driven Development Philosophy

### Core Concepts

Prompt-Driven Development (PDD) inverts traditional software development by treating prompts as the primary artifact - not code. This paradigm shift has profound implications:

1. **Prompts as Source of Truth**:
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.

2. **Natural Language Over Code**:
Prompts are written primarily in natural language, making them more accessible to non-programmers and clearer in expressing intent.

3. **Regenerative Development**:
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.

4. **Intent Preservation**:
Prompts capture the "why" behind code in addition to the "what" - preserving design rationale in a way that comments often fail to do.

### Mental Model

To work effectively with PDD, adopt these mental shifts:

1. **Prompt-First Thinking**:
Always start by defining what you want in a prompt before generating any code.

2. **Bidirectional Flow**:
- Prompt → Code: The primary direction (generation)
- Code → Prompt: Secondary but crucial (keeping prompts in sync with code changes)

3. **Modular Prompts**:
Just as you modularize code, you should modularize prompts into self-contained units that can be composed.

4. **Integration via Examples**:
Modules integrate through their examples, which serve as interfaces, allowing for token-efficient references.

### PDD Workflows: Conceptual Understanding

Each workflow in PDD addresses a fundamental development need:

1. **Initial Development Workflow**
- **Purpose**: Creating functionality from scratch
- **Conceptual Flow**: Define dependencies → Generate implementation → Create interfaces → Ensure runtime functionality → Verify correctness

This workflow embodies the prompt-to-code pipeline, moving from concept to tested implementation.

2. **Code-to-Prompt Update Workflow**
- **Purpose**: Maintaining prompt as source of truth when code changes
- **Conceptual Flow**: Sync code changes to prompt → Identify impacts → Propagate changes

This workflow ensures the information flow from code back to prompts, preserving prompts as the source of truth.

3. **Debugging Workflows**
- **Purpose**: Resolving different types of issues
- **Conceptual Types**:
- **Context Issues**: Addressing misunderstandings in prompt interpretation
- **Runtime Issues**: Fixing execution failures
- **Logical Issues**: Correcting incorrect behavior
- **Traceability Issues**: Connecting code problems back to prompt sections

These workflows recognize that different errors require different resolution approaches.

4. **Refactoring Workflow**
- **Purpose**: Improving prompt organization and reusability
- **Conceptual Flow**: Extract functionality → Ensure dependencies → Create interfaces

This workflow parallels code refactoring but operates at the prompt level.

5. **Multi-Prompt Architecture Workflow**
- **Purpose**: Coordinating systems with multiple prompts
- **Conceptual Flow**: Detect conflicts → Resolve incompatibilities → Regenerate code → Update interfaces → Verify system

This workflow addresses the complexity of managing multiple interdependent prompts.

6. **Enhancement Phase**: Use Feature Enhancement when adding capabilities to existing modules.

### Workflow Selection Principles

The choice of workflow should be guided by your current development phase:

1. **Creation Phase**: Use Initial Development when building new functionality.

2. **Maintenance Phase**: Use Code-to-Prompt Update when existing code changes.

3. **Problem-Solving Phase**: Choose the appropriate Debugging workflow based on the issue type:
- Preprocess → Generate for prompt interpretation issues
- Crash for runtime errors
- Bug → Fix for logical errors
- Trace for locating problematic prompt sections

4. **Restructuring Phase**: Use Refactoring when prompts grow too large or complex.

5. **System Design Phase**: Use Multi-Prompt Architecture when coordinating multiple components.

6. **Enhancement Phase**: Use Feature Enhancement when adding capabilities to existing modules.

### PDD Design Patterns

Effective PDD employs these recurring patterns:

1. **Dependency Injection via Auto-deps**:
Automatically including relevant dependencies in prompts.

2. **Interface Extraction via Example**:
Creating minimal reference implementations for reuse.

3. **Bidirectional Traceability**:
Maintaining connections between prompt sections and generated code.

4. **Test-Driven Prompt Fixing**:
Using tests to guide prompt improvements when fixing issues.

5. **Hierarchical Prompt Organization**:
Structuring prompts from high-level architecture to detailed implementations.

## Basic Usage

```
pdd [GLOBAL OPTIONS] COMMAND [OPTIONS] [ARGS]...
```

## Command Overview

Here is a brief overview of the main commands provided by PDD. Click the command name to jump to its detailed section:

### Command Relationships

The following diagram shows how PDD commands interact:

```mermaid
graph TB
subgraph Entry Points
connect["pdd connect (Web UI - Recommended)"]
cli["Direct CLI"]
ghapp["GitHub App"]
end

gen_url["pdd generate <url>"]

subgraph sync workflow
sync["pdd sync"]
s_deps["auto-deps"]
s_gen["generate"]
s_example["example"]
s_crash["crash"]
s_verify["verify"]
s_test["test"]
s_fix["fix"]
s_update["update"]
end

checkup["pdd checkup <url>"]
test_url["pdd test <url>"]
bug_url["pdd bug <url>"]
fix_url["pdd fix <url>"]
change["pdd change <url>"]
sync_url["pdd sync <url>"]

connect --> gen_url
cli --> gen_url
ghapp --> gen_url
gen_url --> sync
sync --> s_deps
s_deps --> s_gen
s_gen --> s_example
s_example --> s_crash
s_crash --> s_verify
s_verify --> s_test
s_test --> s_fix
s_fix --> s_update
sync --> checkup
checkup --> test_url
checkup --> bug_url
checkup --> change
test_url --> fix_url
bug_url --> fix_url
change --> sync_url
sync_url -.-> sync
```

**Key concepts:**
- **Entry points**: `pdd connect` (web UI), direct CLI, or the GitHub App
- **Start**: `pdd generate ` scaffolds architecture, prompts, and `.pddrc` from a PRD GitHub issue
- **Core loop**: `pdd sync` runs the full auto-deps → generate → example → crash → verify → test → fix → update cycle for each module
- **Health check**: `pdd checkup ` identifies what needs attention next; `pdd checkup --pr ... --issue ...` verifies existing PRs
- **Defect path**: `test ` or `bug ` surfaces failing tests → `fix ` resolves them
- **Feature path**: `change ` implements the feature → `sync ` re-runs sync across affected modules. Auth caveat: `sync ` still runs a LiteLLM-backed generate phase, so OAuth-only CLI setup is not enough; configure an API key first.

### Getting Started
- **[`connect`](#18-connect)**: **[RECOMMENDED]** Launch web interface for visual PDD interaction
- **[`setup`](#post-installation-setup-required-first-step-after-installation)**: Configure API keys and shell completion

### Agentic Commands (Issue-Driven)
- **[`change`](#8-change)**: Implement feature requests from GitHub issues (13-step workflow)
- **[`bug`](#14-bug)**: Analyze bugs and create failing tests from GitHub issues
- **[`checkup`](#17-checkup)**: Run automated project health checks from GitHub issues, or verify existing PRs against source issues
- **[`fix`](#6-fix)**: Fix failing tests (supports issue-driven and manual modes)
- **[`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.
- **[`test`](#4-test)**: Generate UI tests from GitHub issues (18-step workflow in agentic mode)

### Core Commands (Prompt-Based)
- **[`sync`](#1-sync)**: **[PRIMARY FOR PROMPT WORKFLOWS]** Automated prompt-to-code cycle
- **[`generate`](#2-generate)**: Creates runnable code from a prompt file; supports parameterized prompts via `-e/--env`
- **[`example`](#3-example)**: Generates a compact example showing how to use functionality defined in a prompt
- **[`test`](#4-test)**: Generates or enhances unit tests for a code file and its prompt
- **[`update`](#9-update)**: Updates the original prompt file based on modified code
- **[`verify`](#16-verify)**: Verifies functional correctness by running a program and judging output against intent
- **[`crash`](#12-crash)**: Fixes errors in a code module and its calling program that caused a crash

### Prompt Management
- **[`preprocess`](#5-preprocess)**: Preprocesses prompt files, handling includes, comments, and other directives
- **[`split`](#7-split)**: Splits large prompt files into smaller, more manageable ones
- **[`extracts prune`](#21-extracts)**: Garbage-collect orphaned extracts cache entries
- **[`auto-deps`](#15-auto-deps)**: Analyzes and inserts needed dependencies into a prompt file
- **[`sync-architecture`](#1a-sync-architecture)**: Updates `architecture.json` from prompt metadata tags
- **[`detect`](#10-detect)**: Analyzes prompts to determine which ones need changes based on a description
- **[`conflicts`](#11-conflicts)**: Finds and suggests resolutions for conflicts between two prompt files
- **[`trace`](#13-trace)**: Finds the corresponding line number in a prompt file for a given code line

### Utility Commands
- **[`auth`](#19-auth)**: Manages authentication with PDD Cloud
- **[`sessions`](#20-pdd-sessions---manage-remote-sessions)**: Manage remote sessions for `connect`

### User Story Prompt Tests
PDD 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.

Defaults:
- Stories live in `user_stories/` and match `story__*.md`.
- Prompts are loaded from `prompts/` (excluding `*_llm.prompt` by default).

Overrides:
- `PDD_USER_STORIES_DIR` sets the stories directory.
- `PDD_PROMPTS_DIR` sets the prompts directory.

Commands:
- `pdd detect --stories` runs the validation suite.
- `pdd change` runs story validation after prompt modifications and fails if any story fails.
- `pdd fix user_stories/story__*.md` applies a single story to prompts and re-validates it.
- `pdd test [prompt_2.prompt ...]` generates a `story__*.md` file and links those prompts.
- `pdd test user_stories/story__*.md` updates prompt links for an existing story file.

Story prompt linkage:
- Stories may include optional metadata to scope validation to a subset of prompts:
``
- If metadata is missing, `pdd detect --stories` validates against the full prompt set.
- In `--stories` mode, when `detect` identifies impacted prompts, PDD caches links back into the story metadata for future deterministic runs.

Template:
- See `user_stories/story__template.md` for a starter format.
## Global Options

These options can be used with any command:

- `--force`: Skip all interactive prompts (file overwrites, API key requests). Useful for CI/automation.
- `--strength FLOAT`: Set the strength of the AI model (0.0 to 1.0, default is 0.5).
- 0.0: Cheapest available model
- 0.5: Default base model
- 1.0: Most powerful model (highest ELO rating)
- `--time FLOAT`: Controls the reasoning allocation for LLM models supporting reasoning capabilities (0.0 to 1.0, default is 0.25).
- For models with specific reasoning token limits (e.g., 64k), a value of `1.0` utilizes the maximum available tokens.
- For models with discrete effort levels, `1.0` corresponds to the highest effort level.
- Values between 0.0 and 1.0 scale the allocation proportionally.
- `--temperature FLOAT`: Set the temperature of the AI model (default is 0.0).
- `--verbose`: Increase output verbosity for more detailed information. Includes token count and context window usage for each LLM call.
- `--quiet`: Decrease output verbosity for minimal information.
- `--output-cost PATH_TO_CSV_FILE`: Enable cost tracking and output a CSV file with usage details.
- `--review-examples`: Review and optionally exclude few-shot examples before command execution.
- `--local`: Run commands locally instead of in the cloud.
- `--core-dump`: Capture a debug bundle for this run so it can be replayed and analyzed later.
- `report-core`: Report a bug by creating a GitHub issue with the core dump file.
- `--context CONTEXT_NAME`: Override automatic context detection and use the specified context from `.pddrc`.
- `--list-contexts`: List all available contexts defined in `.pddrc` and exit.

### Core Dump Debug Bundles

If 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:

```bash
pdd --core-dump sync factorial_calculator
pdd --core-dump crash prompts/calc_python.prompt src/calc.py examples/run_calc.py crash_errors.log
```

When `--core-dump` is set, PDD:

- Captures the full CLI command and arguments
- Records relevant logs and internal trace information for that run
- Bundles the prompt(s), generated code, and key metadata needed to replay the issue

At the end of the run, PDD prints the path to the core dump bundle.
Attach that bundle when you open a GitHub issue or send a bug report so maintainers can quickly reproduce and diagnose your problem.

#### `report-core` Command

The `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.

**Usage:**
```bash
pdd report-core [OPTIONS] [CORE_FILE]
```

**Arguments:**
- `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.

**Options:**
- `--api`: Create the issue directly via the GitHub API instead of opening a browser. This enables automatic Gist creation for attached files.
- `--repo OWNER/REPO`: Override the target repository (default: `promptdriven/pdd`).
- `--description`, `-d TEXT`: A short description of what went wrong.

**Authentication:**

To use the `--api` flag, you need to be authenticated with GitHub. PDD checks for credentials in the following order:

1. **GitHub CLI**: `gh auth token` (recommended)
2. **Environment Variables**: `GITHUB_TOKEN` or `GH_TOKEN`
3. **Legacy**: `PDD_GITHUB_TOKEN`

**File Tracking & Gists:**

When using `--api`, PDD will:
1. Collect all relevant files (prompts, code, tests, configs, meta files).
2. Create a **private GitHub Gist** containing these files.
3. Link the Gist in the created issue.

This 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.

---

### Context Selection Flags

- `--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.
- `--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.
- Precedence for configuration is: CLI options > `.pddrc` context > environment variables > defaults. See Configuration for details.

## Auto-Update Control

PDD 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:

```bash
# Disable auto-updates
export PDD_AUTO_UPDATE=false

# Enable auto-updates (default behavior)
export PDD_AUTO_UPDATE=true
```

For persistent settings, add this environment variable to your shell's configuration file (e.g., `.bashrc` or `.zshrc`).

This is particularly useful in:
- Production environments where version stability is crucial
- CI/CD pipelines where consistent behavior is required
- Version-sensitive projects that require specific PDD versions

## AI Model Information

PDD uses a large language model to generate and manipulate code. The `--strength` and `--temperature` options allow you to control the model's output:

- 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 ELO rating), while lower values (closer to 0.0) select more cost-effective models.
- 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.
- 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.

When running in local mode, PDD uses LiteLLM to select and interact with language models based on a configuration file that includes:
- Input and output costs per million tokens
- ELO ratings for coding ability
- Required API key environment variables
- Structured output capability flags
- Reasoning capabilities (budget-based or effort-based)

## Output Cost Tracking

PDD 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.

### Usage

To enable cost tracking, use the `--output-cost` option with any command:

```
pdd --output-cost PATH_TO_CSV_FILE [COMMAND] [OPTIONS] [ARGS]...
```

The `PATH_TO_CSV_FILE` should be the desired location and filename for the CSV output.

### Cost Calculation and Presentation

PDD 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:

1. Model strength: Higher strength settings generally result in higher costs.
2. Input size: Larger inputs (e.g., longer prompts or code files) typically incur higher costs.
3. Operation complexity: Some operations (like `fix` and `crash` with multiple iterations) may be more costly than simpler operations.

The 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.

### CSV Output

The generated CSV file includes the following columns:
- timestamp: The date and time of the command execution
- model: The AI model used for the operation
- command: The PDD command that was executed
- 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.
- input_files: A list of input files involved in the operation
- output_files: A list of output files generated or modified by the operation
- 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 > 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.

This 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.

### Environment Variable

You can set a default location for the cost output CSV file using the environment variable:

- **`PDD_OUTPUT_COST_PATH`**: Default path for the cost tracking CSV file.

If 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.

### Cost Budgeting

For 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.

Example:
```
pdd [GLOBAL OPTIONS] fix --budget 5.0 [OTHER OPTIONS] [ARGS]...
```
This sets a maximum budget of $5.00 for the fix operation.

## Commands

Here are the main commands provided by PDD:

### 1. sync

**[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.

```bash
# Project-wide architecture sync (no argument)
pdd [GLOBAL OPTIONS] sync [OPTIONS]

# Single-module sync
pdd [GLOBAL OPTIONS] sync [OPTIONS] BASENAME

# Multi-module sync from a GitHub issue (requires API-key-backed LiteLLM)
pdd [GLOBAL OPTIONS] sync [OPTIONS] GITHUB_ISSUE_URL
```

Important: 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:

```
pdd --force sync BASENAME
```

Arguments:
- No argument: Scan `architecture.json` and sync all modules that need deterministic Tier 1 prompt-to-code updates.
- `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.
- `BASENAME`: The base name for the prompt file (e.g., "factorial_calculator" for "factorial_calculator_python.prompt")
- `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.

Options:
- `--max-attempts INT`: Maximum number of fix attempts in any iterative loop (default is 3)
- `--budget FLOAT`: Maximum total cost allowed for the entire sync process (default is $20.0)
- `--skip-verify`: Skip the functional verification step
- `--skip-tests`: Skip unit test generation and fixing
- `--target-coverage FLOAT`: Desired code coverage percentage (default is 90.0)
- `--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.
- `--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`.
- `--no-steer`: Disable interactive steering of sync operations.
- `--steer-timeout FLOAT`: Timeout in seconds for steering prompts (default: 8.0).
- `--durable`: Issue-sync only. Run each module in an isolated git worktree under `.pdd/worktrees/sync-issue--/` and checkpoint successful module output to a dedicated durable branch worktree under `.pdd/worktrees/durable-issue-/`. Default issue-sync behavior (shared parallel worktree) is unchanged unless this flag is passed.
- `--durable-branch TEXT`: Durable mode only. Override the durable checkpoint branch name. Default is `sync/issue-` derived from the GitHub issue. Refused if it resolves to `main`, `master`, or the repository default branch.
- `--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= module=`) and skips modules already checkpointed for the same issue, which is what makes a cloud rerun safely resume completed work after a partial failure.
- `--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.

**Durable Issue Sync** (`--durable`):

Standard 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= module=` 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/_*.json` is included in checkpoints; secrets, lock files, cost CSVs, `.pdd/worktrees/`, and `.pdd/agentic_sync_state.json` are not.

```bash
# Cloud-friendly issue sync: resumable across reruns
pdd --force sync --durable https://github.com/myorg/myrepo/issues/1328

# Rerun every module fresh on the same durable branch (ignores existing trailers)
pdd --force sync --durable --no-resume \
https://github.com/myorg/myrepo/issues/1328
```

The dedicated durable-branch worktree path is keyed on the issue number (`.pdd/worktrees/durable-issue-/`), not the branch name. A given issue's first durable run claims that path for whichever branch it picked (default `sync/issue-` 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-`) before re-invoking with the new `--durable-branch`. Different issue numbers do not collide.

**Real-time Progress Animation**:
The sync command provides live visual feedback showing:
- Current operation being executed (auto-deps, generate, example, crash, verify, test, fix, update)
- File status indicators with color coding:
- Green: File exists and up-to-date
- Yellow: File being processed
- Red: File has errors or missing
- Blue: File analysis in progress
- Running cost totals and time elapsed
- Progress through the workflow steps

**Language Detection**:
The 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:
- `factorial_calculator_python.prompt` → generates `factorial_calculator.py`
- `factorial_calculator_typescript.prompt` → generates `factorial_calculator.ts`
- `factorial_calculator_javascript.prompt` → generates `factorial_calculator.js`
- `src/models/user_Python.prompt` → generates `src/models/user.py`

If multiple development language prompt files exist for the same basename, sync will process all of them.

**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.

**Advanced Configuration Integration**:
- **Automatic Context Detection**: Detects project structure and applies appropriate settings from `.pddrc`
- **Configuration Hierarchy**: CLI options > .pddrc context > environment variables > defaults
- **Multi-language Support**: Automatically processes all language variants of a basename
- **Intelligent Path Resolution**: Uses sophisticated directory management for complex project structures
- **Architecture-Aware Outputs**: When `architecture.json` provides an explicit `filepath` for a prompt entry, sync uses that code output path instead of flattening to `.pddrc` defaults
- Context-specific settings include output paths, default language, model parameters, coverage targets, and budgets

**Workflow Logic**:

The sync command automatically detects what files exist and executes the appropriate workflow:

1. **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.
2. **generate**: Create or update the code module from the prompt. After generation an **architecture conformance gate** validates the output against both `architecture.json` and the prompt's `` block:
- Each declared symbol must exist in the generated code (architecture.json symbol-existence check).
- 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).
- **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).
- **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.
- **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.
- **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.
- 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 ` line.
3. **example**: Generate usage example if it doesn't exist or is outdated
4. **crash**: Fix any runtime errors to make code executable
5. **verify**: Run functional verification against prompt intent (unless --skip-verify)
6. **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)
7. **fix**: Resolve any bugs found by unit tests
8. **update**: Back-propagate any learnings to the prompt file

**One-Session Mode** (`--one-session`):

By 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.

One-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.

```bash
# Project-wide sync dry run
pdd sync --dry-run

# Single-module sync with one-session mode
pdd sync --one-session factorial_calculator

# Agentic sync (one-session is the default)
pdd sync https://github.com/myorg/myrepo/issues/100

# Disable one-session for agentic sync
pdd sync --no-one-session https://github.com/myorg/myrepo/issues/100
```

**Advanced Decision Making**:
- **Fingerprint-based Change Detection**: Uses content hashes and timestamps to precisely detect what changed
- **LLM-powered Conflict Resolution**: For complex scenarios with multiple file changes, uses AI to determine the best approach
- **Persistent State Tracking**: Maintains sync history and learns from previous operations
- **Smart Lock Management**: Prevents concurrent sync operations with automatic stale lock cleanup
- Detects which files already exist and are up-to-date
- Skips unnecessary steps (e.g., won't regenerate code if prompt hasn't changed)
- Uses git integration to detect changes and determine incremental vs full regeneration
- Accumulates tests over time rather than replacing them (in a single test file per target)
- Automatically handles dependencies between steps

**Robust State Management**:
- **Fingerprint Files**: Maintains `.pdd/meta/{basename}_{language}.json` with operation history
- **Run Reports**: Tracks test results, coverage, and execution status
- **Lock Management**: Prevents race conditions with file-descriptor based locking
- **Git Integration**: Leverages version control for change detection and rollback safety

**The `.pdd` Directory**:
PDD uses a `.pdd` directory in your project root to store various metadata and configuration files:
- `.pdd/meta/` - Contains fingerprint files, run reports, and sync logs
- `.pdd/locks/` - Stores lock files to prevent concurrent operations
- `.pdd/llm_model.csv` - Project-specific LLM model configuration (optional)
- `.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.

This directory should typically be added to version control (except for `.pdd/locks/` and `.pdd/worktrees/`), as it contains important project state information.

**Environment Variables**:
All existing PDD output path environment variables are respected, allowing the sync command to save files in the appropriate locations for your project structure.

**Sync State Analysis**:
The sync command maintains detailed decision-making logs which you can view using the `--dry-run` option:

```bash
# View current sync state analysis (non-blocking)
pdd sync --dry-run calculator

# View detailed LLM reasoning for complex scenarios
pdd --verbose sync --dry-run calculator
```

**Analysis Contents Include**:
- Current file state and fingerprint comparisons
- Real-time decision reasoning (heuristic-based vs LLM-powered analysis)
- Operation recommendations with confidence levels
- Estimated costs for recommended operations
- Lock status and potential conflicts
- State management details

The `--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.

Use `--verbose` with `--dry-run` to see detailed LLM reasoning for complex multi-file change scenarios and advanced state analysis.

**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.

Examples:
```bash
# Complete workflow with progress animation and intelligent decision-making
pdd --force sync factorial_calculator

# Advanced sync with higher budget, custom coverage, and full visual feedback
pdd --force sync --budget 15.0 --target-coverage 95.0 data_processor

# Quick sync with animation showing real-time status updates
pdd --force sync --skip-verify --budget 5.0 web_scraper

# Multi-language sync with fingerprint-based change detection
pdd --force sync multi_language_module

# View comprehensive sync analysis with decision analysis
pdd sync --dry-run factorial_calculator

# View detailed sync analysis with LLM reasoning for complex conflict resolution
pdd --verbose sync --dry-run factorial_calculator

# Monitor what sync would do without executing (with state analysis)
pdd sync --dry-run calculator

# Context-aware examples with automatic configuration detection
cd backend && pdd --force sync calculator # Uses backend context settings with animation
cd frontend && pdd --force sync dashboard # Uses frontend context with real-time feedback
pdd --context backend --force sync calculator # Explicit context override with visual progress
```

**Agentic Multi-Module Sync (GitHub Issue Mode)**:

When a GitHub issue URL is passed instead of a basename, sync enters agentic mode:
1. **Module Identification**: Fetches the issue content and uses an LLM to identify which modules need syncing
2. **Dependency Validation**: Validates architecture.json dependencies and applies corrections if needed
3. **Parallel Execution**: Dispatches parallel sync via `AsyncSyncRunner` with dependency-aware scheduling (max 4 concurrent workers)
4. **Live Progress**: Posts and updates a GitHub comment with real-time module sync status

```bash
# Sync modules identified from a GitHub issue (parallel, dependency-aware)
pdd sync https://github.com/myorg/myrepo/issues/100

# Extend the per-module timeout for a very large module
pdd sync --timeout-adder 600 https://github.com/myorg/myrepo/issues/100
```

Options (agentic mode):
- `--timeout-adder FLOAT`: Add seconds to the per-module timeout (default: 0.0).
- `--no-github-state`: Disable GitHub state persistence, use local-only

**Cross-Machine Resume**: Workflow state is stored in a hidden GitHub comment, enabling resume from any machine. Use `--no-github-state` to disable.

### 1a. sync-architecture

Sync `architecture.json` from prompt metadata tags (``, ``, and ``). 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.

```bash
# Preview architecture updates for all prompts
pdd sync-architecture --dry-run

# Update architecture.json from all prompt metadata tags
pdd sync-architecture

# Update architecture.json from specific prompt entries
pdd sync-architecture commands/maintenance_python.prompt
```

Arguments:
- No argument: Scan all prompt files known to the current project.
- `FILENAMES`: Optional prompt filenames as they appear in `architecture.json` or under the configured prompts directory.

Options:
- `--dry-run`: Report which architecture entries would change without writing `architecture.json`.

The 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.

> 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.

### 2. generate

Create 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.

```bash
# Basic usage
pdd [GLOBAL OPTIONS] generate [OPTIONS] PROMPT_FILE
```

Arguments:
- `PROMPT_FILE`: The filename of the prompt file used to generate the code.

Options:
- `--output LOCATION`: Specify where to save the generated code. Supports `${VAR}`/`$VAR` expansion from `-e/--env`. The default file name is `.`. If an environment variable `PDD_GENERATE_OUTPUT_PATH` is set, the file will be saved in that path unless overridden by this option.
- `--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.
- `--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`.
- `--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`.
- `--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.
- `--exclude-tests`: Do not automatically include test files found in the default tests directory.

**Parameter Variables (-e/--env)**:
Pass 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.

- Syntax: `-e KEY=VALUE` or `--env KEY=VALUE` (repeatable).
- Docker-style env fallback: `-e KEY` reads `VALUE` from the current process environment variable `KEY`.
- Scope: Applies to `generate`.
- Precedence: Values passed with `-e/--env` override same‑named OS environment variables during template expansion for this command.

**Templating**:
Prompt 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.

- In prompt content: `$VAR` and `${VAR}` are replaced only when `VAR` was provided.
- In output path: When using `--output`, PDD also expands `$VAR`/`${VAR}` using the same variable set.
- 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.

Examples:
```
# Basic parameterized generation (Python module)
pdd generate -e MODULE=orders --output 'src/${MODULE}.py' prompts/module_python.prompt

# Generate multiple files from the same prompt
pdd generate -e MODULE=orders --output 'src/${MODULE}.py' prompts/module_python.prompt
pdd generate -e MODULE=payments --output 'src/${MODULE}.py' prompts/module_python.prompt
pdd generate -e MODULE=customers --output 'src/${MODULE}.py' prompts/module_python.prompt

# Multiple variables
pdd generate -e MODULE=orders -e PACKAGE=core --output 'src/${PACKAGE}/${MODULE}.py' prompts/module_python.prompt

# Docker-style env fallback (reads MODULE from your shell env)
export MODULE=orders
pdd generate -e MODULE --output 'src/${MODULE}.py' prompts/module_python.prompt
```

Shell quoting options:
- Quote `KEY=VALUE` if the value contains spaces or shell-special characters: `-e "DISPLAY_NAME=Order Processor"`.
- PDD-side expansion (portable): prevent shell expansion and let PDD expand using `-e/--env` — e.g., `--output 'src/${MODULE}.py'`.
- 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.,
- `export MODULE=orders && pdd generate -e MODULE --output "src/$MODULE.py" prompts/module_python.prompt`
- Or inline for POSIX shells: `MODULE=orders pdd generate -e MODULE --output "src/$MODULE.py" prompts/module_python.prompt`
- Note: PowerShell/Windows shells differ; PDD-side expansion is more portable across shells.

**Git Integration**:
- When the command detects changes between the current prompt and its last committed version, it automatically considers incremental generation if the output file exists.
- 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.
- Full regeneration always happens for new files (when there's no existing output file to update) or when the existing output file is deleted.

**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.

Examples:
```
# Basic generation with automatic git-based change detection
# (incremental if output file exists, full generation if it doesn't)
pdd [GLOBAL OPTIONS] generate --output src/calculator.py calculator_python.prompt

# Force incremental patching (requires output file to exist)
pdd [GLOBAL OPTIONS] generate --incremental --output src/calculator.py calculator_python.prompt

# Force full regeneration (just delete the output file first)
rm src/calculator.py # Delete the file
pdd [GLOBAL OPTIONS] generate --output src/calculator.py calculator_python.prompt

# Specify a different original prompt (bypassing git detection)
pdd [GLOBAL OPTIONS] generate --output src/calculator.py --original-prompt old_calculator_python.prompt calculator_python.prompt
```

**Agentic Architecture Mode:**

When 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.

```bash
pdd generate https://github.com/owner/repo/issues/42
```

The 11-step workflow:

**Analysis & Generation (Steps 1-8):**
1. **Analyze PRD**: Extract features, tech stack, and requirements from the issue content
2. **Deep Analysis**: Feature decomposition, module boundaries, shared concerns
3. **Research**: Web search for tech stack documentation and best practices
4. **Design**: Module breakdown with dependency graph and priority ordering (auth modules are separated into dedicated concerns with low priority numbers)
5. **Research Dependencies**: Find relevant API docs and code examples per module
6. **Generate**: Produce complete `architecture.json` and scaffolding files
7. **Generate .pddrc**: Create project configuration with context-specific paths
8. **Generate Prompts**: Create prompt files for each module in `architecture.json`

**Validation (Steps 9-11):**
9. **Completeness Validation**: Verify all modules have prompts and dependencies
10. **Sync Validation**: Run `pdd sync --dry-run` on each module to catch prompt-discovery and output path issues, including architecture-driven nested paths
11. **Dependency Validation**: Preprocess prompts to verify `` tags resolve under the same rules used at runtime, and reject fabricated example-file include paths

Each validation step retries up to 3 times with automatic fixes before proceeding.

**Options:**
- `--skip-prompts`: Skip prompt file generation (steps 8-11), only generate `architecture.json` and `.pddrc`
- `--project-root `: 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.

**Project Root Detection:**

`pdd generate ` (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:

1. **Tier A (PDD-explicit)**: a directory containing `.pddrc` or a `.pdd/` directory.
2. **Tier B (PDD-conventional)**: a directory containing `sources/` plus PRD/spec markdown (`prd*.md`, `spec*.md`, or `*_prd.md`/`*_spec.md`).
3. **Tier C (git)**: a directory containing `.git`.

`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`.

A 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 ` 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.

Prerequisites:
- `gh` CLI must be installed and authenticated
- The issue must contain a PRD describing the project scope

**Workflow Resumption**: Re-running `pdd generate ` resumes from the last completed step. State is persisted to GitHub issue comments for cross-machine resume.

**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.

Example:
```bash
pdd generate https://github.com/myorg/myrepo/issues/42
# Generates: architecture.json, architecture_diagram.html, .pddrc, prompts/*.prompt

# Skip prompt generation (faster, just architecture)
pdd generate --skip-prompts https://github.com/myorg/myrepo/issues/42
# Generates: architecture.json, architecture_diagram.html, .pddrc
```

**Experimental Incremental PRD Mode (`--incremental --experimental-prd` with a PRD file or issue URL):**

After the initial architecture has been generated, `pdd generate --incremental --experimental-prd ` 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.

```bash
# Diff PRD vs last fingerprint, patch architecture.json + prompts
pdd generate --incremental --experimental-prd docs/prd.md

# Same, sourced from a GitHub issue
pdd generate --incremental --experimental-prd https://github.com/owner/repo/issues/42

# Preview without writing — dry-run is safe (no files modified)
pdd generate --incremental --experimental-prd --dry-run docs/prd.md

# Suppress GitHub issue status comments during agentic runs
pdd generate --incremental --experimental-prd --no-github-state docs/prd.md

# Patch a subproject architecture/prompts directory
pdd generate --incremental --experimental-prd --output-dir service docs/prd.md
```

This 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.

**Current limitations (this experimental mode is intentionally narrower than `pdd generate `):**

- **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 `` 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 && pdd sync`) because generated includes resolve there. Run `pdd sync` from the repo root only for root-level architectures.
- **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.
- **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.
- **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.

These are tracked as follow-ups under #859. The architecture-side propagation (patch validation, transactional commit with rollback, concurrent-modification guard, `` tag preservation, Requirements updates via `detect_change` + `change`) is fully implemented and live-verified.

#### Prompt Templates

Templates 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.

- Front matter (human/CLI):
- name, description, version, tags, language, output
- variables: schema for `-e/--env` (required/optional, type, examples)
- usage: copyable `pdd generate` commands
- discover (optional): CLI‑executed file discovery (root, patterns, exclude, caps)
- output_schema (optional): JSON shape used by the CLI for validation and by `pdd templates show`
- Prompt body (LLM):
- Includes to hydrate context: `${VAR}`, `${LIST}`
- Crisp instructions and an explicit output contract; no human usage notes or discovery logic

Quick examples (templates)

```
# Minimal (PRD required)
pdd generate -e PRD_FILE=docs/specs.md --output architecture.json \
pdd/templates/architecture/architecture_json.prompt

# With extra context
pdd generate -e PRD_FILE=docs/specs.md -e TECH_STACK_FILE=docs/tech_stack.md \
-e DOC_FILES='docs/ux.md,docs/components.md' \
-e INCLUDE_FILES='src/app.py,src/api.py,frontend/app/layout.tsx' \
--output architecture.json pdd/templates/architecture/architecture_json.prompt

# Multiple variants
pdd generate -e PRD_FILE=docs/specs.md -e APP_NAME=Shop --output apps/shop/architecture.json pdd/templates/architecture/architecture_json.prompt
pdd generate -e PRD_FILE=docs/specs.md -e APP_NAME=Admin --output apps/admin/architecture.json pdd/templates/architecture/architecture_json.prompt
pdd generate -e PRD_FILE=docs/specs.md -e APP_NAME=Public --output apps/public/architecture.json pdd/templates/architecture/architecture_json.prompt

# 4) Use variables in the output path
# 5) Use shell env fallback for convenience
export APP=shop
pdd generate -e APP -e PRD_FILE=docs/specs.md --output 'apps/${APP}/architecture.json' pdd/templates/architecture/architecture_json.prompt
```

Tips for authoring templates

- Put human guidance in YAML front matter (variables with examples, usage, notes); keep the prompt body model‑focused.
- Use ``/`` for curated context; prefer specs/configs over large code dumps.
- Parameterized includes: pass file paths via `-e`, e.g. `${PRD_FILE}`; the engine resolves includes after variable expansion.
- If your template outputs a specific filename, show example commands with `--output`.

Behavior notes

- Variable expansion only applies to variables explicitly passed via `-e/--env` (or via the env fallback with `-e KEY`). Other `$NAME` occurrences remain unchanged.
- `--output` also accepts `$VAR`/`${VAR}` from the same set of variables.
- 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.

Templates: Commands

- Front matter is parsed (not sent to the LLM) and powers:
- Variables schema and validation
- Usage examples (rendered by `pdd templates show`)
- Optional `discover` settings (executed by the CLI with caps)
- Optional `output_schema` for validation
- Commands:
- `pdd templates list [--json] [--filter tag=...]`
- `pdd templates show `
- `pdd templates copy --to prompts/`
- `pdd generate --template [-e KEY=VALUE...] [--output PATH]`

#### Built-In Templates

PDD 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).

Where built-ins live (packaged)

- Under the installed package at `pdd/templates//**/*.prompt` (plus optional README/index files). When installed from PyPI, these are included as package data.

Included starter templates

- `architecture/architecture_json.prompt`: Universal architecture generator (requires `-e PRD_FILE=...`; supports optional `TECH_STACK_FILE`, `DOC_FILES`, `INCLUDE_FILES`).

**LLM Toggle Functionality:**

All templates support the `llm` parameter to control whether LLM generation runs:

- **`llm=true`** (default): Full generation with LLM + post-processing
- **`llm=false`**: Skip LLM generation, run only post-processing

**Architecture JSON Template Features:**

The `architecture/architecture_json` template includes automatic **Mermaid diagram generation**:

- **Post-processing**: Automatically converts the generated JSON into an interactive HTML Mermaid diagram
- **Visualization**: Creates `architecture_diagram.html` with color-coded modules (frontend/backend/shared)
- **Interactive**: Hover tooltips show module details, dependencies, and descriptions
- **Self-contained**: HTML file works offline with embedded Mermaid library

**Example Commands:**

```bash
# Full generation (LLM + post-processing + Mermaid HTML)
pdd generate --template architecture/architecture_json \
-e PRD_FILE=docs/specs.md \
-e APP_NAME="MyApp" \
--output architecture.json
# Results in: architecture.json + architecture_diagram.html

# Post-processing only (skip LLM, generate HTML from existing JSON)
pdd generate --template architecture/architecture_json \
-e APP_NAME="MyApp" \
-e llm=false \
--output architecture.json
# Results in: architecture_diagram.html (from existing architecture.json)
```

**Context URLs (optional field):**

Architecture 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 `` tags in the Dependencies section, enabling the LLM to fetch relevant API documentation during code generation.

```json
{
"filename": "orders_api_Python.prompt",
"dependencies": ["models_Python.prompt"],
"context_urls": [
{"url": "https://fastapi.tiangolo.com/tutorial/first-steps/", "purpose": "FastAPI routing patterns"},
{"url": "https://docs.pydantic.dev/latest/concepts/models/", "purpose": "Pydantic model validation"}
],
...
}
```

The `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.

Front Matter (YAML) metadata

- Templates include YAML front matter with human-readable metadata:
- `name`, `description`, `version`, `tags`: docs and discovery
- `language`, `output`: defaults for `generate`
- `variables`: parameter schema for `-e/--env` (type, required, default)

Example (architecture template):

```
---
name: architecture/architecture_json
description: Unified architecture template for multiple stacks
version: 1.0.0
tags: [architecture, template, json]
language: json
output: architecture.json
variables:
TECH_STACK:
required: false
type: string
description: Target tech stack for interface shaping and conventions.
examples: [nextjs, python, fastapi, flask, django, node, go]
API_STYLE:
required: false
type: string
description: API style for backends.
examples: [rest, graphql]
APP_NAME:
required: false
type: string
description: Optional app name for context.
example: Shop
PRD_FILE:
required: true
type: path
description: Primary product requirements document (PRD) describing scope and goals.
example_paths: [PRD.md, docs/specs.md, docs/product/prd.md]
example_content: |
Title: Order Management MVP
Goals: Enable customers to create and track orders end-to-end.
Key Features:
- Create Order: id, user_id, items[], total, status
- View Order: details page with status timeline
- List Orders: filter by status, date, user
Non-Functional Requirements:
- P95 latency < 300ms for read endpoints
- Error rate < 0.1%
TECH_STACK_FILE:
required: false
type: path
description: Tech stack overview (languages, frameworks, infrastructure, and tools).
example_paths: [docs/tech_stack.md, docs/architecture/stack.md]
example_content: |
Backend: Python (FastAPI), Postgres (SQLAlchemy), PyTest
Frontend: Next.js (TypeScript), shadcn/ui, Tailwind CSS
API: REST
Auth: Firebase Auth (GitHub Device Flow), JWT for API
Infra: Vercel (frontend), Cloud Run (backend), Cloud SQL (Postgres)
Observability: OpenTelemetry traces, Cloud Logging
DOC_FILES:
required: false
type: list
description: Additional documentation files (comma/newline-separated).
example_paths: [docs/ux.md, docs/components.md]
example_content: |
Design overview, patterns and constraints
INCLUDE_FILES:
required: false
type: list
description: Specific source files to include (comma/newline-separated).
example_paths: [src/app.py, src/api.py, frontend/app/layout.tsx, frontend/app/page.tsx]
usage:
generate:
- name: Minimal (PRD only)
command: pdd generate -e PRD_FILE=docs/specs.md --output architecture.json pdd/templates/architecture/architecture_json.prompt
- name: With tech stack overview
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
discover:
enabled: false
max_per_pattern: 5
max_total: 10
---
```

Notes

- 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.

Template Variables (reference)

- Architecture (`architecture/architecture_json.prompt`)
- `PRD_FILE` (path, required): Primary spec/PRD file path
- `TECH_STACK_FILE` (path, optional): Tech stack overview file (includes API style; e.g., docs/tech_stack.md)
- `APP_NAME` (string, optional): App name for context
- `DOC_FILES` (list, optional): Comma/newline-separated list of additional doc paths
- `INCLUDE_FILES` (list, optional): Comma/newline-separated list of source files to include
- `SCAN_PATTERNS` (list, optional): Discovery patterns defined in front matter `discover` and executed by the CLI
- `SCAN_ROOT` (path, optional): Discovery root defined in front matter `discover`

Notes

- 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.

Copy-and-generate

- 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.
- Quick copy (Python one‑liner; run from your project root):

```
python - <<'PY'
from importlib.resources import files
import shutil, os

dst_dir = 'prompts/architecture'
src_dir = files('pdd').joinpath('templates/architecture')
os.makedirs(dst_dir, exist_ok=True)

for p in src_dir.rglob('*.prompt'):
shutil.copy(p, dst_dir)
print(f'Copied built-in templates from {src_dir} -> {dst_dir}')
PY

# Then generate from the copied prompt(s)
pdd generate --output architecture.json prompts/architecture/architecture_json.prompt
```

Unified template examples

```
# Frontend (Next.js) — interface.page.route and component props
pdd generate \
-e APP_NAME=Shop \
# (routes are inferred from PRD/tech stack/files)
-e PRD_FILE=docs/specs.md \
-e DOC_FILES='docs/ux.md,docs/components.md' \
-e TECH_STACK_FILE=docs/tech_stack.md \
# discovery, if needed, is configured in template YAML and executed by the CLI
--output architecture.json \
pdd/templates/architecture/architecture_json.prompt

# Backend (Python) — interface.module.functions or interface.api.endpoints
pdd generate \
-e PRD_FILE=docs/backend-spec.md \
-e TECH_STACK_FILE=docs/tech_stack.md \
-e INCLUDE_FILES='src/app.py,src/api.py,pyproject.toml' \
--output architecture.json \
pdd/templates/architecture/architecture_json.prompt
```

**Interface Schema**

- Core keys (every item):
- `reason`, `description`, `dependencies`, `priority`, `filename`, optional `tags`.
- Interface object (typed, include only what applies):
- `type`: `component` | `page` | `module` | `api` | `graphql` | `cli` | `job` | `message` | `config`
- `component`: `props[]`, optional `emits[]`, `context[]`
- `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`
- `module`: `functions[]` with `name`, `signature`, optional `returns`, `errors`, `sideEffects`
- `api`: `endpoints[]` with `method`, `path`, optional `auth`, `requestSchema`, `responseSchema`, `errors`
- `graphql`: optional `sdl`, or `operations` with `queries[]`, `mutations[]`, `subscriptions[]`
- `cli`: `commands[]` with `name`, optional `args[]`, `flags[]`, `exitCodes[]`; optional `io` (`stdin`, `stdout`)
- `job`: `trigger` (cron/event), optional `inputs[]`, `outputs[]`, `retryPolicy`
- `message`: `topics[]` with `name`, `direction` (`publish`|`subscribe`), optional `schema`, `qos`
- `config`: `keys[]` with `name`, `type`, optional `default`, `required`, `source` (`env`|`file`|`secret`)
- Optional: `version`, `stability` (`experimental`|`stable`)

Examples:

```json
{
"reason": "Top-level products page",
"description": "...",
"dependencies": ["layout_tsx.prompt"],
"priority": 1,
"filename": "page_tsx.prompt",
"tags": ["frontend","nextjs"],
"interface": {
"type": "page",
"page": {"route": "/products", "params": [{"name":"id","type":"string"}]},
"component": {"props": [{"name":"initialProducts","type":"Product[]","required":true}]}
}
}
```

```json
{
"reason": "Order service module",
"description": "...",
"dependencies": ["db_python.prompt"],
"priority": 1,
"filename": "orders_python.prompt",
"tags": ["backend","python"],
"interface": {
"type": "module",
"module": {
"functions": [
{"name": "load_orders", "signature": "def load_orders(user_id: str) -> list[Order]"},
{"name": "create_order", "signature": "def create_order(dto: OrderIn) -> Order"}
]
}
}
}
```

```json
{
"reason": "Orders HTTP API",
"description": "...",
"dependencies": ["orders_python.prompt"],
"priority": 2,
"filename": "api_python.prompt",
"tags": ["backend","api"],
"interface": {
"type": "api",
"api": {
"endpoints": [
{
"method": "GET",
"path": "/orders/{id}",
"auth": "bearer",
"responseSchema": {"type":"object","properties":{"id":{"type":"string"}}},
"errors": ["404 Not Found","401 Unauthorized"]
}
]
}
}
}
```

Notes and recommendations

- Treat copied templates as a starting point; edit them to match your stack and conventions.
- Keep templates under version control along with your code to preserve the prompt‑as‑source‑of‑truth model.
- If you maintain your own template set, store them under `prompts//...` and compose with `` to maximize reuse.

Templates: additional UX

- Goals:
- Discover, inspect, and vendor templates without manual file paths.
- Validate required variables and surface defaults from template metadata.
- Support a search order so project templates can override packaged ones.

- Commands:
- `pdd templates list [--json] [--filter tag=frontend]` to discover templates
- `pdd templates show [--raw]` to view metadata and variables
- `pdd templates copy --to prompts/` to vendor into your repo
- `pdd generate --template [-e KEY=VALUE...] [--output PATH]`

- Example usage:
```
# Discover and inspect
pdd templates list --filter tag=frontend
pdd templates show frontend/nextjs_architecture_json

# Vendor and customize
pdd templates copy frontend/nextjs_architecture_json --to prompts/frontend/

# Generate without specifying a file path
pdd generate --template frontend/nextjs_architecture_json \
-e APP_NAME=Shop \
# routes are inferred from PRD/tech stack/files
--output architecture.json
```

- Search order:
- Project: `./prompts/**` (allows team overrides)
- `.pddrc` paths: any configured `templates.paths`
- Packaged: `pdd/templates/**` (built‑ins)
- Optional: `$PDD_PATH/prompts/**` (org‑level packs)

- Template front matter:
- YAML metadata at the top of `.prompt` files to declare `name`, `description`, `tags`, `version`, `language`, default `output`, and `variables` (with `required`, `default`, `type` such as `string` or `json`).
- Variable precedence: values from `-e/--env` override front‑matter defaults; unknowns are validated and surfaced to the user.
- Output path precedence: `--output` (CLI) > `output:` (front matter) > `generate_output_path` (`.pddrc`). If front‑matter `output:` cannot be resolved, the CLI emits a yellow warning and falls back to the default path instead of failing silently.
- Example:
```
---
name: frontend/nextjs_architecture_json
description: Generate a Next.js architecture.json file from app metadata
tags: [frontend, nextjs, json]
version: 1.0.0
language: json
output: architecture.json
variables:
APP_NAME: { required: true }
ROUTES: { type: json, default: [] }
---
...prompt body...
```

### 3. example

Create a compact example demonstrating how to use functionality defined in a prompt. Similar to a header file or API documentation, this produces minimal, token-efficient code that shows the interface without implementation details.

```
pdd [GLOBAL OPTIONS] example [OPTIONS] PROMPT_FILE CODE_FILE
```

Arguments:
- `PROMPT_FILE`: The filename of the prompt file that generated the code.
- `CODE_FILE`: The filename of the existing code file.

Options:
- `--output LOCATION`: Specify where to save the generated example code. The default file name is `_example.`. If an environment variable `PDD_EXAMPLE_OUTPUT_PATH` is set, the file will be saved in that path unless overridden by this option.
- `--format FORMAT`: Output format for the generated example (default: `code`). Valid values:
- `code`: Uses the language-specific file extension (e.g., `.py` for Python, `.js` for JavaScript) when no suffix is supplied on `--output`. If `--output` includes a suffix (`.yml`, `.m`, `.txt`, …), that suffix is honored verbatim — pass `--format md` to force a `.md` extension.
- `md`: Generates markdown content; the resolved output path will always end in lowercase `.md`, replacing any other suffix (including upper-case variants like `.MD`) on `--output`.
When the wrapper rewrites an explicit `--output` path (`--format md` with a non-`.md` suffix, or a bare name under `--format code`) and the rewritten file already exists, you will be prompted to confirm the overwrite unless `--force` is set.

Where used:
- Dependency references: Examples serve as lightweight (token efficient) interface references for other prompts and can be included as dependencies of a generate target.
- Sanity checks: The example program is typically used as the runnable program for `crash` and `verify`, providing a quick end-to-end sanity check that the generated code runs and behaves as intended.
- Auto-deps integration: The `auto-deps` command can scan example files (e.g., `examples/**/*.py`) and insert relevant references into prompts. Based on each example’s content (imports, API usage, filenames), it identifies useful development units to include as dependencies.
- Metadata finalization: A successful `pdd example` updates the affected module's fingerprint and clears its stale `.pdd/meta/__run.json` runtime-verification report, so a regenerated example never leaves runtime state describing the pre-mutation output.

**When to use**: Choose this command when creating reusable references that other prompts can efficiently import. This produces token-efficient examples that are easier to reuse across multiple prompts compared to including full implementations.

Example:
```
pdd [GLOBAL OPTIONS] example --output examples/factorial_calculator_example.py factorial_calculator_python.prompt src/factorial_calculator.py
```

### 4. test

Generate or enhance unit tests for a given code file and its corresponding prompt file. Also supports **agentic mode** for generating UI tests from GitHub issues.

#### Agentic Mode (UI Test Generation)

Generate UI tests from a GitHub issue. The issue describes what needs to be tested (a webpage, CLI, or desktop app), and an agentic workflow analyzes the target, creates a test plan, and generates comprehensive UI tests.

```
pdd [GLOBAL OPTIONS] test
```

**How it works (18-step workflow with GitHub comments):**

1. **Duplicate check** - Search for existing issues describing the same test requirements. If found, merge content and close the duplicate.

2. **Documentation check** - Review repo documentation and codebase to understand what needs to be tested. Identifies OpenAPI/Swagger specs if present.

3. **Analyze & clarify** - Determine if enough information exists in the issue to create tests. Posts comment requesting clarification if needed.

4. **Detect frontend** - Identify the test type: web UI, CLI, desktop app, or API. Determines the appropriate testing framework.

5. **Create test plan** - Design a comprehensive test plan and verify it's achievable.

5b. **Enhance test plan** - Add contract validation test cases (from OpenAPI/Swagger specs) and accessibility test cases (for web apps using `@axe-core/playwright` at WCAG 2.1 AA level).

6. **Assess coverage** *(web only, requires `playwright-cli`)* - Compare requirements against the enhanced test plan to identify gaps needing manual testing.

7. **Create manual testing checklist** *(web only)* - Generate a checklist using three strategies: page-by-page exhaustive testing, user-story walkthroughs, and accessibility spot-checks.

8. **Manual testing execution** *(web only)* - Execute checklist items via `playwright-cli` commands. Runs serially in CLI mode or in parallel via Cloud Batch when `PDD_CLOUD_RUN=true`.

9. **Create regression tests** *(web only)* - Generate automated tests that reproduce bugs found in Step 8.

10. **Validate regression tests** *(web only)* - Confirm regression tests fail against current code (proving bugs exist).

11. **Loop check** *(web only)* - Check checklist completion. Loops back to Step 8 if items remain (max 3 iterations).

12. **Generate tests** - Create tests in a worktree from the enhanced plan, including behavioral, contract, and accessibility tests.

13. **Run tests** - Execute all generated tests against the target.

14. **Fix & iterate** - Fix any failing tests and re-run until they pass.

15. **Validate tests against plan** - Cross-reference the enhanced pla