cadre-ai 3.3.0 → 3.4.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.
Files changed (63) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +45 -2
  4. package/README.md +19 -21
  5. package/dist/cadre-cli.mjs +2 -2
  6. package/dist/cadre-mcp.mjs +1142 -705
  7. package/package.json +1 -1
  8. package/skills/archive/SKILL.md +6 -6
  9. package/skills/create/SKILL.md +5 -4
  10. package/skills/implement/SKILL.md +34 -83
  11. package/skills/implement/references/conflict-handling.md +5 -0
  12. package/skills/implement/references/governed-mode.md +7 -0
  13. package/skills/implement/references/parallel-workers.md +9 -0
  14. package/skills/implement/references/resume-recovery.md +10 -0
  15. package/skills/refresh/SKILL.md +4 -4
  16. package/skills/revert/SKILL.md +6 -6
  17. package/skills/review/SKILL.md +7 -7
  18. package/skills/revise/SKILL.md +6 -6
  19. package/skills/status/SKILL.md +1 -1
  20. package/skills/track/SKILL.md +5 -5
  21. package/templates/v2/init/archive/.gitkeep +1 -0
  22. package/templates/v2/init/gitignore.template +8 -0
  23. package/templates/v2/init/guidelines.md +25 -0
  24. package/templates/v2/init/operations/.gitkeep +1 -0
  25. package/templates/v2/init/patterns/index.md +6 -0
  26. package/templates/v2/init/product.md +30 -0
  27. package/templates/v2/init/project.json +27 -0
  28. package/templates/v2/init/refreshes/.gitkeep +1 -0
  29. package/templates/v2/init/styleguides/general.md +14 -0
  30. package/templates/v2/init/styleguides/language.md +21 -0
  31. package/templates/v2/init/tech-stack.md +21 -0
  32. package/templates/v2/init/tracks/.gitkeep +1 -0
  33. package/templates/v2/init/tracks.md +6 -0
  34. package/templates/v2/init/wisps/.gitkeep +1 -0
  35. package/templates/v2/init/workflow.md +72 -0
  36. package/templates/v2/project/archive-operation.json +19 -0
  37. package/templates/v2/project/pattern.md +20 -0
  38. package/templates/v2/project/refresh-operation.json +18 -0
  39. package/templates/v2/project/refresh.md +21 -0
  40. package/templates/v2/styleguides/dart.md +27 -0
  41. package/templates/v2/styleguides/flutter.md +27 -0
  42. package/templates/v2/styleguides/go.md +29 -0
  43. package/templates/v2/styleguides/gradle.md +28 -0
  44. package/templates/v2/styleguides/html-css.md +39 -0
  45. package/templates/v2/styleguides/index.md +27 -0
  46. package/templates/v2/styleguides/java.md +27 -0
  47. package/templates/v2/styleguides/javascript.md +27 -0
  48. package/templates/v2/styleguides/kotlin.md +26 -0
  49. package/templates/v2/styleguides/maven.md +28 -0
  50. package/templates/v2/styleguides/python.md +27 -0
  51. package/templates/v2/styleguides/react.md +28 -0
  52. package/templates/v2/styleguides/swift.md +27 -0
  53. package/templates/v2/styleguides/swiftui.md +27 -0
  54. package/templates/v2/styleguides/typescript.md +26 -0
  55. package/templates/v2/track/bug.md +14 -0
  56. package/templates/v2/track/execution.json +19 -0
  57. package/templates/v2/track/learning.md +39 -0
  58. package/templates/v2/track/plan.md +39 -0
  59. package/templates/v2/track/revert-operation.json +17 -0
  60. package/templates/v2/track/revise-operation.json +18 -0
  61. package/templates/v2/track/revision.md +36 -0
  62. package/templates/v2/track/spec.md +38 -0
  63. package/templates/v2/track/state.json +31 -0
@@ -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 = resolve12.call(this, root, ref);
2982
+ let _sch = resolve13.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 resolve12(root, ref) {
3009
+ function resolve13(root, ref) {
3010
3010
  let sch;
3011
3011
  while (typeof (sch = this.refs[ref]) == "string")
3012
3012
  ref = sch;
@@ -3637,55 +3637,55 @@ var require_fast_uri = __commonJS({
3637
3637
  }
3638
3638
  return uri;
3639
3639
  }
3640
- function resolve12(baseURI, relativeURI, options) {
3640
+ function resolve13(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;
3644
3644
  return serialize(resolved, schemelessOptions);
3645
3645
  }
3646
- function resolveComponent(base, relative5, options, skipNormalization) {
3646
+ function resolveComponent(base, relative7, options, skipNormalization) {
3647
3647
  const target = {};
3648
3648
  if (!skipNormalization) {
3649
3649
  base = parse4(serialize(base, options), options);
3650
- relative5 = parse4(serialize(relative5, options), options);
3650
+ relative7 = parse4(serialize(relative7, options), options);
3651
3651
  }
3652
3652
  options = options || {};
3653
- if (!options.tolerant && relative5.scheme) {
3654
- target.scheme = relative5.scheme;
3655
- target.userinfo = relative5.userinfo;
3656
- target.host = relative5.host;
3657
- target.port = relative5.port;
3658
- target.path = removeDotSegments(relative5.path || "");
3659
- target.query = relative5.query;
3653
+ if (!options.tolerant && relative7.scheme) {
3654
+ target.scheme = relative7.scheme;
3655
+ target.userinfo = relative7.userinfo;
3656
+ target.host = relative7.host;
3657
+ target.port = relative7.port;
3658
+ target.path = removeDotSegments(relative7.path || "");
3659
+ target.query = relative7.query;
3660
3660
  } else {
3661
- if (relative5.userinfo !== void 0 || relative5.host !== void 0 || relative5.port !== void 0) {
3662
- target.userinfo = relative5.userinfo;
3663
- target.host = relative5.host;
3664
- target.port = relative5.port;
3665
- target.path = removeDotSegments(relative5.path || "");
3666
- target.query = relative5.query;
3661
+ if (relative7.userinfo !== void 0 || relative7.host !== void 0 || relative7.port !== void 0) {
3662
+ target.userinfo = relative7.userinfo;
3663
+ target.host = relative7.host;
3664
+ target.port = relative7.port;
3665
+ target.path = removeDotSegments(relative7.path || "");
3666
+ target.query = relative7.query;
3667
3667
  } else {
3668
- if (!relative5.path) {
3668
+ if (!relative7.path) {
3669
3669
  target.path = base.path;
3670
- if (relative5.query !== void 0) {
3671
- target.query = relative5.query;
3670
+ if (relative7.query !== void 0) {
3671
+ target.query = relative7.query;
3672
3672
  } else {
3673
3673
  target.query = base.query;
3674
3674
  }
3675
3675
  } else {
3676
- if (relative5.path[0] === "/") {
3677
- target.path = removeDotSegments(relative5.path);
3676
+ if (relative7.path[0] === "/") {
3677
+ target.path = removeDotSegments(relative7.path);
3678
3678
  } else {
3679
3679
  if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
3680
- target.path = "/" + relative5.path;
3680
+ target.path = "/" + relative7.path;
3681
3681
  } else if (!base.path) {
3682
- target.path = relative5.path;
3682
+ target.path = relative7.path;
3683
3683
  } else {
3684
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative5.path;
3684
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative7.path;
3685
3685
  }
3686
3686
  target.path = removeDotSegments(target.path);
3687
3687
  }
3688
- target.query = relative5.query;
3688
+ target.query = relative7.query;
3689
3689
  }
3690
3690
  target.userinfo = base.userinfo;
3691
3691
  target.host = base.host;
@@ -3693,7 +3693,7 @@ var require_fast_uri = __commonJS({
3693
3693
  }
3694
3694
  target.scheme = base.scheme;
3695
3695
  }
3696
- target.fragment = relative5.fragment;
3696
+ target.fragment = relative7.fragment;
3697
3697
  return target;
3698
3698
  }
3699
3699
  function equal(uriA, uriB, options) {
@@ -3895,7 +3895,7 @@ var require_fast_uri = __commonJS({
3895
3895
  var fastUri = {
3896
3896
  SCHEMES,
3897
3897
  normalize,
3898
- resolve: resolve12,
3898
+ resolve: resolve13,
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((resolve12) => setTimeout(resolve12, pollInterval));
28846
+ await new Promise((resolve13) => setTimeout(resolve13, 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((resolve12, reject) => {
28863
+ return new Promise((resolve13, 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
- resolve12(parseResult.data);
28941
+ resolve13(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((resolve12, reject) => {
29202
+ return new Promise((resolve13, reject) => {
29203
29203
  if (signal.aborted) {
29204
29204
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
29205
29205
  return;
29206
29206
  }
29207
- const timeoutId = setTimeout(resolve12, interval);
29207
+ const timeoutId = setTimeout(resolve13, 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((resolve12) => setTimeout(resolve12, pollInterval));
30298
+ await new Promise((resolve13) => setTimeout(resolve13, 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,12 +30959,12 @@ var StdioServerTransport = class {
30959
30959
  this.onclose?.();
30960
30960
  }
30961
30961
  send(message) {
30962
- return new Promise((resolve12) => {
30962
+ return new Promise((resolve13) => {
30963
30963
  const json3 = serializeMessage(message);
30964
30964
  if (this._stdout.write(json3)) {
30965
- resolve12();
30965
+ resolve13();
30966
30966
  } else {
30967
- this._stdout.once("drain", resolve12);
30967
+ this._stdout.once("drain", resolve13);
30968
30968
  }
30969
30969
  });
30970
30970
  }
@@ -30972,31 +30972,35 @@ var StdioServerTransport = class {
30972
30972
 
30973
30973
  // src/mcp/server.ts
30974
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";
30975
+ import { readFileSync as readFileSync10 } from "node:fs";
30976
+ import { join as join10, resolve as resolve12 } from "node:path";
30977
30977
  import { pathToFileURL } from "node:url";
30978
30978
 
30979
30979
  // src/domain/init.ts
30980
- import { createHash as createHash5 } from "node:crypto";
30980
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
30981
30981
  import {
30982
- existsSync as existsSync7,
30983
- lstatSync as lstatSync3,
30984
- mkdirSync as mkdirSync2,
30985
- readFileSync as readFileSync6,
30986
- renameSync as renameSync2,
30987
- writeFileSync as writeFileSync3
30982
+ existsSync as existsSync8,
30983
+ lstatSync as lstatSync4,
30984
+ mkdirSync as mkdirSync3,
30985
+ readFileSync as readFileSync7,
30986
+ readdirSync as readdirSync6,
30987
+ renameSync as renameSync3,
30988
+ unlinkSync as unlinkSync3,
30989
+ writeFileSync as writeFileSync4
30988
30990
  } from "node:fs";
30989
30991
  import { dirname as dirname3 } from "node:path";
30990
- import { isAbsolute, join as join5, relative as relative2, resolve as resolve7 } from "node:path";
30992
+ import { isAbsolute as isAbsolute3, join as join6, relative as relative4, resolve as resolve8 } from "node:path";
30991
30993
 
30992
30994
  // src/domain/state.ts
30993
30995
  import { createHash as createHash3 } from "node:crypto";
30994
30996
  import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
30995
- import { join as join3, resolve as resolve5 } from "node:path";
30997
+ import { isAbsolute, join as join3, relative, resolve as resolve5 } from "node:path";
30996
30998
 
30997
30999
  // src/domain/version.ts
30998
- var CADRE_RUNTIME_VERSION = "3.3.0";
30999
- var TEMPLATE_SET_VERSION = "v1";
31000
+ var CADRE_RUNTIME_VERSION = "3.4.0";
31001
+ var LEGACY_RUNTIME_VERSIONS = ["3.3.0"];
31002
+ var TEMPLATE_SET_VERSION = "v2";
31003
+ var LEGACY_TEMPLATE_SET_VERSIONS = ["v1"];
31000
31004
 
31001
31005
  // src/domain/plan.ts
31002
31006
  import { createHash } from "node:crypto";
@@ -31339,6 +31343,16 @@ function resolveGitCommit(projectRoot, revision = "HEAD") {
31339
31343
  if (result2.status !== 0) throw new Error(`Git commit is not reachable: ${revision}`);
31340
31344
  return result2.stdout.trim();
31341
31345
  }
31346
+ function readGitFileAtCommit(projectRoot, revision, path) {
31347
+ if (!path || path.startsWith("/") || path.includes("\\") || path.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
31348
+ throw new Error(`Invalid Git file path: ${path}`);
31349
+ }
31350
+ const root = gitRoot(projectRoot);
31351
+ const commit = resolveGitCommit(root, revision);
31352
+ const result2 = spawnSync("git", ["show", `${commit}:${path}`], { cwd: root, encoding: "utf8" });
31353
+ if (result2.status !== 0) throw new Error(`Git commit ${commit} does not contain ${path}`);
31354
+ return result2.stdout;
31355
+ }
31342
31356
  function isGitAncestor(projectRoot, ancestor, descendant = "HEAD") {
31343
31357
  const root = gitRoot(projectRoot);
31344
31358
  return spawnSync("git", ["merge-base", "--is-ancestor", ancestor, descendant], {
@@ -31556,8 +31570,8 @@ function previewExecutionStart(input) {
31556
31570
  digest: hash2({ stateBody, planBody: readFileSync3(planPath, "utf8"), journal, state: proposedState })
31557
31571
  };
31558
31572
  }
31559
- function applyExecutionStart(input, proposalDigest) {
31560
- const proposal = previewExecutionStart(input);
31573
+ function applyExecutionStart(input, proposalDigest, preparedProposal) {
31574
+ const proposal = preparedProposal ?? previewExecutionStart(input);
31561
31575
  if (proposal.digest !== proposalDigest) throw new Error("execution proposal is stale; preview it again");
31562
31576
  if (lstatSync(proposal.statePath).isSymbolicLink()) throw new Error("refusing to start execution through a state symbolic link");
31563
31577
  mkdirSync(dirname(proposal.journalPath), { recursive: true });
@@ -31849,11 +31863,13 @@ function checkpointUpdates(journal, input) {
31849
31863
  ...Object.hasOwn(input, "worktreePath") ? { worktreePath: input.worktreePath ?? null } : {},
31850
31864
  ...Object.hasOwn(input, "branch") ? { branch: input.branch ?? null } : {}
31851
31865
  });
31852
- } else if (node.status === "running" && Object.hasOwn(input, "workerId")) {
31866
+ } else if (node.status === "running" && ["workerId", "worktreePath", "branch"].some((key) => Object.hasOwn(input, key))) {
31853
31867
  updates.push({
31854
31868
  nodeId: node.id,
31855
31869
  status: "running",
31856
- workerId: input.workerId ?? null,
31870
+ ...Object.hasOwn(input, "workerId") ? { workerId: input.workerId ?? null } : {},
31871
+ ...Object.hasOwn(input, "worktreePath") ? { worktreePath: input.worktreePath ?? null } : {},
31872
+ ...Object.hasOwn(input, "branch") ? { branch: input.branch ?? null } : {},
31857
31873
  ...evidence ? { verification: evidence } : {}
31858
31874
  });
31859
31875
  } else if (node.status !== "running") {
@@ -31884,7 +31900,6 @@ function checkpointUpdates(journal, input) {
31884
31900
  if (node.status !== "integrated") {
31885
31901
  updates.push({ nodeId: node.id, status: "integrated", mergeCommit: commit, verification: evidence });
31886
31902
  }
31887
- updates.push({ nodeId: node.id, status: "completed" });
31888
31903
  break;
31889
31904
  case "record_verification":
31890
31905
  if (node.kind !== "manual-verification" || !commit || !evidence || !authorization) {
@@ -31959,7 +31974,19 @@ function previewExecutionCheckpoint(input) {
31959
31974
  }
31960
31975
  };
31961
31976
  }
31962
- function applyExecutionCheckpoint(input, proposalDigest) {
31977
+ function applyExecutionCheckpoint(input, proposalDigest, preparedProposal) {
31978
+ if (preparedProposal) {
31979
+ if (preparedProposal.digest !== proposalDigest) {
31980
+ throw new Error("execution nodes proposal is stale; preview it again");
31981
+ }
31982
+ writeJournalAtomically(preparedProposal.path, preparedProposal.journal);
31983
+ return {
31984
+ path: preparedProposal.path,
31985
+ journal: preparedProposal.journal,
31986
+ derivedStatus: deriveExecutionStatus(preparedProposal.journal),
31987
+ transition: preparedProposal.transition
31988
+ };
31989
+ }
31963
31990
  const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
31964
31991
  const from = journal.nodes[input.nodeId]?.status;
31965
31992
  if (!from) throw new Error(`unknown execution node ${input.nodeId}`);
@@ -32107,8 +32134,8 @@ function previewExecutionFinish(input) {
32107
32134
  })
32108
32135
  };
32109
32136
  }
32110
- function applyExecutionFinish(input, proposalDigest) {
32111
- const proposal = previewExecutionFinish(input);
32137
+ function applyExecutionFinish(input, proposalDigest, preparedProposal) {
32138
+ const proposal = preparedProposal ?? previewExecutionFinish(input);
32112
32139
  if (proposal.digest !== proposalDigest) throw new Error("execution completion proposal is stale; preview it again");
32113
32140
  if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink() || lstatSync(proposal.planPath).isSymbolicLink() || lstatSync(proposal.tracksPath).isSymbolicLink()) {
32114
32141
  throw new Error("refusing to complete execution through a symbolic link");
@@ -32143,18 +32170,18 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
32143
32170
  if (["ready_for_review", "completed", "archived"].includes(state.status)) errors.push(`${state.trackId}: finalized track requires lastExecution`);
32144
32171
  return;
32145
32172
  }
32146
- const relative5 = String(reference.journal ?? "");
32147
- if (!/^executions\/execution-[0-9A-Za-z-]+\.json$/.test(relative5)) {
32173
+ const relative7 = String(reference.journal ?? "");
32174
+ if (!/^executions\/execution-[0-9A-Za-z-]+\.json$/.test(relative7)) {
32148
32175
  errors.push(`${state.trackId}: invalid execution journal path`);
32149
32176
  return;
32150
32177
  }
32151
- const path = resolve4(trackRoot, relative5);
32178
+ const path = resolve4(trackRoot, relative7);
32152
32179
  if (!path.startsWith(`${resolve4(trackRoot)}/`)) {
32153
32180
  errors.push(`${state.trackId}: execution journal escapes track root`);
32154
32181
  return;
32155
32182
  }
32156
32183
  if (!existsSync4(path)) {
32157
- errors.push(`${state.trackId}: missing execution journal ${relative5}`);
32184
+ errors.push(`${state.trackId}: missing execution journal ${relative7}`);
32158
32185
  return;
32159
32186
  }
32160
32187
  let journal;
@@ -32311,7 +32338,7 @@ function readJson(path, errors) {
32311
32338
  return null;
32312
32339
  }
32313
32340
  }
32314
- function validateOperation(operation, owner, errors) {
32341
+ function validateOperation(operation, owner, errors, artifactRoot, artifactProgress = operation?.artifactProgress ?? []) {
32315
32342
  if (!operation || typeof operation !== "object") {
32316
32343
  errors.push(`${owner}: incomplete state requires an operation journal`);
32317
32344
  return;
@@ -32322,6 +32349,41 @@ function validateOperation(operation, owner, errors) {
32322
32349
  errors.push(`${owner}: operation approvedArtifacts must be a non-empty array`);
32323
32350
  }
32324
32351
  if (!operation.approvedAt) errors.push(`${owner}: operation approvedAt is required`);
32352
+ if (operation.approvalDigest !== void 0 && !/^[0-9a-f]{64}$/.test(operation.approvalDigest)) {
32353
+ errors.push(`${owner}: operation approvalDigest must be a SHA-256 digest`);
32354
+ }
32355
+ if (operation.approvedArtifactHashes !== void 0) {
32356
+ if (!Array.isArray(operation.approvedArtifactHashes) || !operation.approvedArtifactHashes.length) {
32357
+ errors.push(`${owner}: operation approvedArtifactHashes must be a non-empty array`);
32358
+ } else {
32359
+ const seen = /* @__PURE__ */ new Set();
32360
+ for (const artifact2 of operation.approvedArtifactHashes) {
32361
+ if (!artifact2 || typeof artifact2.path !== "string" || !operation.approvedArtifacts?.includes(artifact2.path)) {
32362
+ errors.push(`${owner}: operation artifact hash path must name an approved artifact`);
32363
+ continue;
32364
+ }
32365
+ if (seen.has(artifact2.path)) errors.push(`${owner}: duplicate operation artifact hash for ${artifact2.path}`);
32366
+ seen.add(artifact2.path);
32367
+ if (!/^[0-9a-f]{64}$/.test(artifact2.sha256 ?? "")) {
32368
+ errors.push(`${owner}: operation artifact hash for ${artifact2.path} must be SHA-256`);
32369
+ }
32370
+ if (artifactRoot && artifactProgress.includes(artifact2.path) && /^[0-9a-f]{64}$/.test(artifact2.sha256 ?? "")) {
32371
+ const target = resolve5(artifactRoot, artifact2.path);
32372
+ const relation = relative(artifactRoot, target);
32373
+ if (relation.startsWith("..") || isAbsolute(relation)) {
32374
+ errors.push(`${owner}: approved artifact hash path escapes its operation root: ${artifact2.path}`);
32375
+ } else if (!existsSync5(target) || lstatSync2(target).isSymbolicLink() || !lstatSync2(target).isFile()) {
32376
+ errors.push(`${owner}: promoted approved artifact is unavailable: ${artifact2.path}`);
32377
+ } else {
32378
+ const actual = createHash3("sha256").update(readFileSync4(target, "utf8")).digest("hex");
32379
+ if (actual !== artifact2.sha256) {
32380
+ errors.push(`${owner}: promoted artifact differs from its approved hash: ${artifact2.path}`);
32381
+ }
32382
+ }
32383
+ }
32384
+ }
32385
+ }
32386
+ }
32325
32387
  }
32326
32388
  function validateRevisionOperation(state, owner, errors) {
32327
32389
  const operation = state.operation;
@@ -32446,7 +32508,7 @@ function validateProjectOperations(root, byId, errors) {
32446
32508
  const owner = `operations/${file2}`;
32447
32509
  const operation = readJson(join3(operationsRoot, file2), errors);
32448
32510
  if (!operation) continue;
32449
- validateOperation(operation, owner, errors);
32511
+ validateOperation(operation, owner, errors, root);
32450
32512
  if (!operation.status || !["in_progress", "completed"].includes(operation.status)) {
32451
32513
  errors.push(`${owner}: status must be in_progress or completed`);
32452
32514
  }
@@ -32551,8 +32613,10 @@ function validateProject(projectRoot) {
32551
32613
  if (!existsSync5(join3(root, file2))) errors.push(`${join3(root, file2)}: missing required Cadre file`);
32552
32614
  }
32553
32615
  const gitignorePath = join3(root, ".gitignore");
32616
+ let candidateStageIgnored = false;
32554
32617
  if (existsSync5(gitignorePath)) {
32555
32618
  const gitignore = readFileSync4(gitignorePath, "utf8");
32619
+ candidateStageIgnored = gitignore.split(/\r?\n/).includes("/stage/");
32556
32620
  if (!gitignore.split(/\r?\n/).includes("/.worktrees/")) {
32557
32621
  errors.push(`${gitignorePath}: must ignore /.worktrees/`);
32558
32622
  }
@@ -32562,18 +32626,39 @@ function validateProject(projectRoot) {
32562
32626
  }
32563
32627
  const project = readJson(join3(root, "project.json"), errors);
32564
32628
  if (!project) return { project: null, tracks: [], states: /* @__PURE__ */ new Map(), errors, warnings };
32629
+ if (!candidateStageIgnored) {
32630
+ if (LEGACY_TEMPLATE_SET_VERSIONS.includes(project.templateSetVersion ?? "")) {
32631
+ warnings.push("PROJECT_REFRESH_REQUIRED: .cadre/.gitignore must ignore /stage/");
32632
+ } else errors.push(`${gitignorePath}: must ignore /stage/`);
32633
+ }
32565
32634
  const commitReferences = [];
32566
32635
  collectCommitReferences(project, "project.json", commitReferences);
32567
32636
  if (project.schemaVersion !== 1) errors.push("project.json: unsupported schemaVersion");
32568
- if (project.runtimeVersion !== CADRE_RUNTIME_VERSION) errors.push(`project.json: runtimeVersion must be ${CADRE_RUNTIME_VERSION}`);
32569
- if (project.templateSetVersion !== TEMPLATE_SET_VERSION) errors.push(`project.json: templateSetVersion must be ${TEMPLATE_SET_VERSION}`);
32637
+ if (project.runtimeVersion !== CADRE_RUNTIME_VERSION) {
32638
+ if (LEGACY_RUNTIME_VERSIONS.includes(project.runtimeVersion ?? "")) {
32639
+ warnings.push(`PROJECT_REFRESH_REQUIRED: runtimeVersion ${project.runtimeVersion} must be refreshed to ${CADRE_RUNTIME_VERSION}`);
32640
+ } else errors.push(`project.json: unsupported runtimeVersion ${String(project.runtimeVersion)}`);
32641
+ }
32642
+ if (project.templateSetVersion !== TEMPLATE_SET_VERSION) {
32643
+ if (LEGACY_TEMPLATE_SET_VERSIONS.includes(project.templateSetVersion ?? "")) {
32644
+ warnings.push(
32645
+ `PROJECT_REFRESH_REQUIRED: templateSetVersion ${project.templateSetVersion} must be refreshed to ${TEMPLATE_SET_VERSION}`
32646
+ );
32647
+ } else errors.push(`project.json: unsupported templateSetVersion ${String(project.templateSetVersion)}`);
32648
+ }
32570
32649
  if (!project.project?.context || !["greenfield", "brownfield"].includes(project.project.context)) {
32571
32650
  errors.push("project.json: project context must be greenfield or brownfield");
32572
32651
  }
32573
32652
  if (!project.setup?.checkpoint) errors.push("project.json: setup checkpoint is required");
32574
32653
  if (!Array.isArray(project.setup?.artifactProgress)) errors.push("project.json: setup artifactProgress must be an array");
32575
32654
  if (project.setup?.status === "in_progress") {
32576
- validateOperation(project.setup.operation, "project.json setup", errors);
32655
+ validateOperation(
32656
+ project.setup.operation,
32657
+ "project.json setup",
32658
+ errors,
32659
+ root,
32660
+ project.setup.artifactProgress
32661
+ );
32577
32662
  } else if (project.setup?.status === "completed") {
32578
32663
  if (!/^[0-9a-f]{7,40}$/.test(project.setup?.commit ?? "")) {
32579
32664
  errors.push("project.json: completed setup requires a commit SHA");
@@ -32601,7 +32686,7 @@ function validateProject(projectRoot) {
32601
32686
  if (!state.checkpoint) errors.push(`${track.id}: state checkpoint is required`);
32602
32687
  if (!Array.isArray(state.artifactProgress)) errors.push(`${track.id}: artifactProgress must be an array`);
32603
32688
  if (state.operation != null) {
32604
- validateOperation(state.operation, `${track.id} state`, errors);
32689
+ validateOperation(state.operation, `${track.id} state`, errors, trackRoot, state.artifactProgress);
32605
32690
  validateRevisionOperation(state, `${track.id} state`, errors);
32606
32691
  validateImplementOperation(state, `${track.id} state`, errors);
32607
32692
  validateRevertOperation(state, `${track.id} state`, errors);
@@ -32720,17 +32805,6 @@ function validateProject(projectRoot) {
32720
32805
  }
32721
32806
  return { project, tracks, states, errors, warnings };
32722
32807
  }
32723
- function nextCommand(track) {
32724
- return {
32725
- "drafting-spec": "track",
32726
- "drafting-plan": "track",
32727
- planned: "implement",
32728
- in_progress: "implement",
32729
- ready_for_review: "review",
32730
- completed: "archive",
32731
- archived: "\u2014"
32732
- }[track.status] ?? "\u2014";
32733
- }
32734
32808
  function renderTracksPreview(projectRoot) {
32735
32809
  const result2 = validateProject(projectRoot);
32736
32810
  if (!result2.project) throw new Error(result2.errors.join("\n") || "Cadre project state is unavailable");
@@ -32741,8 +32815,8 @@ function renderTracksPreview(projectRoot) {
32741
32815
  const digest = createHash3("sha256").update(JSON.stringify({ content, previousContent })).digest("hex");
32742
32816
  return { path, content, previousContent, changed: previousContent !== content, digest };
32743
32817
  }
32744
- function writeTracks(projectRoot, proposalDigest) {
32745
- const preview = renderTracksPreview(projectRoot);
32818
+ function writeTracks(projectRoot, proposalDigest, preparedPreview) {
32819
+ const preview = preparedPreview ?? renderTracksPreview(projectRoot);
32746
32820
  if (preview.digest !== proposalDigest) {
32747
32821
  throw new Error("tracks.md proposal is stale; preview it again before applying");
32748
32822
  }
@@ -32753,37 +32827,156 @@ function writeTracks(projectRoot, proposalDigest) {
32753
32827
  writeFileSync2(preview.path, preview.content);
32754
32828
  return preview.path;
32755
32829
  }
32756
- function formatStatus(projectRoot) {
32757
- const result2 = validateProject(projectRoot);
32758
- const project = result2.project;
32759
- if (!project) return { text: result2.errors.join("\n"), result: result2 };
32760
- const lines = [
32761
- `Project: ${project.project?.name ?? "unknown"}; context=${project.project?.context ?? "unknown"}`,
32762
- `Setup: ${project.setup?.status ?? "unknown"}; checkpoint=${project.setup?.checkpoint ?? "none"}; operation=${project.setup?.operation?.action ?? "none"}; commit=${project.setup?.commit ?? "none"}`,
32763
- `Last refresh: ${project.lastRefresh?.commit ?? "none"}`
32764
- ];
32765
- for (const track of result2.tracks) {
32766
- const dependencies = track.dependencies?.length ? track.dependencies.join(",") : "none";
32767
- const state = result2.states.get(track.id);
32768
- const execution = state?.operation?.action === "implement" ? `${String(state.operation.executionId ?? "unknown")}/${String(state.operation.mode ?? "unknown")}/${String(state.operation.approvalMode ?? "governed")}` : state?.lastExecution ? `${String(state.lastExecution.executionId ?? "unknown")}/completed/${String(state.lastExecution.approvalMode ?? "governed")}` : "none";
32769
- lines.push(`${track.id} [${track.type}] ${track.status}; checkpoint=${state?.checkpoint ?? "none"}; operation=${state?.operation?.action ?? "none"}; execution=${execution}; deps=${dependencies}; revision=${track.revision ?? 1}; reviews=${state?.reviewCycles?.length ?? 0}; next=${nextCommand(track)}`);
32770
- }
32771
- const counts = result2.tracks.reduce((summary, track) => {
32772
- summary[track.status] = (summary[track.status] ?? 0) + 1;
32773
- return summary;
32774
- }, {});
32775
- lines.push(`Counts: ready_for_review=${counts.ready_for_review ?? 0}; completed=${counts.completed ?? 0}; archived=${counts.archived ?? 0}`);
32776
- lines.push(
32777
- `Validation: ${result2.errors.length ? `${result2.errors.length} error(s)` : "valid"}; derived=${result2.warnings.length ? `${result2.warnings.length} warning(s)` : "current"}`
32778
- );
32779
- return { text: `${lines.join("\n")}
32780
- `, result: result2 };
32830
+
32831
+ // src/domain/staging.ts
32832
+ import {
32833
+ existsSync as existsSync6,
32834
+ lstatSync as lstatSync3,
32835
+ mkdirSync as mkdirSync2,
32836
+ readFileSync as readFileSync5,
32837
+ readdirSync as readdirSync4,
32838
+ renameSync as renameSync2,
32839
+ unlinkSync as unlinkSync2,
32840
+ writeFileSync as writeFileSync3
32841
+ } from "node:fs";
32842
+ import { isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve as resolve6, sep } from "node:path";
32843
+ var CANDIDATE_STAGE_DIRECTORY = ".cadre/stage";
32844
+ var MAX_CANDIDATE_FILE_BYTES = 1024 * 1024;
32845
+ var MAX_CANDIDATE_TOTAL_BYTES = 8 * 1024 * 1024;
32846
+ var CANDIDATE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32847
+ function normalizeCandidateId(candidateId) {
32848
+ if (!CANDIDATE_ID.test(candidateId)) {
32849
+ throw new Error("candidateId must contain lowercase letters, digits, and single hyphens");
32850
+ }
32851
+ return candidateId;
32852
+ }
32853
+ function normalizeCandidatePath(input) {
32854
+ if (!input || isAbsolute2(input) || input.includes("\\")) {
32855
+ throw new Error(`Candidate artifact path must be a portable relative path: ${input}`);
32856
+ }
32857
+ const normalized = input.replace(/^\.\//, "");
32858
+ if (!normalized || normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
32859
+ throw new Error(`Candidate artifact path is not canonical: ${input}`);
32860
+ }
32861
+ return normalized;
32862
+ }
32863
+ function candidateStageRoot(projectRootInput, candidateIdInput) {
32864
+ const projectRoot = safeProjectRoot(projectRootInput);
32865
+ const candidateId = normalizeCandidateId(candidateIdInput);
32866
+ const cadreRoot2 = join4(projectRoot, ".cadre");
32867
+ if (!existsSync6(cadreRoot2) || !lstatSync3(cadreRoot2).isDirectory() || lstatSync3(cadreRoot2).isSymbolicLink()) {
32868
+ throw new Error(`Cadre candidate root is unavailable or unsafe: ${cadreRoot2}`);
32869
+ }
32870
+ const gitignorePath = join4(cadreRoot2, ".gitignore");
32871
+ if (!existsSync6(gitignorePath) || !lstatSync3(gitignorePath).isFile() || lstatSync3(gitignorePath).isSymbolicLink()) {
32872
+ throw new Error(`Cadre candidate stage requires a regular ${gitignorePath}`);
32873
+ }
32874
+ if (!readFileSync5(gitignorePath, "utf8").split(/\r?\n/).includes("/stage/")) {
32875
+ throw new Error(`${gitignorePath} must ignore /stage/ before candidate files are written`);
32876
+ }
32877
+ const stageParent = join4(projectRoot, CANDIDATE_STAGE_DIRECTORY);
32878
+ if (existsSync6(stageParent) && lstatSync3(stageParent).isSymbolicLink()) {
32879
+ throw new Error(`Refusing candidate stage through symbolic link: ${stageParent}`);
32880
+ }
32881
+ return join4(stageParent, candidateId);
32882
+ }
32883
+ function prepareCandidateStage(projectRootInput, candidateIdInput) {
32884
+ const projectRoot = safeProjectRoot(projectRootInput);
32885
+ const candidateId = normalizeCandidateId(candidateIdInput);
32886
+ const cadreRoot2 = join4(projectRoot, ".cadre");
32887
+ if (existsSync6(cadreRoot2)) {
32888
+ const stat = lstatSync3(cadreRoot2);
32889
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Unsafe Cadre directory: ${cadreRoot2}`);
32890
+ } else mkdirSync2(cadreRoot2);
32891
+ const gitignorePath = join4(cadreRoot2, ".gitignore");
32892
+ let content = "# Cadre-managed temporary execution worktrees\n/.worktrees/\n\n# Disposable Wisp output\n/wisps/\n";
32893
+ if (existsSync6(gitignorePath)) {
32894
+ const stat = lstatSync3(gitignorePath);
32895
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Unsafe Cadre ignore file: ${gitignorePath}`);
32896
+ content = readFileSync5(gitignorePath, "utf8");
32897
+ }
32898
+ if (!content.split(/\r?\n/).includes("/stage/")) {
32899
+ content = `${content.endsWith("\n") ? content : `${content}
32900
+ `}
32901
+ # Unapproved candidate artifacts
32902
+ /stage/
32903
+ `;
32904
+ const temporaryPath = `${gitignorePath}.${process.pid}.tmp`;
32905
+ try {
32906
+ writeFileSync3(temporaryPath, content, { flag: "wx" });
32907
+ renameSync2(temporaryPath, gitignorePath);
32908
+ } finally {
32909
+ if (existsSync6(temporaryPath)) unlinkSync2(temporaryPath);
32910
+ }
32911
+ }
32912
+ const stagePath = join4(cadreRoot2, "stage", candidateId);
32913
+ mkdirSync2(stagePath, { recursive: true });
32914
+ candidateStageRoot(projectRoot, candidateId);
32915
+ return { stagePath, gitignorePath };
32916
+ }
32917
+ function assertRegularPath(root, target) {
32918
+ const relation = relative2(root, target);
32919
+ if (relation.startsWith("..") || isAbsolute2(relation)) {
32920
+ throw new Error(`Candidate artifact escapes its stage: ${target}`);
32921
+ }
32922
+ let current = target;
32923
+ while (current !== root) {
32924
+ if (!existsSync6(current)) throw new Error(`Missing candidate artifact: ${target}`);
32925
+ const stat = lstatSync3(current);
32926
+ if (stat.isSymbolicLink()) throw new Error(`Refusing candidate artifact through symbolic link: ${current}`);
32927
+ current = resolve6(current, "..");
32928
+ }
32929
+ if (!existsSync6(root)) throw new Error(`Missing candidate stage: ${root}`);
32930
+ const rootStat = lstatSync3(root);
32931
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
32932
+ throw new Error(`Candidate stage is not a regular directory: ${root}`);
32933
+ }
32934
+ const targetStat = lstatSync3(target);
32935
+ if (!targetStat.isFile()) throw new Error(`Candidate artifact is not a regular file: ${target}`);
32936
+ if (targetStat.size > MAX_CANDIDATE_FILE_BYTES) {
32937
+ throw new Error(`Candidate artifact exceeds ${MAX_CANDIDATE_FILE_BYTES} bytes: ${target}`);
32938
+ }
32939
+ }
32940
+ function readCandidateFiles(projectRootInput, candidateIdInput, paths) {
32941
+ const root = candidateStageRoot(projectRootInput, candidateIdInput);
32942
+ const seen = /* @__PURE__ */ new Set();
32943
+ let totalBytes = 0;
32944
+ return paths.map((input) => {
32945
+ const path = normalizeCandidatePath(input);
32946
+ if (seen.has(path)) throw new Error(`Duplicate candidate artifact: ${path}`);
32947
+ seen.add(path);
32948
+ const absolutePath = resolve6(root, path);
32949
+ assertRegularPath(root, absolutePath);
32950
+ const content = readFileSync5(absolutePath, "utf8");
32951
+ totalBytes += Buffer.byteLength(content, "utf8");
32952
+ if (totalBytes > MAX_CANDIDATE_TOTAL_BYTES) {
32953
+ throw new Error(`Candidate stage exceeds ${MAX_CANDIDATE_TOTAL_BYTES} bytes`);
32954
+ }
32955
+ return { path, absolutePath, content };
32956
+ });
32957
+ }
32958
+ function listCandidatePaths(projectRootInput, candidateIdInput) {
32959
+ const root = candidateStageRoot(projectRootInput, candidateIdInput);
32960
+ if (!existsSync6(root)) throw new Error(`Missing candidate stage: ${root}`);
32961
+ const rootStat = lstatSync3(root);
32962
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
32963
+ throw new Error(`Candidate stage is not a regular directory: ${root}`);
32964
+ }
32965
+ const walk2 = (directory) => readdirSync4(directory, { withFileTypes: true }).flatMap((entry) => {
32966
+ const target = join4(directory, entry.name);
32967
+ const stat = lstatSync3(target);
32968
+ if (stat.isSymbolicLink()) throw new Error(`Refusing symbolic link in candidate stage: ${target}`);
32969
+ if (stat.isDirectory()) return walk2(target);
32970
+ if (!stat.isFile()) throw new Error(`Candidate stage contains a non-file entry: ${target}`);
32971
+ return [relative2(root, target).split(sep).join("/")];
32972
+ });
32973
+ return walk2(root).sort();
32781
32974
  }
32782
32975
 
32783
32976
  // src/domain/templates.ts
32784
32977
  import { createHash as createHash4 } from "node:crypto";
32785
- import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync as readdirSync4 } from "node:fs";
32786
- import { dirname as dirname2, extname, join as join4, relative, resolve as resolve6, sep } from "node:path";
32978
+ import { existsSync as existsSync7, readFileSync as readFileSync6, readdirSync as readdirSync5 } from "node:fs";
32979
+ import { dirname as dirname2, extname, join as join5, relative as relative3, resolve as resolve7, sep as sep2 } from "node:path";
32787
32980
  import { fileURLToPath } from "node:url";
32788
32981
  var TEMPLATE_IDS = [
32789
32982
  "project/archive-operation",
@@ -32825,22 +33018,49 @@ var TEMPLATE_IDS = [
32825
33018
  "track/spec",
32826
33019
  "track/state"
32827
33020
  ];
33021
+ var TEMPLATE_ARTIFACT_PATHS = {
33022
+ "project/gitignore": ".gitignore",
33023
+ "project/guidelines": "guidelines.md",
33024
+ "project/patterns/index": "patterns/index.md",
33025
+ "project/product": "product.md",
33026
+ "project/project": "project.json",
33027
+ "project/styleguides/general": "styleguides/general.md",
33028
+ "project/styleguides/language": "styleguides/<language>.md",
33029
+ "project/tech-stack": "tech-stack.md",
33030
+ "project/tracks": "tracks.md",
33031
+ "project/workflow": "workflow.md",
33032
+ "styleguide/dart": "styleguides/dart.md",
33033
+ "styleguide/flutter": "styleguides/flutter.md",
33034
+ "styleguide/go": "styleguides/go.md",
33035
+ "styleguide/gradle": "styleguides/gradle.md",
33036
+ "styleguide/html-css": "styleguides/html-css.md",
33037
+ "styleguide/index": "styleguides/index.md",
33038
+ "styleguide/java": "styleguides/java.md",
33039
+ "styleguide/javascript": "styleguides/javascript.md",
33040
+ "styleguide/kotlin": "styleguides/kotlin.md",
33041
+ "styleguide/maven": "styleguides/maven.md",
33042
+ "styleguide/python": "styleguides/python.md",
33043
+ "styleguide/react": "styleguides/react.md",
33044
+ "styleguide/swift": "styleguides/swift.md",
33045
+ "styleguide/swiftui": "styleguides/swiftui.md",
33046
+ "styleguide/typescript": "styleguides/typescript.md"
33047
+ };
32828
33048
  var catalogCache = null;
32829
33049
  function locateTemplateRoot() {
32830
33050
  const moduleDirectory = dirname2(fileURLToPath(import.meta.url));
32831
33051
  const candidates = [
32832
33052
  process.env.CADRE_TEMPLATE_ROOT,
32833
- resolve6(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
32834
- resolve6(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
33053
+ resolve7(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
33054
+ resolve7(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
32835
33055
  ].filter((candidate) => Boolean(candidate));
32836
- const found = candidates.find((candidate) => existsSync6(candidate));
33056
+ const found = candidates.find((candidate) => existsSync7(candidate));
32837
33057
  if (!found) throw new Error(`Cadre template set ${TEMPLATE_SET_VERSION} is unavailable`);
32838
33058
  return found;
32839
33059
  }
32840
33060
  function walk(root, directory = root) {
32841
- return readdirSync4(directory, { withFileTypes: true }).flatMap((entry) => {
32842
- const path = join4(directory, entry.name);
32843
- return entry.isDirectory() ? walk(root, path) : [relative(root, path).split(sep).join("/")];
33061
+ return readdirSync5(directory, { withFileTypes: true }).flatMap((entry) => {
33062
+ const path = join5(directory, entry.name);
33063
+ return entry.isDirectory() ? walk(root, path) : [relative3(root, path).split(sep2).join("/")];
32844
33064
  });
32845
33065
  }
32846
33066
  function templateId(path) {
@@ -32876,7 +33096,7 @@ function templateCatalog() {
32876
33096
  const catalog = walk(root).map((relativePath) => {
32877
33097
  const id = templateId(relativePath);
32878
33098
  if (!id) return null;
32879
- const content = readFileSync5(join4(root, relativePath), "utf8");
33099
+ const content = readFileSync6(join5(root, relativePath), "utf8");
32880
33100
  return {
32881
33101
  id,
32882
33102
  uri: `cadre://templates/${TEMPLATE_SET_VERSION}/${id}`,
@@ -32891,9 +33111,6 @@ function templateCatalog() {
32891
33111
  }
32892
33112
  return catalogCache.map((template) => ({ ...template }));
32893
33113
  }
32894
- function getTemplate(id) {
32895
- return getTemplates([id])[0];
32896
- }
32897
33114
  function getTemplates(ids) {
32898
33115
  const byId = new Map(templateCatalog().map((template) => [template.id, template]));
32899
33116
  return ids.map((id) => {
@@ -32902,6 +33119,11 @@ function getTemplates(ids) {
32902
33119
  return template;
32903
33120
  });
32904
33121
  }
33122
+ function describeTemplate(template) {
33123
+ const { relativePath: _sourcePath, ...descriptor } = template;
33124
+ const artifactPath = TEMPLATE_ARTIFACT_PATHS[template.id];
33125
+ return artifactPath ? { ...descriptor, artifactPath } : descriptor;
33126
+ }
32905
33127
  var STYLEGUIDE_RULES = [
32906
33128
  [/\bhtml\b|\bcss\b|html\/css/i, ["html-css"]],
32907
33129
  [/\btypescript\b/i, ["javascript", "typescript"]],
@@ -32928,13 +33150,8 @@ function resolveStyleguides(technologies) {
32928
33150
  }
32929
33151
 
32930
33152
  // src/domain/init.ts
32931
- var REQUIRED_APPROVED_FILES = /* @__PURE__ */ new Set([
32932
- "product.md",
32933
- "guidelines.md",
32934
- "tech-stack.md",
32935
- "workflow.md",
32936
- "styleguides/general.md"
32937
- ]);
33153
+ var REQUIRED_STAGED_FILES = /* @__PURE__ */ new Set(["product.md", "guidelines.md", "tech-stack.md"]);
33154
+ var OPTIONAL_STAGED_FILE = /^(?:workflow\.md|styleguides\/[a-z0-9-]+\.md)$/;
32938
33155
  function hash3(content) {
32939
33156
  return createHash5("sha256").update(content).digest("hex");
32940
33157
  }
@@ -32946,12 +33163,17 @@ function proposalFileHash(file2) {
32946
33163
  `);
32947
33164
  }
32948
33165
  function normalizeCadrePath(input) {
32949
- if (isAbsolute(input)) throw new Error(`Cadre artifact path must be relative: ${input}`);
33166
+ if (isAbsolute3(input)) throw new Error(`Cadre artifact path must be relative: ${input}`);
32950
33167
  const normalized = input.replaceAll("\\", "/").replace(/^\.\//, "");
32951
33168
  if (normalized.startsWith("../") || normalized.includes("/../") || normalized === "..") {
32952
33169
  throw new Error(`Cadre artifact path escapes the project: ${input}`);
32953
33170
  }
32954
- if (!REQUIRED_APPROVED_FILES.has(normalized) && !/^styleguides\/[a-z0-9-]+\.md$/.test(normalized)) {
33171
+ if (normalized.startsWith("init/")) {
33172
+ throw new Error(
33173
+ `Initialization artifacts are relative to .cadre/stage/create; use ${normalized.slice("init/".length)} instead of ${normalized}`
33174
+ );
33175
+ }
33176
+ if (!REQUIRED_STAGED_FILES.has(normalized) && !OPTIONAL_STAGED_FILE.test(normalized)) {
32955
33177
  throw new Error(`Unsupported initialization artifact: ${input}`);
32956
33178
  }
32957
33179
  return normalized;
@@ -32959,7 +33181,7 @@ function normalizeCadrePath(input) {
32959
33181
  function assertRendered(content, path) {
32960
33182
  if (/\{\{[^}]+\}\}/.test(content)) throw new Error(`${path} contains unresolved template placeholders`);
32961
33183
  }
32962
- function projectState(input, approvedPaths, template) {
33184
+ function projectState(input, approvedPaths, approvedArtifactHashes, template) {
32963
33185
  const state = JSON.parse(template);
32964
33186
  state.runtimeVersion = CADRE_RUNTIME_VERSION;
32965
33187
  state.templateSetVersion = TEMPLATE_SET_VERSION;
@@ -32972,13 +33194,13 @@ function projectState(input, approvedPaths, template) {
32972
33194
  state.setup.operation.repositoryRoot = safeProjectRoot(input.projectRoot);
32973
33195
  state.setup.operation.gitDisposition = input.gitDisposition;
32974
33196
  state.setup.operation.approvedArtifacts = approvedPaths;
33197
+ state.setup.operation.approvedArtifactHashes = approvedArtifactHashes;
32975
33198
  state.setup.operation.approvedAt = input.approvedAt;
32976
33199
  return `${JSON.stringify(state, null, 2)}
32977
33200
  `;
32978
33201
  }
32979
- function previewProjectInit(input) {
33202
+ function buildProjectInitProposal(input) {
32980
33203
  const root = safeProjectRoot(input.projectRoot);
32981
- if (existsSync7(join5(root, ".cadre"))) throw new Error(`${root}/.cadre already exists`);
32982
33204
  if (!input.projectName.trim()) throw new Error("Project name is required");
32983
33205
  if (!Number.isFinite(Date.parse(input.approvedAt))) throw new Error("approvedAt must be an ISO timestamp");
32984
33206
  if (input.baseCommit !== null && !/^[0-9a-f]{7,40}$/.test(input.baseCommit)) {
@@ -32992,19 +33214,47 @@ function previewProjectInit(input) {
32992
33214
  approved.set(path, file2.content.endsWith("\n") ? file2.content : `${file2.content}
32993
33215
  `);
32994
33216
  }
32995
- for (const path of REQUIRED_APPROVED_FILES) {
33217
+ for (const path of REQUIRED_STAGED_FILES) {
32996
33218
  if (!approved.has(path)) throw new Error(`Missing approved initialization artifact: ${path}`);
32997
33219
  }
32998
- const approvedPaths = [...approved.keys()].sort();
32999
- const [gitignoreTemplate, projectTemplate, patternIndexTemplate] = getTemplates([
33220
+ if (!Array.isArray(input.styleguideIds) || !input.styleguideIds.length) {
33221
+ throw new Error("Initialization requires at least the general styleguide ID");
33222
+ }
33223
+ if (new Set(input.styleguideIds).size !== input.styleguideIds.length) {
33224
+ throw new Error("Initialization styleguide IDs must be unique");
33225
+ }
33226
+ if (!input.styleguideIds.includes("project/styleguides/general")) {
33227
+ throw new Error("Initialization styleguide IDs must include project/styleguides/general");
33228
+ }
33229
+ if (input.styleguideIds.some((id) => id !== "project/styleguides/general" && !/^styleguide\/[a-z0-9-]+$/.test(id))) {
33230
+ throw new Error("Initialization styleguide IDs must reference bundled styleguides");
33231
+ }
33232
+ const [gitignoreTemplate, projectTemplate, patternIndexTemplate, workflowTemplate, ...styleguideTemplates] = getTemplates([
33000
33233
  "project/gitignore",
33001
33234
  "project/project",
33002
- "project/patterns/index"
33235
+ "project/patterns/index",
33236
+ "project/workflow",
33237
+ ...input.styleguideIds
33003
33238
  ]);
33239
+ const generatedContext = /* @__PURE__ */ new Map([["workflow.md", workflowTemplate.content]]);
33240
+ for (const template of styleguideTemplates) {
33241
+ const descriptor = describeTemplate(template);
33242
+ if (!descriptor.artifactPath) throw new Error(`Styleguide ${template.id} has no artifact destination`);
33243
+ const content = template.id === "project/styleguides/general" ? template.content.replace("{{GENERAL_STYLE_ADDITIONS}}", "- None.") : template.content;
33244
+ generatedContext.set(descriptor.artifactPath, content);
33245
+ }
33246
+ for (const path of approved.keys()) {
33247
+ if (path.startsWith("styleguides/") && !generatedContext.has(path)) {
33248
+ throw new Error(`Initialization override ${path} is not in the selected styleguide set`);
33249
+ }
33250
+ }
33251
+ for (const [path, content] of approved) generatedContext.set(path, content);
33252
+ const approvedPaths = [...generatedContext.keys()].sort();
33253
+ const approvedArtifactHashes = approvedPaths.map((path) => ({ path, sha256: hash3(generatedContext.get(path)) }));
33004
33254
  const generated = new Map([
33005
- ...approved.entries(),
33255
+ ...generatedContext.entries(),
33006
33256
  [".gitignore", gitignoreTemplate.content],
33007
- ["project.json", projectState(input, approvedPaths, projectTemplate.content)],
33257
+ ["project.json", projectState(input, approvedPaths, approvedArtifactHashes, projectTemplate.content)],
33008
33258
  ["patterns/index.md", patternIndexTemplate.content],
33009
33259
  ["tracks.md", buildTracks([])],
33010
33260
  ["operations/.gitkeep", ""],
@@ -33020,84 +33270,132 @@ function previewProjectInit(input) {
33020
33270
  }));
33021
33271
  return { runtimeVersion: CADRE_RUNTIME_VERSION, templateSetVersion: TEMPLATE_SET_VERSION, files, digest };
33022
33272
  }
33273
+ function loadProjectInitCandidate(input) {
33274
+ const stagedFiles = input.stagedFiles.map(normalizeCadrePath).sort();
33275
+ const actualFiles = listCandidatePaths(input.projectRoot, "create");
33276
+ if (JSON.stringify(actualFiles) !== JSON.stringify(stagedFiles)) {
33277
+ throw new Error(
33278
+ `Initialization candidate manifest differs from staged files; expected ${stagedFiles.join(", ")}, found ${actualFiles.join(", ")}`
33279
+ );
33280
+ }
33281
+ const files = readCandidateFiles(input.projectRoot, "create", stagedFiles).map(({ path, content }) => ({ path, content }));
33282
+ return { ...input, files };
33283
+ }
33284
+ function previewProjectInitCandidate(input) {
33285
+ assertInitializationBootstrap(input.projectRoot);
33286
+ return buildProjectInitProposal(loadProjectInitCandidate(input));
33287
+ }
33288
+ function assertInitializationBootstrap(projectRootInput) {
33289
+ const root = safeProjectRoot(projectRootInput);
33290
+ const cadreRoot2 = join6(root, ".cadre");
33291
+ if (!existsSync8(cadreRoot2) || !lstatSync4(cadreRoot2).isDirectory() || lstatSync4(cadreRoot2).isSymbolicLink()) {
33292
+ throw new Error(`${cadreRoot2} must be a prepared candidate-stage directory`);
33293
+ }
33294
+ const unexpected = readdirSync6(cadreRoot2).filter((entry) => ![".gitignore", "stage"].includes(entry));
33295
+ if (unexpected.length) {
33296
+ throw new Error(`${cadreRoot2} already contains canonical project state: ${unexpected.sort().join(", ")}`);
33297
+ }
33298
+ }
33023
33299
  function targetWithin(root, relativePath) {
33024
- const target = resolve7(root, relativePath);
33025
- const relation = relative2(root, target);
33026
- if (relation.startsWith("..") || isAbsolute(relation)) throw new Error(`Path escapes initialization root: ${relativePath}`);
33300
+ const target = resolve8(root, relativePath);
33301
+ const relation = relative4(root, target);
33302
+ if (relation.startsWith("..") || isAbsolute3(relation)) throw new Error(`Path escapes initialization root: ${relativePath}`);
33027
33303
  return target;
33028
33304
  }
33029
33305
  function assertNoSymlinkPath(root, target) {
33030
33306
  let current = target;
33031
33307
  while (current !== root) {
33032
- if (existsSync7(current) && lstatSync3(current).isSymbolicLink()) {
33308
+ if (existsSync8(current) && lstatSync4(current).isSymbolicLink()) {
33033
33309
  throw new Error(`Refusing symbolic link inside initialization stage: ${current}`);
33034
33310
  }
33035
33311
  current = dirname3(current);
33036
33312
  }
33037
33313
  }
33038
- function applyProjectInit(input, proposalDigest) {
33039
- const proposal = previewProjectInit(input);
33040
- if (proposal.digest !== proposalDigest) throw new Error("Initialization proposal digest does not match; preview again");
33314
+ function applyProjectInitAtRoot(input, proposal) {
33041
33315
  const projectRoot = safeProjectRoot(input.projectRoot);
33042
- const stage = join5(projectRoot, `.cadre-init-${proposal.digest.slice(0, 12)}`);
33043
- if (existsSync7(stage) && (!lstatSync3(stage).isDirectory() || lstatSync3(stage).isSymbolicLink())) {
33044
- throw new Error(`Initialization stage is not a regular directory: ${stage}`);
33045
- }
33046
- mkdirSync2(stage, { recursive: true });
33316
+ const cadreRoot2 = join6(projectRoot, ".cadre");
33047
33317
  for (const file2 of proposal.files) {
33048
- const target = targetWithin(stage, file2.path);
33049
- assertNoSymlinkPath(stage, target);
33050
- mkdirSync2(dirname3(target), { recursive: true });
33051
- if (existsSync7(target)) {
33052
- const current = readFileSync6(target, "utf8");
33318
+ const target = targetWithin(cadreRoot2, file2.path);
33319
+ assertNoSymlinkPath(cadreRoot2, target);
33320
+ mkdirSync3(dirname3(target), { recursive: true });
33321
+ if (existsSync8(target)) {
33322
+ const current = readFileSync7(target, "utf8");
33053
33323
  if (current !== file2.content) throw new Error(`Interrupted initialization disagrees at ${file2.path}`);
33054
- } else writeFileSync3(target, file2.content);
33324
+ continue;
33325
+ }
33326
+ const temporaryPath = join6(dirname3(target), `.cadre-init-${process.pid}-${randomUUID2()}.tmp`);
33327
+ try {
33328
+ writeFileSync4(temporaryPath, file2.content, { flag: "wx" });
33329
+ renameSync3(temporaryPath, target);
33330
+ } finally {
33331
+ if (existsSync8(temporaryPath)) unlinkSync3(temporaryPath);
33332
+ }
33055
33333
  }
33056
- const finalRoot = join5(projectRoot, ".cadre");
33057
- if (existsSync7(finalRoot)) throw new Error(`${finalRoot} appeared after preview; refusing to overwrite it`);
33058
- renameSync2(stage, finalRoot);
33059
33334
  return proposal;
33060
33335
  }
33336
+ function applyProjectInitCandidate(input, proposalDigest) {
33337
+ const materialized = loadProjectInitCandidate(input);
33338
+ const proposal = buildProjectInitProposal(materialized);
33339
+ if (proposal.digest !== proposalDigest) {
33340
+ throw new Error("Initialization candidate changed after preview; preview it again");
33341
+ }
33342
+ return applyProjectInitAtRoot(materialized, proposal);
33343
+ }
33061
33344
  function recordSetupCommit(projectRootInput, commit) {
33062
33345
  if (!/^[0-9a-f]{7,40}$/.test(commit)) throw new Error("commit must be a hexadecimal Git commit SHA");
33063
33346
  const root = safeProjectRoot(projectRootInput);
33064
- const path = join5(root, ".cadre", "project.json");
33065
- const project = JSON.parse(readFileSync6(path, "utf8"));
33347
+ const path = join6(root, ".cadre", "project.json");
33348
+ const project = JSON.parse(readFileSync7(path, "utf8"));
33066
33349
  if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
33067
33350
  throw new Error("Project setup is not awaiting its create commit");
33068
33351
  }
33352
+ if (project.setup.checkpoint !== "commit-pending") {
33353
+ throw new Error(`Project setup checkpoint is ${String(project.setup.checkpoint)}, not commit-pending`);
33354
+ }
33355
+ for (const artifact2 of project.setup.operation.approvedArtifactHashes ?? []) {
33356
+ const artifactPath = targetWithin(join6(root, ".cadre"), normalizeCadrePath(artifact2.path));
33357
+ if (!existsSync8(artifactPath) || lstatSync4(artifactPath).isSymbolicLink()) {
33358
+ throw new Error(`Approved setup artifact is unavailable: ${artifact2.path}`);
33359
+ }
33360
+ if (hash3(readFileSync7(artifactPath, "utf8")) !== artifact2.sha256) {
33361
+ throw new Error(`Approved setup artifact changed before commit recording: ${artifact2.path}`);
33362
+ }
33363
+ if (hash3(readGitFileAtCommit(root, commit, `.cadre/${artifact2.path}`)) !== artifact2.sha256) {
33364
+ throw new Error(`Setup commit does not contain the approved artifact: ${artifact2.path}`);
33365
+ }
33366
+ }
33069
33367
  project.setup.status = "completed";
33070
33368
  project.setup.checkpoint = "completed";
33071
33369
  project.setup.commit = commit;
33072
33370
  project.setup.operation = null;
33073
33371
  project.history = [...project.history ?? [], { action: "create", commit }];
33074
- writeFileSync3(path, `${JSON.stringify(project, null, 2)}
33372
+ writeFileSync4(path, `${JSON.stringify(project, null, 2)}
33075
33373
  `);
33076
33374
  return path;
33077
33375
  }
33078
33376
  function recordGitInitialized(projectRootInput) {
33079
33377
  const root = safeProjectRoot(projectRootInput);
33080
- const path = join5(root, ".cadre", "project.json");
33081
- const project = JSON.parse(readFileSync6(path, "utf8"));
33378
+ const path = join6(root, ".cadre", "project.json");
33379
+ const project = JSON.parse(readFileSync7(path, "utf8"));
33082
33380
  if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
33083
33381
  throw new Error("Project setup is not in an active create operation");
33084
33382
  }
33085
33383
  if (project.setup.operation.gitDisposition !== "initialize") {
33086
33384
  throw new Error("Project setup was not approved to initialize Git");
33087
33385
  }
33088
- if (resolve7(String(project.setup.operation.repositoryRoot)) !== root) {
33386
+ if (resolve8(String(project.setup.operation.repositoryRoot)) !== root) {
33089
33387
  throw new Error("Approved Git repository root does not match projectRoot");
33090
33388
  }
33091
33389
  project.setup.checkpoint = "commit-pending";
33092
- writeFileSync3(path, `${JSON.stringify(project, null, 2)}
33390
+ writeFileSync4(path, `${JSON.stringify(project, null, 2)}
33093
33391
  `);
33094
33392
  return path;
33095
33393
  }
33096
33394
 
33097
33395
  // src/domain/worktrees.ts
33098
33396
  import { createHash as createHash6 } from "node:crypto";
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";
33397
+ import { existsSync as existsSync9, lstatSync as lstatSync5, readdirSync as readdirSync7, realpathSync as realpathSync2, rmdirSync } from "node:fs";
33398
+ import { dirname as dirname4, join as join7, relative as relative5, resolve as resolve9 } from "node:path";
33101
33399
  import { spawnSync as spawnSync2 } from "node:child_process";
33102
33400
  var SHA2 = /^[0-9a-f]{7,40}$/;
33103
33401
  var TRACK_ID2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -33117,7 +33415,7 @@ function hash4(value) {
33117
33415
  }
33118
33416
  function assertRepository(projectRoot) {
33119
33417
  const root = realpathSync2(safeProjectRoot(projectRoot));
33120
- const detected = realpathSync2(resolve8(git(root, ["rev-parse", "--show-toplevel"]).stdout.trim()));
33418
+ const detected = realpathSync2(resolve9(git(root, ["rev-parse", "--show-toplevel"]).stdout.trim()));
33121
33419
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
33122
33420
  return root;
33123
33421
  }
@@ -33143,7 +33441,7 @@ function worktreeIdentity(root, trackId, executionId, nodeId, phaseId) {
33143
33441
  const resolvedPhaseId = phaseForNode(nodeId);
33144
33442
  const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId}/tasks/${resolvedPhaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId}/phases/${nodeId}`;
33145
33443
  const branch = `cadre/${trackId}/${executionId}/${task ? "task" : "phase"}-${nodeSlug(nodeId)}`;
33146
- return { path: join6(root, relativePath), relativePath, branch };
33444
+ return { path: join7(root, relativePath), relativePath, branch };
33147
33445
  }
33148
33446
  function branchHead(root, branch) {
33149
33447
  const result2 = git(root, ["rev-parse", "--verify", `refs/heads/${branch}`], true);
@@ -33154,14 +33452,14 @@ function registeredWorktrees(root) {
33154
33452
  let current = {};
33155
33453
  for (const line of git(root, ["worktree", "list", "--porcelain"]).stdout.split(/\r?\n/)) {
33156
33454
  if (!line) {
33157
- if (current.path && current.head) records.push({ path: resolve8(current.path), branch: current.branch ?? null, head: current.head });
33455
+ if (current.path && current.head) records.push({ path: resolve9(current.path), branch: current.branch ?? null, head: current.head });
33158
33456
  current = {};
33159
33457
  } else if (line.startsWith("worktree ")) current.path = line.slice("worktree ".length);
33160
33458
  else if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length);
33161
33459
  else if (line.startsWith("branch refs/heads/")) current.branch = line.slice("branch refs/heads/".length);
33162
33460
  else if (line === "detached") current.branch = null;
33163
33461
  }
33164
- if (current.path && current.head) records.push({ path: resolve8(current.path), branch: current.branch ?? null, head: current.head });
33462
+ if (current.path && current.head) records.push({ path: resolve9(current.path), branch: current.branch ?? null, head: current.head });
33165
33463
  return records;
33166
33464
  }
33167
33465
  function previewWorktreeCreate(input) {
@@ -33170,12 +33468,12 @@ function previewWorktreeCreate(input) {
33170
33468
  const baseCommit = git(target.path, ["rev-parse", "HEAD^{commit}"]).stdout.trim();
33171
33469
  if (!SHA2.test(baseCommit)) throw new Error("baseCommit does not resolve to a commit");
33172
33470
  const identity = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
33173
- const registered = registeredWorktrees(root).find((entry) => entry.path === resolve8(identity.path));
33471
+ const registered = registeredWorktrees(root).find((entry) => entry.path === resolve9(identity.path));
33174
33472
  const existingBranchHead = branchHead(root, identity.branch);
33175
33473
  if (registered && (registered.branch !== identity.branch || registered.head !== existingBranchHead)) {
33176
33474
  throw new Error(`registered worktree disagrees at ${identity.relativePath}`);
33177
33475
  }
33178
- if (!registered && existsSync8(identity.path)) throw new Error(`unregistered path already exists: ${identity.path}`);
33476
+ if (!registered && existsSync9(identity.path)) throw new Error(`unregistered path already exists: ${identity.path}`);
33179
33477
  if (existingBranchHead) {
33180
33478
  const basedOnExpectedCommit = git(root, ["merge-base", "--is-ancestor", baseCommit, existingBranchHead], true).status === 0;
33181
33479
  if (!basedOnExpectedCommit) throw new Error(`existing branch ${identity.branch} is not based on requested base commit`);
@@ -33188,8 +33486,8 @@ function previewWorktreeCreate(input) {
33188
33486
  };
33189
33487
  return { ...proposal, digest: hash4(proposal) };
33190
33488
  }
33191
- function applyWorktreeCreate(input, proposalDigest) {
33192
- const proposal = previewWorktreeCreate(input);
33489
+ function applyWorktreeCreate(input, proposalDigest, preparedProposal) {
33490
+ const proposal = preparedProposal ?? previewWorktreeCreate(input);
33193
33491
  if (proposal.digest !== proposalDigest) throw new Error("worktree proposal is stale; preview it again");
33194
33492
  if (proposal.existing) return proposal;
33195
33493
  const existingBranch = branchHead(proposal.projectRoot, proposal.branch);
@@ -33210,7 +33508,7 @@ function targetIdentity(root, input) {
33210
33508
  if (TASK_ID.test(input.nodeId)) {
33211
33509
  const phaseId = phaseForNode(input.nodeId);
33212
33510
  const phase = worktreeIdentity(root, input.trackId, input.executionId, phaseId, null);
33213
- const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve8(phase.path));
33511
+ const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve9(phase.path));
33214
33512
  if (phaseWorktree) {
33215
33513
  if (phaseWorktree.branch !== phase.branch) throw new Error(`phase worktree is not on ${phase.branch}`);
33216
33514
  return { path: phase.path, branch: phase.branch };
@@ -33253,8 +33551,8 @@ function previewWorktreeIntegration(input) {
33253
33551
  const root = assertRepository(input.projectRoot);
33254
33552
  const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
33255
33553
  const target = targetIdentity(root, input);
33256
- if (!existsSync8(source.path)) throw new Error(`source worktree is missing: ${source.path}`);
33257
- if (!existsSync8(target.path)) throw new Error(`target worktree is missing: ${target.path}`);
33554
+ if (!existsSync9(source.path)) throw new Error(`source worktree is missing: ${source.path}`);
33555
+ if (!existsSync9(target.path)) throw new Error(`target worktree is missing: ${target.path}`);
33258
33556
  cleanWorktree(source.path);
33259
33557
  const journalPath = `.cadre/tracks/${input.trackId}/executions/execution-${input.executionId}.json`;
33260
33558
  cleanWorktree(target.path, target.path === root ? /* @__PURE__ */ new Set([journalPath]) : /* @__PURE__ */ new Set());
@@ -33281,8 +33579,8 @@ function previewWorktreeIntegration(input) {
33281
33579
  };
33282
33580
  return { ...proposal, digest: hash4(proposal) };
33283
33581
  }
33284
- function applyWorktreeIntegration(input, proposalDigest) {
33285
- const proposal = previewWorktreeIntegration(input);
33582
+ function applyWorktreeIntegration(input, proposalDigest, preparedProposal) {
33583
+ const proposal = preparedProposal ?? previewWorktreeIntegration(input);
33286
33584
  if (proposal.digest !== proposalDigest) throw new Error("integration proposal is stale; preview it again");
33287
33585
  if (proposal.alreadyIntegrated) {
33288
33586
  return { status: "integrated", mergeCommit: proposal.targetHead, conflicts: [], targetPath: proposal.targetPath };
@@ -33305,8 +33603,23 @@ function previewWorktreeCleanup(input) {
33305
33603
  const root = assertRepository(input.projectRoot);
33306
33604
  const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
33307
33605
  const target = targetIdentity(root, input);
33308
- if (!existsSync8(source.path)) throw new Error(`worktree is missing: ${source.path}`);
33309
- if (lstatSync4(source.path).isSymbolicLink()) throw new Error("refusing to clean up a symbolic-link worktree");
33606
+ if (!existsSync9(source.path)) {
33607
+ const branch = branchHead(root, source.branch);
33608
+ const targetHead = git(target.path, ["rev-parse", "HEAD"]).stdout.trim();
33609
+ if (branch && git(root, ["merge-base", "--is-ancestor", branch, target.branch], true).status !== 0) {
33610
+ throw new Error(`${source.branch} is not integrated into ${target.branch}`);
33611
+ }
33612
+ const proposal2 = {
33613
+ path: source.path,
33614
+ branch: source.branch,
33615
+ targetPath: target.path,
33616
+ targetBranch: target.branch,
33617
+ head: branch ?? targetHead,
33618
+ alreadyRemoved: true
33619
+ };
33620
+ return { ...proposal2, digest: hash4(proposal2) };
33621
+ }
33622
+ if (lstatSync5(source.path).isSymbolicLink()) throw new Error("refusing to clean up a symbolic-link worktree");
33310
33623
  cleanWorktree(source.path);
33311
33624
  const head = git(source.path, ["rev-parse", "HEAD"]).stdout.trim();
33312
33625
  const ancestor = git(root, ["merge-base", "--is-ancestor", source.branch, target.branch], true);
@@ -33316,44 +33629,48 @@ function previewWorktreeCleanup(input) {
33316
33629
  branch: source.branch,
33317
33630
  targetPath: target.path,
33318
33631
  targetBranch: target.branch,
33319
- head
33632
+ head,
33633
+ alreadyRemoved: false
33320
33634
  };
33321
33635
  return { ...proposal, digest: hash4(proposal) };
33322
33636
  }
33323
- function applyWorktreeCleanup(input, proposalDigest) {
33324
- const proposal = previewWorktreeCleanup(input);
33637
+ function applyWorktreeCleanup(input, proposalDigest, preparedProposal) {
33638
+ const proposal = preparedProposal ?? previewWorktreeCleanup(input);
33325
33639
  if (proposal.digest !== proposalDigest) throw new Error("cleanup proposal is stale; preview it again");
33326
33640
  const root = assertRepository(input.projectRoot);
33327
- git(root, ["worktree", "remove", proposal.path]);
33328
- git(proposal.targetPath, ["branch", "-d", proposal.branch]);
33329
- const managedRoot = join6(root, ".cadre", ".worktrees");
33641
+ if (!proposal.alreadyRemoved) git(root, ["worktree", "remove", proposal.path]);
33642
+ if (branchHead(root, proposal.branch)) git(proposal.targetPath, ["branch", "-d", proposal.branch]);
33643
+ const managedRoot = join7(root, ".cadre", ".worktrees");
33330
33644
  let directory = dirname4(proposal.path);
33331
33645
  while (directory.startsWith(`${managedRoot}/`)) {
33332
- if (!existsSync8(directory) || readdirSync5(directory).length) break;
33646
+ if (!existsSync9(directory) || readdirSync7(directory).length) break;
33333
33647
  rmdirSync(directory);
33334
33648
  directory = dirname4(directory);
33335
33649
  }
33336
33650
  return { removedPath: proposal.path, removedBranch: proposal.branch };
33337
33651
  }
33652
+ function integrationRequiresApproval(input) {
33653
+ return (readExecution(input.projectRoot, input.trackId, input.executionId).approvalMode ?? "governed") === "governed";
33654
+ }
33338
33655
  function managedWorktreeStatus(projectRoot) {
33339
33656
  const root = assertRepository(projectRoot);
33340
- const managedRoot = join6(root, ".cadre", ".worktrees");
33657
+ const managedRoot = join7(root, ".cadre", ".worktrees");
33341
33658
  const worktrees = registeredWorktrees(root).map((entry) => ({
33342
33659
  ...entry,
33343
- managed: relative3(managedRoot, entry.path) !== "" && !relative3(managedRoot, entry.path).startsWith("..")
33660
+ managed: relative5(managedRoot, entry.path) !== "" && !relative5(managedRoot, entry.path).startsWith("..")
33344
33661
  }));
33345
33662
  const registered = new Set(worktrees.filter((entry) => entry.managed).map((entry) => entry.path));
33346
33663
  const orphanedDirectories = [];
33347
33664
  function walk2(directory) {
33348
- if (!existsSync8(directory)) return;
33349
- if (registered.has(resolve8(directory))) return;
33350
- const entries = readdirSync5(directory, { withFileTypes: true });
33665
+ if (!existsSync9(directory)) return;
33666
+ if (registered.has(resolve9(directory))) return;
33667
+ const entries = readdirSync7(directory, { withFileTypes: true });
33351
33668
  if (entries.some((entry) => entry.name === ".git")) {
33352
33669
  orphanedDirectories.push(directory);
33353
33670
  return;
33354
33671
  }
33355
- for (const entry of entries) if (entry.isDirectory()) walk2(join6(directory, entry.name));
33356
- if (!entries.length && resolve8(directory) !== resolve8(managedRoot)) orphanedDirectories.push(directory);
33672
+ for (const entry of entries) if (entry.isDirectory()) walk2(join7(directory, entry.name));
33673
+ if (!entries.length && resolve9(directory) !== resolve9(managedRoot)) orphanedDirectories.push(directory);
33357
33674
  }
33358
33675
  walk2(managedRoot);
33359
33676
  return { worktrees, orphanedDirectories };
@@ -33362,34 +33679,37 @@ function managedWorktreeStatus(projectRoot) {
33362
33679
  // src/domain/governance.ts
33363
33680
  import { createHash as createHash7 } from "node:crypto";
33364
33681
  import {
33365
- existsSync as existsSync9,
33366
- lstatSync as lstatSync5,
33367
- mkdirSync as mkdirSync3,
33368
- readFileSync as readFileSync7,
33369
- readdirSync as readdirSync6,
33370
- renameSync as renameSync3,
33371
- writeFileSync as writeFileSync4
33682
+ existsSync as existsSync10,
33683
+ lstatSync as lstatSync6,
33684
+ mkdirSync as mkdirSync4,
33685
+ readFileSync as readFileSync8,
33686
+ readdirSync as readdirSync8,
33687
+ renameSync as renameSync4,
33688
+ writeFileSync as writeFileSync5
33372
33689
  } from "node:fs";
33373
- import { dirname as dirname5, join as join7, relative as relative4 } from "node:path";
33690
+ import { dirname as dirname5, join as join8, relative as relative6 } from "node:path";
33374
33691
  var SHA3 = /^[0-9a-f]{7,40}$/;
33375
33692
  var TRACK_ID3 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
33376
33693
  var BATCH_ID = /^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
33377
33694
  function hash5(value) {
33378
33695
  return createHash7("sha256").update(JSON.stringify(value)).digest("hex");
33379
33696
  }
33697
+ function contentHash(content) {
33698
+ return createHash7("sha256").update(content).digest("hex");
33699
+ }
33380
33700
  function json2(value) {
33381
33701
  return `${JSON.stringify(value, null, 2)}
33382
33702
  `;
33383
33703
  }
33384
33704
  function assertWritableFile(path) {
33385
- if (existsSync9(path) && lstatSync5(path).isSymbolicLink()) {
33705
+ if (existsSync10(path) && lstatSync6(path).isSymbolicLink()) {
33386
33706
  throw new Error(`refusing to write through symbolic link ${path}`);
33387
33707
  }
33388
33708
  }
33389
33709
  function writeApprovedFile(path, content) {
33390
33710
  assertWritableFile(path);
33391
- mkdirSync3(dirname5(path), { recursive: true });
33392
- writeFileSync4(path, content);
33711
+ mkdirSync4(dirname5(path), { recursive: true });
33712
+ writeFileSync5(path, content);
33393
33713
  }
33394
33714
  function requireCurrentProject(projectRoot) {
33395
33715
  const validation = validateProject(projectRoot);
@@ -33438,10 +33758,10 @@ function previewReviewComplete(input) {
33438
33758
  if (!execution?.executionId || !execution.planRevision || !execution.graphDigest || execution.headCommit !== input.reviewedHead) {
33439
33759
  throw new Error("review evidence does not match the current completed execution");
33440
33760
  }
33441
- const statePath = join7(cadreRoot(root), track.location, "state.json");
33442
- const tracksPath = join7(cadreRoot(root), "tracks.md");
33443
- const stateBody = readFileSync7(statePath, "utf8");
33444
- const tracksBody = readFileSync7(tracksPath, "utf8");
33761
+ const statePath = join8(cadreRoot(root), track.location, "state.json");
33762
+ const tracksPath = join8(cadreRoot(root), "tracks.md");
33763
+ const stateBody = readFileSync8(statePath, "utf8");
33764
+ const tracksBody = readFileSync8(tracksPath, "utf8");
33445
33765
  const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
33446
33766
  const cycle = {
33447
33767
  cycle: (current.reviewCycles?.length ?? 0) + 1,
@@ -33502,12 +33822,12 @@ function dependencyOrder(tracks) {
33502
33822
  for (const track of tracks) visit(track.id);
33503
33823
  return ordered;
33504
33824
  }
33505
- function deriveArchiveBatchInput(input) {
33825
+ function deriveMaterializedArchiveBatch(input) {
33506
33826
  const root = safeProjectRoot(input.projectRoot);
33507
33827
  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"))
33828
+ const operationsPath = join8(cadreRoot(root), "operations");
33829
+ const activeOperation = existsSync10(operationsPath) ? readdirSync8(operationsPath).filter((file2) => file2.endsWith(".json")).map(
33830
+ (file2) => JSON.parse(readFileSync8(join8(operationsPath, file2), "utf8"))
33511
33831
  ).find((operation) => operation.action === "archive" && operation.status === "in_progress") : void 0;
33512
33832
  const selectedTracks = input.selectedTracks?.length ? [...new Set(input.selectedTracks)] : activeOperation?.selectedTracks ?? dependencyOrder(
33513
33833
  validation.tracks.filter((track) => track.status === "completed" && track.location === `tracks/${track.id}`)
@@ -33535,6 +33855,62 @@ function deriveArchiveBatchInput(input) {
33535
33855
  updates
33536
33856
  };
33537
33857
  }
33858
+ function archiveCandidatePath(update) {
33859
+ if (update.kind === "pattern") {
33860
+ if (!TRACK_ID3.test(update.slug)) throw new Error(`invalid pattern slug ${update.slug}`);
33861
+ return `patterns/${update.slug}.md`;
33862
+ }
33863
+ if (update.kind === "pattern_index") return "patterns/index.md";
33864
+ if (!TRACK_ID3.test(update.trackId)) throw new Error(`invalid active track ID ${update.trackId}`);
33865
+ return `tracks/${update.trackId}/learning.md`;
33866
+ }
33867
+ function materializeArchiveCandidateUpdates(projectRoot, candidateId, updates) {
33868
+ const paths = updates.map(archiveCandidatePath);
33869
+ const files = readCandidateFiles(projectRoot, candidateId, paths);
33870
+ return updates.map((update, index) => {
33871
+ const content = files[index].content;
33872
+ if (update.kind === "pattern") return { ...update, content };
33873
+ if (update.kind === "pattern_index") return { kind: "pattern_index", content };
33874
+ return { ...update, content };
33875
+ });
33876
+ }
33877
+ function deriveArchiveBatchCandidateInput(input) {
33878
+ const materialized = deriveMaterializedArchiveBatch({
33879
+ projectRoot: input.projectRoot,
33880
+ ...input.selectedTracks ? { selectedTracks: input.selectedTracks } : {},
33881
+ updates: materializeArchiveCandidateUpdates(input.projectRoot, input.candidateId, input.updates)
33882
+ });
33883
+ return {
33884
+ projectRoot: materialized.projectRoot,
33885
+ candidateId: input.candidateId,
33886
+ selectedTracks: materialized.selectedTracks,
33887
+ batchId: materialized.batchId,
33888
+ baseCommit: materialized.baseCommit,
33889
+ approvedAt: materialized.approvedAt,
33890
+ updates: input.updates
33891
+ };
33892
+ }
33893
+ function loadArchiveBatchCandidate(input) {
33894
+ const updates = materializeArchiveCandidateUpdates(input.projectRoot, input.candidateId, input.updates).map((update) => {
33895
+ if (update.kind === "pattern") return { path: `patterns/${update.slug}.md`, content: update.content };
33896
+ if (update.kind === "pattern_index") return { path: "patterns/index.md", content: update.content };
33897
+ return { path: `tracks/${update.trackId}/learning.md`, content: update.content };
33898
+ });
33899
+ return {
33900
+ projectRoot: input.projectRoot,
33901
+ batchId: input.batchId,
33902
+ selectedTracks: input.selectedTracks,
33903
+ baseCommit: input.baseCommit,
33904
+ approvedAt: input.approvedAt,
33905
+ updates
33906
+ };
33907
+ }
33908
+ function previewArchiveBatchCandidate(input) {
33909
+ return previewMaterializedArchiveBatch(loadArchiveBatchCandidate(input));
33910
+ }
33911
+ function applyArchiveBatchCandidate(input, proposalDigest) {
33912
+ return applyMaterializedArchiveBatch(loadArchiveBatchCandidate(input), proposalDigest);
33913
+ }
33538
33914
  function assertArchiveUpdate(path, selected) {
33539
33915
  if (path === "patterns/index.md" || /^patterns\/[a-z0-9]+(?:-[a-z0-9]+)*\.md$/.test(path)) return;
33540
33916
  const seed = path.match(/^tracks\/([a-z0-9]+(?:-[a-z0-9]+)*)\/learning\.md$/);
@@ -33544,18 +33920,18 @@ function assertArchiveUpdate(path, selected) {
33544
33920
  function directorySnapshot(path) {
33545
33921
  const files = [];
33546
33922
  function visit(directory) {
33547
- for (const entry of readdirSync6(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
33548
- const target = join7(directory, entry.name);
33923
+ for (const entry of readdirSync8(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
33924
+ const target = join8(directory, entry.name);
33549
33925
  if (entry.isSymbolicLink()) throw new Error(`refusing archive source symbolic link ${target}`);
33550
33926
  if (entry.isDirectory()) visit(target);
33551
- else if (entry.isFile()) files.push({ path: relative4(path, target), content: readFileSync7(target, "utf8") });
33927
+ else if (entry.isFile()) files.push({ path: relative6(path, target), content: readFileSync8(target, "utf8") });
33552
33928
  else throw new Error(`unsupported archive source entry ${target}`);
33553
33929
  }
33554
33930
  }
33555
33931
  visit(path);
33556
33932
  return files;
33557
33933
  }
33558
- function previewArchiveBatch(input) {
33934
+ function previewMaterializedArchiveBatch(input) {
33559
33935
  if (!BATCH_ID.test(input.batchId)) throw new Error("invalid archive batchId");
33560
33936
  if (!SHA3.test(input.baseCommit)) throw new Error("baseCommit must be a Git commit SHA");
33561
33937
  if (!Number.isFinite(Date.parse(input.approvedAt))) throw new Error("approvedAt must be an ISO timestamp");
@@ -33564,8 +33940,8 @@ function previewArchiveBatch(input) {
33564
33940
  }
33565
33941
  if (input.selectedTracks.some((trackId) => !TRACK_ID3.test(trackId))) throw new Error("invalid selected track ID");
33566
33942
  const root = safeProjectRoot(input.projectRoot);
33567
- const operationPath = join7(cadreRoot(root), "operations", `${input.batchId}.json`);
33568
- const existingOperation = existsSync9(operationPath) ? JSON.parse(readFileSync7(operationPath, "utf8")) : null;
33943
+ const operationPath = join8(cadreRoot(root), "operations", `${input.batchId}.json`);
33944
+ const existingOperation = existsSync10(operationPath) ? JSON.parse(readFileSync8(operationPath, "utf8")) : null;
33569
33945
  if (existingOperation && (existingOperation.action !== "archive" || existingOperation.status !== "in_progress" || existingOperation.baseCommit !== input.baseCommit || JSON.stringify(existingOperation.selectedTracks) !== JSON.stringify(input.selectedTracks))) {
33570
33946
  throw new Error(`archive batch ${input.batchId} does not match the approved input`);
33571
33947
  }
@@ -33586,9 +33962,9 @@ function previewArchiveBatch(input) {
33586
33962
  if (existingOperation && existingOperation.approvalDigest !== approvalDigest) {
33587
33963
  throw new Error(`archive batch ${input.batchId} content differs from its approved journal`);
33588
33964
  }
33589
- const activeOperations = join7(cadreRoot(root), "operations");
33590
- const unfinished = existsSync9(activeOperations) ? readdirSync6(activeOperations).filter((file2) => file2.endsWith(".json")).find((file2) => {
33591
- const operation2 = JSON.parse(readFileSync7(join7(activeOperations, file2), "utf8"));
33965
+ const activeOperations = join8(cadreRoot(root), "operations");
33966
+ const unfinished = existsSync10(activeOperations) ? readdirSync8(activeOperations).filter((file2) => file2.endsWith(".json")).find((file2) => {
33967
+ const operation2 = JSON.parse(readFileSync8(join8(activeOperations, file2), "utf8"));
33592
33968
  return operation2.status === "in_progress";
33593
33969
  }) : void 0;
33594
33970
  if (unfinished && unfinished !== `${input.batchId}.json`) {
@@ -33603,9 +33979,9 @@ function previewArchiveBatch(input) {
33603
33979
  if (!pending && !completed || state.operation != null) {
33604
33980
  throw new Error(`${trackId} is not an eligible completed track`);
33605
33981
  }
33606
- const sourcePath = join7(cadreRoot(root), pending ? "tracks" : "archive", trackId);
33607
- const targetPath = join7(cadreRoot(root), "archive", trackId);
33608
- if (pending && existsSync9(targetPath)) throw new Error(`archive target already exists for ${trackId}`);
33982
+ const sourcePath = join8(cadreRoot(root), pending ? "tracks" : "archive", trackId);
33983
+ const targetPath = join8(cadreRoot(root), "archive", trackId);
33984
+ if (pending && existsSync10(targetPath)) throw new Error(`archive target already exists for ${trackId}`);
33609
33985
  return { trackId, sourcePath, targetPath, state: { ...state, status: "archived" }, needsMove: pending };
33610
33986
  });
33611
33987
  const proposedTracks = validation.tracks.map((track) => selected.has(track.id) ? { ...track, status: "archived", location: `archive/${track.id}` } : track);
@@ -33625,6 +34001,7 @@ function previewArchiveBatch(input) {
33625
34001
  selectedTracks: [...input.selectedTracks],
33626
34002
  completedTracks: [],
33627
34003
  approvedArtifacts,
34004
+ approvedArtifactHashes: updates.map((update) => ({ path: update.path, sha256: contentHash(update.content) })),
33628
34005
  artifactProgress: [],
33629
34006
  approvedAt: input.approvedAt,
33630
34007
  approvalDigest,
@@ -33637,12 +34014,12 @@ function previewArchiveBatch(input) {
33637
34014
  artifactProgress: [...moveArtifacts, ...updateArtifacts, "tracks.md"]
33638
34015
  };
33639
34016
  const current = {
33640
- project: readFileSync7(join7(cadreRoot(root), "project.json"), "utf8"),
33641
- tracks: readFileSync7(join7(cadreRoot(root), "tracks.md"), "utf8"),
34017
+ project: readFileSync8(join8(cadreRoot(root), "project.json"), "utf8"),
34018
+ tracks: readFileSync8(join8(cadreRoot(root), "tracks.md"), "utf8"),
33642
34019
  sources: moves.map((move) => ({ trackId: move.trackId, files: directorySnapshot(move.sourcePath) })),
33643
34020
  updates: updates.map((update) => ({
33644
34021
  path: update.path,
33645
- content: existsSync9(join7(cadreRoot(root), update.path)) ? readFileSync7(join7(cadreRoot(root), update.path), "utf8") : null
34022
+ content: existsSync10(join8(cadreRoot(root), update.path)) ? readFileSync8(join8(cadreRoot(root), update.path), "utf8") : null
33646
34023
  }))
33647
34024
  };
33648
34025
  return {
@@ -33651,23 +34028,23 @@ function previewArchiveBatch(input) {
33651
34028
  operation,
33652
34029
  moves,
33653
34030
  writes: updates,
33654
- tracksPath: join7(cadreRoot(root), "tracks.md"),
34031
+ tracksPath: join8(cadreRoot(root), "tracks.md"),
33655
34032
  tracksContent,
33656
34033
  resuming: existingOperation != null,
33657
34034
  digest: hash5({ current, input, initialOperation, operation, moves: moves.map(({ trackId, state, needsMove }) => ({ trackId, state, needsMove })), updates, tracksContent })
33658
34035
  };
33659
34036
  }
33660
- function applyArchiveBatch(input, proposalDigest) {
33661
- const proposal = previewArchiveBatch(input);
34037
+ function applyMaterializedArchiveBatch(input, proposalDigest) {
34038
+ const proposal = previewMaterializedArchiveBatch(input);
33662
34039
  if (proposal.digest !== proposalDigest) throw new Error("archive batch proposal is stale; preview it again");
33663
- const currentOperation = existsSync9(proposal.operationPath) ? JSON.parse(readFileSync7(proposal.operationPath, "utf8")) : proposal.initialOperation;
33664
- if (!existsSync9(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json2(currentOperation));
33665
- mkdirSync3(join7(cadreRoot(input.projectRoot), "archive"), { recursive: true });
34040
+ const currentOperation = existsSync10(proposal.operationPath) ? JSON.parse(readFileSync8(proposal.operationPath, "utf8")) : proposal.initialOperation;
34041
+ if (!existsSync10(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json2(currentOperation));
34042
+ mkdirSync4(join8(cadreRoot(input.projectRoot), "archive"), { recursive: true });
33666
34043
  const completedTracks = new Set(currentOperation.completedTracks);
33667
34044
  const artifactProgress = new Set(currentOperation.artifactProgress);
33668
34045
  for (const move of proposal.moves) {
33669
- if (move.needsMove) renameSync3(move.sourcePath, move.targetPath);
33670
- writeApprovedFile(join7(move.targetPath, "state.json"), json2(move.state));
34046
+ if (move.needsMove) renameSync4(move.sourcePath, move.targetPath);
34047
+ writeApprovedFile(join8(move.targetPath, "state.json"), json2(move.state));
33671
34048
  completedTracks.add(move.trackId);
33672
34049
  artifactProgress.add(`archive/${move.trackId}`);
33673
34050
  writeApprovedFile(proposal.operationPath, json2({
@@ -33677,7 +34054,7 @@ function applyArchiveBatch(input, proposalDigest) {
33677
34054
  }));
33678
34055
  }
33679
34056
  for (const update of proposal.writes) {
33680
- writeApprovedFile(join7(cadreRoot(input.projectRoot), update.path), update.content);
34057
+ writeApprovedFile(join8(cadreRoot(input.projectRoot), update.path), update.content);
33681
34058
  artifactProgress.add(update.path);
33682
34059
  writeApprovedFile(proposal.operationPath, json2({
33683
34060
  ...currentOperation,
@@ -33700,18 +34077,18 @@ function previewArchiveBatchRecord(input) {
33700
34077
  if (!BATCH_ID.test(input.batchId)) throw new Error("invalid archive batchId");
33701
34078
  if (!SHA3.test(input.archiveCommit)) throw new Error("archiveCommit must be a Git commit SHA");
33702
34079
  const root = safeProjectRoot(input.projectRoot);
33703
- const operationPath = join7(cadreRoot(root), "operations", `${input.batchId}.json`);
33704
- const operationBody = readFileSync7(operationPath, "utf8");
34080
+ const operationPath = join8(cadreRoot(root), "operations", `${input.batchId}.json`);
34081
+ const operationBody = readFileSync8(operationPath, "utf8");
33705
34082
  const currentOperation = JSON.parse(operationBody);
33706
34083
  if (currentOperation.action !== "archive" || currentOperation.status !== "in_progress") {
33707
34084
  throw new Error(`${input.batchId} is not an in-progress archive batch`);
33708
34085
  }
33709
- const projectPath = join7(cadreRoot(root), "project.json");
33710
- const projectBody = readFileSync7(projectPath, "utf8");
34086
+ const projectPath = join8(cadreRoot(root), "project.json");
34087
+ const projectBody = readFileSync8(projectPath, "utf8");
33711
34088
  const currentProject = JSON.parse(projectBody);
33712
34089
  const states = currentOperation.selectedTracks.map((trackId) => {
33713
- const path = join7(cadreRoot(root), "archive", trackId, "state.json");
33714
- const body = readFileSync7(path, "utf8");
34090
+ const path = join8(cadreRoot(root), "archive", trackId, "state.json");
34091
+ const body = readFileSync8(path, "utf8");
33715
34092
  const current = JSON.parse(body);
33716
34093
  if (current.status !== "archived") throw new Error(`${trackId} is not archived`);
33717
34094
  return {
@@ -33752,8 +34129,8 @@ function previewArchiveBatchRecord(input) {
33752
34129
  digest: hash5({ operationBody, projectBody, states: states.map(({ path, body, state }) => ({ path, body, state })), operation, project })
33753
34130
  };
33754
34131
  }
33755
- function applyArchiveBatchRecord(input, proposalDigest) {
33756
- const proposal = previewArchiveBatchRecord(input);
34132
+ function applyArchiveBatchRecord(input, proposalDigest, preparedProposal) {
34133
+ const proposal = preparedProposal ?? previewArchiveBatchRecord(input);
33757
34134
  if (proposal.digest !== proposalDigest) throw new Error("archive record proposal is stale; preview it again");
33758
34135
  for (const state of proposal.states) writeApprovedFile(state.path, json2(state.state));
33759
34136
  writeApprovedFile(proposal.projectPath, json2(proposal.project));
@@ -33791,33 +34168,11 @@ var workflowQuestionSchema = external_exports.discriminatedUnion("type", [
33791
34168
  type: external_exports.literal("boolean"),
33792
34169
  default: external_exports.boolean().optional()
33793
34170
  }),
33794
- external_exports.object({
33795
- ...questionBase,
33796
- type: external_exports.literal("number"),
33797
- minimum: external_exports.number().optional(),
33798
- maximum: external_exports.number().optional(),
33799
- default: external_exports.number().optional()
33800
- }),
33801
- external_exports.object({
33802
- ...questionBase,
33803
- type: external_exports.literal("integer"),
33804
- minimum: external_exports.number().int().optional(),
33805
- maximum: external_exports.number().int().optional(),
33806
- default: external_exports.number().int().optional()
33807
- }),
33808
34171
  external_exports.object({
33809
34172
  ...questionBase,
33810
34173
  type: external_exports.literal("single_select"),
33811
34174
  options: external_exports.array(choiceSchema).min(2).max(10),
33812
34175
  default: external_exports.string().max(120).optional()
33813
- }),
33814
- external_exports.object({
33815
- ...questionBase,
33816
- type: external_exports.literal("multi_select"),
33817
- options: external_exports.array(choiceSchema).min(2).max(10),
33818
- minSelections: external_exports.number().int().min(0).optional(),
33819
- maxSelections: external_exports.number().int().min(1).optional(),
33820
- default: external_exports.array(external_exports.string().max(120)).max(10).optional()
33821
34176
  })
33822
34177
  ]);
33823
34178
  var workflowElicitationInputSchema = {
@@ -33854,22 +34209,6 @@ function questionSchema(question) {
33854
34209
  type: "boolean",
33855
34210
  ...question.default === void 0 ? {} : { default: question.default }
33856
34211
  };
33857
- case "number":
33858
- case "integer": {
33859
- if (question.minimum !== void 0 && question.maximum !== void 0 && question.minimum > question.maximum) {
33860
- throw new Error(`${question.id} minimum cannot exceed maximum`);
33861
- }
33862
- if (question.default !== void 0 && (question.minimum !== void 0 && question.default < question.minimum || question.maximum !== void 0 && question.default > question.maximum)) {
33863
- throw new Error(`${question.id} default must be within its numeric bounds`);
33864
- }
33865
- return {
33866
- ...common,
33867
- type: question.type,
33868
- ...question.minimum === void 0 ? {} : { minimum: question.minimum },
33869
- ...question.maximum === void 0 ? {} : { maximum: question.maximum },
33870
- ...question.default === void 0 ? {} : { default: question.default }
33871
- };
33872
- }
33873
34212
  case "single_select": {
33874
34213
  const values = choiceValues(question);
33875
34214
  if (question.default !== void 0 && !values.includes(question.default)) {
@@ -33882,27 +34221,6 @@ function questionSchema(question) {
33882
34221
  ...question.default === void 0 ? {} : { default: question.default }
33883
34222
  };
33884
34223
  }
33885
- case "multi_select": {
33886
- const values = choiceValues(question);
33887
- const minimum = question.minSelections ?? (question.required ? 1 : 0);
33888
- const maximum = question.maxSelections ?? values.length;
33889
- if (minimum > maximum || maximum > values.length) {
33890
- throw new Error(`${question.id} selection bounds are invalid`);
33891
- }
33892
- if (question.default?.some((value) => !values.includes(value))) {
33893
- throw new Error(`${question.id} defaults must match option values`);
33894
- }
33895
- return {
33896
- ...common,
33897
- type: "array",
33898
- items: {
33899
- anyOf: question.options.map((option) => ({ const: option.value, title: option.label }))
33900
- },
33901
- minItems: minimum,
33902
- maxItems: maximum,
33903
- ...question.default === void 0 ? {} : { default: question.default }
33904
- };
33905
- }
33906
34224
  }
33907
34225
  }
33908
34226
  function supportsFormElicitation(capabilities) {
@@ -33991,20 +34309,20 @@ import { randomBytes } from "node:crypto";
33991
34309
  import {
33992
34310
  chmodSync,
33993
34311
  closeSync,
33994
- existsSync as existsSync10,
34312
+ existsSync as existsSync11,
33995
34313
  fstatSync,
33996
34314
  fsyncSync,
33997
- lstatSync as lstatSync6,
33998
- mkdirSync as mkdirSync4,
34315
+ lstatSync as lstatSync7,
34316
+ mkdirSync as mkdirSync5,
33999
34317
  openSync,
34000
- readFileSync as readFileSync8,
34001
- readdirSync as readdirSync7,
34002
- unlinkSync as unlinkSync2,
34003
- writeFileSync as writeFileSync5
34318
+ readFileSync as readFileSync9,
34319
+ readdirSync as readdirSync9,
34320
+ unlinkSync as unlinkSync4,
34321
+ writeFileSync as writeFileSync6
34004
34322
  } from "node:fs";
34005
34323
  import { homedir as homedir2 } from "node:os";
34006
34324
  import { constants } from "node:fs";
34007
- import { join as join8, resolve as resolve10 } from "node:path";
34325
+ import { join as join9, resolve as resolve11 } from "node:path";
34008
34326
  var TOKEN_PREFIX = "cadre_pt1_";
34009
34327
  var TOKEN_PATTERN = /^cadre_pt1_[A-Za-z0-9_-]{32}$/;
34010
34328
  var RECORD_PATTERN = /^cadre_pt1_[A-Za-z0-9_-]{32}\.json$/;
@@ -34021,8 +34339,8 @@ var envelopeSchema = external_exports.object({
34021
34339
  });
34022
34340
  var proposalTokenSchema = external_exports.string().regex(TOKEN_PATTERN, "invalid proposal token format");
34023
34341
  function defaultProposalRoot() {
34024
- const cadreHome = process.env.CADRE_HOME ? resolve10(process.env.CADRE_HOME) : join8(homedir2(), ".cadre");
34025
- return join8(cadreHome, "runtime", "proposals");
34342
+ const cadreHome = process.env.CADRE_HOME ? resolve11(process.env.CADRE_HOME) : join9(homedir2(), ".cadre");
34343
+ return join9(cadreHome, "runtime", "proposals");
34026
34344
  }
34027
34345
  var ProposalTokenStore = class {
34028
34346
  root;
@@ -34031,7 +34349,7 @@ var ProposalTokenStore = class {
34031
34349
  maxAgeMs;
34032
34350
  now;
34033
34351
  constructor(options = {}) {
34034
- this.root = resolve10(options.root ?? defaultProposalRoot());
34352
+ this.root = resolve11(options.root ?? defaultProposalRoot());
34035
34353
  this.maxRetainedProposals = options.maxRetainedProposals ?? DEFAULT_MAX_RETAINED_PROPOSALS;
34036
34354
  this.maxRetainedBytes = options.maxRetainedBytes ?? DEFAULT_MAX_RETAINED_BYTES;
34037
34355
  this.maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
@@ -34065,7 +34383,7 @@ var ProposalTokenStore = class {
34065
34383
  constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
34066
34384
  384
34067
34385
  );
34068
- writeFileSync5(descriptor, serialized, "utf8");
34386
+ writeFileSync6(descriptor, serialized, "utf8");
34069
34387
  fsyncSync(descriptor);
34070
34388
  return token;
34071
34389
  } catch (error51) {
@@ -34079,9 +34397,9 @@ var ProposalTokenStore = class {
34079
34397
  if (!TOKEN_PATTERN.test(token)) throw new Error("invalid proposal token format");
34080
34398
  this.prepareRoot();
34081
34399
  const path = this.pathFor(token);
34082
- if (!existsSync10(path)) {
34400
+ if (!existsSync11(path)) {
34083
34401
  throw new Error(
34084
- "proposal token is unknown or no longer retained; call the matching preview tool again"
34402
+ "proposal token is unknown or no longer retained; request a new proposal from the matching command"
34085
34403
  );
34086
34404
  }
34087
34405
  let descriptor = null;
@@ -34094,12 +34412,12 @@ var ProposalTokenStore = class {
34094
34412
  throw new Error("proposal runtime record is owned by another user");
34095
34413
  }
34096
34414
  if (stat.size > MAX_PROPOSAL_BYTES) throw new Error("proposal record is too large");
34097
- const envelope = envelopeSchema.parse(JSON.parse(readFileSync8(descriptor, "utf8")));
34415
+ const envelope = envelopeSchema.parse(JSON.parse(readFileSync9(descriptor, "utf8")));
34098
34416
  if (this.now().getTime() - Date.parse(envelope.createdAt) > this.maxAgeMs) {
34099
34417
  closeSync(descriptor);
34100
34418
  descriptor = null;
34101
34419
  this.unlinkRecord(path);
34102
- throw new Error("proposal token has expired; call the matching preview tool again");
34420
+ throw new Error("proposal token has expired; request a new proposal from the matching command");
34103
34421
  }
34104
34422
  if (envelope.kind !== kind) throw new Error(`proposal token is for ${envelope.kind}, not ${kind}`);
34105
34423
  return { input: envelope.input, digest: envelope.digest };
@@ -34109,7 +34427,7 @@ var ProposalTokenStore = class {
34109
34427
  }
34110
34428
  if (error51.code === "ENOENT") {
34111
34429
  throw new Error(
34112
- "proposal token is unknown or no longer retained; call the matching preview tool again"
34430
+ "proposal token is unknown or no longer retained; request a new proposal from the matching command"
34113
34431
  );
34114
34432
  }
34115
34433
  throw error51;
@@ -34118,8 +34436,8 @@ var ProposalTokenStore = class {
34118
34436
  }
34119
34437
  }
34120
34438
  prepareRoot() {
34121
- mkdirSync4(this.root, { recursive: true, mode: 448 });
34122
- const stat = lstatSync6(this.root);
34439
+ mkdirSync5(this.root, { recursive: true, mode: 448 });
34440
+ const stat = lstatSync7(this.root);
34123
34441
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
34124
34442
  throw new Error(`proposal runtime root is not a regular directory: ${this.root}`);
34125
34443
  }
@@ -34129,16 +34447,16 @@ var ProposalTokenStore = class {
34129
34447
  if ((stat.mode & 63) !== 0) chmodSync(this.root, 448);
34130
34448
  }
34131
34449
  pathFor(token) {
34132
- return join8(this.root, `${token}.json`);
34450
+ return join9(this.root, `${token}.json`);
34133
34451
  }
34134
34452
  records() {
34135
34453
  const records = [];
34136
- for (const entry of readdirSync7(this.root)) {
34454
+ for (const entry of readdirSync9(this.root)) {
34137
34455
  if (!RECORD_PATTERN.test(entry)) continue;
34138
- const path = join8(this.root, entry);
34456
+ const path = join9(this.root, entry);
34139
34457
  let stat;
34140
34458
  try {
34141
- stat = lstatSync6(path);
34459
+ stat = lstatSync7(path);
34142
34460
  } catch (error51) {
34143
34461
  if (error51.code === "ENOENT") continue;
34144
34462
  throw error51;
@@ -34146,7 +34464,7 @@ var ProposalTokenStore = class {
34146
34464
  if (!stat.isFile() || stat.isSymbolicLink()) continue;
34147
34465
  let createdAt = stat.mtimeMs;
34148
34466
  try {
34149
- const envelope = envelopeSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
34467
+ const envelope = envelopeSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34150
34468
  createdAt = Date.parse(envelope.createdAt);
34151
34469
  } catch {
34152
34470
  }
@@ -34172,7 +34490,7 @@ var ProposalTokenStore = class {
34172
34490
  }
34173
34491
  unlinkRecord(path) {
34174
34492
  try {
34175
- unlinkSync2(path);
34493
+ unlinkSync4(path);
34176
34494
  } catch (error51) {
34177
34495
  if (error51.code !== "ENOENT") throw error51;
34178
34496
  }
@@ -34180,12 +34498,28 @@ var ProposalTokenStore = class {
34180
34498
  };
34181
34499
 
34182
34500
  // src/mcp/server.ts
34183
- function result(value, summary) {
34501
+ function result(value, summary = "Cadre operation completed.") {
34184
34502
  return {
34185
- content: [{ type: "text", text: summary ?? JSON.stringify(value, null, 2) }],
34503
+ content: [{ type: "text", text: summary }],
34186
34504
  structuredContent: value
34187
34505
  };
34188
34506
  }
34507
+ function templateResult(templates) {
34508
+ return {
34509
+ content: templates.map((template) => ({
34510
+ type: "resource",
34511
+ resource: {
34512
+ uri: template.uri,
34513
+ mimeType: template.mimeType,
34514
+ text: template.content
34515
+ }
34516
+ })),
34517
+ structuredContent: {
34518
+ templateSetVersion: TEMPLATE_SET_VERSION,
34519
+ templates: templates.map(({ content: _content, ...descriptor }) => descriptor)
34520
+ }
34521
+ };
34522
+ }
34189
34523
  function sha256(content) {
34190
34524
  return createHash8("sha256").update(content).digest("hex");
34191
34525
  }
@@ -34196,8 +34530,49 @@ function jsonArtifact(path, value) {
34196
34530
  return artifact(path, `${JSON.stringify(value, null, 2)}
34197
34531
  `);
34198
34532
  }
34199
- function proposalInputSchema() {
34200
- return { proposalToken: proposalTokenSchema };
34533
+ function requireCurrentProject2(projectRoot) {
34534
+ const root = safeProjectRoot(projectRoot);
34535
+ const path = join10(root, ".cadre", "project.json");
34536
+ const project = JSON.parse(readFileSync10(path, "utf8"));
34537
+ if (project.runtimeVersion !== CADRE_RUNTIME_VERSION || project.templateSetVersion !== TEMPLATE_SET_VERSION) {
34538
+ throw new CadreError(
34539
+ "PROJECT_REFRESH_REQUIRED",
34540
+ `Cadre project refresh required before mutation: current ${project.runtimeVersion ?? "unknown"}/${project.templateSetVersion ?? "unknown"}, target ${CADRE_RUNTIME_VERSION}/${TEMPLATE_SET_VERSION}.`,
34541
+ {
34542
+ currentRuntimeVersion: project.runtimeVersion ?? null,
34543
+ currentTemplateSetVersion: project.templateSetVersion ?? null,
34544
+ targetRuntimeVersion: CADRE_RUNTIME_VERSION,
34545
+ targetTemplateSetVersion: TEMPLATE_SET_VERSION
34546
+ }
34547
+ );
34548
+ }
34549
+ return root;
34550
+ }
34551
+ var adaptiveModeSchema = external_exports.enum(["prepare", "apply"]);
34552
+ function adaptiveInputSchema(prepare) {
34553
+ const optionalPrepare = Object.fromEntries(Object.entries(prepare).map(([key, schema]) => [
34554
+ key,
34555
+ schema.optional()
34556
+ ]));
34557
+ return external_exports.object({
34558
+ mode: adaptiveModeSchema,
34559
+ proposalToken: proposalTokenSchema.optional(),
34560
+ ...optionalPrepare
34561
+ }).strict();
34562
+ }
34563
+ function normalizeAdaptiveInput(input, requiredPrepareFields, command) {
34564
+ const prepareFields = Object.keys(input).filter((key) => key !== "mode" && key !== "proposalToken");
34565
+ if (input.mode === "apply") {
34566
+ if (typeof input.proposalToken !== "string") throw new Error(`${command} apply mode requires proposalToken`);
34567
+ if (prepareFields.length) throw new Error(`${command} apply mode accepts only mode and proposalToken`);
34568
+ return { mode: "apply", proposalToken: input.proposalToken };
34569
+ }
34570
+ if (input.mode !== "prepare") throw new Error(`${command} mode must be prepare or apply`);
34571
+ if (input.proposalToken !== void 0) throw new Error(`${command} prepare mode cannot include proposalToken`);
34572
+ const missing = requiredPrepareFields.filter((key) => input[key] === void 0);
34573
+ if (missing.length) throw new Error(`${command} prepare mode requires ${missing.join(", ")}`);
34574
+ const { mode: _mode, proposalToken: _proposalToken, ...request } = input;
34575
+ return { mode: "prepare", request };
34201
34576
  }
34202
34577
  function failure(error51) {
34203
34578
  const serialized = serializeCadreError(error51);
@@ -34220,6 +34595,57 @@ function serializableValidation(validation) {
34220
34595
  warnings: validation.warnings
34221
34596
  };
34222
34597
  }
34598
+ function trackSummary(track) {
34599
+ return {
34600
+ id: track.id,
34601
+ title: track.title,
34602
+ type: track.type,
34603
+ status: track.status,
34604
+ checkpoint: track.checkpoint ?? null,
34605
+ operation: track.operation?.action ?? null,
34606
+ dependencies: track.dependencies ?? [],
34607
+ revision: track.revision ?? 1,
34608
+ location: track.location
34609
+ };
34610
+ }
34611
+ function projectTrackSummary(track) {
34612
+ const dependencies = track.dependencies ?? [];
34613
+ return {
34614
+ id: track.id,
34615
+ title: track.title,
34616
+ status: track.status,
34617
+ ...track.checkpoint ? { checkpoint: track.checkpoint } : {},
34618
+ ...track.operation?.action ? { operation: track.operation.action } : {},
34619
+ ...dependencies.length ? { dependencies } : {}
34620
+ };
34621
+ }
34622
+ function projectStatusView(validation) {
34623
+ const counts = Object.fromEntries(
34624
+ [...new Set(validation.tracks.map((track) => track.status))].map((status) => [status, validation.tracks.filter((track) => track.status === status).length])
34625
+ );
34626
+ return {
34627
+ valid: validation.errors.length === 0,
34628
+ derivedStateCurrent: validation.warnings.length === 0,
34629
+ project: validation.project ? {
34630
+ name: validation.project.project?.name ?? null,
34631
+ context: validation.project.project?.context ?? null,
34632
+ runtimeVersion: validation.project.runtimeVersion ?? null,
34633
+ templateSetVersion: validation.project.templateSetVersion ?? null,
34634
+ setup: validation.project.setup ? {
34635
+ status: validation.project.setup.status ?? null,
34636
+ checkpoint: validation.project.setup.checkpoint ?? null
34637
+ } : null,
34638
+ lastRefresh: validation.project.lastRefresh ?? null
34639
+ } : null,
34640
+ upgradeRequired: validation.project ? validation.project.runtimeVersion !== CADRE_RUNTIME_VERSION || validation.project.templateSetVersion !== TEMPLATE_SET_VERSION : false,
34641
+ targetRuntimeVersion: CADRE_RUNTIME_VERSION,
34642
+ targetTemplateSetVersion: TEMPLATE_SET_VERSION,
34643
+ counts,
34644
+ tracks: validation.tracks.map(projectTrackSummary),
34645
+ errors: validation.errors,
34646
+ warnings: validation.warnings
34647
+ };
34648
+ }
34223
34649
  var PLAN_VALIDATION_STATUSES = [
34224
34650
  "drafting-spec",
34225
34651
  "drafting-plan",
@@ -34234,10 +34660,33 @@ function createCadreServer() {
34234
34660
  const proposalTokens = new ProposalTokenStore();
34235
34661
  function proposalResult(kind, input, value) {
34236
34662
  return result({
34663
+ commandStatus: "approval_required",
34237
34664
  ...value,
34238
34665
  proposalToken: proposalTokens.issue(kind, input, value.digest)
34239
34666
  });
34240
34667
  }
34668
+ function applyCheckpointNow(input) {
34669
+ const preview = previewExecutionCheckpoint(input);
34670
+ const applied = applyExecutionCheckpoint(input, preview.digest, preview);
34671
+ return {
34672
+ transition: applied.transition,
34673
+ derivedStatus: executionSchedulerView(applied.journal, [input.nodeId])
34674
+ };
34675
+ }
34676
+ function recordIntegrationNow(input, commit) {
34677
+ const journal = executionStatus(input.projectRoot, input.trackId, input.executionId).journal;
34678
+ const node = journal.nodes[input.nodeId];
34679
+ if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
34680
+ if (["integrated", "completed"].includes(node.status)) {
34681
+ return { transition: null, derivedStatus: executionSchedulerView(journal, [input.nodeId]) };
34682
+ }
34683
+ return applyCheckpointNow({
34684
+ ...input,
34685
+ event: "record_integration",
34686
+ commit,
34687
+ verification: `Integrated ${input.nodeId} into its registered parent worktree.`
34688
+ });
34689
+ }
34241
34690
  const server = new McpServer(
34242
34691
  { name: "cadre", version: CADRE_RUNTIME_VERSION },
34243
34692
  {
@@ -34245,8 +34694,9 @@ function createCadreServer() {
34245
34694
  "Cadre provides deterministic, versioned templates and narrow project-state operations.",
34246
34695
  "Read every existing artifact before proposing edits. Never infer file contents.",
34247
34696
  "For any mutation, present the complete proposed artifacts to the human and obtain approval first.",
34697
+ "Stage unapproved artifact bodies under the project-local .cadre/stage directory and use candidate manifest/command tools; do not transport those bodies through MCP when a candidate tool is available.",
34248
34698
  "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.",
34249
- "Call a preview tool immediately before its matching apply tool and pass only the returned proposal token.",
34699
+ "Use one adaptive command call when authorization already exists. A command returns approval_required with a proposal token only when a human decision is required; call that same command with the token only after approval.",
34250
34700
  "Cadre state is resumable: inspect project_status once at command entry and reserve state_validate for final mutation gates.",
34251
34701
  "The plan is the implementation source of truth. Cadre MCP exposes only constrained, digest-gated Git worktree operations and never approves its own changes."
34252
34702
  ].join(" ")
@@ -34254,7 +34704,7 @@ function createCadreServer() {
34254
34704
  );
34255
34705
  server.registerTool("workflow_elicit", {
34256
34706
  title: "Collect Cadre workflow input",
34257
- description: "Present one client-native Cadre approval or clarification form. This read-only tool never grants approval or mutates state. Do not call it when active task context reports approval policy never, including Codex Full Access; ask one short chat question instead. Otherwise bind approval forms to the current proposal digest or immutable verification checkpoint, never request secrets, and use its chat fallback exactly once when form elicitation is unavailable.",
34707
+ description: "Present one read-only Cadre approval or clarification form. Skip it under non-interactive host policy, bind approvals to an immutable digest or checkpoint, never request secrets, and use its chat fallback once.",
34258
34708
  inputSchema: workflowElicitationInputSchema,
34259
34709
  annotations: { readOnlyHint: true, openWorldHint: false }
34260
34710
  }, async (input) => {
@@ -34285,26 +34735,6 @@ function createCadreServer() {
34285
34735
  async () => ({ contents: [{ uri: template.uri, mimeType: template.mimeType, text: template.content }] })
34286
34736
  );
34287
34737
  }
34288
- server.registerTool("template_catalog", {
34289
- title: "List Cadre templates",
34290
- description: "List immutable template identifiers, URIs, media types, and content hashes.",
34291
- annotations: { readOnlyHint: true, openWorldHint: false }
34292
- }, async () => result({
34293
- templateSetVersion: TEMPLATE_SET_VERSION,
34294
- templates: templateCatalog().map(({ content: _content, ...template }) => template)
34295
- }));
34296
- server.registerTool("template_get", {
34297
- title: "Get a Cadre template",
34298
- description: "Read one immutable, versioned Cadre template by logical identifier.",
34299
- inputSchema: { id: external_exports.enum(TEMPLATE_IDS) },
34300
- annotations: { readOnlyHint: true, openWorldHint: false }
34301
- }, async ({ id }) => {
34302
- try {
34303
- return result(getTemplate(id));
34304
- } catch (error51) {
34305
- return failure(error51);
34306
- }
34307
- });
34308
34738
  server.registerTool("template_get_many", {
34309
34739
  title: "Get multiple Cadre templates",
34310
34740
  description: "Read an ordered set of immutable, versioned Cadre templates in one call.",
@@ -34312,7 +34742,7 @@ function createCadreServer() {
34312
34742
  annotations: { readOnlyHint: true, openWorldHint: false }
34313
34743
  }, async ({ ids }) => {
34314
34744
  try {
34315
- return result({ templateSetVersion: TEMPLATE_SET_VERSION, templates: getTemplates(ids) });
34745
+ return templateResult(getTemplates(ids).map(describeTemplate));
34316
34746
  } catch (error51) {
34317
34747
  return failure(error51);
34318
34748
  }
@@ -34326,21 +34756,75 @@ function createCadreServer() {
34326
34756
  try {
34327
34757
  return result({
34328
34758
  templateSetVersion: TEMPLATE_SET_VERSION,
34329
- templates: resolveStyleguides(technologies)
34330
- });
34759
+ templates: resolveStyleguides(technologies).map((template) => {
34760
+ const { content: _content, ...descriptor } = describeTemplate(template);
34761
+ return descriptor;
34762
+ })
34763
+ }, "Resolved the default Cadre styleguide set.");
34331
34764
  } catch (error51) {
34332
34765
  return failure(error51);
34333
34766
  }
34334
34767
  });
34335
34768
  server.registerTool("project_status", {
34336
34769
  title: "Read Cadre project status",
34337
- description: "Read and summarize current project and track checkpoints, including resumable operations.",
34338
- inputSchema: { projectRoot: external_exports.string().min(1) },
34770
+ description: "Read compact project, focused track, or implementation status with embedded validation.",
34771
+ inputSchema: {
34772
+ projectRoot: external_exports.string().min(1),
34773
+ view: external_exports.enum(["project", "track", "implementation"]).optional().default("project"),
34774
+ trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).optional(),
34775
+ executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/).optional()
34776
+ },
34339
34777
  annotations: { readOnlyHint: true, openWorldHint: false }
34340
- }, async ({ projectRoot }) => {
34778
+ }, async ({ projectRoot, view, trackId, executionId }) => {
34341
34779
  try {
34342
- const status = formatStatus(safeProjectRoot(projectRoot));
34343
- return result({ text: status.text, ...serializableValidation(status.result) }, status.text);
34780
+ const root = safeProjectRoot(projectRoot);
34781
+ const validation = validateProject(root);
34782
+ if (view === "project") {
34783
+ let worktreeRuntime = null;
34784
+ try {
34785
+ worktreeRuntime = managedWorktreeStatus(root);
34786
+ } catch {
34787
+ worktreeRuntime = null;
34788
+ }
34789
+ return result(
34790
+ { ...projectStatusView(validation), worktreeRuntime },
34791
+ `Cadre project ${validation.errors.length ? "has validation errors" : "is valid"}; ${validation.tracks.length} track${validation.tracks.length === 1 ? "" : "s"}.`
34792
+ );
34793
+ }
34794
+ if (!trackId) throw new Error(`${view} project_status requires trackId`);
34795
+ const track = validation.tracks.find((candidate) => candidate.id === trackId);
34796
+ if (!track) throw new Error(`unknown Cadre track ${trackId}`);
34797
+ const dependencies = (track.dependencies ?? []).map((id) => validation.tracks.find((candidate) => candidate.id === id)).filter((candidate) => Boolean(candidate)).map(trackSummary);
34798
+ const focused = {
34799
+ valid: validation.errors.length === 0,
34800
+ derivedStateCurrent: validation.warnings.length === 0,
34801
+ upgradeRequired: validation.project?.runtimeVersion !== CADRE_RUNTIME_VERSION || validation.project?.templateSetVersion !== TEMPLATE_SET_VERSION,
34802
+ targetRuntimeVersion: CADRE_RUNTIME_VERSION,
34803
+ targetTemplateSetVersion: TEMPLATE_SET_VERSION,
34804
+ track: trackSummary(track),
34805
+ state: validation.states.get(trackId) ?? null,
34806
+ dependencies,
34807
+ errors: validation.errors.filter((error51) => error51.startsWith(`${trackId}:`) || error51.startsWith("project.json:")),
34808
+ warnings: validation.warnings
34809
+ };
34810
+ if (view === "track") {
34811
+ return result(focused, `${trackId}: ${track.status}; checkpoint=${track.checkpoint ?? "none"}.`);
34812
+ }
34813
+ const planPath = join10(root, ".cadre", track.location, "plan.md");
34814
+ const graphErrors = [];
34815
+ const graph = parsePlan(planPath, graphErrors);
34816
+ validatePlanGraph(planPath, graph, track.status, graphErrors);
34817
+ const activeExecutionId = executionId ?? (typeof track.operation?.executionId === "string" ? track.operation.executionId : void 0) ?? track.lastExecution?.executionId;
34818
+ const execution = activeExecutionId ? compactExecutionStatus(executionStatus(root, trackId, activeExecutionId).journal) : null;
34819
+ const worktreeStatus = managedWorktreeStatus(root);
34820
+ const trackWorktreeSegment = `${join10(".cadre", ".worktrees", trackId)}/`;
34821
+ return result({
34822
+ ...focused,
34823
+ graph: { valid: graphErrors.length === 0, graph, errors: graphErrors },
34824
+ execution,
34825
+ worktrees: worktreeStatus.worktrees.filter((entry) => entry.path.includes(trackWorktreeSegment)),
34826
+ orphanedDirectories: worktreeStatus.orphanedDirectories.filter((path) => path.includes(trackWorktreeSegment))
34827
+ }, `${trackId}: implementation status is ${track.status}.`);
34344
34828
  } catch (error51) {
34345
34829
  return failure(error51);
34346
34830
  }
@@ -34357,6 +34841,65 @@ function createCadreServer() {
34357
34841
  return failure(error51);
34358
34842
  }
34359
34843
  });
34844
+ server.registerTool("candidate_stage_prepare", {
34845
+ title: "Prepare a Cadre candidate stage",
34846
+ description: "Create or resume one project-local candidate directory and ensure /stage/ is ignored by Git.",
34847
+ inputSchema: {
34848
+ projectRoot: external_exports.string().min(1),
34849
+ candidateId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
34850
+ },
34851
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34852
+ }, async ({ projectRoot, candidateId }) => {
34853
+ try {
34854
+ return result(prepareCandidateStage(projectRoot, candidateId), `Prepared Cadre candidate stage ${candidateId}.`);
34855
+ } catch (error51) {
34856
+ return failure(error51);
34857
+ }
34858
+ });
34859
+ server.registerTool("candidate_inspect", {
34860
+ title: "Inspect staged artifact candidates",
34861
+ description: "Manifest an exact staged file set and optionally validate its plan graph in one read-only call.",
34862
+ inputSchema: {
34863
+ projectRoot: external_exports.string().min(1),
34864
+ candidateId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34865
+ files: external_exports.array(external_exports.string().min(1)).min(1),
34866
+ targetStatus: external_exports.enum(PLAN_VALIDATION_STATUSES).optional()
34867
+ },
34868
+ annotations: { readOnlyHint: true, openWorldHint: false }
34869
+ }, async ({ projectRoot, candidateId, files, targetStatus }) => {
34870
+ try {
34871
+ const root = safeProjectRoot(projectRoot);
34872
+ const candidates = readCandidateFiles(root, candidateId, files);
34873
+ const manifest = candidates.map((file2) => ({ path: file2.path, sha256: sha256(file2.content) })).sort((left, right) => left.path.localeCompare(right.path));
34874
+ const actualPaths = listCandidatePaths(root, candidateId);
34875
+ const expectedPaths = manifest.map((file2) => file2.path);
34876
+ if (JSON.stringify(actualPaths) !== JSON.stringify(expectedPaths)) {
34877
+ throw new Error(
34878
+ `Candidate stage must contain exactly the declared files; expected ${expectedPaths.join(", ")}, found ${actualPaths.join(", ")}`
34879
+ );
34880
+ }
34881
+ let plan;
34882
+ if (targetStatus) {
34883
+ const candidate = candidates.find((file2) => file2.path === "plan.md");
34884
+ if (!candidate) throw new Error("candidate inspection with targetStatus requires plan.md in files");
34885
+ if (Buffer.byteLength(candidate.content, "utf8") > MAX_DRAFT_PLAN_CHARACTERS) {
34886
+ throw new Error(`Candidate plan exceeds ${MAX_DRAFT_PLAN_CHARACTERS} bytes`);
34887
+ }
34888
+ const errors = [];
34889
+ const graph = parsePlanContent(candidate.content, candidate.path, errors);
34890
+ validatePlanGraph(candidate.path, graph, targetStatus, errors);
34891
+ plan = { valid: errors.length === 0, path: candidate.path, graph, errors };
34892
+ }
34893
+ return result({
34894
+ candidateId,
34895
+ files: manifest,
34896
+ digest: sha256(JSON.stringify({ projectRoot: root, candidateId, files: manifest })),
34897
+ ...plan ? { plan } : {}
34898
+ }, `Inspected ${manifest.length} staged Cadre artifact${manifest.length === 1 ? "" : "s"}.`);
34899
+ } catch (error51) {
34900
+ return failure(error51);
34901
+ }
34902
+ });
34360
34903
  server.registerTool("execution_graph_validate", {
34361
34904
  title: "Validate a track execution graph",
34362
34905
  description: "Compile and validate phase/task dependencies and derived manual-verification barriers from an approved plan.",
@@ -34365,9 +34908,9 @@ function createCadreServer() {
34365
34908
  }, async ({ projectRoot, trackId }) => {
34366
34909
  try {
34367
34910
  const root = safeProjectRoot(projectRoot);
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"));
34911
+ const statePath = join10(root, ".cadre", "tracks", trackId, "state.json");
34912
+ const planPath = join10(root, ".cadre", "tracks", trackId, "plan.md");
34913
+ const state = JSON.parse(readFileSync10(statePath, "utf8"));
34371
34914
  const errors = [];
34372
34915
  const graph = parsePlan(planPath, errors);
34373
34916
  validatePlanGraph(planPath, graph, state.status ?? "planned", errors);
@@ -34376,26 +34919,6 @@ function createCadreServer() {
34376
34919
  return failure(error51);
34377
34920
  }
34378
34921
  });
34379
- server.registerTool("execution_graph_validate_draft", {
34380
- title: "Validate a draft execution graph",
34381
- description: "Compile and validate an unapproved plan supplied as Markdown without reading or writing project files.",
34382
- inputSchema: {
34383
- planMarkdown: external_exports.string().min(1).max(MAX_DRAFT_PLAN_CHARACTERS),
34384
- targetStatus: external_exports.enum(PLAN_VALIDATION_STATUSES),
34385
- sourceLabel: external_exports.string().min(1).max(200).regex(/^[^\r\n]+$/).optional()
34386
- },
34387
- annotations: { readOnlyHint: true, openWorldHint: false }
34388
- }, async ({ planMarkdown, targetStatus, sourceLabel }) => {
34389
- try {
34390
- const label = sourceLabel ?? "<draft-plan>";
34391
- const errors = [];
34392
- const graph = parsePlanContent(planMarkdown, label, errors);
34393
- validatePlanGraph(label, graph, targetStatus, errors);
34394
- return result({ valid: errors.length === 0, graph, errors });
34395
- } catch (error51) {
34396
- return failure(error51);
34397
- }
34398
- });
34399
34922
  const reviewCompleteSchema = {
34400
34923
  projectRoot: external_exports.string().min(1),
34401
34924
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
@@ -34403,14 +34926,36 @@ function createCadreServer() {
34403
34926
  approval: external_exports.string().min(1),
34404
34927
  acceptedRisks: external_exports.array(external_exports.string().min(1)).optional()
34405
34928
  };
34406
- server.registerTool("review_complete_preview", {
34407
- title: "Preview clean review completion",
34408
- description: "Preview the exact clean-review cycle, completed track state, and derived index behind one digest.",
34409
- inputSchema: reviewCompleteSchema,
34410
- annotations: { readOnlyHint: true, openWorldHint: false }
34929
+ server.registerTool("review_complete", {
34930
+ title: "Complete a clean review",
34931
+ description: "Prepare the exact clean-review completion for human approval, or apply its unchanged proposal token after approval.",
34932
+ inputSchema: adaptiveInputSchema(reviewCompleteSchema),
34933
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34411
34934
  }, async (input) => {
34412
34935
  try {
34413
- const derived = deriveReviewCompleteInput(input);
34936
+ const adaptive = normalizeAdaptiveInput(
34937
+ input,
34938
+ ["projectRoot", "trackId", "commitRangeStart", "approval"],
34939
+ "review_complete"
34940
+ );
34941
+ if (adaptive.mode === "apply") {
34942
+ const proposal = proposalTokens.resolve("review_complete", adaptive.proposalToken);
34943
+ requireCurrentProject2(proposal.input.projectRoot);
34944
+ const applied = applyReviewComplete(proposal.input, proposal.digest);
34945
+ return result({
34946
+ commandStatus: "applied",
34947
+ trackId: proposal.input.trackId,
34948
+ status: applied.state.status,
34949
+ checkpoint: applied.state.checkpoint,
34950
+ digest: proposal.digest,
34951
+ changedPaths: [applied.statePath, applied.tracksPath],
34952
+ changedCount: 2,
34953
+ valid: applied.valid,
34954
+ derivedStateCurrent: applied.derivedStateCurrent
34955
+ });
34956
+ }
34957
+ requireCurrentProject2(String(adaptive.request.projectRoot));
34958
+ const derived = deriveReviewCompleteInput(adaptive.request);
34414
34959
  const preview = previewReviewComplete(derived);
34415
34960
  return proposalResult("review_complete", derived, {
34416
34961
  digest: preview.digest,
@@ -34427,52 +34972,57 @@ function createCadreServer() {
34427
34972
  return failure(error51);
34428
34973
  }
34429
34974
  });
34430
- server.registerTool("review_complete_apply", {
34431
- title: "Apply clean review completion",
34432
- description: "Apply an approved clean-review transition only while its exact state and index preview remain current.",
34433
- inputSchema: proposalInputSchema(),
34434
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34435
- }, async ({ proposalToken }) => {
34436
- try {
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
- });
34449
- } catch (error51) {
34450
- return failure(error51);
34451
- }
34452
- });
34453
- const archiveBatchSchema = {
34975
+ const archiveCandidateUpdateSchema = external_exports.discriminatedUnion("kind", [
34976
+ external_exports.object({ kind: external_exports.literal("pattern"), slug: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/) }),
34977
+ external_exports.object({ kind: external_exports.literal("pattern_index") }),
34978
+ external_exports.object({
34979
+ kind: external_exports.literal("active_track_seed"),
34980
+ trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
34981
+ })
34982
+ ]);
34983
+ const archiveBatchCandidateSchema = {
34454
34984
  projectRoot: external_exports.string().min(1),
34985
+ candidateId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34455
34986
  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
- ]))
34987
+ updates: external_exports.array(archiveCandidateUpdateSchema)
34465
34988
  };
34466
- server.registerTool("archive_batch_preview", {
34467
- title: "Preview complete archive batch",
34468
- description: "Preview selected moves, lifecycle states, pattern/seed writes, operation journal, and the post-archive track index together.",
34469
- inputSchema: archiveBatchSchema,
34470
- annotations: { readOnlyHint: true, openWorldHint: false }
34989
+ server.registerTool("archive_batch_candidate", {
34990
+ title: "Govern a staged archive batch",
34991
+ description: "Prepare a staged archive batch for human approval, or apply its unchanged proposal token after approval.",
34992
+ inputSchema: adaptiveInputSchema(archiveBatchCandidateSchema),
34993
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34471
34994
  }, async (input) => {
34472
34995
  try {
34473
- const derived = deriveArchiveBatchInput(input);
34474
- const preview = previewArchiveBatch(derived);
34475
- return proposalResult("archive_batch", derived, {
34996
+ const adaptive = normalizeAdaptiveInput(
34997
+ input,
34998
+ ["projectRoot", "candidateId", "updates"],
34999
+ "archive_batch_candidate"
35000
+ );
35001
+ if (adaptive.mode === "apply") {
35002
+ const proposal = proposalTokens.resolve(
35003
+ "archive_batch_candidate",
35004
+ adaptive.proposalToken
35005
+ );
35006
+ requireCurrentProject2(proposal.input.projectRoot);
35007
+ const applied = applyArchiveBatchCandidate(proposal.input, proposal.digest);
35008
+ return result({
35009
+ commandStatus: "applied",
35010
+ batchId: proposal.input.batchId,
35011
+ selectedTracks: proposal.input.selectedTracks,
35012
+ operationPath: applied.operationPath,
35013
+ checkpoint: applied.operation.checkpoint,
35014
+ digest: proposal.digest,
35015
+ moves: applied.moves.map(({ trackId, targetPath }) => ({ trackId, targetPath })),
35016
+ changedPaths: [...applied.writes.map((write) => write.path), applied.tracksPath],
35017
+ changedCount: applied.writes.length + 1,
35018
+ valid: applied.valid,
35019
+ derivedStateCurrent: applied.derivedStateCurrent
35020
+ });
35021
+ }
35022
+ requireCurrentProject2(String(adaptive.request.projectRoot));
35023
+ const derived = deriveArchiveBatchCandidateInput(adaptive.request);
35024
+ const preview = previewArchiveBatchCandidate(derived);
35025
+ return proposalResult("archive_batch_candidate", derived, {
34476
35026
  digest: preview.digest,
34477
35027
  batchId: derived.batchId,
34478
35028
  selectedTracks: derived.selectedTracks,
@@ -34492,76 +35042,29 @@ function createCadreServer() {
34492
35042
  return failure(error51);
34493
35043
  }
34494
35044
  });
34495
- server.registerTool("archive_batch_apply", {
34496
- title: "Apply complete archive batch",
34497
- description: "Journal and apply one approved archive batch only while its complete preview remains current.",
34498
- inputSchema: proposalInputSchema(),
34499
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34500
- }, async ({ proposalToken }) => {
34501
- try {
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
- });
34515
- } catch (error51) {
34516
- return failure(error51);
34517
- }
34518
- });
34519
35045
  const archiveRecordSchema = {
34520
35046
  projectRoot: external_exports.string().min(1),
34521
35047
  batchId: external_exports.string().regex(/^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
34522
35048
  };
34523
- server.registerTool("archive_batch_record_preview", {
34524
- title: "Preview archive provenance record",
34525
- description: "Preview the authorized follow-up that records the archive commit in track, project, and batch state.",
35049
+ server.registerTool("archive_batch_record", {
35050
+ title: "Record archive provenance",
35051
+ description: "Atomically validate and record the already-authorized archive commit in track, project, and batch state.",
34526
35052
  inputSchema: archiveRecordSchema,
34527
- annotations: { readOnlyHint: true, openWorldHint: false }
35053
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34528
35054
  }, async (input) => {
34529
35055
  try {
35056
+ requireCurrentProject2(input.projectRoot);
34530
35057
  const derived = deriveArchiveBatchRecordInput(input);
34531
35058
  const preview = previewArchiveBatchRecord(derived);
34532
- return proposalResult("archive_batch_record", derived, {
34533
- digest: preview.digest,
35059
+ const applied = applyArchiveBatchRecord(derived, preview.digest, preview);
35060
+ return result({
35061
+ commandStatus: "applied",
34534
35062
  batchId: derived.batchId,
34535
35063
  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
- });
34543
- } catch (error51) {
34544
- return failure(error51);
34545
- }
34546
- });
34547
- server.registerTool("archive_batch_record_apply", {
34548
- title: "Record archive provenance",
34549
- description: "Record an approved batch's immutable archive commit and complete its journal behind a stale-state digest.",
34550
- inputSchema: proposalInputSchema(),
34551
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34552
- }, async ({ proposalToken }) => {
34553
- try {
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
35064
  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
- ],
35065
+ digest: preview.digest,
35066
+ changedPaths: [applied.operationPath, applied.projectPath, ...applied.states.map((state) => state.path)],
35067
+ changedCount: applied.states.length + 2,
34565
35068
  valid: applied.valid,
34566
35069
  derivedStateCurrent: applied.derivedStateCurrent
34567
35070
  });
@@ -34576,51 +35079,29 @@ function createCadreServer() {
34576
35079
  approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES).optional(),
34577
35080
  maxWorkers: external_exports.number().int().min(1).max(32).optional().default(3)
34578
35081
  };
34579
- server.registerTool("execution_start_preview", {
34580
- title: "Preview implementation execution",
34581
- description: "Preview the exact resumable implementation journal and track operation for an approved plan DAG.",
35082
+ server.registerTool("execution_start", {
35083
+ title: "Start implementation execution",
35084
+ description: "Atomically validate and start the implementation execution already authorized by the implement invocation.",
34582
35085
  inputSchema: executionStartSchema,
34583
- annotations: { readOnlyHint: true, openWorldHint: false }
35086
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34584
35087
  }, async (input) => {
34585
35088
  try {
35089
+ requireCurrentProject2(input.projectRoot);
34586
35090
  const derived = deriveExecutionStartInput(input);
34587
35091
  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
- });
34604
- } catch (error51) {
34605
- return failure(error51);
34606
- }
34607
- });
34608
- server.registerTool("execution_start_apply", {
34609
- title: "Start implementation execution",
34610
- description: "Write the approved implementation journal and operation only when its preview digest is unchanged.",
34611
- inputSchema: proposalInputSchema(),
34612
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34613
- }, async ({ proposalToken }) => {
34614
- try {
34615
- const proposal = proposalTokens.resolve("execution_start", proposalToken);
34616
- const applied = applyExecutionStart(proposal.input, proposal.digest);
35092
+ const applied = applyExecutionStart(derived, preview.digest, preview);
34617
35093
  return result({
35094
+ commandStatus: "applied",
34618
35095
  journalPath: applied.journalPath,
34619
35096
  statePath: applied.statePath,
34620
35097
  execution: {
34621
35098
  executionId: applied.journal.executionId,
34622
35099
  trackId: applied.journal.trackId,
34623
35100
  checkpoint: applied.journal.checkpoint,
35101
+ requestedMode: applied.journal.requestedMode,
35102
+ effectiveMode: applied.journal.effectiveMode,
35103
+ approvalMode: applied.journal.approvalMode,
35104
+ maxWorkers: applied.journal.maxWorkers,
34624
35105
  nodeCount: Object.keys(applied.journal.nodes).length
34625
35106
  },
34626
35107
  derivedStatus: executionSchedulerView(applied.journal)
@@ -34646,42 +35127,22 @@ function createCadreServer() {
34646
35127
  authorization: external_exports.string().min(1).optional(),
34647
35128
  blocker: external_exports.string().min(1).optional()
34648
35129
  };
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.",
35130
+ server.registerTool("execution_checkpoint", {
35131
+ title: "Apply an execution checkpoint",
35132
+ description: "Atomically validate and apply one already-authorized semantic execution event.",
34652
35133
  inputSchema: executionCheckpointSchema,
34653
- annotations: { readOnlyHint: true, openWorldHint: false }
35134
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34654
35135
  }, async (input) => {
34655
35136
  try {
35137
+ requireCurrentProject2(input.projectRoot);
34656
35138
  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
- );
34667
- } catch (error51) {
34668
- return failure(error51);
34669
- }
34670
- });
34671
- server.registerTool("execution_checkpoint_apply", {
34672
- title: "Apply an execution checkpoint",
34673
- description: "Apply one previewed semantic execution event atomically.",
34674
- inputSchema: proposalInputSchema(),
34675
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34676
- }, async ({ proposalToken }) => {
34677
- try {
34678
- const proposal = proposalTokens.resolve("execution_checkpoint", proposalToken);
34679
- const applied = applyExecutionCheckpoint(proposal.input, proposal.digest);
35139
+ const applied = applyExecutionCheckpoint(input, preview.digest, preview);
34680
35140
  return result({
35141
+ commandStatus: "applied",
34681
35142
  path: applied.path,
34682
35143
  transition: applied.transition,
34683
35144
  checkpoint: applied.journal.checkpoint,
34684
- derivedStatus: executionSchedulerView(applied.journal, [proposal.input.nodeId])
35145
+ derivedStatus: executionSchedulerView(applied.journal, [input.nodeId])
34685
35146
  });
34686
35147
  } catch (error51) {
34687
35148
  return failure(error51);
@@ -34710,52 +35171,26 @@ function createCadreServer() {
34710
35171
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34711
35172
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
34712
35173
  };
34713
- server.registerTool("execution_finish_preview", {
34714
- title: "Preview completed implementation execution",
34715
- description: "Verify all DAG nodes, plan evidence, and worktree cleanup before proposing ready-for-review state and its derived tracks index under one digest.",
35174
+ server.registerTool("execution_finish", {
35175
+ title: "Complete implementation execution",
35176
+ description: "Atomically verify and finalize an execution after its required manual verification is already recorded.",
34716
35177
  inputSchema: executionFinishSchema,
34717
- annotations: { readOnlyHint: true, openWorldHint: false }
35178
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34718
35179
  }, async (input) => {
34719
35180
  try {
35181
+ requireCurrentProject2(input.projectRoot);
34720
35182
  const derived = deriveExecutionFinishInput(input);
34721
35183
  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
- });
34735
- } catch (error51) {
34736
- return failure(error51);
34737
- }
34738
- });
34739
- server.registerTool("execution_finish_apply", {
34740
- title: "Complete implementation execution",
34741
- description: "Finalize an approved execution, ready-for-review state, and derived tracks index together only when the preview is unchanged.",
34742
- inputSchema: proposalInputSchema(),
34743
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34744
- }, async ({ proposalToken }) => {
34745
- try {
34746
- const proposal = proposalTokens.resolve("execution_finish", proposalToken);
34747
- const applied = applyExecutionFinish(proposal.input, proposal.digest);
35184
+ const applied = applyExecutionFinish(derived, preview.digest, preview);
34748
35185
  return result({
34749
- executionId: proposal.input.executionId,
35186
+ commandStatus: "applied",
35187
+ executionId: derived.executionId,
34750
35188
  status: applied.journal.status,
34751
35189
  checkpoint: applied.journal.checkpoint,
34752
35190
  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
- ]
35191
+ digest: preview.digest,
35192
+ changedPaths: [applied.journalPath, applied.statePath, applied.planPath, applied.tracksPath],
35193
+ changedCount: 4
34759
35194
  });
34760
35195
  } catch (error51) {
34761
35196
  return failure(error51);
@@ -34767,112 +35202,141 @@ function createCadreServer() {
34767
35202
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
34768
35203
  nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/)
34769
35204
  };
34770
- server.registerTool("worktree_create_preview", {
34771
- title: "Preview a Cadre worker worktree",
34772
- description: "Resolve the constrained worker path, branch, and exact base commit without mutating Git.",
34773
- inputSchema: worktreeSchema,
34774
- annotations: { readOnlyHint: true, openWorldHint: false }
34775
- }, async (input) => {
34776
- try {
34777
- return proposalResult("worktree_create", input, previewWorktreeCreate(input));
34778
- } catch (error51) {
34779
- return failure(error51);
34780
- }
34781
- });
34782
- server.registerTool("worktree_create_apply", {
35205
+ server.registerTool("worktree_create", {
34783
35206
  title: "Create a Cadre worker worktree",
34784
- description: "Create or reconcile one approved constrained worker worktree using an unchanged preview digest.",
34785
- inputSchema: proposalInputSchema(),
34786
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34787
- }, async ({ proposalToken }) => {
34788
- try {
34789
- const proposal = proposalTokens.resolve("worktree_create", proposalToken);
34790
- return result(applyWorktreeCreate(proposal.input, proposal.digest));
34791
- } catch (error51) {
34792
- return failure(error51);
34793
- }
34794
- });
34795
- server.registerTool("integration_preview", {
34796
- title: "Preview worker integration",
34797
- description: "Verify clean source/target worktrees, protected Cadre state, branch tips, and changed files before merge.",
35207
+ description: "Atomically validate and create or reconcile one already-authorized constrained worker worktree.",
34798
35208
  inputSchema: worktreeSchema,
34799
- annotations: { readOnlyHint: true, openWorldHint: false }
35209
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34800
35210
  }, async (input) => {
34801
35211
  try {
34802
- return proposalResult("worktree_integrate", input, previewWorktreeIntegration(input));
35212
+ requireCurrentProject2(input.projectRoot);
35213
+ const preview = previewWorktreeCreate(input);
35214
+ const applied = applyWorktreeCreate(input, preview.digest, preview);
35215
+ const journal = executionStatus(input.projectRoot, input.trackId, input.executionId).journal;
35216
+ const node = journal.nodes[input.nodeId];
35217
+ if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
35218
+ const checkpoint = node.status === "running" && node.worktreePath === applied.path && node.branch === applied.branch ? { transition: null, derivedStatus: executionSchedulerView(journal, [input.nodeId]) } : applyCheckpointNow({
35219
+ projectRoot: input.projectRoot,
35220
+ trackId: input.trackId,
35221
+ executionId: input.executionId,
35222
+ nodeId: input.nodeId,
35223
+ event: "start",
35224
+ worktreePath: applied.path,
35225
+ branch: applied.branch
35226
+ });
35227
+ return result({ commandStatus: "applied", ...applied, ...checkpoint }, `Created worker worktree for ${input.nodeId}.`);
34803
35228
  } catch (error51) {
34804
35229
  return failure(error51);
34805
35230
  }
34806
35231
  });
34807
- server.registerTool("integration_apply", {
35232
+ server.registerTool("integration", {
34808
35233
  title: "Integrate a worker branch",
34809
- description: "Merge an approved worker branch without squashing; report conflicts without resolving them.",
34810
- inputSchema: proposalInputSchema(),
35234
+ description: "Atomically merge in phase/autonomous mode; in governed mode return approval_required first, then accept the unchanged proposal token after human approval.",
35235
+ inputSchema: adaptiveInputSchema(worktreeSchema),
34811
35236
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34812
- }, async ({ proposalToken }) => {
34813
- try {
34814
- const proposal = proposalTokens.resolve("worktree_integrate", proposalToken);
34815
- return result(applyWorktreeIntegration(proposal.input, proposal.digest));
34816
- } catch (error51) {
34817
- return failure(error51);
34818
- }
34819
- });
34820
- server.registerTool("worktree_cleanup_preview", {
34821
- title: "Preview worker cleanup",
34822
- description: "Verify a clean worker branch is fully integrated before proposing worktree and branch removal, including recovery after its node was already completed.",
34823
- inputSchema: worktreeSchema,
34824
- annotations: { readOnlyHint: true, openWorldHint: false }
34825
35237
  }, async (input) => {
34826
35238
  try {
34827
- return proposalResult("worktree_cleanup", input, previewWorktreeCleanup(input));
35239
+ const adaptive = normalizeAdaptiveInput(
35240
+ input,
35241
+ ["projectRoot", "trackId", "executionId", "nodeId"],
35242
+ "integration"
35243
+ );
35244
+ if (adaptive.mode === "apply") {
35245
+ const proposal = proposalTokens.resolve("worktree_integrate", adaptive.proposalToken);
35246
+ requireCurrentProject2(proposal.input.projectRoot);
35247
+ const applied2 = applyWorktreeIntegration(proposal.input, proposal.digest);
35248
+ const checkpoint2 = applied2.status === "integrated" && applied2.mergeCommit ? recordIntegrationNow(proposal.input, applied2.mergeCommit) : {};
35249
+ return result({ commandStatus: "applied", ...applied2, ...checkpoint2 }, `Integrated ${proposal.input.nodeId}.`);
35250
+ }
35251
+ const integrationInput = adaptive.request;
35252
+ requireCurrentProject2(integrationInput.projectRoot);
35253
+ const preview = previewWorktreeIntegration(integrationInput);
35254
+ if (integrationRequiresApproval(integrationInput)) {
35255
+ return proposalResult("worktree_integrate", integrationInput, preview);
35256
+ }
35257
+ const applied = applyWorktreeIntegration(integrationInput, preview.digest, preview);
35258
+ const checkpoint = applied.status === "integrated" && applied.mergeCommit ? recordIntegrationNow(integrationInput, applied.mergeCommit) : {};
35259
+ return result({
35260
+ commandStatus: "applied",
35261
+ ...applied,
35262
+ ...checkpoint
35263
+ }, `Integrated ${integrationInput.nodeId}.`);
34828
35264
  } catch (error51) {
34829
35265
  return failure(error51);
34830
35266
  }
34831
35267
  });
34832
- server.registerTool("worktree_cleanup_apply", {
35268
+ server.registerTool("worktree_cleanup", {
34833
35269
  title: "Clean up an integrated worker",
34834
- description: "Remove only a clean, fully integrated Cadre worktree and its safely deletable branch, whether its journal node is integrated or already completed.",
34835
- inputSchema: proposalInputSchema(),
35270
+ description: "Atomically verify and remove only a clean, fully integrated Cadre worktree and safely deletable branch.",
35271
+ inputSchema: worktreeSchema,
34836
35272
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
34837
- }, async ({ proposalToken }) => {
34838
- try {
34839
- const proposal = proposalTokens.resolve("worktree_cleanup", proposalToken);
34840
- return result(applyWorktreeCleanup(proposal.input, proposal.digest));
34841
- } catch (error51) {
34842
- return failure(error51);
34843
- }
34844
- });
34845
- server.registerTool("worktree_status", {
34846
- title: "Read Cadre worktree status",
34847
- description: "List registered Cadre-managed worktrees and orphaned empty runtime directories.",
34848
- inputSchema: { projectRoot: external_exports.string().min(1) },
34849
- annotations: { readOnlyHint: true, openWorldHint: false }
34850
- }, async ({ projectRoot }) => {
35273
+ }, async (input) => {
34851
35274
  try {
34852
- return result(managedWorktreeStatus(projectRoot));
35275
+ const cleanupInput = input;
35276
+ requireCurrentProject2(cleanupInput.projectRoot);
35277
+ const preview = previewWorktreeCleanup(cleanupInput);
35278
+ const applied = applyWorktreeCleanup(cleanupInput, preview.digest, preview);
35279
+ const journal = executionStatus(input.projectRoot, input.trackId, input.executionId).journal;
35280
+ const node = journal.nodes[input.nodeId];
35281
+ const checkpoint = node?.status === "completed" ? { transition: null, derivedStatus: executionSchedulerView(journal, [input.nodeId]) } : applyCheckpointNow({ ...cleanupInput, event: "complete" });
35282
+ return result({
35283
+ commandStatus: "applied",
35284
+ ...applied,
35285
+ ...checkpoint
35286
+ }, `Cleaned worker worktree for ${input.nodeId}.`);
34853
35287
  } catch (error51) {
34854
35288
  return failure(error51);
34855
35289
  }
34856
35290
  });
34857
- const approvedFileSchema = external_exports.object({ path: external_exports.string().min(1), content: external_exports.string() });
34858
- const initSchema = {
35291
+ const initCandidateSchema = {
34859
35292
  projectRoot: external_exports.string().min(1),
34860
35293
  projectName: external_exports.string().min(1),
34861
35294
  context: external_exports.enum(["greenfield", "brownfield"]),
34862
35295
  gitDisposition: external_exports.enum(["existing", "initialize"]),
34863
35296
  baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).nullable(),
34864
35297
  approvedAt: external_exports.iso.datetime(),
34865
- files: external_exports.array(approvedFileSchema).min(5)
35298
+ stagedFiles: external_exports.array(external_exports.string().min(1)).min(3),
35299
+ styleguideIds: external_exports.array(external_exports.string().min(1)).min(1)
34866
35300
  };
34867
- server.registerTool("project_init_preview", {
34868
- title: "Preview Cadre project initialization",
34869
- description: "Validate approved rendered artifacts and return the proposed .cadre file set and semantic digest without writing; approvedAt is audit metadata and does not affect the digest.",
34870
- inputSchema: initSchema,
34871
- annotations: { readOnlyHint: true, openWorldHint: false }
35301
+ server.registerTool("project_init_candidate", {
35302
+ title: "Initialize from a staged Cadre candidate",
35303
+ description: "Prepare staged initialization for human approval, or atomically promote its unchanged proposal token after approval.",
35304
+ inputSchema: adaptiveInputSchema(initCandidateSchema),
35305
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34872
35306
  }, async (input) => {
34873
35307
  try {
34874
- const preview = previewProjectInit(input);
34875
- return proposalResult("project_init", input, {
35308
+ const adaptive = normalizeAdaptiveInput(
35309
+ input,
35310
+ [
35311
+ "projectRoot",
35312
+ "projectName",
35313
+ "context",
35314
+ "gitDisposition",
35315
+ "baseCommit",
35316
+ "approvedAt",
35317
+ "stagedFiles",
35318
+ "styleguideIds"
35319
+ ],
35320
+ "project_init_candidate"
35321
+ );
35322
+ if (adaptive.mode === "apply") {
35323
+ const proposal = proposalTokens.resolve(
35324
+ "project_init_candidate",
35325
+ adaptive.proposalToken
35326
+ );
35327
+ const applied = applyProjectInitCandidate(proposal.input, proposal.digest);
35328
+ return result({
35329
+ commandStatus: "applied",
35330
+ runtimeVersion: applied.runtimeVersion,
35331
+ templateSetVersion: applied.templateSetVersion,
35332
+ changedPaths: applied.files.map(({ path }) => path),
35333
+ changedCount: applied.files.length,
35334
+ digest: applied.digest
35335
+ });
35336
+ }
35337
+ const request = adaptive.request;
35338
+ const preview = previewProjectInitCandidate(request);
35339
+ return proposalResult("project_init_candidate", request, {
34876
35340
  runtimeVersion: preview.runtimeVersion,
34877
35341
  templateSetVersion: preview.templateSetVersion,
34878
35342
  files: preview.files.map(({ path, sha256: digest }) => ({ path, sha256: digest })),
@@ -34882,25 +35346,6 @@ function createCadreServer() {
34882
35346
  return failure(error51);
34883
35347
  }
34884
35348
  });
34885
- server.registerTool("project_init_apply", {
34886
- title: "Apply approved Cadre project initialization",
34887
- description: "Atomically create .cadre only when the semantic proposal matches an approved preview digest; records approvedAt as audit metadata.",
34888
- inputSchema: proposalInputSchema(),
34889
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34890
- }, async ({ proposalToken }) => {
34891
- try {
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
- });
34900
- } catch (error51) {
34901
- return failure(error51);
34902
- }
34903
- });
34904
35349
  server.registerTool("setup_record_commit", {
34905
35350
  title: "Record the project setup commit",
34906
35351
  description: "Complete a pending create operation by recording its already-created Git commit SHA.",
@@ -34908,6 +35353,7 @@ function createCadreServer() {
34908
35353
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34909
35354
  }, async ({ projectRoot }) => {
34910
35355
  try {
35356
+ requireCurrentProject2(projectRoot);
34911
35357
  const commit = resolveGitCommit(projectRoot);
34912
35358
  return result({ path: recordSetupCommit(projectRoot, commit), commit });
34913
35359
  } catch (error51) {
@@ -34921,49 +35367,40 @@ function createCadreServer() {
34921
35367
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34922
35368
  }, async ({ projectRoot }) => {
34923
35369
  try {
35370
+ requireCurrentProject2(projectRoot);
34924
35371
  return result({ path: recordGitInitialized(projectRoot), checkpoint: "commit-pending" });
34925
35372
  } catch (error51) {
34926
35373
  return failure(error51);
34927
35374
  }
34928
35375
  });
34929
- server.registerTool("tracks_render_preview", {
34930
- title: "Preview the derived tracks index",
34931
- description: "Read all track-local state and return the exact derived tracks.md update and digest.",
35376
+ server.registerTool("tracks_render", {
35377
+ title: "Render the derived tracks index",
35378
+ description: "Atomically validate and rewrite deterministic tracks.md from current track-local state.",
34932
35379
  inputSchema: { projectRoot: external_exports.string().min(1) },
34933
- annotations: { readOnlyHint: true, openWorldHint: false }
35380
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34934
35381
  }, async ({ projectRoot }) => {
34935
35382
  try {
34936
- const input = { projectRoot: safeProjectRoot(projectRoot) };
35383
+ const input = { projectRoot: requireCurrentProject2(projectRoot) };
34937
35384
  const preview = renderTracksPreview(input.projectRoot);
34938
- return proposalResult("tracks_render", input, {
35385
+ const path = writeTracks(input.projectRoot, preview.digest, preview);
35386
+ return result({
35387
+ commandStatus: "applied",
34939
35388
  path: preview.path,
34940
35389
  sha256: sha256(preview.content),
34941
- digest: preview.digest
35390
+ changed: preview.changed,
35391
+ writtenPath: path
34942
35392
  });
34943
35393
  } catch (error51) {
34944
35394
  return failure(error51);
34945
35395
  }
34946
35396
  });
34947
- server.registerTool("tracks_render_apply", {
34948
- title: "Apply the derived tracks index",
34949
- description: "Rewrite tracks.md only when current state matches a human-approved preview digest.",
34950
- inputSchema: proposalInputSchema(),
34951
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34952
- }, async ({ proposalToken }) => {
34953
- try {
34954
- const proposal = proposalTokens.resolve("tracks_render", proposalToken);
34955
- return result({ path: writeTracks(proposal.input.projectRoot, proposal.digest) });
34956
- } catch (error51) {
34957
- return failure(error51);
34958
- }
34959
- });
34960
35397
  return server;
34961
35398
  }
34962
35399
  async function runCadreServer() {
34963
35400
  const server = createCadreServer();
34964
35401
  await server.connect(new StdioServerTransport());
34965
35402
  }
34966
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve11(process.argv[1])).href) {
35403
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve12(process.argv[1])).href) {
34967
35404
  runCadreServer().catch((error51) => {
34968
35405
  process.stderr.write(`${error51 instanceof Error ? error51.message : String(error51)}
34969
35406
  `);