cadre-ai 3.0.2 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2979,7 +2979,7 @@ var require_compile = __commonJS({
2979
2979
  const schOrFunc = root.refs[ref];
2980
2980
  if (schOrFunc)
2981
2981
  return schOrFunc;
2982
- let _sch = resolve9.call(this, root, ref);
2982
+ let _sch = resolve11.call(this, root, ref);
2983
2983
  if (_sch === void 0) {
2984
2984
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
2985
2985
  const { schemaId } = this.opts;
@@ -3006,7 +3006,7 @@ var require_compile = __commonJS({
3006
3006
  function sameSchemaEnv(s1, s2) {
3007
3007
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
3008
3008
  }
3009
- function resolve9(root, ref) {
3009
+ function resolve11(root, ref) {
3010
3010
  let sch;
3011
3011
  while (typeof (sch = this.refs[ref]) == "string")
3012
3012
  ref = sch;
@@ -3637,7 +3637,7 @@ var require_fast_uri = __commonJS({
3637
3637
  }
3638
3638
  return uri;
3639
3639
  }
3640
- function resolve9(baseURI, relativeURI, options) {
3640
+ function resolve11(baseURI, relativeURI, options) {
3641
3641
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3642
3642
  const resolved = resolveComponent(parse4(baseURI, schemelessOptions), parse4(relativeURI, schemelessOptions), schemelessOptions, true);
3643
3643
  schemelessOptions.skipEscape = true;
@@ -3895,7 +3895,7 @@ var require_fast_uri = __commonJS({
3895
3895
  var fastUri = {
3896
3896
  SCHEMES,
3897
3897
  normalize,
3898
- resolve: resolve9,
3898
+ resolve: resolve11,
3899
3899
  resolveComponent,
3900
3900
  equal,
3901
3901
  serialize,
@@ -28843,7 +28843,7 @@ var Protocol = class {
28843
28843
  return;
28844
28844
  }
28845
28845
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
28846
- await new Promise((resolve9) => setTimeout(resolve9, pollInterval));
28846
+ await new Promise((resolve11) => setTimeout(resolve11, pollInterval));
28847
28847
  options?.signal?.throwIfAborted();
28848
28848
  }
28849
28849
  } catch (error51) {
@@ -28860,7 +28860,7 @@ var Protocol = class {
28860
28860
  */
28861
28861
  request(request, resultSchema, options) {
28862
28862
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
28863
- return new Promise((resolve9, reject) => {
28863
+ return new Promise((resolve11, reject) => {
28864
28864
  const earlyReject = (error51) => {
28865
28865
  reject(error51);
28866
28866
  };
@@ -28938,7 +28938,7 @@ var Protocol = class {
28938
28938
  if (!parseResult.success) {
28939
28939
  reject(parseResult.error);
28940
28940
  } else {
28941
- resolve9(parseResult.data);
28941
+ resolve11(parseResult.data);
28942
28942
  }
28943
28943
  } catch (error51) {
28944
28944
  reject(error51);
@@ -29199,12 +29199,12 @@ var Protocol = class {
29199
29199
  }
29200
29200
  } catch {
29201
29201
  }
29202
- return new Promise((resolve9, reject) => {
29202
+ return new Promise((resolve11, reject) => {
29203
29203
  if (signal.aborted) {
29204
29204
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
29205
29205
  return;
29206
29206
  }
29207
- const timeoutId = setTimeout(resolve9, interval);
29207
+ const timeoutId = setTimeout(resolve11, interval);
29208
29208
  signal.addEventListener("abort", () => {
29209
29209
  clearTimeout(timeoutId);
29210
29210
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -30295,7 +30295,7 @@ var McpServer = class {
30295
30295
  let task = createTaskResult.task;
30296
30296
  const pollInterval = task.pollInterval ?? 5e3;
30297
30297
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
30298
- await new Promise((resolve9) => setTimeout(resolve9, pollInterval));
30298
+ await new Promise((resolve11) => setTimeout(resolve11, pollInterval));
30299
30299
  const updatedTask = await extra.taskStore.getTask(taskId);
30300
30300
  if (!updatedTask) {
30301
30301
  throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
@@ -30959,42 +30959,42 @@ var StdioServerTransport = class {
30959
30959
  this.onclose?.();
30960
30960
  }
30961
30961
  send(message) {
30962
- return new Promise((resolve9) => {
30962
+ return new Promise((resolve11) => {
30963
30963
  const json3 = serializeMessage(message);
30964
30964
  if (this._stdout.write(json3)) {
30965
- resolve9();
30965
+ resolve11();
30966
30966
  } else {
30967
- this._stdout.once("drain", resolve9);
30967
+ this._stdout.once("drain", resolve11);
30968
30968
  }
30969
30969
  });
30970
30970
  }
30971
30971
  };
30972
30972
 
30973
30973
  // src/mcp/server.ts
30974
- import { readFileSync as readFileSync7 } from "node:fs";
30975
- import { join as join7, resolve as resolve8 } from "node:path";
30974
+ import { readFileSync as readFileSync8 } from "node:fs";
30975
+ import { join as join8, resolve as resolve10 } from "node:path";
30976
30976
  import { pathToFileURL } from "node:url";
30977
30977
 
30978
30978
  // src/domain/init.ts
30979
30979
  import { createHash as createHash5 } from "node:crypto";
30980
30980
  import {
30981
- existsSync as existsSync6,
30981
+ existsSync as existsSync7,
30982
30982
  lstatSync as lstatSync3,
30983
30983
  mkdirSync as mkdirSync2,
30984
- readFileSync as readFileSync5,
30984
+ readFileSync as readFileSync6,
30985
30985
  renameSync as renameSync2,
30986
30986
  writeFileSync as writeFileSync3
30987
30987
  } from "node:fs";
30988
30988
  import { dirname as dirname3 } from "node:path";
30989
- import { isAbsolute, join as join4, relative as relative2, resolve as resolve5 } from "node:path";
30989
+ import { isAbsolute, join as join5, relative as relative2, resolve as resolve7 } from "node:path";
30990
30990
 
30991
30991
  // src/domain/state.ts
30992
30992
  import { createHash as createHash3 } from "node:crypto";
30993
- import { existsSync as existsSync4, lstatSync as lstatSync2, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
30994
- import { join as join2, resolve as resolve3 } from "node:path";
30993
+ import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
30994
+ import { join as join3, resolve as resolve5 } from "node:path";
30995
30995
 
30996
30996
  // src/domain/version.ts
30997
- var CADRE_RUNTIME_VERSION = "3.0.2";
30997
+ var CADRE_RUNTIME_VERSION = "3.2.0";
30998
30998
  var TEMPLATE_SET_VERSION = "v1";
30999
30999
 
31000
31000
  // src/domain/plan.ts
@@ -31218,8 +31218,33 @@ function readAndValidatePlan(path, status, errors) {
31218
31218
 
31219
31219
  // src/domain/execution.ts
31220
31220
  import { createHash as createHash2, randomUUID } from "node:crypto";
31221
- import { existsSync as existsSync3, lstatSync, mkdirSync, readFileSync as readFileSync2, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
31222
- import { basename, dirname, join, resolve as resolve2 } from "node:path";
31221
+ import { existsSync as existsSync4, lstatSync, mkdirSync, readFileSync as readFileSync3, readdirSync as readdirSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
31222
+ import { basename, dirname, join as join2, resolve as resolve4 } from "node:path";
31223
+
31224
+ // src/domain/errors.ts
31225
+ var CadreError = class extends Error {
31226
+ code;
31227
+ details;
31228
+ constructor(code, message, details) {
31229
+ super(message);
31230
+ this.name = "CadreError";
31231
+ this.code = code;
31232
+ this.details = details;
31233
+ }
31234
+ };
31235
+ function serializeCadreError(error51) {
31236
+ if (error51 instanceof CadreError) {
31237
+ return {
31238
+ code: error51.code,
31239
+ message: error51.message,
31240
+ ...error51.details ? { details: error51.details } : {}
31241
+ };
31242
+ }
31243
+ return {
31244
+ code: "CADRE_ERROR",
31245
+ message: error51 instanceof Error ? error51.message : String(error51)
31246
+ };
31247
+ }
31223
31248
 
31224
31249
  // src/domain/paths.ts
31225
31250
  import { existsSync as existsSync2, statSync } from "node:fs";
@@ -31236,6 +31261,109 @@ function safeProjectRoot(input) {
31236
31261
  return root;
31237
31262
  }
31238
31263
 
31264
+ // src/domain/tracks-index.ts
31265
+ import { existsSync as existsSync3, readFileSync as readFileSync2, readdirSync } from "node:fs";
31266
+ import { join, resolve as resolve2 } from "node:path";
31267
+ function buildTracks(tracks) {
31268
+ const lines = [
31269
+ "# Tracks",
31270
+ "",
31271
+ "Generated from track-local `state.json` files by the Cadre MCP server.",
31272
+ "",
31273
+ "| Track | Type | Status | Revision |",
31274
+ "| --- | --- | --- | ---: |"
31275
+ ];
31276
+ for (const track of tracks) {
31277
+ lines.push(`| \`${track.id}\` ${track.title ?? ""} | ${track.type} | ${track.status} | ${track.revision ?? 1} |`);
31278
+ }
31279
+ return `${lines.join("\n")}
31280
+ `;
31281
+ }
31282
+ function renderTracksWithState(projectRoot, statePath, proposedState) {
31283
+ const root = join(safeProjectRoot(projectRoot), ".cadre");
31284
+ const resolvedStatePath = resolve2(statePath);
31285
+ const tracks = [];
31286
+ const ids = /* @__PURE__ */ new Set();
31287
+ let overrideFound = false;
31288
+ for (const directory of ["tracks", "archive"]) {
31289
+ const directoryRoot = join(root, directory);
31290
+ if (!existsSync3(directoryRoot)) continue;
31291
+ for (const entry of readdirSync(directoryRoot, { withFileTypes: true }).filter((candidate) => candidate.isDirectory()).sort((left, right) => left.name.localeCompare(right.name))) {
31292
+ const path = join(directoryRoot, entry.name, "state.json");
31293
+ let state;
31294
+ if (resolve2(path) === resolvedStatePath) {
31295
+ overrideFound = true;
31296
+ state = proposedState;
31297
+ } else {
31298
+ state = JSON.parse(readFileSync2(path, "utf8"));
31299
+ }
31300
+ const id = String(state.trackId ?? "");
31301
+ if (!id || id !== entry.name) throw new Error(`invalid track identity at ${path}`);
31302
+ if (ids.has(id)) throw new Error(`duplicate track state for ${id}`);
31303
+ ids.add(id);
31304
+ tracks.push({
31305
+ id,
31306
+ type: String(state.type ?? ""),
31307
+ status: String(state.status ?? ""),
31308
+ ...typeof state.title === "string" ? { title: state.title } : {},
31309
+ ...typeof state.revision === "number" ? { revision: state.revision } : {}
31310
+ });
31311
+ }
31312
+ }
31313
+ if (!overrideFound) throw new Error("execution track state is outside the active track index");
31314
+ tracks.sort((left, right) => left.id.localeCompare(right.id));
31315
+ const tracksPath = join(root, "tracks.md");
31316
+ return {
31317
+ tracksPath,
31318
+ tracksBody: readFileSync2(tracksPath, "utf8"),
31319
+ tracksContent: buildTracks(tracks)
31320
+ };
31321
+ }
31322
+
31323
+ // src/domain/git.ts
31324
+ import { spawnSync } from "node:child_process";
31325
+ import { realpathSync } from "node:fs";
31326
+ import { resolve as resolve3 } from "node:path";
31327
+ function gitRoot(projectRoot) {
31328
+ const root = realpathSync(safeProjectRoot(projectRoot));
31329
+ const result2 = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: root, encoding: "utf8" });
31330
+ if (result2.status !== 0) throw new Error((result2.stderr || result2.stdout || "project is not a Git worktree").trim());
31331
+ const detected = realpathSync(resolve3(result2.stdout.trim()));
31332
+ if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
31333
+ return root;
31334
+ }
31335
+ function resolveGitCommit(projectRoot, revision = "HEAD") {
31336
+ const root = gitRoot(projectRoot);
31337
+ const result2 = spawnSync("git", ["rev-parse", "--verify", `${revision}^{commit}`], { cwd: root, encoding: "utf8" });
31338
+ if (result2.status !== 0) throw new Error(`Git commit is not reachable: ${revision}`);
31339
+ return result2.stdout.trim();
31340
+ }
31341
+ function isGitAncestor(projectRoot, ancestor, descendant = "HEAD") {
31342
+ const root = gitRoot(projectRoot);
31343
+ return spawnSync("git", ["merge-base", "--is-ancestor", ancestor, descendant], {
31344
+ cwd: root,
31345
+ encoding: "utf8"
31346
+ }).status === 0;
31347
+ }
31348
+ function reachableGitCommits(projectRoot, revisions) {
31349
+ let root;
31350
+ try {
31351
+ root = gitRoot(projectRoot);
31352
+ } catch {
31353
+ return null;
31354
+ }
31355
+ const unique = [...new Set(revisions)].filter(Boolean);
31356
+ const listed = spawnSync("git", ["rev-list", "--all"], { cwd: root, encoding: "utf8" });
31357
+ if (listed.status !== 0) throw new Error((listed.stderr || listed.stdout || "cannot enumerate Git history").trim());
31358
+ const history = new Set(listed.stdout.split(/\r?\n/).filter(Boolean));
31359
+ const reachable = /* @__PURE__ */ new Map();
31360
+ for (const revision of unique) {
31361
+ const result2 = spawnSync("git", ["rev-parse", "--verify", `${revision}^{commit}`], { cwd: root, encoding: "utf8" });
31362
+ reachable.set(revision, result2.status === 0 && history.has(result2.stdout.trim()));
31363
+ }
31364
+ return reachable;
31365
+ }
31366
+
31239
31367
  // src/domain/execution.ts
31240
31368
  var EXECUTION_NODE_STATUSES = [
31241
31369
  "pending",
@@ -31249,6 +31377,22 @@ var EXECUTION_NODE_STATUSES = [
31249
31377
  "completed",
31250
31378
  "blocked"
31251
31379
  ];
31380
+ var EXECUTION_APPROVAL_MODES = ["governed", "phase", "autonomous"];
31381
+ function deriveExecutionStartInput(input) {
31382
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
31383
+ const requestedMode = input.requestedMode ?? "parallel";
31384
+ return {
31385
+ projectRoot: input.projectRoot,
31386
+ trackId: input.trackId,
31387
+ executionId: startedAt.replace(/[:.]/g, "-"),
31388
+ requestedMode,
31389
+ effectiveMode: requestedMode,
31390
+ ...input.approvalMode ? { approvalMode: input.approvalMode } : {},
31391
+ maxWorkers: input.maxWorkers ?? 3,
31392
+ baseCommit: resolveGitCommit(input.projectRoot),
31393
+ approvedAt: startedAt
31394
+ };
31395
+ }
31252
31396
  var SHA = /^[0-9a-f]{7,40}$/;
31253
31397
  var TRACK_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
31254
31398
  var EXECUTION_ID = /^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
@@ -31256,13 +31400,13 @@ function hash2(value) {
31256
31400
  return createHash2("sha256").update(JSON.stringify(value)).digest("hex");
31257
31401
  }
31258
31402
  function writeJournalAtomically(path, journal) {
31259
- const temporaryPath = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
31403
+ const temporaryPath = join2(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
31260
31404
  try {
31261
31405
  writeFileSync(temporaryPath, `${JSON.stringify(journal, null, 2)}
31262
31406
  `, { flag: "wx" });
31263
31407
  renameSync(temporaryPath, path);
31264
31408
  } finally {
31265
- if (existsSync3(temporaryPath)) unlinkSync(temporaryPath);
31409
+ if (existsSync4(temporaryPath)) unlinkSync(temporaryPath);
31266
31410
  }
31267
31411
  }
31268
31412
  function assertIdentifiers(trackId, executionId) {
@@ -31270,7 +31414,7 @@ function assertIdentifiers(trackId, executionId) {
31270
31414
  if (!EXECUTION_ID.test(executionId)) throw new Error("executionId must contain only letters, digits, and hyphens");
31271
31415
  }
31272
31416
  function activeTrackRoot(projectRoot, trackId) {
31273
- return join(safeProjectRoot(projectRoot), ".cadre", "tracks", trackId);
31417
+ return join2(safeProjectRoot(projectRoot), ".cadre", "tracks", trackId);
31274
31418
  }
31275
31419
  function journalRelative(executionId) {
31276
31420
  return `executions/execution-${executionId}.json`;
@@ -31330,21 +31474,27 @@ function previewExecutionStart(input) {
31330
31474
  throw new Error("an explicitly sequential execution cannot become parallel");
31331
31475
  }
31332
31476
  const trackRoot = activeTrackRoot(input.projectRoot, input.trackId);
31333
- const statePath = join(trackRoot, "state.json");
31334
- const planPath = join(trackRoot, "plan.md");
31335
- const stateBody = readFileSync2(statePath, "utf8");
31477
+ const statePath = join2(trackRoot, "state.json");
31478
+ const planPath = join2(trackRoot, "plan.md");
31479
+ const stateBody = readFileSync3(statePath, "utf8");
31336
31480
  const state = JSON.parse(stateBody);
31481
+ const approvalMode = input.approvalMode ?? state.lastExecution?.approvalMode ?? "phase";
31482
+ if (!EXECUTION_APPROVAL_MODES.includes(approvalMode)) throw new Error("approvalMode must be governed, phase, or autonomous");
31337
31483
  if (state.trackId !== input.trackId) throw new Error("track state does not match trackId");
31338
31484
  if (!["planned", "in_progress"].includes(state.status)) throw new Error(`track ${input.trackId} is not implementable from ${state.status}`);
31339
31485
  if (state.operation != null) throw new Error(`track ${input.trackId} already has an active operation`);
31340
31486
  if (!SHA.test(state.commits?.plan ?? "")) throw new Error("track has no approved plan commit");
31487
+ const planReachability = reachableGitCommits(input.projectRoot, [state.commits.plan]);
31488
+ if (planReachability?.get(state.commits.plan) === false) {
31489
+ throw new Error(`approved plan commit is not reachable: ${state.commits.plan}`);
31490
+ }
31341
31491
  const planErrors = [];
31342
31492
  const graph = parsePlan(planPath, planErrors);
31343
31493
  validatePlanGraph(planPath, graph, state.status, planErrors);
31344
31494
  if (planErrors.length) throw new Error(planErrors.join("\n"));
31345
31495
  const planRevision = graph.planRevision;
31346
31496
  const relativeJournal = journalRelative(input.executionId);
31347
- const journalPath = join(trackRoot, relativeJournal);
31497
+ const journalPath = join2(trackRoot, relativeJournal);
31348
31498
  const journal = {
31349
31499
  schemaVersion: 1,
31350
31500
  executionId: input.executionId,
@@ -31353,6 +31503,7 @@ function previewExecutionStart(input) {
31353
31503
  checkpoint: "approved",
31354
31504
  requestedMode: input.requestedMode,
31355
31505
  effectiveMode: input.effectiveMode,
31506
+ approvalMode,
31356
31507
  maxWorkers: input.maxWorkers,
31357
31508
  planRevision,
31358
31509
  planCommit: state.commits.plan,
@@ -31363,11 +31514,11 @@ function previewExecutionStart(input) {
31363
31514
  headCommit: null,
31364
31515
  nodes: buildNodes(graph)
31365
31516
  };
31366
- if (existsSync3(journalPath)) {
31517
+ if (existsSync4(journalPath)) {
31367
31518
  if (lstatSync(journalPath).isSymbolicLink()) throw new Error("refusing an execution journal symbolic link");
31368
31519
  let existing;
31369
31520
  try {
31370
- existing = JSON.parse(readFileSync2(journalPath, "utf8"));
31521
+ existing = JSON.parse(readFileSync3(journalPath, "utf8"));
31371
31522
  } catch (error51) {
31372
31523
  throw new Error(`existing execution journal is invalid: ${error51 instanceof Error ? error51.message : String(error51)}`);
31373
31524
  }
@@ -31386,6 +31537,7 @@ function previewExecutionStart(input) {
31386
31537
  executionId: input.executionId,
31387
31538
  journal: relativeJournal,
31388
31539
  mode: input.effectiveMode,
31540
+ approvalMode,
31389
31541
  graphDigest: graph.digest,
31390
31542
  planRevision
31391
31543
  };
@@ -31400,7 +31552,7 @@ function previewExecutionStart(input) {
31400
31552
  journal,
31401
31553
  statePath,
31402
31554
  state: proposedState,
31403
- digest: hash2({ stateBody, planBody: readFileSync2(planPath, "utf8"), journal, state: proposedState })
31555
+ digest: hash2({ stateBody, planBody: readFileSync3(planPath, "utf8"), journal, state: proposedState })
31404
31556
  };
31405
31557
  }
31406
31558
  function applyExecutionStart(input, proposalDigest) {
@@ -31408,7 +31560,7 @@ function applyExecutionStart(input, proposalDigest) {
31408
31560
  if (proposal.digest !== proposalDigest) throw new Error("execution proposal is stale; preview it again");
31409
31561
  if (lstatSync(proposal.statePath).isSymbolicLink()) throw new Error("refusing to start execution through a state symbolic link");
31410
31562
  mkdirSync(dirname(proposal.journalPath), { recursive: true });
31411
- if (!existsSync3(proposal.journalPath)) {
31563
+ if (!existsSync4(proposal.journalPath)) {
31412
31564
  writeFileSync(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
31413
31565
  `);
31414
31566
  }
@@ -31419,11 +31571,11 @@ function applyExecutionStart(input, proposalDigest) {
31419
31571
  function executionPaths(projectRoot, trackId, executionId) {
31420
31572
  assertIdentifiers(trackId, executionId);
31421
31573
  const trackRoot = activeTrackRoot(projectRoot, trackId);
31422
- return { statePath: join(trackRoot, "state.json"), journalPath: join(trackRoot, journalRelative(executionId)) };
31574
+ return { statePath: join2(trackRoot, "state.json"), journalPath: join2(trackRoot, journalRelative(executionId)) };
31423
31575
  }
31424
31576
  function readExecution(projectRoot, trackId, executionId) {
31425
31577
  const { journalPath } = executionPaths(projectRoot, trackId, executionId);
31426
- return JSON.parse(readFileSync2(journalPath, "utf8"));
31578
+ return JSON.parse(readFileSync3(journalPath, "utf8"));
31427
31579
  }
31428
31580
  var ALLOWED_TRANSITIONS = {
31429
31581
  pending: ["running", "blocked"],
@@ -31444,7 +31596,16 @@ function applyNodeTransition(journal, input) {
31444
31596
  const workerAssignmentChanged = Object.hasOwn(input, "workerId") && (input.workerId ?? null) !== node.workerId;
31445
31597
  const phaseWorkerHandoff = node.kind === "phase" && node.status === "running" && input.status === "running" && workerAssignmentChanged && (node.workerId == null || input.workerId == null);
31446
31598
  if (!ALLOWED_TRANSITIONS[node.status]?.includes(input.status) && !phaseWorkerHandoff) {
31447
- throw new Error(`illegal execution transition ${node.status} -> ${input.status}`);
31599
+ throw new CadreError(
31600
+ "ILLEGAL_EXECUTION_TRANSITION",
31601
+ `illegal execution transition ${node.status} -> ${input.status}`,
31602
+ {
31603
+ nodeId: node.id,
31604
+ currentStatus: node.status,
31605
+ requestedStatus: input.status,
31606
+ allowedNextStatuses: ALLOWED_TRANSITIONS[node.status]
31607
+ }
31608
+ );
31448
31609
  }
31449
31610
  if (phaseWorkerHandoff && node.workerId != null && input.workerId == null && !input.verification) {
31450
31611
  throw new Error(`${node.id} requires clean-checkpoint verification before releasing its phase worker`);
@@ -31500,7 +31661,7 @@ function applyNodeTransition(journal, input) {
31500
31661
  throw new Error(`${node.id} requires a commit before it can be marked committed`);
31501
31662
  }
31502
31663
  if (input.status === "committed" && !updated.approval) {
31503
- throw new Error(`${node.id} requires recorded human approval before commit`);
31664
+ throw new Error(`${node.id} requires recorded approval authorization before commit`);
31504
31665
  }
31505
31666
  if (input.status === "committed" && node.kind === "task") {
31506
31667
  const duplicate = Object.values(journal.nodes).find(
@@ -31519,7 +31680,7 @@ function applyNodeTransition(journal, input) {
31519
31680
  if (incompleteTasks.length) throw new Error(`${node.id} has incomplete tasks: ${incompleteTasks.join(", ")}`);
31520
31681
  }
31521
31682
  if (node.kind === "manual-verification" && !updated.approval) {
31522
- throw new Error(`${node.id} requires recorded human approval`);
31683
+ throw new Error(`${node.id} requires recorded verification authorization`);
31523
31684
  }
31524
31685
  }
31525
31686
  if (updated.workerId != null) {
@@ -31543,7 +31704,7 @@ function previewExecutionNodesUpdate(input) {
31543
31704
  throw new Error("updates must contain 1 through 128 ordered node transitions");
31544
31705
  }
31545
31706
  const { journalPath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
31546
- const currentBody = readFileSync2(journalPath, "utf8");
31707
+ const currentBody = readFileSync3(journalPath, "utf8");
31547
31708
  const journal = JSON.parse(currentBody);
31548
31709
  for (const update of input.updates) applyNodeTransition(journal, update);
31549
31710
  return { path: journalPath, journal, digest: hash2({ currentBody, journal }) };
@@ -31558,45 +31719,215 @@ function applyExecutionNodesUpdate(input, proposalDigest) {
31558
31719
  derivedStatus: deriveExecutionStatus(proposal.journal)
31559
31720
  };
31560
31721
  }
31561
- function previewExecutionNodeUpdate(input) {
31562
- const { projectRoot, trackId, executionId, ...update } = input;
31563
- return previewExecutionNodesUpdate({ projectRoot, trackId, executionId, updates: [update] });
31564
- }
31565
- function applyExecutionNodeUpdate(input, proposalDigest) {
31566
- const { projectRoot, trackId, executionId, ...update } = input;
31567
- const proposal = previewExecutionNodesUpdate({ projectRoot, trackId, executionId, updates: [update] });
31568
- if (proposal.digest !== proposalDigest) throw new Error("execution node proposal is stale; preview it again");
31569
- writeJournalAtomically(proposal.path, proposal.journal);
31570
- return {
31571
- path: proposal.path,
31572
- journal: proposal.journal,
31573
- derivedStatus: deriveExecutionStatus(proposal.journal)
31574
- };
31575
- }
31576
31722
  function deriveExecutionStatus(journal) {
31577
31723
  const completed = new Set(Object.values(journal.nodes).filter((node) => node.status === "completed").map((node) => node.id));
31578
31724
  const ready = Object.values(journal.nodes).filter(
31579
31725
  (node) => node.status === "pending" && node.dependencies.every((dependency) => completed.has(dependency))
31580
31726
  );
31727
+ const eventGuidance = Object.fromEntries(Object.values(journal.nodes).map((node) => {
31728
+ const allowed = [];
31729
+ if (node.status === "pending") allowed.push({ event: "start", requiredFields: [] });
31730
+ if (node.status === "running") {
31731
+ allowed.push(node.kind === "manual-verification" ? { event: "record_verification", requiredFields: ["commit", "verification", "authorization"] } : { event: "record_commit", requiredFields: ["commit", "verification", "authorization"] });
31732
+ }
31733
+ if (node.status === "awaiting_approval") {
31734
+ allowed.push({ event: "record_commit", requiredFields: ["commit", "verification", "authorization"] });
31735
+ }
31736
+ if (node.status === "committed") {
31737
+ allowed.push(
31738
+ { event: "record_integration", requiredFields: ["commit", "verification"] },
31739
+ { event: "complete", requiredFields: [] }
31740
+ );
31741
+ }
31742
+ if (["integrating", "conflicted", "integrated"].includes(node.status)) {
31743
+ allowed.push({ event: "record_integration", requiredFields: ["commit", "verification"] });
31744
+ }
31745
+ if (node.status === "awaiting_manual_verification") {
31746
+ allowed.push({ event: "record_verification", requiredFields: ["commit", "verification", "authorization"] });
31747
+ }
31748
+ if (node.status === "blocked") allowed.push({ event: "resume", requiredFields: [] });
31749
+ if (node.status !== "completed") allowed.push({ event: "block", requiredFields: ["blocker"] });
31750
+ return [node.id, { currentStatus: node.status, allowed }];
31751
+ }));
31581
31752
  return {
31582
31753
  readyPhases: ready.filter((node) => node.kind === "phase").map((node) => node.id),
31583
31754
  readyTasks: ready.filter(
31584
31755
  (node) => node.kind !== "phase" && journal.nodes[node.phaseId]?.status === "running"
31585
31756
  ).map((node) => node.id),
31586
31757
  active: Object.values(journal.nodes).filter((node) => !["pending", "completed", "blocked"].includes(node.status)).map((node) => node.id),
31587
- blocked: Object.values(journal.nodes).filter((node) => node.status === "blocked").map((node) => node.id)
31758
+ blocked: Object.values(journal.nodes).filter((node) => node.status === "blocked").map((node) => node.id),
31759
+ eventGuidance
31588
31760
  };
31589
31761
  }
31590
31762
  function executionStatus(projectRoot, trackId, executionId) {
31591
31763
  const journal = readExecution(projectRoot, trackId, executionId);
31592
31764
  return { journal, ...deriveExecutionStatus(journal) };
31593
31765
  }
31766
+ var EXECUTION_CHECKPOINT_EVENTS = [
31767
+ "start",
31768
+ "record_commit",
31769
+ "record_integration",
31770
+ "record_verification",
31771
+ "complete",
31772
+ "block",
31773
+ "resume"
31774
+ ];
31775
+ function checkpointUpdates(journal, input) {
31776
+ const node = journal.nodes[input.nodeId];
31777
+ if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
31778
+ const evidence = input.verification?.trim();
31779
+ const authorization = input.authorization?.trim();
31780
+ const commit = input.commit;
31781
+ const updates = [];
31782
+ const start = () => {
31783
+ if (node.status === "pending" || node.status === "blocked") {
31784
+ updates.push({
31785
+ nodeId: node.id,
31786
+ status: "running",
31787
+ ...Object.hasOwn(input, "workerId") ? { workerId: input.workerId ?? null } : {},
31788
+ ...Object.hasOwn(input, "worktreePath") ? { worktreePath: input.worktreePath ?? null } : {},
31789
+ ...Object.hasOwn(input, "branch") ? { branch: input.branch ?? null } : {}
31790
+ });
31791
+ } else if (node.status === "running" && Object.hasOwn(input, "workerId")) {
31792
+ updates.push({
31793
+ nodeId: node.id,
31794
+ status: "running",
31795
+ workerId: input.workerId ?? null,
31796
+ ...evidence ? { verification: evidence } : {}
31797
+ });
31798
+ } else if (node.status !== "running") {
31799
+ throw new Error(`${node.id} cannot start from ${node.status}`);
31800
+ }
31801
+ };
31802
+ switch (input.event) {
31803
+ case "start":
31804
+ start();
31805
+ break;
31806
+ case "record_commit":
31807
+ if (!commit || !evidence || !authorization) {
31808
+ throw new Error("record_commit requires commit, verification, and authorization");
31809
+ }
31810
+ if (node.status === "running") {
31811
+ updates.push({ nodeId: node.id, status: "awaiting_approval", verification: evidence });
31812
+ } else if (node.status !== "awaiting_approval") {
31813
+ throw new Error(`${node.id} cannot record a commit from ${node.status}`);
31814
+ }
31815
+ updates.push({ nodeId: node.id, status: "committed", workerCommit: commit, approval: authorization });
31816
+ break;
31817
+ case "record_integration":
31818
+ if (!commit || !evidence) throw new Error("record_integration requires commit and verification");
31819
+ if (node.status === "committed") updates.push({ nodeId: node.id, status: "integrating" });
31820
+ else if (node.status !== "integrating" && node.status !== "conflicted" && node.status !== "integrated") {
31821
+ throw new Error(`${node.id} cannot record integration from ${node.status}`);
31822
+ }
31823
+ if (node.status !== "integrated") {
31824
+ updates.push({ nodeId: node.id, status: "integrated", mergeCommit: commit, verification: evidence });
31825
+ }
31826
+ updates.push({ nodeId: node.id, status: "completed" });
31827
+ break;
31828
+ case "record_verification":
31829
+ if (node.kind !== "manual-verification" || !commit || !evidence || !authorization) {
31830
+ throw new Error("record_verification requires a manual-verification node, commit, verification, and authorization");
31831
+ }
31832
+ if (node.status === "pending") updates.push({ nodeId: node.id, status: "running" });
31833
+ else if (node.status !== "running" && node.status !== "awaiting_manual_verification") {
31834
+ throw new Error(`${node.id} cannot record verification from ${node.status}`);
31835
+ }
31836
+ if (node.status !== "awaiting_manual_verification") {
31837
+ updates.push({ nodeId: node.id, status: "awaiting_manual_verification", verification: evidence, workerCommit: commit });
31838
+ }
31839
+ updates.push({ nodeId: node.id, status: "completed", workerCommit: commit, approval: authorization });
31840
+ break;
31841
+ case "complete":
31842
+ if (node.status === "committed") updates.push({
31843
+ nodeId: node.id,
31844
+ status: "completed",
31845
+ ...evidence ? { verification: evidence } : {}
31846
+ });
31847
+ else if (node.status === "integrated") updates.push({
31848
+ nodeId: node.id,
31849
+ status: "completed",
31850
+ ...evidence ? { verification: evidence } : {}
31851
+ });
31852
+ else if (node.kind === "phase" && node.status === "running") {
31853
+ if (!commit || !evidence || !authorization) {
31854
+ throw new Error("completing a running phase requires commit, verification, and authorization");
31855
+ }
31856
+ updates.push(
31857
+ { nodeId: node.id, status: "awaiting_approval", verification: evidence },
31858
+ { nodeId: node.id, status: "committed", workerCommit: commit, approval: authorization },
31859
+ { nodeId: node.id, status: "integrating" },
31860
+ { nodeId: node.id, status: "integrated", mergeCommit: commit },
31861
+ { nodeId: node.id, status: "completed" }
31862
+ );
31863
+ } else throw new Error(`${node.id} cannot complete from ${node.status}`);
31864
+ break;
31865
+ case "block":
31866
+ if (!input.blocker?.trim()) throw new Error("block requires a blocker description");
31867
+ updates.push({ nodeId: node.id, status: "blocked", blocker: input.blocker.trim() });
31868
+ break;
31869
+ case "resume":
31870
+ if (node.status !== "blocked") throw new Error(`${node.id} is not blocked`);
31871
+ updates.push({ nodeId: node.id, status: "pending" });
31872
+ break;
31873
+ }
31874
+ if (!updates.length) throw new Error(`${input.event} produced no change for ${node.id}`);
31875
+ return updates;
31876
+ }
31877
+ function previewExecutionCheckpoint(input) {
31878
+ const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
31879
+ return previewExecutionNodesUpdate({
31880
+ projectRoot: input.projectRoot,
31881
+ trackId: input.trackId,
31882
+ executionId: input.executionId,
31883
+ updates: checkpointUpdates(journal, input)
31884
+ });
31885
+ }
31886
+ function applyExecutionCheckpoint(input, proposalDigest) {
31887
+ const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
31888
+ return applyExecutionNodesUpdate({
31889
+ projectRoot: input.projectRoot,
31890
+ trackId: input.trackId,
31891
+ executionId: input.executionId,
31892
+ updates: checkpointUpdates(journal, input)
31893
+ }, proposalDigest);
31894
+ }
31895
+ function deriveExecutionFinishInput(input) {
31896
+ return {
31897
+ ...input,
31898
+ headCommit: resolveGitCommit(input.projectRoot),
31899
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
31900
+ };
31901
+ }
31902
+ function renderCompletedPlan(planBody, graph, journal) {
31903
+ const lines = planBody.split(/\r?\n/);
31904
+ for (const phase of graph.phases) {
31905
+ const phaseNode = journal.nodes[phase.id];
31906
+ const phaseCommit = phaseNode?.mergeCommit ?? phaseNode?.workerCommit;
31907
+ if (!phaseCommit) throw new Error(`${phase.id} lacks completion commit evidence`);
31908
+ for (const task of phase.tasks) {
31909
+ const taskNode = journal.nodes[task.id];
31910
+ const taskCommit = taskNode?.workerCommit ?? taskNode?.mergeCommit;
31911
+ if (!taskNode || taskNode.status !== "completed" || !taskCommit) {
31912
+ throw new Error(`${task.id} lacks completed commit evidence`);
31913
+ }
31914
+ lines[task.line - 1] = `- [x] ${task.id} ${task.title} <!-- commit: ${taskCommit} -->`;
31915
+ }
31916
+ const nextPhaseLine = graph.phases[phase.number]?.line ?? lines.length + 1;
31917
+ const commitLine = lines.findIndex(
31918
+ (line, index) => index >= phase.line - 1 && index < nextPhaseLine - 1 && line.startsWith("- Phase completion commit:")
31919
+ );
31920
+ if (commitLine < 0) throw new Error(`${phase.id} lacks a completion commit field`);
31921
+ lines[commitLine] = `- Phase completion commit: \`${phaseCommit}\``;
31922
+ }
31923
+ return lines.join("\n");
31924
+ }
31594
31925
  function previewExecutionFinish(input) {
31595
31926
  if (!SHA.test(input.headCommit)) throw new Error("headCommit must be a Git commit SHA");
31596
31927
  if (!Number.isFinite(Date.parse(input.completedAt))) throw new Error("completedAt must be an ISO timestamp");
31597
31928
  const { statePath, journalPath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
31598
- const stateBody = readFileSync2(statePath, "utf8");
31599
- const journalBody = readFileSync2(journalPath, "utf8");
31929
+ const stateBody = readFileSync3(statePath, "utf8");
31930
+ const journalBody = readFileSync3(journalPath, "utf8");
31600
31931
  const state = JSON.parse(stateBody);
31601
31932
  const journal = JSON.parse(journalBody);
31602
31933
  const operation = state.operation;
@@ -31609,16 +31940,32 @@ function previewExecutionFinish(input) {
31609
31940
  }
31610
31941
  const unfinished = Object.values(journal.nodes).filter((node) => node.status !== "completed");
31611
31942
  if (unfinished.length) throw new Error(`execution has unfinished nodes: ${unfinished.map((node) => node.id).join(", ")}`);
31612
- const planPath = join(dirname(statePath), "plan.md");
31943
+ const commits = [
31944
+ input.headCommit,
31945
+ journal.baseCommit,
31946
+ journal.planCommit,
31947
+ ...Object.values(journal.nodes).flatMap((node) => [node.workerCommit, node.mergeCommit].filter(Boolean))
31948
+ ];
31949
+ const reachability = reachableGitCommits(input.projectRoot, commits);
31950
+ const unreachable = reachability ? commits.filter((commit) => reachability.get(commit) === false) : [];
31951
+ if (unreachable.length) throw new Error(`execution contains unreachable commits: ${[...new Set(unreachable)].join(", ")}`);
31952
+ const planPath = join2(dirname(statePath), "plan.md");
31953
+ const planBody = readFileSync3(planPath, "utf8");
31613
31954
  const planErrors = [];
31614
- const graph = parsePlan(planPath, planErrors);
31615
- validatePlanGraph(planPath, graph, "ready_for_review", planErrors);
31955
+ const graph = parsePlanContent(planBody, planPath, planErrors);
31956
+ validatePlanGraph(planPath, graph, "in_progress", planErrors);
31616
31957
  if (planErrors.length) throw new Error(planErrors.join("\n"));
31617
31958
  if (graph.digest !== journal.graphDigest || graph.planRevision !== journal.planRevision) {
31618
31959
  throw new Error("approved plan changed during execution");
31619
31960
  }
31620
- const worktreeRoot = join(safeProjectRoot(input.projectRoot), ".cadre", ".worktrees", input.trackId, input.executionId);
31621
- if (existsSync3(worktreeRoot) && readdirSync(worktreeRoot).length) {
31961
+ const planContent = renderCompletedPlan(planBody, graph, journal);
31962
+ const completedPlanErrors = [];
31963
+ const completedGraph = parsePlanContent(planContent, planPath, completedPlanErrors);
31964
+ validatePlanGraph(planPath, completedGraph, "ready_for_review", completedPlanErrors);
31965
+ if (completedPlanErrors.length) throw new Error(completedPlanErrors.join("\n"));
31966
+ if (completedGraph.digest !== journal.graphDigest) throw new Error("completed plan changed the approved execution graph");
31967
+ const worktreeRoot = join2(safeProjectRoot(input.projectRoot), ".cadre", ".worktrees", input.trackId, input.executionId);
31968
+ if (existsSync4(worktreeRoot) && readdirSync2(worktreeRoot).length) {
31622
31969
  throw new Error(`execution still has managed worktrees under ${worktreeRoot}`);
31623
31970
  }
31624
31971
  const completedJournal = {
@@ -31636,30 +31983,66 @@ function previewExecutionFinish(input) {
31636
31983
  lastExecution: {
31637
31984
  executionId: input.executionId,
31638
31985
  journal: journalRelative(input.executionId),
31986
+ approvalMode: journal.approvalMode,
31639
31987
  planRevision: journal.planRevision,
31640
31988
  graphDigest: journal.graphDigest,
31641
31989
  headCommit: input.headCommit,
31642
31990
  completedAt: input.completedAt
31643
31991
  }
31644
31992
  };
31993
+ const { tracksPath, tracksBody, tracksContent } = renderTracksWithState(
31994
+ input.projectRoot,
31995
+ statePath,
31996
+ completedState
31997
+ );
31645
31998
  return {
31646
31999
  journalPath,
31647
32000
  journal: completedJournal,
31648
32001
  statePath,
31649
32002
  state: completedState,
31650
- digest: hash2({ stateBody, journalBody, journal: completedJournal, state: completedState })
32003
+ planPath,
32004
+ planContent,
32005
+ tracksPath,
32006
+ tracksContent,
32007
+ digest: hash2({
32008
+ stateBody,
32009
+ journalBody,
32010
+ planBody,
32011
+ tracksBody,
32012
+ journal: completedJournal,
32013
+ state: completedState,
32014
+ planContent,
32015
+ tracksContent
32016
+ })
31651
32017
  };
31652
32018
  }
31653
32019
  function applyExecutionFinish(input, proposalDigest) {
31654
32020
  const proposal = previewExecutionFinish(input);
31655
32021
  if (proposal.digest !== proposalDigest) throw new Error("execution completion proposal is stale; preview it again");
31656
- if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink()) {
32022
+ if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink() || lstatSync(proposal.planPath).isSymbolicLink() || lstatSync(proposal.tracksPath).isSymbolicLink()) {
31657
32023
  throw new Error("refusing to complete execution through a symbolic link");
31658
32024
  }
31659
- writeFileSync(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
31660
- `);
31661
- writeFileSync(proposal.statePath, `${JSON.stringify(proposal.state, null, 2)}
31662
- `);
32025
+ const journalTemporaryPath = join2(dirname(proposal.journalPath), `.${basename(proposal.journalPath)}.${process.pid}.${randomUUID()}.tmp`);
32026
+ const stateTemporaryPath = join2(dirname(proposal.statePath), `.${basename(proposal.statePath)}.${process.pid}.${randomUUID()}.tmp`);
32027
+ const planTemporaryPath = join2(dirname(proposal.planPath), `.${basename(proposal.planPath)}.${process.pid}.${randomUUID()}.tmp`);
32028
+ const tracksTemporaryPath = join2(dirname(proposal.tracksPath), `.${basename(proposal.tracksPath)}.${process.pid}.${randomUUID()}.tmp`);
32029
+ try {
32030
+ writeFileSync(journalTemporaryPath, `${JSON.stringify(proposal.journal, null, 2)}
32031
+ `, { flag: "wx" });
32032
+ writeFileSync(stateTemporaryPath, `${JSON.stringify(proposal.state, null, 2)}
32033
+ `, { flag: "wx" });
32034
+ writeFileSync(planTemporaryPath, proposal.planContent, { flag: "wx" });
32035
+ writeFileSync(tracksTemporaryPath, proposal.tracksContent, { flag: "wx" });
32036
+ renameSync(journalTemporaryPath, proposal.journalPath);
32037
+ renameSync(stateTemporaryPath, proposal.statePath);
32038
+ renameSync(planTemporaryPath, proposal.planPath);
32039
+ renameSync(tracksTemporaryPath, proposal.tracksPath);
32040
+ } finally {
32041
+ if (existsSync4(journalTemporaryPath)) unlinkSync(journalTemporaryPath);
32042
+ if (existsSync4(stateTemporaryPath)) unlinkSync(stateTemporaryPath);
32043
+ if (existsSync4(planTemporaryPath)) unlinkSync(planTemporaryPath);
32044
+ if (existsSync4(tracksTemporaryPath)) unlinkSync(tracksTemporaryPath);
32045
+ }
31663
32046
  return proposal;
31664
32047
  }
31665
32048
  function validateExecutionJournal(trackRoot, state, graph, errors) {
@@ -31674,18 +32057,18 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31674
32057
  errors.push(`${state.trackId}: invalid execution journal path`);
31675
32058
  return;
31676
32059
  }
31677
- const path = resolve2(trackRoot, relative5);
31678
- if (!path.startsWith(`${resolve2(trackRoot)}/`)) {
32060
+ const path = resolve4(trackRoot, relative5);
32061
+ if (!path.startsWith(`${resolve4(trackRoot)}/`)) {
31679
32062
  errors.push(`${state.trackId}: execution journal escapes track root`);
31680
32063
  return;
31681
32064
  }
31682
- if (!existsSync3(path)) {
32065
+ if (!existsSync4(path)) {
31683
32066
  errors.push(`${state.trackId}: missing execution journal ${relative5}`);
31684
32067
  return;
31685
32068
  }
31686
32069
  let journal;
31687
32070
  try {
31688
- journal = JSON.parse(readFileSync2(path, "utf8"));
32071
+ journal = JSON.parse(readFileSync3(path, "utf8"));
31689
32072
  } catch (error51) {
31690
32073
  errors.push(`${state.trackId}: invalid execution journal (${error51 instanceof Error ? error51.message : String(error51)})`);
31691
32074
  return;
@@ -31699,6 +32082,9 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31699
32082
  if (journal.requestedMode === "sequential" && journal.effectiveMode !== "sequential") {
31700
32083
  errors.push(`${state.trackId}: sequential request became parallel`);
31701
32084
  }
32085
+ if (!EXECUTION_APPROVAL_MODES.includes(journal.approvalMode ?? "governed")) {
32086
+ errors.push(`${state.trackId}: invalid execution approval mode`);
32087
+ }
31702
32088
  if (!Number.isInteger(journal.maxWorkers) || journal.maxWorkers < 1 || journal.maxWorkers > 32) errors.push(`${state.trackId}: invalid maxWorkers`);
31703
32089
  const requireCurrentGraph = operation?.action === "implement" || ["ready_for_review", "completed", "archived"].includes(state.status);
31704
32090
  if (graph && requireCurrentGraph && (journal.graphDigest !== graph.digest || journal.planRevision !== graph.planRevision)) {
@@ -31763,11 +32149,11 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31763
32149
  }
31764
32150
  if (operation?.action === "implement" && journal.status !== "in_progress") errors.push(`${state.trackId}: active implement operation requires an in-progress journal`);
31765
32151
  if (operation?.action === "implement") {
31766
- if (operation.executionId !== journal.executionId || operation.graphDigest !== journal.graphDigest || operation.planRevision !== journal.planRevision) {
32152
+ if (operation.executionId !== journal.executionId || operation.graphDigest !== journal.graphDigest || operation.planRevision !== journal.planRevision || String(operation.approvalMode ?? "governed") !== String(journal.approvalMode ?? "governed")) {
31767
32153
  errors.push(`${state.trackId}: implement operation does not match its execution journal`);
31768
32154
  }
31769
32155
  } else if (state.lastExecution) {
31770
- if (state.lastExecution.executionId !== journal.executionId || state.lastExecution.graphDigest !== journal.graphDigest || state.lastExecution.planRevision !== journal.planRevision || state.lastExecution.headCommit !== journal.headCommit) {
32156
+ if (state.lastExecution.executionId !== journal.executionId || state.lastExecution.graphDigest !== journal.graphDigest || state.lastExecution.planRevision !== journal.planRevision || state.lastExecution.headCommit !== journal.headCommit || String(state.lastExecution.approvalMode ?? "governed") !== String(journal.approvalMode ?? "governed")) {
31771
32157
  errors.push(`${state.trackId}: lastExecution does not match its execution journal`);
31772
32158
  }
31773
32159
  }
@@ -31783,6 +32169,22 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31783
32169
  }
31784
32170
 
31785
32171
  // src/domain/state.ts
32172
+ function collectCommitReferences(value, owner, references, commitContext = false) {
32173
+ if (Array.isArray(value)) {
32174
+ value.forEach((entry, index) => collectCommitReferences(entry, `${owner}[${index}]`, references, commitContext));
32175
+ return;
32176
+ }
32177
+ if (!value || typeof value !== "object") return;
32178
+ for (const [key, child] of Object.entries(value)) {
32179
+ const childOwner = `${owner}.${key}`;
32180
+ const isCommit = commitContext || /^(?:commit|.*Commit|reviewedHead)$/.test(key);
32181
+ if (isCommit && typeof child === "string" && /^[0-9a-f]{7,40}$/.test(child)) {
32182
+ references.push({ owner: childOwner, commit: child });
32183
+ } else {
32184
+ collectCommitReferences(child, childOwner, references, key === "commits");
32185
+ }
32186
+ }
32187
+ }
31786
32188
  var TRACK_STATUSES = /* @__PURE__ */ new Set([
31787
32189
  "drafting-spec",
31788
32190
  "drafting-plan",
@@ -31808,11 +32210,11 @@ var REQUIRED_CONTEXT = [
31808
32210
  "tracks.md"
31809
32211
  ];
31810
32212
  function cadreRoot(projectRoot) {
31811
- return join2(resolve3(projectRoot), ".cadre");
32213
+ return join3(resolve5(projectRoot), ".cadre");
31812
32214
  }
31813
32215
  function readJson(path, errors) {
31814
32216
  try {
31815
- return JSON.parse(readFileSync3(path, "utf8"));
32217
+ return JSON.parse(readFileSync4(path, "utf8"));
31816
32218
  } catch (error51) {
31817
32219
  errors.push(`${path}: invalid JSON (${error51 instanceof Error ? error51.message : String(error51)})`);
31818
32220
  return null;
@@ -31886,6 +32288,9 @@ function validateImplementOperation(state, owner, errors) {
31886
32288
  errors.push(`${owner}: implement journal path is invalid`);
31887
32289
  }
31888
32290
  if (!["parallel", "sequential"].includes(String(operation.mode ?? ""))) errors.push(`${owner}: implement mode is invalid`);
32291
+ if (!["governed", "phase", "autonomous"].includes(String(operation.approvalMode ?? "governed"))) {
32292
+ errors.push(`${owner}: implement approvalMode is invalid`);
32293
+ }
31889
32294
  if (!/^[0-9a-f]{64}$/.test(String(operation.graphDigest ?? ""))) errors.push(`${owner}: implement graphDigest is invalid`);
31890
32295
  if (!Number.isInteger(operation.planRevision) || Number(operation.planRevision) < 1) errors.push(`${owner}: implement planRevision is invalid`);
31891
32296
  }
@@ -31914,11 +32319,11 @@ function validateRevertOperation(state, owner, errors) {
31914
32319
  }
31915
32320
  }
31916
32321
  function validateLearning(path, required2, errors) {
31917
- if (!existsSync4(path)) {
32322
+ if (!existsSync5(path)) {
31918
32323
  if (required2) errors.push(`${path}: missing learning file`);
31919
32324
  return;
31920
32325
  }
31921
- const body = readFileSync3(path, "utf8");
32326
+ const body = readFileSync4(path, "utf8");
31922
32327
  const start = "<!-- cadre:pattern-seed:start -->";
31923
32328
  const end = "<!-- cadre:pattern-seed:end -->";
31924
32329
  if (!body.includes(start) || !body.includes(end) || body.indexOf(start) >= body.indexOf(end)) {
@@ -31926,11 +32331,11 @@ function validateLearning(path, required2, errors) {
31926
32331
  }
31927
32332
  }
31928
32333
  function validateSpec(path, errors) {
31929
- if (!existsSync4(path)) {
32334
+ if (!existsSync5(path)) {
31930
32335
  errors.push(`${path}: missing specification`);
31931
32336
  return;
31932
32337
  }
31933
- const body = readFileSync3(path, "utf8");
32338
+ const body = readFileSync4(path, "utf8");
31934
32339
  for (const heading of [
31935
32340
  "## Functional Requirements",
31936
32341
  "## Non-Functional Requirements",
@@ -31943,12 +32348,12 @@ function validateSpec(path, errors) {
31943
32348
  }
31944
32349
  }
31945
32350
  function validateProjectOperations(root, byId, errors) {
31946
- const operationsRoot = join2(root, "operations");
31947
- if (!existsSync4(operationsRoot)) return;
32351
+ const operationsRoot = join3(root, "operations");
32352
+ if (!existsSync5(operationsRoot)) return;
31948
32353
  let activeProjectOperations = 0;
31949
- for (const file2 of readdirSync2(operationsRoot).filter((name) => name.endsWith(".json"))) {
32354
+ for (const file2 of readdirSync3(operationsRoot).filter((name) => name.endsWith(".json"))) {
31950
32355
  const owner = `operations/${file2}`;
31951
- const operation = readJson(join2(operationsRoot, file2), errors);
32356
+ const operation = readJson(join3(operationsRoot, file2), errors);
31952
32357
  if (!operation) continue;
31953
32358
  validateOperation(operation, owner, errors);
31954
32359
  if (!operation.status || !["in_progress", "completed"].includes(operation.status)) {
@@ -32020,12 +32425,12 @@ function discoverTracks(root, errors) {
32020
32425
  const states = /* @__PURE__ */ new Map();
32021
32426
  const byId = /* @__PURE__ */ new Map();
32022
32427
  for (const directory of ["tracks", "archive"]) {
32023
- const directoryRoot = join2(root, directory);
32024
- if (!existsSync4(directoryRoot)) continue;
32025
- const entries = readdirSync2(directoryRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).sort((left, right) => left.name.localeCompare(right.name));
32428
+ const directoryRoot = join3(root, directory);
32429
+ if (!existsSync5(directoryRoot)) continue;
32430
+ const entries = readdirSync3(directoryRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).sort((left, right) => left.name.localeCompare(right.name));
32026
32431
  for (const entry of entries) {
32027
32432
  const location = `${directory}/${entry.name}`;
32028
- const state = readJson(join2(directoryRoot, entry.name, "state.json"), errors);
32433
+ const state = readJson(join3(directoryRoot, entry.name, "state.json"), errors);
32029
32434
  if (!state) continue;
32030
32435
  const id = state.trackId;
32031
32436
  if (!id) {
@@ -32047,31 +32452,16 @@ function discoverTracks(root, errors) {
32047
32452
  tracks.sort((left, right) => left.id.localeCompare(right.id));
32048
32453
  return { tracks, states, byId };
32049
32454
  }
32050
- function buildTracks(tracks) {
32051
- const lines = [
32052
- "# Tracks",
32053
- "",
32054
- "Generated from track-local `state.json` files by the Cadre MCP server.",
32055
- "",
32056
- "| Track | Type | Status | Revision |",
32057
- "| --- | --- | --- | ---: |"
32058
- ];
32059
- for (const track of tracks) {
32060
- lines.push(`| \`${track.id}\` ${track.title ?? ""} | ${track.type} | ${track.status} | ${track.revision ?? 1} |`);
32061
- }
32062
- return `${lines.join("\n")}
32063
- `;
32064
- }
32065
32455
  function validateProject(projectRoot) {
32066
32456
  const root = cadreRoot(projectRoot);
32067
32457
  const errors = [];
32068
32458
  const warnings = [];
32069
32459
  for (const file2 of REQUIRED_CONTEXT) {
32070
- if (!existsSync4(join2(root, file2))) errors.push(`${join2(root, file2)}: missing required Cadre file`);
32460
+ if (!existsSync5(join3(root, file2))) errors.push(`${join3(root, file2)}: missing required Cadre file`);
32071
32461
  }
32072
- const gitignorePath = join2(root, ".gitignore");
32073
- if (existsSync4(gitignorePath)) {
32074
- const gitignore = readFileSync3(gitignorePath, "utf8");
32462
+ const gitignorePath = join3(root, ".gitignore");
32463
+ if (existsSync5(gitignorePath)) {
32464
+ const gitignore = readFileSync4(gitignorePath, "utf8");
32075
32465
  if (!gitignore.split(/\r?\n/).includes("/.worktrees/")) {
32076
32466
  errors.push(`${gitignorePath}: must ignore /.worktrees/`);
32077
32467
  }
@@ -32079,8 +32469,10 @@ function validateProject(projectRoot) {
32079
32469
  errors.push(`${gitignorePath}: must ignore /wisps/`);
32080
32470
  }
32081
32471
  }
32082
- const project = readJson(join2(root, "project.json"), errors);
32472
+ const project = readJson(join3(root, "project.json"), errors);
32083
32473
  if (!project) return { project: null, tracks: [], states: /* @__PURE__ */ new Map(), errors, warnings };
32474
+ const commitReferences = [];
32475
+ collectCommitReferences(project, "project.json", commitReferences);
32084
32476
  if (project.schemaVersion !== 1) errors.push("project.json: unsupported schemaVersion");
32085
32477
  if (project.runtimeVersion !== CADRE_RUNTIME_VERSION) errors.push(`project.json: runtimeVersion must be ${CADRE_RUNTIME_VERSION}`);
32086
32478
  if (project.templateSetVersion !== TEMPLATE_SET_VERSION) errors.push(`project.json: templateSetVersion must be ${TEMPLATE_SET_VERSION}`);
@@ -32107,7 +32499,8 @@ function validateProject(projectRoot) {
32107
32499
  const { tracks, states, byId } = discoverTracks(root, errors);
32108
32500
  for (const track of tracks) {
32109
32501
  const state = states.get(track.id);
32110
- const trackRoot = join2(root, track.location);
32502
+ collectCommitReferences(state, `${track.id}/state.json`, commitReferences);
32503
+ const trackRoot = join3(root, track.location);
32111
32504
  if (state.schemaVersion !== 1) errors.push(`${track.id}: unsupported state schemaVersion`);
32112
32505
  if (!state.title || typeof state.title !== "string") errors.push(`${track.id}: title is required`);
32113
32506
  if (!TRACK_TYPES.has(track.type)) errors.push(`${track.id}: type must be feature or bug`);
@@ -32137,23 +32530,54 @@ function validateProject(projectRoot) {
32137
32530
  if (["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && !planCommit && state.operation?.action !== "plan") {
32138
32531
  errors.push(`${track.id}: status ${track.status} requires a recorded plan commit or active plan operation`);
32139
32532
  }
32140
- const specPath = join2(trackRoot, "spec.md");
32141
- const planPath = join2(trackRoot, "plan.md");
32142
- const learningPath = join2(trackRoot, "learning.md");
32143
- if (existsSync4(specPath)) validateSpec(specPath, errors);
32533
+ const specPath = join3(trackRoot, "spec.md");
32534
+ const planPath = join3(trackRoot, "plan.md");
32535
+ const learningPath = join3(trackRoot, "learning.md");
32536
+ if (existsSync5(specPath)) validateSpec(specPath, errors);
32144
32537
  else if (track.status !== "drafting-spec" && state?.operation?.action !== "specify") errors.push(`${track.id}: missing spec.md`);
32145
32538
  let planGraph = null;
32146
- if (existsSync4(planPath)) planGraph = readAndValidatePlan(planPath, track.status, errors);
32147
- else if (["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && state?.operation?.action !== "plan") errors.push(`${track.id}: missing plan.md`);
32539
+ if (existsSync5(planPath)) {
32540
+ planGraph = readAndValidatePlan(planPath, track.status, errors);
32541
+ for (const phase of planGraph.phases) {
32542
+ if (phase.completionCommit) commitReferences.push({
32543
+ owner: `${track.id}/plan.md:${phase.id}`,
32544
+ commit: phase.completionCommit
32545
+ });
32546
+ for (const task of phase.tasks) if (task.commit) commitReferences.push({
32547
+ owner: `${track.id}/plan.md:${task.id}`,
32548
+ commit: task.commit
32549
+ });
32550
+ }
32551
+ } else if (["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && state?.operation?.action !== "plan") errors.push(`${track.id}: missing plan.md`);
32148
32552
  validateLearning(
32149
32553
  learningPath,
32150
32554
  ["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && state?.operation?.action !== "plan",
32151
32555
  errors
32152
32556
  );
32153
32557
  validateExecutionJournal(trackRoot, state, planGraph, errors);
32558
+ const executionReference = state.operation?.action === "implement" ? state.operation : state.lastExecution;
32559
+ const journalRelative2 = typeof executionReference?.journal === "string" ? executionReference.journal : null;
32560
+ if (journalRelative2 && /^executions\/execution-[0-9A-Za-z-]+\.json$/.test(journalRelative2)) {
32561
+ const journalPath = join3(trackRoot, journalRelative2);
32562
+ if (existsSync5(journalPath)) {
32563
+ try {
32564
+ collectCommitReferences(JSON.parse(readFileSync4(journalPath, "utf8")), `${track.id}/${journalRelative2}`, commitReferences);
32565
+ } catch {
32566
+ }
32567
+ }
32568
+ }
32569
+ const revisionsPath = join3(trackRoot, "revisions");
32570
+ if (existsSync5(revisionsPath)) {
32571
+ for (const file2 of readdirSync3(revisionsPath).filter((entry) => entry.endsWith(".md"))) {
32572
+ const content = readFileSync4(join3(revisionsPath, file2), "utf8");
32573
+ for (const match of content.matchAll(/^- Revision commit: `([0-9a-f]{7,40})`$/gm)) {
32574
+ commitReferences.push({ owner: `${track.id}/revisions/${file2}`, commit: match[1] });
32575
+ }
32576
+ }
32577
+ }
32154
32578
  if (["ready_for_review", "completed", "archived"].includes(track.status)) {
32155
- const managedRoot = join2(root, ".worktrees", track.id);
32156
- if (existsSync4(managedRoot) && readdirSync2(managedRoot).length) {
32579
+ const managedRoot = join3(root, ".worktrees", track.id);
32580
+ if (existsSync5(managedRoot) && readdirSync3(managedRoot).length) {
32157
32581
  errors.push(`${track.id}: finalized track retains managed execution worktrees`);
32158
32582
  }
32159
32583
  }
@@ -32191,8 +32615,16 @@ function validateProject(projectRoot) {
32191
32615
  visited.add(id);
32192
32616
  }
32193
32617
  for (const id of byId.keys()) visit(id, []);
32194
- const tracksPath = join2(root, "tracks.md");
32195
- if (existsSync4(tracksPath) && readFileSync3(tracksPath, "utf8") !== buildTracks(tracks)) {
32618
+ const reachability = reachableGitCommits(projectRoot, commitReferences.map((reference) => reference.commit));
32619
+ if (reachability) {
32620
+ for (const reference of commitReferences) {
32621
+ if (reachability.get(reference.commit) === false) {
32622
+ errors.push(`${reference.owner}: commit is not reachable: ${reference.commit}`);
32623
+ }
32624
+ }
32625
+ }
32626
+ const tracksPath = join3(root, "tracks.md");
32627
+ if (existsSync5(tracksPath) && readFileSync4(tracksPath, "utf8") !== buildTracks(tracks)) {
32196
32628
  warnings.push("TRACKS_INDEX_STALE: tracks.md is stale; regenerate it after approved state changes");
32197
32629
  }
32198
32630
  return { project, tracks, states, errors, warnings };
@@ -32212,8 +32644,8 @@ function renderTracksPreview(projectRoot) {
32212
32644
  const result2 = validateProject(projectRoot);
32213
32645
  if (!result2.project) throw new Error(result2.errors.join("\n") || "Cadre project state is unavailable");
32214
32646
  if (result2.errors.length) throw new Error(result2.errors.join("\n"));
32215
- const path = join2(cadreRoot(projectRoot), "tracks.md");
32216
- const previousContent = existsSync4(path) ? readFileSync3(path, "utf8") : null;
32647
+ const path = join3(cadreRoot(projectRoot), "tracks.md");
32648
+ const previousContent = existsSync5(path) ? readFileSync4(path, "utf8") : null;
32217
32649
  const content = buildTracks(result2.tracks);
32218
32650
  const digest = createHash3("sha256").update(JSON.stringify({ content, previousContent })).digest("hex");
32219
32651
  return { path, content, previousContent, changed: previousContent !== content, digest };
@@ -32223,9 +32655,9 @@ function writeTracks(projectRoot, proposalDigest) {
32223
32655
  if (preview.digest !== proposalDigest) {
32224
32656
  throw new Error("tracks.md proposal is stale; preview it again before applying");
32225
32657
  }
32226
- if (existsSync4(preview.path)) {
32658
+ if (existsSync5(preview.path)) {
32227
32659
  if (lstatSync2(preview.path).isSymbolicLink()) throw new Error("Refusing to write tracks.md through a symbolic link");
32228
- readFileSync3(preview.path, "utf8");
32660
+ readFileSync4(preview.path, "utf8");
32229
32661
  }
32230
32662
  writeFileSync2(preview.path, preview.content);
32231
32663
  return preview.path;
@@ -32242,7 +32674,7 @@ function formatStatus(projectRoot) {
32242
32674
  for (const track of result2.tracks) {
32243
32675
  const dependencies = track.dependencies?.length ? track.dependencies.join(",") : "none";
32244
32676
  const state = result2.states.get(track.id);
32245
- const execution = state?.operation?.action === "implement" ? `${String(state.operation.executionId ?? "unknown")}/${String(state.operation.mode ?? "unknown")}` : state?.lastExecution?.executionId ?? "none";
32677
+ const execution = state?.operation?.action === "implement" ? `${String(state.operation.executionId ?? "unknown")}/${String(state.operation.mode ?? "unknown")}/${String(state.operation.approvalMode ?? "governed")}` : state?.lastExecution ? `${String(state.lastExecution.executionId ?? "unknown")}/completed/${String(state.lastExecution.approvalMode ?? "governed")}` : "none";
32246
32678
  lines.push(`${track.id} [${track.type}] ${track.status}; checkpoint=${state?.checkpoint ?? "none"}; operation=${state?.operation?.action ?? "none"}; execution=${execution}; deps=${dependencies}; revision=${track.revision ?? 1}; reviews=${state?.reviewCycles?.length ?? 0}; next=${nextCommand(track)}`);
32247
32679
  }
32248
32680
  const counts = result2.tracks.reduce((summary, track) => {
@@ -32259,8 +32691,8 @@ function formatStatus(projectRoot) {
32259
32691
 
32260
32692
  // src/domain/templates.ts
32261
32693
  import { createHash as createHash4 } from "node:crypto";
32262
- import { existsSync as existsSync5, readFileSync as readFileSync4, readdirSync as readdirSync3 } from "node:fs";
32263
- import { dirname as dirname2, extname, join as join3, relative, resolve as resolve4, sep } from "node:path";
32694
+ import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync as readdirSync4 } from "node:fs";
32695
+ import { dirname as dirname2, extname, join as join4, relative, resolve as resolve6, sep } from "node:path";
32264
32696
  import { fileURLToPath } from "node:url";
32265
32697
  var TEMPLATE_IDS = [
32266
32698
  "project/archive-operation",
@@ -32307,16 +32739,16 @@ function locateTemplateRoot() {
32307
32739
  const moduleDirectory = dirname2(fileURLToPath(import.meta.url));
32308
32740
  const candidates = [
32309
32741
  process.env.CADRE_TEMPLATE_ROOT,
32310
- resolve4(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
32311
- resolve4(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
32742
+ resolve6(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
32743
+ resolve6(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
32312
32744
  ].filter((candidate) => Boolean(candidate));
32313
- const found = candidates.find((candidate) => existsSync5(candidate));
32745
+ const found = candidates.find((candidate) => existsSync6(candidate));
32314
32746
  if (!found) throw new Error(`Cadre template set ${TEMPLATE_SET_VERSION} is unavailable`);
32315
32747
  return found;
32316
32748
  }
32317
32749
  function walk(root, directory = root) {
32318
- return readdirSync3(directory, { withFileTypes: true }).flatMap((entry) => {
32319
- const path = join3(directory, entry.name);
32750
+ return readdirSync4(directory, { withFileTypes: true }).flatMap((entry) => {
32751
+ const path = join4(directory, entry.name);
32320
32752
  return entry.isDirectory() ? walk(root, path) : [relative(root, path).split(sep).join("/")];
32321
32753
  });
32322
32754
  }
@@ -32353,7 +32785,7 @@ function templateCatalog() {
32353
32785
  const catalog = walk(root).map((relativePath) => {
32354
32786
  const id = templateId(relativePath);
32355
32787
  if (!id) return null;
32356
- const content = readFileSync4(join3(root, relativePath), "utf8");
32788
+ const content = readFileSync5(join4(root, relativePath), "utf8");
32357
32789
  return {
32358
32790
  id,
32359
32791
  uri: `cadre://templates/${TEMPLATE_SET_VERSION}/${id}`,
@@ -32415,6 +32847,13 @@ var REQUIRED_APPROVED_FILES = /* @__PURE__ */ new Set([
32415
32847
  function hash3(content) {
32416
32848
  return createHash5("sha256").update(content).digest("hex");
32417
32849
  }
32850
+ function proposalFileHash(file2) {
32851
+ if (file2.path !== "project.json") return file2.sha256;
32852
+ const state = JSON.parse(file2.content);
32853
+ if (state.setup?.operation) state.setup.operation.approvedAt = "<audit-timestamp>";
32854
+ return hash3(`${JSON.stringify(state, null, 2)}
32855
+ `);
32856
+ }
32418
32857
  function normalizeCadrePath(input) {
32419
32858
  if (isAbsolute(input)) throw new Error(`Cadre artifact path must be relative: ${input}`);
32420
32859
  const normalized = input.replaceAll("\\", "/").replace(/^\.\//, "");
@@ -32448,7 +32887,7 @@ function projectState(input, approvedPaths, template) {
32448
32887
  }
32449
32888
  function previewProjectInit(input) {
32450
32889
  const root = safeProjectRoot(input.projectRoot);
32451
- if (existsSync6(join4(root, ".cadre"))) throw new Error(`${root}/.cadre already exists`);
32890
+ if (existsSync7(join5(root, ".cadre"))) throw new Error(`${root}/.cadre already exists`);
32452
32891
  if (!input.projectName.trim()) throw new Error("Project name is required");
32453
32892
  if (!Number.isFinite(Date.parse(input.approvedAt))) throw new Error("approvedAt must be an ISO timestamp");
32454
32893
  if (input.baseCommit !== null && !/^[0-9a-f]{7,40}$/.test(input.baseCommit)) {
@@ -32486,12 +32925,12 @@ function previewProjectInit(input) {
32486
32925
  const digest = hash3(JSON.stringify({
32487
32926
  runtimeVersion: CADRE_RUNTIME_VERSION,
32488
32927
  templateSetVersion: TEMPLATE_SET_VERSION,
32489
- files: files.map(({ path, sha256 }) => ({ path, sha256 }))
32928
+ files: files.map((file2) => ({ path: file2.path, sha256: proposalFileHash(file2) }))
32490
32929
  }));
32491
32930
  return { runtimeVersion: CADRE_RUNTIME_VERSION, templateSetVersion: TEMPLATE_SET_VERSION, files, digest };
32492
32931
  }
32493
32932
  function targetWithin(root, relativePath) {
32494
- const target = resolve5(root, relativePath);
32933
+ const target = resolve7(root, relativePath);
32495
32934
  const relation = relative2(root, target);
32496
32935
  if (relation.startsWith("..") || isAbsolute(relation)) throw new Error(`Path escapes initialization root: ${relativePath}`);
32497
32936
  return target;
@@ -32499,7 +32938,7 @@ function targetWithin(root, relativePath) {
32499
32938
  function assertNoSymlinkPath(root, target) {
32500
32939
  let current = target;
32501
32940
  while (current !== root) {
32502
- if (existsSync6(current) && lstatSync3(current).isSymbolicLink()) {
32941
+ if (existsSync7(current) && lstatSync3(current).isSymbolicLink()) {
32503
32942
  throw new Error(`Refusing symbolic link inside initialization stage: ${current}`);
32504
32943
  }
32505
32944
  current = dirname3(current);
@@ -32509,8 +32948,8 @@ function applyProjectInit(input, proposalDigest) {
32509
32948
  const proposal = previewProjectInit(input);
32510
32949
  if (proposal.digest !== proposalDigest) throw new Error("Initialization proposal digest does not match; preview again");
32511
32950
  const projectRoot = safeProjectRoot(input.projectRoot);
32512
- const stage = join4(projectRoot, `.cadre-init-${proposal.digest.slice(0, 12)}`);
32513
- if (existsSync6(stage) && (!lstatSync3(stage).isDirectory() || lstatSync3(stage).isSymbolicLink())) {
32951
+ const stage = join5(projectRoot, `.cadre-init-${proposal.digest.slice(0, 12)}`);
32952
+ if (existsSync7(stage) && (!lstatSync3(stage).isDirectory() || lstatSync3(stage).isSymbolicLink())) {
32514
32953
  throw new Error(`Initialization stage is not a regular directory: ${stage}`);
32515
32954
  }
32516
32955
  mkdirSync2(stage, { recursive: true });
@@ -32518,21 +32957,21 @@ function applyProjectInit(input, proposalDigest) {
32518
32957
  const target = targetWithin(stage, file2.path);
32519
32958
  assertNoSymlinkPath(stage, target);
32520
32959
  mkdirSync2(dirname3(target), { recursive: true });
32521
- if (existsSync6(target)) {
32522
- const current = readFileSync5(target, "utf8");
32960
+ if (existsSync7(target)) {
32961
+ const current = readFileSync6(target, "utf8");
32523
32962
  if (current !== file2.content) throw new Error(`Interrupted initialization disagrees at ${file2.path}`);
32524
32963
  } else writeFileSync3(target, file2.content);
32525
32964
  }
32526
- const finalRoot = join4(projectRoot, ".cadre");
32527
- if (existsSync6(finalRoot)) throw new Error(`${finalRoot} appeared after preview; refusing to overwrite it`);
32965
+ const finalRoot = join5(projectRoot, ".cadre");
32966
+ if (existsSync7(finalRoot)) throw new Error(`${finalRoot} appeared after preview; refusing to overwrite it`);
32528
32967
  renameSync2(stage, finalRoot);
32529
32968
  return proposal;
32530
32969
  }
32531
32970
  function recordSetupCommit(projectRootInput, commit) {
32532
32971
  if (!/^[0-9a-f]{7,40}$/.test(commit)) throw new Error("commit must be a hexadecimal Git commit SHA");
32533
32972
  const root = safeProjectRoot(projectRootInput);
32534
- const path = join4(root, ".cadre", "project.json");
32535
- const project = JSON.parse(readFileSync5(path, "utf8"));
32973
+ const path = join5(root, ".cadre", "project.json");
32974
+ const project = JSON.parse(readFileSync6(path, "utf8"));
32536
32975
  if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
32537
32976
  throw new Error("Project setup is not awaiting its create commit");
32538
32977
  }
@@ -32547,15 +32986,15 @@ function recordSetupCommit(projectRootInput, commit) {
32547
32986
  }
32548
32987
  function recordGitInitialized(projectRootInput) {
32549
32988
  const root = safeProjectRoot(projectRootInput);
32550
- const path = join4(root, ".cadre", "project.json");
32551
- const project = JSON.parse(readFileSync5(path, "utf8"));
32989
+ const path = join5(root, ".cadre", "project.json");
32990
+ const project = JSON.parse(readFileSync6(path, "utf8"));
32552
32991
  if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
32553
32992
  throw new Error("Project setup is not in an active create operation");
32554
32993
  }
32555
32994
  if (project.setup.operation.gitDisposition !== "initialize") {
32556
32995
  throw new Error("Project setup was not approved to initialize Git");
32557
32996
  }
32558
- if (resolve5(String(project.setup.operation.repositoryRoot)) !== root) {
32997
+ if (resolve7(String(project.setup.operation.repositoryRoot)) !== root) {
32559
32998
  throw new Error("Approved Git repository root does not match projectRoot");
32560
32999
  }
32561
33000
  project.setup.checkpoint = "commit-pending";
@@ -32566,16 +33005,16 @@ function recordGitInitialized(projectRootInput) {
32566
33005
 
32567
33006
  // src/domain/worktrees.ts
32568
33007
  import { createHash as createHash6 } from "node:crypto";
32569
- import { existsSync as existsSync7, lstatSync as lstatSync4, readdirSync as readdirSync4, realpathSync, rmdirSync } from "node:fs";
32570
- import { dirname as dirname4, join as join5, relative as relative3, resolve as resolve6 } from "node:path";
32571
- import { spawnSync } from "node:child_process";
33008
+ import { existsSync as existsSync8, lstatSync as lstatSync4, readdirSync as readdirSync5, realpathSync as realpathSync2, rmdirSync } from "node:fs";
33009
+ import { dirname as dirname4, join as join6, relative as relative3, resolve as resolve8 } from "node:path";
33010
+ import { spawnSync as spawnSync2 } from "node:child_process";
32572
33011
  var SHA2 = /^[0-9a-f]{7,40}$/;
32573
33012
  var TRACK_ID2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32574
33013
  var EXECUTION_ID2 = /^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
32575
33014
  var PHASE_ID = /^P\d+$/;
32576
33015
  var TASK_ID = /^T(\d+)\.(\d+)$/;
32577
33016
  function git(cwd, args, allowFailure = false) {
32578
- const result2 = spawnSync("git", args, { cwd, encoding: "utf8" });
33017
+ const result2 = spawnSync2("git", args, { cwd, encoding: "utf8" });
32579
33018
  if (result2.error) throw result2.error;
32580
33019
  const status = result2.status ?? 1;
32581
33020
  const output = { stdout: result2.stdout ?? "", stderr: result2.stderr ?? "", status };
@@ -32586,8 +33025,8 @@ function hash4(value) {
32586
33025
  return createHash6("sha256").update(JSON.stringify(value)).digest("hex");
32587
33026
  }
32588
33027
  function assertRepository(projectRoot) {
32589
- const root = realpathSync(safeProjectRoot(projectRoot));
32590
- const detected = realpathSync(resolve6(git(root, ["rev-parse", "--show-toplevel"]).stdout.trim()));
33028
+ const root = realpathSync2(safeProjectRoot(projectRoot));
33029
+ const detected = realpathSync2(resolve8(git(root, ["rev-parse", "--show-toplevel"]).stdout.trim()));
32591
33030
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
32592
33031
  return root;
32593
33032
  }
@@ -32597,8 +33036,12 @@ function assertIds(trackId, executionId, nodeId, phaseId) {
32597
33036
  if (!PHASE_ID.test(nodeId) && !TASK_ID.test(nodeId)) throw new Error("nodeId must be a phase or task ID");
32598
33037
  if (phaseId != null && !PHASE_ID.test(phaseId)) throw new Error("invalid phaseId");
32599
33038
  const task = nodeId.match(TASK_ID);
32600
- if (task && phaseId !== `P${task[1]}`) throw new Error(`${nodeId} does not belong to ${phaseId ?? "a phase"}`);
32601
- if (!task && phaseId != null) throw new Error("phase nodes must not supply phaseId");
33039
+ if (task && phaseId != null && phaseId !== `P${task[1]}`) throw new Error(`${nodeId} does not belong to ${phaseId}`);
33040
+ if (!task && phaseId != null && phaseId !== nodeId) throw new Error(`${nodeId} does not belong to ${phaseId}`);
33041
+ }
33042
+ function phaseForNode(nodeId) {
33043
+ const task = nodeId.match(TASK_ID);
33044
+ return task ? `P${task[1]}` : nodeId;
32602
33045
  }
32603
33046
  function nodeSlug(nodeId) {
32604
33047
  return nodeId.toLowerCase().replace(".", "-");
@@ -32606,9 +33049,10 @@ function nodeSlug(nodeId) {
32606
33049
  function worktreeIdentity(root, trackId, executionId, nodeId, phaseId) {
32607
33050
  assertIds(trackId, executionId, nodeId, phaseId);
32608
33051
  const task = TASK_ID.test(nodeId);
32609
- const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId}/tasks/${phaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId}/phases/${nodeId}`;
33052
+ const resolvedPhaseId = phaseForNode(nodeId);
33053
+ const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId}/tasks/${resolvedPhaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId}/phases/${nodeId}`;
32610
33054
  const branch = `cadre/${trackId}/${executionId}/${task ? "task" : "phase"}-${nodeSlug(nodeId)}`;
32611
- return { path: join5(root, relativePath), relativePath, branch };
33055
+ return { path: join6(root, relativePath), relativePath, branch };
32612
33056
  }
32613
33057
  function branchHead(root, branch) {
32614
33058
  const result2 = git(root, ["rev-parse", "--verify", `refs/heads/${branch}`], true);
@@ -32619,27 +33063,28 @@ function registeredWorktrees(root) {
32619
33063
  let current = {};
32620
33064
  for (const line of git(root, ["worktree", "list", "--porcelain"]).stdout.split(/\r?\n/)) {
32621
33065
  if (!line) {
32622
- if (current.path && current.head) records.push({ path: resolve6(current.path), branch: current.branch ?? null, head: current.head });
33066
+ if (current.path && current.head) records.push({ path: resolve8(current.path), branch: current.branch ?? null, head: current.head });
32623
33067
  current = {};
32624
33068
  } else if (line.startsWith("worktree ")) current.path = line.slice("worktree ".length);
32625
33069
  else if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length);
32626
33070
  else if (line.startsWith("branch refs/heads/")) current.branch = line.slice("branch refs/heads/".length);
32627
33071
  else if (line === "detached") current.branch = null;
32628
33072
  }
32629
- if (current.path && current.head) records.push({ path: resolve6(current.path), branch: current.branch ?? null, head: current.head });
33073
+ if (current.path && current.head) records.push({ path: resolve8(current.path), branch: current.branch ?? null, head: current.head });
32630
33074
  return records;
32631
33075
  }
32632
33076
  function previewWorktreeCreate(input) {
32633
33077
  const root = assertRepository(input.projectRoot);
32634
- const baseCommit = git(root, ["rev-parse", `${input.baseCommit}^{commit}`]).stdout.trim();
33078
+ const target = targetIdentity(root, input);
33079
+ const baseCommit = git(target.path, ["rev-parse", "HEAD^{commit}"]).stdout.trim();
32635
33080
  if (!SHA2.test(baseCommit)) throw new Error("baseCommit does not resolve to a commit");
32636
- const identity = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
32637
- const registered = registeredWorktrees(root).find((entry) => entry.path === resolve6(identity.path));
33081
+ const identity = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
33082
+ const registered = registeredWorktrees(root).find((entry) => entry.path === resolve8(identity.path));
32638
33083
  const existingBranchHead = branchHead(root, identity.branch);
32639
33084
  if (registered && (registered.branch !== identity.branch || registered.head !== existingBranchHead)) {
32640
33085
  throw new Error(`registered worktree disagrees at ${identity.relativePath}`);
32641
33086
  }
32642
- if (!registered && existsSync7(identity.path)) throw new Error(`unregistered path already exists: ${identity.path}`);
33087
+ if (!registered && existsSync8(identity.path)) throw new Error(`unregistered path already exists: ${identity.path}`);
32643
33088
  if (existingBranchHead) {
32644
33089
  const basedOnExpectedCommit = git(root, ["merge-base", "--is-ancestor", baseCommit, existingBranchHead], true).status === 0;
32645
33090
  if (!basedOnExpectedCommit) throw new Error(`existing branch ${identity.branch} is not based on requested base commit`);
@@ -32661,17 +33106,20 @@ function applyWorktreeCreate(input, proposalDigest) {
32661
33106
  git(proposal.projectRoot, args);
32662
33107
  return previewWorktreeCreate(input);
32663
33108
  }
32664
- function cleanWorktree(path) {
32665
- const status = git(path, ["status", "--porcelain"]).stdout.trim();
32666
- if (status) throw new Error(`worktree is not clean: ${path}
32667
- ${status}`);
33109
+ function cleanWorktree(path, allowedPaths = /* @__PURE__ */ new Set()) {
33110
+ const lines = git(path, ["status", "--porcelain", "--untracked-files=all"]).stdout.split(/\r?\n/).filter(Boolean);
33111
+ const unexpected = lines.filter((line) => {
33112
+ const changedPath = line.slice(3).split(" -> ").at(-1) ?? "";
33113
+ return !allowedPaths.has(changedPath);
33114
+ });
33115
+ if (unexpected.length) throw new Error(`worktree is not clean: ${path}
33116
+ ${unexpected.join("\n")}`);
32668
33117
  }
32669
33118
  function targetIdentity(root, input) {
32670
33119
  if (TASK_ID.test(input.nodeId)) {
32671
- const phaseId = input.phaseId;
32672
- if (!phaseId) throw new Error("task integration requires phaseId");
33120
+ const phaseId = phaseForNode(input.nodeId);
32673
33121
  const phase = worktreeIdentity(root, input.trackId, input.executionId, phaseId, null);
32674
- const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve6(phase.path));
33122
+ const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve8(phase.path));
32675
33123
  if (phaseWorktree) {
32676
33124
  if (phaseWorktree.branch !== phase.branch) throw new Error(`phase worktree is not on ${phase.branch}`);
32677
33125
  return { path: phase.path, branch: phase.branch };
@@ -32685,7 +33133,8 @@ function journalNode(input) {
32685
33133
  const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
32686
33134
  const node = journal.nodes[input.nodeId];
32687
33135
  if (!node) throw new Error(`execution journal has no node ${input.nodeId}`);
32688
- if (node.phaseId !== (input.phaseId ?? input.nodeId)) {
33136
+ assertIds(input.trackId, input.executionId, input.nodeId);
33137
+ if (node.phaseId !== phaseForNode(input.nodeId)) {
32689
33138
  throw new Error(`execution journal identity disagrees for ${input.nodeId}`);
32690
33139
  }
32691
33140
  return { node, nodes: journal.nodes };
@@ -32704,19 +33153,20 @@ function assertJournalAllowsIntegration(input) {
32704
33153
  }
32705
33154
  function assertJournalAllowsCleanup(input) {
32706
33155
  const { node } = journalNode(input);
32707
- if (node.status !== "integrated") {
32708
- throw new Error(`${input.nodeId} must be integrated in the execution journal before cleanup`);
33156
+ if (!["integrated", "completed"].includes(node.status)) {
33157
+ throw new Error(`${input.nodeId} must be integrated or completed in the execution journal before cleanup`);
32709
33158
  }
32710
33159
  }
32711
33160
  function previewWorktreeIntegration(input) {
32712
33161
  assertJournalAllowsIntegration(input);
32713
33162
  const root = assertRepository(input.projectRoot);
32714
- const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
33163
+ const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
32715
33164
  const target = targetIdentity(root, input);
32716
- if (!existsSync7(source.path)) throw new Error(`source worktree is missing: ${source.path}`);
32717
- if (!existsSync7(target.path)) throw new Error(`target worktree is missing: ${target.path}`);
33165
+ if (!existsSync8(source.path)) throw new Error(`source worktree is missing: ${source.path}`);
33166
+ if (!existsSync8(target.path)) throw new Error(`target worktree is missing: ${target.path}`);
32718
33167
  cleanWorktree(source.path);
32719
- cleanWorktree(target.path);
33168
+ const journalPath = `.cadre/tracks/${input.trackId}/executions/execution-${input.executionId}.json`;
33169
+ cleanWorktree(target.path, target.path === root ? /* @__PURE__ */ new Set([journalPath]) : /* @__PURE__ */ new Set());
32720
33170
  const checkedSource = git(source.path, ["symbolic-ref", "--short", "HEAD"]).stdout.trim();
32721
33171
  const checkedTarget = git(target.path, ["symbolic-ref", "--short", "HEAD"]).stdout.trim();
32722
33172
  if (checkedSource !== source.branch) throw new Error(`source worktree is on ${checkedSource}, expected ${source.branch}`);
@@ -32762,9 +33212,9 @@ function applyWorktreeIntegration(input, proposalDigest) {
32762
33212
  function previewWorktreeCleanup(input) {
32763
33213
  assertJournalAllowsCleanup(input);
32764
33214
  const root = assertRepository(input.projectRoot);
32765
- const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
33215
+ const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
32766
33216
  const target = targetIdentity(root, input);
32767
- if (!existsSync7(source.path)) throw new Error(`worktree is missing: ${source.path}`);
33217
+ if (!existsSync8(source.path)) throw new Error(`worktree is missing: ${source.path}`);
32768
33218
  if (lstatSync4(source.path).isSymbolicLink()) throw new Error("refusing to clean up a symbolic-link worktree");
32769
33219
  cleanWorktree(source.path);
32770
33220
  const head = git(source.path, ["rev-parse", "HEAD"]).stdout.trim();
@@ -32785,10 +33235,10 @@ function applyWorktreeCleanup(input, proposalDigest) {
32785
33235
  const root = assertRepository(input.projectRoot);
32786
33236
  git(root, ["worktree", "remove", proposal.path]);
32787
33237
  git(proposal.targetPath, ["branch", "-d", proposal.branch]);
32788
- const managedRoot = join5(root, ".cadre", ".worktrees");
33238
+ const managedRoot = join6(root, ".cadre", ".worktrees");
32789
33239
  let directory = dirname4(proposal.path);
32790
33240
  while (directory.startsWith(`${managedRoot}/`)) {
32791
- if (!existsSync7(directory) || readdirSync4(directory).length) break;
33241
+ if (!existsSync8(directory) || readdirSync5(directory).length) break;
32792
33242
  rmdirSync(directory);
32793
33243
  directory = dirname4(directory);
32794
33244
  }
@@ -32796,7 +33246,7 @@ function applyWorktreeCleanup(input, proposalDigest) {
32796
33246
  }
32797
33247
  function managedWorktreeStatus(projectRoot) {
32798
33248
  const root = assertRepository(projectRoot);
32799
- const managedRoot = join5(root, ".cadre", ".worktrees");
33249
+ const managedRoot = join6(root, ".cadre", ".worktrees");
32800
33250
  const worktrees = registeredWorktrees(root).map((entry) => ({
32801
33251
  ...entry,
32802
33252
  managed: relative3(managedRoot, entry.path) !== "" && !relative3(managedRoot, entry.path).startsWith("..")
@@ -32804,15 +33254,15 @@ function managedWorktreeStatus(projectRoot) {
32804
33254
  const registered = new Set(worktrees.filter((entry) => entry.managed).map((entry) => entry.path));
32805
33255
  const orphanedDirectories = [];
32806
33256
  function walk2(directory) {
32807
- if (!existsSync7(directory)) return;
32808
- if (registered.has(resolve6(directory))) return;
32809
- const entries = readdirSync4(directory, { withFileTypes: true });
33257
+ if (!existsSync8(directory)) return;
33258
+ if (registered.has(resolve8(directory))) return;
33259
+ const entries = readdirSync5(directory, { withFileTypes: true });
32810
33260
  if (entries.some((entry) => entry.name === ".git")) {
32811
33261
  orphanedDirectories.push(directory);
32812
33262
  return;
32813
33263
  }
32814
- for (const entry of entries) if (entry.isDirectory()) walk2(join5(directory, entry.name));
32815
- if (!entries.length && resolve6(directory) !== resolve6(managedRoot)) orphanedDirectories.push(directory);
33264
+ for (const entry of entries) if (entry.isDirectory()) walk2(join6(directory, entry.name));
33265
+ if (!entries.length && resolve8(directory) !== resolve8(managedRoot)) orphanedDirectories.push(directory);
32816
33266
  }
32817
33267
  walk2(managedRoot);
32818
33268
  return { worktrees, orphanedDirectories };
@@ -32821,15 +33271,15 @@ function managedWorktreeStatus(projectRoot) {
32821
33271
  // src/domain/governance.ts
32822
33272
  import { createHash as createHash7 } from "node:crypto";
32823
33273
  import {
32824
- existsSync as existsSync8,
33274
+ existsSync as existsSync9,
32825
33275
  lstatSync as lstatSync5,
32826
33276
  mkdirSync as mkdirSync3,
32827
- readFileSync as readFileSync6,
32828
- readdirSync as readdirSync5,
33277
+ readFileSync as readFileSync7,
33278
+ readdirSync as readdirSync6,
32829
33279
  renameSync as renameSync3,
32830
33280
  writeFileSync as writeFileSync4
32831
33281
  } from "node:fs";
32832
- import { dirname as dirname5, join as join6, relative as relative4 } from "node:path";
33282
+ import { dirname as dirname5, join as join7, relative as relative4 } from "node:path";
32833
33283
  var SHA3 = /^[0-9a-f]{7,40}$/;
32834
33284
  var TRACK_ID3 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32835
33285
  var BATCH_ID = /^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
@@ -32841,7 +33291,7 @@ function json2(value) {
32841
33291
  `;
32842
33292
  }
32843
33293
  function assertWritableFile(path) {
32844
- if (existsSync8(path) && lstatSync5(path).isSymbolicLink()) {
33294
+ if (existsSync9(path) && lstatSync5(path).isSymbolicLink()) {
32845
33295
  throw new Error(`refusing to write through symbolic link ${path}`);
32846
33296
  }
32847
33297
  }
@@ -32856,6 +33306,25 @@ function requireCurrentProject(projectRoot) {
32856
33306
  if (!validation.project) throw new Error("Cadre project state is unavailable");
32857
33307
  return validation;
32858
33308
  }
33309
+ function deriveReviewCompleteInput(input) {
33310
+ const validation = requireCurrentProject(input.projectRoot);
33311
+ const state = validation.states.get(input.trackId);
33312
+ const reviewedHead = state?.lastExecution?.headCommit;
33313
+ if (!reviewedHead || !SHA3.test(reviewedHead)) throw new Error(`${input.trackId} has no completed execution head`);
33314
+ if (!isGitAncestor(input.projectRoot, reviewedHead)) {
33315
+ throw new Error(`completed execution head ${reviewedHead} is not an ancestor of current HEAD`);
33316
+ }
33317
+ const commitRangeStart = resolveGitCommit(input.projectRoot, input.commitRangeStart);
33318
+ return {
33319
+ projectRoot: input.projectRoot,
33320
+ trackId: input.trackId,
33321
+ reviewedAt: (/* @__PURE__ */ new Date()).toISOString(),
33322
+ reviewedHead,
33323
+ commitRange: `${commitRangeStart}..${reviewedHead}`,
33324
+ approval: input.approval,
33325
+ ...input.acceptedRisks ? { acceptedRisks: input.acceptedRisks } : {}
33326
+ };
33327
+ }
32859
33328
  function previewReviewComplete(input) {
32860
33329
  if (!TRACK_ID3.test(input.trackId)) throw new Error("invalid trackId");
32861
33330
  if (!SHA3.test(input.reviewedHead)) throw new Error("reviewedHead must be a Git commit SHA");
@@ -32878,10 +33347,10 @@ function previewReviewComplete(input) {
32878
33347
  if (!execution?.executionId || !execution.planRevision || !execution.graphDigest || execution.headCommit !== input.reviewedHead) {
32879
33348
  throw new Error("review evidence does not match the current completed execution");
32880
33349
  }
32881
- const statePath = join6(cadreRoot(root), track.location, "state.json");
32882
- const tracksPath = join6(cadreRoot(root), "tracks.md");
32883
- const stateBody = readFileSync6(statePath, "utf8");
32884
- const tracksBody = readFileSync6(tracksPath, "utf8");
33350
+ const statePath = join7(cadreRoot(root), track.location, "state.json");
33351
+ const tracksPath = join7(cadreRoot(root), "tracks.md");
33352
+ const stateBody = readFileSync7(statePath, "utf8");
33353
+ const tracksBody = readFileSync7(tracksPath, "utf8");
32885
33354
  const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
32886
33355
  const cycle = {
32887
33356
  cycle: (current.reviewCycles?.length ?? 0) + 1,
@@ -32922,6 +33391,59 @@ function applyReviewComplete(input, proposalDigest) {
32922
33391
  }
32923
33392
  return { ...proposal, valid: true, derivedStateCurrent: true };
32924
33393
  }
33394
+ function dependencyOrder(tracks) {
33395
+ const included = new Set(tracks.map((track) => track.id));
33396
+ const byId = new Map(tracks.map((track) => [track.id, track]));
33397
+ const ordered = [];
33398
+ const visiting = /* @__PURE__ */ new Set();
33399
+ const visited = /* @__PURE__ */ new Set();
33400
+ const visit = (trackId) => {
33401
+ if (visited.has(trackId)) return;
33402
+ if (visiting.has(trackId)) throw new Error(`track dependency cycle includes ${trackId}`);
33403
+ visiting.add(trackId);
33404
+ for (const dependency of byId.get(trackId)?.dependencies ?? []) {
33405
+ if (included.has(dependency)) visit(dependency);
33406
+ }
33407
+ visiting.delete(trackId);
33408
+ visited.add(trackId);
33409
+ ordered.push(trackId);
33410
+ };
33411
+ for (const track of tracks) visit(track.id);
33412
+ return ordered;
33413
+ }
33414
+ function deriveArchiveBatchInput(input) {
33415
+ const root = safeProjectRoot(input.projectRoot);
33416
+ const validation = requireCurrentProject(root);
33417
+ const operationsPath = join7(cadreRoot(root), "operations");
33418
+ const activeOperation = existsSync9(operationsPath) ? readdirSync6(operationsPath).filter((file2) => file2.endsWith(".json")).map(
33419
+ (file2) => JSON.parse(readFileSync7(join7(operationsPath, file2), "utf8"))
33420
+ ).find((operation) => operation.action === "archive" && operation.status === "in_progress") : void 0;
33421
+ const selectedTracks = input.selectedTracks?.length ? [...new Set(input.selectedTracks)] : activeOperation?.selectedTracks ?? dependencyOrder(
33422
+ validation.tracks.filter((track) => track.status === "completed" && track.location === `tracks/${track.id}`)
33423
+ );
33424
+ if (!selectedTracks.length) throw new Error("there are no completed tracks to archive");
33425
+ if (activeOperation && JSON.stringify(selectedTracks) !== JSON.stringify(activeOperation.selectedTracks)) {
33426
+ throw new Error(`active archive batch ${activeOperation.batchId} must be resumed with its original selection`);
33427
+ }
33428
+ const now = (/* @__PURE__ */ new Date()).toISOString();
33429
+ const updates = input.updates.map((update) => {
33430
+ if (update.kind === "pattern") {
33431
+ if (!TRACK_ID3.test(update.slug)) throw new Error(`invalid pattern slug ${update.slug}`);
33432
+ return { path: `patterns/${update.slug}.md`, content: update.content };
33433
+ }
33434
+ if (update.kind === "pattern_index") return { path: "patterns/index.md", content: update.content };
33435
+ if (!TRACK_ID3.test(update.trackId)) throw new Error(`invalid active track ID ${update.trackId}`);
33436
+ return { path: `tracks/${update.trackId}/learning.md`, content: update.content };
33437
+ });
33438
+ return {
33439
+ projectRoot: root,
33440
+ batchId: activeOperation?.batchId ?? `archive-${now.replace(/[:.]/g, "-")}`,
33441
+ selectedTracks,
33442
+ baseCommit: activeOperation?.baseCommit ?? resolveGitCommit(root),
33443
+ approvedAt: activeOperation?.approvedAt ?? now,
33444
+ updates
33445
+ };
33446
+ }
32925
33447
  function assertArchiveUpdate(path, selected) {
32926
33448
  if (path === "patterns/index.md" || /^patterns\/[a-z0-9]+(?:-[a-z0-9]+)*\.md$/.test(path)) return;
32927
33449
  const seed = path.match(/^tracks\/([a-z0-9]+(?:-[a-z0-9]+)*)\/learning\.md$/);
@@ -32931,11 +33453,11 @@ function assertArchiveUpdate(path, selected) {
32931
33453
  function directorySnapshot(path) {
32932
33454
  const files = [];
32933
33455
  function visit(directory) {
32934
- for (const entry of readdirSync5(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
32935
- const target = join6(directory, entry.name);
33456
+ for (const entry of readdirSync6(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
33457
+ const target = join7(directory, entry.name);
32936
33458
  if (entry.isSymbolicLink()) throw new Error(`refusing archive source symbolic link ${target}`);
32937
33459
  if (entry.isDirectory()) visit(target);
32938
- else if (entry.isFile()) files.push({ path: relative4(path, target), content: readFileSync6(target, "utf8") });
33460
+ else if (entry.isFile()) files.push({ path: relative4(path, target), content: readFileSync7(target, "utf8") });
32939
33461
  else throw new Error(`unsupported archive source entry ${target}`);
32940
33462
  }
32941
33463
  }
@@ -32951,8 +33473,8 @@ function previewArchiveBatch(input) {
32951
33473
  }
32952
33474
  if (input.selectedTracks.some((trackId) => !TRACK_ID3.test(trackId))) throw new Error("invalid selected track ID");
32953
33475
  const root = safeProjectRoot(input.projectRoot);
32954
- const operationPath = join6(cadreRoot(root), "operations", `${input.batchId}.json`);
32955
- const existingOperation = existsSync8(operationPath) ? JSON.parse(readFileSync6(operationPath, "utf8")) : null;
33476
+ const operationPath = join7(cadreRoot(root), "operations", `${input.batchId}.json`);
33477
+ const existingOperation = existsSync9(operationPath) ? JSON.parse(readFileSync7(operationPath, "utf8")) : null;
32956
33478
  if (existingOperation && (existingOperation.action !== "archive" || existingOperation.status !== "in_progress" || existingOperation.baseCommit !== input.baseCommit || JSON.stringify(existingOperation.selectedTracks) !== JSON.stringify(input.selectedTracks))) {
32957
33479
  throw new Error(`archive batch ${input.batchId} does not match the approved input`);
32958
33480
  }
@@ -32973,9 +33495,9 @@ function previewArchiveBatch(input) {
32973
33495
  if (existingOperation && existingOperation.approvalDigest !== approvalDigest) {
32974
33496
  throw new Error(`archive batch ${input.batchId} content differs from its approved journal`);
32975
33497
  }
32976
- const activeOperations = join6(cadreRoot(root), "operations");
32977
- const unfinished = existsSync8(activeOperations) ? readdirSync5(activeOperations).filter((file2) => file2.endsWith(".json")).find((file2) => {
32978
- const operation2 = JSON.parse(readFileSync6(join6(activeOperations, file2), "utf8"));
33498
+ const activeOperations = join7(cadreRoot(root), "operations");
33499
+ const unfinished = existsSync9(activeOperations) ? readdirSync6(activeOperations).filter((file2) => file2.endsWith(".json")).find((file2) => {
33500
+ const operation2 = JSON.parse(readFileSync7(join7(activeOperations, file2), "utf8"));
32979
33501
  return operation2.status === "in_progress";
32980
33502
  }) : void 0;
32981
33503
  if (unfinished && unfinished !== `${input.batchId}.json`) {
@@ -32990,9 +33512,9 @@ function previewArchiveBatch(input) {
32990
33512
  if (!pending && !completed || state.operation != null) {
32991
33513
  throw new Error(`${trackId} is not an eligible completed track`);
32992
33514
  }
32993
- const sourcePath = join6(cadreRoot(root), pending ? "tracks" : "archive", trackId);
32994
- const targetPath = join6(cadreRoot(root), "archive", trackId);
32995
- if (pending && existsSync8(targetPath)) throw new Error(`archive target already exists for ${trackId}`);
33515
+ const sourcePath = join7(cadreRoot(root), pending ? "tracks" : "archive", trackId);
33516
+ const targetPath = join7(cadreRoot(root), "archive", trackId);
33517
+ if (pending && existsSync9(targetPath)) throw new Error(`archive target already exists for ${trackId}`);
32996
33518
  return { trackId, sourcePath, targetPath, state: { ...state, status: "archived" }, needsMove: pending };
32997
33519
  });
32998
33520
  const proposedTracks = validation.tracks.map((track) => selected.has(track.id) ? { ...track, status: "archived", location: `archive/${track.id}` } : track);
@@ -33024,12 +33546,12 @@ function previewArchiveBatch(input) {
33024
33546
  artifactProgress: [...moveArtifacts, ...updateArtifacts, "tracks.md"]
33025
33547
  };
33026
33548
  const current = {
33027
- project: readFileSync6(join6(cadreRoot(root), "project.json"), "utf8"),
33028
- tracks: readFileSync6(join6(cadreRoot(root), "tracks.md"), "utf8"),
33549
+ project: readFileSync7(join7(cadreRoot(root), "project.json"), "utf8"),
33550
+ tracks: readFileSync7(join7(cadreRoot(root), "tracks.md"), "utf8"),
33029
33551
  sources: moves.map((move) => ({ trackId: move.trackId, files: directorySnapshot(move.sourcePath) })),
33030
33552
  updates: updates.map((update) => ({
33031
33553
  path: update.path,
33032
- content: existsSync8(join6(cadreRoot(root), update.path)) ? readFileSync6(join6(cadreRoot(root), update.path), "utf8") : null
33554
+ content: existsSync9(join7(cadreRoot(root), update.path)) ? readFileSync7(join7(cadreRoot(root), update.path), "utf8") : null
33033
33555
  }))
33034
33556
  };
33035
33557
  return {
@@ -33038,7 +33560,7 @@ function previewArchiveBatch(input) {
33038
33560
  operation,
33039
33561
  moves,
33040
33562
  writes: updates,
33041
- tracksPath: join6(cadreRoot(root), "tracks.md"),
33563
+ tracksPath: join7(cadreRoot(root), "tracks.md"),
33042
33564
  tracksContent,
33043
33565
  resuming: existingOperation != null,
33044
33566
  digest: hash5({ current, input, initialOperation, operation, moves: moves.map(({ trackId, state, needsMove }) => ({ trackId, state, needsMove })), updates, tracksContent })
@@ -33047,14 +33569,14 @@ function previewArchiveBatch(input) {
33047
33569
  function applyArchiveBatch(input, proposalDigest) {
33048
33570
  const proposal = previewArchiveBatch(input);
33049
33571
  if (proposal.digest !== proposalDigest) throw new Error("archive batch proposal is stale; preview it again");
33050
- const currentOperation = existsSync8(proposal.operationPath) ? JSON.parse(readFileSync6(proposal.operationPath, "utf8")) : proposal.initialOperation;
33051
- if (!existsSync8(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json2(currentOperation));
33052
- mkdirSync3(join6(cadreRoot(input.projectRoot), "archive"), { recursive: true });
33572
+ const currentOperation = existsSync9(proposal.operationPath) ? JSON.parse(readFileSync7(proposal.operationPath, "utf8")) : proposal.initialOperation;
33573
+ if (!existsSync9(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json2(currentOperation));
33574
+ mkdirSync3(join7(cadreRoot(input.projectRoot), "archive"), { recursive: true });
33053
33575
  const completedTracks = new Set(currentOperation.completedTracks);
33054
33576
  const artifactProgress = new Set(currentOperation.artifactProgress);
33055
33577
  for (const move of proposal.moves) {
33056
33578
  if (move.needsMove) renameSync3(move.sourcePath, move.targetPath);
33057
- writeApprovedFile(join6(move.targetPath, "state.json"), json2(move.state));
33579
+ writeApprovedFile(join7(move.targetPath, "state.json"), json2(move.state));
33058
33580
  completedTracks.add(move.trackId);
33059
33581
  artifactProgress.add(`archive/${move.trackId}`);
33060
33582
  writeApprovedFile(proposal.operationPath, json2({
@@ -33064,7 +33586,7 @@ function applyArchiveBatch(input, proposalDigest) {
33064
33586
  }));
33065
33587
  }
33066
33588
  for (const update of proposal.writes) {
33067
- writeApprovedFile(join6(cadreRoot(input.projectRoot), update.path), update.content);
33589
+ writeApprovedFile(join7(cadreRoot(input.projectRoot), update.path), update.content);
33068
33590
  artifactProgress.add(update.path);
33069
33591
  writeApprovedFile(proposal.operationPath, json2({
33070
33592
  ...currentOperation,
@@ -33080,22 +33602,25 @@ function applyArchiveBatch(input, proposalDigest) {
33080
33602
  }
33081
33603
  return { ...proposal, valid: true, derivedStateCurrent: true };
33082
33604
  }
33605
+ function deriveArchiveBatchRecordInput(input) {
33606
+ return { ...input, archiveCommit: resolveGitCommit(input.projectRoot) };
33607
+ }
33083
33608
  function previewArchiveBatchRecord(input) {
33084
33609
  if (!BATCH_ID.test(input.batchId)) throw new Error("invalid archive batchId");
33085
33610
  if (!SHA3.test(input.archiveCommit)) throw new Error("archiveCommit must be a Git commit SHA");
33086
33611
  const root = safeProjectRoot(input.projectRoot);
33087
- const operationPath = join6(cadreRoot(root), "operations", `${input.batchId}.json`);
33088
- const operationBody = readFileSync6(operationPath, "utf8");
33612
+ const operationPath = join7(cadreRoot(root), "operations", `${input.batchId}.json`);
33613
+ const operationBody = readFileSync7(operationPath, "utf8");
33089
33614
  const currentOperation = JSON.parse(operationBody);
33090
33615
  if (currentOperation.action !== "archive" || currentOperation.status !== "in_progress") {
33091
33616
  throw new Error(`${input.batchId} is not an in-progress archive batch`);
33092
33617
  }
33093
- const projectPath = join6(cadreRoot(root), "project.json");
33094
- const projectBody = readFileSync6(projectPath, "utf8");
33618
+ const projectPath = join7(cadreRoot(root), "project.json");
33619
+ const projectBody = readFileSync7(projectPath, "utf8");
33095
33620
  const currentProject = JSON.parse(projectBody);
33096
33621
  const states = currentOperation.selectedTracks.map((trackId) => {
33097
- const path = join6(cadreRoot(root), "archive", trackId, "state.json");
33098
- const body = readFileSync6(path, "utf8");
33622
+ const path = join7(cadreRoot(root), "archive", trackId, "state.json");
33623
+ const body = readFileSync7(path, "utf8");
33099
33624
  const current = JSON.parse(body);
33100
33625
  if (current.status !== "archived") throw new Error(`${trackId} is not archived`);
33101
33626
  return {
@@ -33149,6 +33674,255 @@ function applyArchiveBatchRecord(input, proposalDigest) {
33149
33674
  return { ...proposal, valid: true, derivedStateCurrent: true };
33150
33675
  }
33151
33676
 
33677
+ // src/mcp/elicitation.ts
33678
+ var FIELD_ID = /^[a-z][a-z0-9_]{0,39}$/;
33679
+ var MAX_MESSAGE_LENGTH = 2e3;
33680
+ var MAX_DESCRIPTION_LENGTH = 400;
33681
+ var MAX_TEXT_LENGTH = 4e3;
33682
+ var choiceSchema = external_exports.object({
33683
+ value: external_exports.string().min(1).max(120),
33684
+ label: external_exports.string().min(1).max(120)
33685
+ });
33686
+ var questionBase = {
33687
+ id: external_exports.string().regex(FIELD_ID),
33688
+ label: external_exports.string().min(1).max(120),
33689
+ description: external_exports.string().max(MAX_DESCRIPTION_LENGTH).optional(),
33690
+ required: external_exports.boolean().optional()
33691
+ };
33692
+ var workflowQuestionSchema = external_exports.discriminatedUnion("type", [
33693
+ external_exports.object({
33694
+ ...questionBase,
33695
+ type: external_exports.literal("text"),
33696
+ default: external_exports.string().max(MAX_TEXT_LENGTH).optional()
33697
+ }),
33698
+ external_exports.object({
33699
+ ...questionBase,
33700
+ type: external_exports.literal("boolean"),
33701
+ default: external_exports.boolean().optional()
33702
+ }),
33703
+ external_exports.object({
33704
+ ...questionBase,
33705
+ type: external_exports.literal("number"),
33706
+ minimum: external_exports.number().optional(),
33707
+ maximum: external_exports.number().optional(),
33708
+ default: external_exports.number().optional()
33709
+ }),
33710
+ external_exports.object({
33711
+ ...questionBase,
33712
+ type: external_exports.literal("integer"),
33713
+ minimum: external_exports.number().int().optional(),
33714
+ maximum: external_exports.number().int().optional(),
33715
+ default: external_exports.number().int().optional()
33716
+ }),
33717
+ external_exports.object({
33718
+ ...questionBase,
33719
+ type: external_exports.literal("single_select"),
33720
+ options: external_exports.array(choiceSchema).min(2).max(10),
33721
+ default: external_exports.string().max(120).optional()
33722
+ }),
33723
+ external_exports.object({
33724
+ ...questionBase,
33725
+ type: external_exports.literal("multi_select"),
33726
+ options: external_exports.array(choiceSchema).min(2).max(10),
33727
+ minSelections: external_exports.number().int().min(0).optional(),
33728
+ maxSelections: external_exports.number().int().min(1).optional(),
33729
+ default: external_exports.array(external_exports.string().max(120)).max(10).optional()
33730
+ })
33731
+ ]);
33732
+ var workflowElicitationInputSchema = {
33733
+ kind: external_exports.enum(["approval", "clarification"]),
33734
+ message: external_exports.string().min(1).max(MAX_MESSAGE_LENGTH),
33735
+ binding: external_exports.string().min(1).max(240).optional(),
33736
+ questions: external_exports.array(workflowQuestionSchema).max(3).optional()
33737
+ };
33738
+ function assertUnique(values, message) {
33739
+ if (new Set(values).size !== values.length) throw new Error(message);
33740
+ }
33741
+ function choiceValues(question) {
33742
+ const values = question.options.map((option) => option.value);
33743
+ assertUnique(values, `${question.id} option values must be unique`);
33744
+ return values;
33745
+ }
33746
+ function questionSchema(question) {
33747
+ const common = {
33748
+ title: question.label,
33749
+ ...question.description ? { description: question.description } : {}
33750
+ };
33751
+ switch (question.type) {
33752
+ case "text":
33753
+ return {
33754
+ ...common,
33755
+ type: "string",
33756
+ ...question.required ? { minLength: 1 } : {},
33757
+ maxLength: MAX_TEXT_LENGTH,
33758
+ ...question.default === void 0 ? {} : { default: question.default }
33759
+ };
33760
+ case "boolean":
33761
+ return {
33762
+ ...common,
33763
+ type: "boolean",
33764
+ ...question.default === void 0 ? {} : { default: question.default }
33765
+ };
33766
+ case "number":
33767
+ case "integer": {
33768
+ if (question.minimum !== void 0 && question.maximum !== void 0 && question.minimum > question.maximum) {
33769
+ throw new Error(`${question.id} minimum cannot exceed maximum`);
33770
+ }
33771
+ if (question.default !== void 0 && (question.minimum !== void 0 && question.default < question.minimum || question.maximum !== void 0 && question.default > question.maximum)) {
33772
+ throw new Error(`${question.id} default must be within its numeric bounds`);
33773
+ }
33774
+ return {
33775
+ ...common,
33776
+ type: question.type,
33777
+ ...question.minimum === void 0 ? {} : { minimum: question.minimum },
33778
+ ...question.maximum === void 0 ? {} : { maximum: question.maximum },
33779
+ ...question.default === void 0 ? {} : { default: question.default }
33780
+ };
33781
+ }
33782
+ case "single_select": {
33783
+ const values = choiceValues(question);
33784
+ if (question.default !== void 0 && !values.includes(question.default)) {
33785
+ throw new Error(`${question.id} default must match an option value`);
33786
+ }
33787
+ return {
33788
+ ...common,
33789
+ type: "string",
33790
+ oneOf: question.options.map((option) => ({ const: option.value, title: option.label })),
33791
+ ...question.default === void 0 ? {} : { default: question.default }
33792
+ };
33793
+ }
33794
+ case "multi_select": {
33795
+ const values = choiceValues(question);
33796
+ const minimum = question.minSelections ?? (question.required ? 1 : 0);
33797
+ const maximum = question.maxSelections ?? values.length;
33798
+ if (minimum > maximum || maximum > values.length) {
33799
+ throw new Error(`${question.id} selection bounds are invalid`);
33800
+ }
33801
+ if (question.default?.some((value) => !values.includes(value))) {
33802
+ throw new Error(`${question.id} defaults must match option values`);
33803
+ }
33804
+ return {
33805
+ ...common,
33806
+ type: "array",
33807
+ items: {
33808
+ anyOf: question.options.map((option) => ({ const: option.value, title: option.label }))
33809
+ },
33810
+ minItems: minimum,
33811
+ maxItems: maximum,
33812
+ ...question.default === void 0 ? {} : { default: question.default }
33813
+ };
33814
+ }
33815
+ }
33816
+ }
33817
+ function supportsFormElicitation(capabilities) {
33818
+ const elicitation = capabilities?.elicitation;
33819
+ if (!elicitation) return false;
33820
+ return elicitation.form !== void 0 || elicitation.url === void 0;
33821
+ }
33822
+ function buildWorkflowElicitation(input) {
33823
+ if (input.kind === "approval") {
33824
+ if (!input.binding) throw new Error("approval elicitation requires a proposal or checkpoint binding");
33825
+ if (input.questions?.length) throw new Error("approval elicitation uses the fixed decision form");
33826
+ return {
33827
+ mode: "form",
33828
+ message: `${input.message}
33829
+
33830
+ Approval binding: ${input.binding}`,
33831
+ requestedSchema: {
33832
+ type: "object",
33833
+ properties: {
33834
+ decision: {
33835
+ type: "string",
33836
+ title: "Decision",
33837
+ description: "Approve the bound proposal, request changes, or cancel.",
33838
+ oneOf: [
33839
+ { const: "approve", title: "Approve" },
33840
+ { const: "request_changes", title: "Request changes" },
33841
+ { const: "cancel", title: "Cancel" }
33842
+ ],
33843
+ default: "approve"
33844
+ },
33845
+ notes: {
33846
+ type: "string",
33847
+ title: "Notes",
33848
+ description: "Optional changes, exceptions, or verification notes.",
33849
+ maxLength: MAX_TEXT_LENGTH
33850
+ }
33851
+ },
33852
+ required: ["decision"]
33853
+ }
33854
+ };
33855
+ }
33856
+ const questions = input.questions ?? [];
33857
+ if (!questions.length) throw new Error("clarification elicitation requires at least one question");
33858
+ assertUnique(questions.map((question) => question.id), "clarification question IDs must be unique");
33859
+ return {
33860
+ mode: "form",
33861
+ message: input.message,
33862
+ requestedSchema: {
33863
+ type: "object",
33864
+ properties: Object.fromEntries(questions.map((question) => [question.id, questionSchema(question)])),
33865
+ required: questions.filter((question) => question.required).map((question) => question.id)
33866
+ }
33867
+ };
33868
+ }
33869
+ function fallbackWorkflowElicitation(input, reason) {
33870
+ return {
33871
+ kind: input.kind,
33872
+ status: "fallback_required",
33873
+ ...input.binding ? { binding: input.binding } : {},
33874
+ fallback: `${reason}. Ask the same concise question once in chat; do not retry the form.`
33875
+ };
33876
+ }
33877
+ function normalizeWorkflowElicitation(input, elicited) {
33878
+ if (elicited.action === "decline") {
33879
+ return { kind: input.kind, status: "declined", ...input.binding ? { binding: input.binding } : {} };
33880
+ }
33881
+ if (elicited.action === "cancel") {
33882
+ return { kind: input.kind, status: "cancelled", ...input.binding ? { binding: input.binding } : {} };
33883
+ }
33884
+ const answers = elicited.content ?? {};
33885
+ if (input.kind === "clarification") {
33886
+ return { kind: input.kind, status: "answered", answers };
33887
+ }
33888
+ const decision = answers.decision;
33889
+ const status = decision === "approve" ? "approved" : decision === "request_changes" ? "changes_requested" : "cancelled";
33890
+ return {
33891
+ kind: input.kind,
33892
+ status,
33893
+ ...input.binding ? { binding: input.binding } : {},
33894
+ answers
33895
+ };
33896
+ }
33897
+
33898
+ // src/mcp/proposals.ts
33899
+ import { gunzipSync, gzipSync } from "node:zlib";
33900
+ var MAX_TOKEN_CHARACTERS = 2 * 1024 * 1024;
33901
+ var MAX_PROPOSAL_BYTES = 8 * 1024 * 1024;
33902
+ var envelopeSchema = external_exports.object({
33903
+ version: external_exports.literal(1),
33904
+ kind: external_exports.string().min(1),
33905
+ input: external_exports.unknown(),
33906
+ digest: external_exports.string().regex(/^[0-9a-f]{64}$/)
33907
+ });
33908
+ var proposalTokenSchema = external_exports.string().min(1).max(MAX_TOKEN_CHARACTERS);
33909
+ function encodeProposalToken(kind, input, digest) {
33910
+ return gzipSync(JSON.stringify({ version: 1, kind, input, digest })).toString("base64url");
33911
+ }
33912
+ function decodeProposalToken(kind, token) {
33913
+ if (token.length > MAX_TOKEN_CHARACTERS) throw new Error("proposal token is too large");
33914
+ let value;
33915
+ try {
33916
+ const compressed = Buffer.from(token, "base64url");
33917
+ value = JSON.parse(gunzipSync(compressed, { maxOutputLength: MAX_PROPOSAL_BYTES }).toString("utf8"));
33918
+ } catch (error51) {
33919
+ throw new Error(`invalid proposal token: ${error51 instanceof Error ? error51.message : String(error51)}`);
33920
+ }
33921
+ const envelope = envelopeSchema.parse(value);
33922
+ if (envelope.kind !== kind) throw new Error(`proposal token is for ${envelope.kind}, not ${kind}`);
33923
+ return { input: envelope.input, digest: envelope.digest };
33924
+ }
33925
+
33152
33926
  // src/mcp/server.ts
33153
33927
  function result(value, summary) {
33154
33928
  return {
@@ -33156,13 +33930,24 @@ function result(value, summary) {
33156
33930
  structuredContent: value
33157
33931
  };
33158
33932
  }
33933
+ function proposalResult(kind, input, value) {
33934
+ return result({
33935
+ ...value,
33936
+ proposalToken: encodeProposalToken(kind, input, value.digest)
33937
+ });
33938
+ }
33939
+ function proposalInputSchema() {
33940
+ return { proposalToken: proposalTokenSchema };
33941
+ }
33159
33942
  function failure(error51) {
33943
+ const serialized = serializeCadreError(error51);
33160
33944
  return {
33161
33945
  isError: true,
33162
33946
  content: [{
33163
33947
  type: "text",
33164
- text: error51 instanceof Error ? error51.message : String(error51)
33165
- }]
33948
+ text: serialized.message
33949
+ }],
33950
+ structuredContent: { error: serialized }
33166
33951
  };
33167
33952
  }
33168
33953
  function serializableValidation(validation) {
@@ -33193,12 +33978,34 @@ function createCadreServer() {
33193
33978
  "Cadre provides deterministic, versioned templates and narrow project-state operations.",
33194
33979
  "Read every existing artifact before proposing edits. Never infer file contents.",
33195
33980
  "For any mutation, present the complete proposed artifacts to the human and obtain approval first.",
33196
- "Call a preview tool immediately before its matching apply tool and pass the returned digest unchanged.",
33981
+ "Use workflow_elicit for concise approval or clarification forms when supported. When active task context reports a non-interactive approval policy such as Codex Full Access, skip the form and ask one short chat question.",
33982
+ "Call a preview tool immediately before its matching apply tool and pass only the returned proposal token.",
33197
33983
  "Cadre state is resumable: inspect project_status once at command entry and reserve state_validate for final mutation gates.",
33198
33984
  "The plan is the implementation source of truth. Cadre MCP exposes only constrained, digest-gated Git worktree operations and never approves its own changes."
33199
33985
  ].join(" ")
33200
33986
  }
33201
33987
  );
33988
+ server.registerTool("workflow_elicit", {
33989
+ title: "Collect Cadre workflow input",
33990
+ description: "Present one client-native Cadre approval or clarification form. This read-only tool never grants approval or mutates state. Do not call it when active task context reports approval policy never, including Codex Full Access; ask one short chat question instead. Otherwise bind approval forms to the current proposal digest or immutable verification checkpoint, never request secrets, and use its chat fallback exactly once when form elicitation is unavailable.",
33991
+ inputSchema: workflowElicitationInputSchema,
33992
+ annotations: { readOnlyHint: true, openWorldHint: false }
33993
+ }, async (input) => {
33994
+ let request;
33995
+ try {
33996
+ request = buildWorkflowElicitation(input);
33997
+ } catch (error51) {
33998
+ return failure(error51);
33999
+ }
34000
+ if (!supportsFormElicitation(server.server.getClientCapabilities())) {
34001
+ return result(fallbackWorkflowElicitation(input, "The MCP client does not support form elicitation"));
34002
+ }
34003
+ try {
34004
+ return result(normalizeWorkflowElicitation(input, await server.server.elicitInput(request)));
34005
+ } catch {
34006
+ return result(fallbackWorkflowElicitation(input, "The MCP client or its active policy rejected form elicitation"));
34007
+ }
34008
+ });
33202
34009
  for (const template of templateCatalog()) {
33203
34010
  server.registerResource(
33204
34011
  `template-${template.id.replaceAll("/", "-")}`,
@@ -33222,7 +34029,7 @@ function createCadreServer() {
33222
34029
  server.registerTool("template_get", {
33223
34030
  title: "Get a Cadre template",
33224
34031
  description: "Read one immutable, versioned Cadre template by logical identifier.",
33225
- inputSchema: { id: external_exports.string().min(1) },
34032
+ inputSchema: { id: external_exports.enum(TEMPLATE_IDS) },
33226
34033
  annotations: { readOnlyHint: true, openWorldHint: false }
33227
34034
  }, async ({ id }) => {
33228
34035
  try {
@@ -33234,7 +34041,7 @@ function createCadreServer() {
33234
34041
  server.registerTool("template_get_many", {
33235
34042
  title: "Get multiple Cadre templates",
33236
34043
  description: "Read an ordered set of immutable, versioned Cadre templates in one call.",
33237
- inputSchema: { ids: external_exports.array(external_exports.string().min(1)).min(1) },
34044
+ inputSchema: { ids: external_exports.array(external_exports.enum(TEMPLATE_IDS)).min(1) },
33238
34045
  annotations: { readOnlyHint: true, openWorldHint: false }
33239
34046
  }, async ({ ids }) => {
33240
34047
  try {
@@ -33291,9 +34098,9 @@ function createCadreServer() {
33291
34098
  }, async ({ projectRoot, trackId }) => {
33292
34099
  try {
33293
34100
  const root = safeProjectRoot(projectRoot);
33294
- const statePath = join7(root, ".cadre", "tracks", trackId, "state.json");
33295
- const planPath = join7(root, ".cadre", "tracks", trackId, "plan.md");
33296
- const state = JSON.parse(readFileSync7(statePath, "utf8"));
34101
+ const statePath = join8(root, ".cadre", "tracks", trackId, "state.json");
34102
+ const planPath = join8(root, ".cadre", "tracks", trackId, "plan.md");
34103
+ const state = JSON.parse(readFileSync8(statePath, "utf8"));
33297
34104
  const errors = [];
33298
34105
  const graph = parsePlan(planPath, errors);
33299
34106
  validatePlanGraph(planPath, graph, state.status ?? "planned", errors);
@@ -33325,9 +34132,7 @@ function createCadreServer() {
33325
34132
  const reviewCompleteSchema = {
33326
34133
  projectRoot: external_exports.string().min(1),
33327
34134
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33328
- reviewedAt: external_exports.iso.datetime(),
33329
- reviewedHead: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33330
- commitRange: external_exports.string().regex(/^[0-9a-f]{7,40}\.\.[0-9a-f]{7,40}$/),
34135
+ commitRangeStart: external_exports.string().min(1),
33331
34136
  approval: external_exports.string().min(1),
33332
34137
  acceptedRisks: external_exports.array(external_exports.string().min(1)).optional()
33333
34138
  };
@@ -33338,7 +34143,8 @@ function createCadreServer() {
33338
34143
  annotations: { readOnlyHint: true, openWorldHint: false }
33339
34144
  }, async (input) => {
33340
34145
  try {
33341
- return result(previewReviewComplete(input));
34146
+ const derived = deriveReviewCompleteInput(input);
34147
+ return proposalResult("review_complete", derived, previewReviewComplete(derived));
33342
34148
  } catch (error51) {
33343
34149
  return failure(error51);
33344
34150
  }
@@ -33346,22 +34152,28 @@ function createCadreServer() {
33346
34152
  server.registerTool("review_complete_apply", {
33347
34153
  title: "Apply clean review completion",
33348
34154
  description: "Apply an approved clean-review transition only while its exact state and index preview remain current.",
33349
- inputSchema: { ...reviewCompleteSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34155
+ inputSchema: proposalInputSchema(),
33350
34156
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33351
- }, async ({ proposalDigest, ...input }) => {
34157
+ }, async ({ proposalToken }) => {
33352
34158
  try {
33353
- return result(applyReviewComplete(input, proposalDigest));
34159
+ const proposal = decodeProposalToken("review_complete", proposalToken);
34160
+ return result(applyReviewComplete(proposal.input, proposal.digest));
33354
34161
  } catch (error51) {
33355
34162
  return failure(error51);
33356
34163
  }
33357
34164
  });
33358
34165
  const archiveBatchSchema = {
33359
34166
  projectRoot: external_exports.string().min(1),
33360
- batchId: external_exports.string().regex(/^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33361
- selectedTracks: external_exports.array(external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)).min(1),
33362
- baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33363
- approvedAt: external_exports.iso.datetime(),
33364
- updates: external_exports.array(external_exports.object({ path: external_exports.string().min(1), content: external_exports.string() }))
34167
+ selectedTracks: external_exports.array(external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)).min(1).optional(),
34168
+ updates: external_exports.array(external_exports.discriminatedUnion("kind", [
34169
+ external_exports.object({ kind: external_exports.literal("pattern"), slug: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/), content: external_exports.string() }),
34170
+ external_exports.object({ kind: external_exports.literal("pattern_index"), content: external_exports.string() }),
34171
+ external_exports.object({
34172
+ kind: external_exports.literal("active_track_seed"),
34173
+ trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34174
+ content: external_exports.string()
34175
+ })
34176
+ ]))
33365
34177
  };
33366
34178
  server.registerTool("archive_batch_preview", {
33367
34179
  title: "Preview complete archive batch",
@@ -33370,7 +34182,8 @@ function createCadreServer() {
33370
34182
  annotations: { readOnlyHint: true, openWorldHint: false }
33371
34183
  }, async (input) => {
33372
34184
  try {
33373
- return result(previewArchiveBatch(input));
34185
+ const derived = deriveArchiveBatchInput(input);
34186
+ return proposalResult("archive_batch", derived, previewArchiveBatch(derived));
33374
34187
  } catch (error51) {
33375
34188
  return failure(error51);
33376
34189
  }
@@ -33378,19 +34191,19 @@ function createCadreServer() {
33378
34191
  server.registerTool("archive_batch_apply", {
33379
34192
  title: "Apply complete archive batch",
33380
34193
  description: "Journal and apply one approved archive batch only while its complete preview remains current.",
33381
- inputSchema: { ...archiveBatchSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34194
+ inputSchema: proposalInputSchema(),
33382
34195
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33383
- }, async ({ proposalDigest, ...input }) => {
34196
+ }, async ({ proposalToken }) => {
33384
34197
  try {
33385
- return result(applyArchiveBatch(input, proposalDigest));
34198
+ const proposal = decodeProposalToken("archive_batch", proposalToken);
34199
+ return result(applyArchiveBatch(proposal.input, proposal.digest));
33386
34200
  } catch (error51) {
33387
34201
  return failure(error51);
33388
34202
  }
33389
34203
  });
33390
34204
  const archiveRecordSchema = {
33391
34205
  projectRoot: external_exports.string().min(1),
33392
- batchId: external_exports.string().regex(/^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33393
- archiveCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/)
34206
+ batchId: external_exports.string().regex(/^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
33394
34207
  };
33395
34208
  server.registerTool("archive_batch_record_preview", {
33396
34209
  title: "Preview archive provenance record",
@@ -33399,7 +34212,8 @@ function createCadreServer() {
33399
34212
  annotations: { readOnlyHint: true, openWorldHint: false }
33400
34213
  }, async (input) => {
33401
34214
  try {
33402
- return result(previewArchiveBatchRecord(input));
34215
+ const derived = deriveArchiveBatchRecordInput(input);
34216
+ return proposalResult("archive_batch_record", derived, previewArchiveBatchRecord(derived));
33403
34217
  } catch (error51) {
33404
34218
  return failure(error51);
33405
34219
  }
@@ -33407,11 +34221,12 @@ function createCadreServer() {
33407
34221
  server.registerTool("archive_batch_record_apply", {
33408
34222
  title: "Record archive provenance",
33409
34223
  description: "Record an approved batch's immutable archive commit and complete its journal behind a stale-state digest.",
33410
- inputSchema: { ...archiveRecordSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34224
+ inputSchema: proposalInputSchema(),
33411
34225
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33412
- }, async ({ proposalDigest, ...input }) => {
34226
+ }, async ({ proposalToken }) => {
33413
34227
  try {
33414
- return result(applyArchiveBatchRecord(input, proposalDigest));
34228
+ const proposal = decodeProposalToken("archive_batch_record", proposalToken);
34229
+ return result(applyArchiveBatchRecord(proposal.input, proposal.digest));
33415
34230
  } catch (error51) {
33416
34231
  return failure(error51);
33417
34232
  }
@@ -33419,12 +34234,9 @@ function createCadreServer() {
33419
34234
  const executionStartSchema = {
33420
34235
  projectRoot: external_exports.string().min(1),
33421
34236
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33422
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33423
- requestedMode: external_exports.enum(["parallel", "sequential"]),
33424
- effectiveMode: external_exports.enum(["parallel", "sequential"]),
33425
- maxWorkers: external_exports.number().int().min(1).max(32),
33426
- baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33427
- approvedAt: external_exports.iso.datetime()
34237
+ requestedMode: external_exports.enum(["parallel", "sequential"]).optional().default("parallel"),
34238
+ approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES).optional(),
34239
+ maxWorkers: external_exports.number().int().min(1).max(32).optional().default(3)
33428
34240
  };
33429
34241
  server.registerTool("execution_start_preview", {
33430
34242
  title: "Preview implementation execution",
@@ -33433,7 +34245,8 @@ function createCadreServer() {
33433
34245
  annotations: { readOnlyHint: true, openWorldHint: false }
33434
34246
  }, async (input) => {
33435
34247
  try {
33436
- return result(previewExecutionStart(input));
34248
+ const derived = deriveExecutionStartInput(input);
34249
+ return proposalResult("execution_start", derived, previewExecutionStart(derived));
33437
34250
  } catch (error51) {
33438
34251
  return failure(error51);
33439
34252
  }
@@ -33441,81 +34254,58 @@ function createCadreServer() {
33441
34254
  server.registerTool("execution_start_apply", {
33442
34255
  title: "Start implementation execution",
33443
34256
  description: "Write the approved implementation journal and operation only when its preview digest is unchanged.",
33444
- inputSchema: { ...executionStartSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34257
+ inputSchema: proposalInputSchema(),
33445
34258
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33446
- }, async ({ proposalDigest, ...input }) => {
34259
+ }, async ({ proposalToken }) => {
33447
34260
  try {
33448
- return result(applyExecutionStart(input, proposalDigest));
34261
+ const proposal = decodeProposalToken("execution_start", proposalToken);
34262
+ return result(applyExecutionStart(proposal.input, proposal.digest));
33449
34263
  } catch (error51) {
33450
34264
  return failure(error51);
33451
34265
  }
33452
34266
  });
33453
- const executionNodeScopeSchema = {
34267
+ const executionScopeSchema = {
33454
34268
  projectRoot: external_exports.string().min(1),
33455
34269
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33456
34270
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
33457
34271
  };
33458
- const executionNodeUpdateSchema = {
34272
+ const executionCheckpointSchema = {
34273
+ ...executionScopeSchema,
33459
34274
  nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/),
33460
- status: external_exports.enum(EXECUTION_NODE_STATUSES),
34275
+ event: external_exports.enum(EXECUTION_CHECKPOINT_EVENTS),
33461
34276
  workerId: external_exports.string().min(1).nullable().optional(),
33462
34277
  worktreePath: external_exports.string().min(1).nullable().optional(),
33463
34278
  branch: external_exports.string().min(1).nullable().optional(),
33464
- workerCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).nullable().optional(),
33465
- mergeCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).nullable().optional(),
33466
- verification: external_exports.string().min(1).nullable().optional(),
33467
- approval: external_exports.string().min(1).nullable().optional(),
33468
- blocker: external_exports.string().min(1).nullable().optional()
33469
- };
33470
- const executionNodeSchema = { ...executionNodeScopeSchema, ...executionNodeUpdateSchema };
33471
- server.registerTool("execution_node_preview", {
33472
- title: "Preview execution node transition",
33473
- description: "Validate and preview one legal runtime node transition without changing its journal.",
33474
- inputSchema: executionNodeSchema,
34279
+ commit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).optional(),
34280
+ verification: external_exports.string().min(1).optional(),
34281
+ authorization: external_exports.string().min(1).optional(),
34282
+ blocker: external_exports.string().min(1).optional()
34283
+ };
34284
+ server.registerTool("execution_checkpoint_preview", {
34285
+ title: "Preview an execution checkpoint",
34286
+ description: "Translate one semantic execution event into the complete legal journal transition sequence.",
34287
+ inputSchema: executionCheckpointSchema,
33475
34288
  annotations: { readOnlyHint: true, openWorldHint: false }
33476
34289
  }, async (input) => {
33477
34290
  try {
33478
- return result(previewExecutionNodeUpdate(input));
33479
- } catch (error51) {
33480
- return failure(error51);
33481
- }
33482
- });
33483
- server.registerTool("execution_node_apply", {
33484
- title: "Apply execution node transition",
33485
- description: "Apply one approved execution node transition only when its preview digest is unchanged.",
33486
- inputSchema: { ...executionNodeSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
33487
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33488
- }, async ({ proposalDigest, ...input }) => {
33489
- try {
33490
- return result(applyExecutionNodeUpdate(input, proposalDigest));
33491
- } catch (error51) {
33492
- return failure(error51);
33493
- }
33494
- });
33495
- const executionNodesSchema = {
33496
- ...executionNodeScopeSchema,
33497
- updates: external_exports.array(external_exports.object(executionNodeUpdateSchema)).min(1).max(128)
33498
- };
33499
- server.registerTool("execution_nodes_preview", {
33500
- title: "Preview ordered execution node transitions",
33501
- description: "Validate and preview an ordered, atomic batch of legal runtime node transitions without changing its journal.",
33502
- inputSchema: executionNodesSchema,
33503
- annotations: { readOnlyHint: true, openWorldHint: false }
33504
- }, async (input) => {
33505
- try {
33506
- return result(previewExecutionNodesUpdate(input));
34291
+ return proposalResult(
34292
+ "execution_checkpoint",
34293
+ input,
34294
+ previewExecutionCheckpoint(input)
34295
+ );
33507
34296
  } catch (error51) {
33508
34297
  return failure(error51);
33509
34298
  }
33510
34299
  });
33511
- server.registerTool("execution_nodes_apply", {
33512
- title: "Apply ordered execution node transitions",
33513
- description: "Apply an approved ordered batch atomically only when its single preview digest is unchanged.",
33514
- inputSchema: { ...executionNodesSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34300
+ server.registerTool("execution_checkpoint_apply", {
34301
+ title: "Apply an execution checkpoint",
34302
+ description: "Apply one previewed semantic execution event atomically.",
34303
+ inputSchema: proposalInputSchema(),
33515
34304
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33516
- }, async ({ proposalDigest, ...input }) => {
34305
+ }, async ({ proposalToken }) => {
33517
34306
  try {
33518
- return result(applyExecutionNodesUpdate(input, proposalDigest));
34307
+ const proposal = decodeProposalToken("execution_checkpoint", proposalToken);
34308
+ return result(applyExecutionCheckpoint(proposal.input, proposal.digest));
33519
34309
  } catch (error51) {
33520
34310
  return failure(error51);
33521
34311
  }
@@ -33539,30 +34329,30 @@ function createCadreServer() {
33539
34329
  const executionFinishSchema = {
33540
34330
  projectRoot: external_exports.string().min(1),
33541
34331
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33542
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33543
- headCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33544
- completedAt: external_exports.iso.datetime()
34332
+ executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
33545
34333
  };
33546
34334
  server.registerTool("execution_finish_preview", {
33547
34335
  title: "Preview completed implementation execution",
33548
- description: "Verify all DAG nodes, plan evidence, and worktree cleanup before proposing ready-for-review state.",
34336
+ description: "Verify all DAG nodes, plan evidence, and worktree cleanup before proposing ready-for-review state and its derived tracks index under one digest.",
33549
34337
  inputSchema: executionFinishSchema,
33550
34338
  annotations: { readOnlyHint: true, openWorldHint: false }
33551
34339
  }, async (input) => {
33552
34340
  try {
33553
- return result(previewExecutionFinish(input));
34341
+ const derived = deriveExecutionFinishInput(input);
34342
+ return proposalResult("execution_finish", derived, previewExecutionFinish(derived));
33554
34343
  } catch (error51) {
33555
34344
  return failure(error51);
33556
34345
  }
33557
34346
  });
33558
34347
  server.registerTool("execution_finish_apply", {
33559
34348
  title: "Complete implementation execution",
33560
- description: "Finalize an approved execution and mark it ready for review only when the preview is unchanged.",
33561
- inputSchema: { ...executionFinishSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34349
+ description: "Finalize an approved execution, ready-for-review state, and derived tracks index together only when the preview is unchanged.",
34350
+ inputSchema: proposalInputSchema(),
33562
34351
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33563
- }, async ({ proposalDigest, ...input }) => {
34352
+ }, async ({ proposalToken }) => {
33564
34353
  try {
33565
- return result(applyExecutionFinish(input, proposalDigest));
34354
+ const proposal = decodeProposalToken("execution_finish", proposalToken);
34355
+ return result(applyExecutionFinish(proposal.input, proposal.digest));
33566
34356
  } catch (error51) {
33567
34357
  return failure(error51);
33568
34358
  }
@@ -33571,17 +34361,16 @@ function createCadreServer() {
33571
34361
  projectRoot: external_exports.string().min(1),
33572
34362
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33573
34363
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33574
- nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/),
33575
- phaseId: external_exports.string().regex(/^P\d+$/).nullable().optional()
34364
+ nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/)
33576
34365
  };
33577
34366
  server.registerTool("worktree_create_preview", {
33578
34367
  title: "Preview a Cadre worker worktree",
33579
34368
  description: "Resolve the constrained worker path, branch, and exact base commit without mutating Git.",
33580
- inputSchema: { ...worktreeSchema, baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/) },
34369
+ inputSchema: worktreeSchema,
33581
34370
  annotations: { readOnlyHint: true, openWorldHint: false }
33582
34371
  }, async (input) => {
33583
34372
  try {
33584
- return result(previewWorktreeCreate(input));
34373
+ return proposalResult("worktree_create", input, previewWorktreeCreate(input));
33585
34374
  } catch (error51) {
33586
34375
  return failure(error51);
33587
34376
  }
@@ -33589,15 +34378,12 @@ function createCadreServer() {
33589
34378
  server.registerTool("worktree_create_apply", {
33590
34379
  title: "Create a Cadre worker worktree",
33591
34380
  description: "Create or reconcile one approved constrained worker worktree using an unchanged preview digest.",
33592
- inputSchema: {
33593
- ...worktreeSchema,
33594
- baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33595
- proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/)
33596
- },
34381
+ inputSchema: proposalInputSchema(),
33597
34382
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
33598
- }, async ({ proposalDigest, ...input }) => {
34383
+ }, async ({ proposalToken }) => {
33599
34384
  try {
33600
- return result(applyWorktreeCreate(input, proposalDigest));
34385
+ const proposal = decodeProposalToken("worktree_create", proposalToken);
34386
+ return result(applyWorktreeCreate(proposal.input, proposal.digest));
33601
34387
  } catch (error51) {
33602
34388
  return failure(error51);
33603
34389
  }
@@ -33609,7 +34395,7 @@ function createCadreServer() {
33609
34395
  annotations: { readOnlyHint: true, openWorldHint: false }
33610
34396
  }, async (input) => {
33611
34397
  try {
33612
- return result(previewWorktreeIntegration(input));
34398
+ return proposalResult("worktree_integrate", input, previewWorktreeIntegration(input));
33613
34399
  } catch (error51) {
33614
34400
  return failure(error51);
33615
34401
  }
@@ -33617,35 +34403,37 @@ function createCadreServer() {
33617
34403
  server.registerTool("integration_apply", {
33618
34404
  title: "Integrate a worker branch",
33619
34405
  description: "Merge an approved worker branch without squashing; report conflicts without resolving them.",
33620
- inputSchema: { ...worktreeSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34406
+ inputSchema: proposalInputSchema(),
33621
34407
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33622
- }, async ({ proposalDigest, ...input }) => {
34408
+ }, async ({ proposalToken }) => {
33623
34409
  try {
33624
- return result(applyWorktreeIntegration(input, proposalDigest));
34410
+ const proposal = decodeProposalToken("worktree_integrate", proposalToken);
34411
+ return result(applyWorktreeIntegration(proposal.input, proposal.digest));
33625
34412
  } catch (error51) {
33626
34413
  return failure(error51);
33627
34414
  }
33628
34415
  });
33629
34416
  server.registerTool("worktree_cleanup_preview", {
33630
34417
  title: "Preview worker cleanup",
33631
- description: "Verify a clean worker branch is fully integrated before proposing worktree and branch removal.",
34418
+ description: "Verify a clean worker branch is fully integrated before proposing worktree and branch removal, including recovery after its node was already completed.",
33632
34419
  inputSchema: worktreeSchema,
33633
34420
  annotations: { readOnlyHint: true, openWorldHint: false }
33634
34421
  }, async (input) => {
33635
34422
  try {
33636
- return result(previewWorktreeCleanup(input));
34423
+ return proposalResult("worktree_cleanup", input, previewWorktreeCleanup(input));
33637
34424
  } catch (error51) {
33638
34425
  return failure(error51);
33639
34426
  }
33640
34427
  });
33641
34428
  server.registerTool("worktree_cleanup_apply", {
33642
34429
  title: "Clean up an integrated worker",
33643
- description: "Remove only a clean, integrated Cadre worktree and its safely deletable branch.",
33644
- inputSchema: { ...worktreeSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34430
+ description: "Remove only a clean, fully integrated Cadre worktree and its safely deletable branch, whether its journal node is integrated or already completed.",
34431
+ inputSchema: proposalInputSchema(),
33645
34432
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
33646
- }, async ({ proposalDigest, ...input }) => {
34433
+ }, async ({ proposalToken }) => {
33647
34434
  try {
33648
- return result(applyWorktreeCleanup(input, proposalDigest));
34435
+ const proposal = decodeProposalToken("worktree_cleanup", proposalToken);
34436
+ return result(applyWorktreeCleanup(proposal.input, proposal.digest));
33649
34437
  } catch (error51) {
33650
34438
  return failure(error51);
33651
34439
  }
@@ -33674,24 +34462,25 @@ function createCadreServer() {
33674
34462
  };
33675
34463
  server.registerTool("project_init_preview", {
33676
34464
  title: "Preview Cadre project initialization",
33677
- description: "Validate approved rendered artifacts and return the exact proposed .cadre file set and digest without writing.",
34465
+ description: "Validate approved rendered artifacts and return the proposed .cadre file set and semantic digest without writing; approvedAt is audit metadata and does not affect the digest.",
33678
34466
  inputSchema: initSchema,
33679
34467
  annotations: { readOnlyHint: true, openWorldHint: false }
33680
34468
  }, async (input) => {
33681
34469
  try {
33682
- return result(previewProjectInit(input));
34470
+ return proposalResult("project_init", input, previewProjectInit(input));
33683
34471
  } catch (error51) {
33684
34472
  return failure(error51);
33685
34473
  }
33686
34474
  });
33687
34475
  server.registerTool("project_init_apply", {
33688
34476
  title: "Apply approved Cadre project initialization",
33689
- description: "Atomically create .cadre only when the current proposal matches an approved preview digest.",
33690
- inputSchema: { ...initSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34477
+ description: "Atomically create .cadre only when the semantic proposal matches an approved preview digest; records approvedAt as audit metadata.",
34478
+ inputSchema: proposalInputSchema(),
33691
34479
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33692
- }, async ({ proposalDigest, ...input }) => {
34480
+ }, async ({ proposalToken }) => {
33693
34481
  try {
33694
- return result(applyProjectInit(input, proposalDigest));
34482
+ const proposal = decodeProposalToken("project_init", proposalToken);
34483
+ return result(applyProjectInit(proposal.input, proposal.digest));
33695
34484
  } catch (error51) {
33696
34485
  return failure(error51);
33697
34486
  }
@@ -33699,13 +34488,11 @@ function createCadreServer() {
33699
34488
  server.registerTool("setup_record_commit", {
33700
34489
  title: "Record the project setup commit",
33701
34490
  description: "Complete a pending create operation by recording its already-created Git commit SHA.",
33702
- inputSchema: {
33703
- projectRoot: external_exports.string().min(1),
33704
- commit: external_exports.string().regex(/^[0-9a-f]{7,40}$/)
33705
- },
34491
+ inputSchema: { projectRoot: external_exports.string().min(1) },
33706
34492
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33707
- }, async ({ projectRoot, commit }) => {
34493
+ }, async ({ projectRoot }) => {
33708
34494
  try {
34495
+ const commit = resolveGitCommit(projectRoot);
33709
34496
  return result({ path: recordSetupCommit(projectRoot, commit), commit });
33710
34497
  } catch (error51) {
33711
34498
  return failure(error51);
@@ -33730,7 +34517,8 @@ function createCadreServer() {
33730
34517
  annotations: { readOnlyHint: true, openWorldHint: false }
33731
34518
  }, async ({ projectRoot }) => {
33732
34519
  try {
33733
- return result(renderTracksPreview(safeProjectRoot(projectRoot)));
34520
+ const input = { projectRoot: safeProjectRoot(projectRoot) };
34521
+ return proposalResult("tracks_render", input, renderTracksPreview(input.projectRoot));
33734
34522
  } catch (error51) {
33735
34523
  return failure(error51);
33736
34524
  }
@@ -33738,14 +34526,12 @@ function createCadreServer() {
33738
34526
  server.registerTool("tracks_render_apply", {
33739
34527
  title: "Apply the derived tracks index",
33740
34528
  description: "Rewrite tracks.md only when current state matches a human-approved preview digest.",
33741
- inputSchema: {
33742
- projectRoot: external_exports.string().min(1),
33743
- proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/)
33744
- },
34529
+ inputSchema: proposalInputSchema(),
33745
34530
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33746
- }, async ({ projectRoot, proposalDigest }) => {
34531
+ }, async ({ proposalToken }) => {
33747
34532
  try {
33748
- return result({ path: writeTracks(safeProjectRoot(projectRoot), proposalDigest) });
34533
+ const proposal = decodeProposalToken("tracks_render", proposalToken);
34534
+ return result({ path: writeTracks(proposal.input.projectRoot, proposal.digest) });
33749
34535
  } catch (error51) {
33750
34536
  return failure(error51);
33751
34537
  }
@@ -33756,7 +34542,7 @@ async function runCadreServer() {
33756
34542
  const server = createCadreServer();
33757
34543
  await server.connect(new StdioServerTransport());
33758
34544
  }
33759
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve8(process.argv[1])).href) {
34545
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve10(process.argv[1])).href) {
33760
34546
  runCadreServer().catch((error51) => {
33761
34547
  process.stderr.write(`${error51 instanceof Error ? error51.message : String(error51)}
33762
34548
  `);