@dzhechkov/harness-core 0.5.4 → 0.6.1

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.
@@ -0,0 +1,348 @@
1
+ /**
2
+ * Amendment traceability — the deterministic half of the Step-8 amendment gate (ADR-001).
3
+ *
4
+ * The gate used to be a paragraph of prompt text asking the QE agent to confirm that every `AM-N`
5
+ * row names a real test. That is layer 4 on the cost-of-detection ladder, and the recalled lesson at
6
+ * reward 1.00 says what happens next: a safety property that lives only in a prompt disappears with
7
+ * the next prompt. `features/qe-scoped-review/08_qe_report.md` recorded the outcome — five ids named,
8
+ * none existing, and the plan writing `## Amendments: None`.
9
+ *
10
+ * Everything here is PURE: text in, verdicts out, file access through an injected reader (NFR-1).
11
+ * The CLI owns I/O and the exit code; this module owns the grammar and the rules.
12
+ *
13
+ * NOT PROVEN HERE: that a resolved test is non-vacuous. `dz discrimination-check` owns "would this
14
+ * test still pass with the protection deleted" (non-goal NG-1, acid case A8). A checker that implied
15
+ * it proved vacuity would be the same lie in a new place.
16
+ */
17
+
18
+ /** One `AM-N` row as it appears in a `## Amendments` section. */
19
+ export interface AmendmentRow {
20
+ readonly id: string;
21
+ readonly testIds: readonly string[];
22
+ readonly file: string | null;
23
+ readonly raw: string;
24
+ }
25
+
26
+ export type AmendmentVerdict =
27
+ | 'resolved'
28
+ | 'placeholder'
29
+ | 'unnamed'
30
+ | 'no-file-named'
31
+ | 'file-missing'
32
+ | 'name-absent-in-file';
33
+
34
+ export interface AmendmentResolution {
35
+ readonly id: string;
36
+ readonly testId: string | null;
37
+ readonly file: string | null;
38
+ readonly verdict: AmendmentVerdict;
39
+ readonly detail: string;
40
+ }
41
+
42
+ export type AmendmentOutcome = 'pass' | 'fail' | 'skip' | 'not-established';
43
+
44
+ export interface AmendmentDecision {
45
+ readonly outcome: AmendmentOutcome;
46
+ /** Derived FROM the outcome — one mapping, never two (AM-3, acid case A3/A7). */
47
+ readonly exit: 0 | 1 | 3;
48
+ readonly reasons: readonly string[];
49
+ readonly counts: Readonly<Record<AmendmentVerdict, number>>;
50
+ }
51
+
52
+ /**
53
+ * Template placeholders that reach shipped reports. A stub read as an ordinary unresolvable id lets
54
+ * the author believe they merely mistyped a name, so it earns its own verdict (acid case A1).
55
+ */
56
+ const PLACEHOLDER_IDS = new Set(['test_name', 'test-name', '<test>', '<test_name>', 'tbd', 'todo', 'name']);
57
+
58
+ /**
59
+ * Below this many normalised characters an id is too short to match anything meaningfully: the
60
+ * substring rule ADR-002 accepts would fire on unrelated prose. Guards the degenerate case the ADR
61
+ * names as its known false-positive risk.
62
+ */
63
+ export const MIN_MATCHABLE_ID_LENGTH = 8;
64
+
65
+ /** Case- and separator-folded form. Authors write ids in prose (`a_b_c`); test titles are sentences. */
66
+ /**
67
+ * Every `it()` / `test()` / `describe()` title in a test file. Empty when none parse.
68
+ *
69
+ * Comments are stripped FIRST. A commented-out `it('deny admin writes')` is not a test, and counting
70
+ * it would leave open the very forgery the title basis exists to close — the cross-family reviewer's
71
+ * two-comment-line attack in a slightly better costume. Table forms (`test.each([…])('…')`) carry an
72
+ * argument list between the modifier and the title, so the pattern allows one.
73
+ */
74
+ export function extractTestTitles(body: string): string[] {
75
+ const code = body.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:])\/\/[^\n]*/g, '$1');
76
+ const out: string[] = [];
77
+ const re = /\b(?:it|test|describe)(?:\.\w+)*(?:\s*\([^()]{0,200}\))?\s*(?:`[^`]*`)?\s*\(\s*(['"`])([\s\S]{1,300}?)\1/g;
78
+ for (let m = re.exec(code); m !== null; m = re.exec(code)) if (m[2]) out.push(m[2]);
79
+ return out;
80
+ }
81
+
82
+ export function normalizeTestId(s: string): string {
83
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, '');
84
+ }
85
+
86
+ /**
87
+ * Row starts, in BOTH shapes the corpus actually contains: a bullet (`- **AM-1 (…):**`) and a table
88
+ * cell (`| **AM-40** |`). A format LEGEND — the literal `AM-N` with an `N` that is not a digit, as in
89
+ * `features/ha-consilium/03.5_ideation_report.md` — is deliberately NOT a row: counting a legend as
90
+ * an amendment would open this feature by falsely accusing a feature that did nothing wrong.
91
+ */
92
+ const ROW_START = /^(?:[-*]\s+\*{0,2}AM-(\d+)|\|\s*\*{0,2}AM-(\d+))/gm;
93
+
94
+ /** The `## Amendments` section body, or null when the document has none (acid case A5). */
95
+ export function amendmentSection(md: string): string | null {
96
+ const m = /^ {0,3}#{2,4}\s+Amendments\b[^\n]*\n/m.exec(md);
97
+ if (!m) return null;
98
+ const start = m.index + m[0].length;
99
+ const rest = md.slice(start);
100
+ const next = /^ {0,3}#{2,4}\s+\S/m.exec(rest);
101
+ return next ? rest.slice(0, next.index) : rest;
102
+ }
103
+
104
+ /** `## Amendments` present but recording nothing to check — distinct from the section being absent. */
105
+ export function planSaysNoAmendments(planMd: string): boolean {
106
+ const sec = amendmentSection(planMd);
107
+ if (sec === null) return false;
108
+ return /^\s*(none|n\/a|нет)\b/i.test(sec.trim());
109
+ }
110
+
111
+ export function parseAmendments(md: string): AmendmentRow[] {
112
+ const section = amendmentSection(md);
113
+ if (section === null) return [];
114
+ const starts: { index: number; num: string }[] = [];
115
+ ROW_START.lastIndex = 0;
116
+ for (let m = ROW_START.exec(section); m !== null; m = ROW_START.exec(section)) {
117
+ starts.push({ index: m.index, num: (m[1] ?? m[2]) as string });
118
+ }
119
+ const rows: AmendmentRow[] = [];
120
+ for (let i = 0; i < starts.length; i++) {
121
+ const s = starts[i] as { index: number; num: string };
122
+ const end = i + 1 < starts.length ? (starts[i + 1] as { index: number }).index : section.length;
123
+ const raw = section.slice(s.index, end);
124
+ rows.push({ id: `AM-${s.num}`, testIds: extractTestIds(raw), file: extractFile(raw), raw });
125
+ }
126
+ return rows;
127
+ }
128
+
129
+ /** `→ test \`a\`` and the two-id shape `→ tests \`a\` and \`b\`` — both are in the corpus. */
130
+ function extractTestIds(raw: string): string[] {
131
+ const out: string[] = [];
132
+ const re = /→\s*tests?\s+`([^`]+)`(?:\s*(?:and|и)\s*`([^`]+)`)?/g;
133
+ for (let m = re.exec(raw); m !== null; m = re.exec(raw)) {
134
+ if (m[1]) out.push(m[1].trim());
135
+ if (m[2]) out.push(m[2].trim());
136
+ }
137
+ return out;
138
+ }
139
+
140
+ /**
141
+ * The `in \`<path>\`` half, which in real reports frequently opens the line AFTER the id. A pattern
142
+ * that cannot cross a newline finds almost nothing here — measured while writing this: three
143
+ * successive shell-written extractors returned 108, 111 and 13 rows over the identical corpus.
144
+ */
145
+ function extractFile(raw: string): string | null {
146
+ const m = /→\s*tests?\s+`[^`]+`(?:\s*(?:and|и)\s*`[^`]+`)?[\s\S]{0,40}?\bin\s+`([^`]+)`/.exec(raw);
147
+ return m && m[1] ? m[1].trim() : null;
148
+ }
149
+
150
+ export function resolveAmendments(
151
+ rows: readonly AmendmentRow[],
152
+ opts: { readFile: (p: string) => string | null },
153
+ ): AmendmentResolution[] {
154
+ const out: AmendmentResolution[] = [];
155
+ for (const row of rows) {
156
+ if (row.testIds.length === 0) {
157
+ out.push({
158
+ id: row.id,
159
+ testId: null,
160
+ file: row.file,
161
+ verdict: 'unnamed',
162
+ detail: 'the row carries no `→ test` token — an amendment with no pointer is not a passing amendment',
163
+ });
164
+ continue;
165
+ }
166
+ for (const testId of row.testIds) {
167
+ out.push(resolveOne(row, testId, opts.readFile));
168
+ }
169
+ }
170
+ return out;
171
+ }
172
+
173
+ function resolveOne(
174
+ row: AmendmentRow,
175
+ testId: string,
176
+ readFile: (p: string) => string | null,
177
+ ): AmendmentResolution {
178
+ const base = { id: row.id, testId, file: row.file };
179
+ if (PLACEHOLDER_IDS.has(testId.trim().toLowerCase())) {
180
+ return { ...base, verdict: 'placeholder', detail: `\`${testId}\` is a template placeholder, not a test name` };
181
+ }
182
+ if (row.file === null) {
183
+ return { ...base, verdict: 'no-file-named', detail: 'the row names a test id but no file to find it in' };
184
+ }
185
+ const body = readFile(row.file);
186
+ if (body === null) {
187
+ return { ...base, verdict: 'file-missing', detail: `\`${row.file}\` does not exist or cannot be read` };
188
+ }
189
+ const needle = normalizeTestId(testId);
190
+ if (needle.length < MIN_MATCHABLE_ID_LENGTH) {
191
+ return {
192
+ ...base,
193
+ verdict: 'name-absent-in-file',
194
+ detail: `\`${testId}\` normalises to ${needle.length} characters — below the ${MIN_MATCHABLE_ID_LENGTH}-character floor, so a match would prove nothing`,
195
+ };
196
+ }
197
+ // An existing FILE never stands in for an existing TEST (ADR-002) — and neither does an existing
198
+ // COMMENT. Matching the whole file body is forgeable with two comment lines whose letters happen to
199
+ // spell the id, so the basis is the file's TEST TITLES. Falling back to the body when none parse is
200
+ // stated in the detail rather than done quietly: a silent fallback restores the hole it closes.
201
+ const titles = extractTestTitles(body);
202
+ const basis = titles.length > 0 ? titles.map(normalizeTestId).join('\n') : normalizeTestId(body);
203
+ const basisNote = titles.length > 0 ? `${titles.length} test title(s)` : 'the whole file body — NO test titles parsed, so this match is weaker';
204
+ if (!basis.includes(needle)) {
205
+ return {
206
+ ...base,
207
+ verdict: 'name-absent-in-file',
208
+ detail: `\`${row.file}\` exists but no test in it is named \`${testId}\` (searched ${basisNote})`,
209
+ };
210
+ }
211
+ return { ...base, verdict: 'resolved', detail: `found in \`${row.file}\` (searched ${basisNote})` };
212
+ }
213
+
214
+ const ZERO_COUNTS: Record<AmendmentVerdict, number> = {
215
+ resolved: 0,
216
+ placeholder: 0,
217
+ unnamed: 0,
218
+ 'no-file-named': 0,
219
+ 'file-missing': 0,
220
+ 'name-absent-in-file': 0,
221
+ };
222
+
223
+ export function decideAmendmentOutcome(input: {
224
+ sectionPresent: boolean;
225
+ rows: readonly AmendmentRow[];
226
+ resolutions: readonly AmendmentResolution[];
227
+ planSaysNone: boolean;
228
+ readError?: string | null;
229
+ /** Ideation amendments the plan fails to carry — absent, or reworded under the same id. */
230
+ missingFromPlan?: readonly { id: string; kind: 'dropped' | 'subject-changed' }[];
231
+ }): AmendmentDecision {
232
+ const counts: Record<AmendmentVerdict, number> = { ...ZERO_COUNTS };
233
+ for (const r of input.resolutions) counts[r.verdict]++;
234
+ const reasons: string[] = [];
235
+
236
+ // Inputs we could not read are never a verdict about the feature (acid case A7).
237
+ if (input.readError) {
238
+ return { outcome: 'not-established', exit: 3, reasons: [`inputs unreadable: ${input.readError}`], counts };
239
+ }
240
+ // Absence is a skip with a stated reason, never a pass and never a silent zero (acid case A5).
241
+ if (!input.sectionPresent) {
242
+ return {
243
+ outcome: 'skip',
244
+ exit: 0,
245
+ reasons: ['no `## Amendments` section — nothing to check (this is an absence, not a pass)'],
246
+ counts,
247
+ };
248
+ }
249
+ // The whole class this feature removes: a check that silently checked nothing (AM-1, acid case A7).
250
+ if (input.rows.length === 0) {
251
+ return {
252
+ outcome: 'not-established',
253
+ exit: 3,
254
+ reasons: [
255
+ 'the `## Amendments` section is present but ZERO rows parsed — the grammar matched nothing, which is not the same as nothing being wrong',
256
+ ],
257
+ counts,
258
+ };
259
+ }
260
+ // Ideation carries rows while the plan records "None" — this is HIGH-2 itself (acid case A6).
261
+ // Discovered while closing HIGH-2: the pointers belong in the PLAN. Step 6's own instruction is
262
+ // "carry AM-N into 06_implementation_plan.md verbatim", and the ideation report is a historical
263
+ // artifact — editing its rows to match tests that were named later would be rewriting the record
264
+ // rather than closing the trail. So the plan's rows are authoritative when present, and the rule
265
+ // that keeps that honest is coverage: an ideation amendment the plan never mentions is a DROPPED
266
+ // amendment, which is the renegotiating-away failure in a quieter form.
267
+ for (const gap of input.missingFromPlan ?? []) {
268
+ reasons.push(
269
+ gap.kind === 'dropped'
270
+ ? `${gap.id} is an amendment in 03.5_ideation_report.md that 06_implementation_plan.md never carries — an amendment dropped in planning is one nobody can audit`
271
+ : `${gap.id} appears in both documents but the plan describes a DIFFERENT change — "carry verbatim" means the subject survives; only the test pointer may be renamed`,
272
+ );
273
+ }
274
+ if (input.planSaysNone) {
275
+ reasons.push(
276
+ `the ideation report carries ${input.rows.length} amendment row(s) while 06_implementation_plan.md records \`## Amendments: None\` — the amendments were renegotiated away, and an amendment nobody can resolve is one nobody can audit`,
277
+ );
278
+ }
279
+ for (const r of input.resolutions) {
280
+ if (r.verdict !== 'resolved') reasons.push(`${r.id} → ${r.verdict}: ${r.detail}`);
281
+ }
282
+ return { outcome: reasons.length > 0 ? 'fail' : 'pass', exit: reasons.length > 0 ? 1 : 0, reasons, counts };
283
+ }
284
+
285
+ /** The one line every caller reads last, in the K2 gate's own shape so the two read alike. */
286
+ export function amendmentVerdictLine(d: AmendmentDecision): string {
287
+ const label = d.outcome === 'not-established' ? 'NOT-ESTABLISHED' : d.outcome.toUpperCase();
288
+ const head = `amendment traceability: ${label}`;
289
+ const tail =
290
+ d.outcome === 'pass'
291
+ ? `${d.counts.resolved} row(s) resolved`
292
+ : (d.reasons[0] ?? 'no reason recorded');
293
+ return `${head} — ${tail}`;
294
+ }
295
+
296
+ /** Printed on every run: this checker does NOT prove a resolved test discriminates (NG-1, A8). */
297
+ export const AMENDMENT_VACUITY_NOTE =
298
+ 'note: this checks that each amendment RESOLVES to a real test, not that the test is non-vacuous — `dz discrimination-check` owns vacuity.';
299
+
300
+
301
+ /**
302
+ * The amendment's own text with the `→ test …` pointer clause and markdown furniture removed — what
303
+ * "carry AM-N into the plan verbatim" is actually about. The POINTER may legitimately change (tests
304
+ * are named later than ideation guesses); the SUBJECT may not.
305
+ */
306
+ export function amendmentSubject(raw: string): string {
307
+ const withoutPointer = raw.split(/→\s*tests?\s/)[0] ?? '';
308
+ // Strip ONLY the row's furniture: bullet/table marks, the bold id, an optional `(source)` tag and
309
+ // a colon. An earlier version consumed up to 80 characters after the id, which ate the SUBJECT
310
+ // itself whenever a row carried no `(source):` tag — the checker then compared two truncations
311
+ // and called honest rows a mismatch.
312
+ const stripped = withoutPointer.replace(/^[\s|*\-]*\**AM-\d+\**\s*(?:\([^)]{0,80}\))?\s*:?\s*/, '');
313
+ return normalizeTestId(stripped);
314
+ }
315
+
316
+ export interface PlanCoverageGap {
317
+ readonly id: string;
318
+ readonly kind: 'dropped' | 'subject-changed';
319
+ }
320
+
321
+ /**
322
+ * Ideation amendments the plan fails to carry: either absent outright, or present under the same id
323
+ * with a DIFFERENT subject. Cross-family review (Codex gpt-5.6-sol, 2026-08-21) found the second
324
+ * case: comparing ids alone let a plan swap "deny unauthenticated deletes" for "render footer" under
325
+ * the same `AM-1` and still pass.
326
+ */
327
+ export function amendmentsMissingFromPlan(
328
+ ideationRows: readonly AmendmentRow[],
329
+ planRows: readonly AmendmentRow[],
330
+ ): PlanCoverageGap[] {
331
+ const byId = new Map(planRows.map((r) => [r.id, r]));
332
+ const gaps: PlanCoverageGap[] = [];
333
+ for (const row of ideationRows) {
334
+ const planRow = byId.get(row.id);
335
+ if (planRow === undefined) {
336
+ gaps.push({ id: row.id, kind: 'dropped' });
337
+ continue;
338
+ }
339
+ const want = amendmentSubject(row.raw);
340
+ const got = amendmentSubject(planRow.raw);
341
+ // Containment either way: a plan may append a note ("closes HIGH-2"), and ideation may be the
342
+ // longer prose. What it may not do is describe a different change.
343
+ if (want.length >= MIN_MATCHABLE_ID_LENGTH && !got.includes(want) && !want.includes(got)) {
344
+ gaps.push({ id: row.id, kind: 'subject-changed' });
345
+ }
346
+ }
347
+ return gaps;
348
+ }
@@ -40,7 +40,10 @@ export type CheckpointStage = (typeof CHECKPOINT_STAGES)[number];
40
40
  * an M+ design must probe its ADR/ideation/architecture files too, not just requirements
41
41
  * (Codex QE #2: a one-file probe accepted a materially incomplete design). */
42
42
  export const STAGE_ARTIFACTS: Record<CheckpointStage, string | null> = {
43
- router: null,
43
+ // Since 2026-08-21 Step 0 WRITES this, so the router stage has something to be witnessed by. It was
44
+ // `null` — a stage that promises nothing verifiable — which is precisely how the tier came to be
45
+ // recorded nowhere while a run was alive, and how C4 lost its input without anyone noticing.
46
+ router: '00_complexity_assessment.md',
44
47
  design: '01_requirements.md',
45
48
  plan: '06_implementation_plan.md',
46
49
  code: '07_code_changes/change_manifest.md',
@@ -71,6 +74,20 @@ export const CHECKPOINT_MAX_RESULT_CHARS = 12_000;
71
74
  */
72
75
  export const CKPT_SCHEMA_VERSION = 'fa-ckpt-3';
73
76
 
77
+ /**
78
+ * Router-stage hash token. Step 0's CONTRACT changed on 2026-08-21 — it must now WRITE
79
+ * `00_complexity_assessment.md` with an acid table — and a contract change that leaves the hash
80
+ * alone lets a pre-change router entry resume: the resume gate only asks whether the artifact is
81
+ * PRESENT, and one of the 66 features that already had a (tableless) file satisfies it. Step 0 then
82
+ * never re-runs, the acid table is never written, and C4 goes on skipping — the exact defect this
83
+ * change exists to close, resurrected through the resume path.
84
+ *
85
+ * Scoped like `LANDING_HASH_TOKEN` (003-10) rather than bumping CKPT_SCHEMA_VERSION: only the router
86
+ * stage re-runs once, while design/plan/code/qe checkpoints stay valid. A global bump would re-spend
87
+ * every in-flight stage to fix one.
88
+ */
89
+ export const ROUTER_CONTRACT_TOKEN = 'router-writes-00-v1';
90
+
74
91
  /** FNV-1a 32-bit over UTF-16 code units, hex-encoded (one pass; building block for the 64-bit form). */
75
92
  export function fnv1a(str: string): string {
76
93
  let h = 0x811c9dc5;
@@ -686,3 +703,59 @@ export function parseArtifactProbe(opts: {
686
703
  if (sentinels !== 1) return null;
687
704
  return found;
688
705
  }
706
+
707
+ /** Why a checkpoint write was refused, or `ok` when it may proceed. */
708
+ export type CheckpointWriteVerdict =
709
+ | { readonly ok: true; readonly line: string; readonly witnessed: readonly string[] }
710
+ | { readonly ok: false; readonly reason: string };
711
+
712
+ /**
713
+ * Decide whether a stage may be recorded — the WITNESS half of `dz feature-adr checkpoint`.
714
+ *
715
+ * Why this exists (2026-08-21). The workflow script runs sandboxed with no filesystem, so it
716
+ * delegated checkpoint writes to a subagent by handing it a FINISHED JSON line and saying "append
717
+ * this". The subagent was a courier: it verified nothing. Read from outside, that shape is one party
718
+ * instructing another to declare a verification gate complete — which is what a safety classifier saw,
719
+ * blocking NINE such writes in one run (router, four design substages, plan, code, qe, and the cost
720
+ * ledger). MEASURED: `.fa-state/checkpoints.jsonl` was never created, while every stage had in fact
721
+ * run and left its artifact on disk. So resume was silently dead and the run still reported success.
722
+ *
723
+ * The classifier's premise was wrong for those writes, but its instinct was not: nothing in the old
724
+ * mechanism could tell a real completion from a fabricated one. A stage whose artifact does not exist
725
+ * could be recorded as complete, and yesterday's cross-family reviewer flagged exactly that for the
726
+ * `fleet` stage. So the fix is not a better-worded prompt — it is to stop hand-writing state at all.
727
+ * The subagent now RUNS A COMMAND; this function is the check that command performs first.
728
+ *
729
+ * @param artifacts repo-relative paths the stage must have produced. EMPTY IS REFUSED: a stage that
730
+ * claims nothing verifiable has nothing to witness, and recording it would restore the very
731
+ * hole this replaces.
732
+ * @param present the subset of `artifacts` the caller MEASURED on disk (never what it planned).
733
+ */
734
+ export function decideCheckpointWrite(opts: {
735
+ stage: string;
736
+ inputHash: string;
737
+ result: unknown;
738
+ artifacts: readonly string[];
739
+ present: readonly string[];
740
+ }): CheckpointWriteVerdict {
741
+ const stage = String(opts.stage ?? '').trim();
742
+ if (stage === '') return { ok: false, reason: 'stage is empty' };
743
+ if (String(opts.inputHash ?? '').trim() === '') return { ok: false, reason: 'inputHash is empty' };
744
+ // A null result is what a DEAD stage returns. Recording it would mark a failure as a success.
745
+ if (opts.result === null || opts.result === undefined) {
746
+ return { ok: false, reason: `stage ${stage} produced no result — a dead stage is never recorded` };
747
+ }
748
+ if (opts.artifacts.length === 0) {
749
+ return { ok: false, reason: `stage ${stage} declared no artifact to witness` };
750
+ }
751
+ const presentSet = new Set(opts.present.map((p) => String(p)));
752
+ const missing = opts.artifacts.filter((a) => !presentSet.has(String(a)));
753
+ if (missing.length > 0) {
754
+ return { ok: false, reason: `stage ${stage} is missing its artifact(s): ${missing.join(', ')}` };
755
+ }
756
+ const line = serializeCheckpoint(stage, opts.inputHash, opts.result);
757
+ if (line === null) {
758
+ return { ok: false, reason: `stage ${stage} result is not serialisable within the size cap` };
759
+ }
760
+ return { ok: true, line, witnessed: [...opts.artifacts] };
761
+ }