cadre-ai 3.5.0 → 3.5.1

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.
@@ -30972,7 +30972,7 @@ var StdioServerTransport = class {
30972
30972
 
30973
30973
  // src/mcp/server.ts
30974
30974
  import { createHash as createHash8 } from "node:crypto";
30975
- import { readFileSync as readFileSync10 } from "node:fs";
30975
+ import { existsSync as existsSync12, readFileSync as readFileSync10, readdirSync as readdirSync10 } from "node:fs";
30976
30976
  import { join as join10, resolve as resolve12 } from "node:path";
30977
30977
  import { pathToFileURL } from "node:url";
30978
30978
 
@@ -30997,8 +30997,8 @@ import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as rea
30997
30997
  import { isAbsolute, join as join3, relative, resolve as resolve5 } from "node:path";
30998
30998
 
30999
30999
  // src/domain/version.ts
31000
- var CADRE_RUNTIME_VERSION = "3.5.0";
31001
- var LEGACY_RUNTIME_VERSIONS = ["3.4.0", "3.3.0"];
31000
+ var CADRE_RUNTIME_VERSION = "3.5.1";
31001
+ var LEGACY_RUNTIME_VERSIONS = ["3.5.0", "3.4.0", "3.3.0"];
31002
31002
  var TEMPLATE_SET_VERSION = "v2";
31003
31003
  var LEGACY_TEMPLATE_SET_VERSIONS = ["v1"];
31004
31004
 
@@ -31415,10 +31415,14 @@ function hash2(value) {
31415
31415
  return createHash2("sha256").update(JSON.stringify(value)).digest("hex");
31416
31416
  }
31417
31417
  function writeJournalAtomically(path, journal) {
31418
+ writeTextAtomically(path, `${JSON.stringify(journal, null, 2)}
31419
+ `);
31420
+ }
31421
+ function writeTextAtomically(path, content) {
31422
+ if (existsSync4(path) && readFileSync3(path, "utf8") === content) return;
31418
31423
  const temporaryPath = join2(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
31419
31424
  try {
31420
- writeFileSync(temporaryPath, `${JSON.stringify(journal, null, 2)}
31421
- `, { flag: "wx" });
31425
+ writeFileSync(temporaryPath, content, { flag: "wx" });
31422
31426
  renameSync(temporaryPath, path);
31423
31427
  } finally {
31424
31428
  if (existsSync4(temporaryPath)) unlinkSync(temporaryPath);
@@ -31838,15 +31842,6 @@ function executionStatus(projectRoot, trackId, executionId) {
31838
31842
  const journal = readExecution(projectRoot, trackId, executionId);
31839
31843
  return { journal, ...deriveExecutionStatus(journal) };
31840
31844
  }
31841
- var EXECUTION_CHECKPOINT_EVENTS = [
31842
- "start",
31843
- "record_commit",
31844
- "record_integration",
31845
- "record_verification",
31846
- "complete",
31847
- "block",
31848
- "resume"
31849
- ];
31850
31845
  function checkpointUpdates(journal, input) {
31851
31846
  const node = journal.nodes[input.nodeId];
31852
31847
  if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
@@ -32011,6 +32006,21 @@ function applyExecutionCheckpoint(input, proposalDigest, preparedProposal) {
32011
32006
  };
32012
32007
  }
32013
32008
  function deriveExecutionFinishInput(input) {
32009
+ const journal = readExecution(input.projectRoot, input.trackId, input.executionId);
32010
+ if (journal.status === "completed" && journal.headCommit && journal.completedAt) {
32011
+ return { ...input, headCommit: journal.headCommit, completedAt: journal.completedAt };
32012
+ }
32013
+ const { statePath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
32014
+ const state = JSON.parse(readFileSync3(statePath, "utf8"));
32015
+ const priorHead = state.lastExecution?.headCommit;
32016
+ const priorCompletedAt = state.lastExecution?.completedAt;
32017
+ if (state.lastExecution?.executionId === input.executionId && typeof priorHead === "string" && typeof priorCompletedAt === "string") {
32018
+ return {
32019
+ ...input,
32020
+ headCommit: priorHead,
32021
+ completedAt: priorCompletedAt
32022
+ };
32023
+ }
32014
32024
  return {
32015
32025
  ...input,
32016
32026
  headCommit: resolveGitCommit(input.projectRoot),
@@ -32049,7 +32059,8 @@ function previewExecutionFinish(input) {
32049
32059
  const state = JSON.parse(stateBody);
32050
32060
  const journal = JSON.parse(journalBody);
32051
32061
  const operation = state.operation;
32052
- if (operation?.action !== "implement" || operation.executionId !== input.executionId) {
32062
+ const stateAlreadyCompleted = state.status === "ready_for_review" && state.lastExecution?.executionId === input.executionId && state.lastExecution.headCommit === input.headCommit && state.lastExecution.completedAt === input.completedAt;
32063
+ if (!stateAlreadyCompleted && (operation?.action !== "implement" || operation.executionId !== input.executionId)) {
32053
32064
  throw new Error("track does not point to this implementation execution");
32054
32065
  }
32055
32066
  if (!["in_progress", "completed"].includes(journal.status)) throw new Error("execution cannot be completed");
@@ -32093,7 +32104,7 @@ function previewExecutionFinish(input) {
32093
32104
  completedAt: input.completedAt,
32094
32105
  headCommit: input.headCommit
32095
32106
  };
32096
- const completedState = {
32107
+ const completedState = stateAlreadyCompleted ? state : {
32097
32108
  ...state,
32098
32109
  status: "ready_for_review",
32099
32110
  checkpoint: "ready_for_review",
@@ -32140,27 +32151,12 @@ function applyExecutionFinish(input, proposalDigest, preparedProposal) {
32140
32151
  if (lstatSync(proposal.journalPath).isSymbolicLink() || lstatSync(proposal.statePath).isSymbolicLink() || lstatSync(proposal.planPath).isSymbolicLink() || lstatSync(proposal.tracksPath).isSymbolicLink()) {
32141
32152
  throw new Error("refusing to complete execution through a symbolic link");
32142
32153
  }
32143
- const journalTemporaryPath = join2(dirname(proposal.journalPath), `.${basename(proposal.journalPath)}.${process.pid}.${randomUUID()}.tmp`);
32144
- const stateTemporaryPath = join2(dirname(proposal.statePath), `.${basename(proposal.statePath)}.${process.pid}.${randomUUID()}.tmp`);
32145
- const planTemporaryPath = join2(dirname(proposal.planPath), `.${basename(proposal.planPath)}.${process.pid}.${randomUUID()}.tmp`);
32146
- const tracksTemporaryPath = join2(dirname(proposal.tracksPath), `.${basename(proposal.tracksPath)}.${process.pid}.${randomUUID()}.tmp`);
32147
- try {
32148
- writeFileSync(journalTemporaryPath, `${JSON.stringify(proposal.journal, null, 2)}
32149
- `, { flag: "wx" });
32150
- writeFileSync(stateTemporaryPath, `${JSON.stringify(proposal.state, null, 2)}
32151
- `, { flag: "wx" });
32152
- writeFileSync(planTemporaryPath, proposal.planContent, { flag: "wx" });
32153
- writeFileSync(tracksTemporaryPath, proposal.tracksContent, { flag: "wx" });
32154
- renameSync(journalTemporaryPath, proposal.journalPath);
32155
- renameSync(stateTemporaryPath, proposal.statePath);
32156
- renameSync(planTemporaryPath, proposal.planPath);
32157
- renameSync(tracksTemporaryPath, proposal.tracksPath);
32158
- } finally {
32159
- if (existsSync4(journalTemporaryPath)) unlinkSync(journalTemporaryPath);
32160
- if (existsSync4(stateTemporaryPath)) unlinkSync(stateTemporaryPath);
32161
- if (existsSync4(planTemporaryPath)) unlinkSync(planTemporaryPath);
32162
- if (existsSync4(tracksTemporaryPath)) unlinkSync(tracksTemporaryPath);
32163
- }
32154
+ writeTextAtomically(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
32155
+ `);
32156
+ writeTextAtomically(proposal.statePath, `${JSON.stringify(proposal.state, null, 2)}
32157
+ `);
32158
+ writeTextAtomically(proposal.planPath, proposal.planContent);
32159
+ writeTextAtomically(proposal.tracksPath, proposal.tracksContent);
32164
32160
  return proposal;
32165
32161
  }
32166
32162
  function validateExecutionJournal(trackRoot, state, graph, errors) {
@@ -32836,6 +32832,7 @@ import {
32836
32832
  readFileSync as readFileSync5,
32837
32833
  readdirSync as readdirSync4,
32838
32834
  renameSync as renameSync2,
32835
+ rmdirSync,
32839
32836
  unlinkSync as unlinkSync2,
32840
32837
  writeFileSync as writeFileSync3
32841
32838
  } from "node:fs";
@@ -32880,9 +32877,13 @@ function candidateStageRoot(projectRootInput, candidateIdInput) {
32880
32877
  }
32881
32878
  return join4(stageParent, candidateId);
32882
32879
  }
32883
- function prepareCandidateStage(projectRootInput, candidateIdInput) {
32880
+ function prepareCandidateStage(projectRootInput, candidateIdInput, expectedFiles) {
32884
32881
  const projectRoot = safeProjectRoot(projectRootInput);
32885
32882
  const candidateId = normalizeCandidateId(candidateIdInput);
32883
+ const normalizedExpected = expectedFiles?.map(normalizeCandidatePath);
32884
+ if (normalizedExpected && new Set(normalizedExpected).size !== normalizedExpected.length) {
32885
+ throw new Error("Candidate expectedFiles contains duplicate paths");
32886
+ }
32886
32887
  const cadreRoot2 = join4(projectRoot, ".cadre");
32887
32888
  if (existsSync6(cadreRoot2)) {
32888
32889
  const stat = lstatSync3(cadreRoot2);
@@ -32912,7 +32913,24 @@ function prepareCandidateStage(projectRootInput, candidateIdInput) {
32912
32913
  const stagePath = join4(cadreRoot2, "stage", candidateId);
32913
32914
  mkdirSync2(stagePath, { recursive: true });
32914
32915
  candidateStageRoot(projectRoot, candidateId);
32915
- return { stagePath, gitignorePath };
32916
+ const retainedFiles = listCandidatePaths(projectRoot, candidateId);
32917
+ if (normalizedExpected === void 0) return { stagePath, gitignorePath, retainedFiles, removedFiles: [] };
32918
+ const expected = new Set(normalizedExpected);
32919
+ const removedFiles = retainedFiles.filter((path) => !expected.has(path));
32920
+ for (const path of removedFiles) unlinkSync2(join4(stagePath, path));
32921
+ const pruneEmptyDirectories = (directory) => {
32922
+ for (const entry of readdirSync4(directory, { withFileTypes: true })) {
32923
+ if (entry.isDirectory()) pruneEmptyDirectories(join4(directory, entry.name));
32924
+ }
32925
+ if (directory !== stagePath && readdirSync4(directory).length === 0) rmdirSync(directory);
32926
+ };
32927
+ pruneEmptyDirectories(stagePath);
32928
+ return {
32929
+ stagePath,
32930
+ gitignorePath,
32931
+ retainedFiles: retainedFiles.filter((path) => expected.has(path)),
32932
+ removedFiles
32933
+ };
32916
32934
  }
32917
32935
  function assertRegularPath(root, target) {
32918
32936
  const relation = relative2(root, target);
@@ -33282,18 +33300,39 @@ function loadProjectInitCandidate(input) {
33282
33300
  return { ...input, files };
33283
33301
  }
33284
33302
  function previewProjectInitCandidate(input) {
33285
- assertInitializationBootstrap(input.projectRoot);
33286
- return buildProjectInitProposal(loadProjectInitCandidate(input));
33303
+ const proposal = buildProjectInitProposal(loadProjectInitCandidate(input));
33304
+ assertInitializationBootstrap(input.projectRoot, proposal);
33305
+ return proposal;
33287
33306
  }
33288
- function assertInitializationBootstrap(projectRootInput) {
33307
+ function assertInitializationBootstrap(projectRootInput, proposal) {
33289
33308
  const root = safeProjectRoot(projectRootInput);
33290
33309
  const cadreRoot2 = join6(root, ".cadre");
33291
33310
  if (!existsSync8(cadreRoot2) || !lstatSync4(cadreRoot2).isDirectory() || lstatSync4(cadreRoot2).isSymbolicLink()) {
33292
33311
  throw new Error(`${cadreRoot2} must be a prepared candidate-stage directory`);
33293
33312
  }
33294
- const unexpected = readdirSync6(cadreRoot2).filter((entry) => ![".gitignore", "stage"].includes(entry));
33295
- if (unexpected.length) {
33296
- throw new Error(`${cadreRoot2} already contains canonical project state: ${unexpected.sort().join(", ")}`);
33313
+ const expected = new Map(proposal.files.map((file2) => [file2.path, file2.content]));
33314
+ const visit = (directory) => {
33315
+ for (const entry of readdirSync6(directory, { withFileTypes: true })) {
33316
+ const target = join6(directory, entry.name);
33317
+ const path = relative4(cadreRoot2, target).replaceAll("\\", "/");
33318
+ if (path === "stage" || path.startsWith("stage/")) continue;
33319
+ if (entry.isSymbolicLink()) throw new Error(`Refusing symbolic link inside initialization state: ${target}`);
33320
+ if (entry.isDirectory()) {
33321
+ visit(target);
33322
+ continue;
33323
+ }
33324
+ if (!entry.isFile()) throw new Error(`Unsupported initialization state entry: ${target}`);
33325
+ const content = expected.get(path);
33326
+ if (content === void 0) throw new Error(`${cadreRoot2} contains unexpected canonical state: ${path}`);
33327
+ if (readFileSync7(target, "utf8") !== content) {
33328
+ throw new Error(`Interrupted initialization disagrees at ${path}`);
33329
+ }
33330
+ }
33331
+ };
33332
+ visit(cadreRoot2);
33333
+ const canonicalEntries = readdirSync6(cadreRoot2).filter((entry) => ![".gitignore", "stage"].includes(entry));
33334
+ if (canonicalEntries.length && !canonicalEntries.some((entry) => proposal.files.some((file2) => file2.path === entry || file2.path.startsWith(`${entry}/`)))) {
33335
+ throw new Error(`${cadreRoot2} contains unrelated canonical project state`);
33297
33336
  }
33298
33337
  }
33299
33338
  function targetWithin(root, relativePath) {
@@ -33394,7 +33433,7 @@ function recordGitInitialized(projectRootInput) {
33394
33433
 
33395
33434
  // src/domain/worktrees.ts
33396
33435
  import { createHash as createHash6 } from "node:crypto";
33397
- import { existsSync as existsSync9, lstatSync as lstatSync5, readdirSync as readdirSync7, realpathSync as realpathSync2, rmdirSync } from "node:fs";
33436
+ import { existsSync as existsSync9, lstatSync as lstatSync5, readdirSync as readdirSync7, realpathSync as realpathSync2, rmdirSync as rmdirSync2 } from "node:fs";
33398
33437
  import { dirname as dirname4, join as join7, relative as relative5, resolve as resolve9 } from "node:path";
33399
33438
  import { spawnSync as spawnSync2 } from "node:child_process";
33400
33439
  var SHA2 = /^[0-9a-f]{7,40}$/;
@@ -33644,7 +33683,7 @@ function applyWorktreeCleanup(input, proposalDigest, preparedProposal) {
33644
33683
  let directory = dirname4(proposal.path);
33645
33684
  while (directory.startsWith(`${managedRoot}/`)) {
33646
33685
  if (!existsSync9(directory) || readdirSync7(directory).length) break;
33647
- rmdirSync(directory);
33686
+ rmdirSync2(directory);
33648
33687
  directory = dirname4(directory);
33649
33688
  }
33650
33689
  return { removedPath: proposal.path, removedBranch: proposal.branch };
@@ -33677,7 +33716,7 @@ function managedWorktreeStatus(projectRoot) {
33677
33716
  }
33678
33717
 
33679
33718
  // src/domain/governance.ts
33680
- import { createHash as createHash7 } from "node:crypto";
33719
+ import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";
33681
33720
  import {
33682
33721
  existsSync as existsSync10,
33683
33722
  lstatSync as lstatSync6,
@@ -33685,6 +33724,7 @@ import {
33685
33724
  readFileSync as readFileSync8,
33686
33725
  readdirSync as readdirSync8,
33687
33726
  renameSync as renameSync4,
33727
+ unlinkSync as unlinkSync4,
33688
33728
  writeFileSync as writeFileSync5
33689
33729
  } from "node:fs";
33690
33730
  import { dirname as dirname5, join as join8, relative as relative6 } from "node:path";
@@ -33709,7 +33749,14 @@ function assertWritableFile(path) {
33709
33749
  function writeApprovedFile(path, content) {
33710
33750
  assertWritableFile(path);
33711
33751
  mkdirSync4(dirname5(path), { recursive: true });
33712
- writeFileSync5(path, content);
33752
+ if (existsSync10(path) && readFileSync8(path, "utf8") === content) return;
33753
+ const temporaryPath = join8(dirname5(path), `.${randomUUID3()}.cadre.tmp`);
33754
+ try {
33755
+ writeFileSync5(temporaryPath, content, { flag: "wx" });
33756
+ renameSync4(temporaryPath, path);
33757
+ } finally {
33758
+ if (existsSync10(temporaryPath)) unlinkSync4(temporaryPath);
33759
+ }
33713
33760
  }
33714
33761
  function requireCurrentProject(projectRoot) {
33715
33762
  const validation = validateProject(projectRoot);
@@ -33721,19 +33768,27 @@ function deriveReviewCompleteInput(input) {
33721
33768
  const validation = requireCurrentProject(input.projectRoot);
33722
33769
  const state = validation.states.get(input.trackId);
33723
33770
  const reviewedHead = state?.lastExecution?.headCommit;
33771
+ const executionId = state?.lastExecution?.executionId;
33724
33772
  if (!reviewedHead || !SHA3.test(reviewedHead)) throw new Error(`${input.trackId} has no completed execution head`);
33773
+ if (!executionId) throw new Error(`${input.trackId} has no completed execution journal`);
33774
+ const execution = executionStatus(input.projectRoot, input.trackId, executionId).journal;
33775
+ if (execution.status !== "completed" || execution.headCommit !== reviewedHead || !SHA3.test(execution.baseCommit)) {
33776
+ throw new Error(`${input.trackId} completed execution evidence is inconsistent`);
33777
+ }
33725
33778
  if (!isGitAncestor(input.projectRoot, reviewedHead)) {
33726
33779
  throw new Error(`completed execution head ${reviewedHead} is not an ancestor of current HEAD`);
33727
33780
  }
33728
- const commitRangeStart = resolveGitCommit(input.projectRoot, input.commitRangeStart);
33781
+ const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
33782
+ const existingCycle = state.status === "completed" ? state.reviewCycles?.at(-1) : void 0;
33783
+ const matchingCycle = existingCycle && existingCycle.outcome === "clean" && existingCycle.executionId === executionId && existingCycle.reviewedHead === reviewedHead && existingCycle.approval === input.approval && JSON.stringify(existingCycle.acceptedRisks ?? []) === JSON.stringify(acceptedRisks) ? existingCycle : void 0;
33729
33784
  return {
33730
33785
  projectRoot: input.projectRoot,
33731
33786
  trackId: input.trackId,
33732
- reviewedAt: (/* @__PURE__ */ new Date()).toISOString(),
33787
+ reviewedAt: typeof matchingCycle?.reviewedAt === "string" ? matchingCycle.reviewedAt : (/* @__PURE__ */ new Date()).toISOString(),
33733
33788
  reviewedHead,
33734
- commitRange: `${commitRangeStart}..${reviewedHead}`,
33789
+ commitRange: `${execution.baseCommit}..${reviewedHead}`,
33735
33790
  approval: input.approval,
33736
- ...input.acceptedRisks ? { acceptedRisks: input.acceptedRisks } : {}
33791
+ ...acceptedRisks.length ? { acceptedRisks } : {}
33737
33792
  };
33738
33793
  }
33739
33794
  function previewReviewComplete(input) {
@@ -33750,9 +33805,7 @@ function previewReviewComplete(input) {
33750
33805
  const track = validation.tracks.find((candidate) => candidate.id === input.trackId);
33751
33806
  const current = validation.states.get(input.trackId);
33752
33807
  if (!track || !current) throw new Error(`unknown track ${input.trackId}`);
33753
- if (track.location !== `tracks/${input.trackId}` || current.status !== "ready_for_review") {
33754
- throw new Error(`${input.trackId} is not ready for review`);
33755
- }
33808
+ if (track.location !== `tracks/${input.trackId}`) throw new Error(`${input.trackId} is not an active track`);
33756
33809
  if (current.operation != null) throw new Error(`${input.trackId} already has an active operation`);
33757
33810
  const execution = current.lastExecution;
33758
33811
  if (!execution?.executionId || !execution.planRevision || !execution.graphDigest || execution.headCommit !== input.reviewedHead) {
@@ -33764,7 +33817,7 @@ function previewReviewComplete(input) {
33764
33817
  const tracksBody = readFileSync8(tracksPath, "utf8");
33765
33818
  const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
33766
33819
  const cycle = {
33767
- cycle: (current.reviewCycles?.length ?? 0) + 1,
33820
+ cycle: current.status === "completed" ? current.reviewCycles?.length ?? 0 : (current.reviewCycles?.length ?? 0) + 1,
33768
33821
  reviewedAt: input.reviewedAt,
33769
33822
  outcome: "clean",
33770
33823
  executionId: execution.executionId,
@@ -33775,7 +33828,10 @@ function previewReviewComplete(input) {
33775
33828
  approval: input.approval,
33776
33829
  ...acceptedRisks.length ? { acceptedRisks } : {}
33777
33830
  };
33778
- const state = {
33831
+ const existingCycle = current.reviewCycles?.at(-1);
33832
+ const resuming = current.status === "completed" && JSON.stringify(existingCycle) === JSON.stringify(cycle);
33833
+ if (current.status !== "ready_for_review" && !resuming) throw new Error(`${input.trackId} is not ready for review`);
33834
+ const state = resuming ? current : {
33779
33835
  ...current,
33780
33836
  status: "completed",
33781
33837
  checkpoint: "completed",
@@ -33788,12 +33844,15 @@ function previewReviewComplete(input) {
33788
33844
  state,
33789
33845
  tracksPath,
33790
33846
  tracksContent,
33791
- digest: hash5({ stateBody, tracksBody, input, state, tracksContent })
33847
+ digest: hash5({ stateBody, tracksBody, input, state, tracksContent }),
33848
+ resuming
33792
33849
  };
33793
33850
  }
33794
33851
  function applyReviewComplete(input, proposalDigest) {
33795
33852
  const proposal = previewReviewComplete(input);
33796
- if (proposal.digest !== proposalDigest) throw new Error("review completion proposal is stale; preview it again");
33853
+ if (proposal.digest !== proposalDigest && !proposal.resuming) {
33854
+ throw new Error("review completion proposal is stale; preview it again");
33855
+ }
33797
33856
  writeApprovedFile(proposal.statePath, json2(proposal.state));
33798
33857
  writeApprovedFile(proposal.tracksPath, proposal.tracksContent);
33799
33858
  const validation = validateProject(input.projectRoot);
@@ -33945,7 +34004,11 @@ function previewMaterializedArchiveBatch(input) {
33945
34004
  if (existingOperation && (existingOperation.action !== "archive" || existingOperation.status !== "in_progress" || existingOperation.baseCommit !== input.baseCommit || JSON.stringify(existingOperation.selectedTracks) !== JSON.stringify(input.selectedTracks))) {
33946
34005
  throw new Error(`archive batch ${input.batchId} does not match the approved input`);
33947
34006
  }
33948
- const validation = requireCurrentProject(root);
34007
+ const validation = validateProject(root);
34008
+ const recoverableErrors = existingOperation ? new Set(existingOperation.selectedTracks.map((trackId) => `${trackId}: status completed requires location tracks/${trackId}`)) : /* @__PURE__ */ new Set();
34009
+ const blockingErrors = validation.errors.filter((error51) => !recoverableErrors.has(error51));
34010
+ if (blockingErrors.length) throw new Error(blockingErrors.join("\n"));
34011
+ if (!validation.project) throw new Error("Cadre project state is unavailable");
33949
34012
  const selected = new Set(input.selectedTracks);
33950
34013
  const updates = input.updates.map((update) => ({ ...update, path: update.path.replaceAll("\\", "/") }));
33951
34014
  if (new Set(updates.map((update) => update.path)).size !== updates.length) {
@@ -33975,8 +34038,8 @@ function previewMaterializedArchiveBatch(input) {
33975
34038
  const state = validation.states.get(trackId);
33976
34039
  if (!track || !state) throw new Error(`unknown selected track ${trackId}`);
33977
34040
  const pending = track.status === "completed" && track.location === `tracks/${trackId}`;
33978
- const completed = existingOperation?.completedTracks.includes(trackId) && track.status === "archived" && track.location === `archive/${trackId}`;
33979
- if (!pending && !completed || state.operation != null) {
34041
+ const partiallyPromoted = existingOperation != null && ["completed", "archived"].includes(track.status) && track.location === `archive/${trackId}`;
34042
+ if (!pending && !partiallyPromoted || state.operation != null) {
33980
34043
  throw new Error(`${trackId} is not an eligible completed track`);
33981
34044
  }
33982
34045
  const sourcePath = join8(cadreRoot(root), pending ? "tracks" : "archive", trackId);
@@ -34036,7 +34099,12 @@ function previewMaterializedArchiveBatch(input) {
34036
34099
  }
34037
34100
  function applyMaterializedArchiveBatch(input, proposalDigest) {
34038
34101
  const proposal = previewMaterializedArchiveBatch(input);
34039
- if (proposal.digest !== proposalDigest) throw new Error("archive batch proposal is stale; preview it again");
34102
+ if (proposal.digest !== proposalDigest) {
34103
+ const existing = existsSync10(proposal.operationPath) ? JSON.parse(readFileSync8(proposal.operationPath, "utf8")) : null;
34104
+ if (!proposal.resuming || existing?.approvalDigest !== proposal.initialOperation.approvalDigest) {
34105
+ throw new Error("archive batch proposal is stale; preview it again");
34106
+ }
34107
+ }
34040
34108
  const currentOperation = existsSync10(proposal.operationPath) ? JSON.parse(readFileSync8(proposal.operationPath, "utf8")) : proposal.initialOperation;
34041
34109
  if (!existsSync10(proposal.operationPath)) writeApprovedFile(proposal.operationPath, json2(currentOperation));
34042
34110
  mkdirSync4(join8(cadreRoot(input.projectRoot), "archive"), { recursive: true });
@@ -34080,8 +34148,8 @@ function previewArchiveBatchRecord(input) {
34080
34148
  const operationPath = join8(cadreRoot(root), "operations", `${input.batchId}.json`);
34081
34149
  const operationBody = readFileSync8(operationPath, "utf8");
34082
34150
  const currentOperation = JSON.parse(operationBody);
34083
- if (currentOperation.action !== "archive" || currentOperation.status !== "in_progress") {
34084
- throw new Error(`${input.batchId} is not an in-progress archive batch`);
34151
+ if (currentOperation.action !== "archive" || !["in_progress", "completed"].includes(currentOperation.status) || currentOperation.status === "completed" && currentOperation.archiveCommit !== input.archiveCommit) {
34152
+ throw new Error(`${input.batchId} is not a matching archive batch`);
34085
34153
  }
34086
34154
  const projectPath = join8(cadreRoot(root), "project.json");
34087
34155
  const projectBody = readFileSync8(projectPath, "utf8");
@@ -34091,13 +34159,21 @@ function previewArchiveBatchRecord(input) {
34091
34159
  const body = readFileSync8(path, "utf8");
34092
34160
  const current = JSON.parse(body);
34093
34161
  if (current.status !== "archived") throw new Error(`${trackId} is not archived`);
34162
+ const existingCommit = current.commits?.archive;
34163
+ if (existingCommit && existingCommit !== input.archiveCommit) {
34164
+ throw new Error(`${trackId} archive commit differs from the current batch`);
34165
+ }
34166
+ const existingHistory = (Array.isArray(current.history) ? current.history : []).find((entry) => typeof entry === "object" && entry !== null && entry.action === "archive" && entry.batchId === input.batchId);
34167
+ if (existingHistory && existingHistory.commit !== input.archiveCommit) {
34168
+ throw new Error(`${trackId} archive history differs from the current batch`);
34169
+ }
34094
34170
  return {
34095
34171
  path,
34096
34172
  body,
34097
34173
  state: {
34098
34174
  ...current,
34099
34175
  commits: { ...current.commits ?? {}, archive: input.archiveCommit },
34100
- history: [...Array.isArray(current.history) ? current.history : [], {
34176
+ history: existingHistory ? current.history : [...Array.isArray(current.history) ? current.history : [], {
34101
34177
  action: "archive",
34102
34178
  batchId: input.batchId,
34103
34179
  commit: input.archiveCommit
@@ -34105,9 +34181,13 @@ function previewArchiveBatchRecord(input) {
34105
34181
  }
34106
34182
  };
34107
34183
  });
34184
+ const existingProjectHistory = (currentProject.history ?? []).find((entry) => typeof entry === "object" && entry !== null && entry.action === "archive" && entry.batchId === input.batchId);
34185
+ if (existingProjectHistory && existingProjectHistory.commit !== input.archiveCommit) {
34186
+ throw new Error(`project archive history differs for ${input.batchId}`);
34187
+ }
34108
34188
  const project = {
34109
34189
  ...currentProject,
34110
- history: [...currentProject.history ?? [], {
34190
+ history: existingProjectHistory ? currentProject.history ?? [] : [...currentProject.history ?? [], {
34111
34191
  action: "archive",
34112
34192
  batchId: input.batchId,
34113
34193
  tracks: [...currentOperation.selectedTracks],
@@ -34317,7 +34397,7 @@ import {
34317
34397
  openSync,
34318
34398
  readFileSync as readFileSync9,
34319
34399
  readdirSync as readdirSync9,
34320
- unlinkSync as unlinkSync4,
34400
+ unlinkSync as unlinkSync5,
34321
34401
  writeFileSync as writeFileSync6
34322
34402
  } from "node:fs";
34323
34403
  import { homedir as homedir2 } from "node:os";
@@ -34490,7 +34570,7 @@ var ProposalTokenStore = class {
34490
34570
  }
34491
34571
  unlinkRecord(path) {
34492
34572
  try {
34493
- unlinkSync4(path);
34573
+ unlinkSync5(path);
34494
34574
  } catch (error51) {
34495
34575
  if (error51.code !== "ENOENT") throw error51;
34496
34576
  }
@@ -34560,6 +34640,9 @@ function sha256(content) {
34560
34640
  function artifact(path, content) {
34561
34641
  return { path, sha256: sha256(content) };
34562
34642
  }
34643
+ function candidateManifest(files) {
34644
+ return files.map((file2) => artifact(file2.path, file2.content)).sort((left, right) => left.path.localeCompare(right.path));
34645
+ }
34563
34646
  function jsonArtifact(path, value) {
34564
34647
  return artifact(path, `${JSON.stringify(value, null, 2)}
34565
34648
  `);
@@ -34582,17 +34665,13 @@ function requireCurrentProject2(projectRoot) {
34582
34665
  }
34583
34666
  return root;
34584
34667
  }
34585
- var adaptiveModeSchema = external_exports.enum(["prepare", "apply"]);
34586
34668
  function adaptiveInputSchema(prepare) {
34587
- const optionalPrepare = Object.fromEntries(Object.entries(prepare).map(([key, schema]) => [
34588
- key,
34589
- schema.optional()
34590
- ]));
34591
- return external_exports.object({
34592
- mode: adaptiveModeSchema,
34593
- proposalToken: proposalTokenSchema.optional(),
34594
- ...optionalPrepare
34595
- }).strict();
34669
+ return {
34670
+ request: external_exports.discriminatedUnion("mode", [
34671
+ external_exports.strictObject({ mode: external_exports.literal("prepare"), ...prepare }),
34672
+ external_exports.strictObject({ mode: external_exports.literal("apply"), proposalToken: proposalTokenSchema })
34673
+ ])
34674
+ };
34596
34675
  }
34597
34676
  function normalizeAdaptiveInput(input, requiredPrepareFields, command) {
34598
34677
  const prepareFields = Object.keys(input).filter((key) => key !== "mode" && key !== "proposalToken");
@@ -34680,6 +34759,48 @@ function projectStatusView(validation) {
34680
34759
  warnings: validation.warnings
34681
34760
  };
34682
34761
  }
34762
+ function focusedValidationErrors(validation, root, trackIds) {
34763
+ const markers = trackIds.flatMap((id) => [
34764
+ `${id}:`,
34765
+ join10(root, ".cadre", "tracks", id),
34766
+ join10(root, ".cadre", "archive", id),
34767
+ `/${id}/`
34768
+ ]);
34769
+ return validation.errors.filter((error51) => markers.some((marker) => error51.includes(marker)));
34770
+ }
34771
+ function stagedTrackCandidates(root, validation) {
34772
+ const stageRoot = join10(root, ".cadre", "stage");
34773
+ if (!existsSync12(stageRoot)) return [];
34774
+ return readdirSync10(stageRoot, { withFileTypes: true }).filter((entry) => entry.name.startsWith("track-") && entry.name.length > "track-".length).map((entry) => {
34775
+ const candidateId = entry.name;
34776
+ const trackId = candidateId.slice("track-".length);
34777
+ const canonical = validation.tracks.find((track) => track.id === trackId);
34778
+ const canonicalState = canonical?.location.startsWith("archive/") ? "archived" : canonical ? "active" : [join10(root, ".cadre", "tracks", trackId), join10(root, ".cadre", "archive", trackId)].some((path) => existsSync12(path)) ? "invalid" : "absent";
34779
+ try {
34780
+ const paths = listCandidatePaths(root, candidateId);
34781
+ const files = candidateManifest(readCandidateFiles(root, candidateId, paths));
34782
+ return {
34783
+ trackId,
34784
+ candidateId,
34785
+ canonicalState,
34786
+ valid: true,
34787
+ files,
34788
+ errors: [],
34789
+ nextAction: canonicalState === "absent" ? "Resume the unapproved proposal with the track workflow and candidate_inspect." : "Reconcile the matching canonical operation, then remove the stage only after approved hashes and provenance are recorded."
34790
+ };
34791
+ } catch (error51) {
34792
+ return {
34793
+ trackId,
34794
+ candidateId,
34795
+ canonicalState,
34796
+ valid: false,
34797
+ files: [],
34798
+ errors: [serializeCadreError(error51).message],
34799
+ nextAction: "Repair or remove the unsafe staged candidate before resuming it."
34800
+ };
34801
+ }
34802
+ }).sort((left, right) => left.trackId.localeCompare(right.trackId));
34803
+ }
34683
34804
  var PLAN_VALIDATION_STATUSES = [
34684
34805
  "drafting-spec",
34685
34806
  "drafting-plan",
@@ -34738,7 +34859,7 @@ function createCadreServer() {
34738
34859
  );
34739
34860
  server.registerTool(CADRE_MCP_TOOLS.workflowElicit, {
34740
34861
  title: "Collect Cadre workflow input",
34741
- description: "Present one read-only Cadre approval or clarification form. Skip it under non-interactive host policy, bind approvals to an immutable digest or checkpoint, never request secrets, and use its chat fallback once.",
34862
+ description: "Request a decision.",
34742
34863
  inputSchema: workflowElicitationInputSchema,
34743
34864
  annotations: { readOnlyHint: true, openWorldHint: false }
34744
34865
  }, async (input) => {
@@ -34771,7 +34892,7 @@ function createCadreServer() {
34771
34892
  }
34772
34893
  server.registerTool(CADRE_MCP_TOOLS.templateGetMany, {
34773
34894
  title: "Get multiple Cadre templates",
34774
- description: "Read ordered immutable Cadre templates in one call.",
34895
+ description: "Read templates.",
34775
34896
  inputSchema: {
34776
34897
  ids: external_exports.array(external_exports.enum(TEMPLATE_IDS)).min(1),
34777
34898
  contentMode: external_exports.enum(["embedded_resource", "text"]).optional().default("embedded_resource")
@@ -34786,7 +34907,7 @@ function createCadreServer() {
34786
34907
  });
34787
34908
  server.registerTool(CADRE_MCP_TOOLS.styleguideResolve, {
34788
34909
  title: "Resolve default styleguides",
34789
- description: "Resolve the bundled idiomatic styleguides relevant to an approved technology list.",
34910
+ description: "Resolve styleguides.",
34790
34911
  inputSchema: { technologies: external_exports.array(external_exports.string()).min(1) },
34791
34912
  annotations: { readOnlyHint: true, openWorldHint: false }
34792
34913
  }, async ({ technologies }) => {
@@ -34804,7 +34925,7 @@ function createCadreServer() {
34804
34925
  });
34805
34926
  server.registerTool(CADRE_MCP_TOOLS.projectStatus, {
34806
34927
  title: "Read Cadre project status",
34807
- description: "Read compact project, focused track, or implementation status with embedded validation.",
34928
+ description: "Read project status.",
34808
34929
  inputSchema: {
34809
34930
  projectRoot: external_exports.string().min(1),
34810
34931
  view: external_exports.enum(["project", "track", "implementation"]).optional().default("project"),
@@ -34824,15 +34945,55 @@ function createCadreServer() {
34824
34945
  worktreeRuntime = null;
34825
34946
  }
34826
34947
  return result(
34827
- { ...projectStatusView(validation), worktreeRuntime },
34948
+ { ...projectStatusView(validation), stagedTrackCandidates: stagedTrackCandidates(root, validation), worktreeRuntime },
34828
34949
  `Cadre project ${validation.errors.length ? "has validation errors" : "is valid"}; ${validation.tracks.length} track${validation.tracks.length === 1 ? "" : "s"}.`
34829
34950
  );
34830
34951
  }
34831
34952
  if (!trackId) throw new Error(`${view} project_status requires trackId`);
34832
34953
  const track = validation.tracks.find((candidate) => candidate.id === trackId);
34833
- if (!track) throw new Error(`unknown Cadre track ${trackId}`);
34954
+ const stagedCandidate = stagedTrackCandidates(root, validation).find((candidate) => candidate.trackId === trackId);
34955
+ if (!track) {
34956
+ const canonicalPaths = [
34957
+ join10(root, ".cadre", "tracks", trackId),
34958
+ join10(root, ".cadre", "archive", trackId)
34959
+ ];
34960
+ if (canonicalPaths.some((path) => existsSync12(path))) {
34961
+ throw new CadreError(
34962
+ "TRACK_STATE_INVALID",
34963
+ `Cadre track ${trackId} has a canonical directory but its state is invalid or unreadable.`,
34964
+ {
34965
+ trackId,
34966
+ errors: validation.errors.filter((error51) => error51.includes(trackId))
34967
+ }
34968
+ );
34969
+ }
34970
+ const candidateId = `track-${trackId}`;
34971
+ if (!stagedCandidate) throw new Error(`unknown Cadre track ${trackId}`);
34972
+ if (view === "implementation") {
34973
+ throw new CadreError(
34974
+ "TRACK_CANDIDATE_ONLY",
34975
+ `Cadre track ${trackId} has a staged candidate but no canonical state; resume it with track status and candidate_inspect before implementation.`,
34976
+ { trackId, candidateId }
34977
+ );
34978
+ }
34979
+ return result({
34980
+ kind: "staged_track_candidate",
34981
+ valid: validation.errors.length === 0 && stagedCandidate.valid,
34982
+ derivedStateCurrent: validation.warnings.length === 0,
34983
+ upgradeRequired: validation.project?.runtimeVersion !== CADRE_RUNTIME_VERSION || validation.project?.templateSetVersion !== TEMPLATE_SET_VERSION,
34984
+ targetRuntimeVersion: CADRE_RUNTIME_VERSION,
34985
+ targetTemplateSetVersion: TEMPLATE_SET_VERSION,
34986
+ trackId,
34987
+ candidate: stagedCandidate,
34988
+ errors: [...validation.errors, ...stagedCandidate.errors],
34989
+ focusedErrors: [...focusedValidationErrors(validation, root, [trackId]), ...stagedCandidate.errors],
34990
+ warnings: validation.warnings,
34991
+ nextAction: "Resume the track proposal with candidate_inspect; do not create canonical state before approval."
34992
+ }, `${trackId}: staged track candidate awaiting inspection or approval.`);
34993
+ }
34834
34994
  const dependencies = (track.dependencies ?? []).map((id) => validation.tracks.find((candidate) => candidate.id === id)).filter((candidate) => Boolean(candidate)).map(trackSummary);
34835
34995
  const focused = {
34996
+ kind: "canonical_track",
34836
34997
  valid: validation.errors.length === 0,
34837
34998
  derivedStateCurrent: validation.warnings.length === 0,
34838
34999
  upgradeRequired: validation.project?.runtimeVersion !== CADRE_RUNTIME_VERSION || validation.project?.templateSetVersion !== TEMPLATE_SET_VERSION,
@@ -34841,7 +35002,9 @@ function createCadreServer() {
34841
35002
  track: trackSummary(track),
34842
35003
  state: validation.states.get(trackId) ?? null,
34843
35004
  dependencies,
34844
- errors: validation.errors.filter((error51) => error51.startsWith(`${trackId}:`) || error51.startsWith("project.json:")),
35005
+ errors: validation.errors,
35006
+ focusedErrors: focusedValidationErrors(validation, root, [trackId, ...dependencies.map((dependency) => dependency.id)]),
35007
+ ...stagedCandidate ? { stagedCandidate } : {},
34845
35008
  warnings: validation.warnings
34846
35009
  };
34847
35010
  if (view === "track") {
@@ -34868,7 +35031,7 @@ function createCadreServer() {
34868
35031
  });
34869
35032
  server.registerTool(CADRE_MCP_TOOLS.stateValidate, {
34870
35033
  title: "Validate Cadre project state",
34871
- description: "Validate Cadre project invariants and return all discovered tracks and errors.",
35034
+ description: "Validate state.",
34872
35035
  inputSchema: { projectRoot: external_exports.string().min(1) },
34873
35036
  annotations: { readOnlyHint: true, openWorldHint: false }
34874
35037
  }, async ({ projectRoot }) => {
@@ -34880,34 +35043,41 @@ function createCadreServer() {
34880
35043
  });
34881
35044
  server.registerTool(CADRE_MCP_TOOLS.candidateStagePrepare, {
34882
35045
  title: "Prepare a Cadre candidate stage",
34883
- description: "Create or resume one project-local candidate directory and ensure /stage/ is ignored by Git.",
35046
+ description: "Prepare staging.",
34884
35047
  inputSchema: {
34885
35048
  projectRoot: external_exports.string().min(1),
34886
- candidateId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
35049
+ candidateId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
35050
+ expectedFiles: external_exports.array(external_exports.string().min(1)).min(1).optional()
34887
35051
  },
34888
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
34889
- }, async ({ projectRoot, candidateId }) => {
35052
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: false }
35053
+ }, async ({ projectRoot, candidateId, expectedFiles }) => {
34890
35054
  try {
34891
- return result(prepareCandidateStage(projectRoot, candidateId), `Prepared Cadre candidate stage ${candidateId}.`);
35055
+ return result(
35056
+ prepareCandidateStage(projectRoot, candidateId, expectedFiles),
35057
+ `Prepared Cadre candidate stage ${candidateId}.`
35058
+ );
34892
35059
  } catch (error51) {
34893
35060
  return failure(error51);
34894
35061
  }
34895
35062
  });
34896
35063
  server.registerTool(CADRE_MCP_TOOLS.candidateInspect, {
34897
35064
  title: "Inspect staged artifact candidates",
34898
- description: "Manifest an exact staged file set and optionally validate its plan graph in one read-only call.",
34899
- inputSchema: {
35065
+ description: "Inspect staging.",
35066
+ inputSchema: external_exports.strictObject({
34900
35067
  projectRoot: external_exports.string().min(1),
34901
35068
  candidateId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34902
35069
  files: external_exports.array(external_exports.string().min(1)).min(1),
34903
- targetStatus: external_exports.enum(PLAN_VALIDATION_STATUSES).optional()
34904
- },
35070
+ planValidations: external_exports.array(external_exports.object({
35071
+ path: external_exports.string().min(1),
35072
+ targetStatus: external_exports.enum(PLAN_VALIDATION_STATUSES)
35073
+ })).optional().default([])
35074
+ }),
34905
35075
  annotations: { readOnlyHint: true, openWorldHint: false }
34906
- }, async ({ projectRoot, candidateId, files, targetStatus }) => {
35076
+ }, async ({ projectRoot, candidateId, files, planValidations }) => {
34907
35077
  try {
34908
35078
  const root = safeProjectRoot(projectRoot);
34909
35079
  const candidates = readCandidateFiles(root, candidateId, files);
34910
- const manifest = candidates.map((file2) => ({ path: file2.path, sha256: sha256(file2.content) })).sort((left, right) => left.path.localeCompare(right.path));
35080
+ const manifest = candidateManifest(candidates);
34911
35081
  const actualPaths = listCandidatePaths(root, candidateId);
34912
35082
  const expectedPaths = manifest.map((file2) => file2.path);
34913
35083
  if (JSON.stringify(actualPaths) !== JSON.stringify(expectedPaths)) {
@@ -34915,23 +35085,48 @@ function createCadreServer() {
34915
35085
  `Candidate stage must contain exactly the declared files; expected ${expectedPaths.join(", ")}, found ${actualPaths.join(", ")}`
34916
35086
  );
34917
35087
  }
34918
- let plan;
34919
- if (targetStatus) {
34920
- const candidate = candidates.find((file2) => file2.path === "plan.md");
34921
- if (!candidate) throw new Error("candidate inspection with targetStatus requires plan.md in files");
35088
+ const normalizedPlanValidations = planValidations.map((validation) => ({
35089
+ path: normalizeCandidatePath(validation.path),
35090
+ targetStatus: validation.targetStatus
35091
+ })).sort((left, right) => left.path.localeCompare(right.path));
35092
+ const validationPaths = normalizedPlanValidations.map((validation) => validation.path);
35093
+ if (new Set(validationPaths).size !== validationPaths.length) {
35094
+ throw new Error("Candidate planValidations contains duplicate paths");
35095
+ }
35096
+ for (const path of validationPaths) {
35097
+ if (path.split("/").at(-1) !== "plan.md") {
35098
+ throw new Error(`Candidate plan validation path must name plan.md: ${path}`);
35099
+ }
35100
+ if (!expectedPaths.includes(path)) {
35101
+ throw new Error(`Candidate plan validation path is not a declared staged file: ${path}`);
35102
+ }
35103
+ }
35104
+ const candidatePlanPaths = candidates.map((candidate) => candidate.path).filter((path) => path.split("/").at(-1) === "plan.md").sort();
35105
+ if (JSON.stringify(candidatePlanPaths) !== JSON.stringify(validationPaths)) {
35106
+ throw new Error(
35107
+ `Candidate planValidations must exactly match staged plan files; expected ${candidatePlanPaths.join(", ") || "none"}, found ${validationPaths.join(", ") || "none"}`
35108
+ );
35109
+ }
35110
+ const plans = normalizedPlanValidations.map((validation) => {
35111
+ const candidate = candidates.find((file2) => file2.path === validation.path);
34922
35112
  if (Buffer.byteLength(candidate.content, "utf8") > MAX_DRAFT_PLAN_CHARACTERS) {
34923
- throw new Error(`Candidate plan exceeds ${MAX_DRAFT_PLAN_CHARACTERS} bytes`);
35113
+ throw new Error(`Candidate plan exceeds ${MAX_DRAFT_PLAN_CHARACTERS} bytes: ${candidate.path}`);
34924
35114
  }
34925
35115
  const errors = [];
34926
35116
  const graph = parsePlanContent(candidate.content, candidate.path, errors);
34927
- validatePlanGraph(candidate.path, graph, targetStatus, errors);
34928
- plan = { valid: errors.length === 0, path: candidate.path, graph, errors };
34929
- }
35117
+ validatePlanGraph(candidate.path, graph, validation.targetStatus, errors);
35118
+ return { ...validation, valid: errors.length === 0, graph, errors };
35119
+ });
34930
35120
  return result({
34931
35121
  candidateId,
34932
35122
  files: manifest,
34933
- digest: sha256(JSON.stringify({ projectRoot: root, candidateId, files: manifest })),
34934
- ...plan ? { plan } : {}
35123
+ plans,
35124
+ digest: sha256(JSON.stringify({
35125
+ projectRoot: root,
35126
+ candidateId,
35127
+ files: manifest,
35128
+ planValidations: normalizedPlanValidations
35129
+ }))
34935
35130
  }, `Inspected ${manifest.length} staged Cadre artifact${manifest.length === 1 ? "" : "s"}.`);
34936
35131
  } catch (error51) {
34937
35132
  return failure(error51);
@@ -34939,7 +35134,7 @@ function createCadreServer() {
34939
35134
  });
34940
35135
  server.registerTool(CADRE_MCP_TOOLS.executionGraphValidate, {
34941
35136
  title: "Validate a track execution graph",
34942
- description: "Compile and validate phase/task dependencies and derived manual-verification barriers from an approved plan.",
35137
+ description: "Validate plan DAG.",
34943
35138
  inputSchema: { projectRoot: external_exports.string().min(1), trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/) },
34944
35139
  annotations: { readOnlyHint: true, openWorldHint: false }
34945
35140
  }, async ({ projectRoot, trackId }) => {
@@ -34959,20 +35154,19 @@ function createCadreServer() {
34959
35154
  const reviewCompleteSchema = {
34960
35155
  projectRoot: external_exports.string().min(1),
34961
35156
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
34962
- commitRangeStart: external_exports.string().min(1),
34963
35157
  approval: external_exports.string().min(1),
34964
35158
  acceptedRisks: external_exports.array(external_exports.string().min(1)).optional()
34965
35159
  };
34966
35160
  server.registerTool(CADRE_MCP_TOOLS.reviewComplete, {
34967
35161
  title: "Complete a clean review",
34968
- description: "Prepare the exact clean-review completion for human approval, or apply its unchanged proposal token after approval.",
35162
+ description: "Complete review.",
34969
35163
  inputSchema: adaptiveInputSchema(reviewCompleteSchema),
34970
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
34971
- }, async (input) => {
35164
+ annotations: { destructiveHint: false, openWorldHint: false }
35165
+ }, async ({ request }) => {
34972
35166
  try {
34973
35167
  const adaptive = normalizeAdaptiveInput(
34974
- input,
34975
- ["projectRoot", "trackId", "commitRangeStart", "approval"],
35168
+ request,
35169
+ ["projectRoot", "trackId", "approval"],
34976
35170
  "review_complete"
34977
35171
  );
34978
35172
  if (adaptive.mode === "apply") {
@@ -35025,13 +35219,13 @@ function createCadreServer() {
35025
35219
  };
35026
35220
  server.registerTool(CADRE_MCP_TOOLS.archiveBatchCandidate, {
35027
35221
  title: "Govern a staged archive batch",
35028
- description: "Prepare a staged archive batch for human approval, or apply its unchanged proposal token after approval.",
35222
+ description: "Apply archive batch.",
35029
35223
  inputSchema: adaptiveInputSchema(archiveBatchCandidateSchema),
35030
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
35031
- }, async (input) => {
35224
+ annotations: { destructiveHint: false, openWorldHint: false }
35225
+ }, async ({ request }) => {
35032
35226
  try {
35033
35227
  const adaptive = normalizeAdaptiveInput(
35034
- input,
35228
+ request,
35035
35229
  ["projectRoot", "candidateId", "updates"],
35036
35230
  "archive_batch_candidate"
35037
35231
  );
@@ -35085,9 +35279,9 @@ function createCadreServer() {
35085
35279
  };
35086
35280
  server.registerTool(CADRE_MCP_TOOLS.archiveBatchRecord, {
35087
35281
  title: "Record archive provenance",
35088
- description: "Atomically validate and record the already-authorized archive commit in track, project, and batch state.",
35282
+ description: "Record archive.",
35089
35283
  inputSchema: archiveRecordSchema,
35090
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
35284
+ annotations: { destructiveHint: false, openWorldHint: false }
35091
35285
  }, async (input) => {
35092
35286
  try {
35093
35287
  requireCurrentProject2(input.projectRoot);
@@ -35118,9 +35312,9 @@ function createCadreServer() {
35118
35312
  };
35119
35313
  server.registerTool(CADRE_MCP_TOOLS.executionStart, {
35120
35314
  title: "Start implementation execution",
35121
- description: "Atomically validate and start the implementation execution already authorized by the implement invocation.",
35315
+ description: "Start execution.",
35122
35316
  inputSchema: executionStartSchema,
35123
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
35317
+ annotations: { destructiveHint: false, openWorldHint: false }
35124
35318
  }, async (input) => {
35125
35319
  try {
35126
35320
  requireCurrentProject2(input.projectRoot);
@@ -35152,34 +35346,66 @@ function createCadreServer() {
35152
35346
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
35153
35347
  executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/)
35154
35348
  };
35155
- const executionCheckpointSchema = {
35349
+ const checkpointScopeSchema = {
35156
35350
  ...executionScopeSchema,
35157
- nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/),
35158
- event: external_exports.enum(EXECUTION_CHECKPOINT_EVENTS),
35159
- workerId: external_exports.string().min(1).nullable().optional(),
35160
- worktreePath: external_exports.string().min(1).nullable().optional(),
35161
- branch: external_exports.string().min(1).nullable().optional(),
35162
- commit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).optional(),
35163
- verification: external_exports.string().min(1).optional(),
35164
- authorization: external_exports.string().min(1).optional(),
35165
- blocker: external_exports.string().min(1).optional()
35351
+ nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/)
35166
35352
  };
35353
+ const commitSchema = external_exports.string().regex(/^[0-9a-f]{7,40}$/);
35354
+ const evidenceSchema = external_exports.string().min(1);
35355
+ const executionCheckpointActionSchema = external_exports.discriminatedUnion("event", [
35356
+ external_exports.strictObject({
35357
+ event: external_exports.literal("start"),
35358
+ workerId: external_exports.string().min(1).nullable().optional(),
35359
+ worktreePath: external_exports.string().min(1).nullable().optional(),
35360
+ branch: external_exports.string().min(1).nullable().optional(),
35361
+ verification: evidenceSchema.optional()
35362
+ }),
35363
+ external_exports.strictObject({
35364
+ event: external_exports.literal("record_commit"),
35365
+ commit: commitSchema,
35366
+ verification: evidenceSchema,
35367
+ authorization: evidenceSchema
35368
+ }),
35369
+ external_exports.strictObject({
35370
+ event: external_exports.literal("record_integration"),
35371
+ commit: commitSchema,
35372
+ verification: evidenceSchema
35373
+ }),
35374
+ external_exports.strictObject({
35375
+ event: external_exports.literal("record_verification"),
35376
+ commit: commitSchema,
35377
+ verification: evidenceSchema,
35378
+ authorization: evidenceSchema
35379
+ }),
35380
+ external_exports.strictObject({
35381
+ event: external_exports.literal("complete"),
35382
+ commit: commitSchema.optional(),
35383
+ verification: evidenceSchema.optional(),
35384
+ authorization: evidenceSchema.optional()
35385
+ }),
35386
+ external_exports.strictObject({ event: external_exports.literal("block"), blocker: evidenceSchema }),
35387
+ external_exports.strictObject({ event: external_exports.literal("resume") })
35388
+ ]);
35167
35389
  server.registerTool(CADRE_MCP_TOOLS.executionCheckpoint, {
35168
35390
  title: "Apply an execution checkpoint",
35169
- description: "Atomically validate and apply one already-authorized semantic execution event.",
35170
- inputSchema: executionCheckpointSchema,
35171
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
35172
- }, async (input) => {
35391
+ description: "Checkpoint execution.",
35392
+ inputSchema: {
35393
+ scope: external_exports.strictObject(checkpointScopeSchema),
35394
+ action: executionCheckpointActionSchema
35395
+ },
35396
+ annotations: { destructiveHint: false, openWorldHint: false }
35397
+ }, async ({ scope, action }) => {
35173
35398
  try {
35174
- requireCurrentProject2(input.projectRoot);
35175
- const preview = previewExecutionCheckpoint(input);
35176
- const applied = applyExecutionCheckpoint(input, preview.digest, preview);
35399
+ requireCurrentProject2(scope.projectRoot);
35400
+ const checkpointInput = { ...scope, ...action };
35401
+ const preview = previewExecutionCheckpoint(checkpointInput);
35402
+ const applied = applyExecutionCheckpoint(checkpointInput, preview.digest, preview);
35177
35403
  return result({
35178
35404
  commandStatus: "applied",
35179
35405
  path: applied.path,
35180
35406
  transition: applied.transition,
35181
35407
  checkpoint: applied.journal.checkpoint,
35182
- derivedStatus: executionSchedulerView(applied.journal, [input.nodeId])
35408
+ derivedStatus: executionSchedulerView(applied.journal, [checkpointInput.nodeId])
35183
35409
  });
35184
35410
  } catch (error51) {
35185
35411
  return failure(error51);
@@ -35187,7 +35413,7 @@ function createCadreServer() {
35187
35413
  });
35188
35414
  server.registerTool(CADRE_MCP_TOOLS.executionStatus, {
35189
35415
  title: "Read implementation execution status",
35190
- description: "Read an execution journal and derive ready, active, and blocked DAG nodes.",
35416
+ description: "Read execution.",
35191
35417
  inputSchema: {
35192
35418
  projectRoot: external_exports.string().min(1),
35193
35419
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
@@ -35210,9 +35436,9 @@ function createCadreServer() {
35210
35436
  };
35211
35437
  server.registerTool(CADRE_MCP_TOOLS.executionFinish, {
35212
35438
  title: "Complete implementation execution",
35213
- description: "Atomically verify and finalize an execution after its required manual verification is already recorded.",
35439
+ description: "Finish execution.",
35214
35440
  inputSchema: executionFinishSchema,
35215
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
35441
+ annotations: { destructiveHint: false, openWorldHint: false }
35216
35442
  }, async (input) => {
35217
35443
  try {
35218
35444
  requireCurrentProject2(input.projectRoot);
@@ -35241,9 +35467,9 @@ function createCadreServer() {
35241
35467
  };
35242
35468
  server.registerTool(CADRE_MCP_TOOLS.worktreeCreate, {
35243
35469
  title: "Create a Cadre worker worktree",
35244
- description: "Atomically validate and create or reconcile one already-authorized constrained worker worktree.",
35470
+ description: "Create worktree.",
35245
35471
  inputSchema: worktreeSchema,
35246
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
35472
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: false }
35247
35473
  }, async (input) => {
35248
35474
  try {
35249
35475
  requireCurrentProject2(input.projectRoot);
@@ -35268,13 +35494,13 @@ function createCadreServer() {
35268
35494
  });
35269
35495
  server.registerTool(CADRE_MCP_TOOLS.integration, {
35270
35496
  title: "Integrate a worker branch",
35271
- description: "Atomically merge in phase/autonomous mode; in governed mode return approval_required first, then accept the unchanged proposal token after human approval.",
35497
+ description: "Integrate branch.",
35272
35498
  inputSchema: adaptiveInputSchema(worktreeSchema),
35273
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
35274
- }, async (input) => {
35499
+ annotations: { destructiveHint: false, openWorldHint: false }
35500
+ }, async ({ request }) => {
35275
35501
  try {
35276
35502
  const adaptive = normalizeAdaptiveInput(
35277
- input,
35503
+ request,
35278
35504
  ["projectRoot", "trackId", "executionId", "nodeId"],
35279
35505
  "integration"
35280
35506
  );
@@ -35304,9 +35530,9 @@ function createCadreServer() {
35304
35530
  });
35305
35531
  server.registerTool(CADRE_MCP_TOOLS.worktreeCleanup, {
35306
35532
  title: "Clean up an integrated worker",
35307
- description: "Atomically verify and remove only a clean, fully integrated Cadre worktree and safely deletable branch.",
35533
+ description: "Clean worktree.",
35308
35534
  inputSchema: worktreeSchema,
35309
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
35535
+ annotations: { destructiveHint: true, openWorldHint: false }
35310
35536
  }, async (input) => {
35311
35537
  try {
35312
35538
  const cleanupInput = input;
@@ -35331,19 +35557,19 @@ function createCadreServer() {
35331
35557
  context: external_exports.enum(["greenfield", "brownfield"]),
35332
35558
  gitDisposition: external_exports.enum(["existing", "initialize"]),
35333
35559
  baseCommit: external_exports.string().regex(/^[0-9a-f]{7,40}$/).nullable(),
35334
- approvedAt: external_exports.iso.datetime(),
35560
+ approvedAt: external_exports.string().min(1),
35335
35561
  stagedFiles: external_exports.array(external_exports.string().min(1)).min(3),
35336
35562
  styleguideIds: external_exports.array(external_exports.string().min(1)).min(1)
35337
35563
  };
35338
35564
  server.registerTool(CADRE_MCP_TOOLS.projectInitCandidate, {
35339
35565
  title: "Initialize from a staged Cadre candidate",
35340
- description: "Prepare staged initialization for human approval, or atomically promote its unchanged proposal token after approval.",
35566
+ description: "Initialize project.",
35341
35567
  inputSchema: adaptiveInputSchema(initCandidateSchema),
35342
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
35343
- }, async (input) => {
35568
+ annotations: { destructiveHint: false, openWorldHint: false }
35569
+ }, async ({ request }) => {
35344
35570
  try {
35345
35571
  const adaptive = normalizeAdaptiveInput(
35346
- input,
35572
+ request,
35347
35573
  [
35348
35574
  "projectRoot",
35349
35575
  "projectName",
@@ -35371,9 +35597,9 @@ function createCadreServer() {
35371
35597
  digest: applied.digest
35372
35598
  });
35373
35599
  }
35374
- const request = adaptive.request;
35375
- const preview = previewProjectInitCandidate(request);
35376
- return proposalResult("project_init_candidate", request, {
35600
+ const initRequest = adaptive.request;
35601
+ const preview = previewProjectInitCandidate(initRequest);
35602
+ return proposalResult("project_init_candidate", initRequest, {
35377
35603
  runtimeVersion: preview.runtimeVersion,
35378
35604
  templateSetVersion: preview.templateSetVersion,
35379
35605
  files: preview.files.map(({ path, sha256: digest }) => ({ path, sha256: digest })),
@@ -35385,9 +35611,8 @@ function createCadreServer() {
35385
35611
  });
35386
35612
  server.registerTool(CADRE_MCP_TOOLS.setupRecordCommit, {
35387
35613
  title: "Record the project setup commit",
35388
- description: "Complete a pending create operation by recording its already-created Git commit SHA.",
35389
35614
  inputSchema: { projectRoot: external_exports.string().min(1) },
35390
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
35615
+ annotations: { destructiveHint: false, openWorldHint: false }
35391
35616
  }, async ({ projectRoot }) => {
35392
35617
  try {
35393
35618
  requireCurrentProject2(projectRoot);
@@ -35399,9 +35624,8 @@ function createCadreServer() {
35399
35624
  });
35400
35625
  server.registerTool(CADRE_MCP_TOOLS.setupRecordGitInitialized, {
35401
35626
  title: "Record Git initialization checkpoint",
35402
- description: "Advance an approved create operation after the caller verifies Git was initialized at the exact project root.",
35403
35627
  inputSchema: { projectRoot: external_exports.string().min(1) },
35404
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
35628
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: false }
35405
35629
  }, async ({ projectRoot }) => {
35406
35630
  try {
35407
35631
  requireCurrentProject2(projectRoot);
@@ -35412,9 +35636,8 @@ function createCadreServer() {
35412
35636
  });
35413
35637
  server.registerTool(CADRE_MCP_TOOLS.tracksRender, {
35414
35638
  title: "Render the derived tracks index",
35415
- description: "Atomically validate and rewrite deterministic tracks.md from current track-local state.",
35416
35639
  inputSchema: { projectRoot: external_exports.string().min(1) },
35417
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
35640
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: false }
35418
35641
  }, async ({ projectRoot }) => {
35419
35642
  try {
35420
35643
  const input = { projectRoot: requireCurrentProject2(projectRoot) };