@tekyzinc/gsd-t 3.29.11 → 4.0.12

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 (108) hide show
  1. package/CHANGELOG.md +146 -0
  2. package/bin/gsd-t-parallel.cjs +64 -13
  3. package/bin/gsd-t.js +48 -376
  4. package/bin/journey-coverage.cjs +6 -3
  5. package/bin/parallel-cli.cjs +13 -1
  6. package/commands/gsd-t-debug.md +47 -533
  7. package/commands/gsd-t-design-decompose.md +24 -497
  8. package/commands/gsd-t-doc-ripple.md +23 -139
  9. package/commands/gsd-t-execute.md +41 -958
  10. package/commands/gsd-t-help.md +0 -2
  11. package/commands/gsd-t-impact.md +26 -295
  12. package/commands/gsd-t-integrate.md +44 -369
  13. package/commands/gsd-t-milestone.md +25 -124
  14. package/commands/gsd-t-partition.md +28 -539
  15. package/commands/gsd-t-plan.md +26 -472
  16. package/commands/gsd-t-prd.md +25 -311
  17. package/commands/gsd-t-quick.md +1 -1
  18. package/commands/gsd-t-resume.md +0 -33
  19. package/commands/gsd-t-verify.md +52 -569
  20. package/commands/gsd-t-wave.md +41 -430
  21. package/package.json +1 -1
  22. package/scripts/gsd-t-calibration-hook.js +3 -1
  23. package/scripts/hooks/pre-commit-journey-coverage +0 -2
  24. package/scripts/hooks/pre-commit-playwright-gate +0 -2
  25. package/templates/CLAUDE-global.md +43 -173
  26. package/templates/CLAUDE-project.md +118 -104
  27. package/templates/prompts/design-verify-subagent.md +3 -0
  28. package/templates/prompts/qa-subagent.md +3 -0
  29. package/templates/prompts/red-team-subagent.md +5 -2
  30. package/templates/workflows/_lib.js +176 -0
  31. package/templates/workflows/gsd-t-debug.workflow.js +86 -0
  32. package/templates/workflows/gsd-t-execute.workflow.js +206 -0
  33. package/templates/workflows/gsd-t-integrate.workflow.js +71 -0
  34. package/templates/workflows/gsd-t-phase.workflow.js +94 -0
  35. package/templates/workflows/gsd-t-quick.workflow.js +72 -0
  36. package/templates/workflows/gsd-t-verify.workflow.js +348 -0
  37. package/templates/workflows/gsd-t-wave.workflow.js +43 -0
  38. package/bin/check-headless-sessions.js +0 -140
  39. package/bin/context-budget-audit.cjs +0 -447
  40. package/bin/context-meter-config.cjs +0 -101
  41. package/bin/context-meter-config.test.cjs +0 -101
  42. package/bin/event-stream.cjs +0 -205
  43. package/bin/gsd-t-benchmark-orchestrator.js +0 -437
  44. package/bin/gsd-t-capture-lint.cjs +0 -440
  45. package/bin/gsd-t-economics.cjs +0 -315
  46. package/bin/gsd-t-in-session-usage.cjs +0 -213
  47. package/bin/gsd-t-orchestrator-config.cjs +0 -161
  48. package/bin/gsd-t-orchestrator-queue.cjs +0 -180
  49. package/bin/gsd-t-orchestrator-recover.cjs +0 -231
  50. package/bin/gsd-t-orchestrator-worker.cjs +0 -219
  51. package/bin/gsd-t-orchestrator.js +0 -535
  52. package/bin/gsd-t-parallel-probe.cjs +0 -132
  53. package/bin/gsd-t-ratelimit-probe-worker.cjs +0 -237
  54. package/bin/gsd-t-ratelimit-probe.cjs +0 -648
  55. package/bin/gsd-t-report-tokens.cjs +0 -549
  56. package/bin/gsd-t-stream-feed-client.cjs +0 -151
  57. package/bin/gsd-t-token-backfill.cjs +0 -366
  58. package/bin/gsd-t-token-capture.cjs +0 -321
  59. package/bin/gsd-t-token-dashboard.cjs +0 -353
  60. package/bin/gsd-t-token-regenerate-log.cjs +0 -129
  61. package/bin/gsd-t-tool-attribution.cjs +0 -377
  62. package/bin/gsd-t-tool-cost.cjs +0 -195
  63. package/bin/gsd-t-transcript-tee.cjs +0 -246
  64. package/bin/gsd-t-unattended-heartbeat.cjs +0 -188
  65. package/bin/gsd-t-unattended-platform.cjs +0 -551
  66. package/bin/gsd-t-unattended-platform.js +0 -381
  67. package/bin/gsd-t-unattended-safety.cjs +0 -773
  68. package/bin/gsd-t-unattended-safety.js +0 -788
  69. package/bin/gsd-t-unattended.cjs +0 -2109
  70. package/bin/gsd-t-unattended.js +0 -1367
  71. package/bin/gsd-t-worker-dispatch.cjs +0 -211
  72. package/bin/handoff-lock.cjs +0 -249
  73. package/bin/handoff-lock.js +0 -249
  74. package/bin/headless-auto-spawn.cjs +0 -711
  75. package/bin/headless-auto-spawn.js +0 -373
  76. package/bin/headless-exit-codes.cjs +0 -67
  77. package/bin/live-activity-report.cjs +0 -615
  78. package/bin/log-tail.cjs +0 -81
  79. package/bin/m44-proof-measure.cjs +0 -285
  80. package/bin/m46-iter-proof.cjs +0 -149
  81. package/bin/m46-worker-proof.cjs +0 -201
  82. package/bin/m55-substrate-proof.cjs +0 -134
  83. package/bin/metrics-rollup.js +0 -200
  84. package/bin/model-windows.cjs +0 -99
  85. package/bin/model-windows.test.cjs +0 -75
  86. package/bin/parallelism-report.cjs +0 -535
  87. package/bin/runway-estimator.cjs +0 -242
  88. package/bin/spawn-plan-derive.cjs +0 -163
  89. package/bin/spawn-plan-status-updater.cjs +0 -292
  90. package/bin/spawn-plan-writer.cjs +0 -204
  91. package/bin/supervisor-pid-fingerprint.cjs +0 -126
  92. package/bin/token-budget.cjs +0 -265
  93. package/bin/unattended-watch-format.cjs +0 -178
  94. package/bin/watch-progress.js +0 -155
  95. package/commands/gsd-t-unattended-stop.md +0 -85
  96. package/commands/gsd-t-unattended-watch.md +0 -465
  97. package/commands/gsd-t-unattended.md +0 -476
  98. package/commands/gsd-t-visualize.md +0 -116
  99. package/scripts/gsd-t-context-meter.e2e.test.js +0 -364
  100. package/scripts/gsd-t-context-meter.js +0 -341
  101. package/scripts/gsd-t-context-meter.test.js +0 -471
  102. package/scripts/gsd-t-dashboard-server.js +0 -1203
  103. package/scripts/gsd-t-post-commit-spawn-plan.sh +0 -86
  104. package/scripts/gsd-t-transcript.html +0 -1821
  105. package/scripts/hooks/gsd-t-conversation-capture.js +0 -439
  106. package/scripts/hooks/gsd-t-in-session-usage-hook.js +0 -84
  107. package/scripts/spawn-plan-fmt-tokens.cjs +0 -80
  108. package/templates/hooks/post-commit-spawn-plan.sh +0 -85
@@ -1,558 +1,72 @@
1
1
  # GSD-T: Debug — Systematic Debugging with Contract Awareness
2
2
 
3
- You are debugging an issue in a contract-driven project. Your approach should identify whether the bug is within a domain or at a contract boundary.
3
+ You are the lead agent. Debug a failing test or runtime error by invoking the canonical Workflow script at `templates/workflows/gsd-t-debug.workflow.js`.
4
4
 
5
- ## Argument Parsing
5
+ ## What this command does
6
6
 
7
- Parse `$ARGUMENTS`. The issue description is `$ISSUE`. M43 D4 removed the `--watch` opt-out; `--in-session`/`--headless` were never shipped. Under `.gsd-t/contracts/headless-default-contract.md` **v2.0.0** the inner fix-loop subagent (Step 0.1) and all validation spawns (Deep Research Step 1.5, Red Team Step 5.3, doc-ripple Step 6) go headless unconditionally. A legacy `--watch` token is accepted but ignored (stderr deprecation line).
7
+ Replaces the M40-era debug-orchestrator scaffolding with a deterministic 2-cycle Workflow per CLAUDE.md Prime Rule ("up to 2 fix attempts before delegating"):
8
8
 
9
- ## Spawn Primitive — Always Headless (M43 D4, v2.0.0)
10
-
11
- Per `.gsd-t/contracts/headless-default-contract.md` v2.0.0. Spawn classifications used below (both always headless):
12
-
13
- - `spawnType: 'primary'` — Step 0.1 fresh-dispatch subagent running the debug session
14
- - `spawnType: 'validation'` — Step 1.5 Deep Research teammates, Step 5.3 Red Team, Step 6 doc-ripple
15
-
16
- Spawn path is `autoSpawnHeadless({command, spawnType, projectDir, sessionContext})`. The outer `gsd-t-debug` command body is itself the interactive spawn target when invoked by `/gsd` or `gsd-t-wave`; nested spawns always go headless.
17
-
18
- ## Model Assignment
19
-
20
- Per `.gsd-t/contracts/model-selection-contract.md` v1.0.0.
21
-
22
- - **Default**: `opus` (`selectModel({phase: "debug"})`) — debugging is high-stakes reasoning by default.
23
- - **Root-cause analysis**: `opus` (`selectModel({phase: "debug", task_type: "root_cause"})`).
24
- - **Fix-apply**: `sonnet` (`selectModel({phase: "debug", task_type: "fix_apply"})`) — applying a known fix is routine code work.
25
- - **Escalation**: already at opus for judgment work; `/advisor` fallback applies if a fix crosses a contract boundary or schema. Never silently downgrade the model under context pressure — M35 removed that behavior.
26
-
27
- ## Step 0.1: Launch via Subagent
28
-
29
- ```bash
30
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 0 --step-label ".1: Launch via Subagent" 2>/dev/null || true
31
- ```
32
-
33
- To give this debug session a fresh context window and prevent compaction, always execute via a Task subagent.
34
-
35
- **If you are the orchestrating agent** (you received the slash command directly):
36
-
37
- **Stack Rules Detection (before spawning subagent):**
38
-
39
- Run via Bash to detect project stack and collect matching rules. Local overrides in `.gsd-t/stacks/` take precedence over global templates.
40
-
41
- ```bash
42
- GSD_T_DIR=$(npm root -g 2>/dev/null)/@tekyzinc/gsd-t
43
- STACKS_DIR="$GSD_T_DIR/templates/stacks"
44
- LOCAL_STACKS=".gsd-t/stacks"
45
- STACK_RULES=""
46
- _sf() { local n=$(basename "$1"); [ -f "$LOCAL_STACKS/$n" ] && cat "$LOCAL_STACKS/$n" || cat "$1"; }
47
- _add() { [ -f "$STACKS_DIR/$1" ] && STACK_RULES="${STACK_RULES}$(_sf "$STACKS_DIR/$1")"$'\n\n'; }
48
- if [ -d "$STACKS_DIR" ]; then
49
- for f in "$STACKS_DIR"/_*.md; do [ -f "$f" ] && STACK_RULES="${STACK_RULES}$(_sf "$f")"$'\n\n'; done
50
- if [ -f "package.json" ]; then
51
- grep -q '"react-native"' package.json 2>/dev/null && _add react-native.md
52
- grep -q '"react"' package.json 2>/dev/null && ! grep -q '"react-native"' package.json 2>/dev/null && _add react.md
53
- grep -q '"next"' package.json 2>/dev/null && _add nextjs.md
54
- grep -q '"vue"' package.json 2>/dev/null && _add vue.md
55
- (grep -q '"typescript"' package.json 2>/dev/null || [ -f "tsconfig.json" ]) && _add typescript.md
56
- grep -qE '"(express|fastify|hono|koa)"' package.json 2>/dev/null && _add node-api.md && _add rest-api.md
57
- grep -q '"tailwindcss"' package.json 2>/dev/null && _add tailwind.md
58
- grep -q '"vite"' package.json 2>/dev/null && _add vite.md
59
- grep -q '"@supabase/supabase-js"' package.json 2>/dev/null && _add supabase.md
60
- grep -q '"firebase"' package.json 2>/dev/null && _add firebase.md
61
- grep -qE '"(graphql|@apollo/client|urql)"' package.json 2>/dev/null && _add graphql.md
62
- grep -q '"zustand"' package.json 2>/dev/null && _add zustand.md
63
- grep -q '"@reduxjs/toolkit"' package.json 2>/dev/null && _add redux.md
64
- grep -q '"neo4j-driver"' package.json 2>/dev/null && _add neo4j.md
65
- grep -qE '"(pg|prisma|drizzle-orm|knex)"' package.json 2>/dev/null && _add postgresql.md
66
- grep -qE '"(prisma|@prisma/client)"' package.json 2>/dev/null && _add prisma.md
67
- grep -qE '"(bullmq|bull|amqplib|@aws-sdk/client-sqs|bee-queue|agenda)"' package.json 2>/dev/null && _add queues.md
68
- grep -qE '"(openai|anthropic|@anthropic-ai/sdk|langchain|llama-index|@google/generative-ai)"' package.json 2>/dev/null && _add llm.md
69
- fi
70
- ([ -f "requirements.txt" ] || [ -f "pyproject.toml" ] || [ -f "Pipfile" ]) && _add python.md
71
- ([ -f "requirements.txt" ] && grep -q "psycopg" requirements.txt 2>/dev/null || [ -f "pyproject.toml" ] && grep -q "psycopg" pyproject.toml 2>/dev/null) && _add postgresql.md
72
- ([ -f "requirements.txt" ] && grep -q "neo4j" requirements.txt 2>/dev/null) && _add neo4j.md
73
- ([ -f "requirements.txt" ] && grep -q "fastapi" requirements.txt 2>/dev/null || [ -f "pyproject.toml" ] && grep -q "fastapi" pyproject.toml 2>/dev/null) && _add fastapi.md
74
- ([ -f "requirements.txt" ] && grep -qE "(celery|dramatiq|rq|arq)" requirements.txt 2>/dev/null || [ -f "pyproject.toml" ] && grep -qE "(celery|dramatiq|rq|arq)" pyproject.toml 2>/dev/null) && _add queues.md
75
- ([ -f "requirements.txt" ] && grep -qE "(openai|anthropic|langchain|llama.index)" requirements.txt 2>/dev/null || [ -f "pyproject.toml" ] && grep -qE "(openai|anthropic|langchain|llama.index)" pyproject.toml 2>/dev/null) && _add llm.md
76
- [ -f "pubspec.yaml" ] && _add flutter.md
77
- [ -f "Dockerfile" ] && _add docker.md
78
- [ -d ".github/workflows" ] && _add github-actions.md
79
- ([ -f "playwright.config.ts" ] || [ -f "playwright.config.js" ]) && _add playwright.md
80
- [ -f "go.mod" ] && _add go.md
81
- [ -f "Cargo.toml" ] && _add rust.md
82
- # Design-to-code detection (design contract, design tokens, Figma config, or Figma MCP configured)
83
- ([ -f ".gsd-t/contracts/design-contract.md" ] || [ -f "design-tokens.json" ] || [ -d "design-tokens" ] || [ -f ".figmarc" ] || [ -f "figma.config.json" ] || grep -q '"figma"' ~/.claude/settings.json 2>/dev/null) && _add design-to-code.md
84
- fi
85
- ```
86
-
87
- If STACK_RULES is non-empty, append to the subagent prompt:
88
- ```
89
- ## Stack Rules (MANDATORY — violations fail this task)
90
-
91
- {STACK_RULES}
92
-
93
- These standards have the same enforcement weight as contract compliance.
94
- Violations are task failures, not warnings.
95
- ```
96
-
97
- If STACK_RULES is empty (no templates/stacks/ dir or no matches), skip silently.
98
-
99
- Spawn a fresh subagent via `captureSpawn` — `spawnType: 'primary'` (always headless per headless-default-contract v2.0.0):
100
-
101
- **OBSERVABILITY LOGGING (MANDATORY) — wrap the primary subagent spawn with `captureSpawn`:**
102
-
103
- ```
104
- node -e "
105
- const { captureSpawn } = require('./bin/gsd-t-token-capture.cjs');
106
- (async () => {
107
- await captureSpawn({
108
- command: 'gsd-t-debug',
109
- step: 'Step 0',
110
- model: 'sonnet',
111
- description: 'debug: {issue summary}',
112
- projectDir: '.',
113
- notes: 'debug: {issue summary}',
114
- spawnFn: async () => { /* Task subagent (general-purpose, spawnType: primary, model: sonnet):
115
- 'You are running gsd-t-debug for this issue: {\$ARGUMENTS}
116
- Working directory: {current project root}
117
- Read CLAUDE.md and .gsd-t/progress.md for project context, then execute gsd-t-debug starting at Step 1.' */ },
118
- });
119
- })();
120
- "
121
- ```
122
-
123
- `captureSpawn` parses `result.usage` and writes the row to `.gsd-t/token-log.md` under the canonical header. Tokens column renders as `in=N out=N cr=N cc=N $X.XX` or `—`, never `N/A`.
124
-
125
- Relay the subagent's summary to the user. **Do not execute Steps 1–5 yourself.**
126
-
127
- **If you are the spawned subagent** (your prompt says "starting at Step 1"):
128
- Continue to Step 1 below.
129
-
130
- ## Step 1: Load Context
131
-
132
- ```bash
133
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 1 --step-label "Load Context" 2>/dev/null || true
134
- ```
135
-
136
- Read:
137
- 1. `CLAUDE.md`
138
- 2. `.gsd-t/progress.md`
139
- 3. `.gsd-t/contracts/` — all contracts
140
- 4. `.gsd-t/domains/*/scope.md` — domain boundaries
141
-
142
- <!-- M56-D4: preflight + brief + verify-gate wire-in -->
143
- **M56 Preflight + Context-Brief (mandatory before any debug investigation):**
144
-
145
- ```bash
146
- gsd-t preflight --json > /tmp/gsd-t-preflight.json || exit 4
147
-
148
- SPAWN_ID="debug-${ARG_OR_DEFAULT:-investigation}-$(date -u +%Y%m%dT%H%M%SZ)"
149
- gsd-t brief --kind debug --out ".gsd-t/briefs/${SPAWN_ID}.json" || true
150
- export BRIEF_PATH=".gsd-t/briefs/${SPAWN_ID}.json"
151
- ```
152
-
153
- If preflight exits 4, surface the failed `severity:"error"` checks (wrong branch, occupied required port) to the user and STOP — do NOT proceed with the debug investigation. The brief replaces the 30–60k context re-read with a ≤2,500-token JSON snapshot.
154
-
155
- **Verify-gate at end** (only if debug fix produced code changes):
156
-
157
- ```bash
158
- if git status --porcelain | grep -q .; then
159
- gsd-t verify-gate --json > /tmp/gsd-t-verify-gate.json || exit 4
160
- fi
161
- ```
162
- <!-- /M56-D4: preflight + brief + verify-gate wire-in -->
163
-
164
- ## Step 1.5: Debug Loop Detection (MANDATORY)
165
-
166
- ```bash
167
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 1 --step-label ".5: Debug Loop Detection (MANDATORY)" 2>/dev/null || true
168
- ```
169
-
170
- Before attempting any fix, check whether this issue has been through multiple failed debug sessions. This prevents the 10–20 attempt death spiral that happens when the same approach is retried repeatedly.
171
-
172
- **Detection:**
173
- 1. Scan `.gsd-t/progress.md` Decision Log for `[debug]` entries related to this issue (match by keyword, error name, or component)
174
- 2. Count distinct debug sessions that attempted to fix this issue
175
- 3. Check `.gsd-t/deferred-items.md` for any entries matching this issue
176
-
177
- **If 3 or more prior sessions found → Enter Deep Research Mode (below). Do NOT attempt another fix with the same approach.**
178
-
179
- **If fewer than 3 sessions → Proceed to Step 2 normally.**
180
-
181
- ---
182
-
183
- ### Deep Research Mode (triggered when debug loop detected)
184
-
185
- The current approach has failed 3+ times. This means the root cause is not yet understood. A different strategy — possibly a fundamentally different technical approach — is required.
186
-
187
- **OBSERVABILITY LOGGING (MANDATORY) — wrap the Deep Research team spawn with `captureSpawn`:**
188
-
189
- ```
190
- node -e "
191
- const { captureSpawn } = require('./bin/gsd-t-token-capture.cjs');
192
- (async () => {
193
- await captureSpawn({
194
- command: 'gsd-t-debug',
195
- step: 'Step 1.5',
196
- model: 'sonnet',
197
- description: 'deep research loop break: {issue summary}',
198
- projectDir: '.',
199
- notes: 'deep research loop break: {issue summary}',
200
- spawnFn: async () => { /* Deep research team (three teammates in parallel):
201
- - Teammate 'researcher-root-cause': broadest look at the problem, ignore prior fix attempts, identify true root cause (possibly architectural, not in code being patched).
202
- - Teammate 'researcher-alternatives': enumerate 3–5 fundamentally different solutions with trade-offs, effort, and risk.
203
- - Teammate 'researcher-prior-art': search external sources, docs, GitHub issues for this class of bug and known workarounds.
204
- Lead synthesizes after all three complete: true root cause, ranked solution paths, whether a different technical approach is required, and the recommended path. */ },
205
- });
206
- })();
207
- "
208
- ```
209
-
210
- `captureSpawn` parses `result.usage` and writes the row to `.gsd-t/token-log.md` under the canonical header. Tokens column renders as `in=N out=N cr=N cc=N $X.XX` or `—`, never `N/A`.
211
-
212
- **STOP. Present findings to the user before making any changes:**
213
-
214
- ```
215
- ## Debug Loop Break — Research Findings
216
-
217
- **Issue**: {issue summary}
218
- **Prior sessions**: {count} failed attempts
219
-
220
- **Root Cause (revised)**: {finding from researcher-root-cause}
221
-
222
- **Solution Options**:
223
- | # | Approach | Effort | Risk | Notes |
224
- |---|----------|--------|------|-------|
225
- | 1 | {option} | {effort} | {risk} | {notes} |
226
- | 2 | {option} | {effort} | {risk} | {notes} |
227
- | 3 | {option} | {effort} | {risk} | {notes} |
228
-
229
- **Recommendation**: {recommended option and rationale}
230
-
231
- **Does this require a different technical direction?** {Yes/No — explain}
232
-
233
- Please select an option (or provide your own direction) before I proceed.
234
- ```
235
-
236
- **Wait for explicit user selection/approval.** Do NOT proceed with any fix until the user confirms the chosen approach. If the recommendation requires refactoring or changing technical direction, the Destructive Action Guard applies — present the full migration path and wait for approval.
237
-
238
- ---
239
-
240
- ## Step 1.7: Experience Retrieval
241
-
242
- ```bash
243
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 1 --step-label ".7: Experience Retrieval" 2>/dev/null || true
244
- ```
245
-
246
- Before proceeding to classification and fix, retrieve relevant past failures from the Decision Log.
247
-
248
- Run via Bash:
249
- `grep -i "\[failure\]\|\[learning\]" .gsd-t/progress.md | tail -10`
250
-
251
- If results found:
252
- - Display a `## ⚠️ Relevant Past Failures` block showing matching entries (max 5 lines)
253
- - Pass this block as context to any debug subagent spawned in Step 3
254
- - Write event via Bash: `node ~/.claude/scripts/gsd-t-event-writer.js --type experience_retrieval --command gsd-t-debug --reasoning "{N entries found}" --outcome null || true`
255
-
256
- If no results found: proceed normally to Step 2.
257
-
258
- ---
259
-
260
- ## Step 1.7: Graph-Enhanced Root Cause Tracing (if available)
261
-
262
- ```bash
263
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 1 --step-label ".7: Graph-Enhanced Root Cause Tracing (if available)" 2>/dev/null || true
264
- ```
265
-
266
- If `.gsd-t/graph/meta.json` exists, use the graph to accelerate root cause identification:
267
-
268
- 1. **Call chain from error**: `query('getCallers', { entity: '{error_function}' })` → trace backward from the error location
269
- 2. **Transitive callers**: `query('getTransitiveCallers', { entity: '{name}', depth: 5 })` → find the full path from entry point to error
270
- 3. **Domain ownership**: `query('getDomainOwner', { entity: '{name}' })` → immediately classify as within-domain or boundary bug
271
- 4. **Contract check**: `query('getContractFor', { entity: '{name}' })` → determine if the bug is at a contract boundary
272
- 5. **Related tests**: `query('getTestsFor', { entity: '{name}' })` → find existing tests that should have caught this
273
-
274
- Graph results replace the manual "classify the bug" analysis in Step 2 — the call chain tells you exactly where the bug type is (within-domain vs boundary) based on whether the caller and callee are in the same domain.
275
-
276
- ## Step 2: Classify the Bug
277
-
278
- ```bash
279
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 2 --step-label "Classify the Bug" 2>/dev/null || true
280
- ```
281
-
282
- Based on the user's description ($ARGUMENTS) and graph analysis (if available), determine:
283
-
284
- ### A) Within-Domain Bug
285
- The issue is entirely inside one domain's scope. Symptoms:
286
- - Error occurs in files owned by a single domain
287
- - No cross-domain data flow involved
288
- - Logic error, typo, missing validation within one area
289
-
290
- → Debug within that domain's files. Fix and verify against domain's acceptance criteria.
291
-
292
- ### B) Contract Boundary Bug
293
- The issue occurs where domains interact. Symptoms:
294
- - Data shape mismatch between producer and consumer
295
- - API returns unexpected format
296
- - UI sends wrong payload to backend
297
- - Auth middleware doesn't integrate correctly with routes
298
-
299
- → Check the relevant contract first. Is the contract correct? Does the implementation match?
300
-
301
- ### C) Contract Gap
302
- The contract didn't specify something it should have. Symptoms:
303
- - Edge case not covered in contract
304
- - Error handling not specified
305
- - Race condition at boundary
306
- - Missing contract entirely
307
-
308
- → Update the contract, then fix implementations on both sides.
309
-
310
- ## Step 2.5: Reproduce First (MANDATORY — Category 5)
311
-
312
- ```bash
313
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 2 --step-label ".5: Reproduce First (MANDATORY — Category 5)" 2>/dev/null || true
314
9
  ```
315
-
316
- **A fix attempt without a reproduction script is a guess, not a fix.**
317
-
318
- Before touching any code:
319
-
320
- 1. **Write a reproduction script** that demonstrates the bug. Automate as much as possible:
321
- - Unit/integration bug → write a failing test that proves the bug exists
322
- - UI/audio/GPU/worker bug (not fully automatable) → write the closest possible script: a headless probe, a log-based trigger, a mock that replicates the failure path. Document the manual remainder explicitly.
323
- - If you cannot write any form of reproduction → you do not yet understand the bug. Keep investigating until you can.
324
-
325
- 2. **Run the reproduction** and confirm it fails before attempting any fix.
326
-
327
- 3. **Never close a debug session with "ready for testing."** A session closes only when the reproduction script passes. If manual steps remain, document them explicitly and confirm they passed.
328
-
329
- 4. **Log the reproduction script path** in `.gsd-t/progress.md` Decision Log: what it tests, how to run it, what passing looks like.
330
-
331
- > This rule exists because code review cannot detect silent runtime failures (GPU compute shaders, audio context state, worker message drops). Only execution proves correctness.
332
-
333
- ---
334
-
335
- ## Step 3: Debug (Solo or Team)
336
-
337
- ```bash
338
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 3 --step-label "Debug (Solo or Team)" 2>/dev/null || true
10
+ preflight → brief → Cycle 1 (diagnose → hypothesis → fix → test → report)
11
+ Cycle 2 (only if Cycle 1 didn't resolve; sees Cycle 1's failed hypothesis)
12
+ → exit "needs-human" if both cycles exhausted
339
13
  ```
340
14
 
341
- ### Parallel Dispatch (MANDATORY single instrument)
15
+ ## Step 1: Read the current milestone state
342
16
 
343
- Delegate to `gsd-t parallel --command` do NOT re-implement probe-and-branch logic here (M44 D9 Step 3: "create 1 instrument that accomplishes this instead of implementing it in all the commands").
17
+ Read `.gsd-t/progress.md`. Note any failing tests or runtime errors in the Decision Log.
344
18
 
345
- ```bash
346
- node bin/gsd-t.js parallel --command gsd-t-debug && exit 0 || true
347
- # Exit 0 → multi-domain debug decomposable; N detached children handle fixes.
348
- # Exit 2+ → single-domain or non-decomposable (the common case for debug).
349
- # Fall through to Solo / Team Mode below.
350
- ```
351
-
352
- `runDispatch` owns the D4/D5/D6 gates + disjoint task-id partitioning + `autoSpawnHeadless()` fan-out. Mode auto-detects from `GSD_T_UNATTENDED=1`. No user prompt. Parallel-when-safe + headless-when-possible are both the default.
353
-
354
- Contract: `.gsd-t/contracts/wave-join-contract.md` v1.1.0; `.gsd-t/contracts/headless-default-contract.md` v2.0.0.
355
-
356
- ### Deviation Rules
357
-
358
- When you encounter unexpected situations during the fix:
359
- 1. **Related bug found while tracing** → Fix it immediately (up to 3 attempts). Log to `.gsd-t/deferred-items.md` if it recurs.
360
- 2. **Missing functionality required for the fix** → Add minimum needed. Note in commit message.
361
- 3. **Blocker (missing file, wrong API response)** → Fix blocker and continue. Log if non-trivial.
362
- 4. **Architectural change required to fix correctly** → STOP. Explain what exists, what needs to change, what breaks, and a migration path. Wait for user approval. Never self-approve.
19
+ ## Step 2: Invoke the debug Workflow
363
20
 
364
- **3-attempt limit**: If your fix doesn't work after 3 attempts within this session, treat it as a loop. Do NOT keep trying the same approach. Before entering Deep Research Mode, first try the headless debug-loop:
365
- 1. Write current failure context to `.gsd-t/debug-state.jsonl` via appendEntry
366
- 2. Log: "Delegating to headless debug-loop (3 in-context attempts exhausted)"
367
- 3. Run: `gsd-t headless --debug-loop --max-iterations 10`
368
- 4. Check exit code:
369
- - 0: Tests pass, continue
370
- - 1/4: Log to `.gsd-t/deferred-items.md`, then enter Deep Research Mode
371
- - 3: Report error, stop
372
-
373
- If the debug-loop also fails (exit 1/4), log the attempt to `.gsd-t/progress.md` Decision Log with a `[failure]` prefix, return to Step 1.5 and run Deep Research Mode before any further attempts. Present findings and options to the user before proceeding.
374
-
375
- ### Solo Mode
376
- 1. Reproduce the issue — **reproduction script must exist before step 2** (see Step 2.5)
377
- 2. Trace through the relevant domain(s)
378
- 3. Check contract compliance at each boundary
379
- 4. Identify root cause
380
- 5. **Destructive Action Guard**: If the fix requires destructive or structural changes (dropping tables, removing columns, changing schema, replacing architecture patterns, removing working modules) → STOP and present the change to the user with what exists, what will change, what will break, and a safe migration path. Wait for explicit approval.
381
- 6. Fix and test — **adapt the fix to existing structures**, not the other way around
382
- 7. Update contracts if needed
383
- 8. **Category 6 — Bug Isolation Check**: After applying the fix, run the FULL test suite and all smoke tests — not just the reproduction script. Do not assume the bug was isolated. A fix that resolves one failure frequently uncovers adjacent failures. Every test must pass before the session closes.
384
-
385
- ### Team Mode (for complex cross-domain bugs)
386
- ```
387
- Create an agent team to debug:
388
- - Teammate 1: Investigate in {domain-1} — check implementation
389
- against contracts, trace data flow
390
- - Teammate 2: Investigate in {domain-2} — check implementation
391
- against contracts, trace data flow
392
- - Teammate 3: Check all contracts for gaps or ambiguities
393
- related to the failing scenario
21
+ Call the `Workflow` tool with:
394
22
 
395
- First to find root cause: message the lead with findings.
23
+ ```js
24
+ {
25
+ scriptPath: "templates/workflows/gsd-t-debug.workflow.js",
26
+ args: {
27
+ symptom: "describe the failing test or runtime error in one sentence",
28
+ projectDir: "."
29
+ }
30
+ }
396
31
  ```
397
32
 
398
- ## Step 4: Document Ripple
399
-
400
- ```bash
401
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 4 --step-label "Document Ripple" 2>/dev/null || true
402
- ```
403
-
404
- After fixing, assess what documentation was affected by the change and update ALL relevant files:
405
-
406
- ### Always check:
407
- 1. **`.gsd-t/progress.md`** — Add to Decision Log: what broke, why, and the fix. Prefix the entry with an outcome tag:
408
- - Debug session start → prefix `[debug]`
409
- - Fix succeeded → prefix `[success]`
410
- - Fix failed → prefix `[failure]`
411
- - Issue deferred → prefix `[deferred]`
412
- 2. **`.gsd-t/contracts/`** — Update any contract if the fix changed an interface, schema, or API shape
413
- 3. **Domain `constraints.md`** — Add a "must not" rule if the bug was caused by a pattern that should be avoided
414
-
415
- ### Check if affected:
416
- 4. **`docs/requirements.md`** — Did the fix reveal a missing or incorrect requirement? Update it
417
- 5. **`docs/architecture.md`** — Did the fix change architectural patterns, data flow, or component relationships? Update it
418
- 6. **`docs/schema.md`** — Did the fix modify the database schema? Update it
419
- 7. **`.gsd-t/techdebt.md`** — Did the fix reveal related debt? Add a new TD item. Did it resolve an existing one? Mark it complete
420
- 8. **Domain `scope.md`** — Did the fix add new files or change ownership? Update it
421
- 9. **Domain `tasks.md`** — If the bug was in an active milestone, update task status or add a remediation task
422
- 10. **`CLAUDE.md`** — Did the fix establish a new convention or pattern that future work should follow? Add it
423
-
424
- ### Scan Doc Micro-Update (if `.gsd-t/scan/` exists):
425
- Patch structural metadata in scan docs so they stay fresh between full scans. Near-zero cost — no LLM re-analysis.
426
-
427
- For each scan doc that exists, apply only the relevant patches:
428
- - **`.gsd-t/scan/architecture.md`** — Update file/directory counts if the fix added/removed files
429
- - **`.gsd-t/scan/quality.md`** — Mark resolved TODOs/FIXMEs, update test counts if tests were added
430
- - **`.gsd-t/scan/security.md`** — If the bug was a security issue, mark the finding `[RESOLVED]`
431
- - **`.gsd-t/scan/business-rules.md`** — If the fix changed validation/auth/workflow logic, update the rule
432
- - **`.gsd-t/scan/contract-drift.md`** — If contracts were updated as part of the fix, mark resolved drift items
433
-
434
- Skip scan docs not affected by this fix. Skip analytical sections — those require a full scan.
435
-
436
- ### Skip what's not affected — don't update docs for the sake of updating them.
437
-
438
- ## Step 5: Test Verification (run tests confirming fix)
439
-
440
- ```bash
441
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 5 --step-label "Test Verification (run tests confirming fix)" 2>/dev/null || true
442
- ```
443
-
444
- Before committing, ensure the fix is solid:
445
-
446
- 1. **Update tests**: If the bug reveals a missing test case, add one that would have caught it
447
- 2. **Run ALL configured test suites** — this is NOT optional:
448
- a. Detect all runners: check for vitest/jest config, playwright.config.*, cypress.config.*
449
- b. Run EVERY detected suite. Unit tests alone are NEVER sufficient when E2E exists.
450
- c. If `playwright.config.*` exists → run `npx playwright test` (full suite)
451
- d. Report ALL results: "Unit: X/Y pass | E2E: X/Y pass"
452
- 3. **Verify passing**: All tests must pass. If any fail, fix before proceeding (up to 2 attempts)
453
- 4. **If the project has a UI but no E2E specs cover the fixed area**: WRITE THEM.
454
- 5. **Functional test quality**: Every E2E assertion must verify an action produced the correct outcome (state changed, data loaded, content updated) — not just that elements exist. Tests that only check `isVisible`/`toBeEnabled` are shallow layout tests and don't catch real bugs. If a test would pass on an empty HTML page with the right IDs, rewrite it.
455
- 6. **Regression check**: Confirm the fix doesn't break any adjacent functionality
456
-
457
- ### Exploratory Testing (if Playwright MCP available)
458
-
459
- After all scripted tests pass:
460
- 1. Check if Playwright MCP is registered in Claude Code settings (look for "playwright" in mcpServers)
461
- 2. If available: spend 3 minutes on interactive exploration using Playwright MCP
462
- - Specifically probe the area around the bug fix — related flows, boundary conditions
463
- - Try variations that might expose similar bugs nearby
464
- - Test the fix path under edge input conditions
465
- 3. Tag all findings [EXPLORATORY] in reports and append to .gsd-t/qa-issues.md
466
- 4. If Playwright MCP is not available: skip this section silently
467
- Note: Exploratory findings do NOT count against the scripted test pass/fail ratio.
468
-
469
- Commit: `[debug] Fix {description} — root cause: {explanation}`
470
-
471
- ## Step 5.3: Red Team — Adversarial QA (MANDATORY)
472
-
473
- ```bash
474
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 5 --step-label ".3: Red Team — Adversarial QA (MANDATORY)" 2>/dev/null || true
475
- ```
476
-
477
- After the fix passes all tests, spawn an adversarial Red Team agent to BREAK the fix and find regressions.
478
-
479
- ⚙ [opus] Red Team → adversarial validation of debug fix
480
-
481
- Resolve the templated prompt path via Bash:
482
- ```
483
- RT_PROMPT="$(npm root -g 2>/dev/null)/@tekyzinc/gsd-t/templates/prompts/red-team-subagent.md"
484
- [ -f "$RT_PROMPT" ] || RT_PROMPT="templates/prompts/red-team-subagent.md"
485
- ```
486
-
487
- **OBSERVABILITY LOGGING (MANDATORY) — wrap the Red Team subagent spawn with `captureSpawn`:**
488
-
489
- ```
490
- node -e "
491
- const { captureSpawn } = require('./bin/gsd-t-token-capture.cjs');
492
- (async () => {
493
- await captureSpawn({
494
- command: 'gsd-t-debug',
495
- step: 'Red Team',
496
- model: 'opus',
497
- description: 'adversarial validation of debug fix',
498
- projectDir: '.',
499
- notes: '{VERDICT} — {N} bugs found',
500
- spawnFn: async () => { /* Task subagent (spawnType: validation, general-purpose, model: opus) — always headless per headless-default-contract v2.0.0:
501
- 'Read \$RT_PROMPT and follow it. Context: post-fix validation for a debug session.
502
- Additional categories for this run:
503
- (a) Regression Around the Fix — test every code path adjacent to the changed lines; fixes frequently break neighboring functionality.
504
- (b) Original Bug Variants — the original bug was {one-line description}; search for SIMILAR bugs in related code (same pattern, different location).
505
- Write findings to .gsd-t/red-team-report.md.' */ },
506
- });
507
- })();
508
- "
509
- ```
510
-
511
- `captureSpawn` parses `result.usage` and writes the row to `.gsd-t/token-log.md` under the canonical header. Tokens column renders as `in=N out=N cr=N cc=N $X.XX` or `—`, never `N/A`.
512
-
513
- **If FAIL:** fix CRITICAL/HIGH bugs (≤2 cycles) → re-run. Persistent bugs → `.gsd-t/deferred-items.md`.
514
- **If GRUDGING PASS:** proceed to metrics and doc-ripple.
515
-
516
- ## Step 5.5: Emit Task Metrics
517
-
518
- ```bash
519
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 5 --step-label ".5: Emit Task Metrics" 2>/dev/null || true
520
- ```
521
-
522
- After committing, emit a task-metrics record for this debug session — run via Bash:
523
- `node bin/metrics-collector.js --milestone {current-milestone-or-none} --domain {domain-or-debug} --task debug-{timestamp} --command debug --duration_s {elapsed} --tokens_used {estimated} --context_pct ${CTX_PCT:-0} --pass {true|false} --fix_cycles {attempts} --signal_type debug-invoked --notes "[debug] {description}" 2>/dev/null || true`
524
-
525
- Signal type is always `debug-invoked` for debug sessions.
526
-
527
- Emit task_complete event — run via Bash:
528
- `node ~/.claude/scripts/gsd-t-event-writer.js --type task_complete --command gsd-t-debug --reasoning "signal_type=debug-invoked, domain={domain}" --outcome {success|failure} || true`
33
+ The Workflow runs up to 2 cycles. Cycle 2 receives Cycle 1's failed hypothesis to prevent re-trying the same approach.
529
34
 
530
- ## Step 6: Doc-Ripple (Automated)
35
+ ## Step 3: Interpret the result
531
36
 
532
- ```bash
533
- node scripts/gsd-t-watch-state.js advance --agent-id "$GSD_T_AGENT_ID" --parent-id "${GSD_T_PARENT_AGENT_ID:-null}" --command gsd-t-debug --step 6 --step-label "Doc-Ripple (Automated)" 2>/dev/null || true
37
+ ```js
38
+ {
39
+ status: "complete" | "needs-human",
40
+ cyclesUsed: 1 | 2,
41
+ finalResult: {
42
+ resolved: boolean,
43
+ rootCause: string,
44
+ filesEdited: [...],
45
+ testRunResult: { pass, fail },
46
+ nextStepsIfNotResolved: string
47
+ }
48
+ }
534
49
  ```
535
50
 
536
- After all work is committed but before reporting completion:
51
+ - `complete` re-run verify (`/gsd-t-verify`); auto-advance.
52
+ - `needs-human` → present root-cause hypothesis + nextStepsIfNotResolved to the user. Do NOT spawn a third cycle; that's the Prime Rule.
537
53
 
538
- 1. Run threshold check — read `git diff --name-only HEAD~1` and evaluate against doc-ripple-contract.md trigger conditions
539
- 2. If SKIP: log "Doc-ripple: SKIP — {reason}" and proceed to completion
540
- 3. If FIRE: spawn doc-ripple agent — `spawnType: 'validation'` (always headless per headless-default-contract v2.0.0):
54
+ ## Contract-Boundary Debugging
541
55
 
542
- [{model}] gsd-t-doc-ripple blast radius analysis + parallel updates
56
+ If the bug is at a domain contract boundary (one domain calls another via API/schema/component contract), the debug cycle agent is instructed to:
57
+ 1. Read both domains' constraints.md
58
+ 2. Read the contract definition
59
+ 3. Verify both sides honor the contract
60
+ 4. Identify which side drifted
543
61
 
544
- Task subagent (spawnType: validation, general-purpose, model: sonnet):
545
- "Execute the doc-ripple workflow per commands/gsd-t-doc-ripple.md.
546
- Git diff context: {files changed list}
547
- Command that triggered: debug
548
- Produce manifest at .gsd-t/doc-ripple-manifest.md.
549
- Update all affected documents.
550
- Report: 'Doc-ripple: {N} checked, {N} updated, {N} skipped'"
62
+ This is a Workflow-stage instruction, not a separate command — same `gsd-t-debug.workflow.js` handles both intra-domain bugs and contract-boundary bugs.
551
63
 
552
- 4. After doc-ripple returns, verify manifest exists and report summary inline
64
+ ## Document Ripple
553
65
 
554
- $ARGUMENTS
66
+ - `.gsd-t/progress.md` — Decision Log entry per cycle with hypothesis + resolution
67
+ - `.gsd-t/qa-issues.md` — append if bug came from QA findings
68
+ - `.gsd-t/red-team-report.md` — mark as resolved if bug came from Red Team
555
69
 
556
- ## Auto-Clear
70
+ ## Next Up
557
71
 
558
- All work is committed to project files. Execute `/clear` to free the context window for the next command.
72
+ `/gsd-t-verify` on resolution, OR human review on `needs-human`.