@sabaiway/agent-workflow-kit 20.2.0 → 22.0.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 (98) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +7 -5
  3. package/SKILL.md +1 -1
  4. package/bin/install.mjs +10 -11
  5. package/capability.json +1 -1
  6. package/launchers/windsurf-workflow.md +3 -1
  7. package/migrations/3.0.0-hardened-core-loop.md +7 -6
  8. package/package.json +5 -2
  9. package/references/advisor-writers.md +1 -1
  10. package/references/contracts.md +11 -10
  11. package/references/modes/bootstrap.md +3 -3
  12. package/references/modes/commit-guard.md +1 -1
  13. package/references/modes/gates.md +2 -2
  14. package/references/modes/recommendations.md +3 -3
  15. package/references/modes/upgrade.md +6 -6
  16. package/references/scripts/{archive-caps.mjs → archives/archive-caps.mjs} +1 -1
  17. package/references/scripts/{archive-changelog.mjs → archives/archive-changelog.mjs} +7 -9
  18. package/references/scripts/{archive-decisions.mjs → archives/archive-decisions.mjs} +13 -10
  19. package/references/scripts/{archive-issues.mjs → archives/archive-issues.mjs} +7 -8
  20. package/references/scripts/{check-docs-size.mjs → docs-size/check-docs-size.mjs} +3 -4
  21. package/references/scripts/docs-size/index.mjs +2 -0
  22. package/references/scripts/family.json +45 -0
  23. package/references/scripts/family.mjs +90 -0
  24. package/references/scripts/gates/kit-command-gates.mjs +117 -0
  25. package/references/scripts/{migrate-gates.mjs → gates/migrate-gates.mjs} +263 -182
  26. package/references/scripts/{install-git-hooks.mjs → git-hooks/install-git-hooks.mjs} +50 -38
  27. package/references/scripts/run.mjs +90 -0
  28. package/references/scripts/shared/index.mjs +3 -0
  29. package/references/scripts/shared/project-root.mjs +11 -0
  30. package/references/scripts/spec-schema/index.mjs +2 -0
  31. package/references/scripts/test-reporter/reporter.mjs +130 -0
  32. package/references/shared/composition-handoff.md +1 -1
  33. package/references/shared/deploy-tail.md +2 -2
  34. package/references/templates/SPEC_TEMPLATE.md +1 -1
  35. package/references/templates/adr-record.md +3 -3
  36. package/tools/apply-danger-check.mjs +9 -5
  37. package/tools/atomic-write.mjs +3 -1
  38. package/tools/coverage-producer.mjs +76 -41
  39. package/tools/direct-run.mjs +2 -0
  40. package/tools/distribution-files/retired.mjs +99 -0
  41. package/tools/distribution-files/scripts.mjs +68 -52
  42. package/tools/ensure-configs.mjs +21 -21
  43. package/tools/ensure-ops.mjs +60 -18
  44. package/tools/ensure-specs.mjs +85 -47
  45. package/tools/ensure-vocabulary.mjs +4 -4
  46. package/tools/epic-shape-cli.mjs +1 -1
  47. package/tools/epic-shape-ledger.mjs +1 -1
  48. package/tools/epic-shape.mjs +1 -1
  49. package/tools/family-registry.mjs +3 -1
  50. package/tools/feedback-record-cli.mjs +1 -1
  51. package/tools/fold-scope.mjs +2 -2
  52. package/tools/gates-declaration.mjs +22 -14
  53. package/tools/gates-init.mjs +33 -17
  54. package/tools/git-hooks.mjs +90 -65
  55. package/tools/jev-connect.mjs +1 -1
  56. package/tools/jev-guide.mjs +1 -1
  57. package/tools/jev-skill.mjs +1 -1
  58. package/tools/known-footprint.mjs +7 -29
  59. package/tools/node-evidence.mjs +29 -15
  60. package/tools/now-cli.mjs +1 -1
  61. package/tools/payload-prune.mjs +53 -58
  62. package/tools/plan-shape-cli.mjs +1 -1
  63. package/tools/plan-shape.mjs +1 -1
  64. package/tools/project-rules/rules-record.mjs +1 -1
  65. package/tools/queue-audit-cli.mjs +1 -1
  66. package/tools/queue-audit.mjs +2 -2
  67. package/tools/queue-purge-archive.mjs +1 -1
  68. package/tools/queue-purge-cli.mjs +1 -1
  69. package/tools/queue-purge.mjs +1 -1
  70. package/tools/recommendations.mjs +37 -25
  71. package/tools/script-priors.mjs +31 -3
  72. package/tools/source-size/piles.mjs +1 -1
  73. package/tools/spec-adoption.mjs +1 -1
  74. package/tools/spec-check-ops.mjs +2 -2
  75. package/tools/spec-check.mjs +2 -2
  76. package/tools/spec-coverage.mjs +1 -1
  77. package/tools/tier-guide.mjs +1 -1
  78. package/tools/transition/index.mjs +1 -1
  79. package/tools/upgrade-runlist.mjs +3 -3
  80. package/tools/write-lanes.mjs +2 -2
  81. package/references/scripts/_expect-shim.mjs +0 -41
  82. package/references/scripts/archive-caps.test.mjs +0 -321
  83. package/references/scripts/archive-changelog.test.mjs +0 -560
  84. package/references/scripts/archive-conservation.test.mjs +0 -466
  85. package/references/scripts/archive-decisions.test.mjs +0 -1503
  86. package/references/scripts/archive-issues.test.mjs +0 -825
  87. package/references/scripts/archiver-structure.test.mjs +0 -84
  88. package/references/scripts/check-docs-size-cli.test.mjs +0 -325
  89. package/references/scripts/check-docs-size-ensure.test.mjs +0 -360
  90. package/references/scripts/check-docs-size.test.mjs +0 -395
  91. package/references/scripts/install-git-hooks-repo-exec.test.mjs +0 -185
  92. package/references/scripts/install-git-hooks.test.mjs +0 -241
  93. package/references/scripts/markdown-blocks.test.mjs +0 -310
  94. package/references/scripts/migrate-gates-branches.test.mjs +0 -302
  95. package/references/scripts/migrate-gates.test.mjs +0 -517
  96. package/references/scripts/spec-schema.test.mjs +0 -352
  97. /package/references/scripts/{markdown-blocks.mjs → shared/markdown-blocks.mjs} +0 -0
  98. /package/references/scripts/{spec-schema.mjs → spec-schema/spec-schema.mjs} +0 -0
@@ -1,1503 +0,0 @@
1
- import { describe, it, afterEach } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync, readdirSync, symlinkSync } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { join, dirname } from 'node:path';
6
- import {
7
- HOT_REL,
8
- WARM_REL,
9
- COLD_REL,
10
- ADR_DIR_REL,
11
- NAV_REL,
12
- HEADING_RE,
13
- RECORD_CAP,
14
- parseDecisionsText,
15
- slugify,
16
- recordFileName,
17
- explode,
18
- blockHash,
19
- verifyConservation,
20
- computeSupersededSet,
21
- buildNavigator,
22
- loadAdrStore,
23
- lineCountOf,
24
- runCli,
25
- defaultRegenerateIndex,
26
- verifyRewriteConservation,
27
- writeInboundRewrites,
28
- } from './archive-decisions.mjs';
29
-
30
- // Hermetic: this test ships as deploy payload and runs inside CONSUMER repos via the pre-commit
31
- // `node --test scripts/*.test.mjs` — it must never read the host repo's docs/ai. Every fixture lives
32
- // in a fresh temp root; the index-regen hook + the git-dir snapshot are always injected.
33
-
34
- const tempDirs = [];
35
- const makeRoot = () => {
36
- const dir = mkdtempSync(join(tmpdir(), 'archive-decisions-'));
37
- tempDirs.push(dir);
38
- return dir;
39
- };
40
- afterEach(() => {
41
- while (tempDirs.length) rmSync(tempDirs.pop(), { recursive: true, force: true });
42
- });
43
-
44
- const fm = (cap) =>
45
- `---\ntype: reference\nlastUpdated: 2026-01-01\nscope: permanent\nstaleAfter: never\nowner: none\nmaxLines: ${cap}\n---\n`;
46
-
47
- // One canonical ADR block. `status: null` omits the status line (the 6-of-9-active default case);
48
- // `separate: true` writes Date and Status on their own lines (the AD-001/AD-043 shape).
49
- const adrBlock = (id, { title = `Decision ${id}`, date = '2026-01-01', status = 'Accepted', body = 2, separate = false } = {}) => {
50
- const lines = [`## AD-${id} — ${title}`, ''];
51
- if (separate) {
52
- if (date) lines.push(`**Date:** ${date}`);
53
- if (status) lines.push(`**Status:** ${status}`);
54
- } else if (date || status) {
55
- lines.push(`**Date:** ${date}${status ? ` · **Status:** ${status}` : ''}`);
56
- }
57
- lines.push('');
58
- for (let i = 0; i < body; i += 1) lines.push(`body ${i + 1} of AD-${id}`);
59
- return lines.join('\n');
60
- };
61
-
62
- const tierText = (cap, preamble, blocks) => `${fm(cap)}\n${preamble}\n\n${blocks.join('\n\n')}\n`;
63
-
64
- const HOT_PREAMBLE = [
65
- '# Architecture Decision Records (ADRs)',
66
- '',
67
- '> Newest at the bottom. Link related ADRs with `[[AD-XXX]]`.',
68
- '>',
69
- '> **Archive:** the stable **AD-003 … AD-004** now live in [`history/decisions-archive.md`](./history/decisions-archive.md) (the earliest **AD-001 … AD-002** rolled further to the COLD [`history/decisions-archive-early.md`](./history/decisions-archive-early.md)); this file carries the active set (AD-005 onward).',
70
- ].join('\n');
71
- const WARM_PREAMBLE = '# ADR Archive (AD-003 … AD-004)\n\n> WARM tier.';
72
- const COLD_PREAMBLE = '# ADR Early Archive (AD-001 … AD-002)\n\n> COLD tier.';
73
-
74
- // Seed a legacy 3-tier tree (pre-migration). Caps generous so nothing overflows unless asked.
75
- const seedLegacy = (root, { hot, warm = [], cold = [], hotCapDelta = 200 }) => {
76
- mkdirSync(join(root, 'docs', 'ai', 'history'), { recursive: true });
77
- const writeTier = (rel, preamble, blocks, capDelta) => {
78
- const probe = tierText(9999, preamble, blocks);
79
- const cap = lineCountOf(probe) + capDelta;
80
- writeFileSync(join(root, rel), tierText(cap, preamble, blocks));
81
- return cap;
82
- };
83
- const hotBlocks = hot.map((spec) => (typeof spec === 'string' ? adrBlock(spec) : adrBlock(spec.id, spec)));
84
- const warmBlocks = warm.map((spec) => (typeof spec === 'string' ? adrBlock(spec) : adrBlock(spec.id, spec)));
85
- const coldBlocks = cold.map((spec) => (typeof spec === 'string' ? adrBlock(spec) : adrBlock(spec.id, spec)));
86
- return {
87
- hotCap: writeTier(HOT_REL, HOT_PREAMBLE, hotBlocks, hotCapDelta),
88
- warmCap: warm.length ? writeTier(WARM_REL, WARM_PREAMBLE, warmBlocks, 200) : null,
89
- coldCap: cold.length ? writeTier(COLD_REL, COLD_PREAMBLE, coldBlocks, 200) : null,
90
- };
91
- };
92
-
93
- const fakeGit = (root) => (cmd) => (cmd === 'git' ? { status: 0, stdout: `${join(root, '.git')}\n` } : { status: 1 });
94
- const noGit = () => ({ status: 1 });
95
-
96
- const run = (argv, root, opts = {}) => {
97
- const out = [];
98
- const err = [];
99
- const calls = [];
100
- const regen = opts.regen ?? ((r, t) => { calls.push([r, t]); return { ok: true, detail: '' }; });
101
- const code = runCli(argv, {
102
- root,
103
- log: (l) => out.push(l),
104
- logError: (l) => err.push(l),
105
- regenerateIndex: regen,
106
- stamp: opts.stamp ?? 'STAMP',
107
- snapshotFallbackBase: opts.fallbackBase,
108
- spawnSync: opts.spawnSync ?? fakeGit(root),
109
- });
110
- return { code, out, err, text: out.join('\n'), errText: err.join('\n'), regenCalls: calls };
111
- };
112
-
113
- const adrFiles = (root) => (existsSync(join(root, ADR_DIR_REL)) ? readdirSync(join(root, ADR_DIR_REL)).filter((n) => /^AD-\d{3,}-/.test(n)).sort() : []);
114
- const idsIn = (root, rel) => parseDecisionsText(readFileSync(join(root, rel), 'utf8'), rel).entries.map((e) => e.id);
115
-
116
- // ── tokenizer contract (Phase 2) — fences, CRLF and mis-levelled AD headings ──────────
117
- //
118
- // The parser reads through markdown-blocks.mjs: a `## ` line inside a fenced sample is BODY (the
119
- // shipped false-refusal — an ADR documenting the changelog heading format was refused), an
120
- // unclosed fence is loud, CRLF never changes a parse, and an AD-shaped heading at the wrong level
121
- // or indent refuses instead of being silently absorbed as body text.
122
-
123
- describe('tokenizer contract — fences, CRLF and mis-levelled AD headings', () => {
124
- const refusal = (fn) => {
125
- let threw = null;
126
- try {
127
- fn();
128
- } catch (err) {
129
- threw = err;
130
- }
131
- assert.ok(threw, 'expected a typed refusal');
132
- assert.equal(threw.exitCode, 1, `a refusal carries exitCode 1 (${threw.message})`);
133
- return threw;
134
- };
135
-
136
- it('an ADR documenting the changelog format parses — a fenced non-AD sample is body', () => {
137
- const block = [
138
- '## AD-050 — documents the changelog heading format',
139
- '',
140
- '**Date:** 2026-01-01 · **Status:** Accepted',
141
- '',
142
- 'Write entries like:',
143
- '',
144
- '```markdown',
145
- '## 2026-07-20 — an example entry',
146
- '```',
147
- '',
148
- 'end.',
149
- ].join('\n');
150
- const p = parseDecisionsText(tierText(500, '# T', [block]), 'x');
151
- assert.deepEqual(p.entries.map((e) => e.id), ['050']);
152
- assert.match(p.entries[0].block, /## 2026-07-20 — an example entry/);
153
- });
154
-
155
- it('a fenced AD-heading sample never splits the enclosing block either', () => {
156
- const block = [
157
- '## AD-050 — shows a record heading',
158
- '',
159
- '```markdown',
160
- '## AD-999 — a sample record heading',
161
- '```',
162
- '',
163
- 'end.',
164
- ].join('\n');
165
- const p = parseDecisionsText(tierText(500, '# T', [block]), 'x');
166
- assert.deepEqual(p.entries.map((e) => e.id), ['050']);
167
- assert.match(p.entries[0].block, /AD-999/);
168
- });
169
-
170
- it('an unclosed fence refuses loudly instead of being scanned through', () => {
171
- const block = ['## AD-050 — opens a fence', '', '```markdown', '## AD-051 — hidden behind it'].join('\n');
172
- const err = refusal(() => parseDecisionsText(tierText(500, '# T', [block]), 'x'));
173
- assert.match(err.message, /never closed/);
174
- });
175
-
176
- it('an AD-shaped heading at the wrong level or indent refuses naming file and line', () => {
177
- for (const bad of ['### AD-051 — wrong level', ' ## AD-051 — indented', '##\tAD-051 — tab separated']) {
178
- const err = refusal(() => parseDecisionsText(tierText(500, '# T', [adrBlock('050'), `${bad}\n\norphan body`]), 'x'));
179
- assert.match(err.message, /^x:\d+:/);
180
- assert.match(err.message, /AD-051/);
181
- }
182
- });
183
-
184
- it('a CRLF decisions file parses identically to its LF twin', () => {
185
- const lf = tierText(500, '# T', [adrBlock('050'), adrBlock('051')]);
186
- const a = parseDecisionsText(lf, 'x');
187
- const b = parseDecisionsText(lf.replace(/\n/g, '\r\n'), 'x');
188
- assert.deepEqual(b.entries.map((e) => e.id), a.entries.map((e) => e.id));
189
- assert.deepEqual(b.entries.map((e) => e.status), a.entries.map((e) => e.status));
190
- });
191
-
192
- it('the check verdict names the parsed HOT ADR count, zero included', () => {
193
- const withTwo = makeRoot();
194
- seedLegacy(withTwo, { hot: ['050', '051'] });
195
- assert.equal(run(['--write-navigator'], withTwo).code, 0);
196
- const two = run(['--check'], withTwo);
197
- assert.equal(two.code, 0);
198
- assert.match(two.text, /2 ADR\(s\) in the HOT window/);
199
-
200
- const empty = makeRoot();
201
- seedLegacy(empty, { hot: [] });
202
- assert.equal(run(['--write-navigator'], empty).code, 0);
203
- const zero = run(['--check'], empty);
204
- assert.equal(zero.code, 0);
205
- assert.match(zero.text, /0 ADR\(s\) in the HOT window/);
206
- });
207
- });
208
-
209
- // ── 1.1 — the widened grammar + real-corpus parser + status/date/lifecycle extraction ──
210
-
211
- describe('1.1 parser — real-corpus formats, widened grammar, verbatim blocks', () => {
212
- it('parses AD-001 (separate Date/Status lines), a same-line + wrapped-rich status, and AD-1000', () => {
213
- const wrapped = ['## AD-042 — Same-line rich', '', '**Date:** 2026-07-04 · **Status:** Accepted (ships kit `1.34.0`;', 'wrapped continuation of the status prose)', '', 'body'].join('\n');
214
- const text = tierText(500, '# T', [
215
- adrBlock('001', { separate: true }),
216
- wrapped,
217
- adrBlock('1000', { title: 'Four digits' }),
218
- ]);
219
- const p = parseDecisionsText(text, 'x');
220
- assert.deepEqual(p.entries.map((e) => e.id), ['001', '042', '1000']);
221
- assert.equal(p.entries[1].status, 'accepted', 'the leading Status word wins even when the prose wraps');
222
- assert.match(p.entries[1].block, /wrapped continuation of the status prose/, 'the block is preserved VERBATIM');
223
- assert.equal(p.entries[0].date, '2026-01-01');
224
- });
225
-
226
- it('a MISSING status line defaults to accepted (6 of 9 active HOT ADRs carry none)', () => {
227
- const noStatus = ['## AD-045 — No status line', '', '**Problem.** starts straight in.', '', 'body'].join('\n');
228
- const p = parseDecisionsText(tierText(500, '# T', [noStatus]), 'x');
229
- assert.equal(p.entries[0].status, 'accepted');
230
- assert.equal(p.entries[0].date, null, 'no Date line → null');
231
- });
232
-
233
- it('backfills supersedes / supersededBy from the real corpus link forms', () => {
234
- const blocks = [
235
- adrBlock('006', { status: 'Amended by [[AD-014]] (later refinement)' }),
236
- adrBlock('007', { status: 'Superseded by [[AD-011]] (Plan B realized)' }),
237
- adrBlock('018', { status: 'Accepted — realized in kit 1.7.0. Supersedes [[AD-007]].' }),
238
- ];
239
- const p = parseDecisionsText(tierText(500, '# T', blocks), 'x');
240
- assert.deepEqual(p.entries[0].supersededBy, ['014']);
241
- assert.equal(p.entries[0].status, 'amended');
242
- assert.deepEqual(p.entries[1].supersededBy, ['011']);
243
- assert.equal(p.entries[1].status, 'superseded');
244
- assert.deepEqual(p.entries[2].supersedes, ['007']);
245
- assert.equal(p.entries[2].status, 'accepted');
246
- });
247
-
248
- const badHeadings = [
249
- ['a hyphen instead of the em-dash', '## AD-024 - Title'],
250
- ['a 2-digit id (below the AD-\\d{3,} floor)', '## AD-24 — Title'],
251
- ['a missing title', '## AD-024 — '],
252
- ['an unrelated H2', '## Notes'],
253
- ];
254
- for (const [name, heading] of badHeadings) {
255
- it(`rejects ${name} naming file:line — never a silent merge`, () => {
256
- const text = `${fm(500)}\n# T\n\n${adrBlock('001')}\n\n${heading}\nbody\n`;
257
- assert.throws(() => parseDecisionsText(text, 'docs/ai/decisions.md'), (e) => {
258
- assert.equal(e.exitCode, 1);
259
- assert.match(e.message, /docs\/ai\/decisions\.md:\d+/);
260
- assert.match(e.message, /non-canonical H2/);
261
- return true;
262
- });
263
- });
264
- }
265
-
266
- it('rejects disordered ids (oldest at the top, NUMERIC order)', () => {
267
- assert.throws(() => parseDecisionsText(tierText(500, '# T', [adrBlock('007'), adrBlock('005')]), 'x'), /strictly ascending/);
268
- });
269
-
270
- it('AD-200 precedes AD-1000 numerically (never lexically — Decision 10)', () => {
271
- const ok = parseDecisionsText(tierText(500, '# T', [adrBlock('200'), adrBlock('1000')]), 'x');
272
- assert.deepEqual(ok.entries.map((e) => e.id), ['200', '1000']);
273
- assert.throws(() => parseDecisionsText(tierText(500, '# T', [adrBlock('1000'), adrBlock('200')]), 'x'), /strictly ascending/, 'AD-1000 before AD-200 is descending numerically');
274
- });
275
- });
276
-
277
- describe('slugify + recordFileName', () => {
278
- it('lowercases, replaces non-alphanumerics, trims to a bounded length', () => {
279
- assert.equal(slugify('Host-level bridge settings surface'), 'host-level-bridge-settings-surface');
280
- assert.equal(slugify('Onboarding UX: batched asks (the seeding↔hook chain)'), 'onboarding-ux-batched-asks-the-seeding-hook-chain');
281
- assert.ok(slugify('x'.repeat(200)).length <= 60);
282
- });
283
- it('the filename encodes the id (the O(1) by-id glob key)', () => {
284
- assert.equal(recordFileName('042', 'a-slug'), 'AD-042-a-slug.md');
285
- });
286
- });
287
-
288
- // ── 1.2 — explode + conservation (pure) ────────────────────────────────────────────────
289
-
290
- describe('1.2 explode — one immutable record per id, verbatim block, lifecycle frontmatter', () => {
291
- it('builds a record per entry with inline lifecycle frontmatter and the verbatim block', () => {
292
- const p = parseDecisionsText(tierText(500, '# T', [adrBlock('003', { status: 'Superseded by [[AD-009]]' })]), 'x');
293
- const [rec] = explode(p.entries, '2026-07-09');
294
- assert.equal(rec.fileName, 'AD-003-decision-003.md');
295
- assert.match(rec.frontmatter, /type: adr/);
296
- assert.match(rec.frontmatter, new RegExp(`maxLines: ${RECORD_CAP}`));
297
- assert.match(rec.frontmatter, /status: superseded/);
298
- assert.match(rec.frontmatter, /supersededBy: \[AD-009\]/);
299
- assert.equal(rec.block, p.entries[0].block, 'the block is carried VERBATIM');
300
- });
301
- });
302
-
303
- describe('1.2 verifyConservation — partition-preserving, extra-aware, fail-loud', () => {
304
- const items = (pairs) => pairs.map(([id, block]) => ({ id, block }));
305
- it('passes when the NEW side is exactly the OLD multiset', () => {
306
- const old = items([['001', 'a'], ['002', 'b']]);
307
- assert.doesNotThrow(() => verifyConservation(old, items([['001', 'a'], ['002', 'b']])));
308
- });
309
- it('fails on a DROPPED id (an ADR would be lost)', () => {
310
- assert.throws(() => verifyConservation(items([['001', 'a'], ['002', 'b']]), items([['001', 'a']])), /absent from the migrated store/);
311
- });
312
- it('fails on an EDITED block (hash mismatch — the block must move verbatim)', () => {
313
- assert.throws(() => verifyConservation(items([['001', 'a']]), items([['001', 'a-edited']])), /block changed during migration/);
314
- });
315
- it('fails on a STRAY new id absent from the OLD tiers (invented history)', () => {
316
- assert.throws(() => verifyConservation(items([['001', 'a']]), items([['001', 'a'], ['009', 'x']])), /stray\/invented/);
317
- });
318
- it('fails on a RENUMBER (old 002 lost, new 003 stray)', () => {
319
- assert.throws(() => verifyConservation(items([['001', 'a'], ['002', 'b']]), items([['001', 'a'], ['003', 'b']])), /lost|absent from the migrated store/);
320
- });
321
- it('blockHash is stable + content-addressed', () => {
322
- assert.equal(blockHash('x'), blockHash('x'));
323
- assert.notEqual(blockHash('x'), blockHash('y'));
324
- });
325
- });
326
-
327
- // ── 1.3 — --migrate + snapshot + retire monoliths + idempotence + legacy guard ─────────
328
-
329
- describe('1.3 --migrate dry-run writes nothing', () => {
330
- it('prints the file set + conservation proof, mutates no file, creates no adr/ tree', () => {
331
- const root = makeRoot();
332
- seedLegacy(root, { hot: ['005', '006'], warm: ['003', '004'], cold: ['001', '002'] });
333
- const before = readFileSync(join(root, HOT_REL), 'utf8');
334
- const { code, text } = run(['--migrate', '--today=2026-07-09'], root);
335
- assert.equal(code, 0, text);
336
- assert.match(text, /DRY-RUN/);
337
- assert.match(text, /conserved/);
338
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), before, 'HOT untouched');
339
- assert.ok(existsSync(join(root, WARM_REL)) && existsSync(join(root, COLD_REL)), 'monoliths untouched');
340
- assert.ok(!existsSync(join(root, ADR_DIR_REL)), 'no adr/ tree created on a dry-run');
341
- });
342
- });
343
-
344
- describe('1.3 --migrate --apply — records + snapshot + retire monoliths + HOT rewrite', () => {
345
- it('writes one record per archived id, a git-dir snapshot, a nav, retires monoliths, rewrites the HOT preamble', () => {
346
- const root = makeRoot();
347
- seedLegacy(root, { hot: ['005', '006', '007', '008'], warm: ['003', '004'], cold: ['001', '002'] });
348
- const { code, text } = run(['--migrate', '--apply', '--today=2026-07-09'], root);
349
- assert.equal(code, 0, text);
350
-
351
- assert.deepEqual(adrFiles(root), ['AD-001-decision-001.md', 'AD-002-decision-002.md', 'AD-003-decision-003.md', 'AD-004-decision-004.md']);
352
- assert.deepEqual(idsIn(root, HOT_REL), ['005', '006', '007', '008'], 'HOT keeps the active window');
353
- assert.ok(!existsSync(join(root, WARM_REL)) && !existsSync(join(root, COLD_REL)), 'both monoliths retired');
354
- assert.ok(existsSync(join(root, NAV_REL)), 'navigator generated');
355
-
356
- const hotText = readFileSync(join(root, HOT_REL), 'utf8');
357
- assert.match(hotText, /adr\/log\.md/, 'the HOT preamble now points at the navigator');
358
- assert.doesNotMatch(hotText, /decisions-archive/, 'the dead monolith links are dropped');
359
- assert.match(hotText, /AD-005 onward/, 'the active-window token is rewritten to the retained oldest');
360
-
361
- const snapDir = join(root, '.git', 'agent-workflow-adr-migration-snapshot-STAMP');
362
- assert.ok(existsSync(snapDir), 'the snapshot landed under the git dir (never the work tree)');
363
- assert.equal(readdirSync(snapDir).sort().length, 3, 'snapshot captured decisions.md + both monoliths');
364
- });
365
-
366
- it('the snapshot captures the ORIGINAL decisions.md + monolith BYTES (recoverable content, not just names)', () => {
367
- const root = makeRoot();
368
- seedLegacy(root, { hot: ['005', '006'], warm: ['003'], cold: ['001'] });
369
- const hotBefore = readFileSync(join(root, HOT_REL), 'utf8');
370
- const warmBefore = readFileSync(join(root, WARM_REL), 'utf8');
371
- const coldBefore = readFileSync(join(root, COLD_REL), 'utf8');
372
- run(['--migrate', '--apply', '--today=2026-07-09'], root);
373
- const snapDir = join(root, '.git', 'agent-workflow-adr-migration-snapshot-STAMP');
374
- assert.equal(readFileSync(join(snapDir, 'docs__ai__decisions.md'), 'utf8'), hotBefore, 'the ORIGINAL HOT is recoverable verbatim');
375
- assert.equal(readFileSync(join(snapDir, 'docs__ai__history__decisions-archive.md'), 'utf8'), warmBefore, 'the ORIGINAL WARM monolith is recoverable verbatim');
376
- assert.equal(readFileSync(join(snapDir, 'docs__ai__history__decisions-archive-early.md'), 'utf8'), coldBefore, 'the ORIGINAL COLD monolith is recoverable verbatim');
377
- });
378
-
379
- it('migrating an OVER-CAP HOT explodes the HOT overflow into records too (not only the monoliths)', () => {
380
- const root = makeRoot();
381
- seedLegacy(root, { hot: ['005', '006', '007', '008'], warm: ['003'], cold: ['001'], hotCapDelta: -1 });
382
- const { code } = run(['--migrate', '--apply', '--today=2026-07-09'], root);
383
- assert.equal(code, 0);
384
- assert.ok(adrFiles(root).includes('AD-005-decision-005.md'), 'the HOT overflow AD-005 exploded to a record');
385
- assert.ok(!idsIn(root, HOT_REL).includes('005'), 'AD-005 left the HOT window');
386
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0, 'the migrated over-cap tree is green');
387
- });
388
-
389
- it('a second --apply no-ops (monoliths already retired → already-migrated)', () => {
390
- const root = makeRoot();
391
- seedLegacy(root, { hot: ['005', '006'], warm: ['003'], cold: ['001'] });
392
- run(['--migrate', '--apply', '--today=2026-07-09'], root);
393
- const snapshotBefore = readdirSync(join(root, '.git'));
394
- const { code, text } = run(['--migrate', '--apply', '--today=2026-07-10'], root);
395
- assert.equal(code, 0);
396
- assert.match(text, /already migrated/);
397
- assert.deepEqual(readdirSync(join(root, '.git')), snapshotBefore, 'no second snapshot');
398
- });
399
-
400
- it('the migrated tree passes --check (green end-to-end)', () => {
401
- const root = makeRoot();
402
- seedLegacy(root, { hot: ['005', '006', '007'], warm: ['003', '004'], cold: ['001', '002'] });
403
- run(['--migrate', '--apply', '--today=2026-07-09'], root);
404
- const { code, text } = run(['--check', '--today=2026-07-09'], root);
405
- assert.equal(code, 0, text);
406
- assert.match(text, /OK — HOT within cap, store integrity intact, navigator fresh/);
407
- });
408
-
409
- it('a stray adr record NEWER than the HOT window fails exit 1 (partition) BEFORE any snapshot/delete', () => {
410
- const root = makeRoot();
411
- seedLegacy(root, { hot: ['005'], warm: ['003'], cold: ['001'] });
412
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
413
- // AD-099 is newer than the HOT window (AD-005) → not a legitimate archived record → refuse.
414
- writeFileSync(join(root, ADR_DIR_REL, 'AD-099-stray.md'), `${fm(RECORD_CAP)}\n${adrBlock('099')}\n`);
415
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-07-09'], root);
416
- assert.equal(code, 1);
417
- assert.match(errText, /partition violated/);
418
- assert.ok(existsSync(join(root, WARM_REL)) && existsSync(join(root, COLD_REL)), 'monoliths NOT deleted on a refused migration');
419
- assert.ok(!existsSync(join(root, '.git', 'agent-workflow-adr-migration-snapshot-STAMP')), 'no snapshot on a refusal (the integrity check precedes the snapshot)');
420
- });
421
-
422
- it('resumes after a post-writeHot / post-partial-delete crash without wedging (idempotent) — internal-sweep major', () => {
423
- const root = makeRoot();
424
- // Reconstruct a post-crash state: HOT ALREADY trimmed to [006,007,008] (AD-005 was the exploded
425
- // overflow, its source no longer in HOT); adr/ holds records 001..005; monoliths STILL present
426
- // (crash before rmSync). A naive conservation would accuse AD-005 of being "invented history".
427
- seedLegacy(root, { hot: ['006', '007', '008'], warm: ['003', '004'], cold: ['001', '002'] });
428
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
429
- const recEntries = ['001', '002', '003', '004', '005'].map((id) => parseDecisionsText(tierText(999, '# T', [adrBlock(id)]), 'x').entries[0]);
430
- for (const rec of explode(recEntries, '2026-07-09')) writeFileSync(join(root, ADR_DIR_REL, rec.fileName), `${rec.frontmatter}\n${rec.block}\n`);
431
- const { code } = run(['--migrate', '--apply', '--today=2026-07-09'], root);
432
- assert.equal(code, 0, 'the resume completes — it never accuses its own migrated records of being stray');
433
- assert.deepEqual(adrFiles(root), ['AD-001-decision-001.md', 'AD-002-decision-002.md', 'AD-003-decision-003.md', 'AD-004-decision-004.md', 'AD-005-decision-005.md']);
434
- assert.deepEqual(idsIn(root, HOT_REL), ['006', '007', '008']);
435
- assert.ok(!existsSync(join(root, WARM_REL)) && !existsSync(join(root, COLD_REL)), 'monoliths retired on the completed resume');
436
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0, 'the resumed tree passes --check');
437
- });
438
-
439
- it('refuses when a pre-existing adr/ record duplicates an ADR that stays in HOT (never two places — review-adr-archive-r04-major-01)', () => {
440
- const root = makeRoot();
441
- seedLegacy(root, { hot: ['005', '006'], warm: ['003'], cold: ['001'] });
442
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
443
- // AD-006 stays in the HOT window, but a store record for it already exists (a corrupt partial state).
444
- const rec = explode(parseDecisionsText(tierText(999, '# T', [adrBlock('006')]), 'x').entries, '2026-07-09')[0];
445
- writeFileSync(join(root, ADR_DIR_REL, rec.fileName), `${rec.frontmatter}\n${rec.block}\n`);
446
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-07-09'], root);
447
- assert.equal(code, 1);
448
- assert.match(errText, /duplicate ADR id AD-006/);
449
- assert.ok(existsSync(join(root, WARM_REL)), 'monoliths NOT deleted on the refused migration');
450
- });
451
-
452
- it('resumes a half-migrated tree (a byte-identical record is skipped, the rest complete)', () => {
453
- const root = makeRoot();
454
- seedLegacy(root, { hot: ['005', '006'], warm: ['003', '004'], cold: ['001', '002'] });
455
- run(['--migrate', '--today=2026-07-09'], root); // dry-run to observe (no writes)
456
- // Simulate a crash mid-write: AD-001's record already on disk, monoliths still present.
457
- const partial = explode(parseDecisionsText(readFileSync(join(root, COLD_REL), 'utf8'), COLD_REL).entries, '2026-07-09')[0];
458
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
459
- writeFileSync(join(root, ADR_DIR_REL, partial.fileName), `${partial.frontmatter}\n${partial.block}\n`);
460
- const { code } = run(['--migrate', '--apply', '--today=2026-07-09'], root);
461
- assert.equal(code, 0, 'the resume completes');
462
- assert.deepEqual(adrFiles(root), ['AD-001-decision-001.md', 'AD-002-decision-002.md', 'AD-003-decision-003.md', 'AD-004-decision-004.md']);
463
- assert.ok(!existsSync(join(root, WARM_REL)), 'monoliths retired on the completed resume');
464
- });
465
-
466
- it('a corrupt crash-resume record (same id, DIFFERENT body) fails loud before any write (conservation is not bypassed)', () => {
467
- const root = makeRoot();
468
- seedLegacy(root, { hot: ['005', '006'], warm: ['003', '004'], cold: ['001', '002'] });
469
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
470
- // An AD-003 record exists on disk but with a TAMPERED body (≠ the WARM monolith's AD-003).
471
- writeFileSync(join(root, ADR_DIR_REL, 'AD-003-decision-003.md'), `${fm(RECORD_CAP)}\n## AD-003 — Decision 003\n\n**Date:** 2026-01-01\n\nTAMPERED body not in the monolith\n`);
472
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-07-09'], root);
473
- assert.equal(code, 1);
474
- assert.match(errText, /DIFFERENT body|corrupt or hand-edited/);
475
- assert.ok(existsSync(join(root, WARM_REL)) && existsSync(join(root, COLD_REL)), 'monoliths NOT deleted — the edited record is never silently overwritten');
476
- assert.ok(!existsSync(join(root, '.git', 'agent-workflow-adr-migration-snapshot-STAMP')), 'no snapshot on a refused migration (conservation precedes the snapshot)');
477
- });
478
-
479
- it('off git, the snapshot falls back to a stated out-of-tree base (never the work tree)', () => {
480
- const root = makeRoot();
481
- const fallback = makeRoot();
482
- seedLegacy(root, { hot: ['005'], warm: ['003'], cold: ['001'] });
483
- const { code } = run(['--migrate', '--apply', '--today=2026-07-09'], root, { spawnSync: noGit, fallbackBase: fallback });
484
- assert.equal(code, 0);
485
- assert.ok(existsSync(join(fallback, 'agent-workflow-adr-migration-snapshot-STAMP')), 'off-git snapshot landed in the fallback base');
486
- assert.ok(!existsSync(join(root, '.git')), 'nothing written under a non-existent git dir');
487
- });
488
- });
489
-
490
- describe('1.3 legacy-substrate guard (Decision 6) — never half-explodes, never green on a monolith', () => {
491
- it('a default rotate with a monolith present fails LOUD (run --migrate first)', () => {
492
- const root = makeRoot();
493
- seedLegacy(root, { hot: ['005'], warm: ['003'], cold: ['001'] });
494
- const { code, errText } = run(['--today=2026-07-09'], root);
495
- assert.equal(code, 1);
496
- assert.match(errText, /legacy monolith present/);
497
- assert.match(errText, /--migrate --apply/);
498
- });
499
- it('--check with a monolith present fails LOUD (half-migrated), never reports green', () => {
500
- const root = makeRoot();
501
- seedLegacy(root, { hot: ['005'], warm: ['003'], cold: ['001'] });
502
- const { code, errText } = run(['--check'], root);
503
- assert.equal(code, 1);
504
- assert.match(errText, /half-migrated/);
505
- });
506
-
507
- it('a LONE monolith (HOT and adr/ both absent) fails the legacy guard, never a clean substrate-absent skip', () => {
508
- const root = makeRoot();
509
- mkdirSync(join(root, 'docs', 'ai', 'history'), { recursive: true });
510
- writeFileSync(join(root, WARM_REL), tierText(500, WARM_PREAMBLE, [adrBlock('003')]));
511
- const { code, errText } = run(['--check'], root);
512
- assert.equal(code, 1);
513
- assert.match(errText, /legacy monolith present/);
514
- });
515
- });
516
-
517
- // ── 1.4 — --check + default rotate + item-(h) regen ────────────────────────────────────
518
-
519
- // A fully-migrated tree (post-migration substrate) built directly for the check/rotate tests.
520
- const seedMigrated = (root, { hotIds, storeIds = [], hotCapDelta = 200, today = '2026-07-09' }) => {
521
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
522
- const hotBlocks = hotIds.map((id) => adrBlock(id));
523
- const probe = tierText(9999, HOT_PREAMBLE.replace(/> \*\*Archive:\*\*.*/, ''), hotBlocks);
524
- const cap = lineCountOf(probe) + hotCapDelta;
525
- const preamble = ['# ADRs', '', '> Newest at the bottom.'].join('\n');
526
- writeFileSync(join(root, HOT_REL), tierText(cap, preamble, hotBlocks));
527
- const storeEntries = storeIds.map((id) => (typeof id === 'string' ? { id } : id));
528
- const records = explode(storeEntries.map((s) => parseDecisionsText(tierText(999, '# T', [adrBlock(s.id, s)]), 'x').entries[0]), today);
529
- for (const rec of records) writeFileSync(join(root, ADR_DIR_REL, rec.fileName), `${rec.frontmatter}\n${rec.block}\n`);
530
- // A fresh navigator so --check is green from the start.
531
- run(['--write-navigator', `--today=${today}`], root);
532
- return { cap };
533
- };
534
-
535
- describe('1.4 --check', () => {
536
- it('a green migrated tree → exit 0', () => {
537
- const root = makeRoot();
538
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: ['001', '002'] });
539
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0);
540
- });
541
-
542
- it('a duplicate id across HOT and adr/ → exit 1', () => {
543
- const root = makeRoot();
544
- seedMigrated(root, { hotIds: ['002', '005'], storeIds: ['001', '002'] }); // AD-002 in BOTH
545
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
546
- assert.equal(code, 1);
547
- assert.match(errText, /duplicate ADR id AD-002/);
548
- });
549
-
550
- it('a decisions.md with NO maxLines cap fails loud (never operates against an unknown budget — review-adr-archive-r04-major-02)', () => {
551
- const root = makeRoot();
552
- mkdirSync(join(root, 'docs', 'ai'), { recursive: true });
553
- const noCapFm = '---\ntype: reference\nlastUpdated: 2026-01-01\nscope: permanent\nstaleAfter: never\nowner: none\n---\n';
554
- writeFileSync(join(root, HOT_REL), `${noCapFm}\n# ADRs\n\n${adrBlock('005')}\n`);
555
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
556
- assert.equal(code, 1);
557
- assert.match(errText, /no maxLines cap/);
558
- });
559
-
560
- it('NO substrate (neither decisions.md nor adr/) → exit 0 with a STATED skip', () => {
561
- const root = makeRoot();
562
- mkdirSync(join(root, 'docs', 'ai'), { recursive: true });
563
- const { code, text } = run(['--check'], root);
564
- assert.equal(code, 0);
565
- assert.match(text, /SKIP — no ADR substrate/);
566
- });
567
-
568
- it('an adr/ record NEWER than a HOT entry fails store integrity (partition — the once-dead check is live)', () => {
569
- const root = makeRoot();
570
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
571
- const rec = explode(parseDecisionsText(tierText(999, '# T', [adrBlock('010')]), 'x').entries, '2026-07-09')[0];
572
- writeFileSync(join(root, ADR_DIR_REL, rec.fileName), `${rec.frontmatter}\n${rec.block}\n`); // AD-010 > HOT AD-005
573
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
574
- assert.equal(code, 1);
575
- assert.match(errText, /partition violated/);
576
- });
577
-
578
- it('an UNEXPECTED markdown file in adr/ fails loud (never silently hidden from the store)', () => {
579
- const root = makeRoot();
580
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
581
- writeFileSync(join(root, ADR_DIR_REL, 'notes.md'), '# stray notes with no frontmatter\n');
582
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
583
- assert.equal(code, 1);
584
- assert.match(errText, /unexpected markdown file/);
585
- });
586
-
587
- it('TWO files for one id (a corrupt duplicate-filled store) fail loud at the SOURCE — never deduped away (council R3)', () => {
588
- const root = makeRoot();
589
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
590
- writeFileSync(join(root, ADR_DIR_REL, 'AD-001-divergent-slug.md'), `${fm(RECORD_CAP)}\n${adrBlock('001')}\n`); // a 2nd file for AD-001
591
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
592
- assert.equal(code, 1);
593
- assert.match(errText, /two records for AD-001/);
594
- });
595
-
596
- it('a rotate over a duplicate-filled store fails loud (the R2 crash-resume dedup no longer hides pre-existing dups — council R3)', () => {
597
- const root = makeRoot();
598
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
599
- const blocks = ['005', '006', '007', '008'].map((id) => adrBlock(id));
600
- const preamble = '# ADRs\n\n> HOT.';
601
- const probe = tierText(9999, preamble, blocks);
602
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, preamble, blocks)); // over cap → rotate proceeds
603
- for (const r of explode(['001'].map((id) => parseDecisionsText(tierText(999, '# T', [adrBlock(id)]), 'x').entries[0]), '2026-07-09')) {
604
- writeFileSync(join(root, ADR_DIR_REL, r.fileName), `${r.frontmatter}\n${r.block}\n`);
605
- }
606
- writeFileSync(join(root, ADR_DIR_REL, 'AD-001-second.md'), `${fm(RECORD_CAP)}\n${adrBlock('001')}\n`); // duplicate id
607
- const { code, errText } = run(['--today=2026-07-09'], root);
608
- assert.equal(code, 1);
609
- assert.match(errText, /two records for AD-001/);
610
- });
611
-
612
- it('a NESTED subdirectory in adr/ fails loud (the store is a flat directory — review-adr-archive-r02-major-01)', () => {
613
- const root = makeRoot();
614
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
615
- mkdirSync(join(root, ADR_DIR_REL, 'nested'), { recursive: true });
616
- writeFileSync(join(root, ADR_DIR_REL, 'nested', 'AD-002-x.md'), `${fm(RECORD_CAP)}\n${adrBlock('002')}\n`);
617
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
618
- assert.equal(code, 1);
619
- assert.match(errText, /FLAT directory/);
620
- });
621
-
622
- it('adr/ present but HOT absent → integrity is STILL checked (not skipped): a stale nav → exit 1', () => {
623
- const root = makeRoot();
624
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001', '002'] });
625
- rmSync(join(root, HOT_REL));
626
- writeFileSync(join(root, NAV_REL), readFileSync(join(root, NAV_REL), 'utf8') + '\nstale junk\n');
627
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
628
- assert.equal(code, 1, 'the check runs (does not skip) even with HOT absent');
629
- assert.match(errText, /stale/);
630
- });
631
- });
632
-
633
- describe('1.4 default rotate — explode the oldest beyond cap + regenerate the index (item h)', () => {
634
- it('a HOT one line over cap explodes EXACTLY the oldest entry, keeps the rest, calls the index regen once', () => {
635
- const root = makeRoot();
636
- // 4 HOT entries, cap = rendered - 1 → exactly one must roll out.
637
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
638
- const blocks = ['005', '006', '007', '008'].map((id) => adrBlock(id));
639
- const preamble = '# ADRs\n\n> Newest at the bottom.';
640
- const probe = tierText(9999, preamble, blocks);
641
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, preamble, blocks));
642
- run(['--write-navigator', '--today=2026-07-09'], root); // seed a fresh nav
643
- const { code, regenCalls } = run(['--today=2026-07-09'], root);
644
- assert.equal(code, 0);
645
- assert.deepEqual(idsIn(root, HOT_REL), ['006', '007', '008'], 'exactly the oldest rolled out');
646
- assert.deepEqual(adrFiles(root), ['AD-005-decision-005.md'], 'AD-005 exploded to a record');
647
- assert.deepEqual(regenCalls, [[root, '2026-07-09']], 'the index regen fired once with (root, today)');
648
- });
649
-
650
- it('an under-cap migrated tree is a no-op (nothing written, no regen)', () => {
651
- const root = makeRoot();
652
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: ['001'] });
653
- const { code, text, regenCalls } = run(['--today=2026-07-09'], root);
654
- assert.equal(code, 0);
655
- assert.match(text, /nothing to rotate/);
656
- assert.equal(regenCalls.length, 0, 'a no-op never regenerates the index');
657
- });
658
-
659
- it('is crash-resumable: a byte-identical record from a crashed prior rotate is deduped, not a fatal duplicate (review-adr-archive-r02-major-02)', () => {
660
- const root = makeRoot();
661
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
662
- const blocks = ['005', '006', '007', '008'].map((id) => adrBlock(id));
663
- const preamble = '# ADRs\n\n> Newest at the bottom.';
664
- const probe = tierText(9999, preamble, blocks);
665
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, preamble, blocks)); // AD-005 overflows
666
- // Crash after writeRecords, before writeHot: AD-005 already exploded, HOT untrimmed; plus archived AD-001.
667
- for (const r of explode(['001', '005'].map((id) => parseDecisionsText(tierText(999, '# T', [adrBlock(id)]), 'x').entries[0]), '2026-07-09')) {
668
- writeFileSync(join(root, ADR_DIR_REL, r.fileName), `${r.frontmatter}\n${r.block}\n`);
669
- }
670
- const { code } = run(['--today=2026-07-09'], root);
671
- assert.equal(code, 0, 'the crashed rotate resumes cleanly — no fatal duplicate on the already-written record');
672
- assert.deepEqual(idsIn(root, HOT_REL), ['006', '007', '008']);
673
- assert.deepEqual(adrFiles(root), ['AD-001-decision-001.md', 'AD-005-decision-005.md']);
674
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0);
675
- });
676
-
677
- it('a no-op rotate still REFUSES a corrupt store (partition) — never a silent green no-op (review-adr-archive-r02-major-03)', () => {
678
- const root = makeRoot();
679
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] }); // under cap
680
- const rec = explode(parseDecisionsText(tierText(999, '# T', [adrBlock('010')]), 'x').entries, '2026-07-09')[0];
681
- writeFileSync(join(root, ADR_DIR_REL, rec.fileName), `${rec.frontmatter}\n${rec.block}\n`); // AD-010 > HOT AD-005
682
- const { code, errText } = run(['--today=2026-07-09'], root);
683
- assert.equal(code, 1);
684
- assert.match(errText, /partition violated/);
685
- });
686
-
687
- it('degrades LOUDLY when the index regen fails — the rotation itself still succeeds (exit 0)', () => {
688
- const root = makeRoot();
689
- const blocks = ['005', '006', '007', '008'].map((id) => adrBlock(id));
690
- const preamble = '# ADRs\n\n> Newest at the bottom.';
691
- const probe = tierText(9999, preamble, blocks);
692
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
693
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, preamble, blocks));
694
- run(['--write-navigator', '--today=2026-07-09'], root);
695
- const { code, errText } = run(['--today=2026-07-09'], root, { regen: () => ({ ok: false, detail: 'the index generator is not beside this script' }) });
696
- assert.equal(code, 0, 'the rotation succeeded — regen is best-effort');
697
- assert.match(errText, /NOT regenerated/);
698
- });
699
- });
700
-
701
- // ── 1.5 — navigator generator + --write-navigator ──────────────────────────────────────
702
-
703
- describe('1.5 navigator — governing heads (computed), superseded drop out but stay reachable', () => {
704
- it('a superseded ADR is absent from the governing list but present by filename + in the recent window', () => {
705
- const root = makeRoot();
706
- // AD-002 is superseded by AD-005 (self-declared); it must drop out of governing.
707
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: [{ id: '001' }, { id: '002', status: 'Superseded by [[AD-005]]' }] });
708
- const nav = readFileSync(join(root, NAV_REL), 'utf8');
709
- const governingSection = nav.split('## Recent')[0];
710
- assert.doesNotMatch(governingSection, /AD-002/, 'the superseded ADR is NOT a governing head');
711
- assert.match(governingSection, /AD-001/, 'a governing ADR is listed');
712
- assert.ok(adrFiles(root).some((f) => f.startsWith('AD-002-')), 'the superseded ADR is still reachable by filename');
713
- assert.match(nav, /AD-002.*superseded/s, 'the recent window still surfaces it, marked superseded');
714
- });
715
-
716
- it('governance is computed across the corpus via inference (no predecessor mutation needed)', () => {
717
- const corpus = [
718
- { id: '001', idNum: 1, title: 'A', status: 'accepted', supersedes: [], supersededBy: [], fileName: 'AD-001-a.md' },
719
- { id: '002', idNum: 2, title: 'B', status: 'accepted', supersedes: ['001'], supersededBy: [], fileName: 'AD-002-b.md' },
720
- ];
721
- const superseded = computeSupersededSet(corpus);
722
- assert.ok(superseded.has('001'), 'AD-001 is inferred superseded because AD-002 declares Supersedes [[AD-001]]');
723
- assert.ok(!superseded.has('002'));
724
- const nav = buildNavigator(corpus, '2026-07-09');
725
- assert.match(nav, /Governing \(1\)/);
726
- assert.match(nav, /AD-001 … AD-002/, 'the navigator range is numeric min…max');
727
- });
728
-
729
- it('a Proposed head is NOT governing; a non-accepted Supersedes does NOT retire an accepted predecessor', () => {
730
- const corpus = [
731
- { id: '001', idNum: 1, title: 'A', status: 'accepted', supersedes: [], supersededBy: [], fileName: 'AD-001-a.md' },
732
- { id: '002', idNum: 2, title: 'B', status: 'proposed', supersedes: ['001'], supersededBy: [], fileName: 'AD-002-b.md' },
733
- ];
734
- const superseded = computeSupersededSet(corpus);
735
- assert.ok(!superseded.has('001'), 'a Proposed ADR does not effectively supersede its accepted predecessor');
736
- const gov = buildNavigator(corpus, '2026-07-09').split('## Recent')[0];
737
- assert.match(gov, /AD-001/, 'the accepted predecessor stays governing');
738
- assert.doesNotMatch(gov, /\| AD-002 \|/, 'the Proposed ADR is NOT a governing head (accepted & not-superseded only)');
739
- });
740
-
741
- // The read-only preflight a guarded caller needs: the SAME parse / half-migrated guard / store
742
- // integrity the writer runs, stopping before every write. Without it a caller can only learn that
743
- // seeding is safe by seeding.
744
- it('--write-navigator --dry-run validates and writes NOTHING', () => {
745
- const root = makeRoot();
746
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: ['001'] });
747
- const navBefore = readFileSync(join(root, NAV_REL), 'utf8');
748
- rmSync(join(root, NAV_REL));
749
- const r = run(['--write-navigator', '--dry-run', '--today=2026-07-09'], root);
750
- assert.equal(r.code, 0);
751
- assert.match(r.out.join('\n'), /DRY-RUN/, 'the run states it changed nothing');
752
- assert.equal(existsSync(join(root, NAV_REL)), false, 'the navigator was NOT written by the dry-run');
753
- // and the real run still produces exactly what the dry-run validated
754
- assert.equal(run(['--write-navigator', '--today=2026-07-09'], root).code, 0);
755
- assert.equal(readFileSync(join(root, NAV_REL), 'utf8'), navBefore);
756
- });
757
-
758
- it('--write-navigator --dry-run REFUSES a corrupt store instead of green-lighting it', () => {
759
- const root = makeRoot();
760
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: ['001'] });
761
- // a record whose id also lives in the HOT window — the store would hold the ADR twice
762
- writeFileSync(join(root, ADR_DIR_REL, 'AD-005-dup.md'), '---\n---\n\n## AD-005 — Dup\n\nBody.\n');
763
- const r = run(['--write-navigator', '--dry-run', '--today=2026-07-09'], root);
764
- assert.notEqual(r.code, 0, 'a corrupt store fails the preflight');
765
- assert.doesNotMatch(r.out.join('\n'), /DRY-RUN/, 'no go-ahead is printed for a tree that cannot converge');
766
- });
767
-
768
- it('authoring a new HOT ADR then --write-navigator keeps --check green; a stale nav with NO write → exit 1, then --write-navigator fixes it', () => {
769
- const root = makeRoot();
770
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: ['001'] });
771
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0, 'starts green');
772
-
773
- // Corrupt the navigator without regenerating → --check must flag it stale.
774
- writeFileSync(join(root, NAV_REL), readFileSync(join(root, NAV_REL), 'utf8') + '\n<!-- drift -->\n');
775
- const stale = run(['--check', '--today=2026-07-09'], root);
776
- assert.equal(stale.code, 1);
777
- assert.match(stale.errText, /navigator|stale|log\.md/i);
778
-
779
- // --write-navigator is the deterministic fix (never a fixless false-block).
780
- assert.equal(run(['--write-navigator', '--today=2026-07-09'], root).code, 0);
781
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0, '--write-navigator restored freshness');
782
- });
783
-
784
- it('--write-navigator refuses a duplicate-id store (never emits a corrupt / duplicate-row navigator)', () => {
785
- const root = makeRoot();
786
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
787
- writeFileSync(join(root, HOT_REL), tierText(500, '# ADRs\n\n> HOT.', [adrBlock('002'), adrBlock('005')]));
788
- const rec = explode(parseDecisionsText(tierText(999, '# T', [adrBlock('002')]), 'x').entries, '2026-07-09')[0];
789
- writeFileSync(join(root, ADR_DIR_REL, rec.fileName), `${rec.frontmatter}\n${rec.block}\n`); // AD-002 in adr/ AND HOT
790
- const { code, errText } = run(['--write-navigator', '--today=2026-07-09'], root);
791
- assert.equal(code, 1);
792
- assert.match(errText, /duplicate ADR id AD-002/);
793
- });
794
-
795
- it('--check does NOT false-block on a mere day-rollover (uses the on-disk nav lastUpdated)', () => {
796
- const root = makeRoot();
797
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'], today: '2026-07-01' });
798
- // "Today" is much later, but the corpus is unchanged → the nav must stay fresh.
799
- assert.equal(run(['--check', '--today=2026-07-31'], root).code, 0);
800
- });
801
- });
802
-
803
- // ── the navigator's stamped cap (docs/ai/specs/memory/adr-navigator.md) ─────────────────
804
- //
805
- // The frame is 38 lines (15 ADRs or more), so 162 governing heads make exactly 200, 163 make 201 and 170 make 208.
806
-
807
- const capOf = (text) => Number(text.match(/^maxLines: (\d+)$/m)[1]);
808
- const corpusOf = (n) =>
809
- Array.from({ length: n }, (_, i) => {
810
- const id = String(i + 1).padStart(3, '0');
811
- return { id, idNum: i + 1, title: `T${id}`, status: 'accepted', supersedes: [], supersededBy: [], fileName: `AD-${id}-t.md` };
812
- });
813
-
814
- describe('the navigator stamps a cap it honours', () => {
815
- it('200 while it fits, its own line count past it', () => {
816
- // spec:adr-navigator/S1
817
- for (const heads of [2, 162]) {
818
- const nav = buildNavigator(corpusOf(heads), '2026-07-09');
819
- assert.equal(capOf(nav), 200, `${heads} heads keep the 200 floor`);
820
- }
821
- assert.equal(lineCountOf(buildNavigator(corpusOf(162), '2026-07-09')), 200);
822
- // 165 entries, two superseded: 163 heads, 201 lines — a stamp from the entry count would read 203.
823
- const corpus = corpusOf(165).map((e, i) => (i < 2 ? { ...e, supersededBy: ['003'] } : e));
824
- const big = buildNavigator(corpus, '2026-07-09');
825
- assert.equal(lineCountOf(big), 201);
826
- assert.equal(capOf(big), 201, 'past the floor the stamp is the file\'s own count');
827
- });
828
-
829
- it('a written navigator past 200 lines fits its cap, --check is green, a hand-edited cap is stale', () => {
830
- // spec:adr-navigator/S2
831
- const root = makeRoot();
832
- seedMigrated(root, { hotIds: ['901'], storeIds: corpusOf(169).map((e) => e.id) });
833
- const nav = readFileSync(join(root, NAV_REL), 'utf8');
834
- assert.ok(lineCountOf(nav) > 200, 'the fixture is past the floor');
835
- assert.ok(lineCountOf(nav) <= capOf(nav), 'the docs gate accepts the written navigator');
836
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0);
837
- writeFileSync(join(root, NAV_REL), nav.replace(/^maxLines: \d+$/m, 'maxLines: 999'));
838
- const stale = run(['--check', '--today=2026-07-09'], root);
839
- assert.equal(stale.code, 1);
840
- assert.match(stale.errText, /log\.md is stale/);
841
- });
842
- });
843
-
844
- // ── item (h) degrade branches on the REAL default regenerator (no injection) ───────────
845
-
846
- describe('defaultRegenerateIndex — loud-degrade branches', () => {
847
- it('an absent index generator sibling → ok:false with a recovery instruct', () => {
848
- const r = defaultRegenerateIndex('/tmp/anyroot', '2026-07-09', { sibling: '/nonexistent/check-docs-size.mjs' });
849
- assert.equal(r.ok, false);
850
- assert.match(r.detail, /not beside this script/);
851
- });
852
- it('a subprocess that exits nonzero → ok:false with the recovery instruct', () => {
853
- const r = defaultRegenerateIndex('/tmp/anyroot', '2026-07-09', { existsSync: () => true, spawnSync: () => ({ status: 1 }) });
854
- assert.equal(r.ok, false);
855
- assert.match(r.detail, /index regeneration failed/);
856
- });
857
- });
858
-
859
- // ── coverage: defensive fail-loud branches + success/degrade paths (M3a) ───────────────
860
-
861
- describe('defensive branches + success/degrade paths', () => {
862
- it('a non-markdown stray in adr/ is IGNORED by the store (never an error)', () => {
863
- const root = makeRoot();
864
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
865
- writeFileSync(join(root, ADR_DIR_REL, 'notes.txt'), 'not markdown — ignored\n');
866
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0);
867
- });
868
-
869
- it('a record file holding TWO ADR blocks fails loud', () => {
870
- const root = makeRoot();
871
- seedMigrated(root, { hotIds: ['005'], storeIds: [] });
872
- writeFileSync(join(root, ADR_DIR_REL, 'AD-001-two.md'), `${fm(RECORD_CAP)}\n${adrBlock('001')}\n\n${adrBlock('002')}\n`);
873
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
874
- assert.equal(code, 1);
875
- assert.match(errText, /exactly one ADR block/);
876
- });
877
-
878
- it('a record whose filename id mismatches its heading id fails loud', () => {
879
- const root = makeRoot();
880
- seedMigrated(root, { hotIds: ['005'], storeIds: [] });
881
- writeFileSync(join(root, ADR_DIR_REL, 'AD-001-mismatch.md'), `${fm(RECORD_CAP)}\n${adrBlock('002')}\n`);
882
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
883
- assert.equal(code, 1);
884
- assert.match(errText, /does not match the heading id/);
885
- });
886
-
887
- it('a migration with NO writable snapshot base fails loud, monoliths untouched', () => {
888
- const root = makeRoot();
889
- seedLegacy(root, { hot: ['005'], warm: ['003'], cold: ['001'] });
890
- const fileAsBase = join(makeRoot(), 'i-am-a-file');
891
- writeFileSync(fileAsBase, 'x'); // mkdir UNDER a file → ENOTDIR → both bases fail
892
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-07-09'], root, { spawnSync: noGit, fallbackBase: fileAsBase });
893
- assert.equal(code, 1);
894
- assert.match(errText, /no writable snapshot location/);
895
- assert.ok(existsSync(join(root, WARM_REL)), 'monoliths untouched when the snapshot cannot be written');
896
- });
897
-
898
- it('defaultRegenerateIndex: a successful subprocess (status 0) → ok:true with the trimmed stdout', () => {
899
- const r = defaultRegenerateIndex('/tmp/anyroot', '2026-07-09', { existsSync: () => true, spawnSync: () => ({ status: 0, stdout: 'Wrote docs/ai/index.md\n' }) });
900
- assert.equal(r.ok, true);
901
- assert.match(r.detail, /Wrote docs\/ai\/index\.md/);
902
- });
903
-
904
- it('migrate on a tree with NO monolith and NO store → a stated "nothing to migrate"', () => {
905
- const root = makeRoot();
906
- mkdirSync(join(root, 'docs', 'ai'), { recursive: true });
907
- writeFileSync(join(root, HOT_REL), tierText(500, '# ADRs', [adrBlock('005')]));
908
- const { code, text } = run(['--migrate', '--today=2026-07-09'], root);
909
- assert.equal(code, 0);
910
- assert.match(text, /nothing to migrate/);
911
- });
912
-
913
- it('migrate --apply with a FAILING index regen degrades loudly (migration still exit 0)', () => {
914
- const root = makeRoot();
915
- seedLegacy(root, { hot: ['005'], warm: ['003'], cold: ['001'] });
916
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-07-09'], root, { regen: () => ({ ok: false, detail: 'boom' }) });
917
- assert.equal(code, 0);
918
- assert.match(errText, /NOT regenerated/);
919
- });
920
-
921
- it('--write-navigator on an empty tree → a stated skip', () => {
922
- const root = makeRoot();
923
- mkdirSync(join(root, 'docs', 'ai'), { recursive: true });
924
- const { code, text } = run(['--write-navigator'], root);
925
- assert.equal(code, 0);
926
- assert.match(text, /SKIP — no ADR substrate/);
927
- });
928
-
929
- it('--write-navigator with a FAILING index regen degrades loudly (exit 0)', () => {
930
- const root = makeRoot();
931
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
932
- const { code, errText } = run(['--write-navigator', '--today=2026-07-09'], root, { regen: () => ({ ok: false, detail: 'boom' }) });
933
- assert.equal(code, 0);
934
- assert.match(errText, /NOT regenerated/);
935
- });
936
-
937
- it('a SINGLE HOT entry over cap fails loud (cannot be reduced below one)', () => {
938
- const root = makeRoot();
939
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
940
- const block = adrBlock('005', { body: 12 });
941
- const probe = tierText(9999, '# ADRs', [block]);
942
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, '# ADRs', [block]));
943
- const { code, errText } = run(['--today=2026-07-09'], root);
944
- assert.equal(code, 1);
945
- assert.match(errText, /cannot be reduced/);
946
- });
947
-
948
- it('rotate refuses a DIVERGENT-body crash-resume record', () => {
949
- const root = makeRoot();
950
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
951
- const blocks = ['005', '006', '007', '008'].map((id) => adrBlock(id));
952
- const probe = tierText(9999, '# ADRs', blocks);
953
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, '# ADRs', blocks)); // AD-005 overflows
954
- writeFileSync(join(root, ADR_DIR_REL, 'AD-005-decision-005.md'), `${fm(RECORD_CAP)}\n## AD-005 — Decision 005\n\n**Date:** 2026-01-01\n\nDIVERGENT body\n`);
955
- const { code, errText } = run(['--today=2026-07-09'], root);
956
- assert.equal(code, 1);
957
- assert.match(errText, /diverges from the freshly-exploded block/);
958
- });
959
-
960
- it('rotate --dry-run prints the move-set and writes nothing', () => {
961
- const root = makeRoot();
962
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
963
- const blocks = ['005', '006', '007', '008'].map((id) => adrBlock(id));
964
- const probe = tierText(9999, '# ADRs', blocks);
965
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, '# ADRs', blocks));
966
- const before = readFileSync(join(root, HOT_REL), 'utf8');
967
- const { code, text } = run(['--dry-run', '--today=2026-07-09'], root);
968
- assert.equal(code, 0);
969
- assert.match(text, /DRY-RUN/);
970
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), before);
971
- });
972
- });
973
-
974
- describe('usage', () => {
975
- it('an unknown argument is a loud exit 2', () => {
976
- const { code, errText } = run(['--frobnicate'], makeRoot());
977
- assert.equal(code, 2);
978
- assert.match(errText, /Unknown argument/);
979
- });
980
- it('--help prints usage and exits 0', () => {
981
- const { code, text } = run(['--help'], makeRoot());
982
- assert.equal(code, 0);
983
- assert.match(text, /Usage: archive-decisions/);
984
- });
985
- });
986
-
987
- // ── reference integrity — inbound anchor rewrite + check assertions (the anchor-orphan fix) ────
988
- //
989
- // Rotation/migration move ADR blocks out of HOT while inbound `decisions.md#ad-NNN…` links keep
990
- // pointing at the old home. The write passes rewrite those links (monolith forms too under
991
- // migrate) under a conservation invariant, `--check` asserts every inbound ADR reference
992
- // resolves, and the exported verifier refuses a dropped/altered rewrite with nothing written.
993
- // Fenced occurrences never count; inline code is treated as live (a stated limitation).
994
-
995
- const writeDoc = (root, rel, text) => {
996
- mkdirSync(dirname(join(root, rel)), { recursive: true });
997
- writeFileSync(join(root, rel), text);
998
- };
999
-
1000
- // An over-cap migrated-shape HOT (no monolith): cap = rendered - 1 → exactly the oldest explodes.
1001
- const seedOverCapHot = (root, ids) => {
1002
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
1003
- const blocks = ids.map((id) => adrBlock(id));
1004
- const preamble = '# ADRs\n\n> Newest at the bottom.';
1005
- const probe = tierText(9999, preamble, blocks);
1006
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, preamble, blocks));
1007
- };
1008
-
1009
- describe('reference integrity — rotate/migrate rewrite inbound links, --check asserts them', () => {
1010
- // Legacy tree whose migrate moves AD-001…AD-005 (HOT overflows by one) and retains AD-006…AD-008,
1011
- // with inbound links at two depths: pages (needs ../) and history (monolith sibling).
1012
- const seedMigrateFixture = (root) => {
1013
- seedLegacy(root, { hot: ['005', '006', '007', '008'], warm: ['003', '004'], cold: ['001', '002'], hotCapDelta: -1 });
1014
- writeDoc(root, 'docs/ai/pages/spec.md', [
1015
- 'hot [AD-005](../decisions.md#ad-005--decision-005)',
1016
- 'warm [AD-003](../history/decisions-archive.md#ad-003--decision-003)',
1017
- '',
1018
- ].join('\n'));
1019
- writeDoc(root, 'docs/ai/history/notes.md', 'cold sibling [AD-001](decisions-archive-early.md#ad-001--decision-001)\n');
1020
- };
1021
-
1022
- it('rotate rewrites inbound decisions.md anchors to record links, fragment preserved', () => {
1023
- const root = makeRoot();
1024
- seedOverCapHot(root, ['001', '002', '003', '004']);
1025
- writeDoc(root, 'docs/ai/pages/spec.md', '# Spec\n\nsee [AD-001](../decisions.md#ad-001--decision-001) for the decision.\n');
1026
- const { code, errText } = run(['--today=2026-08-07'], root);
1027
- assert.equal(code, 0, errText);
1028
- const text = readFileSync(join(root, 'docs/ai/pages/spec.md'), 'utf8');
1029
- assert.match(text, /\[AD-001\]\(\.\.\/adr\/AD-001-decision-001\.md#ad-001--decision-001\)/);
1030
- assert.doesNotMatch(text, /decisions\.md#ad-001(?!-)|\(\.\.\/decisions\.md/);
1031
- });
1032
-
1033
- it('rotate rewrite is count-preserving: every moved-id link rewritten, all other bytes identical', () => {
1034
- const root = makeRoot();
1035
- seedOverCapHot(root, ['001', '002', '003', '004']);
1036
- const spec = [
1037
- '# Spec',
1038
- '',
1039
- 'moved [AD-001](../decisions.md#ad-001--decision-001) and inline `../decisions.md#ad-001--decision-001` on one line.',
1040
- 'retained [AD-004](../decisions.md#ad-004--decision-004) stays.',
1041
- 'negatives: [other](../other-decisions.md#ad-001--decision-001) and [bare](#ad-001--decision-001).',
1042
- '',
1043
- ].join('\n');
1044
- writeDoc(root, 'docs/ai/pages/spec.md', spec);
1045
- writeDoc(root, 'docs/ai/history/notes.md', 'notes: [AD-001](../decisions.md#ad-001--decision-001)\n');
1046
- const { code, errText } = run(['--today=2026-08-07'], root);
1047
- assert.equal(code, 0, errText);
1048
- assert.equal(readFileSync(join(root, 'docs/ai/pages/spec.md'), 'utf8'), [
1049
- '# Spec',
1050
- '',
1051
- 'moved [AD-001](../adr/AD-001-decision-001.md#ad-001--decision-001) and inline `../adr/AD-001-decision-001.md#ad-001--decision-001` on one line.',
1052
- 'retained [AD-004](../decisions.md#ad-004--decision-004) stays.',
1053
- 'negatives: [other](../other-decisions.md#ad-001--decision-001) and [bare](#ad-001--decision-001).',
1054
- '',
1055
- ].join('\n'));
1056
- assert.equal(readFileSync(join(root, 'docs/ai/history/notes.md'), 'utf8'), 'notes: [AD-001](../adr/AD-001-decision-001.md#ad-001--decision-001)\n');
1057
- });
1058
-
1059
- it('rotate dry-run prints the rewrite set and writes nothing', () => {
1060
- const root = makeRoot();
1061
- seedOverCapHot(root, ['001', '002', '003', '004']);
1062
- const spec = 'see [AD-001](../decisions.md#ad-001--decision-001).\n';
1063
- writeDoc(root, 'docs/ai/pages/spec.md', spec);
1064
- const hotBefore = readFileSync(join(root, HOT_REL), 'utf8');
1065
- const { code, text } = run(['--dry-run', '--today=2026-08-07'], root);
1066
- assert.equal(code, 0, text);
1067
- assert.match(text, /docs\/ai\/pages\/spec\.md:1 decisions\.md#ad-001--decision-001 → adr\/AD-001-decision-001\.md#ad-001--decision-001/);
1068
- assert.equal(readFileSync(join(root, 'docs/ai/pages/spec.md'), 'utf8'), spec, 'the doc is byte-unchanged');
1069
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), hotBefore, 'HOT is byte-unchanged');
1070
- assert.deepEqual(adrFiles(root), [], 'no record written on a dry-run');
1071
- });
1072
-
1073
- it('--check exits 1 listing every stale decisions.md anchor with file:line', () => {
1074
- const root = makeRoot();
1075
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: ['001'] });
1076
- writeDoc(root, 'docs/ai/pages/spec.md', [
1077
- 'stale-but-archived [AD-001](../decisions.md#ad-001--decision-001)',
1078
- 'nonexistent [AD-099](../decisions.md#ad-099--gone)',
1079
- '',
1080
- ].join('\n'));
1081
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
1082
- assert.equal(code, 1);
1083
- assert.match(errText, /docs\/ai\/pages\/spec\.md:1: .*ad-001/);
1084
- assert.match(errText, /docs\/ai\/pages\/spec\.md:2: .*ad-099/);
1085
- });
1086
-
1087
- it('--check exits 1 with file:line on a dead adr record link (exact filename)', () => {
1088
- const root = makeRoot();
1089
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
1090
- writeDoc(root, 'docs/ai/pages/spec.md', [
1091
- 'good [AD-001](../adr/AD-001-decision-001.md)',
1092
- 'dead [AD-001](../adr/AD-001-wrong-slug.md)',
1093
- '',
1094
- ].join('\n'));
1095
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
1096
- assert.equal(code, 1);
1097
- assert.match(errText, /docs\/ai\/pages\/spec\.md:2: .*AD-001-wrong-slug\.md/);
1098
- assert.doesNotMatch(errText, /spec\.md:1:/, 'the resolving record link is not flagged');
1099
- });
1100
-
1101
- it('--migrate --apply rewrites inbound links including monolith-form anchors, source-relative', () => {
1102
- const root = makeRoot();
1103
- seedMigrateFixture(root);
1104
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-08-07'], root);
1105
- assert.equal(code, 0, errText);
1106
- assert.equal(readFileSync(join(root, 'docs/ai/pages/spec.md'), 'utf8'), [
1107
- 'hot [AD-005](../adr/AD-005-decision-005.md#ad-005--decision-005)',
1108
- 'warm [AD-003](../adr/AD-003-decision-003.md#ad-003--decision-003)',
1109
- '',
1110
- ].join('\n'));
1111
- assert.equal(readFileSync(join(root, 'docs/ai/history/notes.md'), 'utf8'), 'cold sibling [AD-001](../adr/AD-001-decision-001.md#ad-001--decision-001)\n');
1112
- assert.equal(run(['--check', '--today=2026-08-07'], root).code, 0, 'the rewritten tree is green end-to-end');
1113
- });
1114
-
1115
- it('migrate dry-run prints the monolith and HOT rewrite set and writes nothing', () => {
1116
- const root = makeRoot();
1117
- seedMigrateFixture(root);
1118
- const specBefore = readFileSync(join(root, 'docs/ai/pages/spec.md'), 'utf8');
1119
- const notesBefore = readFileSync(join(root, 'docs/ai/history/notes.md'), 'utf8');
1120
- const { code, text } = run(['--migrate', '--today=2026-08-07'], root);
1121
- assert.equal(code, 0, text);
1122
- assert.match(text, /DRY-RUN/);
1123
- assert.match(text, /docs\/ai\/pages\/spec\.md:1 decisions\.md#ad-005--decision-005 → adr\/AD-005-decision-005\.md#ad-005--decision-005/);
1124
- assert.match(text, /docs\/ai\/pages\/spec\.md:2 \.\.\/history\/decisions-archive\.md#ad-003--decision-003 → \.\.\/adr\/AD-003-decision-003\.md#ad-003--decision-003/);
1125
- assert.match(text, /docs\/ai\/history\/notes\.md:1 decisions-archive-early\.md#ad-001--decision-001 → \.\.\/adr\/AD-001-decision-001\.md#ad-001--decision-001/);
1126
- assert.equal(readFileSync(join(root, 'docs/ai/pages/spec.md'), 'utf8'), specBefore);
1127
- assert.equal(readFileSync(join(root, 'docs/ai/history/notes.md'), 'utf8'), notesBefore);
1128
- assert.ok(existsSync(join(root, WARM_REL)) && existsSync(join(root, COLD_REL)), 'monoliths untouched');
1129
- assert.ok(!existsSync(join(root, ADR_DIR_REL)), 'no adr/ tree created on a dry-run');
1130
- });
1131
-
1132
- it('rotate and migrate refuse pre-write when the ADR corpus links a moved id', () => {
1133
- // (a) the HOT preamble links the moved id
1134
- {
1135
- const root = makeRoot();
1136
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
1137
- const preamble = '# ADRs\n\n> see [old](decisions.md#ad-005--decision-005)';
1138
- const blocks = ['005', '006', '007', '008'].map((id) => adrBlock(id));
1139
- const probe = tierText(9999, preamble, blocks);
1140
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, preamble, blocks));
1141
- const before = readFileSync(join(root, HOT_REL), 'utf8');
1142
- const { code, errText } = run(['--today=2026-08-07'], root);
1143
- assert.equal(code, 1);
1144
- assert.match(errText, /docs\/ai\/decisions\.md:\d+/);
1145
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), before, 'HOT untouched');
1146
- assert.deepEqual(adrFiles(root), [], 'no record written');
1147
- }
1148
- // (b) a HOT block body links the moved id
1149
- {
1150
- const root = makeRoot();
1151
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
1152
- const linked = ['## AD-007 — Decision 007', '', '**Date:** 2026-01-01 · **Status:** Accepted', '', 'refers to [x](decisions.md#ad-005--decision-005)'].join('\n');
1153
- const blocks = [adrBlock('005'), adrBlock('006'), linked, adrBlock('008')];
1154
- const probe = tierText(9999, '# ADRs', blocks);
1155
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, '# ADRs', blocks));
1156
- const before = readFileSync(join(root, HOT_REL), 'utf8');
1157
- const { code, errText } = run(['--today=2026-08-07'], root);
1158
- assert.equal(code, 1);
1159
- assert.match(errText, /docs\/ai\/decisions\.md:\d+/);
1160
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), before, 'HOT untouched');
1161
- assert.deepEqual(adrFiles(root), [], 'no record written');
1162
- }
1163
- // (c) an existing adr/ record block links the moved id
1164
- {
1165
- const root = makeRoot();
1166
- seedOverCapHot(root, ['005', '006', '007', '008']);
1167
- writeFileSync(join(root, ADR_DIR_REL, 'AD-001-decision-001.md'), `${fm(RECORD_CAP)}\n## AD-001 — Decision 001\n\n**Date:** 2026-01-01\n\nsee [x](../decisions.md#ad-005--decision-005)\n`);
1168
- const before = readFileSync(join(root, HOT_REL), 'utf8');
1169
- const { code, errText } = run(['--today=2026-08-07'], root);
1170
- assert.equal(code, 1);
1171
- assert.match(errText, /adr\/AD-001-decision-001\.md:\d+/);
1172
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), before, 'HOT untouched');
1173
- assert.deepEqual(adrFiles(root), ['AD-001-decision-001.md'], 'no new record written');
1174
- }
1175
- // (d) a WARM monolith block links a moved id (migrate)
1176
- {
1177
- const root = makeRoot();
1178
- mkdirSync(join(root, 'docs', 'ai', 'history'), { recursive: true });
1179
- writeFileSync(join(root, HOT_REL), tierText(500, '# ADRs', [adrBlock('005')]));
1180
- const warmBlock = ['## AD-003 — Decision 003', '', '**Date:** 2026-01-01', '', 'see [x](../decisions.md#ad-001--decision-001)'].join('\n');
1181
- writeFileSync(join(root, WARM_REL), tierText(500, WARM_PREAMBLE, [warmBlock]));
1182
- writeFileSync(join(root, COLD_REL), tierText(500, COLD_PREAMBLE, [adrBlock('001')]));
1183
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-08-07'], root);
1184
- assert.equal(code, 1);
1185
- assert.match(errText, /docs\/ai\/history\/decisions-archive\.md:\d+/);
1186
- assert.ok(existsSync(join(root, WARM_REL)) && existsSync(join(root, COLD_REL)), 'monoliths untouched');
1187
- assert.ok(!existsSync(join(root, ADR_DIR_REL)), 'no record written');
1188
- assert.ok(!existsSync(join(root, '.git', 'agent-workflow-adr-migration-snapshot-STAMP')), 'no snapshot on the refusal');
1189
- }
1190
- // (e) a COLD monolith block carries a monolith-form link to a moved id (migrate)
1191
- {
1192
- const root = makeRoot();
1193
- mkdirSync(join(root, 'docs', 'ai', 'history'), { recursive: true });
1194
- writeFileSync(join(root, HOT_REL), tierText(500, '# ADRs', [adrBlock('005')]));
1195
- writeFileSync(join(root, WARM_REL), tierText(500, WARM_PREAMBLE, [adrBlock('003')]));
1196
- const coldBlock = ['## AD-001 — Decision 001', '', '**Date:** 2026-01-01', '', 'see [x](decisions-archive.md#ad-003--decision-003)'].join('\n');
1197
- writeFileSync(join(root, COLD_REL), tierText(500, COLD_PREAMBLE, [coldBlock]));
1198
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-08-07'], root);
1199
- assert.equal(code, 1);
1200
- assert.match(errText, /docs\/ai\/history\/decisions-archive-early\.md:\d+/);
1201
- assert.ok(existsSync(join(root, WARM_REL)) && existsSync(join(root, COLD_REL)), 'monoliths untouched');
1202
- assert.ok(!existsSync(join(root, ADR_DIR_REL)), 'no record written');
1203
- }
1204
- });
1205
-
1206
- it('--check exits 1 on a dead reference inside an ADR block body', () => {
1207
- const root = makeRoot();
1208
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
1209
- const hotBlock = ['## AD-005 — Decision 005', '', '**Date:** 2026-01-01', '', 'cites [gone](decisions.md#ad-002--decision-002)'].join('\n');
1210
- writeFileSync(join(root, HOT_REL), tierText(500, '# ADRs', [hotBlock]));
1211
- writeFileSync(join(root, ADR_DIR_REL, 'AD-001-decision-001.md'), `${fm(RECORD_CAP)}\n## AD-001 — Decision 001\n\n**Date:** 2026-01-01\n\ncites [gone too](../decisions.md#ad-099--gone)\n`);
1212
- assert.equal(run(['--write-navigator', '--today=2026-07-09'], root).code, 0);
1213
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
1214
- assert.equal(code, 1);
1215
- assert.match(errText, /docs\/ai\/decisions\.md:\d+: .*ad-002/);
1216
- assert.match(errText, /docs\/ai\/adr\/AD-001-decision-001\.md:\d+: .*ad-099/);
1217
- });
1218
-
1219
- it('--check without an ADR substrate still fails on a matching reference', () => {
1220
- const root = makeRoot();
1221
- writeDoc(root, 'docs/ai/pages/spec.md', 'orphan [AD-001](../decisions.md#ad-001--decision-001)\n');
1222
- const { code, errText } = run(['--check'], root);
1223
- assert.equal(code, 1);
1224
- assert.match(errText, /docs\/ai\/pages\/spec\.md:1/);
1225
-
1226
- const clean = makeRoot();
1227
- writeDoc(clean, 'docs/ai/pages/spec.md', 'no adr links here\n');
1228
- const skip = run(['--check'], clean);
1229
- assert.equal(skip.code, 0);
1230
- assert.match(skip.text, /SKIP — no ADR substrate/);
1231
- });
1232
-
1233
- it('the rewrite conservation verifier refuses a dropped or altered link with nothing written', () => {
1234
- const base = {
1235
- rel: 'docs/ai/pages/spec.md',
1236
- frontLines: 0,
1237
- rewrites: [{ index: 0, line: 1, old: 'decisions.md#ad-001--decision-001', new: 'adr/AD-001-decision-001.md#ad-001--decision-001' }],
1238
- };
1239
- // a dropped link: the output line never received the planned rewrite
1240
- assert.throws(() => verifyRewriteConservation({
1241
- ...base,
1242
- beforeLines: ['see [x](../decisions.md#ad-001--decision-001)', 'tail'],
1243
- afterLines: ['see [x](../decisions.md#ad-001--decision-001)', 'tail'],
1244
- }), (e) => e.exitCode === 1 && /conservation/.test(e.message));
1245
- // an altered byte outside the planned rewrite set
1246
- assert.throws(() => verifyRewriteConservation({
1247
- ...base,
1248
- beforeLines: ['see [x](../decisions.md#ad-001--decision-001)', 'tail'],
1249
- afterLines: ['see [x](../adr/AD-001-decision-001.md#ad-001--decision-001)', 'tail ALTERED'],
1250
- }), (e) => e.exitCode === 1 && /conservation/.test(e.message));
1251
- // the honest plan passes
1252
- assert.doesNotThrow(() => verifyRewriteConservation({
1253
- ...base,
1254
- beforeLines: ['see [x](../decisions.md#ad-001--decision-001)', 'tail'],
1255
- afterLines: ['see [x](../adr/AD-001-decision-001.md#ad-001--decision-001)', 'tail'],
1256
- }));
1257
- });
1258
-
1259
- it('a fenced dead-link sample leaves --check green and survives rotate byte-identically', () => {
1260
- const root = makeRoot();
1261
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: ['001'] });
1262
- writeDoc(root, 'docs/ai/pages/spec.md', ['fenced sample:', '', '```md', 'dead [x](../decisions.md#ad-099--gone)', '```', ''].join('\n'));
1263
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0, 'a fenced dead link never counts');
1264
-
1265
- const root2 = makeRoot();
1266
- seedOverCapHot(root2, ['001', '002', '003', '004']);
1267
- const doc2 = ['```md', 'fenced moved link [x](../decisions.md#ad-001--decision-001)', '```', ''].join('\n');
1268
- writeDoc(root2, 'docs/ai/pages/spec.md', doc2);
1269
- assert.equal(run(['--today=2026-08-07'], root2).code, 0);
1270
- assert.equal(readFileSync(join(root2, 'docs/ai/pages/spec.md'), 'utf8'), doc2, 'the fenced occurrence survives rotate byte-identically');
1271
- });
1272
-
1273
- it('an unclosed fence in a scanned doc aborts BOTH write paths exit 1 with the tree untouched', () => {
1274
- const root = makeRoot();
1275
- seedOverCapHot(root, ['001', '002', '003', '004']);
1276
- writeDoc(root, 'docs/ai/pages/broken.md', '```md\nnever closed\n');
1277
- const hotBefore = readFileSync(join(root, HOT_REL), 'utf8');
1278
- const r = run(['--today=2026-08-07'], root);
1279
- assert.equal(r.code, 1);
1280
- assert.match(r.errText, /never closed/);
1281
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), hotBefore, 'HOT untouched');
1282
- assert.deepEqual(adrFiles(root), [], 'no record written');
1283
-
1284
- const root2 = makeRoot();
1285
- seedLegacy(root2, { hot: ['005'], warm: ['003'], cold: ['001'] });
1286
- writeDoc(root2, 'docs/ai/pages/broken.md', '```md\nnever closed\n');
1287
- const m = run(['--migrate', '--apply', '--today=2026-08-07'], root2);
1288
- assert.equal(m.code, 1);
1289
- assert.match(m.errText, /never closed/);
1290
- assert.ok(existsSync(join(root2, WARM_REL)) && existsSync(join(root2, COLD_REL)), 'monoliths untouched');
1291
- assert.ok(!existsSync(join(root2, ADR_DIR_REL)), 'no record written');
1292
- });
1293
-
1294
- it('the migrate rewrite set never targets a monolith file and written records preserve moved blocks verbatim', () => {
1295
- const root = makeRoot();
1296
- mkdirSync(join(root, 'docs', 'ai', 'history'), { recursive: true });
1297
- writeFileSync(join(root, HOT_REL), tierText(500, '# ADRs', [adrBlock('005')]));
1298
- const warmBlock = ['## AD-003 — Decision 003', '', '**Date:** 2026-01-01', '', 'links retained [AD-005](../decisions.md#ad-005--decision-005)'].join('\n');
1299
- writeFileSync(join(root, WARM_REL), tierText(500, WARM_PREAMBLE, [warmBlock]));
1300
- const dry = run(['--migrate', '--today=2026-08-07'], root);
1301
- assert.equal(dry.code, 0, dry.errText);
1302
- assert.doesNotMatch(dry.text, /history\/decisions-archive\.md:\d+ /, 'no rewrite entry targets a monolith file');
1303
- const applied = run(['--migrate', '--apply', '--today=2026-08-07'], root);
1304
- assert.equal(applied.code, 0, applied.errText);
1305
- const rec = readFileSync(join(root, ADR_DIR_REL, 'AD-003-decision-003.md'), 'utf8');
1306
- assert.match(rec, /links retained \[AD-005\]\(\.\.\/decisions\.md#ad-005--decision-005\)/, 'the moved block is preserved verbatim');
1307
- });
1308
-
1309
- it('D9 negative fixtures stay byte-identical: a different filename and a bare fragment never match', () => {
1310
- const root = makeRoot();
1311
- seedOverCapHot(root, ['001', '002', '003', '004']);
1312
- const doc = 'neg: [a](../my-decisions.md#ad-001--decision-001) [b](#ad-001--decision-001)\n';
1313
- writeDoc(root, 'docs/ai/pages/neg.md', doc);
1314
- const { code, errText } = run(['--today=2026-08-07'], root);
1315
- assert.equal(code, 0, errText);
1316
- assert.equal(readFileSync(join(root, 'docs/ai/pages/neg.md'), 'utf8'), doc);
1317
- });
1318
-
1319
- it('an interrupted state (records + rewrites written, HOT untrimmed) re-runs to completion', () => {
1320
- const root = makeRoot();
1321
- seedOverCapHot(root, ['001', '002', '003', '004']);
1322
- const entry = parseDecisionsText(tierText(999, '# T', [adrBlock('001')]), 'x').entries[0];
1323
- const [rec] = explode([entry], '2026-08-07');
1324
- writeFileSync(join(root, ADR_DIR_REL, rec.fileName), `${rec.frontmatter}\n${rec.block}\n`);
1325
- writeDoc(root, 'docs/ai/pages/spec.md', 'see [AD-001](../adr/AD-001-decision-001.md#ad-001--decision-001)\n');
1326
- const { code, errText } = run(['--today=2026-08-07'], root);
1327
- assert.equal(code, 0, errText);
1328
- assert.deepEqual(idsIn(root, HOT_REL), ['002', '003', '004'], 'the re-run completed the trim');
1329
- assert.equal(run(['--check', '--today=2026-08-07'], root).code, 0);
1330
- });
1331
-
1332
- it('--check stays green on a live tree with resolving anchors', () => {
1333
- const root = makeRoot();
1334
- seedMigrated(root, { hotIds: ['005', '006'], storeIds: ['001'] });
1335
- writeDoc(root, 'docs/ai/pages/spec.md', [
1336
- 'live [AD-005](../decisions.md#ad-005--decision-005)',
1337
- 'archived [AD-001](../adr/AD-001-decision-001.md#ad-001--decision-001)',
1338
- '',
1339
- ].join('\n'));
1340
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0);
1341
- });
1342
-
1343
- it('--migrate --apply --dry-run refuses loudly pre-spend', () => {
1344
- const root = makeRoot();
1345
- seedLegacy(root, { hot: ['005'], warm: ['003'], cold: ['001'] });
1346
- const { code, errText } = run(['--migrate', '--apply', '--dry-run'], root);
1347
- assert.equal(code, 2);
1348
- assert.match(errText, /--migrate --apply --dry-run/);
1349
- assert.ok(existsSync(join(root, WARM_REL)), 'nothing written');
1350
- });
1351
-
1352
- it('a symlinked markdown file in the scan tree refuses loudly (never read or written through)', () => {
1353
- const root = makeRoot();
1354
- seedOverCapHot(root, ['001', '002', '003', '004']);
1355
- writeFileSync(join(root, 'outside.md'), 'outside the docs tree\n');
1356
- mkdirSync(join(root, 'docs', 'ai', 'pages'), { recursive: true });
1357
- symlinkSync(join(root, 'outside.md'), join(root, 'docs/ai/pages/link.md'));
1358
- const hotBefore = readFileSync(join(root, HOT_REL), 'utf8');
1359
- const rotate = run(['--today=2026-08-07'], root);
1360
- assert.equal(rotate.code, 1);
1361
- assert.match(rotate.errText, /link\.md/);
1362
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), hotBefore, 'HOT untouched');
1363
- assert.deepEqual(adrFiles(root), [], 'no record written');
1364
- assert.equal(readFileSync(join(root, 'outside.md'), 'utf8'), 'outside the docs tree\n', 'the symlink target is never touched');
1365
- const check = run(['--check', '--today=2026-08-07'], root);
1366
- assert.equal(check.code, 1);
1367
- assert.match(check.errText, /link\.md/);
1368
-
1369
- const clean = makeRoot();
1370
- seedMigrated(clean, { hotIds: ['005'], storeIds: ['001'] });
1371
- writeFileSync(join(clean, 'notes.txt'), 'plain\n');
1372
- mkdirSync(join(clean, 'docs', 'ai', 'pages'), { recursive: true });
1373
- symlinkSync(join(clean, 'notes.txt'), join(clean, 'docs/ai/pages/notes.txt'));
1374
- assert.equal(run(['--check', '--today=2026-07-09'], clean).code, 0, 'a non-markdown symlink stays an ignored stray');
1375
- });
1376
-
1377
- it('a rewrite-scope file that changed after planning refuses pre-write with the human edit intact', () => {
1378
- const root = makeRoot();
1379
- mkdirSync(join(root, 'docs', 'ai', 'pages'), { recursive: true });
1380
- const rel = 'docs/ai/pages/spec.md';
1381
- const before = 'see [AD-001](../decisions.md#ad-001--decision-001)\n';
1382
- writeFileSync(join(root, rel), before);
1383
- const plan = {
1384
- rel,
1385
- frontmatter: '',
1386
- frontLines: 0,
1387
- beforeLines: before.split('\n'),
1388
- afterLines: before.replace('decisions.md#ad-001--decision-001', 'adr/AD-001-decision-001.md#ad-001--decision-001').split('\n'),
1389
- rewrites: [],
1390
- };
1391
- writeFileSync(join(root, rel), 'humanly edited meanwhile\n');
1392
- assert.throws(() => writeInboundRewrites(root, [plan]), (e) => e.exitCode === 1 && /stale snapshot/.test(e.message));
1393
- assert.equal(readFileSync(join(root, rel), 'utf8'), 'humanly edited meanwhile\n', 'the human edit survives');
1394
- writeFileSync(join(root, rel), before);
1395
- writeInboundRewrites(root, [plan]);
1396
- assert.match(readFileSync(join(root, rel), 'utf8'), /adr\/AD-001-decision-001\.md#ad-001--decision-001/, 'the unchanged file is rewritten');
1397
- });
1398
-
1399
- it('a symlinked directory in the scan tree refuses loudly instead of hiding its subtree', () => {
1400
- const root = makeRoot();
1401
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
1402
- mkdirSync(join(root, 'elsewhere'), { recursive: true });
1403
- writeFileSync(join(root, 'elsewhere', 'notes.md'), 'dead [x](../decisions.md#ad-099--gone)\n');
1404
- symlinkSync(join(root, 'elsewhere'), join(root, 'docs/ai/pages'));
1405
- const { code, errText } = run(['--check', '--today=2026-07-09'], root);
1406
- assert.equal(code, 1);
1407
- assert.match(errText, /docs\/ai\/pages/);
1408
-
1409
- const root2 = makeRoot();
1410
- seedMigrated(root2, { hotIds: ['005'], storeIds: ['001'] });
1411
- symlinkSync(join(root2, 'gone-target'), join(root2, 'docs/ai/dangling'));
1412
- const r2 = run(['--check', '--today=2026-07-09'], root2);
1413
- assert.equal(r2.code, 1);
1414
- assert.match(r2.errText, /dangling symlink/);
1415
- });
1416
-
1417
- it('migrate refuses pre-write when a monolith-form link targets an id outside the moved set', () => {
1418
- const root = makeRoot();
1419
- seedLegacy(root, { hot: ['005'], warm: ['003'], cold: ['001'] });
1420
- writeDoc(root, 'docs/ai/pages/spec.md', 'dead-after-apply [x](../history/decisions-archive.md#ad-777--nope)\n');
1421
- const { code, errText } = run(['--migrate', '--apply', '--today=2026-08-07'], root);
1422
- assert.equal(code, 1);
1423
- assert.match(errText, /docs\/ai\/pages\/spec\.md:1/);
1424
- assert.ok(existsSync(join(root, WARM_REL)) && existsSync(join(root, COLD_REL)), 'monoliths untouched');
1425
- assert.ok(!existsSync(join(root, ADR_DIR_REL)), 'no record written');
1426
- });
1427
-
1428
- it('rotate refuses pre-write when a MOVING block links a retained id', () => {
1429
- const root = makeRoot();
1430
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
1431
- const moving = ['## AD-001 — Decision 001', '', '**Date:** 2026-01-01', '', 'see [x](decisions.md#ad-004--decision-004)'].join('\n');
1432
- const blocks = [moving, adrBlock('002'), adrBlock('003'), adrBlock('004')];
1433
- const probe = tierText(9999, '# ADRs', blocks);
1434
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, '# ADRs', blocks));
1435
- const before = readFileSync(join(root, HOT_REL), 'utf8');
1436
- const { code, errText } = run(['--today=2026-08-07'], root);
1437
- assert.equal(code, 1);
1438
- assert.match(errText, /docs\/ai\/decisions\.md:\d+/);
1439
- assert.match(errText, /RETAINED/);
1440
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), before, 'HOT untouched');
1441
- assert.deepEqual(adrFiles(root), [], 'no record written');
1442
- });
1443
-
1444
- it('rotate refuses pre-write when a MOVING block carries a record-form link', () => {
1445
- const root = makeRoot();
1446
- mkdirSync(join(root, ADR_DIR_REL), { recursive: true });
1447
- const rec = explode(parseDecisionsText(tierText(999, '# T', [adrBlock('001')]), 'x').entries, '2026-08-07')[0];
1448
- writeFileSync(join(root, ADR_DIR_REL, rec.fileName), `${rec.frontmatter}\n${rec.block}\n`);
1449
- const moving = ['## AD-005 — Decision 005', '', '**Date:** 2026-01-01', '', 'see [x](adr/AD-001-decision-001.md)'].join('\n');
1450
- const blocks = [moving, adrBlock('006'), adrBlock('007'), adrBlock('008')];
1451
- const probe = tierText(9999, '# ADRs', blocks);
1452
- writeFileSync(join(root, HOT_REL), tierText(lineCountOf(probe) - 1, '# ADRs', blocks));
1453
- const before = readFileSync(join(root, HOT_REL), 'utf8');
1454
- const { code, errText } = run(['--today=2026-08-07'], root);
1455
- assert.equal(code, 1);
1456
- assert.match(errText, /docs\/ai\/decisions\.md:\d+/);
1457
- assert.match(errText, /record link|relative ADR link/);
1458
- assert.equal(readFileSync(join(root, HOT_REL), 'utf8'), before, 'HOT untouched');
1459
- assert.deepEqual(adrFiles(root), ['AD-001-decision-001.md'], 'no new record written');
1460
- });
1461
-
1462
- it('a record-link match ends exactly at .md — a suffixed or child path is a different target', () => {
1463
- const root = makeRoot();
1464
- seedMigrated(root, { hotIds: ['005'], storeIds: ['001'] });
1465
- writeDoc(root, 'docs/ai/pages/spec.md', [
1466
- 'not-a-record-link [a](../adr/AD-777-zzz.md.bak)',
1467
- 'not-a-record-link [b](../adr/AD-001-decision-001.md/child)',
1468
- '',
1469
- ].join('\n'));
1470
- assert.equal(run(['--check', '--today=2026-07-09'], root).code, 0, 'suffixed and child paths are different filenames, never record-form links');
1471
- });
1472
-
1473
- it('a negative sharing bytes with a valid link on ONE line never poisons the rewrite', () => {
1474
- const root = makeRoot();
1475
- seedOverCapHot(root, ['001', '002', '003', '004']);
1476
- writeDoc(root, 'docs/ai/pages/spec.md', 'both [a](../decisions.md#ad-001--decision-001) and [n](../other-decisions.md#ad-001--decision-001)\n');
1477
- const { code, errText } = run(['--today=2026-08-07'], root);
1478
- assert.equal(code, 0, errText);
1479
- assert.equal(readFileSync(join(root, 'docs/ai/pages/spec.md'), 'utf8'),
1480
- 'both [a](../adr/AD-001-decision-001.md#ad-001--decision-001) and [n](../other-decisions.md#ad-001--decision-001)\n');
1481
- });
1482
-
1483
- it('a drift in ANY planned file refuses the whole rewrite phase with nothing written', () => {
1484
- const root = makeRoot();
1485
- mkdirSync(join(root, 'docs', 'ai', 'pages'), { recursive: true });
1486
- const before1 = 'one [AD-001](../decisions.md#ad-001--decision-001)\n';
1487
- const before2 = 'two [AD-001](../decisions.md#ad-001--decision-001)\n';
1488
- writeFileSync(join(root, 'docs/ai/pages/a.md'), before1);
1489
- writeFileSync(join(root, 'docs/ai/pages/b.md'), before2);
1490
- const planOf = (rel, before) => ({
1491
- rel,
1492
- frontmatter: '',
1493
- frontLines: 0,
1494
- beforeLines: before.split('\n'),
1495
- afterLines: before.replace('decisions.md#ad-001--decision-001', 'adr/AD-001-decision-001.md#ad-001--decision-001').split('\n'),
1496
- rewrites: [],
1497
- });
1498
- const plans = [planOf('docs/ai/pages/a.md', before1), planOf('docs/ai/pages/b.md', before2)];
1499
- writeFileSync(join(root, 'docs/ai/pages/b.md'), 'moved meanwhile\n');
1500
- assert.throws(() => writeInboundRewrites(root, plans), /stale snapshot/);
1501
- assert.equal(readFileSync(join(root, 'docs/ai/pages/a.md'), 'utf8'), before1, 'the earlier planned file is byte-unchanged');
1502
- });
1503
- });