check-openspec-archive-ready.mjs 4 KB
#!/usr/bin/env node

import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';

const args = process.argv.slice(2);

function readFlag(name) {
  const index = args.indexOf(name);
  if (index === -1) {
    return undefined;
  }
  return args[index + 1];
}

function fail(message) {
  console.error(`Archive gate failed: ${message}`);
  process.exit(1);
}

function info(message) {
  console.log(`Archive gate: ${message}`);
}

const projectArg = readFlag('--project');
const stateArg = readFlag('--state');
const changeArg = readFlag('--change');
const repoRoot = path.resolve(import.meta.dirname, '..');

if (!projectArg && !stateArg) {
  fail('pass --project workspace/<project> or --state path/to/.workflow-state.json');
}

const statePath = path.resolve(repoRoot, stateArg ?? path.join(projectArg, '.workflow-state.json'));
if (!existsSync(statePath)) {
  fail(`state file not found: ${path.relative(repoRoot, statePath)}`);
}

let state;
try {
  state = JSON.parse(readFileSync(statePath, 'utf8'));
} catch (error) {
  fail(`state file is not valid JSON: ${error.message}`);
}

const project = projectArg ?? state.project;
const change = changeArg ?? state.change;

if (!project) {
  fail('state.project is missing; pass --project explicitly');
}

if (!change) {
  fail('state.change is missing; pass --change explicitly');
}

if (changeArg && state.change && changeArg !== state.change) {
  fail(`--change ${changeArg} does not match state.change ${state.change}`);
}

if (state.stage !== 'READY_TO_ARCHIVE') {
  fail(`stage must be READY_TO_ARCHIVE, got ${state.stage ?? 'missing'}`);
}

const gates = state.gates ?? {};
if (gates.review_completed !== true) {
  fail('gates.review_completed must be true');
}

if (gates.validation_completed !== true) {
  fail('gates.validation_completed must be true');
}

if (gates.openspec_locked !== true) {
  fail('gates.openspec_locked must be true');
}

if (state.last_validation?.result !== 'PASS') {
  fail('last_validation.result must be PASS');
}

if (!Array.isArray(state.last_validation?.commands) || state.last_validation.commands.length === 0) {
  fail('last_validation.commands must record the fresh verification commands');
}

const projectCwd = path.resolve(repoRoot, project);
if (!existsSync(projectCwd)) {
  fail(`project directory not found: ${project}`);
}

const changeDir = path.join(projectCwd, 'openspec', 'changes', change);
if (!existsSync(changeDir)) {
  fail(`OpenSpec change directory not found: ${path.relative(repoRoot, changeDir)}`);
}

function commandBin() {
  const rtk = spawnSync('rtk', ['--version'], { cwd: repoRoot, encoding: 'utf8' });
  return rtk.error ? 'openspec' : 'rtk';
}

function runOpenSpec(subArgs) {
  const bin = commandBin();
  const commandArgs = bin === 'rtk' ? ['openspec', ...subArgs] : subArgs;
  const result = spawnSync(bin, commandArgs, {
    cwd: projectCwd,
    encoding: 'utf8',
  });

  if (result.error) {
    fail(`failed to run ${bin}: ${result.error.message}`);
  }

  if (result.status !== 0) {
    const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim();
    fail(`${bin} ${commandArgs.join(' ')} exited ${result.status}${output ? `\n${output}` : ''}`);
  }

  return result.stdout ?? '';
}

function parseJsonFromOutput(output) {
  const start = output.indexOf('{');
  const end = output.lastIndexOf('}');
  if (start === -1 || end === -1 || end < start) {
    fail('openspec status did not return a JSON object');
  }

  try {
    return JSON.parse(output.slice(start, end + 1));
  } catch (error) {
    fail(`failed to parse openspec status JSON: ${error.message}`);
  }
}

info(`checking ${project} / ${change}`);
runOpenSpec(['validate', change, '--strict']);
const status = parseJsonFromOutput(runOpenSpec(['status', '--change', change, '--json']));

if (status.changeName !== change) {
  fail(`openspec status changeName mismatch: ${status.changeName ?? 'missing'}`);
}

if (status.isComplete !== true) {
  fail('openspec status isComplete must be true');
}

info('ready to archive');