@sabaiway/agent-workflow-kit 20.1.0 → 21.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 (94) hide show
  1. package/CHANGELOG.md +62 -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/package.json +5 -2
  8. package/references/contracts.md +9 -9
  9. package/references/modes/bootstrap.md +3 -3
  10. package/references/modes/commit-guard.md +1 -1
  11. package/references/modes/gates.md +1 -1
  12. package/references/modes/recommendations.md +2 -2
  13. package/references/modes/upgrade.md +4 -4
  14. package/references/scripts/{archive-caps.mjs → archives/archive-caps.mjs} +1 -1
  15. package/references/scripts/{archive-changelog.mjs → archives/archive-changelog.mjs} +7 -9
  16. package/references/scripts/{archive-decisions.mjs → archives/archive-decisions.mjs} +13 -10
  17. package/references/scripts/{archive-issues.mjs → archives/archive-issues.mjs} +7 -8
  18. package/references/scripts/{check-docs-size.mjs → docs-size/check-docs-size.mjs} +3 -4
  19. package/references/scripts/docs-size/index.mjs +2 -0
  20. package/references/scripts/family.json +43 -0
  21. package/references/scripts/family.mjs +90 -0
  22. package/references/scripts/gates/kit-command-gates.mjs +117 -0
  23. package/references/scripts/{migrate-gates.mjs → gates/migrate-gates.mjs} +30 -13
  24. package/references/scripts/{install-git-hooks.mjs → git-hooks/install-git-hooks.mjs} +50 -38
  25. package/references/scripts/run.mjs +74 -0
  26. package/references/scripts/shared/index.mjs +3 -0
  27. package/references/scripts/shared/project-root.mjs +11 -0
  28. package/references/scripts/spec-schema/index.mjs +2 -0
  29. package/references/shared/composition-handoff.md +1 -1
  30. package/references/shared/deploy-tail.md +2 -2
  31. package/references/templates/SPEC_TEMPLATE.md +1 -1
  32. package/references/templates/adr-record.md +3 -3
  33. package/tools/apply-danger-check.mjs +9 -5
  34. package/tools/atomic-write.mjs +3 -1
  35. package/tools/checker-gates-read.mjs +4 -1
  36. package/tools/direct-run.mjs +2 -0
  37. package/tools/distribution-files/retired.mjs +99 -0
  38. package/tools/distribution-files/scripts.mjs +67 -52
  39. package/tools/ensure-configs.mjs +21 -21
  40. package/tools/ensure-ops.mjs +60 -18
  41. package/tools/ensure-specs.mjs +82 -47
  42. package/tools/ensure-vocabulary.mjs +4 -4
  43. package/tools/epic-shape-cli.mjs +1 -1
  44. package/tools/epic-shape-ledger.mjs +1 -1
  45. package/tools/epic-shape.mjs +1 -1
  46. package/tools/family-registry.mjs +3 -1
  47. package/tools/feedback-record-cli.mjs +1 -1
  48. package/tools/fold-scope.mjs +2 -2
  49. package/tools/gates-declaration.mjs +8 -4
  50. package/tools/git-hooks.mjs +90 -65
  51. package/tools/jev-connect.mjs +1 -1
  52. package/tools/jev-guide.mjs +1 -1
  53. package/tools/jev-skill.mjs +1 -1
  54. package/tools/known-footprint.mjs +7 -29
  55. package/tools/node-evidence.mjs +29 -15
  56. package/tools/now-cli.mjs +1 -1
  57. package/tools/payload-prune.mjs +53 -58
  58. package/tools/plan-shape-cli.mjs +1 -1
  59. package/tools/plan-shape.mjs +1 -1
  60. package/tools/project-rules/rules-record.mjs +1 -1
  61. package/tools/queue-audit-cli.mjs +1 -1
  62. package/tools/queue-audit.mjs +2 -2
  63. package/tools/queue-purge-archive.mjs +1 -1
  64. package/tools/queue-purge-cli.mjs +1 -1
  65. package/tools/queue-purge.mjs +1 -1
  66. package/tools/recommendations.mjs +22 -19
  67. package/tools/script-priors.mjs +31 -3
  68. package/tools/source-size/piles.mjs +1 -1
  69. package/tools/spec-adoption.mjs +1 -1
  70. package/tools/spec-check-ops.mjs +2 -2
  71. package/tools/spec-check.mjs +2 -2
  72. package/tools/spec-coverage.mjs +1 -1
  73. package/tools/tier-guide.mjs +1 -1
  74. package/tools/transition/index.mjs +1 -1
  75. package/tools/upgrade-runlist.mjs +1 -1
  76. package/tools/write-lanes.mjs +2 -2
  77. package/references/scripts/_expect-shim.mjs +0 -41
  78. package/references/scripts/archive-caps.test.mjs +0 -321
  79. package/references/scripts/archive-changelog.test.mjs +0 -560
  80. package/references/scripts/archive-conservation.test.mjs +0 -466
  81. package/references/scripts/archive-decisions.test.mjs +0 -1503
  82. package/references/scripts/archive-issues.test.mjs +0 -825
  83. package/references/scripts/archiver-structure.test.mjs +0 -84
  84. package/references/scripts/check-docs-size-cli.test.mjs +0 -325
  85. package/references/scripts/check-docs-size-ensure.test.mjs +0 -360
  86. package/references/scripts/check-docs-size.test.mjs +0 -395
  87. package/references/scripts/install-git-hooks-repo-exec.test.mjs +0 -185
  88. package/references/scripts/install-git-hooks.test.mjs +0 -241
  89. package/references/scripts/markdown-blocks.test.mjs +0 -310
  90. package/references/scripts/migrate-gates-branches.test.mjs +0 -302
  91. package/references/scripts/migrate-gates.test.mjs +0 -517
  92. package/references/scripts/spec-schema.test.mjs +0 -352
  93. /package/references/scripts/{markdown-blocks.mjs → shared/markdown-blocks.mjs} +0 -0
  94. /package/references/scripts/{spec-schema.mjs → spec-schema/spec-schema.mjs} +0 -0
@@ -1,241 +0,0 @@
1
- // install-git-hooks.test.mjs — the pre-commit installer on a deployed copy: the hooks path comes from git
2
- // plumbing (a linked worktree resolves ITS OWN hooks path); the guard, rules-check and layout-check lines
3
- // are carried by role, fail closed on a duplicate and refuse a bad flag value, writing nothing. Every child
4
- // runs with each inherited GIT_* variable stripped, so a hook's environment never leaks in.
5
-
6
- import { describe, it } from 'node:test';
7
- import assert from 'node:assert/strict';
8
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, cpSync, existsSync, realpathSync } from 'node:fs';
9
- import { tmpdir } from 'node:os';
10
- import { basename, join, dirname, resolve } from 'node:path';
11
- import { fileURLToPath } from 'node:url';
12
- import { spawnSync } from 'node:child_process';
13
-
14
- const HERE = dirname(fileURLToPath(import.meta.url));
15
- const INSTALLER_SRC = join(HERE, 'install-git-hooks.mjs');
16
- const MALFORMED_PACKAGE_JSON = '{ not json';
17
- const [NAMED_PACKAGE_JSON, NAMED_FIXTURE] = ['{"name":"named-fixture"}', 'named-fixture'];
18
- const WIN32 = ['--import', 'data:text/javascript,Object.defineProperty(process,"platform",{value:"win32"})'];
19
- const BACKSLASH = String.fromCharCode(92);
20
- const SHELL_ACTIVE = [34, 36, 96, 92, 13, 10].map((code) => String.fromCharCode(code)).filter((ch) => process.platform !== 'win32' || ch !== BACKSLASH);
21
- const shown = (path) => (process.platform === 'win32' ? path.replaceAll(BACKSLASH, '/') : path);
22
-
23
- const BASE_ENV = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^[Gg][Ii][Tt]_/.test(key)));
24
- const envAt = (home) => ({
25
- ...BASE_ENV, HOME: home, XDG_CONFIG_HOME: join(home, '.config'), LC_ALL: 'C', GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null',
26
- GIT_CONFIG_NOSYSTEM: '1', GIT_ATTR_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'p', GIT_AUTHOR_EMAIL: 'p@e', GIT_COMMITTER_NAME: 'p', GIT_COMMITTER_EMAIL: 'p@e',
27
- });
28
-
29
- // A child that never started or was killed has no exit status to judge — it fails the cell outright.
30
- const spawnChecked = (command, args, cwd) => {
31
- const r = spawnSync(command, args, { cwd, env: envAt(cwd), encoding: 'utf8' });
32
- if (r.error) throw r.error;
33
- if (r.signal !== null) throw new Error(`${command} was killed by ${r.signal}`);
34
- return r;
35
- };
36
- const succeeds = (r) => { assert.equal(r.status, 0, r.stderr); return r; };
37
- const git = (cwd, ...args) => succeeds(spawnChecked('git', args, cwd));
38
-
39
- // The installer anchors ROOT at <its dir>/.. — deploy it into a fixture's scripts/ like a consumer.
40
- const mkProject = () => {
41
- const root = realpathSync(mkdtempSync(join(tmpdir(), 'install-hooks-')));
42
- const g = (...a) => git(root, ...a);
43
- g('init', '-q');
44
- mkdirSync(join(root, 'scripts'), { recursive: true });
45
- cpSync(INSTALLER_SRC, join(root, 'scripts', 'install-git-hooks.mjs'));
46
- writeFileSync(join(root, 'guard.mjs'), '// a stand-in commit-guard tool\n');
47
- writeFileSync(join(root, 'base.txt'), 'base\n');
48
- for (const args of [['add', '-A'], ['commit', '-qm', 'base']]) g(...args);
49
- return { root, g };
50
- };
51
- const inProject = (cell) => () => { const fx = mkProject(); try { cell(fx); } finally { rmSync(fx.root, { recursive: true, force: true }); } };
52
-
53
- const runInstaller = (root, args = [], pre = []) =>
54
- spawnChecked(process.execPath, [...pre, join(root, 'scripts', 'install-git-hooks.mjs'), ...args], root);
55
- const installs = (...a) => succeeds(runInstaller(...a));
56
-
57
- const hooksPathOf = (root) => resolve(root, git(root, 'rev-parse', '--git-path', 'hooks').stdout.trim());
58
- const markerFor = (name) => `# ${name}:install-git-hooks.mjs`;
59
- const readHook = (root) => readFileSync(join(hooksPathOf(root), 'pre-commit'), 'utf8');
60
- const stub = (root, rel) => (mkdirSync(dirname(join(root, rel)), { recursive: true }), writeFileSync(join(root, rel), '// a stand-in tool\n'), join(root, rel));
61
-
62
- // The hook the 8.3.0 installer body writes with no guard: the six docs and scripts lines.
63
- const plainHook = (root) => `#!/usr/bin/env bash
64
- ${markerFor(basename(root))}
65
- # Auto-installed by scripts/install-git-hooks.mjs (run it from "prepare" or by hand).
66
- # Runs the docs cap-validator + index-freshness gate + rotation-freshness checks
67
- # + the scripts/ test suite before every commit, so files cannot drift over their
68
- # declared maxLines, the auto-generated index.md cannot silently go stale, stale
69
- # archive entries never reach a commit, and regressions to the scripts are caught.
70
- set -e
71
- node scripts/check-docs-size.mjs
72
- node scripts/check-docs-size.mjs --check-index
73
- node scripts/archive-changelog.mjs --check
74
- node scripts/archive-issues.mjs --check
75
- node scripts/archive-decisions.mjs --check
76
- node --test scripts/*.test.mjs
77
- `;
78
- const LOCAL_LINE = 'if [ -f scripts/pre-commit.local ]; then bash scripts/pre-commit.local; fi';
79
- // The plain hook every write carries: the 8.3.0 hook with, right after set -e, one `# ` comment naming
80
- // scripts/pre-commit.local (its wording is free, so it is read from the written hook) and the exact local line.
81
- const localHook = (root) => {
82
- const lines = readHook(root).split('\n');
83
- const comment = lines[lines.indexOf('set -e') + 1];
84
- assert.ok(comment?.startsWith('# ') && comment.includes('scripts/pre-commit.local'), `right after set -e a # comment names scripts/pre-commit.local, got ${JSON.stringify(comment)}`);
85
- assert.deepEqual(lines.filter((l) => l.includes('scripts/pre-commit.local')), [comment, LOCAL_LINE], 'the comment and the local line are the only lines naming scripts/pre-commit.local');
86
- return plainHook(root).replace('set -e\n', `set -e\n${comment}\n${LOCAL_LINE}\n`);
87
- };
88
- const line = (path, role) => `node "${role ? shown(path) : path}" --check${role ? ` # ${role}` : ''}\n`;
89
-
90
- describe('install-git-hooks — beside no package.json, or a malformed one, the marker names the directory basename', () => {
91
- it('no package.json, then a MALFORMED one — the marker names the directory basename', inProject(({ root }) => {
92
- const expected = markerFor(basename(root));
93
- installs(root);
94
- assert.ok(readHook(root).split('\n').includes(expected));
95
- writeFileSync(join(root, 'package.json'), MALFORMED_PACKAGE_JSON);
96
- installs(root);
97
- assert.ok(readHook(root).split('\n').includes(expected));
98
- }));
99
-
100
- it('a named package.json wins — the marker carries its name', inProject(({ root }) => {
101
- writeFileSync(join(root, 'package.json'), NAMED_PACKAGE_JSON);
102
- installs(root);
103
- assert.ok(readHook(root).split('\n').includes(markerFor(NAMED_FIXTURE)));
104
- }));
105
- });
106
-
107
- describe('install-git-hooks — the hooks path comes from git plumbing (C7)', () => {
108
- it('a normal repo installs at the git-path hooks location', inProject(({ root }) => {
109
- installs(root);
110
- assert.ok(existsSync(join(hooksPathOf(root), 'pre-commit')), 'the hook lands where git says hooks live');
111
- }));
112
-
113
- it('a LINKED WORKTREE installs at ITS OWN git-path hooks (never a hardcoded <worktree>/.git/hooks)', inProject(({ root, g }) => {
114
- const wt = join(root, '..', `wt-${Date.now() % 1e6}`);
115
- g('worktree', 'add', '-q', wt);
116
- try {
117
- mkdirSync(join(wt, 'scripts'), { recursive: true });
118
- cpSync(INSTALLER_SRC, join(wt, 'scripts', 'install-git-hooks.mjs'));
119
- installs(wt);
120
- const expected = join(hooksPathOf(wt), 'pre-commit');
121
- assert.ok(existsSync(expected), `the worktree hook lands at git's own answer (${expected})`);
122
- assert.ok(!existsSync(join(wt, '.git', 'hooks', 'pre-commit')), 'never a literal <worktree>/.git/hooks (a worktree .git is a FILE)');
123
- } finally {
124
- rmSync(wt, { recursive: true, force: true });
125
- }
126
- }));
127
- });
128
-
129
- describe('install-git-hooks — the commit-guard arm persists (C8)', () => {
130
- it('an armed guard SURVIVES a later flagless re-run (carried forward from the managed hook)', inProject(({ root }) => {
131
- assert.equal(runInstaller(root, ['--commit-guard', 'guard.mjs']).status, 0);
132
- assert.match(readHook(root), /guard\.mjs" --check/, 'the guard line is written armed');
133
- assert.equal(runInstaller(root).status, 0, 'the flagless canonical re-run succeeds');
134
- assert.match(readHook(root), /guard\.mjs" --check/, 'the armed guard line survives a flagless re-run');
135
- }));
136
-
137
- it('--no-commit-guard is the ONLY consented disable; combining both flags is a usage error', inProject(({ root }) => {
138
- assert.equal(runInstaller(root, ['--commit-guard', 'guard.mjs']).status, 0);
139
- assert.equal(runInstaller(root, ['--no-commit-guard']).status, 0);
140
- assert.doesNotMatch(readHook(root), /" --check$/m, 'the guard line is removed on the explicit disable');
141
- const both = runInstaller(root, ['--commit-guard', 'guard.mjs', '--no-commit-guard']);
142
- assert.equal(both.status, 2, 'both flags together are a usage error, never an order-dependent pick');
143
- }));
144
-
145
- it('a DUPLICATED/malformed guard line in the managed hook fails CLOSED on a flagless re-run', inProject(({ root }) => {
146
- assert.equal(runInstaller(root, ['--commit-guard', 'guard.mjs']).status, 0);
147
- const armed = readHook(root);
148
- const guardLine = armed.split('\n').find((l) => /" --check$/.test(l));
149
- writeFileSync(join(hooksPathOf(root), 'pre-commit'), `${armed}${guardLine}\n`); // duplicate the guard line
150
- const r = runInstaller(root);
151
- assert.equal(r.status, 1, 'two guard lines are ambiguous — fail closed, never guess');
152
- assert.match(r.stderr, /guard/i);
153
- }));
154
- });
155
-
156
- describe('spec:init-project/S58 install-git-hooks — the rules-check and layout-check lines on a deployed copy', () => {
157
- it('each flag writes its resolved path and role comment, ordered docs, rules, layout, guard; a flagless re-run keeps all three; --commit-guard replaces and --no-commit-guard drops the guard alone', inProject(({ root }) => {
158
- const [rules, layout, guard, guard2] = ['tools/rules-cli.mjs', 'tools/source-size-check.mjs', 'guard.mjs', 'g2/guard.mjs'].map((rel) => stub(root, rel));
159
- installs(root, ['--commit-guard', 'guard.mjs']);
160
- installs(root, ['--layout-check', 'tools/source-size-check.mjs']);
161
- assert.equal(readHook(root), localHook(root) + line(layout, 'layout-check') + line(guard), 'the --layout-check run carried the guard line');
162
- installs(root, ['--rules-check', rules]);
163
- const armed = localHook(root) + line(rules, 'rules-check') + line(layout, 'layout-check');
164
- assert.equal(readHook(root), armed + line(guard), 'each arming run carried the other armed lines');
165
- assert.match(installs(root).stdout, /already up to date/, 'a flagless re-run keeps all three');
166
- assert.equal(readHook(root), armed + line(guard));
167
- installs(root, ['--commit-guard', guard2]);
168
- assert.equal(readHook(root), armed + line(guard2), '--commit-guard replaces the guard line alone');
169
- installs(root, ['--no-commit-guard']);
170
- assert.equal(readHook(root), armed, '--no-commit-guard drops the guard line alone');
171
- }));
172
-
173
- it('a legacy guard line whose file name is rules-cli.mjs keeps the guard role beside a rules line', inProject(({ root }) => {
174
- const [legacy, rules] = ['legacy/rules-cli.mjs', 'tools/rules-cli.mjs'].map((rel) => stub(root, rel));
175
- installs(root, ['--commit-guard', legacy]);
176
- installs(root, ['--rules-check', rules]);
177
- const expected = localHook(root) + line(rules, 'rules-check') + line(legacy);
178
- assert.equal(readHook(root), expected);
179
- installs(root);
180
- assert.equal(readHook(root), expected, 'the flagless re-run keeps the legacy line as the guard');
181
- }));
182
-
183
- it('two lines of one role exit 1 naming that role, the hook unchanged', inProject(({ root }) => {
184
- installs(root, ['--rules-check', stub(root, 'tools/rules-cli.mjs'), '--layout-check', stub(root, 'tools/source-size-check.mjs')]);
185
- const armed = readHook(root);
186
- for (const role of ['rules-check', 'layout-check']) {
187
- const roleLine = armed.split('\n').find((l) => l.endsWith(` --check # ${role}`));
188
- assert.ok(roleLine, `the ${role} line is armed`);
189
- writeFileSync(join(hooksPathOf(root), 'pre-commit'), `${armed}${roleLine}\n`);
190
- const r = runInstaller(root);
191
- assert.equal(r.status, 1, r.stderr);
192
- assert.match(r.stderr, new RegExp(`carries 2 ${role} lines`));
193
- assert.equal(readHook(root), `${armed}${roleLine}\n`);
194
- }
195
- }));
196
-
197
- it('over a hook with no rules or layout line, a flagless and a --commit-guard run write the plain hook with the comment line and the local line right after set -e', inProject(({ root }) => {
198
- installs(root);
199
- assert.equal(readHook(root), localHook(root));
200
- installs(root, ['--commit-guard', 'guard.mjs']);
201
- assert.equal(readHook(root), localHook(root) + line(join(root, 'guard.mjs')));
202
- }));
203
-
204
- it('a wrong file name, a shell-active path or a missing value exits 2, a missing file exits 1, each writing nothing', inProject(({ root }) => {
205
- const [rules, layout] = ['tools/rules-cli.mjs', 'tools/source-size-check.mjs'].map((rel) => stub(root, rel));
206
- installs(root, ['--commit-guard', 'guard.mjs']);
207
- const before = readHook(root);
208
- const cases = [
209
- [['--rules-check', layout], 2, /--rules-check takes a path to rules-cli\.mjs/],
210
- [['--layout-check', rules], 2, /--layout-check takes a path to source-size-check\.mjs/],
211
- ...SHELL_ACTIVE.flatMap((ch, at) => [
212
- [['--rules-check', join(root, `r${at}${ch}x`, 'rules-cli.mjs')], 2, /a backslash, CR or LF/],
213
- [['--layout-check', join(root, `l${at}${ch}x`, 'source-size-check.mjs')], 2, /a backslash, CR or LF/],
214
- ]),
215
- [['--rules-check', join(root, 'nowhere', 'rules-cli.mjs')], 1, /does not exist/],
216
- [['--layout-check', join(root, 'nowhere', 'source-size-check.mjs')], 1, /does not exist/],
217
- [['--rules-check'], 2, /--rules-check needs a path/],
218
- [['--layout-check'], 2, /--layout-check needs a path/],
219
- ];
220
- for (const [args, status, message] of cases) {
221
- const r = runInstaller(root, args);
222
- assert.equal(r.status, status, `${JSON.stringify(args)}: ${r.stderr}`);
223
- assert.match(r.stderr, message);
224
- assert.equal(readHook(root), before, `${JSON.stringify(args)} wrote nothing`);
225
- }
226
- }));
227
-
228
- it('an ordinary win32 path, its separators made /, arms and a flagless re-run carries it; on posix it is the backslash refusal', inProject(({ root }) => {
229
- installs(root);
230
- const given = `${root}/a${BACKSLASH}b/rules-cli.mjs`;
231
- const armedAt = stub(root, 'a/b/rules-cli.mjs');
232
- if (process.platform !== 'win32') { // there the backslash is refused, writing nothing
233
- const posix = runInstaller(root, ['--rules-check', given]);
234
- assert.deepEqual([posix.status, /a backslash, CR or LF/.test(posix.stderr), readHook(root)], [2, true, localHook(root)], posix.stderr);
235
- }
236
- installs(root, ['--rules-check', given], WIN32);
237
- assert.equal(readHook(root), localHook(root) + line(armedAt, 'rules-check'));
238
- assert.match(installs(root).stdout, /already up to date/, 'the flagless re-run recognises the win32-armed line');
239
- assert.equal(readHook(root), localHook(root) + line(armedAt, 'rules-check'));
240
- }));
241
- });
@@ -1,310 +0,0 @@
1
- import { describe, it } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { tokenizeMarkdown, findParagraphBreak } from './markdown-blocks.mjs';
4
-
5
- const FM = '---\ntype: history\nlastUpdated: 2026-07-28\nmaxLines: 700\n---\n';
6
- const B = '```';
7
- const T = '~~~';
8
-
9
- describe('frontmatter', () => {
10
- it('splits the leading block and counts its lines, leaving the body byte-exact', () => {
11
- const { frontmatter, frontLines, lines } = tokenizeMarkdown(`${FM}\n# Doc\n\n## 2026-07-20 — a\n`);
12
- assert.equal(frontmatter, FM);
13
- assert.equal(frontLines, 5);
14
- assert.equal(lines[1], '# Doc');
15
- });
16
-
17
- it('recognises CRLF frontmatter', () => {
18
- const { frontmatter, frontLines } = tokenizeMarkdown(`${FM}\n# Doc\n`.replace(/\n/g, '\r\n'));
19
- assert.match(frontmatter, /^---\r\n/);
20
- assert.equal(frontLines, 5);
21
- });
22
-
23
- it('tolerates a document with no frontmatter at all', () => {
24
- const { frontmatter, frontLines, headings } = tokenizeMarkdown('# Doc\n\n## 2026-07-20 — a\n');
25
- assert.equal(frontmatter, '');
26
- assert.equal(frontLines, 0);
27
- assert.equal(headings.length, 2);
28
- });
29
-
30
- it('REFUSES a leading `---` block that is indistinguishable from a thematic break', () => {
31
- assert.throws(
32
- () => tokenizeMarkdown('---\n\n# Doc\n\n## 2026-07-20 — a\n\n---\n\n## 2026-07-19 — b\n', 'docs/ai/changelog.md'),
33
- (err) => {
34
- assert.equal(err.exitCode, 1);
35
- assert.match(err.message, /docs\/ai\/changelog\.md:3:/);
36
- return true;
37
- },
38
- );
39
- });
40
-
41
- it('REFUSES rather than silently demoting frontmatter that holds a YAML comment', () => {
42
- // Demoting it would leave the real frontmatter in the body, so a rebuild writes a fresh one and
43
- // the original is duplicated. Guessing the other way hides content. Both are silent; refuse.
44
- assert.throws(
45
- () => tokenizeMarkdown('---\n# pinned by AD-084\ntype: history\n---\n\n## 2026-07-20 — a\n', 'f.md'),
46
- /f\.md:2:/,
47
- );
48
- });
49
- });
50
-
51
- describe('headings', () => {
52
- it('reports level, index and a trailing-whitespace-free text, keeping raw byte-exact', () => {
53
- const { headings } = tokenizeMarkdown(`${FM}\n## 2026-07-20 — a \n\n### deeper\n`);
54
- assert.deepEqual(headings.map((h) => h.level), [2, 3]);
55
- assert.equal(headings[0].text, '## 2026-07-20 — a');
56
- assert.equal(headings[0].raw, '## 2026-07-20 — a ');
57
- });
58
-
59
- it('sees a heading that carries a CR, so a Windows file parses identically', () => {
60
- const { headings } = tokenizeMarkdown(`${FM}\n## 2026-07-20\n`.replace(/\n/g, '\r\n'));
61
- assert.equal(headings.length, 1);
62
- assert.equal(headings[0].text, '## 2026-07-20');
63
- });
64
-
65
- it('emits an indented heading as a TOKEN so a column-0 grammar can refuse it loudly', () => {
66
- const { headings } = tokenizeMarkdown(`${FM}\n## 2026-07-20 — a\n\n ## 2026-07-19 — indented\n`);
67
- assert.deepEqual(headings.map((h) => h.text), ['## 2026-07-20 — a', ' ## 2026-07-19 — indented']);
68
- });
69
-
70
- it('does not treat a bare hash run without a space as a heading', () => {
71
- const { headings } = tokenizeMarkdown(`${FM}\n##notaheading\n`);
72
- assert.equal(headings.length, 0);
73
- });
74
-
75
- it('a tab after the hashes still makes a heading token (CommonMark allows spaces or tabs)', () => {
76
- const { headings } = tokenizeMarkdown(`${FM}\n##\t2026-07-18 — tab separated\n`);
77
- assert.deepEqual(headings.map((h) => h.level), [2]);
78
- assert.equal(headings[0].text, '##\t2026-07-18 — tab separated');
79
- });
80
- });
81
-
82
- describe('fences', () => {
83
- it('hides headings inside a backtick fence', () => {
84
- const { headings, fencedLines } = tokenizeMarkdown(
85
- `${FM}\n## 2026-07-20 — real\n\n${B}markdown\n## 2026-07-19 — a sample\n${B}\n\nend.\n`,
86
- );
87
- assert.deepEqual(headings.map((h) => h.text), ['## 2026-07-20 — real']);
88
- assert.equal(fencedLines.has(3), true);
89
- assert.equal(fencedLines.has(5), true);
90
- });
91
-
92
- it('a backtick run whose info string contains a backtick is inline code, not a fence', () => {
93
- const { headings } = tokenizeMarkdown(
94
- `${FM}\n${B}a${B} used inline\n\n## 2026-07-20 — a real entry\n\nbody.\n\n${B}\nsample\n${B}\n`,
95
- );
96
- assert.deepEqual(headings.map((h) => h.text), ['## 2026-07-20 — a real entry']);
97
- });
98
-
99
- it('a tilde fence MAY carry backticks in its info string', () => {
100
- const { headings } = tokenizeMarkdown(`${FM}\n${T}a${B}\n## 2026-07-19 — fenced\n${T}\n\n## 2026-07-20 — real\n`);
101
- assert.deepEqual(headings.map((h) => h.text), ['## 2026-07-20 — real']);
102
- });
103
-
104
- it('closes only on the same marker, so a backtick run inside a tilde fence stays content', () => {
105
- const { headings } = tokenizeMarkdown(
106
- `${FM}\n## 2026-07-20 — real\n\n${T}markdown\n${B}\n## 2026-07-19 — nested sample\n${B}\n${T}\n\nend.\n`,
107
- );
108
- assert.deepEqual(headings.map((h) => h.text), ['## 2026-07-20 — real']);
109
- });
110
-
111
- it('needs a closer at least as long as the opener', () => {
112
- const { headings } = tokenizeMarkdown(
113
- `${FM}\n## 2026-07-20 — real\n\n\`\`\`\`\n${B}\n## 2026-07-19 — still fenced\n\`\`\`\`\n\nend.\n`,
114
- );
115
- assert.deepEqual(headings.map((h) => h.text), ['## 2026-07-20 — real']);
116
- });
117
-
118
- it('does not let an info string close a fence', () => {
119
- const { headings } = tokenizeMarkdown(
120
- `${FM}\n## 2026-07-20 — real\n\n${B}markdown\n${B}js\n## 2026-07-19 — still fenced\n${B}\n\nend.\n`,
121
- );
122
- assert.deepEqual(headings.map((h) => h.text), ['## 2026-07-20 — real']);
123
- });
124
-
125
- it('REFUSES an unclosed fence, naming the 1-based file line that opened it', () => {
126
- let caught;
127
- try {
128
- tokenizeMarkdown(`${FM}\n## 2026-07-20 — real\n\n${B}markdown\n## 2026-07-19 — hidden\n`, 'docs/ai/changelog.md');
129
- } catch (err) {
130
- caught = err;
131
- }
132
- assert.ok(caught, 'expected a refusal');
133
- assert.equal(caught.exitCode, 1);
134
- assert.match(caught.message, /docs\/ai\/changelog\.md:9:/);
135
- assert.match(caught.message, /never closed/);
136
- });
137
- });
138
-
139
- describe('findParagraphBreak', () => {
140
- it('skips blank lines that live inside a fence', () => {
141
- const { lines, fencedLines } = tokenizeMarkdown(`${FM}\n## 2026-07-20 — a\n${B}\nx\n\ny\n${B}\n\nafter.\n`);
142
- assert.equal(fencedLines.has(4), true);
143
- assert.equal(findParagraphBreak(lines, fencedLines, 1), 7);
144
- });
145
-
146
- it('returns -1 when no unfenced blank line follows', () => {
147
- const { lines, fencedLines } = tokenizeMarkdown(`${FM}\n## 2026-07-20 — a\nbody.\n`);
148
- assert.equal(findParagraphBreak(lines, fencedLines, 4), -1);
149
- });
150
- });
151
-
152
- // ── properties over generated documents ───────────────────────────────────────────────
153
- //
154
- // The generator builds each document AND its ground truth in the SAME pass, by construction: when
155
- // it emits a fenced region it records those line indexes directly, never by re-deriving them with a
156
- // regex. So the oracle is independent of the tokenizer's logic, and a disagreement is a real
157
- // failure rather than two copies of the same mistake agreeing.
158
- //
159
- // It deliberately emits the shapes that shipped as bugs: unclosed fences mid-document, closers that
160
- // are too short, closers carrying an info string, the other marker inside a fence, backtick inline
161
- // code at column 0, indented headings, trailing whitespace, and both line endings. Seeded, so a
162
- // failure replays from its seed alone.
163
-
164
- const buildDocument = (seed) => {
165
- let state = seed;
166
- // Drawn from the HIGH bits: this LCG's low bit strictly alternates, so `state % 2` is fixed by
167
- // call parity and every other two-apart draw correlates. With the low bits, a backtick fence
168
- // carrying an info string was unreachable in every seed — a generator blind spot that looks like
169
- // coverage.
170
- const rand = (n) => {
171
- state = (state * 1103515245 + 12345) % 2147483648;
172
- return Math.floor(state / 65536) % n;
173
- };
174
-
175
- const eol = rand(2) === 0 ? '\n' : '\r\n';
176
- const rows = [];
177
- const fenced = new Set();
178
- const headings = [];
179
- let unclosedAt = null;
180
-
181
- const pushHeading = () => {
182
- const indent = ' '.repeat(rand(4));
183
- const hashes = '#'.repeat(2 + rand(2));
184
- const body = rand(2) === 0 ? `2026-07-2${rand(9)} — entry` : `2026-7-${rand(9)} — malformed`;
185
- const text = `${indent}${hashes} ${body}`;
186
- headings.push({ index: rows.length, text });
187
- rows.push(text + ' '.repeat(rand(3)));
188
- };
189
-
190
- const pushFence = (allowUnclosed) => {
191
- const char = rand(2) === 0 ? '`' : '~';
192
- const length = 3 + rand(3);
193
- const marker = char.repeat(length);
194
- const info = rand(2) === 0 ? '' : 'markdown';
195
- const openIndex = rows.length;
196
- fenced.add(openIndex);
197
- rows.push(`${marker}${info}` + ' '.repeat(rand(3)));
198
-
199
- const inner = [
200
- `## 2026-07-1${rand(9)} — fenced sample`,
201
- '',
202
- char.repeat(length - 1), // too short to close
203
- `${marker}js`, // info string never closes
204
- (char === '`' ? '~' : '`').repeat(length + 1), // the other marker never closes
205
- 'plain fenced text',
206
- ];
207
- const innerCount = 1 + rand(inner.length);
208
- for (let i = 0; i < innerCount; i += 1) {
209
- fenced.add(rows.length);
210
- rows.push(inner[(i + rand(inner.length)) % inner.length]);
211
- }
212
-
213
- if (allowUnclosed && rand(4) === 0) {
214
- unclosedAt = openIndex;
215
- return;
216
- }
217
- fenced.add(rows.length);
218
- rows.push(char.repeat(length + rand(2)) + ' '.repeat(rand(3)));
219
- };
220
-
221
- const frontmatter = rand(2) === 0 ? FM.replace(/\n/g, eol) : '';
222
- const segmentCount = 3 + rand(5);
223
- // An unclosed fence may open ANYWHERE, not only last: the generator keeps emitting after it and
224
- // marks the remainder fenced, so the refusal is exercised with real content behind it rather than
225
- // at a convenient end-of-file.
226
- for (let i = 0; i < segmentCount; i += 1) {
227
- if (unclosedAt !== null) {
228
- fenced.add(rows.length);
229
- rows.push(rand(2) === 0 ? `## 2026-07-0${i} — hidden behind the open fence` : `trailing text ${i}`);
230
- continue;
231
- }
232
- const kind = rand(5);
233
- if (kind === 0) pushHeading();
234
- else if (kind === 1) rows.push('');
235
- else if (kind === 2) rows.push(`${B}inline${B} used in prose`);
236
- else if (kind === 3) pushFence(true);
237
- else rows.push(`body text ${i}`);
238
- }
239
-
240
- return { text: frontmatter + rows.join(eol) + eol, frontmatter, fenced, headings, unclosedAt };
241
- };
242
-
243
- describe('properties over generated documents', () => {
244
- const SEEDS = 400;
245
-
246
- it('the fenced-line set equals the oracle the generator recorded', () => {
247
- for (let seed = 1; seed <= SEEDS; seed += 1) {
248
- const doc = buildDocument(seed);
249
- if (doc.unclosedAt !== null) continue;
250
- const { fencedLines } = tokenizeMarkdown(doc.text, `seed-${seed}`);
251
- assert.deepEqual([...fencedLines].sort((a, b) => a - b), [...doc.fenced].sort((a, b) => a - b), `seed ${seed}`);
252
- }
253
- });
254
-
255
- it('the heading tokens equal the oracle — index and text', () => {
256
- for (let seed = 1; seed <= SEEDS; seed += 1) {
257
- const doc = buildDocument(seed);
258
- if (doc.unclosedAt !== null) continue;
259
- const { headings } = tokenizeMarkdown(doc.text, `seed-${seed}`);
260
- assert.deepEqual(
261
- headings.map((h) => ({ index: h.index, text: h.text })),
262
- doc.headings,
263
- `seed ${seed}`,
264
- );
265
- }
266
- });
267
-
268
- it('an unclosed fence always refuses, naming the line the generator opened it on', () => {
269
- let covered = 0;
270
- for (let seed = 1; seed <= SEEDS; seed += 1) {
271
- const doc = buildDocument(seed);
272
- if (doc.unclosedAt === null) continue;
273
- covered += 1;
274
- const frontLines = doc.frontmatter === '' ? 0 : doc.frontmatter.split('\n').length - 1;
275
- assert.throws(
276
- () => tokenizeMarkdown(doc.text, `seed-${seed}`),
277
- (err) => {
278
- assert.equal(err.exitCode, 1, `seed ${seed}`);
279
- assert.ok(
280
- err.message.startsWith(`seed-${seed}:${frontLines + doc.unclosedAt + 1}:`),
281
- `seed ${seed}: refusal names the wrong line — ${err.message.slice(0, 60)}`,
282
- );
283
- return true;
284
- },
285
- );
286
- }
287
- assert.ok(covered >= 10, `the generator must actually produce unclosed fences (got ${covered})`);
288
- });
289
-
290
- it('line endings never change the block structure', () => {
291
- for (let seed = 1; seed <= SEEDS; seed += 1) {
292
- const doc = buildDocument(seed);
293
- if (doc.unclosedAt !== null) continue;
294
- const lf = doc.text.replace(/\r\n/g, '\n');
295
- const a = tokenizeMarkdown(lf, `seed-${seed}`);
296
- const b = tokenizeMarkdown(lf.replace(/\n/g, '\r\n'), `seed-${seed}`);
297
- assert.deepEqual(a.headings.map((h) => h.text), b.headings.map((h) => h.text), `seed ${seed}`);
298
- assert.deepEqual([...a.fencedLines], [...b.fencedLines], `seed ${seed}`);
299
- }
300
- });
301
-
302
- it('the body is returned byte-exact — rejoining reproduces the input', () => {
303
- for (let seed = 1; seed <= SEEDS; seed += 1) {
304
- const doc = buildDocument(seed);
305
- if (doc.unclosedAt !== null) continue;
306
- const { frontmatter, lines } = tokenizeMarkdown(doc.text, `seed-${seed}`);
307
- assert.equal(frontmatter + lines.join('\n'), doc.text, `seed ${seed}`);
308
- }
309
- });
310
- });