cadre-ai 3.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2979,7 +2979,7 @@ var require_compile = __commonJS({
2979
2979
  const schOrFunc = root.refs[ref];
2980
2980
  if (schOrFunc)
2981
2981
  return schOrFunc;
2982
- let _sch = resolve9.call(this, root, ref);
2982
+ let _sch = resolve10.call(this, root, ref);
2983
2983
  if (_sch === void 0) {
2984
2984
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
2985
2985
  const { schemaId } = this.opts;
@@ -3006,7 +3006,7 @@ var require_compile = __commonJS({
3006
3006
  function sameSchemaEnv(s1, s2) {
3007
3007
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
3008
3008
  }
3009
- function resolve9(root, ref) {
3009
+ function resolve10(root, ref) {
3010
3010
  let sch;
3011
3011
  while (typeof (sch = this.refs[ref]) == "string")
3012
3012
  ref = sch;
@@ -3637,7 +3637,7 @@ var require_fast_uri = __commonJS({
3637
3637
  }
3638
3638
  return uri;
3639
3639
  }
3640
- function resolve9(baseURI, relativeURI, options) {
3640
+ function resolve10(baseURI, relativeURI, options) {
3641
3641
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3642
3642
  const resolved = resolveComponent(parse4(baseURI, schemelessOptions), parse4(relativeURI, schemelessOptions), schemelessOptions, true);
3643
3643
  schemelessOptions.skipEscape = true;
@@ -3895,7 +3895,7 @@ var require_fast_uri = __commonJS({
3895
3895
  var fastUri = {
3896
3896
  SCHEMES,
3897
3897
  normalize,
3898
- resolve: resolve9,
3898
+ resolve: resolve10,
3899
3899
  resolveComponent,
3900
3900
  equal,
3901
3901
  serialize,
@@ -28843,7 +28843,7 @@ var Protocol = class {
28843
28843
  return;
28844
28844
  }
28845
28845
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
28846
- await new Promise((resolve9) => setTimeout(resolve9, pollInterval));
28846
+ await new Promise((resolve10) => setTimeout(resolve10, pollInterval));
28847
28847
  options?.signal?.throwIfAborted();
28848
28848
  }
28849
28849
  } catch (error51) {
@@ -28860,7 +28860,7 @@ var Protocol = class {
28860
28860
  */
28861
28861
  request(request, resultSchema, options) {
28862
28862
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
28863
- return new Promise((resolve9, reject) => {
28863
+ return new Promise((resolve10, reject) => {
28864
28864
  const earlyReject = (error51) => {
28865
28865
  reject(error51);
28866
28866
  };
@@ -28938,7 +28938,7 @@ var Protocol = class {
28938
28938
  if (!parseResult.success) {
28939
28939
  reject(parseResult.error);
28940
28940
  } else {
28941
- resolve9(parseResult.data);
28941
+ resolve10(parseResult.data);
28942
28942
  }
28943
28943
  } catch (error51) {
28944
28944
  reject(error51);
@@ -29199,12 +29199,12 @@ var Protocol = class {
29199
29199
  }
29200
29200
  } catch {
29201
29201
  }
29202
- return new Promise((resolve9, reject) => {
29202
+ return new Promise((resolve10, reject) => {
29203
29203
  if (signal.aborted) {
29204
29204
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
29205
29205
  return;
29206
29206
  }
29207
- const timeoutId = setTimeout(resolve9, interval);
29207
+ const timeoutId = setTimeout(resolve10, interval);
29208
29208
  signal.addEventListener("abort", () => {
29209
29209
  clearTimeout(timeoutId);
29210
29210
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -30295,7 +30295,7 @@ var McpServer = class {
30295
30295
  let task = createTaskResult.task;
30296
30296
  const pollInterval = task.pollInterval ?? 5e3;
30297
30297
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
30298
- await new Promise((resolve9) => setTimeout(resolve9, pollInterval));
30298
+ await new Promise((resolve10) => setTimeout(resolve10, pollInterval));
30299
30299
  const updatedTask = await extra.taskStore.getTask(taskId);
30300
30300
  if (!updatedTask) {
30301
30301
  throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
@@ -30959,42 +30959,42 @@ var StdioServerTransport = class {
30959
30959
  this.onclose?.();
30960
30960
  }
30961
30961
  send(message) {
30962
- return new Promise((resolve9) => {
30962
+ return new Promise((resolve10) => {
30963
30963
  const json3 = serializeMessage(message);
30964
30964
  if (this._stdout.write(json3)) {
30965
- resolve9();
30965
+ resolve10();
30966
30966
  } else {
30967
- this._stdout.once("drain", resolve9);
30967
+ this._stdout.once("drain", resolve10);
30968
30968
  }
30969
30969
  });
30970
30970
  }
30971
30971
  };
30972
30972
 
30973
30973
  // src/mcp/server.ts
30974
- import { readFileSync as readFileSync7 } from "node:fs";
30975
- import { join as join7, resolve as resolve8 } from "node:path";
30974
+ import { readFileSync as readFileSync8 } from "node:fs";
30975
+ import { join as join8, resolve as resolve9 } from "node:path";
30976
30976
  import { pathToFileURL } from "node:url";
30977
30977
 
30978
30978
  // src/domain/init.ts
30979
30979
  import { createHash as createHash5 } from "node:crypto";
30980
30980
  import {
30981
- existsSync as existsSync6,
30981
+ existsSync as existsSync7,
30982
30982
  lstatSync as lstatSync3,
30983
30983
  mkdirSync as mkdirSync2,
30984
- readFileSync as readFileSync5,
30984
+ readFileSync as readFileSync6,
30985
30985
  renameSync as renameSync2,
30986
30986
  writeFileSync as writeFileSync3
30987
30987
  } from "node:fs";
30988
30988
  import { dirname as dirname3 } from "node:path";
30989
- import { isAbsolute, join as join4, relative as relative2, resolve as resolve5 } from "node:path";
30989
+ import { isAbsolute, join as join5, relative as relative2, resolve as resolve6 } from "node:path";
30990
30990
 
30991
30991
  // src/domain/state.ts
30992
30992
  import { createHash as createHash3 } from "node:crypto";
30993
- import { existsSync as existsSync4, lstatSync as lstatSync2, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
30994
- import { join as join2, resolve as resolve3 } from "node:path";
30993
+ import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
30994
+ import { join as join3, resolve as resolve4 } from "node:path";
30995
30995
 
30996
30996
  // src/domain/version.ts
30997
- var CADRE_RUNTIME_VERSION = "3.0.1";
30997
+ var CADRE_RUNTIME_VERSION = "3.1.0";
30998
30998
  var TEMPLATE_SET_VERSION = "v1";
30999
30999
 
31000
31000
  // src/domain/plan.ts
@@ -31023,16 +31023,12 @@ function graphDigest(graph) {
31023
31023
  };
31024
31024
  return createHash("sha256").update(JSON.stringify(normalized)).digest("hex");
31025
31025
  }
31026
- function parsePlan(path, errors = []) {
31027
- if (!existsSync(path)) {
31028
- errors.push(`${path}: missing plan`);
31029
- return { specRevision: null, planRevision: null, phases: [], digest: graphDigest({ specRevision: null, planRevision: null, phases: [] }) };
31030
- }
31026
+ function parsePlanContent(content, sourceLabel, errors = []) {
31031
31027
  const phases = [];
31032
31028
  let specRevision = null;
31033
31029
  let planRevision = null;
31034
31030
  let currentTask = null;
31035
- const lines = readFileSync(path, "utf8").split(/\r?\n/);
31031
+ const lines = content.split(/\r?\n/);
31036
31032
  for (const [index, line] of lines.entries()) {
31037
31033
  const lineNumber = index + 1;
31038
31034
  const spec = line.match(/^- Spec revision: (\d+)$/);
@@ -31059,8 +31055,8 @@ function parsePlan(path, errors = []) {
31059
31055
  const phaseDependencies = line.match(/^- Phase dependencies: (.+)$/);
31060
31056
  if (phaseDependencies) {
31061
31057
  const phase = phases.at(-1);
31062
- if (!phase) errors.push(`${path}:${lineNumber}: phase dependencies appear before a phase`);
31063
- else if (phase.dependencyDeclared) errors.push(`${path}:${lineNumber}: ${phase.id} has duplicate phase dependencies`);
31058
+ if (!phase) errors.push(`${sourceLabel}:${lineNumber}: phase dependencies appear before a phase`);
31059
+ else if (phase.dependencyDeclared) errors.push(`${sourceLabel}:${lineNumber}: ${phase.id} has duplicate phase dependencies`);
31064
31060
  else {
31065
31061
  phase.dependencies = dependencyList(phaseDependencies[1]);
31066
31062
  phase.dependencyDeclared = true;
@@ -31070,7 +31066,7 @@ function parsePlan(path, errors = []) {
31070
31066
  const phaseCommit = line.match(/^- Phase completion commit: (pending|`([0-9a-f]{7,40})`)$/);
31071
31067
  if (phaseCommit) {
31072
31068
  const phase = phases.at(-1);
31073
- if (!phase) errors.push(`${path}:${lineNumber}: phase completion commit appears before a phase`);
31069
+ if (!phase) errors.push(`${sourceLabel}:${lineNumber}: phase completion commit appears before a phase`);
31074
31070
  else phase.completionCommit = phaseCommit[1] === "pending" ? null : phaseCommit[2];
31075
31071
  continue;
31076
31072
  }
@@ -31078,7 +31074,7 @@ function parsePlan(path, errors = []) {
31078
31074
  if (taskMatch) {
31079
31075
  const phase = phases.at(-1);
31080
31076
  if (!phase) {
31081
- errors.push(`${path}:${lineNumber}: task appears before a phase`);
31077
+ errors.push(`${sourceLabel}:${lineNumber}: task appears before a phase`);
31082
31078
  continue;
31083
31079
  }
31084
31080
  let title = taskMatch[5].trim();
@@ -31105,8 +31101,8 @@ function parsePlan(path, errors = []) {
31105
31101
  }
31106
31102
  const taskDependencies = line.match(/^ - Task dependencies: (.+)$/);
31107
31103
  if (taskDependencies) {
31108
- if (!currentTask) errors.push(`${path}:${lineNumber}: task dependencies do not follow a task`);
31109
- else if (currentTask.dependencyDeclared) errors.push(`${path}:${lineNumber}: ${currentTask.id} has duplicate task dependencies`);
31104
+ if (!currentTask) errors.push(`${sourceLabel}:${lineNumber}: task dependencies do not follow a task`);
31105
+ else if (currentTask.dependencyDeclared) errors.push(`${sourceLabel}:${lineNumber}: ${currentTask.id} has duplicate task dependencies`);
31110
31106
  else {
31111
31107
  currentTask.dependencies = dependencyList(taskDependencies[1]);
31112
31108
  currentTask.dependencyDeclared = true;
@@ -31116,6 +31112,13 @@ function parsePlan(path, errors = []) {
31116
31112
  const graphWithoutDigest = { specRevision, planRevision, phases };
31117
31113
  return { ...graphWithoutDigest, digest: graphDigest(graphWithoutDigest) };
31118
31114
  }
31115
+ function parsePlan(path, errors = []) {
31116
+ if (!existsSync(path)) {
31117
+ errors.push(`${path}: missing plan`);
31118
+ return { specRevision: null, planRevision: null, phases: [], digest: graphDigest({ specRevision: null, planRevision: null, phases: [] }) };
31119
+ }
31120
+ return parsePlanContent(readFileSync(path, "utf8"), path, errors);
31121
+ }
31119
31122
  function findCycles(nodes, owner, errors) {
31120
31123
  const ids = new Set(nodes.map((node) => node.id));
31121
31124
  const visiting = /* @__PURE__ */ new Set();
@@ -31215,8 +31218,33 @@ function readAndValidatePlan(path, status, errors) {
31215
31218
 
31216
31219
  // src/domain/execution.ts
31217
31220
  import { createHash as createHash2, randomUUID } from "node:crypto";
31218
- import { existsSync as existsSync3, lstatSync, mkdirSync, readFileSync as readFileSync2, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
31219
- import { basename, dirname, join, resolve as resolve2 } from "node:path";
31221
+ import { existsSync as existsSync4, lstatSync, mkdirSync, readFileSync as readFileSync3, readdirSync as readdirSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
31222
+ import { basename, dirname, join as join2, resolve as resolve3 } from "node:path";
31223
+
31224
+ // src/domain/errors.ts
31225
+ var CadreError = class extends Error {
31226
+ code;
31227
+ details;
31228
+ constructor(code, message, details) {
31229
+ super(message);
31230
+ this.name = "CadreError";
31231
+ this.code = code;
31232
+ this.details = details;
31233
+ }
31234
+ };
31235
+ function serializeCadreError(error51) {
31236
+ if (error51 instanceof CadreError) {
31237
+ return {
31238
+ code: error51.code,
31239
+ message: error51.message,
31240
+ ...error51.details ? { details: error51.details } : {}
31241
+ };
31242
+ }
31243
+ return {
31244
+ code: "CADRE_ERROR",
31245
+ message: error51 instanceof Error ? error51.message : String(error51)
31246
+ };
31247
+ }
31220
31248
 
31221
31249
  // src/domain/paths.ts
31222
31250
  import { existsSync as existsSync2, statSync } from "node:fs";
@@ -31233,6 +31261,65 @@ function safeProjectRoot(input) {
31233
31261
  return root;
31234
31262
  }
31235
31263
 
31264
+ // src/domain/tracks-index.ts
31265
+ import { existsSync as existsSync3, readFileSync as readFileSync2, readdirSync } from "node:fs";
31266
+ import { join, resolve as resolve2 } from "node:path";
31267
+ function buildTracks(tracks) {
31268
+ const lines = [
31269
+ "# Tracks",
31270
+ "",
31271
+ "Generated from track-local `state.json` files by the Cadre MCP server.",
31272
+ "",
31273
+ "| Track | Type | Status | Revision |",
31274
+ "| --- | --- | --- | ---: |"
31275
+ ];
31276
+ for (const track of tracks) {
31277
+ lines.push(`| \`${track.id}\` ${track.title ?? ""} | ${track.type} | ${track.status} | ${track.revision ?? 1} |`);
31278
+ }
31279
+ return `${lines.join("\n")}
31280
+ `;
31281
+ }
31282
+ function renderTracksWithState(projectRoot, statePath, proposedState) {
31283
+ const root = join(safeProjectRoot(projectRoot), ".cadre");
31284
+ const resolvedStatePath = resolve2(statePath);
31285
+ const tracks = [];
31286
+ const ids = /* @__PURE__ */ new Set();
31287
+ let overrideFound = false;
31288
+ for (const directory of ["tracks", "archive"]) {
31289
+ const directoryRoot = join(root, directory);
31290
+ if (!existsSync3(directoryRoot)) continue;
31291
+ for (const entry of readdirSync(directoryRoot, { withFileTypes: true }).filter((candidate) => candidate.isDirectory()).sort((left, right) => left.name.localeCompare(right.name))) {
31292
+ const path = join(directoryRoot, entry.name, "state.json");
31293
+ let state;
31294
+ if (resolve2(path) === resolvedStatePath) {
31295
+ overrideFound = true;
31296
+ state = proposedState;
31297
+ } else {
31298
+ state = JSON.parse(readFileSync2(path, "utf8"));
31299
+ }
31300
+ const id = String(state.trackId ?? "");
31301
+ if (!id || id !== entry.name) throw new Error(`invalid track identity at ${path}`);
31302
+ if (ids.has(id)) throw new Error(`duplicate track state for ${id}`);
31303
+ ids.add(id);
31304
+ tracks.push({
31305
+ id,
31306
+ type: String(state.type ?? ""),
31307
+ status: String(state.status ?? ""),
31308
+ ...typeof state.title === "string" ? { title: state.title } : {},
31309
+ ...typeof state.revision === "number" ? { revision: state.revision } : {}
31310
+ });
31311
+ }
31312
+ }
31313
+ if (!overrideFound) throw new Error("execution track state is outside the active track index");
31314
+ tracks.sort((left, right) => left.id.localeCompare(right.id));
31315
+ const tracksPath = join(root, "tracks.md");
31316
+ return {
31317
+ tracksPath,
31318
+ tracksBody: readFileSync2(tracksPath, "utf8"),
31319
+ tracksContent: buildTracks(tracks)
31320
+ };
31321
+ }
31322
+
31236
31323
  // src/domain/execution.ts
31237
31324
  var EXECUTION_NODE_STATUSES = [
31238
31325
  "pending",
@@ -31246,6 +31333,7 @@ var EXECUTION_NODE_STATUSES = [
31246
31333
  "completed",
31247
31334
  "blocked"
31248
31335
  ];
31336
+ var EXECUTION_APPROVAL_MODES = ["governed", "phase", "autonomous"];
31249
31337
  var SHA = /^[0-9a-f]{7,40}$/;
31250
31338
  var TRACK_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
31251
31339
  var EXECUTION_ID = /^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
@@ -31253,13 +31341,13 @@ function hash2(value) {
31253
31341
  return createHash2("sha256").update(JSON.stringify(value)).digest("hex");
31254
31342
  }
31255
31343
  function writeJournalAtomically(path, journal) {
31256
- const temporaryPath = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
31344
+ const temporaryPath = join2(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
31257
31345
  try {
31258
31346
  writeFileSync(temporaryPath, `${JSON.stringify(journal, null, 2)}
31259
31347
  `, { flag: "wx" });
31260
31348
  renameSync(temporaryPath, path);
31261
31349
  } finally {
31262
- if (existsSync3(temporaryPath)) unlinkSync(temporaryPath);
31350
+ if (existsSync4(temporaryPath)) unlinkSync(temporaryPath);
31263
31351
  }
31264
31352
  }
31265
31353
  function assertIdentifiers(trackId, executionId) {
@@ -31267,7 +31355,7 @@ function assertIdentifiers(trackId, executionId) {
31267
31355
  if (!EXECUTION_ID.test(executionId)) throw new Error("executionId must contain only letters, digits, and hyphens");
31268
31356
  }
31269
31357
  function activeTrackRoot(projectRoot, trackId) {
31270
- return join(safeProjectRoot(projectRoot), ".cadre", "tracks", trackId);
31358
+ return join2(safeProjectRoot(projectRoot), ".cadre", "tracks", trackId);
31271
31359
  }
31272
31360
  function journalRelative(executionId) {
31273
31361
  return `executions/execution-${executionId}.json`;
@@ -31326,10 +31414,12 @@ function previewExecutionStart(input) {
31326
31414
  if (input.requestedMode === "sequential" && input.effectiveMode !== "sequential") {
31327
31415
  throw new Error("an explicitly sequential execution cannot become parallel");
31328
31416
  }
31417
+ const approvalMode = input.approvalMode ?? "phase";
31418
+ if (!EXECUTION_APPROVAL_MODES.includes(approvalMode)) throw new Error("approvalMode must be governed, phase, or autonomous");
31329
31419
  const trackRoot = activeTrackRoot(input.projectRoot, input.trackId);
31330
- const statePath = join(trackRoot, "state.json");
31331
- const planPath = join(trackRoot, "plan.md");
31332
- const stateBody = readFileSync2(statePath, "utf8");
31420
+ const statePath = join2(trackRoot, "state.json");
31421
+ const planPath = join2(trackRoot, "plan.md");
31422
+ const stateBody = readFileSync3(statePath, "utf8");
31333
31423
  const state = JSON.parse(stateBody);
31334
31424
  if (state.trackId !== input.trackId) throw new Error("track state does not match trackId");
31335
31425
  if (!["planned", "in_progress"].includes(state.status)) throw new Error(`track ${input.trackId} is not implementable from ${state.status}`);
@@ -31341,7 +31431,7 @@ function previewExecutionStart(input) {
31341
31431
  if (planErrors.length) throw new Error(planErrors.join("\n"));
31342
31432
  const planRevision = graph.planRevision;
31343
31433
  const relativeJournal = journalRelative(input.executionId);
31344
- const journalPath = join(trackRoot, relativeJournal);
31434
+ const journalPath = join2(trackRoot, relativeJournal);
31345
31435
  const journal = {
31346
31436
  schemaVersion: 1,
31347
31437
  executionId: input.executionId,
@@ -31350,6 +31440,7 @@ function previewExecutionStart(input) {
31350
31440
  checkpoint: "approved",
31351
31441
  requestedMode: input.requestedMode,
31352
31442
  effectiveMode: input.effectiveMode,
31443
+ approvalMode,
31353
31444
  maxWorkers: input.maxWorkers,
31354
31445
  planRevision,
31355
31446
  planCommit: state.commits.plan,
@@ -31360,11 +31451,11 @@ function previewExecutionStart(input) {
31360
31451
  headCommit: null,
31361
31452
  nodes: buildNodes(graph)
31362
31453
  };
31363
- if (existsSync3(journalPath)) {
31454
+ if (existsSync4(journalPath)) {
31364
31455
  if (lstatSync(journalPath).isSymbolicLink()) throw new Error("refusing an execution journal symbolic link");
31365
31456
  let existing;
31366
31457
  try {
31367
- existing = JSON.parse(readFileSync2(journalPath, "utf8"));
31458
+ existing = JSON.parse(readFileSync3(journalPath, "utf8"));
31368
31459
  } catch (error51) {
31369
31460
  throw new Error(`existing execution journal is invalid: ${error51 instanceof Error ? error51.message : String(error51)}`);
31370
31461
  }
@@ -31383,6 +31474,7 @@ function previewExecutionStart(input) {
31383
31474
  executionId: input.executionId,
31384
31475
  journal: relativeJournal,
31385
31476
  mode: input.effectiveMode,
31477
+ approvalMode,
31386
31478
  graphDigest: graph.digest,
31387
31479
  planRevision
31388
31480
  };
@@ -31397,7 +31489,7 @@ function previewExecutionStart(input) {
31397
31489
  journal,
31398
31490
  statePath,
31399
31491
  state: proposedState,
31400
- digest: hash2({ stateBody, planBody: readFileSync2(planPath, "utf8"), journal, state: proposedState })
31492
+ digest: hash2({ stateBody, planBody: readFileSync3(planPath, "utf8"), journal, state: proposedState })
31401
31493
  };
31402
31494
  }
31403
31495
  function applyExecutionStart(input, proposalDigest) {
@@ -31405,7 +31497,7 @@ function applyExecutionStart(input, proposalDigest) {
31405
31497
  if (proposal.digest !== proposalDigest) throw new Error("execution proposal is stale; preview it again");
31406
31498
  if (lstatSync(proposal.statePath).isSymbolicLink()) throw new Error("refusing to start execution through a state symbolic link");
31407
31499
  mkdirSync(dirname(proposal.journalPath), { recursive: true });
31408
- if (!existsSync3(proposal.journalPath)) {
31500
+ if (!existsSync4(proposal.journalPath)) {
31409
31501
  writeFileSync(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
31410
31502
  `);
31411
31503
  }
@@ -31416,11 +31508,11 @@ function applyExecutionStart(input, proposalDigest) {
31416
31508
  function executionPaths(projectRoot, trackId, executionId) {
31417
31509
  assertIdentifiers(trackId, executionId);
31418
31510
  const trackRoot = activeTrackRoot(projectRoot, trackId);
31419
- return { statePath: join(trackRoot, "state.json"), journalPath: join(trackRoot, journalRelative(executionId)) };
31511
+ return { statePath: join2(trackRoot, "state.json"), journalPath: join2(trackRoot, journalRelative(executionId)) };
31420
31512
  }
31421
31513
  function readExecution(projectRoot, trackId, executionId) {
31422
31514
  const { journalPath } = executionPaths(projectRoot, trackId, executionId);
31423
- return JSON.parse(readFileSync2(journalPath, "utf8"));
31515
+ return JSON.parse(readFileSync3(journalPath, "utf8"));
31424
31516
  }
31425
31517
  var ALLOWED_TRANSITIONS = {
31426
31518
  pending: ["running", "blocked"],
@@ -31441,7 +31533,16 @@ function applyNodeTransition(journal, input) {
31441
31533
  const workerAssignmentChanged = Object.hasOwn(input, "workerId") && (input.workerId ?? null) !== node.workerId;
31442
31534
  const phaseWorkerHandoff = node.kind === "phase" && node.status === "running" && input.status === "running" && workerAssignmentChanged && (node.workerId == null || input.workerId == null);
31443
31535
  if (!ALLOWED_TRANSITIONS[node.status]?.includes(input.status) && !phaseWorkerHandoff) {
31444
- throw new Error(`illegal execution transition ${node.status} -> ${input.status}`);
31536
+ throw new CadreError(
31537
+ "ILLEGAL_EXECUTION_TRANSITION",
31538
+ `illegal execution transition ${node.status} -> ${input.status}`,
31539
+ {
31540
+ nodeId: node.id,
31541
+ currentStatus: node.status,
31542
+ requestedStatus: input.status,
31543
+ allowedNextStatuses: ALLOWED_TRANSITIONS[node.status]
31544
+ }
31545
+ );
31445
31546
  }
31446
31547
  if (phaseWorkerHandoff && node.workerId != null && input.workerId == null && !input.verification) {
31447
31548
  throw new Error(`${node.id} requires clean-checkpoint verification before releasing its phase worker`);
@@ -31497,7 +31598,7 @@ function applyNodeTransition(journal, input) {
31497
31598
  throw new Error(`${node.id} requires a commit before it can be marked committed`);
31498
31599
  }
31499
31600
  if (input.status === "committed" && !updated.approval) {
31500
- throw new Error(`${node.id} requires recorded human approval before commit`);
31601
+ throw new Error(`${node.id} requires recorded approval authorization before commit`);
31501
31602
  }
31502
31603
  if (input.status === "committed" && node.kind === "task") {
31503
31604
  const duplicate = Object.values(journal.nodes).find(
@@ -31516,7 +31617,7 @@ function applyNodeTransition(journal, input) {
31516
31617
  if (incompleteTasks.length) throw new Error(`${node.id} has incomplete tasks: ${incompleteTasks.join(", ")}`);
31517
31618
  }
31518
31619
  if (node.kind === "manual-verification" && !updated.approval) {
31519
- throw new Error(`${node.id} requires recorded human approval`);
31620
+ throw new Error(`${node.id} requires recorded verification authorization`);
31520
31621
  }
31521
31622
  }
31522
31623
  if (updated.workerId != null) {
@@ -31540,7 +31641,7 @@ function previewExecutionNodesUpdate(input) {
31540
31641
  throw new Error("updates must contain 1 through 128 ordered node transitions");
31541
31642
  }
31542
31643
  const { journalPath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
31543
- const currentBody = readFileSync2(journalPath, "utf8");
31644
+ const currentBody = readFileSync3(journalPath, "utf8");
31544
31645
  const journal = JSON.parse(currentBody);
31545
31646
  for (const update of input.updates) applyNodeTransition(journal, update);
31546
31647
  return { path: journalPath, journal, digest: hash2({ currentBody, journal }) };
@@ -31581,7 +31682,22 @@ function deriveExecutionStatus(journal) {
31581
31682
  (node) => node.kind !== "phase" && journal.nodes[node.phaseId]?.status === "running"
31582
31683
  ).map((node) => node.id),
31583
31684
  active: Object.values(journal.nodes).filter((node) => !["pending", "completed", "blocked"].includes(node.status)).map((node) => node.id),
31584
- blocked: Object.values(journal.nodes).filter((node) => node.status === "blocked").map((node) => node.id)
31685
+ blocked: Object.values(journal.nodes).filter((node) => node.status === "blocked").map((node) => node.id),
31686
+ transitionGuidance: Object.fromEntries(Object.values(journal.nodes).map((node) => [
31687
+ node.id,
31688
+ {
31689
+ currentStatus: node.status,
31690
+ allowed: ALLOWED_TRANSITIONS[node.status].map((status) => ({
31691
+ status,
31692
+ requiredFields: [
31693
+ ...["blocked", "conflicted"].includes(status) ? ["blocker"] : [],
31694
+ ...status === "committed" ? ["workerCommit", "approval"] : [],
31695
+ ...status === "integrated" ? ["mergeCommit"] : [],
31696
+ ...status === "completed" && node.kind === "manual-verification" ? ["approval"] : []
31697
+ ]
31698
+ }))
31699
+ }
31700
+ ]))
31585
31701
  };
31586
31702
  }
31587
31703
  function executionStatus(projectRoot, trackId, executionId) {
@@ -31592,8 +31708,8 @@ function previewExecutionFinish(input) {
31592
31708
  if (!SHA.test(input.headCommit)) throw new Error("headCommit must be a Git commit SHA");
31593
31709
  if (!Number.isFinite(Date.parse(input.completedAt))) throw new Error("completedAt must be an ISO timestamp");
31594
31710
  const { statePath, journalPath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
31595
- const stateBody = readFileSync2(statePath, "utf8");
31596
- const journalBody = readFileSync2(journalPath, "utf8");
31711
+ const stateBody = readFileSync3(statePath, "utf8");
31712
+ const journalBody = readFileSync3(journalPath, "utf8");
31597
31713
  const state = JSON.parse(stateBody);
31598
31714
  const journal = JSON.parse(journalBody);
31599
31715
  const operation = state.operation;
@@ -31606,7 +31722,7 @@ function previewExecutionFinish(input) {
31606
31722
  }
31607
31723
  const unfinished = Object.values(journal.nodes).filter((node) => node.status !== "completed");
31608
31724
  if (unfinished.length) throw new Error(`execution has unfinished nodes: ${unfinished.map((node) => node.id).join(", ")}`);
31609
- const planPath = join(dirname(statePath), "plan.md");
31725
+ const planPath = join2(dirname(statePath), "plan.md");
31610
31726
  const planErrors = [];
31611
31727
  const graph = parsePlan(planPath, planErrors);
31612
31728
  validatePlanGraph(planPath, graph, "ready_for_review", planErrors);
@@ -31614,8 +31730,8 @@ function previewExecutionFinish(input) {
31614
31730
  if (graph.digest !== journal.graphDigest || graph.planRevision !== journal.planRevision) {
31615
31731
  throw new Error("approved plan changed during execution");
31616
31732
  }
31617
- const worktreeRoot = join(safeProjectRoot(input.projectRoot), ".cadre", ".worktrees", input.trackId, input.executionId);
31618
- if (existsSync3(worktreeRoot) && readdirSync(worktreeRoot).length) {
31733
+ const worktreeRoot = join2(safeProjectRoot(input.projectRoot), ".cadre", ".worktrees", input.trackId, input.executionId);
31734
+ if (existsSync4(worktreeRoot) && readdirSync2(worktreeRoot).length) {
31619
31735
  throw new Error(`execution still has managed worktrees under ${worktreeRoot}`);
31620
31736
  }
31621
31737
  const completedJournal = {
@@ -31633,30 +31749,58 @@ function previewExecutionFinish(input) {
31633
31749
  lastExecution: {
31634
31750
  executionId: input.executionId,
31635
31751
  journal: journalRelative(input.executionId),
31752
+ approvalMode: journal.approvalMode,
31636
31753
  planRevision: journal.planRevision,
31637
31754
  graphDigest: journal.graphDigest,
31638
31755
  headCommit: input.headCommit,
31639
31756
  completedAt: input.completedAt
31640
31757
  }
31641
31758
  };
31759
+ const { tracksPath, tracksBody, tracksContent } = renderTracksWithState(
31760
+ input.projectRoot,
31761
+ statePath,
31762
+ completedState
31763
+ );
31642
31764
  return {
31643
31765
  journalPath,
31644
31766
  journal: completedJournal,
31645
31767
  statePath,
31646
31768
  state: completedState,
31647
- digest: hash2({ stateBody, journalBody, journal: completedJournal, state: completedState })
31769
+ tracksPath,
31770
+ tracksContent,
31771
+ digest: hash2({
31772
+ stateBody,
31773
+ journalBody,
31774
+ tracksBody,
31775
+ journal: completedJournal,
31776
+ state: completedState,
31777
+ tracksContent
31778
+ })
31648
31779
  };
31649
31780
  }
31650
31781
  function applyExecutionFinish(input, proposalDigest) {
31651
31782
  const proposal = previewExecutionFinish(input);
31652
31783
  if (proposal.digest !== proposalDigest) throw new Error("execution completion proposal is stale; preview it again");
31653
- if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink()) {
31784
+ if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink() || lstatSync(proposal.tracksPath).isSymbolicLink()) {
31654
31785
  throw new Error("refusing to complete execution through a symbolic link");
31655
31786
  }
31656
- writeFileSync(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
31657
- `);
31658
- writeFileSync(proposal.statePath, `${JSON.stringify(proposal.state, null, 2)}
31659
- `);
31787
+ const journalTemporaryPath = join2(dirname(proposal.journalPath), `.${basename(proposal.journalPath)}.${process.pid}.${randomUUID()}.tmp`);
31788
+ const stateTemporaryPath = join2(dirname(proposal.statePath), `.${basename(proposal.statePath)}.${process.pid}.${randomUUID()}.tmp`);
31789
+ const tracksTemporaryPath = join2(dirname(proposal.tracksPath), `.${basename(proposal.tracksPath)}.${process.pid}.${randomUUID()}.tmp`);
31790
+ try {
31791
+ writeFileSync(journalTemporaryPath, `${JSON.stringify(proposal.journal, null, 2)}
31792
+ `, { flag: "wx" });
31793
+ writeFileSync(stateTemporaryPath, `${JSON.stringify(proposal.state, null, 2)}
31794
+ `, { flag: "wx" });
31795
+ writeFileSync(tracksTemporaryPath, proposal.tracksContent, { flag: "wx" });
31796
+ renameSync(journalTemporaryPath, proposal.journalPath);
31797
+ renameSync(stateTemporaryPath, proposal.statePath);
31798
+ renameSync(tracksTemporaryPath, proposal.tracksPath);
31799
+ } finally {
31800
+ if (existsSync4(journalTemporaryPath)) unlinkSync(journalTemporaryPath);
31801
+ if (existsSync4(stateTemporaryPath)) unlinkSync(stateTemporaryPath);
31802
+ if (existsSync4(tracksTemporaryPath)) unlinkSync(tracksTemporaryPath);
31803
+ }
31660
31804
  return proposal;
31661
31805
  }
31662
31806
  function validateExecutionJournal(trackRoot, state, graph, errors) {
@@ -31671,18 +31815,18 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31671
31815
  errors.push(`${state.trackId}: invalid execution journal path`);
31672
31816
  return;
31673
31817
  }
31674
- const path = resolve2(trackRoot, relative5);
31675
- if (!path.startsWith(`${resolve2(trackRoot)}/`)) {
31818
+ const path = resolve3(trackRoot, relative5);
31819
+ if (!path.startsWith(`${resolve3(trackRoot)}/`)) {
31676
31820
  errors.push(`${state.trackId}: execution journal escapes track root`);
31677
31821
  return;
31678
31822
  }
31679
- if (!existsSync3(path)) {
31823
+ if (!existsSync4(path)) {
31680
31824
  errors.push(`${state.trackId}: missing execution journal ${relative5}`);
31681
31825
  return;
31682
31826
  }
31683
31827
  let journal;
31684
31828
  try {
31685
- journal = JSON.parse(readFileSync2(path, "utf8"));
31829
+ journal = JSON.parse(readFileSync3(path, "utf8"));
31686
31830
  } catch (error51) {
31687
31831
  errors.push(`${state.trackId}: invalid execution journal (${error51 instanceof Error ? error51.message : String(error51)})`);
31688
31832
  return;
@@ -31696,6 +31840,9 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31696
31840
  if (journal.requestedMode === "sequential" && journal.effectiveMode !== "sequential") {
31697
31841
  errors.push(`${state.trackId}: sequential request became parallel`);
31698
31842
  }
31843
+ if (!EXECUTION_APPROVAL_MODES.includes(journal.approvalMode ?? "governed")) {
31844
+ errors.push(`${state.trackId}: invalid execution approval mode`);
31845
+ }
31699
31846
  if (!Number.isInteger(journal.maxWorkers) || journal.maxWorkers < 1 || journal.maxWorkers > 32) errors.push(`${state.trackId}: invalid maxWorkers`);
31700
31847
  const requireCurrentGraph = operation?.action === "implement" || ["ready_for_review", "completed", "archived"].includes(state.status);
31701
31848
  if (graph && requireCurrentGraph && (journal.graphDigest !== graph.digest || journal.planRevision !== graph.planRevision)) {
@@ -31760,11 +31907,11 @@ function validateExecutionJournal(trackRoot, state, graph, errors) {
31760
31907
  }
31761
31908
  if (operation?.action === "implement" && journal.status !== "in_progress") errors.push(`${state.trackId}: active implement operation requires an in-progress journal`);
31762
31909
  if (operation?.action === "implement") {
31763
- if (operation.executionId !== journal.executionId || operation.graphDigest !== journal.graphDigest || operation.planRevision !== journal.planRevision) {
31910
+ if (operation.executionId !== journal.executionId || operation.graphDigest !== journal.graphDigest || operation.planRevision !== journal.planRevision || String(operation.approvalMode ?? "governed") !== String(journal.approvalMode ?? "governed")) {
31764
31911
  errors.push(`${state.trackId}: implement operation does not match its execution journal`);
31765
31912
  }
31766
31913
  } else if (state.lastExecution) {
31767
- if (state.lastExecution.executionId !== journal.executionId || state.lastExecution.graphDigest !== journal.graphDigest || state.lastExecution.planRevision !== journal.planRevision || state.lastExecution.headCommit !== journal.headCommit) {
31914
+ if (state.lastExecution.executionId !== journal.executionId || state.lastExecution.graphDigest !== journal.graphDigest || state.lastExecution.planRevision !== journal.planRevision || state.lastExecution.headCommit !== journal.headCommit || String(state.lastExecution.approvalMode ?? "governed") !== String(journal.approvalMode ?? "governed")) {
31768
31915
  errors.push(`${state.trackId}: lastExecution does not match its execution journal`);
31769
31916
  }
31770
31917
  }
@@ -31805,11 +31952,11 @@ var REQUIRED_CONTEXT = [
31805
31952
  "tracks.md"
31806
31953
  ];
31807
31954
  function cadreRoot(projectRoot) {
31808
- return join2(resolve3(projectRoot), ".cadre");
31955
+ return join3(resolve4(projectRoot), ".cadre");
31809
31956
  }
31810
31957
  function readJson(path, errors) {
31811
31958
  try {
31812
- return JSON.parse(readFileSync3(path, "utf8"));
31959
+ return JSON.parse(readFileSync4(path, "utf8"));
31813
31960
  } catch (error51) {
31814
31961
  errors.push(`${path}: invalid JSON (${error51 instanceof Error ? error51.message : String(error51)})`);
31815
31962
  return null;
@@ -31883,6 +32030,9 @@ function validateImplementOperation(state, owner, errors) {
31883
32030
  errors.push(`${owner}: implement journal path is invalid`);
31884
32031
  }
31885
32032
  if (!["parallel", "sequential"].includes(String(operation.mode ?? ""))) errors.push(`${owner}: implement mode is invalid`);
32033
+ if (!["governed", "phase", "autonomous"].includes(String(operation.approvalMode ?? "governed"))) {
32034
+ errors.push(`${owner}: implement approvalMode is invalid`);
32035
+ }
31886
32036
  if (!/^[0-9a-f]{64}$/.test(String(operation.graphDigest ?? ""))) errors.push(`${owner}: implement graphDigest is invalid`);
31887
32037
  if (!Number.isInteger(operation.planRevision) || Number(operation.planRevision) < 1) errors.push(`${owner}: implement planRevision is invalid`);
31888
32038
  }
@@ -31911,11 +32061,11 @@ function validateRevertOperation(state, owner, errors) {
31911
32061
  }
31912
32062
  }
31913
32063
  function validateLearning(path, required2, errors) {
31914
- if (!existsSync4(path)) {
32064
+ if (!existsSync5(path)) {
31915
32065
  if (required2) errors.push(`${path}: missing learning file`);
31916
32066
  return;
31917
32067
  }
31918
- const body = readFileSync3(path, "utf8");
32068
+ const body = readFileSync4(path, "utf8");
31919
32069
  const start = "<!-- cadre:pattern-seed:start -->";
31920
32070
  const end = "<!-- cadre:pattern-seed:end -->";
31921
32071
  if (!body.includes(start) || !body.includes(end) || body.indexOf(start) >= body.indexOf(end)) {
@@ -31923,11 +32073,11 @@ function validateLearning(path, required2, errors) {
31923
32073
  }
31924
32074
  }
31925
32075
  function validateSpec(path, errors) {
31926
- if (!existsSync4(path)) {
32076
+ if (!existsSync5(path)) {
31927
32077
  errors.push(`${path}: missing specification`);
31928
32078
  return;
31929
32079
  }
31930
- const body = readFileSync3(path, "utf8");
32080
+ const body = readFileSync4(path, "utf8");
31931
32081
  for (const heading of [
31932
32082
  "## Functional Requirements",
31933
32083
  "## Non-Functional Requirements",
@@ -31940,12 +32090,12 @@ function validateSpec(path, errors) {
31940
32090
  }
31941
32091
  }
31942
32092
  function validateProjectOperations(root, byId, errors) {
31943
- const operationsRoot = join2(root, "operations");
31944
- if (!existsSync4(operationsRoot)) return;
32093
+ const operationsRoot = join3(root, "operations");
32094
+ if (!existsSync5(operationsRoot)) return;
31945
32095
  let activeProjectOperations = 0;
31946
- for (const file2 of readdirSync2(operationsRoot).filter((name) => name.endsWith(".json"))) {
32096
+ for (const file2 of readdirSync3(operationsRoot).filter((name) => name.endsWith(".json"))) {
31947
32097
  const owner = `operations/${file2}`;
31948
- const operation = readJson(join2(operationsRoot, file2), errors);
32098
+ const operation = readJson(join3(operationsRoot, file2), errors);
31949
32099
  if (!operation) continue;
31950
32100
  validateOperation(operation, owner, errors);
31951
32101
  if (!operation.status || !["in_progress", "completed"].includes(operation.status)) {
@@ -32017,12 +32167,12 @@ function discoverTracks(root, errors) {
32017
32167
  const states = /* @__PURE__ */ new Map();
32018
32168
  const byId = /* @__PURE__ */ new Map();
32019
32169
  for (const directory of ["tracks", "archive"]) {
32020
- const directoryRoot = join2(root, directory);
32021
- if (!existsSync4(directoryRoot)) continue;
32022
- const entries = readdirSync2(directoryRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).sort((left, right) => left.name.localeCompare(right.name));
32170
+ const directoryRoot = join3(root, directory);
32171
+ if (!existsSync5(directoryRoot)) continue;
32172
+ const entries = readdirSync3(directoryRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).sort((left, right) => left.name.localeCompare(right.name));
32023
32173
  for (const entry of entries) {
32024
32174
  const location = `${directory}/${entry.name}`;
32025
- const state = readJson(join2(directoryRoot, entry.name, "state.json"), errors);
32175
+ const state = readJson(join3(directoryRoot, entry.name, "state.json"), errors);
32026
32176
  if (!state) continue;
32027
32177
  const id = state.trackId;
32028
32178
  if (!id) {
@@ -32044,31 +32194,16 @@ function discoverTracks(root, errors) {
32044
32194
  tracks.sort((left, right) => left.id.localeCompare(right.id));
32045
32195
  return { tracks, states, byId };
32046
32196
  }
32047
- function buildTracks(tracks) {
32048
- const lines = [
32049
- "# Tracks",
32050
- "",
32051
- "Generated from track-local `state.json` files by the Cadre MCP server.",
32052
- "",
32053
- "| Track | Type | Status | Revision |",
32054
- "| --- | --- | --- | ---: |"
32055
- ];
32056
- for (const track of tracks) {
32057
- lines.push(`| \`${track.id}\` ${track.title ?? ""} | ${track.type} | ${track.status} | ${track.revision ?? 1} |`);
32058
- }
32059
- return `${lines.join("\n")}
32060
- `;
32061
- }
32062
32197
  function validateProject(projectRoot) {
32063
32198
  const root = cadreRoot(projectRoot);
32064
32199
  const errors = [];
32065
32200
  const warnings = [];
32066
32201
  for (const file2 of REQUIRED_CONTEXT) {
32067
- if (!existsSync4(join2(root, file2))) errors.push(`${join2(root, file2)}: missing required Cadre file`);
32202
+ if (!existsSync5(join3(root, file2))) errors.push(`${join3(root, file2)}: missing required Cadre file`);
32068
32203
  }
32069
- const gitignorePath = join2(root, ".gitignore");
32070
- if (existsSync4(gitignorePath)) {
32071
- const gitignore = readFileSync3(gitignorePath, "utf8");
32204
+ const gitignorePath = join3(root, ".gitignore");
32205
+ if (existsSync5(gitignorePath)) {
32206
+ const gitignore = readFileSync4(gitignorePath, "utf8");
32072
32207
  if (!gitignore.split(/\r?\n/).includes("/.worktrees/")) {
32073
32208
  errors.push(`${gitignorePath}: must ignore /.worktrees/`);
32074
32209
  }
@@ -32076,7 +32211,7 @@ function validateProject(projectRoot) {
32076
32211
  errors.push(`${gitignorePath}: must ignore /wisps/`);
32077
32212
  }
32078
32213
  }
32079
- const project = readJson(join2(root, "project.json"), errors);
32214
+ const project = readJson(join3(root, "project.json"), errors);
32080
32215
  if (!project) return { project: null, tracks: [], states: /* @__PURE__ */ new Map(), errors, warnings };
32081
32216
  if (project.schemaVersion !== 1) errors.push("project.json: unsupported schemaVersion");
32082
32217
  if (project.runtimeVersion !== CADRE_RUNTIME_VERSION) errors.push(`project.json: runtimeVersion must be ${CADRE_RUNTIME_VERSION}`);
@@ -32104,7 +32239,7 @@ function validateProject(projectRoot) {
32104
32239
  const { tracks, states, byId } = discoverTracks(root, errors);
32105
32240
  for (const track of tracks) {
32106
32241
  const state = states.get(track.id);
32107
- const trackRoot = join2(root, track.location);
32242
+ const trackRoot = join3(root, track.location);
32108
32243
  if (state.schemaVersion !== 1) errors.push(`${track.id}: unsupported state schemaVersion`);
32109
32244
  if (!state.title || typeof state.title !== "string") errors.push(`${track.id}: title is required`);
32110
32245
  if (!TRACK_TYPES.has(track.type)) errors.push(`${track.id}: type must be feature or bug`);
@@ -32134,13 +32269,13 @@ function validateProject(projectRoot) {
32134
32269
  if (["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && !planCommit && state.operation?.action !== "plan") {
32135
32270
  errors.push(`${track.id}: status ${track.status} requires a recorded plan commit or active plan operation`);
32136
32271
  }
32137
- const specPath = join2(trackRoot, "spec.md");
32138
- const planPath = join2(trackRoot, "plan.md");
32139
- const learningPath = join2(trackRoot, "learning.md");
32140
- if (existsSync4(specPath)) validateSpec(specPath, errors);
32272
+ const specPath = join3(trackRoot, "spec.md");
32273
+ const planPath = join3(trackRoot, "plan.md");
32274
+ const learningPath = join3(trackRoot, "learning.md");
32275
+ if (existsSync5(specPath)) validateSpec(specPath, errors);
32141
32276
  else if (track.status !== "drafting-spec" && state?.operation?.action !== "specify") errors.push(`${track.id}: missing spec.md`);
32142
32277
  let planGraph = null;
32143
- if (existsSync4(planPath)) planGraph = readAndValidatePlan(planPath, track.status, errors);
32278
+ if (existsSync5(planPath)) planGraph = readAndValidatePlan(planPath, track.status, errors);
32144
32279
  else if (["planned", "in_progress", "ready_for_review", "completed", "archived"].includes(track.status) && state?.operation?.action !== "plan") errors.push(`${track.id}: missing plan.md`);
32145
32280
  validateLearning(
32146
32281
  learningPath,
@@ -32149,8 +32284,8 @@ function validateProject(projectRoot) {
32149
32284
  );
32150
32285
  validateExecutionJournal(trackRoot, state, planGraph, errors);
32151
32286
  if (["ready_for_review", "completed", "archived"].includes(track.status)) {
32152
- const managedRoot = join2(root, ".worktrees", track.id);
32153
- if (existsSync4(managedRoot) && readdirSync2(managedRoot).length) {
32287
+ const managedRoot = join3(root, ".worktrees", track.id);
32288
+ if (existsSync5(managedRoot) && readdirSync3(managedRoot).length) {
32154
32289
  errors.push(`${track.id}: finalized track retains managed execution worktrees`);
32155
32290
  }
32156
32291
  }
@@ -32188,8 +32323,8 @@ function validateProject(projectRoot) {
32188
32323
  visited.add(id);
32189
32324
  }
32190
32325
  for (const id of byId.keys()) visit(id, []);
32191
- const tracksPath = join2(root, "tracks.md");
32192
- if (existsSync4(tracksPath) && readFileSync3(tracksPath, "utf8") !== buildTracks(tracks)) {
32326
+ const tracksPath = join3(root, "tracks.md");
32327
+ if (existsSync5(tracksPath) && readFileSync4(tracksPath, "utf8") !== buildTracks(tracks)) {
32193
32328
  warnings.push("TRACKS_INDEX_STALE: tracks.md is stale; regenerate it after approved state changes");
32194
32329
  }
32195
32330
  return { project, tracks, states, errors, warnings };
@@ -32209,8 +32344,8 @@ function renderTracksPreview(projectRoot) {
32209
32344
  const result2 = validateProject(projectRoot);
32210
32345
  if (!result2.project) throw new Error(result2.errors.join("\n") || "Cadre project state is unavailable");
32211
32346
  if (result2.errors.length) throw new Error(result2.errors.join("\n"));
32212
- const path = join2(cadreRoot(projectRoot), "tracks.md");
32213
- const previousContent = existsSync4(path) ? readFileSync3(path, "utf8") : null;
32347
+ const path = join3(cadreRoot(projectRoot), "tracks.md");
32348
+ const previousContent = existsSync5(path) ? readFileSync4(path, "utf8") : null;
32214
32349
  const content = buildTracks(result2.tracks);
32215
32350
  const digest = createHash3("sha256").update(JSON.stringify({ content, previousContent })).digest("hex");
32216
32351
  return { path, content, previousContent, changed: previousContent !== content, digest };
@@ -32220,9 +32355,9 @@ function writeTracks(projectRoot, proposalDigest) {
32220
32355
  if (preview.digest !== proposalDigest) {
32221
32356
  throw new Error("tracks.md proposal is stale; preview it again before applying");
32222
32357
  }
32223
- if (existsSync4(preview.path)) {
32358
+ if (existsSync5(preview.path)) {
32224
32359
  if (lstatSync2(preview.path).isSymbolicLink()) throw new Error("Refusing to write tracks.md through a symbolic link");
32225
- readFileSync3(preview.path, "utf8");
32360
+ readFileSync4(preview.path, "utf8");
32226
32361
  }
32227
32362
  writeFileSync2(preview.path, preview.content);
32228
32363
  return preview.path;
@@ -32239,7 +32374,7 @@ function formatStatus(projectRoot) {
32239
32374
  for (const track of result2.tracks) {
32240
32375
  const dependencies = track.dependencies?.length ? track.dependencies.join(",") : "none";
32241
32376
  const state = result2.states.get(track.id);
32242
- const execution = state?.operation?.action === "implement" ? `${String(state.operation.executionId ?? "unknown")}/${String(state.operation.mode ?? "unknown")}` : state?.lastExecution?.executionId ?? "none";
32377
+ 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";
32243
32378
  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)}`);
32244
32379
  }
32245
32380
  const counts = result2.tracks.reduce((summary, track) => {
@@ -32256,8 +32391,8 @@ function formatStatus(projectRoot) {
32256
32391
 
32257
32392
  // src/domain/templates.ts
32258
32393
  import { createHash as createHash4 } from "node:crypto";
32259
- import { existsSync as existsSync5, readFileSync as readFileSync4, readdirSync as readdirSync3 } from "node:fs";
32260
- import { dirname as dirname2, extname, join as join3, relative, resolve as resolve4, sep } from "node:path";
32394
+ import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync as readdirSync4 } from "node:fs";
32395
+ import { dirname as dirname2, extname, join as join4, relative, resolve as resolve5, sep } from "node:path";
32261
32396
  import { fileURLToPath } from "node:url";
32262
32397
  var TEMPLATE_IDS = [
32263
32398
  "project/archive-operation",
@@ -32304,16 +32439,16 @@ function locateTemplateRoot() {
32304
32439
  const moduleDirectory = dirname2(fileURLToPath(import.meta.url));
32305
32440
  const candidates = [
32306
32441
  process.env.CADRE_TEMPLATE_ROOT,
32307
- resolve4(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
32308
- resolve4(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
32442
+ resolve5(moduleDirectory, "../../templates", TEMPLATE_SET_VERSION),
32443
+ resolve5(moduleDirectory, "../templates", TEMPLATE_SET_VERSION)
32309
32444
  ].filter((candidate) => Boolean(candidate));
32310
- const found = candidates.find((candidate) => existsSync5(candidate));
32445
+ const found = candidates.find((candidate) => existsSync6(candidate));
32311
32446
  if (!found) throw new Error(`Cadre template set ${TEMPLATE_SET_VERSION} is unavailable`);
32312
32447
  return found;
32313
32448
  }
32314
32449
  function walk(root, directory = root) {
32315
- return readdirSync3(directory, { withFileTypes: true }).flatMap((entry) => {
32316
- const path = join3(directory, entry.name);
32450
+ return readdirSync4(directory, { withFileTypes: true }).flatMap((entry) => {
32451
+ const path = join4(directory, entry.name);
32317
32452
  return entry.isDirectory() ? walk(root, path) : [relative(root, path).split(sep).join("/")];
32318
32453
  });
32319
32454
  }
@@ -32350,7 +32485,7 @@ function templateCatalog() {
32350
32485
  const catalog = walk(root).map((relativePath) => {
32351
32486
  const id = templateId(relativePath);
32352
32487
  if (!id) return null;
32353
- const content = readFileSync4(join3(root, relativePath), "utf8");
32488
+ const content = readFileSync5(join4(root, relativePath), "utf8");
32354
32489
  return {
32355
32490
  id,
32356
32491
  uri: `cadre://templates/${TEMPLATE_SET_VERSION}/${id}`,
@@ -32412,6 +32547,13 @@ var REQUIRED_APPROVED_FILES = /* @__PURE__ */ new Set([
32412
32547
  function hash3(content) {
32413
32548
  return createHash5("sha256").update(content).digest("hex");
32414
32549
  }
32550
+ function proposalFileHash(file2) {
32551
+ if (file2.path !== "project.json") return file2.sha256;
32552
+ const state = JSON.parse(file2.content);
32553
+ if (state.setup?.operation) state.setup.operation.approvedAt = "<audit-timestamp>";
32554
+ return hash3(`${JSON.stringify(state, null, 2)}
32555
+ `);
32556
+ }
32415
32557
  function normalizeCadrePath(input) {
32416
32558
  if (isAbsolute(input)) throw new Error(`Cadre artifact path must be relative: ${input}`);
32417
32559
  const normalized = input.replaceAll("\\", "/").replace(/^\.\//, "");
@@ -32445,7 +32587,7 @@ function projectState(input, approvedPaths, template) {
32445
32587
  }
32446
32588
  function previewProjectInit(input) {
32447
32589
  const root = safeProjectRoot(input.projectRoot);
32448
- if (existsSync6(join4(root, ".cadre"))) throw new Error(`${root}/.cadre already exists`);
32590
+ if (existsSync7(join5(root, ".cadre"))) throw new Error(`${root}/.cadre already exists`);
32449
32591
  if (!input.projectName.trim()) throw new Error("Project name is required");
32450
32592
  if (!Number.isFinite(Date.parse(input.approvedAt))) throw new Error("approvedAt must be an ISO timestamp");
32451
32593
  if (input.baseCommit !== null && !/^[0-9a-f]{7,40}$/.test(input.baseCommit)) {
@@ -32483,12 +32625,12 @@ function previewProjectInit(input) {
32483
32625
  const digest = hash3(JSON.stringify({
32484
32626
  runtimeVersion: CADRE_RUNTIME_VERSION,
32485
32627
  templateSetVersion: TEMPLATE_SET_VERSION,
32486
- files: files.map(({ path, sha256 }) => ({ path, sha256 }))
32628
+ files: files.map((file2) => ({ path: file2.path, sha256: proposalFileHash(file2) }))
32487
32629
  }));
32488
32630
  return { runtimeVersion: CADRE_RUNTIME_VERSION, templateSetVersion: TEMPLATE_SET_VERSION, files, digest };
32489
32631
  }
32490
32632
  function targetWithin(root, relativePath) {
32491
- const target = resolve5(root, relativePath);
32633
+ const target = resolve6(root, relativePath);
32492
32634
  const relation = relative2(root, target);
32493
32635
  if (relation.startsWith("..") || isAbsolute(relation)) throw new Error(`Path escapes initialization root: ${relativePath}`);
32494
32636
  return target;
@@ -32496,7 +32638,7 @@ function targetWithin(root, relativePath) {
32496
32638
  function assertNoSymlinkPath(root, target) {
32497
32639
  let current = target;
32498
32640
  while (current !== root) {
32499
- if (existsSync6(current) && lstatSync3(current).isSymbolicLink()) {
32641
+ if (existsSync7(current) && lstatSync3(current).isSymbolicLink()) {
32500
32642
  throw new Error(`Refusing symbolic link inside initialization stage: ${current}`);
32501
32643
  }
32502
32644
  current = dirname3(current);
@@ -32506,8 +32648,8 @@ function applyProjectInit(input, proposalDigest) {
32506
32648
  const proposal = previewProjectInit(input);
32507
32649
  if (proposal.digest !== proposalDigest) throw new Error("Initialization proposal digest does not match; preview again");
32508
32650
  const projectRoot = safeProjectRoot(input.projectRoot);
32509
- const stage = join4(projectRoot, `.cadre-init-${proposal.digest.slice(0, 12)}`);
32510
- if (existsSync6(stage) && (!lstatSync3(stage).isDirectory() || lstatSync3(stage).isSymbolicLink())) {
32651
+ const stage = join5(projectRoot, `.cadre-init-${proposal.digest.slice(0, 12)}`);
32652
+ if (existsSync7(stage) && (!lstatSync3(stage).isDirectory() || lstatSync3(stage).isSymbolicLink())) {
32511
32653
  throw new Error(`Initialization stage is not a regular directory: ${stage}`);
32512
32654
  }
32513
32655
  mkdirSync2(stage, { recursive: true });
@@ -32515,21 +32657,21 @@ function applyProjectInit(input, proposalDigest) {
32515
32657
  const target = targetWithin(stage, file2.path);
32516
32658
  assertNoSymlinkPath(stage, target);
32517
32659
  mkdirSync2(dirname3(target), { recursive: true });
32518
- if (existsSync6(target)) {
32519
- const current = readFileSync5(target, "utf8");
32660
+ if (existsSync7(target)) {
32661
+ const current = readFileSync6(target, "utf8");
32520
32662
  if (current !== file2.content) throw new Error(`Interrupted initialization disagrees at ${file2.path}`);
32521
32663
  } else writeFileSync3(target, file2.content);
32522
32664
  }
32523
- const finalRoot = join4(projectRoot, ".cadre");
32524
- if (existsSync6(finalRoot)) throw new Error(`${finalRoot} appeared after preview; refusing to overwrite it`);
32665
+ const finalRoot = join5(projectRoot, ".cadre");
32666
+ if (existsSync7(finalRoot)) throw new Error(`${finalRoot} appeared after preview; refusing to overwrite it`);
32525
32667
  renameSync2(stage, finalRoot);
32526
32668
  return proposal;
32527
32669
  }
32528
32670
  function recordSetupCommit(projectRootInput, commit) {
32529
32671
  if (!/^[0-9a-f]{7,40}$/.test(commit)) throw new Error("commit must be a hexadecimal Git commit SHA");
32530
32672
  const root = safeProjectRoot(projectRootInput);
32531
- const path = join4(root, ".cadre", "project.json");
32532
- const project = JSON.parse(readFileSync5(path, "utf8"));
32673
+ const path = join5(root, ".cadre", "project.json");
32674
+ const project = JSON.parse(readFileSync6(path, "utf8"));
32533
32675
  if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
32534
32676
  throw new Error("Project setup is not awaiting its create commit");
32535
32677
  }
@@ -32544,15 +32686,15 @@ function recordSetupCommit(projectRootInput, commit) {
32544
32686
  }
32545
32687
  function recordGitInitialized(projectRootInput) {
32546
32688
  const root = safeProjectRoot(projectRootInput);
32547
- const path = join4(root, ".cadre", "project.json");
32548
- const project = JSON.parse(readFileSync5(path, "utf8"));
32689
+ const path = join5(root, ".cadre", "project.json");
32690
+ const project = JSON.parse(readFileSync6(path, "utf8"));
32549
32691
  if (project.setup?.status !== "in_progress" || project.setup.operation?.action !== "create") {
32550
32692
  throw new Error("Project setup is not in an active create operation");
32551
32693
  }
32552
32694
  if (project.setup.operation.gitDisposition !== "initialize") {
32553
32695
  throw new Error("Project setup was not approved to initialize Git");
32554
32696
  }
32555
- if (resolve5(String(project.setup.operation.repositoryRoot)) !== root) {
32697
+ if (resolve6(String(project.setup.operation.repositoryRoot)) !== root) {
32556
32698
  throw new Error("Approved Git repository root does not match projectRoot");
32557
32699
  }
32558
32700
  project.setup.checkpoint = "commit-pending";
@@ -32563,8 +32705,8 @@ function recordGitInitialized(projectRootInput) {
32563
32705
 
32564
32706
  // src/domain/worktrees.ts
32565
32707
  import { createHash as createHash6 } from "node:crypto";
32566
- import { existsSync as existsSync7, lstatSync as lstatSync4, readdirSync as readdirSync4, realpathSync, rmdirSync } from "node:fs";
32567
- import { dirname as dirname4, join as join5, relative as relative3, resolve as resolve6 } from "node:path";
32708
+ import { existsSync as existsSync8, lstatSync as lstatSync4, readdirSync as readdirSync5, realpathSync, rmdirSync } from "node:fs";
32709
+ import { dirname as dirname4, join as join6, relative as relative3, resolve as resolve7 } from "node:path";
32568
32710
  import { spawnSync } from "node:child_process";
32569
32711
  var SHA2 = /^[0-9a-f]{7,40}$/;
32570
32712
  var TRACK_ID2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -32584,7 +32726,7 @@ function hash4(value) {
32584
32726
  }
32585
32727
  function assertRepository(projectRoot) {
32586
32728
  const root = realpathSync(safeProjectRoot(projectRoot));
32587
- const detected = realpathSync(resolve6(git(root, ["rev-parse", "--show-toplevel"]).stdout.trim()));
32729
+ const detected = realpathSync(resolve7(git(root, ["rev-parse", "--show-toplevel"]).stdout.trim()));
32588
32730
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
32589
32731
  return root;
32590
32732
  }
@@ -32594,8 +32736,12 @@ function assertIds(trackId, executionId, nodeId, phaseId) {
32594
32736
  if (!PHASE_ID.test(nodeId) && !TASK_ID.test(nodeId)) throw new Error("nodeId must be a phase or task ID");
32595
32737
  if (phaseId != null && !PHASE_ID.test(phaseId)) throw new Error("invalid phaseId");
32596
32738
  const task = nodeId.match(TASK_ID);
32597
- if (task && phaseId !== `P${task[1]}`) throw new Error(`${nodeId} does not belong to ${phaseId ?? "a phase"}`);
32598
- if (!task && phaseId != null) throw new Error("phase nodes must not supply phaseId");
32739
+ if (task && phaseId != null && phaseId !== `P${task[1]}`) throw new Error(`${nodeId} does not belong to ${phaseId}`);
32740
+ if (!task && phaseId != null && phaseId !== nodeId) throw new Error(`${nodeId} does not belong to ${phaseId}`);
32741
+ }
32742
+ function phaseForNode(nodeId) {
32743
+ const task = nodeId.match(TASK_ID);
32744
+ return task ? `P${task[1]}` : nodeId;
32599
32745
  }
32600
32746
  function nodeSlug(nodeId) {
32601
32747
  return nodeId.toLowerCase().replace(".", "-");
@@ -32603,9 +32749,10 @@ function nodeSlug(nodeId) {
32603
32749
  function worktreeIdentity(root, trackId, executionId, nodeId, phaseId) {
32604
32750
  assertIds(trackId, executionId, nodeId, phaseId);
32605
32751
  const task = TASK_ID.test(nodeId);
32606
- const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId}/tasks/${phaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId}/phases/${nodeId}`;
32752
+ const resolvedPhaseId = phaseForNode(nodeId);
32753
+ const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId}/tasks/${resolvedPhaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId}/phases/${nodeId}`;
32607
32754
  const branch = `cadre/${trackId}/${executionId}/${task ? "task" : "phase"}-${nodeSlug(nodeId)}`;
32608
- return { path: join5(root, relativePath), relativePath, branch };
32755
+ return { path: join6(root, relativePath), relativePath, branch };
32609
32756
  }
32610
32757
  function branchHead(root, branch) {
32611
32758
  const result2 = git(root, ["rev-parse", "--verify", `refs/heads/${branch}`], true);
@@ -32616,14 +32763,14 @@ function registeredWorktrees(root) {
32616
32763
  let current = {};
32617
32764
  for (const line of git(root, ["worktree", "list", "--porcelain"]).stdout.split(/\r?\n/)) {
32618
32765
  if (!line) {
32619
- if (current.path && current.head) records.push({ path: resolve6(current.path), branch: current.branch ?? null, head: current.head });
32766
+ if (current.path && current.head) records.push({ path: resolve7(current.path), branch: current.branch ?? null, head: current.head });
32620
32767
  current = {};
32621
32768
  } else if (line.startsWith("worktree ")) current.path = line.slice("worktree ".length);
32622
32769
  else if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length);
32623
32770
  else if (line.startsWith("branch refs/heads/")) current.branch = line.slice("branch refs/heads/".length);
32624
32771
  else if (line === "detached") current.branch = null;
32625
32772
  }
32626
- if (current.path && current.head) records.push({ path: resolve6(current.path), branch: current.branch ?? null, head: current.head });
32773
+ if (current.path && current.head) records.push({ path: resolve7(current.path), branch: current.branch ?? null, head: current.head });
32627
32774
  return records;
32628
32775
  }
32629
32776
  function previewWorktreeCreate(input) {
@@ -32631,12 +32778,12 @@ function previewWorktreeCreate(input) {
32631
32778
  const baseCommit = git(root, ["rev-parse", `${input.baseCommit}^{commit}`]).stdout.trim();
32632
32779
  if (!SHA2.test(baseCommit)) throw new Error("baseCommit does not resolve to a commit");
32633
32780
  const identity = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
32634
- const registered = registeredWorktrees(root).find((entry) => entry.path === resolve6(identity.path));
32781
+ const registered = registeredWorktrees(root).find((entry) => entry.path === resolve7(identity.path));
32635
32782
  const existingBranchHead = branchHead(root, identity.branch);
32636
32783
  if (registered && (registered.branch !== identity.branch || registered.head !== existingBranchHead)) {
32637
32784
  throw new Error(`registered worktree disagrees at ${identity.relativePath}`);
32638
32785
  }
32639
- if (!registered && existsSync7(identity.path)) throw new Error(`unregistered path already exists: ${identity.path}`);
32786
+ if (!registered && existsSync8(identity.path)) throw new Error(`unregistered path already exists: ${identity.path}`);
32640
32787
  if (existingBranchHead) {
32641
32788
  const basedOnExpectedCommit = git(root, ["merge-base", "--is-ancestor", baseCommit, existingBranchHead], true).status === 0;
32642
32789
  if (!basedOnExpectedCommit) throw new Error(`existing branch ${identity.branch} is not based on requested base commit`);
@@ -32665,10 +32812,9 @@ ${status}`);
32665
32812
  }
32666
32813
  function targetIdentity(root, input) {
32667
32814
  if (TASK_ID.test(input.nodeId)) {
32668
- const phaseId = input.phaseId;
32669
- if (!phaseId) throw new Error("task integration requires phaseId");
32815
+ const phaseId = phaseForNode(input.nodeId);
32670
32816
  const phase = worktreeIdentity(root, input.trackId, input.executionId, phaseId, null);
32671
- const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve6(phase.path));
32817
+ const phaseWorktree = registeredWorktrees(root).find((entry) => entry.path === resolve7(phase.path));
32672
32818
  if (phaseWorktree) {
32673
32819
  if (phaseWorktree.branch !== phase.branch) throw new Error(`phase worktree is not on ${phase.branch}`);
32674
32820
  return { path: phase.path, branch: phase.branch };
@@ -32682,7 +32828,8 @@ function journalNode(input) {
32682
32828
  const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
32683
32829
  const node = journal.nodes[input.nodeId];
32684
32830
  if (!node) throw new Error(`execution journal has no node ${input.nodeId}`);
32685
- if (node.phaseId !== (input.phaseId ?? input.nodeId)) {
32831
+ assertIds(input.trackId, input.executionId, input.nodeId, input.phaseId);
32832
+ if (node.phaseId !== phaseForNode(input.nodeId)) {
32686
32833
  throw new Error(`execution journal identity disagrees for ${input.nodeId}`);
32687
32834
  }
32688
32835
  return { node, nodes: journal.nodes };
@@ -32701,8 +32848,8 @@ function assertJournalAllowsIntegration(input) {
32701
32848
  }
32702
32849
  function assertJournalAllowsCleanup(input) {
32703
32850
  const { node } = journalNode(input);
32704
- if (node.status !== "integrated") {
32705
- throw new Error(`${input.nodeId} must be integrated in the execution journal before cleanup`);
32851
+ if (!["integrated", "completed"].includes(node.status)) {
32852
+ throw new Error(`${input.nodeId} must be integrated or completed in the execution journal before cleanup`);
32706
32853
  }
32707
32854
  }
32708
32855
  function previewWorktreeIntegration(input) {
@@ -32710,8 +32857,8 @@ function previewWorktreeIntegration(input) {
32710
32857
  const root = assertRepository(input.projectRoot);
32711
32858
  const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
32712
32859
  const target = targetIdentity(root, input);
32713
- if (!existsSync7(source.path)) throw new Error(`source worktree is missing: ${source.path}`);
32714
- if (!existsSync7(target.path)) throw new Error(`target worktree is missing: ${target.path}`);
32860
+ if (!existsSync8(source.path)) throw new Error(`source worktree is missing: ${source.path}`);
32861
+ if (!existsSync8(target.path)) throw new Error(`target worktree is missing: ${target.path}`);
32715
32862
  cleanWorktree(source.path);
32716
32863
  cleanWorktree(target.path);
32717
32864
  const checkedSource = git(source.path, ["symbolic-ref", "--short", "HEAD"]).stdout.trim();
@@ -32761,7 +32908,7 @@ function previewWorktreeCleanup(input) {
32761
32908
  const root = assertRepository(input.projectRoot);
32762
32909
  const source = worktreeIdentity(root, input.trackId, input.executionId, input.nodeId, input.phaseId);
32763
32910
  const target = targetIdentity(root, input);
32764
- if (!existsSync7(source.path)) throw new Error(`worktree is missing: ${source.path}`);
32911
+ if (!existsSync8(source.path)) throw new Error(`worktree is missing: ${source.path}`);
32765
32912
  if (lstatSync4(source.path).isSymbolicLink()) throw new Error("refusing to clean up a symbolic-link worktree");
32766
32913
  cleanWorktree(source.path);
32767
32914
  const head = git(source.path, ["rev-parse", "HEAD"]).stdout.trim();
@@ -32782,10 +32929,10 @@ function applyWorktreeCleanup(input, proposalDigest) {
32782
32929
  const root = assertRepository(input.projectRoot);
32783
32930
  git(root, ["worktree", "remove", proposal.path]);
32784
32931
  git(proposal.targetPath, ["branch", "-d", proposal.branch]);
32785
- const managedRoot = join5(root, ".cadre", ".worktrees");
32932
+ const managedRoot = join6(root, ".cadre", ".worktrees");
32786
32933
  let directory = dirname4(proposal.path);
32787
32934
  while (directory.startsWith(`${managedRoot}/`)) {
32788
- if (!existsSync7(directory) || readdirSync4(directory).length) break;
32935
+ if (!existsSync8(directory) || readdirSync5(directory).length) break;
32789
32936
  rmdirSync(directory);
32790
32937
  directory = dirname4(directory);
32791
32938
  }
@@ -32793,7 +32940,7 @@ function applyWorktreeCleanup(input, proposalDigest) {
32793
32940
  }
32794
32941
  function managedWorktreeStatus(projectRoot) {
32795
32942
  const root = assertRepository(projectRoot);
32796
- const managedRoot = join5(root, ".cadre", ".worktrees");
32943
+ const managedRoot = join6(root, ".cadre", ".worktrees");
32797
32944
  const worktrees = registeredWorktrees(root).map((entry) => ({
32798
32945
  ...entry,
32799
32946
  managed: relative3(managedRoot, entry.path) !== "" && !relative3(managedRoot, entry.path).startsWith("..")
@@ -32801,15 +32948,15 @@ function managedWorktreeStatus(projectRoot) {
32801
32948
  const registered = new Set(worktrees.filter((entry) => entry.managed).map((entry) => entry.path));
32802
32949
  const orphanedDirectories = [];
32803
32950
  function walk2(directory) {
32804
- if (!existsSync7(directory)) return;
32805
- if (registered.has(resolve6(directory))) return;
32806
- const entries = readdirSync4(directory, { withFileTypes: true });
32951
+ if (!existsSync8(directory)) return;
32952
+ if (registered.has(resolve7(directory))) return;
32953
+ const entries = readdirSync5(directory, { withFileTypes: true });
32807
32954
  if (entries.some((entry) => entry.name === ".git")) {
32808
32955
  orphanedDirectories.push(directory);
32809
32956
  return;
32810
32957
  }
32811
- for (const entry of entries) if (entry.isDirectory()) walk2(join5(directory, entry.name));
32812
- if (!entries.length && resolve6(directory) !== resolve6(managedRoot)) orphanedDirectories.push(directory);
32958
+ for (const entry of entries) if (entry.isDirectory()) walk2(join6(directory, entry.name));
32959
+ if (!entries.length && resolve7(directory) !== resolve7(managedRoot)) orphanedDirectories.push(directory);
32813
32960
  }
32814
32961
  walk2(managedRoot);
32815
32962
  return { worktrees, orphanedDirectories };
@@ -32818,15 +32965,15 @@ function managedWorktreeStatus(projectRoot) {
32818
32965
  // src/domain/governance.ts
32819
32966
  import { createHash as createHash7 } from "node:crypto";
32820
32967
  import {
32821
- existsSync as existsSync8,
32968
+ existsSync as existsSync9,
32822
32969
  lstatSync as lstatSync5,
32823
32970
  mkdirSync as mkdirSync3,
32824
- readFileSync as readFileSync6,
32825
- readdirSync as readdirSync5,
32971
+ readFileSync as readFileSync7,
32972
+ readdirSync as readdirSync6,
32826
32973
  renameSync as renameSync3,
32827
32974
  writeFileSync as writeFileSync4
32828
32975
  } from "node:fs";
32829
- import { dirname as dirname5, join as join6, relative as relative4 } from "node:path";
32976
+ import { dirname as dirname5, join as join7, relative as relative4 } from "node:path";
32830
32977
  var SHA3 = /^[0-9a-f]{7,40}$/;
32831
32978
  var TRACK_ID3 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32832
32979
  var BATCH_ID = /^archive-[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/;
@@ -32838,7 +32985,7 @@ function json2(value) {
32838
32985
  `;
32839
32986
  }
32840
32987
  function assertWritableFile(path) {
32841
- if (existsSync8(path) && lstatSync5(path).isSymbolicLink()) {
32988
+ if (existsSync9(path) && lstatSync5(path).isSymbolicLink()) {
32842
32989
  throw new Error(`refusing to write through symbolic link ${path}`);
32843
32990
  }
32844
32991
  }
@@ -32875,10 +33022,10 @@ function previewReviewComplete(input) {
32875
33022
  if (!execution?.executionId || !execution.planRevision || !execution.graphDigest || execution.headCommit !== input.reviewedHead) {
32876
33023
  throw new Error("review evidence does not match the current completed execution");
32877
33024
  }
32878
- const statePath = join6(cadreRoot(root), track.location, "state.json");
32879
- const tracksPath = join6(cadreRoot(root), "tracks.md");
32880
- const stateBody = readFileSync6(statePath, "utf8");
32881
- const tracksBody = readFileSync6(tracksPath, "utf8");
33025
+ const statePath = join7(cadreRoot(root), track.location, "state.json");
33026
+ const tracksPath = join7(cadreRoot(root), "tracks.md");
33027
+ const stateBody = readFileSync7(statePath, "utf8");
33028
+ const tracksBody = readFileSync7(tracksPath, "utf8");
32882
33029
  const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
32883
33030
  const cycle = {
32884
33031
  cycle: (current.reviewCycles?.length ?? 0) + 1,
@@ -32928,11 +33075,11 @@ function assertArchiveUpdate(path, selected) {
32928
33075
  function directorySnapshot(path) {
32929
33076
  const files = [];
32930
33077
  function visit(directory) {
32931
- for (const entry of readdirSync5(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
32932
- const target = join6(directory, entry.name);
33078
+ for (const entry of readdirSync6(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
33079
+ const target = join7(directory, entry.name);
32933
33080
  if (entry.isSymbolicLink()) throw new Error(`refusing archive source symbolic link ${target}`);
32934
33081
  if (entry.isDirectory()) visit(target);
32935
- else if (entry.isFile()) files.push({ path: relative4(path, target), content: readFileSync6(target, "utf8") });
33082
+ else if (entry.isFile()) files.push({ path: relative4(path, target), content: readFileSync7(target, "utf8") });
32936
33083
  else throw new Error(`unsupported archive source entry ${target}`);
32937
33084
  }
32938
33085
  }
@@ -32948,8 +33095,8 @@ function previewArchiveBatch(input) {
32948
33095
  }
32949
33096
  if (input.selectedTracks.some((trackId) => !TRACK_ID3.test(trackId))) throw new Error("invalid selected track ID");
32950
33097
  const root = safeProjectRoot(input.projectRoot);
32951
- const operationPath = join6(cadreRoot(root), "operations", `${input.batchId}.json`);
32952
- const existingOperation = existsSync8(operationPath) ? JSON.parse(readFileSync6(operationPath, "utf8")) : null;
33098
+ const operationPath = join7(cadreRoot(root), "operations", `${input.batchId}.json`);
33099
+ const existingOperation = existsSync9(operationPath) ? JSON.parse(readFileSync7(operationPath, "utf8")) : null;
32953
33100
  if (existingOperation && (existingOperation.action !== "archive" || existingOperation.status !== "in_progress" || existingOperation.baseCommit !== input.baseCommit || JSON.stringify(existingOperation.selectedTracks) !== JSON.stringify(input.selectedTracks))) {
32954
33101
  throw new Error(`archive batch ${input.batchId} does not match the approved input`);
32955
33102
  }
@@ -32970,9 +33117,9 @@ function previewArchiveBatch(input) {
32970
33117
  if (existingOperation && existingOperation.approvalDigest !== approvalDigest) {
32971
33118
  throw new Error(`archive batch ${input.batchId} content differs from its approved journal`);
32972
33119
  }
32973
- const activeOperations = join6(cadreRoot(root), "operations");
32974
- const unfinished = existsSync8(activeOperations) ? readdirSync5(activeOperations).filter((file2) => file2.endsWith(".json")).find((file2) => {
32975
- const operation2 = JSON.parse(readFileSync6(join6(activeOperations, file2), "utf8"));
33120
+ const activeOperations = join7(cadreRoot(root), "operations");
33121
+ const unfinished = existsSync9(activeOperations) ? readdirSync6(activeOperations).filter((file2) => file2.endsWith(".json")).find((file2) => {
33122
+ const operation2 = JSON.parse(readFileSync7(join7(activeOperations, file2), "utf8"));
32976
33123
  return operation2.status === "in_progress";
32977
33124
  }) : void 0;
32978
33125
  if (unfinished && unfinished !== `${input.batchId}.json`) {
@@ -32987,9 +33134,9 @@ function previewArchiveBatch(input) {
32987
33134
  if (!pending && !completed || state.operation != null) {
32988
33135
  throw new Error(`${trackId} is not an eligible completed track`);
32989
33136
  }
32990
- const sourcePath = join6(cadreRoot(root), pending ? "tracks" : "archive", trackId);
32991
- const targetPath = join6(cadreRoot(root), "archive", trackId);
32992
- if (pending && existsSync8(targetPath)) throw new Error(`archive target already exists for ${trackId}`);
33137
+ const sourcePath = join7(cadreRoot(root), pending ? "tracks" : "archive", trackId);
33138
+ const targetPath = join7(cadreRoot(root), "archive", trackId);
33139
+ if (pending && existsSync9(targetPath)) throw new Error(`archive target already exists for ${trackId}`);
32993
33140
  return { trackId, sourcePath, targetPath, state: { ...state, status: "archived" }, needsMove: pending };
32994
33141
  });
32995
33142
  const proposedTracks = validation.tracks.map((track) => selected.has(track.id) ? { ...track, status: "archived", location: `archive/${track.id}` } : track);
@@ -33021,12 +33168,12 @@ function previewArchiveBatch(input) {
33021
33168
  artifactProgress: [...moveArtifacts, ...updateArtifacts, "tracks.md"]
33022
33169
  };
33023
33170
  const current = {
33024
- project: readFileSync6(join6(cadreRoot(root), "project.json"), "utf8"),
33025
- tracks: readFileSync6(join6(cadreRoot(root), "tracks.md"), "utf8"),
33171
+ project: readFileSync7(join7(cadreRoot(root), "project.json"), "utf8"),
33172
+ tracks: readFileSync7(join7(cadreRoot(root), "tracks.md"), "utf8"),
33026
33173
  sources: moves.map((move) => ({ trackId: move.trackId, files: directorySnapshot(move.sourcePath) })),
33027
33174
  updates: updates.map((update) => ({
33028
33175
  path: update.path,
33029
- content: existsSync8(join6(cadreRoot(root), update.path)) ? readFileSync6(join6(cadreRoot(root), update.path), "utf8") : null
33176
+ content: existsSync9(join7(cadreRoot(root), update.path)) ? readFileSync7(join7(cadreRoot(root), update.path), "utf8") : null
33030
33177
  }))
33031
33178
  };
33032
33179
  return {
@@ -33035,7 +33182,7 @@ function previewArchiveBatch(input) {
33035
33182
  operation,
33036
33183
  moves,
33037
33184
  writes: updates,
33038
- tracksPath: join6(cadreRoot(root), "tracks.md"),
33185
+ tracksPath: join7(cadreRoot(root), "tracks.md"),
33039
33186
  tracksContent,
33040
33187
  resuming: existingOperation != null,
33041
33188
  digest: hash5({ current, input, initialOperation, operation, moves: moves.map(({ trackId, state, needsMove }) => ({ trackId, state, needsMove })), updates, tracksContent })
@@ -33044,14 +33191,14 @@ function previewArchiveBatch(input) {
33044
33191
  function applyArchiveBatch(input, proposalDigest) {
33045
33192
  const proposal = previewArchiveBatch(input);
33046
33193
  if (proposal.digest !== proposalDigest) throw new Error("archive batch proposal is stale; preview it again");
33047
- const currentOperation = existsSync8(proposal.operationPath) ? JSON.parse(readFileSync6(proposal.operationPath, "utf8")) : proposal.initialOperation;
33048
- if (!existsSync8(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json2(currentOperation));
33049
- mkdirSync3(join6(cadreRoot(input.projectRoot), "archive"), { recursive: true });
33194
+ const currentOperation = existsSync9(proposal.operationPath) ? JSON.parse(readFileSync7(proposal.operationPath, "utf8")) : proposal.initialOperation;
33195
+ if (!existsSync9(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json2(currentOperation));
33196
+ mkdirSync3(join7(cadreRoot(input.projectRoot), "archive"), { recursive: true });
33050
33197
  const completedTracks = new Set(currentOperation.completedTracks);
33051
33198
  const artifactProgress = new Set(currentOperation.artifactProgress);
33052
33199
  for (const move of proposal.moves) {
33053
33200
  if (move.needsMove) renameSync3(move.sourcePath, move.targetPath);
33054
- writeApprovedFile(join6(move.targetPath, "state.json"), json2(move.state));
33201
+ writeApprovedFile(join7(move.targetPath, "state.json"), json2(move.state));
33055
33202
  completedTracks.add(move.trackId);
33056
33203
  artifactProgress.add(`archive/${move.trackId}`);
33057
33204
  writeApprovedFile(proposal.operationPath, json2({
@@ -33061,7 +33208,7 @@ function applyArchiveBatch(input, proposalDigest) {
33061
33208
  }));
33062
33209
  }
33063
33210
  for (const update of proposal.writes) {
33064
- writeApprovedFile(join6(cadreRoot(input.projectRoot), update.path), update.content);
33211
+ writeApprovedFile(join7(cadreRoot(input.projectRoot), update.path), update.content);
33065
33212
  artifactProgress.add(update.path);
33066
33213
  writeApprovedFile(proposal.operationPath, json2({
33067
33214
  ...currentOperation,
@@ -33081,18 +33228,18 @@ function previewArchiveBatchRecord(input) {
33081
33228
  if (!BATCH_ID.test(input.batchId)) throw new Error("invalid archive batchId");
33082
33229
  if (!SHA3.test(input.archiveCommit)) throw new Error("archiveCommit must be a Git commit SHA");
33083
33230
  const root = safeProjectRoot(input.projectRoot);
33084
- const operationPath = join6(cadreRoot(root), "operations", `${input.batchId}.json`);
33085
- const operationBody = readFileSync6(operationPath, "utf8");
33231
+ const operationPath = join7(cadreRoot(root), "operations", `${input.batchId}.json`);
33232
+ const operationBody = readFileSync7(operationPath, "utf8");
33086
33233
  const currentOperation = JSON.parse(operationBody);
33087
33234
  if (currentOperation.action !== "archive" || currentOperation.status !== "in_progress") {
33088
33235
  throw new Error(`${input.batchId} is not an in-progress archive batch`);
33089
33236
  }
33090
- const projectPath = join6(cadreRoot(root), "project.json");
33091
- const projectBody = readFileSync6(projectPath, "utf8");
33237
+ const projectPath = join7(cadreRoot(root), "project.json");
33238
+ const projectBody = readFileSync7(projectPath, "utf8");
33092
33239
  const currentProject = JSON.parse(projectBody);
33093
33240
  const states = currentOperation.selectedTracks.map((trackId) => {
33094
- const path = join6(cadreRoot(root), "archive", trackId, "state.json");
33095
- const body = readFileSync6(path, "utf8");
33241
+ const path = join7(cadreRoot(root), "archive", trackId, "state.json");
33242
+ const body = readFileSync7(path, "utf8");
33096
33243
  const current = JSON.parse(body);
33097
33244
  if (current.status !== "archived") throw new Error(`${trackId} is not archived`);
33098
33245
  return {
@@ -33146,6 +33293,227 @@ function applyArchiveBatchRecord(input, proposalDigest) {
33146
33293
  return { ...proposal, valid: true, derivedStateCurrent: true };
33147
33294
  }
33148
33295
 
33296
+ // src/mcp/elicitation.ts
33297
+ var FIELD_ID = /^[a-z][a-z0-9_]{0,39}$/;
33298
+ var MAX_MESSAGE_LENGTH = 2e3;
33299
+ var MAX_DESCRIPTION_LENGTH = 400;
33300
+ var MAX_TEXT_LENGTH = 4e3;
33301
+ var choiceSchema = external_exports.object({
33302
+ value: external_exports.string().min(1).max(120),
33303
+ label: external_exports.string().min(1).max(120)
33304
+ });
33305
+ var questionBase = {
33306
+ id: external_exports.string().regex(FIELD_ID),
33307
+ label: external_exports.string().min(1).max(120),
33308
+ description: external_exports.string().max(MAX_DESCRIPTION_LENGTH).optional(),
33309
+ required: external_exports.boolean().optional()
33310
+ };
33311
+ var workflowQuestionSchema = external_exports.discriminatedUnion("type", [
33312
+ external_exports.object({
33313
+ ...questionBase,
33314
+ type: external_exports.literal("text"),
33315
+ default: external_exports.string().max(MAX_TEXT_LENGTH).optional()
33316
+ }),
33317
+ external_exports.object({
33318
+ ...questionBase,
33319
+ type: external_exports.literal("boolean"),
33320
+ default: external_exports.boolean().optional()
33321
+ }),
33322
+ external_exports.object({
33323
+ ...questionBase,
33324
+ type: external_exports.literal("number"),
33325
+ minimum: external_exports.number().optional(),
33326
+ maximum: external_exports.number().optional(),
33327
+ default: external_exports.number().optional()
33328
+ }),
33329
+ external_exports.object({
33330
+ ...questionBase,
33331
+ type: external_exports.literal("integer"),
33332
+ minimum: external_exports.number().int().optional(),
33333
+ maximum: external_exports.number().int().optional(),
33334
+ default: external_exports.number().int().optional()
33335
+ }),
33336
+ external_exports.object({
33337
+ ...questionBase,
33338
+ type: external_exports.literal("single_select"),
33339
+ options: external_exports.array(choiceSchema).min(2).max(10),
33340
+ default: external_exports.string().max(120).optional()
33341
+ }),
33342
+ external_exports.object({
33343
+ ...questionBase,
33344
+ type: external_exports.literal("multi_select"),
33345
+ options: external_exports.array(choiceSchema).min(2).max(10),
33346
+ minSelections: external_exports.number().int().min(0).optional(),
33347
+ maxSelections: external_exports.number().int().min(1).optional(),
33348
+ default: external_exports.array(external_exports.string().max(120)).max(10).optional()
33349
+ })
33350
+ ]);
33351
+ var workflowElicitationInputSchema = {
33352
+ kind: external_exports.enum(["approval", "clarification"]),
33353
+ message: external_exports.string().min(1).max(MAX_MESSAGE_LENGTH),
33354
+ binding: external_exports.string().min(1).max(240).optional(),
33355
+ questions: external_exports.array(workflowQuestionSchema).max(3).optional()
33356
+ };
33357
+ function assertUnique(values, message) {
33358
+ if (new Set(values).size !== values.length) throw new Error(message);
33359
+ }
33360
+ function choiceValues(question) {
33361
+ const values = question.options.map((option) => option.value);
33362
+ assertUnique(values, `${question.id} option values must be unique`);
33363
+ return values;
33364
+ }
33365
+ function questionSchema(question) {
33366
+ const common = {
33367
+ title: question.label,
33368
+ ...question.description ? { description: question.description } : {}
33369
+ };
33370
+ switch (question.type) {
33371
+ case "text":
33372
+ return {
33373
+ ...common,
33374
+ type: "string",
33375
+ ...question.required ? { minLength: 1 } : {},
33376
+ maxLength: MAX_TEXT_LENGTH,
33377
+ ...question.default === void 0 ? {} : { default: question.default }
33378
+ };
33379
+ case "boolean":
33380
+ return {
33381
+ ...common,
33382
+ type: "boolean",
33383
+ ...question.default === void 0 ? {} : { default: question.default }
33384
+ };
33385
+ case "number":
33386
+ case "integer": {
33387
+ if (question.minimum !== void 0 && question.maximum !== void 0 && question.minimum > question.maximum) {
33388
+ throw new Error(`${question.id} minimum cannot exceed maximum`);
33389
+ }
33390
+ if (question.default !== void 0 && (question.minimum !== void 0 && question.default < question.minimum || question.maximum !== void 0 && question.default > question.maximum)) {
33391
+ throw new Error(`${question.id} default must be within its numeric bounds`);
33392
+ }
33393
+ return {
33394
+ ...common,
33395
+ type: question.type,
33396
+ ...question.minimum === void 0 ? {} : { minimum: question.minimum },
33397
+ ...question.maximum === void 0 ? {} : { maximum: question.maximum },
33398
+ ...question.default === void 0 ? {} : { default: question.default }
33399
+ };
33400
+ }
33401
+ case "single_select": {
33402
+ const values = choiceValues(question);
33403
+ if (question.default !== void 0 && !values.includes(question.default)) {
33404
+ throw new Error(`${question.id} default must match an option value`);
33405
+ }
33406
+ return {
33407
+ ...common,
33408
+ type: "string",
33409
+ oneOf: question.options.map((option) => ({ const: option.value, title: option.label })),
33410
+ ...question.default === void 0 ? {} : { default: question.default }
33411
+ };
33412
+ }
33413
+ case "multi_select": {
33414
+ const values = choiceValues(question);
33415
+ const minimum = question.minSelections ?? (question.required ? 1 : 0);
33416
+ const maximum = question.maxSelections ?? values.length;
33417
+ if (minimum > maximum || maximum > values.length) {
33418
+ throw new Error(`${question.id} selection bounds are invalid`);
33419
+ }
33420
+ if (question.default?.some((value) => !values.includes(value))) {
33421
+ throw new Error(`${question.id} defaults must match option values`);
33422
+ }
33423
+ return {
33424
+ ...common,
33425
+ type: "array",
33426
+ items: {
33427
+ anyOf: question.options.map((option) => ({ const: option.value, title: option.label }))
33428
+ },
33429
+ minItems: minimum,
33430
+ maxItems: maximum,
33431
+ ...question.default === void 0 ? {} : { default: question.default }
33432
+ };
33433
+ }
33434
+ }
33435
+ }
33436
+ function supportsFormElicitation(capabilities) {
33437
+ const elicitation = capabilities?.elicitation;
33438
+ if (!elicitation) return false;
33439
+ return elicitation.form !== void 0 || elicitation.url === void 0;
33440
+ }
33441
+ function buildWorkflowElicitation(input) {
33442
+ if (input.kind === "approval") {
33443
+ if (!input.binding) throw new Error("approval elicitation requires a proposal or checkpoint binding");
33444
+ if (input.questions?.length) throw new Error("approval elicitation uses the fixed decision form");
33445
+ return {
33446
+ mode: "form",
33447
+ message: `${input.message}
33448
+
33449
+ Approval binding: ${input.binding}`,
33450
+ requestedSchema: {
33451
+ type: "object",
33452
+ properties: {
33453
+ decision: {
33454
+ type: "string",
33455
+ title: "Decision",
33456
+ description: "Approve the bound proposal, request changes, or cancel.",
33457
+ oneOf: [
33458
+ { const: "approve", title: "Approve" },
33459
+ { const: "request_changes", title: "Request changes" },
33460
+ { const: "cancel", title: "Cancel" }
33461
+ ],
33462
+ default: "approve"
33463
+ },
33464
+ notes: {
33465
+ type: "string",
33466
+ title: "Notes",
33467
+ description: "Optional changes, exceptions, or verification notes.",
33468
+ maxLength: MAX_TEXT_LENGTH
33469
+ }
33470
+ },
33471
+ required: ["decision"]
33472
+ }
33473
+ };
33474
+ }
33475
+ const questions = input.questions ?? [];
33476
+ if (!questions.length) throw new Error("clarification elicitation requires at least one question");
33477
+ assertUnique(questions.map((question) => question.id), "clarification question IDs must be unique");
33478
+ return {
33479
+ mode: "form",
33480
+ message: input.message,
33481
+ requestedSchema: {
33482
+ type: "object",
33483
+ properties: Object.fromEntries(questions.map((question) => [question.id, questionSchema(question)])),
33484
+ required: questions.filter((question) => question.required).map((question) => question.id)
33485
+ }
33486
+ };
33487
+ }
33488
+ function fallbackWorkflowElicitation(input, reason) {
33489
+ return {
33490
+ kind: input.kind,
33491
+ status: "fallback_required",
33492
+ ...input.binding ? { binding: input.binding } : {},
33493
+ fallback: `${reason}. Ask the same concise question once in chat; do not retry the form.`
33494
+ };
33495
+ }
33496
+ function normalizeWorkflowElicitation(input, elicited) {
33497
+ if (elicited.action === "decline") {
33498
+ return { kind: input.kind, status: "declined", ...input.binding ? { binding: input.binding } : {} };
33499
+ }
33500
+ if (elicited.action === "cancel") {
33501
+ return { kind: input.kind, status: "cancelled", ...input.binding ? { binding: input.binding } : {} };
33502
+ }
33503
+ const answers = elicited.content ?? {};
33504
+ if (input.kind === "clarification") {
33505
+ return { kind: input.kind, status: "answered", answers };
33506
+ }
33507
+ const decision = answers.decision;
33508
+ const status = decision === "approve" ? "approved" : decision === "request_changes" ? "changes_requested" : "cancelled";
33509
+ return {
33510
+ kind: input.kind,
33511
+ status,
33512
+ ...input.binding ? { binding: input.binding } : {},
33513
+ answers
33514
+ };
33515
+ }
33516
+
33149
33517
  // src/mcp/server.ts
33150
33518
  function result(value, summary) {
33151
33519
  return {
@@ -33153,13 +33521,18 @@ function result(value, summary) {
33153
33521
  structuredContent: value
33154
33522
  };
33155
33523
  }
33524
+ function proposalResult(value) {
33525
+ return result({ ...value, proposalDigest: value.digest });
33526
+ }
33156
33527
  function failure(error51) {
33528
+ const serialized = serializeCadreError(error51);
33157
33529
  return {
33158
33530
  isError: true,
33159
33531
  content: [{
33160
33532
  type: "text",
33161
- text: error51 instanceof Error ? error51.message : String(error51)
33162
- }]
33533
+ text: serialized.message
33534
+ }],
33535
+ structuredContent: { error: serialized }
33163
33536
  };
33164
33537
  }
33165
33538
  function serializableValidation(validation) {
@@ -33172,6 +33545,16 @@ function serializableValidation(validation) {
33172
33545
  warnings: validation.warnings
33173
33546
  };
33174
33547
  }
33548
+ var PLAN_VALIDATION_STATUSES = [
33549
+ "drafting-spec",
33550
+ "drafting-plan",
33551
+ "planned",
33552
+ "in_progress",
33553
+ "ready_for_review",
33554
+ "completed",
33555
+ "archived"
33556
+ ];
33557
+ var MAX_DRAFT_PLAN_CHARACTERS = 256 * 1024;
33175
33558
  function createCadreServer() {
33176
33559
  const server = new McpServer(
33177
33560
  { name: "cadre", version: CADRE_RUNTIME_VERSION },
@@ -33180,12 +33563,34 @@ function createCadreServer() {
33180
33563
  "Cadre provides deterministic, versioned templates and narrow project-state operations.",
33181
33564
  "Read every existing artifact before proposing edits. Never infer file contents.",
33182
33565
  "For any mutation, present the complete proposed artifacts to the human and obtain approval first.",
33566
+ "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.",
33183
33567
  "Call a preview tool immediately before its matching apply tool and pass the returned digest unchanged.",
33184
33568
  "Cadre state is resumable: inspect project_status once at command entry and reserve state_validate for final mutation gates.",
33185
33569
  "The plan is the implementation source of truth. Cadre MCP exposes only constrained, digest-gated Git worktree operations and never approves its own changes."
33186
33570
  ].join(" ")
33187
33571
  }
33188
33572
  );
33573
+ server.registerTool("workflow_elicit", {
33574
+ title: "Collect Cadre workflow input",
33575
+ 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.",
33576
+ inputSchema: workflowElicitationInputSchema,
33577
+ annotations: { readOnlyHint: true, openWorldHint: false }
33578
+ }, async (input) => {
33579
+ let request;
33580
+ try {
33581
+ request = buildWorkflowElicitation(input);
33582
+ } catch (error51) {
33583
+ return failure(error51);
33584
+ }
33585
+ if (!supportsFormElicitation(server.server.getClientCapabilities())) {
33586
+ return result(fallbackWorkflowElicitation(input, "The MCP client does not support form elicitation"));
33587
+ }
33588
+ try {
33589
+ return result(normalizeWorkflowElicitation(input, await server.server.elicitInput(request)));
33590
+ } catch {
33591
+ return result(fallbackWorkflowElicitation(input, "The MCP client or its active policy rejected form elicitation"));
33592
+ }
33593
+ });
33189
33594
  for (const template of templateCatalog()) {
33190
33595
  server.registerResource(
33191
33596
  `template-${template.id.replaceAll("/", "-")}`,
@@ -33278,9 +33683,9 @@ function createCadreServer() {
33278
33683
  }, async ({ projectRoot, trackId }) => {
33279
33684
  try {
33280
33685
  const root = safeProjectRoot(projectRoot);
33281
- const statePath = join7(root, ".cadre", "tracks", trackId, "state.json");
33282
- const planPath = join7(root, ".cadre", "tracks", trackId, "plan.md");
33283
- const state = JSON.parse(readFileSync7(statePath, "utf8"));
33686
+ const statePath = join8(root, ".cadre", "tracks", trackId, "state.json");
33687
+ const planPath = join8(root, ".cadre", "tracks", trackId, "plan.md");
33688
+ const state = JSON.parse(readFileSync8(statePath, "utf8"));
33284
33689
  const errors = [];
33285
33690
  const graph = parsePlan(planPath, errors);
33286
33691
  validatePlanGraph(planPath, graph, state.status ?? "planned", errors);
@@ -33289,6 +33694,26 @@ function createCadreServer() {
33289
33694
  return failure(error51);
33290
33695
  }
33291
33696
  });
33697
+ server.registerTool("execution_graph_validate_draft", {
33698
+ title: "Validate a draft execution graph",
33699
+ description: "Compile and validate an unapproved plan supplied as Markdown without reading or writing project files.",
33700
+ inputSchema: {
33701
+ planMarkdown: external_exports.string().min(1).max(MAX_DRAFT_PLAN_CHARACTERS),
33702
+ targetStatus: external_exports.enum(PLAN_VALIDATION_STATUSES),
33703
+ sourceLabel: external_exports.string().min(1).max(200).regex(/^[^\r\n]+$/).optional()
33704
+ },
33705
+ annotations: { readOnlyHint: true, openWorldHint: false }
33706
+ }, async ({ planMarkdown, targetStatus, sourceLabel }) => {
33707
+ try {
33708
+ const label = sourceLabel ?? "<draft-plan>";
33709
+ const errors = [];
33710
+ const graph = parsePlanContent(planMarkdown, label, errors);
33711
+ validatePlanGraph(label, graph, targetStatus, errors);
33712
+ return result({ valid: errors.length === 0, graph, errors });
33713
+ } catch (error51) {
33714
+ return failure(error51);
33715
+ }
33716
+ });
33292
33717
  const reviewCompleteSchema = {
33293
33718
  projectRoot: external_exports.string().min(1),
33294
33719
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
@@ -33305,7 +33730,7 @@ function createCadreServer() {
33305
33730
  annotations: { readOnlyHint: true, openWorldHint: false }
33306
33731
  }, async (input) => {
33307
33732
  try {
33308
- return result(previewReviewComplete(input));
33733
+ return proposalResult(previewReviewComplete(input));
33309
33734
  } catch (error51) {
33310
33735
  return failure(error51);
33311
33736
  }
@@ -33337,7 +33762,7 @@ function createCadreServer() {
33337
33762
  annotations: { readOnlyHint: true, openWorldHint: false }
33338
33763
  }, async (input) => {
33339
33764
  try {
33340
- return result(previewArchiveBatch(input));
33765
+ return proposalResult(previewArchiveBatch(input));
33341
33766
  } catch (error51) {
33342
33767
  return failure(error51);
33343
33768
  }
@@ -33366,7 +33791,7 @@ function createCadreServer() {
33366
33791
  annotations: { readOnlyHint: true, openWorldHint: false }
33367
33792
  }, async (input) => {
33368
33793
  try {
33369
- return result(previewArchiveBatchRecord(input));
33794
+ return proposalResult(previewArchiveBatchRecord(input));
33370
33795
  } catch (error51) {
33371
33796
  return failure(error51);
33372
33797
  }
@@ -33389,6 +33814,7 @@ function createCadreServer() {
33389
33814
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/),
33390
33815
  requestedMode: external_exports.enum(["parallel", "sequential"]),
33391
33816
  effectiveMode: external_exports.enum(["parallel", "sequential"]),
33817
+ approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES).optional().default("phase"),
33392
33818
  maxWorkers: external_exports.number().int().min(1).max(32),
33393
33819
  baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/),
33394
33820
  approvedAt: external_exports.iso.datetime()
@@ -33400,7 +33826,7 @@ function createCadreServer() {
33400
33826
  annotations: { readOnlyHint: true, openWorldHint: false }
33401
33827
  }, async (input) => {
33402
33828
  try {
33403
- return result(previewExecutionStart(input));
33829
+ return proposalResult(previewExecutionStart(input));
33404
33830
  } catch (error51) {
33405
33831
  return failure(error51);
33406
33832
  }
@@ -33442,7 +33868,7 @@ function createCadreServer() {
33442
33868
  annotations: { readOnlyHint: true, openWorldHint: false }
33443
33869
  }, async (input) => {
33444
33870
  try {
33445
- return result(previewExecutionNodeUpdate(input));
33871
+ return proposalResult(previewExecutionNodeUpdate(input));
33446
33872
  } catch (error51) {
33447
33873
  return failure(error51);
33448
33874
  }
@@ -33470,7 +33896,7 @@ function createCadreServer() {
33470
33896
  annotations: { readOnlyHint: true, openWorldHint: false }
33471
33897
  }, async (input) => {
33472
33898
  try {
33473
- return result(previewExecutionNodesUpdate(input));
33899
+ return proposalResult(previewExecutionNodesUpdate(input));
33474
33900
  } catch (error51) {
33475
33901
  return failure(error51);
33476
33902
  }
@@ -33512,19 +33938,19 @@ function createCadreServer() {
33512
33938
  };
33513
33939
  server.registerTool("execution_finish_preview", {
33514
33940
  title: "Preview completed implementation execution",
33515
- description: "Verify all DAG nodes, plan evidence, and worktree cleanup before proposing ready-for-review state.",
33941
+ description: "Verify all DAG nodes, plan evidence, and worktree cleanup before proposing ready-for-review state and its derived tracks index under one digest.",
33516
33942
  inputSchema: executionFinishSchema,
33517
33943
  annotations: { readOnlyHint: true, openWorldHint: false }
33518
33944
  }, async (input) => {
33519
33945
  try {
33520
- return result(previewExecutionFinish(input));
33946
+ return proposalResult(previewExecutionFinish(input));
33521
33947
  } catch (error51) {
33522
33948
  return failure(error51);
33523
33949
  }
33524
33950
  });
33525
33951
  server.registerTool("execution_finish_apply", {
33526
33952
  title: "Complete implementation execution",
33527
- description: "Finalize an approved execution and mark it ready for review only when the preview is unchanged.",
33953
+ description: "Finalize an approved execution, ready-for-review state, and derived tracks index together only when the preview is unchanged.",
33528
33954
  inputSchema: { ...executionFinishSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
33529
33955
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33530
33956
  }, async ({ proposalDigest, ...input }) => {
@@ -33548,7 +33974,7 @@ function createCadreServer() {
33548
33974
  annotations: { readOnlyHint: true, openWorldHint: false }
33549
33975
  }, async (input) => {
33550
33976
  try {
33551
- return result(previewWorktreeCreate(input));
33977
+ return proposalResult(previewWorktreeCreate(input));
33552
33978
  } catch (error51) {
33553
33979
  return failure(error51);
33554
33980
  }
@@ -33576,7 +34002,7 @@ function createCadreServer() {
33576
34002
  annotations: { readOnlyHint: true, openWorldHint: false }
33577
34003
  }, async (input) => {
33578
34004
  try {
33579
- return result(previewWorktreeIntegration(input));
34005
+ return proposalResult(previewWorktreeIntegration(input));
33580
34006
  } catch (error51) {
33581
34007
  return failure(error51);
33582
34008
  }
@@ -33595,19 +34021,19 @@ function createCadreServer() {
33595
34021
  });
33596
34022
  server.registerTool("worktree_cleanup_preview", {
33597
34023
  title: "Preview worker cleanup",
33598
- description: "Verify a clean worker branch is fully integrated before proposing worktree and branch removal.",
34024
+ description: "Verify a clean worker branch is fully integrated before proposing worktree and branch removal, including recovery after its node was already completed.",
33599
34025
  inputSchema: worktreeSchema,
33600
34026
  annotations: { readOnlyHint: true, openWorldHint: false }
33601
34027
  }, async (input) => {
33602
34028
  try {
33603
- return result(previewWorktreeCleanup(input));
34029
+ return proposalResult(previewWorktreeCleanup(input));
33604
34030
  } catch (error51) {
33605
34031
  return failure(error51);
33606
34032
  }
33607
34033
  });
33608
34034
  server.registerTool("worktree_cleanup_apply", {
33609
34035
  title: "Clean up an integrated worker",
33610
- description: "Remove only a clean, integrated Cadre worktree and its safely deletable branch.",
34036
+ description: "Remove only a clean, fully integrated Cadre worktree and its safely deletable branch, whether its journal node is integrated or already completed.",
33611
34037
  inputSchema: { ...worktreeSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
33612
34038
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
33613
34039
  }, async ({ proposalDigest, ...input }) => {
@@ -33641,19 +34067,19 @@ function createCadreServer() {
33641
34067
  };
33642
34068
  server.registerTool("project_init_preview", {
33643
34069
  title: "Preview Cadre project initialization",
33644
- description: "Validate approved rendered artifacts and return the exact proposed .cadre file set and digest without writing.",
34070
+ 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.",
33645
34071
  inputSchema: initSchema,
33646
34072
  annotations: { readOnlyHint: true, openWorldHint: false }
33647
34073
  }, async (input) => {
33648
34074
  try {
33649
- return result(previewProjectInit(input));
34075
+ return proposalResult(previewProjectInit(input));
33650
34076
  } catch (error51) {
33651
34077
  return failure(error51);
33652
34078
  }
33653
34079
  });
33654
34080
  server.registerTool("project_init_apply", {
33655
34081
  title: "Apply approved Cadre project initialization",
33656
- description: "Atomically create .cadre only when the current proposal matches an approved preview digest.",
34082
+ description: "Atomically create .cadre only when the semantic proposal matches an approved preview digest; records approvedAt as audit metadata.",
33657
34083
  inputSchema: { ...initSchema, proposalDigest: external_exports.string().regex(/^[0-9a-f]{64}$/) },
33658
34084
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
33659
34085
  }, async ({ proposalDigest, ...input }) => {
@@ -33697,7 +34123,7 @@ function createCadreServer() {
33697
34123
  annotations: { readOnlyHint: true, openWorldHint: false }
33698
34124
  }, async ({ projectRoot }) => {
33699
34125
  try {
33700
- return result(renderTracksPreview(safeProjectRoot(projectRoot)));
34126
+ return proposalResult(renderTracksPreview(safeProjectRoot(projectRoot)));
33701
34127
  } catch (error51) {
33702
34128
  return failure(error51);
33703
34129
  }
@@ -33723,7 +34149,7 @@ async function runCadreServer() {
33723
34149
  const server = createCadreServer();
33724
34150
  await server.connect(new StdioServerTransport());
33725
34151
  }
33726
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve8(process.argv[1])).href) {
34152
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve9(process.argv[1])).href) {
33727
34153
  runCadreServer().catch((error51) => {
33728
34154
  process.stderr.write(`${error51 instanceof Error ? error51.message : String(error51)}
33729
34155
  `);