cadre-ai 3.1.0 → 3.3.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.
@@ -405,11 +405,11 @@ var require_codegen = __commonJS({
405
405
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
406
406
  return `${varKind} ${this.name}${rhs};` + _n;
407
407
  }
408
- optimizeNames(names, constants) {
408
+ optimizeNames(names, constants2) {
409
409
  if (!names[this.name.str])
410
410
  return;
411
411
  if (this.rhs)
412
- this.rhs = optimizeExpr(this.rhs, names, constants);
412
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
413
413
  return this;
414
414
  }
415
415
  get names() {
@@ -426,10 +426,10 @@ var require_codegen = __commonJS({
426
426
  render({ _n }) {
427
427
  return `${this.lhs} = ${this.rhs};` + _n;
428
428
  }
429
- optimizeNames(names, constants) {
429
+ optimizeNames(names, constants2) {
430
430
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
431
431
  return;
432
- this.rhs = optimizeExpr(this.rhs, names, constants);
432
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
433
433
  return this;
434
434
  }
435
435
  get names() {
@@ -490,8 +490,8 @@ var require_codegen = __commonJS({
490
490
  optimizeNodes() {
491
491
  return `${this.code}` ? this : void 0;
492
492
  }
493
- optimizeNames(names, constants) {
494
- this.code = optimizeExpr(this.code, names, constants);
493
+ optimizeNames(names, constants2) {
494
+ this.code = optimizeExpr(this.code, names, constants2);
495
495
  return this;
496
496
  }
497
497
  get names() {
@@ -520,12 +520,12 @@ var require_codegen = __commonJS({
520
520
  }
521
521
  return nodes.length > 0 ? this : void 0;
522
522
  }
523
- optimizeNames(names, constants) {
523
+ optimizeNames(names, constants2) {
524
524
  const { nodes } = this;
525
525
  let i = nodes.length;
526
526
  while (i--) {
527
527
  const n = nodes[i];
528
- if (n.optimizeNames(names, constants))
528
+ if (n.optimizeNames(names, constants2))
529
529
  continue;
530
530
  subtractNames(names, n.names);
531
531
  nodes.splice(i, 1);
@@ -578,12 +578,12 @@ var require_codegen = __commonJS({
578
578
  return void 0;
579
579
  return this;
580
580
  }
581
- optimizeNames(names, constants) {
581
+ optimizeNames(names, constants2) {
582
582
  var _a3;
583
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
584
- if (!(super.optimizeNames(names, constants) || this.else))
583
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
584
+ if (!(super.optimizeNames(names, constants2) || this.else))
585
585
  return;
586
- this.condition = optimizeExpr(this.condition, names, constants);
586
+ this.condition = optimizeExpr(this.condition, names, constants2);
587
587
  return this;
588
588
  }
589
589
  get names() {
@@ -606,10 +606,10 @@ var require_codegen = __commonJS({
606
606
  render(opts) {
607
607
  return `for(${this.iteration})` + super.render(opts);
608
608
  }
609
- optimizeNames(names, constants) {
610
- if (!super.optimizeNames(names, constants))
609
+ optimizeNames(names, constants2) {
610
+ if (!super.optimizeNames(names, constants2))
611
611
  return;
612
- this.iteration = optimizeExpr(this.iteration, names, constants);
612
+ this.iteration = optimizeExpr(this.iteration, names, constants2);
613
613
  return this;
614
614
  }
615
615
  get names() {
@@ -645,10 +645,10 @@ var require_codegen = __commonJS({
645
645
  render(opts) {
646
646
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
647
647
  }
648
- optimizeNames(names, constants) {
649
- if (!super.optimizeNames(names, constants))
648
+ optimizeNames(names, constants2) {
649
+ if (!super.optimizeNames(names, constants2))
650
650
  return;
651
- this.iterable = optimizeExpr(this.iterable, names, constants);
651
+ this.iterable = optimizeExpr(this.iterable, names, constants2);
652
652
  return this;
653
653
  }
654
654
  get names() {
@@ -690,11 +690,11 @@ var require_codegen = __commonJS({
690
690
  (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
691
691
  return this;
692
692
  }
693
- optimizeNames(names, constants) {
693
+ optimizeNames(names, constants2) {
694
694
  var _a3, _b;
695
- super.optimizeNames(names, constants);
696
- (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
697
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
695
+ super.optimizeNames(names, constants2);
696
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
697
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants2);
698
698
  return this;
699
699
  }
700
700
  get names() {
@@ -995,7 +995,7 @@ var require_codegen = __commonJS({
995
995
  function addExprNames(names, from) {
996
996
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
997
997
  }
998
- function optimizeExpr(expr, names, constants) {
998
+ function optimizeExpr(expr, names, constants2) {
999
999
  if (expr instanceof code_1.Name)
1000
1000
  return replaceName(expr);
1001
1001
  if (!canOptimize(expr))
@@ -1010,14 +1010,14 @@ var require_codegen = __commonJS({
1010
1010
  return items;
1011
1011
  }, []));
1012
1012
  function replaceName(n) {
1013
- const c = constants[n.str];
1013
+ const c = constants2[n.str];
1014
1014
  if (c === void 0 || names[n.str] !== 1)
1015
1015
  return n;
1016
1016
  delete names[n.str];
1017
1017
  return c;
1018
1018
  }
1019
1019
  function canOptimize(e) {
1020
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
1020
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants2[c.str] !== void 0);
1021
1021
  }
1022
1022
  }
1023
1023
  function subtractNames(names, from) {
@@ -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 = resolve10.call(this, root, ref);
2982
+ let _sch = resolve12.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 resolve10(root, ref) {
3009
+ function resolve12(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 resolve10(baseURI, relativeURI, options) {
3640
+ function resolve12(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: resolve10,
3898
+ resolve: resolve12,
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((resolve10) => setTimeout(resolve10, pollInterval));
28846
+ await new Promise((resolve12) => setTimeout(resolve12, 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((resolve10, reject) => {
28863
+ return new Promise((resolve12, 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
- resolve10(parseResult.data);
28941
+ resolve12(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((resolve10, reject) => {
29202
+ return new Promise((resolve12, reject) => {
29203
29203
  if (signal.aborted) {
29204
29204
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
29205
29205
  return;
29206
29206
  }
29207
- const timeoutId = setTimeout(resolve10, interval);
29207
+ const timeoutId = setTimeout(resolve12, 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((resolve10) => setTimeout(resolve10, pollInterval));
30298
+ await new Promise((resolve12) => setTimeout(resolve12, 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,20 +30959,21 @@ var StdioServerTransport = class {
30959
30959
  this.onclose?.();
30960
30960
  }
30961
30961
  send(message) {
30962
- return new Promise((resolve10) => {
30962
+ return new Promise((resolve12) => {
30963
30963
  const json3 = serializeMessage(message);
30964
30964
  if (this._stdout.write(json3)) {
30965
- resolve10();
30965
+ resolve12();
30966
30966
  } else {
30967
- this._stdout.once("drain", resolve10);
30967
+ this._stdout.once("drain", resolve12);
30968
30968
  }
30969
30969
  });
30970
30970
  }
30971
30971
  };
30972
30972
 
30973
30973
  // src/mcp/server.ts
30974
- import { readFileSync as readFileSync8 } from "node:fs";
30975
- import { join as join8, resolve as resolve9 } from "node:path";
30974
+ import { createHash as createHash8 } from "node:crypto";
30975
+ import { readFileSync as readFileSync9 } from "node:fs";
30976
+ import { join as join9, resolve as resolve11 } from "node:path";
30976
30977
  import { pathToFileURL } from "node:url";
30977
30978
 
30978
30979
  // src/domain/init.ts
@@ -30986,15 +30987,15 @@ import {
30986
30987
  writeFileSync as writeFileSync3
30987
30988
  } from "node:fs";
30988
30989
  import { dirname as dirname3 } from "node:path";
30989
- import { isAbsolute, join as join5, relative as relative2, resolve as resolve6 } from "node:path";
30990
+ import { isAbsolute, join as join5, relative as relative2, resolve as resolve7 } from "node:path";
30990
30991
 
30991
30992
  // src/domain/state.ts
30992
30993
  import { createHash as createHash3 } from "node:crypto";
30993
30994
  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 resolve4 } from "node:path";
30995
+ import { join as join3, resolve as resolve5 } from "node:path";
30995
30996
 
30996
30997
  // src/domain/version.ts
30997
- var CADRE_RUNTIME_VERSION = "3.1.0";
30998
+ var CADRE_RUNTIME_VERSION = "3.3.0";
30998
30999
  var TEMPLATE_SET_VERSION = "v1";
30999
31000
 
31000
31001
  // src/domain/plan.ts
@@ -31219,7 +31220,7 @@ function readAndValidatePlan(path, status, errors) {
31219
31220
  // src/domain/execution.ts
31220
31221
  import { createHash as createHash2, randomUUID } from "node:crypto";
31221
31222
  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 resolve3 } from "node:path";
31223
+ import { basename, dirname, join as join2, resolve as resolve4 } from "node:path";
31223
31224
 
31224
31225
  // src/domain/errors.ts
31225
31226
  var CadreError = class extends Error {
@@ -31320,6 +31321,50 @@ function renderTracksWithState(projectRoot, statePath, proposedState) {
31320
31321
  };
31321
31322
  }
31322
31323
 
31324
+ // src/domain/git.ts
31325
+ import { spawnSync } from "node:child_process";
31326
+ import { realpathSync } from "node:fs";
31327
+ import { resolve as resolve3 } from "node:path";
31328
+ function gitRoot(projectRoot) {
31329
+ const root = realpathSync(safeProjectRoot(projectRoot));
31330
+ const result2 = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: root, encoding: "utf8" });
31331
+ if (result2.status !== 0) throw new Error((result2.stderr || result2.stdout || "project is not a Git worktree").trim());
31332
+ const detected = realpathSync(resolve3(result2.stdout.trim()));
31333
+ if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
31334
+ return root;
31335
+ }
31336
+ function resolveGitCommit(projectRoot, revision = "HEAD") {
31337
+ const root = gitRoot(projectRoot);
31338
+ const result2 = spawnSync("git", ["rev-parse", "--verify", `${revision}^{commit}`], { cwd: root, encoding: "utf8" });
31339
+ if (result2.status !== 0) throw new Error(`Git commit is not reachable: ${revision}`);
31340
+ return result2.stdout.trim();
31341
+ }
31342
+ function isGitAncestor(projectRoot, ancestor, descendant = "HEAD") {
31343
+ const root = gitRoot(projectRoot);
31344
+ return spawnSync("git", ["merge-base", "--is-ancestor", ancestor, descendant], {
31345
+ cwd: root,
31346
+ encoding: "utf8"
31347
+ }).status === 0;
31348
+ }
31349
+ function reachableGitCommits(projectRoot, revisions) {
31350
+ let root;
31351
+ try {
31352
+ root = gitRoot(projectRoot);
31353
+ } catch {
31354
+ return null;
31355
+ }
31356
+ const unique = [...new Set(revisions)].filter(Boolean);
31357
+ const listed = spawnSync("git", ["rev-list", "--all"], { cwd: root, encoding: "utf8" });
31358
+ if (listed.status !== 0) throw new Error((listed.stderr || listed.stdout || "cannot enumerate Git history").trim());
31359
+ const history = new Set(listed.stdout.split(/\r?\n/).filter(Boolean));
31360
+ const reachable = /* @__PURE__ */ new Map();
31361
+ for (const revision of unique) {
31362
+ const result2 = spawnSync("git", ["rev-parse", "--verify", `${revision}^{commit}`], { cwd: root, encoding: "utf8" });
31363
+ reachable.set(revision, result2.status === 0 && history.has(result2.stdout.trim()));
31364
+ }
31365
+ return reachable;
31366
+ }
31367
+
31323
31368
  // src/domain/execution.ts
31324
31369
  var EXECUTION_NODE_STATUSES = [
31325
31370
  "pending",
@@ -31334,6 +31379,21 @@ var EXECUTION_NODE_STATUSES = [
31334
31379
  "blocked"
31335
31380
  ];
31336
31381
  var EXECUTION_APPROVAL_MODES = ["governed", "phase", "autonomous"];
31382
+ function deriveExecutionStartInput(input) {
31383
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
31384
+ const requestedMode = input.requestedMode ?? "parallel";
31385
+ return {
31386
+ projectRoot: input.projectRoot,
31387
+ trackId: input.trackId,
31388
+ executionId: startedAt.replace(/[:.]/g, "-"),
31389
+ requestedMode,
31390
+ effectiveMode: requestedMode,
31391
+ ...input.approvalMode ? { approvalMode: input.approvalMode } : {},
31392
+ maxWorkers: input.maxWorkers ?? 3,
31393
+ baseCommit: resolveGitCommit(input.projectRoot),
31394
+ approvedAt: startedAt
31395
+ };
31396
+ }
31337
31397
  var SHA = /^[0-9a-f]{7,40}$/;
31338
31398
  var TRACK_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
31339
31399
  var EXECUTION_ID = /^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
@@ -31414,17 +31474,21 @@ function previewExecutionStart(input) {
31414
31474
  if (input.requestedMode === "sequential" && input.effectiveMode !== "sequential") {
31415
31475
  throw new Error("an explicitly sequential execution cannot become parallel");
31416
31476
  }
31417
- const approvalMode = input.approvalMode ?? "phase";
31418
- if (!EXECUTION_APPROVAL_MODES.includes(approvalMode)) throw new Error("approvalMode must be governed, phase, or autonomous");
31419
31477
  const trackRoot = activeTrackRoot(input.projectRoot, input.trackId);
31420
31478
  const statePath = join2(trackRoot, "state.json");
31421
31479
  const planPath = join2(trackRoot, "plan.md");
31422
31480
  const stateBody = readFileSync3(statePath, "utf8");
31423
31481
  const state = JSON.parse(stateBody);
31482
+ const approvalMode = input.approvalMode ?? state.lastExecution?.approvalMode ?? "phase";
31483
+ if (!EXECUTION_APPROVAL_MODES.includes(approvalMode)) throw new Error("approvalMode must be governed, phase, or autonomous");
31424
31484
  if (state.trackId !== input.trackId) throw new Error("track state does not match trackId");
31425
31485
  if (!["planned", "in_progress"].includes(state.status)) throw new Error(`track ${input.trackId} is not implementable from ${state.status}`);
31426
31486
  if (state.operation != null) throw new Error(`track ${input.trackId} already has an active operation`);
31427
31487
  if (!SHA.test(state.commits?.plan ?? "")) throw new Error("track has no approved plan commit");
31488
+ const planReachability = reachableGitCommits(input.projectRoot, [state.commits.plan]);
31489
+ if (planReachability?.get(state.commits.plan) === false) {
31490
+ throw new Error(`approved plan commit is not reachable: ${state.commits.plan}`);
31491
+ }
31428
31492
  const planErrors = [];
31429
31493
  const graph = parsePlan(planPath, planErrors);
31430
31494
  validatePlanGraph(planPath, graph, state.status, planErrors);
@@ -31656,26 +31720,36 @@ function applyExecutionNodesUpdate(input, proposalDigest) {
31656
31720
  derivedStatus: deriveExecutionStatus(proposal.journal)
31657
31721
  };
31658
31722
  }
31659
- function previewExecutionNodeUpdate(input) {
31660
- const { projectRoot, trackId, executionId, ...update } = input;
31661
- return previewExecutionNodesUpdate({ projectRoot, trackId, executionId, updates: [update] });
31662
- }
31663
- function applyExecutionNodeUpdate(input, proposalDigest) {
31664
- const { projectRoot, trackId, executionId, ...update } = input;
31665
- const proposal = previewExecutionNodesUpdate({ projectRoot, trackId, executionId, updates: [update] });
31666
- if (proposal.digest !== proposalDigest) throw new Error("execution node proposal is stale; preview it again");
31667
- writeJournalAtomically(proposal.path, proposal.journal);
31668
- return {
31669
- path: proposal.path,
31670
- journal: proposal.journal,
31671
- derivedStatus: deriveExecutionStatus(proposal.journal)
31672
- };
31673
- }
31674
31723
  function deriveExecutionStatus(journal) {
31675
31724
  const completed = new Set(Object.values(journal.nodes).filter((node) => node.status === "completed").map((node) => node.id));
31676
31725
  const ready = Object.values(journal.nodes).filter(
31677
31726
  (node) => node.status === "pending" && node.dependencies.every((dependency) => completed.has(dependency))
31678
31727
  );
31728
+ const eventGuidance = Object.fromEntries(Object.values(journal.nodes).map((node) => {
31729
+ const allowed = [];
31730
+ if (node.status === "pending") allowed.push({ event: "start", requiredFields: [] });
31731
+ if (node.status === "running") {
31732
+ allowed.push(node.kind === "manual-verification" ? { event: "record_verification", requiredFields: ["commit", "verification", "authorization"] } : { event: "record_commit", requiredFields: ["commit", "verification", "authorization"] });
31733
+ }
31734
+ if (node.status === "awaiting_approval") {
31735
+ allowed.push({ event: "record_commit", requiredFields: ["commit", "verification", "authorization"] });
31736
+ }
31737
+ if (node.status === "committed") {
31738
+ allowed.push(
31739
+ { event: "record_integration", requiredFields: ["commit", "verification"] },
31740
+ { event: "complete", requiredFields: [] }
31741
+ );
31742
+ }
31743
+ if (["integrating", "conflicted", "integrated"].includes(node.status)) {
31744
+ allowed.push({ event: "record_integration", requiredFields: ["commit", "verification"] });
31745
+ }
31746
+ if (node.status === "awaiting_manual_verification") {
31747
+ allowed.push({ event: "record_verification", requiredFields: ["commit", "verification", "authorization"] });
31748
+ }
31749
+ if (node.status === "blocked") allowed.push({ event: "resume", requiredFields: [] });
31750
+ if (node.status !== "completed") allowed.push({ event: "block", requiredFields: ["blocker"] });
31751
+ return [node.id, { currentStatus: node.status, allowed }];
31752
+ }));
31679
31753
  return {
31680
31754
  readyPhases: ready.filter((node) => node.kind === "phase").map((node) => node.id),
31681
31755
  readyTasks: ready.filter(
@@ -31683,27 +31757,262 @@ function deriveExecutionStatus(journal) {
31683
31757
  ).map((node) => node.id),
31684
31758
  active: Object.values(journal.nodes).filter((node) => !["pending", "completed", "blocked"].includes(node.status)).map((node) => node.id),
31685
31759
  blocked: Object.values(journal.nodes).filter((node) => node.status === "blocked").map((node) => node.id),
31686
- transitionGuidance: Object.fromEntries(Object.values(journal.nodes).map((node) => [
31687
- node.id,
31688
- {
31689
- currentStatus: node.status,
31690
- allowed: ALLOWED_TRANSITIONS[node.status].map((status) => ({
31691
- status,
31692
- requiredFields: [
31693
- ...["blocked", "conflicted"].includes(status) ? ["blocker"] : [],
31694
- ...status === "committed" ? ["workerCommit", "approval"] : [],
31695
- ...status === "integrated" ? ["mergeCommit"] : [],
31696
- ...status === "completed" && node.kind === "manual-verification" ? ["approval"] : []
31697
- ]
31698
- }))
31699
- }
31700
- ]))
31760
+ eventGuidance
31761
+ };
31762
+ }
31763
+ function executionSchedulerView(journal, focusNodeIds = []) {
31764
+ const status = deriveExecutionStatus(journal);
31765
+ const relevant = /* @__PURE__ */ new Set([
31766
+ ...status.active,
31767
+ ...status.blocked,
31768
+ ...focusNodeIds
31769
+ ]);
31770
+ return {
31771
+ readyPhases: status.readyPhases,
31772
+ readyTasks: status.readyTasks,
31773
+ active: status.active,
31774
+ blocked: status.blocked,
31775
+ eventGuidance: Object.fromEntries(
31776
+ Object.entries(status.eventGuidance).filter(([nodeId]) => relevant.has(nodeId))
31777
+ )
31778
+ };
31779
+ }
31780
+ function compactExecutionStatus(journal, nodeId) {
31781
+ if (nodeId && !journal.nodes[nodeId]) throw new Error(`unknown execution node ${nodeId}`);
31782
+ const derivedStatus = executionSchedulerView(journal, nodeId ? [nodeId] : []);
31783
+ const actionableIds = /* @__PURE__ */ new Set([
31784
+ ...derivedStatus.active,
31785
+ ...derivedStatus.blocked
31786
+ ]);
31787
+ const actionableNodes = [...actionableIds].map((id) => {
31788
+ const node = journal.nodes[id];
31789
+ return {
31790
+ id: node.id,
31791
+ kind: node.kind,
31792
+ phaseId: node.phaseId,
31793
+ status: node.status,
31794
+ dependencies: node.dependencies,
31795
+ ...node.workerId ? { workerId: node.workerId } : {},
31796
+ ...node.worktreePath ? { worktreePath: node.worktreePath } : {},
31797
+ ...node.branch ? { branch: node.branch } : {},
31798
+ ...node.blocker ? { blocker: node.blocker } : {}
31799
+ };
31800
+ });
31801
+ const counts = {};
31802
+ for (const node of Object.values(journal.nodes)) counts[node.status] = (counts[node.status] ?? 0) + 1;
31803
+ return {
31804
+ execution: {
31805
+ executionId: journal.executionId,
31806
+ trackId: journal.trackId,
31807
+ status: journal.status,
31808
+ checkpoint: journal.checkpoint,
31809
+ requestedMode: journal.requestedMode,
31810
+ effectiveMode: journal.effectiveMode,
31811
+ approvalMode: journal.approvalMode,
31812
+ maxWorkers: journal.maxWorkers,
31813
+ planRevision: journal.planRevision,
31814
+ startedAt: journal.startedAt,
31815
+ completedAt: journal.completedAt
31816
+ },
31817
+ counts,
31818
+ actionableNodes,
31819
+ ...nodeId ? { node: journal.nodes[nodeId] } : {},
31820
+ derivedStatus
31701
31821
  };
31702
31822
  }
31703
31823
  function executionStatus(projectRoot, trackId, executionId) {
31704
31824
  const journal = readExecution(projectRoot, trackId, executionId);
31705
31825
  return { journal, ...deriveExecutionStatus(journal) };
31706
31826
  }
31827
+ var EXECUTION_CHECKPOINT_EVENTS = [
31828
+ "start",
31829
+ "record_commit",
31830
+ "record_integration",
31831
+ "record_verification",
31832
+ "complete",
31833
+ "block",
31834
+ "resume"
31835
+ ];
31836
+ function checkpointUpdates(journal, input) {
31837
+ const node = journal.nodes[input.nodeId];
31838
+ if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
31839
+ const evidence = input.verification?.trim();
31840
+ const authorization = input.authorization?.trim();
31841
+ const commit = input.commit;
31842
+ const updates = [];
31843
+ const start = () => {
31844
+ if (node.status === "pending" || node.status === "blocked") {
31845
+ updates.push({
31846
+ nodeId: node.id,
31847
+ status: "running",
31848
+ ...Object.hasOwn(input, "workerId") ? { workerId: input.workerId ?? null } : {},
31849
+ ...Object.hasOwn(input, "worktreePath") ? { worktreePath: input.worktreePath ?? null } : {},
31850
+ ...Object.hasOwn(input, "branch") ? { branch: input.branch ?? null } : {}
31851
+ });
31852
+ } else if (node.status === "running" && Object.hasOwn(input, "workerId")) {
31853
+ updates.push({
31854
+ nodeId: node.id,
31855
+ status: "running",
31856
+ workerId: input.workerId ?? null,
31857
+ ...evidence ? { verification: evidence } : {}
31858
+ });
31859
+ } else if (node.status !== "running") {
31860
+ throw new Error(`${node.id} cannot start from ${node.status}`);
31861
+ }
31862
+ };
31863
+ switch (input.event) {
31864
+ case "start":
31865
+ start();
31866
+ break;
31867
+ case "record_commit":
31868
+ if (!commit || !evidence || !authorization) {
31869
+ throw new Error("record_commit requires commit, verification, and authorization");
31870
+ }
31871
+ if (node.status === "running") {
31872
+ updates.push({ nodeId: node.id, status: "awaiting_approval", verification: evidence });
31873
+ } else if (node.status !== "awaiting_approval") {
31874
+ throw new Error(`${node.id} cannot record a commit from ${node.status}`);
31875
+ }
31876
+ updates.push({ nodeId: node.id, status: "committed", workerCommit: commit, approval: authorization });
31877
+ break;
31878
+ case "record_integration":
31879
+ if (!commit || !evidence) throw new Error("record_integration requires commit and verification");
31880
+ if (node.status === "committed") updates.push({ nodeId: node.id, status: "integrating" });
31881
+ else if (node.status !== "integrating" && node.status !== "conflicted" && node.status !== "integrated") {
31882
+ throw new Error(`${node.id} cannot record integration from ${node.status}`);
31883
+ }
31884
+ if (node.status !== "integrated") {
31885
+ updates.push({ nodeId: node.id, status: "integrated", mergeCommit: commit, verification: evidence });
31886
+ }
31887
+ updates.push({ nodeId: node.id, status: "completed" });
31888
+ break;
31889
+ case "record_verification":
31890
+ if (node.kind !== "manual-verification" || !commit || !evidence || !authorization) {
31891
+ throw new Error("record_verification requires a manual-verification node, commit, verification, and authorization");
31892
+ }
31893
+ if (node.status === "pending") updates.push({ nodeId: node.id, status: "running" });
31894
+ else if (node.status !== "running" && node.status !== "awaiting_manual_verification") {
31895
+ throw new Error(`${node.id} cannot record verification from ${node.status}`);
31896
+ }
31897
+ if (node.status !== "awaiting_manual_verification") {
31898
+ updates.push({ nodeId: node.id, status: "awaiting_manual_verification", verification: evidence, workerCommit: commit });
31899
+ }
31900
+ updates.push({ nodeId: node.id, status: "completed", workerCommit: commit, approval: authorization });
31901
+ break;
31902
+ case "complete":
31903
+ if (node.status === "committed") updates.push({
31904
+ nodeId: node.id,
31905
+ status: "completed",
31906
+ ...evidence ? { verification: evidence } : {}
31907
+ });
31908
+ else if (node.status === "integrated") updates.push({
31909
+ nodeId: node.id,
31910
+ status: "completed",
31911
+ ...evidence ? { verification: evidence } : {}
31912
+ });
31913
+ else if (node.kind === "phase" && node.status === "running") {
31914
+ if (!commit || !evidence || !authorization) {
31915
+ throw new Error("completing a running phase requires commit, verification, and authorization");
31916
+ }
31917
+ updates.push(
31918
+ { nodeId: node.id, status: "awaiting_approval", verification: evidence },
31919
+ { nodeId: node.id, status: "committed", workerCommit: commit, approval: authorization },
31920
+ { nodeId: node.id, status: "integrating" },
31921
+ { nodeId: node.id, status: "integrated", mergeCommit: commit },
31922
+ { nodeId: node.id, status: "completed" }
31923
+ );
31924
+ } else throw new Error(`${node.id} cannot complete from ${node.status}`);
31925
+ break;
31926
+ case "block":
31927
+ if (!input.blocker?.trim()) throw new Error("block requires a blocker description");
31928
+ updates.push({ nodeId: node.id, status: "blocked", blocker: input.blocker.trim() });
31929
+ break;
31930
+ case "resume":
31931
+ if (node.status !== "blocked") throw new Error(`${node.id} is not blocked`);
31932
+ updates.push({ nodeId: node.id, status: "pending" });
31933
+ break;
31934
+ }
31935
+ if (!updates.length) throw new Error(`${input.event} produced no change for ${node.id}`);
31936
+ return updates;
31937
+ }
31938
+ function previewExecutionCheckpoint(input) {
31939
+ const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
31940
+ const from = journal.nodes[input.nodeId]?.status;
31941
+ if (!from) throw new Error(`unknown execution node ${input.nodeId}`);
31942
+ const updates = checkpointUpdates(journal, input);
31943
+ const proposal = previewExecutionNodesUpdate({
31944
+ projectRoot: input.projectRoot,
31945
+ trackId: input.trackId,
31946
+ executionId: input.executionId,
31947
+ updates
31948
+ });
31949
+ const statuses = updates.map((update) => update.status);
31950
+ return {
31951
+ ...proposal,
31952
+ transition: {
31953
+ nodeId: input.nodeId,
31954
+ event: input.event,
31955
+ from,
31956
+ through: statuses.slice(0, -1),
31957
+ to: statuses.at(-1),
31958
+ checkpoint: proposal.journal.checkpoint
31959
+ }
31960
+ };
31961
+ }
31962
+ function applyExecutionCheckpoint(input, proposalDigest) {
31963
+ const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
31964
+ const from = journal.nodes[input.nodeId]?.status;
31965
+ if (!from) throw new Error(`unknown execution node ${input.nodeId}`);
31966
+ const updates = checkpointUpdates(journal, input);
31967
+ const applied = applyExecutionNodesUpdate({
31968
+ projectRoot: input.projectRoot,
31969
+ trackId: input.trackId,
31970
+ executionId: input.executionId,
31971
+ updates
31972
+ }, proposalDigest);
31973
+ const statuses = updates.map((update) => update.status);
31974
+ return {
31975
+ ...applied,
31976
+ transition: {
31977
+ nodeId: input.nodeId,
31978
+ event: input.event,
31979
+ from,
31980
+ through: statuses.slice(0, -1),
31981
+ to: statuses.at(-1),
31982
+ checkpoint: applied.journal.checkpoint
31983
+ }
31984
+ };
31985
+ }
31986
+ function deriveExecutionFinishInput(input) {
31987
+ return {
31988
+ ...input,
31989
+ headCommit: resolveGitCommit(input.projectRoot),
31990
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
31991
+ };
31992
+ }
31993
+ function renderCompletedPlan(planBody, graph, journal) {
31994
+ const lines = planBody.split(/\r?\n/);
31995
+ for (const phase of graph.phases) {
31996
+ const phaseNode = journal.nodes[phase.id];
31997
+ const phaseCommit = phaseNode?.mergeCommit ?? phaseNode?.workerCommit;
31998
+ if (!phaseCommit) throw new Error(`${phase.id} lacks completion commit evidence`);
31999
+ for (const task of phase.tasks) {
32000
+ const taskNode = journal.nodes[task.id];
32001
+ const taskCommit = taskNode?.workerCommit ?? taskNode?.mergeCommit;
32002
+ if (!taskNode || taskNode.status !== "completed" || !taskCommit) {
32003
+ throw new Error(`${task.id} lacks completed commit evidence`);
32004
+ }
32005
+ lines[task.line - 1] = `- [x] ${task.id} ${task.title} <!-- commit: ${taskCommit} -->`;
32006
+ }
32007
+ const nextPhaseLine = graph.phases[phase.number]?.line ?? lines.length + 1;
32008
+ const commitLine = lines.findIndex(
32009
+ (line, index) => index >= phase.line - 1 && index < nextPhaseLine - 1 && line.startsWith("- Phase completion commit:")
32010
+ );
32011
+ if (commitLine < 0) throw new Error(`${phase.id} lacks a completion commit field`);
32012
+ lines[commitLine] = `- Phase completion commit: \`${phaseCommit}\``;
32013
+ }
32014
+ return lines.join("\n");
32015
+ }
31707
32016
  function previewExecutionFinish(input) {
31708
32017
  if (!SHA.test(input.headCommit)) throw new Error("headCommit must be a Git commit SHA");
31709
32018
  if (!Number.isFinite(Date.parse(input.completedAt))) throw new Error("completedAt must be an ISO timestamp");
@@ -31722,14 +32031,30 @@ function previewExecutionFinish(input) {
31722
32031
  }
31723
32032
  const unfinished = Object.values(journal.nodes).filter((node) => node.status !== "completed");
31724
32033
  if (unfinished.length) throw new Error(`execution has unfinished nodes: ${unfinished.map((node) => node.id).join(", ")}`);
32034
+ const commits = [
32035
+ input.headCommit,
32036
+ journal.baseCommit,
32037
+ journal.planCommit,
32038
+ ...Object.values(journal.nodes).flatMap((node) => [node.workerCommit, node.mergeCommit].filter(Boolean))
32039
+ ];
32040
+ const reachability = reachableGitCommits(input.projectRoot, commits);
32041
+ const unreachable = reachability ? commits.filter((commit) => reachability.get(commit) === false) : [];
32042
+ if (unreachable.length) throw new Error(`execution contains unreachable commits: ${[...new Set(unreachable)].join(", ")}`);
31725
32043
  const planPath = join2(dirname(statePath), "plan.md");
32044
+ const planBody = readFileSync3(planPath, "utf8");
31726
32045
  const planErrors = [];
31727
- const graph = parsePlan(planPath, planErrors);
31728
- validatePlanGraph(planPath, graph, "ready_for_review", planErrors);
32046
+ const graph = parsePlanContent(planBody, planPath, planErrors);
32047
+ validatePlanGraph(planPath, graph, "in_progress", planErrors);
31729
32048
  if (planErrors.length) throw new Error(planErrors.join("\n"));
31730
32049
  if (graph.digest !== journal.graphDigest || graph.planRevision !== journal.planRevision) {
31731
32050
  throw new Error("approved plan changed during execution");
31732
32051
  }
32052
+ const planContent = renderCompletedPlan(planBody, graph, journal);
32053
+ const completedPlanErrors = [];
32054
+ const completedGraph = parsePlanContent(planContent, planPath, completedPlanErrors);
32055
+ validatePlanGraph(planPath, completedGraph, "ready_for_review", completedPlanErrors);
32056
+ if (completedPlanErrors.length) throw new Error(completedPlanErrors.join("\n"));
32057
+ if (completedGraph.digest !== journal.graphDigest) throw new Error("completed plan changed the approved execution graph");
31733
32058
  const worktreeRoot = join2(safeProjectRoot(input.projectRoot), ".cadre", ".worktrees", input.trackId, input.executionId);
31734
32059
  if (existsSync4(worktreeRoot) && readdirSync2(worktreeRoot).length) {
31735
32060
  throw new Error(`execution still has managed worktrees under ${worktreeRoot}`);
@@ -31766,14 +32091,18 @@ function previewExecutionFinish(input) {
31766
32091
  journal: completedJournal,
31767
32092
  statePath,
31768
32093
  state: completedState,
32094
+ planPath,
32095
+ planContent,
31769
32096
  tracksPath,
31770
32097
  tracksContent,
31771
32098
  digest: hash2({
31772
32099
  stateBody,
31773
32100
  journalBody,
32101
+ planBody,
31774
32102
  tracksBody,
31775
32103
  journal: completedJournal,
31776
32104
  state: completedState,
32105
+ planContent,
31777
32106
  tracksContent
31778
32107
  })
31779
32108
  };
@@ -31781,24 +32110,28 @@ function previewExecutionFinish(input) {
31781
32110
  function applyExecutionFinish(input, proposalDigest) {
31782
32111
  const proposal = previewExecutionFinish(input);
31783
32112
  if (proposal.digest !== proposalDigest) throw new Error("execution completion proposal is stale; preview it again");
31784
- if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink() || lstatSync(proposal.tracksPath).isSymbolicLink()) {
32113
+ if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink() || lstatSync(proposal.planPath).isSymbolicLink() || lstatSync(proposal.tracksPath).isSymbolicLink()) {
31785
32114
  throw new Error("refusing to complete execution through a symbolic link");
31786
32115
  }
31787
32116
  const journalTemporaryPath = join2(dirname(proposal.journalPath), `.${basename(proposal.journalPath)}.${process.pid}.${randomUUID()}.tmp`);
31788
32117
  const stateTemporaryPath = join2(dirname(proposal.statePath), `.${basename(proposal.statePath)}.${process.pid}.${randomUUID()}.tmp`);
32118
+ const planTemporaryPath = join2(dirname(proposal.planPath), `.${basename(proposal.planPath)}.${process.pid}.${randomUUID()}.tmp`);
31789
32119
  const tracksTemporaryPath = join2(dirname(proposal.tracksPath), `.${basename(proposal.tracksPath)}.${process.pid}.${randomUUID()}.tmp`);
31790
32120
  try {
31791
32121
  writeFileSync(journalTemporaryPath, `${JSON.stringify(proposal.journal, null, 2)}
31792
32122
  `, { flag: "wx" });
31793
32123
  writeFileSync(stateTemporaryPath, `${JSON.stringify(proposal.state, null, 2)}
31794
32124
  `, { flag: "wx" });
32125
+ writeFileSync(planTemporaryPath, proposal.planContent, { flag: "wx" });
31795
32126
  writeFileSync(tracksTemporaryPath, proposal.tracksContent, { flag: "wx" });
31796
32127
  renameSync(journalTemporaryPath, proposal.journalPath);
31797
32128
  renameSync(stateTemporaryPath, proposal.statePath);
32129
+ renameSync(planTemporaryPath, proposal.planPath);
31798
32130
  renameSync(tracksTemporaryPath, proposal.tracksPath);
31799
32131
  } finally {
31800
32132
  if (existsSync4(journalTemporaryPath)) unlinkSync(journalTemporaryPath);
31801
32133
  if (existsSync4(stateTemporaryPath)) unlinkSync(stateTemporaryPath);
32134
+ if (existsSync4(planTemporaryPath)) unlinkSync(planTemporaryPath);
31802
32135
  if (existsSync4(tracksTemporaryPath)) unlinkSync(tracksTemporaryPath);
31803
32136
  }
31804
32137
  return proposal;
@@ -31815,8 +32148,8 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31815
32148
  errors.push(`${state.trackId}: invalid execution journal path`);
31816
32149
  return;
31817
32150
  }
31818
- const path = resolve3(trackRoot, relative5);
31819
- if (!path.startsWith(`${resolve3(trackRoot)}/`)) {
32151
+ const path = resolve4(trackRoot, relative5);
32152
+ if (!path.startsWith(`${resolve4(trackRoot)}/`)) {
31820
32153
  errors.push(`${state.trackId}: execution journal escapes track root`);
31821
32154
  return;
31822
32155
  }
@@ -31927,6 +32260,22 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31927
32260
  }
31928
32261
 
31929
32262
  // src/domain/state.ts
32263
+ function collectCommitReferences(value, owner, references, commitContext = false) {
32264
+ if (Array.isArray(value)) {
32265
+ value.forEach((entry, index) => collectCommitReferences(entry, `${owner}[${index}]`, references, commitContext));
32266
+ return;
32267
+ }
32268
+ if (!value || typeof value !== "object") return;
32269
+ for (const [key, child] of Object.entries(value)) {
32270
+ const childOwner = `${owner}.${key}`;
32271
+ const isCommit = commitContext || /^(?:commit|.*Commit|reviewedHead)$/.test(key);
32272
+ if (isCommit && typeof child === "string" && /^[0-9a-f]{7,40}$/.test(child)) {
32273
+ references.push({ owner: childOwner, commit: child });
32274
+ } else {
32275
+ collectCommitReferences(child, childOwner, references, key === "commits");
32276
+ }
32277
+ }
32278
+ }
31930
32279
  var TRACK_STATUSES = /* @__PURE__ */ new Set([
31931
32280
  "drafting-spec",
31932
32281
  "drafting-plan",
@@ -31952,7 +32301,7 @@ var REQUIRED_CONTEXT = [
31952
32301
  "tracks.md"
31953
32302
  ];
31954
32303
  function cadreRoot(projectRoot) {
31955
- return join3(resolve4(projectRoot), ".cadre");
32304
+ return join3(resolve5(projectRoot), ".cadre");
31956
32305
  }
31957
32306
  function readJson(path, errors) {
31958
32307
  try {
@@ -32213,6 +32562,8 @@ function validateProject(projectRoot) {
32213
32562
  }
32214
32563
  const project = readJson(join3(root, "project.json"), errors);
32215
32564
  if (!project) return { project: null, tracks: [], states: /* @__PURE__ */ new Map(), errors, warnings };
32565
+ const commitReferences = [];
32566
+ collectCommitReferences(project, "project.json", commitReferences);
32216
32567
  if (project.schemaVersion !== 1) errors.push("project.json: unsupported schemaVersion");
32217
32568
  if (project.runtimeVersion !== CADRE_RUNTIME_VERSION) errors.push(`project.json: runtimeVersion must be ${CADRE_RUNTIME_VERSION}`);
32218
32569
  if (project.templateSetVersion !== TEMPLATE_SET_VERSION) errors.push(`project.json: templateSetVersion must be ${TEMPLATE_SET_VERSION}`);
@@ -32239,6 +32590,7 @@ function validateProject(projectRoot) {
32239
32590
  const { tracks, states, byId } = discoverTracks(root, errors);
32240
32591
  for (const track of tracks) {
32241
32592
  const state = states.get(track.id);
32593
+ collectCommitReferences(state, `${track.id}/state.json`, commitReferences);
32242
32594
  const trackRoot = join3(root, track.location);
32243
32595
  if (state.schemaVersion !== 1) errors.push(`${track.id}: unsupported state schemaVersion`);
32244
32596
  if (!state.title || typeof state.title !== "string") errors.push(`${track.id}: title is required`);
@@ -32275,14 +32627,45 @@ function validateProject(projectRoot) {
32275
32627
  if (existsSync5(specPath)) validateSpec(specPath, errors);
32276
32628
  else if (track.status !== "drafting-spec" && state?.operation?.action !== "specify") errors.push(`${track.id}: missing spec.md`);
32277
32629
  let planGraph = null;
32278
- if (existsSync5(planPath)) planGraph = readAndValidatePlan(planPath, track.status, errors);
32279
- else if (["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && state?.operation?.action !== "plan") errors.push(`${track.id}: missing plan.md`);
32630
+ if (existsSync5(planPath)) {
32631
+ planGraph = readAndValidatePlan(planPath, track.status, errors);
32632
+ for (const phase of planGraph.phases) {
32633
+ if (phase.completionCommit) commitReferences.push({
32634
+ owner: `${track.id}/plan.md:${phase.id}`,
32635
+ commit: phase.completionCommit
32636
+ });
32637
+ for (const task of phase.tasks) if (task.commit) commitReferences.push({
32638
+ owner: `${track.id}/plan.md:${task.id}`,
32639
+ commit: task.commit
32640
+ });
32641
+ }
32642
+ } else if (["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && state?.operation?.action !== "plan") errors.push(`${track.id}: missing plan.md`);
32280
32643
  validateLearning(
32281
32644
  learningPath,
32282
32645
  ["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && state?.operation?.action !== "plan",
32283
32646
  errors
32284
32647
  );
32285
32648
  validateExecutionJournal(trackRoot, state, planGraph, errors);
32649
+ const executionReference = state.operation?.action === "implement" ? state.operation : state.lastExecution;
32650
+ const journalRelative2 = typeof executionReference?.journal === "string" ? executionReference.journal : null;
32651
+ if (journalRelative2 && /^executions\/execution-[0-9A-Za-z-]+\.json$/.test(journalRelative2)) {
32652
+ const journalPath = join3(trackRoot, journalRelative2);
32653
+ if (existsSync5(journalPath)) {
32654
+ try {
32655
+ collectCommitReferences(JSON.parse(readFileSync4(journalPath, "utf8")), `${track.id}/${journalRelative2}`, commitReferences);
32656
+ } catch {
32657
+ }
32658
+ }
32659
+ }
32660
+ const revisionsPath = join3(trackRoot, "revisions");
32661
+ if (existsSync5(revisionsPath)) {
32662
+ for (const file2 of readdirSync3(revisionsPath).filter((entry) => entry.endsWith(".md"))) {
32663
+ const content = readFileSync4(join3(revisionsPath, file2), "utf8");
32664
+ for (const match of content.matchAll(/^- Revision commit: `([0-9a-f]{7,40})`$/gm)) {
32665
+ commitReferences.push({ owner: `${track.id}/revisions/${file2}`, commit: match[1] });
32666
+ }
32667
+ }
32668
+ }
32286
32669
  if (["ready_for_review", "completed", "archived"].includes(track.status)) {
32287
32670
  const managedRoot = join3(root, ".worktrees", track.id);
32288
32671
  if (existsSync5(managedRoot) && readdirSync3(managedRoot).length) {
@@ -32323,6 +32706,14 @@ function validateProject(projectRoot) {
32323
32706
  visited.add(id);
32324
32707
  }
32325
32708
  for (const id of byId.keys()) visit(id, []);
32709
+ const reachability = reachableGitCommits(projectRoot, commitReferences.map((reference) => reference.commit));
32710
+ if (reachability) {
32711
+ for (const reference of commitReferences) {
32712
+ if (reachability.get(reference.commit) === false) {
32713
+ errors.push(`${reference.owner}: commit is not reachable: ${reference.commit}`);
32714
+ }
32715
+ }
32716
+ }
32326
32717
  const tracksPath = join3(root, "tracks.md");
32327
32718
  if (existsSync5(tracksPath) && readFileSync4(tracksPath, "utf8") !== buildTracks(tracks)) {
32328
32719
  warnings.push("TRACKS_INDEX_STALE: tracks.md is stale; regenerate it after approved state changes");
@@ -32392,7 +32783,7 @@ function formatStatus(projectRoot) {
32392
32783
  // src/domain/templates.ts
32393
32784
  import { createHash as createHash4 } from "node:crypto";
32394
32785
  import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync as readdirSync4 } from "node:fs";
32395
- import { dirname as dirname2, extname, join as join4, relative, resolve as resolve5, sep } from "node:path";
32786
+ import { dirname as dirname2, extname, join as join4, relative, resolve as resolve6, sep } from "node:path";
32396
32787
  import { fileURLToPath } from "node:url";
32397
32788
  var TEMPLATE_IDS = [
32398
32789
  "project/archive-operation",
@@ -32439,8 +32830,8 @@ function locateTemplateRoot() {
32439
32830
  const moduleDirectory = dirname2(fileURLToPath(import.meta.url));
32440
32831
  const candidates = [
32441
32832
  process.env.CADRE_TEMPLATE_ROOT,
32442
- resolve5(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
32443
- resolve5(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
32833
+ resolve6(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
32834
+ resolve6(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
32444
32835
  ].filter((candidate) => Boolean(candidate));
32445
32836
  const found = candidates.find((candidate) => existsSync6(candidate));
32446
32837
  if (!found) throw new Error(`Cadre template set ${TEMPLATE_SET_VERSION} is unavailable`);
@@ -32630,7 +33021,7 @@ function previewProjectInit(input) {
32630
33021
  return { runtimeVersion: CADRE_RUNTIME_VERSION, templateSetVersion: TEMPLATE_SET_VERSION, files, digest };
32631
33022
  }
32632
33023
  function targetWithin(root, relativePath) {
32633
- const target = resolve6(root, relativePath);
33024
+ const target = resolve7(root, relativePath);
32634
33025
  const relation = relative2(root, target);
32635
33026
  if (relation.startsWith("..") || isAbsolute(relation)) throw new Error(`Path escapes initialization root: ${relativePath}`);
32636
33027
  return target;
@@ -32694,7 +33085,7 @@ function recordGitInitialized(projectRootInput) {
32694
33085
  if (project.setup.operation.gitDisposition !== "initialize") {
32695
33086
  throw new Error("Project setup was not approved to initialize Git");
32696
33087
  }
32697
- if (resolve6(String(project.setup.operation.repositoryRoot)) !== root) {
33088
+ if (resolve7(String(project.setup.operation.repositoryRoot)) !== root) {
32698
33089
  throw new Error("Approved Git repository root does not match projectRoot");
32699
33090
  }
32700
33091
  project.setup.checkpoint = "commit-pending";
@@ -32705,16 +33096,16 @@ function recordGitInitialized(projectRootInput) {
32705
33096
 
32706
33097
  // src/domain/worktrees.ts
32707
33098
  import { createHash as createHash6 } from "node:crypto";
32708
- import { existsSync as existsSync8, lstatSync as lstatSync4, readdirSync as readdirSync5, realpathSync, rmdirSync } from "node:fs";
32709
- import { dirname as dirname4, join as join6, relative as relative3, resolve as resolve7 } from "node:path";
32710
- import { spawnSync } from "node:child_process";
33099
+ import { existsSync as existsSync8, lstatSync as lstatSync4, readdirSync as readdirSync5, realpathSync as realpathSync2, rmdirSync } from "node:fs";
33100
+ import { dirname as dirname4, join as join6, relative as relative3, resolve as resolve8 } from "node:path";
33101
+ import { spawnSync as spawnSync2 } from "node:child_process";
32711
33102
  var SHA2 = /^[0-9a-f]{7,40}$/;
32712
33103
  var TRACK_ID2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32713
33104
  var EXECUTION_ID2 = /^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
32714
33105
  var PHASE_ID = /^P\d+$/;
32715
33106
  var TASK_ID = /^T(\d+)\.(\d+)$/;
32716
33107
  function git(cwd, args, allowFailure = false) {
32717
- const result2 = spawnSync("git", args, { cwd, encoding: "utf8" });
33108
+ const result2 = spawnSync2("git", args, { cwd, encoding: "utf8" });
32718
33109
  if (result2.error) throw result2.error;
32719
33110
  const status = result2.status ?? 1;
32720
33111
  const output = { stdout: result2.stdout ?? "", stderr: result2.stderr ?? "", status };
@@ -32725,8 +33116,8 @@ function hash4(value) {
32725
33116
  return createHash6("sha256").update(JSON.stringify(value)).digest("hex");
32726
33117
  }
32727
33118
  function assertRepository(projectRoot) {
32728
- const root = realpathSync(safeProjectRoot(projectRoot));
32729
- const detected = realpathSync(resolve7(git(root, ["rev-parse", "--show-toplevel"]).stdout.trim()));
33119
+ const root = realpathSync2(safeProjectRoot(projectRoot));
33120
+ const detected = realpathSync2(resolve8(git(root, ["rev-parse", "--show-toplevel"]).stdout.trim()));
32730
33121
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
32731
33122
  return root;
32732
33123
  }
@@ -32763,22 +33154,23 @@ function registeredWorktrees(root) {
32763
33154
  let current = {};
32764
33155
  for (const line of git(root, ["worktree", "list", "--porcelain"]).stdout.split(/\r?\n/)) {
32765
33156
  if (!line) {
32766
- if (current.path && current.head) records.push({ path: resolve7(current.path), branch: current.branch ?? null, head: current.head });
33157
+ if (current.path && current.head) records.push({ path: resolve8(current.path), branch: current.branch ?? null, head: current.head });
32767
33158
  current = {};
32768
33159
  } else if (line.startsWith("worktree ")) current.path = line.slice("worktree ".length);
32769
33160
  else if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length);
32770
33161
  else if (line.startsWith("branch refs/heads/")) current.branch = line.slice("branch refs/heads/".length);
32771
33162
  else if (line === "detached") current.branch = null;
32772
33163
  }
32773
- if (current.path && current.head) records.push({ path: resolve7(current.path), branch: current.branch ?? null, head: current.head });
33164
+ if (current.path && current.head) records.push({ path: resolve8(current.path), branch: current.branch ?? null, head: current.head });
32774
33165
  return records;
32775
33166
  }
32776
33167
  function previewWorktreeCreate(input) {
32777
33168
  const root = assertRepository(input.projectRoot);
32778
- const baseCommit = git(root, ["rev-parse", `${input.baseCommit}^{commit}`]).stdout.trim();
33169
+ const target = targetIdentity(root, input);
33170
+ const baseCommit = git(target.path, ["rev-parse", "HEAD^{commit}"]).stdout.trim();
32779
33171
  if (!SHA2.test(baseCommit)) throw new Error("baseCommit does not resolve to a commit");
32780
- const identity = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
32781
- const registered = registeredWorktrees(root).find((entry) => entry.path === resolve7(identity.path));
33172
+ const identity = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
33173
+ const registered = registeredWorktrees(root).find((entry) => entry.path === resolve8(identity.path));
32782
33174
  const existingBranchHead = branchHead(root, identity.branch);
32783
33175
  if (registered && (registered.branch !== identity.branch || registered.head !== existingBranchHead)) {
32784
33176
  throw new Error(`registered worktree disagrees at ${identity.relativePath}`);
@@ -32805,16 +33197,20 @@ function applyWorktreeCreate(input, proposalDigest) {
32805
33197
  git(proposal.projectRoot, args);
32806
33198
  return previewWorktreeCreate(input);
32807
33199
  }
32808
- function cleanWorktree(path) {
32809
- const status = git(path, ["status", "--porcelain"]).stdout.trim();
32810
- if (status) throw new Error(`worktree is not clean: ${path}
32811
- ${status}`);
33200
+ function cleanWorktree(path, allowedPaths = /* @__PURE__ */ new Set()) {
33201
+ const lines = git(path, ["status", "--porcelain", "--untracked-files=all"]).stdout.split(/\r?\n/).filter(Boolean);
33202
+ const unexpected = lines.filter((line) => {
33203
+ const changedPath = line.slice(3).split(" -> ").at(-1) ?? "";
33204
+ return !allowedPaths.has(changedPath);
33205
+ });
33206
+ if (unexpected.length) throw new Error(`worktree is not clean: ${path}
33207
+ ${unexpected.join("\n")}`);
32812
33208
  }
32813
33209
  function targetIdentity(root, input) {
32814
33210
  if (TASK_ID.test(input.nodeId)) {
32815
33211
  const phaseId = phaseForNode(input.nodeId);
32816
33212
  const phase = worktreeIdentity(root, input.trackId, input.executionId, phaseId, null);
32817
- const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve7(phase.path));
33213
+ const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve8(phase.path));
32818
33214
  if (phaseWorktree) {
32819
33215
  if (phaseWorktree.branch !== phase.branch) throw new Error(`phase worktree is not on ${phase.branch}`);
32820
33216
  return { path: phase.path, branch: phase.branch };
@@ -32828,7 +33224,7 @@ function journalNode(input) {
32828
33224
  const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
32829
33225
  const node = journal.nodes[input.nodeId];
32830
33226
  if (!node) throw new Error(`execution journal has no node ${input.nodeId}`);
32831
- assertIds(input.trackId, input.executionId, input.nodeId, input.phaseId);
33227
+ assertIds(input.trackId, input.executionId, input.nodeId);
32832
33228
  if (node.phaseId !== phaseForNode(input.nodeId)) {
32833
33229
  throw new Error(`execution journal identity disagrees for ${input.nodeId}`);
32834
33230
  }
@@ -32855,12 +33251,13 @@ function assertJournalAllowsCleanup(input) {
32855
33251
  function previewWorktreeIntegration(input) {
32856
33252
  assertJournalAllowsIntegration(input);
32857
33253
  const root = assertRepository(input.projectRoot);
32858
- const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
33254
+ const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
32859
33255
  const target = targetIdentity(root, input);
32860
33256
  if (!existsSync8(source.path)) throw new Error(`source worktree is missing: ${source.path}`);
32861
33257
  if (!existsSync8(target.path)) throw new Error(`target worktree is missing: ${target.path}`);
32862
33258
  cleanWorktree(source.path);
32863
- cleanWorktree(target.path);
33259
+ const journalPath = `.cadre/tracks/${input.trackId}/executions/execution-${input.executionId}.json`;
33260
+ cleanWorktree(target.path, target.path === root ? /* @__PURE__ */ new Set([journalPath]) : /* @__PURE__ */ new Set());
32864
33261
  const checkedSource = git(source.path, ["symbolic-ref", "--short", "HEAD"]).stdout.trim();
32865
33262
  const checkedTarget = git(target.path, ["symbolic-ref", "--short", "HEAD"]).stdout.trim();
32866
33263
  if (checkedSource !== source.branch) throw new Error(`source worktree is on ${checkedSource}, expected ${source.branch}`);
@@ -32906,7 +33303,7 @@ function applyWorktreeIntegration(input, proposalDigest) {
32906
33303
  function previewWorktreeCleanup(input) {
32907
33304
  assertJournalAllowsCleanup(input);
32908
33305
  const root = assertRepository(input.projectRoot);
32909
- const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
33306
+ const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
32910
33307
  const target = targetIdentity(root, input);
32911
33308
  if (!existsSync8(source.path)) throw new Error(`worktree is missing: ${source.path}`);
32912
33309
  if (lstatSync4(source.path).isSymbolicLink()) throw new Error("refusing to clean up a symbolic-link worktree");
@@ -32949,14 +33346,14 @@ function managedWorktreeStatus(projectRoot) {
32949
33346
  const orphanedDirectories = [];
32950
33347
  function walk2(directory) {
32951
33348
  if (!existsSync8(directory)) return;
32952
- if (registered.has(resolve7(directory))) return;
33349
+ if (registered.has(resolve8(directory))) return;
32953
33350
  const entries = readdirSync5(directory, { withFileTypes: true });
32954
33351
  if (entries.some((entry) => entry.name === ".git")) {
32955
33352
  orphanedDirectories.push(directory);
32956
33353
  return;
32957
33354
  }
32958
33355
  for (const entry of entries) if (entry.isDirectory()) walk2(join6(directory, entry.name));
32959
- if (!entries.length && resolve7(directory) !== resolve7(managedRoot)) orphanedDirectories.push(directory);
33356
+ if (!entries.length && resolve8(directory) !== resolve8(managedRoot)) orphanedDirectories.push(directory);
32960
33357
  }
32961
33358
  walk2(managedRoot);
32962
33359
  return { worktrees, orphanedDirectories };
@@ -33000,6 +33397,25 @@ function requireCurrentProject(projectRoot) {
33000
33397
  if (!validation.project) throw new Error("Cadre project state is unavailable");
33001
33398
  return validation;
33002
33399
  }
33400
+ function deriveReviewCompleteInput(input) {
33401
+ const validation = requireCurrentProject(input.projectRoot);
33402
+ const state = validation.states.get(input.trackId);
33403
+ const reviewedHead = state?.lastExecution?.headCommit;
33404
+ if (!reviewedHead || !SHA3.test(reviewedHead)) throw new Error(`${input.trackId} has no completed execution head`);
33405
+ if (!isGitAncestor(input.projectRoot, reviewedHead)) {
33406
+ throw new Error(`completed execution head ${reviewedHead} is not an ancestor of current HEAD`);
33407
+ }
33408
+ const commitRangeStart = resolveGitCommit(input.projectRoot, input.commitRangeStart);
33409
+ return {
33410
+ projectRoot: input.projectRoot,
33411
+ trackId: input.trackId,
33412
+ reviewedAt: (/* @__PURE__ */ new Date()).toISOString(),
33413
+ reviewedHead,
33414
+ commitRange: `${commitRangeStart}..${reviewedHead}`,
33415
+ approval: input.approval,
33416
+ ...input.acceptedRisks ? { acceptedRisks: input.acceptedRisks } : {}
33417
+ };
33418
+ }
33003
33419
  function previewReviewComplete(input) {
33004
33420
  if (!TRACK_ID3.test(input.trackId)) throw new Error("invalid trackId");
33005
33421
  if (!SHA3.test(input.reviewedHead)) throw new Error("reviewedHead must be a Git commit SHA");
@@ -33066,6 +33482,59 @@ function applyReviewComplete(input, proposalDigest) {
33066
33482
  }
33067
33483
  return { ...proposal, valid: true, derivedStateCurrent: true };
33068
33484
  }
33485
+ function dependencyOrder(tracks) {
33486
+ const included = new Set(tracks.map((track) => track.id));
33487
+ const byId = new Map(tracks.map((track) => [track.id, track]));
33488
+ const ordered = [];
33489
+ const visiting = /* @__PURE__ */ new Set();
33490
+ const visited = /* @__PURE__ */ new Set();
33491
+ const visit = (trackId) => {
33492
+ if (visited.has(trackId)) return;
33493
+ if (visiting.has(trackId)) throw new Error(`track dependency cycle includes ${trackId}`);
33494
+ visiting.add(trackId);
33495
+ for (const dependency of byId.get(trackId)?.dependencies ?? []) {
33496
+ if (included.has(dependency)) visit(dependency);
33497
+ }
33498
+ visiting.delete(trackId);
33499
+ visited.add(trackId);
33500
+ ordered.push(trackId);
33501
+ };
33502
+ for (const track of tracks) visit(track.id);
33503
+ return ordered;
33504
+ }
33505
+ function deriveArchiveBatchInput(input) {
33506
+ const root = safeProjectRoot(input.projectRoot);
33507
+ const validation = requireCurrentProject(root);
33508
+ const operationsPath = join7(cadreRoot(root), "operations");
33509
+ const activeOperation = existsSync9(operationsPath) ? readdirSync6(operationsPath).filter((file2) => file2.endsWith(".json")).map(
33510
+ (file2) => JSON.parse(readFileSync7(join7(operationsPath, file2), "utf8"))
33511
+ ).find((operation) => operation.action === "archive" && operation.status === "in_progress") : void 0;
33512
+ const selectedTracks = input.selectedTracks?.length ? [...new Set(input.selectedTracks)] : activeOperation?.selectedTracks ?? dependencyOrder(
33513
+ validation.tracks.filter((track) => track.status === "completed" && track.location === `tracks/${track.id}`)
33514
+ );
33515
+ if (!selectedTracks.length) throw new Error("there are no completed tracks to archive");
33516
+ if (activeOperation && JSON.stringify(selectedTracks) !== JSON.stringify(activeOperation.selectedTracks)) {
33517
+ throw new Error(`active archive batch ${activeOperation.batchId} must be resumed with its original selection`);
33518
+ }
33519
+ const now = (/* @__PURE__ */ new Date()).toISOString();
33520
+ const updates = input.updates.map((update) => {
33521
+ if (update.kind === "pattern") {
33522
+ if (!TRACK_ID3.test(update.slug)) throw new Error(`invalid pattern slug ${update.slug}`);
33523
+ return { path: `patterns/${update.slug}.md`, content: update.content };
33524
+ }
33525
+ if (update.kind === "pattern_index") return { path: "patterns/index.md", content: update.content };
33526
+ if (!TRACK_ID3.test(update.trackId)) throw new Error(`invalid active track ID ${update.trackId}`);
33527
+ return { path: `tracks/${update.trackId}/learning.md`, content: update.content };
33528
+ });
33529
+ return {
33530
+ projectRoot: root,
33531
+ batchId: activeOperation?.batchId ?? `archive-${now.replace(/[:.]/g, "-")}`,
33532
+ selectedTracks,
33533
+ baseCommit: activeOperation?.baseCommit ?? resolveGitCommit(root),
33534
+ approvedAt: activeOperation?.approvedAt ?? now,
33535
+ updates
33536
+ };
33537
+ }
33069
33538
  function assertArchiveUpdate(path, selected) {
33070
33539
  if (path === "patterns/index.md" || /^patterns\/[a-z0-9]+(?:-[a-z0-9]+)*\.md$/.test(path)) return;
33071
33540
  const seed = path.match(/^tracks\/([a-z0-9]+(?:-[a-z0-9]+)*)\/learning\.md$/);
@@ -33224,6 +33693,9 @@ function applyArchiveBatch(input, proposalDigest) {
33224
33693
  }
33225
33694
  return { ...proposal, valid: true, derivedStateCurrent: true };
33226
33695
  }
33696
+ function deriveArchiveBatchRecordInput(input) {
33697
+ return { ...input, archiveCommit: resolveGitCommit(input.projectRoot) };
33698
+ }
33227
33699
  function previewArchiveBatchRecord(input) {
33228
33700
  if (!BATCH_ID.test(input.batchId)) throw new Error("invalid archive batchId");
33229
33701
  if (!SHA3.test(input.archiveCommit)) throw new Error("archiveCommit must be a Git commit SHA");
@@ -33514,6 +33986,199 @@ function normalizeWorkflowElicitation(input, elicited) {
33514
33986
  };
33515
33987
  }
33516
33988
 
33989
+ // src/mcp/proposals.ts
33990
+ import { randomBytes } from "node:crypto";
33991
+ import {
33992
+ chmodSync,
33993
+ closeSync,
33994
+ existsSync as existsSync10,
33995
+ fstatSync,
33996
+ fsyncSync,
33997
+ lstatSync as lstatSync6,
33998
+ mkdirSync as mkdirSync4,
33999
+ openSync,
34000
+ readFileSync as readFileSync8,
34001
+ readdirSync as readdirSync7,
34002
+ unlinkSync as unlinkSync2,
34003
+ writeFileSync as writeFileSync5
34004
+ } from "node:fs";
34005
+ import { homedir as homedir2 } from "node:os";
34006
+ import { constants } from "node:fs";
34007
+ import { join as join8, resolve as resolve10 } from "node:path";
34008
+ var TOKEN_PREFIX = "cadre_pt1_";
34009
+ var TOKEN_PATTERN = /^cadre_pt1_[A-Za-z0-9_-]{32}$/;
34010
+ var RECORD_PATTERN = /^cadre_pt1_[A-Za-z0-9_-]{32}\.json$/;
34011
+ var MAX_PROPOSAL_BYTES = 8 * 1024 * 1024;
34012
+ var DEFAULT_MAX_RETAINED_PROPOSALS = 256;
34013
+ var DEFAULT_MAX_RETAINED_BYTES = 32 * 1024 * 1024;
34014
+ var DEFAULT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
34015
+ var envelopeSchema = external_exports.object({
34016
+ version: external_exports.literal(2),
34017
+ kind: external_exports.string().min(1),
34018
+ input: external_exports.unknown(),
34019
+ digest: external_exports.string().regex(/^[0-9a-f]{64}$/),
34020
+ createdAt: external_exports.iso.datetime()
34021
+ });
34022
+ var proposalTokenSchema = external_exports.string().regex(TOKEN_PATTERN, "invalid proposal token format");
34023
+ function defaultProposalRoot() {
34024
+ const cadreHome = process.env.CADRE_HOME ? resolve10(process.env.CADRE_HOME) : join8(homedir2(), ".cadre");
34025
+ return join8(cadreHome, "runtime", "proposals");
34026
+ }
34027
+ var ProposalTokenStore = class {
34028
+ root;
34029
+ maxRetainedProposals;
34030
+ maxRetainedBytes;
34031
+ maxAgeMs;
34032
+ now;
34033
+ constructor(options = {}) {
34034
+ this.root = resolve10(options.root ?? defaultProposalRoot());
34035
+ this.maxRetainedProposals = options.maxRetainedProposals ?? DEFAULT_MAX_RETAINED_PROPOSALS;
34036
+ this.maxRetainedBytes = options.maxRetainedBytes ?? DEFAULT_MAX_RETAINED_BYTES;
34037
+ this.maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
34038
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
34039
+ if (!Number.isInteger(this.maxRetainedProposals) || this.maxRetainedProposals < 1) {
34040
+ throw new Error("maxRetainedProposals must be a positive integer");
34041
+ }
34042
+ if (!Number.isInteger(this.maxRetainedBytes) || this.maxRetainedBytes < MAX_PROPOSAL_BYTES) {
34043
+ throw new Error(`maxRetainedBytes must be at least ${MAX_PROPOSAL_BYTES}`);
34044
+ }
34045
+ if (!Number.isFinite(this.maxAgeMs) || this.maxAgeMs <= 0) {
34046
+ throw new Error("maxAgeMs must be positive");
34047
+ }
34048
+ }
34049
+ issue(kind, input, digest) {
34050
+ const createdAt = this.now().toISOString();
34051
+ const serialized = `${JSON.stringify({ version: 2, kind, input, digest, createdAt })}
34052
+ `;
34053
+ const bytes = Buffer.byteLength(serialized, "utf8");
34054
+ if (bytes > MAX_PROPOSAL_BYTES) throw new Error("proposal is too large");
34055
+ envelopeSchema.parse(JSON.parse(serialized));
34056
+ this.prepareRoot();
34057
+ this.makeRoom(bytes);
34058
+ for (; ; ) {
34059
+ const token = `${TOKEN_PREFIX}${randomBytes(24).toString("base64url")}`;
34060
+ const path = this.pathFor(token);
34061
+ let descriptor = null;
34062
+ try {
34063
+ descriptor = openSync(
34064
+ path,
34065
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
34066
+ 384
34067
+ );
34068
+ writeFileSync5(descriptor, serialized, "utf8");
34069
+ fsyncSync(descriptor);
34070
+ return token;
34071
+ } catch (error51) {
34072
+ if (error51.code !== "EEXIST") throw error51;
34073
+ } finally {
34074
+ if (descriptor !== null) closeSync(descriptor);
34075
+ }
34076
+ }
34077
+ }
34078
+ resolve(kind, token) {
34079
+ if (!TOKEN_PATTERN.test(token)) throw new Error("invalid proposal token format");
34080
+ this.prepareRoot();
34081
+ const path = this.pathFor(token);
34082
+ if (!existsSync10(path)) {
34083
+ throw new Error(
34084
+ "proposal token is unknown or no longer retained; call the matching preview tool again"
34085
+ );
34086
+ }
34087
+ let descriptor = null;
34088
+ try {
34089
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
34090
+ const stat = fstatSync(descriptor);
34091
+ if (!stat.isFile()) throw new Error("proposal token does not reference a regular runtime record");
34092
+ if ((stat.mode & 63) !== 0) throw new Error("proposal runtime record permissions are too broad");
34093
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
34094
+ throw new Error("proposal runtime record is owned by another user");
34095
+ }
34096
+ if (stat.size > MAX_PROPOSAL_BYTES) throw new Error("proposal record is too large");
34097
+ const envelope = envelopeSchema.parse(JSON.parse(readFileSync8(descriptor, "utf8")));
34098
+ if (this.now().getTime() - Date.parse(envelope.createdAt) > this.maxAgeMs) {
34099
+ closeSync(descriptor);
34100
+ descriptor = null;
34101
+ this.unlinkRecord(path);
34102
+ throw new Error("proposal token has expired; call the matching preview tool again");
34103
+ }
34104
+ if (envelope.kind !== kind) throw new Error(`proposal token is for ${envelope.kind}, not ${kind}`);
34105
+ return { input: envelope.input, digest: envelope.digest };
34106
+ } catch (error51) {
34107
+ if (error51.code === "ELOOP") {
34108
+ throw new Error("refusing proposal token through a symbolic link");
34109
+ }
34110
+ if (error51.code === "ENOENT") {
34111
+ throw new Error(
34112
+ "proposal token is unknown or no longer retained; call the matching preview tool again"
34113
+ );
34114
+ }
34115
+ throw error51;
34116
+ } finally {
34117
+ if (descriptor !== null) closeSync(descriptor);
34118
+ }
34119
+ }
34120
+ prepareRoot() {
34121
+ mkdirSync4(this.root, { recursive: true, mode: 448 });
34122
+ const stat = lstatSync6(this.root);
34123
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
34124
+ throw new Error(`proposal runtime root is not a regular directory: ${this.root}`);
34125
+ }
34126
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
34127
+ throw new Error(`proposal runtime root is owned by another user: ${this.root}`);
34128
+ }
34129
+ if ((stat.mode & 63) !== 0) chmodSync(this.root, 448);
34130
+ }
34131
+ pathFor(token) {
34132
+ return join8(this.root, `${token}.json`);
34133
+ }
34134
+ records() {
34135
+ const records = [];
34136
+ for (const entry of readdirSync7(this.root)) {
34137
+ if (!RECORD_PATTERN.test(entry)) continue;
34138
+ const path = join8(this.root, entry);
34139
+ let stat;
34140
+ try {
34141
+ stat = lstatSync6(path);
34142
+ } catch (error51) {
34143
+ if (error51.code === "ENOENT") continue;
34144
+ throw error51;
34145
+ }
34146
+ if (!stat.isFile() || stat.isSymbolicLink()) continue;
34147
+ let createdAt = stat.mtimeMs;
34148
+ try {
34149
+ const envelope = envelopeSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
34150
+ createdAt = Date.parse(envelope.createdAt);
34151
+ } catch {
34152
+ }
34153
+ records.push({ path, bytes: stat.size, createdAt });
34154
+ }
34155
+ return records.sort((left, right) => left.createdAt - right.createdAt);
34156
+ }
34157
+ makeRoom(incomingBytes) {
34158
+ const now = this.now().getTime();
34159
+ let records = this.records();
34160
+ for (const record2 of records) {
34161
+ if (now - record2.createdAt <= this.maxAgeMs) continue;
34162
+ this.unlinkRecord(record2.path);
34163
+ }
34164
+ records = this.records();
34165
+ let retainedBytes = records.reduce((total, record2) => total + record2.bytes, 0);
34166
+ while (records.length >= this.maxRetainedProposals || retainedBytes + incomingBytes > this.maxRetainedBytes) {
34167
+ const oldest = records.shift();
34168
+ if (!oldest) break;
34169
+ this.unlinkRecord(oldest.path);
34170
+ retainedBytes -= oldest.bytes;
34171
+ }
34172
+ }
34173
+ unlinkRecord(path) {
34174
+ try {
34175
+ unlinkSync2(path);
34176
+ } catch (error51) {
34177
+ if (error51.code !== "ENOENT") throw error51;
34178
+ }
34179
+ }
34180
+ };
34181
+
33517
34182
  // src/mcp/server.ts
33518
34183
  function result(value, summary) {
33519
34184
  return {
@@ -33521,8 +34186,18 @@ function result(value, summary) {
33521
34186
  structuredContent: value
33522
34187
  };
33523
34188
  }
33524
- function proposalResult(value) {
33525
- return result({ ...value, proposalDigest: value.digest });
34189
+ function sha256(content) {
34190
+ return createHash8("sha256").update(content).digest("hex");
34191
+ }
34192
+ function artifact(path, content) {
34193
+ return { path, sha256: sha256(content) };
34194
+ }
34195
+ function jsonArtifact(path, value) {
34196
+ return artifact(path, `${JSON.stringify(value, null, 2)}
34197
+ `);
34198
+ }
34199
+ function proposalInputSchema() {
34200
+ return { proposalToken: proposalTokenSchema };
33526
34201
  }
33527
34202
  function failure(error51) {
33528
34203
  const serialized = serializeCadreError(error51);
@@ -33556,6 +34231,13 @@ var PLAN_VALIDATION_STATUSES = [
33556
34231
  ];
33557
34232
  var MAX_DRAFT_PLAN_CHARACTERS = 256 * 1024;
33558
34233
  function createCadreServer() {
34234
+ const proposalTokens = new ProposalTokenStore();
34235
+ function proposalResult(kind, input, value) {
34236
+ return result({
34237
+ ...value,
34238
+ proposalToken: proposalTokens.issue(kind, input, value.digest)
34239
+ });
34240
+ }
33559
34241
  const server = new McpServer(
33560
34242
  { name: "cadre", version: CADRE_RUNTIME_VERSION },
33561
34243
  {
@@ -33564,7 +34246,7 @@ function createCadreServer() {
33564
34246
  "Read every existing artifact before proposing edits. Never infer file contents.",
33565
34247
  "For any mutation, present the complete proposed artifacts to the human and obtain approval first.",
33566
34248
  "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.",
33567
- "Call a preview tool immediately before its matching apply tool and pass the returned digest unchanged.",
34249
+ "Call a preview tool immediately before its matching apply tool and pass only the returned proposal token.",
33568
34250
  "Cadre state is resumable: inspect project_status once at command entry and reserve state_validate for final mutation gates.",
33569
34251
  "The plan is the implementation source of truth. Cadre MCP exposes only constrained, digest-gated Git worktree operations and never approves its own changes."
33570
34252
  ].join(" ")
@@ -33614,7 +34296,7 @@ function createCadreServer() {
33614
34296
  server.registerTool("template_get", {
33615
34297
  title: "Get a Cadre template",
33616
34298
  description: "Read one immutable, versioned Cadre template by logical identifier.",
33617
- inputSchema: { id: external_exports.string().min(1) },
34299
+ inputSchema: { id: external_exports.enum(TEMPLATE_IDS) },
33618
34300
  annotations: { readOnlyHint: true, openWorldHint: false }
33619
34301
  }, async ({ id }) => {
33620
34302
  try {
@@ -33626,7 +34308,7 @@ function createCadreServer() {
33626
34308
  server.registerTool("template_get_many", {
33627
34309
  title: "Get multiple Cadre templates",
33628
34310
  description: "Read an ordered set of immutable, versioned Cadre templates in one call.",
33629
- inputSchema: { ids: external_exports.array(external_exports.string().min(1)).min(1) },
34311
+ inputSchema: { ids: external_exports.array(external_exports.enum(TEMPLATE_IDS)).min(1) },
33630
34312
  annotations: { readOnlyHint: true, openWorldHint: false }
33631
34313
  }, async ({ ids }) => {
33632
34314
  try {
@@ -33683,9 +34365,9 @@ function createCadreServer() {
33683
34365
  }, async ({ projectRoot, trackId }) => {
33684
34366
  try {
33685
34367
  const root = safeProjectRoot(projectRoot);
33686
- const statePath = join8(root, ".cadre", "tracks", trackId, "state.json");
33687
- const planPath = join8(root, ".cadre", "tracks", trackId, "plan.md");
33688
- const state = JSON.parse(readFileSync8(statePath, "utf8"));
34368
+ const statePath = join9(root, ".cadre", "tracks", trackId, "state.json");
34369
+ const planPath = join9(root, ".cadre", "tracks", trackId, "plan.md");
34370
+ const state = JSON.parse(readFileSync9(statePath, "utf8"));
33689
34371
  const errors = [];
33690
34372
  const graph = parsePlan(planPath, errors);
33691
34373
  validatePlanGraph(planPath, graph, state.status ?? "planned", errors);
@@ -33717,9 +34399,7 @@ function createCadreServer() {
33717
34399
  const reviewCompleteSchema = {
33718
34400
  projectRoot: external_exports.string().min(1),
33719
34401
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33720
- reviewedAt: external_exports.iso.datetime(),
33721
- reviewedHead: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33722
- commitRange: external_exports.string().regex(/^[0-9a-f]{7,40}\.\.[0-9a-f]{7,40}$/),
34402
+ commitRangeStart: external_exports.string().min(1),
33723
34403
  approval: external_exports.string().min(1),
33724
34404
  acceptedRisks: external_exports.array(external_exports.string().min(1)).optional()
33725
34405
  };
@@ -33730,7 +34410,19 @@ function createCadreServer() {
33730
34410
  annotations: { readOnlyHint: true, openWorldHint: false }
33731
34411
  }, async (input) => {
33732
34412
  try {
33733
- return proposalResult(previewReviewComplete(input));
34413
+ const derived = deriveReviewCompleteInput(input);
34414
+ const preview = previewReviewComplete(derived);
34415
+ return proposalResult("review_complete", derived, {
34416
+ digest: preview.digest,
34417
+ trackId: derived.trackId,
34418
+ reviewedHead: derived.reviewedHead,
34419
+ commitRange: derived.commitRange,
34420
+ targetStatus: preview.state.status,
34421
+ files: [
34422
+ jsonArtifact(preview.statePath, preview.state),
34423
+ artifact(preview.tracksPath, preview.tracksContent)
34424
+ ]
34425
+ });
33734
34426
  } catch (error51) {
33735
34427
  return failure(error51);
33736
34428
  }
@@ -33738,22 +34430,38 @@ function createCadreServer() {
33738
34430
  server.registerTool("review_complete_apply", {
33739
34431
  title: "Apply clean review completion",
33740
34432
  description: "Apply an approved clean-review transition only while its exact state and index preview remain current.",
33741
- inputSchema: { ...reviewCompleteSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34433
+ inputSchema: proposalInputSchema(),
33742
34434
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33743
- }, async ({ proposalDigest, ...input }) => {
34435
+ }, async ({ proposalToken }) => {
33744
34436
  try {
33745
- return result(applyReviewComplete(input, proposalDigest));
34437
+ const proposal = proposalTokens.resolve("review_complete", proposalToken);
34438
+ const applied = applyReviewComplete(proposal.input, proposal.digest);
34439
+ return result({
34440
+ trackId: proposal.input.trackId,
34441
+ status: applied.state.status,
34442
+ files: [
34443
+ jsonArtifact(applied.statePath, applied.state),
34444
+ artifact(applied.tracksPath, applied.tracksContent)
34445
+ ],
34446
+ valid: applied.valid,
34447
+ derivedStateCurrent: applied.derivedStateCurrent
34448
+ });
33746
34449
  } catch (error51) {
33747
34450
  return failure(error51);
33748
34451
  }
33749
34452
  });
33750
34453
  const archiveBatchSchema = {
33751
34454
  projectRoot: external_exports.string().min(1),
33752
- batchId: external_exports.string().regex(/^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33753
- selectedTracks: external_exports.array(external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)).min(1),
33754
- baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33755
- approvedAt: external_exports.iso.datetime(),
33756
- updates: external_exports.array(external_exports.object({ path: external_exports.string().min(1), content: external_exports.string() }))
34455
+ selectedTracks: external_exports.array(external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)).min(1).optional(),
34456
+ updates: external_exports.array(external_exports.discriminatedUnion("kind", [
34457
+ external_exports.object({ kind: external_exports.literal("pattern"), slug: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/), content: external_exports.string() }),
34458
+ external_exports.object({ kind: external_exports.literal("pattern_index"), content: external_exports.string() }),
34459
+ external_exports.object({
34460
+ kind: external_exports.literal("active_track_seed"),
34461
+ trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34462
+ content: external_exports.string()
34463
+ })
34464
+ ]))
33757
34465
  };
33758
34466
  server.registerTool("archive_batch_preview", {
33759
34467
  title: "Preview complete archive batch",
@@ -33762,7 +34470,24 @@ function createCadreServer() {
33762
34470
  annotations: { readOnlyHint: true, openWorldHint: false }
33763
34471
  }, async (input) => {
33764
34472
  try {
33765
- return proposalResult(previewArchiveBatch(input));
34473
+ const derived = deriveArchiveBatchInput(input);
34474
+ const preview = previewArchiveBatch(derived);
34475
+ return proposalResult("archive_batch", derived, {
34476
+ digest: preview.digest,
34477
+ batchId: derived.batchId,
34478
+ selectedTracks: derived.selectedTracks,
34479
+ operationPath: preview.operationPath,
34480
+ checkpoint: preview.operation.checkpoint,
34481
+ resuming: preview.resuming,
34482
+ moves: preview.moves.map(({ trackId, sourcePath, targetPath, needsMove }) => ({
34483
+ trackId,
34484
+ sourcePath,
34485
+ targetPath,
34486
+ needsMove
34487
+ })),
34488
+ writes: preview.writes.map((write) => artifact(write.path, write.content)),
34489
+ tracks: artifact(preview.tracksPath, preview.tracksContent)
34490
+ });
33766
34491
  } catch (error51) {
33767
34492
  return failure(error51);
33768
34493
  }
@@ -33770,19 +34495,30 @@ function createCadreServer() {
33770
34495
  server.registerTool("archive_batch_apply", {
33771
34496
  title: "Apply complete archive batch",
33772
34497
  description: "Journal and apply one approved archive batch only while its complete preview remains current.",
33773
- inputSchema: { ...archiveBatchSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34498
+ inputSchema: proposalInputSchema(),
33774
34499
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33775
- }, async ({ proposalDigest, ...input }) => {
34500
+ }, async ({ proposalToken }) => {
33776
34501
  try {
33777
- return result(applyArchiveBatch(input, proposalDigest));
34502
+ const proposal = proposalTokens.resolve("archive_batch", proposalToken);
34503
+ const applied = applyArchiveBatch(proposal.input, proposal.digest);
34504
+ return result({
34505
+ batchId: proposal.input.batchId,
34506
+ selectedTracks: proposal.input.selectedTracks,
34507
+ operationPath: applied.operationPath,
34508
+ checkpoint: applied.operation.checkpoint,
34509
+ moves: applied.moves.map(({ trackId, targetPath }) => ({ trackId, targetPath })),
34510
+ writes: applied.writes.map((write) => artifact(write.path, write.content)),
34511
+ tracks: artifact(applied.tracksPath, applied.tracksContent),
34512
+ valid: applied.valid,
34513
+ derivedStateCurrent: applied.derivedStateCurrent
34514
+ });
33778
34515
  } catch (error51) {
33779
34516
  return failure(error51);
33780
34517
  }
33781
34518
  });
33782
34519
  const archiveRecordSchema = {
33783
34520
  projectRoot: external_exports.string().min(1),
33784
- batchId: external_exports.string().regex(/^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33785
- archiveCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/)
34521
+ batchId: external_exports.string().regex(/^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
33786
34522
  };
33787
34523
  server.registerTool("archive_batch_record_preview", {
33788
34524
  title: "Preview archive provenance record",
@@ -33791,7 +34527,19 @@ function createCadreServer() {
33791
34527
  annotations: { readOnlyHint: true, openWorldHint: false }
33792
34528
  }, async (input) => {
33793
34529
  try {
33794
- return proposalResult(previewArchiveBatchRecord(input));
34530
+ const derived = deriveArchiveBatchRecordInput(input);
34531
+ const preview = previewArchiveBatchRecord(derived);
34532
+ return proposalResult("archive_batch_record", derived, {
34533
+ digest: preview.digest,
34534
+ batchId: derived.batchId,
34535
+ archiveCommit: derived.archiveCommit,
34536
+ checkpoint: preview.operation.checkpoint,
34537
+ files: [
34538
+ jsonArtifact(preview.operationPath, preview.operation),
34539
+ jsonArtifact(preview.projectPath, preview.project),
34540
+ ...preview.states.map((state) => jsonArtifact(state.path, state.state))
34541
+ ]
34542
+ });
33795
34543
  } catch (error51) {
33796
34544
  return failure(error51);
33797
34545
  }
@@ -33799,11 +34547,24 @@ function createCadreServer() {
33799
34547
  server.registerTool("archive_batch_record_apply", {
33800
34548
  title: "Record archive provenance",
33801
34549
  description: "Record an approved batch's immutable archive commit and complete its journal behind a stale-state digest.",
33802
- inputSchema: { ...archiveRecordSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34550
+ inputSchema: proposalInputSchema(),
33803
34551
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33804
- }, async ({ proposalDigest, ...input }) => {
34552
+ }, async ({ proposalToken }) => {
33805
34553
  try {
33806
- return result(applyArchiveBatchRecord(input, proposalDigest));
34554
+ const proposal = proposalTokens.resolve("archive_batch_record", proposalToken);
34555
+ const applied = applyArchiveBatchRecord(proposal.input, proposal.digest);
34556
+ return result({
34557
+ batchId: proposal.input.batchId,
34558
+ archiveCommit: proposal.input.archiveCommit,
34559
+ checkpoint: applied.operation.checkpoint,
34560
+ files: [
34561
+ jsonArtifact(applied.operationPath, applied.operation),
34562
+ jsonArtifact(applied.projectPath, applied.project),
34563
+ ...applied.states.map((state) => jsonArtifact(state.path, state.state))
34564
+ ],
34565
+ valid: applied.valid,
34566
+ derivedStateCurrent: applied.derivedStateCurrent
34567
+ });
33807
34568
  } catch (error51) {
33808
34569
  return failure(error51);
33809
34570
  }
@@ -33811,13 +34572,9 @@ function createCadreServer() {
33811
34572
  const executionStartSchema = {
33812
34573
  projectRoot: external_exports.string().min(1),
33813
34574
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33814
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33815
- requestedMode: external_exports.enum(["parallel", "sequential"]),
33816
- effectiveMode: external_exports.enum(["parallel", "sequential"]),
33817
- approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES).optional().default("phase"),
33818
- maxWorkers: external_exports.number().int().min(1).max(32),
33819
- baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33820
- approvedAt: external_exports.iso.datetime()
34575
+ requestedMode: external_exports.enum(["parallel", "sequential"]).optional().default("parallel"),
34576
+ approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES).optional(),
34577
+ maxWorkers: external_exports.number().int().min(1).max(32).optional().default(3)
33821
34578
  };
33822
34579
  server.registerTool("execution_start_preview", {
33823
34580
  title: "Preview implementation execution",
@@ -33826,7 +34583,24 @@ function createCadreServer() {
33826
34583
  annotations: { readOnlyHint: true, openWorldHint: false }
33827
34584
  }, async (input) => {
33828
34585
  try {
33829
- return proposalResult(previewExecutionStart(input));
34586
+ const derived = deriveExecutionStartInput(input);
34587
+ const preview = previewExecutionStart(derived);
34588
+ return proposalResult("execution_start", derived, {
34589
+ digest: preview.digest,
34590
+ journalPath: preview.journalPath,
34591
+ statePath: preview.statePath,
34592
+ execution: {
34593
+ executionId: preview.journal.executionId,
34594
+ trackId: preview.journal.trackId,
34595
+ checkpoint: preview.journal.checkpoint,
34596
+ requestedMode: preview.journal.requestedMode,
34597
+ effectiveMode: preview.journal.effectiveMode,
34598
+ approvalMode: preview.journal.approvalMode,
34599
+ maxWorkers: preview.journal.maxWorkers,
34600
+ nodeCount: Object.keys(preview.journal.nodes).length
34601
+ },
34602
+ derivedStatus: executionSchedulerView(preview.journal)
34603
+ });
33830
34604
  } catch (error51) {
33831
34605
  return failure(error51);
33832
34606
  }
@@ -33834,81 +34608,81 @@ function createCadreServer() {
33834
34608
  server.registerTool("execution_start_apply", {
33835
34609
  title: "Start implementation execution",
33836
34610
  description: "Write the approved implementation journal and operation only when its preview digest is unchanged.",
33837
- inputSchema: { ...executionStartSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34611
+ inputSchema: proposalInputSchema(),
33838
34612
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33839
- }, async ({ proposalDigest, ...input }) => {
34613
+ }, async ({ proposalToken }) => {
33840
34614
  try {
33841
- return result(applyExecutionStart(input, proposalDigest));
34615
+ const proposal = proposalTokens.resolve("execution_start", proposalToken);
34616
+ const applied = applyExecutionStart(proposal.input, proposal.digest);
34617
+ return result({
34618
+ journalPath: applied.journalPath,
34619
+ statePath: applied.statePath,
34620
+ execution: {
34621
+ executionId: applied.journal.executionId,
34622
+ trackId: applied.journal.trackId,
34623
+ checkpoint: applied.journal.checkpoint,
34624
+ nodeCount: Object.keys(applied.journal.nodes).length
34625
+ },
34626
+ derivedStatus: executionSchedulerView(applied.journal)
34627
+ });
33842
34628
  } catch (error51) {
33843
34629
  return failure(error51);
33844
34630
  }
33845
34631
  });
33846
- const executionNodeScopeSchema = {
34632
+ const executionScopeSchema = {
33847
34633
  projectRoot: external_exports.string().min(1),
33848
34634
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33849
34635
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
33850
34636
  };
33851
- const executionNodeUpdateSchema = {
34637
+ const executionCheckpointSchema = {
34638
+ ...executionScopeSchema,
33852
34639
  nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/),
33853
- status: external_exports.enum(EXECUTION_NODE_STATUSES),
34640
+ event: external_exports.enum(EXECUTION_CHECKPOINT_EVENTS),
33854
34641
  workerId: external_exports.string().min(1).nullable().optional(),
33855
34642
  worktreePath: external_exports.string().min(1).nullable().optional(),
33856
34643
  branch: external_exports.string().min(1).nullable().optional(),
33857
- workerCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).nullable().optional(),
33858
- mergeCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).nullable().optional(),
33859
- verification: external_exports.string().min(1).nullable().optional(),
33860
- approval: external_exports.string().min(1).nullable().optional(),
33861
- blocker: external_exports.string().min(1).nullable().optional()
33862
- };
33863
- const executionNodeSchema = { ...executionNodeScopeSchema, ...executionNodeUpdateSchema };
33864
- server.registerTool("execution_node_preview", {
33865
- title: "Preview execution node transition",
33866
- description: "Validate and preview one legal runtime node transition without changing its journal.",
33867
- inputSchema: executionNodeSchema,
33868
- annotations: { readOnlyHint: true, openWorldHint: false }
33869
- }, async (input) => {
33870
- try {
33871
- return proposalResult(previewExecutionNodeUpdate(input));
33872
- } catch (error51) {
33873
- return failure(error51);
33874
- }
33875
- });
33876
- server.registerTool("execution_node_apply", {
33877
- title: "Apply execution node transition",
33878
- description: "Apply one approved execution node transition only when its preview digest is unchanged.",
33879
- inputSchema: { ...executionNodeSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
33880
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33881
- }, async ({ proposalDigest, ...input }) => {
33882
- try {
33883
- return result(applyExecutionNodeUpdate(input, proposalDigest));
33884
- } catch (error51) {
33885
- return failure(error51);
33886
- }
33887
- });
33888
- const executionNodesSchema = {
33889
- ...executionNodeScopeSchema,
33890
- updates: external_exports.array(external_exports.object(executionNodeUpdateSchema)).min(1).max(128)
33891
- };
33892
- server.registerTool("execution_nodes_preview", {
33893
- title: "Preview ordered execution node transitions",
33894
- description: "Validate and preview an ordered, atomic batch of legal runtime node transitions without changing its journal.",
33895
- inputSchema: executionNodesSchema,
34644
+ commit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).optional(),
34645
+ verification: external_exports.string().min(1).optional(),
34646
+ authorization: external_exports.string().min(1).optional(),
34647
+ blocker: external_exports.string().min(1).optional()
34648
+ };
34649
+ server.registerTool("execution_checkpoint_preview", {
34650
+ title: "Preview an execution checkpoint",
34651
+ description: "Translate one semantic execution event into the complete legal journal transition sequence.",
34652
+ inputSchema: executionCheckpointSchema,
33896
34653
  annotations: { readOnlyHint: true, openWorldHint: false }
33897
34654
  }, async (input) => {
33898
34655
  try {
33899
- return proposalResult(previewExecutionNodesUpdate(input));
34656
+ const preview = previewExecutionCheckpoint(input);
34657
+ return proposalResult(
34658
+ "execution_checkpoint",
34659
+ input,
34660
+ {
34661
+ path: preview.path,
34662
+ digest: preview.digest,
34663
+ transition: preview.transition,
34664
+ checkpoint: preview.journal.checkpoint
34665
+ }
34666
+ );
33900
34667
  } catch (error51) {
33901
34668
  return failure(error51);
33902
34669
  }
33903
34670
  });
33904
- server.registerTool("execution_nodes_apply", {
33905
- title: "Apply ordered execution node transitions",
33906
- description: "Apply an approved ordered batch atomically only when its single preview digest is unchanged.",
33907
- inputSchema: { ...executionNodesSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34671
+ server.registerTool("execution_checkpoint_apply", {
34672
+ title: "Apply an execution checkpoint",
34673
+ description: "Apply one previewed semantic execution event atomically.",
34674
+ inputSchema: proposalInputSchema(),
33908
34675
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33909
- }, async ({ proposalDigest, ...input }) => {
34676
+ }, async ({ proposalToken }) => {
33910
34677
  try {
33911
- return result(applyExecutionNodesUpdate(input, proposalDigest));
34678
+ const proposal = proposalTokens.resolve("execution_checkpoint", proposalToken);
34679
+ const applied = applyExecutionCheckpoint(proposal.input, proposal.digest);
34680
+ return result({
34681
+ path: applied.path,
34682
+ transition: applied.transition,
34683
+ checkpoint: applied.journal.checkpoint,
34684
+ derivedStatus: executionSchedulerView(applied.journal, [proposal.input.nodeId])
34685
+ });
33912
34686
  } catch (error51) {
33913
34687
  return failure(error51);
33914
34688
  }
@@ -33919,12 +34693,14 @@ function createCadreServer() {
33919
34693
  inputSchema: {
33920
34694
  projectRoot: external_exports.string().min(1),
33921
34695
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33922
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
34696
+ executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
34697
+ nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/).optional()
33923
34698
  },
33924
34699
  annotations: { readOnlyHint: true, openWorldHint: false }
33925
34700
  }, async (input) => {
33926
34701
  try {
33927
- return result(executionStatus(input.projectRoot, input.trackId, input.executionId));
34702
+ const status = executionStatus(input.projectRoot, input.trackId, input.executionId);
34703
+ return result(compactExecutionStatus(status.journal, input.nodeId));
33928
34704
  } catch (error51) {
33929
34705
  return failure(error51);
33930
34706
  }
@@ -33932,9 +34708,7 @@ function createCadreServer() {
33932
34708
  const executionFinishSchema = {
33933
34709
  projectRoot: external_exports.string().min(1),
33934
34710
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33935
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33936
- headCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33937
- completedAt: external_exports.iso.datetime()
34711
+ executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
33938
34712
  };
33939
34713
  server.registerTool("execution_finish_preview", {
33940
34714
  title: "Preview completed implementation execution",
@@ -33943,7 +34717,21 @@ function createCadreServer() {
33943
34717
  annotations: { readOnlyHint: true, openWorldHint: false }
33944
34718
  }, async (input) => {
33945
34719
  try {
33946
- return proposalResult(previewExecutionFinish(input));
34720
+ const derived = deriveExecutionFinishInput(input);
34721
+ const preview = previewExecutionFinish(derived);
34722
+ return proposalResult("execution_finish", derived, {
34723
+ digest: preview.digest,
34724
+ executionId: derived.executionId,
34725
+ targetStatus: preview.state.status,
34726
+ headCommit: derived.headCommit,
34727
+ completedAt: derived.completedAt,
34728
+ files: [
34729
+ jsonArtifact(preview.journalPath, preview.journal),
34730
+ jsonArtifact(preview.statePath, preview.state),
34731
+ artifact(preview.planPath, preview.planContent),
34732
+ artifact(preview.tracksPath, preview.tracksContent)
34733
+ ]
34734
+ });
33947
34735
  } catch (error51) {
33948
34736
  return failure(error51);
33949
34737
  }
@@ -33951,11 +34739,24 @@ function createCadreServer() {
33951
34739
  server.registerTool("execution_finish_apply", {
33952
34740
  title: "Complete implementation execution",
33953
34741
  description: "Finalize an approved execution, ready-for-review state, and derived tracks index together only when the preview is unchanged.",
33954
- inputSchema: { ...executionFinishSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34742
+ inputSchema: proposalInputSchema(),
33955
34743
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33956
- }, async ({ proposalDigest, ...input }) => {
34744
+ }, async ({ proposalToken }) => {
33957
34745
  try {
33958
- return result(applyExecutionFinish(input, proposalDigest));
34746
+ const proposal = proposalTokens.resolve("execution_finish", proposalToken);
34747
+ const applied = applyExecutionFinish(proposal.input, proposal.digest);
34748
+ return result({
34749
+ executionId: proposal.input.executionId,
34750
+ status: applied.journal.status,
34751
+ checkpoint: applied.journal.checkpoint,
34752
+ headCommit: applied.journal.headCommit,
34753
+ files: [
34754
+ jsonArtifact(applied.journalPath, applied.journal),
34755
+ jsonArtifact(applied.statePath, applied.state),
34756
+ artifact(applied.planPath, applied.planContent),
34757
+ artifact(applied.tracksPath, applied.tracksContent)
34758
+ ]
34759
+ });
33959
34760
  } catch (error51) {
33960
34761
  return failure(error51);
33961
34762
  }
@@ -33964,17 +34765,16 @@ function createCadreServer() {
33964
34765
  projectRoot: external_exports.string().min(1),
33965
34766
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
33966
34767
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33967
- nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/),
33968
- phaseId: external_exports.string().regex(/^P\d+$/).nullable().optional()
34768
+ nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/)
33969
34769
  };
33970
34770
  server.registerTool("worktree_create_preview", {
33971
34771
  title: "Preview a Cadre worker worktree",
33972
34772
  description: "Resolve the constrained worker path, branch, and exact base commit without mutating Git.",
33973
- inputSchema: { ...worktreeSchema, baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/) },
34773
+ inputSchema: worktreeSchema,
33974
34774
  annotations: { readOnlyHint: true, openWorldHint: false }
33975
34775
  }, async (input) => {
33976
34776
  try {
33977
- return proposalResult(previewWorktreeCreate(input));
34777
+ return proposalResult("worktree_create", input, previewWorktreeCreate(input));
33978
34778
  } catch (error51) {
33979
34779
  return failure(error51);
33980
34780
  }
@@ -33982,15 +34782,12 @@ function createCadreServer() {
33982
34782
  server.registerTool("worktree_create_apply", {
33983
34783
  title: "Create a Cadre worker worktree",
33984
34784
  description: "Create or reconcile one approved constrained worker worktree using an unchanged preview digest.",
33985
- inputSchema: {
33986
- ...worktreeSchema,
33987
- baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33988
- proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/)
33989
- },
34785
+ inputSchema: proposalInputSchema(),
33990
34786
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
33991
- }, async ({ proposalDigest, ...input }) => {
34787
+ }, async ({ proposalToken }) => {
33992
34788
  try {
33993
- return result(applyWorktreeCreate(input, proposalDigest));
34789
+ const proposal = proposalTokens.resolve("worktree_create", proposalToken);
34790
+ return result(applyWorktreeCreate(proposal.input, proposal.digest));
33994
34791
  } catch (error51) {
33995
34792
  return failure(error51);
33996
34793
  }
@@ -34002,7 +34799,7 @@ function createCadreServer() {
34002
34799
  annotations: { readOnlyHint: true, openWorldHint: false }
34003
34800
  }, async (input) => {
34004
34801
  try {
34005
- return proposalResult(previewWorktreeIntegration(input));
34802
+ return proposalResult("worktree_integrate", input, previewWorktreeIntegration(input));
34006
34803
  } catch (error51) {
34007
34804
  return failure(error51);
34008
34805
  }
@@ -34010,11 +34807,12 @@ function createCadreServer() {
34010
34807
  server.registerTool("integration_apply", {
34011
34808
  title: "Integrate a worker branch",
34012
34809
  description: "Merge an approved worker branch without squashing; report conflicts without resolving them.",
34013
- inputSchema: { ...worktreeSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34810
+ inputSchema: proposalInputSchema(),
34014
34811
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34015
- }, async ({ proposalDigest, ...input }) => {
34812
+ }, async ({ proposalToken }) => {
34016
34813
  try {
34017
- return result(applyWorktreeIntegration(input, proposalDigest));
34814
+ const proposal = proposalTokens.resolve("worktree_integrate", proposalToken);
34815
+ return result(applyWorktreeIntegration(proposal.input, proposal.digest));
34018
34816
  } catch (error51) {
34019
34817
  return failure(error51);
34020
34818
  }
@@ -34026,7 +34824,7 @@ function createCadreServer() {
34026
34824
  annotations: { readOnlyHint: true, openWorldHint: false }
34027
34825
  }, async (input) => {
34028
34826
  try {
34029
- return proposalResult(previewWorktreeCleanup(input));
34827
+ return proposalResult("worktree_cleanup", input, previewWorktreeCleanup(input));
34030
34828
  } catch (error51) {
34031
34829
  return failure(error51);
34032
34830
  }
@@ -34034,11 +34832,12 @@ function createCadreServer() {
34034
34832
  server.registerTool("worktree_cleanup_apply", {
34035
34833
  title: "Clean up an integrated worker",
34036
34834
  description: "Remove only a clean, fully integrated Cadre worktree and its safely deletable branch, whether its journal node is integrated or already completed.",
34037
- inputSchema: { ...worktreeSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34835
+ inputSchema: proposalInputSchema(),
34038
34836
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
34039
- }, async ({ proposalDigest, ...input }) => {
34837
+ }, async ({ proposalToken }) => {
34040
34838
  try {
34041
- return result(applyWorktreeCleanup(input, proposalDigest));
34839
+ const proposal = proposalTokens.resolve("worktree_cleanup", proposalToken);
34840
+ return result(applyWorktreeCleanup(proposal.input, proposal.digest));
34042
34841
  } catch (error51) {
34043
34842
  return failure(error51);
34044
34843
  }
@@ -34072,7 +34871,13 @@ function createCadreServer() {
34072
34871
  annotations: { readOnlyHint: true, openWorldHint: false }
34073
34872
  }, async (input) => {
34074
34873
  try {
34075
- return proposalResult(previewProjectInit(input));
34874
+ const preview = previewProjectInit(input);
34875
+ return proposalResult("project_init", input, {
34876
+ runtimeVersion: preview.runtimeVersion,
34877
+ templateSetVersion: preview.templateSetVersion,
34878
+ files: preview.files.map(({ path, sha256: digest }) => ({ path, sha256: digest })),
34879
+ digest: preview.digest
34880
+ });
34076
34881
  } catch (error51) {
34077
34882
  return failure(error51);
34078
34883
  }
@@ -34080,11 +34885,18 @@ function createCadreServer() {
34080
34885
  server.registerTool("project_init_apply", {
34081
34886
  title: "Apply approved Cadre project initialization",
34082
34887
  description: "Atomically create .cadre only when the semantic proposal matches an approved preview digest; records approvedAt as audit metadata.",
34083
- inputSchema: { ...initSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
34888
+ inputSchema: proposalInputSchema(),
34084
34889
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34085
- }, async ({ proposalDigest, ...input }) => {
34890
+ }, async ({ proposalToken }) => {
34086
34891
  try {
34087
- return result(applyProjectInit(input, proposalDigest));
34892
+ const proposal = proposalTokens.resolve("project_init", proposalToken);
34893
+ const applied = applyProjectInit(proposal.input, proposal.digest);
34894
+ return result({
34895
+ runtimeVersion: applied.runtimeVersion,
34896
+ templateSetVersion: applied.templateSetVersion,
34897
+ files: applied.files.map(({ path, sha256: digest }) => ({ path, sha256: digest })),
34898
+ digest: applied.digest
34899
+ });
34088
34900
  } catch (error51) {
34089
34901
  return failure(error51);
34090
34902
  }
@@ -34092,13 +34904,11 @@ function createCadreServer() {
34092
34904
  server.registerTool("setup_record_commit", {
34093
34905
  title: "Record the project setup commit",
34094
34906
  description: "Complete a pending create operation by recording its already-created Git commit SHA.",
34095
- inputSchema: {
34096
- projectRoot: external_exports.string().min(1),
34097
- commit: external_exports.string().regex(/^[0-9a-f]{7,40}$/)
34098
- },
34907
+ inputSchema: { projectRoot: external_exports.string().min(1) },
34099
34908
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34100
- }, async ({ projectRoot, commit }) => {
34909
+ }, async ({ projectRoot }) => {
34101
34910
  try {
34911
+ const commit = resolveGitCommit(projectRoot);
34102
34912
  return result({ path: recordSetupCommit(projectRoot, commit), commit });
34103
34913
  } catch (error51) {
34104
34914
  return failure(error51);
@@ -34123,7 +34933,13 @@ function createCadreServer() {
34123
34933
  annotations: { readOnlyHint: true, openWorldHint: false }
34124
34934
  }, async ({ projectRoot }) => {
34125
34935
  try {
34126
- return proposalResult(renderTracksPreview(safeProjectRoot(projectRoot)));
34936
+ const input = { projectRoot: safeProjectRoot(projectRoot) };
34937
+ const preview = renderTracksPreview(input.projectRoot);
34938
+ return proposalResult("tracks_render", input, {
34939
+ path: preview.path,
34940
+ sha256: sha256(preview.content),
34941
+ digest: preview.digest
34942
+ });
34127
34943
  } catch (error51) {
34128
34944
  return failure(error51);
34129
34945
  }
@@ -34131,14 +34947,12 @@ function createCadreServer() {
34131
34947
  server.registerTool("tracks_render_apply", {
34132
34948
  title: "Apply the derived tracks index",
34133
34949
  description: "Rewrite tracks.md only when current state matches a human-approved preview digest.",
34134
- inputSchema: {
34135
- projectRoot: external_exports.string().min(1),
34136
- proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/)
34137
- },
34950
+ inputSchema: proposalInputSchema(),
34138
34951
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34139
- }, async ({ projectRoot, proposalDigest }) => {
34952
+ }, async ({ proposalToken }) => {
34140
34953
  try {
34141
- return result({ path: writeTracks(safeProjectRoot(projectRoot), proposalDigest) });
34954
+ const proposal = proposalTokens.resolve("tracks_render", proposalToken);
34955
+ return result({ path: writeTracks(proposal.input.projectRoot, proposal.digest) });
34142
34956
  } catch (error51) {
34143
34957
  return failure(error51);
34144
34958
  }
@@ -34149,7 +34963,7 @@ async function runCadreServer() {
34149
34963
  const server = createCadreServer();
34150
34964
  await server.connect(new StdioServerTransport());
34151
34965
  }
34152
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve9(process.argv[1])).href) {
34966
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve11(process.argv[1])).href) {
34153
34967
  runCadreServer().catch((error51) => {
34154
34968
  process.stderr.write(`${error51 instanceof Error ? error51.message : String(error51)}
34155
34969
  `);