voyage/lib/validators/session-state-validator.mjs
Kjell Tore Guttormsen 29b4ac91b3
fix: round 7 of the release review of 6.3.0, for 6.3.1
Round 7 (516dffa..45aa9e1, WARN: 12 MAJOR, 0 BLOCKER) and the fence defect
found while writing its review.md. Each fix began with a test that failed on
0f400d3 (v6.3.0); suite 2208 (2206/0/2), 14 tests more.

- Tests-only (operator 2026-10-11): the plan's Files: alone decides, and the
  text says so (red-proof, trekexecute Sub-step B, step-implementer,
  HANDOVER-CONTRACTS). red-proof no longer reads the step's diff, so a change
  already in the tree when the step began no longer counts against it, and a
  plan placed outside .claude/ reads the same. The round-6 test that had the
  diff overrule the plan is rewritten to the new rule.
- The Files: reader keeps a plain file beside a backticked path
  (", Dockerfile", "the CLI entry src/cli.mjs", "and Makefile"). Measured on
  the 520 Files: fields in 182 plans: no field reads differently.
- Red proof reports a command its timeout killed as killed after the timeout,
  not "could not start"; the release check tells a timeout from output past
  its buffer and from another signal. One reading of a stop
  (criteria-runner stoppedBy) for red proof, the criteria runner and the
  release check.
- A trailing `# comment` is dropped in a backticked check too, and in a
  command passed as written, so the words screened are the words run.
- The release check reads a relative --review in --repo.
- The 15-minute timeout is defined once (criteria-runner.mjs).
- The findings check reads each cited file once per validation.
- One isMain helper (lib/util/is-main.mjs) for every CLI: the 31 copies of
  the realpath guard and the 20 modules still on the file:// guard, which
  exited 0 having done nothing under a symlink or a path with a space.
- The Bash guard writes its no-one-to-ask refusal once, on a direct condition.
- The findings check ends a ```json block only at a fence on its own line, so
  three backticks inside a JSON string no longer end it (also in 6.2.0).
- Brief-conformance notes: a test for test-lock green on exit 127 (it
  passed at once; it fails when 127 is read as could-not-run); the prose now
  names the git revision `@~1` as the one leading-@ exception.

Not changed: the example plan's steps 1-2 keep their tests-only warning
(operator decision 2026-10-09; the r5 test records it). Brief note 4 (a
Regression: whose runner is not installed goes to the fix rounds) is a
routing question for the operator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 09:11:57 +02:00

118 lines
4.4 KiB
JavaScript

// lib/validators/session-state-validator.mjs
// Validate .session-state.local.json — the contract consumed by /trekcontinue.
// Schema v1 documented in docs/HANDOVER-CONTRACTS.md (Handover 7).
import { readFileSync, existsSync } from 'node:fs';
import { issue, fail } from '../util/result.mjs';
import { isMain } from '../util/is-main.mjs';
export const SESSION_STATE_REQUIRED_TOP = [
'schema_version',
'project',
'next_session_brief_path',
'next_session_label',
'status',
'updated_at',
];
// All five statuses parse as valid; `completed` emits a warning that the
// session is not resumable. Unknown statuses fail.
export const SESSION_STATE_VALID_STATUSES = ['in_progress', 'partial', 'failed', 'stopped', 'completed'];
// Statuses that /trekcontinue can resume from. `completed` is intentionally
// excluded — running trekcontinue on a completed project should signal "no
// further sessions to resume", not load stale context.
export const SESSION_STATE_RESUMABLE_STATUSES = ['in_progress', 'partial', 'failed', 'stopped'];
export function validateSessionStateContent(jsonText, opts = {}) {
let parsed;
try { parsed = JSON.parse(jsonText); }
catch (e) {
return fail(issue('SESSION_STATE_PARSE_ERROR', `Cannot parse JSON: ${e.message}`));
}
return validateSessionStateObject(parsed, opts);
}
export function validateSessionStateObject(parsed, opts = {}) {
const errors = [];
const warnings = [];
if (typeof parsed !== 'object' || parsed === null) {
return fail(issue('SESSION_STATE_NOT_OBJECT', 'Session-state payload is not an object'));
}
for (const k of SESSION_STATE_REQUIRED_TOP) {
if (!(k in parsed)) {
errors.push(issue('SESSION_STATE_MISSING_FIELD', `Required field missing: ${k}`));
}
}
if (parsed.schema_version !== undefined && parsed.schema_version !== 1) {
errors.push(issue(
'SESSION_STATE_SCHEMA_MISMATCH',
`schema_version ${JSON.stringify(parsed.schema_version)} not supported (expected 1)`,
));
}
if (parsed.status !== undefined) {
if (!SESSION_STATE_VALID_STATUSES.includes(parsed.status)) {
errors.push(issue(
'SESSION_STATE_INVALID_STATUS',
`status "${parsed.status}" not in [${SESSION_STATE_VALID_STATUSES.join(', ')}]`,
));
} else if (parsed.status === 'completed') {
warnings.push(issue(
'SESSION_STATE_NOT_RESUMABLE',
'status "completed" — project is done; no further sessions to resume',
));
}
}
if (parsed.next_session_brief_path !== undefined) {
if (typeof parsed.next_session_brief_path !== 'string' || parsed.next_session_brief_path.length === 0) {
errors.push(issue('SESSION_STATE_INVALID_PATH', 'next_session_brief_path must be a non-empty string'));
}
}
if (parsed.updated_at !== undefined) {
if (typeof parsed.updated_at !== 'string' || Number.isNaN(Date.parse(parsed.updated_at))) {
errors.push(issue('SESSION_STATE_INVALID_TIMESTAMP', `updated_at "${parsed.updated_at}" is not a valid ISO-8601 timestamp`));
}
}
// Forward-compat: unknown top-level keys are tolerated silently.
// This protects future graceful-handoff v2.2 dual-writes that emit
// additional fields (branch, git_status, committed_by, ...).
return { valid: errors.length === 0, errors, warnings, parsed };
}
export function validateSessionState(filePath, opts = {}) {
if (!existsSync(filePath)) {
return fail(issue('SESSION_STATE_NOT_FOUND', `File not found: ${filePath}`));
}
let text;
try { text = readFileSync(filePath, 'utf-8'); }
catch (e) {
return fail(issue('SESSION_STATE_READ_ERROR', `Cannot read ${filePath}: ${e.message}`));
}
return validateSessionStateContent(text, opts);
}
if (isMain(import.meta.url)) {
const args = process.argv.slice(2);
const filePath = args.find(a => !a.startsWith('--'));
if (!filePath) {
process.stderr.write('Usage: session-state-validator.mjs [--json] <.session-state.local.json>\n');
process.exit(2);
}
const r = validateSessionState(filePath);
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(`session-state-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);
}