chore(voyage): release v5.0.0 — remove bespoke playground + /trekrevise + Handover 8; render produced artifacts to HTML + link, annotate via /playground

The v4.2/v4.3 bespoke playground SPA (~388 KB), the /trekrevise command,
Handover 8 (annotation → revision), the supporting lib/ modules
(anchor-parser, annotation-digest, markdown-write, revision-guard), the
Playwright e2e suite, and the @playwright/test / @axe-core/playwright
devDeps are removed. A browser walkthrough found the playground borderline
unusable, and it duplicated the official /playground plugin's
document-critique / diff-review templates.

In their place: scripts/render-artifact.mjs — a small, zero-dependency
renderer that turns a brief/plan/review .md into a self-contained,
design-system-styled, zero-network .html (frontmatter folded into a
<details> block). /trekbrief, /trekplan, and /trekreview call it on their
last step and print the file:// link; to annotate, run /playground
(document-critique) on the .md and paste the generated prompt back.

Resolves the v4.3.1-deferred findings as moot (their target files are
deleted). npm test green: 509 tests, 507 pass, 0 fail, 2 skipped.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-05-12 14:05:07 +02:00
commit 916d30f63e
96 changed files with 620 additions and 14716 deletions

View file

@ -80,7 +80,7 @@ test('commands/trekexecute.md still parses v1.7 plan schema', () => {
test('settings.json has only known top-level scopes after Spor 0 cleanup', () => {
const cfg = JSON.parse(read('settings.json'));
const known = ['trekplan', 'trekresearch', 'trekrevise'];
const known = ['trekplan', 'trekresearch'];
for (const k of Object.keys(cfg)) {
assert.ok(known.includes(k), `Unknown top-level scope in settings.json: ${k}`);
}
@ -94,10 +94,9 @@ test('settings.json no longer carries vestigial exploration block', () => {
'agentTeam block was vestigial — should be deleted in v3.1.0 Spor 0');
});
test('CLAUDE.md mentions all seven pipeline commands', () => {
test('CLAUDE.md mentions all six pipeline commands', () => {
// v4.1 Step 21 — added /trekcontinue to coverage (was 5/6 before).
// v4.2 Step 12 — added /trekrevise (Handover 8 producer), bringing the
// canonical pipeline to seven commands.
// v5.0.0 — /trekrevise removed (bespoke playground retired); back to six.
const md = read('CLAUDE.md');
for (const c of [
'/trekbrief',
@ -105,7 +104,6 @@ test('CLAUDE.md mentions all seven pipeline commands', () => {
'/trekplan',
'/trekexecute',
'/trekreview',
'/trekrevise',
'/trekcontinue',
]) {
assert.ok(md.includes(c), `CLAUDE.md missing reference to ${c}`);
@ -261,7 +259,6 @@ const PIPELINE_COMMANDS = [
'trekplan.md',
'trekexecute.md',
'trekreview.md',
'trekrevise.md',
'trekcontinue.md',
];
@ -403,246 +400,87 @@ test('commands/trekplan.md Phase 8 seals Opus-4.7 schema-drift defense', () => {
);
});
// --- v4.2 Step 12 — Handover 8 + annotation pipeline pins ---
// --- v5.0.0 — bespoke playground + /trekrevise + Handover 8 removed ---
//
// CLAUDE.md / README.md / CHANGELOG / annotation-quickstart pins are deferred
// to Step 13 (post-write of those files). Step 12 only pins HANDOVER-CONTRACTS,
// templates, scaffold-files, and the parseAnchors round-trip on the example
// fixture.
// The v4.2/v4.3 bespoke playground SPA, the /trekrevise command, and
// Handover 8 (annotation → revision) were removed in v5.0.0. Producing
// commands now render artifacts to self-contained HTML via
// scripts/render-artifact.mjs and direct operators at the official
// `/playground` plugin for annotation. These pins lock the removal in.
import { existsSync, statSync } from 'node:fs';
import { existsSync } from 'node:fs';
test('HANDOVER-CONTRACTS.md contains Handover 8 section (annotation → revision)', () => {
test('playground/ directory no longer exists (removed in v5.0.0)', () => {
assert.ok(
!existsSync(join(ROOT, 'playground')),
'plugins/voyage/playground/ should be deleted — the bespoke playground was retired in v5.0.0',
);
});
test('commands/trekrevise.md no longer exists (removed in v5.0.0)', () => {
assert.ok(
!existsSync(join(ROOT, 'commands/trekrevise.md')),
'/trekrevise was removed in v5.0.0 — its command file should be gone',
);
});
test('Handover 8 deleted from HANDOVER-CONTRACTS.md (back to seven handovers)', () => {
const text = read('docs/HANDOVER-CONTRACTS.md');
assert.ok(
text.includes('## Handover 8'),
'docs/HANDOVER-CONTRACTS.md should document Handover 8 (annotation → revision) — added in v4.2',
);
assert.ok(!text.includes('## Handover 8'), 'Handover 8 section should be removed in v5.0.0');
assert.ok(text.includes('## Handover 7'), 'Handover 7 must remain');
});
test('HANDOVER-CONTRACTS.md Handover 8 names annotation_digest and source_annotations', () => {
const text = read('docs/HANDOVER-CONTRACTS.md');
const h8Start = text.indexOf('## Handover 8');
assert.ok(h8Start >= 0, 'Handover 8 heading missing');
const h8End = text.indexOf('## Stability summary', h8Start);
assert.ok(h8End > h8Start, 'Stability summary heading missing — could not bound Handover 8');
const h8 = text.slice(h8Start, h8End);
assert.ok(
h8.includes('annotation_digest'),
'Handover 8 section should document the annotation_digest frontmatter field',
);
assert.ok(
h8.includes('source_annotations'),
'Handover 8 section should document the source_annotations frontmatter field',
);
assert.ok(
h8.includes('revision'),
'Handover 8 section should document the revision counter field',
);
});
test('templates/plan-template.md documents annotation revision fields', () => {
const tpl = read('templates/plan-template.md');
assert.ok(
tpl.includes('revision:'),
'plan-template.md must document optional revision counter (Handover 8)',
);
assert.ok(
tpl.includes('source_annotations:'),
'plan-template.md must document optional source_annotations list (Handover 8)',
);
assert.ok(
tpl.includes('annotation_digest'),
'plan-template.md must document optional annotation_digest field (Handover 8)',
);
});
test('templates/trekbrief-template.md documents annotation revision fields', () => {
const tpl = read('templates/trekbrief-template.md');
assert.ok(
tpl.includes('revision:'),
'trekbrief-template.md must document optional revision counter (Handover 8)',
);
assert.ok(
tpl.includes('source_annotations:'),
'trekbrief-template.md must document optional source_annotations list (Handover 8)',
);
assert.ok(
tpl.includes('annotation_digest'),
'trekbrief-template.md must document optional annotation_digest field (Handover 8)',
);
});
test('templates/trekreview-template.md documents annotation revision fields', () => {
const tpl = read('templates/trekreview-template.md');
assert.ok(
tpl.includes('revision:'),
'trekreview-template.md must document optional revision counter (Handover 8)',
);
assert.ok(
tpl.includes('source_annotations:'),
'trekreview-template.md must document optional source_annotations list (Handover 8)',
);
assert.ok(
tpl.includes('annotation_digest'),
'trekreview-template.md must document optional annotation_digest field (Handover 8)',
);
});
test('playground/ directory exists at voyage root (Handover 8 producer surface)', () => {
const playgroundDir = join(ROOT, 'playground');
assert.ok(existsSync(playgroundDir), 'playground/ directory missing');
assert.ok(statSync(playgroundDir).isDirectory(), 'playground/ is not a directory');
// Self-contained HTML must exist
assert.ok(
existsSync(join(playgroundDir, 'voyage-playground.html')),
'playground/voyage-playground.html missing — operator-facing entry point',
);
});
test('playground/ files do NOT import or reference `marked` (risk-assessor H1)', () => {
// Walk playground/ recursively. Exclude vendor/playground-design-system
// (consumed via the shared design system; not part of voyage's playground
// markdown renderer). Exclude any *MANIFEST.json files. Assert no file
// contains the standalone identifier `marked` (case-sensitive, word-boundary).
// markdown-it is the locked renderer per research-03 + alternatives table.
const playgroundDir = join(ROOT, 'playground');
assert.ok(existsSync(playgroundDir), 'playground/ directory missing — cannot verify marked-ban');
const offenders = [];
function walk(dir) {
for (const entry of readdirSync(dir)) {
const p = join(dir, entry);
const s = statSync(p);
if (s.isDirectory()) {
// Skip vendor design-system trees (shared infra, not voyage's renderer)
if (entry === 'playground-design-system') continue;
walk(p);
} else if (s.isFile()) {
// Skip vendor manifest JSONs
if (entry.endsWith('MANIFEST.json')) continue;
if (entry === 'VENDOR-MANIFEST.json') continue;
const txt = readFileSync(p, 'utf-8');
if (/\bmarked\b/.test(txt)) {
offenders.push(p.slice(ROOT.length + 1));
}
}
}
}
walk(playgroundDir);
assert.deepStrictEqual(
offenders,
[],
`playground/ files contain banned identifier "marked": ${offenders.join(', ')}. ` +
`Use markdown-it instead — see plan Alternatives table (Issue #3515 disqualifies marked).`,
);
});
test('scripts/render-artifact.mjs exists (SC1/SC11 self-render gate)', () => {
test('scripts/render-artifact.mjs exists (v5.0.0 render-and-link step)', () => {
assert.ok(
existsSync(join(ROOT, 'scripts/render-artifact.mjs')),
'scripts/render-artifact.mjs missing — required by SC1 (offline render) and SC11 (pipeline-self-eat)',
'scripts/render-artifact.mjs is required — producing commands call it to render artifacts to HTML',
);
});
test('lib/util/revision-guard.mjs exists (plan-critic M4 — atomic-write rollback guard)', () => {
assert.ok(
existsSync(join(ROOT, 'lib/util/revision-guard.mjs')),
'lib/util/revision-guard.mjs missing — required for /trekrevise rollback hygiene',
);
});
test('tests/fixtures/annotation/annotation-example.md parses cleanly via parseAnchors (ESM)', async () => {
// Plan-critic m4 — fix the SC12 require/import mixup. Use ESM dynamic import,
// not require(). The parser is pure — no I/O, no side effects.
const { parseAnchors } = await import('../../lib/parsers/anchor-parser.mjs');
const fixturePath = join(ROOT, 'tests/fixtures/annotation/annotation-example.md');
assert.ok(existsSync(fixturePath), 'tests/fixtures/annotation/annotation-example.md missing');
const result = parseAnchors(readFileSync(fixturePath, 'utf-8'));
assert.ok(
result.valid,
`parseAnchors failed on annotation-example.md fixture: ${JSON.stringify(result.errors || [])}`,
);
});
// --- v4.2 Step 13 — late doc-consistency pins (post-write of CLAUDE / READMEs / CHANGELOG / quickstart) ---
//
// These were deferred from Step 12 per plan-critic M1 ordering finding —
// Step 13 is where these files are written, so pins go here.
test('plugin README.md mentions /trekrevise in commands section', () => {
// Already covered for CLAUDE.md by the "all seven pipeline commands" test;
// this pin extends coverage to the plugin-level README.
const md = read('README.md');
assert.ok(
md.includes('/trekrevise'),
'plugin README.md must reference /trekrevise (added in v4.2 Step 13)',
);
});
test('marketplace root README.md mentions /trekrevise and v4.2.0', () => {
// ../../README.md is the marketplace landing — must surface v4.2 ship.
// Path traversal is allowed here per feedback_plugin_scope_strict
// (root README updates are explicitly in Step 13's scope).
const md = read('../../README.md');
assert.ok(
md.includes('/trekrevise') || md.includes('trekrevise'),
'marketplace root README.md must reference /trekrevise (v4.2)',
);
assert.ok(
md.includes('v4.2.0'),
'marketplace root README.md must reference voyage v4.2.0',
);
});
test('CHANGELOG.md has v4.2.0 entry', () => {
const cl = read('CHANGELOG.md');
assert.match(
cl,
/## v4\.2\.0\b/,
'CHANGELOG.md must include "## v4.2.0" entry per Keep-a-Changelog 1.1.0',
);
});
test('docs/annotation-quickstart.md exists with ≤7 numbered steps and example-fixture reference', () => {
// SC12 — operator-facing quickstart. The plan caps numbered steps at 7
// to keep cognitive load minimal; reference to the example fixture
// anchors the doc to a concrete artifact operators can replay.
const path = 'docs/annotation-quickstart.md';
assert.ok(existsSync(join(ROOT, path)), `${path} missing`);
const text = read(path);
// Numbered top-level steps: lines starting with "1." through "7." at
// line-start. Forbid 8.+ line-starts.
const numberedSteps = (text.match(/^[1-9]\./gm) || []);
for (const s of numberedSteps) {
const n = parseInt(s, 10);
test('producing commands reference render-artifact.mjs (render-and-link step)', () => {
for (const f of ['trekbrief.md', 'trekplan.md', 'trekreview.md']) {
assert.ok(
n >= 1 && n <= 7,
`${path} contains step ${s} — only 1.-7. permitted (single-screen quickstart)`,
read(`commands/${f}`).includes('render-artifact.mjs'),
`commands/${f} must wire the render-artifact.mjs render-and-link step (v5.0.0)`,
);
}
assert.ok(
text.includes('tests/fixtures/annotation/annotation-example.md'),
`${path} must reference the canonical example fixture for hands-on verification`,
);
});
test('commands/trekplan.md Phase 9 documents plan_critic injection via readAndUpdate (906f155d)', () => {
// Phase 9 (adversarial review) writes the plan-critic verdict back into
// plan.md frontmatter AFTER plan-review-dedup completes. The inject must
// happen post-Phase-8 (write) because Phase 8 precedes Phase 9 in the
// pipeline — the value cannot be in Phase 8's frontmatter template.
// Both the field name (plan_critic) and the inject mechanism
// (readAndUpdate from lib/util/markdown-write.mjs) must be documented
// so future maintainers can trace the contract.
const text = read('commands/trekplan.md');
assert.match(
text,
/plan_critic/,
'commands/trekplan.md must document plan_critic frontmatter field (906f155d)',
);
assert.match(
text,
/readAndUpdate/,
'commands/trekplan.md must reference readAndUpdate from lib/util/markdown-write.mjs (906f155d)',
);
test('producing commands point operators at the /playground plugin for annotation', () => {
for (const f of ['trekbrief.md', 'trekplan.md', 'trekreview.md']) {
assert.ok(
read(`commands/${f}`).includes('/playground'),
`commands/${f} must mention the /playground plugin as the annotation path (v5.0.0)`,
);
}
});
test('CHANGELOG.md has v5.0.0 entry', () => {
const cl = read('CHANGELOG.md');
assert.match(cl, /## v5\.0\.0\b/, 'CHANGELOG.md must include "## v5.0.0" entry');
});
test('CHANGELOG.md retains v4.2.0 entry (history is not rewritten)', () => {
const cl = read('CHANGELOG.md');
assert.match(cl, /## v4\.2\.0\b/, 'CHANGELOG.md must keep the historical "## v4.2.0" entry');
});
test('operational files no longer reference trekrevise (v5.0.0 removal)', () => {
// Templates, the touched command/orchestrator files, settings.json, and the
// handover-contracts doc must be fully scrubbed. CLAUDE.md / README.md are
// intentionally allowed to mention /trekrevise in their "removed in v5.0.0"
// prose — those are historical notes, not live references.
const targets = [
'settings.json',
'docs/HANDOVER-CONTRACTS.md',
'templates/plan-template.md', 'templates/trekbrief-template.md', 'templates/trekreview-template.md',
'commands/trekplan.md', 'commands/trekbrief.md', 'commands/trekreview.md',
'agents/planning-orchestrator.md',
];
for (const t of targets) {
assert.ok(
!read(t).includes('trekrevise'),
`${t} still references trekrevise — it was removed in v5.0.0`,
);
}
});

View file

@ -1,189 +0,0 @@
// tests/lib/markdown-write.test.mjs
// Unit tests for lib/util/markdown-write.mjs (v4.2)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync, readdirSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
serializeFrontmatter,
atomicWriteMarkdown,
readAndUpdate,
} from '../../lib/util/markdown-write.mjs';
import { parseFrontmatter, parseDocument } from '../../lib/util/frontmatter.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const FIXTURES_ROOT = resolve(__dirname, '..', 'fixtures');
test('serializeFrontmatter — empty object returns empty string', () => {
assert.equal(serializeFrontmatter({}), '');
});
test('serializeFrontmatter — round-trip fidelity for scalars + arrays + list-of-dicts', () => {
const obj = {
name: 'voyage-test',
revision: 0,
enabled: true,
notes: null,
tags: ['alpha', 'beta', 'gamma'],
findings: [
{ id: 'a', severity: 'major' },
{ id: 'b', severity: 'minor' },
],
};
const yaml = serializeFrontmatter(obj);
const reparsed = parseFrontmatter(yaml).parsed;
assert.deepEqual(reparsed, obj);
});
test('serializeFrontmatter — block-style YAML for arrays (no flow style)', () => {
const yaml = serializeFrontmatter({ tags: ['a', 'b'] });
assert.ok(!yaml.includes('[a, b]'), 'flow-style array forbidden');
assert.ok(yaml.includes('tags:\n - a\n - b'), 'block-style required');
});
test('serializeFrontmatter — strings with colons are quoted', () => {
const yaml = serializeFrontmatter({ task: 'Re-architect: phase 2' });
assert.match(yaml, /task: ".*Re-architect.*phase 2.*"/);
const reparsed = parseFrontmatter(yaml).parsed;
assert.equal(reparsed.task, 'Re-architect: phase 2');
});
test('serializeFrontmatter — integer revision: 0 emitted unquoted', () => {
const yaml = serializeFrontmatter({ revision: 0 });
assert.equal(yaml, 'revision: 0');
});
test('serializeFrontmatter — round-trips 6-key source_annotations dict (v4.2 schema)', () => {
const obj = {
revision: 1,
source_annotations: [
{
id: 'ANN-0001',
target_artifact: 'plan.md',
target_anchor: 'step-3',
intent: 'change',
comment: 'Reorder before step 4',
timestamp: '2026-05-09T10:00:00Z',
},
{
id: 'ANN-0002',
target_artifact: 'plan.md',
target_anchor: 'step-7',
intent: 'fix',
comment: 'typo in heading',
timestamp: '2026-05-09T10:05:00Z',
},
],
annotation_digest: 'abc123def4567890',
};
const yaml = serializeFrontmatter(obj);
const reparsed = parseFrontmatter(yaml).parsed;
assert.deepEqual(reparsed, obj, '6-key list-of-dict must round-trip');
});
test('atomicWriteMarkdown — writes file with frontmatter + body', () => {
const dir = mkdtempSync(join(tmpdir(), 'mdw-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { plan_version: '1.7', revision: 0 }, '# Title\n\nBody.\n');
const text = readFileSync(path, 'utf-8');
assert.match(text, /^---\nplan_version: "?1\.7"?\nrevision: 0\n---\n# Title\n\nBody\.\n$/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('atomicWriteMarkdown — leaves no .tmp orphan after success', () => {
const dir = mkdtempSync(join(tmpdir(), 'mdw-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { ok: true }, 'body');
assert.ok(existsSync(path));
assert.ok(!existsSync(path + '.tmp'));
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('atomicWriteMarkdown — overwrites existing file atomically', () => {
const dir = mkdtempSync(join(tmpdir(), 'mdw-test-'));
try {
const path = join(dir, 'plan.md');
writeFileSync(path, 'old content');
atomicWriteMarkdown(path, { new: true }, 'new body\n');
const text = readFileSync(path, 'utf-8');
assert.match(text, /new: true/);
assert.match(text, /new body/);
assert.ok(!text.includes('old content'));
assert.ok(!existsSync(path + '.tmp'));
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('atomicWriteMarkdown — preserves body bytes verbatim', () => {
const dir = mkdtempSync(join(tmpdir(), 'mdw-test-'));
try {
const path = join(dir, 'plan.md');
const body = '# Title\n\n- item with `code`\n\n```yaml\nmanifest:\n expected_paths:\n - foo\n```\n\nTrailing text.';
atomicWriteMarkdown(path, { v: 1 }, body);
const text = readFileSync(path, 'utf-8');
const split = text.split('---\n');
const recoveredBody = split.slice(2).join('---\n');
assert.equal(recoveredBody, body);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('readAndUpdate — round-trips frontmatter + body via mutator', () => {
const dir = mkdtempSync(join(tmpdir(), 'mdw-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { plan_version: '1.7', revision: 0 }, '# Original\nBody.\n');
const result = readAndUpdate(path, ({ frontmatter, body }) => ({
frontmatter: { ...frontmatter, revision: 1 },
body,
}));
assert.equal(result.valid, true);
const re = parseDocument(readFileSync(path, 'utf-8'));
assert.equal(re.parsed.frontmatter.revision, 1);
assert.match(re.parsed.body, /# Original/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
// Round-trip ALL existing fixture frontmatters (per risk-assessor C3).
// Walk tests/fixtures/**, parse + serialize + parse, assert deep-equal.
function walkMd(root, out = []) {
if (!existsSync(root)) return out;
for (const entry of readdirSync(root)) {
const p = join(root, entry);
const st = statSync(p);
if (st.isDirectory()) walkMd(p, out);
else if (entry.endsWith('.md')) out.push(p);
}
return out;
}
test('serializeFrontmatter — round-trips ALL existing fixture frontmatters', () => {
const fixtures = walkMd(FIXTURES_ROOT);
let checked = 0;
for (const path of fixtures) {
const text = readFileSync(path, 'utf-8');
const parsed = parseDocument(text);
if (!parsed.valid) continue; // some fixtures are intentionally malformed
const fm = parsed.parsed.frontmatter;
if (!fm || Object.keys(fm).length === 0) continue;
const yaml = serializeFrontmatter(fm);
const reparsed = parseFrontmatter(yaml);
if (!reparsed.valid) continue; // skip malformed-on-purpose fixtures
assert.deepEqual(reparsed.parsed, fm, `round-trip failed for fixture: ${path}`);
checked++;
}
assert.ok(checked > 0, 'expected to round-trip at least one fixture');
});

View file

@ -1,135 +0,0 @@
// tests/lib/revision-guard.test.mjs
// Unit tests for lib/util/revision-guard.mjs (v4.2)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync, copyFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createHash } from 'node:crypto';
import { revisionGuard } from '../../lib/util/revision-guard.mjs';
import { atomicWriteMarkdown } from '../../lib/util/markdown-write.mjs';
function sha256(path) {
return createHash('sha256').update(readFileSync(path)).digest('hex');
}
const ALWAYS_VALID = () => ({ valid: true, errors: [], warnings: [] });
const ALWAYS_INVALID = () => ({ valid: false, errors: [{ code: 'TEST', message: 'forced fail' }], warnings: [] });
test('revisionGuard — validator-PASS commits revision and deletes bak', () => {
const dir = mkdtempSync(join(tmpdir(), 'rg-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { plan_version: '1.7', revision: 0 }, '# Hello\n');
const r = revisionGuard(
path,
({ frontmatter, body }) => ({ frontmatter: { ...frontmatter, revision: 1 }, body }),
ALWAYS_VALID,
);
assert.equal(r.outcome, 'applied');
assert.ok(!existsSync(path + '.local.bak'), 'bak should be deleted on success');
const text = readFileSync(path, 'utf-8');
assert.match(text, /revision: 1/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('revisionGuard — validator-FAIL rolls back to byte-identical pre-revision', () => {
const dir = mkdtempSync(join(tmpdir(), 'rg-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { plan_version: '1.7', revision: 0 }, '# Hello\n');
const before = sha256(path);
const r = revisionGuard(
path,
({ frontmatter, body }) => ({ frontmatter: { ...frontmatter, revision: 1 }, body }),
ALWAYS_INVALID,
);
assert.equal(r.outcome, 'rolled-back');
const after = sha256(path);
assert.equal(after, before, 'rollback must restore byte-identical content');
assert.ok(!existsSync(path + '.local.bak'), 'bak should be cleaned up after rollback');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('revisionGuard — pre-existing .local.bak aborts with operator guidance', () => {
const dir = mkdtempSync(join(tmpdir(), 'rg-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { plan_version: '1.7' }, '# Hello\n');
const bak = path + '.local.bak';
writeFileSync(bak, 'stale backup from prior run');
const r = revisionGuard(path, ({ frontmatter, body }) => ({ frontmatter, body }), ALWAYS_VALID);
assert.equal(r.outcome, 'mutator-failed');
assert.match(r.error, /pre-existing backup/);
// Original file untouched, stale bak preserved for operator inspection
assert.equal(readFileSync(bak, 'utf-8'), 'stale backup from prior run');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('revisionGuard — mutator that throws restores original via bak', () => {
const dir = mkdtempSync(join(tmpdir(), 'rg-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { plan_version: '1.7' }, '# Hello\n');
const before = sha256(path);
const r = revisionGuard(
path,
() => { throw new Error('boom'); },
ALWAYS_VALID,
);
assert.equal(r.outcome, 'mutator-failed');
assert.match(r.error, /boom/);
const after = sha256(path);
assert.equal(after, before, 'mutator-throw must preserve original');
assert.ok(!existsSync(path + '.local.bak'), 'bak cleaned up after mutator-throw');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('revisionGuard — mutator returns invalid object rejected before validator runs', () => {
const dir = mkdtempSync(join(tmpdir(), 'rg-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { plan_version: '1.7' }, '# Hello\n');
const before = sha256(path);
let validatorCalled = false;
const r = revisionGuard(
path,
() => null, // not an object
() => { validatorCalled = true; return { valid: true, errors: [], warnings: [] }; },
);
assert.equal(r.outcome, 'mutator-failed');
assert.equal(validatorCalled, false, 'validator must not run if mutator returned invalid result');
const after = sha256(path);
assert.equal(after, before, 'invalid mutator must preserve original');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('revisionGuard — sha256 fields populated and stable', () => {
const dir = mkdtempSync(join(tmpdir(), 'rg-test-'));
try {
const path = join(dir, 'plan.md');
atomicWriteMarkdown(path, { plan_version: '1.7', revision: 0 }, '# Hello\n');
const before = sha256(path);
const r = revisionGuard(
path,
({ frontmatter, body }) => ({ frontmatter: { ...frontmatter, revision: 1 }, body }),
ALWAYS_VALID,
);
assert.equal(r.sha256_before, before);
assert.equal(typeof r.sha256_after, 'string');
assert.notEqual(r.sha256_after, r.sha256_before, 'sha256 must change after applied revision');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

View file

@ -1,244 +0,0 @@
// tests/lib/source-annotations.test.mjs
// Additive-field invariant for source_annotations: array (Handover 8).
//
// Mirrors tests/lib/source-findings.test.mjs:9-13 — the structural three-part
// contract that v4.2 brief-validator + plan-validator + review-validator must
// uphold for the new optional source_annotations frontmatter field:
//
// 1. validators accept an artifact with source_annotations (additive optional)
// 2. frontmatter parser extracts source_annotations as an array
// 3. each entry has the documented annotation shape
// ({id, target_artifact, target_anchor, intent, ...})
//
// LLM behavior (the planner actually emitting source_annotations) is
// non-testable without live invocation — this test only covers the schema
// half. See Step 12 doc-pin for the operator-level contract.
import { test } from 'node:test';
import { strict as assert } from 'node:assert';
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { parseDocument } from '../../lib/util/frontmatter.mjs';
import { validateBrief } from '../../lib/validators/brief-validator.mjs';
import { validatePlan } from '../../lib/validators/plan-validator.mjs';
import { validateReview } from '../../lib/validators/review-validator.mjs';
const ID_RE = /^ANN-\d{4}$/;
const VALID_INTENT = new Set(['fix', 'change', 'question', 'block']);
function makeFixture(name, body) {
const dir = mkdtempSync(join(tmpdir(), 'voyage-source-ann-'));
const path = join(dir, name);
writeFileSync(path, body);
return { dir, path };
}
const BRIEF_WITH_SOURCE_ANNOTATIONS = `---
type: trekbrief
brief_version: "1.0"
task: Demo brief with source_annotations
slug: source-annotations-demo-brief
research_topics: 0
research_status: complete
revision: 1
annotation_digest: deadbeefcafe1234
source_annotations:
- id: ANN-0001
target_artifact: brief.md
target_anchor: goal
line: 20
intent: change
- id: ANN-0002
target_artifact: brief.md
target_anchor: success-criteria
line: 30
intent: fix
---
# Demo
## Intent
Test fixture.
## Goal
Test fixture.
## Success Criteria
- It validates.
`;
const PLAN_WITH_SOURCE_ANNOTATIONS = `---
plan_version: 1.7
profile: balanced
revision: 2
annotation_digest: cafebabe98765432
source_annotations:
- id: ANN-0001
target_artifact: plan.md
target_anchor: step-1
line: 25
intent: fix
---
# Demo plan
## Implementation Plan
### Step 1: Sentinel
- **Files:** \`tmp/x.txt\` (new)
- **Changes:** Touch.
- **Verify:** \`test -f tmp/x.txt\`
- **On failure:** revert.
- **Checkpoint:** \`git commit -m "chore: x"\`
- **Manifest:**
\`\`\`yaml
manifest:
expected_paths:
- tmp/x.txt
min_file_count: 1
commit_message_pattern: "^chore: x"
bash_syntax_check: []
forbidden_paths: []
must_contain: []
\`\`\`
## Verification
- It validates.
`;
const REVIEW_WITH_SOURCE_ANNOTATIONS = `---
type: trekreview
review_version: "1.0"
task: Demo review with source_annotations
slug: source-annotations-demo-review
project_dir: .claude/projects/2026-05-09-demo
brief_path: .claude/projects/2026-05-09-demo/brief.md
scope_sha_end: 0000000000000000000000000000000000000000
reviewed_files_count: 0
findings: []
revision: 1
annotation_digest: 0123456789abcdef
source_annotations:
- id: ANN-0001
target_artifact: review.md
target_anchor: executive-summary
line: 18
intent: question
---
# Demo
## Executive Summary
Verdict: ALLOW.
## Coverage
| File | Treatment |
|------|-----------|
| _none_ | _no diff_ |
## Remediation Summary
ALLOW.
`;
test('validators accept artifacts with source_annotations field (additive optional, brief)', () => {
const { dir, path } = makeFixture('brief.md', BRIEF_WITH_SOURCE_ANNOTATIONS);
try {
const r = validateBrief(path, { strict: true });
assert.ok(
r.valid,
`brief-validator rejected synthetic brief with source_annotations: ` +
`${(r.errors || []).map(e => `[${e.code}] ${e.message}`).join('; ')}`,
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('validators accept artifacts with source_annotations field (additive optional, plan)', () => {
const { dir, path } = makeFixture('plan.md', PLAN_WITH_SOURCE_ANNOTATIONS);
try {
const r = validatePlan(path, { strict: true });
assert.ok(
r.valid,
`plan-validator rejected synthetic plan with source_annotations: ` +
`${(r.errors || []).map(e => `[${e.code}] ${e.message}`).join('; ')}`,
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('validators accept artifacts with source_annotations field (additive optional, review)', () => {
const { dir, path } = makeFixture('review.md', REVIEW_WITH_SOURCE_ANNOTATIONS);
try {
const r = validateReview(path, { strict: true });
assert.ok(
r.valid,
`review-validator rejected synthetic review with source_annotations: ` +
`${(r.errors || []).map(e => `[${e.code}] ${e.message}`).join('; ')}`,
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('frontmatter parser extracts source_annotations as array of dicts (per artifact)', () => {
const cases = [
{ name: 'brief.md', body: BRIEF_WITH_SOURCE_ANNOTATIONS, expected: 2 },
{ name: 'plan.md', body: PLAN_WITH_SOURCE_ANNOTATIONS, expected: 1 },
{ name: 'review.md', body: REVIEW_WITH_SOURCE_ANNOTATIONS, expected: 1 },
];
for (const c of cases) {
const doc = parseDocument(c.body);
assert.ok(doc.valid, `${c.name}: frontmatter did not parse: ${(doc.errors || []).map(e => e.message).join(', ')}`);
const sa = doc.parsed.frontmatter && doc.parsed.frontmatter.source_annotations;
assert.ok(Array.isArray(sa), `${c.name}: frontmatter.source_annotations is not an array (got ${typeof sa})`);
assert.strictEqual(sa.length, c.expected, `${c.name}: expected ${c.expected} entries, got ${sa.length}`);
}
});
test('source_annotations entries match documented annotation shape', () => {
const doc = parseDocument(BRIEF_WITH_SOURCE_ANNOTATIONS);
const entries = doc.parsed.frontmatter.source_annotations;
for (const e of entries) {
assert.strictEqual(typeof e, 'object', `source_annotations entry is not an object: ${JSON.stringify(e)}`);
assert.ok(typeof e.id === 'string' && ID_RE.test(e.id), `source_annotations[*].id must match /^ANN-\\d{4}$/, got ${JSON.stringify(e.id)}`);
assert.ok(typeof e.target_artifact === 'string' && e.target_artifact.endsWith('.md'),
`source_annotations[*].target_artifact must be a *.md path, got ${JSON.stringify(e.target_artifact)}`);
assert.ok(typeof e.target_anchor === 'string' && e.target_anchor.length > 0,
`source_annotations[*].target_anchor must be a non-empty string, got ${JSON.stringify(e.target_anchor)}`);
if (e.intent !== undefined && e.intent !== null) {
assert.ok(VALID_INTENT.has(e.intent),
`source_annotations[*].intent must be in {fix|change|question|block}, got ${JSON.stringify(e.intent)}`);
}
}
});
test('artifacts WITHOUT source_annotations still validate (forward-compat baseline)', () => {
// Forward-compat: artifacts that predate v4.2 must still validate. Fall back
// to an artifact with neither revision nor source_annotations.
const baseline = BRIEF_WITH_SOURCE_ANNOTATIONS
.replace(/^revision:.*\n/m, '')
.replace(/^annotation_digest:.*\n/m, '')
.replace(/^source_annotations:[\s\S]*?(?=^---$|^[A-Za-z])/m, '');
const { dir, path } = makeFixture('brief.md', baseline);
try {
const r = validateBrief(path, { strict: true });
assert.ok(
r.valid,
`brief-validator must accept artifacts WITHOUT source_annotations (forward-compat baseline): ` +
`${(r.errors || []).map(e => `[${e.code}] ${e.message}`).join('; ')}`,
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});