@tekyzinc/gsd-t 3.29.11 → 4.0.14

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 (114) hide show
  1. package/CHANGELOG.md +171 -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-complete-milestone.md +6 -12
  7. package/commands/gsd-t-debug.md +47 -533
  8. package/commands/gsd-t-design-decompose.md +24 -497
  9. package/commands/gsd-t-doc-ripple.md +23 -139
  10. package/commands/gsd-t-execute.md +41 -958
  11. package/commands/gsd-t-feature.md +2 -6
  12. package/commands/gsd-t-gap-analysis.md +3 -6
  13. package/commands/gsd-t-help.md +2 -4
  14. package/commands/gsd-t-impact.md +26 -295
  15. package/commands/gsd-t-init-scan-setup.md +7 -7
  16. package/commands/gsd-t-integrate.md +44 -369
  17. package/commands/gsd-t-milestone.md +25 -124
  18. package/commands/gsd-t-partition.md +28 -539
  19. package/commands/gsd-t-plan.md +26 -472
  20. package/commands/gsd-t-prd.md +25 -311
  21. package/commands/gsd-t-quick.md +1 -1
  22. package/commands/gsd-t-resume.md +0 -33
  23. package/commands/gsd-t-scan.md +45 -652
  24. package/commands/gsd-t-verify.md +52 -569
  25. package/commands/gsd-t-wave.md +41 -430
  26. package/package.json +1 -1
  27. package/scripts/gsd-t-calibration-hook.js +3 -1
  28. package/scripts/hooks/pre-commit-journey-coverage +0 -2
  29. package/scripts/hooks/pre-commit-playwright-gate +0 -2
  30. package/templates/CLAUDE-global.md +44 -173
  31. package/templates/CLAUDE-project.md +118 -104
  32. package/templates/prompts/design-verify-subagent.md +3 -0
  33. package/templates/prompts/qa-subagent.md +3 -0
  34. package/templates/prompts/red-team-subagent.md +5 -2
  35. package/templates/workflows/_lib.js +176 -0
  36. package/templates/workflows/gsd-t-debug.workflow.js +86 -0
  37. package/templates/workflows/gsd-t-execute.workflow.js +206 -0
  38. package/templates/workflows/gsd-t-integrate.workflow.js +71 -0
  39. package/templates/workflows/gsd-t-phase.workflow.js +94 -0
  40. package/templates/workflows/gsd-t-quick.workflow.js +72 -0
  41. package/templates/workflows/gsd-t-scan.workflow.js +711 -0
  42. package/templates/workflows/gsd-t-verify.workflow.js +348 -0
  43. package/templates/workflows/gsd-t-wave.workflow.js +43 -0
  44. package/bin/check-headless-sessions.js +0 -140
  45. package/bin/context-budget-audit.cjs +0 -447
  46. package/bin/context-meter-config.cjs +0 -101
  47. package/bin/context-meter-config.test.cjs +0 -101
  48. package/bin/event-stream.cjs +0 -205
  49. package/bin/gsd-t-benchmark-orchestrator.js +0 -437
  50. package/bin/gsd-t-capture-lint.cjs +0 -440
  51. package/bin/gsd-t-economics.cjs +0 -315
  52. package/bin/gsd-t-in-session-usage.cjs +0 -213
  53. package/bin/gsd-t-orchestrator-config.cjs +0 -161
  54. package/bin/gsd-t-orchestrator-queue.cjs +0 -180
  55. package/bin/gsd-t-orchestrator-recover.cjs +0 -231
  56. package/bin/gsd-t-orchestrator-worker.cjs +0 -219
  57. package/bin/gsd-t-orchestrator.js +0 -535
  58. package/bin/gsd-t-parallel-probe.cjs +0 -132
  59. package/bin/gsd-t-ratelimit-probe-worker.cjs +0 -237
  60. package/bin/gsd-t-ratelimit-probe.cjs +0 -648
  61. package/bin/gsd-t-report-tokens.cjs +0 -549
  62. package/bin/gsd-t-stream-feed-client.cjs +0 -151
  63. package/bin/gsd-t-token-backfill.cjs +0 -366
  64. package/bin/gsd-t-token-capture.cjs +0 -321
  65. package/bin/gsd-t-token-dashboard.cjs +0 -353
  66. package/bin/gsd-t-token-regenerate-log.cjs +0 -129
  67. package/bin/gsd-t-tool-attribution.cjs +0 -377
  68. package/bin/gsd-t-tool-cost.cjs +0 -195
  69. package/bin/gsd-t-transcript-tee.cjs +0 -246
  70. package/bin/gsd-t-unattended-heartbeat.cjs +0 -188
  71. package/bin/gsd-t-unattended-platform.cjs +0 -551
  72. package/bin/gsd-t-unattended-platform.js +0 -381
  73. package/bin/gsd-t-unattended-safety.cjs +0 -773
  74. package/bin/gsd-t-unattended-safety.js +0 -788
  75. package/bin/gsd-t-unattended.cjs +0 -2109
  76. package/bin/gsd-t-unattended.js +0 -1367
  77. package/bin/gsd-t-worker-dispatch.cjs +0 -211
  78. package/bin/handoff-lock.cjs +0 -249
  79. package/bin/handoff-lock.js +0 -249
  80. package/bin/headless-auto-spawn.cjs +0 -711
  81. package/bin/headless-auto-spawn.js +0 -373
  82. package/bin/headless-exit-codes.cjs +0 -67
  83. package/bin/live-activity-report.cjs +0 -615
  84. package/bin/log-tail.cjs +0 -81
  85. package/bin/m44-proof-measure.cjs +0 -285
  86. package/bin/m46-iter-proof.cjs +0 -149
  87. package/bin/m46-worker-proof.cjs +0 -201
  88. package/bin/m55-substrate-proof.cjs +0 -134
  89. package/bin/metrics-rollup.js +0 -200
  90. package/bin/model-windows.cjs +0 -99
  91. package/bin/model-windows.test.cjs +0 -75
  92. package/bin/parallelism-report.cjs +0 -535
  93. package/bin/runway-estimator.cjs +0 -242
  94. package/bin/spawn-plan-derive.cjs +0 -163
  95. package/bin/spawn-plan-status-updater.cjs +0 -292
  96. package/bin/spawn-plan-writer.cjs +0 -204
  97. package/bin/supervisor-pid-fingerprint.cjs +0 -126
  98. package/bin/token-budget.cjs +0 -265
  99. package/bin/unattended-watch-format.cjs +0 -178
  100. package/bin/watch-progress.js +0 -155
  101. package/commands/gsd-t-unattended-stop.md +0 -85
  102. package/commands/gsd-t-unattended-watch.md +0 -465
  103. package/commands/gsd-t-unattended.md +0 -476
  104. package/commands/gsd-t-visualize.md +0 -116
  105. package/scripts/gsd-t-context-meter.e2e.test.js +0 -364
  106. package/scripts/gsd-t-context-meter.js +0 -341
  107. package/scripts/gsd-t-context-meter.test.js +0 -471
  108. package/scripts/gsd-t-dashboard-server.js +0 -1203
  109. package/scripts/gsd-t-post-commit-spawn-plan.sh +0 -86
  110. package/scripts/gsd-t-transcript.html +0 -1821
  111. package/scripts/hooks/gsd-t-conversation-capture.js +0 -439
  112. package/scripts/hooks/gsd-t-in-session-usage-hook.js +0 -84
  113. package/scripts/spawn-plan-fmt-tokens.cjs +0 -80
  114. package/templates/hooks/post-commit-spawn-plan.sh +0 -85
@@ -1,685 +1,78 @@
1
1
  # GSD-T: Scan — Deep Codebase Analysis and Tech Debt Discovery
2
2
 
3
- You are the lead agent performing a comprehensive analysis of an existing codebase. Your job is to understand the architecture, identify business rules, surface vulnerabilities, find inefficiencies, and produce an actionable tech debt register.
3
+ You are the lead agent. Run a deep codebase scan by invoking the canonical Workflow script at `templates/workflows/gsd-t-scan.workflow.js`.
4
4
 
5
- ## Argument Parsing
5
+ ## What this command does
6
6
 
7
- Parse `$ARGUMENTS`. M43 D4 removed the `--watch` opt-out; `--in-session`/`--headless` were never shipped. Under `.gsd-t/contracts/headless-default-contract.md` **v2.0.0** every scan spawn goes headless unconditionally (Step 0 outer subagent, Step 2 dimension agents, Step 3 synthesis agent, Step 5 living-document updater, Step 8 HTML report generator). A legacy `--watch` token is accepted but ignored (stderr deprecation line).
7
+ Replaces the legacy 5-teammate prose scan with a single deterministic, **volume-scaled** Workflow:
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 outer fresh-dispatch subagent, Step 2 dimension agents, Step 3 synthesis agent
14
- - `spawnType: 'validation'` — Step 5 living-document updater, Step 8 HTML report generator
15
-
16
- Spawn path is `autoSpawnHeadless({command, spawnType, projectDir, sessionContext})`.
17
-
18
- ## Step 0: Launch via Subagent
19
-
20
- ```bash
21
- 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-scan --step 0 --step-label "Launch via Subagent" 2>/dev/null || true
22
- ```
23
-
24
- Scans are long-running and context-heavy. Always execute via a Task subagent for a fresh context window.
25
-
26
- **If you are the orchestrating agent** (you received the slash command directly):
27
- Spawn a fresh subagent using the Task tool — `spawnType: 'primary'` (always headless per headless-default-contract v2.0.0):
28
- ```
29
- subagent_type: general-purpose
30
- spawnType: primary
31
- prompt: "You are running gsd-t-scan. Working directory: {current project root}
32
- Read CLAUDE.md and .gsd-t/progress.md for project context, then execute gsd-t-scan starting at Step 1.
33
- IMPORTANT: Step 2 requires team mode — spawn 5 teammates (architecture, business-rules, security, quality, contracts)
34
- running in parallel. Do not skip team mode or run dimensions sequentially."
35
- ```
36
- Wait for the subagent to complete. Relay its summary to the user. **Do not execute Steps 1+ yourself.**
37
-
38
- **If you are the spawned subagent** (your prompt says "starting at Step 1"):
39
- Continue to Step 1 below. At Step 2, use team mode — spawn the 5 teammates in parallel.
40
-
41
- ## Step 1: Load Existing Context
42
-
43
- ```bash
44
- 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-scan --step 1 --step-label "Load Existing Context" 2>/dev/null || true
45
- ```
46
-
47
- Read:
48
- 1. `CLAUDE.md` (if exists)
49
- 2. `.gsd-t/progress.md` (if exists)
50
- 3. `.gsd-t/contracts/` (if exists) — compare contracts to reality
51
- 4. `.gsd-t/techdebt.md` (if exists) — archive before replacing (see Step 2.9)
52
- 5. `docs/` — any existing documentation
53
-
54
- ## Step 1.5: Graph Index (if available)
55
-
56
- ```bash
57
- 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-scan --step 1 --step-label ".5: Graph Index (if available)" 2>/dev/null || true
58
- ```
59
-
60
- Before scanning, check if `bin/graph-indexer.js` exists in the GSD-T installation or if `.gsd-t/graph/meta.json` exists in the project. If so:
61
-
62
- ```bash
63
- # Run or refresh the graph index
64
- node -e "const g = require('{gsd-t-path}/bin/graph-indexer'); console.log(JSON.stringify(g.indexProject('{project-root}')))"
65
- ```
66
-
67
- If the graph is available, the scan teammates can use these queries for deeper analysis:
68
- - `query('findDeadCode', {})` → unused functions the quality team should flag
69
- - `query('findDuplicates', { threshold: 0.8 })` → semantic duplication (name-based or AST via CGC)
70
- - `query('findCircularDeps', {})` → circular import cycles
71
- - `query('getDomainBoundaryViolations', {})` → cross-domain access violations
72
- - `query('getEntitiesByDomain', { domain })` → entities per domain for architecture analysis
73
-
74
- Pass the graph query results to each teammate in their prompt context so they can reference concrete entity data instead of relying solely on grep patterns.
75
-
76
- ## Step 2: Full Codebase Scan
77
-
78
- ```bash
79
- 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-scan --step 2 --step-label "Full Codebase Scan" 2>/dev/null || true
80
- ```
81
-
82
- **Always use Team Mode** unless the codebase is trivially small (< 5 files) or agent teams are explicitly disabled. Each dimension is fully independent — parallel scanning is faster and produces better results.
83
-
84
- ```
85
- Create an agent team to scan this codebase:
86
-
87
- ALL TEAMMATES read first:
88
- - CLAUDE.md (if exists)
89
- - .gsd-t/contracts/ (if exists)
90
- - .gsd-t/graph/index.json (if exists) — entity registry for graph-enhanced analysis
91
-
92
- - Teammate "architecture" (model: haiku): Analyze project structure, tech stack,
93
- data flow, patterns. If graph available, use entity counts per file and import
94
- edges to map component relationships. Write findings to .gsd-t/scan/architecture.md
95
- - Teammate "business-rules" (model: haiku): Extract all embedded business logic,
96
- validation, auth rules, workflows. Write to .gsd-t/scan/business-rules.md
97
- - Teammate "security" (model: sonnet): Full security audit — auth, injection, exposure,
98
- dependencies. Write to .gsd-t/scan/security.md
99
- - Teammate "quality" (model: sonnet): Dead code, duplication, complexity, test gaps,
100
- performance, stale deps. If graph available, use findDeadCode and findDuplicates
101
- results for precise dead code and duplication detection instead of grep heuristics.
102
- Also: identify reusability candidates — functions or modules that appear in multiple
103
- places doing similar work, and consumer surfaces (web/mobile/CLI/etc.) that call the
104
- same backend operations independently. Write to .gsd-t/scan/quality.md
105
- - Teammate "contracts" (model: haiku): Compare .gsd-t/contracts/ to actual implementation,
106
- find drift and undocumented interfaces. If graph available, use contract mappings
107
- to verify every contract has implementing code. Write to .gsd-t/scan/contract-drift.md
108
- (skip if no contracts exist)
109
-
110
- Each teammate: write your findings to your assigned file.
111
- Lead: synthesize all findings into .gsd-t/techdebt.md when complete.
112
- ```
113
-
114
- ### Solo Mode (fallback — only if < 5 files or teams disabled)
115
- Work through each dimension sequentially:
116
-
117
- Systematically analyze the entire codebase across these dimensions:
118
-
119
- ### A) Architecture Analysis
120
- Scan and document:
121
- - **Project structure**: Directory organization, module boundaries
122
- - **Tech stack**: Languages, frameworks, versions (check package.json, requirements.txt, go.mod, etc.)
123
- - **Architecture pattern**: Monolith, microservices, serverless, hybrid
124
- - **Data flow**: How data moves through the system (request → handler → service → data layer → response)
125
- - **State management**: Where state lives (DB, cache, session, client)
126
- - **Configuration**: How env vars, secrets, and config are managed
127
-
128
- Produce: `.gsd-t/scan/architecture.md`
129
-
130
- ```markdown
131
- # Architecture Analysis — {date}
132
-
133
- ## Stack
134
- - Language: {lang} {version}
135
- - Framework: {framework} {version}
136
- - Database: {db} {version}
137
- - Cache: {if any}
138
- - Deployment: {platform/method}
139
-
140
- ## Structure
141
- {directory tree with annotations}
142
-
143
- ## Data Flow
144
- {description of primary request/response paths}
145
-
146
- ## Patterns Observed
147
- - {pattern}: used in {where}, {assessment}
148
- - {pattern}: used in {where}, {assessment}
149
-
150
- ## Architecture Concerns
151
- - {concern with explanation}
152
- ```
153
-
154
- ### B) Business Rules Extraction
155
- Find and document embedded business logic:
156
- - **Validation rules**: Input constraints, field requirements
157
- - **Authorization rules**: Who can do what, role-based access
158
- - **Workflow rules**: State machines, approval flows, conditional logic
159
- - **Calculation rules**: Pricing, scoring, rate limiting, quotas
160
- - **Integration rules**: Retry policies, fallback behavior, timeout handling
161
-
162
- Produce: `.gsd-t/scan/business-rules.md`
163
-
164
- ```markdown
165
- # Business Rules — {date}
166
-
167
- ## Authentication & Authorization
168
- - {rule}: {where implemented} — {assessment}
169
-
170
- ## Data Validation
171
- - {rule}: {where implemented} — {assessment}
172
-
173
- ## Business Logic
174
- - {rule}: {where implemented} — {assessment}
175
-
176
- ## Undocumented Rules (logic with no comments or docs)
177
- - {file}:{line} — {what it does} — {risk if changed unknowingly}
178
- ```
179
-
180
- ### C) Security Audit
181
- Check for:
182
- - **Auth vulnerabilities**: Token handling, session management, password storage
183
- - **Input validation**: SQL injection, XSS, path traversal, command injection
184
- - **Data exposure**: Sensitive data in logs, API responses, error messages
185
- - **Dependency vulnerabilities**: Run `npm audit`, `pip audit`, or equivalent
186
- - **Secret management**: Hardcoded credentials, exposed API keys, .env in repo
187
- - **CORS/CSP**: Cross-origin policies, content security headers
188
- - **Rate limiting**: API abuse protection
189
- - **File upload**: Unrestricted types, size limits, storage location
190
-
191
- Produce: `.gsd-t/scan/security.md`
192
-
193
- ```markdown
194
- # Security Audit — {date}
195
-
196
- ## Critical (fix immediately)
197
- - [{severity}] {finding} — {file}:{line} — {remediation}
198
-
199
- ## High (fix soon)
200
- - [{severity}] {finding} — {file}:{line} — {remediation}
201
-
202
- ## Medium (plan to fix)
203
- - [{severity}] {finding} — {file}:{line} — {remediation}
204
-
205
- ## Low (nice to have)
206
- - [{severity}] {finding} — {file}:{line} — {remediation}
207
-
208
- ## Dependency Audit
209
- {output of npm audit / pip audit / etc.}
210
- ```
211
-
212
- ### D) Code Quality & Inefficiency Analysis
213
- Check for:
214
- - **Dead code**: Unused functions, unreachable branches, commented-out blocks
215
- - **Duplication**: Copy-pasted logic that should be abstracted
216
- - **Reusability / Shared Service Candidates**: Functions implementing the same operation in multiple modules; consumer surfaces (web, mobile, CLI) calling the same backend logic through separate implementations instead of a shared layer
217
- - **Complexity**: Functions with high cyclomatic complexity, deep nesting
218
- - **Error handling**: Missing try/catch, swallowed errors, inconsistent patterns
219
- - **Performance**: N+1 queries, missing indexes, unnecessary re-renders, large bundles
220
- - **Naming**: Inconsistent conventions, misleading names
221
- - **TODOs/FIXMEs**: Grep for unresolved developer notes
222
- - **Test gaps**: Critical paths without test coverage
223
- - **Stale dependencies**: Outdated packages with available updates
224
-
225
- Produce: `.gsd-t/scan/quality.md`
226
-
227
- ```markdown
228
- # Code Quality Analysis — {date}
229
-
230
- ## Dead Code
231
- - {file}: {description}
232
-
233
- ## Duplication
234
- - {file-a} ↔ {file-b}: {description of duplicated logic}
235
-
236
- ## Reusability Analysis
237
-
238
- ### Consumer Surfaces Detected
239
- | Surface | Type | Operations Used |
240
- |---------|------|----------------|
241
- | {module/app} | {web/mobile/cli/other} | {list of backend operations it calls} |
242
-
243
- ### Shared Service Candidates
244
- Operations implemented independently in 2+ places — candidates for extraction to a shared module:
245
-
246
- | Operation | Found In | Recommendation |
247
- |-----------|----------|----------------|
248
- | {operation} | {file-a}, {file-b} | Extract to shared-core |
249
- | {operation} | {file-a}, {file-b}, {file-c} | Extract to shared-core (high priority — 3 copies) |
250
-
251
- If none found: `✅ No shared service candidates detected.`
252
-
253
- > **Note**: These candidates should seed Step 1.6 (Consumer Surface Identification) the next
254
- > time `/gsd-t-partition` is run. Copy the "Consumer Surfaces Detected" table into
255
- > partition's Step 1.6.1 to skip re-research.
256
-
257
- ## Complexity Hotspots
258
- - {file}:{function} — complexity: {score/assessment} — {suggestion}
259
-
260
- ## Error Handling Gaps
261
- - {file}: {description}
262
-
263
- ## Performance Issues
264
- - {description} — impact: {high/medium/low} — {fix}
265
-
266
- ## Unresolved Developer Notes
267
- - {file}:{line}: {TODO/FIXME text}
268
-
269
- ## Test Coverage Gaps
270
- - {critical path}: {not tested / partially tested}
271
-
272
- ## Stale Dependencies
273
- - {package}: current {version}, latest {version} — {breaking changes?}
274
- ```
275
-
276
- ### E) Contract Reality Check (if contracts exist)
277
- Compare existing `.gsd-t/contracts/` to the actual implementation:
278
- - Do API endpoints match the api-contract?
279
- - Does the schema match the schema-contract?
280
- - Are there undocumented endpoints or tables?
281
- - Have contracts drifted from reality?
282
-
283
- Produce: `.gsd-t/scan/contract-drift.md`
284
-
285
- ```markdown
286
- # Contract Drift Analysis — {date}
287
-
288
- ## API Contract vs Reality
289
- - {endpoint}: {matches | drifted | undocumented}
290
- - Contract says: {X}
291
- - Reality: {Y}
292
-
293
- ## Schema Contract vs Reality
294
- - {table}: {matches | drifted | undocumented}
295
-
296
- ## Undocumented (exists in code, no contract)
297
- - {endpoint/table/component}: {description}
298
- ```
299
-
300
- ## Step 2.5: Schema Extraction
301
-
302
- ```bash
303
- 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-scan --step 2 --step-label ".5: Schema Extraction" 2>/dev/null || true
304
- ```
305
-
306
- Run schema extraction on the scanned project to detect ORM/database schema files and parse entity definitions. This data feeds the database schema diagram in Step 3.5.
307
-
308
- Using Bash tool:
309
- ```
310
- node -e "const {extractSchema}=require('./bin/scan-schema.js'); const r=extractSchema(process.argv[1]); process.stdout.write(JSON.stringify(r))" "$SCANNED_PROJECT_ROOT"
311
9
  ```
312
-
313
- Capture output as `schemaData`. Log:
314
- - Detected ORM type: `schemaData.ormType`
315
- - Entity count: `schemaData.entities.length`
316
-
317
- If `schemaData.detected === false`, note: "No ORM/schema files detected — database diagram will use placeholder."
318
-
319
- ## Step 2.9: Archive Previous Tech Debt Register
320
-
321
- ```bash
322
- 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-scan --step 2 --step-label ".9: Archive Previous Tech Debt Register" 2>/dev/null || true
10
+ preflight → volume-probe → pipeline(per-slice deep finder → single verify) → synthesis → document → render
323
11
  ```
324
12
 
325
- Before building the new register, archive the existing one so the file stays small. Each scan is a complete snapshot the archive preserves history.
326
-
327
- If `.gsd-t/techdebt.md` exists:
328
- 1. Determine the archive date from the file's header (e.g., "Updated 2026-03-19" → `2026-03-19`). If no date found, use today's date.
329
- 2. Rename it to `.gsd-t/techdebt_YYYY-MM-DD.md` (using the extracted date)
330
- 3. If a file with that name already exists (same-day rescan), append a counter: `techdebt_YYYY-MM-DD_2.md`
331
-
332
- The new `techdebt.md` created in Step 3 will contain only the current scan's findings. Between scans, mark items as `[RESOLVED]` inline as they are fixed. The next scan replaces the file again.
333
-
334
- ## Step 3: Build Tech Debt Register
335
-
336
- ```bash
337
- 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-scan --step 3 --step-label "Build Tech Debt Register" 2>/dev/null || true
338
- ```
339
-
340
- Synthesize ALL findings into a **fresh** `.gsd-t/techdebt.md` (the previous version was archived in Step 2.9). This file contains only the current scan's findings — no resolved items table, no scan history. Previous scans are preserved in `techdebt_YYYY-MM-DD.md` archives.
341
-
342
- **Between scans:** when an item is fixed, change its `**Status**:` field to `[RESOLVED] — {brief reason/milestone}`. Do not delete the item — it stays visible until the next scan replaces the file.
343
-
344
- **TD numbering:** continue from the highest TD number in the archived file. Check the archive to find the last TD-NNN used.
345
-
346
- ```markdown
347
- # Tech Debt Register — {date} (Scan #{N})
348
-
349
- ## Summary
350
- - Critical items: {N}
351
- - High priority: {N}
352
- - Medium priority: {N}
353
- - Low priority: {N}
354
- - Total estimated scope: {N domains} / {N waves} / $X-Y token-spend (GSD-T units only — see `feedback_no_human_hour_estimates.md`)
355
- - Previous scan archive: techdebt_{previous-date}.md
356
-
357
- ---
358
-
359
- ## Critical Priority
360
- Items that pose active risk or block progress.
361
-
362
- ### TD-001: {title}
363
- - **Category**: {security | performance | architecture | quality | dependency}
364
- - **Severity**: CRITICAL
365
- - **Status**: OPEN
366
- - **Location**: {file(s)}
367
- - **Description**: {what's wrong}
368
- - **Impact**: {what happens if not fixed}
369
- - **Remediation**: {how to fix}
370
- - **Effort**: {small | medium | large}
371
- - **Milestone candidate**: YES — recommended as standalone milestone
372
- - **Promoted**: [ ] — (check when added to roadmap)
373
-
374
- ### TD-002: {title}
375
- ...
376
-
377
- ---
378
-
379
- ## High Priority
380
- Items that should be addressed in the next 1-2 milestones.
13
+ **Why volume-scaled (M66):** the legacy scan hard-coded exactly 5 teammates (one per dimension) with zero volume scaling — a 5-file repo and a 1,809-file repo both got 5 agents, so a single `quality` agent sampled the top ~5 issues across the whole codebase and stopped. The volume-probe stage now measures the codebase (files, routes, ORM tables, components, top-level dirs) and carves it into **narrow slices** — one deep-finder agent per area, scaling from 1-3 slices on a tiny repo to 15-40 on a large one. Each finder OWNS its slice and is mandated to *enumerate, not sample*. A single verify pass confirms each finding against the real code and drops false positives. Synthesis dedups/merges/re-ranks into `techdebt.md` and continues TD numbering from the archived prior register.
381
14
 
382
- ### TD-010: {title}
383
- - **Category**: {category}
384
- - **Severity**: HIGH
385
- - **Status**: OPEN
386
- - **Location**: {file(s)}
387
- - **Description**: {what's wrong}
388
- - **Impact**: {what happens if not fixed}
389
- - **Remediation**: {how to fix}
390
- - **Effort**: {small | medium | large}
391
- - **Milestone candidate**: {YES | NO — fold into existing milestone}
392
- - **Promoted**: [ ]
393
-
394
- ---
395
-
396
- ## Medium Priority
397
- Items to plan for but not urgent.
398
-
399
- ### TD-020: {title}
400
- ...
401
-
402
- ---
403
-
404
- ## Low Priority
405
- Nice-to-haves and cleanup.
406
-
407
- ### TD-030: {title}
408
- ...
409
-
410
- ---
411
-
412
- ## Dependency Updates
413
- | Package | Current | Latest | Breaking? | Priority |
414
- |---------|---------|--------|-----------|----------|
415
- | {name} | {ver} | {ver} | {yes/no} | {priority} |
416
-
417
- ---
418
-
419
- ## Scan Metadata
420
- - Scan date: {date}
421
- - Scan number: {N}
422
- - Files analyzed: {count}
423
- - Lines of code: {approximate}
424
- - Languages: {list}
425
- - Previous scan archive: techdebt_{previous-date}.md (or "first scan")
426
- ```
427
-
428
- ## Step 3.5: Diagram Generation
429
-
430
- ```bash
431
- 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-scan --step 3 --step-label ".5: Diagram Generation" 2>/dev/null || true
432
- ```
433
-
434
- Generate all 6 architectural diagrams using analysis data from Step 2 and schema data from Step 2.5.
435
-
436
- Using Bash tool:
437
- ```
438
- node -e "
439
- const {generateDiagrams}=require('./bin/scan-diagrams.js');
440
- const analysisData=JSON.parse(process.argv[1]);
441
- const schemaData=JSON.parse(process.argv[2]);
442
- const r=generateDiagrams(analysisData, schemaData, {projectRoot: process.argv[3]});
443
- process.stdout.write(JSON.stringify(r.map(d=>({type:d.type,rendered:d.rendered,rendererUsed:d.rendererUsed}))));
444
- " "$ANALYSIS_JSON" "$SCHEMA_JSON" "$SCANNED_PROJECT_ROOT"
445
- ```
446
-
447
- Capture the full array as `diagrams`. Log:
448
- - Diagrams rendered: count of `diagrams.filter(d => d.rendered).length` out of 6
449
- - Renderer used per diagram: `diagrams.map(d => d.type + ': ' + d.rendererUsed).join(', ')`
450
-
451
- ## Step 4: Suggest Milestone Promotions
452
-
453
- ```bash
454
- 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-scan --step 4 --step-label "Suggest Milestone Promotions" 2>/dev/null || true
455
- ```
15
+ **Deep document stage (M67):** after the register lands, a `document` phase fans out **one agent per document**, each drawing on the same slices + verified findings, to deterministically produce the full living-document set — `docs/architecture.md` (component map per feature-domain slice), `docs/workflows.md` (a user journey per slice), `docs/infrastructure.md`, `docs/requirements.md`, `README.md` (all merge-not-overwrite) — plus the five `.gsd-t/scan/*.md` dimension files (`architecture`, `security`, `quality`, `business-rules`, `contract-drift`) in the renderer's parsed formats. This replaces M66's non-deterministic "lead-agent follow-on" so the documents are as thorough as the register. The deterministic `bin/scan-*.js` renderers (schema extraction, diagrams, HTML report) run last, reading the deep `.gsd-t/scan/architecture.md`.
456
16
 
457
- Review all items marked `Milestone candidate: YES` and group them into logical milestones:
17
+ Each stage is a schema-validated `agent()` call (or deterministic CLI). Finders and verifiers run concurrently up to the Workflow runtime's concurrency cap. Slice DEPTH scales with `budget.total` when a per-turn token target is set.
458
18
 
459
- ```markdown
460
- ## Suggested Tech Debt Milestones
19
+ ## Step 1: Read existing context
461
20
 
462
- ### Suggested: Security Hardening (Critical)
463
- Combines: TD-001, TD-003, TD-005
464
- Estimated scope: {domain-count} domains, {wave-count} waves, $X-Y token-spend (express in GSD-T units — domain/wave/spawn/token — never human-hours/days/sprints per `feedback_no_human_hour_estimates.md`)
465
- Should be prioritized: BEFORE next feature milestone
21
+ Read `CLAUDE.md`, `.gsd-t/progress.md`, `.gsd-t/contracts/`, and any existing `.gsd-t/techdebt.md` (the Workflow archives and continues from it). This tells the scan what's already known so it dedups rather than re-discovers.
466
22
 
467
- ### Suggested: Performance Optimization (High)
468
- Combines: TD-010, TD-012, TD-015
469
- Estimated scope: {domain-count} domains, {wave-count} waves, $X-Y token-spend (express in GSD-T units — domain/wave/spawn/token — never human-hours/days/sprints per `feedback_no_human_hour_estimates.md`)
470
- Can be scheduled: AFTER current feature work
23
+ ## Step 2: Invoke the scan Workflow
471
24
 
472
- ### Suggested: Dependency Update (Medium)
473
- Combines: TD-020, dependency table items with breaking=yes
474
- Estimated scope: {domain-count} domains, {wave-count} waves, $X-Y token-spend (express in GSD-T units — domain/wave/spawn/token — never human-hours/days/sprints per `feedback_no_human_hour_estimates.md`)
475
- Can be scheduled: During next maintenance window
25
+ Call the `Workflow` tool with:
476
26
 
477
- ### Suggested: Shared Service Extraction (if candidates found)
478
- Combines: all "Shared Service Candidates" from quality.md Reusability Analysis
479
- Estimated scope: {domain-count} domains, {wave-count} waves, $X-Y token-spend (express in GSD-T units — domain/wave/spawn/token — never human-hours/days/sprints per `feedback_no_human_hour_estimates.md`)
480
- Should be prioritized: BEFORE adding new consumer surfaces to the system
481
- Note: Use `/gsd-t-partition` Step 1.6 to design the SharedCore domain
482
- ```
483
-
484
- ## Step 5: Update Living Documents
485
-
486
- ```bash
487
- 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-scan --step 5 --step-label "Update Living Documents" 2>/dev/null || true
488
- ```
489
-
490
- The scan produces deep analysis in `.gsd-t/scan/`. Now cross-populate findings into the living docs so knowledge persists across milestones.
491
-
492
- ### docs/architecture.md
493
- Using findings from `.gsd-t/scan/architecture.md`, update or create `docs/architecture.md`:
494
- - System overview (stack, structure, patterns)
495
- - Component descriptions with locations and dependencies
496
- - Data flow (request → handler → service → data layer → response)
497
- - Data models from schema files or ORM definitions
498
- - API structure from route definitions
499
- - External integrations
500
- - Design decisions found in code comments or configs
501
-
502
- If the file exists, merge new findings — don't overwrite existing content.
503
-
504
- ### docs/workflows.md
505
- Using findings from `.gsd-t/scan/business-rules.md`, update or create `docs/workflows.md`:
506
- - User workflows traced from routes/handlers (registration, login, core features)
507
- - Technical workflows from cron jobs, queue workers, scheduled tasks
508
- - API workflows for multi-step operations
509
- - Integration workflows for external system syncing
510
- - State machines and approval flows discovered in code
511
-
512
- ### docs/infrastructure.md
513
- Scan the codebase for operational knowledge and update or create `docs/infrastructure.md`:
514
- - **Quick Reference commands** from package.json scripts, Makefile, README, CI/CD configs
515
- - **Local development setup** from README, docker-compose, .env.example
516
- - **Database commands** from migrations, seeds, ORM config, backup scripts
517
- - **Cloud provisioning** from Terraform, CloudFormation, Pulumi, or deployment scripts
518
- - **Credentials and secrets** from .env.example (names only, not values) and secret manager configs
519
- - **Deployment** from CI/CD configs, Dockerfiles, cloud platform configs
520
- - **Logging and monitoring** from any logging setup or dashboard configs
521
-
522
- This is critical — infrastructure knowledge is the most commonly lost between sessions.
523
-
524
- ### docs/requirements.md
525
- Using all scan findings, update or create `docs/requirements.md`:
526
- - Functional requirements discovered from routes, handlers, UI components
527
- - Technical requirements from configs, package.json, runtime settings
528
- - Non-functional requirements from performance configs, rate limits, caching
529
-
530
- ### README.md
531
- Update or create `README.md` with scan findings:
532
- - Project name and description
533
- - Tech stack and versions discovered
534
- - Getting started / setup instructions (from infrastructure findings)
535
- - Brief architecture overview
536
- - Link to `docs/` for detailed documentation
537
-
538
- If `README.md` exists, merge — update tech stack and setup sections but preserve the user's existing structure and custom content.
539
-
540
- ### For all docs:
541
- - If the file exists and has real content, **merge** — don't overwrite
542
- - If the file exists with only placeholder text, **replace** with real findings
543
- - If the file doesn't exist, **create** it
544
- - Replace `{Project Name}` and `{Date}` tokens with actual values
545
-
546
- ## Step 6: Test Verification
547
-
548
- ```bash
549
- 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-scan --step 6 --step-label "Test Verification" 2>/dev/null || true
550
- ```
551
-
552
- After updating living documents, verify nothing was broken:
553
-
554
- 1. **Run existing tests**: Execute the full test suite to establish a baseline — document what passes and what was already failing
555
- 2. **Verify passing**: If any tests fail that were passing before the scan began, investigate and fix
556
- 3. **Log test baseline**: Record the current test state in `.gsd-t/scan/test-baseline.md` — this gives future milestones a starting point
557
-
558
- ## Step 6.5: Generate Scan Freshness Cache
559
-
560
- ```bash
561
- 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-scan --step 6 --step-label ".5: Generate Scan Freshness Cache" 2>/dev/null || true
562
- ```
563
-
564
- After the scan completes and living docs are updated, generate a hash cache so downstream commands can detect staleness without re-scanning.
565
-
566
- Create `.gsd-t/scan/.cache.json` with this structure:
567
-
568
- ```bash
569
- node -e "
570
- const fs = require('fs');
571
- const path = require('path');
572
- const crypto = require('crypto');
573
-
574
- const root = process.argv[1];
575
- const scanDir = path.join(root, '.gsd-t', 'scan');
576
-
577
- // Hash all source files that affect each scan dimension
578
- const dimensions = {
579
- architecture: ['**/*.js', '**/*.ts', '**/*.py', '**/*.json', '**/package.json', '**/tsconfig.json'],
580
- quality: ['**/*.js', '**/*.ts', '**/*.py', '**/*.test.*', '**/*.spec.*'],
581
- security: ['**/*.js', '**/*.ts', '**/*.py', '**/*.env*', '**/package.json', '**/package-lock.json'],
582
- 'business-rules': ['**/*.js', '**/*.ts', '**/*.py'],
583
- 'contract-drift': ['.gsd-t/contracts/**']
584
- };
585
-
586
- // For each dimension, hash the scan doc itself to track its version
587
- const cache = { generated: new Date().toISOString(), dimensions: {} };
588
- for (const [dim, _patterns] of Object.entries(dimensions)) {
589
- const scanFile = path.join(scanDir, dim + '.md');
590
- if (fs.existsSync(scanFile)) {
591
- const content = fs.readFileSync(scanFile, 'utf8');
592
- cache.dimensions[dim] = {
593
- scanHash: crypto.createHash('md5').update(content).digest('hex'),
594
- scannedAt: new Date().toISOString()
595
- };
27
+ ```js
28
+ {
29
+ scriptPath: "templates/workflows/gsd-t-scan.workflow.js",
30
+ args: {
31
+ projectDir: ".", // the project to scan
32
+ scanNumber: 12, // optional — for the register header
33
+ maxSlicesHint: 40, // optional — soft cap on derived slices (no silent truncation)
34
+ verify: "single" // optional "single" (default) | "none"
596
35
  }
597
36
  }
598
-
599
- fs.writeFileSync(path.join(scanDir, '.cache.json'), JSON.stringify(cache, null, 2));
600
- console.log('Scan cache generated:', Object.keys(cache.dimensions).length, 'dimensions cached');
601
- " "$PROJECT_ROOT"
602
- ```
603
-
604
- This cache enables downstream commands (`partition`, `feature`, `gap-analysis`) to check scan freshness and auto-refresh stale dimensions before consuming scan data.
605
-
606
- ## Step 7: Update Project State
607
-
608
- ```bash
609
- 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-scan --step 7 --step-label "Update Project State" 2>/dev/null || true
610
37
  ```
611
38
 
612
- If `.gsd-t/progress.md` exists:
613
- - Log scan in Decision Log
614
- - Note critical findings
39
+ The Workflow handles preflight, the volume probe, the per-slice deep-finder fan-out, the single verify pass, register synthesis (with archive + TD-numbering continuation), and the deterministic schema/diagram/HTML render. Each stage emits a progress line visible via `/workflows`. The runtime persists the script path on every invocation; iterate by editing the persisted file and re-invoking with the same `scriptPath`.
615
40
 
616
- If `.gsd-t/roadmap.md` exists:
617
- - Do NOT auto-add milestones — present suggestions to user
618
- - User decides which to promote with `/gsd-t-promote-debt`
41
+ ## Step 3: Interpret the result
619
42
 
620
- If `CLAUDE.md` exists:
621
- - Suggest updates for any patterns or conventions discovered during scan
43
+ The Workflow returns:
622
44
 
623
- ## Step 8: Report to User
624
-
625
- ```bash
626
- 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-scan --step 8 --step-label "Report to User" 2>/dev/null || true
45
+ ```js
46
+ {
47
+ status: "complete" | "failed",
48
+ slices: 24, // how many slices the probe derived
49
+ findings: 117, // verified findings after the verify pass
50
+ counts: { critical, high, medium, low, total },
51
+ registerPath: ".gsd-t/techdebt.md",
52
+ archivePath: ".gsd-t/techdebt_YYYY-MM-DD.md" | null,
53
+ htmlReport: "<path>" | null,
54
+ probeTotals: { files, routes, tables, components, ... }
55
+ }
627
56
  ```
628
57
 
629
- Present a summary:
630
- 1. Architecture overview (brief)
631
- 2. Business rules found (count + any undocumented ones)
632
- 3. Security findings by severity
633
- 4. Top 5 quality issues
634
- 5. Contract drift (if applicable)
635
- 6. Tech debt summary with milestone suggestions
636
- 7. Recommended immediate actions
637
-
638
- All detailed findings are in `.gsd-t/scan/` for review.
58
+ - `status === "complete"`: the deep register is written; present the summary (counts + top critical items) and offer `/gsd-t-promote-debt`.
59
+ - `status === "failed"`: read `reason` — `preflight-failed`, `no-slices` (probe produced an empty slice list), or `synthesis-failed` (register not written).
639
60
 
640
- Ask: "Want to promote any tech debt items to milestones? Or address the critical items first?"
641
-
642
- ### HTML Report Generation
643
-
644
- After writing the text report to `.gsd-t/techdebt.md`, generate the self-contained HTML scan report:
645
-
646
- Using Bash tool:
647
- ```
648
- node -e "
649
- const {collectScanData}=require('./bin/scan-data-collector.js');
650
- const {extractSchema}=require('./bin/scan-schema.js');
651
- const {generateDiagrams}=require('./bin/scan-diagrams.js');
652
- const {generateReport}=require('./bin/scan-report.js');
653
- const root=process.argv[1];
654
- const analysisData=collectScanData(root);
655
- const schemaData=extractSchema(root);
656
- const diagrams=generateDiagrams(analysisData, schemaData, {projectRoot:root});
657
- const r=generateReport(analysisData, schemaData, diagrams, {projectRoot:root});
658
- if (r.outputPath) console.log('HTML report:', r.outputPath, '| Diagrams rendered:', r.diagramsRendered + '/6');
659
- else console.error('Report generation failed:', r.error);
660
- " "$SCANNED_PROJECT_ROOT"
661
- ```
662
-
663
- Report the HTML output path and diagram render count to the user.
61
+ Present a summary: headline volume totals, findings by severity, the top critical items, and the archive path. Then ask: "Want to promote any tech debt items to milestones with `/gsd-t-promote-debt`?"
664
62
 
665
63
  ## Document Ripple
666
64
 
667
- Scan produces analysis files and updates living documents (Step 5 already covers most updates). Verify:
65
+ The scan Workflow updates ALL of these deterministically (no manual follow-on):
668
66
 
669
- ### Always update:
670
- 1. **`.gsd-t/progress.md`**Log scan completion with summary stats in Decision Log
671
- 2. **`docs/architecture.md`**Merge scan findings (Step 5)
672
- 3. **`docs/workflows.md`** Merge business rules findings (Step 5)
673
- 4. **`docs/infrastructure.md`** — Merge operational findings (Step 5)
674
- 5. **`docs/requirements.md`** — Merge discovered requirements (Step 5)
675
- 6. **`README.md`** — Update tech stack and setup if needed (Step 5)
67
+ - `.gsd-t/techdebt.md` — fresh register (synthesis; prior one archived to `.gsd-t/techdebt_YYYY-MM-DD.md`)
68
+ - `.gsd-t/scan/{architecture,security,quality,business-rules,contract-drift}.md`dimension analysis files (document phase)
69
+ - `docs/architecture.md`, `docs/workflows.md`, `docs/infrastructure.md`, `docs/requirements.md`, `README.md` living docs, **merged not overwritten** (document phase)
70
+ - HTML scan report via `bin/scan-report.js` (render phase)
676
71
 
677
- ### Check if affected:
678
- 7. **`.gsd-t/techdebt.md`** — Created/updated with all findings (Step 3)
679
- 8. **`CLAUDE.md`** — If new conventions or patterns were discovered, suggest additions
72
+ The document phase + render commit these via git on the feature branch (no push). The lead agent should still add a `.gsd-t/progress.md` Decision Log entry with the scan summary stats.
680
73
 
681
- $ARGUMENTS
74
+ ## Next Up
682
75
 
683
- ## Auto-Clear
76
+ `/gsd-t-promote-debt` — convert tech-debt items to milestones.
684
77
 
685
- All work is committed to project files. Execute `/clear` to free the context window for the next command.
78
+ $ARGUMENTS