@opengsd/gsd-core 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.opencode/plugins/gsd-core.js +14 -0
  4. package/README.md +2 -0
  5. package/agents/gsd-debug-session-manager.md +42 -4
  6. package/agents/gsd-debugger.md +87 -29
  7. package/agents/gsd-executor.md +29 -2
  8. package/agents/gsd-planner.md +29 -36
  9. package/agents/gsd-verifier.md +2 -2
  10. package/bin/install.js +1152 -80
  11. package/commands/gsd/ai-integration-phase.md +1 -1
  12. package/commands/gsd/mempalace-capture.md +9 -5
  13. package/commands/gsd/new-milestone.md +1 -1
  14. package/commands/gsd/plan-phase.md +5 -3
  15. package/commands/gsd/plan-review-convergence.md +3 -2
  16. package/gsd-core/bin/gsd-tools.cjs +1878 -2507
  17. package/gsd-core/bin/lib/adapter-imperative.cjs +8 -1
  18. package/gsd-core/bin/lib/agent-command-router.cjs +20 -5
  19. package/gsd-core/bin/lib/api-coverage.cjs +338 -45
  20. package/gsd-core/bin/lib/broken-windows.cjs +716 -0
  21. package/gsd-core/bin/lib/capability-command-router.cjs +733 -0
  22. package/gsd-core/bin/lib/capability-registry.cjs +155 -86
  23. package/gsd-core/bin/lib/capability-writer.cjs +6 -1
  24. package/gsd-core/bin/lib/check-command-router.cjs +128 -25
  25. package/gsd-core/bin/lib/claude-orchestration-command-router.cjs +115 -27
  26. package/gsd-core/bin/lib/claude-orchestration.cjs +84 -9
  27. package/gsd-core/bin/lib/command-aliases.cjs +14 -0
  28. package/gsd-core/bin/lib/commands.cjs +81 -4
  29. package/gsd-core/bin/lib/config-loader.cjs +14 -2
  30. package/gsd-core/bin/lib/config.cjs +69 -18
  31. package/gsd-core/bin/lib/core-utils.cjs +6 -1
  32. package/gsd-core/bin/lib/decisions.cjs +32 -8
  33. package/gsd-core/bin/lib/docs.cjs +6 -0
  34. package/gsd-core/bin/lib/external-descriptor-trust.cjs +14 -2
  35. package/gsd-core/bin/lib/gap-checker.cjs +17 -2
  36. package/gsd-core/bin/lib/init.cjs +111 -47
  37. package/gsd-core/bin/lib/install-engine.cjs +298 -23
  38. package/gsd-core/bin/lib/install-profiles.cjs +239 -1
  39. package/gsd-core/bin/lib/installer-migrations/005-opencode-baseline-commands-dir.cjs +146 -0
  40. package/gsd-core/bin/lib/installer-migrations/006-pi-extension-cjs-to-js.cjs +91 -0
  41. package/gsd-core/bin/lib/installer-migrations.cjs +44 -5
  42. package/gsd-core/bin/lib/markdown-sectionizer.cjs +107 -0
  43. package/gsd-core/bin/lib/milestone.cjs +246 -12
  44. package/gsd-core/bin/lib/model-catalog.cjs +19 -4
  45. package/gsd-core/bin/lib/model-resolver.cjs +189 -7
  46. package/gsd-core/bin/lib/onboard-projection.cjs +11 -8
  47. package/gsd-core/bin/lib/phase-id.cjs +26 -4
  48. package/gsd-core/bin/lib/phase.cjs +201 -12
  49. package/gsd-core/bin/lib/plan-scan.cjs +70 -2
  50. package/gsd-core/bin/lib/roadmap-parser.cjs +7 -4
  51. package/gsd-core/bin/lib/roadmap.cjs +13 -3
  52. package/gsd-core/bin/lib/runtime-artifact-conversion.cjs +7 -1
  53. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +22 -8
  54. package/gsd-core/bin/lib/runtime-hooks-surface.cjs +16 -0
  55. package/gsd-core/bin/lib/smart-entry.cjs +69 -4
  56. package/gsd-core/bin/lib/state-document.cjs +7 -4
  57. package/gsd-core/bin/lib/state-transition.cjs +22 -1
  58. package/gsd-core/bin/lib/state.cjs +65 -11
  59. package/gsd-core/bin/lib/surface.cjs +51 -9
  60. package/gsd-core/bin/lib/uat.cjs +420 -5
  61. package/gsd-core/bin/lib/validate.cjs +12 -8
  62. package/gsd-core/bin/lib/verification.cjs +112 -17
  63. package/gsd-core/bin/lib/verify.cjs +220 -22
  64. package/gsd-core/bin/shared/config-schema.manifest.json +3 -2
  65. package/gsd-core/references/api-coverage.md +37 -7
  66. package/gsd-core/references/checkpoints.md +1 -1
  67. package/gsd-core/references/common-bug-patterns.md +13 -0
  68. package/gsd-core/references/debugger-bug-taxonomy.md +111 -0
  69. package/gsd-core/references/debugger-fix-acceptance.md +157 -0
  70. package/gsd-core/references/debugger-philosophy.md +1 -0
  71. package/gsd-core/references/debugger-prevention.md +98 -0
  72. package/gsd-core/references/debugger-rca-branching.md +98 -0
  73. package/gsd-core/references/debugger-repro-hardening.md +130 -0
  74. package/gsd-core/references/debugger-sbfl.md +110 -0
  75. package/gsd-core/references/debugger-semantic-recall.md +81 -0
  76. package/gsd-core/references/execute-phase-quota-recovery.md +55 -0
  77. package/gsd-core/references/execute-phase-requirement-revert.md +8 -0
  78. package/gsd-core/references/execute-phase-response-language.md +7 -0
  79. package/gsd-core/references/planner-antipatterns.md +6 -0
  80. package/gsd-core/references/planner-mvp-mode.md +12 -13
  81. package/gsd-core/references/planner-preconditions.md +156 -0
  82. package/gsd-core/references/planner-reversibility.md +132 -0
  83. package/gsd-core/references/reviewer-instances.md +9 -7
  84. package/gsd-core/references/skeleton-template.md +1 -1
  85. package/gsd-core/references/thinking-models-planning.md +3 -1
  86. package/gsd-core/templates/DEBUG.md +5 -3
  87. package/gsd-core/workflows/add-phase.md +2 -0
  88. package/gsd-core/workflows/add-tests.md +3 -1
  89. package/gsd-core/workflows/add-todo.md +32 -1
  90. package/gsd-core/workflows/ai-integration-phase.md +4 -2
  91. package/gsd-core/workflows/audit-fix.md +2 -2
  92. package/gsd-core/workflows/check-todos.md +3 -1
  93. package/gsd-core/workflows/cleanup.md +7 -1
  94. package/gsd-core/workflows/code-review.md +17 -5
  95. package/gsd-core/workflows/complete-milestone.md +3 -0
  96. package/gsd-core/workflows/debug.md +25 -5
  97. package/gsd-core/workflows/diagnose-issues.md +1 -1
  98. package/gsd-core/workflows/discovery-phase.md +7 -0
  99. package/gsd-core/workflows/discuss-phase/templates/context.md +16 -2
  100. package/gsd-core/workflows/discuss-phase-assumptions.md +3 -0
  101. package/gsd-core/workflows/do.md +7 -1
  102. package/gsd-core/workflows/docs-update.md +1 -0
  103. package/gsd-core/workflows/eval-review.md +3 -0
  104. package/gsd-core/workflows/execute-phase/steps/post-merge-gate.md +4 -4
  105. package/gsd-core/workflows/execute-phase/steps/regression-gate.md +2 -2
  106. package/gsd-core/workflows/execute-phase.md +25 -34
  107. package/gsd-core/workflows/execute-plan.md +15 -4
  108. package/gsd-core/workflows/graduation.md +3 -0
  109. package/gsd-core/workflows/health.md +7 -1
  110. package/gsd-core/workflows/help/modes/full.md +6 -2
  111. package/gsd-core/workflows/import.md +8 -2
  112. package/gsd-core/workflows/inbox.md +7 -0
  113. package/gsd-core/workflows/ingest-docs.md +15 -10
  114. package/gsd-core/workflows/manager.md +3 -1
  115. package/gsd-core/workflows/map-codebase.md +4 -4
  116. package/gsd-core/workflows/mvp-phase.md +3 -0
  117. package/gsd-core/workflows/new-milestone.md +69 -21
  118. package/gsd-core/workflows/new-project.md +17 -15
  119. package/gsd-core/workflows/new-workspace.md +3 -1
  120. package/gsd-core/workflows/onboard.md +3 -0
  121. package/gsd-core/workflows/plan-phase.md +14 -5
  122. package/gsd-core/workflows/plan-review-convergence.md +48 -3
  123. package/gsd-core/workflows/plant-seed.md +3 -0
  124. package/gsd-core/workflows/profile-user.md +7 -1
  125. package/gsd-core/workflows/progress.md +31 -3
  126. package/gsd-core/workflows/quick.md +19 -7
  127. package/gsd-core/workflows/remove-workspace.md +3 -0
  128. package/gsd-core/workflows/review.md +89 -73
  129. package/gsd-core/workflows/scan.md +1 -1
  130. package/gsd-core/workflows/secure-phase.md +3 -0
  131. package/gsd-core/workflows/settings-integrations.md +3 -0
  132. package/gsd-core/workflows/settings.md +3 -0
  133. package/gsd-core/workflows/ship.md +50 -3
  134. package/gsd-core/workflows/sketch.md +3 -0
  135. package/gsd-core/workflows/smart-entry.md +3 -0
  136. package/gsd-core/workflows/spike.md +7 -1
  137. package/gsd-core/workflows/ui-phase.md +3 -1
  138. package/gsd-core/workflows/ui-review.md +3 -0
  139. package/gsd-core/workflows/undo.md +7 -0
  140. package/gsd-core/workflows/update.md +2 -0
  141. package/gsd-core/workflows/validate-phase.md +3 -0
  142. package/gsd-core/workflows/verify-phase.md +2 -2
  143. package/gsd-core/workflows/verify-work.md +7 -3
  144. package/hooks/dist/gsd-context-monitor.js +27 -9
  145. package/hooks/dist/gsd-statusline.js +88 -3
  146. package/hooks/gsd-context-monitor.js +27 -9
  147. package/hooks/gsd-statusline.js +88 -3
  148. package/package.json +6 -4
  149. package/pi/gsd.cjs +8 -2
  150. package/scripts/changeset/lint.cjs +1 -0
  151. package/scripts/changeset/parse.cjs +26 -0
  152. package/scripts/check-glossary-refs.cjs +220 -0
  153. package/scripts/ci-rebase-check.cjs +48 -4
  154. package/scripts/gen-adr-index.cjs +526 -0
  155. package/scripts/gen-test-timings.cjs +201 -0
  156. package/scripts/lint-portable-timeout.cjs +140 -0
  157. package/scripts/lint-test-file-count.allowlist.json +1 -0
  158. package/scripts/release-tarball-smoke.cjs +18 -11
  159. package/scripts/run-tests.cjs +420 -58
  160. package/skills/gsd-ai-integration-phase/SKILL.md +1 -1
  161. package/skills/gsd-mempalace-capture/SKILL.md +9 -5
  162. package/skills/gsd-new-milestone/SKILL.md +1 -1
  163. package/skills/gsd-plan-phase/SKILL.md +5 -3
  164. package/skills/gsd-plan-review-convergence/SKILL.md +3 -2
  165. package/vscode/package.json +1 -1
@@ -0,0 +1,526 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Generates the ADR index table in docs/adr/README.md from the ADR files
6
+ * themselves, and validates the corpus' lifecycle invariants.
7
+ *
8
+ * The index is a DERIVED artifact: it is regenerated from every
9
+ * `docs/adr/<id>-<slug>.md` on disk, so it cannot silently drift out of date
10
+ * the way a hand-maintained table does. CI re-runs this with `--check` and
11
+ * fails on any diff or invariant violation.
12
+ *
13
+ * Invariants enforced (see docs/adr/README.md "Lifecycle rules"):
14
+ * 1. Every ADR declares `- **Status:** <Token>` with Token in STATUSES.
15
+ * 2. A Superseded/Retired ADR names its successor as a markdown link to the
16
+ * target file — never a bare "ADR-N", which is ambiguous (ADR-0010 and
17
+ * ADR-0011 each resolve to more than one file).
18
+ * 3. Supersession is symmetric: if A supersedes B, B records superseded-by A.
19
+ * 4. An ADR whose H1 declares an id must match its filename's id.
20
+ * 5. The committed index equals the generated index.
21
+ *
22
+ * Usage:
23
+ * node scripts/gen-adr-index.cjs # print the index to stdout
24
+ * node scripts/gen-adr-index.cjs --write # rewrite the index in README.md
25
+ * node scripts/gen-adr-index.cjs --check # exit 1 if stale or invalid
26
+ */
27
+
28
+ const fs = require('node:fs');
29
+ const path = require('node:path');
30
+
31
+ const { ExitError, runMain } = require('./lib/cli-exit.cjs');
32
+
33
+ const ROOT = path.resolve(__dirname, '..');
34
+ const ADR_DIR = path.join(ROOT, 'docs', 'adr');
35
+ const README_PATH = path.join(ADR_DIR, 'README.md');
36
+
37
+ const START_MARKER = '<!-- ADR-INDEX:START — generated by scripts/gen-adr-index.cjs; do not edit by hand -->';
38
+ const END_MARKER = '<!-- ADR-INDEX:END -->';
39
+
40
+ /**
41
+ * The canonical status vocabulary.
42
+ *
43
+ * `Legacy` and `Retired` are deliberately distinct from `Superseded`:
44
+ * - Superseded — a specific newer ADR replaced this decision. Names it.
45
+ * - Retired — the thing this ADR decided no longer exists at all, and no
46
+ * single ADR replaced it (e.g. a deleted package boundary).
47
+ * - Legacy — frozen historical record, kept for provenance, not a
48
+ * pattern to imitate.
49
+ *
50
+ * NOTE: `Legacy` describes a DECISION's standing, not a filename. The
51
+ * `0001-`..`0012-` sequential *naming* era is legacy, but many of those ADRs
52
+ * (e.g. 0002, 0004, 0008, 0009) are Accepted and load-bearing today. Do not
53
+ * conflate the two: grep the naming rule in README.md, not this enum.
54
+ */
55
+ const STATUSES = ['Accepted', 'Proposed', 'Superseded', 'Legacy', 'Retired'];
56
+
57
+ /**
58
+ * Header fields that assert a lifecycle relation.
59
+ *
60
+ * Two DISTINCT relations, deliberately not conflated:
61
+ *
62
+ * supersedes — the target decision is REPLACED. The target's status becomes
63
+ * Superseded and it must name this ADR. (ADR-0174 → ADR-0005.)
64
+ *
65
+ * subsumes — the target decision still HOLDS, but a broader ADR now frames
66
+ * it; the target keeps its Accepted status and becomes a component of the
67
+ * larger decision. (ADR-1239/EoS subsumes ADR-1016 "as the declarative
68
+ * adapter" — the descriptor is still real and still correct.)
69
+ *
70
+ * Both directions are symmetry-checked, but only `supersedes` implies a status
71
+ * change on the target. Collapsing subsumption into supersession would mark
72
+ * four live, load-bearing ADRs as dead — the opposite of the truth.
73
+ */
74
+ const RELATION_FIELDS = new Map([
75
+ ['supersedes', { kind: 'supersedes', dir: 'out' }],
76
+ ['superseded by', { kind: 'supersedes', dir: 'in' }],
77
+ ['subsumes', { kind: 'subsumes', dir: 'out' }],
78
+ ['subsumed by', { kind: 'subsumes', dir: 'in' }],
79
+ ]);
80
+
81
+ /** Relation kinds and the header field a reader should add to fix each gap. */
82
+ const RELATION_SPEC = {
83
+ supersedes: { out: 'Supersedes', in: 'Superseded by' },
84
+ subsumes: { out: 'Subsumes', in: 'Subsumed by' },
85
+ };
86
+
87
+ /**
88
+ * A relation field whose value opens with "nothing"/"none"/"n/a" asserts the
89
+ * absence of the relation, whatever prose follows it.
90
+ */
91
+ const NEGATED_RELATION_RE = /^\s*(?:nothing|none|n\/a|[—–-])\s*(?:$|[;,.]|\s)/i;
92
+
93
+ /**
94
+ * Header fields appear in two shapes across the corpus, both legitimate:
95
+ * bullet — `- **Status:** Accepted`
96
+ * table — `| **Status** | Accepted |`
97
+ * Yield [field, value] for either.
98
+ */
99
+ function* headerFields(header) {
100
+ const bullet = /^\s*[-*]\s*\*\*([^*:]+?)(?::)?\*\*\s*(.*)$/gm;
101
+ let m;
102
+ while ((m = bullet.exec(header)) !== null) yield [m[1].trim(), m[2].trim()];
103
+
104
+ const row = /^\s*\|\s*\*\*([^*|]+?)(?::)?\*\*\s*\|\s*(.*?)\s*\|\s*$/gm;
105
+ while ((m = row.exec(header)) !== null) yield [m[1].trim(), m[2].trim()];
106
+ }
107
+
108
+ /** Numeric identity of an ADR: "0011" and "11" are the same id. */
109
+ function canonicalId(raw) {
110
+ return String(raw).replace(/^0+(?=\d)/, '');
111
+ }
112
+
113
+ /** The documented filename shape: `<issue#>-<kebab-slug>.md`. */
114
+ const ADR_FILENAME_RE = /^[0-9]+-[a-z0-9-]+\.md$/;
115
+
116
+ function adrFiles() {
117
+ return fs
118
+ .readdirSync(ADR_DIR)
119
+ .filter((f) => f.endsWith('.md') && f !== 'README.md')
120
+ .filter((f) => fs.statSync(path.join(ADR_DIR, f)).isFile())
121
+ .sort();
122
+ }
123
+
124
+ /**
125
+ * Split the directory into files this tool can parse and files it cannot.
126
+ *
127
+ * A file without a numeric prefix is not merely unparseable — it is invisible
128
+ * to the index, which is the failure this gate exists to prevent. Report it as
129
+ * a violation naming the convention, rather than crashing on `match(...)[1]`
130
+ * or silently skipping it.
131
+ */
132
+ function partitionAdrFiles() {
133
+ const conforming = [];
134
+ const nonConforming = [];
135
+ for (const f of adrFiles()) (ADR_FILENAME_RE.test(f) ? conforming : nonConforming).push(f);
136
+ return { conforming, nonConforming };
137
+ }
138
+
139
+ /** Extract the leading bullet-field header block (everything before the first `##`). */
140
+ function headerBlock(text) {
141
+ const body = text.split(/\r?\n/);
142
+ const stop = body.findIndex((l) => /^##\s/.test(l));
143
+ return (stop === -1 ? body : body.slice(0, stop)).join('\n');
144
+ }
145
+
146
+ /**
147
+ * A relation may also be declared as a whole SECTION rather than a header field.
148
+ * ADR-0174 is the exemplar: a `## Supersedes` heading over a table whose first
149
+ * column links each superseded ADR and whose remaining columns explain why.
150
+ * That is the richest form in the corpus and must count — reading only the
151
+ * header block would report the repo's best-documented supersession as missing.
152
+ *
153
+ * Returns { supersedes: [file…], subsumes: [file…] } from matching sections.
154
+ */
155
+ const RELATION_SECTION_RE = /^##\s+(Supersedes|Subsumes)\b[^\n]*$/i;
156
+
157
+ function relationSections(text) {
158
+ const lines = text.split(/\r?\n/);
159
+ const out = { supersedes: [], subsumes: [] };
160
+ for (let i = 0; i < lines.length; i++) {
161
+ const m = lines[i].match(RELATION_SECTION_RE);
162
+ if (!m) continue;
163
+ const kind = m[1].toLowerCase() === 'supersedes' ? 'supersedes' : 'subsumes';
164
+ // Collect until the next heading of any level.
165
+ let j = i + 1;
166
+ const body = [];
167
+ for (; j < lines.length && !/^#{1,6}\s/.test(lines[j]); j++) body.push(lines[j]);
168
+ const chunk = body.join('\n');
169
+ if (NEGATED_RELATION_RE.test(chunk.trim())) continue;
170
+ out[kind].push(...linkedAdrFiles(chunk));
171
+ i = j - 1;
172
+ }
173
+ return out;
174
+ }
175
+
176
+ /** All markdown links to sibling ADR files inside a chunk of text. */
177
+ function linkedAdrFiles(text) {
178
+ const out = [];
179
+ const re = /\]\(\s*(?:\.\/)?([0-9]+-[a-z0-9-]+\.md)\s*\)/gi;
180
+ let m;
181
+ while ((m = re.exec(text)) !== null) out.push(m[1]);
182
+ return out;
183
+ }
184
+
185
+ /** Bare `ADR-123` / `ADR 123` mentions that are NOT part of a markdown link. */
186
+ function bareAdrRefs(text) {
187
+ const withoutLinks = text.replace(/\[[^\]]*\]\([^)]*\)/g, '');
188
+ const out = [];
189
+ const re = /\bADR[-\s]0*(\d+)\b/gi;
190
+ let m;
191
+ while ((m = re.exec(withoutLinks)) !== null) out.push(canonicalId(m[1]));
192
+ return out;
193
+ }
194
+
195
+ function parseAdr(file) {
196
+ const full = path.join(ADR_DIR, file);
197
+ const text = fs.readFileSync(full, 'utf8');
198
+ const lines = text.split(/\r?\n/);
199
+
200
+ // `fileId` is the numeric identity used for comparison ("0011" === "11");
201
+ // `displayId` preserves the filename's prefix exactly as written, because the
202
+ // corpus and its cross-references say "ADR-0001" and "ADR-58", not "ADR-1".
203
+ const rawId = file.match(/^([0-9]+)-/)[1];
204
+ const fileId = canonicalId(rawId);
205
+ const displayId = rawId;
206
+
207
+ const h1 = (lines.find((l) => /^#\s/.test(l)) || '').replace(/^#\s+/, '').trim();
208
+ // Title as displayed: drop a leading "ADR-123 — " / "ADR-123: " prefix and a
209
+ // trailing "[Proposed]"-style status bracket, both of which the index renders
210
+ // from structured fields instead.
211
+ const title = h1
212
+ .replace(/^ADR[-\s]?0*\d+\s*(?:[—:-]\s*)?/i, '')
213
+ .replace(/\s*\[(?:Proposed|Accepted|Superseded|Legacy|Retired)\]\s*$/i, '')
214
+ .trim();
215
+
216
+ const declaredIdMatch = h1.match(/^ADR[-\s]?0*(\d+)\b/i);
217
+ const declaredId = declaredIdMatch ? canonicalId(declaredIdMatch[1]) : null;
218
+
219
+ const header = headerBlock(text);
220
+
221
+ let statusRaw = null;
222
+ // relations[kind][dir] = [{field, value, links, bare}]
223
+ const relations = { supersedes: { out: [], in: [] }, subsumes: { out: [], in: [] } };
224
+
225
+ for (const [field, value] of headerFields(header)) {
226
+ if (field.toLowerCase() === 'status') {
227
+ if (statusRaw === null) statusRaw = value;
228
+ continue;
229
+ }
230
+ // "Supersedes (generalizes)" / "Subsumes as adapters" → "supersedes" / "subsumes"
231
+ const key = field.toLowerCase().replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+as\s+.*$/, '').trim();
232
+ const spec = RELATION_FIELDS.get(key);
233
+ if (!spec) continue;
234
+ // "Supersedes: nothing; amends the ADR-1239 harness" asserts NO relation. Such a
235
+ // field routinely name-drops other ADRs in its prose ("related", "amends", "builds
236
+ // on"); reading those as supersession claims invents links that were never made.
237
+ if (NEGATED_RELATION_RE.test(value)) continue;
238
+ relations[spec.kind][spec.dir].push({ field, value, links: linkedAdrFiles(value), bare: bareAdrRefs(value) });
239
+ }
240
+
241
+ const statusToken = statusRaw ? (statusRaw.match(/^([A-Za-z]+)/) || [])[1] : null;
242
+
243
+ // A "Superseded by X" written into the Status line itself is the relation.
244
+ if (statusRaw && /^Superseded\b/i.test(statusRaw)) {
245
+ relations.supersedes.in.push({ field: 'Status', value: statusRaw, links: linkedAdrFiles(statusRaw), bare: bareAdrRefs(statusRaw) });
246
+ }
247
+
248
+ // `## Supersedes` / `## Subsumes` sections count as OUT claims (ADR-0174's table).
249
+ const sections = relationSections(text);
250
+ for (const kind of ['supersedes', 'subsumes']) {
251
+ if (sections[kind].length === 0) continue;
252
+ relations[kind].out.push({ field: `## ${kind === 'supersedes' ? 'Supersedes' : 'Subsumes'} section`, value: '', links: sections[kind], bare: [] });
253
+ }
254
+
255
+ return { file, fileId, displayId, title, declaredId, statusRaw, statusToken, relations, text };
256
+ }
257
+
258
+ function buildCorpus() {
259
+ const { conforming, nonConforming } = partitionAdrFiles();
260
+ const adrs = conforming.map(parseAdr);
261
+ const byFile = new Map(adrs.map((a) => [a.file, a]));
262
+ const byId = new Map();
263
+ for (const a of adrs) {
264
+ if (!byId.has(a.fileId)) byId.set(a.fileId, []);
265
+ byId.get(a.fileId).push(a);
266
+ }
267
+ return { adrs, byFile, byId, nonConforming };
268
+ }
269
+
270
+ function validate({ adrs, byFile, byId, nonConforming }) {
271
+ const errors = [];
272
+ const add = (file, msg) => errors.push(`${file}: ${msg}`);
273
+
274
+ for (const f of nonConforming) {
275
+ add(
276
+ f,
277
+ 'filename does not match the `<issue#>-<kebab-slug>.md` convention, so it cannot appear in the index. ' +
278
+ 'Rename it (see docs/adr/README.md "Naming Convention"), or move it out of docs/adr/ if it is not an ADR.',
279
+ );
280
+ }
281
+
282
+ for (const a of adrs) {
283
+ if (!a.statusToken) {
284
+ add(a.file, 'no `- **Status:** <Token>` field found in the header block.');
285
+ continue;
286
+ }
287
+ if (!STATUSES.includes(a.statusToken)) {
288
+ add(a.file, `status "${a.statusToken}" is not one of ${STATUSES.join(' | ')} (full line: "${a.statusRaw}").`);
289
+ }
290
+ if (a.declaredId && a.declaredId !== a.fileId) {
291
+ add(a.file, `H1 declares ADR-${a.declaredId} but the filename says ${a.fileId}. The id must match the filename.`);
292
+ }
293
+
294
+ // A Superseded ADR must point at its successor by FILE LINK.
295
+ if (a.statusToken === 'Superseded') {
296
+ const links = a.relations.supersedes.in.flatMap((r) => r.links);
297
+ if (links.length === 0) {
298
+ const bare = a.relations.supersedes.in.flatMap((r) => r.bare);
299
+ add(
300
+ a.file,
301
+ bare.length
302
+ ? `status is Superseded and mentions ADR-${bare.join('/')} but not as a markdown link to the file. ` +
303
+ 'Bare ids are ambiguous (ADR-0010 and ADR-0011 each resolve to multiple files) — link the target file.'
304
+ : 'status is Superseded but names no successor. Write `Superseded by [ADR-N](N-slug.md)`.',
305
+ );
306
+ }
307
+ }
308
+
309
+ // Every relation link must resolve; every bare id must be linked (and exist).
310
+ for (const kind of Object.keys(RELATION_SPEC)) {
311
+ for (const dir of ['out', 'in']) {
312
+ for (const rel of a.relations[kind][dir]) {
313
+ for (const l of rel.links) {
314
+ if (!byFile.has(l)) add(a.file, `"${rel.field}" links "${l}", which does not exist in docs/adr/.`);
315
+ }
316
+ // The synthetic relation lifted out of the Status line is already covered by
317
+ // the dedicated Superseded check above; reporting it again just duplicates.
318
+ if (rel.field === 'Status') continue;
319
+ // Ids already linked ANYWHERE in this field. A field legitimately
320
+ // reads "…([ADR-58](58-x.md)) — see 'Relation to ADR-58' below": the
321
+ // trailing prose repeats an id that is linked earlier, and flagging
322
+ // that would be noise. But an id that appears ONLY bare is an
323
+ // unchecked claim — and testing `rel.links.length` instead of the
324
+ // specific id silently dropped every bare claim in a field that
325
+ // happened to carry one link.
326
+ const linkedIds = new Set(rel.links.map((l) => (byFile.get(l) || {}).fileId).filter(Boolean));
327
+ for (const b of rel.bare) {
328
+ if (linkedIds.has(b)) continue;
329
+ const candidates = byId.get(b) || [];
330
+ if (candidates.length === 0) {
331
+ add(a.file, `"${rel.field}" names ADR-${b}, which does not exist in docs/adr/. If it is an ISSUE number, write "#${b}" — not "ADR-${b}".`);
332
+ } else {
333
+ add(
334
+ a.file,
335
+ `"${rel.field}" names ADR-${b} without a file link` +
336
+ (candidates.length > 1 ? ` (ambiguous — resolves to ${candidates.length} files: ${candidates.map((c) => c.file).join(', ')})` : '') +
337
+ '. Link the target file so the relation is checkable.',
338
+ );
339
+ }
340
+ }
341
+ }
342
+ }
343
+ }
344
+ }
345
+
346
+ // Symmetry, per relation kind: A -out-> B <=> B -in-> A.
347
+ //
348
+ // Only a RATIFIED (Accepted) claimant is owed the back-link. A Proposed ADR's
349
+ // supersession claim is prospective — it has not taken effect, so stamping its
350
+ // target as superseded would assert something untrue (ADR-857 is Proposed and
351
+ // claims to generalize ADR-0011/ADR-58, both of which are Accepted and live).
352
+ // When such an ADR is ratified to Accepted, this check starts demanding the
353
+ // back-links at exactly the right moment.
354
+ const OPPOSITE = { out: 'in', in: 'out' };
355
+ for (const a of adrs) {
356
+ for (const kind of Object.keys(RELATION_SPEC)) {
357
+ for (const dir of ['out', 'in']) {
358
+ // The ratification guard applies to the OUT direction only: an unratified
359
+ // ADR's claim over someone else is prospective and must not obligate the
360
+ // target. The IN direction is this ADR's statement about ITSELF ("I am
361
+ // superseded by X") and is always owed a reciprocal — guarding it too
362
+ // would skip every Superseded ADR (statusToken !== 'Accepted') and leave
363
+ // dangling one-way claims unchecked, which is the bug this gate exists
364
+ // to catch.
365
+ if (dir === 'out' && a.statusToken !== 'Accepted') continue;
366
+ for (const target of new Set(a.relations[kind][dir].flatMap((r) => r.links))) {
367
+ const b = byFile.get(target);
368
+ if (!b) continue;
369
+ const back = new Set(b.relations[kind][OPPOSITE[dir]].flatMap((r) => r.links));
370
+ if (back.has(a.file)) continue;
371
+ const needed = RELATION_SPEC[kind][OPPOSITE[dir]];
372
+ const claim = dir === 'out' ? `it ${kind} this ADR` : `it is ${kind === 'supersedes' ? 'superseded' : 'subsumed'} by this ADR`;
373
+ add(
374
+ target,
375
+ `${a.file} declares ${claim}, but this ADR does not record it. ` +
376
+ `Add \`- **${needed}:** [ADR-${a.displayId}](${a.file})\` so a reader of THIS file learns the decision moved on.`,
377
+ );
378
+ }
379
+ }
380
+ }
381
+ }
382
+
383
+ return errors;
384
+ }
385
+
386
+ const GROUPS = [
387
+ {
388
+ heading: 'Active decisions',
389
+ blurb: 'These govern the system as it stands. Cite these.',
390
+ match: (a) => a.statusToken === 'Accepted',
391
+ },
392
+ {
393
+ heading: 'Proposed',
394
+ blurb: 'Decided in principle, not yet ratified. Do not cite as settled architecture.',
395
+ match: (a) => a.statusToken === 'Proposed',
396
+ },
397
+ {
398
+ heading: 'Superseded, Retired, and Legacy',
399
+ blurb: 'Historical record. **Do not follow these** — each names what replaced it, or why it was retired.',
400
+ match: (a) => ['Superseded', 'Retired', 'Legacy'].includes(a.statusToken),
401
+ },
402
+ ];
403
+
404
+ /**
405
+ * Render ADR-authored text (a title) into a markdown table cell.
406
+ *
407
+ * Three hazards, all from text this script does not control:
408
+ * - `|` would split the cell and corrupt the row.
409
+ * - An HTML comment would be emitted verbatim into README.md. A title
410
+ * containing the END marker relocates it, so the NEXT `--write` splices
411
+ * against the wrong boundary and silently eats the rest of the file.
412
+ * Escaping `<`/`>` makes a comment sequence unformable, which also blocks
413
+ * any other HTML injected through a title.
414
+ * - A backslash is markdown's own escape character, so it MUST be escaped
415
+ * first. Escaping `|` → `\|` without it turns the input `\|` into `\\|`,
416
+ * which markdown reads as a literal backslash followed by an UNESCAPED
417
+ * pipe — re-opening the cell break the pipe escape exists to prevent.
418
+ * Order is load-bearing: backslash first, then everything that emits one.
419
+ */
420
+ function cellText(text) {
421
+ return String(text)
422
+ .replace(/\\/g, '\\\\')
423
+ .replace(/\|/g, '\\|')
424
+ .replace(/</g, '&lt;')
425
+ .replace(/>/g, '&gt;')
426
+ .replace(/\r?\n/g, ' ')
427
+ .trim();
428
+ }
429
+
430
+ function linkCell(files, byFile) {
431
+ if (files.length === 0) return '—';
432
+ return files.map((l) => `[ADR-${(byFile.get(l) || {}).displayId || '?'}](${l})`).join(', ');
433
+ }
434
+
435
+ function renderIndex(corpus) {
436
+ const { byFile } = corpus;
437
+ const out = [START_MARKER, ''];
438
+
439
+ for (const g of GROUPS) {
440
+ const rows = corpus.adrs.filter(g.match).sort((x, y) => Number(x.fileId) - Number(y.fileId));
441
+ if (rows.length === 0) continue;
442
+
443
+ out.push(`### ${g.heading} (${rows.length})`, '', g.blurb, '');
444
+ const isHistorical = g.heading.startsWith('Superseded');
445
+ // "Read first" points at the broader ADR that now frames this one. It is how a
446
+ // reader of a still-Accepted component decision (e.g. the runtime descriptor)
447
+ // discovers the wider decision that reframed it (e.g. EoS) instead of assuming
448
+ // the component IS the architecture.
449
+ out.push(
450
+ isHistorical ? '| ADR | Title | Status | Replaced by |' : '| ADR | Title | Status | Read first |',
451
+ isHistorical ? '|-----|-------|--------|-------------|' : '|-----|-------|--------|------------|',
452
+ );
453
+ for (const a of rows) {
454
+ const cells = [`[ADR-${a.displayId}](${a.file})`, cellText(a.title), a.statusToken];
455
+ cells.push(
456
+ isHistorical
457
+ ? linkCell([...new Set(a.relations.supersedes.in.flatMap((r) => r.links))], byFile)
458
+ : linkCell([...new Set(a.relations.subsumes.in.flatMap((r) => r.links))], byFile),
459
+ );
460
+ out.push(`| ${cells.join(' | ')} |`);
461
+ }
462
+ out.push('');
463
+ }
464
+
465
+ out.push(
466
+ `_${corpus.adrs.length} ADRs. Generated by \`scripts/gen-adr-index.cjs\` — run \`--write\` after adding or restatusing an ADR._`,
467
+ '',
468
+ END_MARKER,
469
+ );
470
+ return out.join('\n');
471
+ }
472
+
473
+ function spliceIntoReadme(readme, index) {
474
+ const start = readme.indexOf(START_MARKER);
475
+ const end = readme.indexOf(END_MARKER);
476
+ if (start === -1 || end === -1) {
477
+ throw new ExitError(
478
+ 1,
479
+ `docs/adr/README.md is missing the index markers.\nExpected:\n ${START_MARKER}\n ${END_MARKER}\n`,
480
+ );
481
+ }
482
+ return readme.slice(0, start) + index + readme.slice(end + END_MARKER.length);
483
+ }
484
+
485
+ function main() {
486
+ const [, , flag] = process.argv;
487
+
488
+ const corpus = buildCorpus();
489
+ const errors = validate(corpus);
490
+
491
+ if (errors.length > 0 && flag !== '--write') {
492
+ process.stderr.write(
493
+ `docs/adr/ has ${errors.length} lifecycle violation(s).\n` +
494
+ 'See docs/adr/README.md "Lifecycle rules" for the contract.\n\n',
495
+ );
496
+ for (const e of errors) process.stderr.write(` ✗ ${e}\n`);
497
+ process.stderr.write('\n');
498
+ throw new ExitError(1);
499
+ }
500
+
501
+ const index = renderIndex(corpus);
502
+
503
+ if (flag === '--check') {
504
+ const readme = fs.readFileSync(README_PATH, 'utf8');
505
+ const expected = spliceIntoReadme(readme, index);
506
+ if (expected !== readme) {
507
+ process.stderr.write(
508
+ 'docs/adr/README.md index is stale. Run:\n node scripts/gen-adr-index.cjs --write\n\n',
509
+ );
510
+ throw new ExitError(1);
511
+ }
512
+ process.stdout.write(`docs/adr/README.md index is up to date (${corpus.adrs.length} ADRs).\n`);
513
+ } else if (flag === '--write') {
514
+ const readme = fs.readFileSync(README_PATH, 'utf8');
515
+ fs.writeFileSync(README_PATH, spliceIntoReadme(readme, index));
516
+ process.stdout.write(`Wrote ADR index into ${README_PATH} (${corpus.adrs.length} ADRs).\n`);
517
+ if (errors.length > 0) {
518
+ process.stderr.write(`\n${errors.length} lifecycle violation(s) remain — --check will fail:\n\n`);
519
+ for (const e of errors) process.stderr.write(` ✗ ${e}\n`);
520
+ }
521
+ } else {
522
+ process.stdout.write(index + '\n');
523
+ }
524
+ }
525
+
526
+ runMain(main);