Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

30.7 KB
Raw Blame
#!/usr/bin/env node
'use strict';
// Deterministic provenance gate for planner-authored markdown.
//
// WHY this is a script: the orchestrator is an AI workflow and `genpage-plan.md` /
// `genpage-edit-plan.md` may already exist from an earlier run. Checking "file exists" after a
// planner invocation accepts stale approved content if the planner failed to write this time. The
// contract is two-part:
//   1. `prepare` quarantines the old authoritative file BEFORE the planner is re-invoked, so the file
//      existing afterwards means this invocation wrote it.
//   2. `verify` proves the written file targets exactly what the approved plan named and,
//      for an edit, contains the same ordered change list.
//   3. For a create plan, `verify` also compares the semantic records both documents carry — what was assumed, each page's
//      relationship and filter decisions, the lookups it uses (lib/genpage-plan-semantics.js) — and, with
//      `--require-assumptions`, requires them of a newly authored plan; with `--lookup-metadata <file>` it checks the observed
//      lookups against the saved metadata read, and with `--require-observed-lookups` no lookup may still be planned.
//
// Why not a hash of the whole approved body: the planner hands back a PREVIEW for approval and then
// writes a DIFFERENT document. The preview is
//   ## Genpage Plan / ### Pages (N total) / ### Data Strategy …   (full prefixed names)
// and the written plan is
//   # Genpage Plan / ## User Requirements / … / ## Pages / … / ## Per-Page Specifications   (suffixes)
// (agents/genpage-planner.md Steps 5 and 6; the edit planner likewise, Steps 3 and 4). No two such
// documents hash equal, so a hash gate halted every approved run. What both documents DO state is
// what the run will touch — the page files of a create, the page id and proposed changes of an edit.
// Compare those structured fields, not contextual text or the whole document.

const fs = require('node:fs');
const path = require('node:path');
const { pagesTables } = require('./lib/page-file-targets.js');
const { sha256 } = require('./lib/hash.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
const {
  readWrittenSemantics, readPreviewSemantics, hasSemanticContract, requiredContractProblems, compareSemantics, lookupEvidenceProblems, semanticRecord,
} = require('./lib/genpage-plan-semantics.js');

// What a plan document targets.
//   create:  the Pages table's File column — `## Pages` in the written plan, `### Pages (N total)`
//            in the preview.
//   edit:    the page id — `- **Page ID:** <guid>` in the written edit plan, and
//            `- **File:** <guid>/page.tsx` in the preview's `### Current State`.
// Returns { kind, targets } or null when the document names neither.
//
// Both GUID patterns are bounded by `[\w-]` on the side that could run on, as the id read from `pac`'s
// upload output once was (`Page ID: <guid>`): an overlong `<guid>deadbeef` was
// truncated to its first 36 characters and certified.
//
// The written edit plan states the id ONCE, structurally, in `## File Being Edited`
// (agents/genpage-edit-planner.md), and only that section is read. Earlier plans copied page context
// into `## Original Page Context`, and a label quoted there — "(**Page ID:** …)",
// "Show the **Page ID:** in the footer" — blocked every later edit of that page. Within the section every
// label must hold the same well-formed id: a malformed one makes the plan name NOTHING and is never
// rescued by an id found elsewhere, since the edit worker reads that very label.
//
// The approval PREVIEW has no such section. It names its page in its own `- **File:** <guid>/page.tsx`
// line under `### Current State`. Earlier previews quoted a prompt snippet there, so a label read
// anywhere came out of that quote and decided the approved target — the same page halting on every
// edit. Context is still untrusted even without that snippet, so a
// preview is read by the File line in its Current State block ALONE: a block whose File line is missing
// or names another file is a broken preview, and reading on found a label or a path quoted from the
// prompt, which approved another page. Only a document with neither section nor block is read by a File
// line anywhere, then by a label that BEGINS a line (under the same rule), and then by any
// `<guid>/page.tsx` path.
const GUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
const LABELLED_ID = new RegExp(`^\`?\\{?(${GUID})\\}?\`?(?![\\w-])`);
function labelledPageIds(text, { lineStart = false } = {}) {
  const label = lineStart ? /^[ \t]*(?:[-*+][ \t]+)?\*\*Page ID:\*\*[ \t]*([^\r\n]*)/gm : /\*\*Page ID:\*\*[ \t]*([^\r\n]*)/g;
  return [...text.matchAll(label)].map((m) => {
    const id = LABELLED_ID.exec(m[1].trim());
    return id ? id[1].toLowerCase() : null;
  });
}
// A path names `page.tsx` only when the name ENDS there: `page\.tsx\b` also took `<guid>/page.tsx.bak`, a
// different file, and since an edit's provenance compares only the GUID, an approval naming it certified a
// written plan for the real page. What goes on naming a file is a letter or digit in any script, one of
// `_ - ~ + # $ @ % & =`, an opening bracket, or a path separator (`page.tsx/old.tsx` is a file in a FOLDER
// of that name) — or a `.` or `:` before one of those (`page.tsx.bak`, the NTFS stream `page.tsx:alt`).
// Anything else ends it: a blank, the end, sentence punctuation, a quote, a dash or a closing mark in any
// script (`”`, `»`, `<br>`). The rule says what CONTINUES a name, not what ends one, because a path the
// fallback cannot end is skipped and the next one in the document wins — which may be a path quoted in the
// page's own prompt.
const NAME_GOES_ON = String.raw`[\p{L}\p{N}_\-~+#$@%&=(\[{/\\]`;
const PAGE_END = `(?!${NAME_GOES_ON}|[.:]+${NAME_GOES_ON})`;
// The File line reads the same way; a note after the path (` (edit)`) is not part of it. The page folder may
// come after a path (`D:\work\edit\<guid>\page.tsx`, `./<guid>/page.tsx`), which a planner writing the
// plan's absolute path beside it can easily carry over: only the GUID is compared, so it changes nothing.
const FILE_LINE = new RegExp(`^[ \\t]*[-*+][ \\t]+\\*\\*File:\\*\\*[ \\t]*\`?(?:[^\\r\\n\`]*[\\\\/])?(${GUID})[\\\\/]page\\.tsx${PAGE_END}`, 'imu');
// The preview's own block, or null when there is none. Its File line is read there only: older previews
// quoted the page's prompt, and a `- **File:** <other>/page.tsx` bullet in that quote, placed ahead of
// the block, decided the target.
function currentStateBlock(src) {
  const state = /^###[ \t]+Current State[ \t]*$/im.exec(src);
  if (!state) return null;
  const rest = src.slice(state.index + state[0].length);
  const next = /^#{1,3}[ \t]+\S/m.exec(rest);
  return next ? rest.slice(0, next.index) : rest;
}
// `kind` is what the flow says the document is ('create' | 'edit' — see planKindOf), or null to read it from
// the document itself. With a kind, only that kind's target is read. `doc` says which of the two documents
// this is — the approval 'preview' or the 'written' plan — and each is then read by its own authoritative
// part alone; null reads either way, as before.
function planTargets(text, { kind = null, doc = null } = {}) {
  const src = String(text || '');
  if (kind !== 'edit') {
    // A Pages table decides "create" first when the kind is not known: an edit plan has none of its own,
    // while a create plan's per-page `- **File:**` lines could hold a `<guid>/page.tsx` path and be misread
    // as an edit target. Each file is compared in the page-file rule's own spelling, `.` segments dropped:
    // `./overview.tsx` in the preview and `overview.tsx` in the written plan name the same page.
    // Read by the page-file gate's own rule, `## Pages` in the written plan and `### Pages (N total)` in the
    // preview alike. More than one table with a File column names nothing — a Pages table quoted in the
    // requirements used to stand in for the real one (lib/page-file-targets.js pagesSections).
    const { tables, unreadable } = pagesTables(src);
    if (unreadable || tables.length > 1) return null;
    const files = tables[0];
    if (files && files.length) return { kind: 'create', targets: files.map((f) => path.posix.normalize(f.trim())).sort() };
    // A create plan is read by its Pages table alone: without one it names nothing, never a page id its text
    // happens to hold.
    if (kind === 'create') return null;
  }
  // The edit target is the page's GUID: the written plan's `- **Page ID:** <guid>`, or else the GUID
  // folder directly before `page.tsx`, which both the preview's `- **File:** <guid>/page.tsx` and the
  // written plan's `- **Absolute path:** <working-dir>/<guid>/page.tsx` carry.
  //
  // The approval preview names its page in its own Current State block, and nowhere else: contextual text
  // may quote anything — a `## File Being Edited` section included, which, read first, named another page.
  if (doc === 'preview') {
    const state = currentStateBlock(src);
    const file = state === null ? null : FILE_LINE.exec(state);
    return file ? { kind: 'edit', targets: [file[1].toLowerCase()] } : null;
  }
  const section = /^##[ \t]+File Being Edited[ \t]*$/im.exec(src);
  // The written plan names its page in its `## File Being Edited` section, and nowhere else.
  if (doc === 'written' && !section) return null;
  let scope = src;
  if (section) {
    const rest = src.slice(section.index + section[0].length);
    const next = /^#{1,2}[ \t]+\S/m.exec(rest);
    const body = next ? rest.slice(0, next.index) : rest;
    const labels = labelledPageIds(body);
    if (labels.length) return labels.every((id) => id && id === labels[0]) ? { kind: 'edit', targets: [labels[0]] } : null;
    if (doc === 'written') scope = body;
  } else {
    const state = currentStateBlock(src);
    const file = FILE_LINE.exec(state === null ? src : state);
    if (file) return { kind: 'edit', targets: [file[1].toLowerCase()] };
    if (state !== null) return null;
    const [first] = labelledPageIds(src, { lineStart: true });
    if (first !== undefined) return first ? { kind: 'edit', targets: [first] } : null;
  }
  const folder = scope.match(new RegExp(`(?<![\\w-])(${GUID})[\\\\/]page\\.tsx${PAGE_END}`, 'u'));
  if (folder) return { kind: 'edit', targets: [folder[1].toLowerCase()] };
  return null;
}

// The approval preview uses `### Proposed Changes`, while the written plan uses
// `## Requested Changes`, each followed by `1. Add a filter` (or `- Add a filter`).
// Ignore list markers, line wrapping and whitespace only; wording and order carry approval.
// Duplicate headings or unlisted prose make the list unreadable, never an empty approval.
function editChanges(text, doc) {
  const level = doc === 'preview' ? 3 : 2;
  const title = doc === 'preview' ? 'Proposed Changes' : 'Requested Changes';
  const src = String(text || '').replace(/\r\n/g, '\n');
  const headings = [...src.matchAll(new RegExp(`^#{${level}}[ \\t]+${title}[ \\t]*$`, 'gim'))];
  if (headings.length !== 1) return null;
  const rest = src.slice(headings[0].index + headings[0][0].length);
  const next = new RegExp(`^#{1,${level}}[ \\t]+\\S`, 'm').exec(rest);
  const body = next ? rest.slice(0, next.index) : rest;
  const changes = [];
  for (const line of body.split('\n')) {
    if (!line.trim()) continue;
    const bullet = /^[ \t]{0,3}(?:\d+[.)]|[-*+])[ \t]+(\S.*)$/.exec(line);
    if (bullet) {
      changes.push(bullet[1]);
    } else if (/^[ \t]+\S/.test(line) && changes.length) {
      changes[changes.length - 1] += ` ${line.trim()}`;
    } else {
      return null;
    }
  }
  return changes.length ? changes.map((change) => change.replace(/\s+/g, ' ').trim().normalize('NFC')) : null;
}

// What is AT `p` — lstat, not existsSync. existsSync follows a link and answers false for a DANGLING
// one, so a planted link at the plan path read as "no plan here" and stayed in place for the planner
// to write through. null when there is nothing there at all.
function entryAt(p) {
  try { return fs.lstatSync(p); } catch (e) { if (e && e.code === 'ENOENT') return null; throw e; }
}

function uniquePath(basePath) {
  if (!entryAt(basePath)) return basePath;
  const parsed = path.parse(basePath);
  for (let i = 1; i < 1000; i += 1) {
    const candidate = path.join(parsed.dir, `${parsed.name}-${i}${parsed.ext}`);
    if (!entryAt(candidate)) return candidate;
  }
  throw new Error(`could not allocate quarantine path for ${basePath}`);
}

// Both paths this touches are refused when they are links (dangling ones included) or not the kind of
// entry they should be. The planner writes THROUGH a link at the plan path, putting the approved plan
// wherever it points; and mkdir({ recursive }) plus rename both follow a link at `.genpage-provenance`,
// which moved the stale plan outside the working directory. The workflow never creates either link, so
// refusing costs a legitimate run nothing. Every failure is an `ok:false` result, never a throw.
function preparePlanProvenance({ planPath }) {
  if (!planPath) return { ok: false, error: '--plan is required' };
  const absPlanPath = path.resolve(planPath);
  const refuse = (error) => ({ ok: false, action: 'prepare', planPath: absPlanPath, error });
  try {
    // The working directory ITSELF must not be a link — the rule the page-file gate and the manifest
    // generator apply to the same directory. With the plan absent this returned ok at once, and the planner
    // then wrote the plan, and the orchestrator its approval sidecar, wherever a link planted there points.
    // A linked ANCESTOR is still followed, a normal setup (macOS temp dirs sit under a symlinked /var).
    const workingDir = path.dirname(absPlanPath);
    const dir = entryAt(workingDir);
    if (dir && dir.isSymbolicLink()) {
      return refuse(`${workingDir} is a symbolic link or junction — pass the directory it points to as the working directory`);
    }
    // The approval sidecar the skill has the orchestrator write next to the plan
    // (`.approved-genpage-plan.md`, `.approved-genpage-edit-plan.md`) is written IN PLACE after this
    // runs, so a link there — or a hard link, whose other name the write would rewrite — puts the approved
    // body wherever it points. Refused here, before anything is written, like a link at the plan path.
    const sidecarPath = path.join(path.dirname(absPlanPath), `.approved-${path.basename(absPlanPath)}`);
    const sidecar = entryAt(sidecarPath);
    if (sidecar && (!sidecar.isFile() || sidecar.nlink > 1)) {
      return refuse(`${sidecarPath} is not a plain file (a link, junction, hard link or folder) — remove it and re-run; the approved plan would be written through it`);
    }
    const plan = entryAt(absPlanPath);
    if (!plan) return { ok: true, action: 'prepare', planPath: absPlanPath, quarantinedPath: null };
    if (plan.isSymbolicLink()) return refuse(`${absPlanPath} is a symbolic link or junction — remove it and re-run; the planner would write the plan through it`);
    if (!plan.isFile()) return refuse(`${absPlanPath} is not a regular file — remove it and re-run`);
    // A HARD link is a plain file to lstat, yet quarantining it only renames this name: the plan stays
    // reachable through its other names, outside the working directory included — the sidecar rule, here.
    if (plan.nlink > 1) return refuse(`${absPlanPath} is a hard link (${plan.nlink} names for one file) — remove it and re-run`);
    const quarantineDir = path.join(path.dirname(absPlanPath), '.genpage-provenance');
    const quarantine = entryAt(quarantineDir);
    // lstat never reports a link as a directory, so this refuses a link, a junction and a file alike.
    if (quarantine && !quarantine.isDirectory()) {
      return refuse(`${quarantineDir} is not a plain directory (a link, junction or file) — remove it and re-run`);
    }
    if (!quarantine) fs.mkdirSync(quarantineDir);
    const stale = fs.readFileSync(absPlanPath, 'utf8');
    const staleHash = sha256(stale);
    const parsed = path.parse(absPlanPath);
    const quarantinedPath = uniquePath(path.join(quarantineDir, `${parsed.name}.stale-${staleHash.slice(0, 12)}${parsed.ext || '.md'}`));
    fs.renameSync(absPlanPath, quarantinedPath);
    return { ok: true, action: 'prepare', planPath: absPlanPath, quarantinedPath, staleHash };
  } catch (e) {
    return refuse(`could not quarantine the earlier plan: ${e.message}`);
  }
}

// Which kind of plan a path holds is the flow's choice, not the document's: /genpage writes a create plan to
// `genpage-plan.md` and an edit plan to `genpage-edit-plan.md` (skills/genpage/SKILL.md and edit-flow.md), and
// neither the planner nor the maker's text names the file. Context cannot decide the kind reliably:
// earlier edit plans embedded prompts, and a Pages table quoted in their preview or written context
// read both as the same create, so an edit of ANOTHER page was certified. Keep that boundary even
// though current plans only reference the prompt file. null for any other name reads the document as before.
function planKindOf(planPath) {
  const name = path.basename(String(planPath || '')).toLowerCase();
  if (name === 'genpage-edit-plan.md') return 'edit';
  if (name === 'genpage-plan.md') return 'create';
  return null;
}

// The semantic records of a create plan (references/plan-schema.md: ## Assumptions, and per page Data semantics and Lookup
// metadata), compared between the approved preview and the written plan by lib/genpage-plan-semantics.js — structured fields by id,
// never a whole-document hash, for the reason above. Same page files are not enough: a changed assumption, decision or lookup scope
// is something the maker did not approve. Returns { problems, hash }.
//   - Either document carrying any part of the contract requires its counterpart in the other: one-sided is never "older plan".
//   - requireAssumptions (a newly authored plan): both documents carry Assumptions and, for every page, Data semantics and Lookup
//     metadata — so leaving the contract out of both cannot evade the comparison.
//   - lookupMetadataPath: the successful get-lookup-metadata.js answer saved after provisioning. Every `observed` lookup of the
//     written plan must match it, and only with it may a lookup approved as `planned` be written `observed` with its measured
//     paths (the post-provision reconciliation). It is read here, never fetched: this gate does no network I/O.
//   - requireObservedLookups (before generation): no lookup is still `planned`, which needs that evidence.
function createSemanticsProblems({ approvedPlan, written, targets, requireAssumptions, requireObservedLookups, lookupMetadataPath }) {
  const approvedRead = readPreviewSemantics(approvedPlan);
  const writtenRead = readWrittenSemantics(written);
  const problems = [
    ...approvedRead.problems.map((p) => `the approved plan: ${p.message}`),
    ...writtenRead.problems.map((p) => `the written plan: ${p.message}`),
  ];
  for (const file of approvedRead.pages.keys()) {
    if (!targets.includes(file)) problems.push(`the approved plan records ${file}, which is not one of its pages`);
  }
  for (const [file, page] of writtenRead.pages) {
    if ((page.semantics !== null || page.lookups !== null) && !targets.includes(file)) problems.push(`the written plan records ${file}, which is not one of its pages`);
  }
  if (requireAssumptions) {
    problems.push(...requiredContractProblems(approvedRead, targets, 'the approved plan').map((p) => p.message));
    problems.push(...requiredContractProblems(writtenRead, targets, 'the written plan').map((p) => p.message));
  }
  // "Read" and "valid" are kept apart from the value: a file holding JSON `null` (or `false`, `0`, `[]`) was read and is
  // validated like any other answer — it is not "no evidence supplied". Only evidence that validated authorizes a
  // `planned` → `observed` promotion, and --require-observed-lookups needs exactly that, not merely a path.
  let evidence;
  let evidenceRead = false;
  let evidenceValid = false;
  if (lookupMetadataPath) {
    try {
      const file = path.resolve(lookupMetadataPath);
      if (!fs.lstatSync(file).isFile()) throw new Error(`${file} is not a regular file (a link, junction or folder)`);
      evidence = JSON.parse(fs.readFileSync(file, 'utf8'));
      evidenceRead = true;
    } catch (e) {
      problems.push(`could not read the lookup metadata evidence: ${e.message}`);
    }
    if (evidenceRead) {
      const evidenceProblems = lookupEvidenceProblems(writtenRead, evidence).map((p) => p.message);
      problems.push(...evidenceProblems);
      evidenceValid = evidenceProblems.length === 0;
    }
  }
  if (requireObservedLookups) {
    if (!lookupMetadataPath) problems.push('--require-observed-lookups needs --lookup-metadata <path>: the successful lookup metadata read');
    else if (!evidenceValid) problems.push('--require-observed-lookups needs lookup metadata evidence that is a successful get-lookup-metadata.js answer every observed lookup matches');
    for (const [file, page] of writtenRead.pages) {
      for (const row of page.lookups && !page.lookups.sentinel ? page.lookups.rows.values() : []) {
        if (row.state !== 'observed') problems.push(`${file} ${row.table}.${row.column} is still planned: read its metadata after provisioning and reconcile the plan before generation`);
      }
    }
  }
  problems.push(...compareSemantics(approvedRead, writtenRead, { promotions: evidenceValid }));
  const contract = hasSemanticContract(approvedRead) || hasSemanticContract(writtenRead);
  return { problems, hash: contract ? sha256(JSON.stringify(semanticRecord(writtenRead))) : null };
}

const SEMANTIC_OPTIONS = ['requireAssumptions', 'requireObservedLookups', 'lookupMetadataPath'];

function verifyPlanProvenance({ planPath, approvedPlan, requireAssumptions = false, requireObservedLookups = false, lookupMetadataPath = null }) {
  if (!planPath) return { ok: false, error: '--plan is required' };
  if (approvedPlan == null) return { ok: false, error: '--approved is required' };
  const absPlanPath = path.resolve(planPath);
  const kind = planKindOf(absPlanPath);
  const approved = planTargets(approvedPlan, { kind, doc: 'preview' });
  if (!approved) {
    return {
      ok: false,
      action: 'verify',
      planPath: absPlanPath,
      error: 'the approved plan body names no pages — save the plan body the planner returned for approval (its Pages table, or the Current State file of an edit) as the --approved file',
    };
  }
  // The semantic records are a create plan's; an edit plan keeps its own change-list comparison and is never verified against them.
  const options = { requireAssumptions, requireObservedLookups, lookupMetadataPath };
  if (approved.kind === 'edit' && SEMANTIC_OPTIONS.some((name) => options[name])) {
    return {
      ok: false,
      action: 'verify',
      planPath: absPlanPath,
      approvedTargets: approved.targets,
      error: 'the semantic options (--require-assumptions, --require-observed-lookups, --lookup-metadata) apply to a create plan; an edit plan is verified by its change list',
    };
  }
  // The file this certifies must be the one written in place: a link would have it vouch for a
  // document that lives somewhere else.
  let entry;
  try { entry = entryAt(absPlanPath); } catch (e) {
    return { ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, error: `could not inspect ${absPlanPath}: ${e.message}` };
  }
  if (!entry) {
    return { ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, error: `planner did not write ${absPlanPath}` };
  }
  // lstat reports a link as a link, never as a file, so this refuses links and folders alike — and a hard
  // link, whose other names the planner's write would have rewritten too.
  if (!entry.isFile() || entry.nlink > 1) {
    return { ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, error: `${absPlanPath} is not a plain file (a link, junction, hard link or folder) — the plan must be written in place` };
  }
  let written;
  try { written = fs.readFileSync(absPlanPath, 'utf8'); } catch (e) {
    return { ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, error: `could not read ${absPlanPath}: ${e.message}` };
  }
  // Recorded, not compared: an audit line for workflow-log.md naming the exact file that was verified.
  const writtenHash = sha256(written);
  const actual = planTargets(written, { kind, doc: 'written' });
  const same = actual && actual.kind === approved.kind
    && actual.targets.length === approved.targets.length
    && actual.targets.every((t, i) => t === approved.targets[i]);
  if (!same) {
    return {
      ok: false,
      action: 'verify',
      planPath: absPlanPath,
      approvedTargets: approved.targets,
      writtenTargets: actual ? actual.targets : [],
      writtenHash,
      error: `the written plan targets ${actual ? actual.targets.join(', ') || 'nothing' : 'no pages'}, but the approved plan named ${approved.targets.join(', ')}`,
    };
  }
  let changesHash;
  if (approved.kind === 'edit') {
    const approvedChanges = editChanges(approvedPlan, 'preview');
    const writtenChanges = editChanges(written, 'written');
    const sameChanges = approvedChanges && writtenChanges
      && approvedChanges.length === writtenChanges.length
      && approvedChanges.every((change, i) => change === writtenChanges[i]);
    if (!sameChanges) {
      return {
        ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets,
        writtenTargets: actual.targets, writtenHash, approvedChanges, writtenChanges,
        error: 'the written Requested Changes do not match the approved Proposed Changes; both must contain one non-empty list with the same wording and order',
      };
    }
    changesHash = sha256(JSON.stringify(approvedChanges));
  }
  let semanticsHash;
  if (approved.kind === 'create') {
    const semantic = createSemanticsProblems({ approvedPlan, written, targets: approved.targets, requireAssumptions, requireObservedLookups, lookupMetadataPath });
    if (semantic.problems.length) {
      const more = semantic.problems.length > 1 ? ` (and ${semantic.problems.length - 1} more)` : '';
      return {
        ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, writtenTargets: actual.targets, writtenHash,
        semanticProblems: semantic.problems,
        error: `the written plan's semantic records are not the approved ones: ${semantic.problems[0]}${more}`,
      };
    }
    semanticsHash = semantic.hash || undefined;
  }
  return {
    ok: true, action: 'verify', planPath: absPlanPath, kind: approved.kind, targets: approved.targets, writtenHash,
    ...(changesHash ? { changesHash } : {}), ...(semanticsHash ? { semanticsHash } : {}),
  };
}

const USAGE = 'Usage: node genpage-plan-provenance.js prepare --plan <path> OR verify --plan <path> --approved @<approved-plan-file> '
  + '[--require-assumptions] [--require-observed-lookups --lookup-metadata <lookup-metadata.json>]';
const VALUE_FLAGS = ['plan', 'approved', 'lookup-metadata'];
const BOOLEAN_FLAGS = ['require-assumptions', 'require-observed-lookups'];

// `prepare --plan <path>` / `verify --plan <path> --approved @<file> [--require-assumptions] [--require-observed-lookups]
// [--lookup-metadata <path>]`. Every flag is declared: an unknown one — `--require-assumption`, a typo that would otherwise drop
// the gate it names without a word — a stray word, or a boolean flag given a value is a usage error (`usage` set), never ignored.
// A value flag takes the next word whatever it is, as before, so a missing --plan value still reads as "--plan is required".
function parseArgv(argv) {
  const out = { command: argv[0] || '' };
  for (let i = 1; i < argv.length; i += 1) {
    const key = argv[i];
    if (!key.startsWith('--')) { out.usage = out.usage || `unexpected argument '${key}'`; continue; }
    const name = key.slice(2);
    if (BOOLEAN_FLAGS.includes(name)) { out[name] = true; continue; }
    if (!VALUE_FLAGS.includes(name)) { out.usage = out.usage || `unknown flag ${key}`; continue; }
    if (name === 'lookup-metadata' && (argv[i + 1] === undefined || argv[i + 1].startsWith('--'))) { out.usage = out.usage || '--lookup-metadata needs a path'; continue; }
    out[name] = argv[i + 1];
    i += 1;
  }
  if (out.command === 'prepare' && [...BOOLEAN_FLAGS, 'lookup-metadata', 'approved'].some((name) => out[name] !== undefined)) {
    out.usage = out.usage || 'prepare takes --plan only';
  }
  return out;
}

// The approved body comes from a file the orchestrator wrote. It must be that file, written in place — a
// link would have the gate compare against whatever it points at.
function readApproved(value) {
  if (!(value && value.startsWith('@'))) return value;
  const file = path.resolve(value.slice(1));
  if (!fs.lstatSync(file).isFile()) throw new Error(`${file} is not a regular file (a link, junction or folder) — the approved plan must be written in place`);
  return fs.readFileSync(file, 'utf8');
}

function main() {
  const args = parseArgv(process.argv.slice(2));
  let result;
  let usage = false;
  if (args.usage) {
    result = { ok: false, error: `${args.usage} — ${USAGE}` };
    usage = true;
  } else if (args.command === 'prepare') {
    result = preparePlanProvenance({ planPath: args.plan });
  } else if (args.command === 'verify') {
    let approvedPlan;
    try {
      approvedPlan = readApproved(args.approved);
      result = verifyPlanProvenance({
        planPath: args.plan,
        approvedPlan,
        requireAssumptions: args['require-assumptions'] === true,
        requireObservedLookups: args['require-observed-lookups'] === true,
        lookupMetadataPath: args['lookup-metadata'] || null,
      });
    } catch (e) {
      result = { ok: false, action: 'verify', error: `could not read the approved plan: ${e.message}` };
    }
  } else {
    result = { ok: false, error: USAGE };
  }

  // A mismatch carries both change lists whole, and the process exits right after the write: it is made blocking
  // first, or a pipe on Linux and macOS takes only what fits at once (lib/output-redaction.js).
  makeWritesBlocking(process.stdout, process.stderr);
  process.stdout.write(JSON.stringify(result) + '\n');
  process.exit(result.ok ? 0 : (!usage && (args.command === 'prepare' || args.command === 'verify') ? 3 : 1));
}

if (require.main === module) main();

module.exports = { preparePlanProvenance, verifyPlanProvenance, planTargets, sha256 };