cadre-ai 3.2.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 +127 -0
  4. package/README.md +20 -22
  5. package/dist/cadre-cli.mjs +2 -2
  6. package/dist/cadre-mcp.mjs +1510 -652
  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
@@ -405,11 +405,11 @@ var require_codegen = __commonJS({
405
405
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
406
406
  return `${varKind} ${this.name}${rhs};` + _n;
407
407
  }
408
- optimizeNames(names, constants) {
408
+ optimizeNames(names, constants2) {
409
409
  if (!names[this.name.str])
410
410
  return;
411
411
  if (this.rhs)
412
- this.rhs = optimizeExpr(this.rhs, names, constants);
412
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
413
413
  return this;
414
414
  }
415
415
  get names() {
@@ -426,10 +426,10 @@ var require_codegen = __commonJS({
426
426
  render({ _n }) {
427
427
  return `${this.lhs} = ${this.rhs};` + _n;
428
428
  }
429
- optimizeNames(names, constants) {
429
+ optimizeNames(names, constants2) {
430
430
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
431
431
  return;
432
- this.rhs = optimizeExpr(this.rhs, names, constants);
432
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
433
433
  return this;
434
434
  }
435
435
  get names() {
@@ -490,8 +490,8 @@ var require_codegen = __commonJS({
490
490
  optimizeNodes() {
491
491
  return `${this.code}` ? this : void 0;
492
492
  }
493
- optimizeNames(names, constants) {
494
- this.code = optimizeExpr(this.code, names, constants);
493
+ optimizeNames(names, constants2) {
494
+ this.code = optimizeExpr(this.code, names, constants2);
495
495
  return this;
496
496
  }
497
497
  get names() {
@@ -520,12 +520,12 @@ var require_codegen = __commonJS({
520
520
  }
521
521
  return nodes.length > 0 ? this : void 0;
522
522
  }
523
- optimizeNames(names, constants) {
523
+ optimizeNames(names, constants2) {
524
524
  const { nodes } = this;
525
525
  let i = nodes.length;
526
526
  while (i--) {
527
527
  const n = nodes[i];
528
- if (n.optimizeNames(names, constants))
528
+ if (n.optimizeNames(names, constants2))
529
529
  continue;
530
530
  subtractNames(names, n.names);
531
531
  nodes.splice(i, 1);
@@ -578,12 +578,12 @@ var require_codegen = __commonJS({
578
578
  return void 0;
579
579
  return this;
580
580
  }
581
- optimizeNames(names, constants) {
581
+ optimizeNames(names, constants2) {
582
582
  var _a3;
583
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
584
- if (!(super.optimizeNames(names, constants) || this.else))
583
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
584
+ if (!(super.optimizeNames(names, constants2) || this.else))
585
585
  return;
586
- this.condition = optimizeExpr(this.condition, names, constants);
586
+ this.condition = optimizeExpr(this.condition, names, constants2);
587
587
  return this;
588
588
  }
589
589
  get names() {
@@ -606,10 +606,10 @@ var require_codegen = __commonJS({
606
606
  render(opts) {
607
607
  return `for(${this.iteration})` + super.render(opts);
608
608
  }
609
- optimizeNames(names, constants) {
610
- if (!super.optimizeNames(names, constants))
609
+ optimizeNames(names, constants2) {
610
+ if (!super.optimizeNames(names, constants2))
611
611
  return;
612
- this.iteration = optimizeExpr(this.iteration, names, constants);
612
+ this.iteration = optimizeExpr(this.iteration, names, constants2);
613
613
  return this;
614
614
  }
615
615
  get names() {
@@ -645,10 +645,10 @@ var require_codegen = __commonJS({
645
645
  render(opts) {
646
646
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
647
647
  }
648
- optimizeNames(names, constants) {
649
- if (!super.optimizeNames(names, constants))
648
+ optimizeNames(names, constants2) {
649
+ if (!super.optimizeNames(names, constants2))
650
650
  return;
651
- this.iterable = optimizeExpr(this.iterable, names, constants);
651
+ this.iterable = optimizeExpr(this.iterable, names, constants2);
652
652
  return this;
653
653
  }
654
654
  get names() {
@@ -690,11 +690,11 @@ var require_codegen = __commonJS({
690
690
  (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
691
691
  return this;
692
692
  }
693
- optimizeNames(names, constants) {
693
+ optimizeNames(names, constants2) {
694
694
  var _a3, _b;
695
- super.optimizeNames(names, constants);
696
- (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
697
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
695
+ super.optimizeNames(names, constants2);
696
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
697
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants2);
698
698
  return this;
699
699
  }
700
700
  get names() {
@@ -995,7 +995,7 @@ var require_codegen = __commonJS({
995
995
  function addExprNames(names, from) {
996
996
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
997
997
  }
998
- function optimizeExpr(expr, names, constants) {
998
+ function optimizeExpr(expr, names, constants2) {
999
999
  if (expr instanceof code_1.Name)
1000
1000
  return replaceName(expr);
1001
1001
  if (!canOptimize(expr))
@@ -1010,14 +1010,14 @@ var require_codegen = __commonJS({
1010
1010
  return items;
1011
1011
  }, []));
1012
1012
  function replaceName(n) {
1013
- const c = constants[n.str];
1013
+ const c = constants2[n.str];
1014
1014
  if (c === void 0 || names[n.str] !== 1)
1015
1015
  return n;
1016
1016
  delete names[n.str];
1017
1017
  return c;
1018
1018
  }
1019
1019
  function canOptimize(e) {
1020
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
1020
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants2[c.str] !== void 0);
1021
1021
  }
1022
1022
  }
1023
1023
  function subtractNames(names, from) {
@@ -2979,7 +2979,7 @@ var require_compile = __commonJS({
2979
2979
  const schOrFunc = root.refs[ref];
2980
2980
  if (schOrFunc)
2981
2981
  return schOrFunc;
2982
- let _sch = resolve11.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 resolve11(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 resolve11(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: resolve11,
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((resolve11) => setTimeout(resolve11, 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((resolve11, 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
- resolve11(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((resolve11, 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(resolve11, 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((resolve11) => setTimeout(resolve11, 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,43 +30959,48 @@ var StdioServerTransport = class {
30959
30959
  this.onclose?.();
30960
30960
  }
30961
30961
  send(message) {
30962
- return new Promise((resolve11) => {
30962
+ return new Promise((resolve13) => {
30963
30963
  const json3 = serializeMessage(message);
30964
30964
  if (this._stdout.write(json3)) {
30965
- resolve11();
30965
+ resolve13();
30966
30966
  } else {
30967
- this._stdout.once("drain", resolve11);
30967
+ this._stdout.once("drain", resolve13);
30968
30968
  }
30969
30969
  });
30970
30970
  }
30971
30971
  };
30972
30972
 
30973
30973
  // src/mcp/server.ts
30974
- import { readFileSync as readFileSync8 } from "node:fs";
30975
- import { join as join8, resolve as resolve10 } from "node:path";
30974
+ import { createHash as createHash8 } from "node:crypto";
30975
+ import { readFileSync as readFileSync10 } from "node:fs";
30976
+ import { join as join10, resolve as resolve12 } from "node:path";
30976
30977
  import { pathToFileURL } from "node:url";
30977
30978
 
30978
30979
  // src/domain/init.ts
30979
- import { createHash as createHash5 } from "node:crypto";
30980
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
30980
30981
  import {
30981
- existsSync as existsSync7,
30982
- lstatSync as lstatSync3,
30983
- mkdirSync as mkdirSync2,
30984
- readFileSync as readFileSync6,
30985
- renameSync as renameSync2,
30986
- 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
30987
30990
  } from "node:fs";
30988
30991
  import { dirname as dirname3 } from "node:path";
30989
- 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";
30990
30993
 
30991
30994
  // src/domain/state.ts
30992
30995
  import { createHash as createHash3 } from "node:crypto";
30993
30996
  import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
30994
- import { join as join3, resolve as resolve5 } from "node:path";
30997
+ import { isAbsolute, join as join3, relative, resolve as resolve5 } from "node:path";
30995
30998
 
30996
30999
  // src/domain/version.ts
30997
- var CADRE_RUNTIME_VERSION = "3.2.0";
30998
- 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"];
30999
31004
 
31000
31005
  // src/domain/plan.ts
31001
31006
  import { createHash } from "node:crypto";
@@ -31338,6 +31343,16 @@ function resolveGitCommit(projectRoot, revision = "HEAD") {
31338
31343
  if (result2.status !== 0) throw new Error(`Git commit is not reachable: ${revision}`);
31339
31344
  return result2.stdout.trim();
31340
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
+ }
31341
31356
  function isGitAncestor(projectRoot, ancestor, descendant = "HEAD") {
31342
31357
  const root = gitRoot(projectRoot);
31343
31358
  return spawnSync("git", ["merge-base", "--is-ancestor", ancestor, descendant], {
@@ -31555,8 +31570,8 @@ function previewExecutionStart(input) {
31555
31570
  digest: hash2({ stateBody, planBody: readFileSync3(planPath, "utf8"), journal, state: proposedState })
31556
31571
  };
31557
31572
  }
31558
- function applyExecutionStart(input, proposalDigest) {
31559
- const proposal = previewExecutionStart(input);
31573
+ function applyExecutionStart(input, proposalDigest, preparedProposal) {
31574
+ const proposal = preparedProposal ?? previewExecutionStart(input);
31560
31575
  if (proposal.digest !== proposalDigest) throw new Error("execution proposal is stale; preview it again");
31561
31576
  if (lstatSync(proposal.statePath).isSymbolicLink()) throw new Error("refusing to start execution through a state symbolic link");
31562
31577
  mkdirSync(dirname(proposal.journalPath), { recursive: true });
@@ -31759,6 +31774,66 @@ function deriveExecutionStatus(journal) {
31759
31774
  eventGuidance
31760
31775
  };
31761
31776
  }
31777
+ function executionSchedulerView(journal, focusNodeIds = []) {
31778
+ const status = deriveExecutionStatus(journal);
31779
+ const relevant = /* @__PURE__ */ new Set([
31780
+ ...status.active,
31781
+ ...status.blocked,
31782
+ ...focusNodeIds
31783
+ ]);
31784
+ return {
31785
+ readyPhases: status.readyPhases,
31786
+ readyTasks: status.readyTasks,
31787
+ active: status.active,
31788
+ blocked: status.blocked,
31789
+ eventGuidance: Object.fromEntries(
31790
+ Object.entries(status.eventGuidance).filter(([nodeId]) => relevant.has(nodeId))
31791
+ )
31792
+ };
31793
+ }
31794
+ function compactExecutionStatus(journal, nodeId) {
31795
+ if (nodeId && !journal.nodes[nodeId]) throw new Error(`unknown execution node ${nodeId}`);
31796
+ const derivedStatus = executionSchedulerView(journal, nodeId ? [nodeId] : []);
31797
+ const actionableIds = /* @__PURE__ */ new Set([
31798
+ ...derivedStatus.active,
31799
+ ...derivedStatus.blocked
31800
+ ]);
31801
+ const actionableNodes = [...actionableIds].map((id) => {
31802
+ const node = journal.nodes[id];
31803
+ return {
31804
+ id: node.id,
31805
+ kind: node.kind,
31806
+ phaseId: node.phaseId,
31807
+ status: node.status,
31808
+ dependencies: node.dependencies,
31809
+ ...node.workerId ? { workerId: node.workerId } : {},
31810
+ ...node.worktreePath ? { worktreePath: node.worktreePath } : {},
31811
+ ...node.branch ? { branch: node.branch } : {},
31812
+ ...node.blocker ? { blocker: node.blocker } : {}
31813
+ };
31814
+ });
31815
+ const counts = {};
31816
+ for (const node of Object.values(journal.nodes)) counts[node.status] = (counts[node.status] ?? 0) + 1;
31817
+ return {
31818
+ execution: {
31819
+ executionId: journal.executionId,
31820
+ trackId: journal.trackId,
31821
+ status: journal.status,
31822
+ checkpoint: journal.checkpoint,
31823
+ requestedMode: journal.requestedMode,
31824
+ effectiveMode: journal.effectiveMode,
31825
+ approvalMode: journal.approvalMode,
31826
+ maxWorkers: journal.maxWorkers,
31827
+ planRevision: journal.planRevision,
31828
+ startedAt: journal.startedAt,
31829
+ completedAt: journal.completedAt
31830
+ },
31831
+ counts,
31832
+ actionableNodes,
31833
+ ...nodeId ? { node: journal.nodes[nodeId] } : {},
31834
+ derivedStatus
31835
+ };
31836
+ }
31762
31837
  function executionStatus(projectRoot, trackId, executionId) {
31763
31838
  const journal = readExecution(projectRoot, trackId, executionId);
31764
31839
  return { journal, ...deriveExecutionStatus(journal) };
@@ -31788,11 +31863,13 @@ function checkpointUpdates(journal, input) {
31788
31863
  ...Object.hasOwn(input, "worktreePath") ? { worktreePath: input.worktreePath ?? null } : {},
31789
31864
  ...Object.hasOwn(input, "branch") ? { branch: input.branch ?? null } : {}
31790
31865
  });
31791
- } else if (node.status === "running" && Object.hasOwn(input, "workerId")) {
31866
+ } else if (node.status === "running" && ["workerId", "worktreePath", "branch"].some((key) => Object.hasOwn(input, key))) {
31792
31867
  updates.push({
31793
31868
  nodeId: node.id,
31794
31869
  status: "running",
31795
- 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 } : {},
31796
31873
  ...evidence ? { verification: evidence } : {}
31797
31874
  });
31798
31875
  } else if (node.status !== "running") {
@@ -31823,7 +31900,6 @@ function checkpointUpdates(journal, input) {
31823
31900
  if (node.status !== "integrated") {
31824
31901
  updates.push({ nodeId: node.id, status: "integrated", mergeCommit: commit, verification: evidence });
31825
31902
  }
31826
- updates.push({ nodeId: node.id, status: "completed" });
31827
31903
  break;
31828
31904
  case "record_verification":
31829
31905
  if (node.kind !== "manual-verification" || !commit || !evidence || !authorization) {
@@ -31876,21 +31952,63 @@ function checkpointUpdates(journal, input) {
31876
31952
  }
31877
31953
  function previewExecutionCheckpoint(input) {
31878
31954
  const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
31879
- return previewExecutionNodesUpdate({
31955
+ const from = journal.nodes[input.nodeId]?.status;
31956
+ if (!from) throw new Error(`unknown execution node ${input.nodeId}`);
31957
+ const updates = checkpointUpdates(journal, input);
31958
+ const proposal = previewExecutionNodesUpdate({
31880
31959
  projectRoot: input.projectRoot,
31881
31960
  trackId: input.trackId,
31882
31961
  executionId: input.executionId,
31883
- updates: checkpointUpdates(journal, input)
31962
+ updates
31884
31963
  });
31964
+ const statuses = updates.map((update) => update.status);
31965
+ return {
31966
+ ...proposal,
31967
+ transition: {
31968
+ nodeId: input.nodeId,
31969
+ event: input.event,
31970
+ from,
31971
+ through: statuses.slice(0, -1),
31972
+ to: statuses.at(-1),
31973
+ checkpoint: proposal.journal.checkpoint
31974
+ }
31975
+ };
31885
31976
  }
31886
- 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
+ }
31887
31990
  const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
31888
- return applyExecutionNodesUpdate({
31991
+ const from = journal.nodes[input.nodeId]?.status;
31992
+ if (!from) throw new Error(`unknown execution node ${input.nodeId}`);
31993
+ const updates = checkpointUpdates(journal, input);
31994
+ const applied = applyExecutionNodesUpdate({
31889
31995
  projectRoot: input.projectRoot,
31890
31996
  trackId: input.trackId,
31891
31997
  executionId: input.executionId,
31892
- updates: checkpointUpdates(journal, input)
31998
+ updates
31893
31999
  }, proposalDigest);
32000
+ const statuses = updates.map((update) => update.status);
32001
+ return {
32002
+ ...applied,
32003
+ transition: {
32004
+ nodeId: input.nodeId,
32005
+ event: input.event,
32006
+ from,
32007
+ through: statuses.slice(0, -1),
32008
+ to: statuses.at(-1),
32009
+ checkpoint: applied.journal.checkpoint
32010
+ }
32011
+ };
31894
32012
  }
31895
32013
  function deriveExecutionFinishInput(input) {
31896
32014
  return {
@@ -32016,8 +32134,8 @@ function previewExecutionFinish(input) {
32016
32134
  })
32017
32135
  };
32018
32136
  }
32019
- function applyExecutionFinish(input, proposalDigest) {
32020
- const proposal = previewExecutionFinish(input);
32137
+ function applyExecutionFinish(input, proposalDigest, preparedProposal) {
32138
+ const proposal = preparedProposal ?? previewExecutionFinish(input);
32021
32139
  if (proposal.digest !== proposalDigest) throw new Error("execution completion proposal is stale; preview it again");
32022
32140
  if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink() || lstatSync(proposal.planPath).isSymbolicLink() || lstatSync(proposal.tracksPath).isSymbolicLink()) {
32023
32141
  throw new Error("refusing to complete execution through a symbolic link");
@@ -32052,18 +32170,18 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
32052
32170
  if (["ready_for_review", "completed", "archived"].includes(state.status)) errors.push(`${state.trackId}: finalized track requires lastExecution`);
32053
32171
  return;
32054
32172
  }
32055
- const relative5 = String(reference.journal ?? "");
32056
- 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)) {
32057
32175
  errors.push(`${state.trackId}: invalid execution journal path`);
32058
32176
  return;
32059
32177
  }
32060
- const path = resolve4(trackRoot, relative5);
32178
+ const path = resolve4(trackRoot, relative7);
32061
32179
  if (!path.startsWith(`${resolve4(trackRoot)}/`)) {
32062
32180
  errors.push(`${state.trackId}: execution journal escapes track root`);
32063
32181
  return;
32064
32182
  }
32065
32183
  if (!existsSync4(path)) {
32066
- errors.push(`${state.trackId}: missing execution journal ${relative5}`);
32184
+ errors.push(`${state.trackId}: missing execution journal ${relative7}`);
32067
32185
  return;
32068
32186
  }
32069
32187
  let journal;
@@ -32220,7 +32338,7 @@ function readJson(path, errors) {
32220
32338
  return null;
32221
32339
  }
32222
32340
  }
32223
- function validateOperation(operation, owner, errors) {
32341
+ function validateOperation(operation, owner, errors, artifactRoot, artifactProgress = operation?.artifactProgress ?? []) {
32224
32342
  if (!operation || typeof operation !== "object") {
32225
32343
  errors.push(`${owner}: incomplete state requires an operation journal`);
32226
32344
  return;
@@ -32231,6 +32349,41 @@ function validateOperation(operation, owner, errors) {
32231
32349
  errors.push(`${owner}: operation approvedArtifacts must be a non-empty array`);
32232
32350
  }
32233
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
+ }
32234
32387
  }
32235
32388
  function validateRevisionOperation(state, owner, errors) {
32236
32389
  const operation = state.operation;
@@ -32355,7 +32508,7 @@ function validateProjectOperations(root, byId, errors) {
32355
32508
  const owner = `operations/${file2}`;
32356
32509
  const operation = readJson(join3(operationsRoot, file2), errors);
32357
32510
  if (!operation) continue;
32358
- validateOperation(operation, owner, errors);
32511
+ validateOperation(operation, owner, errors, root);
32359
32512
  if (!operation.status || !["in_progress", "completed"].includes(operation.status)) {
32360
32513
  errors.push(`${owner}: status must be in_progress or completed`);
32361
32514
  }
@@ -32460,8 +32613,10 @@ function validateProject(projectRoot) {
32460
32613
  if (!existsSync5(join3(root, file2))) errors.push(`${join3(root, file2)}: missing required Cadre file`);
32461
32614
  }
32462
32615
  const gitignorePath = join3(root, ".gitignore");
32616
+ let candidateStageIgnored = false;
32463
32617
  if (existsSync5(gitignorePath)) {
32464
32618
  const gitignore = readFileSync4(gitignorePath, "utf8");
32619
+ candidateStageIgnored = gitignore.split(/\r?\n/).includes("/stage/");
32465
32620
  if (!gitignore.split(/\r?\n/).includes("/.worktrees/")) {
32466
32621
  errors.push(`${gitignorePath}: must ignore /.worktrees/`);
32467
32622
  }
@@ -32471,18 +32626,39 @@ function validateProject(projectRoot) {
32471
32626
  }
32472
32627
  const project = readJson(join3(root, "project.json"), errors);
32473
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
+ }
32474
32634
  const commitReferences = [];
32475
32635
  collectCommitReferences(project, "project.json", commitReferences);
32476
32636
  if (project.schemaVersion !== 1) errors.push("project.json: unsupported schemaVersion");
32477
- if (project.runtimeVersion !== CADRE_RUNTIME_VERSION) errors.push(`project.json: runtimeVersion must be ${CADRE_RUNTIME_VERSION}`);
32478
- 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
+ }
32479
32649
  if (!project.project?.context || !["greenfield", "brownfield"].includes(project.project.context)) {
32480
32650
  errors.push("project.json: project context must be greenfield or brownfield");
32481
32651
  }
32482
32652
  if (!project.setup?.checkpoint) errors.push("project.json: setup checkpoint is required");
32483
32653
  if (!Array.isArray(project.setup?.artifactProgress)) errors.push("project.json: setup artifactProgress must be an array");
32484
32654
  if (project.setup?.status === "in_progress") {
32485
- 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
+ );
32486
32662
  } else if (project.setup?.status === "completed") {
32487
32663
  if (!/^[0-9a-f]{7,40}$/.test(project.setup?.commit ?? "")) {
32488
32664
  errors.push("project.json: completed setup requires a commit SHA");
@@ -32510,7 +32686,7 @@ function validateProject(projectRoot) {
32510
32686
  if (!state.checkpoint) errors.push(`${track.id}: state checkpoint is required`);
32511
32687
  if (!Array.isArray(state.artifactProgress)) errors.push(`${track.id}: artifactProgress must be an array`);
32512
32688
  if (state.operation != null) {
32513
- validateOperation(state.operation, `${track.id} state`, errors);
32689
+ validateOperation(state.operation, `${track.id} state`, errors, trackRoot, state.artifactProgress);
32514
32690
  validateRevisionOperation(state, `${track.id} state`, errors);
32515
32691
  validateImplementOperation(state, `${track.id} state`, errors);
32516
32692
  validateRevertOperation(state, `${track.id} state`, errors);
@@ -32629,17 +32805,6 @@ function validateProject(projectRoot) {
32629
32805
  }
32630
32806
  return { project, tracks, states, errors, warnings };
32631
32807
  }
32632
- function nextCommand(track) {
32633
- return {
32634
- "drafting-spec": "track",
32635
- "drafting-plan": "track",
32636
- planned: "implement",
32637
- in_progress: "implement",
32638
- ready_for_review: "review",
32639
- completed: "archive",
32640
- archived: "\u2014"
32641
- }[track.status] ?? "\u2014";
32642
- }
32643
32808
  function renderTracksPreview(projectRoot) {
32644
32809
  const result2 = validateProject(projectRoot);
32645
32810
  if (!result2.project) throw new Error(result2.errors.join("\n") || "Cadre project state is unavailable");
@@ -32650,8 +32815,8 @@ function renderTracksPreview(projectRoot) {
32650
32815
  const digest = createHash3("sha256").update(JSON.stringify({ content, previousContent })).digest("hex");
32651
32816
  return { path, content, previousContent, changed: previousContent !== content, digest };
32652
32817
  }
32653
- function writeTracks(projectRoot, proposalDigest) {
32654
- const preview = renderTracksPreview(projectRoot);
32818
+ function writeTracks(projectRoot, proposalDigest, preparedPreview) {
32819
+ const preview = preparedPreview ?? renderTracksPreview(projectRoot);
32655
32820
  if (preview.digest !== proposalDigest) {
32656
32821
  throw new Error("tracks.md proposal is stale; preview it again before applying");
32657
32822
  }
@@ -32662,37 +32827,156 @@ function writeTracks(projectRoot, proposalDigest) {
32662
32827
  writeFileSync2(preview.path, preview.content);
32663
32828
  return preview.path;
32664
32829
  }
32665
- function formatStatus(projectRoot) {
32666
- const result2 = validateProject(projectRoot);
32667
- const project = result2.project;
32668
- if (!project) return { text: result2.errors.join("\n"), result: result2 };
32669
- const lines = [
32670
- `Project: ${project.project?.name ?? "unknown"}; context=${project.project?.context ?? "unknown"}`,
32671
- `Setup: ${project.setup?.status ?? "unknown"}; checkpoint=${project.setup?.checkpoint ?? "none"}; operation=${project.setup?.operation?.action ?? "none"}; commit=${project.setup?.commit ?? "none"}`,
32672
- `Last refresh: ${project.lastRefresh?.commit ?? "none"}`
32673
- ];
32674
- for (const track of result2.tracks) {
32675
- const dependencies = track.dependencies?.length ? track.dependencies.join(",") : "none";
32676
- const state = result2.states.get(track.id);
32677
- const execution = state?.operation?.action === "implement" ? `${String(state.operation.executionId ?? "unknown")}/${String(state.operation.mode ?? "unknown")}/${String(state.operation.approvalMode ?? "governed")}` : state?.lastExecution ? `${String(state.lastExecution.executionId ?? "unknown")}/completed/${String(state.lastExecution.approvalMode ?? "governed")}` : "none";
32678
- lines.push(`${track.id} [${track.type}] ${track.status}; checkpoint=${state?.checkpoint ?? "none"}; operation=${state?.operation?.action ?? "none"}; execution=${execution}; deps=${dependencies}; revision=${track.revision ?? 1}; reviews=${state?.reviewCycles?.length ?? 0}; next=${nextCommand(track)}`);
32679
- }
32680
- const counts = result2.tracks.reduce((summary, track) => {
32681
- summary[track.status] = (summary[track.status] ?? 0) + 1;
32682
- return summary;
32683
- }, {});
32684
- lines.push(`Counts: ready_for_review=${counts.ready_for_review ?? 0}; completed=${counts.completed ?? 0}; archived=${counts.archived ?? 0}`);
32685
- lines.push(
32686
- `Validation: ${result2.errors.length ? `${result2.errors.length} error(s)` : "valid"}; derived=${result2.warnings.length ? `${result2.warnings.length} warning(s)` : "current"}`
32687
- );
32688
- return { text: `${lines.join("\n")}
32689
- `, 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();
32690
32974
  }
32691
32975
 
32692
32976
  // src/domain/templates.ts
32693
32977
  import { createHash as createHash4 } from "node:crypto";
32694
- import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync as readdirSync4 } from "node:fs";
32695
- import { dirname as dirname2, extname, join as join4, relative, resolve as resolve6, sep } from "node:path";
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";
32696
32980
  import { fileURLToPath } from "node:url";
32697
32981
  var TEMPLATE_IDS = [
32698
32982
  "project/archive-operation",
@@ -32734,22 +33018,49 @@ var TEMPLATE_IDS = [
32734
33018
  "track/spec",
32735
33019
  "track/state"
32736
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
+ };
32737
33048
  var catalogCache = null;
32738
33049
  function locateTemplateRoot() {
32739
33050
  const moduleDirectory = dirname2(fileURLToPath(import.meta.url));
32740
33051
  const candidates = [
32741
33052
  process.env.CADRE_TEMPLATE_ROOT,
32742
- resolve6(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
32743
- resolve6(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
33053
+ resolve7(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
33054
+ resolve7(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
32744
33055
  ].filter((candidate) => Boolean(candidate));
32745
- const found = candidates.find((candidate) => existsSync6(candidate));
33056
+ const found = candidates.find((candidate) => existsSync7(candidate));
32746
33057
  if (!found) throw new Error(`Cadre template set ${TEMPLATE_SET_VERSION} is unavailable`);
32747
33058
  return found;
32748
33059
  }
32749
33060
  function walk(root, directory = root) {
32750
- return readdirSync4(directory, { withFileTypes: true }).flatMap((entry) => {
32751
- const path = join4(directory, entry.name);
32752
- 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("/")];
32753
33064
  });
32754
33065
  }
32755
33066
  function templateId(path) {
@@ -32785,7 +33096,7 @@ function templateCatalog() {
32785
33096
  const catalog = walk(root).map((relativePath) => {
32786
33097
  const id = templateId(relativePath);
32787
33098
  if (!id) return null;
32788
- const content = readFileSync5(join4(root, relativePath), "utf8");
33099
+ const content = readFileSync6(join5(root, relativePath), "utf8");
32789
33100
  return {
32790
33101
  id,
32791
33102
  uri: `cadre://templates/${TEMPLATE_SET_VERSION}/${id}`,
@@ -32800,9 +33111,6 @@ function templateCatalog() {
32800
33111
  }
32801
33112
  return catalogCache.map((template) => ({ ...template }));
32802
33113
  }
32803
- function getTemplate(id) {
32804
- return getTemplates([id])[0];
32805
- }
32806
33114
  function getTemplates(ids) {
32807
33115
  const byId = new Map(templateCatalog().map((template) => [template.id, template]));
32808
33116
  return ids.map((id) => {
@@ -32811,6 +33119,11 @@ function getTemplates(ids) {
32811
33119
  return template;
32812
33120
  });
32813
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
+ }
32814
33127
  var STYLEGUIDE_RULES = [
32815
33128
  [/\bhtml\b|\bcss\b|html\/css/i, ["html-css"]],
32816
33129
  [/\btypescript\b/i, ["javascript", "typescript"]],
@@ -32837,13 +33150,8 @@ function resolveStyleguides(technologies) {
32837
33150
  }
32838
33151
 
32839
33152
  // src/domain/init.ts
32840
- var REQUIRED_APPROVED_FILES = /* @__PURE__ */ new Set([
32841
- "product.md",
32842
- "guidelines.md",
32843
- "tech-stack.md",
32844
- "workflow.md",
32845
- "styleguides/general.md"
32846
- ]);
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)$/;
32847
33155
  function hash3(content) {
32848
33156
  return createHash5("sha256").update(content).digest("hex");
32849
33157
  }
@@ -32855,12 +33163,17 @@ function proposalFileHash(file2) {
32855
33163
  `);
32856
33164
  }
32857
33165
  function normalizeCadrePath(input) {
32858
- 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}`);
32859
33167
  const normalized = input.replaceAll("\\", "/").replace(/^\.\//, "");
32860
33168
  if (normalized.startsWith("../") || normalized.includes("/../") || normalized === "..") {
32861
33169
  throw new Error(`Cadre artifact path escapes the project: ${input}`);
32862
33170
  }
32863
- 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)) {
32864
33177
  throw new Error(`Unsupported initialization artifact: ${input}`);
32865
33178
  }
32866
33179
  return normalized;
@@ -32868,7 +33181,7 @@ function normalizeCadrePath(input) {
32868
33181
  function assertRendered(content, path) {
32869
33182
  if (/\{\{[^}]+\}\}/.test(content)) throw new Error(`${path} contains unresolved template placeholders`);
32870
33183
  }
32871
- function projectState(input, approvedPaths, template) {
33184
+ function projectState(input, approvedPaths, approvedArtifactHashes, template) {
32872
33185
  const state = JSON.parse(template);
32873
33186
  state.runtimeVersion = CADRE_RUNTIME_VERSION;
32874
33187
  state.templateSetVersion = TEMPLATE_SET_VERSION;
@@ -32881,13 +33194,13 @@ function projectState(input, approvedPaths, template) {
32881
33194
  state.setup.operation.repositoryRoot = safeProjectRoot(input.projectRoot);
32882
33195
  state.setup.operation.gitDisposition = input.gitDisposition;
32883
33196
  state.setup.operation.approvedArtifacts = approvedPaths;
33197
+ state.setup.operation.approvedArtifactHashes = approvedArtifactHashes;
32884
33198
  state.setup.operation.approvedAt = input.approvedAt;
32885
33199
  return `${JSON.stringify(state, null, 2)}
32886
33200
  `;
32887
33201
  }
32888
- function previewProjectInit(input) {
33202
+ function buildProjectInitProposal(input) {
32889
33203
  const root = safeProjectRoot(input.projectRoot);
32890
- if (existsSync7(join5(root, ".cadre"))) throw new Error(`${root}/.cadre already exists`);
32891
33204
  if (!input.projectName.trim()) throw new Error("Project name is required");
32892
33205
  if (!Number.isFinite(Date.parse(input.approvedAt))) throw new Error("approvedAt must be an ISO timestamp");
32893
33206
  if (input.baseCommit !== null && !/^[0-9a-f]{7,40}$/.test(input.baseCommit)) {
@@ -32901,19 +33214,47 @@ function previewProjectInit(input) {
32901
33214
  approved.set(path, file2.content.endsWith("\n") ? file2.content : `${file2.content}
32902
33215
  `);
32903
33216
  }
32904
- for (const path of REQUIRED_APPROVED_FILES) {
33217
+ for (const path of REQUIRED_STAGED_FILES) {
32905
33218
  if (!approved.has(path)) throw new Error(`Missing approved initialization artifact: ${path}`);
32906
33219
  }
32907
- const approvedPaths = [...approved.keys()].sort();
32908
- 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([
32909
33233
  "project/gitignore",
32910
33234
  "project/project",
32911
- "project/patterns/index"
33235
+ "project/patterns/index",
33236
+ "project/workflow",
33237
+ ...input.styleguideIds
32912
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)) }));
32913
33254
  const generated = new Map([
32914
- ...approved.entries(),
33255
+ ...generatedContext.entries(),
32915
33256
  [".gitignore", gitignoreTemplate.content],
32916
- ["project.json", projectState(input, approvedPaths, projectTemplate.content)],
33257
+ ["project.json", projectState(input, approvedPaths, approvedArtifactHashes, projectTemplate.content)],
32917
33258
  ["patterns/index.md", patternIndexTemplate.content],
32918
33259
  ["tracks.md", buildTracks([])],
32919
33260
  ["operations/.gitkeep", ""],
@@ -32929,84 +33270,132 @@ function previewProjectInit(input) {
32929
33270
  }));
32930
33271
  return { runtimeVersion: CADRE_RUNTIME_VERSION, templateSetVersion: TEMPLATE_SET_VERSION, files, digest };
32931
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
+ }
32932
33299
  function targetWithin(root, relativePath) {
32933
- const target = resolve7(root, relativePath);
32934
- const relation = relative2(root, target);
32935
- 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}`);
32936
33303
  return target;
32937
33304
  }
32938
33305
  function assertNoSymlinkPath(root, target) {
32939
33306
  let current = target;
32940
33307
  while (current !== root) {
32941
- if (existsSync7(current) && lstatSync3(current).isSymbolicLink()) {
33308
+ if (existsSync8(current) && lstatSync4(current).isSymbolicLink()) {
32942
33309
  throw new Error(`Refusing symbolic link inside initialization stage: ${current}`);
32943
33310
  }
32944
33311
  current = dirname3(current);
32945
33312
  }
32946
33313
  }
32947
- function applyProjectInit(input, proposalDigest) {
32948
- const proposal = previewProjectInit(input);
32949
- if (proposal.digest !== proposalDigest) throw new Error("Initialization proposal digest does not match; preview again");
33314
+ function applyProjectInitAtRoot(input, proposal) {
32950
33315
  const projectRoot = safeProjectRoot(input.projectRoot);
32951
- const stage = join5(projectRoot, `.cadre-init-${proposal.digest.slice(0, 12)}`);
32952
- if (existsSync7(stage) && (!lstatSync3(stage).isDirectory() || lstatSync3(stage).isSymbolicLink())) {
32953
- throw new Error(`Initialization stage is not a regular directory: ${stage}`);
32954
- }
32955
- mkdirSync2(stage, { recursive: true });
33316
+ const cadreRoot2 = join6(projectRoot, ".cadre");
32956
33317
  for (const file2 of proposal.files) {
32957
- const target = targetWithin(stage, file2.path);
32958
- assertNoSymlinkPath(stage, target);
32959
- mkdirSync2(dirname3(target), { recursive: true });
32960
- if (existsSync7(target)) {
32961
- 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");
32962
33323
  if (current !== file2.content) throw new Error(`Interrupted initialization disagrees at ${file2.path}`);
32963
- } 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
+ }
32964
33333
  }
32965
- const finalRoot = join5(projectRoot, ".cadre");
32966
- if (existsSync7(finalRoot)) throw new Error(`${finalRoot} appeared after preview; refusing to overwrite it`);
32967
- renameSync2(stage, finalRoot);
32968
33334
  return proposal;
32969
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
+ }
32970
33344
  function recordSetupCommit(projectRootInput, commit) {
32971
33345
  if (!/^[0-9a-f]{7,40}$/.test(commit)) throw new Error("commit must be a hexadecimal Git commit SHA");
32972
33346
  const root = safeProjectRoot(projectRootInput);
32973
- const path = join5(root, ".cadre", "project.json");
32974
- const project = JSON.parse(readFileSync6(path, "utf8"));
33347
+ const path = join6(root, ".cadre", "project.json");
33348
+ const project = JSON.parse(readFileSync7(path, "utf8"));
32975
33349
  if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
32976
33350
  throw new Error("Project setup is not awaiting its create commit");
32977
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
+ }
32978
33367
  project.setup.status = "completed";
32979
33368
  project.setup.checkpoint = "completed";
32980
33369
  project.setup.commit = commit;
32981
33370
  project.setup.operation = null;
32982
33371
  project.history = [...project.history ?? [], { action: "create", commit }];
32983
- writeFileSync3(path, `${JSON.stringify(project, null, 2)}
33372
+ writeFileSync4(path, `${JSON.stringify(project, null, 2)}
32984
33373
  `);
32985
33374
  return path;
32986
33375
  }
32987
33376
  function recordGitInitialized(projectRootInput) {
32988
33377
  const root = safeProjectRoot(projectRootInput);
32989
- const path = join5(root, ".cadre", "project.json");
32990
- const project = JSON.parse(readFileSync6(path, "utf8"));
33378
+ const path = join6(root, ".cadre", "project.json");
33379
+ const project = JSON.parse(readFileSync7(path, "utf8"));
32991
33380
  if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
32992
33381
  throw new Error("Project setup is not in an active create operation");
32993
33382
  }
32994
33383
  if (project.setup.operation.gitDisposition !== "initialize") {
32995
33384
  throw new Error("Project setup was not approved to initialize Git");
32996
33385
  }
32997
- if (resolve7(String(project.setup.operation.repositoryRoot)) !== root) {
33386
+ if (resolve8(String(project.setup.operation.repositoryRoot)) !== root) {
32998
33387
  throw new Error("Approved Git repository root does not match projectRoot");
32999
33388
  }
33000
33389
  project.setup.checkpoint = "commit-pending";
33001
- writeFileSync3(path, `${JSON.stringify(project, null, 2)}
33390
+ writeFileSync4(path, `${JSON.stringify(project, null, 2)}
33002
33391
  `);
33003
33392
  return path;
33004
33393
  }
33005
33394
 
33006
33395
  // src/domain/worktrees.ts
33007
33396
  import { createHash as createHash6 } from "node:crypto";
33008
- import { existsSync as existsSync8, lstatSync as lstatSync4, readdirSync as readdirSync5, realpathSync as realpathSync2, rmdirSync } from "node:fs";
33009
- import { dirname as dirname4, join as join6, relative as relative3, resolve as resolve8 } from "node:path";
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";
33010
33399
  import { spawnSync as spawnSync2 } from "node:child_process";
33011
33400
  var SHA2 = /^[0-9a-f]{7,40}$/;
33012
33401
  var TRACK_ID2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -33026,7 +33415,7 @@ function hash4(value) {
33026
33415
  }
33027
33416
  function assertRepository(projectRoot) {
33028
33417
  const root = realpathSync2(safeProjectRoot(projectRoot));
33029
- 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()));
33030
33419
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
33031
33420
  return root;
33032
33421
  }
@@ -33052,7 +33441,7 @@ function worktreeIdentity(root, trackId, executionId, nodeId, phaseId) {
33052
33441
  const resolvedPhaseId = phaseForNode(nodeId);
33053
33442
  const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId}/tasks/${resolvedPhaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId}/phases/${nodeId}`;
33054
33443
  const branch = `cadre/${trackId}/${executionId}/${task ? "task" : "phase"}-${nodeSlug(nodeId)}`;
33055
- return { path: join6(root, relativePath), relativePath, branch };
33444
+ return { path: join7(root, relativePath), relativePath, branch };
33056
33445
  }
33057
33446
  function branchHead(root, branch) {
33058
33447
  const result2 = git(root, ["rev-parse", "--verify", `refs/heads/${branch}`], true);
@@ -33063,14 +33452,14 @@ function registeredWorktrees(root) {
33063
33452
  let current = {};
33064
33453
  for (const line of git(root, ["worktree", "list", "--porcelain"]).stdout.split(/\r?\n/)) {
33065
33454
  if (!line) {
33066
- 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 });
33067
33456
  current = {};
33068
33457
  } else if (line.startsWith("worktree ")) current.path = line.slice("worktree ".length);
33069
33458
  else if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length);
33070
33459
  else if (line.startsWith("branch refs/heads/")) current.branch = line.slice("branch refs/heads/".length);
33071
33460
  else if (line === "detached") current.branch = null;
33072
33461
  }
33073
- 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 });
33074
33463
  return records;
33075
33464
  }
33076
33465
  function previewWorktreeCreate(input) {
@@ -33079,12 +33468,12 @@ function previewWorktreeCreate(input) {
33079
33468
  const baseCommit = git(target.path, ["rev-parse", "HEAD^{commit}"]).stdout.trim();
33080
33469
  if (!SHA2.test(baseCommit)) throw new Error("baseCommit does not resolve to a commit");
33081
33470
  const identity = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
33082
- const registered = registeredWorktrees(root).find((entry) => entry.path === resolve8(identity.path));
33471
+ const registered = registeredWorktrees(root).find((entry) => entry.path === resolve9(identity.path));
33083
33472
  const existingBranchHead = branchHead(root, identity.branch);
33084
33473
  if (registered && (registered.branch !== identity.branch || registered.head !== existingBranchHead)) {
33085
33474
  throw new Error(`registered worktree disagrees at ${identity.relativePath}`);
33086
33475
  }
33087
- 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}`);
33088
33477
  if (existingBranchHead) {
33089
33478
  const basedOnExpectedCommit = git(root, ["merge-base", "--is-ancestor", baseCommit, existingBranchHead], true).status === 0;
33090
33479
  if (!basedOnExpectedCommit) throw new Error(`existing branch ${identity.branch} is not based on requested base commit`);
@@ -33097,8 +33486,8 @@ function previewWorktreeCreate(input) {
33097
33486
  };
33098
33487
  return { ...proposal, digest: hash4(proposal) };
33099
33488
  }
33100
- function applyWorktreeCreate(input, proposalDigest) {
33101
- const proposal = previewWorktreeCreate(input);
33489
+ function applyWorktreeCreate(input, proposalDigest, preparedProposal) {
33490
+ const proposal = preparedProposal ?? previewWorktreeCreate(input);
33102
33491
  if (proposal.digest !== proposalDigest) throw new Error("worktree proposal is stale; preview it again");
33103
33492
  if (proposal.existing) return proposal;
33104
33493
  const existingBranch = branchHead(proposal.projectRoot, proposal.branch);
@@ -33119,7 +33508,7 @@ function targetIdentity(root, input) {
33119
33508
  if (TASK_ID.test(input.nodeId)) {
33120
33509
  const phaseId = phaseForNode(input.nodeId);
33121
33510
  const phase = worktreeIdentity(root, input.trackId, input.executionId, phaseId, null);
33122
- const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve8(phase.path));
33511
+ const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve9(phase.path));
33123
33512
  if (phaseWorktree) {
33124
33513
  if (phaseWorktree.branch !== phase.branch) throw new Error(`phase worktree is not on ${phase.branch}`);
33125
33514
  return { path: phase.path, branch: phase.branch };
@@ -33162,8 +33551,8 @@ function previewWorktreeIntegration(input) {
33162
33551
  const root = assertRepository(input.projectRoot);
33163
33552
  const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
33164
33553
  const target = targetIdentity(root, input);
33165
- if (!existsSync8(source.path)) throw new Error(`source worktree is missing: ${source.path}`);
33166
- if (!existsSync8(target.path)) throw new Error(`target worktree is missing: ${target.path}`);
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}`);
33167
33556
  cleanWorktree(source.path);
33168
33557
  const journalPath = `.cadre/tracks/${input.trackId}/executions/execution-${input.executionId}.json`;
33169
33558
  cleanWorktree(target.path, target.path === root ? /* @__PURE__ */ new Set([journalPath]) : /* @__PURE__ */ new Set());
@@ -33190,8 +33579,8 @@ function previewWorktreeIntegration(input) {
33190
33579
  };
33191
33580
  return { ...proposal, digest: hash4(proposal) };
33192
33581
  }
33193
- function applyWorktreeIntegration(input, proposalDigest) {
33194
- const proposal = previewWorktreeIntegration(input);
33582
+ function applyWorktreeIntegration(input, proposalDigest, preparedProposal) {
33583
+ const proposal = preparedProposal ?? previewWorktreeIntegration(input);
33195
33584
  if (proposal.digest !== proposalDigest) throw new Error("integration proposal is stale; preview it again");
33196
33585
  if (proposal.alreadyIntegrated) {
33197
33586
  return { status: "integrated", mergeCommit: proposal.targetHead, conflicts: [], targetPath: proposal.targetPath };
@@ -33214,8 +33603,23 @@ function previewWorktreeCleanup(input) {
33214
33603
  const root = assertRepository(input.projectRoot);
33215
33604
  const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId);
33216
33605
  const target = targetIdentity(root, input);
33217
- if (!existsSync8(source.path)) throw new Error(`worktree is missing: ${source.path}`);
33218
- 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");
33219
33623
  cleanWorktree(source.path);
33220
33624
  const head = git(source.path, ["rev-parse", "HEAD"]).stdout.trim();
33221
33625
  const ancestor = git(root, ["merge-base", "--is-ancestor", source.branch, target.branch], true);
@@ -33225,44 +33629,48 @@ function previewWorktreeCleanup(input) {
33225
33629
  branch: source.branch,
33226
33630
  targetPath: target.path,
33227
33631
  targetBranch: target.branch,
33228
- head
33632
+ head,
33633
+ alreadyRemoved: false
33229
33634
  };
33230
33635
  return { ...proposal, digest: hash4(proposal) };
33231
33636
  }
33232
- function applyWorktreeCleanup(input, proposalDigest) {
33233
- const proposal = previewWorktreeCleanup(input);
33637
+ function applyWorktreeCleanup(input, proposalDigest, preparedProposal) {
33638
+ const proposal = preparedProposal ?? previewWorktreeCleanup(input);
33234
33639
  if (proposal.digest !== proposalDigest) throw new Error("cleanup proposal is stale; preview it again");
33235
33640
  const root = assertRepository(input.projectRoot);
33236
- git(root, ["worktree", "remove", proposal.path]);
33237
- git(proposal.targetPath, ["branch", "-d", proposal.branch]);
33238
- 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");
33239
33644
  let directory = dirname4(proposal.path);
33240
33645
  while (directory.startsWith(`${managedRoot}/`)) {
33241
- if (!existsSync8(directory) || readdirSync5(directory).length) break;
33646
+ if (!existsSync9(directory) || readdirSync7(directory).length) break;
33242
33647
  rmdirSync(directory);
33243
33648
  directory = dirname4(directory);
33244
33649
  }
33245
33650
  return { removedPath: proposal.path, removedBranch: proposal.branch };
33246
33651
  }
33652
+ function integrationRequiresApproval(input) {
33653
+ return (readExecution(input.projectRoot, input.trackId, input.executionId).approvalMode ?? "governed") === "governed";
33654
+ }
33247
33655
  function managedWorktreeStatus(projectRoot) {
33248
33656
  const root = assertRepository(projectRoot);
33249
- const managedRoot = join6(root, ".cadre", ".worktrees");
33657
+ const managedRoot = join7(root, ".cadre", ".worktrees");
33250
33658
  const worktrees = registeredWorktrees(root).map((entry) => ({
33251
33659
  ...entry,
33252
- managed: relative3(managedRoot, entry.path) !== "" && !relative3(managedRoot, entry.path).startsWith("..")
33660
+ managed: relative5(managedRoot, entry.path) !== "" && !relative5(managedRoot, entry.path).startsWith("..")
33253
33661
  }));
33254
33662
  const registered = new Set(worktrees.filter((entry) => entry.managed).map((entry) => entry.path));
33255
33663
  const orphanedDirectories = [];
33256
33664
  function walk2(directory) {
33257
- if (!existsSync8(directory)) return;
33258
- if (registered.has(resolve8(directory))) return;
33259
- 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 });
33260
33668
  if (entries.some((entry) => entry.name === ".git")) {
33261
33669
  orphanedDirectories.push(directory);
33262
33670
  return;
33263
33671
  }
33264
- for (const entry of entries) if (entry.isDirectory()) walk2(join6(directory, entry.name));
33265
- if (!entries.length && resolve8(directory) !== resolve8(managedRoot)) orphanedDirectories.push(directory);
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);
33266
33674
  }
33267
33675
  walk2(managedRoot);
33268
33676
  return { worktrees, orphanedDirectories };
@@ -33271,34 +33679,37 @@ function managedWorktreeStatus(projectRoot) {
33271
33679
  // src/domain/governance.ts
33272
33680
  import { createHash as createHash7 } from "node:crypto";
33273
33681
  import {
33274
- existsSync as existsSync9,
33275
- lstatSync as lstatSync5,
33276
- mkdirSync as mkdirSync3,
33277
- readFileSync as readFileSync7,
33278
- readdirSync as readdirSync6,
33279
- renameSync as renameSync3,
33280
- 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
33281
33689
  } from "node:fs";
33282
- 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";
33283
33691
  var SHA3 = /^[0-9a-f]{7,40}$/;
33284
33692
  var TRACK_ID3 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
33285
33693
  var BATCH_ID = /^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
33286
33694
  function hash5(value) {
33287
33695
  return createHash7("sha256").update(JSON.stringify(value)).digest("hex");
33288
33696
  }
33697
+ function contentHash(content) {
33698
+ return createHash7("sha256").update(content).digest("hex");
33699
+ }
33289
33700
  function json2(value) {
33290
33701
  return `${JSON.stringify(value, null, 2)}
33291
33702
  `;
33292
33703
  }
33293
33704
  function assertWritableFile(path) {
33294
- if (existsSync9(path) && lstatSync5(path).isSymbolicLink()) {
33705
+ if (existsSync10(path) && lstatSync6(path).isSymbolicLink()) {
33295
33706
  throw new Error(`refusing to write through symbolic link ${path}`);
33296
33707
  }
33297
33708
  }
33298
33709
  function writeApprovedFile(path, content) {
33299
33710
  assertWritableFile(path);
33300
- mkdirSync3(dirname5(path), { recursive: true });
33301
- writeFileSync4(path, content);
33711
+ mkdirSync4(dirname5(path), { recursive: true });
33712
+ writeFileSync5(path, content);
33302
33713
  }
33303
33714
  function requireCurrentProject(projectRoot) {
33304
33715
  const validation = validateProject(projectRoot);
@@ -33347,10 +33758,10 @@ function previewReviewComplete(input) {
33347
33758
  if (!execution?.executionId || !execution.planRevision || !execution.graphDigest || execution.headCommit !== input.reviewedHead) {
33348
33759
  throw new Error("review evidence does not match the current completed execution");
33349
33760
  }
33350
- const statePath = join7(cadreRoot(root), track.location, "state.json");
33351
- const tracksPath = join7(cadreRoot(root), "tracks.md");
33352
- const stateBody = readFileSync7(statePath, "utf8");
33353
- const tracksBody = readFileSync7(tracksPath, "utf8");
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");
33354
33765
  const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
33355
33766
  const cycle = {
33356
33767
  cycle: (current.reviewCycles?.length ?? 0) + 1,
@@ -33411,12 +33822,12 @@ function dependencyOrder(tracks) {
33411
33822
  for (const track of tracks) visit(track.id);
33412
33823
  return ordered;
33413
33824
  }
33414
- function deriveArchiveBatchInput(input) {
33825
+ function deriveMaterializedArchiveBatch(input) {
33415
33826
  const root = safeProjectRoot(input.projectRoot);
33416
33827
  const validation = requireCurrentProject(root);
33417
- const operationsPath = join7(cadreRoot(root), "operations");
33418
- const activeOperation = existsSync9(operationsPath) ? readdirSync6(operationsPath).filter((file2) => file2.endsWith(".json")).map(
33419
- (file2) => JSON.parse(readFileSync7(join7(operationsPath, file2), "utf8"))
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"))
33420
33831
  ).find((operation) => operation.action === "archive" && operation.status === "in_progress") : void 0;
33421
33832
  const selectedTracks = input.selectedTracks?.length ? [...new Set(input.selectedTracks)] : activeOperation?.selectedTracks ?? dependencyOrder(
33422
33833
  validation.tracks.filter((track) => track.status === "completed" && track.location === `tracks/${track.id}`)
@@ -33444,6 +33855,62 @@ function deriveArchiveBatchInput(input) {
33444
33855
  updates
33445
33856
  };
33446
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
+ }
33447
33914
  function assertArchiveUpdate(path, selected) {
33448
33915
  if (path === "patterns/index.md" || /^patterns\/[a-z0-9]+(?:-[a-z0-9]+)*\.md$/.test(path)) return;
33449
33916
  const seed = path.match(/^tracks\/([a-z0-9]+(?:-[a-z0-9]+)*)\/learning\.md$/);
@@ -33453,18 +33920,18 @@ function assertArchiveUpdate(path, selected) {
33453
33920
  function directorySnapshot(path) {
33454
33921
  const files = [];
33455
33922
  function visit(directory) {
33456
- for (const entry of readdirSync6(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
33457
- 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);
33458
33925
  if (entry.isSymbolicLink()) throw new Error(`refusing archive source symbolic link ${target}`);
33459
33926
  if (entry.isDirectory()) visit(target);
33460
- 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") });
33461
33928
  else throw new Error(`unsupported archive source entry ${target}`);
33462
33929
  }
33463
33930
  }
33464
33931
  visit(path);
33465
33932
  return files;
33466
33933
  }
33467
- function previewArchiveBatch(input) {
33934
+ function previewMaterializedArchiveBatch(input) {
33468
33935
  if (!BATCH_ID.test(input.batchId)) throw new Error("invalid archive batchId");
33469
33936
  if (!SHA3.test(input.baseCommit)) throw new Error("baseCommit must be a Git commit SHA");
33470
33937
  if (!Number.isFinite(Date.parse(input.approvedAt))) throw new Error("approvedAt must be an ISO timestamp");
@@ -33473,8 +33940,8 @@ function previewArchiveBatch(input) {
33473
33940
  }
33474
33941
  if (input.selectedTracks.some((trackId) => !TRACK_ID3.test(trackId))) throw new Error("invalid selected track ID");
33475
33942
  const root = safeProjectRoot(input.projectRoot);
33476
- const operationPath = join7(cadreRoot(root), "operations", `${input.batchId}.json`);
33477
- 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;
33478
33945
  if (existingOperation && (existingOperation.action !== "archive" || existingOperation.status !== "in_progress" || existingOperation.baseCommit !== input.baseCommit || JSON.stringify(existingOperation.selectedTracks) !== JSON.stringify(input.selectedTracks))) {
33479
33946
  throw new Error(`archive batch ${input.batchId} does not match the approved input`);
33480
33947
  }
@@ -33495,9 +33962,9 @@ function previewArchiveBatch(input) {
33495
33962
  if (existingOperation && existingOperation.approvalDigest !== approvalDigest) {
33496
33963
  throw new Error(`archive batch ${input.batchId} content differs from its approved journal`);
33497
33964
  }
33498
- const activeOperations = join7(cadreRoot(root), "operations");
33499
- const unfinished = existsSync9(activeOperations) ? readdirSync6(activeOperations).filter((file2) => file2.endsWith(".json")).find((file2) => {
33500
- const operation2 = JSON.parse(readFileSync7(join7(activeOperations, file2), "utf8"));
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"));
33501
33968
  return operation2.status === "in_progress";
33502
33969
  }) : void 0;
33503
33970
  if (unfinished && unfinished !== `${input.batchId}.json`) {
@@ -33512,9 +33979,9 @@ function previewArchiveBatch(input) {
33512
33979
  if (!pending && !completed || state.operation != null) {
33513
33980
  throw new Error(`${trackId} is not an eligible completed track`);
33514
33981
  }
33515
- const sourcePath = join7(cadreRoot(root), pending ? "tracks" : "archive", trackId);
33516
- const targetPath = join7(cadreRoot(root), "archive", trackId);
33517
- if (pending && existsSync9(targetPath)) throw new Error(`archive target already exists for ${trackId}`);
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}`);
33518
33985
  return { trackId, sourcePath, targetPath, state: { ...state, status: "archived" }, needsMove: pending };
33519
33986
  });
33520
33987
  const proposedTracks = validation.tracks.map((track) => selected.has(track.id) ? { ...track, status: "archived", location: `archive/${track.id}` } : track);
@@ -33534,6 +34001,7 @@ function previewArchiveBatch(input) {
33534
34001
  selectedTracks: [...input.selectedTracks],
33535
34002
  completedTracks: [],
33536
34003
  approvedArtifacts,
34004
+ approvedArtifactHashes: updates.map((update) => ({ path: update.path, sha256: contentHash(update.content) })),
33537
34005
  artifactProgress: [],
33538
34006
  approvedAt: input.approvedAt,
33539
34007
  approvalDigest,
@@ -33546,12 +34014,12 @@ function previewArchiveBatch(input) {
33546
34014
  artifactProgress: [...moveArtifacts, ...updateArtifacts, "tracks.md"]
33547
34015
  };
33548
34016
  const current = {
33549
- project: readFileSync7(join7(cadreRoot(root), "project.json"), "utf8"),
33550
- 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"),
33551
34019
  sources: moves.map((move) => ({ trackId: move.trackId, files: directorySnapshot(move.sourcePath) })),
33552
34020
  updates: updates.map((update) => ({
33553
34021
  path: update.path,
33554
- 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
33555
34023
  }))
33556
34024
  };
33557
34025
  return {
@@ -33560,23 +34028,23 @@ function previewArchiveBatch(input) {
33560
34028
  operation,
33561
34029
  moves,
33562
34030
  writes: updates,
33563
- tracksPath: join7(cadreRoot(root), "tracks.md"),
34031
+ tracksPath: join8(cadreRoot(root), "tracks.md"),
33564
34032
  tracksContent,
33565
34033
  resuming: existingOperation != null,
33566
34034
  digest: hash5({ current, input, initialOperation, operation, moves: moves.map(({ trackId, state, needsMove }) => ({ trackId, state, needsMove })), updates, tracksContent })
33567
34035
  };
33568
34036
  }
33569
- function applyArchiveBatch(input, proposalDigest) {
33570
- const proposal = previewArchiveBatch(input);
34037
+ function applyMaterializedArchiveBatch(input, proposalDigest) {
34038
+ const proposal = previewMaterializedArchiveBatch(input);
33571
34039
  if (proposal.digest !== proposalDigest) throw new Error("archive batch proposal is stale; preview it again");
33572
- const currentOperation = existsSync9(proposal.operationPath) ? JSON.parse(readFileSync7(proposal.operationPath, "utf8")) : proposal.initialOperation;
33573
- if (!existsSync9(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json2(currentOperation));
33574
- mkdirSync3(join7(cadreRoot(input.projectRoot), "archive"), { recursive: true });
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 });
33575
34043
  const completedTracks = new Set(currentOperation.completedTracks);
33576
34044
  const artifactProgress = new Set(currentOperation.artifactProgress);
33577
34045
  for (const move of proposal.moves) {
33578
- if (move.needsMove) renameSync3(move.sourcePath, move.targetPath);
33579
- 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));
33580
34048
  completedTracks.add(move.trackId);
33581
34049
  artifactProgress.add(`archive/${move.trackId}`);
33582
34050
  writeApprovedFile(proposal.operationPath, json2({
@@ -33586,7 +34054,7 @@ function applyArchiveBatch(input, proposalDigest) {
33586
34054
  }));
33587
34055
  }
33588
34056
  for (const update of proposal.writes) {
33589
- writeApprovedFile(join7(cadreRoot(input.projectRoot), update.path), update.content);
34057
+ writeApprovedFile(join8(cadreRoot(input.projectRoot), update.path), update.content);
33590
34058
  artifactProgress.add(update.path);
33591
34059
  writeApprovedFile(proposal.operationPath, json2({
33592
34060
  ...currentOperation,
@@ -33609,18 +34077,18 @@ function previewArchiveBatchRecord(input) {
33609
34077
  if (!BATCH_ID.test(input.batchId)) throw new Error("invalid archive batchId");
33610
34078
  if (!SHA3.test(input.archiveCommit)) throw new Error("archiveCommit must be a Git commit SHA");
33611
34079
  const root = safeProjectRoot(input.projectRoot);
33612
- const operationPath = join7(cadreRoot(root), "operations", `${input.batchId}.json`);
33613
- const operationBody = readFileSync7(operationPath, "utf8");
34080
+ const operationPath = join8(cadreRoot(root), "operations", `${input.batchId}.json`);
34081
+ const operationBody = readFileSync8(operationPath, "utf8");
33614
34082
  const currentOperation = JSON.parse(operationBody);
33615
34083
  if (currentOperation.action !== "archive" || currentOperation.status !== "in_progress") {
33616
34084
  throw new Error(`${input.batchId} is not an in-progress archive batch`);
33617
34085
  }
33618
- const projectPath = join7(cadreRoot(root), "project.json");
33619
- const projectBody = readFileSync7(projectPath, "utf8");
34086
+ const projectPath = join8(cadreRoot(root), "project.json");
34087
+ const projectBody = readFileSync8(projectPath, "utf8");
33620
34088
  const currentProject = JSON.parse(projectBody);
33621
34089
  const states = currentOperation.selectedTracks.map((trackId) => {
33622
- const path = join7(cadreRoot(root), "archive", trackId, "state.json");
33623
- const body = readFileSync7(path, "utf8");
34090
+ const path = join8(cadreRoot(root), "archive", trackId, "state.json");
34091
+ const body = readFileSync8(path, "utf8");
33624
34092
  const current = JSON.parse(body);
33625
34093
  if (current.status !== "archived") throw new Error(`${trackId} is not archived`);
33626
34094
  return {
@@ -33661,8 +34129,8 @@ function previewArchiveBatchRecord(input) {
33661
34129
  digest: hash5({ operationBody, projectBody, states: states.map(({ path, body, state }) => ({ path, body, state })), operation, project })
33662
34130
  };
33663
34131
  }
33664
- function applyArchiveBatchRecord(input, proposalDigest) {
33665
- const proposal = previewArchiveBatchRecord(input);
34132
+ function applyArchiveBatchRecord(input, proposalDigest, preparedProposal) {
34133
+ const proposal = preparedProposal ?? previewArchiveBatchRecord(input);
33666
34134
  if (proposal.digest !== proposalDigest) throw new Error("archive record proposal is stale; preview it again");
33667
34135
  for (const state of proposal.states) writeApprovedFile(state.path, json2(state.state));
33668
34136
  writeApprovedFile(proposal.projectPath, json2(proposal.project));
@@ -33700,33 +34168,11 @@ var workflowQuestionSchema = external_exports.discriminatedUnion("type", [
33700
34168
  type: external_exports.literal("boolean"),
33701
34169
  default: external_exports.boolean().optional()
33702
34170
  }),
33703
- external_exports.object({
33704
- ...questionBase,
33705
- type: external_exports.literal("number"),
33706
- minimum: external_exports.number().optional(),
33707
- maximum: external_exports.number().optional(),
33708
- default: external_exports.number().optional()
33709
- }),
33710
- external_exports.object({
33711
- ...questionBase,
33712
- type: external_exports.literal("integer"),
33713
- minimum: external_exports.number().int().optional(),
33714
- maximum: external_exports.number().int().optional(),
33715
- default: external_exports.number().int().optional()
33716
- }),
33717
34171
  external_exports.object({
33718
34172
  ...questionBase,
33719
34173
  type: external_exports.literal("single_select"),
33720
34174
  options: external_exports.array(choiceSchema).min(2).max(10),
33721
34175
  default: external_exports.string().max(120).optional()
33722
- }),
33723
- external_exports.object({
33724
- ...questionBase,
33725
- type: external_exports.literal("multi_select"),
33726
- options: external_exports.array(choiceSchema).min(2).max(10),
33727
- minSelections: external_exports.number().int().min(0).optional(),
33728
- maxSelections: external_exports.number().int().min(1).optional(),
33729
- default: external_exports.array(external_exports.string().max(120)).max(10).optional()
33730
34176
  })
33731
34177
  ]);
33732
34178
  var workflowElicitationInputSchema = {
@@ -33763,22 +34209,6 @@ function questionSchema(question) {
33763
34209
  type: "boolean",
33764
34210
  ...question.default === void 0 ? {} : { default: question.default }
33765
34211
  };
33766
- case "number":
33767
- case "integer": {
33768
- if (question.minimum !== void 0 && question.maximum !== void 0 && question.minimum > question.maximum) {
33769
- throw new Error(`${question.id} minimum cannot exceed maximum`);
33770
- }
33771
- if (question.default !== void 0 && (question.minimum !== void 0 && question.default < question.minimum || question.maximum !== void 0 && question.default > question.maximum)) {
33772
- throw new Error(`${question.id} default must be within its numeric bounds`);
33773
- }
33774
- return {
33775
- ...common,
33776
- type: question.type,
33777
- ...question.minimum === void 0 ? {} : { minimum: question.minimum },
33778
- ...question.maximum === void 0 ? {} : { maximum: question.maximum },
33779
- ...question.default === void 0 ? {} : { default: question.default }
33780
- };
33781
- }
33782
34212
  case "single_select": {
33783
34213
  const values = choiceValues(question);
33784
34214
  if (question.default !== void 0 && !values.includes(question.default)) {
@@ -33791,27 +34221,6 @@ function questionSchema(question) {
33791
34221
  ...question.default === void 0 ? {} : { default: question.default }
33792
34222
  };
33793
34223
  }
33794
- case "multi_select": {
33795
- const values = choiceValues(question);
33796
- const minimum = question.minSelections ?? (question.required ? 1 : 0);
33797
- const maximum = question.maxSelections ?? values.length;
33798
- if (minimum > maximum || maximum > values.length) {
33799
- throw new Error(`${question.id} selection bounds are invalid`);
33800
- }
33801
- if (question.default?.some((value) => !values.includes(value))) {
33802
- throw new Error(`${question.id} defaults must match option values`);
33803
- }
33804
- return {
33805
- ...common,
33806
- type: "array",
33807
- items: {
33808
- anyOf: question.options.map((option) => ({ const: option.value, title: option.label }))
33809
- },
33810
- minItems: minimum,
33811
- maxItems: maximum,
33812
- ...question.default === void 0 ? {} : { default: question.default }
33813
- };
33814
- }
33815
34224
  }
33816
34225
  }
33817
34226
  function supportsFormElicitation(capabilities) {
@@ -33896,48 +34305,274 @@ function normalizeWorkflowElicitation(input, elicited) {
33896
34305
  }
33897
34306
 
33898
34307
  // src/mcp/proposals.ts
33899
- import { gunzipSync, gzipSync } from "node:zlib";
33900
- var MAX_TOKEN_CHARACTERS = 2 * 1024 * 1024;
34308
+ import { randomBytes } from "node:crypto";
34309
+ import {
34310
+ chmodSync,
34311
+ closeSync,
34312
+ existsSync as existsSync11,
34313
+ fstatSync,
34314
+ fsyncSync,
34315
+ lstatSync as lstatSync7,
34316
+ mkdirSync as mkdirSync5,
34317
+ openSync,
34318
+ readFileSync as readFileSync9,
34319
+ readdirSync as readdirSync9,
34320
+ unlinkSync as unlinkSync4,
34321
+ writeFileSync as writeFileSync6
34322
+ } from "node:fs";
34323
+ import { homedir as homedir2 } from "node:os";
34324
+ import { constants } from "node:fs";
34325
+ import { join as join9, resolve as resolve11 } from "node:path";
34326
+ var TOKEN_PREFIX = "cadre_pt1_";
34327
+ var TOKEN_PATTERN = /^cadre_pt1_[A-Za-z0-9_-]{32}$/;
34328
+ var RECORD_PATTERN = /^cadre_pt1_[A-Za-z0-9_-]{32}\.json$/;
33901
34329
  var MAX_PROPOSAL_BYTES = 8 * 1024 * 1024;
34330
+ var DEFAULT_MAX_RETAINED_PROPOSALS = 256;
34331
+ var DEFAULT_MAX_RETAINED_BYTES = 32 * 1024 * 1024;
34332
+ var DEFAULT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
33902
34333
  var envelopeSchema = external_exports.object({
33903
- version: external_exports.literal(1),
34334
+ version: external_exports.literal(2),
33904
34335
  kind: external_exports.string().min(1),
33905
34336
  input: external_exports.unknown(),
33906
- digest: external_exports.string().regex(/^[0-9a-f]{64}$/)
33907
- });
33908
- var proposalTokenSchema = external_exports.string().min(1).max(MAX_TOKEN_CHARACTERS);
33909
- function encodeProposalToken(kind, input, digest) {
33910
- return gzipSync(JSON.stringify({ version: 1, kind, input, digest })).toString("base64url");
33911
- }
33912
- function decodeProposalToken(kind, token) {
33913
- if (token.length > MAX_TOKEN_CHARACTERS) throw new Error("proposal token is too large");
33914
- let value;
33915
- try {
33916
- const compressed = Buffer.from(token, "base64url");
33917
- value = JSON.parse(gunzipSync(compressed, { maxOutputLength: MAX_PROPOSAL_BYTES }).toString("utf8"));
33918
- } catch (error51) {
33919
- throw new Error(`invalid proposal token: ${error51 instanceof Error ? error51.message : String(error51)}`);
34337
+ digest: external_exports.string().regex(/^[0-9a-f]{64}$/),
34338
+ createdAt: external_exports.iso.datetime()
34339
+ });
34340
+ var proposalTokenSchema = external_exports.string().regex(TOKEN_PATTERN, "invalid proposal token format");
34341
+ function defaultProposalRoot() {
34342
+ const cadreHome = process.env.CADRE_HOME ? resolve11(process.env.CADRE_HOME) : join9(homedir2(), ".cadre");
34343
+ return join9(cadreHome, "runtime", "proposals");
34344
+ }
34345
+ var ProposalTokenStore = class {
34346
+ root;
34347
+ maxRetainedProposals;
34348
+ maxRetainedBytes;
34349
+ maxAgeMs;
34350
+ now;
34351
+ constructor(options = {}) {
34352
+ this.root = resolve11(options.root ?? defaultProposalRoot());
34353
+ this.maxRetainedProposals = options.maxRetainedProposals ?? DEFAULT_MAX_RETAINED_PROPOSALS;
34354
+ this.maxRetainedBytes = options.maxRetainedBytes ?? DEFAULT_MAX_RETAINED_BYTES;
34355
+ this.maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
34356
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
34357
+ if (!Number.isInteger(this.maxRetainedProposals) || this.maxRetainedProposals < 1) {
34358
+ throw new Error("maxRetainedProposals must be a positive integer");
34359
+ }
34360
+ if (!Number.isInteger(this.maxRetainedBytes) || this.maxRetainedBytes < MAX_PROPOSAL_BYTES) {
34361
+ throw new Error(`maxRetainedBytes must be at least ${MAX_PROPOSAL_BYTES}`);
34362
+ }
34363
+ if (!Number.isFinite(this.maxAgeMs) || this.maxAgeMs <= 0) {
34364
+ throw new Error("maxAgeMs must be positive");
34365
+ }
34366
+ }
34367
+ issue(kind, input, digest) {
34368
+ const createdAt = this.now().toISOString();
34369
+ const serialized = `${JSON.stringify({ version: 2, kind, input, digest, createdAt })}
34370
+ `;
34371
+ const bytes = Buffer.byteLength(serialized, "utf8");
34372
+ if (bytes > MAX_PROPOSAL_BYTES) throw new Error("proposal is too large");
34373
+ envelopeSchema.parse(JSON.parse(serialized));
34374
+ this.prepareRoot();
34375
+ this.makeRoom(bytes);
34376
+ for (; ; ) {
34377
+ const token = `${TOKEN_PREFIX}${randomBytes(24).toString("base64url")}`;
34378
+ const path = this.pathFor(token);
34379
+ let descriptor = null;
34380
+ try {
34381
+ descriptor = openSync(
34382
+ path,
34383
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
34384
+ 384
34385
+ );
34386
+ writeFileSync6(descriptor, serialized, "utf8");
34387
+ fsyncSync(descriptor);
34388
+ return token;
34389
+ } catch (error51) {
34390
+ if (error51.code !== "EEXIST") throw error51;
34391
+ } finally {
34392
+ if (descriptor !== null) closeSync(descriptor);
34393
+ }
34394
+ }
33920
34395
  }
33921
- const envelope = envelopeSchema.parse(value);
33922
- if (envelope.kind !== kind) throw new Error(`proposal token is for ${envelope.kind}, not ${kind}`);
33923
- return { input: envelope.input, digest: envelope.digest };
33924
- }
34396
+ resolve(kind, token) {
34397
+ if (!TOKEN_PATTERN.test(token)) throw new Error("invalid proposal token format");
34398
+ this.prepareRoot();
34399
+ const path = this.pathFor(token);
34400
+ if (!existsSync11(path)) {
34401
+ throw new Error(
34402
+ "proposal token is unknown or no longer retained; request a new proposal from the matching command"
34403
+ );
34404
+ }
34405
+ let descriptor = null;
34406
+ try {
34407
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
34408
+ const stat = fstatSync(descriptor);
34409
+ if (!stat.isFile()) throw new Error("proposal token does not reference a regular runtime record");
34410
+ if ((stat.mode & 63) !== 0) throw new Error("proposal runtime record permissions are too broad");
34411
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
34412
+ throw new Error("proposal runtime record is owned by another user");
34413
+ }
34414
+ if (stat.size > MAX_PROPOSAL_BYTES) throw new Error("proposal record is too large");
34415
+ const envelope = envelopeSchema.parse(JSON.parse(readFileSync9(descriptor, "utf8")));
34416
+ if (this.now().getTime() - Date.parse(envelope.createdAt) > this.maxAgeMs) {
34417
+ closeSync(descriptor);
34418
+ descriptor = null;
34419
+ this.unlinkRecord(path);
34420
+ throw new Error("proposal token has expired; request a new proposal from the matching command");
34421
+ }
34422
+ if (envelope.kind !== kind) throw new Error(`proposal token is for ${envelope.kind}, not ${kind}`);
34423
+ return { input: envelope.input, digest: envelope.digest };
34424
+ } catch (error51) {
34425
+ if (error51.code === "ELOOP") {
34426
+ throw new Error("refusing proposal token through a symbolic link");
34427
+ }
34428
+ if (error51.code === "ENOENT") {
34429
+ throw new Error(
34430
+ "proposal token is unknown or no longer retained; request a new proposal from the matching command"
34431
+ );
34432
+ }
34433
+ throw error51;
34434
+ } finally {
34435
+ if (descriptor !== null) closeSync(descriptor);
34436
+ }
34437
+ }
34438
+ prepareRoot() {
34439
+ mkdirSync5(this.root, { recursive: true, mode: 448 });
34440
+ const stat = lstatSync7(this.root);
34441
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
34442
+ throw new Error(`proposal runtime root is not a regular directory: ${this.root}`);
34443
+ }
34444
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
34445
+ throw new Error(`proposal runtime root is owned by another user: ${this.root}`);
34446
+ }
34447
+ if ((stat.mode & 63) !== 0) chmodSync(this.root, 448);
34448
+ }
34449
+ pathFor(token) {
34450
+ return join9(this.root, `${token}.json`);
34451
+ }
34452
+ records() {
34453
+ const records = [];
34454
+ for (const entry of readdirSync9(this.root)) {
34455
+ if (!RECORD_PATTERN.test(entry)) continue;
34456
+ const path = join9(this.root, entry);
34457
+ let stat;
34458
+ try {
34459
+ stat = lstatSync7(path);
34460
+ } catch (error51) {
34461
+ if (error51.code === "ENOENT") continue;
34462
+ throw error51;
34463
+ }
34464
+ if (!stat.isFile() || stat.isSymbolicLink()) continue;
34465
+ let createdAt = stat.mtimeMs;
34466
+ try {
34467
+ const envelope = envelopeSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34468
+ createdAt = Date.parse(envelope.createdAt);
34469
+ } catch {
34470
+ }
34471
+ records.push({ path, bytes: stat.size, createdAt });
34472
+ }
34473
+ return records.sort((left, right) => left.createdAt - right.createdAt);
34474
+ }
34475
+ makeRoom(incomingBytes) {
34476
+ const now = this.now().getTime();
34477
+ let records = this.records();
34478
+ for (const record2 of records) {
34479
+ if (now - record2.createdAt <= this.maxAgeMs) continue;
34480
+ this.unlinkRecord(record2.path);
34481
+ }
34482
+ records = this.records();
34483
+ let retainedBytes = records.reduce((total, record2) => total + record2.bytes, 0);
34484
+ while (records.length >= this.maxRetainedProposals || retainedBytes + incomingBytes > this.maxRetainedBytes) {
34485
+ const oldest = records.shift();
34486
+ if (!oldest) break;
34487
+ this.unlinkRecord(oldest.path);
34488
+ retainedBytes -= oldest.bytes;
34489
+ }
34490
+ }
34491
+ unlinkRecord(path) {
34492
+ try {
34493
+ unlinkSync4(path);
34494
+ } catch (error51) {
34495
+ if (error51.code !== "ENOENT") throw error51;
34496
+ }
34497
+ }
34498
+ };
33925
34499
 
33926
34500
  // src/mcp/server.ts
33927
- function result(value, summary) {
34501
+ function result(value, summary = "Cadre operation completed.") {
33928
34502
  return {
33929
- content: [{ type: "text", text: summary ?? JSON.stringify(value, null, 2) }],
34503
+ content: [{ type: "text", text: summary }],
33930
34504
  structuredContent: value
33931
34505
  };
33932
34506
  }
33933
- function proposalResult(kind, input, value) {
33934
- return result({
33935
- ...value,
33936
- proposalToken: encodeProposalToken(kind, input, value.digest)
33937
- });
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
+ }
34523
+ function sha256(content) {
34524
+ return createHash8("sha256").update(content).digest("hex");
34525
+ }
34526
+ function artifact(path, content) {
34527
+ return { path, sha256: sha256(content) };
34528
+ }
34529
+ function jsonArtifact(path, value) {
34530
+ return artifact(path, `${JSON.stringify(value, null, 2)}
34531
+ `);
34532
+ }
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;
33938
34550
  }
33939
- function proposalInputSchema() {
33940
- return { proposalToken: proposalTokenSchema };
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 };
33941
34576
  }
33942
34577
  function failure(error51) {
33943
34578
  const serialized = serializeCadreError(error51);
@@ -33960,6 +34595,57 @@ function serializableValidation(validation) {
33960
34595
  warnings: validation.warnings
33961
34596
  };
33962
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
+ }
33963
34649
  var PLAN_VALIDATION_STATUSES = [
33964
34650
  "drafting-spec",
33965
34651
  "drafting-plan",
@@ -33971,6 +34657,36 @@ var PLAN_VALIDATION_STATUSES = [
33971
34657
  ];
33972
34658
  var MAX_DRAFT_PLAN_CHARACTERS = 256 * 1024;
33973
34659
  function createCadreServer() {
34660
+ const proposalTokens = new ProposalTokenStore();
34661
+ function proposalResult(kind, input, value) {
34662
+ return result({
34663
+ commandStatus: "approval_required",
34664
+ ...value,
34665
+ proposalToken: proposalTokens.issue(kind, input, value.digest)
34666
+ });
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
+ }
33974
34690
  const server = new McpServer(
33975
34691
  { name: "cadre", version: CADRE_RUNTIME_VERSION },
33976
34692
  {
@@ -33978,8 +34694,9 @@ function createCadreServer() {
33978
34694
  "Cadre provides deterministic, versioned templates and narrow project-state operations.",
33979
34695
  "Read every existing artifact before proposing edits. Never infer file contents.",
33980
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.",
33981
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.",
33982
- "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.",
33983
34700
  "Cadre state is resumable: inspect project_status once at command entry and reserve state_validate for final mutation gates.",
33984
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."
33985
34702
  ].join(" ")
@@ -33987,7 +34704,7 @@ function createCadreServer() {
33987
34704
  );
33988
34705
  server.registerTool("workflow_elicit", {
33989
34706
  title: "Collect Cadre workflow input",
33990
- description: "Present one client-native Cadre approval or clarification form. This read-only tool never grants approval or mutates state. Do not call it when active task context reports approval policy never, including Codex Full Access; ask one short chat question instead. Otherwise bind approval forms to the current proposal digest or immutable verification checkpoint, never request secrets, and use its chat fallback exactly once when form elicitation is unavailable.",
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.",
33991
34708
  inputSchema: workflowElicitationInputSchema,
33992
34709
  annotations: { readOnlyHint: true, openWorldHint: false }
33993
34710
  }, async (input) => {
@@ -34018,26 +34735,6 @@ function createCadreServer() {
34018
34735
  async () => ({ contents: [{ uri: template.uri, mimeType: template.mimeType, text: template.content }] })
34019
34736
  );
34020
34737
  }
34021
- server.registerTool("template_catalog", {
34022
- title: "List Cadre templates",
34023
- description: "List immutable template identifiers, URIs, media types, and content hashes.",
34024
- annotations: { readOnlyHint: true, openWorldHint: false }
34025
- }, async () => result({
34026
- templateSetVersion: TEMPLATE_SET_VERSION,
34027
- templates: templateCatalog().map(({ content: _content, ...template }) => template)
34028
- }));
34029
- server.registerTool("template_get", {
34030
- title: "Get a Cadre template",
34031
- description: "Read one immutable, versioned Cadre template by logical identifier.",
34032
- inputSchema: { id: external_exports.enum(TEMPLATE_IDS) },
34033
- annotations: { readOnlyHint: true, openWorldHint: false }
34034
- }, async ({ id }) => {
34035
- try {
34036
- return result(getTemplate(id));
34037
- } catch (error51) {
34038
- return failure(error51);
34039
- }
34040
- });
34041
34738
  server.registerTool("template_get_many", {
34042
34739
  title: "Get multiple Cadre templates",
34043
34740
  description: "Read an ordered set of immutable, versioned Cadre templates in one call.",
@@ -34045,7 +34742,7 @@ function createCadreServer() {
34045
34742
  annotations: { readOnlyHint: true, openWorldHint: false }
34046
34743
  }, async ({ ids }) => {
34047
34744
  try {
34048
- return result({ templateSetVersion: TEMPLATE_SET_VERSION, templates: getTemplates(ids) });
34745
+ return templateResult(getTemplates(ids).map(describeTemplate));
34049
34746
  } catch (error51) {
34050
34747
  return failure(error51);
34051
34748
  }
@@ -34059,21 +34756,75 @@ function createCadreServer() {
34059
34756
  try {
34060
34757
  return result({
34061
34758
  templateSetVersion: TEMPLATE_SET_VERSION,
34062
- templates: resolveStyleguides(technologies)
34063
- });
34759
+ templates: resolveStyleguides(technologies).map((template) => {
34760
+ const { content: _content, ...descriptor } = describeTemplate(template);
34761
+ return descriptor;
34762
+ })
34763
+ }, "Resolved the default Cadre styleguide set.");
34064
34764
  } catch (error51) {
34065
34765
  return failure(error51);
34066
34766
  }
34067
34767
  });
34068
34768
  server.registerTool("project_status", {
34069
34769
  title: "Read Cadre project status",
34070
- description: "Read and summarize current project and track checkpoints, including resumable operations.",
34071
- 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
+ },
34072
34777
  annotations: { readOnlyHint: true, openWorldHint: false }
34073
- }, async ({ projectRoot }) => {
34778
+ }, async ({ projectRoot, view, trackId, executionId }) => {
34074
34779
  try {
34075
- const status = formatStatus(safeProjectRoot(projectRoot));
34076
- 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}.`);
34077
34828
  } catch (error51) {
34078
34829
  return failure(error51);
34079
34830
  }
@@ -34090,6 +34841,65 @@ function createCadreServer() {
34090
34841
  return failure(error51);
34091
34842
  }
34092
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
+ });
34093
34903
  server.registerTool("execution_graph_validate", {
34094
34904
  title: "Validate a track execution graph",
34095
34905
  description: "Compile and validate phase/task dependencies and derived manual-verification barriers from an approved plan.",
@@ -34098,9 +34908,9 @@ function createCadreServer() {
34098
34908
  }, async ({ projectRoot, trackId }) => {
34099
34909
  try {
34100
34910
  const root = safeProjectRoot(projectRoot);
34101
- const statePath = join8(root, ".cadre", "tracks", trackId, "state.json");
34102
- const planPath = join8(root, ".cadre", "tracks", trackId, "plan.md");
34103
- const state = JSON.parse(readFileSync8(statePath, "utf8"));
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"));
34104
34914
  const errors = [];
34105
34915
  const graph = parsePlan(planPath, errors);
34106
34916
  validatePlanGraph(planPath, graph, state.status ?? "planned", errors);
@@ -34109,26 +34919,6 @@ function createCadreServer() {
34109
34919
  return failure(error51);
34110
34920
  }
34111
34921
  });
34112
- server.registerTool("execution_graph_validate_draft", {
34113
- title: "Validate a draft execution graph",
34114
- description: "Compile and validate an unapproved plan supplied as Markdown without reading or writing project files.",
34115
- inputSchema: {
34116
- planMarkdown: external_exports.string().min(1).max(MAX_DRAFT_PLAN_CHARACTERS),
34117
- targetStatus: external_exports.enum(PLAN_VALIDATION_STATUSES),
34118
- sourceLabel: external_exports.string().min(1).max(200).regex(/^[^\r\n]+$/).optional()
34119
- },
34120
- annotations: { readOnlyHint: true, openWorldHint: false }
34121
- }, async ({ planMarkdown, targetStatus, sourceLabel }) => {
34122
- try {
34123
- const label = sourceLabel ?? "<draft-plan>";
34124
- const errors = [];
34125
- const graph = parsePlanContent(planMarkdown, label, errors);
34126
- validatePlanGraph(label, graph, targetStatus, errors);
34127
- return result({ valid: errors.length === 0, graph, errors });
34128
- } catch (error51) {
34129
- return failure(error51);
34130
- }
34131
- });
34132
34922
  const reviewCompleteSchema = {
34133
34923
  projectRoot: external_exports.string().min(1),
34134
34924
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
@@ -34136,67 +34926,118 @@ function createCadreServer() {
34136
34926
  approval: external_exports.string().min(1),
34137
34927
  acceptedRisks: external_exports.array(external_exports.string().min(1)).optional()
34138
34928
  };
34139
- server.registerTool("review_complete_preview", {
34140
- title: "Preview clean review completion",
34141
- description: "Preview the exact clean-review cycle, completed track state, and derived index behind one digest.",
34142
- inputSchema: reviewCompleteSchema,
34143
- annotations: { readOnlyHint: true, openWorldHint: false }
34144
- }, async (input) => {
34145
- try {
34146
- const derived = deriveReviewCompleteInput(input);
34147
- return proposalResult("review_complete", derived, previewReviewComplete(derived));
34148
- } catch (error51) {
34149
- return failure(error51);
34150
- }
34151
- });
34152
- server.registerTool("review_complete_apply", {
34153
- title: "Apply clean review completion",
34154
- description: "Apply an approved clean-review transition only while its exact state and index preview remain current.",
34155
- inputSchema: proposalInputSchema(),
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),
34156
34933
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34157
- }, async ({ proposalToken }) => {
34934
+ }, async (input) => {
34158
34935
  try {
34159
- const proposal = decodeProposalToken("review_complete", proposalToken);
34160
- return result(applyReviewComplete(proposal.input, proposal.digest));
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);
34959
+ const preview = previewReviewComplete(derived);
34960
+ return proposalResult("review_complete", derived, {
34961
+ digest: preview.digest,
34962
+ trackId: derived.trackId,
34963
+ reviewedHead: derived.reviewedHead,
34964
+ commitRange: derived.commitRange,
34965
+ targetStatus: preview.state.status,
34966
+ files: [
34967
+ jsonArtifact(preview.statePath, preview.state),
34968
+ artifact(preview.tracksPath, preview.tracksContent)
34969
+ ]
34970
+ });
34161
34971
  } catch (error51) {
34162
34972
  return failure(error51);
34163
34973
  }
34164
34974
  });
34165
- 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 = {
34166
34984
  projectRoot: external_exports.string().min(1),
34985
+ candidateId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34167
34986
  selectedTracks: external_exports.array(external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)).min(1).optional(),
34168
- updates: external_exports.array(external_exports.discriminatedUnion("kind", [
34169
- external_exports.object({ kind: external_exports.literal("pattern"), slug: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/), content: external_exports.string() }),
34170
- external_exports.object({ kind: external_exports.literal("pattern_index"), content: external_exports.string() }),
34171
- external_exports.object({
34172
- kind: external_exports.literal("active_track_seed"),
34173
- trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34174
- content: external_exports.string()
34175
- })
34176
- ]))
34987
+ updates: external_exports.array(archiveCandidateUpdateSchema)
34177
34988
  };
34178
- server.registerTool("archive_batch_preview", {
34179
- title: "Preview complete archive batch",
34180
- description: "Preview selected moves, lifecycle states, pattern/seed writes, operation journal, and the post-archive track index together.",
34181
- inputSchema: archiveBatchSchema,
34182
- annotations: { readOnlyHint: true, openWorldHint: false }
34183
- }, async (input) => {
34184
- try {
34185
- const derived = deriveArchiveBatchInput(input);
34186
- return proposalResult("archive_batch", derived, previewArchiveBatch(derived));
34187
- } catch (error51) {
34188
- return failure(error51);
34189
- }
34190
- });
34191
- server.registerTool("archive_batch_apply", {
34192
- title: "Apply complete archive batch",
34193
- description: "Journal and apply one approved archive batch only while its complete preview remains current.",
34194
- inputSchema: proposalInputSchema(),
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),
34195
34993
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34196
- }, async ({ proposalToken }) => {
34994
+ }, async (input) => {
34197
34995
  try {
34198
- const proposal = decodeProposalToken("archive_batch", proposalToken);
34199
- return result(applyArchiveBatch(proposal.input, proposal.digest));
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, {
35026
+ digest: preview.digest,
35027
+ batchId: derived.batchId,
35028
+ selectedTracks: derived.selectedTracks,
35029
+ operationPath: preview.operationPath,
35030
+ checkpoint: preview.operation.checkpoint,
35031
+ resuming: preview.resuming,
35032
+ moves: preview.moves.map(({ trackId, sourcePath, targetPath, needsMove }) => ({
35033
+ trackId,
35034
+ sourcePath,
35035
+ targetPath,
35036
+ needsMove
35037
+ })),
35038
+ writes: preview.writes.map((write) => artifact(write.path, write.content)),
35039
+ tracks: artifact(preview.tracksPath, preview.tracksContent)
35040
+ });
34200
35041
  } catch (error51) {
34201
35042
  return failure(error51);
34202
35043
  }
@@ -34205,28 +35046,28 @@ function createCadreServer() {
34205
35046
  projectRoot: external_exports.string().min(1),
34206
35047
  batchId: external_exports.string().regex(/^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
34207
35048
  };
34208
- server.registerTool("archive_batch_record_preview", {
34209
- title: "Preview archive provenance record",
34210
- 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.",
34211
35052
  inputSchema: archiveRecordSchema,
34212
- annotations: { readOnlyHint: true, openWorldHint: false }
35053
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34213
35054
  }, async (input) => {
34214
35055
  try {
35056
+ requireCurrentProject2(input.projectRoot);
34215
35057
  const derived = deriveArchiveBatchRecordInput(input);
34216
- return proposalResult("archive_batch_record", derived, previewArchiveBatchRecord(derived));
34217
- } catch (error51) {
34218
- return failure(error51);
34219
- }
34220
- });
34221
- server.registerTool("archive_batch_record_apply", {
34222
- title: "Record archive provenance",
34223
- description: "Record an approved batch's immutable archive commit and complete its journal behind a stale-state digest.",
34224
- inputSchema: proposalInputSchema(),
34225
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34226
- }, async ({ proposalToken }) => {
34227
- try {
34228
- const proposal = decodeProposalToken("archive_batch_record", proposalToken);
34229
- return result(applyArchiveBatchRecord(proposal.input, proposal.digest));
35058
+ const preview = previewArchiveBatchRecord(derived);
35059
+ const applied = applyArchiveBatchRecord(derived, preview.digest, preview);
35060
+ return result({
35061
+ commandStatus: "applied",
35062
+ batchId: derived.batchId,
35063
+ archiveCommit: derived.archiveCommit,
35064
+ checkpoint: applied.operation.checkpoint,
35065
+ digest: preview.digest,
35066
+ changedPaths: [applied.operationPath, applied.projectPath, ...applied.states.map((state) => state.path)],
35067
+ changedCount: applied.states.length + 2,
35068
+ valid: applied.valid,
35069
+ derivedStateCurrent: applied.derivedStateCurrent
35070
+ });
34230
35071
  } catch (error51) {
34231
35072
  return failure(error51);
34232
35073
  }
@@ -34238,28 +35079,33 @@ function createCadreServer() {
34238
35079
  approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES).optional(),
34239
35080
  maxWorkers: external_exports.number().int().min(1).max(32).optional().default(3)
34240
35081
  };
34241
- server.registerTool("execution_start_preview", {
34242
- title: "Preview implementation execution",
34243
- 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.",
34244
35085
  inputSchema: executionStartSchema,
34245
- annotations: { readOnlyHint: true, openWorldHint: false }
35086
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34246
35087
  }, async (input) => {
34247
35088
  try {
35089
+ requireCurrentProject2(input.projectRoot);
34248
35090
  const derived = deriveExecutionStartInput(input);
34249
- return proposalResult("execution_start", derived, previewExecutionStart(derived));
34250
- } catch (error51) {
34251
- return failure(error51);
34252
- }
34253
- });
34254
- server.registerTool("execution_start_apply", {
34255
- title: "Start implementation execution",
34256
- description: "Write the approved implementation journal and operation only when its preview digest is unchanged.",
34257
- inputSchema: proposalInputSchema(),
34258
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34259
- }, async ({ proposalToken }) => {
34260
- try {
34261
- const proposal = decodeProposalToken("execution_start", proposalToken);
34262
- return result(applyExecutionStart(proposal.input, proposal.digest));
35091
+ const preview = previewExecutionStart(derived);
35092
+ const applied = applyExecutionStart(derived, preview.digest, preview);
35093
+ return result({
35094
+ commandStatus: "applied",
35095
+ journalPath: applied.journalPath,
35096
+ statePath: applied.statePath,
35097
+ execution: {
35098
+ executionId: applied.journal.executionId,
35099
+ trackId: applied.journal.trackId,
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,
35105
+ nodeCount: Object.keys(applied.journal.nodes).length
35106
+ },
35107
+ derivedStatus: executionSchedulerView(applied.journal)
35108
+ });
34263
35109
  } catch (error51) {
34264
35110
  return failure(error51);
34265
35111
  }
@@ -34281,31 +35127,23 @@ function createCadreServer() {
34281
35127
  authorization: external_exports.string().min(1).optional(),
34282
35128
  blocker: external_exports.string().min(1).optional()
34283
35129
  };
34284
- server.registerTool("execution_checkpoint_preview", {
34285
- title: "Preview an execution checkpoint",
34286
- description: "Translate one semantic execution event into the complete legal journal transition sequence.",
34287
- inputSchema: executionCheckpointSchema,
34288
- annotations: { readOnlyHint: true, openWorldHint: false }
34289
- }, async (input) => {
34290
- try {
34291
- return proposalResult(
34292
- "execution_checkpoint",
34293
- input,
34294
- previewExecutionCheckpoint(input)
34295
- );
34296
- } catch (error51) {
34297
- return failure(error51);
34298
- }
34299
- });
34300
- server.registerTool("execution_checkpoint_apply", {
35130
+ server.registerTool("execution_checkpoint", {
34301
35131
  title: "Apply an execution checkpoint",
34302
- description: "Apply one previewed semantic execution event atomically.",
34303
- inputSchema: proposalInputSchema(),
35132
+ description: "Atomically validate and apply one already-authorized semantic execution event.",
35133
+ inputSchema: executionCheckpointSchema,
34304
35134
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34305
- }, async ({ proposalToken }) => {
35135
+ }, async (input) => {
34306
35136
  try {
34307
- const proposal = decodeProposalToken("execution_checkpoint", proposalToken);
34308
- return result(applyExecutionCheckpoint(proposal.input, proposal.digest));
35137
+ requireCurrentProject2(input.projectRoot);
35138
+ const preview = previewExecutionCheckpoint(input);
35139
+ const applied = applyExecutionCheckpoint(input, preview.digest, preview);
35140
+ return result({
35141
+ commandStatus: "applied",
35142
+ path: applied.path,
35143
+ transition: applied.transition,
35144
+ checkpoint: applied.journal.checkpoint,
35145
+ derivedStatus: executionSchedulerView(applied.journal, [input.nodeId])
35146
+ });
34309
35147
  } catch (error51) {
34310
35148
  return failure(error51);
34311
35149
  }
@@ -34316,12 +35154,14 @@ function createCadreServer() {
34316
35154
  inputSchema: {
34317
35155
  projectRoot: external_exports.string().min(1),
34318
35156
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34319
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
35157
+ executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
35158
+ nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/).optional()
34320
35159
  },
34321
35160
  annotations: { readOnlyHint: true, openWorldHint: false }
34322
35161
  }, async (input) => {
34323
35162
  try {
34324
- return result(executionStatus(input.projectRoot, input.trackId, input.executionId));
35163
+ const status = executionStatus(input.projectRoot, input.trackId, input.executionId);
35164
+ return result(compactExecutionStatus(status.journal, input.nodeId));
34325
35165
  } catch (error51) {
34326
35166
  return failure(error51);
34327
35167
  }
@@ -34331,28 +35171,27 @@ function createCadreServer() {
34331
35171
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34332
35172
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
34333
35173
  };
34334
- server.registerTool("execution_finish_preview", {
34335
- title: "Preview completed implementation execution",
34336
- description: "Verify all DAG nodes, plan evidence, and worktree cleanup before proposing ready-for-review state and its derived tracks index under one digest.",
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.",
34337
35177
  inputSchema: executionFinishSchema,
34338
- annotations: { readOnlyHint: true, openWorldHint: false }
35178
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34339
35179
  }, async (input) => {
34340
35180
  try {
35181
+ requireCurrentProject2(input.projectRoot);
34341
35182
  const derived = deriveExecutionFinishInput(input);
34342
- return proposalResult("execution_finish", derived, previewExecutionFinish(derived));
34343
- } catch (error51) {
34344
- return failure(error51);
34345
- }
34346
- });
34347
- server.registerTool("execution_finish_apply", {
34348
- title: "Complete implementation execution",
34349
- description: "Finalize an approved execution, ready-for-review state, and derived tracks index together only when the preview is unchanged.",
34350
- inputSchema: proposalInputSchema(),
34351
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34352
- }, async ({ proposalToken }) => {
34353
- try {
34354
- const proposal = decodeProposalToken("execution_finish", proposalToken);
34355
- return result(applyExecutionFinish(proposal.input, proposal.digest));
35183
+ const preview = previewExecutionFinish(derived);
35184
+ const applied = applyExecutionFinish(derived, preview.digest, preview);
35185
+ return result({
35186
+ commandStatus: "applied",
35187
+ executionId: derived.executionId,
35188
+ status: applied.journal.status,
35189
+ checkpoint: applied.journal.checkpoint,
35190
+ headCommit: applied.journal.headCommit,
35191
+ digest: preview.digest,
35192
+ changedPaths: [applied.journalPath, applied.statePath, applied.planPath, applied.tracksPath],
35193
+ changedCount: 4
35194
+ });
34356
35195
  } catch (error51) {
34357
35196
  return failure(error51);
34358
35197
  }
@@ -34363,124 +35202,146 @@ function createCadreServer() {
34363
35202
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
34364
35203
  nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/)
34365
35204
  };
34366
- server.registerTool("worktree_create_preview", {
34367
- title: "Preview a Cadre worker worktree",
34368
- description: "Resolve the constrained worker path, branch, and exact base commit without mutating Git.",
34369
- inputSchema: worktreeSchema,
34370
- annotations: { readOnlyHint: true, openWorldHint: false }
34371
- }, async (input) => {
34372
- try {
34373
- return proposalResult("worktree_create", input, previewWorktreeCreate(input));
34374
- } catch (error51) {
34375
- return failure(error51);
34376
- }
34377
- });
34378
- server.registerTool("worktree_create_apply", {
35205
+ server.registerTool("worktree_create", {
34379
35206
  title: "Create a Cadre worker worktree",
34380
- description: "Create or reconcile one approved constrained worker worktree using an unchanged preview digest.",
34381
- inputSchema: proposalInputSchema(),
34382
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34383
- }, async ({ proposalToken }) => {
34384
- try {
34385
- const proposal = decodeProposalToken("worktree_create", proposalToken);
34386
- return result(applyWorktreeCreate(proposal.input, proposal.digest));
34387
- } catch (error51) {
34388
- return failure(error51);
34389
- }
34390
- });
34391
- server.registerTool("integration_preview", {
34392
- title: "Preview worker integration",
34393
- 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.",
34394
35208
  inputSchema: worktreeSchema,
34395
- annotations: { readOnlyHint: true, openWorldHint: false }
35209
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34396
35210
  }, async (input) => {
34397
35211
  try {
34398
- 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}.`);
34399
35228
  } catch (error51) {
34400
35229
  return failure(error51);
34401
35230
  }
34402
35231
  });
34403
- server.registerTool("integration_apply", {
35232
+ server.registerTool("integration", {
34404
35233
  title: "Integrate a worker branch",
34405
- description: "Merge an approved worker branch without squashing; report conflicts without resolving them.",
34406
- 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),
34407
35236
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34408
- }, async ({ proposalToken }) => {
34409
- try {
34410
- const proposal = decodeProposalToken("worktree_integrate", proposalToken);
34411
- return result(applyWorktreeIntegration(proposal.input, proposal.digest));
34412
- } catch (error51) {
34413
- return failure(error51);
34414
- }
34415
- });
34416
- server.registerTool("worktree_cleanup_preview", {
34417
- title: "Preview worker cleanup",
34418
- description: "Verify a clean worker branch is fully integrated before proposing worktree and branch removal, including recovery after its node was already completed.",
34419
- inputSchema: worktreeSchema,
34420
- annotations: { readOnlyHint: true, openWorldHint: false }
34421
35237
  }, async (input) => {
34422
35238
  try {
34423
- 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}.`);
34424
35264
  } catch (error51) {
34425
35265
  return failure(error51);
34426
35266
  }
34427
35267
  });
34428
- server.registerTool("worktree_cleanup_apply", {
35268
+ server.registerTool("worktree_cleanup", {
34429
35269
  title: "Clean up an integrated worker",
34430
- description: "Remove only a clean, fully integrated Cadre worktree and its safely deletable branch, whether its journal node is integrated or already completed.",
34431
- inputSchema: proposalInputSchema(),
35270
+ description: "Atomically verify and remove only a clean, fully integrated Cadre worktree and safely deletable branch.",
35271
+ inputSchema: worktreeSchema,
34432
35272
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
34433
- }, async ({ proposalToken }) => {
34434
- try {
34435
- const proposal = decodeProposalToken("worktree_cleanup", proposalToken);
34436
- return result(applyWorktreeCleanup(proposal.input, proposal.digest));
34437
- } catch (error51) {
34438
- return failure(error51);
34439
- }
34440
- });
34441
- server.registerTool("worktree_status", {
34442
- title: "Read Cadre worktree status",
34443
- description: "List registered Cadre-managed worktrees and orphaned empty runtime directories.",
34444
- inputSchema: { projectRoot: external_exports.string().min(1) },
34445
- annotations: { readOnlyHint: true, openWorldHint: false }
34446
- }, async ({ projectRoot }) => {
35273
+ }, async (input) => {
34447
35274
  try {
34448
- 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}.`);
34449
35287
  } catch (error51) {
34450
35288
  return failure(error51);
34451
35289
  }
34452
35290
  });
34453
- const approvedFileSchema = external_exports.object({ path: external_exports.string().min(1), content: external_exports.string() });
34454
- const initSchema = {
35291
+ const initCandidateSchema = {
34455
35292
  projectRoot: external_exports.string().min(1),
34456
35293
  projectName: external_exports.string().min(1),
34457
35294
  context: external_exports.enum(["greenfield", "brownfield"]),
34458
35295
  gitDisposition: external_exports.enum(["existing", "initialize"]),
34459
35296
  baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).nullable(),
34460
35297
  approvedAt: external_exports.iso.datetime(),
34461
- 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)
34462
35300
  };
34463
- server.registerTool("project_init_preview", {
34464
- title: "Preview Cadre project initialization",
34465
- description: "Validate approved rendered artifacts and return the proposed .cadre file set and semantic digest without writing; approvedAt is audit metadata and does not affect the digest.",
34466
- inputSchema: initSchema,
34467
- annotations: { readOnlyHint: true, openWorldHint: false }
34468
- }, async (input) => {
34469
- try {
34470
- return proposalResult("project_init", input, previewProjectInit(input));
34471
- } catch (error51) {
34472
- return failure(error51);
34473
- }
34474
- });
34475
- server.registerTool("project_init_apply", {
34476
- title: "Apply approved Cadre project initialization",
34477
- description: "Atomically create .cadre only when the semantic proposal matches an approved preview digest; records approvedAt as audit metadata.",
34478
- inputSchema: proposalInputSchema(),
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),
34479
35305
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34480
- }, async ({ proposalToken }) => {
35306
+ }, async (input) => {
34481
35307
  try {
34482
- const proposal = decodeProposalToken("project_init", proposalToken);
34483
- return result(applyProjectInit(proposal.input, proposal.digest));
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, {
35340
+ runtimeVersion: preview.runtimeVersion,
35341
+ templateSetVersion: preview.templateSetVersion,
35342
+ files: preview.files.map(({ path, sha256: digest }) => ({ path, sha256: digest })),
35343
+ digest: preview.digest
35344
+ });
34484
35345
  } catch (error51) {
34485
35346
  return failure(error51);
34486
35347
  }
@@ -34492,6 +35353,7 @@ function createCadreServer() {
34492
35353
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34493
35354
  }, async ({ projectRoot }) => {
34494
35355
  try {
35356
+ requireCurrentProject2(projectRoot);
34495
35357
  const commit = resolveGitCommit(projectRoot);
34496
35358
  return result({ path: recordSetupCommit(projectRoot, commit), commit });
34497
35359
  } catch (error51) {
@@ -34505,33 +35367,29 @@ function createCadreServer() {
34505
35367
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34506
35368
  }, async ({ projectRoot }) => {
34507
35369
  try {
35370
+ requireCurrentProject2(projectRoot);
34508
35371
  return result({ path: recordGitInitialized(projectRoot), checkpoint: "commit-pending" });
34509
35372
  } catch (error51) {
34510
35373
  return failure(error51);
34511
35374
  }
34512
35375
  });
34513
- server.registerTool("tracks_render_preview", {
34514
- title: "Preview the derived tracks index",
34515
- 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.",
34516
35379
  inputSchema: { projectRoot: external_exports.string().min(1) },
34517
- annotations: { readOnlyHint: true, openWorldHint: false }
35380
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34518
35381
  }, async ({ projectRoot }) => {
34519
35382
  try {
34520
- const input = { projectRoot: safeProjectRoot(projectRoot) };
34521
- return proposalResult("tracks_render", input, renderTracksPreview(input.projectRoot));
34522
- } catch (error51) {
34523
- return failure(error51);
34524
- }
34525
- });
34526
- server.registerTool("tracks_render_apply", {
34527
- title: "Apply the derived tracks index",
34528
- description: "Rewrite tracks.md only when current state matches a human-approved preview digest.",
34529
- inputSchema: proposalInputSchema(),
34530
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34531
- }, async ({ proposalToken }) => {
34532
- try {
34533
- const proposal = decodeProposalToken("tracks_render", proposalToken);
34534
- return result({ path: writeTracks(proposal.input.projectRoot, proposal.digest) });
35383
+ const input = { projectRoot: requireCurrentProject2(projectRoot) };
35384
+ const preview = renderTracksPreview(input.projectRoot);
35385
+ const path = writeTracks(input.projectRoot, preview.digest, preview);
35386
+ return result({
35387
+ commandStatus: "applied",
35388
+ path: preview.path,
35389
+ sha256: sha256(preview.content),
35390
+ changed: preview.changed,
35391
+ writtenPath: path
35392
+ });
34535
35393
  } catch (error51) {
34536
35394
  return failure(error51);
34537
35395
  }
@@ -34542,7 +35400,7 @@ async function runCadreServer() {
34542
35400
  const server = createCadreServer();
34543
35401
  await server.connect(new StdioServerTransport());
34544
35402
  }
34545
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve10(process.argv[1])).href) {
35403
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve12(process.argv[1])).href) {
34546
35404
  runCadreServer().catch((error51) => {
34547
35405
  process.stderr.write(`${error51 instanceof Error ? error51.message : String(error51)}
34548
35406
  `);