cleargate 0.8.2 → 0.11.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 (122) hide show
  1. package/CHANGELOG.md +210 -0
  2. package/README.md +22 -1
  3. package/dist/MANIFEST.json +276 -31
  4. package/dist/chunk-HZPJ5QX4.js +459 -0
  5. package/dist/chunk-HZPJ5QX4.js.map +1 -0
  6. package/dist/{chunk-OM4FAEA7.js → chunk-Q3BTSXCK.js} +69 -3
  7. package/dist/chunk-Q3BTSXCK.js.map +1 -0
  8. package/dist/cli.cjs +2888 -598
  9. package/dist/cli.cjs.map +1 -1
  10. package/dist/cli.js +2481 -619
  11. package/dist/cli.js.map +1 -1
  12. package/dist/lib/ledger.cjs +120 -0
  13. package/dist/lib/ledger.cjs.map +1 -0
  14. package/dist/lib/ledger.d.cts +64 -0
  15. package/dist/lib/ledger.d.ts +64 -0
  16. package/dist/lib/ledger.js +96 -0
  17. package/dist/lib/ledger.js.map +1 -0
  18. package/dist/lib/lifecycle-reconcile.cjs +497 -0
  19. package/dist/lib/lifecycle-reconcile.cjs.map +1 -0
  20. package/dist/lib/lifecycle-reconcile.d.cts +136 -0
  21. package/dist/lib/lifecycle-reconcile.d.ts +136 -0
  22. package/dist/lib/lifecycle-reconcile.js +20 -0
  23. package/dist/lib/lifecycle-reconcile.js.map +1 -0
  24. package/dist/templates/cleargate-planning/.claude/agents/architect.md +65 -10
  25. package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-contradict.md +108 -0
  26. package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-ingest.md +49 -3
  27. package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-lint.md +6 -1
  28. package/dist/templates/cleargate-planning/.claude/agents/developer.md +51 -2
  29. package/dist/templates/cleargate-planning/.claude/agents/devops.md +249 -0
  30. package/dist/templates/cleargate-planning/.claude/agents/qa.md +91 -1
  31. package/dist/templates/cleargate-planning/.claude/agents/reporter.md +72 -14
  32. package/dist/templates/cleargate-planning/.claude/hooks/pre-commit-surface-gate.sh +21 -0
  33. package/dist/templates/cleargate-planning/.claude/hooks/pre-tool-use-task.sh +148 -0
  34. package/dist/templates/cleargate-planning/.claude/hooks/session-start.sh +6 -0
  35. package/dist/templates/cleargate-planning/.claude/hooks/stamp-and-gate.sh +12 -1
  36. package/dist/templates/cleargate-planning/.claude/hooks/token-ledger.sh +334 -96
  37. package/dist/templates/cleargate-planning/.claude/settings.json +4 -0
  38. package/dist/templates/cleargate-planning/.claude/skills/sprint-execution/SKILL.md +644 -0
  39. package/dist/templates/cleargate-planning/.cleargate/config.example.yml +19 -0
  40. package/dist/templates/cleargate-planning/.cleargate/knowledge/cleargate-enforcement.md +542 -0
  41. package/dist/templates/cleargate-planning/.cleargate/knowledge/cleargate-protocol.md +102 -428
  42. package/dist/templates/cleargate-planning/.cleargate/knowledge/mid-sprint-triage-rubric.md +160 -0
  43. package/dist/templates/cleargate-planning/.cleargate/knowledge/readiness-gates.md +72 -9
  44. package/dist/templates/cleargate-planning/.cleargate/knowledge/sprint-closeout-checklist.md +71 -0
  45. package/dist/templates/cleargate-planning/.cleargate/scripts/assert_story_files.mjs +24 -2
  46. package/dist/templates/cleargate-planning/.cleargate/scripts/close_sprint.mjs +471 -29
  47. package/dist/templates/cleargate-planning/.cleargate/scripts/dedupe_frontmatter.mjs +219 -0
  48. package/dist/templates/cleargate-planning/.cleargate/scripts/gate-checks.json +3 -3
  49. package/dist/templates/cleargate-planning/.cleargate/scripts/init_sprint.mjs +86 -10
  50. package/dist/templates/cleargate-planning/.cleargate/scripts/lib/report-filename.mjs +54 -0
  51. package/dist/templates/cleargate-planning/.cleargate/scripts/prep_doc_refresh.mjs +378 -0
  52. package/dist/templates/cleargate-planning/.cleargate/scripts/prep_qa_context.mjs +888 -0
  53. package/dist/templates/cleargate-planning/.cleargate/scripts/run_script.sh +173 -87
  54. package/dist/templates/cleargate-planning/.cleargate/scripts/sprint_trends.mjs +71 -0
  55. package/dist/templates/cleargate-planning/.cleargate/scripts/suggest_improvements.mjs +483 -13
  56. package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_prep_qa_context.sh +482 -0
  57. package/dist/templates/cleargate-planning/.cleargate/scripts/validate_state.mjs +32 -8
  58. package/dist/templates/cleargate-planning/.cleargate/scripts/write_dispatch.sh +136 -0
  59. package/dist/templates/cleargate-planning/.cleargate/templates/Bug.md +27 -1
  60. package/dist/templates/cleargate-planning/.cleargate/templates/CR.md +35 -1
  61. package/dist/templates/cleargate-planning/.cleargate/templates/Sprint Plan Template.md +48 -14
  62. package/dist/templates/cleargate-planning/.cleargate/templates/epic.md +40 -3
  63. package/dist/templates/cleargate-planning/.cleargate/templates/hotfix.md +53 -0
  64. package/dist/templates/cleargate-planning/.cleargate/templates/initiative.md +98 -29
  65. package/dist/templates/cleargate-planning/.cleargate/templates/proposal.md +17 -4
  66. package/dist/templates/cleargate-planning/.cleargate/templates/sprint_context.md +8 -0
  67. package/dist/templates/cleargate-planning/.cleargate/templates/sprint_report.md +23 -4
  68. package/dist/templates/cleargate-planning/.cleargate/templates/story.md +58 -3
  69. package/dist/templates/cleargate-planning/CLAUDE.md +30 -10
  70. package/dist/templates/cleargate-planning/MANIFEST.json +276 -31
  71. package/dist/{whoami-CX7CXJD5.js → whoami-W4U6DPVG.js} +17 -17
  72. package/dist/whoami-W4U6DPVG.js.map +1 -0
  73. package/package.json +20 -6
  74. package/templates/cleargate-planning/.claude/agents/architect.md +65 -10
  75. package/templates/cleargate-planning/.claude/agents/cleargate-wiki-contradict.md +108 -0
  76. package/templates/cleargate-planning/.claude/agents/cleargate-wiki-ingest.md +49 -3
  77. package/templates/cleargate-planning/.claude/agents/cleargate-wiki-lint.md +6 -1
  78. package/templates/cleargate-planning/.claude/agents/developer.md +51 -2
  79. package/templates/cleargate-planning/.claude/agents/devops.md +249 -0
  80. package/templates/cleargate-planning/.claude/agents/qa.md +91 -1
  81. package/templates/cleargate-planning/.claude/agents/reporter.md +72 -14
  82. package/templates/cleargate-planning/.claude/hooks/pre-commit-surface-gate.sh +21 -0
  83. package/templates/cleargate-planning/.claude/hooks/pre-tool-use-task.sh +148 -0
  84. package/templates/cleargate-planning/.claude/hooks/session-start.sh +6 -0
  85. package/templates/cleargate-planning/.claude/hooks/stamp-and-gate.sh +12 -1
  86. package/templates/cleargate-planning/.claude/hooks/token-ledger.sh +334 -96
  87. package/templates/cleargate-planning/.claude/settings.json +4 -0
  88. package/templates/cleargate-planning/.claude/skills/sprint-execution/SKILL.md +644 -0
  89. package/templates/cleargate-planning/.cleargate/config.example.yml +19 -0
  90. package/templates/cleargate-planning/.cleargate/knowledge/cleargate-enforcement.md +542 -0
  91. package/templates/cleargate-planning/.cleargate/knowledge/cleargate-protocol.md +102 -428
  92. package/templates/cleargate-planning/.cleargate/knowledge/mid-sprint-triage-rubric.md +160 -0
  93. package/templates/cleargate-planning/.cleargate/knowledge/readiness-gates.md +72 -9
  94. package/templates/cleargate-planning/.cleargate/knowledge/sprint-closeout-checklist.md +71 -0
  95. package/templates/cleargate-planning/.cleargate/scripts/assert_story_files.mjs +24 -2
  96. package/templates/cleargate-planning/.cleargate/scripts/close_sprint.mjs +471 -29
  97. package/templates/cleargate-planning/.cleargate/scripts/dedupe_frontmatter.mjs +219 -0
  98. package/templates/cleargate-planning/.cleargate/scripts/gate-checks.json +3 -3
  99. package/templates/cleargate-planning/.cleargate/scripts/init_sprint.mjs +86 -10
  100. package/templates/cleargate-planning/.cleargate/scripts/lib/report-filename.mjs +54 -0
  101. package/templates/cleargate-planning/.cleargate/scripts/prep_doc_refresh.mjs +378 -0
  102. package/templates/cleargate-planning/.cleargate/scripts/prep_qa_context.mjs +888 -0
  103. package/templates/cleargate-planning/.cleargate/scripts/run_script.sh +173 -87
  104. package/templates/cleargate-planning/.cleargate/scripts/sprint_trends.mjs +71 -0
  105. package/templates/cleargate-planning/.cleargate/scripts/suggest_improvements.mjs +483 -13
  106. package/templates/cleargate-planning/.cleargate/scripts/test/test_prep_qa_context.sh +482 -0
  107. package/templates/cleargate-planning/.cleargate/scripts/validate_state.mjs +32 -8
  108. package/templates/cleargate-planning/.cleargate/scripts/write_dispatch.sh +136 -0
  109. package/templates/cleargate-planning/.cleargate/templates/Bug.md +27 -1
  110. package/templates/cleargate-planning/.cleargate/templates/CR.md +35 -1
  111. package/templates/cleargate-planning/.cleargate/templates/Sprint Plan Template.md +48 -14
  112. package/templates/cleargate-planning/.cleargate/templates/epic.md +40 -3
  113. package/templates/cleargate-planning/.cleargate/templates/hotfix.md +53 -0
  114. package/templates/cleargate-planning/.cleargate/templates/initiative.md +98 -29
  115. package/templates/cleargate-planning/.cleargate/templates/sprint_context.md +8 -0
  116. package/templates/cleargate-planning/.cleargate/templates/sprint_report.md +23 -4
  117. package/templates/cleargate-planning/.cleargate/templates/story.md +58 -3
  118. package/templates/cleargate-planning/CLAUDE.md +30 -10
  119. package/templates/cleargate-planning/MANIFEST.json +276 -31
  120. package/dist/chunk-OM4FAEA7.js.map +0 -1
  121. package/dist/whoami-CX7CXJD5.js.map +0 -1
  122. package/templates/cleargate-planning/.cleargate/templates/proposal.md +0 -61
@@ -0,0 +1,644 @@
1
+ ---
2
+ name: sprint-execution
3
+ description: |
4
+ Use to orchestrate the five-dispatch sprint loop end-to-end — Architect → QA-Red →
5
+ Developer → QA-Verify → Reporter — across one ClearGate sprint. Activates from sprint kickoff
6
+ (preflight + cut sprint branch + state init) through per-story execution
7
+ (worktree → dev → QA → flashcard gate → merge) into walkthrough and Gate-4 close.
8
+ Triggers: SessionStart banner mentioning an active sprint; explicit user phrases
9
+ "start the sprint", "run the sprint", "execute the sprint", "begin sprint
10
+ execution", "kick off SPRINT-NN", "run STORY-NNN-NN"; CLI directives ending
11
+ with `→ Load skill: sprint-execution`. The skill does not draft work items, run
12
+ triage, or manage planning — those stay in always-on CLAUDE.md surface.
13
+ ---
14
+
15
+ # Sprint Execution — The Playbook
16
+
17
+ You are the **Orchestrator**. You read this playbook top to bottom once when a sprint becomes active, then execute it. You never write production code. You delegate every implementation step to the four execution agents (`architect`, `developer`, `qa`, `reporter`) by spawning them via the `Agent` tool with the matching `subagent_type`.
18
+
19
+ This skill is the **execution-time** layer. Triage, drafting, and pre-sprint planning stay in CLAUDE.md and `cleargate-protocol.md`. Read those before deciding to load this skill.
20
+
21
+ ---
22
+
23
+ ## 0. When This Skill Loads
24
+
25
+ Three explicit load points (belt-and-suspenders — the SKILL description handles the rest):
26
+
27
+ 1. **SessionStart banner.** When the doctor banner reports `Active sprint: SPRINT-NN`, the skill auto-loads. (Banner emitted by `.claude/hooks/session-start.sh`; `.cleargate/sprint-runs/.active` is the sentinel file.)
28
+ 2. **CLI directive.** Any `cleargate sprint *` command finishing with the line `→ Load skill: sprint-execution` instructs the orchestrator to load this skill before continuing.
29
+ 3. **Natural-language triggers.** "start the sprint", "kick off SPRINT-NN", "run the sprint", "execute the loop", "run STORY-NNN-NN" → load the skill, do not improvise.
30
+
31
+ If you are running a sprint and you have not loaded this skill yet, **stop and load it now**. Do not orchestrate from memory.
32
+
33
+ ---
34
+
35
+ ## 0.5 Goal-First Execution
36
+
37
+ **The sprint goal is the success criterion — not the count of merged stories.** A sprint where every story passes QA but the goal is not met is a failed sprint. Read `sprint_goal:` from the active sprint plan's frontmatter (or §1 if unstructured) at kickoff and treat it as the anchor for every decision the orchestrator makes.
38
+
39
+ Five touchpoints where the goal is the tiebreaker:
40
+
41
+ 1. **Kickoff (§A.5).** Surface the sprint goal verbatim in chat before any Architect dispatch. State it as the explicit acceptance condition for the sprint.
42
+ 2. **Architect dispatch (§B).** Pass the sprint goal in the dispatch prompt. The milestone plan should reference how each story advances the goal, not only what files it changes.
43
+ 3. **Mid-sprint CR triage (§C.10 rubric → §C.11 routing).** When classifying `CR:scope-change`, evaluate goal alignment before quarantining. If the new requirement is critical to the goal, escalate to the human with "this may need to land THIS sprint, not the next."
44
+ 4. **Escalation (§8).** When `qa_bounces ≥ 3`, `arch_bounces ≥ 3`, or 3 circuit-breaker hits flip a story to `Escalated`, frame the human-decision question through the goal lens: "Drop this story → goal still met? Re-approach → goal still met by sprint end?"
45
+ 5. **Walkthrough + Reporter brief (§D, §E.2).** Walkthrough invitation leads with the goal, not the feature checklist. Reporter brief MUST include a goal-achievement verdict — `met / partial / missed` — as a first-class signal in the close-gate Brief.
46
+
47
+ **What goal-first is NOT:**
48
+ - Not authority to skip stories the orchestrator deems "off-goal" — splits and merges are decomposition-time decisions, never mid-sprint.
49
+ - Not authority to rewrite the goal mid-flight — that requires a CR or a sprint reset.
50
+ - Not a license to relax acceptance criteria — story Gherkin still passes verbatim.
51
+
52
+ It is pure framing: surface deviations from the goal as first-class events, not afterthoughts.
53
+
54
+ ---
55
+
56
+ ## 1. Agent Roster + Dispatch Contract
57
+
58
+ | Subagent | Model | Spawn point | Output artifact |
59
+ |---|---|---|---|
60
+ | `architect` | opus | (a) Sprint Design Review pre-confirm, (b) per-milestone plan | `sprint-runs/<id>/plans/M<N>.md` (per milestone); markdown block §2 (design review) |
61
+ | `developer` | sonnet | One per story, inside its worktree | One commit `feat(<epic>): STORY-NNN-NN <desc>` + `STORY-NNN-NN-dev.md` report |
62
+ | `qa` | sonnet | After Developer reports `STATUS=done` | `STORY-NNN-NN-qa.md` report (no code edits) |
63
+ | `devops` | sonnet | Per-story, after QA-Verify + Architect post-flight | One merge commit (no-ff) + `STORY-NNN-NN-devops.md` report |
64
+ | `reporter` | sonnet | Once at sprint close, after all stories merged + walkthrough done | `sprint-runs/<id>/SPRINT-<#>_REPORT.md` |
65
+
66
+ **Registration constraint:** The Claude Code agent registry caches at session start. If an agent `.md` file under `.claude/agents/` was added or modified after the current session began, `Agent(subagent_type=<name>)` will return "Agent type '<name>' not found" even though the file exists. Fix: restart the Claude Code session. Verify `devops` reachable at sprint preflight (§A.1 check 6). If unavailable mid-sprint, use the §C.7 DevOps Escape Hatch.
67
+
68
+ ### Wall-clock budgets
69
+
70
+ Each agent dispatch has a target duration. Note the start time before each `Agent` spawn; after the call returns, compare elapsed against the budget. Ran-long stories get flagged in sprint §4 Execution Log even on success.
71
+
72
+ | Agent | Budget | Notes |
73
+ |---|---|---|
74
+ | `architect` (per milestone) | ≤ 10 min | Plan-only output; long runs usually mean too many stories in the milestone |
75
+ | `developer` (per story) | ≤ 30 min | Includes typecheck + tests in the worktree; long runs near the circuit-breaker threshold |
76
+ | `qa` (per story) | ≤ 15 min | Read + re-run gates; should not edit code |
77
+ | `devops` (per story) | ≤ 5 min | Mechanical work only — merge, teardown, state; long runs indicate git/npm issue |
78
+ | `reporter` (per sprint) | ≤ 20 min | Single file write; long runs mean ledger reconciliation issues |
79
+
80
+ If a Task call has been pending for **>2× the budget** with no visible progress, surface it to the human and offer to interrupt. There is no automatic stall detection — the parent session blocks on `Agent` calls and cannot poll mid-run. The human's interrupt is the only reliable kill path until ambient watcher infra exists.
81
+
82
+ ### Dispatch marker — write before every spawn
83
+
84
+ The token-ledger hook attributes tokens by reading `.cleargate/sprint-runs/<sprint>/.dispatch-<session-id>.json`. You write that file immediately before each `Agent` call:
85
+
86
+ ```bash
87
+ bash .cleargate/scripts/write_dispatch.sh <work_item_id> <agent_type>
88
+ ```
89
+
90
+ - `<work_item_id>`: e.g. `STORY-020-02`, `CR-016`, `BUG-021`. For the Reporter at sprint close use the sprint ID (e.g. `SPRINT-19`).
91
+ - `<agent_type>`: exact string — `developer | architect | qa | reporter | devops | cleargate-wiki-contradict`.
92
+
93
+ If you forget the marker, ledger attribution falls back to transcript-grep heuristics (unreliable). The hook deletes the file after consumption — write fresh per dispatch.
94
+
95
+ ---
96
+
97
+ ## 2. v1 / v2 Mode Switch
98
+
99
+ Every step below is gated by the active sprint's `execution_mode:` frontmatter:
100
+
101
+ | Mode | Effect |
102
+ |---|---|
103
+ | `v1` | All §§ rules in `cleargate-enforcement.md` are advisory — document workflow; no script enforcement. Rework counters, flashcard gate, surface contract, etc. are informational. |
104
+ | `v2` | All §§ rules are mandatory. Hooks block on violations. Worktree isolation, pre-gate scans, file-surface contract, flashcard gate, sprint close — all enforced. |
105
+
106
+ Default is `v1`. Read the field before spawning Developer/QA/Reporter. If absent, treat as `v1`. **Do not infer mode from sprint number — read the frontmatter.**
107
+
108
+ ---
109
+
110
+ ## 3. Phase A — Sprint Kickoff (Ready → Active)
111
+
112
+ Run this sequence exactly once, when the human says "start sprint NN" or equivalent. Halt on any failure; do not improvise around a failed gate.
113
+
114
+ ### A.1 Sprint Execution Gate (Gate 3) — preflight
115
+
116
+ ```bash
117
+ cleargate sprint preflight <sprint-id>
118
+ ```
119
+
120
+ Six checks, all must pass:
121
+
122
+ 1. Previous sprint `sprint_status: "Completed"` in `state.json`.
123
+ 2. No leftover worktrees — `git worktree list` must not contain `.worktrees/STORY-*`.
124
+ 3. Sprint branch ref free — `git show-ref refs/heads/sprint/S-NN` returns nothing.
125
+ 4. `main` clean — `git status --porcelain` empty.
126
+ 5. Per-item readiness gates pass — every work-item ID in §1 Consolidated Deliverables has fresh `cached_gate_result.pass: true` (or terminal status). Under `execution_mode: v2` a failing item hard-blocks; under `v1` it warns. Failure punch-list names each item + its failing criteria.
127
+ 6. **Verify `devops` subagent reachable** — attempt `Agent(subagent_type=devops, prompt: "echo preflight-check")` immediately after session start. If it returns "Agent type 'devops' not found", halt and ask the human to restart the Claude Code session; do NOT proceed under assumption the escape hatch will cover every merge. This check is manual (not enforced by `cleargate sprint preflight`); document result in sprint §4 Execution Log.
128
+
129
+ On failure, surface the punch list verbatim and halt. Per-item resolution:
130
+
131
+ - Prev sprint not closed → run sprint close on prev first.
132
+ - Leftover worktree → `git worktree remove` if abandoned, otherwise merge.
133
+ - Branch ref exists → investigate; force-deletion only with explicit human approval.
134
+ - Dirty main → human commits/stashes/discards. **Never `git reset --hard` or stash without explicit human approval.**
135
+ - Per-item gate fail → run `cleargate gate check <file> -v` for the named item; fix the failing criterion (e.g., populate `context_source`, resolve TBDs); re-run preflight.
136
+ - Devops unreachable → restart Claude Code session; re-run all 6 preflight checks.
137
+
138
+ ### A.2 Cut sprint branch
139
+
140
+ ```bash
141
+ git checkout -b sprint/S-NN main
142
+ ```
143
+
144
+ Sprint branch is **never committed to directly**. All work lands via story-branch merges.
145
+
146
+ ### A.3 Initialize sprint state
147
+
148
+ ```bash
149
+ node .cleargate/scripts/init_sprint.mjs SPRINT-NN
150
+ ```
151
+
152
+ This writes `.cleargate/sprint-runs/SPRINT-NN/state.json` and flips `.cleargate/sprint-runs/.active` to `SPRINT-NN`. Without `state.json` the lane router, dispatch hook, and close pipeline all fail.
153
+
154
+ `init_sprint.mjs` also writes `<sprintDir>/sprint-context.md` from `.cleargate/templates/sprint_context.md`, populated with `sprint_id` + goal (extracted from sprint plan §0 `- **Sprint Goal:** …` bullet, or placeholder if absent) + active CR list. Every Dev/QA/Architect/DevOps dispatch reads this file as preflight (see §B + §C contracts + agent prompts `## Preflight`).
155
+
156
+ ### A.4 Architect Sprint Design Review (v2 only)
157
+
158
+ Mandatory under `execution_mode: v2`; optional but encouraged under `v1`. Spawn the Architect with all candidate stories' §3 Implementation Guides + ADRs + flashcards + sprint plan path:
159
+
160
+ ```
161
+ Task instruction: "SPRINT DESIGN REVIEW — write Sprint Plan §2 Execution Strategy.
162
+ You have WRITE ACCESS to Sprint Plan §2 ONLY. Produce §§2.1–2.4 (Phase Plan,
163
+ Merge Ordering, Shared-Surface Warnings, ADR-Conflict Flags) plus §2.4 Lane Audit."
164
+ ```
165
+
166
+ Architect returns a markdown block; you insert it into the sprint plan file. Then halt and ask the human to confirm the sprint plan before any story executes.
167
+
168
+ ### A.5 Flip sprint status
169
+
170
+ After human confirms, update sprint frontmatter `status: Active` (via `cleargate stamp` after the edit).
171
+
172
+ > 🎯 **Goal check.** Before the first Architect dispatch, surface the sprint goal verbatim from the plan's `sprint_goal:` frontmatter (or §1 if unstructured) in chat: *"Sprint goal: <verbatim>. Success = this is met by close. Stories are the means; this is the end."* All subsequent halts and decisions reference back to this line.
173
+
174
+ ---
175
+
176
+ ## 4. Phase B — Per-Milestone Architect Plan
177
+
178
+ Before any Developer dispatches in a milestone, spawn the Architect once for the whole milestone:
179
+
180
+ ```bash
181
+ bash .cleargate/scripts/write_dispatch.sh M<N> architect
182
+ ```
183
+
184
+ Then `Agent(subagent_type=architect, ...)` with the milestone story IDs and instruction to write `.cleargate/sprint-runs/<sprint-id>/plans/M<N>.md`.
185
+
186
+ **Skip per-milestone Architect for `lane: fast` stories** — they dispatch to Developer without a plan, per the lane contract (see `.claude/agents/architect.md` Lane Classification).
187
+
188
+ - Cross-cutting rules: Read `.cleargate/sprint-runs/<sprint-id>/sprint-context.md` BEFORE any other action (Sprint Goal + Cross-Cutting Rules + Active CRs sections constrain every decision).
189
+
190
+ > 🎯 **Goal check.** Pass the sprint goal verbatim in the Architect's dispatch prompt. The plan should explicitly tie each story to the goal under "Per-story blueprint" — e.g. *"STORY-NNN-NN advances goal by <one sentence>"*. Plans that don't reference the goal go back to the Architect with a re-dispatch.
191
+
192
+ ---
193
+
194
+ ## 5. Phase C — Per-Story Execution Loop
195
+
196
+ Run this loop **per story**, in the order the milestone plan declares (parallel waves vs sequential chains). Each iteration: Worktree → **QA-Red** → **TPV (Test Pattern Validation, Architect-only)** → Developer → QA-Verify → (Architect pass for `lane: standard` v2 only) → Merge → Flashcard Gate.
197
+
198
+ > **Naming note.** State-machine values (`Bouncing`, `Ready to Bounce`), `state.json` counter fields (`qa_bounces`, `arch_bounces`), and script names (`validate_bounce_readiness.mjs`) retain the legacy "bounce" term because they are code-bound. The narrative in this skill uses "execution loop", "story cycle", and "rework" to describe the same mechanics.
199
+
200
+ ### C.1 Pre-execution check
201
+
202
+ ```bash
203
+ node .cleargate/scripts/validate_state.mjs
204
+ node .cleargate/scripts/validate_bounce_readiness.mjs STORY-NNN-NN
205
+ ```
206
+
207
+ `state.json` `sprintId` must equal the active sprint. If not, re-run `init_sprint.mjs` — **do not create a worktree with a stale state.json**.
208
+
209
+ `validate_bounce_readiness.mjs` checks: story is "Ready to Bounce", §§1/2/3 present, working tree clean. Fail → halt.
210
+
211
+ ### C.2 Create worktree
212
+
213
+ ```bash
214
+ git worktree add .worktrees/STORY-NNN-NN -b story/STORY-NNN-NN sprint/S-NN
215
+ ```
216
+
217
+ Story branch is cut from the **sprint branch**, never from main. Verify:
218
+
219
+ ```bash
220
+ git worktree list
221
+ ```
222
+
223
+ **Do not run `git worktree add` inside `mcp/`.** It is a nested git repo. If the story touches `mcp/`, the Developer edits `mcp/` from inside `.worktrees/STORY-NNN-NN/mcp/...` — visible as a subdirectory of the outer worktree. (`cleargate-enforcement.md` §1.3.)
224
+
225
+ ### C.3 Spawn QA-Red (standard lane only — fast lane skips this step)
226
+
227
+ ```bash
228
+ bash .cleargate/scripts/write_dispatch.sh STORY-NNN-NN qa
229
+ ```
230
+
231
+ **Script invocation rule (CR-046):** Any bash/node script invoked within the QA-Red dispatch MUST go through the wrapper: `bash .cleargate/scripts/run_script.sh <cmd> [args...]`. Direct invocation without the wrapper is forbidden under v2.
232
+
233
+ Then spawn with `subagent_type=qa`. Dispatch prompt MUST inject:
234
+
235
+ - Cross-cutting rules: Read `.cleargate/sprint-runs/<sprint-id>/sprint-context.md` BEFORE any other action.
236
+
237
+ > `Mode: RED — write failing tests against §4 acceptance, no implementation Read access. Tests must fail with "not yet implemented" errors against the clean baseline. File-naming: *.red.node.test.ts (immutable post-Red). Forbidden: editing implementation files.`
238
+
239
+ QA-Red returns:
240
+
241
+ ```
242
+ QA-RED: WRITTEN | BLOCKED
243
+ RED_TESTS: <list of *.red.node.test.ts files written>
244
+ BASELINE_FAIL: <count of failing scenarios>
245
+ flashcards_flagged: [ ... ]
246
+ ```
247
+
248
+ On `QA-RED: BLOCKED`: surface Spec-Gap to human; do not proceed to §C.4 until resolved.
249
+
250
+ On `QA-RED: WRITTEN`: orchestrator commits the Red tests on the story branch with subject `qa-red(STORY-NNN-NN): write failing tests`, then proceeds to §C.3.5 TPV Gate.
251
+
252
+ **Fast lane skip:** if `state.json.stories[<id>].lane === "fast"`, skip this entire step AND §C.3.5 and proceed directly to §C.4 Spawn Developer.
253
+
254
+ ### C.3.5 TPV Gate (Architect-only — standard lane, v2 only)
255
+
256
+ **Skip if:** `state.json.stories[<id>].lane === 'fast'` OR `execution_mode: v1`.
257
+
258
+ After QA-Red commits Red tests, spawn the Architect in `Mode: TPV` to perform wiring-only validation before Dev dispatch. TPV does NOT evaluate test logic correctness — it verifies wiring so Dev does not waste a full dispatch on a mis-wired test harness.
259
+
260
+ ```bash
261
+ bash .cleargate/scripts/write_dispatch.sh STORY-NNN-NN architect
262
+ ```
263
+
264
+ Dispatch prompt MUST inject:
265
+
266
+ > `Mode: TPV — Test Pattern Validation only. You receive: story file, QA-Red commit SHA, list of *.red.node.test.ts files. Verify ONLY: (1) imports resolve to real paths, (2) constructor signatures match, (3) mocked methods exist on the mocked object, (4) after-hooks present when before-hooks write state, (5) file naming *.red.node.test.ts. Do NOT evaluate test logic. Return: TPV: APPROVED (Dev proceeds) or TPV: BLOCKED-WIRING-GAP — <one-sentence specific issue> (orchestrator routes back to QA-Red).`
267
+
268
+ Architect returns one of:
269
+
270
+ - `TPV: APPROVED` — proceed to §C.4 Spawn Developer.
271
+ - `TPV: BLOCKED-WIRING-GAP — <issue>` — orchestrator increments `arch_bounces` via:
272
+ ```bash
273
+ node .cleargate/scripts/update_state.mjs STORY-NNN-NN --arch-bounce
274
+ ```
275
+ Then routes back to §C.3 QA-Red with the gap description in the re-dispatch prompt. If `arch_bounces ≥ 3` → flip story to `Escalated`, halt.
276
+
277
+ TPV is a WIRING gate, not a correctness gate. A test that imports the right module but asserts incorrectly still gets `TPV: APPROVED` — Dev's TDD cycle handles assertion correctness.
278
+
279
+ ### C.4 Spawn Developer
280
+
281
+ ```bash
282
+ bash .cleargate/scripts/write_dispatch.sh STORY-NNN-NN developer
283
+ ```
284
+
285
+ **Script invocation rule (CR-046):** Any bash/node script invoked within the Developer dispatch MUST go through the wrapper: `bash .cleargate/scripts/run_script.sh <cmd> [args...]`. Direct invocation without the wrapper is forbidden under v2.
286
+
287
+ Then spawn with `subagent_type=developer`. Inputs the prompt must include verbatim:
288
+
289
+ - Cross-cutting rules: Read `.cleargate/sprint-runs/<sprint-id>/sprint-context.md` BEFORE any other action.
290
+
291
+ - `STORY=NNN-NN` (Developer must echo this on its first response line).
292
+ - Path to story file.
293
+ - Path to milestone plan.
294
+ - Worktree path (assigned).
295
+ - Sprint ID.
296
+
297
+ Developer returns:
298
+
299
+ ```
300
+ STORY: STORY-NNN-NN
301
+ STATUS: done | blocked
302
+ COMMIT: <sha> | none
303
+ TYPECHECK: pass | fail
304
+ TESTS: X passed, Y failed
305
+ FILES_CHANGED: <list>
306
+ flashcards_flagged: [ ... ]
307
+ ```
308
+
309
+ If `STATUS=blocked`: route per §C.8 (Blockers Triage).
310
+
311
+ ### C.5 Spawn QA-Verify
312
+
313
+ ```bash
314
+ bash .cleargate/scripts/write_dispatch.sh STORY-NNN-NN qa
315
+ ```
316
+
317
+ **Script invocation rule (CR-046):** Any bash/node script invoked within the QA-Verify dispatch MUST go through the wrapper: `bash .cleargate/scripts/run_script.sh <cmd> [args...]`. Direct invocation without the wrapper is forbidden under v2.
318
+
319
+ Dispatch prompt MUST inject: `Mode: VERIFY — read-only acceptance trace. Verify Developer's implementation against the story's §4 acceptance Gherkin. Do not write or modify any files.`
320
+
321
+ - Cross-cutting rules: Read `.cleargate/sprint-runs/<sprint-id>/sprint-context.md` BEFORE any other action.
322
+
323
+ QA inputs: story file path, worktree path, Developer commit SHA. QA returns:
324
+
325
+ ```
326
+ QA: PASS | FAIL
327
+ ACCEPTANCE_COVERAGE: N of M scenarios
328
+ MISSING: <list>
329
+ REGRESSIONS: <list>
330
+ flashcards_flagged: [ ... ]
331
+ ```
332
+
333
+ **On `QA: FAIL`:** increment `qa_bounces` via `update_state.mjs STORY-NNN-NN --qa-bounce`. If counter ≥ 3 → flip story to `Escalated`, surface to human, halt. Else → re-spawn Developer with QA's bug report as input. Return to §C.4.
334
+
335
+ **On `QA: PASS`:** update state to `QA Passed`, proceed.
336
+
337
+ ### C.6 Architect Pass (v2, `lane: standard` only)
338
+
339
+ `lane: fast` skips this step entirely.
340
+
341
+ - Cross-cutting rules: Read `.cleargate/sprint-runs/<sprint-id>/sprint-context.md` BEFORE any other action.
342
+
343
+ **Script invocation rule (CR-046):** Any bash/node script invoked within the Architect Pass dispatch MUST go through the wrapper: `bash .cleargate/scripts/run_script.sh <cmd> [args...]`. Direct invocation without the wrapper is forbidden under v2.
344
+
345
+ ```bash
346
+ bash .cleargate/scripts/pre_gate_runner.sh arch .worktrees/STORY-NNN-NN/ sprint/S-NN
347
+ ```
348
+
349
+ If pre-gate scan reveals new dependencies / structural issues → return to Developer (do NOT spawn Architect for mechanical failures). 3+ pre-gate failures → escalate.
350
+
351
+ If pre-gate passes, spawn Architect for post-flight review. On `FAIL`: increment `arch_bounces`. ≥ 3 → escalate.
352
+
353
+ ### C.7 Story Merge
354
+
355
+ **DevOps-owned.** The orchestrator does NOT run `git merge`, `git worktree remove`, `git branch -d`, `update_state.mjs`, or `npm run prebuild` directly. All mechanical merge work is delegated to the DevOps agent.
356
+
357
+ **Required reports — verify before dispatch:**
358
+
359
+ | Report | Required when |
360
+ |---|---|
361
+ | `STORY-NNN-NN-dev.md` | Always (all lanes) |
362
+ | `STORY-NNN-NN-qa.md` | Always, unless lane=fast explicitly skipped QA-Verify |
363
+ | `STORY-NNN-NN-arch.md` | v2 standard-lane only |
364
+ | `STORY-NNN-NN-devops.md` | Written BY DevOps during this step (not a prerequisite) |
365
+
366
+ Missing `dev.md` or `qa.md` (when required) → return to spawn that agent. **Do not dispatch DevOps with missing reports.**
367
+
368
+ **Orchestrator dispatch sequence:**
369
+
370
+ 1. Mark the dispatch:
371
+ ```bash
372
+ bash .cleargate/scripts/write_dispatch.sh STORY-NNN-NN devops
373
+ ```
374
+
375
+ 2. Spawn the DevOps agent with the following context (§3.1 Context Pack):
376
+ ```
377
+ SPRINT-{NN} — DevOps dispatch for {STORY-ID}.
378
+
379
+ INPUTS:
380
+ - Story ID: {STORY-ID}
381
+ - Sprint ID: SPRINT-{NN}
382
+ - Worktree path: .worktrees/{STORY-ID}/
383
+ - Story branch: story/{STORY-ID}
384
+ - Sprint branch: sprint/S-{NN}
385
+ - Dev commit SHA: {abc1234}
386
+ - QA commit SHA (if present): {def5678}
387
+ - Architect commit SHA (if present): {ghi9012}
388
+ - Files-changed manifest: {list from git show --stat <dev-sha>}
389
+ - Canonical scaffold touched? {yes|no}
390
+ - Lane: {standard | fast}
391
+ - Required reports present:
392
+ - {STORY-ID}-dev.md ✓
393
+ - {STORY-ID}-qa.md ✓ (or "skipped — fast lane")
394
+ - {STORY-ID}-arch.md ✓ (v2 standard lane only)
395
+
396
+ ACTIONS (in order):
397
+ 1. Verify all required reports exist; halt if any missing.
398
+ 2. Checkout sprint branch.
399
+ 3. git merge story/{STORY-ID} --no-ff -m "merge(story/{STORY-ID}): {commit subject}"
400
+ 4. If canonical scaffold touched: cd cleargate-cli && npm run prebuild
401
+ 5. Mirror parity audit: for each file in files-changed where canonical mirror exists,
402
+ diff live ↔ canonical. Report drift in §Mirror Parity (DO NOT auto-fix).
403
+ 6. Post-merge test verification: run only test files touched by this commit.
404
+ 7. git worktree remove .worktrees/{STORY-ID}
405
+ 8. git branch -d story/{STORY-ID}
406
+ 9. CLEARGATE_STATE_FILE=... node .cleargate/scripts/update_state.mjs {STORY-ID} Done
407
+ ```
408
+
409
+ 3. **Halt** and wait for DevOps to return `STATUS=done` or `STATUS=blocked`.
410
+
411
+ **On `STATUS=done`:** DevOps has written `.cleargate/sprint-runs/SPRINT-{NN}/reports/{STORY-ID}-devops.md`. If it notes live re-sync needed (mirror parity drift), address via `cleargate init` or hand-port at Gate-4 doc-refresh (see §C.9 Flashcard Gate for the next step, then proceed to the next story / wave).
412
+
413
+ **On `STATUS=blocked`:** DevOps has written `{STORY-ID}-devops-blockers.md`. Surface the blockers report to the human. DevOps does NOT auto-resolve conflicts — orchestrator escalates and waits for human resolution before re-dispatching DevOps.
414
+
415
+ **Forbidden orchestrator patterns (v2):** `git merge`, `git worktree remove`, `git branch -d`, `update_state.mjs`, `npm run prebuild` in the orchestrator's main session bash log. If any appear, classify as edge case and document in sprint §4 Execution Log.
416
+
417
+ #### DevOps Escape Hatch — subagent_type=devops unavailable
418
+
419
+ If spawning `Agent(subagent_type=devops)` returns "Agent type 'devops' not found" (registry miss — see §1 registration constraint note), the orchestrator executes the §C.7 ACTIONS steps 2-9 verbatim inline (in the orchestrator's own bash session). All rules still apply: no `git merge` short-circuit, no conflict auto-resolution. Write the same `STORY-NNN-NN-devops.md` report with an additional frontmatter field `operator: orchestrator-fallback` and note the session restart requirement. This path is exceptional — if it triggers, queue a session restart at the next natural break and verify `devops` appears in the next session's available agent list before continuing the sprint.
420
+
421
+ ### C.8 Blockers Triage (Developer circuit breaker)
422
+
423
+ When Developer returns `BLOCKED: circuit breaker triggered`, read `.cleargate/sprint-runs/<id>/reports/STORY-NNN-NN-dev-blockers.md`. The report has three sections:
424
+
425
+ | Non-N/A section | Routing |
426
+ |---|---|
427
+ | `## Test-Pattern` | Re-launch Developer with the pattern hint as additional context. Pass the sentence verbatim in the new prompt. |
428
+ | `## Spec-Gap` | **Halt and surface the sentence to the human.** Do NOT re-launch Developer until human clarifies. |
429
+ | `## Environment` | Re-run `pre_gate_runner.sh`. If pre-gate passes, re-launch Developer; otherwise surface env issue. |
430
+
431
+ 3 consecutive circuit-breaker hits on the same story → `update_state.mjs STORY-NNN-NN Escalated`, halt.
432
+
433
+ ### C.9 Flashcard Gate (v2 mandatory; v1 dogfood)
434
+
435
+ After every story merge — **before creating story N+1's worktree** — process the merged `flashcards_flagged` list (union of dev + QA, dedupe by exact-string):
436
+
437
+ For each card:
438
+
439
+ | Action | Effect |
440
+ |---|---|
441
+ | **Approve** | Append the line verbatim to `.cleargate/FLASHCARD.md` (newest-first). |
442
+ | **Reject** | Discard. Log `FLASHCARD-REJECT YYYY-MM-DD — "<card>" — reason: <one sentence>` in sprint §4 Execution Log. |
443
+
444
+ Then mark each card processed:
445
+
446
+ ```bash
447
+ HASH=$(printf '%s' "<card text>" | shasum -a 1 | cut -c1-12)
448
+ touch .cleargate/sprint-runs/<sprint-id>/.processed-${HASH}
449
+ ```
450
+
451
+ Under v2, the `pending-task-sentinel.sh` PreToolUse hook blocks the next `Task` spawn until every card has a `.processed-<hash>` marker. Bypass only with `SKIP_FLASHCARD_GATE=1` — log the bypass in sprint §4.
452
+
453
+ ### C.10 Mid-Sprint Triage
454
+
455
+ When the user injects new input mid-sprint (between story kickoff and merge), classify it before routing. Use the keyword-heuristic classifier (`classify()` from `cleargate-cli/src/lib/triage-classifier.ts`) as a first-pass advisory, then confirm. See authoritative rubric: `.cleargate/knowledge/mid-sprint-triage-rubric.md`.
456
+
457
+ | Class | Trigger | Counter | Human Approval | First-pass action |
458
+ |---|---|---|---|---|
459
+ | `bug` | Defect vs spec | `qa_bounces++` | No | Re-open story; Dev fix; QA re-verify |
460
+ | `clarification` | Ambiguity question | None | No (yes if spec gap) | Update §1.2 in place; re-run impacted test |
461
+ | `scope` | Net-new requirement | None | YES for mid-sprint add | Quarantine to next sprint (default); escalate if goal-critical |
462
+ | `approach` | Different impl, same spec | None | No (yes if cross-story impact) | Reset Dev context; re-spawn with updated approach |
463
+
464
+ **Confidence signal:** `classify()` returns `confidence: 'low'` when no keyword matched. LOW confidence classifications MUST be confirmed with the human before routing.
465
+
466
+ **Scope-only note:** This rubric covers USER input only. QA-FAIL bounces continue to use `qa_bounces` (existing §C.5 path). TPV-gap bounces use `arch_bounces` (§C.3.5 path).
467
+
468
+ For the operational routing table with per-type routing rules, see §C.11 (Mid-cycle User Input — CR Triage).
469
+
470
+ ### C.11 Mid-cycle User Input — CR Triage
471
+
472
+ If the user injects new input mid-story, classify before routing:
473
+
474
+ | Type | Effect | Routing |
475
+ |---|---|---|
476
+ | `CR:bug` | Defect in current story | Increments `qa_bounces`; re-open story; Dev fixes; QA re-verifies |
477
+ | `CR:spec-clarification` | Removes ambiguity, no new scope | No counter; update §1.2 in place; re-run impacted test |
478
+ | `CR:scope-change` | Net-new requirement | **Quarantine.** New Story file in `pending-sync/`; current story unchanged |
479
+ | `CR:approach-change` | Different impl, same spec | No counter; reset Dev context; re-spawn with updated approach |
480
+
481
+ Log every CR in sprint §4 Execution Log with date + ID.
482
+
483
+ > 🎯 **Goal check on `CR:scope-change`.** Default routing is quarantine-into-next-sprint. **Override the default if the new requirement is critical to the active sprint goal** — escalate to the human with: *"This scope-change is goal-critical: the sprint goal is `<verbatim>` and without this change, the goal will not be met. Add to current sprint? (Adding mid-sprint requires explicit ack per §C.11.)"* Quarantine remains default for goal-incidental scope.
484
+
485
+ ### C.11 Script Invocation Contract (CR-046)
486
+
487
+ All bash/node script invocations dispatched FROM agents (Developer / QA / Architect / DevOps) MUST use the wrapper:
488
+
489
+ ```bash
490
+ bash .cleargate/scripts/run_script.sh <command> [args...]
491
+ ```
492
+
493
+ **What the wrapper does (on failure):**
494
+ - Captures stdout + stderr independently (≤4KB each; truncated with `... [truncated]` if exceeded).
495
+ - Writes a structured JSON incident to `.cleargate/sprint-runs/<sprint-id>/.script-incidents/<ts>-<hash>.json`.
496
+ - Propagates the original exit code to the caller.
497
+
498
+ **Self-exemption clause:** The wrapper itself (`run_script.sh`) is exempt from wrapping — it sets `RUN_SCRIPT_ACTIVE=1` before executing the wrapped command so recursive calls pass through directly. Orchestrator-direct invocations of `run_script.sh` are the canonical entry point; they are exempt by this contract.
499
+
500
+ **Agent reporting obligation:** If a wrapped script fails (incident JSON written), the dispatching agent MUST include the incident JSON path in its report's `## Script Incidents` section.
501
+
502
+ **Pre-sprint invocations (before `.active` sentinel exists):** Wrapper writes to `.cleargate/sprint-runs/_off-sprint/.script-incidents/` when no active sprint is detected. This is expected during preflight steps.
503
+
504
+ ---
505
+
506
+ ## 6. Phase D — Sprint Walkthrough (v2)
507
+
508
+ Mandatory under v2. After all stories merged into `sprint/S-NN` (every story state ∈ `TERMINAL_STATES`) and **before** sprint→main merge, invite the user to test on the sprint branch. Classify every piece of feedback:
509
+
510
+ | Event | Definition | Bug-Fix Tax |
511
+ |---|---|---|
512
+ | `UR:bug` | Defect, crash, behavior broken vs spec | Increments |
513
+ | `UR:review-feedback` | Polish, copy, UX preference | Does not increment |
514
+
515
+ **When in doubt, ask:** "Is this broken vs spec, or a preference?" Do not default to `UR:bug`.
516
+
517
+ Log every event in sprint §4. **Sprint branch MUST NOT merge to main while any `UR:bug` is unresolved.** `UR:review-feedback` may defer with explicit human sign-off.
518
+
519
+ > 🎯 **Goal check.** Open the walkthrough invitation with the sprint goal verbatim, not a feature checklist: *"Sprint goal: `<verbatim>`. The branch is ready on `sprint/S-NN`. Test it and tell me — does the running build achieve the goal?"* This forces the framing to be outcome-vs-spec rather than feature-tour.
520
+
521
+ ---
522
+
523
+ ## 7. Phase E — Gate 4 Close (Reporter + Human Sign-off)
524
+
525
+ This is a **Gate-3-class action**. Authorising sprint execution does NOT authorise close. Close requires its own dedicated human approval.
526
+
527
+ ### E.1 Step A — orchestrator runs close
528
+
529
+ ```bash
530
+ node .cleargate/scripts/close_sprint.mjs <sprint-id>
531
+ ```
532
+
533
+ No flags. Script validates Steps 1–2.6 (lifecycle reconciler runs at Step 2.6; see `cleargate-enforcement.md` §10), prefills `SPRINT-<#>_REPORT.md` stub if missing via the Reporter agent, and exits 0 with the prompt:
534
+
535
+ > Review the report, then confirm close by re-running with --assume-ack.
536
+
537
+ ### E.2 Reporter dispatch (Step 3.5)
538
+
539
+ If the report stub does not exist, dispatch the Reporter:
540
+
541
+ ```bash
542
+ bash .cleargate/scripts/write_dispatch.sh SPRINT-NN reporter
543
+ ```
544
+
545
+ - Cross-cutting rules: Read `.cleargate/sprint-runs/<sprint-id>/sprint-context.md` BEFORE any other action.
546
+
547
+ > **Fresh session.** The Reporter MUST dispatch in a fresh session — do not inherit dev+qa cumulative context. `write_dispatch.sh` already spawns a clean shell child; the `Agent` tool path requires no session-continuation flag. If the runtime offers a session-reset knob (e.g. `--resume false` or equivalent), use it. The Reporter starts cold and reads only `.reporter-context.md` + `sprint_report.md`.
548
+
549
+ > **Token budget.** Soft warn at 200k tokens, hard advisory at 500k (per CR-036). The token-ledger SubagentStop hook emits the warning to stdout; orchestrator surfaces the line into chat. Hard advisory auto-records a flashcard. The dispatch is NOT killed — the warning is informational; review the bundle slices on next sprint.
550
+
551
+ Reporter writes `.cleargate/sprint-runs/<id>/SPRINT-<#>_REPORT.md` and returns the Brief:
552
+
553
+ > **Goal:** `<verbatim sprint goal>` — **Verdict: met | partial | missed.**
554
+ > Delivered N stories, M epics. Observe: X bugs, Y review-feedback. Carry-over: Z. Token cost: T.
555
+ > See SPRINT-\<#>_REPORT.md for full report.
556
+ > Ready to authorize close (Gate 4)?
557
+
558
+ > 🎯 **Goal check.** The verdict line is mandatory and is the first line of the Brief. `met` = goal achieved as written. `partial` = some sprint-goal acceptance criteria met, others not — explain which in REPORT §1. `missed` = goal not achieved despite stories merging. A `partial` or `missed` verdict does NOT block close, but it is a first-class signal to the human that close-ack should be deliberate, not reflexive.
559
+
560
+ ### E.3 Step B — surface and HALT
561
+
562
+ Surface the Brief verbatim to the human. **Halt.** Do not re-run with `--assume-ack`.
563
+
564
+ The human either:
565
+
566
+ - Re-runs `close_sprint.mjs <id> --assume-ack` themselves, OR
567
+ - Says "approved, close it" — at which point you may pass the flag on their behalf.
568
+
569
+ `--assume-ack` is reserved for **automated test environments only**. Passing it autonomously is a Gate-4 breach equivalent to an unauthorized push.
570
+
571
+ ### E.4 Doc & metadata refresh on close
572
+
573
+ During Gate 4 sign-off, read `.cleargate/sprint-runs/<id>/.doc-refresh-checklist.md` (generated by `prep_doc_refresh.mjs`). Apply or punt each `- [ ]` item per `.cleargate/knowledge/sprint-closeout-checklist.md`. Items already `- [x]` mean "no changes detected, skip."
574
+
575
+ ### E.5 Sprint→main merge
576
+
577
+ After sign-off and after all walkthrough `UR:bug` items resolved:
578
+
579
+ ```bash
580
+ git checkout main
581
+ git merge sprint/S-NN --no-ff -m "Sprint S-NN: <goal>"
582
+ ```
583
+
584
+ Then flip sprint frontmatter `status: Completed`, archive the sprint file (`pending-sync/` → `archive/`).
585
+
586
+ ---
587
+
588
+ ## 8. Rework Counter Quick Reference
589
+
590
+ | Counter | Increment trigger | Escalation |
591
+ |---|---|---|
592
+ | `qa_bounces` | Each `QA: FAIL` | ≥ 3 → `Escalated`, halt |
593
+ | `arch_bounces` | Each `Architect: FAIL` | ≥ 3 → `Escalated`, halt |
594
+ | Circuit breaker | 50 tool calls without test pass OR 2 identical failures | 3 hits same story → `Escalated`, halt |
595
+ | Pre-gate failures | Each `pre_gate_runner.sh` non-zero | 3 hits same story → human escalation (descope / re-approach) |
596
+
597
+ > 🎯 **Goal check on escalation.** When a story flips to `Escalated`, frame the human-decision question through the goal lens, not in isolation: *"STORY-NNN-NN escalated after N rework cycles. Sprint goal is `<verbatim>`. Options: (a) drop the story — is the goal still met without it? (b) re-approach with X — same goal met by sprint end? (c) split into smaller stories — which scope serves the goal? (d) defer to next sprint — does the goal change?"* Never present escalation as a generic "what do you want to do?" — always tie options to goal achievement.
598
+
599
+ State updates go through:
600
+
601
+ ```bash
602
+ node .cleargate/scripts/update_state.mjs STORY-NNN-NN [--qa-bounce | --arch-bounce | <new-state>]
603
+ ```
604
+
605
+ `Escalated` halts the loop until human decides: descope, re-assign approach, or split story.
606
+
607
+ ---
608
+
609
+ ## 9. File-Surface Contract (v2)
610
+
611
+ Each story's §3.1 "Context & Files" table is the **authoritative file surface** for its commit. The pre-commit hook (`.git/hooks/pre-commit` → `.claude/hooks/pre-commit-surface-gate.sh`) blocks commits that touch off-surface files.
612
+
613
+ Off-surface edits require **either**:
614
+
615
+ 1. A `CR:scope-change` approved before the commit, OR
616
+ 2. An updated §3.1 table committed in the same story (self-amending — must be justified in commit message).
617
+
618
+ Bypass with `SKIP_SURFACE_GATE=1` only when absolutely necessary; log in sprint §4. Under v1 the hook only warns.
619
+
620
+ ---
621
+
622
+ ## 10. What This Skill Does NOT Cover
623
+
624
+ These live elsewhere — do not duplicate inline:
625
+
626
+ - **Triage / drafting / Gate 1 Brief** → CLAUDE.md + `cleargate-protocol.md` §§1–4.
627
+ - **Worktree command details and edge cases** → `cleargate-enforcement.md` §1.
628
+ - **Lane classification rubric (7 checks)** → `.claude/agents/architect.md` Lane Classification + `cleargate-enforcement.md` §9.
629
+ - **Sprint Plan template / Gate 2 Sprint Ready** → `.cleargate/templates/Sprint Plan Template.md`.
630
+ - **Wiki ingest / lint / contradiction detection** → `cleargate-protocol.md` §10.
631
+ - **Doctor exit codes** → `cleargate-enforcement.md` §8.
632
+ - **Hotfix flow** → V-Bounce-style hotfix handling, see flashcard tag `#hotfix` and `wiki/topics/hotfix-ledger.md`.
633
+
634
+ When in doubt, read the source-of-truth doc — this skill cites them, it does not replace them.
635
+
636
+ ---
637
+
638
+ ## 11. Conversational Discipline During Execution
639
+
640
+ - **Sprint execution is autonomous.** Once started, run the loop end-to-end. Escalate only on blockers, gate failures, or destructive operations.
641
+ - **Terse output.** Status updates one sentence each. Details live in story reports and `SPRINT-<#>_REPORT.md`, not in chat.
642
+ - **Halt at gates without negotiation.** Gate 3 (preflight), Gate 4 (close sign-off), `Escalated` state — these are not advisory. Surface, halt, wait.
643
+ - **Never `--no-verify`, `--assume-ack` autonomously, force-push, or `git reset --hard`.** Every one of these requires explicit per-action human approval.
644
+ - **Verify, don't trust agent self-reports.** A Developer claiming `STATUS=done` is not done — QA verifies. A `QA: PASS` is not approved-to-merge until reports exist and merge prerequisites pass.