@haposoft/cafekit 0.14.1 → 0.15.0

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 (100) hide show
  1. package/README.md +86 -11
  2. package/bin/__tests__/codex-hooks.test.js +331 -0
  3. package/bin/__tests__/codex-native.test.js +458 -0
  4. package/bin/__tests__/installer-safety.test.js +259 -0
  5. package/bin/install.js +30 -8
  6. package/bin/lib/backup.js +82 -18
  7. package/bin/lib/codex-frontmatter.js +56 -0
  8. package/bin/lib/codex-install.js +195 -0
  9. package/bin/lib/context.js +65 -8
  10. package/bin/lib/copy-utils.js +1 -1
  11. package/bin/lib/i18n.js +12 -3
  12. package/bin/lib/managed-writer.js +17 -2
  13. package/bin/lib/manifest.js +21 -4
  14. package/bin/lib/opencode-install.js +21 -19
  15. package/bin/lib/path-safety.js +40 -0
  16. package/bin/lib/version-check.js +25 -12
  17. package/bin/phases/claude-runtime.js +60 -9
  18. package/bin/phases/codex-runtime.js +110 -0
  19. package/bin/phases/copy-payload.js +36 -16
  20. package/bin/phases/post-install.js +98 -48
  21. package/bin/phases/root-config.js +4 -2
  22. package/bin/phases/select-platform.js +105 -66
  23. package/bin/phases/summary.js +6 -1
  24. package/package.json +3 -2
  25. package/src/claude/CLAUDE.md +1 -1
  26. package/src/claude/agents/code-auditor.md +1 -1
  27. package/src/claude/agents/debugger.md +1 -0
  28. package/src/claude/agents/god-developer.md +10 -1
  29. package/src/claude/agents/inspector.md +1 -0
  30. package/src/claude/agents/spec-maker.md +1 -1
  31. package/src/claude/agents/test-runner.md +2 -2
  32. package/src/claude/hooks/__tests__/privacy-block.test.js +50 -10
  33. package/src/claude/hooks/__tests__/spec-gate.test.js +75 -1
  34. package/src/claude/hooks/__tests__/state.test.js +65 -0
  35. package/src/claude/hooks/docs-sync.cjs +15 -21
  36. package/src/claude/hooks/inspect-block.cjs +1 -1
  37. package/src/claude/hooks/lib/config.cjs +0 -5
  38. package/src/claude/hooks/privacy-block.cjs +39 -62
  39. package/src/claude/hooks/spec-gate.cjs +18 -7
  40. package/src/claude/hooks/spec-state.cjs +4 -0
  41. package/src/claude/hooks/state.cjs +13 -3
  42. package/src/claude/hooks/usage.cjs +6 -0
  43. package/src/claude/rules/orchestrator.md +2 -2
  44. package/src/claude/rules/skill-domain-routing.md +27 -86
  45. package/src/claude/rules/skill-workflow-routing.md +11 -82
  46. package/src/claude/rules/state-sync.md +1 -1
  47. package/src/claude/runtime.json +7 -7
  48. package/src/claude/scripts/generate-skill-catalog.cjs +8 -3
  49. package/src/claude/scripts/validate-spec-output.cjs +6 -0
  50. package/src/claude/skills/code-review/references/spec-compliance-review.md +1 -1
  51. package/src/claude/skills/develop/SKILL.md +26 -5
  52. package/src/claude/skills/develop/references/parallel-waves.md +112 -0
  53. package/src/claude/skills/develop/references/quality-gate.md +10 -2
  54. package/src/claude/skills/hotfix/references/parallel-patterns.md +1 -1
  55. package/src/claude/skills/inspect/SKILL.md +42 -113
  56. package/src/claude/skills/inspect/references/internal-inspection.md +16 -135
  57. package/src/claude/skills/specs/SKILL.md +134 -386
  58. package/src/claude/skills/specs/rules/tasks-generation.md +1 -1
  59. package/src/claude/skills/specs/templates/task.md +3 -1
  60. package/src/claude/skills/sync/SKILL.md +2 -2
  61. package/src/claude/skills/sync/references/sync-protocols.md +4 -4
  62. package/src/claude/skills/test/SKILL.md +1 -1
  63. package/src/claude/status.cjs +9 -6
  64. package/src/codex/AGENTS.md +30 -0
  65. package/src/codex/agents-gitignore +11 -0
  66. package/src/codex/gitignore +12 -0
  67. package/src/codex/hooks/agent.cjs +66 -0
  68. package/src/codex/hooks/docs-sync.cjs +66 -0
  69. package/src/codex/hooks/inspect-block.cjs +40 -0
  70. package/src/codex/hooks/lib/hook-context.cjs +93 -0
  71. package/src/codex/hooks/lib/inspect-paths.cjs +199 -0
  72. package/src/codex/hooks/lib/privacy-state.cjs +199 -0
  73. package/src/codex/hooks/lib/spec-receipt.cjs +78 -0
  74. package/src/codex/hooks/lib/spec-utils.cjs +50 -0
  75. package/src/codex/hooks/lib/state-store.cjs +166 -0
  76. package/src/codex/hooks/privacy-approval.cjs +59 -0
  77. package/src/codex/hooks/privacy-block.cjs +182 -0
  78. package/src/codex/hooks/rules.cjs +79 -0
  79. package/src/codex/hooks/session.cjs +114 -0
  80. package/src/codex/hooks/spec-gate.cjs +80 -0
  81. package/src/codex/hooks/spec-state.cjs +73 -0
  82. package/src/codex/hooks/state.cjs +157 -0
  83. package/src/codex/hooks/task-scaffold-guard.cjs +63 -0
  84. package/src/codex/hooks.json +122 -0
  85. package/src/codex/rules/hook-protocols.md +32 -0
  86. package/src/codex/rules/state-sync.md +41 -0
  87. package/src/codex/runtime.json +28 -0
  88. package/src/opencode/plugins/docs-sync.ts +10 -16
  89. package/src/claude/archive-command/code/SKILL.md +0 -55
  90. package/src/claude/archive-command/code/references/execution-loop.md +0 -21
  91. package/src/claude/archive-command/code.md +0 -17
  92. package/src/claude/archive-command/docs.md +0 -609
  93. package/src/claude/archive-command/review/codebase/parallel.md +0 -76
  94. package/src/claude/archive-command/spec-design.md +0 -247
  95. package/src/claude/archive-command/spec-init.md +0 -120
  96. package/src/claude/archive-command/spec-requirements.md +0 -138
  97. package/src/claude/archive-command/spec-status.md +0 -98
  98. package/src/claude/archive-command/spec-tasks.md +0 -173
  99. package/src/claude/archive-command/spec-validate.md +0 -118
  100. package/src/claude/archive-command/test.md +0 -8
@@ -16,18 +16,9 @@ metadata:
16
16
 
17
17
  ## Overview
18
18
 
19
- This skill provides a 10-step workflow to transform ideas into evidence-backed specs:
19
+ 10-step pipeline: `Analyze → Dependency Scan → Complexity Assessment → Init → Evidence Gate + Requirements → Design → Tasks → Review → Completion`. Flags + **Interactive State Discovery** choose *what to run and where to stop* — see **Default Behavior**.
20
20
 
21
- ```
22
- Analyze → Dependency Scan → Complexity Assessment → Init → Evidence Gate + Requirements → Design → Tasks → Review → Completion
23
- ```
24
-
25
- An entry/dispatch layer sits in front of the pipeline: four flags (`--auto`, `--validate`, `--status`, `--archive`) plus **Interactive State Discovery** (the no-flag path) decide *which part of the pipeline to run and where to stop* — see **Default Behavior**. The pipeline itself is unchanged regardless of how it is invoked.
26
-
27
- **CRITICAL:** Before starting, the system MUST:
28
- 1. Scan `specs/` directory for incomplete specs
29
- 2. If any spec is `in_progress` (accept legacy `in-progress` when reading) → ask user whether to continue or create new
30
- 3. Detect cross-spec dependencies (see `references/cross-spec-dependency.md`)
21
+ **CRITICAL before starting:** scan `specs/` for incomplete work; if any is `in_progress` (read legacy `in-progress`) → ask continue vs new; detect cross-spec deps (`references/cross-spec-dependency.md`).
31
22
 
32
23
  ## Core Responsibilities & Rules
33
24
 
@@ -49,22 +40,20 @@ An entry/dispatch layer sits in front of the pipeline: four flags (`--auto`, `--
49
40
  - If scope change needed → ask user, record reason in `spec.json`
50
41
 
51
42
  ### State & Integrity Rules
52
- - Canonical active status string is `in_progress`. Legacy `in-progress` may be READ for compatibility but MUST NOT be generated in new specs.
53
- - `current_phase` is required for live work and must track the active phase (`init`, `requirements`, `design`, `tasks`, `develop`, `test`, `review`).
54
- - `task_files` in `spec.json` MUST exactly match the real files under `tasks/` after Step 7.
55
- - `task_registry` in `spec.json` MUST exist once task files are generated and MUST contain one entry per task file, keyed by relative path.
56
- - `ready_for_implementation` is a hard gate, not a convenience flag. Never set it before the finalization audit passes.
57
- - Non-trivial specs MUST have an evidence trail in `research.md` before requirements, design, or tasks are finalized. Evidence can be codebase scout findings, external/current research, or an explicit skip rationale.
43
+ - Canonical active status: `in_progress` (legacy `in-progress` may be READ only; never emit it).
44
+ - `current_phase` must track the active phase (`init` … `review`).
45
+ - Deterministic validator enforces the structural rules — see Step 8.5.
46
+ - `ready_for_implementation` is a hard gate — never set it before the finalization audit passes.
47
+ - Non-trivial specs MUST have an evidence trail in `research.md` before finalizing requirements/design/tasks.
58
48
 
59
49
  ### Language & Canonical Rules
60
- - **English is the canonical language for every spec artifact** (`spec.json`, `requirements.md`, `research.md`, `design.md`, `tasks/*.md`) — write them in English regardless of the session's response language.
61
- - If the configured language (`.claude/settings.json` → `language`) is not English, you MAY additionally generate a **reference-only translation mirror** under `i18n/<lang>/`. See `references/translation-mirror.md`. The mirror never replaces canonical and is never a source of truth.
50
+ - **English is the canonical language for every spec artifact** — write them in English regardless of the session's response language.
51
+ - Non-English `language` setting MAY add a **reference-only translation mirror** under `i18n/<lang>/`. See `references/translation-mirror.md`.
62
52
 
63
53
  ### Output Criteria
64
54
  - Never implement code — only create spec documents
65
55
  - Return file paths and a brief summary
66
- - Spec files must be self-contained (full context)
67
- - Insert code samples/pseudocode when needed to clarify flow
56
+ - Spec files must be self-contained; insert code samples when needed to clarify flow
68
57
  - Comply with `./docs/development-rules.md` if it exists
69
58
 
70
59
  ### Hard Output Contract
@@ -93,19 +82,17 @@ Forbidden generated artifacts:
93
82
  - Before marking a spec ready, run the deterministic validator:
94
83
  - `node .claude/scripts/validate-spec-output.cjs specs/<feature>`
95
84
  - Any validator failure blocks `ready_for_implementation = true`.
85
+ - Deterministic validator enforces the structural rules — see Step 8.5.
96
86
 
97
87
  ### Writing Style
98
- - Concise, prefer bullet lists
99
- - Get straight to the point, no fluff
88
+ - Concise, prefer bullet lists; no fluff
100
89
  - Unresolved questions → list at the end of each document
101
90
 
102
91
  ## Default Behavior
103
92
 
104
- > **This section is the entry/dispatch layer ONLY.** It decides *which part of the pipeline to run and where to stop*. It does NOT change any pipeline step, the validator, templates, or rules. The detailed Steps 1–10 below are unchanged.
105
-
106
- `hapo:specs` exposes exactly **four flags**: `--auto`, `--validate`, `--status`, `--archive`. Everything else (which spec, new vs continue, how far to run) is resolved by **Interactive State Discovery**, never by extra flags.
93
+ > **This section is the entry/dispatch layer ONLY.** It decides *which part of the pipeline to run and where to stop*. It does NOT change any pipeline step, the validator, templates, or rules.
107
94
 
108
- **Back-compat aliases** (accepted silently, not advertised): bare `status` / `archive` / `resume`, and `--validate` as today. Treat them as their `--flag` equivalents.
95
+ `hapo:specs` exposes exactly **four flags**: `--auto`, `--validate`, `--status`, `--archive`. Everything else is resolved by **Interactive State Discovery**. Bare `status` / `archive` / `resume` are silent back-compat aliases.
109
96
 
110
97
  ### Dispatch order
111
98
 
@@ -117,26 +104,15 @@ Forbidden generated artifacts:
117
104
 
118
105
  ### Interactive State Discovery (no-flag path)
119
106
 
120
- Goal: ask the user enough to determine **state** and **intent**, then run the existing pipeline. This only chooses *what to run and where to stop* — it does not alter any step's logic.
121
-
122
- 1. **Detect state.** Scan `specs/` for unfinished specs (`status=in_progress` / `ready_for_implementation=false`) and git-branch match.
123
- - Found → `AskUserQuestion`: `Continue <spec A> · Continue <spec B> · Create new spec`.
124
- - None → default to create-new.
125
- 2. **Create-new + no description yet** → ask for the description, then analyze it (logic unchanged):
126
- - If description is too short (< 20 words) or missing one concrete detail → stop and ask 1-2 clarifying questions
127
- - If the idea has unresolved architecture choices, unclear acceptance criteria, unclear scope boundaries, or multiple plausible approaches → stop and route to `/hapo:brainstorm <idea>` before creating spec artifacts
128
- - If task is simple (small bugfix, config change) → suggest "A spec may not be needed for this. Continue anyway?"
129
- - If task is complex (multi-module, security/migration related) → auto-activate deep research, ask user 3 scope questions
130
- - For non-trivial specs, execute the Step 5 Evidence Gate before writing final requirements. Do not design from memory when codebase or current external evidence can answer the question.
131
- 3. **Creation Mode Gate** (how far to run) — see the dedicated section below. Options: `Auto (→ Tasks)` · `Stop after Design` · `Step by step`. If `.claude/settings.json` → `language` is not English, also offer the **Translation Mirror** (see below).
132
- 4. **Continue an unfinished spec** → read `spec.json.current_phase`, then `AskUserQuestion` offering the **remaining** stop points (e.g. `→ Design`, `→ Tasks`, `Step by step`) and resume the existing pipeline from that phase. If a message accompanied the call, treat it as added context for the next phase (scope expansion → ask, per `references/ask-user-question-gates.md`).
133
- 5. **Run the chosen scope.** On an early stop, emit the Paused Block (Step 9b). Sync `spec.json` per `state-sync.md`.
134
-
135
- > The pipeline, validator, templates, and rules are unchanged. "Stop after Design" simply halts before Step 7; it runs Steps 1–6 exactly as specified.
107
+ 1. **Detect state** — unfinished specs (`in_progress` / not ready) + git-branch match → `Continue <A> · Continue <B> · Create new`; else create-new.
108
+ 2. **Create-new** — ask description if missing. Too short → 1-2 questions. Unclear architecture/acceptance/scope/multi-approach → `/hapo:brainstorm`. Simple → "spec may not be needed?". Complex → deep research + 3 scope Qs. Non-trivial → Step 5 Evidence Gate.
109
+ 3. **Creation Mode Gate** — see below. Non-English → also offer **Translation Mirror**.
110
+ 4. **Continue** unfinished → resume from `current_phase` with remaining stop points.
111
+ 5. **Run** chosen scope; early stop → Step 9b; sync per `state-sync.md`.
136
112
 
137
113
  ### Creation Mode Gate
138
114
 
139
- Shown once (via `AskUserQuestion`) on the no-flag create path, after the description passes the safety gates. It selects the **stop point only** — every phase that runs uses the unchanged Step logic.
115
+ Shown once on the no-flag create path. Selects the **stop point only**.
140
116
 
141
117
  | Option | Runs | Stops after | Approvals |
142
118
  |---|---|---|---|
@@ -144,19 +120,11 @@ Shown once (via `AskUserQuestion`) on the no-flag create path, after the descrip
144
120
  | **Stop after Design** | Step 1→6 | `design` (before Step 7) | requirements + design `approved=true`; `ready_for_implementation=false` |
145
121
  | **Step by step** | one phase at a time | after each phase | per phase `generated=true`, `approved=false` until user approves |
146
122
 
147
- Rules:
148
- - `--auto` equals choosing **Auto (→ Tasks)** without showing this gate.
149
- - **Stop after Design** / **Step by step** leave `ready_for_implementation=false` and emit the Paused Block (Step 9b).
150
- - Continuing later: run `/hapo:specs` again → Interactive State Discovery detects the unfinished spec and offers the remaining stop points. No flag or keyword required.
123
+ `--auto` = Auto without the gate. Early stops leave `ready_for_implementation=false` and emit Step 9b. Resume via `/hapo:specs` Interactive State Discovery.
151
124
 
152
125
  ### Translation Mirror (optional reference copy)
153
126
 
154
- Load `references/translation-mirror.md`. This is the only language feature in the entry layer; canonical artifacts are always English.
155
-
156
- - Read `.claude/settings.json` → `language`. If it is **not** English and the run is **interactive** (no `--auto`), ask once via `AskUserQuestion`: "Generate a `<language>` reference copy of this spec? (kept in sync, read-only)".
157
- - On `Yes` → set `spec.json.translation` (`enabled`, `language`, `language_code`, `dir: i18n/<code>`, `sync: always`) and, after each canonical doc is written in Steps 5–7, regenerate the matching file under `i18n/<code>/` with the reference-only marker.
158
- - `--auto` does not prompt for a mirror, so an `--auto` create makes none. But if the spec already has `translation.enabled = true` (set in an earlier interactive run), always-sync still applies: an `--auto` resume keeps regenerating the mirror after each canonical write.
159
- - The mirror is reference-only: never validated, never a source of truth, ignored by `hapo:develop`.
127
+ Load `references/translation-mirror.md`. Canonical = English. Non-English interactive run may set `spec.json.translation` and regenerate `i18n/<code>/` after Steps 5–7 writes. `--auto` create skips the prompt unless already enabled. Mirror is reference-only (never validated / never SoT / ignored by develop).
160
128
 
161
129
  ### When called WITH `--validate` argument
162
130
 
@@ -227,185 +195,84 @@ flowchart TD
227
195
  ## Detailed Workflow
228
196
 
229
197
  ### Step 1: Analyze Description
230
- - Load `references/ask-user-question-gates.md` before asking user questions. Ask only at documented gates; do not ask questions that repo evidence or official/current docs can answer.
231
- - Assess clarity and complexity of the description
232
- - Route to `hapo:brainstorm` before creating files when:
233
- - the expected output or acceptance criteria are not concrete
234
- - the scope boundary is unknown
235
- - the request has 2-3 viable architectures and no user-approved direction
236
- - the feature spans 3+ independent subsystems and needs decomposition
237
- - the user is explicitly asking to explore, compare, debate, or decide
238
- - **Multimodal & Document Auto-Ingestion (MANDATORY)**: If the input includes file paths or URLs pointing to images, audio, video, or Office documents, activate the matching skill workflow to extract content BEFORE proceeding:
239
- - `.mp3`, `.wav`, `.mp4`, `.mov`, `.jpg`, `.png`, `.webp` → use `hapo:ai-multimodal` to transcribe/analyze the file
240
- - `.pdf` → use `hapo:pdf` to extract text and tables
241
- - `.docx` → use `hapo:docx` to extract document content
242
- - `.pptx` → use `hapo:pptx` to extract slide content
243
- - `.xlsx`, `.csv` → use `hapo:xlsx` to extract data
244
- - *Append the extracted findings into your working memory as the enriched "description".*
245
- - If description < 20 words or lacks concrete nouns → ask 1-2 clarifying questions
246
- - If task is too simple → warn user that a spec may not be needed
198
+ - Load `references/ask-user-question-gates.md` before asking; do not ask what repo evidence or current docs can answer.
199
+ - Route to `hapo:brainstorm` before creating files when acceptance criteria are not concrete, scope is unknown, 2-3 viable architectures lack a winner, the feature spans 3+ subsystems, or the user wants to explore/compare/debate.
200
+ - **Multimodal & Document Auto-Ingestion (MANDATORY):** media → `hapo:ai-multimodal`; `.pdf` → `hapo:pdf`; `.docx` → `hapo:docx`; `.pptx` → `hapo:pptx`; `.xlsx`/`.csv` → `hapo:xlsx`. Append findings as the enriched description.
201
+ - Description < 20 words or lacks concrete nouns → 1-2 clarifying questions. Too simple → warn a spec may not be needed.
247
202
 
248
203
  ### Step 2: Cross-Spec Dependency Scan
249
- Load: `references/cross-spec-dependency.md`
250
- - Scan `specs/` for incomplete specs
251
- - Compare scope: overlapping files, shared dependencies, same feature area
252
- - Update `spec.json` bidirectionally if relationship detected
204
+ Load: `references/cross-spec-dependency.md` — scan incomplete specs; compare overlapping files/deps; update `spec.json` bidirectionally if related.
253
205
 
254
206
  ### Step 3: Complexity Assessment & Scope Inquiry
255
- Load: `references/scope-inquiry.md`
256
- - Also load `references/ask-user-question-gates.md` when scope, evidence, contract, or architecture decisions require user input.
257
- - Evaluate the request across **5 dimensions**: Semantic Intent, Implementation Hypothesis, Gap Sizing, Risk/Uncertainty (Cynefin), and Blast Radius
258
- - If Risk = **Chaotic** → exit spec workflow, redirect to `hapo:hotfix`
259
- - If Risk = **Complex** → include spike/prototype tasks in the spec
260
- - If Blast Radius = **Critical Path** → spec MUST include rollback strategy and test coverage requirements
261
- - **Complexity smell check (by numbers)** — quick YAGNI tripwires: >8 files touched / >2 new classes-services / >12 task files → challenge or simplify; **>15 task files → split into sibling specs** (a mega-spec is slow + failure-prone, per field test). Surface tripwires in the scope summary; never silently build the mega-version.
262
- - User picks scope level: Expand / Hold / Reduce
263
- - **Skip if:** trivial task (< 20 words, 1 file, user says "just do it")
264
-
265
- #### Execution Tier (auto-scale — set right after the 5-Dimension assessment)
266
- Pick ONE tier from the assessment; it controls how deep the pipeline runs so small specs stay cheap. Record it in `spec.json.design_context.execution_tier`.
267
-
268
- | Tier | Trigger | Research (Step 5 external) | Discovery (Step 6) | Red-Team (Step 8) | Always runs |
207
+ Load: `references/scope-inquiry.md` (+ `references/ask-user-question-gates.md` for scope/evidence/contract/architecture decisions).
208
+ - 5 dimensions: Semantic Intent, Implementation Hypothesis, Gap Sizing, Risk/Cynefin, Blast Radius
209
+ - **Chaotic** → `hapo:hotfix`; **Complex** → spike/prototype tasks; **Critical Path** → rollback + test coverage
210
+ - Smell: >8 files / >2 new classes / >12 tasks → challenge; **>15 tasks → sibling specs**
211
+ - User: Expand / Hold / Reduce. Skip if trivial (< 20 words, 1 file, "just do it")
212
+
213
+ #### Execution Tier (auto-scale — after 5-Dimension assessment)
214
+ Record in `spec.json.design_context.execution_tier`.
215
+
216
+ | Tier | Trigger | Research | Discovery | Red-Team | Always runs |
269
217
  |---|---|---|---|---|---|
270
- | **Light** | Cynefin Clear + Blast Isolated + likely ≤2 tasks | skip (record skip rationale) | minimal | skip → Validate-only | scope_lock, EARS, **Layer 1 + Layer 2 grounding** |
271
- | **Standard** | default (Complicated / Moderate blast / 3-4 tasks) | targeted | light | per Step 8 auto-decision | all of the above |
272
- | **Deep** | Complex/Critical-path / security-migration / 5+ tasks | full (researchers + per-area scout) | full | Red-Team → Validate (mandatory) | all of the above |
218
+ | **Light** | Clear + Isolated + ≤2 tasks | skip (rationale) | minimal | Validate-only | scope_lock, EARS, **Layer 1+2** |
219
+ | **Standard** | default / 3-4 tasks | targeted | light | per Step 8 | all of the above |
220
+ | **Deep** | Complex/Critical / security-migration / 5+ tasks | full | full | Red-Team → Validate | all of the above |
273
221
 
274
- Rules:
275
- - Grounding (Layer 2) + structural validator (Layer 1) + scope_lock **never skip**, any tier — they are the quality floor, not depth knobs.
276
- - Light tier is the antidote to "small spec, full-pipeline overhead". Do NOT use Light for auth/payment/migration/schema/privacy work — those force Deep regardless of size.
277
- - Tier only changes *research/discovery/review depth*; it never changes the Hard Output Contract or DoCT.
222
+ Grounding + validator + scope_lock never skip. Auth/payment/migration/schema/privacy force Deep. Tier never changes Hard Output Contract or DoCT.
278
223
 
279
224
  ### Step 4: Init
280
- - Check for duplicate slugs in `specs/` via Glob
281
- - Create directory `specs/<feature-name>/`
282
- - Create `spec.json` from template `templates/spec-state.json`. The output file name MUST be `spec.json`; never write the template filename into the spec directory.
283
- - Create empty `requirements.md` from template `templates/requirements-init.md`
284
- - Initialize `scope_lock` in `spec.json`:
285
- - `source`: original description
286
- - `in_scope`: confirmed scope items
287
- - `out_of_scope`: excluded items
288
- - `expansion_policy`: `requires-user-approval`
289
- - Step 4 itself only initializes files. The Creation Mode Gate (or `--auto`) decides how far the run proceeds; in every mode Step 4 continues into Step 5 — Init is never a stop point.
225
+ - Check duplicate slugs; create `specs/<feature-name>/`
226
+ - Create `spec.json` from `templates/spec-state.json` (output name MUST be `spec.json`, never the template filename)
227
+ - Create empty `requirements.md` from `templates/requirements-init.md`
228
+ - Init `scope_lock`: `source`, `in_scope`, `out_of_scope`, `expansion_policy: requires-user-approval`
229
+ - Step 4 only initializes; Creation Mode / `--auto` decides how far — Init is never a stop point.
290
230
 
291
231
  ### Step 5: Evidence Gate, Requirements & Research
292
- - Read `spec.json` — stop if init hasn't completed
293
- - Stop if requirements already exist, unless user wants to regenerate
294
- - Respect `scope_lock` — keep new requirements within `in_scope`
295
- - Load `references/research-strategy.md` and `references/codebase-analysis.md`
296
- - Classify evidence needs before writing requirements:
297
- - **Targeted codebase scout is mandatory** when the spec changes existing behavior, touches an API/CLI/package export/schema/auth/session/permission/config/hook/runtime contract, lacks exact file paths, may invalidate tests, resumes an older spec, or crosses monorepo/package/runtime boundaries.
298
- - **External/current research is mandatory** when the spec depends on third-party APIs, libraries, platform policies, AI providers/models/tooling, security/auth/payment/privacy/delete-data rules, performance/accessibility/SEO/security standards, or the user asks for "best", "optimal", "latest", "recommended", or equivalent.
299
- - **Skip evidence gathering only** for trivial one-file edits, internal text/docs changes, isolated new files with no integration points, or decisions already backed by a recent user-provided report. Record the skip rationale in `research.md`.
300
- - Codebase scout must be targeted, not a blind full-repo crawl. Identify relevant files/modules, current patterns, existing tests, contracts, and likely blast radius.
301
- - External/current research must prefer official docs, standards, primary sources, or maintained upstream references. Record source links and the date/context of the finding.
302
- - Write `research.md` before final requirements. It MUST include an Evidence Summary with: codebase scout result, external research result or skip rationale, selected decision, rejected alternatives, remaining gaps, and downstream task/test implications.
303
- - If evidence exposes unresolved architecture choices, unclear acceptance criteria, or multiple viable approaches with no obvious winner, stop and route to `/hapo:brainstorm` instead of forcing a spec.
304
- - Write requirements in **EARS** format (see `rules/ears-format.md`). Give each acceptance criterion an **explicit literal ID `R{N}.{M}`** (e.g. `- **R1.1** When ...`), NOT a bare numbered list. This activates per-criterion coverage at Layer 1 (each `R1.1` must be mapped by a task `_Requirements: 1.1_`). A bare `1. 2. 3.` list silently disables sub-criterion coverage — do not use it for non-trivial specs.
305
- - **Feasibility Check:** Cross-check each requirement against known technical constraints from `research.md`.
306
- - Each requirement gets a unique numeric ID
307
- - **Verify Quality:** Before proceeding, assert each requirement is: *Singular, Unambiguous, Testable, and has a numeric ID*. Include Non-Functional Requirements (Performance, Security, Scalability, Reliability, Accessibility).
308
- - Record any findings in `research.md` from template `templates/research.md`
309
- - Update `spec.json` phase + timestamps
232
+ - Stop if init incomplete or requirements exist (unless regenerate). Respect `scope_lock`.
233
+ - Load `references/research-strategy.md` + `references/codebase-analysis.md`
234
+ - **Scout mandatory** when changing existing behavior, touching API/CLI/export/schema/auth/config/hook/runtime contracts, lacking paths, invalidating tests, resuming old specs, or crossing package boundaries.
235
+ - **External research mandatory** for third-party APIs/libs/policies/AI/security/auth/payment/privacy/standards, or "best/optimal/latest/recommended".
236
+ - **Skip only** for trivial one-file/docs/isolated new files or user-provided report — record rationale in `research.md`.
237
+ - Scout is targeted (not full-repo). External prefers official/primary sources with links + date.
238
+ - Write `research.md` first with Evidence Summary: scout result, external or skip rationale, selected decision, rejected alternatives, gaps, task/test implications.
239
+ - Unresolved architecture / acceptance / multi-approach → `/hapo:brainstorm`, don't force a spec.
240
+ - EARS requirements (`rules/ears-format.md`) with literal IDs `R{N}.{M}` (not bare `1. 2. 3.`) so Layer 1 sub-criterion coverage works via `_Requirements: 1.1_`.
241
+ - Feasibility vs `research.md`; unique numeric IDs; quality = Singular, Unambiguous, Testable + NFRs. Template `templates/research.md`. Update phase + timestamps.
310
242
 
311
243
  ### Step 6: Design
312
- - Read `spec.json` — stop if requirements haven't completed
313
- - Pick discovery mode: `minimal` / `light` / `full` based on complexity. **Default: `light`** unless certain it is simple UI (minimal) or complex integration (full).
314
- - Load `rules/design-principles.md`
315
- - Load `rules/phase-decision-matrix.md` to define implementation slices, task clusters, foundation boundaries, spike needs, integration gates, and verification gates before task generation.
316
- - Load `references/ask-user-question-gates.md` if a design decision would change scope, contract, provider/platform, or implementation safety.
317
- - Load `rules/design-discovery-[mode].md`:
318
- - **minimal**: UI-only or simple CRUD
319
- - **light**: extending existing system
320
- - **full**: integration, security, schema, or performance
321
- - Record findings in `research.md` before finalizing design
322
- - Write `design.md` from template `templates/design.md` (see `rules/design-principles.md`)
323
- - Design decisions MUST trace back to `research.md` evidence. If a design choice lacks evidence and is not a user-approved constraint, gather more evidence or ask the user before finalizing.
324
- - Add diagrams only when design has multi-step or cross-boundary flows
325
- - For auth/session, transport/entrypoint, persistence/schema, generated-artifact, or runtime-sensitive work, the design MUST fill the `Canonical Contracts & Invariants` section and tasks MUST inherit the same decisions verbatim.
326
- - When a data shape must stay byte-identical across layers (e.g. an API response consumed by both a backend task and a frontend task, or a DB row shape), declare it as a **named contract block** — `<!-- contract:NAME -->` followed by a fenced block — per `templates/design.md`. Tasks that produce/consume it add `Contracts: NAME` and copy the block verbatim; the validator then hard-fails on cross-layer drift. Prefer this for any spec spanning BE/FE/DB.
327
- - Update `spec.json` phase, timestamps, discovery mode
244
+ - Stop if requirements incomplete. Discovery: `minimal` / `light` (default) / `full`.
245
+ - Load `rules/design-principles.md`, `rules/phase-decision-matrix.md` (implementation slices, clusters, foundation, spike needs, integration/verification gates), `references/ask-user-question-gates.md` when needed, and `rules/design-discovery-[mode].md`.
246
+ - Record research findings; write `design.md` from `templates/design.md`. Decisions MUST trace to `research.md` evidence.
247
+ - Diagrams only for multi-step/cross-boundary flows. Auth/session/transport/persistence/artifact/runtime work MUST fill `Canonical Contracts & Invariants`; tasks inherit verbatim.
248
+ - Any spec whose tasks span both backend and frontend surfaces MUST declare shared data shapes as named contract blocks. Declare each as `<!-- contract:NAME -->` followed by a fenced block — per `templates/design.md`. Tasks that produce/consume it add `Contracts: NAME` and copy the block verbatim; the validator then hard-fails on cross-layer drift.
249
+ - Update phase, timestamps, discovery mode.
328
250
 
329
251
  ### Step 7: Task Breakdown
330
- - Read `spec.json` — stop if `requirements.md` or `design.md` missing
331
- - Respect `scope_lock` — only use valid requirement IDs within `in_scope`
332
- - Load `rules/tasks-generation.md` for core principles
333
- - Load `rules/phase-decision-matrix.md` before generating task files. Treat "phase" as an implementation slice/task cluster, not a `phase-XX.md` artifact.
334
- - Load `rules/task-scoring-rubric.md` for every candidate task to decide priority, split/merge, spike needs, dependencies, parallel eligibility, and evidence depth.
335
- - Load `references/ask-user-question-gates.md`; if scoring reveals unapproved scope expansion or an unresolved user-owned choice, pause before writing task files.
336
- - **Scaffold is mandatory — raw `Write` to a task file is blocked.** A PreToolUse hook (`task-scaffold-guard.cjs`) rejects any `Write` whose path matches `specs/<feature>/tasks/task-*.md`. The only path to a task file is scaffold → Edit. Once the task list is decided, generate the stubs:
252
+ - Stop if `requirements.md` or `design.md` missing. Respect `scope_lock`.
253
+ - Load `rules/tasks-generation.md`, `rules/phase-decision-matrix.md` (implementation slice/task cluster, not `phase-XX.md`), `rules/task-scoring-rubric.md` (priority, split/merge, spike needs, deps, parallel, evidence depth), and `references/ask-user-question-gates.md` if scoring expands scope.
254
+ - **Scaffold is mandatory — raw `Write` to a task file is blocked.** PreToolUse `task-scaffold-guard.cjs` rejects `Write` to `specs/<feature>/tasks/task-*.md`. Path: scaffold → Edit:
337
255
  `node .claude/scripts/spec-scaffold.cjs <feature> --tasks "R0-01-slug,R1-01-slug,..." --tasks-only`
338
- This creates each `tasks/task-R*.md` from `templates/task.md` and merges `task_files` + `task_registry` into the existing `spec.json` (pending, no overwrite of already-filled tasks). Then **Edit-fill** the `{{...}}` placeholders in each stub (`Edit`/`MultiEdit` are allowed; `Write` is not). (The guard fails open if the scaffold script is absent, and can be disabled via `"spec": { "scaffold_guard": false }` in `.claude/runtime.json`.)
339
- - Each task file follows template `templates/task.md` (scaffold already applies it). **Leave NO `{{...}}` placeholder unfilled** — a stub with placeholders is an incomplete task.
340
- - `Related Files` and test plans must inherit paths, contracts, and test targets from the codebase scout. If exact files/tests cannot be named for an enhancement, run targeted inspect before generating tasks. Every `Related Files` path will be grounded (Layer 2) at Step 8.5 — phantom paths hard-fail, so cite real paths.
341
- - Each task file MUST include `Completion Criteria` and `Evidence` sections detailed enough that a downstream quality gate can prove the task is truly done. Existing specs may use `Task Test Plan & Verification Evidence` or legacy `Verification & Evidence`.
342
- - Each task's `Evidence` MUST choose the right proof type for the touched surface: unit for pure logic, component/integration for UI or state wiring, E2E/UI flow for complete user workflows, visual/responsive checks for style/layout work, accessibility checks for interactive UI, smoke checks for scaffold/config, regression checks for bug fixes, and performance/security checks only when the requirement or risk calls for them.
343
- - Every task MUST preserve the approved `scope_lock`: implement all scoped acceptance criteria for its requirement, avoid out-of-scope features, and record any intentional deferral as a named later task rather than implicit omission.
344
- - For UI/app/runtime features, generate a final integration/reachability task or final section that names the real runtime entrypoint and proves prior task outputs are imported, mounted, registered, invoked, or otherwise reachable.
345
- - Build `spec.json.task_registry` alongside `task_files`. For each task file, register at minimum:
346
- - `id`
347
- - `title`
348
- - `status` (`pending` by default)
349
- - `dependencies` (relative task paths, not prose labels)
350
- - `blocker`
351
- - `started_at`
352
- - `completed_at`
353
- - `last_updated_at`
354
- - Update `spec.json` phase + task metadata
256
+ Creates stubs from `templates/task.md`, merges `task_files` + `task_registry` (no overwrite of filled tasks). **Edit-fill** all `{{...}}` (`Edit`/`MultiEdit` ok; `Write` not). Fails open if scaffold missing; disable via `"spec": { "scaffold_guard": false }`.
257
+ - Leave NO `{{...}}` unfilled. Related Files/tests inherit scout paths — Layer 2 grounds them at Step 8.5; phantom paths hard-fail.
258
+ - Each task MUST include `Completion Criteria` and `## Evidence` (legacy heading aliases still parse). Choose proof type by surface (unit / component / E2E / visual / a11y / smoke / regression / perf-security when required).
259
+ - Preserve `scope_lock`; deferrals = named later tasks. UI/runtime specs need a final reachability task naming a real entrypoint.
260
+ - Register each task: `id`, `title`, `status` (`pending`), `dependencies` (relative paths), `blocker`, `started_at`, `completed_at`, `last_updated_at`.
355
261
 
356
262
  #### Requirement-Covered Task Grouping (MANDATORY)
357
- Tasks MUST be organized by implementation flow while preserving explicit requirement coverage. Foundation work uses `R0`; feature work uses `R1+`.
263
+ **Naming:** `tasks/task-R{N}-{SEQ}-<slug>.md` — R0 foundation, R1+ feature; SEQ two-digit; kebab slug.
264
+ Example: `task-R0-01-database-schema-foundation.md`, `task-R1-01-captions-observer.md`.
358
265
 
359
- **Naming convention:** `tasks/task-R{N}-{SEQ}-<slug>.md`
360
- - `R{N}` = foundation or implementation cluster (R0 foundation, R1+ feature work)
361
- - `{SEQ}` = sequential number within that requirement (01, 02, 03...)
362
- - `<slug>` = descriptive kebab-case name
363
-
364
- **Example output:**
365
- ```
366
- tasks/
367
- ├── task-R0-01-database-schema-foundation.md # Shared foundation
368
- ├── task-R0-02-auth-routing-foundation.md # Shared foundation
369
- ├── task-R1-01-captions-observer.md
370
- ├── task-R1-02-gap-marker-detector.md
371
- ├── task-R1-03-chunk-api-endpoint.md
372
- ├── task-R2-01-summarize-orchestrator.md
373
- ├── task-R2-02-provider-integration.md
374
- ├── task-R3-01-consent-onboarding.md
375
- ...
376
- ```
377
-
378
- **Splitting rules:**
379
- - Split by real implementation dependency chain first: model/schema -> service -> API -> UI -> integration.
380
- - A task file MAY cover multiple requirement IDs when one code change naturally satisfies them.
381
- - A requirement MAY be covered by multiple task files when it spans layers.
382
- - Do not create all tasks under `R0`; `R0` is only shared foundation/setup.
383
- - After generating all tasks: verify **every requirement ID** appears in at least one task file's `## Requirements` section — gaps = failure.
384
- - **Legacy Protection:** If the `research.md` identified existing codebase files or tests that will be broken (Blast Radius), you MUST generate explicitly tasked files (e.g., `task-R5-01-update-legacy-tests.md`) to fix those breakages. Do not leave broken tests out of scope.
385
-
386
- **Dependency ordering:** Tasks within the same requirement are ordered by natural implementation flow. Cross-requirement dependencies use `Dependencies:` field referencing other task file names.
266
+ Split by dependency chain (schema → service → API → UI → integration). Tasks may cover multiple IDs; IDs may span tasks. Not all under R0. Every requirement ID must appear in some task's `## Requirements`. Blast-radius breakages → explicit fix tasks. Cross-req deps via `Dependencies:`.
387
267
 
388
268
  #### Task File Quality Requirements (MANDATORY)
389
- Each task file MUST be **self-contained and implementation-ready** — detailed enough for a junior developer or AI coding agent to execute without guessing.
390
-
391
- **Structure per task file:**
392
- 1. **Context** — why this task exists, current state, target outcome, relevant exact files.
393
- 2. **Constraints** — MUST / SHOULD / MUST NOT / SCOPE guardrails.
394
- 3. **Steps** — concise implementation checklist with business intent and code-level detail.
395
- 4. **Requirements** — list requirement IDs and acceptance criteria covered by this task.
396
- 5. **Related Files** — table with exact paths, action type, and descriptions when paths are known; otherwise run scout first.
397
- 6. **Completion Criteria** — observable, testable criteria.
398
- 7. **Evidence** — automated command(s), artifact/runtime proof, negative-path proof, and runtime reachability proof.
399
- 8. **Risk Assessment** — table with risk, severity, mitigation.
269
+ Self-contained and implementation-ready. Structure: **Context**, **Constraints**, **Steps**, **Requirements**, **Related Files**, **Completion Criteria**, **Evidence**, **Risk Assessment**.
400
270
 
401
271
  **Template fidelity is mandatory:** preserve the task template headings exactly. Do NOT rename `## Context` to `## Objective`, do NOT replace `## Completion Criteria` with prose, do NOT remove `## Related Files`, `## Constraints`, or `## Risk Assessment`, and do NOT collapse `## Evidence` into generic QA scenarios. Compact wording is fine; missing sections are invalid.
402
272
 
403
- **Parallel markers:** Append `(P)` to tasks that can run concurrently (no data dependency, no shared files, no prerequisite approval from another task). Tasks serving DIFFERENT requirements are often parallelizable.
404
-
405
- **FORBIDDEN:** Task files with only vague checkboxes and no exact files, requirements, or evidence. Compact is good; vague is invalid.
273
+ Parallel: append `(P)` when no data/file/approval deps. **FORBIDDEN:** vague checkboxes without exact files/requirements/evidence.
406
274
 
407
275
  #### Definition of a Complete Task (DoCT) — the quality bar
408
- A task is "complete enough to implement without guessing" only when ALL hold. Each item is enforced by a named mechanism, not goodwill:
409
276
 
410
277
  | DoCT element | Enforced by |
411
278
  |---|---|
@@ -415,48 +282,39 @@ A task is "complete enough to implement without guessing" only when ALL hold. Ea
415
282
  | **Evidence** uses commands that exist in the project (`package.json`) | Author + grounding spirit; never invent test commands |
416
283
  | **Reachability** names a real entrypoint/caller | `Runtime reachability verification` (Layer 1 presence) + judgment |
417
284
  | **Requirements mapping** present (`_Requirements: x.y_`) | Layer 1 coverage check |
418
- | **FE fidelity** — if a visual reference (image/Figma/tokens/style guide) is provided, the task carries the concrete values (hex/font/spacing/verbatim text) + a `match <reference>` constraint | `tasks-generation.md` Frontend Fidelity Rule + reviewer/visual check |
285
+ | **FE fidelity** — if a visual reference is provided, task carries concrete values + `match <reference>` constraint | `tasks-generation.md` Frontend Fidelity Rule + reviewer/visual check |
419
286
 
420
- A stub with unfilled `{{...}}` placeholders fails DoCT by definition. The two scripts (Layer 1 structural + Layer 2 grounding) are the floor; reviewer judgment covers the rest.
287
+ Unfilled `{{...}}` fails DoCT. Layer 1+2 are the floor; reviewer judgment covers the rest.
421
288
 
422
289
  ### Step 8: Validation Review (Optional)
423
- Load: `references/review.md` + `rules/design-review.md`
424
- - Load `references/ask-user-question-gates.md` before applying validation or red-team changes. User approval is required when findings modify approved scope, requirements, canonical contracts, design decisions, or task behavior.
425
- - System auto-evaluates spec complexity and decides review depth:
426
- - **< 3 task files, no security concerns** → Validate only (lightweight interview)
427
- - **>= 5 task files OR security/migration keywords** → Red Team first, then Validate
428
- - **User explicit request** → respect user's intent
429
- - Set `design_context.validation_recommended = true` if the spec includes any of: auth/session, privacy, deletion, migration, schema change, external AI/provider switching, browser extension permissions, or 5+ task files.
430
- - When both run: Red Team ALWAYS before Validate (red team may change the spec)
431
- - **PROHIBITION:** The system MUST NOT skip Red Team because of a prior code-auditor review. Code review ≠ Spec review.
432
- - **PROHIBITION:** The system MUST NOT create `.ts`, `.js`, `.py` or any implementation files during validation. Spec-only outputs.
433
- - **Reconciliation Rule:** `validation.status = "completed"` is forbidden until all accepted findings and validation decisions are physically propagated into `requirements.md`, `design.md`, `tasks/*.md`, and `spec.json` where applicable.
434
- - **Deterministic Gate (2 layers):** Run `node .claude/scripts/validate-spec-output.cjs specs/<feature>` (structural) AND `node .claude/scripts/spec-ground.cjs specs/<feature> [--root <work-context>]` (grounding — paths exist) after all fixes and before final output. Either script failing overrides any LLM checklist result and blocks `ready_for_implementation = true`.
290
+ Load: `references/review.md` + `rules/design-review.md` + `references/ask-user-question-gates.md` before applying findings that change scope/contracts/tasks.
291
+ - Auto-depth: **< 3 tasks, no security** → Validate only; **≥ 5 OR security/migration** → Red Team then Validate; user request → respect
292
+ - `validation_recommended = true` for auth/session/privacy/deletion/migration/schema/AI-provider/extension-permissions or 5+ tasks
293
+ - Red Team always before Validate when both run. MUST NOT skip Red Team for code-auditor reviews. MUST NOT create implementation files.
294
+ - `validation.status = "completed"` only after findings propagated into requirements/design/tasks/spec.json.
295
+ - **Deterministic Gate (2 layers):** `validate-spec-output.cjs` + `spec-ground.cjs` after fixes. Either script failing overrides any LLM checklist result and blocks `ready_for_implementation = true`.
435
296
 
436
297
  ### Step 8.5: Finalization Audit (MANDATORY)
437
- - Re-scan the `tasks/` directory and rebuild `spec.json.task_files` + `task_registry` from the real filesystem (sorted relative paths; preserve task status when the path still matches).
438
- - **Layer 1 — Structural:** run `node .claude/scripts/validate-spec-output.cjs specs/<feature>` and treat any non-zero exit as a blocking failure.
439
- - **Layer 2 — Grounding (MANDATORY):** run `node .claude/scripts/spec-ground.cjs specs/<feature> [--root <work-context>]` and treat any non-zero exit as a blocking failure. This greps the real work tree to verify every `Related Files` path a task cites (Modify/Delete/Read) actually exists — or is Created by another task in the spec. Pass `--root` when the code lives apart from the spec (monorepo / sibling project). A spec that PASSES Layer 1 but FAILS Layer 2 is trolling phantom files and is NOT ready.
298
+ - Rebuild `task_files` + `task_registry` from real `tasks/` (sorted; preserve status when path matches).
299
+ - **Layer 1 — Structural:** `node .claude/scripts/validate-spec-output.cjs specs/<feature>` — non-zero = block.
300
+ - **Layer 2 — Grounding (MANDATORY):** `node .claude/scripts/spec-ground.cjs specs/<feature> [--root <work-context>]` — non-zero = block. Verifies every Modify/Delete/Read Related Files path exists or is Created earlier. Layer 1 pass + Layer 2 fail = NOT ready.
440
301
 
441
302
  **Validator-enforced (do not re-check by hand — a clean exit clears all of these):** task_files/task_registry synced to disk; task naming `tasks/task-R{N}-{SEQ}-<slug>.md`; no forbidden artifacts; research.md Evidence Summary present; every requirement **and sub-criterion** covered by a task; each task keeps the full template (Context, Constraints, Steps, Related Files, Completion Criteria, Evidence, Risk Assessment) plus Runtime reachability; numeric requirement IDs only; validation_recommended vs validation.status; timestamps not reused from init; ready_for_implementation blocked while any error exists.
442
303
 
443
- **Grounding-enforced (spec-ground.cjs — do not re-check by hand):** every Modify/Delete/Read path in any task's `Related Files` exists in the work tree or is Created earlier in the spec. Phantom paths hard-fail.
444
-
445
- **Judgment-only audit (validator cannot see these — assert manually):**
446
- - FAIL if a UI/app/runtime spec has multiple user-facing task outputs but no final integration/reachability task or section.
447
- - FAIL if accepted validation/red-team decisions exist in reports but are not reflected in implementation-facing sections (`Context`, `Steps`, `Requirements`, `Completion Criteria`, `Evidence`, canonical contracts, or requirements text).
448
- - FAIL if the scope/provider switched away from Anthropic/Claude but `requirements.md`, `design.md`, or `tasks/*.md` still contain stale strings such as `Claude API`, `Haiku`, or `haiku_reachable`. `research.md` is the only allowed place for historical comparisons.
449
- - FAIL if privacy/delete-data work lacks a single canonical deletion policy. The design MUST explicitly choose either:
450
- 1. hard-delete with no re-registration lock, or
451
- 2. privacy-preserving re-registration lock using a non-raw identifier (for example `email_hash` / `email_fingerprint`) with a retention period.
452
- Tasks and requirements must reuse the same policy verbatim; mixed policies are invalid.
453
- - FAIL if `validation.status = "completed"` but `timestamps.validation_done` / `review_done`, `updated_at`, and report metadata are not synchronized with the final reviewed state.
454
- - If `validation_recommended = true` and `validation.status` is not `completed` (or an explicit user-accepted risk state), `ready_for_implementation` MUST remain `false`.
455
- - If `translation.enabled = true`, ensure `i18n/<language_code>/` exists and was re-synced after the final canonical write; the mirror is excluded from validation and never blocks `ready_for_implementation`.
456
- - Only after this audit passes may the system mark `progress.tasks = "done"` and `ready_for_implementation = true`.
304
+ **Grounding-enforced:** every Modify/Delete/Read Related Files path exists or is Created earlier. Phantom paths hard-fail.
305
+
306
+ **Judgment-only audit:**
307
+ - FAIL: multi-output UI/runtime spec without final integration/reachability task.
308
+ - FAIL: accepted review decisions not reflected in Context/Steps/Requirements/Completion Criteria/Evidence/contracts.
309
+ - FAIL: stale Claude/Haiku strings outside `research.md` after provider switch.
310
+ - FAIL: privacy/delete-data without one canonical policy (hard-delete, or hash-based re-reg lock + retention) reused verbatim by tasks.
311
+ - FAIL: `validation.status=completed` without synced `validation_done`/`review_done`/`updated_at`/report metadata.
312
+ - `validation_recommended` without completed validation (or recorded risk acceptance) → keep `ready_for_implementation=false`.
313
+ - `translation.enabled` → re-sync `i18n/<code>/` after final write (mirror never blocks ready).
314
+ - Only after audit passes: `progress.tasks = "done"` and `ready_for_implementation = true`.
457
315
 
458
316
  ### Step 9: Completion — Context Reminder (MANDATORY)
459
- After completing the spec, output a short summary of what was generated, then you MUST output the following block EXACTLY as written. DO NOT use awkward translations like "Điểm đã phản ánh đúng quyết định của bạn", keep it professional or just output the block directly:
317
+ Output a short summary, then this block EXACTLY (no awkward translations — keep professional):
460
318
 
461
319
  **Command integrity:** The implementation handoff command is always `/hapo:develop <feature>`. Never suggest `/work`, `/code`, or any non-CafeKit alias as the next step for this workflow.
462
320
 
@@ -470,7 +328,7 @@ After completing the spec, output a short summary of what was generated, then yo
470
328
 
471
329
  ### Step 9b: Paused Block (early stop)
472
330
 
473
- When the run stops before Tasks (Creation Mode = **Stop after Design** or **Step by step**), do NOT print the completion block above and do NOT run the deterministic validator (no tasks exist yet). Instead print:
331
+ Early stop (**Stop after Design** / **Step by step**): no completion block, no validator. Print:
474
332
 
475
333
  ```
476
334
  ⏸ Spec paused at <phase>: specs/<feature>/
@@ -478,99 +336,39 @@ When the run stops before Tasks (Creation Mode = **Stop after Design** or **Step
478
336
  (or /hapo:specs <feature> --auto to finish straight to Tasks)
479
337
  ```
480
338
 
481
- `ready_for_implementation` stays `false`. The next `/hapo:specs` run re-detects this spec via Interactive State Discovery and offers the remaining phases.
339
+ `ready_for_implementation` stays `false`. Next `/hapo:specs` re-detects via Interactive State Discovery.
482
340
 
483
341
  ## Active Spec State
484
342
 
485
- When user calls `hapo:specs`, system checks `specs/`:
486
-
487
- | Situation | Action |
488
- |---|---|
489
- | A spec is `in_progress` | Interactive State Discovery offers `Continue <name>` (resume from `<phase>`) vs `Create new spec` |
490
- | A spec matches current git branch | Offer `Continue <X>` vs `Create new` |
491
- | Nothing found | Create new spec → Creation Mode Gate |
492
-
493
- **Next step suggestions based on `spec.json`:**
494
-
495
- | Current phase | Suggestion |
343
+ | Situation / phase | Action / suggestion |
496
344
  |---|---|
497
- | `init` done | "Next: write requirements" |
498
- | `requirements` done | "Next: architectural design" |
499
- | `design` done | "Next: break into tasks" |
500
- | `tasks` done + validation recommended but incomplete | "Next: `/hapo:specs --validate <feature>`" |
501
- | `tasks` done + ready_for_implementation = true | "Next: `/hapo:develop <feature>`" |
502
- | Spec is `blocked` | "Warning: spec `X` is blocking this spec" |
345
+ | `in_progress` or branch match | Continue vs Create new |
346
+ | Nothing found | Create new → Creation Mode Gate |
347
+ | `init` / `requirements` / `design` done | write requirements / design / break into tasks |
348
+ | tasks done, validation incomplete | `/hapo:specs --validate <feature>` |
349
+ | ready_for_implementation = true | `/hapo:develop <feature>` |
350
+ | `blocked` | warn which spec blocks |
503
351
 
504
- **State persistence:** Update `spec.json` `phase` field on each transition. `spec.json` is the single source of truth.
352
+ `spec.json` is the single source of truth — sync phase on each transition.
505
353
 
506
354
  ### spec.json Update Rules (MANDATORY)
507
355
 
508
- **Canonical status vocabulary:** Use `in_progress`, `blocked`, `done`, and `archived`. New specs MUST NOT emit `in-progress`.
509
-
510
- **Timestamps:** Each `timestamps.*_done` field MUST use the **actual current time** (ISO 8601 with timezone) when that specific phase completes. This includes `review_done` and `validation_done` after review/validate workflows. Do NOT reuse the `init` timestamp for later phases. If running the full pipeline end-to-end, capture a fresh timestamp at each phase transition.
511
-
512
- **Approvals (auto-approval behavior):**
513
- - When running the **full pipeline end-to-end** (`--auto` or Creation Mode "Auto", init → tasks in one session): set `approvals.{phase}.generated = true` AND `approvals.{phase}.approved = true` for each completed phase before proceeding to the next.
514
- - When running to an **early stop point** (Creation Mode "Stop after Design"): for each phase that ran to reach the stop point, set `generated = true` AND `approved = true`; do not generate later phases; keep `ready_for_implementation = false`.
515
- - When running a **single phase** (Creation Mode "Step by step"): set `generated = true` but leave `approved = false` — user must explicitly approve before continuing.
516
-
517
- **Task inventory:** `task_files` MUST be present and MUST list every real task file exactly once using relative paths like `tasks/task-R1-01-example.md`.
518
- Task paths that omit the `task-` prefix or use non-padded sequence numbers (for example `tasks/R1-1-example.md`) are invalid for new CafeKit specs.
519
-
520
- **Task machine-state:** `task_registry` MUST be present after Step 7. Each key is a relative task path, and each value MUST contain `id`, `title`, `status`, `dependencies`, `blocker`, `started_at`, `completed_at`, and `last_updated_at`.
521
-
522
- **Validation recommendation:** `design_context.validation_recommended` MUST be `true` for auth, privacy, delete-data, migration, schema-change, browser-extension-permission, external-provider, or 5+ task file specs.
523
-
524
- **Translation mirror:** `translation` records the optional reference copy (`enabled`, `language`, `language_code`, `dir`, `sync: always`, `last_synced_at`). Canonical artifacts stay English; when `enabled = true`, regenerate `i18n/<language_code>/` after each canonical doc write and stamp `last_synced_at`. The mirror never affects `ready_for_implementation`. See `references/translation-mirror.md`.
525
-
526
- **`ready_for_implementation`:** This field MUST only be set to `true` when ALL of the following conditions are met:
527
- 1. `approvals.requirements.approved = true`
528
- 2. `approvals.design.approved = true`
529
- 3. `approvals.tasks.approved = true`
530
- 4. `progress.tasks = "done"`
531
- 5. `task_files` matches the real filesystem
532
- 6. `task_registry` matches the real filesystem and does not omit any task file
533
- 7. If `design_context.validation_recommended = true`, `validation.status = "completed"` (or another explicit user-accepted risk state that is recorded)
534
-
535
- If any approval is `false`, `ready_for_implementation` MUST remain `false`. If the spec has 5+ task files, `ready_for_implementation` MUST remain `false` until `/hapo:specs <feature> --validate` completes Red Team + Validate and writes `validation.status = "completed"`.
536
-
537
- ## Output Structure
538
-
539
- ```
540
- specs/
541
- └── <feature-name>/
542
- ├── spec.json # Metadata, state, scope_lock, dependencies, task_registry
543
- ├── requirements.md # Technical requirements (EARS format)
544
- ├── research.md # Research notes
545
- ├── design.md # Architectural design
546
- ├── tasks/ # Foundation + implementation clusters (R0, R1, R2...)
547
- │ ├── task-R0-01-foundation.md
548
- │ ├── task-R1-01-<slug>.md
549
- │ ├── task-R1-02-<slug>.md
550
- │ ├── task-R2-01-<slug>.md
551
- │ ├── task-R3-01-<slug>.md
552
- │ └── ...
553
- └── reports/ # Auxiliary reports
554
- ├── researcher-01.md
555
- ├── inspect-report.md
556
- └── red-team-report.md
557
- ```
558
-
559
- When `translation.enabled` is true, a reference-only mirror is added alongside (English stays canonical):
560
-
561
- ```
562
- specs/<feature-name>/
563
- └── i18n/<lang-code>/ # reference only — generated from canonical, never validated
564
- ├── requirements.md
565
- ├── design.md
566
- ├── research.md
567
- └── tasks/task-R*.md
568
- ```
356
+ | Field | Rule |
357
+ |---|---|
358
+ | Status | `in_progress` / `blocked` / `done` / `archived` only (never emit `in-progress`) |
359
+ | Timestamps | Each `timestamps.*_done` = actual ISO 8601 time at that phase; never reuse init |
360
+ | Approvals (Auto / full pipeline) | `generated=true` + `approved=true` per completed phase |
361
+ | Approvals (Stop after Design) | phases that ran: both true; later phases ungenerated; `ready_for_implementation=false` |
362
+ | Approvals (Step by step) | `generated=true`, `approved=false` until user approves |
363
+ | `task_files` / `task_registry` | Exact match to disk after Step 7; registry keys = relative paths with full registry fields |
364
+ | `validation_recommended` | `true` for auth/privacy/delete/migration/schema/extension/provider or 5+ tasks |
365
+ | `translation` | optional mirror metadata; never affects ready gate |
366
+ | `ready_for_implementation` | `true` only when requirements+design+tasks approved, `progress.tasks=done`, inventories match disk, and validation completed when recommended |
367
+
368
+ If any approval is `false`, keep `ready_for_implementation = false`. Specs with 5+ tasks stay not-ready until `--validate` writes `validation.status = "completed"`.
569
369
 
570
370
  ## Subcommands
571
371
 
572
- The canonical surface is four flags. Bare-verb forms are kept only as silent back-compat aliases.
573
-
574
372
  | Command | Purpose | Reference |
575
373
  |---|---|---|
576
374
  | `/hapo:specs --status` | View status of all specs (alias: `status`) | — |
@@ -582,81 +380,31 @@ The canonical surface is four flags. Bare-verb forms are kept only as silent bac
582
380
  ## Quality Standards
583
381
 
584
382
  ### Spec Content
585
- - Specific enough for a junior developer to understand and execute
586
- - Every requirement must be testable/verifiable
587
- - Design must state trade-offs, not just solutions
588
- - Every task must have clear definition of done
383
+ - Junior-executable; every requirement testable; design states trade-offs; tasks have clear DoD
589
384
 
590
385
  ### Security & Performance
591
- - Design must include security assessment (at least OWASP Top 10)
592
- - Evaluate performance for potential bottlenecks
593
- - Rollback plan for each major change
386
+ - OWASP-minded security assessment; bottlenecks + rollback for major changes
594
387
 
595
388
  ### Consistency
596
- - Match existing codebase patterns
597
- - Comply with `./docs/development-rules.md`, `./docs/code-standards.md`
598
- - Check file naming conventions per project rules
389
+ - Match codebase patterns; comply with `./docs/development-rules.md`, `./docs/code-standards.md`
599
390
 
600
391
  ### Maintainability
601
- - Design for the future — require extensibility
602
- - Document rationale behind every architectural decision
603
- - No over-engineering: if a function suffices, don't create a class
392
+ - Document rationale; extensible without over-engineering (function > class when enough)
604
393
 
605
394
  ### Pre-Finalization Checklist
606
- Before finalizing any specification, assert all the following.
607
-
608
- **Machine-enforced** (run `node .claude/scripts/validate-spec-output.cjs specs/<feature>` — it hard-fails on all of these, so do not re-verify by hand): scope_lock object, research.md Evidence Summary, every requirement + sub-criterion covered by a task, each task has Completion Criteria + Evidence + Risk Assessment + the required headings, task_files/task_registry synced to disk with valid dependencies, task naming convention, validation gate vs validation.status, timestamps not reused. A clean validator exit clears this whole group.
395
+ Deterministic validator enforces the structural rules — see Step 8.5.
609
396
 
610
- **Judgment-only** (validator cannot see these — assert manually):
611
- - [ ] **EARS format** applied to all acceptance criteria, with measurable thresholds (no "fast"/"safe"/"robust")
612
- - [ ] **Discovery mode** selected and recorded in spec.json.design_context
613
- - [ ] **Requirements traceability** matrix present in design.md
614
- - [ ] **Canonical Contracts & Invariants** filled for auth/transport/persistence/artifact-sensitive work, and inherited verbatim by every task that touches the contract
615
- - [ ] **State Machine Blueprint:** design.md contains Mermaid diagrams for non-trivial flows
616
- - [ ] **Test strategy defined**: what gets unit tested, integration tested, e2e validated
617
- - [ ] **Provider wording clean**: no stale vendor/provider strings outside allowed research context
618
- - [ ] **Validation decisions propagated** into implementation-facing sections, not only reports/Risk Assessment
397
+ **Judgment-only:** EARS with measurable thresholds; discovery mode recorded; traceability matrix; Canonical Contracts filled + inherited; Mermaid for non-trivial flows; unit/integration/e2e strategy; clean provider wording outside research; validation decisions propagated into implementation-facing sections.
619
398
 
620
- ## When TO Use
399
+ ## When TO Use / NOT
621
400
 
622
- ✅ Creating a new complex feature
623
- ✅ Need documentation before coding
624
- ✅ Working with a team (need spec review)
625
- ✅ Project requires an audit trail
401
+ ✅ Complex features, pre-code docs, team review, audit trail
402
+ ❌ Simple bugfixes, < 1 hour changes, emergency hotfixes
626
403
 
627
- ## When NOT to Use
404
+ ## Resources
628
405
 
629
- ❌ Simple bugfixes
630
- ❌ Small changes (< 1 hour)
631
- ❌ Emergency hotfixes
406
+ **Templates:** `spec-state.json`, `requirements-init.md`, `requirements.md`, `design.md`, `research.md`, `task.md`; validator `.claude/scripts/validate-spec-output.cjs`
632
407
 
633
- ## Resources
408
+ **Rules:** `ears-format.md`, `design-principles.md`, `design-discovery-full.md`, `design-discovery-light.md`, `design-review.md`, `phase-decision-matrix.md`, `tasks-generation.md`, `task-scoring-rubric.md`
634
409
 
635
- ### Templates (`templates/`)
636
- - `spec-state.json` — Metadata/state schema used to create `spec.json`
637
- - `requirements-init.md` — Empty requirements template
638
- - `requirements.md` — Full requirements template
639
- - `design.md` — Design document template
640
- - `research.md` — Research log template
641
- - `task.md` — Template for individual task file
642
- - `.claude/scripts/validate-spec-output.cjs` — Deterministic validator for generated spec artifacts
643
-
644
- ### Rules (`rules/`)
645
- - `ears-format.md` — EARS requirements standard
646
- - `design-principles.md` — Design principles
647
- - `design-discovery-full.md` — Full research workflow
648
- - `design-discovery-light.md` — Lightweight research workflow
649
- - `design-review.md` — Design review GO/NO-GO process
650
- - `phase-decision-matrix.md` — Implementation slice/task-cluster boundary rules
651
- - `tasks-generation.md` — Task generation rules (includes spike task rules + parallel analysis)
652
- - `task-scoring-rubric.md` — Task priority, split/merge, spike, dependency, and evidence-depth scoring
653
-
654
- ### References (`references/`)
655
- - `ask-user-question-gates.md` — AskUserQuestion gate matrix for user-owned decisions
656
- - `cross-spec-dependency.md` — Cross-spec dependency detection
657
- - `scope-inquiry.md` — 5-Dimension Complexity Assessment (Semantic, Hypothesis, Gap, Risk/Cynefin, Blast Radius)
658
- - `research-strategy.md` — Research strategy (7 tools)
659
- - `codebase-analysis.md` — Codebase analysis (4 mandatory files)
660
- - `review.md` — Spec review (auto-decides: red team 8 steps + validate 6 steps)
661
- - `archive-workflow.md` — Archive workflow (5 steps)
662
- - `translation-mirror.md` — Optional reference-only translation mirror (detection, layout, sync, fields)
410
+ **References:** `ask-user-question-gates.md`, `cross-spec-dependency.md`, `scope-inquiry.md`, `research-strategy.md`, `codebase-analysis.md`, `review.md`, `archive-workflow.md`, `translation-mirror.md`