- lib/util/markdown-write.mjs: serializeFrontmatter (subset matches frontmatter.mjs parser), atomicWriteMarkdown (single tmp+rename, body bytes verbatim), readAndUpdate (read+mutate+write). - lib/util/revision-guard.mjs: revisionGuard(path, mutator, validator) — backup -> mutate -> validate -> restore-on-fail. Extracted from /trekrevise prompt so rollback can be unit-tested. - 12 tests for markdown-write, including 6-key source_annotations round-trip + walk-all-fixtures regression. - 6 tests for revision-guard: applied/rolled-back/mutator-failed/sha256 stability/pre-existing-bak abort. - Forward-compat policy comments in 3 validators (brief/plan/review) — non-functional pin against future strict-key refactors. Pass: 508/510 (was 490; +18 net from v4.2 Step 1, 2 skipped Docker)
116 lines
4.2 KiB
JavaScript
116 lines
4.2 KiB
JavaScript
// lib/validators/review-validator.mjs
|
|
// Validate trekreview frontmatter + body invariants.
|
|
// 3-layer pattern (Content → File → CLI shim) mirroring brief-validator.
|
|
//
|
|
// Schema is forward-compatible: unknown top-level frontmatter keys are
|
|
// tolerated silently. Adding new optional fields (e.g. revision,
|
|
// source_annotations, annotation_digest, revision_reason from v4.2) does
|
|
// not require a review_version bump (jf. source_findings precedent).
|
|
// Strict-key checks are intentionally avoided so the /trekrevise
|
|
// revision-loop can extend frontmatter without re-versioning.
|
|
|
|
import { readFileSync, existsSync } from 'node:fs';
|
|
import { parseDocument } from '../util/frontmatter.mjs';
|
|
import { issue, ok, fail } from '../util/result.mjs';
|
|
|
|
export const REVIEW_REQUIRED_FRONTMATTER = [
|
|
'type',
|
|
'review_version',
|
|
'task',
|
|
'slug',
|
|
'project_dir',
|
|
'brief_path',
|
|
'scope_sha_end',
|
|
'reviewed_files_count',
|
|
'findings',
|
|
];
|
|
export const REVIEW_BODY_SECTIONS = ['Executive Summary', 'Coverage', 'Remediation Summary'];
|
|
|
|
const HEX_ID_RE = /^[0-9a-f]{40}$/;
|
|
|
|
export function validateReviewContent(text, opts = {}) {
|
|
const strict = opts.strict !== false;
|
|
const doc = parseDocument(text);
|
|
if (!doc.valid) return doc;
|
|
|
|
const fm = doc.parsed.frontmatter || {};
|
|
const body = doc.parsed.body || '';
|
|
const errors = [];
|
|
const warnings = [];
|
|
|
|
for (const k of REVIEW_REQUIRED_FRONTMATTER) {
|
|
if (!(k in fm)) {
|
|
errors.push(issue('REVIEW_MISSING_FIELD', `Required frontmatter field missing: ${k}`));
|
|
}
|
|
}
|
|
|
|
if (fm.type !== undefined && fm.type !== 'trekreview') {
|
|
errors.push(issue('REVIEW_WRONG_TYPE', `frontmatter.type must be "trekreview", got "${fm.type}"`));
|
|
}
|
|
|
|
if (fm.findings !== undefined) {
|
|
if (!Array.isArray(fm.findings)) {
|
|
errors.push(issue(
|
|
'REVIEW_BAD_FINDINGS_TYPE',
|
|
`Field "findings" must be an array of finding-IDs, got ${typeof fm.findings}`,
|
|
'Use block-style YAML: `findings:\\n - <id1>\\n - <id2>`',
|
|
));
|
|
} else {
|
|
for (let i = 0; i < fm.findings.length; i++) {
|
|
const id = fm.findings[i];
|
|
if (typeof id !== 'string' || !HEX_ID_RE.test(id)) {
|
|
errors.push(issue(
|
|
'REVIEW_BAD_FINDING_ID',
|
|
`findings[${i}] is not a 40-char hex ID: ${JSON.stringify(id)}`,
|
|
));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const section of REVIEW_BODY_SECTIONS) {
|
|
const re = new RegExp(`^##\\s+${section}\\b`, 'm');
|
|
if (!re.test(body)) {
|
|
const issueObj = issue('REVIEW_MISSING_SECTION', `Required body section missing: ## ${section}`);
|
|
if (strict) errors.push(issueObj);
|
|
else warnings.push(issueObj);
|
|
}
|
|
}
|
|
|
|
if (typeof fm.review_version === 'string') {
|
|
const m = fm.review_version.match(/^(\d+)\.(\d+)$/);
|
|
if (!m) {
|
|
warnings.push(issue('REVIEW_VERSION_FORMAT', `review_version "${fm.review_version}" not in N.M form`));
|
|
}
|
|
}
|
|
|
|
return { valid: errors.length === 0, errors, warnings, parsed: { frontmatter: fm, body } };
|
|
}
|
|
|
|
export function validateReview(filePath, opts = {}) {
|
|
if (!existsSync(filePath)) return fail(issue('REVIEW_NOT_FOUND', `File not found: ${filePath}`));
|
|
let text;
|
|
try { text = readFileSync(filePath, 'utf-8'); }
|
|
catch (e) { return fail(issue('REVIEW_READ_ERROR', `Cannot read ${filePath}: ${e.message}`)); }
|
|
const r = validateReviewContent(text, opts);
|
|
return { ...r, parsed: { ...r.parsed, filePath } };
|
|
}
|
|
|
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
const args = process.argv.slice(2);
|
|
const strict = !args.includes('--soft');
|
|
const filePath = args.find(a => !a.startsWith('--'));
|
|
if (!filePath) {
|
|
process.stderr.write('Usage: review-validator.mjs [--soft] [--json] <review.md>\n');
|
|
process.exit(2);
|
|
}
|
|
const r = validateReview(filePath, { strict });
|
|
if (args.includes('--json')) {
|
|
process.stdout.write(JSON.stringify({ valid: r.valid, errors: r.errors, warnings: r.warnings }, null, 2) + '\n');
|
|
} else {
|
|
process.stdout.write(`review-validator: ${r.valid ? 'PASS' : 'FAIL'} ${filePath}\n`);
|
|
for (const e of r.errors) process.stderr.write(` ERROR [${e.code}] ${e.message}\n`);
|
|
for (const w of r.warnings) process.stderr.write(` WARN [${w.code}] ${w.message}\n`);
|
|
}
|
|
process.exit(r.valid ? 0 : 1);
|
|
}
|