- 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)
123 lines
4.9 KiB
JavaScript
123 lines
4.9 KiB
JavaScript
// lib/validators/brief-validator.mjs
|
|
// Validate trekbrief frontmatter + body invariants.
|
|
//
|
|
// 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 brief_version bump (jf. source_findings precedent on
|
|
// trekreview). 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 BRIEF_REQUIRED_FRONTMATTER = ['type', 'brief_version', 'task', 'slug', 'research_topics', 'research_status'];
|
|
export const REVIEW_AS_BRIEF_REQUIRED_FRONTMATTER = ['type', 'task', 'slug', 'project_dir', 'findings'];
|
|
export const BRIEF_TYPE_VALUES = Object.freeze(['trekbrief', 'trekreview']);
|
|
export const BRIEF_RESEARCH_STATUS_VALUES = ['pending', 'in_progress', 'complete', 'skipped'];
|
|
export const BRIEF_BODY_SECTIONS = ['Intent', 'Goal', 'Success Criteria'];
|
|
|
|
function getRequiredFields(type) {
|
|
return type === 'trekreview' ? REVIEW_AS_BRIEF_REQUIRED_FRONTMATTER : BRIEF_REQUIRED_FRONTMATTER;
|
|
}
|
|
|
|
export function validateBriefContent(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 getRequiredFields(fm.type)) {
|
|
if (!(k in fm)) {
|
|
errors.push(issue('BRIEF_MISSING_FIELD', `Required frontmatter field missing: ${k}`));
|
|
}
|
|
}
|
|
|
|
if (fm.type !== undefined && !BRIEF_TYPE_VALUES.includes(fm.type)) {
|
|
errors.push(issue(
|
|
'BRIEF_WRONG_TYPE',
|
|
`frontmatter.type must be one of [${BRIEF_TYPE_VALUES.join(', ')}], got "${fm.type}"`,
|
|
));
|
|
}
|
|
|
|
if (fm.type === 'trekreview' && fm.findings !== undefined && !Array.isArray(fm.findings)) {
|
|
errors.push(issue(
|
|
'BRIEF_BAD_FINDINGS_TYPE',
|
|
'Field "findings" must be an array of finding-IDs for type:trekreview',
|
|
'Use block-style YAML: `findings:\\n - <id1>\\n - <id2>`',
|
|
));
|
|
}
|
|
|
|
if (fm.research_status !== undefined && !BRIEF_RESEARCH_STATUS_VALUES.includes(fm.research_status)) {
|
|
errors.push(issue(
|
|
'BRIEF_BAD_STATUS',
|
|
`research_status "${fm.research_status}" not in [${BRIEF_RESEARCH_STATUS_VALUES.join(', ')}]`,
|
|
));
|
|
}
|
|
|
|
if (typeof fm.research_topics === 'number' && fm.research_topics > 0 && fm.research_status === 'skipped') {
|
|
if (fm.brief_quality !== 'partial') {
|
|
errors.push(issue(
|
|
'BRIEF_STATE_INCOHERENT',
|
|
`research_topics=${fm.research_topics} but research_status=skipped`,
|
|
'Either set research_status to a real progress value, or mark brief_quality: partial.',
|
|
));
|
|
} else {
|
|
warnings.push(issue(
|
|
'BRIEF_PARTIAL_SKIPPED',
|
|
`Brief has unresolved research topics (${fm.research_topics}) but is partial`,
|
|
));
|
|
}
|
|
}
|
|
|
|
for (const section of BRIEF_BODY_SECTIONS) {
|
|
const re = new RegExp(`^##\\s+${section}\\b`, 'm');
|
|
if (!re.test(body)) {
|
|
const issueObj = issue('BRIEF_MISSING_SECTION', `Required body section missing: ## ${section}`);
|
|
if (strict) errors.push(issueObj);
|
|
else warnings.push(issueObj);
|
|
}
|
|
}
|
|
|
|
if (typeof fm.brief_version === 'string') {
|
|
const m = fm.brief_version.match(/^(\d+)\.(\d+)$/);
|
|
if (!m) {
|
|
warnings.push(issue('BRIEF_VERSION_FORMAT', `brief_version "${fm.brief_version}" not in N.M form`));
|
|
}
|
|
}
|
|
|
|
return { valid: errors.length === 0, errors, warnings, parsed: { frontmatter: fm, body } };
|
|
}
|
|
|
|
export function validateBrief(filePath, opts = {}) {
|
|
if (!existsSync(filePath)) return fail(issue('BRIEF_NOT_FOUND', `File not found: ${filePath}`));
|
|
let text;
|
|
try { text = readFileSync(filePath, 'utf-8'); }
|
|
catch (e) { return fail(issue('BRIEF_READ_ERROR', `Cannot read ${filePath}: ${e.message}`)); }
|
|
const r = validateBriefContent(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: brief-validator.mjs [--soft] <brief.md>\n');
|
|
process.exit(2);
|
|
}
|
|
const r = validateBrief(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(`brief-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);
|
|
}
|