refactor(review): simplify pass over E (reuse, simplification, efficiency)

Quality only, no behaviour change (four cleanup reviewers, one implementer;
npm test 2480/0 on the working tree):

- threat-model.mjs splitBacked(): the one known_outside backing check of
  plan-gate (record and bare gate), verdict-gate and review-finalize, with
  one why-text; the engines' security keys derived from ENGINES; isSecurity.
- coordinator-contract: "not a security engine" read from ENGINES (a string
  engine only), not the code-review literal.
- review-rounds owns trailingBlock, findingsBlockSha, isMajor, isBlocker;
  review-answers imports them (review-rounds still imports nothing from it).
  prepare keeps the archive bytes it read instead of reading the previous
  archive again.
- engine-compare exports rowIn and payloadEngine; finalize uses them.
- plan-gate: one accepted_open builder; the stop-rule check hoisted; one
  top-level lookup for --record --brief.
- security-engine: notFullShas(), runCli's usage flag, readScopeList shared
  with engine-findings; findReport and reviewRoundSummary module-private;
  two dead defaults gone.
- tests: shared plan-gate harness and threat-model brief helpers; the [CNV]
  table cases call convertReport in-process, one CLI case per exit path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-11-08 21:27:59 +01:00
commit f820081bdc
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
18 changed files with 332 additions and 373 deletions

View file

@ -12,6 +12,7 @@ import { strict as assert } from 'node:assert';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { TM, briefWith } from '../helpers/threat-model-brief.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
@ -19,43 +20,7 @@ const validator = () => import(join(ROOT, 'lib', 'validators', 'brief-validator.
const approval = () => import(join(ROOT, 'lib', 'validators', 'intent-approval.mjs'));
const read = (rel) => readFileSync(join(ROOT, rel), 'utf8');
const TM = `## Threat Model
- Inside: a crafted file name in a pull request reaches the shell
- Outside: a local user who can already edit the repo's hooks
`;
const brief = (threat = '') => `---
type: trekbrief
brief_version: "2.2"
created: 2026-11-08
task: "Add an upload hook"
slug: upload-hook
project_dir: .claude/projects/2026-11-08-upload-hook/
research_topics: 0
research_status: complete
framing: new-direction
---
# Task
## TL;DR
An upload hook.
## Intent
Uploads arrive from strangers.
## Goal
A hook that checks each upload.
${threat}
## Success Criteria
- It checks.
`;
const brief = (threat = '') => briefWith(threat);
const codes = (r) => r.errors.map((e) => e.code);
const STAMP_AT = new Date('2026-11-08T08:00:00Z');

View file

@ -13,51 +13,28 @@
import { test } from 'node:test';
import { strict as assert } from 'node:assert';
import { resolve } from 'node:path';
import { gatePlan, recordVerdict, planHash, operativeText, acceptOpen } from '../../lib/validators/plan-gate.mjs';
import { gatePlan, planHash, operativeText, acceptOpen } from '../../lib/validators/plan-gate.mjs';
import * as diffMod from '../../lib/review/critic-diff.mjs';
import { dedupFindings, contentOverlap } from '../../lib/review/plan-review-dedup.mjs';
import { contentOverlap } from '../../lib/review/plan-review-dedup.mjs';
import { computeFindingId } from '../../lib/parsers/finding-id.mjs';
import { buildPlan } from '../helpers/plan-v18-builder.mjs';
import { spawnSync } from 'node:child_process';
import {
mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync, readdirSync, appendFileSync, realpathSync,
} from 'node:fs';
import { join, dirname } from 'node:path';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { childEnv } from '../helpers/child-env.mjs';
import {
ROOT, at, baseOf, recorder, dd, R2_CHANGES, R2_EDITED, editA, runGate as gate, GIT_CLEAN, tempRepo,
} from '../helpers/plan-gate-harness.mjs';
const NOW = '2026-10-16T00:00:00.000Z';
const PLAN = resolve('plan.md');
const PATHS = [PLAN];
const BOTH = [{ agent: 'plan-critic', present: true }, { agent: 'scope-guardian', present: true }];
/** The 1-based full-file line holding `s` (findIndex over the whole text). */
function at(text, s) {
const n = text.split('\n').findIndex(l => l.includes(s)) + 1;
assert.ok(n > 0, `the plan holds ${JSON.stringify(s)}`);
return n;
}
/** The base a round diffs against: the operative text the previous round reviewed. */
const baseOf = t => ({ sha256: planHash(t), text: operativeText(t) });
/** One round as Phase 9 runs it, with the plan path known to the gate. */
function rec(text, d, opts = {}) {
const r = recordVerdict(text, d, { reviewed: planHash(text), planPaths: PATHS, now: NOW, ...opts });
assert.equal(r.code, 0, r.message);
return r;
}
/** Reviewer payloads through the real dedup. */
function dd({ pc = [], sg = [], pcPrev, sgPrev } = {}) {
return dedupFindings([
{ agent: 'plan-critic', payload: { findings: pc, ...(pcPrev ? { previous: pcPrev } : {}) } },
{ agent: 'scope-guardian', payload: { findings: sg, ...(sgPrev ? { previous: sgPrev } : {}) } },
]);
}
const rec = recorder(NOW);
const f = (severity, line, text, extra = {}) => ({ file: 'plan.md', line, rule_key: 'step-quality', severity, text, ...extra });
const byText = (v, s) => {
@ -69,15 +46,8 @@ const byId = (v, id) => v.findings.filter(x => x.id === id);
// ---- the edits ---------------------------------------------------------------
const R2_CHANGES = '- **Changes:** Add `run2()` to `src/mod2.mjs`. (new file)';
const R2_EDITED = '- **Changes:** Add `run2()` and its error path to `src/mod2.mjs`. (new file)\n - `run2()` throws on empty input.';
const WHY = 'Why: the brief asks for a parser CLI.';
/** Edit A: Step 2's Changes line becomes two lines (a two-line hunk, nothing above it moves). */
function editA(t) {
assert.ok(t.includes(R2_CHANGES));
return t.replace(R2_CHANGES, R2_EDITED);
}
/** Edit B: the Context line is reworded (a one-line hunk high in the plan, nothing moves). */
function editB(t) {
assert.ok(t.includes(WHY));
@ -702,26 +672,10 @@ test('acceptOpen after round 3 lists only the real majors, never a lowered one',
// .git. Expected hashes come from the CLI's own --hash (taken before the
// round), expected line numbers from findIndex over the plan text.
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const GATE = join(ROOT, 'lib', 'validators', 'plan-gate.mjs');
const GIT_CLEAN = { GIT_DIR: undefined, GIT_WORK_TREE: undefined, GIT_INDEX_FILE: undefined };
function gate(cwd, args, input) {
const r = spawnSync(process.execPath, [GATE, ...args], { cwd, input, encoding: 'utf-8', env: childEnv(GIT_CLEAN) });
return { code: r.status, out: r.stdout, err: r.stderr };
}
const git = (cwd, args) => spawnSync('git', args, { cwd, encoding: 'utf-8', env: childEnv(GIT_CLEAN) });
/** A fresh temp dir (real path), `git init`-ed when `repo` is true. */
function tempDir(prefix, repo) {
const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix)));
if (repo) {
const g = git(dir, ['init', '-q']);
assert.equal(g.status, 0, g.stderr);
}
return dir;
}
const tempDir = (prefix, repo) => (repo ? tempRepo(prefix) : realpathSync(mkdtempSync(join(tmpdir(), prefix))));
/** The plan in its own temp git repo; the gate runs with that repo as cwd. */
function withRepo(text, fn) {

View file

@ -23,45 +23,18 @@
import { test } from 'node:test';
import { strict as assert } from 'node:assert';
import { resolve, join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, readFileSync, rmSync, realpathSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import { writeFileSync, readFileSync, rmSync } from 'node:fs';
import {
gatePlan, recordVerdict, planHash, operativeText, acceptOpen, extractVerdict, REVIEW_LOG_SECTIONS,
gatePlan, recordVerdict, planHash, acceptOpen, extractVerdict, REVIEW_LOG_SECTIONS,
} from '../../lib/validators/plan-gate.mjs';
import { dedupFindings } from '../../lib/review/plan-review-dedup.mjs';
import { buildPlan } from '../helpers/plan-v18-builder.mjs';
import { childEnv } from '../helpers/child-env.mjs';
import {
PATHS, at, baseOf, recorder, dd, keyedFinding as f, R1_CHANGES, editA, runGate as run, lastJson, tempRepo,
} from '../helpers/plan-gate-harness.mjs';
const NOW = '2026-11-08T00:00:00.000Z';
const PLAN = resolve('plan.md');
const PATHS = [PLAN];
function at(text, s) {
const n = text.split('\n').findIndex(l => l.includes(s)) + 1;
assert.ok(n > 0, `the plan holds ${JSON.stringify(s)}`);
return n;
}
const baseOf = t => ({ sha256: planHash(t), text: operativeText(t) });
function rec(text, d, opts = {}) {
const r = recordVerdict(text, d, { reviewed: planHash(text), planPaths: PATHS, now: NOW, ...opts });
assert.equal(r.code, 0, r.message);
return r;
}
function dd({ pc = [], sg = [], pcPrev, sgPrev } = {}) {
return dedupFindings([
{ agent: 'plan-critic', payload: { findings: pc, ...(pcPrev ? { previous: pcPrev } : {}) } },
{ agent: 'scope-guardian', payload: { findings: sg, ...(sgPrev ? { previous: sgPrev } : {}) } },
]);
}
const f = (severity, line, text, rule_key, extra = {}) => ({ file: 'plan.md', line, rule_key, severity, text, ...extra });
const R2_CHANGES = '- **Changes:** Add `run2()` to `src/mod2.mjs`. (new file)';
const R2_EDITED = '- **Changes:** Add `run2()` and its error path to `src/mod2.mjs`. (new file)\n - `run2()` throws on empty input.';
const R1_CHANGES = 'Add `run1()`';
const editA = t => { assert.ok(t.includes(R2_CHANGES)); return t.replace(R2_CHANGES, R2_EDITED); };
const rec = recorder(NOW);
const B1 = 'The dependency on the parser module is never declared in the manifest list';
const B2 = 'A second import chain reaches the CLI without passing through its argument checker';
@ -327,19 +300,9 @@ test('the "Adversarial Pass 2 (v5.1.1 high-effort)" heading is no longer review
// ---- CLI ------------------------------------------------------------------------------
const ROOT = join(fileURLToPath(new URL('.', import.meta.url)), '..', '..');
const GATE = join(ROOT, 'lib', 'validators', 'plan-gate.mjs');
const GIT_CLEAN = { GIT_DIR: undefined, GIT_WORK_TREE: undefined, GIT_INDEX_FILE: undefined };
const run = (cwd, args, input) => {
const r = spawnSync(process.execPath, [GATE, ...args], { cwd, input, encoding: 'utf-8', env: childEnv(GIT_CLEAN) });
return { code: r.status, out: r.stdout, err: r.stderr };
};
const lastJson = out => JSON.parse(out.split('\n').filter(l => l !== '').at(-1));
test('CLI: two rounds with a new dep blocker each -> the gate stops with PLAN_GATE_STOP_RULE and a third --record is refused', () => {
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'plan-gate-stop-')));
const dir = tempRepo('plan-gate-stop-');
try {
assert.equal(spawnSync('git', ['init', '-q'], { cwd: dir, env: childEnv(GIT_CLEAN) }).status, 0);
const p = join(dir, 'plan.md');
writeFileSync(p, buildPlan());
const round = (payload, extra = []) => run(dir, ['--record', p, '--reviewed', planHash(readFileSync(p, 'utf-8')), ...extra], JSON.stringify(dd(payload)));

View file

@ -21,22 +21,20 @@
import { test } from 'node:test';
import { strict as assert } from 'node:assert';
import { resolve, join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, realpathSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { gatePlan, recordVerdict, planHash, operativeText, extractVerdict } from '../../lib/validators/plan-gate.mjs';
import { join } from 'node:path';
import { mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
import { gatePlan, recordVerdict, planHash, extractVerdict } from '../../lib/validators/plan-gate.mjs';
import { dedupFindings } from '../../lib/review/plan-review-dedup.mjs';
import { readThreatModel } from '../../lib/review/threat-model.mjs';
import { stampIntentApproval } from '../../lib/validators/intent-approval.mjs';
import { appendApproval, normalizeHex, normalizeSubject, resolveRepo } from '../../lib/util/approval-log.mjs';
import { buildPlan } from '../helpers/plan-v18-builder.mjs';
import { childEnv } from '../helpers/child-env.mjs';
import {
ROOT, PATHS, at, baseOf, recorder, dd, keyedFinding as f, R1_CHANGES, editA, runGate as run, lastJson, tempRepo,
} from '../helpers/plan-gate-harness.mjs';
const NOW = '2026-11-08T00:00:00.000Z';
const PLAN = resolve('plan.md');
const PATHS = [PLAN];
const rec = recorder(NOW);
const OUTSIDE = "a local user who can already edit the repo's hooks";
const INSIDE = 'a crafted file name in a pull request reaches the shell';
@ -78,30 +76,6 @@ A parser CLI that checks its input.
const TM = { usable: true, why: null, threatModel: readThreatModel(BRIEF) };
const NOT_USABLE = { usable: false, why: 'the intent approval is not current (BRIEF_INTENT_APPROVAL_STALE)', threatModel: readThreatModel(BRIEF) };
function at(text, s) {
const n = text.split('\n').findIndex(l => l.includes(s)) + 1;
assert.ok(n > 0, `the plan holds ${JSON.stringify(s)}`);
return n;
}
const baseOf = t => ({ sha256: planHash(t), text: operativeText(t) });
function rec(text, d, opts = {}) {
const r = recordVerdict(text, d, { reviewed: planHash(text), planPaths: PATHS, now: NOW, ...opts });
assert.equal(r.code, 0, r.message);
return r;
}
function dd({ pc = [], sg = [], pcPrev, sgPrev } = {}) {
return dedupFindings([
{ agent: 'plan-critic', payload: { findings: pc, ...(pcPrev ? { previous: pcPrev } : {}) } },
{ agent: 'scope-guardian', payload: { findings: sg, ...(sgPrev ? { previous: sgPrev } : {}) } },
]);
}
const f = (severity, line, text, rule_key, extra = {}) => ({ file: 'plan.md', line, rule_key, severity, text, ...extra });
const R1_CHANGES = 'Add `run1()`';
const R2_CHANGES = '- **Changes:** Add `run2()` to `src/mod2.mjs`. (new file)';
const R2_EDITED = '- **Changes:** Add `run2()` and its error path to `src/mod2.mjs`. (new file)\n - `run2()` throws on empty input.';
const editA = t => { assert.ok(t.includes(R2_CHANGES)); return t.replace(R2_CHANGES, R2_EDITED); };
const S1 = 'A hook file edited by a local user runs before the parser checks its input';
const B1 = 'The dependency on the parser module is never declared in the manifest list';
@ -267,19 +241,9 @@ test('gate: without --brief the brief is read from the verdict\'s brief_path; no
// ---- CLI ------------------------------------------------------------------------------
const ROOT = join(fileURLToPath(new URL('.', import.meta.url)), '..', '..');
const GATE = join(ROOT, 'lib', 'validators', 'plan-gate.mjs');
const GIT_CLEAN = { GIT_DIR: undefined, GIT_WORK_TREE: undefined, GIT_INDEX_FILE: undefined };
const run = (cwd, args, input) => {
const r = spawnSync(process.execPath, [GATE, ...args], { cwd, input, encoding: 'utf-8', env: childEnv(GIT_CLEAN) });
return { code: r.status, out: r.stdout, err: r.stderr };
};
const lastJson = out => JSON.parse(out.split('\n').filter(l => l !== '').at(-1));
test('CLI: --record --brief lists a backed finding as a known issue; the gate warns, and STOPs once the Outside line changes', () => {
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'plan-gate-tm-')));
const dir = tempRepo('plan-gate-tm-');
try {
assert.equal(spawnSync('git', ['init', '-q'], { cwd: dir, env: childEnv(GIT_CLEAN) }).status, 0);
const b = join(dir, 'brief.md');
const s = stampIntentApproval(BRIEF, new Date(NOW));
assert.equal(s.stamped, true);
@ -315,9 +279,8 @@ test('CLI: --record --brief lists a backed finding as a known issue; the gate wa
});
test('fix 6: brief_path is stored relative to the repo top level, and the gate run from a subdirectory reads the same brief', () => {
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'plan-gate-tm-')));
const dir = tempRepo('plan-gate-tm-');
try {
assert.equal(spawnSync('git', ['init', '-q'], { cwd: dir, env: childEnv(GIT_CLEAN) }).status, 0);
const b = join(dir, 'brief.md');
const s = stampIntentApproval(BRIEF, new Date(NOW));
writeFileSync(b, s.text);
@ -344,9 +307,8 @@ test('fix 6: brief_path is stored relative to the repo top level, and the gate r
});
test('CLI: --brief without a value is a usage error; a threat model that is not usable is said in the output', () => {
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'plan-gate-tm-')));
const dir = tempRepo('plan-gate-tm-');
try {
assert.equal(spawnSync('git', ['init', '-q'], { cwd: dir, env: childEnv(GIT_CLEAN) }).status, 0);
const p = join(dir, 'plan.md');
writeFileSync(p, buildPlan());
const t1 = readFileSync(p, 'utf-8');