specpro-cli 0.1.0__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 (76) hide show
  1. specpro_cli/__init__.py +16 -0
  2. specpro_cli/assets/commands/specpro.analyze.md +1102 -0
  3. specpro_cli/assets/commands/specpro.checklist.md +335 -0
  4. specpro_cli/assets/commands/specpro.clarify.md +581 -0
  5. specpro_cli/assets/commands/specpro.constitution.md +488 -0
  6. specpro_cli/assets/commands/specpro.feature.md +115 -0
  7. specpro_cli/assets/commands/specpro.implement.md +1881 -0
  8. specpro_cli/assets/commands/specpro.manual-test.md +206 -0
  9. specpro_cli/assets/commands/specpro.plan.md +3284 -0
  10. specpro_cli/assets/commands/specpro.qc.md +1489 -0
  11. specpro_cli/assets/commands/specpro.scenarios.md +154 -0
  12. specpro_cli/assets/commands/specpro.specify.md +1449 -0
  13. specpro_cli/assets/commands/specpro.status.md +863 -0
  14. specpro_cli/assets/commands/specpro.tasks.md +1207 -0
  15. specpro_cli/assets/commands/specpro.test-implement.md +462 -0
  16. specpro_cli/assets/commands/specpro.test-plan.md +383 -0
  17. specpro_cli/assets/commands/specpro.user-manual.md +178 -0
  18. specpro_cli/assets/scripts/bash/check-anti-coupling.sh +293 -0
  19. specpro_cli/assets/scripts/bash/check-prerequisites.sh +176 -0
  20. specpro_cli/assets/scripts/bash/common.sh +88 -0
  21. specpro_cli/assets/scripts/bash/create-new-feature.sh +336 -0
  22. specpro_cli/assets/scripts/bash/qc-auto-fix.sh +121 -0
  23. specpro_cli/assets/scripts/bash/setup-plan.sh +60 -0
  24. specpro_cli/assets/scripts/bash/verify-cumulative-records.sh +203 -0
  25. specpro_cli/assets/scripts/bash/verify-deliverables-tracked.sh +147 -0
  26. specpro_cli/assets/scripts/bash/verify-deployment.sh +239 -0
  27. specpro_cli/assets/scripts/bash/verify-frontmatter-yaml.sh +63 -0
  28. specpro_cli/assets/scripts/bash/verify-ledger.sh +376 -0
  29. specpro_cli/assets/scripts/bash/verify-shapes.sh +1082 -0
  30. specpro_cli/assets/scripts/git-hooks/pre-commit +243 -0
  31. specpro_cli/assets/scripts/install-git-hooks.sh +67 -0
  32. specpro_cli/assets/scripts/powershell/check-anti-coupling.ps1 +249 -0
  33. specpro_cli/assets/scripts/powershell/check-prerequisites.ps1 +148 -0
  34. specpro_cli/assets/scripts/powershell/common.ps1 +95 -0
  35. specpro_cli/assets/scripts/powershell/create-new-feature.ps1 +229 -0
  36. specpro_cli/assets/scripts/powershell/qc-auto-fix.ps1 +110 -0
  37. specpro_cli/assets/scripts/powershell/setup-plan.ps1 +61 -0
  38. specpro_cli/assets/scripts/powershell/verify-cumulative-records.ps1 +133 -0
  39. specpro_cli/assets/scripts/powershell/verify-deliverables-tracked.ps1 +112 -0
  40. specpro_cli/assets/scripts/powershell/verify-deployment.ps1 +278 -0
  41. specpro_cli/assets/scripts/powershell/verify-frontmatter-yaml.ps1 +56 -0
  42. specpro_cli/assets/scripts/powershell/verify-ledger.ps1 +383 -0
  43. specpro_cli/assets/scripts/powershell/verify-shapes.ps1 +978 -0
  44. specpro_cli/assets/templates/agent-context-template.md +49 -0
  45. specpro_cli/assets/templates/assumptions-template.md +248 -0
  46. specpro_cli/assets/templates/checklist-template.md +40 -0
  47. specpro_cli/assets/templates/clarifications-template.md +155 -0
  48. specpro_cli/assets/templates/constitution-template.md +50 -0
  49. specpro_cli/assets/templates/feature-spec-template.md +66 -0
  50. specpro_cli/assets/templates/plan-overview-template.md +150 -0
  51. specpro_cli/assets/templates/plan-template.md +387 -0
  52. specpro_cli/assets/templates/protocol-golden-bytes-guide.md +195 -0
  53. specpro_cli/assets/templates/requirements-template.md +356 -0
  54. specpro_cli/assets/templates/spec-template.md +267 -0
  55. specpro_cli/assets/templates/tasks-template.md +252 -0
  56. specpro_cli/assets/templates/test-tasks-template.md +174 -0
  57. specpro_cli/cli/__init__.py +5 -0
  58. specpro_cli/cli/cmd_init.py +416 -0
  59. specpro_cli/cli/cmd_remove.py +122 -0
  60. specpro_cli/cli/entry.py +181 -0
  61. specpro_cli/integrations/__init__.py +36 -0
  62. specpro_cli/integrations/base.py +601 -0
  63. specpro_cli/integrations/claude/__init__.py +101 -0
  64. specpro_cli/integrations/copilot/__init__.py +153 -0
  65. specpro_cli/integrations/cursor_agent/__init__.py +51 -0
  66. specpro_cli/integrations/gemini/__init__.py +44 -0
  67. specpro_cli/integrations/opencode/__init__.py +48 -0
  68. specpro_cli/integrations/qodercli/__init__.py +54 -0
  69. specpro_cli/integrations/registry.py +88 -0
  70. specpro_cli/packaged/__init__.py +5 -0
  71. specpro_cli/packaged/sync.py +106 -0
  72. specpro_cli-0.1.0.dist-info/METADATA +117 -0
  73. specpro_cli-0.1.0.dist-info/RECORD +76 -0
  74. specpro_cli-0.1.0.dist-info/WHEEL +4 -0
  75. specpro_cli-0.1.0.dist-info/entry_points.txt +2 -0
  76. specpro_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1881 @@
1
+ ---
2
+ description: Execute the implementation plan by processing and executing all tasks defined in tasks.md
3
+ writes:
4
+ # This command's write surface: only what it produces AS THE PRODUCER of that
5
+ # (artifact, unit) pair. A write this command makes on a non-producer path is a
6
+ # boundary violation by definition (FR-051) and MUST NOT be declared here.
7
+ # The full ownership map is the UNION of every command's writes: block.
8
+ - artifact: <product code paths named by each task Location>
9
+ unit: "the files each task names, up to and including that task's whole deliverable"
10
+ - artifact: .gitignore / .prettierignore / .npmignore / .terraformignore / .helmignore
11
+ unit: "whole file when missing; otherwise only the missing critical patterns are appended"
12
+ - artifact: specs/tasks.md
13
+ unit: "the executed task lines -> checkbox [ ] -> [x]"
14
+ - artifact: specs/research.md
15
+ unit: "appended ## Addendum (<task-id>, <date>) sections - implementation findings"
16
+ - artifact: specs/implement_issues.md
17
+ unit: "new ISS-NNN entries in the owning section; the statistics table (**its own row only** — seven commands declare this artifact). ⚠️ **Marking another section's entries `[x]` is NOT in this unit** (T233/ISS-206): `specs/contracts/ledger.md` → Write boundary reads *「标记(`[x]`)= **限于本分区**」* and *「**登记方从不标记他方条目**——承接方是该分区条目的唯一勾选方」*, and it lists this command's write as *'new ISS-NNN entries in the owning section'* alone. The `[tasks]` section is consumed — and therefore marked — by `/specpro-tasks --review-issues` (§ the `--review-issues` entry above)."
18
+ - artifact: specs/fix-tasks.md
19
+ unit: "FT-XXX checkbox plus diagnostic notes - never test-task checkboxes; **not** the evidence or the PASS verdict, which are /specpro-test-implement's"
20
+ - artifact: docs/implement/**
21
+ unit: "the whole document set: PROJECT_NAVIGATION.md, {topic}/index.md, per-topic work documents and their reverse indexes"
22
+ ---
23
+
24
+ ## User Input
25
+
26
+ ```text
27
+ $ARGUMENTS
28
+ ```
29
+
30
+ You **MUST** consider the user input before proceeding (if not empty).
31
+
32
+ **Rerun safety — writes product code and process docs, not design artifacts** ⚠️ [settled 2026-09-13]:
33
+
34
+ This command **produces no design artifact**. It executes tasks from `tasks.md`, writing product code and the process documents those tasks require. The shared rerun rule (*detect the artifact; absent → initial, present → incremental; overwriting requires explicit AND re-confirmed intent*) governs the commands that produce design artifacts — `specify`, `plan`, `tasks`, `test-plan` and the rest.
35
+
36
+ **Progress is carried by the task list, not by regeneration.** Tasks already marked complete are never redone: a re-run resumes from the first unfinished task, and the task list's own incremental semantics (unmodified entries preserved verbatim) do the work the detection check does elsewhere. Resetting a completion state requires the same explicit, re-confirmed intent that overwriting an artifact requires.
37
+
38
+ > **Why a shared rule rather than per-command courtesy**: nine of the twelve non-implementation commands already had some protection, but each wrote it its own way (`EXISTING_SPEC` check · "creates a NEW file" · `NEVER overwrite` · "incremental regeneration" · `AUTO_MODE=false`), and **three had none at all** — not by decision, but because the discipline had no shared carrier. Overwriting an artifact the user has been evolving is not recoverable within the session; the cost of asking is one prompt. **This command writes no design artifact, so it never triggers the rule's third clause** — its guard against lost work is the task list's completion state, which is likewise never reset silently.
39
+
40
+ **Execution Mode Selection** (Interactive):
41
+ - If NO arguments provided: Show interactive mode selection menu
42
+ - If arguments provided: Parse and execute directly (skip menu)
43
+
44
+ **Supported arguments**:
45
+ - `--once`: Execute only one task, then exit
46
+ - `--count N`: Execute N tasks, then exit
47
+ - `--phase PHASE`: Execute all tasks in specific phase
48
+ - `--continue`: Execute all tasks (⚠️ WARNING: Context overflow risk)
49
+ - `--review-issues`: **skip the question** — the `[tasks]` queue is known to be non-empty, proceed with the normal run. ⚠️ **This flag does NOT process that queue** (T172): the `[tasks]` section is owned by `/specpro-tasks --review-issues`, which is the only party that marks its entries `[x]`. This command never writes `specs/tasks.md`.
50
+ - `--fix-defects`: **skip the question and process the pending `FT-xxx` fix tasks** directly (product-code fixes — see below). *(Renamed from `--fix-issues`, settled 2026-09-13: `fix` now unambiguously means product code, `review` means upstream artifacts. The old name was undefined in every command and meant two different things depending on who received it — TOOL-008.)*
51
+
52
+ **Two pending sets, both detected on every run** ⚠️ [settled 2026-09-13]:
53
+
54
+ This command has **two independent queues**. Neither is opted into by a flag — a flag only means "I already know, don't ask".
55
+
56
+ | Queue | Where | What the fix touches — **and who applies it** |
57
+ |-------|-------|--------------------|
58
+ | **Upstream-artifact issues** | the `[tasks]` section of `specs/implement_issues.md` | `specs/tasks.md` — **and the fix is applied by `/specpro-tasks --review-issues`, not by this command**: that command both updates the file and marks the entry `[x]`. This command touches **neither** (`T156` / `ISS-79`: this row used to leave the applier unnamed, and read as *"this command does it"* — while `writes:` declares for `specs/tasks.md` **only** the checkbox of an executed task line). |
59
+ | **Product defects** | pending `[ ]` **FT-xxx** in `specs/fix-tasks.md` | **product code** |
60
+
61
+ **On every run, before any normal work, check BOTH.** Then:
62
+
63
+ | Situation | Behaviour |
64
+ |-----------|-----------|
65
+ | Both empty | Proceed with the normal run. **No prompt.** |
66
+ | Either non-empty | **Ask once, covering both** — "N pending items: `[tasks]`-section issues X · product defects (FT) Y. Process which first, or run normally?" The menu above already surfaces defects as option 1️⃣ (*Recommended when offered*); the rule here is that **the pending sets MUST be surfaced, not silently skipped.** |
67
+ | `--review-issues` passed | Skip the question for the `[tasks]` queue. **The queue itself is still processed by `/specpro-tasks --review-issues`** — this flag only says "don't ask me again". |
68
+ | `--fix-defects` passed | Skip the question for the FT queue; process it directly. |
69
+ | Both passed | Skip both questions. |
70
+
71
+ > **Why the flags are not switches** (the failure this replaces): the old semantics — flag = on, no flag = off — pushed the risk onto the user. *Not* passing one risked silently leaving that queue unprocessed; passing it risked overriding work the user meant to do in the normal mode. Neither was safe, and **which items were pending was invisible until the command ran**. **Detect-then-ask makes it an explicit choice; each flag is left doing only the one thing it is good at: saying "don't ask me again".**
72
+ >
73
+ > ⚠️ **History** (TOOL-008): `--fix-issues` was declared by no command, yet passed repeatedly by habit, and two commands *interpreted it differently* (here: execute FT; in `/specpro-test-plan`: process the `[test-plan]` section — which is what that command's `--review-issues` means, so the name was pure duplication). Anything the executor has to *guess* is neither reviewable nor reproducible.
74
+
75
+
76
+ ### Scope Resolution 🆕 (FR-063 / T050 · v0.23)
77
+
78
+ 1. **作用域判定**: 当前工作目录位于 `specs/fNNN-简称/` 内 ⇒ **feature 作用域**(读写范围 = 本 feature 目录,由 `check-prerequisites.sh` 的作用域感知解析);位于仓库根或 `specs/` 根 ⇒ **母作用域**(读写母规格链)。feature 作用域内 MUST NOT 写母产物——唯一例外:**发现登记**(台账路由,`[specify]`/`[plan]` 分区)。
79
+ 2. **新会话首次执行**: 若 `specs/features.md` 存在且含 `active` 行、而用户未指明作用域 ⇒ **询问用户**在母作用域还是某个 feature 内工作,MUST NOT 自行挑选。
80
+ 3. 本命令的产物路径随之解析:feature 作用域下落 `<feature 目录>/`,母作用域下落 `specs/`。
81
+
82
+ ## Outline
83
+
84
+ ## Implement Responsibility Boundaries ⚖️ [CRITICAL]
85
+
86
+ **Purpose**: Define what implement command MUST do vs. what it CAN decide freely
87
+
88
+ **SDD Principle**: Specification-Driven Development requires strict separation between:
89
+ - **Specification** (what to build): Defined by spec.md, plan.md, tasks.md
90
+ - **Implementation** (how to build): Executed by implement command
91
+
92
+ Implement command's job is to **execute specifications**, not to **make design decisions**.
93
+
94
+ ### Core Principles
95
+
96
+ **1. Function and Flow: STRICT EXECUTION** ✅
97
+ - **MUST**: Execute exactly what tasks.md specifies
98
+ - **MUST NOT**: Add new features not in tasks.md
99
+ - **MUST NOT**: Change design/specification
100
+ - **MUST NOT**: Skip required functionality
101
+ - **SDD rationale**: Features are specified in spec.md, designed in plan.md, broken down in tasks.md. Implement's job is to **execute**, not to **decide**.
102
+ - **Examples**:
103
+ - ✅ Task: "Implement authentication module" → Implement authentication exactly
104
+ - ❌ Don't add: "and also authorization" (not in task)
105
+ - ✅ Task: "Create login form with email/password" → Create form with email/password
106
+ - ❌ Don't add: "and also social login" (not in task)
107
+
108
+ **2. UI and Interaction: FREE DISCRETION** 🎨
109
+ - **Layout**: Full freedom (positioning, spacing, alignment)
110
+ - **Style**: Full freedom (colors, fonts, sizes, shapes)
111
+ - **Interaction**: Full freedom (animations, transitions, feedback)
112
+ - **Extra features**: OK to add (undo, batch operations, shortcuts)
113
+ - **No recording needed**: Don't document UI/interaction decisions
114
+ - **SDD rationale**: UI/implementation details are NOT specified in SDD workflow. They are implementation concerns that implement command can decide freely.
115
+ - **Examples**:
116
+ - ✅ Task: "Create login form" → Choose any layout/style you want
117
+ - ✅ Task: "Add 'Delete' button" → Position it anywhere, use any color
118
+ - ✅ OK to add: Confirm dialog, undo operation, keyboard shortcuts
119
+ - ✅ No need to record: "Changed button from blue to green" or "Added animation"
120
+
121
+ **3. Implementation-level technology choices: FREE, but MUST be recorded** 📝 (settled 2026-09-13)
122
+ - **What this covers**: choosing *which* API / library / mechanism satisfies a requirement whose FR does not name one. Example: the FR says "platform cryptography APIs"; whether the iOS side uses `CommonCrypto` cinterop or `CryptoKit` is an implementation choice — the FR is satisfied either way.
123
+ - **Why it is free**: the FR states WHAT, not HOW. Picking the mechanism is exactly the implement command's job.
124
+ - **Why it MUST be recorded**: the choice had **alternatives**, and a future reader hitting the same decision will otherwise re-litigate it (or pick differently and silently diverge). The rejected alternatives are the valuable part — they are what stops the same evaluation being redone.
125
+ - **WHERE — the location is fixed, not yours to pick** ⚠️: append to **`specs/research.md`**, under a heading of the form `## Addendum (<task-id>, <date>): <choice> — <alternative> vs <alternative>`. `research.md` is the artifact that carries *why*, and `plan.md`'s `### Architecture Patterns` already points at it with `See: research.md` anchors — so the reasoning lands where the design already says reasoning lives.
126
+ - **Do NOT** put it in `plan.md` (that records conclusions, not implementation findings — and this command MUST NOT modify plan.md), **do NOT** put it in `tasks.md` (it is not a task), and **do NOT** leave it only in a commit message or a `docs/implement/` note (neither is on the design's reference path).
127
+ - **Trigger — record when BOTH hold**: (a) you selected a mechanism where a reasonable alternative existed, **and** (b) the selection is not derivable from the FR text alone. Routine choices with no real alternative (which data class field name, which collection type) do **not** trigger it.
128
+ - **Minimum content**: what was chosen · what was rejected · why (with evidence, not assertion) · what was deferred or left unimplemented, and under what honest semantics.
129
+ - **SDD rationale**: `plan.md` carries the design conclusion ("use platform crypto APIs"); `research.md` carries the argument for how that conclusion was realised. Keeping the argument there preserves the plan/research division of labour instead of diluting the design artifact with implementation detail.
130
+
131
+ ### Decision Tree
132
+
133
+ ```
134
+ When implementing a task, ask:
135
+
136
+ Is this about:
137
+ ├─ Function/Flow (what the code does)?
138
+ │ ├─ YES → STRICT: Follow tasks.md exactly
139
+ │ └─ NO → Continue
140
+ │
141
+ ├─ UI/Interaction (how it looks/feels)?
142
+ │ ├─ YES → FREE: Use your best judgment
143
+ │ └─ NO → Continue
144
+ │
145
+ └─ Which mechanism satisfies the requirement (an API/library/approach the FR does not name)?
146
+ ├─ YES, and a real alternative existed → FREE to choose, **MUST record in specs/research.md**
147
+ │ (what · rejected · why · deferred — see Principle 3)
148
+ └─ NO → It's probably function/flow → Be strict
149
+ ```
150
+
151
+ ### Examples
152
+
153
+ **Function/Flow (STRICT)**:
154
+ - ❌ Wrong: Task says "Add user login" but you implement OAuth
155
+ - **Reason**: OAuth is a different login method, not in task
156
+ - ✅ Correct: Task says "Add user login" → Implement username/password login
157
+ - **Reason**: This is exactly what task specifies
158
+
159
+ **UI/Interaction (FREE)**:
160
+ - ✅ OK: Task says "Add button" → You choose red color, rounded corners
161
+ - ✅ OK: Task says "Create form" → You add validation hints
162
+ - ✅ OK: Task says "Show list" → You add pull-to-refresh
163
+ - ✅ No need to record any of these decisions
164
+
165
+ **Gray Areas (Use Judgment)**:
166
+ - ✅ Task: "Add error handling" → You add user-friendly error messages (FREE - UI)
167
+ - ✅ Task: "Handle network errors" → You implement retry logic (STRICT - function)
168
+ - ✅ Task: "Improve performance" → You optimize algorithms (STRICT - function)
169
+ - ✅ Task: "Make it responsive" → You choose breakpoints and layout (FREE - UI)
170
+
171
+ ### Key Improvements
172
+
173
+ - ✅ **SDD Compliance**: Implement executes specifications, doesn't make design decisions
174
+ - ✅ **Function/Flow**: Strict execution of tasks.md requirements
175
+ - ✅ **UI/Interaction**: Complete discretion for layout/style/interaction
176
+ - ✅ **No Recording**: Most UI/interaction decisions don't need documentation
177
+ - ✅ **Clear Separation**: Easy to decide what's strict vs. free
178
+ - ✅ **Workflow Integrity**: Problems go through issues feedback, not arbitrary changes
179
+
180
+ ### When in Doubt
181
+
182
+ - **Ask**: "Does this change WHAT the system does or HOW it looks?"
183
+ - WHAT = Function/Flow → Strict
184
+ - HOW = UI/Interaction → Free
185
+
186
+ - **Ask**: "Would this change require updating tasks.md?"
187
+ - Yes → It's probably a functional change → Don't do it
188
+ - No → It's probably a UI/interaction change → Go ahead
189
+
190
+ ---
191
+
192
+ ## Implementation Steps
193
+
194
+ 1. Run `.specpro/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
195
+
196
+
197
+
198
+ 1.5. **Quality gate: requirements.md validation** 🆕 (CRITICAL pre-flight check):
199
+
200
+ **Purpose**: Verify spec quality validation completed before implementation begins
201
+
202
+ **Rationale**: Implementation should only proceed after spec quality is validated. This prevents implementing requirements with quality issues.
203
+
204
+ a. **Check file exists**:
205
+ ```bash
206
+ # ⚠️ `$FEATURE_DIR`,不是本文件此前用的那个路径变量(T172):它在本文件里**出现 2 次、赋值 0 次**,
207
+ # 而 Step 1 指定的 `check-prerequisites.sh` 只输出 `FEATURE_DIR`。逐字执行时路径会塌成
208
+ # `/checklists/requirements.md` ⇒ 恒走 "File not found … EXIT 1" 分支,把人挡在实现之外。
209
+ # ⚠️ **此处刻意不写它的名字**:复核这条发现的命令是 `grep -c <那个名字> <本文件>`,而
210
+ # **返回 2 曾是该发现的证据** —— 留一个名字在注释里,复核就会永远非零,那条检查也就永远
211
+ # 分不清"已修"与"未修"。散文让位于可复核性。
212
+ if [[ ! -f "$FEATURE_DIR/checklists/requirements.md" ]]; then
213
+ ❌ ERROR: Spec quality validation not completed.
214
+
215
+ Required: specs/checklists/requirements.md (all items marked [x])
216
+ Current: File not found
217
+
218
+ Impact: Cannot proceed with implementation without quality validation
219
+
220
+ Next steps:
221
+ 1. Run /specpro-specify to complete the specification workflow
222
+ - This will automatically run clarify and qc
223
+ 2. Then run /specpro-implement again
224
+
225
+ For more info: /specpro-specify --help
226
+ EXIT 1
227
+ fi
228
+ ```
229
+
230
+ b. **Check all items passed**:
231
+ ```bash
232
+ # 完成度按「Status 取值」判定,不按复选框——模板即 `- [ ] **Status**: …`,
233
+ # 「诚实跳过」与「未做」在复选框上完全同形(工具缺陷 #10)
234
+ QC_UNRESOLVED=$(grep -E '^- \[[ x]\] \*\*Status\*\*:' "$FEATURE_DIR/checklists/requirements.md" 2>/dev/null \
235
+ | grep -vE '\*\*Status\*\*:[[:space:]]*(x|⊘[[:space:]]*Skipped)[[:space:]]*$' || true)
236
+ if [ -n "$QC_UNRESOLVED" ]; then
237
+ ❌ ERROR: Spec quality validation not completed.
238
+
239
+ Required: specs/checklists/requirements.md (all items marked [x])
240
+ Current: Some items are still unchecked [ ]
241
+
242
+ Impact: Cannot proceed with implementation with unresolved quality issues
243
+
244
+ Next steps:
245
+ 1. Check specs/checklists/requirements.md for specific issues
246
+ 2. Run /specpro-specify to complete quality validation
247
+ - This will automatically run clarify and qc to fix remaining issues
248
+ 3. Then run /specpro-implement again
249
+
250
+ For more info: Check specs/checklists/requirements.md for details
251
+ EXIT 1
252
+ fi
253
+
254
+ ✓ Quality validation passed - All quality criteria met
255
+ ```
256
+
257
+ c. **Log quality status**:
258
+ ```bash
259
+ echo "✓ Spec quality validation passed"
260
+ echo " All quality criteria met"
261
+ echo " Proceeding with implementation..."
262
+ ```
263
+
264
+ 1.6. **Commit gate: repository hooks installed** 🆕 (CRITICAL pre-flight check):
265
+
266
+ **Purpose**: Verify the repository's git hooks are actually installed before work begins.
267
+
268
+ **Rationale**: git hooks are **not version-controlled** — a fresh clone has none. Command
269
+ documents state that a pre-commit hook enforces the ledger's structural checks ("a violation
270
+ blocks the commit rather than being discovered later"). Shipping the hook source and its
271
+ installer solves only **getting it**; it does not solve **going and installing it**. This
272
+ step is the call site. **A check that is assumed to exist and does not is worse than no
273
+ check at all** — every reader who skipped the manual check did so with a clear conscience.
274
+
275
+ a. **Run the installer's self-check**:
276
+ ```bash
277
+ if ! scripts/install-git-hooks.sh --check; then
278
+ echo ""
279
+ echo "❌ ERROR: the commit gate is not installed in this clone."
280
+ echo ""
281
+ echo " Impact: the ledger's structural invariants and the shape-register"
282
+ echo " sync are NOT enforced at commit time. A commit can succeed"
283
+ echo " while leaving a structurally invalid artifact behind —"
284
+ echo " silently, which is the whole reason the gate exists."
285
+ echo ""
286
+ echo " Fix: run scripts/install-git-hooks.sh"
287
+ echo " (it installs into every repository in this workspace that"
288
+ echo " should carry the hook, and reports what it did)"
289
+ echo ""
290
+ exit 1
291
+ fi
292
+
293
+ echo "✓ git hooks installed — commit-time checks are live"
294
+ ```
295
+
296
+ b. **Why exit rather than warn** ⚠️: what this guards is **silent corruption**, and the
297
+ repair is one command that the message names. A warning inside a long report is passed
298
+ over — and a gate that is passed over is a statement, not a gate. ⚠️ **When the hook is
299
+ genuinely absent this stops a session that would otherwise have run to completion**:
300
+ that is intended, and the exit message is the whole mitigation.
301
+
302
+ 2. **Mandatory Cross-Artifact Analysis** ✨ NEW (enforced quality gate):
303
+
304
+ **Purpose**: Run comprehensive cross-artifact analysis before implementation begins
305
+
306
+ a. **Execute /specpro-analyze**:
307
+ - Run analysis automatically (mandatory pre-flight check)
308
+ - Parse analysis results for CRITICAL and HIGH severity issues
309
+ - Extract issue counts by category and severity
310
+
311
+ b. **Check for CRITICAL issues**:
312
+ - If CRITICAL issues found:
313
+ * Display blocking message
314
+ * Show critical issues summary
315
+ * Require user acknowledgment before proceeding
316
+
317
+ ```markdown
318
+ 🔴 CRITICAL ISSUES DETECTED
319
+
320
+ **Cannot proceed with implementation until CRITICAL issues are resolved**
321
+
322
+ **Critical Issues** (CRITICAL):
323
+ 1. [Issue summary]
324
+ - Source: [Constitution/Principle/Standard if applicable]
325
+ - Impact: [Why this blocks implementation]
326
+ - Recommendation: [How to fix]
327
+
328
+ **Options**:
329
+ 1. Fix issues now → Run the OWNING command's --review-issues (see the note below), then re-run /specpro-implement
330
+ 2. Halt implementation → Fix issues manually, then re-run /specpro-implement
331
+ 3. Proceed with caution → Type 'UNDERSTAND' to acknowledge risks and proceed anyway
332
+
333
+ Your choice (1/2/3):
334
+ ```
335
+
336
+ - If user chooses 1: Run the owning command's `--review-issues`, then re-evaluate
337
+ - If user chooses 2: Halt execution
338
+ - If user chooses 3: Require 'UNDERSTAND' acknowledgment, then proceed to step 2c
339
+
340
+ ⚠️ **There is no auto-fix path here** [settled 2026-09-18, `ISS-141` / `T184`]: option 1 used to read "Run /specpro-analyze --auto-fix". That path is gone — `/specpro-analyze` **reports, it does not repair**. The repair belongs to the command that **owns** the artifact the finding sits in, and `/specpro-analyze` decides *which* command that is per finding. ⚠️ **That mapping has one owner — the routing table in `/specpro-analyze`'s Finding Registration step — and it is POINTED AT here, not restated** (a second copy is a second source, and the two diverge silently: FR-025 / 原则 II).
341
+ ⚠️ **Why this is not a matter of preference**: a command that repairs what it judged has spent the verdict (**Principle III**), and `/specpro-analyze`'s write surface does not include those artifacts (**FR-051**) — so an option that offers the repair offers a boundary violation, which is why it was removed rather than made conditional.
342
+
343
+ c. **Check for HIGH severity issues** (if no CRITICAL):
344
+ - If HIGH issues found:
345
+ * Display warning message
346
+ * Show high-severity issues summary
347
+ * Require acknowledgment before proceeding
348
+
349
+ ```markdown
350
+ ⚠️ HIGH SEVERITY ISSUES DETECTED
351
+
352
+ **Recommended**: Address HIGH issues before implementation for best results
353
+
354
+ **High Issues** (HIGH):
355
+ 1. [Issue summary]
356
+ - Impact: [Potential problems]
357
+ - Recommendation: [How to fix]
358
+
359
+ **Options**:
360
+ 1. Fix now → Run the OWNING command's --review-issues (same routing as option 1 above), then re-run /specpro-implement
361
+ 2. Proceed → Type 'PROCEED' to acknowledge and continue
362
+ 3. Details → Run /specpro-analyze for full report
363
+
364
+ Your choice (1/2/3):
365
+ ```
366
+
367
+ d. **Log analysis status for implementation**:
368
+ - Store analysis results for use during implementation
369
+ - Highlight risk areas when implementing related features
370
+ - Track which requirements have coverage issues
371
+
372
+ 3. **Check quality validation status** ✨ (enhanced with content validation):
373
+
374
+ **Purpose**: Verify quality checklist status AND validate that issues are addressed in plan/tasks
375
+
376
+ a. **Check if checklists/ directory exists**:
377
+ - If not, proceed to step 3 (no quality gate)
378
+ - If yes, continue to validation
379
+
380
+ b. **Scan the quality checklist** — ⚠️ **`FEATURE_DIR/checklists/requirements.md`, by name** (`T233`/`ISS-206`):
381
+ - This step used to read *"Scan all *.md files in FEATURE_DIR/checklists/"*. ⚠️ **Only one producer emits the fields read below** — `templates/requirements-template.md`. `templates/checklist-template.md` **emits none of them** (`**Total Items**` / `**Passed**` / `**Failed**` / the per-item `**Status**` rows) ⇒ on every other checklist this step reads **nothing**, and "nothing read" prints the same as "all passed". A directory-wide scan whose fields exist in one file is a scan whose scope is wider than its predicate — narrow the **scope**, never the fields. ⚠️ **If a second checklist template ever gains those fields, widen this back — and widen it by the field, not by the directory.**
382
+ - Read the checklist's **own** fields — verbatim, and only these:
383
+ * `**Status**`: `PASS` | `BLOCK` — the producer sets `PASS` ⟺ `**Failed**` == 0
384
+ * `**Total Items**` · `**Passed**` · `**Failed**`
385
+ * per-item rows: `- [ ] **Status**: x | ⊘ Skipped | ✗ Failed`
386
+ * Extract specific problems (not just checkbox counts)
387
+ - ⚠️ Do **not** look for `Overall Quality`, an `N/M` score, `❌ FAIL` or
388
+ `⚠️ WARNING`: `templates/requirements-template.md` emits none of them ⇒ a
389
+ reader keyed on them finds nothing on **every** checklist and reports
390
+ "all quality checks passed", which is indistinguishable from a clean pass.
391
+ - The blocking set = the rows whose per-item value is `✗ Failed`
392
+ - The `⊘ Skipped` rows are **non-blocking** (the template's rule: an honest
393
+ skip is a conclusion, not a debt) — surface them, never gate on them
394
+
395
+ c. **Parse quality issues from checklist** (NEW):
396
+ - Read `FEATURE_DIR/checklists/requirements.md` — ⚠️ **not "(or equivalent)"**: no other checklist in this toolchain carries these fields (`b` above).
397
+ - Parse for specific quality issues. The issue text is what the item's
398
+ **explanation line** says; the value on the row is only the status:
399
+ * ✗ Failed example: "Critical module lacks test coverage"
400
+ - Problem: Test coverage below required threshold
401
+ - Location: [Module/function reference]
402
+ * ⊘ Skipped example: "Edge cases not identified"
403
+ - Problem: this item yields no derivation source on this project;
404
+ recorded as an honest skip, **not** as a pending improvement
405
+
406
+ d. **Verify issues are addressed in plan.md/tasks.md** (NEW):
407
+ - Load plan.md and tasks.md (if exist)
408
+ - For each `✗ Failed` item:
409
+ * Search plan.md for design addressing the issue
410
+ * Search tasks.md for tasks addressing the issue
411
+ * Example: For "Test coverage insufficient" FAIL:
412
+ - Check if plan.md includes test strategy
413
+ - Check if tasks.md includes test tasks for the module
414
+ - Mark as "Addressed" or "Unaddressed"
415
+ - ⚠️ `⊘ Skipped` items are **not** verified for coverage: they assert that
416
+ nothing here needs covering.
417
+
418
+ e. **Generate enhanced status table** (columns are the checklist's own fields):
419
+ ```text
420
+ | Checklist | Total | Passed | Skipped | Failed | Issues Addressed | Status |
421
+ |-----------|-------|--------|---------|--------|------------------|--------|
422
+ | requirements.md | 12 | 10 | 1 | 1 | 0/1 | ⛔ BLOCK |
423
+ ```
424
+ ⚠️ **The table has one row because the scan has one subject** (`b` above) **and its numbers are illustrative** — do not read them back as this project's counts (the live values are the checklist's own `**Total Items**` / `**Passed**` / `**Failed**`). This example used to show `ux.md` and `security.md` rows — files **no template in this toolchain produces**, which is how the wider scan stayed invisible: the example made the reader believe there was a family of checklists emitting the same fields.
425
+ - `Status` is the checklist's own `**Status**` value, copied — not re-derived
426
+ - `Skipped` is shown for visibility and is **not** an input to that value
427
+
428
+ f. **Overall status** — carry the checklists' verdicts, do not re-derive one:
429
+ - **PASS**: every checklist's `**Status**` is `PASS`
430
+ - **BLOCK**: any checklist's `**Status**` is `BLOCK`
431
+ ⚠️ There is no third tier, and no "unaddressed" variant: the checklist is
432
+ two-valued. `Passed < Total Items` on its own is **not** a reason to warn —
433
+ the difference is `⊘ Skipped` rows, which its template declares non-blocking;
434
+ warning on them would push the reader to "fix" an honest skip.
435
+
436
+ g. **Handle quality validation results** (ENHANCED):
437
+
438
+ **Case 1: All checklists PASS** (ideal scenario)
439
+ - Display status table showing all passed
440
+ - Display message: "✓ All quality checks passed. Proceeding with implementation..."
441
+ - Automatically proceed to step 3
442
+
443
+ **Case 2: Any checklist BLOCKs** — the only non-pass case, because the
444
+ checklist's `**Status**` is two-valued (`PASS` ⟺ `**Failed**` == 0).
445
+ ⚠️ `⊘ Skipped` rows never reach this case: skips are non-blocking.
446
+ - Display status table showing the blocking failures
447
+ - Display the blocking issues, plus the skipped rows for visibility:
448
+
449
+ ```markdown
450
+ 🛑 BLOCKING ISSUES DETECTED
451
+
452
+ **Status**: BLOCK (the checklist's own verdict — copied, not re-derived)
453
+ **Issues Addressed**: X of Y
454
+
455
+ **Blocking (✗ Failed)**:
456
+ 1. "Critical module lacks test coverage"
457
+ - Requirement: Project requires [specific %] test coverage for critical modules
458
+ - Location: [Module name/reference]
459
+ - Plan.md: No test strategy found
460
+ - Tasks.md: No test tasks found
461
+ - **Risk**: Low test coverage, potential bugs in critical path
462
+
463
+ **Skipped (⊘)** — non-blocking; these need no risk acknowledgment:
464
+ 2. "Edge cases not identified" (yields no derivation source on this project)
465
+
466
+ **Addressed Issues** (Resolved):
467
+ 3. ✓ "Success criteria are measurable" (addressed in plan.md)
468
+ ```
469
+
470
+ - **The checklist's own rule is that a BLOCK must be fixed**: its template
471
+ reads "Cannot proceed to plan/tasks/implement until all items pass". So the
472
+ default is to stop; proceeding is an explicit, acknowledged exception.
473
+ - **CRITICAL: Require explicit risk acknowledgment** to proceed:
474
+ ```markdown
475
+ **Some quality issues were NOT addressed in plan.md or tasks.md**.
476
+
477
+ This means:
478
+ - The design may not account for these quality concerns
479
+ - The implementation may have quality deficiencies
480
+ - You may need to re-plan or re-task after implementation
481
+
482
+ **To proceed despite unaddressed issues**, you must:
483
+ 1. Review each unaddressed issue above
484
+ 2. Acknowledge the risks
485
+ 3. Type 'UNDERSTAND' to confirm you accept these risks
486
+
487
+ Your response:
488
+ ```
489
+
490
+ - Wait for user to type 'UNDERSTAND'
491
+ - If user types 'UNDERSTAND':
492
+ * Display: "✓ Risks acknowledged. Proceeding with implementation..."
493
+ * Proceed to step 3
494
+ - If user types anything else:
495
+ * Display: "Implementation cancelled. Please address quality issues first."
496
+ * Halt execution
497
+
498
+ h. **Log quality status for implementation** (NEW):
499
+ **Purpose**: Store quality issues for use during task execution
500
+
501
+ **Store as variables** (in memory, not files):
502
+ - `QUALITY_STATUS`: The checklists' verdict — `"PASS"` / `"BLOCK"` (two values
503
+ only; see **f**). `"BLOCK"` here means the operator typed `UNDERSTAND` and
504
+ the run proceeded anyway, so the unaddressed issues below are live.
505
+ - `UNADDRESSED_ISSUES`: The `✗ Failed` items that **d** marked "Unaddressed"
506
+ — one entry per issue, quoted from the item's explanation line
507
+ - `COVERAGE_GAPS`: The keywords under which those unaddressed issues fall
508
+ - ⚠️ There is no third variable: the retired warning tier was the only source
509
+ a "non-blocking issue" list could have had, and a list nobody reads is the
510
+ same as not storing it.
511
+
512
+ **How to use during implementation** (see Step 9):
513
+ - Before executing each task, scan task description for keywords
514
+ - Match keywords against `UNADDRESSED_ISSUES` and `COVERAGE_GAPS`
515
+ - If match found: Display context-aware warning
516
+
517
+ **Example workflow**:
518
+ ```markdown
519
+ Step 3 (Quality validation) stores:
520
+ - QUALITY_STATUS = "BLOCK" (the operator typed UNDERSTAND to get here)
521
+ - UNADDRESSED_ISSUES = ["Critical module lacks test coverage"]
522
+ - COVERAGE_GAPS = ["streaming", "error handling"]
523
+
524
+ Step 9 (Task execution):
525
+ Task: "Implement streaming data processing"
526
+
527
+ System checks:
528
+ - Task contains "streaming" → Matches COVERAGE_GAPS
529
+ - Issue exists: "Critical module lacks test coverage"
530
+
531
+ Display warning (use PROJECT_LANGUAGE):
532
+ "⚠️ QUALITY NOTE: This task involves streaming, and quality check
533
+ flagged 'Critical module lacks test coverage' — which the operator
534
+ acknowledged as an accepted risk. Consider adding tests for:
535
+ - Network interruption
536
+ - Data corruption
537
+ - Buffer overflow"
538
+ ```
539
+
540
+ **Keyword matching examples**:
541
+ - Task mentions "streaming" → Check for "Edge cases" issue
542
+ - Task mentions "performance" → Check for "Performance metrics" issue
543
+ - Task mentions "authentication" → Check for "Security" issues
544
+ - Task mentions "error handling" → Check for "Edge cases" issue
545
+
546
+ **DO NOT**:
547
+ - Store in files (not needed between runs)
548
+ - Block execution on warnings (only BLOCK status should halt)
549
+ - Re-run quality checks (already done in Step 3)
550
+
551
+ 4. **Load project constitution** 📜 [CRITICAL - DECISION CONTEXT]:
552
+ **Purpose**: Load project preferences BEFORE any user interaction
553
+ **Why Early**: Language preference affects ALL user-facing messages
554
+
555
+ a. **Check if constitution exists**:
556
+ - Look for `specs/constitution.md`
557
+ - If not found: Use defaults (English language)
558
+ - If found: Proceed to extract language setting
559
+
560
+ b. **Extract language preference** 🌐 [AFFECTS ALL USER INTERACTION]:
561
+ - ⚠️ **读宪法实际声明的那个字段**(T172 修正):宪法写的是 **`**Artifact Language**: <code>`**,
562
+ 而本节此前叫它 `**Language Preference**` —— **一个字段名、两套标签**:照本节去 `grep`
563
+ 那个名字,在**任何**合规的宪法里都**零命中**,于是永远回落到默认值,而**没有任何东西会报错**。
564
+ - 取值优先级:① 宪法里 `**Artifact Language**: <code>` 的值 · ② 缺该字段时,检查同文件有无
565
+ `**Language Preference**:`(历史别名,容错读取)· ③ 两者皆无 ⇒ 默认 `en`
566
+ - Store as `PROJECT_LANGUAGE` variable
567
+
568
+ **Use this for**:
569
+ - All user-facing messages (errors, warnings, progress reports, menus)
570
+ - Interactive mode selection menu text
571
+ - Development process documentation (Step 9.d)
572
+ - Task completion messages
573
+
574
+ **Example**:
575
+ - If `PROJECT_LANGUAGE = zh`:
576
+ * Menu: localized "Select Execution Mode" text (in Chinese)
577
+ * Progress: localized "Completed: [task]" text (in Chinese)
578
+ * Errors: localized "Quality issues detected" warning text (in Chinese)
579
+ - If `PROJECT_LANGUAGE = en`: Display in English
580
+ - If `PROJECT_LANGUAGE = ja`: Display in Japanese
581
+
582
+ **Important**:
583
+ - Technical terms remain in English (API, HTTP, JSON, protocol identifiers, etc.)
584
+ - Code and file paths remain in English
585
+ - Section headers remain in English
586
+
587
+ c. **Display language confirmation**:
588
+ ```markdown
589
+ 🌐 Project Language: [language name]
590
+
591
+ All user interaction will use this language.
592
+ ```
593
+
594
+ d. **Note on testing and quality principles**:
595
+ - Constitution principles (testing, security, performance, etc.) primarily influence spec/plan/tasks phases
596
+ - Implement phase TRUSTS that tasks.md already reflects constitutional requirements
597
+ - Implement follows task order: if test task exists before implementation task, execute test first
598
+ - No need to validate constitutional compliance during implementation (already validated in earlier phases)
599
+
600
+ 5. **Scan for first pending task** 🎯 [TASK DISCOVERY]:
601
+ **Purpose**: Find the next task to execute BEFORE loading detailed context
602
+
603
+ a. **Read tasks.md and scan**:
604
+ - Read from top to bottom
605
+ - Skip all tasks marked `[x]` (completed)
606
+ - Stop at first task marked `[ ]` (pending)
607
+ - Extract task details:
608
+ * Phase (Setup/Foundational/US-XXX/Polish)
609
+ * Task description
610
+ * Parallel marker `[P]` (if present)
611
+ * File paths mentioned in task
612
+ * FR annotation `(FR-XXX)` (if present)
613
+
614
+ b. **Display next task preview**:
615
+ ```markdown
616
+ 📍 Next Pending Task Found
617
+
618
+ **Phase**: [phase name]
619
+ **Task**: [task description]
620
+ **Files**: [file paths from task]
621
+ ```
622
+
623
+ 6. **Interactive execution mode selection** 🎯 [USER EXPERIENCE]:
624
+ **Purpose**: Let user choose how many tasks to execute in this session
625
+
626
+ **Skip this step** if user provided arguments (`$ARGUMENTS` is not empty)
627
+
628
+ a. **Analyze task status**:
629
+ - Scan tasks.md and count:
630
+ * Total tasks: X
631
+ * Completed tasks [x]: Y
632
+ * Pending tasks [ ]: Z = X - Y
633
+ * Overall progress: Y/X (Z% complete)
634
+
635
+ b. **Display execution mode menu**:
636
+ ```markdown
637
+ 📋 Implementation Session Setup
638
+
639
+ **Task Status**:
640
+ - Total tasks: X
641
+ - Completed: Y (Z%)
642
+ - Remaining: Z
643
+
644
+ **Select Execution Mode**:
645
+
646
+ 1️⃣ **Fix Product Defects** (N pending in specs/fix-tasks.md) (Recommended when offered)
647
+ - Execute FT-XXX fix tasks dispatched by /specpro-test-implement
648
+ - Defects before features: fixes unblock blocked test tasks
649
+ - ONLY shown when specs/fix-tasks.md exists with pending [ ] FT items;
650
+ when absent, omit this option and number the remaining options 1-5
651
+
652
+ 2️⃣ **Single Task** (Recommended for first-time users)
653
+ - Execute 1 task, then pause
654
+ - Safest option, prevents context overflow
655
+ - You'll be prompted to continue after each task
656
+ - Estimated time: 2-5 minutes
657
+
658
+ 3️⃣ **Small Batch** (3 tasks)
659
+ - Execute next 3 tasks, then pause
660
+ - Balanced option for efficiency and safety
661
+ - Good for small, related tasks
662
+ - Estimated time: 5-15 minutes
663
+
664
+ 4️⃣ **Medium Batch** (5 tasks)
665
+ - Execute next 5 tasks, then pause
666
+ - For experienced users who know task size is small
667
+ - Use with caution if tasks are large
668
+ - Estimated time: 10-25 minutes
669
+
670
+ 5️⃣ **Phase Execution**
671
+ - Execute all remaining tasks in current phase
672
+ - Efficient for completing entire phase
673
+ - Risk: May execute many tasks (check phase size first)
674
+ - Estimated time: Varies (see phase details below)
675
+
676
+ 6️⃣ **Continue All** (⚠️ ADVANCED ONLY)
677
+ - Execute ALL remaining tasks (Z tasks)
678
+ - WARNING: High risk of context overflow!
679
+ - Only use if Z < 10 or you have large context window
680
+ - Estimated time: Very long (Z × 3 minutes)
681
+
682
+ **Current Phase**: [Setup/Foundational/US-XXX/Polish]
683
+ **Tasks in current phase**: N
684
+ **Completed in phase**: M
685
+ **Remaining in phase**: N - M
686
+
687
+ ⚠️ **选项 1️⃣ 缺席时,其余各项整体上移一位**(T172 修正):本节此前只在上面的说明里写了
688
+ 「omit this option and number the remaining options 1-5」,而**下面这组标签是写死的 2️⃣–6️⃣**
689
+ —— 于是"说明"与"菜单"在**同一屏里**对不上:说明说按 1–5 选,屏幕上只有 2–6。
690
+ ⇒ 1️⃣ 不在时,屏幕上印的是 **1️⃣ Single Task · 2️⃣ Small Batch · 3️⃣ Medium Batch ·
691
+ 4️⃣ Phase Execution · 5️⃣ Continue All**。
692
+
693
+ Your choice (1-6, or 1-5 when no fix tasks are pending — see the note above):
694
+ ```
695
+
696
+ c. **Handle user selection**:
697
+ - **Choice 1 (Fix Product Defects, only when offered)**: Set `execution_mode = "fix"` (execute ALL pending FT items in specs/fix-tasks.md — procedure in Step 9.a2)
698
+ - **Choice 2 (Single Task)**: Set `execution_mode = "once"`, `task_limit = 1`
699
+ - **Choice 3 (Small Batch)**: Set `execution_mode = "count"`, `task_limit = 3`
700
+ - **Choice 4 (Medium Batch)**: Set `execution_mode = "count"`, `task_limit = 5`
701
+ - **Choice 5 (Phase Execution)**: Set `execution_mode = "phase"`, `target_phase = current_phase`
702
+ - **Choice 6 (Continue All)**:
703
+ * If Z >= 20: Show warning:
704
+ ```markdown
705
+ ⚠️ WARNING: You have Z remaining tasks.
706
+ Executing all tasks will likely exceed context limits.
707
+
708
+ Recommended: Choose option 2 or 3 for batch execution.
709
+
710
+ Do you want to:
711
+ 1. Proceed with all tasks (understood the risk)
712
+ 2. Switch to Small Batch (3 tasks)
713
+ 3. Switch to Medium Batch (5 tasks)
714
+
715
+ Your choice (1-3):
716
+ ```
717
+ * If user confirms 1: Set `execution_mode = "continue"`, `task_limit = infinity`
718
+ * If user chooses 2 or 3: Set corresponding mode
719
+
720
+ - **Invalid input**: Display menu again
721
+
722
+ - **Note**: ALL modes are subject to the **Checkpoint Gate** (Step 9.e) — when a User Story phase boundary is crossed and test-plan relevance is HIGH, execution pauses even in Phase/Continue modes. This protects the optimal timing for `/specpro-test-plan` (run tests planning right after each story's implementation lands).
723
+
724
+ d. **Confirm execution plan**:
725
+ ```markdown
726
+ ✅ Execution Plan Confirmed
727
+
728
+ **Mode**: [Single Task / Small Batch (3 tasks) / ...]
729
+ **Tasks to execute**: [N]
730
+ **Current phase**: [phase name]
731
+
732
+ Starting implementation...
733
+ ```
734
+
735
+ 7. **Load task-specific context** 🎯 [ON-DEMAND]:
736
+ **Purpose**: Load ONLY the information needed for current task(s)
737
+ **Key Principle**: Read files based on task requirements, not preemptively
738
+ **Note**: Constitution already loaded in Step 4, no need to reload here
739
+
740
+ a. **Always load** (required for every task):
741
+ - **plan.md → `## Technical Context`** — the ONLY unconditionally-loaded plan.md section: language/version, dependencies, target platform are general background for any task.
742
+ - **tasks.md**: Task list and current task details
743
+
744
+ a2. **plan.md's other sections: load by keyword, same mechanism as (b)** ⚠️ [settled 2026-09-13]:
745
+ Do **not** load the whole of plan.md. plan.md is split into **Part I (machine-read)** and **Part II (human-read)**, and they load differently:
746
+
747
+ | `specs/plan.md` section | Load when the task description / file paths mention |
748
+ |-----------------|------------------------------------------------------|
749
+ | `## Project Structure` → module layout | creating or placing a file · any path |
750
+ | `## Architecture` → `### Shared/Platform Boundary Declaration` | a layer · a source set · expect/actual · where a file belongs |
751
+ | `## Architecture` → `### Layered Architecture` | a layer · layer ownership · a MUST/MUST NOT constraint |
752
+ | `## Architecture` → the pattern / interaction / constraint the task touches | that pattern's, interaction's or constraint's components |
753
+ | `## Architecture` → `### Protocol Codec Design Artifacts` | a protocol point · encoding/decoding · a byte stream · a wire format |
754
+ | `## Quality Targets` | the task carries `[Quality]`, or mentions coverage |
755
+
756
+ - **Match by keyword in the task text — never by task "type".** Tasks cross boundaries constantly: one task may create a file *and* implement a pattern *and* carry a test obligation. A keyword scan collects every section the task actually touches; a type-based mapping would silently drop the ones it does not anticipate.
757
+ - **`plan-overview.md` is NEVER loaded** — it is a **separate file** holding the human-read half (`## Summary`, `## System Overview`, `## Constitution Check`, `## Implementation Plan`, `## Documentation Layout`, `## Complexity Tracking`). None of them is an input to executing a task. The file split is what makes this structural: those sections are not *in* the file you read, so no whole-file load can pull them in by accident.
758
+ - Why this shape (rather than "always load plan.md"): a whole-file load puts the human sections into every task's context while the sections a task genuinely needs are read anyway — the cost is noise, and the benefit was never measurable. The three earlier statements in this step disagreed with each other (`Always load plan.md: Tech stack, architecture, project structure` / `Don't read entire files` / the `plan.md (full …)` example); this replaces all three.
759
+
760
+ b. **Load based on task analysis** 📋:
761
+ Scan task description and file paths for keywords:
762
+
763
+ **If task mentions data entities** (User, Product, Order, etc.):
764
+ * Read **data-model.md** (IF EXISTS)
765
+ * Extract ONLY relevant entities and relationships
766
+ * Example: Task says "Implement User authentication" → Read User entity only
767
+
768
+ **If task mentions API endpoints** (POST /users, GET /products, etc.):
769
+ * Read **contracts/** directory (IF EXISTS)
770
+ * Extract ONLY related API contracts
771
+ * Example: Task says "Implement login API" → Read auth-related contracts
772
+
773
+ **If task mentions complex algorithms** (encoding, compression, crypto, parsing):
774
+ * Read **research.md** (IF EXISTS)
775
+ * Extract ONLY relevant technical decisions
776
+ * Example: Task says "Implement the decoder" → Read the encoding decisions
777
+
778
+ **If task mentions integration** (connect to service, external API):
779
+ * Read **quickstart.md** (IF EXISTS)
780
+ * Extract ONLY relevant integration scenarios
781
+
782
+ **Note**: ⚠️ **Nothing further is loaded here.** Step 4 reads the constitution for its language setting (`PROJECT_LANGUAGE`) and states the division of labour explicitly: implementation **trusts** that `tasks.md` already reflects the constitutional requirements, so no test-requirements variable exists to consult. This note used to read *"use `TESTING_RULES` variable"* — that variable **has no producer anywhere in the tree** (`T233`/`ISS-206`), i.e. it named a binding that was never made. ⚠️ **Do not reintroduce it by defining it**: the thing it would carry is already discharged upstream (Step 4.d).
783
+
784
+ c. **Smart extraction strategy** ✨:
785
+ - **Don't read entire files**: Extract only relevant sections — this applies to **plan.md as much as to any other file** (see a2: only `Technical Context` is unconditional)
786
+ - **Use keyword matching**: Search for entity names, API paths, feature names
787
+ - **Build minimal context**: Include only what's needed for this task
788
+ - **Cache for reuse**: If executing multiple tasks, cache loaded sections
789
+
790
+ d. **Example**:
791
+ ```
792
+ Task: "Implement User authentication with JWT tokens"
793
+
794
+ Context loaded:
795
+ ✅ plan.md → Technical Context only (unconditional)
796
+ ✅ plan.md → Architecture → Boundary + the crypto/security constraint
797
+ (keywords: authentication, credentials)
798
+ ✅ tasks.md (current task)
799
+ ✅ data-model.md → User entity only (not all 50 entities)
800
+ ✅ contracts/ → auth contracts only (not all API endpoints)
801
+ ✅ research.md → JWT/auth decisions only
802
+ ❌ plan-overview.md → never loaded (separate file, human-read half)
803
+ ❌ quickstart.md → Not needed (not integration task)
804
+ ❌ Other entities → Not needed (not mentioned in task)
805
+ ```
806
+
807
+ e. **Context summary for execution**:
808
+ ```markdown
809
+ 📚 Task Context Loaded
810
+
811
+ **Core**: plan.md → Technical Context (+ the Part I sections matched this task)
812
+ **Entities**: [list of relevant entities]
813
+ **APIs**: [list of relevant contracts]
814
+ **Decisions**: [list of relevant research items]
815
+ ```
816
+
817
+ 8. **Project Setup Verification**:
818
+ - **REQUIRED**: Create/verify ignore files based on actual project setup:
819
+
820
+ **Detection & Creation Logic**:
821
+ - Check if the following command succeeds to determine if the repository is a git repo (create/verify .gitignore if so):
822
+
823
+ ```sh
824
+ git rev-parse --git-dir 2>/dev/null
825
+ ```
826
+
827
+ - Check if Dockerfile* exists or Docker in plan.md → create/verify .dockerignore
828
+ - Check if .eslintrc* exists → create/verify .eslintignore
829
+ - Check if eslint.config.* exists → ensure the config's `ignores` entries cover required patterns
830
+ - Check if .prettierrc* exists → create/verify .prettierignore
831
+ - Check if .npmrc or package.json exists → create/verify .npmignore (if publishing)
832
+ - Check if terraform files (*.tf) exist → create/verify .terraformignore
833
+ - Check if .helmignore needed (helm charts present) → create/verify .helmignore
834
+
835
+ **If ignore file already exists**: Verify it contains essential patterns, append missing critical patterns only
836
+ **If ignore file missing**: Create with full pattern set for detected technology
837
+
838
+ **Common Patterns by Technology** (from plan.md tech stack):
839
+ - **Node.js/JavaScript/TypeScript**: `node_modules/`, `dist/`, `build/`, `*.log`, `.env*`
840
+ - **Python**: `__pycache__/`, `*.pyc`, `.venv/`, `venv/`, `dist/`, `*.egg-info/`
841
+ - **Java**: `target/`, `*.class`, `*.jar`, `.gradle/`, `build/`
842
+ - **C#/.NET**: `bin/`, `obj/`, `*.user`, `*.suo`, `packages/`
843
+ - **Go**: `*.exe`, `*.test`, `vendor/`, `*.out`
844
+ - **Ruby**: `.bundle/`, `log/`, `tmp/`, `*.gem`, `vendor/bundle/`
845
+ - **PHP**: `vendor/`, `*.log`, `*.cache`, `*.env`
846
+ - **Rust**: `target/`, `debug/`, `release/`, `*.rs.bk`, `*.rlib`, `*.prof*`, `.idea/`, `*.log`, `.env*`
847
+ - **Kotlin**: `build/`, `out/`, `.gradle/`, `.idea/`, `*.class`, `*.jar`, `*.iml`, `*.log`, `.env*`
848
+ - **C++**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.so`, `*.a`, `*.exe`, `*.dll`, `.idea/`, `*.log`, `.env*`
849
+ - **C**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.a`, `*.so`, `*.exe`, `Makefile`, `config.log`, `.idea/`, `*.log`, `.env*`
850
+ - **Swift**: `.build/`, `DerivedData/`, `*.swiftpm/`, `Packages/`
851
+ - **R**: `.Rproj.user/`, `.Rhistory`, `.RData`, `.Ruserdata`, `*.Rproj`, `packrat/`, `renv/`
852
+ - **Universal**: `.DS_Store`, `Thumbs.db`, `*.tmp`, `*.swp`, `.vscode/`, `.idea/`
853
+
854
+ **Tool-Specific Patterns**:
855
+ - **Docker**: `node_modules/`, `.git/`, `Dockerfile*`, `.dockerignore`, `*.log*`, `.env*`, `coverage/`
856
+ - **ESLint**: `node_modules/`, `dist/`, `build/`, `coverage/`, `*.min.js`
857
+ - **Prettier**: `node_modules/`, `dist/`, `build/`, `coverage/`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
858
+ - **Terraform**: `.terraform/`, `*.tfstate*`, `*.tfvars`, `.terraform.lock.hcl`
859
+ - **Kubernetes/k8s**: `*.secret.yaml`, `secrets/`, `.kube/`, `kubeconfig*`, `*.key`, `*.crt`
860
+
861
+ 9. **Incremental task parsing and execution** 🔄 [OPTIMIZED]:
862
+ **Purpose**: Execute task(s) using task-specific context loaded in Step 7 and language preference from Step 4
863
+
864
+ a. **Use execution mode from Step 6** (or parse from arguments):
865
+ - If Step 5 set `execution_mode` and `task_limit`: Use those values
866
+ - Else if `$ARGUMENTS` provided: Parse from arguments
867
+ * `--once`: Set `execution_mode = "once"`, `task_limit = 1`
868
+ * `--count N`: Set `execution_mode = "count"`, `task_limit = N`
869
+ * `--continue`: Set `execution_mode = "continue"`, `task_limit = infinity`
870
+ * `--phase PHASE`: Set `execution_mode = "phase"`, `target_phase = PHASE`
871
+ - Else (should not happen): Default to `execution_mode = "once"`, `task_limit = 1`
872
+
873
+ a2. **Fix-task execution** 🛠️ [NEW — when `execution_mode = "fix"`]:
874
+ **Purpose**: Execute product-defect fix tasks dispatched by `/specpro-test-implement` in `specs/fix-tasks.md`. Two-AI separation of duties: the testing AI never fixes code; this command fixes code but never re-judges tests.
875
+
876
+ - Load `specs/fix-tasks.md`. If absent or no pending `[ ]` FT items → report "no pending fix tasks" and fall through to normal task execution
877
+ - **Pre-enqueue triage** ⚠️ [settled 2026-09-13, TOOL-010]: **before** working an FT, decide whether this command can actually discharge its `Validates`. If discharging it would require **modifying test code**, or any artifact **outside this command's jurisdiction**, do **not** start it — mark it `<unclosable by this command>` and move on. Rationale: the exit below is binary (PASS → `[x]`, FAIL → `[ ]`), so an FT that *cannot* pass by construction pins the queue head with a `[ ]` that no amount of fixing will clear, and every `--fix-defects` run re-does the same diagnosis. The observed case was an FT whose `Validates` depended on a test-side defect while this command is forbidden from touching test code — FAIL was guaranteed.
878
+ - For each pending FT-XXX (top to bottom):
879
+ * Load its Evidence / Location / Fix Direction / Validates / Blocked-Tests; locate the root cause in PRODUCT code — the fix target is code, NOT the test
880
+ * Fix the product code: Function/Flow STRICT to the FT's Validates; no scope creep; NEVER modify the source test's code or its assertions
881
+ * Run the Validates-named test: PASS → mark the FT `- [x]` in fix-tasks.md; FAIL → leave `[ ]`, display output, iterate the fix or report
882
+ * **Legal terminal states** ⚠️ [settled 2026-09-13, TOOL-010]: there are **three**, not two — and the third must be stated, never improvised:
883
+ 1. **Fixed** — `Validates` passes → mark `[x]`.
884
+ 2. **Not yet fixed** — the fix is within this command's power; FAIL is informative → leave `[ ]` **with the failing output** and iterate.
885
+ 3. **Not closable here** — the defect is real but its resolution lies outside this command (test-side defect, missing fixture, another owner's artifact). Do **not** leave a bare `[ ]` that reads like "still working on it": leave `[ ]`, **append a diagnostic note to the FT** recording what was found and why this command cannot close it, and **report it for hand-off** (`/specpro-test-plan` → `/specpro-test-implement`, or whichever owner the note names). This keeps the queue honest: the next run can skip it in one glance instead of re-deriving the diagnosis.
886
+ * Write boundary ⚠️ [CRITICAL]: mark ONLY the FT checkbox in fix-tasks.md. NEVER write `specs/test-tasks.md` — task checkboxes, coverage matrix, and Progress Statistics are `/specpro-test-implement`'s jurisdiction. Re-verification and test-task write-back happen when the user runs `/specpro-test-implement`
887
+ - After the loop: report fixed / still-open / **not-closable-here** counts, name the FTs in the third bucket with their hand-off target, and remind: "run /specpro-test-implement to re-verify the fixes and complete test-task bookkeeping"
888
+ ⚠️ **`<unclosable by this command>` 的读取点就是这一句**(T172 / audit finding:「标记被定义,
889
+ 却没有任何读取点」):上面第 3 条终态要求给这类 FT 打这个标记并附诊断说明,而**在此之前
890
+ 没有任何一步读它** —— 一个只管写、没人读的标记,与不写它同形。⇒ **收尾必须逐个点名它们**,
891
+ 并写出移交目标(`/specpro-test-plan` → `/specpro-test-implement`,或诊断说明里点名的那个)。
892
+
893
+ b. **Scan for first pending task**:
894
+ - Read tasks.md from top to bottom
895
+ - Skip all tasks marked `[x]` (completed)
896
+ - Stop at first task marked `[ ]` (pending)
897
+ - Extract task details:
898
+ * Phase (Setup/Foundational/US-XXX/Polish)
899
+ * Task description
900
+ * Parallel marker `[P]` (if present)
901
+ * File paths mentioned in task
902
+ * FR annotation `(FR-XXX)` (if present)
903
+
904
+ c. **Determine execution scope**:
905
+ - **Single sequential task**: No `[P]` marker
906
+ * Verify previous task in same phase is `[x]`
907
+ * If not, find and execute previous task first
908
+ * Execute this single task
909
+
910
+ - **Parallel task group** `[P]`: Task has parallel marker
911
+ * Collect all consecutive `[P]` tasks at same indentation level
912
+ * Verify no file conflicts (parallel tasks must not affect same files)
913
+ * Execute all parallel tasks concurrently
914
+
915
+ d. **Execute task(s)** 🎯:
916
+ - **Single task**:
917
+ * **Identify task type** from task description and file paths:
918
+ - **Test task**: Task description contains "Test", "test", OR file path ends with `Test.kt`, `Test.java`, `Test.ts`, `test.py`, `*_test.go`, etc.
919
+ - **Implementation task**: Task contains "Implement", "Create", "Add", "Build", OR file path ends with implementation extension (`.kt`, `.java`, `.ts`, `.py`, `.go`, etc.)
920
+
921
+ * **Check quality status warnings** ⚠️ (if QUALITY_STATUS = "BLOCK" — i.e. the run proceeded on an acknowledged `UNDERSTAND`; a `PASS` run has no unaddressed issues to surface):
922
+ - Extract keywords from task description (e.g., "streaming", "authentication", "performance")
923
+ - Match keywords against `UNADDRESSED_ISSUES` and `COVERAGE_GAPS` (stored in Step 3h)
924
+ - **If keyword match found**:
925
+ - Display quality warning (use `PROJECT_LANGUAGE`):
926
+ ```markdown
927
+ ⚠️ QUALITY NOTE
928
+
929
+ **Issue**: [Issue description from UNADDRESSED_ISSUES]
930
+ **Relevance**: This task involves [keyword], which relates to the quality issue
931
+
932
+ **Suggestions**:
933
+ - [Specific suggestions based on issue type]
934
+
935
+ **Example**:
936
+ Issue: "Edge cases not identified"
937
+ Task: "Implement streaming data processing"
938
+ Suggestions:
939
+ - Consider network interruption scenarios
940
+ - Consider data corruption scenarios
941
+ - Consider buffer overflow scenarios
942
+ ```
943
+ - Ask: "Proceed with implementation? (y/n):"
944
+ - If user says 'n': Skip task, return to Step 9b to find next task
945
+ - If user says 'y': Continue with implementation
946
+ - **If no keyword match**: No warning needed, proceed to next step
947
+
948
+ * **Identify target files** from task description
949
+
950
+ * **Check Test-First compliance** (if implementation task):
951
+ - Extract module/class name from implementation task
952
+ - Search tasks.md for corresponding test task:
953
+ * Pattern: `ModuleNameTest`, `ModuleName.test`, or similar
954
+ * Search in tasks before current task (test should come first)
955
+ - **If test task found and is `[ ]` (not completed)**:
956
+ - Display warning (use `PROJECT_LANGUAGE`): "⚠️ Test task exists but is not completed. Test-First approach recommends completing tests before implementation."
957
+ - Show test task ID and description
958
+ - Ask: "Continue with implementation anyway? (y/n):"
959
+ - If user says 'n': Skip this task, return to step 9b to execute test task first
960
+ - **If test task found and is `[x]` (completed)**:
961
+ - Proceed with implementation (tests already in place)
962
+ - **If no test task found**:
963
+ - Proceed with implementation (tasks.md defines test requirements, not implement phase)
964
+
965
+ * **For each target file**:
966
+ - **Check if file exists** (use Glob tool to search)
967
+ - **If file exists**:
968
+ - **Read entire file** (use Read tool)
969
+ - **Analyze existing code**:
970
+ - Check if task requirements are already implemented
971
+ - Verify code quality and style
972
+ - **Decision**:
973
+ - If fully implemented → Skip this file
974
+ - If partially implemented → Use Edit tool to add missing parts
975
+ - If wrong implementation → Use Edit tool to fix
976
+ - **Preserve existing code structure** (style, patterns)
977
+ - **If file does not exist**:
978
+ - **Verify parent directory exists** (create if needed)
979
+ - **Create new file** (use Write tool)
980
+
981
+ * **Execute based on task type**:
982
+ - **Test task**:
983
+ - Write test file with appropriate test cases
984
+ - Run test to verify it fails (RED phase of TDD)
985
+ - Mark task as `[x]` when test is written and fails as expected
986
+
987
+ - **Implementation task** (when tests are in place):
988
+ - Write implementation code
989
+ - Run tests to verify they pass (GREEN phase of TDD)
990
+ - Check test coverage if specified in tasks.md or plan.md
991
+ - Mark task as `[x]` when implementation passes tests
992
+
993
+ - **Implementation task** (when tests are NOT required or not in place):
994
+ - Write implementation code
995
+ - Basic verification (compile, lint check if available)
996
+ - Mark task as `[x]` when implementation is complete
997
+ - ⚠️ **Platform source-set tasks** [CRITICAL]: if the task writes platform-specific sources (`androidMain/`, `iosMain/`, `wasmMain/`, ...), the owning compilation target MUST be registered in the module build script and the file MUST participate in the compile verification above. If the target is NOT registered, do NOT mark `[x]` — the file would be orphan dead code that silently passes every gate; implement what is verifiable and register an implement issue for the missing target registration
998
+
999
+ * **Task already completed check**:
1000
+ - After checking all target files, if ALL files are fully implemented
1001
+ - Mark task as `[x]` in tasks.md
1002
+ - No code changes needed
1003
+
1004
+ * **Create development process documentation** 📝 [WHEN NEEDED]:
1005
+ - **Purpose**: Document complex problems, difficult debugging, and important learnings
1006
+ - **When to create** (NOT for every task):
1007
+ * ✅ **ALWAYS create** for:
1008
+ - Complex algorithms (encoding, compression, crypto, protocol parsing)
1009
+ - Bugs that took >2 hours to solve
1010
+ - Issues requiring multiple attempts to fix
1011
+ - Cross-component debugging (data flow, state synchronization)
1012
+ - Performance optimizations with measurable results
1013
+ - Integration issues with external systems
1014
+ * ❌ **DO NOT create** for:
1015
+ - Simple CRUD operations
1016
+ - Straightforward UI adjustments
1017
+ - Trivial bug fixes (typos, simple logic errors)
1018
+ - Routine refactoring
1019
+
1020
+ - **⚠️ 机制选择记录 —— 这是 §"Implement Responsibility Boundaries" 第 3 条的执行步骤**
1021
+ (T172 / audit finding:「WHERE 写了落点,而没有任何执行步骤」):
1022
+ **每次**在实现中选了一个"有合理替代方案、且无法从 FR 正文推出"的机制时,**当轮**在
1023
+ `specs/research.md` 追加一节 `## Addendum (<task-id>, <date>): <选择> — <被拒的替代> vs <被拒的替代>`,
1024
+ 内容四项:**选了什么 · 否决了什么 · 为什么(证据,不是断言)· 推迟或未做的部分及其诚实语义**。
1025
+ ⚠️ **判据不在"有没有写",在"它是否落在设计所指的推理路径上"**:`plan.md` 的
1026
+ `### Architecture Patterns` 用 `See: research.md` 指向它 ⇒ **写进提交信息或 `docs/implement/`
1027
+ 都不算**(那两处都不在那条路径上,下一个做同样选择的人读不到)。
1028
+
1029
+ - **Document types** (choose based on situation):
1030
+ 1. **{FEATURE}_FORMAT.md**: Protocol format or data structure specification
1031
+ * When: Implementing new protocol, encoding, or data format
1032
+ * Content: Format specification, byte structure, examples
1033
+ * Examples: `USER_AUTH_FORMAT.md`, `DATABASE_SCHEMA_FORMAT.md`
1034
+
1035
+ 2. **ROOT_CAUSE.md**: Root cause analysis for complex bugs
1036
+ * When: Bug took >2 hours to solve or involved multiple components
1037
+ * Content: Problem description, investigation steps, root cause, evidence
1038
+ * Examples: `MEMORY_LEAK_ROOT_CAUSE.md`, `CONNECTION_TIMEOUT_ROOT_CAUSE.md`
1039
+
1040
+ 3. **DEBUG.md**: Debugging guide for specific issues
1041
+ * When: Encountering difficult-to-reproduce or complex issues
1042
+ * Content: Debug steps, log analysis, diagnostic commands
1043
+ * Examples: `API_INTEGRATION_DEBUG.md`, `PERFORMANCE_DEBUG.md`
1044
+
1045
+ 4. **FIX.md**: Solution record for specific fixes
1046
+ * When: Implementing a fix after investigation
1047
+ * Content: Problem, solution, code changes, verification
1048
+ * Examples: `AUTH_BYPASS_FIX.md`, `DATA_CORRUPTION_FIX.md`
1049
+
1050
+ 5. **VERIFICATION.md**: Verification results and testing
1051
+ * When: Complex verification logic or cross-platform testing
1052
+ * Content: Test methods, results, edge cases covered
1053
+ * Examples: `CROSS_PLATFORM_VERIFICATION.md`, `SECURITY_TEST_VERIFICATION.md`
1054
+
1055
+ 6. **SUMMARY.md**: Implementation summary for complete features
1056
+ * When: Completing a major feature or encoding implementation
1057
+ * Content: Overview, files changed, key decisions, lessons learned
1058
+ * Examples: `PAYMENT_SYSTEM_SUMMARY.md`, `FILE_SYNC_SUMMARY.md`
1059
+
1060
+ 7. **{TOPIC}_RUN_GUIDE.md**: Operational run guide for a test suite/tool 🧪 [WHO / WHEN / WHAT / WHERE]
1061
+ * WHO (writer): `/specpro-implement` — run guides are work products of development tasks (tasks.md work, including unit tests). NEVER written by test-plan/test-implement
1062
+ * WHEN (trigger): MANDATORY whenever a user story delivered or changed unit tests — create or update the affected test module's run guide BEFORE marking the story complete. NOT one guide per story: ONE guide per test module/source set, incrementally extended as later stories add tests to the same module
1063
+ * WHAT (minimum content): (1) suite inventory — test class ↔ tasks.md task ID ↔ FR; (2) how to run all / single class / single method / by package; (3) expected output on success; (4) how to view test results and coverage reports; (5) failure debugging steps; (6) common problems / FAQ; (7) quick command reference
1064
+ * WHERE (location): `docs/implement/` — never `docs/test/`, never the repository root; register in PROJECT_NAVIGATION.md
1065
+ * **Grounding iron rule ⚠️**: every command in the guide MUST have been actually executed with its output observed BEFORE being written into the guide. Never document an unverified module path, task name, or report path — a decoupled run guide misleads humans and AI alike (the documentation-form of running against nonexistent infrastructure)
1066
+ * Examples: `RUN_UNIT_TESTS_GUIDE.md` (one per unit-test module), `RUN_E2E_SUITE_GUIDE.md`
1067
+
1068
+ 8. **PROJECT_NAVIGATION.md**: Development docs main index (fixed name)
1069
+ * When: Create UP-FRONT (when `docs/implement/` is set up) or at the latest when the FIRST technical document is produced — project documentation is assumed to be multi-document, do NOT wait for multiple topics
1070
+ * Content: Topic location table with US/FR/keyword mappings
1071
+ * Location: `docs/implement/PROJECT_NAVIGATION.md` (conventional)
1072
+
1073
+ 9. **index.md**: Topic-specific navigation (pattern-based name)
1074
+ * When: Topic has 3+ documents or needs detailed navigation
1075
+ * Content: Document list, status, reading order, task mappings
1076
+ * Location: `docs/implement/{topic}/index.md`
1077
+ * Note: `{topic}` is variable (examples: `authentication/`, `storage/`, `api/`)
1078
+
1079
+ - **Content organization principles**:
1080
+ * **Problem-oriented**: Start with problem, then solution
1081
+ * **Evidence chain**: Include logs, code snippets, test results
1082
+ * **Verifiability**: Provide reproduction steps, test methods
1083
+ * **Timestamps**: Include dates for timeline tracking
1084
+ * **Cross-references**: Link to related documents
1085
+ * **Language**: Follow project constitution's language policy
1086
+
1087
+ - **Navigation maintenance best practices** 📋:
1088
+ * **Start simple**: Begin with just Topic Index table, add reverse indexes later
1089
+ * **Batch updates**: Update all indexes in one edit (not multiple separate edits)
1090
+ * **Use verification checklist**: ALWAYS run Step 5 verification after updates
1091
+ * **Keep keywords minimal**: 3-5 keywords per topic max
1092
+ * **Consistent format**: Use exact same format as template
1093
+ * **Read before write**: Read entire PROJECT_NAVIGATION.md before editing
1094
+ * **Test links**: After update, click each link to verify they work
1095
+
1096
+ - **Directory structure** (illustrative - adapt to your project):
1097
+ ```
1098
+ project-root/
1099
+ ├── specs/ # SpecPro workflow (spec, plan, tasks, contracts, etc.)
1100
+ ├── docs/ # All project documentation
1101
+ │ ├── user/ # User requirements documentation
1102
+ │ │ ├── user-stories.md
1103
+ │ │ └── use-cases.md
1104
+ │ ├── reference/ # Design reference documentation
1105
+ │ │ ├── architecture.md
1106
+ │ │ ├── data-model.md
1107
+ │ │ └── api-reference.md
1108
+ │ ├── implement/ # Development process documentation (conventional)
1109
+ │ │ ├── PROJECT_NAVIGATION.md # Main index (create up-front or with the first document)
1110
+ │ │ ├── authentication/ # Example topic 1 (actual name varies)
1111
+ │ │ │ ├── index.md # Topic navigation (recommended for 3+ docs)
1112
+ │ │ │ ├── OAUTH_FORMAT.md # Example doc (pattern-based name)
1113
+ │ │ │ └── AUTH_FIX.md # Example doc (pattern-based name)
1114
+ │ │ ├── storage/ # Example topic 2 (actual name varies)
1115
+ │ │ │ ├── index.md
1116
+ │ │ │ └── DATABASE_MIGRATION_ROOT_CAUSE.md
1117
+ │ │ └── [other topics] # Your project's topics
1118
+ │ ├── user_manual/ # User manual
1119
+ │ │ ├── getting-started.md
1120
+ │ │ └── user-guide.md
1121
+ │ └── developer_manual/ # Developer manual
1122
+ │ ├── setup.md
1123
+ │ ├── contribution-guide.md
1124
+ │ └── api-reference.md
1125
+ └── [other project files...]
1126
+ ```
1127
+ **Note**: Topic names (`authentication/`, `storage/`) are EXAMPLES. Use names appropriate for your project.
1128
+ ```
1129
+ *Benefits*: Clear category separation, centralized docs, clean root directory, follows community conventions
1130
+
1131
+ **Structure principles**:
1132
+ - **Centralized in docs/**: All documentation under one directory — NEVER place documents in the repository root (violation example: a run guide left at project root instead of under docs/)
1133
+ - **Categorized by purpose**: user/, reference/, implement/, test/, user_manual/, developer_manual/
1134
+ - **Development docs in implement/**: Grouped by topic/FR
1135
+ - **docs/ root = project-level/stakeholder documents only** (e.g., plain-language overviews of significant changes for non-specialist readers); create ONLY on explicit user request, never spontaneously
1136
+ - **Two-level navigation**: PROJECT_NAVIGATION.md (location) → {topic}/index.md (details)
1137
+ - **Shallow hierarchy**: Max 2-3 levels deep (docs/implement/topic/filename.md)
1138
+ - **Ownership boundary ⚠️**: document LOCATION follows the ownership of the work that produced it, NOT the document's topic. Docs produced by development tasks (tasks.md — including unit tests and their run guides) belong to `docs/implement/`, even when the subject is testing. NEVER write into `docs/test/` from this command — that directory belongs to `/specpro-test-implement` (work products of test-tasks.md execution: INF/IT/CE/AE)
1139
+
1140
+ - **File naming conventions**:
1141
+ * Use `{FEATURE}_{TYPE}.md` pattern for feature-specific docs
1142
+ * Use descriptive names: `MEMORY_LEAK_ROOT_CAUSE.md` (not `fix3.md`)
1143
+ * Avoid numbers in filenames (use dates in content instead)
1144
+ * Keep names under 50 characters for readability
1145
+
1146
+ - **Document templates**:
1147
+
1148
+ **PROJECT_NAVIGATION.md template** (main navigation - location lookup):
1149
+ ```markdown
1150
+ # Development Process Documentation Navigation
1151
+
1152
+ **Last Updated**: [YYYY-MM-DD]
1153
+
1154
+ ---
1155
+
1156
+ ## Topic Index
1157
+
1158
+ | Topic | Location | US | FR | Keywords |
1159
+ |-------|----------|-----|-----|----------|
1160
+ | [{Topic}](topic/index.md) | `docs/implement/topic/` | [US-numbers] | [FR-numbers] | [keyword1, keyword2, ...] |
1161
+
1162
+ ## Reverse Index
1163
+
1164
+ ### By User Story
1165
+ - **US-{N}**: [{Topic}](topic/index.md), [{Topic}](topic2/index.md)
1166
+
1167
+ ### By Functional Requirement
1168
+ - **FR-{N}**: [{Topic}](topic/index.md)
1169
+
1170
+ ### By Keyword
1171
+ - **{keyword}**: [{Topic}](topic/index.md), [{Topic}](topic2/index.md)
1172
+ ```
1173
+
1174
+ **{topic}/index.md template** (topic navigation - detailed information):
1175
+ ```markdown
1176
+ # {Topic} Documentation
1177
+
1178
+ **Related**: US-{N}, FR-{N}
1179
+ **Keywords**: [keyword1, keyword2, ...]
1180
+
1181
+ ---
1182
+
1183
+ ## Documents
1184
+
1185
+ | Document | Type | Status | Purpose | Updated |
1186
+ |----------|------|--------|---------|---------|
1187
+ | [{DOC1}.md]({DOC1}.md) | [Format/Root Cause/Fix/Summary] | [✅ Complete / 🚧 In Progress] | [Purpose] | [YYYY-MM-DD] |
1188
+
1189
+ ## Reading Order
1190
+
1191
+ **Beginners**:
1192
+ 1. {DOC}.md
1193
+ 2. {DOC}.md
1194
+
1195
+ **Debugging**:
1196
+ 1. {DOC}.md
1197
+ 2. {DOC}.md
1198
+
1199
+ ## Related Tasks
1200
+
1201
+ - T-{N}: [Task description]
1202
+ - T-{N}: [Task description]
1203
+
1204
+ ## Key Insights
1205
+
1206
+ - [Key point 1]
1207
+ - [Key point 2]
1208
+ ```
1209
+
1210
+ **ROOT_CAUSE.md template**:
1211
+ ```markdown
1212
+ # {Feature} Root Cause Analysis
1213
+
1214
+ ## Problem
1215
+ - **Symptom**: [What went wrong]
1216
+ - **Impact**: [Severity, affected components]
1217
+ - **Timeline**: [When discovered, duration to fix]
1218
+
1219
+ ## Investigation
1220
+ ### Step 1: [Initial approach]
1221
+ - Finding: [What was discovered]
1222
+ - Evidence: [Logs, code snippets]
1223
+
1224
+ ### Step 2: [Next approach]
1225
+ - Finding: [More discoveries]
1226
+ - Evidence: [More evidence]
1227
+
1228
+ ## Root Cause
1229
+ - **Primary cause**: [The actual root cause]
1230
+ - **Contributing factors**: [Other factors]
1231
+
1232
+ ## Solution
1233
+ - **Fix**: [What was changed]
1234
+ - **Files**: [List of modified files]
1235
+ - **Verification**: [How fix was verified]
1236
+ ```
1237
+
1238
+ **SUMMARY.md template**:
1239
+ ```markdown
1240
+ # {Feature} Implementation Summary
1241
+
1242
+ ## Overview
1243
+ - **Feature**: [Feature description]
1244
+ - **Duration**: [Start date] - [End date]
1245
+ - **Status**: [Complete/Incomplete]
1246
+
1247
+ ## Files Changed
1248
+ - `path/to/file1`: [Change description]
1249
+ - `path/to/file2`: [Change description]
1250
+
1251
+ ## Key Decisions
1252
+ 1. [Decision 1 with rationale]
1253
+ 2. [Decision 2 with rationale]
1254
+
1255
+ ## Challenges Solved
1256
+ 1. [Challenge 1 and solution]
1257
+ 2. [Challenge 2 and solution]
1258
+
1259
+ ## Lessons Learned
1260
+ - [What to avoid next time]
1261
+ - [Best practices discovered]
1262
+
1263
+ ## Related Documents
1264
+ - [{RELATED_DOC}.md]: [Brief description]
1265
+ ```
1266
+
1267
+ - **When to update docs/implement/PROJECT_NAVIGATION.md**:
1268
+ * When adding a new topic folder
1269
+ * When US/FR/keyword mappings change
1270
+ * Update: Add entry to Topic Index table, update reverse indexes
1271
+
1272
+ - **First-time creation** ⚠️ [UP-FRONT or with the first document]:
1273
+ * Assume project documentation will be multi-document: create `docs/implement/PROJECT_NAVIGATION.md` UP-FRONT (when `docs/implement/` is set up) or at the latest when the FIRST technical document is produced — do NOT wait for multiple topics
1274
+ * If it does not exist yet when an update is needed, CREATE it from the template below BEFORE applying any update step
1275
+ * Start simple: initial content = title + Last Updated + Topic Index table only; add the Reverse Index sections incrementally as topics accumulate
1276
+
1277
+ - **How to update PROJECT_NAVIGATION.md correctly** ⚠️ [CRITICAL]:
1278
+ **Step 1: Update Topic Index table**:
1279
+ - Add row for new topic: `| [{Topic}](topic/index.md) | docs/implement/topic/ | US-{N} | FR-{N}, FR-{N} | keyword1, keyword2 |`
1280
+
1281
+ **Step 2: Update "By User Story" section**:
1282
+ - Find or create entry for US-{N}
1283
+ - Add topic link: `**US-{N}**: [{Existing Topic}](topic1/index.md), [{New Topic}](topic2/index.md)`
1284
+ - Ensure each US links to ALL related topics
1285
+
1286
+ **Step 3: Update "By Functional Requirement" section**:
1287
+ - For EACH FR listed in Topic Index table:
1288
+ * Create entry: `**FR-{N}**: [{Topic}](topic/index.md)`
1289
+ * If FR maps to multiple topics, list all: `**FR-{N}**: [{Topic1}](topic1/index.md), [{Topic2}](topic2/index.md)`
1290
+
1291
+ **Step 4: Update "By Keyword" section**:
1292
+ - For EACH keyword listed in Topic Index table:
1293
+ * Find or create entry for keyword
1294
+ * Add topic link: `**{keyword}**: [{Topic}](topic/index.md), [{Another Topic}](topic2/index.md)`
1295
+ * Keep keyword list short (3-5 per topic)
1296
+
1297
+ **Step 5: Verify consistency** ✅ [QUALITY CHECK]:
1298
+ - For EACH topic in Topic Index table:
1299
+ * US numbers exist in "By User Story" section? ✅/❌
1300
+ * ALL FR numbers exist in "By Functional Requirement" section? ✅/❌
1301
+ * ALL keywords exist in "By Keyword" section? ✅/❌
1302
+ - No orphan entries in reverse indexes (topics not in table)? ✅/❌
1303
+ - Table row count matches number of topics? ✅/❌
1304
+
1305
+ - **When to create docs/implement/{topic}/index.md**:
1306
+ * Topic has 3+ documents
1307
+ * Topic needs detailed navigation (reading order, task mappings)
1308
+ * Create in topic folder, link from PROJECT_NAVIGATION.md
1309
+
1310
+ - **Documentation maintenance**:
1311
+ * Review docs when related features change
1312
+ * Mark obsolete docs as `[DEPRECATED]` at top
1313
+ * Cross-link related docs for better navigation
1314
+ * Use Git history for old versions (don't keep multiple copies)
1315
+
1316
+ - **Quality checklist** before saving:
1317
+ ✅ Problem is clearly described
1318
+ ✅ Evidence/log snippets included
1319
+ ✅ Solution is reproducible
1320
+ ✅ Related docs are cross-referenced
1321
+ ✅ Filename follows naming convention
1322
+ ✅ Document is in correct location
1323
+
1324
+ - **Example: Updating PROJECT_NAVIGATION.md when adding new topic**:
1325
+ **Scenario**: Adding new topic "storage" with docs at `docs/implement/storage/`
1326
+ **Mapping**: US-3, FR-xxx, FR-yyy, Keywords: database, migration, storage
1327
+
1328
+ **Before** (Topic Index table):
1329
+ ```markdown
1330
+ | Topic | Location | US | FR | Keywords |
1331
+ |-------|----------|-----|-----|----------|
1332
+ | [Authentication](authentication/index.md) | docs/implement/authentication/ | 1 | 101, 102 | oauth, login, auth |
1333
+ ```
1334
+
1335
+ **After** (Topic Index table):
1336
+ ```markdown
1337
+ | Topic | Location | US | FR | Keywords |
1338
+ |-------|----------|-----|-----|----------|
1339
+ | [Authentication](authentication/index.md) | docs/implement/authentication/ | 1 | 101, 102 | oauth, login, auth |
1340
+ | [Storage](storage/index.md) | docs/implement/storage/ | 3 | 301, 302 | database, migration, storage |
1341
+ ```
1342
+
1343
+ **Reverse indexes updates**:
1344
+ ```markdown
1345
+ ### By User Story
1346
+ - **US-1**: [Authentication](authentication/index.md)
1347
+ - **US-3**: [Storage](storage/index.md) # NEW
1348
+
1349
+ ### By Functional Requirement
1350
+ - **FR-xxx**: [Authentication](authentication/index.md)
1351
+ - **FR-xxx**: [Authentication](authentication/index.md)
1352
+ - **FR-xxx**: [Storage](storage/index.md) # NEW
1353
+ - **FR-xxx**: [Storage](storage/index.md) # NEW
1354
+
1355
+ ### By Keyword
1356
+ - **oauth**: [Authentication](authentication/index.md)
1357
+ - **database**: [Storage](storage/index.md) # NEW
1358
+ - **migration**: [Storage](storage/index.md) # NEW
1359
+ - **storage**: [Storage](storage/index.md) # NEW
1360
+ ```
1361
+
1362
+ **Verification**:
1363
+ - ✅ Storage row added to table
1364
+ - ✅ US-3 added to User Story index
1365
+ - ✅ FR-xxx, FR-yyy added to FR index
1366
+ - ✅ database, migration, storage added to Keyword index
1367
+ - ✅ No orphan entries
1368
+ - ✅ Table has 2 rows (Authentication + Storage)
1369
+
1370
+ - **Parallel tasks** `[P`:
1371
+ * **For each parallel task**:
1372
+ - Extract target files from task description
1373
+ - Identify task type (test vs implementation)
1374
+ - Check Test-First compliance (same as single task)
1375
+ - Check file existence and read existing code (same as single task)
1376
+ - Verify no file conflicts with other parallel tasks
1377
+ - Execute based on task type (same as single task)
1378
+ * **Mark successful tasks as `[x]`**
1379
+ * **Report failed tasks without halting** (parallel failure tolerance)
1380
+
1381
+ e. **Task completion and exit decision** ⚠️ [CRITICAL - CONTEXT MANAGEMENT]:
1382
+ - **Track executed task count**: Initialize counter at 0, increment after each task completion
1383
+
1384
+ - **Checkpoint Gate** 🧪 [TESTPLAN TIMING — fires when a User Story phase boundary is crossed]:
1385
+ **Purpose**: The optimal moment to run `/specpro-test-plan` is right after a story's implementation lands (newly implemented modules become testable; the incremental mode converts their matrix rows from `pending-impl` to real tasks). Without this gate, continuous modes (`--continue`, `--phase`, large `--count`) would blow through story boundaries and the user loses that timing. Do NOT add pseudo "pause" tasks to tasks.md for this — the gate lives here, in the executor.
1386
+
1387
+ **Trigger detection**: after completing a task, check whether the just-completed task was the LAST pending task of its **User Story phase** (phase with `[US#]` labels — Setup/Foundational/Polish do NOT trigger the gate).
1388
+
1389
+ **If triggered, compute test-plan relevance** (cheap checks, in order):
1390
+ 1. `specs/test-tasks.md` does not exist → **HIGH** (test system not built yet)
1391
+ 2. `spec.md` last-modified more recently than `specs/test-tasks.md` → **HIGH** (spec changed since last test plan)
1392
+ 3. Any FR annotated on tasks completed **in this story** has matrix row status `pending-impl` (or is absent from the matrix) → **HIGH** (newly testable — the exact incremental-mode use case)
1393
+ 4. Otherwise → **LOW**
1394
+
1395
+ **On HIGH relevance — PAUSE** (in EVERY mode, including `--continue`/`--phase`) and show the story-completion menu:
1396
+ ```markdown
1397
+ 🎯 User Story [US#] implementation complete — Checkpoint
1398
+
1399
+ **Test-plan relevance**: HIGH
1400
+ - [reason: e.g. "spec.md changed after last test-plan run" / "FR-0xx newly testable (matrix row pending-impl)"]
1401
+
1402
+ **Options**:
1403
+ 1. Continue to next story
1404
+ 2. Run `/specpro-test-plan` (incremental) now, then continue
1405
+ 3. Run `/specpro-test-implement` now (execute pending test tasks), then continue
1406
+ 4. End this session
1407
+
1408
+ Your choice (1-4):
1409
+ ```
1410
+ - Choice 2: hand off to `/specpro-test-plan` (its change-log-driven incremental mode processes exactly the drifted/newly-testable FRs), then resume this session at the user's discretion
1411
+ - Choice 3: hand off to `/specpro-test-implement` (dual write-back keeps the matrix in sync), then resume
1412
+ - Choice 4: exit via the normal exit path with the completion report
1413
+
1414
+ **On LOW relevance — do NOT interrupt**: set `TESTPLAN_HINT=true` and continue; the hint surfaces in the exit report only.
1415
+
1416
+ - **Check exit conditions** (in order of priority):
1417
+ 1. **`--once` mode**: Exit after 1 task completed
1418
+ 2. **`--count N` mode**: Exit after N tasks completed
1419
+ 3. **`--phase PHASE` mode**: Exit when phase completes or no pending tasks in phase
1420
+ 4. **`--continue` mode**: Continue until all tasks complete (⚠️ WARNING: Context may overflow)
1421
+ 5. **No more tasks**: Exit when scan finds no `[ ]` tasks (all are `[x]`)
1422
+
1423
+ - **Before exit**:
1424
+ * Report completion summary: "Executed N tasks in this session"
1425
+ * Show remaining progress: "Overall progress: X/Y tasks completed (Z%)"
1426
+ * **If `TESTPLAN_HINT=true` OR the session ended at a User Story boundary**: append the test-timing hint:
1427
+ ```markdown
1428
+ 🧪 Test Timing Hint:
1429
+ - A User Story just completed — this is the optimal checkpoint for test planning.
1430
+ - Run `/specpro-test-plan` (incremental if specs/test-tasks.md exists) to register newly
1431
+ testable FRs, then `/specpro-test-implement` to execute pending test tasks.
1432
+ ```
1433
+ * **If tasks remain**: Provide clear instructions:
1434
+ ```markdown
1435
+ ⚠️ Session complete to prevent context overflow.
1436
+
1437
+ **Progress**: X/Y tasks completed (Z%)
1438
+
1439
+ **Next Steps**:
1440
+ - Run `/specpro-implement` again to continue implementation
1441
+ - Progress is preserved (completed tasks marked [x])
1442
+
1443
+ **Or execute multiple tasks**:
1444
+ - `/specpro-implement --count 5` (Execute next 5 tasks)
1445
+ - `/specpro-implement --phase Foundational` (Execute entire Foundational phase)
1446
+ ```
1447
+
1448
+ f. **Final validation** (only when no tasks remain):
1449
+ - When scan finds no `[ ]` tasks (all are `[x]`)
1450
+ - Proceed to step 14 (final validation)
1451
+
1452
+ 10. **Error handling and recovery** ⚠️:
1453
+ a. **Sequential task failure**:
1454
+ - Halt execution immediately
1455
+ - Display error with context (file, line, error message)
1456
+ - Suggest next steps to fix
1457
+ - **Do NOT mark failed task as `[x]`
1458
+ - User can re-run `/specpro-implement` after fix (task remains `[ ]`)
1459
+
1460
+ b. **Parallel task failure** `[P`:
1461
+ - Continue executing other parallel tasks
1462
+ - Collect all failures
1463
+ - Report summary: "X of Y parallel tasks succeeded"
1464
+ - Mark only successful tasks as `[x]`
1465
+ - Failed tasks remain `[ ]` for next run
1466
+
1467
+ c. **Validation failure**:
1468
+ - Tests fail → Do NOT mark as `[x]`, display test output
1469
+ - Compilation errors → Do NOT mark as `[x]`, display errors
1470
+ - User must fix and re-run
1471
+
1472
+ 11. **Progress reporting** 📊:
1473
+ - After each task completion: Display "✓ Completed: [task description]" (use `PROJECT_LANGUAGE` from Step 4)
1474
+ - For parallel tasks: Display "✓ Completed X/Y parallel tasks"
1475
+ - Show cumulative count: "Progress: N/M tasks completed"
1476
+ - Display current phase: "Current phase: [Setup/Foundational/US-XXX/Polish]"
1477
+
1478
+ 12. **Task completion tracking** ✅:
1479
+ - **CRITICAL**: Always mark completed tasks as `[x]` in tasks.md
1480
+ - Use Edit tool to update task status
1481
+ - Preserve task description and metadata
1482
+ - Only change `[ ]` → `[x]`
1483
+ - This enables resumable execution (interrupted runs continue from last `[ ]`)
1484
+
1485
+ 13. **Issue recording and feedback** 🔄 [WORKFLOW CLOSURE]:
1486
+ - **Purpose**: Record issues found during implementation for feedback to earlier phases
1487
+
1488
+ - **Tool defects route through the ledger, not a side registry** ⚠️ [T089 · FR-023]: if the defect you found is in **specpro itself** (this project's command documents, templates, or support scripts — when a project bootstraps specpro, those **are** the project's product), route it by ONE criterion: **does spec.md already demand the corrected behavior?**
1489
+ 1. **Not demanded yet** → establish the requirement FIRST: register a `[specify]` entry naming the tool-source file and the missing requirement. `/specpro-specify --review-issues` amends spec.md; the fix then flows down the chain ([plan] → [tasks]) and returns as an executable task. Bypassing the requirement layer produces a task backed by no requirement — and a task with no requirement behind it cannot be verified against anything.
1490
+ 2. **Already demanded** → the requirement exists and the tool fails it: register a `[tasks]` entry naming the tool-source file. `/specpro-implement` discharges it by executing a task whose Location names that file — the same single entry tool source has always had.
1491
+ - **Why no side registry** ⚠️: a defect written to a file no command consumes is indistinguishable from one never reported (FR-023 — a record only human convention reads does not satisfy routing). The former side registry was absorbed into the spec chain and deleted (`T089`); where history needs its entry IDs, cite them as 「原 TOOL-0NN」 — a historical label, never a live pointer.
1492
+ - **When to use**: When implement discovers problems with spec/plan/tasks
1493
+ - **Not to be confused** ⚠️: product-defect FIX TASKS dispatched by `/specpro-test-implement` live in `specs/fix-tasks.md` (FT-XXX, executed via `execution_mode = "fix"` in Step 9.a2). `implement_issues.md` is exclusively for **planning-artifact feedback** — errors in a *plan* (spec / plan / tasks / test-tasks), never errors in *execution* (an execution error is fixed in place, or dispatched as an FT when it is product code)
1494
+ - **Governing rule** ⚖️: **a planning error is fixed by the planner, an implementation error by the implementer.** Record an issue only against an artifact whose planner consumes that section — filing into a section no one legitimately consumes is a boundary violation, not thoroughness
1495
+
1496
+ a. **Check if issues exist**:
1497
+ - Review implementation problems encountered
1498
+ - Classify by phase: [specify], [plan], [tasks], or [constitution] — the sections whose planners are the `--review-issues` commands below
1499
+ - Recognise the remaining section without resolving it: **[test-plan]** holds planning errors in `specs/test-tasks.md`, reported by `/specpro-test-implement` (its Step 11) and fixed by `/specpro-test-plan`. You may **append** a new `[test-plan]` issue if you genuinely find such a defect (that is correct routing to its planner), but you never mark one `[x]`
1500
+ - Examples:
1501
+ * **[specify]**: Missing requirements, unclear specifications, conflicting requirements
1502
+ * **[plan]**: Unreasonable design, impossible to implement, design conflicts
1503
+ * **[tasks]**: Incorrect task descriptions, missing tasks, wrong task order, duplicate tasks
1504
+
1505
+ b. **Record issues in specs/implement_issues.md**:
1506
+ ```markdown
1507
+ ## [specify] Phase Issues
1508
+
1509
+ Issues related to functional requirements: missing, unclear, conflicting, etc.
1510
+ - [ ] ISS-XXX: [Issue description]
1511
+
1512
+ ## [plan] Phase Issues
1513
+
1514
+ Issues related to design approach: unreasonable, conflicting, unachievable, etc.
1515
+ - [ ] ISS-XXX: [Issue description]
1516
+
1517
+ ## [tasks] Phase Issues
1518
+
1519
+ Issues related to task descriptions: incorrect, duplicate, missing, ordering, etc.
1520
+ - [ ] ISS-XXX: [Issue description]
1521
+
1522
+ ## [test-plan] Phase Issues
1523
+
1524
+ Issues related to test planning: coverage-matrix rows, task location/source/verdicts, task-annotation consistency, etc.
1525
+ - [ ] ISS-XXX: [Issue description]
1526
+ ```
1527
+
1528
+ ⚠️ **The template shows the sections in their canonical order — it is NOT a licence to append to the file's end.** The live file may carry additional sections and interleaved content; find the section this issue belongs to and append **inside it**.
1529
+
1530
+ b2. **Entry placement** ⚠️ [a silent-corruption failure mode, observed 2026-09-12]:
1531
+ - Append the new entry to the **end of its own section** — i.e. after that section's last existing entry, and **before** the next `## […] Phase Issues` heading. **Never append to the end of the file.**
1532
+ - **Why this is not cosmetic**: "append to the end of the file" is correct only for whichever section happens to be last. For every other section it silently files the issue where its consuming stage will never read it — the entry looks registered, the statistics table looks plausible, and nothing errors. This exact failure occurred: an `[tasks]`-side issue was appended to the file end and landed in the last section (`[test-plan]`), where that section's consumer has no mandate to act on it.
1533
+ - **Verify mechanically after writing** (one command, no judgement):
1534
+ ```bash
1535
+ .specpro/scripts/bash/verify-ledger.sh
1536
+ ```
1537
+ One pass checks: every entry sits inside a section (nothing past the end-of-file sentinel), the statistics table matches the actual per-section counts, and the file ends with exactly one newline. Non-zero exit names the violation — fix it before continuing. A pre-commit hook enforces the same check, so a violation blocks the commit rather than being discovered later.
1538
+ - **Update that section's row** in the statistics table at the top (Total +1, Pending +1 unless you also resolved it). A section whose entry count and statistics row disagree is the same defect wearing a different hat — `verify-ledger.sh` reports it as a count mismatch.
1539
+ - **Edit order and idempotency check** ⚠️ [a silent false-skip, observed 2026-09-13]: write the **entry body first** (into its own section), then the derived summaries (statistics table + `Last Updated`) — never the reverse. A derived summary written first introduces the new ID into the file's text before the entry exists, so an idempotency guard that greps the file for that ID falsely concludes "already present" and **skips the entry**, while the summaries still claim it landed. For the same reason the guard MUST match the entry body's **line-start pattern**, never a full-text keyword search:
1540
+ ```bash
1541
+ grep -qE '^- \[[x ]\] ISS-<N>:' specs/implement_issues.md # correct — matches an ENTRY, not a mention
1542
+ # grep -q 'ISS-<N>' … # wrong — also matches the statistics Pending-Items column, the Last Updated line, cross-references
1543
+ ```
1544
+ - **General rule: every grep/awk example shown in an instruction or template must itself obey the line-start pattern** (TOOL-009) — the executing side copies examples verbatim, so an example that uses a whole-file match propagates the same misjudgment to everyone who copies it. This file has already corrected its own sentinel self-check command under this rule.
1545
+
1546
+ c. **Issue format**:
1547
+ - Use format: `- [ ] ISS-XXX: [Description]`
1548
+ - XXX: Auto-increment number (001, 002, 003, ...)
1549
+ ⚠️ **Take the next number with a NUMERIC sort — this is the command, and the
1550
+ reason is not stylistic** (`T206` / `ISS-166`):
1551
+ ```bash
1552
+ # next ISS id = current maximum + 1
1553
+ grep -oE '^- \[[x ]\] ISS-[0-9]+:' specs/implement_issues.md \
1554
+ | grep -oE '[0-9]+' | sort -n | tail -1
1555
+ ```
1556
+ ⚠️ **`sort` without `-n` is WRONG here and fails silently.** The IDs are
1557
+ **variable width**, so lexicographically `ISS-100` sorts *before* `ISS-97`
1558
+ (`"1" < "9"`). Measured 2026-09-19: `… | sort -u | tail -1` returned `99` while
1559
+ the true maximum was `161` — following it would have **reused an existing ID**.
1560
+ ⚠️ **The former tool-defect clause (原 TOOL-011, deleted by `T089`) used `sort -u`
1561
+ in its example — CORRECT for its subject**: that
1562
+ one numbered fixed-width three-digit IDs, where lexicographic and
1563
+ numeric order coincide. Copying it here is the mistake; the example is not at
1564
+ fault, the copying is. (Same family as `TOOL-009`: an example is copied
1565
+ verbatim, so it must be correct *for the artifact it is applied to*.)
1566
+ ⚠️ **And a collision is not self-announcing**: the IDs are how `--review-issues`
1567
+ runs ADDRESS entries, so two entries sharing one make the address name neither —
1568
+ while the statistics table still reconciles if its counts are bumped to match.
1569
+ `verify-ledger.sh` now carries that invariant (its check 7); this command is the
1570
+ writer side of it.
1571
+ - Description: Clear, concise problem statement
1572
+ - Example: `- [ ] ISS-xxx: FR-xxx missing implementation details for error handling`
1573
+
1574
+ d. **After recording issues**:
1575
+ - Display summary: "⚠️ N issues recorded in specs/implement_issues.md"
1576
+ - Show breakdown: "[specify]: X, [plan]: Y, [tasks]: Z, [test-plan]: W, [constitution]: V" (omit a section when its count is 0)
1577
+ - Provide next steps:
1578
+ ```markdown
1579
+ **Issues recorded during implementation**
1580
+
1581
+ To fix these issues, run commands in order:
1582
+ 1. /specpro-specify --review-issues (Fixes [specify] issues, marks them [x])
1583
+ 2. /specpro-plan --review-issues (Updates plan.md based on changes)
1584
+ 3. /specpro-tasks --review-issues (Updates tasks.md based on changes)
1585
+ 4. /specpro-implement (Continue implementation)
1586
+
1587
+ If any [test-plan] issues were recorded, resolve them separately:
1588
+ /specpro-test-plan (incremental run — updates specs/test-tasks.md, marks them [x])
1589
+
1590
+ Each command only marks issues in its own section as [x].
1591
+ ```
1592
+
1593
+ e. **Issue resolution workflow**:
1594
+ - **NOT in scope**: Implement command should NOT fix these issues
1595
+ - **User workflow**:
1596
+ 1. User reviews issues in implement_issues.md
1597
+ 2. User runs `/specpro-specify --review-issues`
1598
+ - Reads [specify] section issues
1599
+ - Applies fixes to spec.md
1600
+ - Marks [specify] issues as [x]
1601
+ 3. User runs `/specpro-plan --review-issues`
1602
+ - Detects spec.md changes
1603
+ - Updates plan.md accordingly
1604
+ - Marks [plan] issues as [x]
1605
+ 4. User runs `/specpro-tasks --review-issues`
1606
+ - Detects plan.md changes
1607
+ - Updates tasks.md accordingly
1608
+ - Marks [tasks] issues as [x]
1609
+ 5. User runs `/specpro-implement` to continue
1610
+ 6. If any `[test-plan]` issues exist, the user runs `/specpro-test-plan` (incremental)
1611
+ - Reads the [test-plan] section issues
1612
+ - Updates `specs/test-tasks.md` accordingly
1613
+ - Marks [test-plan] issues as [x]
1614
+ - This is NOT part of the phase order below — it is a separate track that
1615
+ must run before `/specpro-test-implement` resumes against test-tasks.md
1616
+ - **Sequential processing**: Issues must be fixed in phase order (specify → plan → tasks). `[test-plan]` sits outside that chain (test-tasks.md downstream of plan/tasks, not between them)
1617
+
1618
+ f. **Do NOT halt execution**:
1619
+ - Implement should continue even if issues are found
1620
+ - Issues are recorded for later resolution
1621
+ - Only halt for CRITICAL blocking issues (from Step 2 analysis)
1622
+
1623
+ 13.5. **Git commit at batch boundaries** 🆕 [PERSISTENCE — repo stays buildable & traceable]:
1624
+ - **Purpose**: Persist task outputs to version control at controlled granularity. Prevents the "entire implementation phase completed with zero commits" failure class (fresh clone unbuildable, one giant commit hiding all intermediate states, no regression anchors for incident investigation). This step is part of workflow closure, NOT optional housekeeping.
1625
+
1626
+ **Trigger rules — commit timing is DECOUPLED from the execution mode** (the mode decides session length only; commit granularity is fixed by these two rules):
1627
+ - **a. Internal cadence** [MANDATORY for unbounded mode]: immediately after crossing any logical-group boundary (Phase / user story / task group), commit once. In unbounded mode (no execution-mode argument) this is a HARD requirement — never let an unbounded session accumulate into one giant commit.
1628
+ - **b. Session closure** [MANDATORY for ALL modes — `--once` / `--count N` / `--phase` / unbounded / group]: before the completion report, commit everything the session produced but has not yet committed.
1629
+
1630
+ **Multi-repository layout — one commit per repository, not one commit per trigger** ⚠️:
1631
+ The artifacts this step persists can live in **different repositories**, and a single `git add` + commit **cannot span repositories**. Before committing, determine which repository each changed path belongs to — typically by checking whether the path's containing directory has its own `.git`:
1632
+
1633
+ - Some projects keep plan/task artifacts in a **separate repository** from the implementation source (e.g. a nested repo mounted at the specs directory).
1634
+ - Others keep everything in one repository — in that case the per-repository split below collapses into the single original commit.
1635
+
1636
+ Resolve it per project; do not assume. When a trigger fires, issue **one commit per repository that has changes**, each with a message describing **that repository's** changes. Never use one generic message across repositories — it produces a history that describes nothing.
1637
+
1638
+ **Path form — every path is expressed relative to its owning repository** ⚠️ (FR-027): this is a **different obligation** from the grouping below, and getting the grouping right while still writing `specs/...` fails whenever the project root is not the owning repository. When you commit in repository `R`, every path passed to `git -C "$R" add` MUST be expressed **relative to `R`** — never as an absolute path, and never as a literal prefix that is only correct when the project root *is* `R` (the common instance: a hardcoded `specs/...`).
1639
+ ```bash
1640
+ # $R = the path's owning repository — resolved above, from the path's own containing
1641
+ # directory, NOT from the project root
1642
+ # Use the Python form directly — macOS `realpath(1)` has no --relative-to.
1643
+ # ⚠️ `os.path.realpath` on BOTH sides is the whole point (ISS-144): `os.path.relpath` only
1644
+ # compares literal prefixes, and `git rev-parse --show-toplevel` returns a PHYSICAL path while
1645
+ # a path built with `cd … && pwd` is logical — reached through a symlink the two share no
1646
+ # prefix and relpath walks ABOVE the repository (reproduced with `/tmp` → `/private/tmp`).
1647
+ # ⚠️ Copied verbatim in `specpro.specify.md` and `specpro.test-implement.md` — change all three.
1648
+ relpath() { python3 -c 'import os,sys;print(os.path.relpath(os.path.realpath(sys.argv[2]),os.path.realpath(sys.argv[1])))' "$1" "$2"; }
1649
+ git -C "$R" add -- "$(relpath "$R" "$ARTIFACT")"
1650
+ ```
1651
+
1652
+ **What to commit** — grouped by which repository it belongs to:
1653
+ - **In the repository holding the plan/task artifacts**: the task list (checkbox + annotation updates) and the issues ledger (if new entries were recorded)
1654
+ - **In the repository holding the implementation** (often the project root, and possibly different from the above): implementation sources and tests written or executed during the batch; build/config files the tasks created or changed
1655
+ - **Wherever the documentation lives**: work documentation produced by the tasks (per docs ownership rules, e.g. `docs/implement/...`)
1656
+
1657
+ **What NOT to commit**:
1658
+ - Debug artifacts already disposed as DELETE (removed), and anything under `tmp/debug/` or gitignored paths
1659
+ - Files excluded by the project's `.gitignore` policy (AI-tool files, local-only artifacts) — respect it, never `git add -f`
1660
+
1661
+ **Commit message**: `<type>(<scope>): <task-range> <one-line summary> — <validation verdict>`
1662
+ Example: `feat(protocol): T-xxx~T-yyy remote viewing — 12/12 tests green`
1663
+ Task range + validation verdict make the git history double as the execution audit trail.
1664
+
1665
+ When the change spans repositories, each message is **written for its own repository**, not reused:
1666
+ - Implementation repository → the `<type>(<scope>)` form above.
1667
+ - Plan/task artifact repository → the same task range, but stated against what changed there, e.g. `tasks: T-xxx~T-yyy marked complete — <verdict>`. Its history must read as the *plan's* history, not as a duplicate of the code repository's.
1668
+
1669
+ **Tracked-deliverable gate** ⚠️ [before the completion report — T150 / ISS-56 ②]:
1670
+ every deliverable the batch produced must actually be **tracked**, not merely written to disk —
1671
+ a file that exists but was never `git add`ed survives on this machine only, and nothing
1672
+ else reports the difference. Run the re-runnable assertion:
1673
+
1674
+ ```bash
1675
+ scripts/bash/verify-deliverables-tracked.sh # PowerShell twin: scripts/powershell/verify-deliverables-tracked.ps1
1676
+ ```
1677
+
1678
+ Non-zero exit names the untracked deliverable — commit it before closing the batch.
1679
+ (Scope note: the assertion covers the deliverable source dirs and the artifact repos;
1680
+ root-level session transcripts are NOT deliverables and are out of its scope by
1681
+ construction — ISS-75.)
1682
+
1683
+ **If nothing to commit** (pure-analysis batch, or all outputs gitignored): state "nothing to commit" and move on.
1684
+
1685
+ 14. **Final validation** ✨:
1686
+ - Verify no `[ ]` tasks remain in tasks.md
1687
+ - **Frontmatter-YAML assertion** 🆕 [T152 / ISS-59 ① · ISS-81]: every frontmatter block in `commands/*.md` MUST parse — an unparseable block and a missing block are indistinguishable to every executor (the `handoffs:` topology and the `writes:` ownership map both live there). Run:
1688
+ ```bash
1689
+ scripts/bash/verify-frontmatter-yaml.sh # PowerShell twin: scripts/powershell/verify-frontmatter-yaml.ps1
1690
+ ```
1691
+ Non-zero exit names the failing file. Templates carry no frontmatter and are out of scope (ISS-81); the deployed mirror is covered by scanning the source side (deployment-verified byte-identical).
1692
+ - Run full test suite: `./gradlew test` or `npm test` or equivalent (detect from project)
1693
+ - **Code coverage acceptance** 🧪 [CONCRETE PROCEDURE — "verify they are met" by assumption is a false completion]:
1694
+ 1. **Locate thresholds**: read plan.md "Quality Targets" → "Risk-Based Coverage Targets" table (per risk level); tasks.md `[Quality]` coverage tasks may refine them
1695
+ 2. **Produce evidence**: run the project's coverage tooling (e.g., JaCoCo report task) and locate the ACTUAL report file (HTML/XML). Confirm the report path exists before quoting any number — a referenced-but-missing report is a false completion
1696
+ 3. **Compare per module**: classify measured modules by risk level and compare measured vs target PER MODULE — never a project-wide average (an average can mask an untested HIGH-RISK module)
1697
+ 4. **Verdict**:
1698
+ * All HIGH-RISK / MEDIUM-RISK modules meet targets → record measured numbers + report path in the completion report
1699
+ * Any module below target → do NOT report complete; record an issue in `specs/implement_issues.md` ([plan]/[tasks] as appropriate) and report the gap with measured numbers
1700
+ * Coverage tooling NOT configured despite targets existing → do NOT silently skip; record an issue ([tasks]: coverage measurement infrastructure missing) and surface it to the user
1701
+ 5. **No numeric target to compare against** — **two distinct cases, one branch** (`T250` / `ISS-226`):
1702
+ * **(5a) no targets defined anywhere** (no plan.md targets, no `[Quality]` coverage tasks, no constitution mandate) → skip, but state "coverage: no targets defined" explicitly in the report.
1703
+ * **(5b) the target exists but is NOT a number** — the `Risk-Based Coverage Targets` table carries a **replacement standard** instead of percentages (clause ids, a named manual procedure). ⚠️ **This used to fall through**: step 1 reads "the table" as if it held thresholds, steps 2–4 then have nothing to compare against, and the old wording of this step ("*No targets defined anywhere*") does **not** fire because a target *is* defined — just not in the form steps 2–4 assume. ⇒ When the cells are not numbers: **follow the standard the table states** (it is binding exactly as a percentage would be), and **state explicitly** in the completion report that this project does not use coverage percentages — quoting the table's own wording. **MUST NOT** report a `>XX%`-shaped threshold and **MUST NOT** pass over the item in silence.
1704
+ ⚠️ The two cases share one branch **deliberately**: splitting them into parallel steps would make each the other's silent gap, which is the shape this repository keeps removing.
1705
+ - Validate implementation matches spec.md requirements (if spec.md exists)
1706
+ - Validate implementation follows plan.md technical design (if plan.md exists)
1707
+ - Report final status: "✓ Implementation complete: N tasks executed"
1708
+
1709
+ Note: This command uses **incremental parsing**, **interactive mode selection**, and **batch execution** for efficiency, safety, and resumability.
1710
+
1711
+ **Interactive Mode Selection** 🎯 [DEFAULT]:
1712
+ - **No arguments**: Shows interactive menu with 5 execution modes
1713
+ - **User chooses**: Single task (1), Small batch (3), Medium batch (5), Phase execution, or All tasks
1714
+ - **Safety first**: Menu displays task counts, progress, and warnings for risky options
1715
+ - **Recommended**: Start with "Single Task" mode, then increase batch size as you gain confidence
1716
+
1717
+ **Advanced Usage** (Arguments):
1718
+ - `--once`: Skip menu, execute 1 task
1719
+ - `--count N`: Skip menu, execute N tasks
1720
+ - `--phase PHASE`: Skip menu, execute entire phase
1721
+ - `--continue`: Skip menu, execute all tasks (⚠️ risk of context overflow)
1722
+
1723
+ **Context Management** ⚠️ [CRITICAL]:
1724
+ - **Default behavior (via menu)**: 1 task per session (safest)
1725
+ - **Small batch (via menu)**: 3 tasks per session (balanced)
1726
+ - **Medium batch (via menu)**: 5 tasks per session (efficient for small tasks)
1727
+ - **Session-based**: Each execution is a session, progress preserved across sessions
1728
+ - **Prevents overflow**: Menu explicitly warns when choosing risky options
1729
+
1730
+ **Resumability**:
1731
+ - Each execution finds the next `[ ]` task
1732
+ - Completed tasks are marked `[x]`
1733
+ - Interrupted runs can resume from last `[ ]` task
1734
+ - No need to parse entire task list on each run
1735
+ - Progress is preserved between sessions
1736
+ - **No need to remember arguments**: Menu guides you every time
1737
+
1738
+ **Test-First Execution** 🧪 [UNIVERSAL]:
1739
+ - **tasks.md may contain test tasks** (project-dependent)
1740
+ - **Test tasks typically appear BEFORE implementation tasks** (Test-First principle)
1741
+ - **Command checks Test-First compliance**:
1742
+ - If implementation task has corresponding test task that's not completed → Warning
1743
+ - If project constitution exists and requires tests → Warning if missing
1744
+ - **Coverage requirements** (if specified in project):
1745
+ - Read from plan.md "Quality Targets" (authoritative), tasks.md `[Quality]` coverage tasks, or constitution
1746
+ - Acceptance = the concrete evidence procedure in Step 14 (actual report + per-module comparison) — never assumed
1747
+ - No targets defined anywhere → explicit "coverage: no targets defined" line in the report (never a silent skip)
1748
+ - **TDD workflow** (when tests are in place):
1749
+ - Test task: Write test, verify it fails (RED)
1750
+ - Implementation task: Write code, verify tests pass (GREEN)
1751
+ - **Universal test file detection**:
1752
+ - Pattern: `*Test.kt`, `*Test.java`, `*Test.ts`, `*test.py`, `*_test.go`
1753
+ - Detects test files across multiple languages
1754
+
1755
+ **Responsibility Boundaries** ⚖️ [CRITICAL]:
1756
+ - **SDD Principle**: Specification-Driven Development requires strict separation
1757
+ * Specification (what): spec.md, plan.md, tasks.md define WHAT to build
1758
+ * Implementation (how): implement command decides HOW to build it
1759
+ - **Function/Flow**: STRICT execution of tasks.md requirements
1760
+ * Implement exactly what tasks.md specifies
1761
+ * Do NOT add features not in tasks.md
1762
+ * Do NOT change design/specification
1763
+ - **UI/Interaction**: FREE discretion
1764
+ * Layout: Full freedom (positioning, spacing, alignment)
1765
+ * Style: Full freedom (colors, fonts, sizes, shapes)
1766
+ * Interaction: Full freedom (animations, transitions, feedback)
1767
+ * Extra features: OK to add (undo, batch operations, shortcuts)
1768
+ - **Decision tree**: "Does it change WHAT (function) or HOW (UI)?"
1769
+ * WHAT = Function → Strict execution
1770
+ * HOW = UI → Free discretion
1771
+ - **No recording**: Most UI/interaction decisions don't need documentation
1772
+ - **Examples**:
1773
+ * ✅ Task: "Add button" → Choose any color/position (FREE - UI)
1774
+ * ❌ Task: "Add login" → Don't add OAuth (STRICT - function)
1775
+ - **See**: "Implement Responsibility Boundaries" section above for full details
1776
+
1777
+ **Issue Feedback Mechanism** 🔄 [WORKFLOW CLOSURE]:
1778
+ - **Purpose**: Record **planning-artifact** issues for feedback to the phase whose planner owns them
1779
+ - **Governing rule**: *a planning error is fixed by the planner, an implementation error by the implementer* — an execution error belongs in fix-tasks.md (product code) or is fixed in place; it is never an issue entry
1780
+ - **Location**: `specs/implement_issues.md`
1781
+ - **The sections this command may write into**: [specify] · [plan] · [tasks] · [constitution] · [test-plan]
1782
+ * **[specify] / [plan] / [tasks] / [constitution]** each have a `--review-issues` consumer — the detect-then-ask model applies to all four
1783
+ * **[constitution]** carries defects in `specs/constitution.md` itself: a principle that no longer matches the practice it governs, a carve-out narrower than its intent, a clause with no enforcement point
1784
+ * **[test-plan]** covers planning errors in `specs/test-tasks.md` — normally reported by `/specpro-test-implement` (its Step 11); `/specpro-implement` may append one but never resolves one
1785
+ - **Format**: `- [ ] ISS-XXX: [Description]`
1786
+ - **Workflow**:
1787
+ * Implement records issues when discovered
1788
+ * User runs `/specpro-specify --review-issues` → Fixes [specify] issues
1789
+ * User runs `/specpro-plan --review-issues` → Updates plan.md
1790
+ * User runs `/specpro-tasks --review-issues` → Updates tasks.md
1791
+ * User runs `/specpro-test-plan` (incremental) → Updates specs/test-tasks.md, if any [test-plan] issues exist
1792
+ * Continue with `/specpro-implement`
1793
+ - **Sequential**: Must fix in order (specify → plan → tasks); `[test-plan]` and `[constitution]` resolve on their own tracks (test-tasks.md sits downstream of plan/tasks; the constitution governs all of them), each by the command that owns it
1794
+ - **Each phase marks only its own issues as [x]**
1795
+ - **See**: Step 13 for complete details
1796
+
1797
+ **Debug Artifact Management** 📝 [MANDATORY DURING DEBUGGING]:
1798
+
1799
+ **Purpose**: Control where AI-generated debugging scripts/programs live and their lifecycle, preventing temporary files from polluting the repository root or source directories
1800
+
1801
+ **Rules**:
1802
+ 1. **Location** — all temporary scripts/programs created during debugging (wrapper scripts, standalone diagnostics, one-off test harnesses, code-surgery scripts) MUST go into a dedicated temporary directory (conventional: `tmp/debug/`), NOT the repository root or source directories
1803
+ 2. **Repository hygiene** — the temporary directory SHOULD be listed in `.gitignore` so accidental artifacts never enter version control
1804
+ 3. **End-of-session disposal** (three-way decision):
1805
+ * **Decision test FIRST** ⚠️ — before picking a branch, ask: **is this tool tied to a STANDING quality target or an expected future re-run** (e.g., a measurement harness for an ongoing perf/memory target, a validator later tasks will reuse)? YES → PROMOTE; NO → DELETE (findings DOCUMENTed). Do NOT match "job is done" mechanically — every branch presumes the current run is finished; the branches differ ONLY on "will it be run again", not on "is this task complete". Evidence found while working (e.g., you documented future re-measurement scenarios) counts as reuse value
1806
+ * DELETE — one-off scripts with no standing re-run need; code-surgery scripts (those editing source files by line number or pattern) MUST be deleted after use — keeping them risks accidental re-execution against changed code
1807
+ * PROMOTE — tools that passed the decision test. Form is flexible: standalone scripts move to a conventional tools directory (e.g., `tools/`); harnesses depending on a module's test classpath (e.g., JUnit profiling classes reusing module fixtures) stay IN that module with ownership clearly marked in KDoc (task ID, non-matrix status) and get registered in the project's tools index / development docs
1808
+ * DOCUMENT — keep only the findings as a development doc (ROOT_CAUSE/DEBUG/FIX); the script itself is not preserved (naturally combined with DELETE; never applied to a tool that passed the decision test)
1809
+ * **Reversibility tiebreaker** — when genuinely uncertain between branches, choose the REVERSIBLE one: keeping/registering a cheap-to-remove artifact costs near zero, deletion requires rework to restore
1810
+ 4. **Forbidden** — creating debug scripts in the repository root, source directories, or documentation directories
1811
+
1812
+ **Development Process Documentation** 📝 [WHEN NEEDED]:
1813
+
1814
+ **Purpose**: Document complex problems, difficult debugging, and important learnings
1815
+
1816
+ **Language Policy**: ⚠️ **the constitution's field is `**Artifact Language**`** — `Documentation Language Policy` is a **section name that exists nowhere** (`T233`/`ISS-206`), so the old pointer sent the reader to a heading they cannot find, in a file that has the real one. The single source is that field (`T172` in this file already reads it by that name).
1817
+ - Follow the project constitution's `**Artifact Language**` setting
1818
+ - See `specs/constitution.md` → the `**Artifact Language**` field (its value is the code the Step 4 language section reads)
1819
+
1820
+ **When to Create Docs**:
1821
+ - **NOT for every task**: Only create docs when needed (see Step 9.d for detailed criteria)
1822
+ - **User-facing docs**: Do NOT create unless explicitly required by tasks.md
1823
+ * Examples: README, API docs, user guides, tutorials
1824
+ * These belong in separate documentation phase if needed
1825
+ - **Development docs**: SHOULD create when encountering complex situations
1826
+ * File type examples: ROOT_CAUSE.md, FORMAT.md, DEBUG.md, FIX.md, SUMMARY.md, RUN_GUIDE.md
1827
+ * Focus on: Problem → Investigation → Solution → Verification
1828
+ * Help future developers (and AI assistants) understand complex code
1829
+ - **Quality over quantity**: Better to have fewer high-quality docs than many low-quality ones
1830
+ - **Location boundary**: development-work docs (tasks.md deliverables, including unit tests and their run guides) go under `docs/implement/` — NEVER in the repository root and NEVER in `docs/test/` (owned by `/specpro-test-implement`)
1831
+
1832
+ **Documentation Structure** (when project has many technical docs):
1833
+
1834
+ **Required** (fixed name):
1835
+ - `PROJECT_NAVIGATION.md`: Main index for development process documentation
1836
+ * Location: `docs/implement/PROJECT_NAVIGATION.md` (conventional location)
1837
+ * Purpose: Quick lookup for finding documents by topic/user story/keyword
1838
+ * When to create: UP-FRONT or when the FIRST technical document is produced (project documentation is assumed to be multi-document)
1839
+
1840
+ **Recommended** (pattern-based names):
1841
+ - `{topic}/index.md`: Topic-specific navigation
1842
+ * Location: `docs/implement/{topic}/index.md`
1843
+ * `{topic}`: Replace with actual topic name (examples: `encoding/`, `authentication/`, `storage/`)
1844
+ * Purpose: Document list, status, reading order for that topic
1845
+ * When to create: Topic has 3+ documents or needs detailed navigation
1846
+
1847
+ **Optional** (pattern-based names):
1848
+ - `{FEATURE}_{TYPE}.md`: Feature-specific documentation
1849
+ * Examples: `USER_AUTH_FIX.md`, `DATABASE_MIGRATION_FORMAT.md`
1850
+ * Type examples: ROOT_CAUSE, FORMAT, DEBUG, FIX, SUMMARY, IMPLEMENTATION, RUN_GUIDE
1851
+ * Purpose: Detailed analysis of specific feature or problem
1852
+
1853
+ **Directory Structure Examples** (illustrative - adapt to your project):
1854
+ ```
1855
+ docs/
1856
+ └── implement/ # Development process documentation (conventional)
1857
+ ├── PROJECT_NAVIGATION.md # Main index (create up-front or with the first document)
1858
+ ├── authentication/ # Example topic name (actual name varies)
1859
+ │ ├── index.md # Topic navigation (recommended for 3+ docs)
1860
+ │ ├── OAUTH_FLOW_FIX.md # Example doc name (follows pattern)
1861
+ │ └── AUTH_DEBUG.md # Example doc name (follows pattern)
1862
+ ├── storage/ # Another example topic
1863
+ │ ├── index.md
1864
+ │ └── DATABASE_MIGRATION_ROOT_CAUSE.md
1865
+ └── [other topics] # Your project's topics
1866
+ ```
1867
+
1868
+ **Note**: Directory names like `authentication/` or `storage/` are EXAMPLES. Use topic names appropriate for your project.
1869
+
1870
+ ---
1871
+
1872
+ ## Protocol Codec Implementation Rules 🌐 [CONDITIONAL — wire-format / protocol implementation]
1873
+
1874
+ **Activation**: decided by the **Activation Gate** (`.specpro/templates/protocol-golden-bytes-guide.md` §6) — trigger T3 (implementing or fixing a byte-stream encoder/decoder or protocol message parser). Consume the verdict recorded upstream (§6.4); do not re-judge it. When activated, the following implementation rules apply.
1875
+
1876
+ - **Single source of truth for same-semantics branches**: byte-count, packing and stream-semantics branches inside a when/switch family MUST NOT be duplicated across functions — converge them into one helper. A family carrying N duplicated branches means a fix can touch N−1 and leave one latent.
1877
+ - **No per-tile or per-message state in decoder member variables**: it leaks across instances. State that genuinely must be shared between callers belongs in a host-side anchor, not inside the decoder.
1878
+ - **Byte-count lateral audit**: after fixing a byte-count or stream-semantics defect in one function, you MUST scan sibling functions in the same decoder family for the same-shaped branch. Symptom-driven fixes miss siblings — fixing one codec without scanning its neighbour is how the same defect recurs.
1879
+ - **Stream-semantics check before touching an encoder**: verify that encoder's stream semantics (continuous single stream vs per-message independent stream; where the in-stream byte count comes from) before editing. Carrying a lesson between encoders whose semantics are opposite is a high-risk trap.
1880
+ - See `.specpro/templates/protocol-golden-bytes-guide.md` §7 for the structural defences in full.
1881
+