ktg-plugin-marketplace/plugins/ultraplan-local/lib/validators/session-state-validator.mjs
Kjell Tore Guttormsen 14ecda886c feat(voyage)!: bulk content rewrite ultra -> voyage/trek prose [skip-docs]
Sed-pipeline (16 patterns, longest-match-first) sweeper residuelle ultra*-treff
i prose, command-narrativ, agent-prompts, hook-kommentarer, doc-prosa.

Pipeline-utvidelser fra V4-prompten:
- BSD-syntax [[:<:]]ultra[[:>:]] istedenfor \bultra\b (BSD sed mangler \b)
- 6 compound-patterns for ultraplan/ultraexecute/ultraresearch/ultrabrief/
  ultrareview/ultracontinue uten -local-suffiks
- ultra*-stats glob -> trek*-stats glob
- Linje-eksklusjon redusert til ultra-cc-architect (Q8); session-state-
  eksklusjonen var over-protektiv
- File-eksklusjon utvidet til settings.json, package.json, plugin.json,
  hele .claude/-treet (gitignored + V5-territorium)

Q8-undantak holdt: architecture-discovery.mjs + project-discovery.mjs urort.
Filnavn-konvensjon holdt: .session-state.local.json + *.local.* preservert.

Manuell narrative-fix: tests/lib/agent-frontmatter.test.mjs linje 10
mangled "/ultra*-local" til "/voyage*-local" (ingen slik kommando finnes);
korrigert til "/trek*".

Residualer utenfor scope (V5 handterer): package.json + .claude-plugin/
plugin.json (Step 12-14 versjons-bump). .claude/* er gitignored
spec-historikk med tilsiktet BEFORE/AFTER-narrativ.

Part of voyage-rebrand session 3 (Wave 4 / Step 10).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-05 15:08:20 +02:00

117 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';
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 (import.meta.url === `file://${process.argv[1]}`) {
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);
}