@skathio/somi 2.2.1 → 3.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 (128) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +8 -2
  3. package/.copilot-extension/extension.json +9 -8
  4. package/.copilot-extension/marketplace.json +2 -2
  5. package/README.md +45 -33
  6. package/VERSION +1 -1
  7. package/agents/architecture-reviewer.md +16 -0
  8. package/agents/atlas.md +102 -0
  9. package/agents/coder.md +66 -22
  10. package/agents/designer.md +20 -16
  11. package/agents/discovery-analyst.md +6 -5
  12. package/agents/impact.md +97 -0
  13. package/agents/incident.md +96 -0
  14. package/agents/plan-reviewer.md +70 -0
  15. package/agents/planner.md +77 -20
  16. package/agents/pr.md +101 -0
  17. package/agents/refactor-designer.md +82 -0
  18. package/agents/refactorer.md +30 -24
  19. package/agents/reviewer.md +28 -25
  20. package/agents/sdlc-reviewer.md +69 -0
  21. package/agents/security-reviewer.md +17 -0
  22. package/agents/somi.md +207 -209
  23. package/agents/test-strategist.md +16 -1
  24. package/commands/adopt.md +21 -7
  25. package/commands/architecture-review.md +8 -5
  26. package/commands/atlas.md +24 -72
  27. package/commands/code-loop.md +46 -15
  28. package/commands/code-parallel.md +6 -4
  29. package/commands/code.md +29 -21
  30. package/commands/debug.md +17 -11
  31. package/commands/design.md +48 -31
  32. package/commands/discover.md +26 -16
  33. package/commands/impact.md +16 -54
  34. package/commands/incident.md +22 -55
  35. package/commands/plan-loop.md +43 -17
  36. package/commands/plan.md +64 -26
  37. package/commands/pr.md +19 -66
  38. package/commands/refactor-design.md +98 -0
  39. package/commands/refactor.md +22 -23
  40. package/commands/release-readiness.md +16 -7
  41. package/commands/review-panel.md +31 -10
  42. package/commands/review.md +21 -14
  43. package/commands/security-review.md +12 -3
  44. package/commands/ship-loop.md +71 -54
  45. package/commands/ship.md +17 -13
  46. package/commands/test-strategy.md +6 -4
  47. package/commands/upgrade.md +10 -8
  48. package/examples/discovery-example.md +2 -2
  49. package/examples/sample-consumer/CLAUDE.md +41 -7
  50. package/examples/sample-consumer/README.md +36 -22
  51. package/hooks/lib/common.mjs +66 -20
  52. package/hooks/post-tool/audit-log.mjs +7 -11
  53. package/hooks/post-tool/lint-changed-files.mjs +8 -11
  54. package/hooks/pre-tool/block-dangerous-bash.mjs +32 -44
  55. package/hooks/pre-tool/block-secret-writes.mjs +6 -9
  56. package/hooks/pre-tool/gate-dep-install.mjs +18 -27
  57. package/hooks/pre-tool/guard-protected-paths.mjs +9 -11
  58. package/hooks/session-start/detect-repo-instructions.mjs +21 -23
  59. package/hooks/user-prompt-submit/inject-workflow-context.mjs +190 -42
  60. package/mcp.json +10 -0
  61. package/package.json +5 -2
  62. package/rules/CLAUDE.md +22 -19
  63. package/scripts/check-links.mjs +218 -0
  64. package/scripts/check-session-artefacts.mjs +149 -0
  65. package/scripts/check-size-budget.mjs +137 -0
  66. package/scripts/generate-digest.mjs +176 -0
  67. package/scripts/lib/cost-ceiling.mjs +317 -0
  68. package/scripts/lib/cost-model.mjs +95 -0
  69. package/scripts/lib/dispatch-resolver.mjs +224 -0
  70. package/scripts/lib/mcp-project-root.mjs +183 -0
  71. package/scripts/size-budget-overrides.json +74 -0
  72. package/scripts/somi-check.mjs +6 -13
  73. package/scripts/somi-dispatch.mjs +141 -0
  74. package/scripts/somi-findings.mjs +4 -5
  75. package/scripts/somi-loop.mjs +181 -13
  76. package/scripts/somi-mcp.mjs +357 -0
  77. package/scripts/validate.sh +690 -29
  78. package/skills/clean-code/SKILL.md +1 -1
  79. package/skills/plan-review/SKILL.md +79 -0
  80. package/skills/rules/SKILL.md +47 -0
  81. package/skills/sdlc-process/SKILL.md +74 -0
  82. package/skills/somi-dispatch/SKILL.md +220 -0
  83. package/skills/somi-routing/SKILL.md +33 -8
  84. package/skills/{test-strategy → testing-playbook}/SKILL.md +1 -1
  85. package/templates/ATLAS.md.tmpl +4 -4
  86. package/templates/BRIEF.md.tmpl +23 -22
  87. package/templates/DECISIONS.md.tmpl +1 -0
  88. package/templates/DESIGN.md.tmpl +5 -5
  89. package/templates/DIARY.md.tmpl +10 -5
  90. package/templates/DOD.md.tmpl +24 -0
  91. package/templates/PROGRESS.md.tmpl +3 -16
  92. package/templates/SOMI-README.md.tmpl +3 -3
  93. package/tests/hooks/cases/inject-workflow-context.json +120 -7
  94. package/tests/hooks/run.sh +20 -11
  95. package/tests/scripts/check-links.sh +105 -0
  96. package/tests/scripts/check-session-artefacts.sh +60 -0
  97. package/tests/scripts/check-size-budget.sh +71 -0
  98. package/tests/scripts/checkpoint-gate.sh +90 -0
  99. package/tests/scripts/convergence-runner.sh +1510 -0
  100. package/tests/scripts/cost-ceiling.sh +343 -0
  101. package/tests/scripts/cost-model.sh +192 -0
  102. package/tests/scripts/dispatch-guard.sh +108 -0
  103. package/tests/scripts/dispatch-reference-gate.sh +173 -0
  104. package/tests/scripts/eval-runner.sh +3691 -0
  105. package/tests/scripts/evals-packaging.sh +117 -0
  106. package/tests/scripts/fixtures/legacy-shard-no-schema.json +50 -0
  107. package/tests/scripts/generate-digest.sh +180 -0
  108. package/tests/scripts/goldens/loop-state-breach.json +1 -0
  109. package/tests/scripts/goldens/loop-state-done.json +1 -0
  110. package/tests/scripts/goldens/somi-loop.json +1 -1
  111. package/tests/scripts/lib/adr-shape.mjs +41 -0
  112. package/tests/scripts/lib/checkpoint-gate.mjs +54 -0
  113. package/tests/scripts/lib/digest-marker-coupling.mjs +52 -0
  114. package/tests/scripts/lib/dispatch-reference-gate.mjs +112 -0
  115. package/tests/scripts/lib/multipass-dependence.mjs +192 -0
  116. package/tests/scripts/lib/multipass-source-identity.mjs +243 -0
  117. package/tests/scripts/lib/reference-pair.mjs +61 -0
  118. package/tests/scripts/lib/retirement-gate.mjs +167 -0
  119. package/tests/scripts/lib/shell-embedded-js.mjs +47 -0
  120. package/tests/scripts/lib/somi-mcp-client.mjs +102 -0
  121. package/tests/scripts/lib/somi-mcp-tests.mjs +401 -0
  122. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +38 -0
  123. package/tests/scripts/retirement-gate.sh +287 -0
  124. package/tests/scripts/review-panel-seats.sh +32 -0
  125. package/tests/scripts/run.sh +184 -2
  126. package/tests/scripts/somi-agent-dispatch-contract.sh +195 -0
  127. package/tests/scripts/somi-dispatch.sh +354 -0
  128. package/tests/scripts/somi-mcp.sh +12 -0
@@ -0,0 +1,192 @@
1
+ #!/usr/bin/env node
2
+ // Dependence proof for multipass-code's A/B pair.
3
+ // This is the BEHAVIOUR layer only -- see multipass-source-identity.mjs for the SOURCE layer.
4
+ // Neither is sufficient alone (same two-layer split reference-pair.mjs's own header documents for
5
+ // task02, generalized here from an insertion-shaped diff to mutant-b's replacement-shaped one):
6
+ // this file can only see a difference some probed input actually exercises, so a hand-copy slip
7
+ // in a validation branch no probe cursor ever trips (a neutered negative-offset guard, a
8
+ // neutered string/empty-cursor guard, a neutered VERSION check)
9
+ // leaves SHIPPED_VS_MUTANT_B_DIFF=0 even though mutant-b's construction is wrong. The source layer
10
+ // closes that: it asserts mutant-b's source is shipped's, plus EXACTLY one vocabulary-constrained
11
+ // hunk (B's own return-line fix), so a change anywhere else in the file fails regardless of
12
+ // whether any probed input would ever observe it.
13
+ //
14
+ // Four states, three independently observable plus one construction-only: shipped (A present, B masked) and mutant-a (A fixed, B newly reachable) and control
15
+ // (neither) are told apart by SOME probed input. mutant-b (B "fixed" alone, A still broken) is
16
+ // asserted EQUAL to shipped, exactly, across the whole probed-input set -- that equality IS the
17
+ // reachability proof: it fails if B ever becomes reachable pre-A-fix. A vacuous equality pass (too
18
+ // narrow a probe set to exercise a real difference) is guarded against below by a self-check: a
19
+ // deliberately-broken variant must be caught, not waved through.
20
+ //
21
+ // Lives in a file rather than a `node -e "..."` block -- backticks/double-quotes inside a shell
22
+ // string are live syntax (tests/scripts/lib/shell-embedded-js.mjs guards that class).
23
+
24
+ import { readFileSync } from 'node:fs';
25
+
26
+ const [root] = process.argv.slice(2);
27
+ if (!root) { process.stderr.write('usage: multipass-dependence.mjs <repo-root>\n'); process.exit(1); }
28
+ const F = `${root}/tests/evals/fixtures`;
29
+
30
+ const cursorMod = await import(`${F}/multipass-code/src/pagination/cursor.mjs`);
31
+ const paginateMod = await import(`${F}/multipass-code/src/pagination/paginate.mjs`);
32
+ const shipped = { encodeCursor: cursorMod.encodeCursor, decodeCursor: cursorMod.decodeCursor, listPage: paginateMod.listPage };
33
+
34
+ const states = {
35
+ shipped,
36
+ mutant_a: await import(`${F}/multipass-code-mutant-a.mjs`),
37
+ mutant_b: await import(`${F}/multipass-code-mutant-b.mjs`),
38
+ control: await import(`${F}/multipass-code-control.mjs`),
39
+ };
40
+
41
+ // Standalone encoder -- independent of any state's own encodeCursor, so a probe's cursor is
42
+ // never sourced from the module under test.
43
+ const mint = (offset) => Buffer.from(JSON.stringify({ v: 1, offset }), 'utf8').toString('base64url');
44
+
45
+ function probeListPage(state, total, pageSize, offset) {
46
+ const items = Array.from({ length: total }, (_, i) => i);
47
+ const cursor = offset === null ? null : mint(offset);
48
+ try {
49
+ return 'OK:' + JSON.stringify(state.listPage(items, cursor, pageSize));
50
+ } catch (e) {
51
+ return 'ERR:' + e.message;
52
+ }
53
+ }
54
+
55
+ // --- the shared probed-input set -- every check below sweeps this same set, not a smaller one --
56
+ const TOTALS = [0, 1, 2, 3, 4, 5, 8, 13];
57
+ const PAGE_SIZES = [1, 2, 3, 5, 8];
58
+ const probes = [];
59
+ for (const total of TOTALS) {
60
+ for (const pageSize of PAGE_SIZES) {
61
+ for (const offset of new Set([null, 0, Math.floor(total / 2), total, total + 1, total + 50])) {
62
+ probes.push({ total, pageSize, offset });
63
+ }
64
+ }
65
+ }
66
+ const boundaryIdxs = probes.map((p, i) => (p.offset === p.total ? i : -1)).filter((i) => i >= 0);
67
+
68
+ const outcomes = {};
69
+ for (const name of Object.keys(states)) {
70
+ outcomes[name] = probes.map((p) => probeListPage(states[name], p.total, p.pageSize, p.offset));
71
+ }
72
+ const diffCount = (a, b) => outcomes[a].reduce((n, v, i) => n + (v !== outcomes[b][i] ? 1 : 0), 0);
73
+
74
+ const shippedExhibitsA = boundaryIdxs.every((i) => outcomes.shipped[i] === 'ERR:cursor out of range');
75
+ const mutantANotA = boundaryIdxs.every((i) => outcomes.mutant_a[i].startsWith('OK:'));
76
+ const mutantAExhibitsB = boundaryIdxs.every(
77
+ (i) => outcomes.mutant_a[i].startsWith('OK:') && JSON.parse(outcomes.mutant_a[i].slice(3)).nextCursor !== null,
78
+ );
79
+ const controlClean = boundaryIdxs.every(
80
+ (i) => outcomes.control[i].startsWith('OK:') && JSON.parse(outcomes.control[i].slice(3)).nextCursor === null,
81
+ );
82
+
83
+ // --- B unreached on shipped: same outcome as if the branch didn't exist at all ------------------
84
+ // A "no-B" variant: shipped's own decodeCursor (A's bug intact) feeding a listPage with the
85
+ // shrink branch deleted, so it falls straight through to the ordinary slice path.
86
+ function noBranchListPage(items, cursor, pageSize) {
87
+ if (!Number.isInteger(pageSize) || pageSize <= 0) throw new Error('invalid page size');
88
+ if (cursor == null) {
89
+ const slice = items.slice(0, pageSize);
90
+ return { items: slice, nextCursor: slice.length < items.length ? shipped.encodeCursor(slice.length) : null, remaining: items.length - slice.length };
91
+ }
92
+ const offset = shipped.decodeCursor(cursor, items.length);
93
+ const slice = items.slice(offset, offset + pageSize);
94
+ const nextOffset = offset + slice.length;
95
+ return { items: slice, nextCursor: nextOffset < items.length ? shipped.encodeCursor(nextOffset) : null, remaining: items.length - nextOffset };
96
+ }
97
+ // Swept over ALL 225 probes, not just the 40 boundary ones -- scoped to boundaryIdxs alone this
98
+ // check is a tautology of SHIPPED_EXHIBITS_A (shipped.decodeCursor, called by noBranchListPage
99
+ // too, throws before either listPage body runs on every one of those 40), and it was measured reporting a false "yes" on a widened-boundary mutant the equality check
100
+ // (below) correctly caught. The null-cursor case needs its own branch: `mint(null)` would encode a
101
+ // bogus non-null cursor rather than the real `cursor == null` no-cursor path noBranchListPage (and
102
+ // shipped) special-case.
103
+ const bUnreached = probes.every((p, i) => {
104
+ const items = Array.from({ length: p.total }, (_, k) => k);
105
+ const cursor = p.offset === null ? null : mint(p.offset);
106
+ let out;
107
+ try { out = 'OK:' + JSON.stringify(noBranchListPage(items, cursor, p.pageSize)); }
108
+ catch (e) { out = 'ERR:' + e.message; }
109
+ return out === outcomes.shipped[i];
110
+ });
111
+
112
+ // --- self-validating harness: the equality check must be ABLE to fail ---------------------------
113
+ // A deliberately-broken "mutant-b" that also loosens the bound -- touches more than B's branch.
114
+ // The equality sweep must flag a mismatch here, or the real mutant-b check above is vacuous.
115
+ function brokenMutantB(items, cursor, pageSize) {
116
+ if (!Number.isInteger(pageSize) || pageSize <= 0) throw new Error('invalid page size');
117
+ if (cursor == null) {
118
+ const slice = items.slice(0, pageSize);
119
+ return { items: slice, nextCursor: slice.length < items.length ? shipped.encodeCursor(slice.length) : null, remaining: items.length - slice.length };
120
+ }
121
+ const raw = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
122
+ if (typeof raw.offset !== 'number' || !Number.isInteger(raw.offset) || raw.offset < 0) throw new Error('malformed cursor');
123
+ if (raw.offset > items.length) throw new Error('cursor out of range'); // the deliberate breakage
124
+ if (raw.offset === items.length) return { items: [], nextCursor: null, remaining: 0 };
125
+ const slice = items.slice(raw.offset, raw.offset + pageSize);
126
+ const nextOffset = raw.offset + slice.length;
127
+ return { items: slice, nextCursor: nextOffset < items.length ? shipped.encodeCursor(nextOffset) : null, remaining: items.length - nextOffset };
128
+ }
129
+ // Calls probeListPage itself (not a re-implementation of its body) so the self-check exercises
130
+ // the SAME comparison path the real mutant-b check above uses .
131
+ const brokenOutcomes = probes.map((p) => probeListPage({ listPage: brokenMutantB }, p.total, p.pageSize, p.offset));
132
+ const brokenDiffCount = outcomes.shipped.reduce((n, v, i) => n + (v !== brokenOutcomes[i] ? 1 : 0), 0);
133
+
134
+ // --- bounded adversarial sweep: no third shipped defect --------
135
+ // SCOPE DECISION: this sweep varies pageSize
136
+ // and cursor payload, not `items`, and never calls encodeCursor directly. A string `items` does
137
+ // produce an anomalous result (`listPage('abcdef', null, 2)` -> a string sliced into "items"),
138
+ // but R1-R4 (backward paging, `spec.md` in the fixture's own tree) never hand listPage anything
139
+ // but the in-memory array the hermetic sandbox seeds it with -- no live draw, and no reachable
140
+ // path through the fixture's own R-requirements, ever calls listPage with a non-array. Adding the
141
+ // axis would mean either fixing a THIRD shipped defect this pass (violating this pass's own frozen-
142
+ // shape constraint on multipass-code/src/**) or reporting it and stalling the freeze on a defect no
143
+ // requirement can reach. Deferred, not silently dropped -- recorded in diary.md. Same reasoning
144
+ // covers encodeCursor: never called directly by any R-requirement's own control flow either.
145
+ const KNOWN_ERRORS = new Set(['invalid page size', 'malformed cursor', 'cursor out of range']);
146
+ let thirdDefect = null;
147
+ outer:
148
+ for (const pageSize of [0, -1, -5, 1.5, NaN, Infinity]) {
149
+ for (const total of [0, 1, 5]) {
150
+ const out = probeListPage(shipped, total, pageSize, null);
151
+ if (!out.startsWith('ERR:') || !KNOWN_ERRORS.has(out.slice(4))) { thirdDefect = `pageSize=${pageSize} total=${total} -> ${out}`; break outer; }
152
+ }
153
+ }
154
+ if (!thirdDefect) {
155
+ const badCursors = [
156
+ Buffer.from(JSON.stringify({ v: 1, offset: 1.5 }), 'utf8').toString('base64url'),
157
+ Buffer.from(JSON.stringify({ v: 1, offset: -1 }), 'utf8').toString('base64url'),
158
+ Buffer.from(JSON.stringify({ v: 1, offset: 'x' }), 'utf8').toString('base64url'),
159
+ ];
160
+ outer2:
161
+ for (const cursor of badCursors) {
162
+ for (const total of [0, 1, 5]) {
163
+ const items = Array.from({ length: total }, (_, k) => k);
164
+ let out;
165
+ try { out = 'OK:' + JSON.stringify(shipped.listPage(items, cursor, 2)); }
166
+ catch (e) { out = 'ERR:' + e.message; }
167
+ if (!out.startsWith('ERR:') || !KNOWN_ERRORS.has(out.slice(4))) { thirdDefect = `cursor=${cursor} total=${total} -> ${out}`; break outer2; }
168
+ }
169
+ }
170
+ }
171
+
172
+ // --- report ---------------------------------------------------------------------------------
173
+ // One field per line, each line's value running to end-of-line -- so the shell side's field()
174
+ // can extract with an anchored `^NAME=` match and take the whole rest of the line, correctly,
175
+ // for every field including a multi-word one (THIRD_DEFECT). Previously PROBES/BOUNDARY_PROBES
176
+ // and HARNESS_SELF_CHECK/broken_diffs shared a line each, which is exactly what forced field()
177
+ // into a stop-at-first-space extraction that silently truncated THIRD_DEFECT's own value
178
+ //.
179
+ console.log(`PROBES=${probes.length}`);
180
+ console.log(`BOUNDARY_PROBES=${boundaryIdxs.length}`);
181
+ console.log(`SHIPPED_EXHIBITS_A=${shippedExhibitsA ? 'yes' : 'no'}`);
182
+ console.log(`SHIPPED_B_UNREACHED=${bUnreached ? 'yes' : 'no'}`);
183
+ console.log(`MUTANT_A_EXHIBITS_B=${mutantAExhibitsB ? 'yes' : 'no'}`);
184
+ console.log(`MUTANT_A_NOT_A=${mutantANotA ? 'yes' : 'no'}`);
185
+ console.log(`CONTROL_CLEAN=${controlClean ? 'yes' : 'no'}`);
186
+ console.log(`SHIPPED_VS_MUTANT_A_DIFF=${diffCount('shipped', 'mutant_a')}`);
187
+ console.log(`SHIPPED_VS_CONTROL_DIFF=${diffCount('shipped', 'control')}`);
188
+ console.log(`MUTANT_A_VS_CONTROL_DIFF=${diffCount('mutant_a', 'control')}`);
189
+ console.log(`SHIPPED_VS_MUTANT_B_DIFF=${diffCount('shipped', 'mutant_b')}`);
190
+ console.log(`HARNESS_SELF_CHECK=${brokenDiffCount > 0 ? 'ok' : 'FAILED-TO-DETECT'}`);
191
+ console.log(`HARNESS_SELF_CHECK_DIFFS=${brokenDiffCount}`);
192
+ console.log(`THIRD_DEFECT=${thirdDefect ?? 'none'}`);
@@ -0,0 +1,243 @@
1
+ #!/usr/bin/env node
2
+ // Source-identity proof for multipass-code's mutant-a, mutant-b, and control This is the SOURCE layer -- see multipass-dependence.mjs for the BEHAVIOUR
3
+ // layer. Neither is sufficient alone: multipass-dependence.mjs's 225-probe equality/inequality
4
+ // sweeps can only see a difference SOME probed input actually exercises. Every probe cursor it
5
+ // mints is well-formed (`v:1`, a non-negative integer offset) by construction, so a hand-copy slip
6
+ // in a validation branch no probe ever trips -- a neutered negative-offset guard, a neutered
7
+ // string/empty-cursor guard, a neutered VERSION check -- all leave the behaviour layer's own
8
+ // diff counts unaffected. This file closes that gap by asserting
9
+ // SOURCE identity instead of just behavioural identity, for all three hand-copied reference files:
10
+ // mutant-a is scored against draws (the well-formed-probe argument is a property of the probe
11
+ // set, not of any one reference file), control likewise,
12
+ // and mutant-b (construction-only, never scored) keeps the coverage it already had.
13
+ //
14
+ // tests/scripts/lib/reference-pair.mjs already solved a version of this problem for task02's
15
+ // mutant/control pair (see that file's own header for the "absorbed anything written inside the
16
+ // matched region" incident this class of check exists to prevent) and its hunk-walking core is
17
+ // the technique this file generalizes -- but not the algorithm verbatim. reference-pair.mjs's walk
18
+ // assumes CONTROL IS MUTANT PLUS A PURE INSERTION (`if (i < mut.length && mut[i] === ctl[j])`
19
+ // only ever advances forward through an unbroken prefix match, i.e. every mutant line must appear,
20
+ // in order, inside the control). Each of this fixture's three reference files differs from the
21
+ // shipped source by one or more single-line REPLACEMENTs (A's bound check, B's return statement),
22
+ // never a pure insertion -- shipped's own line never reappears anywhere in the mutant, so an
23
+ // insertion-only walk would reject every legitimately-built reference file as "does not contain
24
+ // every line", never reaching a positive result. The walk below is a real (bidirectional)
25
+ // longest-common-subsequence diff, so it tolerates insertion, deletion, AND replacement, all
26
+ // collapsed into hunks the same way `diff -u` reports them; the discipline is otherwise identical
27
+ // to reference-pair.mjs's: exactly the expected number of contiguous hunks, each hunk a strict
28
+ // 1-for-1 line replacement (not a deletion, not a multi-line splice), every line in every hunk (both sides) constrained to a caller-supplied vocabulary.
29
+ //
30
+ // Lives in a file rather than a `node -e "..."` block -- backticks/double-quotes inside a shell
31
+ // string are live syntax (tests/scripts/lib/shell-embedded-js.mjs guards that class).
32
+
33
+ import { readFileSync } from 'node:fs';
34
+
35
+ // Same code-line filter reference-pair.mjs uses (blanks and comments excluded -- "the two files
36
+ // explain different things and should say so"), broadened to `/*` generally rather than the exact
37
+ // `/**` reference-pair.mjs checks (cursor.mjs uses single-line `/** ... */` JSDoc for
38
+ // encodeCursor -- `startsWith('/*')` alone misses it, and it has no counterpart in the reference
39
+ // files, which carry no JSDoc at all; measured directly by running this file before writing this
40
+ // comment).
41
+ //
42
+ // The `import` strip is applied to the SHIPPED side only (`stripImports: true`), not to any
43
+ // reference file's side. It exists to absorb shipped's own
44
+ // `paginate.mjs -> cursor.mjs` import line, which has no counterpart in a self-contained reference
45
+ // file (mutant-a/mutant-b/control import nothing, the same convention task02-code-mutant.mjs uses
46
+ // for token.mjs) -- stripping it from the shipped side only is what makes that an EXPECTED
47
+ // structural difference rather than a spurious extra hunk. Stripping it from BOTH sides would also
48
+ // erase the evidence of an import line a reference file was never supposed to have: prepending one
49
+ // to a reference file previously passed silently because the old filter stripped
50
+ // it back out again before the diff ever ran.
51
+ const codeLines = (text, { stripImports = false } = {}) =>
52
+ text
53
+ .split('\n')
54
+ .filter((l) => {
55
+ const t = l.trim();
56
+ if (!t || t.startsWith('//') || t.startsWith('*') || t.startsWith('/*')) return false;
57
+ if (stripImports && t.startsWith('import ')) return false;
58
+ return true;
59
+ });
60
+
61
+ export function readCodeLines(paths, opts) {
62
+ return paths.flatMap((p) => codeLines(readFileSync(p, 'utf8'), opts));
63
+ }
64
+
65
+ // Real (bidirectional) LCS, computed by DP -- these files are tens of lines, so the O(n*m) table
66
+ // is trivial. Returns the matched (i, j) index pairs, in order.
67
+ function lcsPairs(a, b) {
68
+ const n = a.length, m = b.length;
69
+ const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
70
+ for (let i = n - 1; i >= 0; i--) {
71
+ for (let j = m - 1; j >= 0; j--) {
72
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
73
+ }
74
+ }
75
+ const pairs = [];
76
+ let i = 0, j = 0;
77
+ while (i < n && j < m) {
78
+ if (a[i] === b[j]) { pairs.push([i, j]); i++; j++; }
79
+ else if (dp[i + 1][j] >= dp[i][j + 1]) i++;
80
+ else j++;
81
+ }
82
+ return pairs;
83
+ }
84
+
85
+ // Collapse the gaps between consecutive LCS matches into hunks -- a gap on the `a` side alone is a
86
+ // pure deletion, on the `b` side alone a pure insertion, on both a replacement; consecutive gaps
87
+ // separated by at least one match are two DIFFERENT hunks, which is exactly the signal a change
88
+ // outside the one intended locus needs to trip.
89
+ function diffHunks(a, b) {
90
+ const pairs = lcsPairs(a, b);
91
+ const hunks = [];
92
+ let ai = 0, bi = 0;
93
+ for (const [pi, pj] of pairs) {
94
+ if (ai < pi || bi < pj) hunks.push({ removed: a.slice(ai, pi), added: b.slice(bi, pj) });
95
+ ai = pi + 1; bi = pj + 1;
96
+ }
97
+ if (ai < a.length || bi < b.length) hunks.push({ removed: a.slice(ai), added: b.slice(bi) });
98
+ return hunks;
99
+ }
100
+
101
+ /**
102
+ * @param {string[]} aLines "before" code lines (e.g. shipped, concatenated across files)
103
+ * @param {string[]} bLines "after" code lines (e.g. mutant-a, mutant-b, or control)
104
+ * @param {RegExp} vocab every line inside every allowed hunk (both sides) must match
105
+ * @param {number} expectedHunkCount how many separate hunks this pair should differ by (mutant-a
106
+ * and mutant-b: 1 -- A's bound alone, or B's return alone; control: 2 -- both A's bound and B's
107
+ * return, since it fixes both loci)
108
+ * @returns {string} 'ok', or a diagnostic string
109
+ */
110
+ export function assertVocabHunks(aLines, bLines, vocab, expectedHunkCount = 1) {
111
+ const hunks = diffHunks(aLines, bLines);
112
+ if (hunks.length === 0) return 'files are identical -- no change at all (expected the fix(es) to be present)';
113
+ if (hunks.length !== expectedHunkCount) {
114
+ const locus = (h) => JSON.stringify((h.removed[0] ?? h.added[0] ?? '').trim());
115
+ return `${hunks.length} separate hunks, not the expected ${expectedHunkCount}: ${hunks.map(locus).join(', ')}`;
116
+ }
117
+ for (const hunk of hunks) {
118
+ // A 1-for-1 replacement only -- not a deletion (a hunk with `added.length === 0` means
119
+ // the line was REMOVED, not fixed, and the vocabulary check below runs over
120
+ // `[...removed, ...added]`, so a pure deletion of B's line would otherwise satisfy a
121
+ // vocabulary built only from the two REPLACEMENT forms without ever containing a stray line).
122
+ if (hunk.removed.length !== 1 || hunk.added.length !== 1) {
123
+ return `a hunk is not a 1-for-1 replacement (${hunk.removed.length} removed, ${hunk.added.length} added): ` +
124
+ JSON.stringify([...hunk.removed, ...hunk.added]);
125
+ }
126
+ const lines = [...hunk.removed, ...hunk.added];
127
+ const stray = lines.find((l) => !vocab.test(l.trim()));
128
+ if (stray !== undefined) return `the hunk contains a line outside the allowed vocabulary: ${JSON.stringify(stray.trim())}`;
129
+ }
130
+ return 'ok';
131
+ }
132
+
133
+ // --- A's own vocabulary: decodeCursor's bound check, before and after its fix -------------------
134
+ // Anchored at both ends against the trimmed line; admits exactly two literal strings (the shipped
135
+ // `>=` form and the fixed `>` form), nothing else that could plausibly appear in this file.
136
+ export const A_VOCAB = /^if \(payload\.offset (>=|>) total\) \{$/;
137
+
138
+ // --- B's own vocabulary: the shrink branch's return statement, before and after its fix ---------
139
+ // Anchored at both ends against the trimmed line; admits exactly two literal strings (shipped's
140
+ // re-minted cursor, the fixed `null`), nothing else that could plausibly appear in this file.
141
+ // Materially TIGHTER than the `EXPIRY_VOCAB` precedent it was previously compared to
142
+ //: `EXPIRY_VOCAB` (`reference-pair.mjs:27`) is an
143
+ // unanchored prefix alternation that also admits a bare `}` or a bare `nowMs` anywhere in the
144
+ // file; this vocabulary admits only the two exact forms below, anchored start to end.
145
+ export const B_VOCAB = /^return \{ items: \[\], nextCursor: (encodeCursor\(offset\)|null), remaining: 0 \};$/;
146
+
147
+ // --- control's combined vocabulary: both loci, since control fixes A AND B ----------------------
148
+ // Derived from A_VOCAB/B_VOCAB (stripping each one's own start/end anchors, then re-anchoring the
149
+ // alternation as a whole) rather than restated as a fourth literal regex, so the two vocabularies
150
+ // can never drift out of sync with the combined one if either is ever edited.
151
+ //
152
+ // Guard, not a comment: the original one-line
153
+ // `.replace(/^\^/, '').replace(/\$$/, '')` strips a trailing `$` unconditionally, so a vocabulary
154
+ // not genuinely anchored `^...$` is silently corrupted into a valid-but-different regex instead
155
+ // of failing loudly -- and this function's only two callers feed it AB_VOCAB's own inputs, the
156
+ // sole constraint on what `control`'s two hunks may contain.
157
+ //
158
+ // The review offered two fixes and left the choice to this pass: a two-line
159
+ // `!s.startsWith('^') || !s.endsWith('$')` check, or a five-line version whose end-anchor test
160
+ // also rejects an escaped trailing dollar. Verified directly (both forms actually executed
161
+ // against the review's own two demonstrated shapes, not assumed from the review's prose) before
162
+ // choosing: `/^cost is \$/` -- source `"^cost is \\$"` -- literally ends in the character `$`,
163
+ // so BOTH forms' naive `endsWith('$')` passes it; only a check for an UNESCAPED trailing `$`
164
+ // (the five-line form's own regex) rejects it. `/^aaa$|^bbb$/` -- an alternation of two
165
+ // independently-anchored halves, not one `^...$` pattern -- also literally starts with `^` and
166
+ // ends with an unescaped `$`, so BOTH the two-line and five-line forms as written pass it
167
+ // unchanged too; the review's own claim that the two-line form "covers the alternation case"
168
+ // does not hold up under execution. Closing that gap needs a check neither proposed form makes:
169
+ // after the outer anchors are confirmed and stripped, the remaining body must contain no
170
+ // unescaped `^` or `$` of its own -- exactly what an independently-anchored alternative
171
+ // (`^bbb$`) sitting inside the body would be.
172
+ //
173
+ // Known scope limit, stated so the claim above matches it: a TOP-LEVEL alternation whose alternatives carry no inner anchors of their own
174
+ // (`/^a|b$/` -> body `a|b`) passes this check even though it is not actually a single `^...$`
175
+ // pattern -- `^` binds only to `a`, `$` only to `b` (it matches `axxx`, not only `a`). Contained,
176
+ // not closed: every caller below wraps a vocabulary's stripped body in a non-capturing group
177
+ // (`(?:...)`) before combining it into `AB_VOCAB`, so this kind of alternation precedence can
178
+ // never corrupt the combined pattern regardless; reaching this gap requires hand-writing a
179
+ // vocabulary that is already semantically broken on its own terms.
180
+ const unanchoredBody = (re) => {
181
+ const s = re.source;
182
+ if (!s.startsWith('^')) {
183
+ throw new Error(`vocabulary is not anchored at the start (^) and cannot be safely combined: ${s}`);
184
+ }
185
+ // An unescaped `$` at the very end -- distinguishes a real end anchor from a literal `\$`
186
+ // that merely happens to be the last character (the `cost is \$` shape above).
187
+ if (!/(?:^|[^\\])(?:\\\\)*\$$/.test(s)) {
188
+ throw new Error(`vocabulary is not anchored at the end ($) and cannot be safely combined: ${s}`);
189
+ }
190
+ const body = s.slice(1, -1);
191
+ // Strip every escaped character first (`\X`) -- an escaped `\^`/`\$` inside the body is a
192
+ // literal character, not an anchor, and must not trip this check. Then strip every character
193
+ // CLASS span (`[...]`) too: a `^` immediately
194
+ // after `[` negates the class rather than anchoring, and a `$` inside `[...]` is just the
195
+ // literal character -- `[^)]` and `[$]` are not anchors and must be ACCEPTED, not rejected.
196
+ // Without this, the check's own thrown message ("contains its own anchor") is a false
197
+ // diagnosis of a vocabulary that does not, in fact, contain one.
198
+ if (/[$^]/.test(body.replace(/\\./g, '').replace(/\[[^\]]*\]/g, ''))) {
199
+ throw new Error(`vocabulary body contains its own anchor and is not a single ^...$ pattern: ${s}`);
200
+ }
201
+ return body;
202
+ };
203
+
204
+ // Self-check (R12): proves the guard above CAN fail, not just that A_VOCAB/B_VOCAB currently
205
+ // pass it. Exercises the two demonstrated hazard shapes (both must throw) plus the vocabularies
206
+ // that must be ACCEPTED (neither must throw) -- the same shapes verified by hand in the comment
207
+ // above, plus a negated character class that a future field_ident vocabulary widening is
208
+ // likely to reach for (e.g. `[^\s)]`).
209
+ export function unanchoredBodySelfCheck() {
210
+ const mustThrow = [/^cost is \$/, /^aaa$|^bbb$/, /no leading anchor\$/];
211
+ for (const re of mustThrow) {
212
+ try {
213
+ unanchoredBody(re);
214
+ return `did not reject an unanchored vocabulary: ${re.source}`;
215
+ } catch {
216
+ // expected
217
+ }
218
+ }
219
+ const mustAccept = [A_VOCAB, B_VOCAB, /^f\(([^)]*)\)$/];
220
+ for (const re of mustAccept) {
221
+ try {
222
+ unanchoredBody(re);
223
+ } catch (e) {
224
+ return `rejected a genuinely well-formed vocabulary: ${e.message}`;
225
+ }
226
+ }
227
+ return 'ok';
228
+ }
229
+
230
+ export const AB_VOCAB = new RegExp(`^(?:${unanchoredBody(A_VOCAB)}|${unanchoredBody(B_VOCAB)})$`);
231
+
232
+ // --- CLI entry ------------------------------------------------------------------------------
233
+ const [cursorPath, paginatePath, mutantAPath, mutantBPath, controlPath] = process.argv.slice(2);
234
+ if (cursorPath && paginatePath && mutantAPath && mutantBPath && controlPath) {
235
+ const shippedLines = readCodeLines([cursorPath, paginatePath], { stripImports: true });
236
+ const mutantALines = readCodeLines([mutantAPath]);
237
+ const mutantBLines = readCodeLines([mutantBPath]);
238
+ const controlLines = readCodeLines([controlPath]);
239
+ console.log(`UNANCHORED_SELF_CHECK=${unanchoredBodySelfCheck()}`);
240
+ console.log(`MUTANT_A=${assertVocabHunks(shippedLines, mutantALines, A_VOCAB, 1)}`);
241
+ console.log(`MUTANT_B=${assertVocabHunks(shippedLines, mutantBLines, B_VOCAB, 1)}`);
242
+ console.log(`CONTROL=${assertVocabHunks(shippedLines, controlLines, AB_VOCAB, 2)}`);
243
+ }
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ // Asserts task02's mutant/control pair differ ONLY in expiry enforcement.
3
+ //
4
+ // Two layers, because neither is sufficient alone:
5
+ // 1. SOURCE — the code-only diff must be exactly one contiguous insertion hunk, and every line
6
+ // in it must belong to the expiry vocabulary.
7
+ // 2. BEHAVIOUR — cross-verified over well-formed AND malformed inputs.
8
+ //
9
+ // Layer 1 replaced a "locate the expiry block by regex and delete it" check. That shape absorbed
10
+ // anything written inside the matched region: the end anchor was the first `^ *}$`, so injecting
11
+ // `if (payload.sub === 'admin') throw new Error('bad signature');` above the expiry test was
12
+ // stripped along with it and passed at 38/38. A single-hunk assertion cannot absorb an extra
13
+ // statement anywhere, because an extra statement is either inside the hunk (caught by the
14
+ // vocabulary check) or makes a second hunk (caught by the count).
15
+ //
16
+ // Lives in a file rather than a `node -e "..."` block: those are shell-quoted context where a
17
+ // backtick is command substitution and a double quote ends the program. That has bitten once
18
+ // already, silently.
19
+
20
+ import { readFileSync } from 'node:fs';
21
+
22
+ const codeLines = (f) =>
23
+ readFileSync(f, 'utf8')
24
+ .split('\n')
25
+ .filter((l) => { const t = l.trim(); return t && !t.startsWith('//') && !t.startsWith('*') && t !== '/**'; });
26
+
27
+ // 'expired token', adjective-noun, matching the candidate-visible house style the shipped
28
+ // token.mjs establishes ('malformed token', 'bad signature') and its shipped tests assert on.
29
+ // It read 'token expired' until 2026-09-17, alone against that convention and against the very
30
+ // next line of its own file -- every one of the first three real draws wrote a correct
31
+ // expiry test, asserted /expired token/ by following the convention in front of it, and was
32
+ // failed at the control step for word order the task never specified.
33
+ const EXPIRY_VOCAB = /^(if \(typeof payload\.exp|throw new Error\('expired token'\);|\}|nowMs|&&)/;
34
+
35
+ const [mutFile, ctlFile] = process.argv.slice(2);
36
+ const mut = codeLines(mutFile);
37
+ const ctl = codeLines(ctlFile);
38
+
39
+ // Longest-common-subsequence-free: the control is the mutant plus an insertion, so walk both and
40
+ // collect maximal runs present in ctl but not mut, in order.
41
+ const hunks = [];
42
+ let i = 0, j = 0, cur = null;
43
+ while (j < ctl.length) {
44
+ if (i < mut.length && mut[i] === ctl[j]) {
45
+ if (cur) { hunks.push(cur); cur = null; }
46
+ i++; j++;
47
+ } else {
48
+ (cur ??= []).push(ctl[j]);
49
+ j++;
50
+ }
51
+ }
52
+ if (cur) hunks.push(cur);
53
+
54
+ const out = (m) => { process.stdout.write(m); process.exit(0); };
55
+ if (i !== mut.length) out(`control does not contain every mutant line (diverged at mutant line ${i + 1}: ${JSON.stringify(mut[i])})`);
56
+ if (hunks.length === 0) out('control is identical to the mutant - it does not enforce expiry');
57
+ if (hunks.length > 1) out(`control adds ${hunks.length} separate hunks, not one: ${JSON.stringify(hunks.map((h) => h[0]))}`);
58
+
59
+ const stray = hunks[0].map((l) => l.trim()).filter((l) => !EXPIRY_VOCAB.test(l));
60
+ if (stray.length) out(`the added hunk contains non-expiry code: ${JSON.stringify(stray[0])}`);
61
+ out('ok');