pdd-cli 0.0.90__py3-none-any.whl → 0.0.118__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. pdd/__init__.py +38 -6
  2. pdd/agentic_bug.py +323 -0
  3. pdd/agentic_bug_orchestrator.py +497 -0
  4. pdd/agentic_change.py +231 -0
  5. pdd/agentic_change_orchestrator.py +526 -0
  6. pdd/agentic_common.py +521 -786
  7. pdd/agentic_e2e_fix.py +319 -0
  8. pdd/agentic_e2e_fix_orchestrator.py +426 -0
  9. pdd/agentic_fix.py +118 -3
  10. pdd/agentic_update.py +25 -8
  11. pdd/architecture_sync.py +565 -0
  12. pdd/auth_service.py +210 -0
  13. pdd/auto_deps_main.py +63 -53
  14. pdd/auto_include.py +185 -3
  15. pdd/auto_update.py +125 -47
  16. pdd/bug_main.py +195 -23
  17. pdd/cmd_test_main.py +345 -197
  18. pdd/code_generator.py +4 -2
  19. pdd/code_generator_main.py +118 -32
  20. pdd/commands/__init__.py +6 -0
  21. pdd/commands/analysis.py +87 -29
  22. pdd/commands/auth.py +309 -0
  23. pdd/commands/connect.py +290 -0
  24. pdd/commands/fix.py +136 -113
  25. pdd/commands/maintenance.py +3 -2
  26. pdd/commands/misc.py +8 -0
  27. pdd/commands/modify.py +190 -164
  28. pdd/commands/sessions.py +284 -0
  29. pdd/construct_paths.py +334 -32
  30. pdd/context_generator_main.py +167 -170
  31. pdd/continue_generation.py +6 -3
  32. pdd/core/__init__.py +33 -0
  33. pdd/core/cli.py +27 -3
  34. pdd/core/cloud.py +237 -0
  35. pdd/core/errors.py +4 -0
  36. pdd/core/remote_session.py +61 -0
  37. pdd/crash_main.py +219 -23
  38. pdd/data/llm_model.csv +4 -4
  39. pdd/docs/prompting_guide.md +864 -0
  40. pdd/docs/whitepaper_with_benchmarks/data_and_functions/benchmark_analysis.py +495 -0
  41. pdd/docs/whitepaper_with_benchmarks/data_and_functions/creation_compare.py +528 -0
  42. pdd/fix_code_loop.py +208 -34
  43. pdd/fix_code_module_errors.py +6 -2
  44. pdd/fix_error_loop.py +291 -38
  45. pdd/fix_main.py +204 -4
  46. pdd/fix_verification_errors_loop.py +235 -26
  47. pdd/fix_verification_main.py +269 -83
  48. pdd/frontend/dist/assets/index-B5DZHykP.css +1 -0
  49. pdd/frontend/dist/assets/index-DQ3wkeQ2.js +449 -0
  50. pdd/frontend/dist/index.html +376 -0
  51. pdd/frontend/dist/logo.svg +33 -0
  52. pdd/generate_output_paths.py +46 -5
  53. pdd/generate_test.py +212 -151
  54. pdd/get_comment.py +19 -44
  55. pdd/get_extension.py +8 -9
  56. pdd/get_jwt_token.py +309 -20
  57. pdd/get_language.py +8 -7
  58. pdd/get_run_command.py +7 -5
  59. pdd/insert_includes.py +2 -1
  60. pdd/llm_invoke.py +459 -95
  61. pdd/load_prompt_template.py +15 -34
  62. pdd/path_resolution.py +140 -0
  63. pdd/postprocess.py +4 -1
  64. pdd/preprocess.py +68 -12
  65. pdd/preprocess_main.py +33 -1
  66. pdd/prompts/agentic_bug_step10_pr_LLM.prompt +182 -0
  67. pdd/prompts/agentic_bug_step1_duplicate_LLM.prompt +73 -0
  68. pdd/prompts/agentic_bug_step2_docs_LLM.prompt +129 -0
  69. pdd/prompts/agentic_bug_step3_triage_LLM.prompt +95 -0
  70. pdd/prompts/agentic_bug_step4_reproduce_LLM.prompt +97 -0
  71. pdd/prompts/agentic_bug_step5_root_cause_LLM.prompt +123 -0
  72. pdd/prompts/agentic_bug_step6_test_plan_LLM.prompt +107 -0
  73. pdd/prompts/agentic_bug_step7_generate_LLM.prompt +172 -0
  74. pdd/prompts/agentic_bug_step8_verify_LLM.prompt +119 -0
  75. pdd/prompts/agentic_bug_step9_e2e_test_LLM.prompt +289 -0
  76. pdd/prompts/agentic_change_step10_identify_issues_LLM.prompt +1006 -0
  77. pdd/prompts/agentic_change_step11_fix_issues_LLM.prompt +984 -0
  78. pdd/prompts/agentic_change_step12_create_pr_LLM.prompt +131 -0
  79. pdd/prompts/agentic_change_step1_duplicate_LLM.prompt +73 -0
  80. pdd/prompts/agentic_change_step2_docs_LLM.prompt +101 -0
  81. pdd/prompts/agentic_change_step3_research_LLM.prompt +126 -0
  82. pdd/prompts/agentic_change_step4_clarify_LLM.prompt +164 -0
  83. pdd/prompts/agentic_change_step5_docs_change_LLM.prompt +981 -0
  84. pdd/prompts/agentic_change_step6_devunits_LLM.prompt +1005 -0
  85. pdd/prompts/agentic_change_step7_architecture_LLM.prompt +1044 -0
  86. pdd/prompts/agentic_change_step8_analyze_LLM.prompt +1027 -0
  87. pdd/prompts/agentic_change_step9_implement_LLM.prompt +1077 -0
  88. pdd/prompts/agentic_e2e_fix_step1_unit_tests_LLM.prompt +90 -0
  89. pdd/prompts/agentic_e2e_fix_step2_e2e_tests_LLM.prompt +91 -0
  90. pdd/prompts/agentic_e2e_fix_step3_root_cause_LLM.prompt +89 -0
  91. pdd/prompts/agentic_e2e_fix_step4_fix_e2e_tests_LLM.prompt +96 -0
  92. pdd/prompts/agentic_e2e_fix_step5_identify_devunits_LLM.prompt +91 -0
  93. pdd/prompts/agentic_e2e_fix_step6_create_unit_tests_LLM.prompt +106 -0
  94. pdd/prompts/agentic_e2e_fix_step7_verify_tests_LLM.prompt +116 -0
  95. pdd/prompts/agentic_e2e_fix_step8_run_pdd_fix_LLM.prompt +120 -0
  96. pdd/prompts/agentic_e2e_fix_step9_verify_all_LLM.prompt +146 -0
  97. pdd/prompts/agentic_fix_primary_LLM.prompt +2 -2
  98. pdd/prompts/agentic_update_LLM.prompt +192 -338
  99. pdd/prompts/auto_include_LLM.prompt +22 -0
  100. pdd/prompts/change_LLM.prompt +3093 -1
  101. pdd/prompts/detect_change_LLM.prompt +571 -14
  102. pdd/prompts/fix_code_module_errors_LLM.prompt +8 -0
  103. pdd/prompts/fix_errors_from_unit_tests_LLM.prompt +1 -0
  104. pdd/prompts/generate_test_LLM.prompt +20 -1
  105. pdd/prompts/generate_test_from_example_LLM.prompt +115 -0
  106. pdd/prompts/insert_includes_LLM.prompt +262 -252
  107. pdd/prompts/prompt_code_diff_LLM.prompt +119 -0
  108. pdd/prompts/prompt_diff_LLM.prompt +82 -0
  109. pdd/remote_session.py +876 -0
  110. pdd/server/__init__.py +52 -0
  111. pdd/server/app.py +335 -0
  112. pdd/server/click_executor.py +587 -0
  113. pdd/server/executor.py +338 -0
  114. pdd/server/jobs.py +661 -0
  115. pdd/server/models.py +241 -0
  116. pdd/server/routes/__init__.py +31 -0
  117. pdd/server/routes/architecture.py +451 -0
  118. pdd/server/routes/auth.py +364 -0
  119. pdd/server/routes/commands.py +929 -0
  120. pdd/server/routes/config.py +42 -0
  121. pdd/server/routes/files.py +603 -0
  122. pdd/server/routes/prompts.py +1322 -0
  123. pdd/server/routes/websocket.py +473 -0
  124. pdd/server/security.py +243 -0
  125. pdd/server/terminal_spawner.py +209 -0
  126. pdd/server/token_counter.py +222 -0
  127. pdd/summarize_directory.py +236 -237
  128. pdd/sync_animation.py +8 -4
  129. pdd/sync_determine_operation.py +329 -47
  130. pdd/sync_main.py +272 -28
  131. pdd/sync_orchestration.py +136 -75
  132. pdd/template_expander.py +161 -0
  133. pdd/templates/architecture/architecture_json.prompt +41 -46
  134. pdd/trace.py +1 -1
  135. pdd/track_cost.py +0 -13
  136. pdd/unfinished_prompt.py +2 -1
  137. pdd/update_main.py +23 -5
  138. {pdd_cli-0.0.90.dist-info → pdd_cli-0.0.118.dist-info}/METADATA +15 -10
  139. pdd_cli-0.0.118.dist-info/RECORD +227 -0
  140. pdd_cli-0.0.90.dist-info/RECORD +0 -153
  141. {pdd_cli-0.0.90.dist-info → pdd_cli-0.0.118.dist-info}/WHEEL +0 -0
  142. {pdd_cli-0.0.90.dist-info → pdd_cli-0.0.118.dist-info}/entry_points.txt +0 -0
  143. {pdd_cli-0.0.90.dist-info → pdd_cli-0.0.118.dist-info}/licenses/LICENSE +0 -0
  144. {pdd_cli-0.0.90.dist-info → pdd_cli-0.0.118.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,864 @@
1
+ # Prompt‑Driven Development Prompting Guide
2
+
3
+ This guide shows how to write effective prompts for Prompt‑Driven Development (PDD). It distills best practices from the PDD whitepaper, the PDD doctrine, and working patterns in this repo. It also contrasts PDD prompts with interactive agentic coding tools (e.g., Claude Code, Cursor) where prompts act as ad‑hoc patches instead of the source of truth.
4
+
5
+ References: pdd/docs/whitepaper.md, pdd/docs/prompt-driven-development-doctrine.md, README.md (repo structure, conventions), [Effective Context Engineering](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents), [Anthropic Prompt Engineering Overview](https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/overview).
6
+
7
+ ---
8
+
9
+ ## Quickstart: PDD in 5 Minutes
10
+
11
+ If you are new to Prompt-Driven Development (PDD), follow this recipe:
12
+
13
+ 1. **Think "One Prompt = One Module":** Don't try to generate the whole app at once. Focus on one file (e.g., `user_service.py`).
14
+ 2. **Use a Template:** Start with a clear structure: Role, Requirements, Dependencies, Instructions.
15
+ 3. **Explicitly Include Context:** Use `<include>path/to/file</include>` to give the model *only* what it needs (e.g., a shared preamble or a dependency interface). This is a **PDD directive**, not just XML.
16
+ 4. **Regenerate, Don't Patch:** If the code is wrong, fix it using `pdd fix`. This updates the system's memory so the next `pdd generate` is grounded in the correct solution.
17
+ 5. **Verify:** Run the generated code/tests.
18
+
19
+ *Tip: Treat your prompt like source code. It is the single source of truth.*
20
+
21
+ *For the conceptual foundation of why this works, see [The Mold Paradigm](prompt-driven-development-doctrine.md#the-mold-paradigm) in the doctrine.*
22
+
23
+ ---
24
+
25
+ ## Glossary
26
+
27
+ - **Context Engineering:** The art of curating exactly what information (code, docs, examples) fits into the LLM's limited "working memory" (context window) to get the best result.
28
+ - **Shared Preamble:** A standard text file (e.g., `project_preamble.prompt`) included in every prompt to enforce common rules like coding style, forbidden libraries, and formatting.
29
+ - **PDD Directive:** Special tags like `<include>` or `<shell>` that the PDD tool processes *before* sending the text to the AI. The AI sees the *result* (the file content), not the tag.
30
+ - **Source of Truth:** The definitive record. In PDD, the **Prompt** is the source of truth; the code is just a temporary artifact generated from it.
31
+ - **Grounding (Few-Shot History):** The process where the PDD system automatically uses successful past pairs of (Prompt, Code) as "few-shot" examples during generation. This ensures that regenerated code adheres to the established style and logic of the previous version, preventing the model from hallucinating a completely different implementation.
32
+ - **Drift:** When the generated code slowly diverges from the prompt's intent over time, or when manual edits to code make it inconsistent with the prompt.
33
+
34
+ ---
35
+
36
+ ## Why PDD Prompts (Not Patches)
37
+
38
+ - Prompts are the source of truth; code is a generated artifact. Update the prompt and regenerate instead of patching code piecemeal.
39
+ - Regeneration preserves conceptual integrity and reduces long‑term maintenance cost (see pdd/docs/whitepaper.md).
40
+ - Prompts consolidate intent, constraints, dependencies, and examples into one place so the model can enforce them.
41
+ - Tests accumulate across regenerations and act as a regression net; prompts and tests stay in sync.
42
+
43
+ Contrast with interactive patching (Claude Code, Cursor): prompts are ephemeral instructions for local diffs. They are great for short, local fixes, but tend to drift from original intent as context is implicit and often lost. In PDD, prompts are versioned, explicit, and designed for batch, reproducible generation.
44
+
45
+ For a deeper exploration of why this paradigm shift matters—and an analogy to manufacturing's wood‑to‑plastic transition—see [The Mold Paradigm](prompt-driven-development-doctrine.md#the-mold-paradigm) in the doctrine.
46
+
47
+ ---
48
+
49
+ ## The PDD Mental Model
50
+
51
+ - One prompt typically maps to one code file or narrowly scoped module.
52
+ - You explicitly curate the context to place in the model’s window (don’t “dump the repo”).
53
+ - Change behavior by editing the prompt; re‑generate the file; run crash/verify/test/fix; then update the prompt with learnings.
54
+ - Keep the “dev unit” synchronized: prompt + generated code + minimal runnable example + tests.
55
+
56
+ Key principles: everything is explicit, prompts are the programming language, and you regenerate rather than patch.
57
+
58
+ Dev Unit (Prompt with Code, Example, Test):
59
+
60
+ ```mermaid
61
+ flowchart TB
62
+ P[Prompt]
63
+ C[Code]
64
+ E[Example]
65
+ T[Tests]
66
+
67
+ P --> C
68
+ P --> E
69
+ P --> T
70
+ ```
71
+
72
+ Notes:
73
+ - The prompt defines intent. Code, example, and tests are generated artifacts.
74
+ - Regenerate rather than patch; keep tests accumulating over time.
75
+
76
+ ---
77
+
78
+ <a name="automated-grounding"></a>
79
+ ## Automated Grounding (PDD Cloud)
80
+
81
+ Unlike standard LLM interactions where every request is a blank slate, PDD Cloud uses **Automated Grounding** to prevent "implementation drift."
82
+
83
+ ### How It Works
84
+
85
+ When you run `pdd generate`, the system:
86
+ 1. Embeds your prompt into a vector
87
+ 2. Searches for similar prompts in the cloud database (cosine similarity)
88
+ 3. Auto-injects the closest (prompt, code) pair as a few-shot example
89
+
90
+ **This is automatic.** You don't configure it. As you edit your prompt:
91
+ - The embedding changes
92
+ - Different examples may be retrieved
93
+ - Generation naturally adapts to your prompt's content
94
+
95
+ On first generation: Similar existing modules in your project provide grounding.
96
+ On re-generation: Your prior successful generation is typically the closest match.
97
+
98
+ ### Why This Matters for Prompt Writing
99
+
100
+ - **Your prompt wording affects grounding.** Similar prompts retrieve similar examples.
101
+ - **Implementation patterns are handled automatically.** Grounding provides structural consistency from similar modules (class vs functional, helper patterns, etc.).
102
+ - **Prompts can be minimal.** Focus on requirements; grounding handles implementation patterns.
103
+
104
+ *Note: This is distinct from "Examples as Interfaces" (which teach how to **use** a dependency). Grounding teaches the model how to **write** the current module.*
105
+
106
+ > **Local users (no cloud):** Without grounding, prompts must be more detailed—include structural guidance and explicit examples via `<include>`. Use a shared preamble for coding style. The minimal prompt guidance in this document assumes cloud access.
107
+
108
+ ---
109
+
110
+ ## Grounding Overrides: Pin & Exclude (PDD Cloud)
111
+
112
+ For users with PDD Cloud access, you can override automatic grounding using XML tags:
113
+
114
+ **`<pin>module_name</pin>`** — Force a specific example to always be included
115
+ - Use case: Ensure a critical module always follows a "golden" pattern
116
+ - Use case: Bootstrap a new module with a specific style
117
+
118
+ **`<exclude>module_name</exclude>`** — Block a specific example(s) from being retrieved
119
+ - Use case: Escape an old pattern that's pulling generation in the wrong direction
120
+ - Use case: Intentionally break from established patterns for a redesign
121
+
122
+ These tags are processed by the preprocessor (like `<include>`) and removed before the LLM sees the prompt.
123
+
124
+ **Most prompts don't need these.** Automatic grounding works well for:
125
+ - Standard modules with similar existing examples
126
+ - Re-generations of established modules
127
+ - Modules following common project patterns
128
+
129
+ ---
130
+
131
+ ## Anatomy of a Good PDD Prompt
132
+
133
+ A well-designed prompt contains **only what can't be handled elsewhere**. With cloud grounding and accumulated tests, prompts can be minimal.
134
+
135
+ ### Required Sections
136
+
137
+ 1. **Role and scope** (1-2 sentences): What this module does
138
+ 2. **Requirements** (5-10 items): Functional and non-functional specs
139
+ 3. **Dependencies** (via `<include>`): Only external or critical interfaces
140
+
141
+ ### Optional Sections
142
+
143
+ 4. **Instructions**: Only if default behavior needs overriding
144
+ 5. **Deliverables**: Only if non-obvious
145
+
146
+ ### What NOT to Include
147
+
148
+ - **Coding style** (naming, formatting, imports) → Handled by shared preamble
149
+ - **Implementation patterns** (class structure, helpers) → Handled by grounding
150
+ - **Every edge case** → Handled by accumulated tests
151
+ - **Implementation steps** → Let the LLM decide (unless critical)
152
+
153
+ ### Target Size: Prompt-to-Code Ratio
154
+
155
+ Aim for **10-30%** of your expected code size:
156
+
157
+ | Ratio | Meaning |
158
+ |-------|---------|
159
+ | **< 10%** | Too vague—missing contracts, error handling, or key constraints |
160
+ | **10-30%** | Just right—requirements and contracts without implementation details |
161
+ | **> 50%** | Too detailed—prompt is doing preamble's or grounding's job |
162
+
163
+ If your prompt exceeds 30%, ask: Am I specifying things that preamble, grounding, or tests should handle?
164
+
165
+ **Note:** Tests are generated from the module prompt (via Requirements), so explicit Testing sections are unnecessary—well-written Requirements are inherently testable. Use `context/test.prompt` for project-wide test guidance.
166
+
167
+ See pdd/pdd/templates/generic/generate_prompt.prompt for a concrete scaffold.
168
+
169
+ ---
170
+
171
+ ## Prompt Syntax Essentials
172
+
173
+ These patterns are used across prompts in this repo:
174
+
175
+ - Preamble and role: start with a concise, authoritative description of the task and audience (e.g., “You are an expert Python engineer…”).
176
+ - Includes for context: bring only what the model needs.
177
+ - Single include: `<include>path/to/file</include>`. **Note:** This is a PDD directive, not standard XML. The PDD tool replaces this tag with the actual file content *before* the LLM sees it. (Handles both text and images).
178
+ - Multiple: `<include-many>path1, path2, …</include-many>`
179
+ - Grouping: wrap includes in a semantic tag to name the dependency or file they represent, for example:
180
+ ```xml
181
+ <render_js>
182
+ <include>src/render.js</include>
183
+ </render_js>
184
+ ```
185
+ - When including larger files inline for clarity, wrap with opening/closing tags named after the file, e.g. `<render.js>…</render.js>`.
186
+ - Note: `<include>`, `<include-many>`, `<shell>`, and `<web>` inside fenced code blocks (``` or ~~~) or inline backticks are treated as literal text.
187
+ - Inputs/outputs: state them explicitly (names, types, shapes). Prompts should define Inputs/Outputs and steps clearly.
188
+ - Steps & Chain of Thought: Outline a short, deterministic plan. For complex logical tasks, explicitly instruct the model to "Analyze the requirements and think step-by-step before writing code." This improves accuracy on difficult reasoning problems.
189
+ - Constraints: specify style, performance targets, security, and error handling.
190
+ - Environment: reference required env vars (e.g., `PDD_PATH`) when reading data files.
191
+
192
+ Tip: Prefer small, named sections using XML‑style tags to make context scannable and deterministic.
193
+
194
+ ### Special XML Tags: pdd, shell, web
195
+
196
+ The PDD preprocessor supports additional XML‑style tags to keep prompts clean, reproducible, and self‑contained. Processing order (per spec) is: `pdd` → `include`/`include-many` → `shell` → `web`. When `recursive=True`, `<shell>` and `<web>` are deferred until a non‑recursive pass.
197
+
198
+ - `<pdd>…</pdd>`
199
+ - Purpose: human‑only comment. Removed entirely during preprocessing.
200
+ - Use: inline rationale or notes that should not reach the model.
201
+ - Example: `Before step X <pdd>explain why we do this here</pdd>`
202
+
203
+ - `<shell>…</shell>`
204
+ - Purpose: run a shell command and inline stdout at that position.
205
+ - Behavior: executes during non‑recursive preprocessing; on non‑zero exit, inserts a bracketed error with the exit code instead of failing the pipeline.
206
+ - Example: `<shell>git config --get user.name</shell>`
207
+
208
+ - `<web>URL</web>`
209
+ - Purpose: fetch the page (via Firecrawl) and inline the markdown content.
210
+ - Behavior: executes during non‑recursive preprocessing; on failure, inserts a bracketed error note.
211
+ - Example: `<web>https://docs.litellm.ai/docs/completion/json_mode</web>`
212
+
213
+ > ⚠️ **Warning: Non-Deterministic Tags**
214
+ >
215
+ > `<shell>` and `<web>` introduce **non-determinism**:
216
+ > - `<shell>` output varies by environment (different machines, different results)
217
+ > - `<web>` content changes over time (same URL, different content)
218
+ >
219
+ > **Impact:** Same prompt file → different generations on different machines/times
220
+ >
221
+ > **Prefer instead:** Capture output to a static file, then `<include>` that file. This ensures reproducible regeneration.
222
+
223
+ Use these tags sparingly. When you must use them, prefer stable commands with bounded output (e.g., `head -n 20` in `<shell>`).
224
+
225
+ ---
226
+
227
+ ## Architecture Metadata Tags
228
+
229
+ PDD prompts can include optional XML metadata tags that sync with `architecture.json`. These tags enable bidirectional sync between prompt files and the architecture visualization, keeping your project's architecture documentation automatically up-to-date.
230
+
231
+ ### Tag Format
232
+
233
+ Place architecture metadata tags at the **top of your prompt file** (after any `<include>` directives but before the main content):
234
+
235
+ ```xml
236
+ <pdd-reason>Brief description of module's purpose (60-120 chars)</pdd-reason>
237
+
238
+ <pdd-interface>
239
+ {
240
+ "type": "module",
241
+ "module": {
242
+ "functions": [
243
+ {"name": "function_name", "signature": "(...)", "returns": "Type"}
244
+ ]
245
+ }
246
+ }
247
+ </pdd-interface>
248
+
249
+ <pdd-dependency>dependency_prompt_1.prompt</pdd-dependency>
250
+ <pdd-dependency>dependency_prompt_2.prompt</pdd-dependency>
251
+ ```
252
+
253
+ ### Tag Reference
254
+
255
+ **`<pdd-reason>`**
256
+ - **Purpose**: One-line description of why this module exists
257
+ - **Maps to**: `architecture.json["reason"]`
258
+ - **Format**: Single line string (recommended 60-120 characters)
259
+ - **Example**: `<pdd-reason>Provides unified LLM invocation across all PDD operations.</pdd-reason>`
260
+
261
+ **`<pdd-interface>`**
262
+ - **Purpose**: JSON describing the module's public API (functions, commands, pages)
263
+ - **Maps to**: `architecture.json["interface"]`
264
+ - **Format**: Valid JSON matching one of four interface types (see below)
265
+ - **Example**:
266
+ ```xml
267
+ <pdd-interface>
268
+ {
269
+ "type": "module",
270
+ "module": {
271
+ "functions": [
272
+ {"name": "llm_invoke", "signature": "(prompt, strength, ...)", "returns": "Dict"}
273
+ ]
274
+ }
275
+ }
276
+ </pdd-interface>
277
+ ```
278
+
279
+ **`<pdd-dependency>`**
280
+ - **Purpose**: References other prompt files this module depends on
281
+ - **Maps to**: `architecture.json["dependencies"]` array
282
+ - **Format**: Prompt filename (e.g., `llm_invoke_python.prompt`)
283
+ - **Multiple tags**: Use one `<pdd-dependency>` tag per dependency
284
+ - **Example**:
285
+ ```xml
286
+ <pdd-dependency>llm_invoke_python.prompt</pdd-dependency>
287
+ <pdd-dependency>path_resolution_python.prompt</pdd-dependency>
288
+ ```
289
+
290
+ ### Interface Types
291
+
292
+ The `<pdd-interface>` tag supports four interface types, matching the architecture.json schema:
293
+
294
+ **Module Interface** (Python modules with functions):
295
+ ```json
296
+ {
297
+ "type": "module",
298
+ "module": {
299
+ "functions": [
300
+ {"name": "func_name", "signature": "(arg1, arg2)", "returns": "Type"}
301
+ ]
302
+ }
303
+ }
304
+ ```
305
+
306
+ **CLI Interface** (Command-line interfaces):
307
+ ```json
308
+ {
309
+ "type": "cli",
310
+ "cli": {
311
+ "commands": [
312
+ {"name": "cmd_name", "description": "What it does"}
313
+ ]
314
+ }
315
+ }
316
+ ```
317
+
318
+ **Command Interface** (PDD commands):
319
+ ```json
320
+ {
321
+ "type": "command",
322
+ "command": {
323
+ "commands": [
324
+ {"name": "cmd_name", "description": "What it does"}
325
+ ]
326
+ }
327
+ }
328
+ ```
329
+
330
+ **Frontend Interface** (UI pages):
331
+ ```json
332
+ {
333
+ "type": "frontend",
334
+ "frontend": {
335
+ "pages": [
336
+ {"name": "page_name", "route": "/path"}
337
+ ]
338
+ }
339
+ }
340
+ ```
341
+
342
+ ### Sync Workflow
343
+
344
+ 1. **Add/edit tags** in your prompt files using the format above
345
+ 2. **Click "Sync from Prompt"** in the PDD Connect Architecture page (or call the API endpoint)
346
+ 3. **Tags automatically update** `architecture.json` with your changes
347
+ 4. **Architecture visualization** reflects the updated dependencies and interfaces
348
+
349
+ Prompts are the **source of truth** - tags in prompt files override what's in `architecture.json`. This aligns with PDD's core philosophy that prompts, not code or documentation, are authoritative.
350
+
351
+ ### Validation
352
+
353
+ Validation is **lenient**:
354
+ - Missing tags are OK - only fields with tags get updated
355
+ - Malformed XML/JSON is skipped without blocking sync
356
+ - Circular dependencies are detected and prevent invalid updates
357
+ - Missing dependency files generate warnings but don't block sync
358
+
359
+ ### Best Practices
360
+
361
+ **Keep `<pdd-reason>` concise** (60-120 chars)
362
+ - Good: "Provides unified LLM invocation across all PDD operations."
363
+ - Too long: "This module exists because we needed a way to call different LLM providers through a unified interface that supports both streaming and non-streaming modes while also handling rate limiting and retry logic..."
364
+
365
+ **Use prompt filenames for dependencies**, not module names
366
+ - Correct: `<pdd-dependency>llm_invoke_python.prompt</pdd-dependency>`
367
+ - Wrong: `<pdd-dependency>pdd.llm_invoke</pdd-dependency>`
368
+ - Wrong: `<pdd-dependency>context/example.py</pdd-dependency>`
369
+
370
+ **Validate interface JSON before committing**
371
+ - Use a JSON validator to check syntax
372
+ - Ensure `type` field matches one of: `module`, `cli`, `command`, `frontend`
373
+ - Include required nested keys (`functions`, `commands`, or `pages`)
374
+
375
+ **Run "Sync All" after bulk prompt updates**
376
+ - If you've edited multiple prompts, sync all at once
377
+ - Review the validation results for circular dependencies
378
+ - Fix any warnings before committing changes
379
+
380
+ ### Relationship to Other Tags
381
+
382
+ **`<pdd-dependency>` vs `<include>`**:
383
+ - `<pdd-dependency>`: Declares architectural dependency (updates `architecture.json`)
384
+ - `<include>`: Injects content into prompt for LLM context (does NOT affect architecture)
385
+ - Use both when appropriate - they serve different purposes
386
+
387
+ **`<pdd-*>` tags vs `<pdd>` comments**:
388
+ - `<pdd-reason>`, `<pdd-interface>`, `<pdd-dependency>`: Metadata tags (processed by sync tool)
389
+ - `<pdd>...</pdd>`: Human-only comments (removed by preprocessor, never reach LLM)
390
+ - Both are valid PDD directives with different purposes
391
+
392
+ ### Example: Complete Prompt with Metadata Tags
393
+
394
+ See `docs/examples/prompt_with_metadata.prompt` for a full example showing all three metadata tags in context.
395
+
396
+ ---
397
+
398
+ ## Advanced Tips
399
+
400
+ ### Shared Preamble for Consistency
401
+
402
+ Use a shared include (e.g., `<include>context/project_preamble.prompt</include>`) at the top of every prompt. You should create this file in your project's `context/` directory to define your "Constitution": consistent coding style (e.g., indentation, naming conventions), preferred linting rules, and forbidden libraries. This ensures all generated code speaks the same language without cluttering individual prompts.
403
+
404
+ ### Automatic Update Propagation via Includes
405
+
406
+ A key benefit of `<include>` directives is **automatic propagation**: when the included file changes, all prompts that reference it automatically reflect those changes on the next generation—without editing the prompts themselves.
407
+
408
+ Use this pattern when:
409
+ - **Authoritative documentation exists elsewhere** (e.g., a README that defines environment variables, API contracts, or configuration options). Include it rather than duplicating the content.
410
+ - **Shared constraints evolve** (e.g., coding standards, security policies). A single edit to the preamble file updates all prompts.
411
+ - **Interface definitions change** (e.g., a dependency's example file). Prompts consuming that example stay current.
412
+
413
+ *Tradeoff:* Large includes consume context tokens. If only a small portion of a file is relevant, consider extracting that portion into a dedicated include file (e.g., `docs/output_conventions.md` rather than the full `README.md`).
414
+
415
+ ### Positive over Negative Constraints
416
+
417
+ Models often struggle with negative constraints ("Do not use X"). Instead, phrase requirements positively: instead of "Do not use unassigned variables," prefer "Initialize all variables with default values." This greatly improves reliability.
418
+
419
+ ### Positioning Critical Instructions (Hierarchy of Attention)
420
+
421
+ LLMs exhibit "middle-loss" – they pay more attention to the **beginning** (role, preamble) and the **end** (steps, deliverables) of the prompt context. If a critical constraint (e.g., security, output format) is ignored, ensure it's placed in your shared preamble, explicitly reiterated in the final "Instructions" or "Steps" section, or even pre-filled in the expected output format if applicable.
422
+
423
+ ### Command-Specific Context Files
424
+
425
+ Some PDD commands (e.g., `pdd test`, `pdd example`) can automatically include project-specific context files like `context/test.prompt` or `context/example.prompt` during their internal preprocessing. Use these to provide instructions tailored to your project, such as preferred testing frameworks or specific import statements, without modifying the main prompt.
426
+
427
+ **`context/test.prompt`** is particularly important:
428
+ - Defines testing conventions, frameworks, and patterns for your project
429
+ - Included automatically when running `pdd test` (alongside the module prompt and generated code)
430
+ - Tests accumulate over time via `--merge` as bugs are found
431
+ - Tests persist when the module prompt changes—only code is regenerated, not tests
432
+ - This ensures tests remain stable "permanent assets" while code can be freely regenerated
433
+
434
+ ---
435
+
436
+ ## Why PDD Scales to Large Codebases
437
+
438
+ - Explicit, curated context: use minimal examples and targeted includes instead of dumping source, reducing tokens and confusion.
439
+ - Modular dev units: one prompt per file/module constrains scope, enabling independent regeneration and parallel work.
440
+ - Batch, reproducible flow: eliminate long chat histories; regeneration avoids patch accumulation and incoherent diffs.
441
+ - Accumulating tests: protect behavior across wide regenerations and refactors; failures localize issues quickly.
442
+ - Single source of truth: prompts unify intent and dependencies, improving cross‑team coordination and reducing drift.
443
+ - Automated Grounding: By feeding successful past generations back into the context, the system stabilizes the code over time, making "regeneration" safe even for complex modules.
444
+
445
+ ### Tests as Generation Context
446
+
447
+ A key PDD feature: existing tests are automatically included as context when generating code. This means:
448
+
449
+ - The LLM sees the test file and knows what behaviors must be preserved
450
+ - Generated code is constrained to pass existing tests
451
+ - New tests accumulate over time, progressively constraining future generations
452
+ - This creates a "ratchet effect" - each bug fix adds a test, preventing regression
453
+
454
+ This is distinct from test *generation*. Tests are generated via `pdd test PROMPT_FILE CODE_FILE`, which uses the module prompt, generated code, and `context/test.prompt` for project-wide guidance. Tests accumulate over time via `--merge` as bugs are found. Requirements in the module prompt implicitly define what to test—each requirement should correspond to at least one test case.
455
+
456
+ ```mermaid
457
+ flowchart LR
458
+ subgraph Assets
459
+ P[Module Prompt] --> G[pdd generate]
460
+ T[Existing Tests] --> G
461
+ G --> C[Generated Code]
462
+ end
463
+
464
+ subgraph Accumulation
465
+ BUG[Bug Found] --> NT[New Test Written]
466
+ NT --> T
467
+ end
468
+ ```
469
+
470
+ ---
471
+
472
+ Patch vs PDD at Scale (diagram):
473
+
474
+ ```mermaid
475
+ flowchart LR
476
+ subgraph Patching
477
+ C0[Codebase] --> P0[Chat prompt]
478
+ P0 --> D0[Local diff]
479
+ D0 --> C0
480
+ end
481
+
482
+ subgraph PDD
483
+ PG[Prompts graph] --> GZ[Batch regenerate]
484
+ GZ --> CM[Code modules]
485
+ CM --> XT[Examples and Tests]
486
+ XT --> UP[Update prompts]
487
+ UP --> PG
488
+ end
489
+ ```
490
+
491
+ ---
492
+
493
+ ## The Three Pillars of PDD Generation
494
+
495
+ Understanding how prompts, grounding, and tests work together is key to writing minimal, effective prompts.
496
+
497
+ | Pillar | What It Provides | Maintained By |
498
+ |--------|-----------------|---------------|
499
+ | **Prompt** | Requirements and constraints (WHAT) | Developer (explicit) |
500
+ | **Grounding** | Implementation patterns (HOW) | System (automatic, Cloud) |
501
+ | **Tests** | Behavioral correctness | Accumulated over time |
502
+
503
+ ### How They Interact
504
+
505
+ - **Prompt** defines WHAT → "validate user input, return errors"
506
+ - **Grounding** defines HOW → class structure, helper patterns (from similar modules)
507
+ - **Tests** define CORRECTNESS → edge cases discovered through bugs
508
+
509
+ ### Conflict Resolution
510
+
511
+ - **Tests override grounding**: If a test requires new behavior, generation must satisfy it
512
+ - **Explicit requirements override grounding**: If prompt says "use functional style", that overrides OOP examples in grounding
513
+ - **Grounding fills gaps**: Everything not specified in prompt or constrained by tests
514
+
515
+ ### Why Prompts Can Be Minimal
516
+
517
+ You don't need to specify:
518
+ - **Coding style** → preamble provides it
519
+ - **Implementation patterns** → grounding provides them
520
+ - **Edge cases** → tests encode them
521
+
522
+ You only specify:
523
+ - What the module does
524
+ - What contracts it must satisfy
525
+ - What constraints apply
526
+
527
+ ---
528
+
529
+ ## Example (Minimal, Python)
530
+
531
+ This simplified example illustrates a minimal functional prompt:
532
+
533
+ ```text
534
+ % You are an expert Python engineer. Your goal is to write a function `get_extension` that returns the file extension for a given language.
535
+
536
+ <include>context/python_preamble.prompt</include>
537
+
538
+ % Inputs/Outputs
539
+ Input: language (str), like "Python" or "Makefile".
540
+ Output: str file extension (e.g., ".py"), or "" if unknown.
541
+
542
+ % Data
543
+ The CSV at $PDD_PATH/data/language_format.csv contains: language,comment,extension
544
+
545
+ % Steps
546
+ 1) Load env var PDD_PATH and read the CSV
547
+ 2) Normalize language case
548
+ 3) Lookup extension
549
+ 4) Return "" if not found or invalid
550
+ ```
551
+
552
+ This style:
553
+ - Declares role and outcome
554
+ - Specifies IO, data sources, and steps
555
+ - Uses an `<include>` to pull a shared preamble
556
+
557
+ ---
558
+
559
+ ## Scoping & Modularity
560
+
561
+ - One prompt → one file/module. If a prompt gets too large or brittle, split it into smaller prompts that compose via explicit interfaces.
562
+ - Treat examples as interfaces: create a minimal runnable example demonstrating how the module is meant to be used.
563
+ - Avoid “mega‑prompts” that try to implement an entire subsystem. Use the PDD graph of prompts instead. For how prompts compose via examples, see “Dependencies & Composability (Token‑Efficient Examples)”.
564
+
565
+ ---
566
+
567
+ ## Writing Effective Requirements
568
+
569
+ Requirements are the core of your prompt. Everything else is handled automatically by grounding and tests.
570
+
571
+ ### Structure (aim for 5-10 items)
572
+
573
+ 1. **Primary function**: What does this module do? (one sentence)
574
+ 2. **Input contract**: Types, validation rules, what's accepted
575
+ 3. **Output contract**: Types, error conditions, return values
576
+ 4. **Key invariants**: What must always be true
577
+ 5. **Performance constraints**: If any (latency, memory, complexity)
578
+ 6. **Security constraints**: If any (input sanitization, auth requirements)
579
+
580
+ ### Each Requirement Should Be
581
+
582
+ - **Testable**: If you can't write a test for it, it's too vague
583
+ - **Behavioral**: Describe WHAT, not HOW
584
+ - **Unique**: Don't duplicate what preamble or grounding provides
585
+
586
+ ### Example: Before/After
587
+
588
+ **Too detailed:**
589
+ ```
590
+ 1. Create a UserValidator class with validate() method
591
+ 2. Use snake_case for all methods ← belongs in preamble
592
+ 3. Import typing at the top ← belongs in preamble
593
+ 4. Add docstrings to all public methods ← belongs in preamble
594
+ 5. Handle null by returning ValidationError
595
+ 6. Handle empty string by returning ValidationError
596
+ 7. Handle whitespace-only by returning ValidationError
597
+ ```
598
+
599
+ **Just right** (requirements only):
600
+ ```
601
+ 1. Function: validate_user(input) → ValidationResult
602
+ 2. Input: Any type (untrusted user input)
603
+ 3. Output: ValidationResult with is_valid bool and errors list
604
+ 4. Invalid inputs: null, empty, whitespace-only, malformed
605
+ 5. Performance: O(n) in input length
606
+ 6. Security: No eval/exec, treat input as untrusted
607
+ ```
608
+
609
+ Style conventions (2-4) belong in a shared preamble. Edge cases (5-7) can be collapsed into a single requirement.
610
+
611
+ **Requirements as Test Specifications:** Each requirement implies at least one test case. If you can't test a requirement, it's too vague.
612
+
613
+ ---
614
+
615
+ ## Prompt Abstraction Level
616
+
617
+ ![Goldilocks Prompt](goldilocks_prompt.jpeg)
618
+
619
+ Write prompts at the level of *architecture, contract, and intent*, not line-by-line *implementation details*.
620
+
621
+ ### Heuristics: Are You at the Right Level?
622
+
623
+ | Indicator | Too Detailed (> 30%) | Too Vague (< 10%) |
624
+ |-----------|----------------------|-------------------|
625
+ | **Content** | Specifying variable names, loop structures | Missing error handling strategy |
626
+ | **Style** | Dictating indentation, imports | No input/output types |
627
+ | **Result** | Prompt harder to maintain than code | Every generation is wildly different |
628
+
629
+ ### If Your Prompt Is Too Long
630
+
631
+ Ask yourself:
632
+ - **Am I specifying coding style?** → Remove it (preamble handles this)
633
+ - **Am I specifying implementation patterns?** → Remove them (grounding handles this)
634
+ - **Am I listing every edge case?** → Remove them (tests handle this)
635
+ - **Is the module too big?** → Split into multiple prompts
636
+
637
+ ### Examples
638
+
639
+ - **Too Vague:** "Create a user page." (Model guesses everything; unrepeatable)
640
+ - **Too Detailed:** "Create a class User with a private field _id. In the constructor, set _id. Write a getter..." (Prompt is harder to maintain than code)
641
+ - **Just Right:** "Implement a UserProfile component that displays user details and handles the 'update' action via the API. It must handle loading/error states and match the existing design system."
642
+
643
+ **Rule of Thumb:** Focus on **Interfaces**, **Invariants**, and **Outcomes**. Let the preamble handle coding style; let grounding handle implementation patterns.
644
+
645
+ ---
646
+
647
+ ## Dependencies
648
+
649
+ ### When to Use `<include>`
650
+
651
+ Include dependencies explicitly when:
652
+ - **External libraries** not in your grounding history
653
+ - **Critical interfaces** that must be exact
654
+ - **New modules** with no similar examples in grounding
655
+
656
+ ```xml
657
+ <billing_service>
658
+ <include>context/billing_service_example.py</include>
659
+ </billing_service>
660
+ ```
661
+
662
+ ### When to Rely on Grounding
663
+
664
+ If you've successfully generated code that uses a dependency before, grounding often suffices—the usage pattern is already in the cloud database.
665
+
666
+ **Prefer explicit `<include>` for:** External APIs, critical contracts, cross-team interfaces
667
+ **Rely on grounding for:** Internal modules with established patterns
668
+
669
+ ### Token Efficiency
670
+
671
+ Real source code is heavy. A 500-line module might have a 50-line usage example. By including only the example, you save ~90% of tokens. Use `pdd auto-deps` to automatically populate relevant examples.
672
+
673
+ ```mermaid
674
+ flowchart LR
675
+ subgraph Module_B
676
+ PB[Prompt B] --> GB[Generate] --> CB[Code B]
677
+ CB --> EB[Example B]
678
+ end
679
+
680
+ subgraph Module_A
681
+ PA[Prompt A] --> GA[Generate] --> CA[Code A]
682
+ PA --> EB
683
+ end
684
+
685
+ EB --> CA
686
+ ```
687
+
688
+ ---
689
+
690
+ ## Regenerate, Verify, Test, Update
691
+
692
+ **Crucial Prerequisite:** Before regenerating a module, ensure you have **high test coverage** for its current functionality. Because PDD overwrites the code file entirely, your test suite is the critical safety net that prevents regression of existing features while you iterate on new ones.
693
+
694
+ The PDD workflow (see pdd/docs/whitepaper.md):
695
+
696
+ 1) **Generate:** Fully regenerate (overwrite) the code module and its example.
697
+ 2) **Crash → Verify:** Run the example. Fix immediate runtime errors.
698
+ 3) **Test (Accumulate):** Run existing tests. If fixing a bug, **write a new failing test case first** and append it to the test file. *Never overwrite the test file; tests must accumulate to prevent regressions.*
699
+ 4) **Fix via Command:** When you use `pdd fix` (or manual fixes verified by tests), the system **automatically submits** the successful Prompt+Code pair to PDD Cloud (or local history).
700
+ 5) **Fix via Prompt:** If the logic is fundamentally flawed, update the prompt text to clarify the requirement or constraint that was missed, then **go to step 1**.
701
+ 5) **Drift Check (Optional):** Occasionally regenerate the module *without* changing the prompt (e.g., after upgrading LLM versions or before major releases). If the output differs significantly or fails tests, your prompt has "drifted" (it relied on lucky seeds or implicit context). Tighten the prompt until the output is stable.
702
+ 6) **Update:** Once tests pass, back-propagate any final learnings into the prompt.
703
+
704
+ Key practice: Code and examples are ephemeral (regenerated); Tests and Prompts are permanent assets (accumulated and versioned).
705
+
706
+ **Important:** Tests ARE generated from the module prompt (plus code and `context/test.prompt`). The key distinction is their lifecycle:
707
+ - Code is regenerated on prompt changes; tests accumulate and persist
708
+ - Requirements implicitly define test coverage—each requirement implies at least one test
709
+ - Use `context/test.prompt` for project-wide test guidance (frameworks, patterns)
710
+ - Existing tests are included as context during code generation
711
+ - This creates a "ratchet effect" where each new test permanently constrains future generations
712
+
713
+ ### Workflow Cheatsheet: Features vs. Bugs
714
+
715
+ | Task Type | Where to Start | The Workflow |
716
+ | :--- | :--- | :--- |
717
+ | **New Feature** | **The Prompt** | 1. Add/Update Requirements in Prompt.<br>2. Regenerate Code (LLM sees existing tests).<br>3. Write new Tests to verify. |
718
+ | **Bug Fix** | **The Test File** | 1. Use `pdd bug` to create a failing test case (repro) in the Test file.<br>2. Clarify the Prompt to address the edge case if needed.<br>3. Run `pdd fix` (LLM sees the new test and must pass it). |
719
+
720
+ **Key insight:** When you run `pdd generate` after adding a test, the LLM sees that test as context. This means the generated code is constrained to pass it - the test acts as a specification, not just a verification.
721
+
722
+ **Why?** Features represent *new intent* (Prompt). Bugs represent *missed intent* which must first be captured as a constraint (Test) before refining the definition (Prompt).
723
+
724
+ ### When to Update the Prompt (and When Not To)
725
+
726
+ After a successful fix, ask: "Where should this knowledge live?"
727
+
728
+ | Knowledge Type | Where It Lives | Update Prompt? |
729
+ |---------------|----------------|----------------|
730
+ | New edge case behavior | Test file | **No** |
731
+ | Implementation pattern fix | Grounding (auto-captured) | **No** |
732
+ | Missing requirement | Prompt | **Yes** |
733
+ | Wrong constraint | Prompt | **Yes** |
734
+ | Security/compliance rule | Prompt or preamble | **Yes** |
735
+
736
+ **Rule of thumb:** Update the prompt only for **intent changes**:
737
+ - "The module should also handle X" → Add requirement
738
+ - "The constraint was wrong" → Fix requirement
739
+ - "This security rule applies" → Add requirement
740
+
741
+ **Don't update for implementation fixes:**
742
+ - "There was a bug with null handling" → Add test; grounding captures the fix
743
+ - "The code style was inconsistent" → Update preamble (not prompt)
744
+ - "I prefer different variable names" → Update preamble/prompt
745
+
746
+ ---
747
+
748
+ ## PDD vs Interactive Agentic Coders (Claude Code, Cursor)
749
+
750
+ - Source of truth:
751
+ - PDD: the prompt is primary and versioned; code is regenerated output
752
+ - Interactive: the code is primary; prompts are ephemeral patch instructions
753
+ - Workflow:
754
+ - PDD: batch‑oriented, reproducible runs; explicit context via includes
755
+ - Interactive: live chat loops; implicit context; local diffs
756
+ - Scope:
757
+ - PDD: scoped to modules/files with clear interfaces; compose via examples
758
+ - Interactive: excels at small, local edits; struggles as scope and history grow
759
+ - Synchronization:
760
+ - PDD: update prompts after fixes; tests accumulate and protect behavior
761
+ - Interactive: prompt history rarely persists; documentation often drifts
762
+
763
+ When to use which: Use PDD for substantive new modules, refactors, and anything requiring long‑term maintainability and repeatability. Use interactive patching for trivial hotfixes; follow up with a prompt `update` so the source of truth remains synchronized.
764
+
765
+ ---
766
+
767
+ ## Patch vs PDD: Concrete Examples
768
+
769
+ Patch‑style prompt (interactive agent):
770
+
771
+ ```text
772
+ Fix this bug in src/utils/user.ts. In function parseUserId, passing null should return null instead of throwing.
773
+
774
+ Constraints:
775
+ - Change the minimum number of lines
776
+ - Do not alter the function signature or add new functions
777
+ - Keep existing imports and formatting
778
+ - Output a unified diff only
779
+
780
+ Snippet:
781
+ export function parseUserId(input: string) {
782
+ return input.trim().split(":")[1];
783
+ }
784
+ ```
785
+
786
+ PDD‑style prompt (source of truth):
787
+
788
+ ```text
789
+ % You are an expert TypeScript engineer. Create a module `user_id_parser` with a function `parseUserId` that safely extracts a user id.
790
+
791
+ % Role & Scope
792
+ A utility module responsible for parsing user identifiers from various inputs.
793
+
794
+ % Requirements
795
+ 1) Function: `parseUserId(input: unknown): string | null`
796
+ 2) Accepts strings like "user:abc123" and returns "abc123"
797
+ 3) For null/undefined/non‑string, return null without throwing
798
+ 4) Trim whitespace; reject blank ids as null
799
+ 5) Log at debug level on parse failures; no exceptions for expected cases
800
+ 6) Performance: O(n) in input length; no regex backtracking pitfalls
801
+ 7) Security: no eval/exec; treat input as untrusted
802
+
803
+ % Dependencies
804
+ <logger>
805
+ <include>context/logger_example.ts</include>
806
+ </logger>
807
+
808
+ % Instructions
809
+ - Implement in `src/utils/user_id_parser.ts`
810
+ - Export `parseUserId`
811
+ - Add narrow helpers if needed; keep module cohesive
812
+ - Include basic JSDoc and simple debug logging hooks
813
+ ```
814
+
815
+ Key differences:
816
+ - Patch prompt constrains a local edit and often asks for a diff. It assumes code is the source of truth.
817
+ - PDD prompt defines the module's contract, dependencies, and deliverables. It is the source of truth; code is regenerated to match it, while tests accumulate over time.
818
+
819
+ ---
820
+
821
+ ## Checklist: Before You Run `pdd generate`
822
+
823
+ ### Must Have
824
+ - [ ] Module purpose is clear (1-2 sentences)
825
+ - [ ] Requirements are testable and behavioral (5-10 items)
826
+ - [ ] Dependencies included (if external or critical)
827
+
828
+ ### For Established Modules
829
+ - [ ] Tests exist for known edge cases
830
+ - [ ] Previous generation was successful (grounding will use it)
831
+
832
+ ### For New Modules
833
+ - [ ] Similar modules exist in codebase (grounding will find them)
834
+ - [ ] Or: Consider `<pin>` to reference a template module (Cloud)
835
+
836
+ ### You Don't Need to Specify
837
+ - Coding style (preamble handles this)
838
+ - Implementation patterns (grounding handles this)
839
+ - Every edge case (tests handle this)
840
+
841
+ ---
842
+
843
+ ## Common Pitfalls (And Fixes)
844
+
845
+ - Too much context: prune includes; prefer targeted examples over entire files.
846
+ - Vague requirements: convert to explicit contracts, budgets, and behaviors.
847
+ - Mega‑prompts: split into smaller prompts (one per file/module) and compose.
848
+ - Prompt outweighs the code: if the prompt is larger than the generated file, it’s usually over‑specifying control flow. Aim for prompts to be a fraction of the target code size; keep them at the interface/behavior level and let the model fill in routine implementation.
849
+ - Patching code directly: make the change in the prompt and regenerate; then `update` with learnings.
850
+ - Throwing away tests: keep and expand; they are your long‑term leverage.
851
+
852
+ ---
853
+
854
+ ## Naming & Conventions (This Repo)
855
+
856
+ - One prompt per module/file, named like `${BASENAME}_${LanguageOrFramework}.prompt` (see templates under `pdd/pdd/templates`).
857
+ - Follow codebase conventions from README.md for Python and TypeScript style.
858
+ - Use curated examples under `context/` to encode interfaces and behaviors.
859
+
860
+ ---
861
+
862
+ ## Final Notes
863
+
864
+ Think of prompts as your programming language. Keep them concise, explicit, and modular. Regenerate instead of patching, verify behavior with accumulating tests, and continuously back‑propagate implementation learnings into your prompts. That discipline is what converts maintenance from an endless patchwork into a compounding system of leverage.