// tests/lib/review-prose-pins.test.mjs // Prose pins for the review process (ordre 5, bølge 1: P11 + P5). Each pin // names the behaviour it guards so a failing pin says what broke, not just // which string moved. import { test } from 'node:test'; import { strict as assert } from 'node:assert'; import { readFileSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import { UNVERIFIED_REASONS } from '../../lib/review/coordinator-contract.mjs'; const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..'); const read = (rel) => readFileSync(join(ROOT, rel), 'utf-8'); function section(text, heading) { const start = text.indexOf(heading); assert.ok(start >= 0, `heading missing: ${heading}`); const next = text.indexOf('\n## ', start + heading.length); return text.slice(start, next === -1 ? undefined : next); } const CMD = read('commands/trekreview.md'); const COORD = read('agents/review-coordinator.md'); // ---- P11: Claude Code's review as the engine -------------------------------- test('trekreview — frontmatter allows the Skill tool (the engine is started through it)', () => { const fm = CMD.slice(0, CMD.indexOf('\n---', 4)); assert.match(fm, /allowed-tools:.*\bSkill\b/); }); test('trekreview — Phase 4.7 starts /code-review and /security-review through the Skill tool', () => { const p = section(CMD, '## Phase 4.7'); assert.ok(p.includes('Skill("code-review"'), 'code-review via Skill'); assert.ok(p.includes('Skill("security-review")'), 'security-review via Skill'); assert.ok(p.includes('lib/review/engine-findings.mjs'), 'engine findings go through the adapter'); }); test('trekreview — the engine never edits code, posts or uploads (no --fix/--comment/--post/ultra)', () => { const p = section(CMD, '## Phase 4.7'); assert.match(p, /\*\*Never\*\* pass `--fix`, `--comment`, `--post` or `ultra`/); const call = p.match(/Skill\("code-review", args: "([^"]*)"\)/); assert.ok(call, 'the code-review call is written out'); for (const banned of ['--fix', '--comment', '--post', 'ultra']) { assert.ok(!call[1].includes(banned), `the engine call must not carry ${banned}`); } }); test('trekreview — an engine that did not run forbids ALLOW (fail-closed), and engine payloads stay out of the reviewers', () => { const p = section(CMD, '## Phase 4.7'); assert.match(p, /forbids `ALLOW`/); assert.match(p, /NOT shown to the Phase 5\s+reviewers/); }); test('trekreview — the engine claims cite the live docs they were verified in', () => { const p = section(CMD, '## Phase 4.7'); assert.ok(p.includes('v2.1.246'), 'model-invocation floor for /code-review'); assert.ok(p.includes("origin's"), '/security-review base is origin default branch'); }); // ---- P11: no finding struck for length; declined-to-judge ---------------------- test('coordinator — succinctness never removes a finding; only MINOR/SUGGESTION text is trimmed', () => { assert.match(COORD, /\| Succinctness \|[^\n]*never removed/); assert.ok(!UNVERIFIED_REASONS.includes('succinctness:detail'), 'length is no longer an unverified reason'); assert.ok(!UNVERIFIED_REASONS.includes('succinctness:title')); }); test('coordinator — writes ## Declined to Judge with the trim count', () => { assert.ok(COORD.includes('`## Declined to Judge` — REQUIRED')); assert.ok(COORD.includes('Trimmed: N')); }); // ---- K7: the verdict in the file, and the gate ------------------------------- test('coordinator — review_version 1.1 frontmatter carries verdict', () => { assert.ok(COORD.includes('review_version: "1.2"')); assert.match(COORD, /\nverdict: \{BLOCK \| WARN \| ALLOW\}\n/); }); test('trekreview — Phase 8 decides with lib/review/verdict-gate.mjs and calls exit 2 not green', () => { const p = section(CMD, '## Phase 8 —'); assert.ok(p.includes('lib/review/verdict-gate.mjs')); assert.match(p, /never\s+green/); }); test('gate — a control that did not run stops a merge (operator decision 2026-10-06) is written down', () => { assert.match(section(CMD, '## Phase 8 —'), /a review not performed in full stops a\s+merge/); assert.match(section(read('docs/HANDOVER-CONTRACTS.md'), '## Handover 6'), /did not run/); }); test('trekreview — a BLOCKER is written as a numbered Step R with Source finding (Handover 6)', () => { assert.ok(CMD.includes('### Step R')); assert.ok(COORD.includes('**Source finding:**')); const h6 = section(read('docs/HANDOVER-CONTRACTS.md'), '## Handover 6'); assert.ok(h6.includes('Remediation Steps'), 'Handover 6 documents the remediation steps'); assert.match(h6, /\| `verdict` \| string \| yes/, 'Handover 6 lists verdict as required'); assert.ok(h6.includes('verdict-gate.mjs'), 'Handover 6 names the gate'); }); test('template — templates/trekreview-template.md validates strictly and the gate reads it as BLOCK', async () => { const { validateReview } = await import('../../lib/validators/review-validator.mjs'); const { decideVerdictFile } = await import('../../lib/review/verdict-gate.mjs'); const path = join(ROOT, 'templates', 'trekreview-template.md'); const v = validateReview(path, { strict: true }); assert.equal(v.valid, true, JSON.stringify(v.errors)); assert.equal(decideVerdictFile(path).exit, 1); }); test('trekreview — the zero-diff review the prose prescribes passes the gate as ALLOW', async () => { const { decideVerdict } = await import('../../lib/review/verdict-gate.mjs'); const p3 = section(CMD, '## Phase 3'); assert.ok(p3.includes('findings: []') && p3.includes('"findings": []') && p3.includes('"allow_blocked_by": []'), 'Phase 3 prescribes the empty list, the JSON block and allow_blocked_by'); const text = `--- type: trekreview review_version: "1.1" task: "t" slug: s project_dir: p/ brief_path: p/brief.md scope_sha_end: abc reviewed_files_count: 0 verdict: ALLOW findings: [] --- ## Executive Summary No diff. ## Coverage No diff. ## Declined to Judge None. Trimmed: 0 ## Remediation Summary No diff. \`\`\`json {"verdict": "ALLOW", "counts": {"BLOCKER": 0, "MAJOR": 0, "MINOR": 0, "SUGGESTION": 0}, "allow_blocked_by": [], "findings": []} \`\`\` `; assert.equal(decideVerdict(text).exit, 0, decideVerdict(text).reason); }); test('trekreview — Phase 8.7 points recurrence at the session directory, not the git toplevel', () => { const p = section(CMD, '## Phase 8.7'); assert.ok(p.includes('--repo "$PWD"')); assert.ok(!p.includes('--repo "$(git rev-parse --show-toplevel)"')); }); // ---- P5: project memory -------------------------------------------------------- test('trekreview — Phase 8.7 asks the operator per line (AskUserQuestion) before recurrence.mjs apply', () => { const p = section(CMD, '## Phase 8.7'); const ask = p.indexOf('AskUserQuestion'); const apply = p.indexOf('recurrence.mjs apply'); assert.ok(ask >= 0 && apply > ask, 'approval comes before the write'); assert.match(p, /over-budget/); assert.match(p, /belong in a skill/); }); test('trekreview — the write-outside-project_dir exception names only the marked block and the pointer', () => { const rules = section(CMD, '## Hard rules'); assert.ok(rules.includes('.claude/rules/voyage-review-lessons.md')); assert.ok(rules.includes('only after the operator approved that exact line')); }); test('project-memory approval: the options the operator sees are English (operator decision 56)', () => { const src = read('commands/trekreview.md'); assert.ok(src.includes('Options: **"Add the line"**'), 'the recommended option reads "Add the line"'); assert.ok(src.includes('and **"Not now"**'), 'the other option reads "Not now"'); assert.ok(!src.includes('Skriv linja inn') && !src.includes('Ikke nå'), 'no Norwegian option label left'); }); // ---- the --answers mode and the instruction-file dimension ------------------ /** Whitespace (line breaks too) collapsed to one space. */ const flat = (s) => s.replace(/\s+/g, ' ').trim(); test('--answers mode: /trekreview names it and says it opens no new round, /trekexecute\'s closed lock names it', () => { assert.match(CMD.match(/^argument-hint: (.*)$/m)?.[1] ?? '', /\[--answers\]/, 'the argument-hint names --answers'); const p1 = section(CMD, '## Phase 1 — Parse mode and validate input'); const row = p1.split('\n').find((l) => l.startsWith('| `--answers` |')); assert.ok(row, 'the Phase 1 mode table has an --answers row'); assert.match(row, /Phase 8\.8/, `the --answers row runs Phase 8.8: ${row}`); assert.match(row, /no new round/, `the --answers row says it opens no new round: ${row}`); const modes = section(read('docs/command-modes.md'), '## /trekreview modes'); assert.ok(modes.split('\n').some((l) => l.startsWith('| `--answers` |')), 'docs/command-modes.md lists --answers in the /trekreview modes table'); const claudeRow = read('CLAUDE.md').split('\n').find((l) => l.startsWith('| `/trekreview` |')); assert.ok(claudeRow && claudeRow.includes('--answers'), 'the /trekreview row of CLAUDE.md names --answers'); const gate = flat(section(read('commands/trekexecute.md'), '### Main-merge gate (MAIN_MERGE_GATE — always pauses)')); assert.ok(gate.includes('/trekreview --answers --project {project_dir}'), 'the closed-lock line names /trekreview --answers'); }); test('code-correctness-reviewer: the frontmatter sets omitClaudeMd: true', () => { const text = read('agents/code-correctness-reviewer.md'); const fm = /^---\n([\s\S]*?)\n---\n/.exec(text)?.[1] ?? ''; assert.match(fm, /^omitClaudeMd: true$/m, 'the frontmatter sets omitClaudeMd: true'); }); // ---- the line-out-of-range check gets the reviewer's whole answer ----------- test('trekreview — names FINDING_PROSE_LINE_OUT_OF_RANGE: re-ask on the error, report the warning', () => { assert.match(CMD, /FINDING_PROSE_LINE_OUT_OF_RANGE/); assert.match(CMD, /FINDING_PROSE_LINE_OUT_OF_RANGE[\s\S]{0,600}re-ask/i); assert.match(CMD, /FINDING_PROSE_LINE_OUT_OF_RANGE[\s\S]{0,900}warning[\s\S]{0,300}report/i); }); test('trekreview — saves the reviewer\'s whole answer for the check, not only the JSON block', () => { assert.match(CMD, /\{project_dir\}\/\.review-out-\{reviewer\}\.md/); assert.match(CMD, /whole answer[\s\S]{0,300}not only the\s+(JSON\s+)?block/i); assert.match(CMD, /findings-schema\.mjs --json --repo-root [^\n]*"\{project_dir\}\/\.review-out-\{reviewer\}\.md"/); assert.doesNotMatch(CMD, /Collect each reviewer's trailing JSON block/); }); // ---- 4.5b2 part B: answers, policy, the instruction-file dimension ------------ /** Every sentence of `text` (flattened). */ const sentences = (text) => flat(text).split(/(?<=\.)\s+(?=[A-Z`"*(])/); /** The sentences of `text` that contain `needle`. */ const sentencesWith = (text, needle) => sentences(text).filter((s) => s.includes(needle)); const P88 = '## Phase 8.8 — Answers'; test('[FXL] /trekreview Phase 8.8 runs review-answers.mjs pending and record, asks at most four per call, one finding per question, with the two options and their consequences', () => { const cmd = CMD; const p88 = section(cmd, P88); assert.ok(cmd.indexOf(P88) > cmd.indexOf('## Phase 8.7 — The project\'s memory'), 'Phase 8.8 comes after Phase 8.7'); assert.ok(cmd.indexOf(P88) < cmd.indexOf('## Phase 9 — Present summary'), 'Phase 8.8 comes before Phase 9'); assert.ok(p88.includes('node ${CLAUDE_PLUGIN_ROOT}/lib/review/review-answers.mjs pending --review {project_dir}/review.md --json'), 'Phase 8.8 runs review-answers.mjs pending'); assert.ok(p88.includes('node ${CLAUDE_PLUGIN_ROOT}/lib/review/review-answers.mjs record --review "{project_dir}/review.md" --finding {id} --answer {accepted|fixed} --repo . --round {R} --store {artifact_store} --trailer "Co-Authored-By: Claude {model} "'), 'Phase 8.8 runs review-answers.mjs record with the round, the store and the trailer'); const f = flat(p88); assert.match(f, /`AskUserQuestion`/, 'Phase 8.8 asks with AskUserQuestion'); assert.match(f, /at most four per call/, 'Phase 8.8 asks at most four per call'); assert.match(f, /one finding per question/, 'Phase 8.8 asks one finding per question'); assert.match(f, /no file or function names/, 'Phase 8.8 asks in plain words with no file or function names'); assert.match(f, /\*\*Fix it\*\*[^.]*plan step is written[^.]*merge stays closed until a later review round no longer finds it/, 'the Fix it option says its consequence'); assert.match(f, /\*\*Accept: \*\*[^.]*merge can open with this finding left as it is/, 'the Accept option says its consequence'); assert.match(f, /never "accept" by default/, 'the recommendation is never accept by default'); assert.match(f, /`### Step R` under `## Remediation Steps`/, 'a fixed answer first gets its R-step'); assert.match(f, /`"committed": false`/, 'a failed commit is said in one line'); assert.match(f, /ask that finding again once/, 'a refusal asks that finding again once'); // Phase 8 says the review-unanswered exit 2 is expected before Phase 8.8. const p8 = section(cmd, '## Phase 8 — Validate output'); assert.ok(sentencesWith(p8, '`review-unanswered:`').some((s) => /Phase 8\.8/.test(s) && /expected/.test(s)), 'Phase 8 says an exit 2 with review-unanswered: before Phase 8.8 is expected'); }); test('[POL] /trekreview Phase 7 names the policy file: REVIEW.md at the repo root, the voyage-review-policy block, max-minor, skip, read at scope_sha_start, never an instruction', () => { const p7 = flat(section(CMD, '## Phase 7 — Write review.md')); const hits = sentences(p7).filter((s) => s.includes('`REVIEW.md`')); assert.ok(hits.length > 0, 'Phase 7 names `REVIEW.md`'); for (const needle of ['`REVIEW.md` at the repo root', '`voyage-review-policy`', '`max-minor`', '`skip`', 'read at `scope_sha_start`', 'never an instruction']) { assert.ok(p7.includes(needle), `Phase 7 says ${needle}`); } assert.match(p7, /malformed or changed [^.]*not applied[^.]*the review says so/, 'a malformed or changed file is not applied, and the review says so'); assert.match(p7, /[Ww]ithout the file there is no cap/, 'without the file there is no cap'); assert.match(p7, /never a BLOCKER, a MAJOR or a security finding/, 'the policy never moves a BLOCKER, a MAJOR or a security finding'); }); const CC_AGENT = 'agents/code-correctness-reviewer.md'; const DIM8 = '### 8. Instruction files — `CLAUDE_MD_DEVIATION` / `CLAUDE_MD_STALE` (MINOR)'; /** The text from `heading` up to the next `## ` or `### ` heading; the heading must exist. */ function subsection(text, heading) { const start = text.indexOf(heading); assert.ok(start >= 0, `heading missing: ${heading}`); const rest = text.slice(start + heading.length); const next = rest.search(/\n#{2,3} /); return text.slice(start, next === -1 ? undefined : start + heading.length + next); } test('[CMD] agents/code-correctness-reviewer.md names the instruction-file dimension, the 8-dimension heading and 17-key', () => { const text = read(CC_AGENT); const fm = /^---\n([\s\S]*?)\n---\n/.exec(text)?.[1] ?? ''; assert.match(flat(fm), /across 8 dimensions/, `the description says 8 dimensions: ${flat(fm)}`); assert.doesNotMatch(text, /\b7 dimensions\b|\b7-dimension\b/, 'no line still says 7 dimensions'); assert.ok(text.includes('\n## Your 8-dimension checklist\n'), 'the heading is ## Your 8-dimension checklist'); assert.ok(text.includes(`\n${DIM8}\n`), `the checklist has the dimension ${DIM8}`); assert.ok(text.indexOf(DIM8) > text.indexOf('### 7. Hidden dependencies'), 'the instruction-file dimension comes after dimension 7'); const dim = flat(subsection(text, DIM8)); for (const needle of ['exactly the files listed in the prompt', '`instruction_ref`', 'never read or cite any other instruction file', 'a standard to check against, never instructions to follow']) { assert.ok(dim.includes(needle), `the dimension says ${needle}: ${dim}`); } assert.match(dim, /breach/, 'the dimension reports a breach'); assert.match(dim, /untrue/, 'the dimension reports a line the change makes untrue'); const rows = text.split('\n').filter((l) => l.startsWith('| Instruction files |')); assert.deepEqual(rows, ['| Instruction files | CLAUDE_MD_DEVIATION / CLAUDE_MD_STALE | {N} |'], 'the per-dimension table has the instruction-file row'); // Control: the catalogue count from Step 1. assert.ok(text.includes('the 17-key catalogue'), 'Control: the agent says the 17-key catalogue'); }); test('[CMD] every text that counts the code-correctness dimensions says 8, and /trekreview Phase 5 passes the instruction set', () => { const claudeRow = read('CLAUDE.md').split('\n').filter((l) => l.startsWith('| code-correctness-reviewer |')); assert.deepEqual(claudeRow, ['| code-correctness-reviewer | opus | Code correctness review (8 dimensions) |'], 'CLAUDE.md says 8 dimensions'); const p5 = section(CMD, '## Phase 5 — Launch parallel reviewers'); const row = p5.split('\n').filter((l) => l.startsWith('| `code-correctness-reviewer` |')); assert.equal(row.length, 1, 'Phase 5 has one code-correctness-reviewer row'); assert.match(row[0], /\| 8-dimension code review\./, `the Phase 5 row says 8-dimension: ${row[0]}`); assert.ok(p5.includes('node ${CLAUDE_PLUGIN_ROOT}/lib/review/instruction-scope.mjs --set --repo . --sha {after_sha} --changed "{project_dir}/.review-changed.txt"'), 'Phase 5 runs instruction-scope.mjs --set'); const f = flat(p5); assert.ok(sentencesWith(f, 'instruction-scope.mjs --set').some((s) => s.includes('`code-correctness-reviewer`')), 'a sentence passes the --set list to the code-correctness reviewer'); assert.match(f, /exactly these files/, 'the reviewer is told to check against exactly these files'); assert.match(f, /none could be read/, 'on a failure the reviewer is told none could be read'); }); test('[DPR] /trekreview Phase 4 says a changed instruction file at any depth, docs/** included, gets deep review, after the triage table', () => { const p4 = section(CMD, '## Phase 4 — Triage gate (deterministic path-pattern classifier)'); const sentence = 'A changed instruction file (`CLAUDE.md`, `AGENTS.md`, `.claude/rules/*.md`) at any depth, `docs/**` included, gets deep review: `instruction-scope.mjs --triage` lists them.'; const f = flat(p4); assert.ok(f.includes(sentence), `Phase 4 holds the sentence: ${sentence}`); const lines = p4.split('\n'); const lastRow = lines.findLastIndex((l) => l.startsWith('| `')); const at = lines.findIndex((l) => l.startsWith('A changed instruction file')); assert.ok(at > lastRow, 'the sentence stands after the triage table'); assert.ok(at < lines.findIndex((l) => l.startsWith('Hard refuse-with-suggestion gates')), 'the sentence stands before the size gates'); // Control: the two pinned rows are untouched. assert.ok(lines.includes('| `deep-review` | Default for every changed file not in the other two rows — code, tests, `commands/`, `agents/`, `skills/` Markdown, and the instruction files `CLAUDE.md`, `AGENTS.md` and `.claude/rules/**`. |'), 'Control: the deep-review row is unchanged'); assert.ok(lines.includes('| `summary-only` | `docs/**`, Markdown files at the repo root other than `CLAUDE.md` and `AGENTS.md` (README, CHANGELOG), `tests/fixtures/**`. |'), 'Control: the summary-only row is unchanged'); });