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