@tekyzinc/gsd-t 2.50.12 → 2.53.10

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 (99) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +379 -372
  3. package/bin/component-registry.js +250 -0
  4. package/bin/graph-cgc.js +510 -510
  5. package/bin/graph-indexer.js +147 -147
  6. package/bin/graph-overlay.js +195 -195
  7. package/bin/graph-parsers.js +327 -327
  8. package/bin/graph-query.js +453 -452
  9. package/bin/graph-store.js +154 -154
  10. package/bin/qa-calibrator.js +194 -0
  11. package/bin/scan-data-collector.js +153 -153
  12. package/bin/scan-diagrams-generators.js +187 -187
  13. package/bin/scan-diagrams.js +79 -79
  14. package/bin/scan-renderer.js +92 -92
  15. package/bin/scan-report-sections.js +121 -121
  16. package/bin/scan-report.js +184 -184
  17. package/bin/scan-schema-parsers.js +199 -199
  18. package/bin/scan-schema.js +103 -103
  19. package/bin/token-budget.js +246 -0
  20. package/commands/Claude-md.md +10 -10
  21. package/commands/branch.md +15 -15
  22. package/commands/checkin.md +45 -45
  23. package/commands/global-change.md +209 -209
  24. package/commands/gsd-t-audit.md +199 -0
  25. package/commands/gsd-t-backlog-add.md +94 -94
  26. package/commands/gsd-t-backlog-edit.md +111 -111
  27. package/commands/gsd-t-backlog-list.md +63 -63
  28. package/commands/gsd-t-backlog-move.md +94 -94
  29. package/commands/gsd-t-backlog-promote.md +123 -123
  30. package/commands/gsd-t-backlog-remove.md +86 -86
  31. package/commands/gsd-t-backlog-settings.md +158 -158
  32. package/commands/gsd-t-complete-milestone.md +528 -515
  33. package/commands/gsd-t-debug.md +506 -399
  34. package/commands/gsd-t-discuss.md +174 -174
  35. package/commands/gsd-t-execute.md +758 -634
  36. package/commands/gsd-t-feature.md +276 -276
  37. package/commands/gsd-t-health.md +142 -142
  38. package/commands/gsd-t-help.md +465 -457
  39. package/commands/gsd-t-impact.md +302 -302
  40. package/commands/gsd-t-init.md +320 -280
  41. package/commands/gsd-t-integrate.md +365 -249
  42. package/commands/gsd-t-milestone.md +87 -87
  43. package/commands/gsd-t-partition.md +442 -361
  44. package/commands/gsd-t-pause.md +82 -82
  45. package/commands/gsd-t-plan.md +345 -344
  46. package/commands/gsd-t-populate.md +111 -111
  47. package/commands/gsd-t-prd.md +326 -326
  48. package/commands/gsd-t-project.md +211 -211
  49. package/commands/gsd-t-promote-debt.md +123 -123
  50. package/commands/gsd-t-prompt.md +137 -137
  51. package/commands/gsd-t-qa.md +266 -266
  52. package/commands/gsd-t-quick.md +357 -234
  53. package/commands/gsd-t-reflect.md +134 -134
  54. package/commands/gsd-t-resume.md +72 -72
  55. package/commands/gsd-t-scan.md +615 -615
  56. package/commands/gsd-t-setup.md +76 -0
  57. package/commands/gsd-t-status.md +192 -166
  58. package/commands/gsd-t-test-sync.md +381 -381
  59. package/commands/gsd-t-triage-and-merge.md +171 -171
  60. package/commands/gsd-t-verify.md +382 -382
  61. package/commands/gsd-t-visualize.md +118 -118
  62. package/commands/gsd-t-wave.md +401 -378
  63. package/docs/GSD-T-README.md +425 -422
  64. package/docs/architecture.md +385 -369
  65. package/docs/harness-design-analysis.md +371 -0
  66. package/docs/infrastructure.md +205 -205
  67. package/docs/prd-graph-engine.md +398 -398
  68. package/docs/prd-gsd2-hybrid.md +559 -559
  69. package/docs/prd-harness-evolution.md +583 -0
  70. package/docs/requirements.md +14 -0
  71. package/docs/workflows.md +226 -226
  72. package/examples/.gsd-t/domains/example-domain/scope.md +13 -13
  73. package/package.json +40 -40
  74. package/scripts/gsd-t-auto-route.js +39 -39
  75. package/scripts/gsd-t-dashboard-mockup.html +1143 -1143
  76. package/scripts/gsd-t-dashboard-server.js +171 -171
  77. package/scripts/gsd-t-dashboard.html +262 -262
  78. package/scripts/gsd-t-event-writer.js +128 -128
  79. package/scripts/gsd-t-statusline.js +94 -94
  80. package/scripts/gsd-t-tools.js +175 -175
  81. package/templates/CLAUDE-global.md +639 -614
  82. package/templates/CLAUDE-project.md +24 -0
  83. package/templates/backlog-settings.md +18 -18
  84. package/templates/backlog.md +1 -1
  85. package/templates/progress.md +40 -40
  86. package/templates/shared-services-contract.md +60 -60
  87. package/templates/stacks/desktop.ini +2 -2
  88. package/bin/desktop.ini +0 -2
  89. package/commands/desktop.ini +0 -2
  90. package/docs/ci-examples/desktop.ini +0 -2
  91. package/docs/desktop.ini +0 -2
  92. package/examples/.gsd-t/contracts/desktop.ini +0 -2
  93. package/examples/.gsd-t/desktop.ini +0 -2
  94. package/examples/.gsd-t/domains/desktop.ini +0 -2
  95. package/examples/.gsd-t/domains/example-domain/desktop.ini +0 -2
  96. package/examples/desktop.ini +0 -2
  97. package/examples/rules/desktop.ini +0 -2
  98. package/scripts/desktop.ini +0 -2
  99. package/templates/desktop.ini +0 -2
@@ -1,378 +1,401 @@
1
- # GSD-T: Wave — Full Cycle Orchestration (Agent-Per-Phase)
2
-
3
- You are the wave orchestrator. You do NOT execute phases yourself. Instead, you spawn an **independent agent for each phase**, giving each a fresh context window. This eliminates context accumulation across phases and prevents mid-wave compaction.
4
-
5
- ## Step 1: Load State (Lightweight)
6
-
7
- Read ONLY:
8
- 1. `.gsd-t/progress.md` — current status, milestone name, phase state
9
- 2. `CLAUDE.md` — autonomy level only (scan for Level 1/2/3)
10
-
11
- Do NOT read contracts, domains, docs, or source code. You are the orchestrator — phase agents handle their own context loading.
12
-
13
- ### Integrity Check
14
-
15
- After reading progress.md, verify it contains the required fields before proceeding:
16
- - **Status field**: A `Status:` line with a recognized value (DEFINED, PARTITIONED, PLANNED, etc.)
17
- - **Milestone name**: A `Milestone` heading or table entry identifying the current milestone
18
- - **Domains table**: A `| Domain |` table with at least one row
19
-
20
- If ANY of these are missing or malformed, STOP and report:
21
- "Wave cannot proceed — progress.md is missing required fields: {list}. Run `/user:gsd-t-status` to inspect, or `/user:gsd-t-init` to repair."
22
- Do NOT attempt to fix progress.md yourself — that risks data loss.
23
-
24
- ## Step 2: Determine Resume Point
25
-
26
- From progress.md status, determine which phase to start from:
27
-
28
- | Status | Next Phase |
29
- |--------|------------|
30
- | READY | Need milestone first — prompt user or run milestone |
31
- | INITIALIZED / DEFINED | Partition |
32
- | PARTITIONED | Discuss (or skip to Plan if path is clear) |
33
- | DISCUSSED | Plan |
34
- | PLANNED | Impact |
35
- | IMPACT_ANALYZED | Execute |
36
- | EXECUTED | Test-Sync |
37
- | TESTS_SYNCED | Integrate |
38
- | INTEGRATED | Verify |
39
- | VERIFIED | Complete |
40
- | VERIFY_FAILED | Remediate → re-Verify |
41
-
42
- ## Step 3: Phase Orchestration Loop
43
-
44
- For each remaining phase, spawn an **independent agent** using the Task tool. Each agent gets a fresh context window, loads its own state from files, and reports back.
45
-
46
- ### Graph Availability
47
-
48
- If `.gsd-t/graph/meta.json` exists, the code graph is available for all phases. Each phase agent's spawn prompt should include:
49
- "If .gsd-t/graph/meta.json exists, use graph queries (getCallers, getDomainBoundaryViolations, getTestsFor, etc.) to enhance analysis per the phase command instructions."
50
-
51
- ### Phase Agent Spawn Pattern
52
-
53
- For each phase, spawn the agent like this:
54
-
55
- **Stack Rules Detection (before spawning subagent):**
56
- Run via Bash to detect project stack and collect matching rules:
57
- `GSD_T_DIR=$(npm root -g 2>/dev/null)/@tekyzinc/gsd-t; STACKS_DIR="$GSD_T_DIR/templates/stacks"; STACK_RULES=""; if [ -d "$STACKS_DIR" ]; then for f in "$STACKS_DIR"/_*.md; do [ -f "$f" ] && STACK_RULES="${STACK_RULES}$(cat "$f")"$'\n\n'; done; if [ -f "package.json" ]; then grep -q '"react"' package.json 2>/dev/null && [ -f "$STACKS_DIR/react.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/react.md")"$'\n\n'; (grep -q '"typescript"' package.json 2>/dev/null || [ -f "tsconfig.json" ]) && [ -f "$STACKS_DIR/typescript.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/typescript.md")"$'\n\n'; grep -qE '"(express|fastify|hono|koa)"' package.json 2>/dev/null && [ -f "$STACKS_DIR/node-api.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/node-api.md")"$'\n\n'; fi; [ -f "requirements.txt" ] || [ -f "pyproject.toml" ] && [ -f "$STACKS_DIR/python.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/python.md")"$'\n\n'; [ -f "go.mod" ] && [ -f "$STACKS_DIR/go.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/go.md")"$'\n\n'; [ -f "Cargo.toml" ] && [ -f "$STACKS_DIR/rust.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/rust.md")"$'\n\n'; fi`
58
-
59
- If STACK_RULES is non-empty, append to the subagent prompt:
60
- ```
61
- ## Stack Rules (MANDATORY violations fail this task)
62
-
63
- {STACK_RULES}
64
-
65
- These standards have the same enforcement weight as contract compliance.
66
- Violations are task failures, not warnings.
67
- ```
68
-
69
- If STACK_RULES is empty (no templates/stacks/ dir or no matches), skip silently.
70
-
71
- **OBSERVABILITY LOGGING (MANDATORY) — repeat for every phase spawn:**
72
- Before spawning run via Bash:
73
- `T_START=$(date +%s) && DT_START=$(date +"%Y-%m-%d %H:%M") && TOK_START=${CLAUDE_CONTEXT_TOKENS_USED:-0} && TOK_MAX=${CLAUDE_CONTEXT_TOKENS_MAX:-200000}`
74
-
75
- ```
76
- Task agent (subagent_type: "general-purpose", mode: "bypassPermissions"):
77
- "Execute the {PHASE} phase of the current GSD-T milestone.
78
-
79
- Read and follow the full instructions in commands/gsd-t-{phase}.md
80
- Read .gsd-t/progress.md for current milestone and state.
81
- Read CLAUDE.md for project conventions.
82
- Read .gsd-t/contracts/ for domain interfaces.
83
-
84
- Complete the phase fully:
85
- - Follow every step in the command file
86
- - Update .gsd-t/progress.md status when done
87
- - Run document ripple as specified
88
- - Commit your work
89
-
90
- Report back: one-line status summary."
91
- ```
92
-
93
- After phase agent returns — run via Bash:
94
- `T_END=$(date +%s) && DT_END=$(date +"%Y-%m-%d %H:%M") && TOK_END=${CLAUDE_CONTEXT_TOKENS_USED:-0} && DURATION=$((T_END-T_START))`
95
- Compute tokens and compaction:
96
- - No compaction (TOK_END >= TOK_START): `TOKENS=$((TOK_END-TOK_START))`, COMPACTED=null
97
- - Compaction detected (TOK_END < TOK_START): `TOKENS=$(((TOK_MAX-TOK_START)+TOK_END))`, COMPACTED=$DT_END
98
- Compute context utilization — run via Bash:
99
- `if [ "${CLAUDE_CONTEXT_TOKENS_MAX:-0}" -gt 0 ]; then CTX_PCT=$(echo "scale=1; ${CLAUDE_CONTEXT_TOKENS_USED:-0} * 100 / ${CLAUDE_CONTEXT_TOKENS_MAX}" | bc); else CTX_PCT="N/A"; fi`
100
- Alert on context thresholds (display to user inline):
101
- - If CTX_PCT >= 85: `echo "🔴 CRITICAL: Context at ${CTX_PCT}% — compaction likely. Task MUST be split."`
102
- - If CTX_PCT >= 70: `echo "⚠️ WARNING: Context at ${CTX_PCT}% — approaching compaction threshold. Consider splitting in plan."`
103
-
104
- **Orchestrator Context Self-Check (MANDATORY):**
105
- After EVERY phase agent returns, check the wave orchestrator's own context:
106
- - **If CTX_PCT >= 70:**
107
- 1. Save checkpoint to `.gsd-t/progress.md` — record which phases are complete, which remain
108
- 2. Output: `⚠️ Wave orchestrator context at {CTX_PCT}% — approaching limit. Progress saved. Run /clear then /user:gsd-t-wave to continue from the next phase.`
109
- 3. **STOP the wave loop.** Do NOT spawn the next phase agent. The next session resumes from saved state.
110
- - **If CTX_PCT < 70:** Continue to next phase.
111
-
112
- This prevents the wave orchestrator from running out of context mid-wave.
113
-
114
- Append to `.gsd-t/token-log.md` (create with header `| Datetime-start | Datetime-end | Command | Step | Model | Duration(s) | Notes | Tokens | Compacted | Domain | Task | Ctx% |` if missing):
115
- `| {DT_START} | {DT_END} | gsd-t-wave | {PHASE} | sonnet | {DURATION}s | phase: {PHASE} | {TOKENS} | {COMPACTED} | | | {CTX_PCT} |`
116
-
117
- ### Phase Sequence
118
-
119
- Execute phases in this order, spawning one agent per phase:
120
-
121
- #### 1. PARTITION
122
- Spawn agent `commands/gsd-t-partition.md`
123
- - After: Read `progress.md`, verify status = PARTITIONED
124
- - If failed: Report error, stop
125
-
126
- #### 2. DISCUSS (conditional)
127
- - **Structured skip check** — skip discuss and go directly to Plan if ALL of these are true:
128
- - (a) Single domain milestone (only one entry in Domains table)
129
- - (b) No items containing "OPEN QUESTION" in the Decision Log
130
- - (c) For multi-domain milestones: all cross-domain contracts exist in `.gsd-t/contracts/`
131
- - If ANY check fails: Spawn agent `commands/gsd-t-discuss.md`
132
- - **Note**: Discuss always pauses for user input, even at Level 3. The discuss agent will interact with the user directly.
133
- - If all checks pass: Skip to Plan
134
-
135
- #### 3. PLAN
136
- Spawn agent → `commands/gsd-t-plan.md`
137
- - After: Read `progress.md`, verify status = PLANNED
138
-
139
- #### 4. IMPACT
140
- Spawn agent → `commands/gsd-t-impact.md`
141
- - After: Read `progress.md` and `.gsd-t/impact-report.md`
142
- - **Decision Gate**:
143
- - PROCEED → continue to Execute
144
- - PROCEED WITH CAUTION → log items, continue
145
- - BLOCKstop, report to user, wait for decision
146
-
147
- #### 5. EXECUTE
148
- Spawn agent → `commands/gsd-t-execute.md`
149
- - This is the heaviest phase. The execute agent uses **task-level dispatch** (fresh-dispatch-contract.md): one Task subagent per task within each domain, each receiving only scope.md + relevant contracts + single task + graph context + up to 5 prior summaries. The execute agent handles domain task-dispatching and QA internally.
150
- - **Adaptive replanning**: After each domain completes, the execute agent runs a replan check (per `adaptive-replan-contract.md`). If a completed domain's task summaries reveal new constraints (e.g., deprecated API, wrong column name, incompatible library), the execute agent checks remaining domains' `tasks.md` files for invalidated assumptions and revises them on disk before dispatching the next domain. Maximum 2 replan cycles per execute run — if exceeded, execution pauses for user input. All replan decisions are logged to the Decision Log in `progress.md`. The wave phase summary includes any replan actions taken.
151
- - **Team/parallel mode**: If the plan defines parallel domains (same wave), the execute agent dispatches each domain teammate with `isolation: "worktree"` (per worktree-isolation-contract.md). Each domain works in an isolated git worktree. After all domains complete, the execute agent runs the Sequential Merge Protocol: merge domain A → test → merge domain B → test. Per-domain rollback if tests fail. Worktrees are cleaned up after all merges complete.
152
- - After: Read `progress.md`, verify status = EXECUTED. Phase summary must include replan actions if any occurred:
153
- ```
154
- 📋 Phase 5 (EXECUTE): {N}/{N} tasks done | Replan cycles: {N} | Domains revised: {list or "none"}
155
- ```
156
-
157
- #### 6. TEST-SYNC
158
- Spawn agent → `commands/gsd-t-test-sync.md`
159
- - After: Read `progress.md`, verify status = TESTS_SYNCED
160
-
161
- #### 7. INTEGRATE
162
- Spawn agent → `commands/gsd-t-integrate.md`
163
- - After: Read `progress.md`, verify status = INTEGRATED
164
-
165
- #### 8. VERIFY + COMPLETE
166
- Spawn agent`commands/gsd-t-verify.md`
167
- - The verify agent runs all 8 standard quality gates **plus** the goal-backward verification step (Step 5.5 in gsd-t-verify.md), which checks that milestone goals are actually achieved end-to-end and scans for placeholder patterns per `.gsd-t/contracts/goal-backward-contract.md`
168
- - Goal-backward runs after all structural gates pass CRITICAL or HIGH findings block verification; MEDIUM findings are warnings only
169
- - **Verify auto-invokes complete-milestone** (Step 8 of gsd-t-verify.md). The verify agent handles both verification AND milestone completion in a single agent context. Do NOT spawn a separate complete agent.
170
- - After: Read `progress.md`, check status:
171
- - COMPLETEDmilestone done (verify passed and auto-completed)
172
- - VERIFIED verify passed but complete-milestone failed spawn a standalone complete agent as fallback
173
- - VERIFY_FAILED handle remediation (see Error Recovery) — includes goal-backward failures
174
- - Phase summary must include the `Goal-Backward:` line from verify-report.md:
175
- ```
176
- 📋 Phase 8 (VERIFY+COMPLETE): {N} gates passed | Goal-Backward: {PASS/WARN/FAIL} — {N} requirements checked, {N} findings
177
- ```
178
-
179
- #### 9. DOC-RIPPLE (Automated — after verify+complete)
180
-
181
- After the final phase completes but before wave reports done:
182
-
183
- 1. Run threshold check — read `git diff --name-only HEAD~1` and evaluate against doc-ripple-contract.md trigger conditions
184
- 2. If SKIP: log "Doc-ripple: SKIP — {reason}" and proceed
185
- 3. If FIRE: spawn doc-ripple agent:
186
-
187
- ⚙ [{model}] gsd-t-doc-ripple → blast radius analysis + parallel updates
188
-
189
- Task subagent (general-purpose, model: sonnet):
190
- "Execute the doc-ripple workflow per commands/gsd-t-doc-ripple.md.
191
- Git diff context: {files changed list}
192
- Command that triggered: wave
193
- Produce manifest at .gsd-t/doc-ripple-manifest.md.
194
- Update all affected documents.
195
- Report: 'Doc-ripple: {N} checked, {N} updated, {N} skipped'"
196
-
197
- 4. After doc-ripple returns, verify manifest exists and report summary inline
198
-
199
- ### Between Each Phase
200
-
201
- After each agent completes, run this spot-check before proceeding:
202
-
203
- 1. **Status check**: Read `.gsd-t/progress.md` — verify the phase updated status correctly (no FAILED markers, status matches expected phase completion state)
204
- 2. **Git check**: Run `git log --oneline -5` verify commits were made during this phase (if execute/integrate: at least one commit per task completed)
205
- 3. **Filesystem check**: Verify key output files exist on disk — e.g., for partition: `.gsd-t/domains/*/scope.md` and `.gsd-t/contracts/` files; for execute: newly created source files; for verify: `.gsd-t/verify-report.md`. Do not trust agent-reported completions alone.
206
- 4. Report to user:
207
- ```
208
- {Phase} complete {agent's one-line summary}
209
- 📋 Spot-check: {N} commits | {N} output files verified | no FAILED markers
210
- ```
211
- 5. If spot-check fails: write failure event via Bash, then report the discrepancy, re-spawn the phase agent once to correct it, then re-verify. If still failing: stop and report to user.
212
- ```bash
213
- node ~/.claude/scripts/gsd-t-event-writer.js \
214
- --type phase_transition \
215
- --command gsd-t-wave \
216
- --phase {COMPLETED_PHASE} \
217
- --reasoning "Spot-check failed: {one-line discrepancy summary}" \
218
- --outcome failure \
219
- --agent-id "${CLAUDE_SESSION_ID:-unknown}" || true
220
- ```
221
- 5a. After spot-check passes, write success event via Bash:
222
- ```bash
223
- node ~/.claude/scripts/gsd-t-event-writer.js \
224
- --type phase_transition \
225
- --command gsd-t-wave \
226
- --phase {COMPLETED_PHASE} \
227
- --reasoning "Phase complete: {one-line spot-check summary}" \
228
- --outcome success \
229
- --agent-id "${CLAUDE_SESSION_ID:-unknown}" || true
230
- ```
231
- The `|| true` ensures event write failure never blocks wave execution.
232
- 6. Proceed to next phase
233
-
234
- ## Step 4: Autonomy Behavior
235
-
236
- **Level 3 (Full Auto)**: Auto-advance to next phase after each agent completes. Only STOP for:
237
- - Destructive Action Guard violations (reported by phase agent)
238
- - Impact analysis BLOCK verdict
239
- - Unrecoverable errors after 2 fix attempts
240
- - Discuss phase (always pauses for user input)
241
-
242
- **Level 1–2**: Pause between phases, show status, ask to continue.
243
-
244
- ## Step 5: Completion
245
-
246
- When all phases are done:
247
- ```
248
- ═══════════════════════════════════════════════════════════════════════════════
249
- Milestone "{name}" complete!
250
- ═══════════════════════════════════════════════════════════════════════════════
251
-
252
- 📁 Archived to: .gsd-t/milestones/{name}-{date}/
253
- 🏷️ Tagged as: milestone/{name}
254
-
255
- Summary:
256
- - Domains: {list}
257
- - Tasks completed: {N}
258
- - Contracts: {N} defined/verified
259
- - Tests: {N} added/updated
260
- - Impact items addressed: {N}
261
- - Decision log entries: {N}
262
-
263
- Next steps:
264
- - Push tag: git push origin milestone/{name}
265
- - Start next: /user:gsd-t-milestone "{next}"
266
- - View roadmap: /user:gsd-t-status
267
- ═══════════════════════════════════════════════════════════════════════════════
268
- ```
269
-
270
- ## Interruption Handling
271
-
272
- If the user interrupts or a phase agent fails:
273
- 1. The current phase agent saves its own state to `.gsd-t/progress.md`
274
- 2. Report: "Paused at {phase}. Run `/user:gsd-t-resume` to continue."
275
- 3. Resume will pick up from the last completed phase
276
-
277
- ## Error Recovery
278
-
279
- ### If impact analysis blocks:
280
- - Read the impact report from the agent's output
281
- - Report blocking issues to user
282
-
283
- **Level 3**: Spawn a remediation agent to fix blocking issues, then re-spawn impact agent. Max 2 attempts.
284
- If both attempts fail:
285
- 1. Write failure context to `.gsd-t/debug-state.jsonl` via `node -e "require('./bin/debug-ledger.js').appendEntry('.', {iteration:1,timestamp:new Date().toISOString(),test:'impact-remediation',error:'2 in-context fix attempts exhausted',hypothesis:'see impact-report.md',fix:'n/a',fixFiles:[],result:'STILL_FAILS',learning:'delegating to headless debug-loop',model:'sonnet',duration:0})"`
286
- 2. Log: "Delegating to headless debug-loop (2 in-context attempts exhausted)"
287
- 3. Run: `gsd-t headless --debug-loop --max-iterations 10`
288
- 4. Exit code 0 → continue; 1/4 → log to `.gsd-t/deferred-items.md`, report to user; 3 → report error
289
- **Level 1–2**: Ask user for direction.
290
-
291
- ### If tests fail during execute:
292
- - The execute agent handles test failures internally (up to 2 fix attempts)
293
- - If still failing after 2 attempts, the execute agent reports failure
294
- - Orchestrator stops and reports to user
295
-
296
- ### If verify fails:
297
- - Read verify report for failure details
298
-
299
- **Level 3**: Spawn remediation agent, then re-spawn verify agent. Max 2 attempts.
300
- If both attempts fail:
301
- 1. Write failure context to `.gsd-t/debug-state.jsonl` via `node -e "require('./bin/debug-ledger.js').appendEntry('.', {iteration:1,timestamp:new Date().toISOString(),test:'verify-remediation',error:'2 in-context fix attempts exhausted',hypothesis:'see verify-report.md',fix:'n/a',fixFiles:[],result:'STILL_FAILS',learning:'delegating to headless debug-loop',model:'sonnet',duration:0})"`
302
- 2. Log: "Delegating to headless debug-loop (2 in-context attempts exhausted)"
303
- 3. Run: `gsd-t headless --debug-loop --max-iterations 10`
304
- 4. Exit code 0 → re-spawn verify agent; 1/4 → log to `.gsd-t/deferred-items.md`, report to user; 3 → report error
305
- **Level 1–2**: Ask user for direction.
306
-
307
- ## Why Agent-Per-Phase
308
-
309
- Each phase agent gets a **fresh context window** (~200K tokens). This means:
310
- - Phase 7 doesn't carry the context baggage from phases 1-6
311
- - Mid-phase compaction is eliminated for standard-sized phases
312
- - Each agent loads only what it needs from state files
313
- - The orchestrator stays lightweight (~30KB total)
314
-
315
- State handoff happens through `.gsd-t/` files exactly what they were designed for.
316
-
317
- ## Security Considerations
318
-
319
- ### bypassPermissions Mode
320
-
321
- Wave spawns each phase agent with `mode: "bypassPermissions"`. This means agents execute bash commands, write files, and perform git operations **without per-action user approval**. This is by design — wave phases would be impractical with manual approval at every step.
322
-
323
- ### Attack Surface
324
-
325
- If command files in `~/.claude/commands/` are tampered with, wave agents will execute the modified instructions with full permissions. The attack requires:
326
- 1. Write access to the user's `~/.claude/commands/` directory
327
- 2. Knowledge of the GSD-T command file format
328
- 3. The user to run `/gsd-t-wave` after tampering
329
-
330
- ### Current Mitigations
331
-
332
- - **npm-installed files**: Command files are installed from the npm registry, providing a known-good source
333
- - **Content comparison on update**: `gsd-t update` compares file contents and reports changes
334
- - **User-owned directory**: `~/.claude/commands/` inherits the user's filesystem permissions
335
- - **Destructive Action Guard**: CLAUDE.md instructions provide soft protection against destructive operations (DROP TABLE, schema changes, etc.), though agents could theoretically ignore these
336
- - **Autonomy levels**: Level 1 and Level 2 pause between phases, giving users visibility into agent activity
337
-
338
- ### Recommendations
339
-
340
- - For sensitive projects, use **Level 1 or Level 2 autonomy** instead of Level 3 to review each phase's output
341
- - Periodically verify command file integrity: `gsd-t doctor` checks installation health
342
- - If security is a concern, audit `~/.claude/commands/gsd-t-*.md` files for unexpected modifications
343
- - Keep GSD-T updated (`gsd-t update`) to receive the latest command files from npm
344
-
345
- ## Workflow Visualization
346
-
347
- ```
348
- ┌──────────────────────────────────────────────────────────────────────────────┐
349
- │ Wave Orchestrator (lightweight) │
350
- │ │
351
- │ ┌─────────┐ ┌─────────┐ ┌──────┐ ┌────────┐ ┌─────────┐ │
352
- │ │PARTITION│ → │ DISCUSS │ → │ PLAN │ → │ IMPACT │ → │ EXECUTE │ │
353
- │ │ agent 1 │ │ agent 2 │ │agent 3│ │agent 4 │ │ agent 5 │ │
354
- │ └────┬────┘ └────┬────┘ └───┬──┘ └───┬────┘ └────┬────┘ │
355
- │ ↓ ↓ ↓ ↓ ↓ │
356
- │ status status status status status │
357
- │ check check check check + check │
358
- │ gate │
359
- │ │
360
- │ ┌──────────────────┐ ┌───────────┐ ┌─────────────────┐ │
361
- │ │ VERIFY+COMPLETE │ ← │ INTEGRATE │ ←──── │ FULL TEST-SYNC │ │
362
- │ │ agent 8 │ │ agent 7 │ │ agent 6 │ │
363
- │ └────────┬─────────┘ └─────┬─────┘ └────────┬────────┘ │
364
- │ ↓ ↓ ↓ │
365
- │ gate check → status status │
366
- │ auto-complete check check │
367
- │ archive + tag │
368
- │ │
369
- │ Each agent: fresh context window, reads state from files, dies when done │
370
- │ Orchestrator: 8 agents (was 9), ~30KB total, never compacts │
371
- └──────────────────────────────────────────────────────────────────────────────┘
372
- ```
373
-
374
- $ARGUMENTS
375
-
376
- ## Auto-Clear
377
-
378
- The full wave cycle is complete. All work is committed to project files. Execute `/clear` to free the orchestrator context window.
1
+ # GSD-T: Wave — Full Cycle Orchestration (Agent-Per-Phase)
2
+
3
+ You are the wave orchestrator. You do NOT execute phases yourself. Instead, you spawn an **independent agent for each phase**, giving each a fresh context window. This eliminates context accumulation across phases and prevents mid-wave compaction.
4
+
5
+ ## Step 1: Load State (Lightweight)
6
+
7
+ Read ONLY:
8
+ 1. `.gsd-t/progress.md` — current status, milestone name, phase state
9
+ 2. `CLAUDE.md` — autonomy level only (scan for Level 1/2/3)
10
+
11
+ Do NOT read contracts, domains, docs, or source code. You are the orchestrator — phase agents handle their own context loading.
12
+
13
+ ### Integrity Check
14
+
15
+ After reading progress.md, verify it contains the required fields before proceeding:
16
+ - **Status field**: A `Status:` line with a recognized value (DEFINED, PARTITIONED, PLANNED, etc.)
17
+ - **Milestone name**: A `Milestone` heading or table entry identifying the current milestone
18
+ - **Domains table**: A `| Domain |` table with at least one row
19
+
20
+ If ANY of these are missing or malformed, STOP and report:
21
+ "Wave cannot proceed — progress.md is missing required fields: {list}. Run `/user:gsd-t-status` to inspect, or `/user:gsd-t-init` to repair."
22
+ Do NOT attempt to fix progress.md yourself — that risks data loss.
23
+
24
+ ## Step 2: Determine Resume Point
25
+
26
+ From progress.md status, determine which phase to start from:
27
+
28
+ | Status | Next Phase |
29
+ |--------|------------|
30
+ | READY | Need milestone first — prompt user or run milestone |
31
+ | INITIALIZED / DEFINED | Partition |
32
+ | PARTITIONED | Discuss (or skip to Plan if path is clear) |
33
+ | DISCUSSED | Plan |
34
+ | PLANNED | Impact |
35
+ | IMPACT_ANALYZED | Execute |
36
+ | EXECUTED | Test-Sync |
37
+ | TESTS_SYNCED | Integrate |
38
+ | INTEGRATED | Verify |
39
+ | VERIFIED | Complete |
40
+ | VERIFY_FAILED | Remediate → re-Verify |
41
+
42
+ ## Step 2.5: Token Budget Pre-Flight (if available)
43
+
44
+ Before starting the phase loop, check the projected token cost for this milestone:
45
+
46
+ Run via Bash:
47
+ `node -e "const tb = require('./bin/token-budget.js'); const est = tb.estimateMilestoneCost('.'); if(est) process.stdout.write(JSON.stringify(est));" 2>/dev/null`
48
+
49
+ If the command returns data, display to user:
50
+ - `estimated_tokens`: projected total tokens for this milestone
51
+ - `warning`: if `estimated_tokens > budget_ceiling * 0.8`, warn: "Token budget pre-flight: {estimated_tokens} tokens estimated — approaching session ceiling. Consider splitting milestone."
52
+
53
+ If the file doesn't exist or returns nothing, skip silently and proceed.
54
+
55
+ ## Step 3: Phase Orchestration Loop
56
+
57
+ For each remaining phase, spawn an **independent agent** using the Task tool. Each agent gets a fresh context window, loads its own state from files, and reports back.
58
+
59
+ ### Graph Availability
60
+
61
+ If `.gsd-t/graph/meta.json` exists, the code graph is available for all phases. Each phase agent's spawn prompt should include:
62
+ "If .gsd-t/graph/meta.json exists, use graph queries (getCallers, getDomainBoundaryViolations, getTestsFor, etc.) to enhance analysis per the phase command instructions."
63
+
64
+ ### Phase Agent Spawn Pattern
65
+
66
+ For each phase, spawn the agent like this:
67
+
68
+ **Stack Rules Detection (before spawning subagent):**
69
+ Run via Bash to detect project stack and collect matching rules:
70
+ `GSD_T_DIR=$(npm root -g 2>/dev/null)/@tekyzinc/gsd-t; STACKS_DIR="$GSD_T_DIR/templates/stacks"; STACK_RULES=""; if [ -d "$STACKS_DIR" ]; then for f in "$STACKS_DIR"/_*.md; do [ -f "$f" ] && STACK_RULES="${STACK_RULES}$(cat "$f")"$'\n\n'; done; if [ -f "package.json" ]; then grep -q '"react"' package.json 2>/dev/null && [ -f "$STACKS_DIR/react.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/react.md")"$'\n\n'; (grep -q '"typescript"' package.json 2>/dev/null || [ -f "tsconfig.json" ]) && [ -f "$STACKS_DIR/typescript.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/typescript.md")"$'\n\n'; grep -qE '"(express|fastify|hono|koa)"' package.json 2>/dev/null && [ -f "$STACKS_DIR/node-api.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/node-api.md")"$'\n\n'; fi; [ -f "requirements.txt" ] || [ -f "pyproject.toml" ] && [ -f "$STACKS_DIR/python.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/python.md")"$'\n\n'; [ -f "go.mod" ] && [ -f "$STACKS_DIR/go.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/go.md")"$'\n\n'; [ -f "Cargo.toml" ] && [ -f "$STACKS_DIR/rust.md" ] && STACK_RULES="${STACK_RULES}$(cat "$STACKS_DIR/rust.md")"$'\n\n'; fi`
71
+
72
+ If STACK_RULES is non-empty, append to the subagent prompt:
73
+ ```
74
+ ## Stack Rules (MANDATORY — violations fail this task)
75
+
76
+ {STACK_RULES}
77
+
78
+ These standards have the same enforcement weight as contract compliance.
79
+ Violations are task failures, not warnings.
80
+ ```
81
+
82
+ If STACK_RULES is empty (no templates/stacks/ dir or no matches), skip silently.
83
+
84
+ **Per-Phase Token Budget Check (before each phase spawn):**
85
+
86
+ Run via Bash:
87
+ `node -e "const tb = require('./bin/token-budget.js'); const s = tb.getSessionStatus('.'); process.stdout.write(s.threshold);" 2>/dev/null`
88
+
89
+ - `normal` or file missing → proceed normally
90
+ - `downgrade` apply model overrides from `getDegradationActions()` in the phase agent prompt
91
+ - `conserve` → checkpoint progress, skip non-essential phases (test-sync if code unchanged, discuss if already done)
92
+ - `stop` → checkpoint all progress and output: "Token budget exhausted — wave paused. Resume after session reset." then halt
93
+
94
+ **OBSERVABILITY LOGGING (MANDATORY) repeat for every phase spawn:**
95
+ Before spawning run via Bash:
96
+ `T_START=$(date +%s) && DT_START=$(date +"%Y-%m-%d %H:%M") && TOK_START=${CLAUDE_CONTEXT_TOKENS_USED:-0} && TOK_MAX=${CLAUDE_CONTEXT_TOKENS_MAX:-200000}`
97
+
98
+ ```
99
+ Task agent (subagent_type: "general-purpose", mode: "bypassPermissions"):
100
+ "Execute the {PHASE} phase of the current GSD-T milestone.
101
+
102
+ Read and follow the full instructions in commands/gsd-t-{phase}.md
103
+ Read .gsd-t/progress.md for current milestone and state.
104
+ Read CLAUDE.md for project conventions.
105
+ Read .gsd-t/contracts/ for domain interfaces.
106
+
107
+ Complete the phase fully:
108
+ - Follow every step in the command file
109
+ - Update .gsd-t/progress.md status when done
110
+ - Run document ripple as specified
111
+ - Commit your work
112
+
113
+ Report back: one-line status summary."
114
+ ```
115
+
116
+ After phase agent returns — run via Bash:
117
+ `T_END=$(date +%s) && DT_END=$(date +"%Y-%m-%d %H:%M") && TOK_END=${CLAUDE_CONTEXT_TOKENS_USED:-0} && DURATION=$((T_END-T_START))`
118
+ Compute tokens and compaction:
119
+ - No compaction (TOK_END >= TOK_START): `TOKENS=$((TOK_END-TOK_START))`, COMPACTED=null
120
+ - Compaction detected (TOK_END < TOK_START): `TOKENS=$(((TOK_MAX-TOK_START)+TOK_END))`, COMPACTED=$DT_END
121
+ Compute context utilization — run via Bash:
122
+ `if [ "${CLAUDE_CONTEXT_TOKENS_MAX:-0}" -gt 0 ]; then CTX_PCT=$(echo "scale=1; ${CLAUDE_CONTEXT_TOKENS_USED:-0} * 100 / ${CLAUDE_CONTEXT_TOKENS_MAX}" | bc); else CTX_PCT="N/A"; fi`
123
+ Alert on context thresholds (display to user inline):
124
+ - If CTX_PCT >= 85: `echo "🔴 CRITICAL: Context at ${CTX_PCT}% — compaction likely. Task MUST be split."`
125
+ - If CTX_PCT >= 70: `echo "⚠️ WARNING: Context at ${CTX_PCT}% — approaching compaction threshold. Consider splitting in plan."`
126
+
127
+ **Orchestrator Context Self-Check (MANDATORY):**
128
+ After EVERY phase agent returns, check the wave orchestrator's own context:
129
+ - **If CTX_PCT >= 70:**
130
+ 1. Save checkpoint to `.gsd-t/progress.md` record which phases are complete, which remain
131
+ 2. Output: `⚠️ Wave orchestrator context at {CTX_PCT}% — approaching limit. Progress saved. Run /clear then /user:gsd-t-wave to continue from the next phase.`
132
+ 3. **STOP the wave loop.** Do NOT spawn the next phase agent. The next session resumes from saved state.
133
+ - **If CTX_PCT < 70:** Continue to next phase.
134
+
135
+ This prevents the wave orchestrator from running out of context mid-wave.
136
+
137
+ Append to `.gsd-t/token-log.md` (create with header `| Datetime-start | Datetime-end | Command | Step | Model | Duration(s) | Notes | Tokens | Compacted | Domain | Task | Ctx% |` if missing):
138
+ `| {DT_START} | {DT_END} | gsd-t-wave | {PHASE} | sonnet | {DURATION}s | phase: {PHASE} | {TOKENS} | {COMPACTED} | | | {CTX_PCT} |`
139
+
140
+ ### Phase Sequence
141
+
142
+ Execute phases in this order, spawning one agent per phase:
143
+
144
+ #### 1. PARTITION
145
+ Spawn agent`commands/gsd-t-partition.md`
146
+ - After: Read `progress.md`, verify status = PARTITIONED
147
+ - If failed: Report error, stop
148
+
149
+ #### 2. DISCUSS (conditional)
150
+ - **Structured skip check** skip discuss and go directly to Plan if ALL of these are true:
151
+ - (a) Single domain milestone (only one entry in Domains table)
152
+ - (b) No items containing "OPEN QUESTION" in the Decision Log
153
+ - (c) For multi-domain milestones: all cross-domain contracts exist in `.gsd-t/contracts/`
154
+ - If ANY check fails: Spawn agent `commands/gsd-t-discuss.md`
155
+ - **Note**: Discuss always pauses for user input, even at Level 3. The discuss agent will interact with the user directly.
156
+ - If all checks pass: Skip to Plan
157
+
158
+ #### 3. PLAN
159
+ Spawn agent `commands/gsd-t-plan.md`
160
+ - After: Read `progress.md`, verify status = PLANNED
161
+
162
+ #### 4. IMPACT
163
+ Spawn agent `commands/gsd-t-impact.md`
164
+ - After: Read `progress.md` and `.gsd-t/impact-report.md`
165
+ - **Decision Gate**:
166
+ - PROCEEDcontinue to Execute
167
+ - PROCEED WITH CAUTION log items, continue
168
+ - BLOCK stop, report to user, wait for decision
169
+
170
+ #### 5. EXECUTE
171
+ Spawn agent`commands/gsd-t-execute.md`
172
+ - This is the heaviest phase. The execute agent uses **task-level dispatch** (fresh-dispatch-contract.md): one Task subagent per task within each domain, each receiving only scope.md + relevant contracts + single task + graph context + up to 5 prior summaries. The execute agent handles domain task-dispatching and QA internally.
173
+ - **Adaptive replanning**: After each domain completes, the execute agent runs a replan check (per `adaptive-replan-contract.md`). If a completed domain's task summaries reveal new constraints (e.g., deprecated API, wrong column name, incompatible library), the execute agent checks remaining domains' `tasks.md` files for invalidated assumptions and revises them on disk before dispatching the next domain. Maximum 2 replan cycles per execute run if exceeded, execution pauses for user input. All replan decisions are logged to the Decision Log in `progress.md`. The wave phase summary includes any replan actions taken.
174
+ - **Team/parallel mode**: If the plan defines parallel domains (same wave), the execute agent dispatches each domain teammate with `isolation: "worktree"` (per worktree-isolation-contract.md). Each domain works in an isolated git worktree. After all domains complete, the execute agent runs the Sequential Merge Protocol: merge domain A → test → merge domain B → test. Per-domain rollback if tests fail. Worktrees are cleaned up after all merges complete.
175
+ - After: Read `progress.md`, verify status = EXECUTED. Phase summary must include replan actions if any occurred:
176
+ ```
177
+ 📋 Phase 5 (EXECUTE): {N}/{N} tasks done | Replan cycles: {N} | Domains revised: {list or "none"}
178
+ ```
179
+
180
+ #### 6. TEST-SYNC
181
+ Spawn agent `commands/gsd-t-test-sync.md`
182
+ - After: Read `progress.md`, verify status = TESTS_SYNCED
183
+
184
+ #### 7. INTEGRATE
185
+ Spawn agent `commands/gsd-t-integrate.md`
186
+ - After: Read `progress.md`, verify status = INTEGRATED
187
+
188
+ #### 8. VERIFY + COMPLETE
189
+ Spawn agent → `commands/gsd-t-verify.md`
190
+ - The verify agent runs all 8 standard quality gates **plus** the goal-backward verification step (Step 5.5 in gsd-t-verify.md), which checks that milestone goals are actually achieved end-to-end and scans for placeholder patterns per `.gsd-t/contracts/goal-backward-contract.md`
191
+ - Goal-backward runs after all structural gates pass — CRITICAL or HIGH findings block verification; MEDIUM findings are warnings only
192
+ - **Verify auto-invokes complete-milestone** (Step 8 of gsd-t-verify.md). The verify agent handles both verification AND milestone completion in a single agent context. Do NOT spawn a separate complete agent.
193
+ - After: Read `progress.md`, check status:
194
+ - COMPLETED milestone done (verify passed and auto-completed)
195
+ - VERIFIED → verify passed but complete-milestone failed spawn a standalone complete agent as fallback
196
+ - VERIFY_FAILED → handle remediation (see Error Recovery) — includes goal-backward failures
197
+ - Phase summary must include the `Goal-Backward:` line from verify-report.md:
198
+ ```
199
+ 📋 Phase 8 (VERIFY+COMPLETE): {N} gates passed | Goal-Backward: {PASS/WARN/FAIL} — {N} requirements checked, {N} findings
200
+ ```
201
+
202
+ #### 9. DOC-RIPPLE (Automated — after verify+complete)
203
+
204
+ After the final phase completes but before wave reports done:
205
+
206
+ 1. Run threshold check — read `git diff --name-only HEAD~1` and evaluate against doc-ripple-contract.md trigger conditions
207
+ 2. If SKIP: log "Doc-ripple: SKIP — {reason}" and proceed
208
+ 3. If FIRE: spawn doc-ripple agent:
209
+
210
+ ⚙ [{model}] gsd-t-doc-ripple → blast radius analysis + parallel updates
211
+
212
+ Task subagent (general-purpose, model: sonnet):
213
+ "Execute the doc-ripple workflow per commands/gsd-t-doc-ripple.md.
214
+ Git diff context: {files changed list}
215
+ Command that triggered: wave
216
+ Produce manifest at .gsd-t/doc-ripple-manifest.md.
217
+ Update all affected documents.
218
+ Report: 'Doc-ripple: {N} checked, {N} updated, {N} skipped'"
219
+
220
+ 4. After doc-ripple returns, verify manifest exists and report summary inline
221
+
222
+ ### Between Each Phase
223
+
224
+ After each agent completes, run this spot-check before proceeding:
225
+
226
+ 1. **Status check**: Read `.gsd-t/progress.md` — verify the phase updated status correctly (no FAILED markers, status matches expected phase completion state)
227
+ 2. **Git check**: Run `git log --oneline -5` — verify commits were made during this phase (if execute/integrate: at least one commit per task completed)
228
+ 3. **Filesystem check**: Verify key output files exist on disk — e.g., for partition: `.gsd-t/domains/*/scope.md` and `.gsd-t/contracts/` files; for execute: newly created source files; for verify: `.gsd-t/verify-report.md`. Do not trust agent-reported completions alone.
229
+ 4. Report to user:
230
+ ```
231
+ {Phase} complete {agent's one-line summary}
232
+ 📋 Spot-check: {N} commits | {N} output files verified | no FAILED markers
233
+ ```
234
+ 5. If spot-check fails: write failure event via Bash, then report the discrepancy, re-spawn the phase agent once to correct it, then re-verify. If still failing: stop and report to user.
235
+ ```bash
236
+ node ~/.claude/scripts/gsd-t-event-writer.js \
237
+ --type phase_transition \
238
+ --command gsd-t-wave \
239
+ --phase {COMPLETED_PHASE} \
240
+ --reasoning "Spot-check failed: {one-line discrepancy summary}" \
241
+ --outcome failure \
242
+ --agent-id "${CLAUDE_SESSION_ID:-unknown}" || true
243
+ ```
244
+ 5a. After spot-check passes, write success event via Bash:
245
+ ```bash
246
+ node ~/.claude/scripts/gsd-t-event-writer.js \
247
+ --type phase_transition \
248
+ --command gsd-t-wave \
249
+ --phase {COMPLETED_PHASE} \
250
+ --reasoning "Phase complete: {one-line spot-check summary}" \
251
+ --outcome success \
252
+ --agent-id "${CLAUDE_SESSION_ID:-unknown}" || true
253
+ ```
254
+ The `|| true` ensures event write failure never blocks wave execution.
255
+ 6. Proceed to next phase
256
+
257
+ ## Step 4: Autonomy Behavior
258
+
259
+ **Level 3 (Full Auto)**: Auto-advance to next phase after each agent completes. Only STOP for:
260
+ - Destructive Action Guard violations (reported by phase agent)
261
+ - Impact analysis BLOCK verdict
262
+ - Unrecoverable errors after 2 fix attempts
263
+ - Discuss phase (always pauses for user input)
264
+
265
+ **Level 1–2**: Pause between phases, show status, ask to continue.
266
+
267
+ ## Step 5: Completion
268
+
269
+ When all phases are done:
270
+ ```
271
+ ═══════════════════════════════════════════════════════════════════════════════
272
+ Milestone "{name}" complete!
273
+ ═══════════════════════════════════════════════════════════════════════════════
274
+
275
+ 📁 Archived to: .gsd-t/milestones/{name}-{date}/
276
+ 🏷️ Tagged as: milestone/{name}
277
+
278
+ Summary:
279
+ - Domains: {list}
280
+ - Tasks completed: {N}
281
+ - Contracts: {N} defined/verified
282
+ - Tests: {N} added/updated
283
+ - Impact items addressed: {N}
284
+ - Decision log entries: {N}
285
+
286
+ Next steps:
287
+ - Push tag: git push origin milestone/{name}
288
+ - Start next: /user:gsd-t-milestone "{next}"
289
+ - View roadmap: /user:gsd-t-status
290
+ ═══════════════════════════════════════════════════════════════════════════════
291
+ ```
292
+
293
+ ## Interruption Handling
294
+
295
+ If the user interrupts or a phase agent fails:
296
+ 1. The current phase agent saves its own state to `.gsd-t/progress.md`
297
+ 2. Report: "Paused at {phase}. Run `/user:gsd-t-resume` to continue."
298
+ 3. Resume will pick up from the last completed phase
299
+
300
+ ## Error Recovery
301
+
302
+ ### If impact analysis blocks:
303
+ - Read the impact report from the agent's output
304
+ - Report blocking issues to user
305
+
306
+ **Level 3**: Spawn a remediation agent to fix blocking issues, then re-spawn impact agent. Max 2 attempts.
307
+ If both attempts fail:
308
+ 1. Write failure context to `.gsd-t/debug-state.jsonl` via `node -e "require('./bin/debug-ledger.js').appendEntry('.', {iteration:1,timestamp:new Date().toISOString(),test:'impact-remediation',error:'2 in-context fix attempts exhausted',hypothesis:'see impact-report.md',fix:'n/a',fixFiles:[],result:'STILL_FAILS',learning:'delegating to headless debug-loop',model:'sonnet',duration:0})"`
309
+ 2. Log: "Delegating to headless debug-loop (2 in-context attempts exhausted)"
310
+ 3. Run: `gsd-t headless --debug-loop --max-iterations 10`
311
+ 4. Exit code 0 continue; 1/4 → log to `.gsd-t/deferred-items.md`, report to user; 3 → report error
312
+ **Level 1–2**: Ask user for direction.
313
+
314
+ ### If tests fail during execute:
315
+ - The execute agent handles test failures internally (up to 2 fix attempts)
316
+ - If still failing after 2 attempts, the execute agent reports failure
317
+ - Orchestrator stops and reports to user
318
+
319
+ ### If verify fails:
320
+ - Read verify report for failure details
321
+
322
+ **Level 3**: Spawn remediation agent, then re-spawn verify agent. Max 2 attempts.
323
+ If both attempts fail:
324
+ 1. Write failure context to `.gsd-t/debug-state.jsonl` via `node -e "require('./bin/debug-ledger.js').appendEntry('.', {iteration:1,timestamp:new Date().toISOString(),test:'verify-remediation',error:'2 in-context fix attempts exhausted',hypothesis:'see verify-report.md',fix:'n/a',fixFiles:[],result:'STILL_FAILS',learning:'delegating to headless debug-loop',model:'sonnet',duration:0})"`
325
+ 2. Log: "Delegating to headless debug-loop (2 in-context attempts exhausted)"
326
+ 3. Run: `gsd-t headless --debug-loop --max-iterations 10`
327
+ 4. Exit code 0 → re-spawn verify agent; 1/4 → log to `.gsd-t/deferred-items.md`, report to user; 3 → report error
328
+ **Level 1–2**: Ask user for direction.
329
+
330
+ ## Why Agent-Per-Phase
331
+
332
+ Each phase agent gets a **fresh context window** (~200K tokens). This means:
333
+ - Phase 7 doesn't carry the context baggage from phases 1-6
334
+ - Mid-phase compaction is eliminated for standard-sized phases
335
+ - Each agent loads only what it needs from state files
336
+ - The orchestrator stays lightweight (~30KB total)
337
+
338
+ State handoff happens through `.gsd-t/` files — exactly what they were designed for.
339
+
340
+ ## Security Considerations
341
+
342
+ ### bypassPermissions Mode
343
+
344
+ Wave spawns each phase agent with `mode: "bypassPermissions"`. This means agents execute bash commands, write files, and perform git operations **without per-action user approval**. This is by design — wave phases would be impractical with manual approval at every step.
345
+
346
+ ### Attack Surface
347
+
348
+ If command files in `~/.claude/commands/` are tampered with, wave agents will execute the modified instructions with full permissions. The attack requires:
349
+ 1. Write access to the user's `~/.claude/commands/` directory
350
+ 2. Knowledge of the GSD-T command file format
351
+ 3. The user to run `/gsd-t-wave` after tampering
352
+
353
+ ### Current Mitigations
354
+
355
+ - **npm-installed files**: Command files are installed from the npm registry, providing a known-good source
356
+ - **Content comparison on update**: `gsd-t update` compares file contents and reports changes
357
+ - **User-owned directory**: `~/.claude/commands/` inherits the user's filesystem permissions
358
+ - **Destructive Action Guard**: CLAUDE.md instructions provide soft protection against destructive operations (DROP TABLE, schema changes, etc.), though agents could theoretically ignore these
359
+ - **Autonomy levels**: Level 1 and Level 2 pause between phases, giving users visibility into agent activity
360
+
361
+ ### Recommendations
362
+
363
+ - For sensitive projects, use **Level 1 or Level 2 autonomy** instead of Level 3 to review each phase's output
364
+ - Periodically verify command file integrity: `gsd-t doctor` checks installation health
365
+ - If security is a concern, audit `~/.claude/commands/gsd-t-*.md` files for unexpected modifications
366
+ - Keep GSD-T updated (`gsd-t update`) to receive the latest command files from npm
367
+
368
+ ## Workflow Visualization
369
+
370
+ ```
371
+ ┌──────────────────────────────────────────────────────────────────────────────┐
372
+ │ Wave Orchestrator (lightweight) │
373
+ │ │
374
+ │ ┌─────────┐ ┌─────────┐ ┌──────┐ ┌────────┐ ┌─────────┐ │
375
+ │ │PARTITION│ → │ DISCUSS │ → │ PLAN │ → │ IMPACT │ → │ EXECUTE │ │
376
+ │ │ agent 1 │ │ agent 2 │ │agent 3│ │agent 4 │ │ agent 5 │ │
377
+ │ └────┬────┘ └────┬────┘ └───┬──┘ └───┬────┘ └────┬────┘ │
378
+ │ ↓ ↓ ↓ ↓ ↓ │
379
+ │ status status status status status │
380
+ │ check check check check + check │
381
+ │ gate │
382
+ │ │
383
+ │ ┌──────────────────┐ ┌───────────┐ ┌─────────────────┐ │
384
+ │ │ VERIFY+COMPLETE │ ← │ INTEGRATE │ ←──── │ FULL TEST-SYNC │ │
385
+ │ │ agent 8 │ │ agent 7 │ │ agent 6 │ │
386
+ │ └────────┬─────────┘ └─────┬─────┘ └────────┬────────┘ │
387
+ │ ↓ ↓ ↓ │
388
+ │ gate check → status status │
389
+ │ auto-complete check check │
390
+ │ archive + tag │
391
+ │ │
392
+ │ Each agent: fresh context window, reads state from files, dies when done │
393
+ │ Orchestrator: 8 agents (was 9), ~30KB total, never compacts │
394
+ └──────────────────────────────────────────────────────────────────────────────┘
395
+ ```
396
+
397
+ $ARGUMENTS
398
+
399
+ ## Auto-Clear
400
+
401
+ The full wave cycle is complete. All work is committed to project files. Execute `/clear` to free the orchestrator context window.