cadre-ai 3.7.1 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +13 -1
  4. package/README.md +41 -6
  5. package/agents/cadre-phase-worker.md +1 -1
  6. package/agents/cadre-task-worker.md +1 -1
  7. package/dist/cadre-cli.mjs +3 -3
  8. package/dist/cadre-mcp.mjs +1182 -875
  9. package/package.json +1 -1
  10. package/skills/archive/SKILL.md +1 -1
  11. package/skills/implement/SKILL.md +22 -10
  12. package/skills/implement/agents/openai.yaml +1 -1
  13. package/skills/implement/references/conflict-handling.md +1 -1
  14. package/skills/implement/references/resume-recovery.md +2 -0
  15. package/skills/refresh/SKILL.md +12 -1
  16. package/skills/revert/SKILL.md +1 -1
  17. package/skills/review/SKILL.md +74 -10
  18. package/skills/revise/SKILL.md +1 -1
  19. package/skills/track/SKILL.md +1 -1
  20. package/templates/v4/init/archive/.gitkeep +1 -0
  21. package/templates/v4/init/gitignore.template +8 -0
  22. package/templates/v4/init/guidelines.md +25 -0
  23. package/templates/v4/init/operations/.gitkeep +1 -0
  24. package/templates/v4/init/patterns/index.md +8 -0
  25. package/templates/v4/init/product.md +30 -0
  26. package/templates/v4/init/project.json +27 -0
  27. package/templates/v4/init/refreshes/.gitkeep +1 -0
  28. package/templates/v4/init/styleguides/general.md +14 -0
  29. package/templates/v4/init/styleguides/language.md +21 -0
  30. package/templates/v4/init/tech-stack.md +21 -0
  31. package/templates/v4/init/tracks/.gitkeep +1 -0
  32. package/templates/v4/init/tracks.md +6 -0
  33. package/templates/v4/init/wisps/.gitkeep +1 -0
  34. package/templates/v4/init/workflow.md +91 -0
  35. package/templates/v4/project/archive-operation.json +19 -0
  36. package/templates/v4/project/pattern.md +20 -0
  37. package/templates/v4/project/refresh-operation.json +18 -0
  38. package/templates/v4/project/refresh.md +21 -0
  39. package/templates/v4/styleguides/dart.md +27 -0
  40. package/templates/v4/styleguides/flutter.md +27 -0
  41. package/templates/v4/styleguides/go.md +29 -0
  42. package/templates/v4/styleguides/gradle.md +28 -0
  43. package/templates/v4/styleguides/html-css.md +39 -0
  44. package/templates/v4/styleguides/index.md +27 -0
  45. package/templates/v4/styleguides/java.md +27 -0
  46. package/templates/v4/styleguides/javascript.md +27 -0
  47. package/templates/v4/styleguides/kotlin.md +26 -0
  48. package/templates/v4/styleguides/maven.md +28 -0
  49. package/templates/v4/styleguides/python.md +27 -0
  50. package/templates/v4/styleguides/react.md +28 -0
  51. package/templates/v4/styleguides/swift.md +27 -0
  52. package/templates/v4/styleguides/swiftui.md +27 -0
  53. package/templates/v4/styleguides/typescript.md +26 -0
  54. package/templates/v4/track/bug.md +14 -0
  55. package/templates/v4/track/execution.json +20 -0
  56. package/templates/v4/track/learning.md +45 -0
  57. package/templates/v4/track/plan.md +39 -0
  58. package/templates/v4/track/revert-operation.json +17 -0
  59. package/templates/v4/track/revise-operation.json +18 -0
  60. package/templates/v4/track/revision.md +36 -0
  61. package/templates/v4/track/spec.md +38 -0
  62. package/templates/v4/track/state.json +31 -0
@@ -2979,7 +2979,7 @@ var require_compile = __commonJS({
2979
2979
  const schOrFunc = root.refs[ref];
2980
2980
  if (schOrFunc)
2981
2981
  return schOrFunc;
2982
- let _sch = resolve14.call(this, root, ref);
2982
+ let _sch = resolve13.call(this, root, ref);
2983
2983
  if (_sch === void 0) {
2984
2984
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
2985
2985
  const { schemaId } = this.opts;
@@ -3006,7 +3006,7 @@ var require_compile = __commonJS({
3006
3006
  function sameSchemaEnv(s1, s2) {
3007
3007
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
3008
3008
  }
3009
- function resolve14(root, ref) {
3009
+ function resolve13(root, ref) {
3010
3010
  let sch;
3011
3011
  while (typeof (sch = this.refs[ref]) == "string")
3012
3012
  ref = sch;
@@ -3637,7 +3637,7 @@ var require_fast_uri = __commonJS({
3637
3637
  }
3638
3638
  return uri;
3639
3639
  }
3640
- function resolve14(baseURI, relativeURI, options) {
3640
+ function resolve13(baseURI, relativeURI, options) {
3641
3641
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3642
3642
  const resolved = resolveComponent(parse4(baseURI, schemelessOptions), parse4(relativeURI, schemelessOptions), schemelessOptions, true);
3643
3643
  schemelessOptions.skipEscape = true;
@@ -3895,7 +3895,7 @@ var require_fast_uri = __commonJS({
3895
3895
  var fastUri = {
3896
3896
  SCHEMES,
3897
3897
  normalize,
3898
- resolve: resolve14,
3898
+ resolve: resolve13,
3899
3899
  resolveComponent,
3900
3900
  equal,
3901
3901
  serialize,
@@ -6884,10 +6884,6 @@ var require_dist = __commonJS({
6884
6884
  }
6885
6885
  });
6886
6886
 
6887
- // src/domain/context.ts
6888
- import { existsSync as existsSync4, readdirSync as readdirSync2 } from "node:fs";
6889
- import { join as join3 } from "node:path";
6890
-
6891
6887
  // ../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
6892
6888
  var external_exports = {};
6893
6889
  __export(external_exports, {
@@ -21402,6 +21398,77 @@ function date4(params) {
21402
21398
  // ../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
21403
21399
  config(en_default());
21404
21400
 
21401
+ // src/domain/autonomous-review.ts
21402
+ var commit = external_exports.string().regex(/^[0-9a-f]{7,40}$/);
21403
+ var executionId = external_exports.string().regex(/^[0-9A-Za-z-]+$/);
21404
+ var autonomousReviewSchema = external_exports.strictObject({
21405
+ policyVersion: external_exports.literal(2),
21406
+ originExecutionId: executionId,
21407
+ authorizedAt: external_exports.iso.datetime(),
21408
+ initialBaseCommit: commit,
21409
+ specCommit: commit,
21410
+ checkpoint: external_exports.enum(["implementing", "reviewing", "remediating", "awaiting_approval", "blocked", "completed"]),
21411
+ reviewedExecutionId: executionId.optional(),
21412
+ reviewedHead: commit.optional(),
21413
+ blocker: external_exports.string().trim().min(1).optional(),
21414
+ findings: external_exports.array(external_exports.strictObject({
21415
+ id: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
21416
+ summary: external_exports.string().trim().min(1),
21417
+ status: external_exports.enum(["open", "resolved"]),
21418
+ attemptExecutionIds: external_exports.array(executionId)
21419
+ }))
21420
+ }).superRefine((loop, context) => {
21421
+ const issue2 = (message) => context.addIssue({ code: "custom", message });
21422
+ if (new Set(loop.findings.map((finding) => finding.id)).size !== loop.findings.length) issue2("duplicate finding identity");
21423
+ for (const finding of loop.findings) {
21424
+ if (new Set(finding.attemptExecutionIds).size !== finding.attemptExecutionIds.length) issue2("duplicate remediation attempt");
21425
+ }
21426
+ if (loop.checkpoint === "blocked" && !loop.blocker) issue2("blocked review loop requires a blocker");
21427
+ if (["awaiting_approval", "completed"].includes(loop.checkpoint)) {
21428
+ if (!loop.reviewedExecutionId || !loop.reviewedHead) issue2("clean review requires execution and HEAD evidence");
21429
+ if (loop.findings.some((finding) => finding.status === "open")) issue2("clean review retains unresolved findings");
21430
+ }
21431
+ });
21432
+ function requireReviewProgress(value) {
21433
+ const loop = autonomousReviewSchema.parse(value);
21434
+ if (loop.checkpoint === "blocked") throw new Error(`Autonomous review is blocked: ${loop.blocker}`);
21435
+ const stalled = loop.findings.filter((finding) => finding.status === "open" && finding.attemptExecutionIds.length >= 2);
21436
+ if (stalled.length) throw new Error(`Autonomous review stalled after two remediation attempts: ${stalled.map((finding) => finding.id).join(", ")}; ask the human how to continue`);
21437
+ return loop;
21438
+ }
21439
+ function requireCleanAutonomousReview(value, execution, acceptedRisks) {
21440
+ const loop = autonomousReviewSchema.parse(value);
21441
+ if (!["awaiting_approval", "completed"].includes(loop.checkpoint) || loop.reviewedExecutionId !== execution.executionId || loop.reviewedHead !== execution.headCommit) {
21442
+ throw new Error("Autonomous completion requires a clean review bound to the current execution and HEAD");
21443
+ }
21444
+ if (acceptedRisks.length) throw new Error("Autonomous review cannot waive findings through acceptedRisks");
21445
+ }
21446
+ function validateAutonomousRemediation(previous, candidate, execution) {
21447
+ const next = requireReviewProgress(autonomousReviewSchema.parse(candidate));
21448
+ for (const field of ["originExecutionId", "authorizedAt", "initialBaseCommit", "specCommit"]) {
21449
+ if (next[field] !== previous[field]) throw new Error(`Autonomous remediation cannot change ${field}; obtain explicit scope authorization`);
21450
+ }
21451
+ if (next.checkpoint !== "remediating" || !next.findings.some((finding) => finding.status === "open")) {
21452
+ throw new Error("Autonomous remediation requires open findings and its remediating checkpoint");
21453
+ }
21454
+ if (next.reviewedExecutionId !== execution.executionId || next.reviewedHead !== execution.headCommit) {
21455
+ throw new Error("Autonomous remediation must review the current completed execution and HEAD");
21456
+ }
21457
+ for (const finding of previous.findings) {
21458
+ const updated = next.findings.find((item) => item.id === finding.id);
21459
+ if (!updated || finding.attemptExecutionIds.some((id2) => !updated.attemptExecutionIds.includes(id2))) {
21460
+ throw new Error(`Autonomous remediation must preserve finding identity and attempts: ${finding.id}`);
21461
+ }
21462
+ }
21463
+ for (const finding of next.findings) {
21464
+ const recorded = previous.findings.find((item) => item.id === finding.id)?.attemptExecutionIds ?? [];
21465
+ if (finding.attemptExecutionIds.some((id2) => !recorded.includes(id2) && (id2 !== execution.executionId || id2 === previous.originExecutionId))) {
21466
+ throw new Error(`Autonomous remediation contains an unverified attempt: ${finding.id}`);
21467
+ }
21468
+ }
21469
+ return next;
21470
+ }
21471
+
21405
21472
  // src/domain/errors.ts
21406
21473
  var CadreError = class extends Error {
21407
21474
  code;
@@ -21427,6 +21494,77 @@ function serializeCadreError(error51) {
21427
21494
  };
21428
21495
  }
21429
21496
 
21497
+ // src/domain/approval-policy.ts
21498
+ var EXECUTION_APPROVAL_MODES = ["governed", "phase", "track", "autonomous"];
21499
+ var APPROVAL_POLICY_VERSION = 2;
21500
+ var approvalModeMigrationSchema = external_exports.strictObject({
21501
+ executionId: external_exports.string().regex(/^[0-9A-Za-z-]+$/),
21502
+ approvalMode: external_exports.enum(["track", "autonomous"]),
21503
+ approvedAt: external_exports.iso.datetime(),
21504
+ refreshPath: external_exports.string().regex(/^refreshes\/refresh-[0-9A-Za-z-]+\.md$/)
21505
+ });
21506
+ function migrationRequired(reference, migration) {
21507
+ return reference?.approvalMode === "autonomous" && reference.approvalPolicyVersion !== APPROVAL_POLICY_VERSION && (!migration || !approvalModeMigrationSchema.safeParse(migration).success || migration.executionId !== reference.executionId);
21508
+ }
21509
+ function resolveApprovalMode(reference, migration) {
21510
+ if (migrationRequired(reference, migration)) {
21511
+ throw new CadreError(
21512
+ "APPROVAL_MODE_MIGRATION_REQUIRED",
21513
+ "Legacy Autonomous requires an explicit Track or Autonomous choice in a digest-bound refresh before continuing or inheriting this execution."
21514
+ );
21515
+ }
21516
+ if (reference?.approvalPolicyVersion != null && ![1, APPROVAL_POLICY_VERSION].includes(reference.approvalPolicyVersion)) {
21517
+ throw new Error("unsupported approvalPolicyVersion");
21518
+ }
21519
+ const mode = reference?.approvalMode === "autonomous" && reference.approvalPolicyVersion !== APPROVAL_POLICY_VERSION ? migration.approvalMode : reference?.approvalMode ?? "governed";
21520
+ if (!EXECUTION_APPROVAL_MODES.includes(mode)) {
21521
+ throw new Error("approvalMode must be governed, phase, track, or autonomous");
21522
+ }
21523
+ return mode;
21524
+ }
21525
+ function validateTrackApprovalPolicy(state, errors, warnings = []) {
21526
+ if (state.approvalModeMigration && !approvalModeMigrationSchema.safeParse(state.approvalModeMigration).success) {
21527
+ errors.push(`${state.trackId}: invalid approvalModeMigration`);
21528
+ }
21529
+ const policyReference = state.operation?.action === "implement" ? state.operation : state.lastExecution;
21530
+ if (!["completed", "archived"].includes(state.status) && migrationRequired(policyReference, state.operation?.action === "implement" ? void 0 : state.approvalModeMigration)) {
21531
+ warnings.push(`APPROVAL_MODE_MIGRATION_REQUIRED: ${state.trackId}: choose Track or Autonomous through an approved refresh before continuing or inheriting ${policyReference?.executionId}`);
21532
+ }
21533
+ if (state.autonomousReview) {
21534
+ const loop = autonomousReviewSchema.safeParse(state.autonomousReview);
21535
+ if (!loop.success) errors.push(`${state.trackId}: invalid autonomousReview: ${loop.error.message}`);
21536
+ else {
21537
+ if (state.operation?.kind === "review" && state.operation.action !== "review") {
21538
+ errors.push(`${state.trackId}: review operation must use action: "review", not a finding disposition`);
21539
+ }
21540
+ if (["completed", "archived"].includes(state.status) && loop.data.checkpoint !== "completed") errors.push(`${state.trackId}: terminal track requires completed autonomous review`);
21541
+ if (loop.data.checkpoint === "completed" && !["completed", "archived"].includes(state.status)) errors.push(`${state.trackId}: completed autonomous review requires a terminal track`);
21542
+ if (state.operation?.action === "review") {
21543
+ const authority = state.operation.authorization ?? {};
21544
+ if (authority.kind !== "persisted-mode" || authority.originExecutionId !== loop.data.originExecutionId || authority.proposalDigest !== state.operation.approvalDigest) errors.push(`${state.trackId}: review authorization must bind originating Autonomous mode and exact proposal digest`);
21545
+ }
21546
+ }
21547
+ }
21548
+ if (policyReference?.approvalMode === "autonomous" && !state.autonomousReview && (policyReference.approvalPolicyVersion === 2 || state.approvalModeMigration?.executionId === policyReference.executionId && state.approvalModeMigration?.approvalMode === "autonomous")) {
21549
+ errors.push(`${state.trackId}: Autonomous policy requires persisted review loop authority`);
21550
+ }
21551
+ }
21552
+ function requireExecutionAuthority(reference, state) {
21553
+ const mode = resolveApprovalMode(reference);
21554
+ if (mode === "autonomous") {
21555
+ if (!state.autonomousReview) throw new Error("Autonomous execution requires persisted review loop authority");
21556
+ const loop = requireReviewProgress(state.autonomousReview);
21557
+ if (loop.specCommit !== state.commits?.spec) throw new Error("Autonomous scope changed; obtain explicit authorization through refresh");
21558
+ if (loop.checkpoint !== "implementing") throw new Error("Autonomous execution requires its implementing checkpoint");
21559
+ }
21560
+ return mode;
21561
+ }
21562
+
21563
+ // src/domain/execution.ts
21564
+ import { createHash as createHash3, randomUUID } from "node:crypto";
21565
+ import { existsSync as existsSync5, lstatSync as lstatSync3, mkdirSync, readFileSync as readFileSync3, readdirSync as readdirSync3, renameSync, unlinkSync, writeFileSync } from "node:fs";
21566
+ import { basename, dirname, join as join4, resolve as resolve5 } from "node:path";
21567
+
21430
21568
  // src/domain/inspection.ts
21431
21569
  import { AsyncLocalStorage } from "node:async_hooks";
21432
21570
  import { readFileSync } from "node:fs";
@@ -21575,7 +21713,7 @@ function inspectMemory(input) {
21575
21713
  function requireFreshTrackMemory(projectRoot, trackId) {
21576
21714
  const root = safeProjectRoot(projectRoot);
21577
21715
  const project = JSON.parse(readSafeArtifact(root, ".cadre/project.json"));
21578
- if (project.templateSetVersion !== "v3") return;
21716
+ if (!["v3", "v4"].includes(project.templateSetVersion ?? "")) return;
21579
21717
  const path = `.cadre/tracks/${trackId}/learning.md`;
21580
21718
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(trackId)) throw new Error("invalid trackId");
21581
21719
  const plan = readSafeArtifact(root, `.cadre/tracks/${trackId}/plan.md`);
@@ -21606,264 +21744,20 @@ function sourceFreshness(projectRoot, reference, read = (path) => readSafeArtifa
21606
21744
  }
21607
21745
  }
21608
21746
 
21609
- // src/domain/plan.ts
21610
- import { createHash as createHash2 } from "node:crypto";
21611
- import { existsSync as existsSync2 } from "node:fs";
21612
- function dependencyList(value) {
21613
- const trimmed = value.trim();
21614
- if (trimmed === "none") return [];
21615
- return trimmed.split(",").map((entry) => entry.trim()).filter(Boolean);
21616
- }
21617
- function graphDigest(graph) {
21618
- const normalized = {
21619
- specRevision: graph.specRevision,
21620
- planRevision: graph.planRevision,
21621
- phases: graph.phases.map((phase) => ({
21622
- id: phase.id,
21623
- title: phase.title,
21624
- dependencies: phase.dependencies,
21625
- tasks: phase.tasks.map((task) => ({
21626
- id: task.id,
21627
- title: task.title,
21628
- dependencies: task.dependencies,
21629
- manualVerification: task.manualVerification
21630
- }))
21631
- }))
21632
- };
21633
- return createHash2("sha256").update(JSON.stringify(normalized)).digest("hex");
21634
- }
21635
- function parsePlanContent(content, sourceLabel, errors = []) {
21636
- const phases = [];
21637
- let specRevision = null;
21638
- let planRevision = null;
21639
- let currentTask = null;
21640
- const lines = content.split(/\r?\n/);
21641
- for (const [index, line] of lines.entries()) {
21642
- const lineNumber = index + 1;
21643
- const spec = line.match(/^- Spec revision: (\d+)$/);
21644
- if (spec) specRevision = Number(spec[1]);
21645
- const revision = line.match(/^- Plan revision: (\d+)$/);
21646
- if (revision) planRevision = Number(revision[1]);
21647
- const phaseMatch = line.match(/^## Phase (\d+): (.+)$/);
21648
- if (phaseMatch) {
21649
- const number4 = Number(phaseMatch[1]);
21650
- phases.push({
21651
- number: number4,
21652
- id: `P${number4}`,
21653
- title: phaseMatch[2].trim(),
21654
- dependencies: [],
21655
- dependencyDeclared: false,
21656
- tasks: [],
21657
- completionCommit: void 0,
21658
- line: lineNumber,
21659
- trackVerification: phaseMatch[2].trim() === "Track-level User Manual Verification"
21660
- });
21661
- currentTask = null;
21662
- continue;
21663
- }
21664
- const phaseDependencies = line.match(/^- Phase dependencies: (.+)$/);
21665
- if (phaseDependencies) {
21666
- const phase = phases.at(-1);
21667
- if (!phase) errors.push(`${sourceLabel}:${lineNumber}: phase dependencies appear before a phase`);
21668
- else if (phase.dependencyDeclared) errors.push(`${sourceLabel}:${lineNumber}: ${phase.id} has duplicate phase dependencies`);
21669
- else {
21670
- phase.dependencies = dependencyList(phaseDependencies[1]);
21671
- phase.dependencyDeclared = true;
21672
- }
21673
- continue;
21674
- }
21675
- const phaseCommit = line.match(/^- Phase completion commit: (pending|`([0-9a-f]{7,40})`)$/);
21676
- if (phaseCommit) {
21677
- const phase = phases.at(-1);
21678
- if (!phase) errors.push(`${sourceLabel}:${lineNumber}: phase completion commit appears before a phase`);
21679
- else phase.completionCommit = phaseCommit[1] === "pending" ? null : phaseCommit[2];
21680
- continue;
21681
- }
21682
- const taskMatch = line.match(/^- \[([ xX])\] (T(\d+)\.(\d+)) (.+)$/);
21683
- if (taskMatch) {
21684
- const phase = phases.at(-1);
21685
- if (!phase) {
21686
- errors.push(`${sourceLabel}:${lineNumber}: task appears before a phase`);
21687
- continue;
21688
- }
21689
- let title = taskMatch[5].trim();
21690
- let commit = null;
21691
- const marker = title.match(/^(.*?)\s+<!-- commit: ([0-9a-f]{7,40}) -->$/);
21692
- if (marker) {
21693
- title = marker[1].trim();
21694
- commit = marker[2];
21695
- }
21696
- currentTask = {
21697
- checked: taskMatch[1].toLowerCase() === "x",
21698
- id: taskMatch[2],
21699
- phaseId: `P${taskMatch[3]}`,
21700
- ordinal: Number(taskMatch[4]),
21701
- title,
21702
- commit,
21703
- dependencies: [],
21704
- dependencyDeclared: false,
21705
- manualVerification: title === "User Manual Verification",
21706
- line: lineNumber
21707
- };
21708
- phase.tasks.push(currentTask);
21709
- continue;
21710
- }
21711
- const taskDependencies = line.match(/^ - Task dependencies: (.+)$/);
21712
- if (taskDependencies) {
21713
- if (!currentTask) errors.push(`${sourceLabel}:${lineNumber}: task dependencies do not follow a task`);
21714
- else if (currentTask.dependencyDeclared) errors.push(`${sourceLabel}:${lineNumber}: ${currentTask.id} has duplicate task dependencies`);
21715
- else {
21716
- currentTask.dependencies = dependencyList(taskDependencies[1]);
21717
- currentTask.dependencyDeclared = true;
21718
- }
21719
- }
21720
- }
21721
- const graphWithoutDigest = { specRevision, planRevision, phases };
21722
- return { ...graphWithoutDigest, digest: graphDigest(graphWithoutDigest) };
21723
- }
21724
- function parsePlan(path, errors = []) {
21725
- if (!existsSync2(path)) {
21726
- errors.push(`${path}: missing plan`);
21727
- return { specRevision: null, planRevision: null, phases: [], digest: graphDigest({ specRevision: null, planRevision: null, phases: [] }) };
21728
- }
21729
- return parsePlanContent(readInspectionText(path, "utf8"), path, errors);
21730
- }
21731
- function findCycles(nodes, owner, errors) {
21732
- const ids = new Set(nodes.map((node) => node.id));
21733
- const visiting = /* @__PURE__ */ new Set();
21734
- const visited = /* @__PURE__ */ new Set();
21735
- const byId = new Map(nodes.map((node) => [node.id, node]));
21736
- function visit(id2, trail) {
21737
- if (visiting.has(id2)) {
21738
- errors.push(`${owner}: dependency cycle ${[...trail, id2].join(" -> ")}`);
21739
- return;
21740
- }
21741
- if (visited.has(id2)) return;
21742
- visiting.add(id2);
21743
- for (const dependency of byId.get(id2)?.dependencies ?? []) {
21744
- if (ids.has(dependency)) visit(dependency, [...trail, id2]);
21745
- }
21746
- visiting.delete(id2);
21747
- visited.add(id2);
21748
- }
21749
- for (const node of nodes) visit(node.id, []);
21750
- }
21751
- function validatePlanGraph(path, graph, status, errors) {
21752
- if (!graph.phases.length) {
21753
- if (!["drafting-spec", "drafting-plan"].includes(status)) errors.push(`${path}: approved plan must contain phases`);
21754
- return;
21755
- }
21756
- if (!Number.isInteger(graph.specRevision) || (graph.specRevision ?? 0) < 1) {
21757
- errors.push(`${path}: Spec revision must be a positive integer`);
21758
- }
21759
- if (!Number.isInteger(graph.planRevision) || (graph.planRevision ?? 0) < 1) {
21760
- errors.push(`${path}: Plan revision must be a positive integer`);
21761
- }
21762
- const phaseIds = new Set(graph.phases.map((phase) => phase.id));
21763
- const finalPhase = graph.phases.at(-1);
21764
- graph.phases.forEach((phase, phaseIndex) => {
21765
- if (phase.number !== phaseIndex + 1) errors.push(`${path}: phases must be sequential from 1`);
21766
- if (!phase.tasks.length) errors.push(`${path}: ${phase.id} has no tasks`);
21767
- if (phase.trackVerification) {
21768
- phase.dependencies = graph.phases.slice(0, phaseIndex).map((previous) => previous.id);
21769
- if (phase !== finalPhase && (!phase.completionCommit || !phase.tasks.length || phase.tasks.some((task) => !task.checked))) {
21770
- errors.push(`${path}: historical Track-level User Manual Verification must be completed with commit provenance`);
21771
- }
21772
- }
21773
- if (!phase.trackVerification && !phase.dependencyDeclared) {
21774
- errors.push(`${path}:${phase.line}: ${phase.id} must declare phase dependencies`);
21775
- }
21776
- if (phase.trackVerification && phase.dependencyDeclared) {
21777
- errors.push(`${path}:${phase.line}: final track verification dependencies are derived and must not be declared`);
21778
- }
21779
- if (new Set(phase.dependencies).size !== phase.dependencies.length) {
21780
- errors.push(`${path}:${phase.line}: ${phase.id} contains duplicate phase dependencies`);
21781
- }
21782
- for (const dependency of phase.dependencies) {
21783
- if (!/^P\d+$/.test(dependency) || !phaseIds.has(dependency)) errors.push(`${path}:${phase.line}: ${phase.id} has unknown phase dependency ${dependency}`);
21784
- if (dependency === phase.id) errors.push(`${path}:${phase.line}: ${phase.id} cannot depend on itself`);
21785
- if (dependency === finalPhase.id) errors.push(`${path}:${phase.line}: ${phase.id} cannot depend on final track verification`);
21786
- }
21787
- const nonManualTasks = phase.tasks.filter((task) => !task.manualVerification);
21788
- if (!phase.trackVerification && !nonManualTasks.length) errors.push(`${path}: ${phase.id} has no delivery task`);
21789
- if (phase.trackVerification && (phase.tasks.length !== 1 || !phase.tasks[0]?.manualVerification)) {
21790
- errors.push(`${path}: final track verification phase must contain only User Manual Verification`);
21791
- }
21792
- phase.tasks.forEach((task, taskIndex) => {
21793
- if (task.phaseId !== phase.id) errors.push(`${path}:${task.line}: ${task.id} is in the wrong phase`);
21794
- if (task.ordinal !== taskIndex + 1) errors.push(`${path}:${task.line}: task ordinals must be sequential`);
21795
- if (task.checked && !task.commit) errors.push(`${path}:${task.line}: completed task ${task.id} has no commit marker`);
21796
- if (!task.checked && task.commit) errors.push(`${path}:${task.line}: pending task ${task.id} has a commit marker`);
21797
- if (task.manualVerification) {
21798
- if (task !== phase.tasks.at(-1)) errors.push(`${path}:${task.line}: User Manual Verification must be the final phase task`);
21799
- if (task.dependencyDeclared) errors.push(`${path}:${task.line}: ${task.id} dependencies are derived and must not be declared`);
21800
- task.dependencies = nonManualTasks.map((candidate) => candidate.id);
21801
- } else if (!task.dependencyDeclared) {
21802
- errors.push(`${path}:${task.line}: ${task.id} must declare task dependencies`);
21803
- }
21804
- if (new Set(task.dependencies).size !== task.dependencies.length) {
21805
- errors.push(`${path}:${task.line}: ${task.id} contains duplicate task dependencies`);
21806
- }
21807
- for (const dependency of task.dependencies) {
21808
- const target = phase.tasks.find((candidate) => candidate.id === dependency);
21809
- if (!target) errors.push(`${path}:${task.line}: ${task.id} has unknown or cross-phase task dependency ${dependency}`);
21810
- if (dependency === task.id) errors.push(`${path}:${task.line}: ${task.id} cannot depend on itself`);
21811
- if (target?.manualVerification) errors.push(`${path}:${task.line}: ${task.id} cannot depend on manual verification`);
21812
- }
21813
- });
21814
- if (phase.completionCommit === void 0) errors.push(`${path}: ${phase.id} lacks a completion commit field`);
21815
- const phaseDone = phase.tasks.length > 0 && phase.tasks.every((task) => task.checked);
21816
- if (phaseDone && !phase.completionCommit) errors.push(`${path}: completed ${phase.id} has no completion commit`);
21817
- if (!phaseDone && phase.completionCommit) errors.push(`${path}: incomplete ${phase.id} has a completion commit`);
21818
- findCycles(phase.tasks, `${path}:${phase.id}`, errors);
21819
- });
21820
- if (!finalPhase.trackVerification) errors.push(`${path}: final phase must be Track-level User Manual Verification`);
21821
- findCycles(graph.phases, path, errors);
21822
- if (["ready_for_review", "completed", "archived"].includes(status)) {
21823
- const pending = graph.phases.flatMap((phase) => phase.tasks).filter((task) => !task.checked);
21824
- if (pending.length) errors.push(`${path}: ${status} track has ${pending.length} pending task(s)`);
21825
- }
21826
- }
21827
- function readAndValidatePlan(path, status, errors) {
21828
- const graph = parsePlan(path, errors);
21829
- validatePlanGraph(path, graph, status, errors);
21830
- return graph;
21831
- }
21832
-
21833
- // src/domain/markdown-context.ts
21834
- function markdownHeadings(body) {
21835
- const headings = [];
21836
- let fence = null;
21837
- let offset = 0, ambiguous = false;
21838
- for (const line of body.split(/(?<=\n)/)) {
21839
- const marker = /^ {0,3}(`{3,}|~{3,})(.*)/.exec(line);
21840
- if (marker) {
21841
- if (!fence) fence = { character: marker[1][0], length: marker[1].length };
21842
- else if (marker[1][0] === fence.character && marker[1].length >= fence.length && !marker[2].trim()) fence = null;
21843
- } else if (!fence) {
21844
- const heading = /^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*\r?\n?$/.exec(line);
21845
- if (heading) headings.push({ level: heading[1].length, title: heading[2], offset });
21846
- if (/^ {0,3}(?:=+|-+)[ \t]*$/.test(line.trimEnd()) || /^\s*<(?!\!--)/.test(line) || /^ {4,}#{1,6}\s/.test(line)) ambiguous = true;
21847
- }
21848
- offset += line.length;
21849
- }
21850
- return { headings, ambiguous: ambiguous || fence !== null };
21851
- }
21852
-
21853
21747
  // src/domain/execution-evidence.ts
21854
- import { existsSync as existsSync3, lstatSync as lstatSync2, readdirSync } from "node:fs";
21748
+ import { existsSync as existsSync2, lstatSync as lstatSync2, readdirSync } from "node:fs";
21855
21749
  import { join as join2 } from "node:path";
21856
21750
  function inspectExecutionBindings(trackRoot, state, read = (path) => readInspectionJson(path), paths) {
21857
21751
  const directory = join2(trackRoot, "executions");
21858
- if (existsSync3(directory) && lstatSync2(directory).isSymbolicLink()) return ["unsafe execution directory symbolic link"];
21859
- const journals = paths ?? (existsSync3(directory) ? readdirSync(directory).filter((path) => /^execution-.+\.json$/.test(path)) : []);
21752
+ if (existsSync2(directory) && lstatSync2(directory).isSymbolicLink()) return ["unsafe execution directory symbolic link"];
21753
+ const journals = paths ?? (existsSync2(directory) ? readdirSync(directory).filter((path) => /^execution-.+\.json$/.test(path)) : []);
21860
21754
  const references = [state.operation, state.lastExecution].filter(Boolean);
21861
21755
  const errors = [];
21862
21756
  for (const file2 of journals) {
21863
21757
  try {
21864
21758
  const absolute = join2(directory, file2);
21865
21759
  if (!/^execution-[^/\\]+\.json$/.test(file2)) throw new Error("unsafe execution journal path");
21866
- if (existsSync3(absolute) && (lstatSync2(absolute).isSymbolicLink() || !lstatSync2(absolute).isFile())) throw new Error("unsafe execution journal file");
21760
+ if (existsSync2(absolute) && (lstatSync2(absolute).isSymbolicLink() || !lstatSync2(absolute).isFile())) throw new Error("unsafe execution journal file");
21867
21761
  const journal = read(absolute);
21868
21762
  if (journal.status === "in_progress" && !references.some((reference) => reference?.executionId === journal.executionId && reference?.journal === `executions/${file2}`)) {
21869
21763
  errors.push(`orphaned in-progress execution ${file2}; retain its executionId/journal binding during repair and resume from persisted checkpoints`);
@@ -21875,496 +21769,16 @@ function inspectExecutionBindings(trackRoot, state, read = (path) => readInspect
21875
21769
  return errors;
21876
21770
  }
21877
21771
 
21878
- // src/domain/context.ts
21879
- var id = external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
21880
- var contextInputSchema = external_exports.strictObject({
21881
- projectRoot: external_exports.string().min(1),
21882
- trackId: id,
21883
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/).optional(),
21884
- nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/).optional(),
21885
- maxBytes: external_exports.number().int().min(4096).max(65536).default(16384),
21886
- cursor: external_exports.string().max(1024).optional(),
21887
- knownSources: external_exports.array(external_exports.strictObject({
21888
- path: external_exports.string(),
21889
- sha256: external_exports.string().regex(/^[0-9a-f]{64}$/),
21890
- section: external_exports.string(),
21891
- contentHash: external_exports.string().regex(/^[0-9a-f]{64}$/)
21892
- })).max(256).default([])
21893
- });
21894
- var cursorSchema = external_exports.strictObject({ snapshot: external_exports.string().regex(/^[0-9a-f]{64}$/), source: external_exports.number().int().nonnegative(), offset: external_exports.number().int().nonnegative() });
21895
- function learningSections(body, phaseIds) {
21896
- if (!phaseIds || !seedSection(body)) return [{ section: "full learning (conservative)", content: body }];
21897
- const parsed = markdownHeadings(body), headings = parsed.headings.filter((heading) => heading.level === 2);
21898
- const matches = headings.filter((heading) => /^Phase \d+: .+$/.test(heading.title));
21899
- const phaseId = (heading) => `P${/^Phase (\d+):/.exec(heading.title)[1]}`;
21900
- const present = new Set(matches.map(phaseId));
21901
- if (parsed.ambiguous || present.size !== matches.length || [...phaseIds].some((phase) => !present.has(phase)) || headings.some((heading) => heading.title !== "Pattern Seed" && !/^Phase \d+: .+$/.test(heading.title))) {
21902
- return [{ section: "full learning (ambiguous or missing phase context)", content: body }];
21903
- }
21904
- const selected = [{ section: "Pattern Seed and general instructions", content: body.slice(0, matches[0]?.offset ?? body.length) }];
21905
- matches.forEach((match, index) => {
21906
- if (phaseIds.has(phaseId(match))) selected.push({ section: phaseId(match), content: body.slice(match.offset, matches[index + 1]?.offset ?? body.length) });
21907
- });
21908
- return selected;
21909
- }
21910
- function collectContext(input) {
21911
- const root = safeProjectRoot(input.projectRoot), sources = [], errors = [], staleMemory = [];
21912
- const inputHashes = /* @__PURE__ */ new Map();
21913
- const read = (path) => {
21914
- const body = readSafeArtifact(root, path);
21915
- inputHashes.set(path, contentHash(body));
21916
- return body;
21917
- };
21918
- const add = (path, reason, section = "full") => {
21919
- const content = read(path);
21920
- sources.push({ path, sha256: contentHash(content), reason, section, format: "source", content });
21921
- return content;
21922
- };
21923
- for (const path of ["workflow.md", "product.md", "guidelines.md", "tech-stack.md", "patterns/index.md"]) {
21924
- add(`.cadre/${path}`, "required project instructions and applicability catalog");
21925
- }
21926
- const guides = join3(root, ".cadre/styleguides");
21927
- if (existsSync4(guides)) for (const file2 of readdirSync2(guides).filter((file3) => /^[a-z0-9-]+\.md$/.test(file3)).sort()) {
21928
- add(`.cadre/styleguides/${file2}`, "project styleguide; retain until applicability is established");
21929
- }
21930
- const project = JSON.parse(read(".cadre/project.json"));
21931
- const locate = (trackId) => {
21932
- id.parse(trackId);
21933
- const active = `.cadre/tracks/${trackId}`, archived = `.cadre/archive/${trackId}`;
21934
- if (existsSync4(join3(root, active, "state.json")) && existsSync4(join3(root, archived, "state.json"))) throw new Error(`duplicate track ${trackId}`);
21935
- return existsSync4(join3(root, active, "state.json")) ? active : archived;
21936
- };
21937
- const trackPath = locate(input.trackId);
21938
- const stateBody = read(`${trackPath}/state.json`);
21939
- const state = JSON.parse(stateBody);
21940
- errors.push(...inspectExecutionBindings(join3(root, trackPath), state));
21941
- add(`${trackPath}/spec.md`, "complete approved scope and acceptance criteria");
21942
- const planBody = add(`${trackPath}/plan.md`, "complete plan, including task descriptions and verification requirements");
21943
- const graph = parsePlanContent(planBody, `${trackPath}/plan.md`, errors);
21944
- validatePlanGraph(`${trackPath}/plan.md`, graph, state.status, errors);
21945
- let phases = null;
21946
- if (input.nodeId) {
21947
- const phase = graph.phases.find((phase2) => phase2.id === input.nodeId || phase2.tasks.some((task) => task.id === input.nodeId));
21948
- if (!phase) throw new Error(`unknown plan node ${input.nodeId}`);
21949
- phases = /* @__PURE__ */ new Set();
21950
- const visit = (phaseId) => {
21951
- if (phases.has(phaseId)) return;
21952
- phases.add(phaseId);
21953
- const parent = graph.phases.find((phase2) => phase2.id === phaseId);
21954
- if (!parent) throw new Error(`unknown dependency phase ${phaseId}`);
21955
- parent.dependencies.forEach(visit);
21956
- };
21957
- visit(phase.id);
21958
- }
21959
- const patternPaths = /* @__PURE__ */ new Set();
21960
- let uncertainPatterns = false;
21961
- const addLearning = (path, trackId, historical, selected, plan) => {
21962
- const body = read(path);
21963
- const inspected = inspectMemory({
21964
- trackId,
21965
- path,
21966
- body,
21967
- graph: plan,
21968
- required: project.templateSetVersion === "v3",
21969
- historical,
21970
- readPattern: (path2) => read(`.cadre/${path2}`)
21971
- });
21972
- errors.push(...inspected.errors);
21973
- staleMemory.push(...inspected.stale);
21974
- if (!inspected.metadata) uncertainPatterns = true;
21975
- if (!historical) for (const pattern of inspected.metadata?.patterns ?? []) patternPaths.add(pattern.path);
21976
- for (const section of learningSections(body, selected)) sources.push({
21977
- path,
21978
- sha256: contentHash(body),
21979
- reason: "declared dependency learning and current phase decisions",
21980
- format: "source",
21981
- ...section
21982
- });
21983
- };
21984
- addLearning(`${trackPath}/learning.md`, input.trackId, ["completed", "archived"].includes(state.status), phases, graph);
21985
- const visited = /* @__PURE__ */ new Set([input.trackId]);
21986
- const visitDependency = (trackId) => {
21987
- if (visited.has(trackId)) return;
21988
- visited.add(trackId);
21989
- const base = locate(trackId);
21990
- const dependency = JSON.parse(read(`${base}/state.json`));
21991
- add(`${base}/spec.md`, "declared dependency contract");
21992
- const plan = parsePlanContent(read(`${base}/plan.md`), `${base}/plan.md`);
21993
- addLearning(`${base}/learning.md`, trackId, ["completed", "archived"].includes(dependency.status), null, plan);
21994
- (dependency.dependencies ?? []).forEach(visitDependency);
21995
- };
21996
- (state.dependencies ?? []).forEach(visitDependency);
21997
- if (uncertainPatterns) for (const path of readdirSync2(join3(root, ".cadre/patterns")).filter((path2) => /^[a-z0-9-]+\.md$/.test(path2) && path2 !== "index.md")) {
21998
- patternPaths.add(`patterns/${path}`);
21999
- }
22000
- for (const path of [...patternPaths].sort()) {
22001
- try {
22002
- add(`.cadre/${path}`, uncertainPatterns ? "full pattern fallback: applicability metadata unavailable" : "explicit seed reference");
22003
- } catch (error51) {
22004
- errors.push(`${path}: ${error51 instanceof Error ? error51.message : String(error51)}`);
22005
- }
22006
- }
22007
- const executionId = contextInputSchema.shape.executionId.parse(input.executionId ?? state.operation?.executionId ?? state.lastExecution?.executionId);
22008
- if (executionId) {
22009
- const path = `${trackPath}/executions/execution-${executionId}.json`, body = read(path);
22010
- const journal = JSON.parse(body);
22011
- if (journal.trackId !== input.trackId || journal.executionId !== executionId) throw new Error("execution identity mismatch");
22012
- const differentGraph = journal.graphDigest !== graph.digest || journal.planRevision !== graph.planRevision;
22013
- const historical = differentGraph && ["planned", "in_progress"].includes(state.status) && journal.status === "completed" && state.lastExecution?.executionId === executionId && state.lastExecution.journal === `executions/execution-${executionId}.json` && state.lastExecution.graphDigest === journal.graphDigest && state.lastExecution.planRevision === journal.planRevision && state.lastExecution.headCommit === journal.headCommit;
22014
- if (differentGraph && !historical) errors.push("execution handoffs belong to a different plan graph; reconcile before use");
22015
- for (const node of Object.values(journal.nodes)) {
22016
- if (phases && !phases.has(node.phaseId)) continue;
22017
- const handoff = node.handoff === void 0 ? null : handoffSchema.parse(node.handoff);
22018
- if (!handoff && node.id !== input.nodeId) continue;
22019
- const content = JSON.stringify({
22020
- nodeId: node.id,
22021
- handoff,
22022
- ...historical ? { historical: true, planRevision: journal.planRevision, graphDigest: journal.graphDigest } : {},
22023
- note: (historical ? "Historical execution; reassess for the current plan. " : "") + (handoff ? "Persisted evidence, not authorization" : "not recorded"),
22024
- sources: handoff?.sources.map((reference) => ({ ...reference, freshness: sourceFreshness(root, reference, read) })) ?? []
22025
- });
22026
- sources.push({
22027
- path,
22028
- sha256: contentHash(body),
22029
- section: node.id,
22030
- reason: historical ? "historical handoff from retained completed execution; not current execution state" : "persisted handoff; reconcile journal/Git before resuming",
22031
- format: "handoff",
22032
- content
22033
- });
22034
- }
22035
- }
22036
- const identity = {
22037
- projectRoot: root,
22038
- trackId: input.trackId,
22039
- executionId: executionId ?? null,
22040
- nodeId: input.nodeId ?? null,
22041
- stateHash: contentHash(stateBody),
22042
- inputs: [...inputHashes].sort(),
22043
- sources,
22044
- errors,
22045
- staleMemory
22046
- };
22047
- return { sources, errors, staleMemory, snapshot: contentHash(JSON.stringify(identity)) };
22048
- }
22049
- function readContext(raw) {
22050
- const input = contextInputSchema.parse(raw);
22051
- return inspectOnce(() => {
22052
- const collected = collectContext(input), { errors, staleMemory } = collected;
22053
- const sources = collected.sources.map((source2) => {
22054
- const hash6 = contentHash(source2.content);
22055
- const reused = input.knownSources.some((known) => known.path === source2.path && known.sha256 === source2.sha256 && known.section === source2.section && known.contentHash === hash6);
22056
- return { ...source2, contentHash: hash6, reused, content: reused ? "" : source2.content };
22057
- });
22058
- const snapshot = contentHash(JSON.stringify({ sources: collected.snapshot, knownSources: input.knownSources }));
22059
- const cursor = input.cursor ? cursorSchema.parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8"))) : { snapshot, source: 0, offset: 0 };
22060
- if (cursor.snapshot !== snapshot) throw new CadreError("CONTEXT_SNAPSHOT_CHANGED", "Required sources changed; restart context_read without a cursor.");
22061
- if (cursor.source >= sources.length || cursor.offset > sources[cursor.source].content.length) throw new Error("invalid context cursor position");
22062
- let source = cursor.source, offset = cursor.offset;
22063
- const page = { snapshot, complete: false, contextReady: false, nextCursor: null, totalSources: sources.length, excerpts: [], errors, staleMemory };
22064
- const encode3 = () => Buffer.from(JSON.stringify({ snapshot, source, offset })).toString("base64url");
22065
- while (source < sources.length) {
22066
- const item = sources[source];
22067
- let low = 0, high = item.content.length - offset, take = 0;
22068
- const excerpt = (length) => ({
22069
- ...item,
22070
- content: item.content.slice(offset, offset + length),
22071
- offset,
22072
- endOffset: offset + length,
22073
- sourceComplete: offset + length === item.content.length
22074
- });
22075
- while (low <= high) {
22076
- const mid = Math.floor((low + high) / 2);
22077
- const bytes = Buffer.byteLength(JSON.stringify({ ...page, excerpts: [...page.excerpts, excerpt(mid)], nextCursor: encode3() }));
22078
- if (bytes <= input.maxBytes - 64) {
22079
- take = mid;
22080
- low = mid + 1;
22081
- } else high = mid - 1;
22082
- }
22083
- if (take && /[\uD800-\uDBFF]/.test(item.content[offset + take - 1])) take--;
22084
- if (!take && item.content.length > offset) break;
22085
- page.excerpts.push(excerpt(take));
22086
- offset += take;
22087
- if (offset === item.content.length) {
22088
- source++;
22089
- offset = 0;
22090
- } else break;
22091
- }
22092
- if (!page.excerpts.length) throw new CadreError("CONTEXT_PAGE_TOO_SMALL", "Context findings or metadata exceed the page budget; increase maxBytes and inspect diagnostics.");
22093
- page.complete = source === sources.length;
22094
- page.contextReady = page.complete && !errors.length && !staleMemory.length;
22095
- page.nextCursor = page.complete ? null : encode3();
22096
- return page;
22097
- });
22098
- }
22099
-
22100
- // src/domain/staged-memory.ts
22101
- import { existsSync as existsSync6, readdirSync as readdirSync4 } from "node:fs";
22102
- import { dirname, join as join5 } from "node:path";
22103
-
22104
- // src/domain/staging.ts
22105
- import {
22106
- existsSync as existsSync5,
22107
- lstatSync as lstatSync3,
22108
- mkdirSync,
22109
- readFileSync as readFileSync2,
22110
- readdirSync as readdirSync3,
22111
- renameSync,
22112
- rmdirSync,
22113
- unlinkSync,
22114
- writeFileSync
22115
- } from "node:fs";
22116
- import { isAbsolute, join as join4, relative, resolve as resolve3, sep } from "node:path";
22117
- var CANDIDATE_STAGE_DIRECTORY = ".cadre/stage";
22118
- var MAX_CANDIDATE_FILE_BYTES = 1024 * 1024;
22119
- var MAX_CANDIDATE_TOTAL_BYTES = 8 * 1024 * 1024;
22120
- var CANDIDATE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
22121
- function candidateArtifactPath(candidateId, path) {
22122
- const normalized = normalizeCandidatePath(path);
22123
- const owner = candidateId.match(/^(?:track|revise|review|revert)-([a-z0-9-]+)$/)?.[1];
22124
- return owner && !/^(?:tracks|archive|patterns|refreshes)\//.test(normalized) ? `tracks/${owner}/${normalized}` : normalized;
22125
- }
22126
- function normalizeCandidateId(candidateId) {
22127
- if (!CANDIDATE_ID.test(candidateId)) {
22128
- throw new Error("candidateId must contain lowercase letters, digits, and single hyphens");
22129
- }
22130
- return candidateId;
22131
- }
22132
- function normalizeCandidatePath(input) {
22133
- if (!input || isAbsolute(input) || input.includes("\\")) {
22134
- throw new Error(`Candidate artifact path must be a portable relative path: ${input}`);
22135
- }
22136
- const normalized = input.replace(/^\.\//, "");
22137
- if (normalized === ".cadre" || normalized.startsWith(".cadre/")) {
22138
- throw new Error(`Candidate paths are relative to the candidate stage, without a .cadre/ prefix: ${input}. Use state.json for the owned track or tracks/<id>/state.json for nested updates.`);
22139
- }
22140
- if (!normalized || normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
22141
- throw new Error(`Candidate artifact path is not canonical: ${input}`);
22142
- }
22143
- return normalized;
22144
- }
22145
- function candidateStageRoot(projectRootInput, candidateIdInput) {
22146
- const projectRoot = safeProjectRoot(projectRootInput);
22147
- const candidateId = normalizeCandidateId(candidateIdInput);
22148
- const cadreRoot2 = join4(projectRoot, ".cadre");
22149
- if (!existsSync5(cadreRoot2) || !lstatSync3(cadreRoot2).isDirectory() || lstatSync3(cadreRoot2).isSymbolicLink()) {
22150
- throw new Error(`Cadre candidate root is unavailable or unsafe: ${cadreRoot2}`);
22151
- }
22152
- const gitignorePath = join4(cadreRoot2, ".gitignore");
22153
- if (!existsSync5(gitignorePath) || !lstatSync3(gitignorePath).isFile() || lstatSync3(gitignorePath).isSymbolicLink()) {
22154
- throw new Error(`Cadre candidate stage requires a regular ${gitignorePath}`);
22155
- }
22156
- if (!readFileSync2(gitignorePath, "utf8").split(/\r?\n/).includes("/stage/")) {
22157
- throw new Error(`${gitignorePath} must ignore /stage/ before candidate files are written`);
22158
- }
22159
- const stageParent = join4(projectRoot, CANDIDATE_STAGE_DIRECTORY);
22160
- if (existsSync5(stageParent) && lstatSync3(stageParent).isSymbolicLink()) {
22161
- throw new Error(`Refusing candidate stage through symbolic link: ${stageParent}`);
22162
- }
22163
- return join4(stageParent, candidateId);
22164
- }
22165
- function prepareCandidateStage(projectRootInput, candidateIdInput, expectedFiles) {
22166
- const projectRoot = safeProjectRoot(projectRootInput);
22167
- const candidateId = normalizeCandidateId(candidateIdInput);
22168
- const normalizedExpected = expectedFiles?.map(normalizeCandidatePath);
22169
- if (normalizedExpected && new Set(normalizedExpected).size !== normalizedExpected.length) {
22170
- throw new Error("Candidate expectedFiles contains duplicate paths");
22171
- }
22172
- const cadreRoot2 = join4(projectRoot, ".cadre");
22173
- if (existsSync5(cadreRoot2)) {
22174
- const stat = lstatSync3(cadreRoot2);
22175
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Unsafe Cadre directory: ${cadreRoot2}`);
22176
- } else mkdirSync(cadreRoot2);
22177
- const gitignorePath = join4(cadreRoot2, ".gitignore");
22178
- let content = "# Cadre-managed temporary execution worktrees\n/.worktrees/\n\n# Disposable Wisp output\n/wisps/\n";
22179
- if (existsSync5(gitignorePath)) {
22180
- const stat = lstatSync3(gitignorePath);
22181
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Unsafe Cadre ignore file: ${gitignorePath}`);
22182
- content = readFileSync2(gitignorePath, "utf8");
22183
- }
22184
- if (!content.split(/\r?\n/).includes("/stage/")) {
22185
- content = `${content.endsWith("\n") ? content : `${content}
22186
- `}
22187
- # Unapproved candidate artifacts
22188
- /stage/
22189
- `;
22190
- const temporaryPath = `${gitignorePath}.${process.pid}.tmp`;
22191
- try {
22192
- writeFileSync(temporaryPath, content, { flag: "wx" });
22193
- renameSync(temporaryPath, gitignorePath);
22194
- } finally {
22195
- if (existsSync5(temporaryPath)) unlinkSync(temporaryPath);
22196
- }
22197
- }
22198
- const stagePath = join4(cadreRoot2, "stage", candidateId);
22199
- mkdirSync(stagePath, { recursive: true });
22200
- candidateStageRoot(projectRoot, candidateId);
22201
- const retainedFiles = listCandidatePaths(projectRoot, candidateId);
22202
- if (normalizedExpected === void 0) return { stagePath, gitignorePath, retainedFiles, removedFiles: [] };
22203
- const expected = new Set(normalizedExpected);
22204
- const removedFiles = retainedFiles.filter((path) => !expected.has(path));
22205
- for (const path of removedFiles) unlinkSync(join4(stagePath, path));
22206
- const pruneEmptyDirectories = (directory) => {
22207
- for (const entry of readdirSync3(directory, { withFileTypes: true })) {
22208
- if (entry.isDirectory()) pruneEmptyDirectories(join4(directory, entry.name));
22209
- }
22210
- if (directory !== stagePath && readdirSync3(directory).length === 0) rmdirSync(directory);
22211
- };
22212
- pruneEmptyDirectories(stagePath);
22213
- return {
22214
- stagePath,
22215
- gitignorePath,
22216
- retainedFiles: retainedFiles.filter((path) => expected.has(path)),
22217
- removedFiles
22218
- };
22219
- }
22220
- function assertRegularPath(root, target) {
22221
- const relation = relative(root, target);
22222
- if (relation.startsWith("..") || isAbsolute(relation)) {
22223
- throw new Error(`Candidate artifact escapes its stage: ${target}`);
22224
- }
22225
- let current2 = target;
22226
- while (current2 !== root) {
22227
- if (!existsSync5(current2)) throw new Error(`Missing candidate artifact: ${target}`);
22228
- const stat = lstatSync3(current2);
22229
- if (stat.isSymbolicLink()) throw new Error(`Refusing candidate artifact through symbolic link: ${current2}`);
22230
- current2 = resolve3(current2, "..");
22231
- }
22232
- if (!existsSync5(root)) throw new Error(`Missing candidate stage: ${root}`);
22233
- const rootStat = lstatSync3(root);
22234
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
22235
- throw new Error(`Candidate stage is not a regular directory: ${root}`);
22236
- }
22237
- const targetStat = lstatSync3(target);
22238
- if (!targetStat.isFile()) throw new Error(`Candidate artifact is not a regular file: ${target}`);
22239
- if (targetStat.size > MAX_CANDIDATE_FILE_BYTES) {
22240
- throw new Error(`Candidate artifact exceeds ${MAX_CANDIDATE_FILE_BYTES} bytes: ${target}`);
22241
- }
22242
- }
22243
- function readCandidateFiles(projectRootInput, candidateIdInput, paths) {
22244
- const root = candidateStageRoot(projectRootInput, candidateIdInput);
22245
- const seen = /* @__PURE__ */ new Set();
22246
- let totalBytes = 0;
22247
- return paths.map((input) => {
22248
- const path = normalizeCandidatePath(input);
22249
- if (seen.has(path)) throw new Error(`Duplicate candidate artifact: ${path}`);
22250
- seen.add(path);
22251
- const absolutePath = resolve3(root, path);
22252
- assertRegularPath(root, absolutePath);
22253
- const content = readFileSync2(absolutePath, "utf8");
22254
- totalBytes += Buffer.byteLength(content, "utf8");
22255
- if (totalBytes > MAX_CANDIDATE_TOTAL_BYTES) {
22256
- throw new Error(`Candidate stage exceeds ${MAX_CANDIDATE_TOTAL_BYTES} bytes`);
22257
- }
22258
- return { path, absolutePath, content };
22259
- });
22260
- }
22261
- function listCandidatePaths(projectRootInput, candidateIdInput) {
22262
- const root = candidateStageRoot(projectRootInput, candidateIdInput);
22263
- if (!existsSync5(root)) throw new Error(`Missing candidate stage: ${root}`);
22264
- const rootStat = lstatSync3(root);
22265
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
22266
- throw new Error(`Candidate stage is not a regular directory: ${root}`);
22267
- }
22268
- const walk2 = (directory) => readdirSync3(directory, { withFileTypes: true }).flatMap((entry) => {
22269
- const target = join4(directory, entry.name);
22270
- const stat = lstatSync3(target);
22271
- if (stat.isSymbolicLink()) throw new Error(`Refusing symbolic link in candidate stage: ${target}`);
22272
- if (stat.isDirectory()) return walk2(target);
22273
- if (!stat.isFile()) throw new Error(`Candidate stage contains a non-file entry: ${target}`);
22274
- return [relative(root, target).split(sep).join("/")];
22275
- });
22276
- return walk2(root).sort();
22277
- }
22278
-
22279
- // src/domain/staged-memory.ts
22280
- function inspectStagedMemory(projectRoot, candidateId, files) {
22281
- const originalPaths = new Map(files.map((file2) => [candidateArtifactPath(candidateId, file2.path), file2.path]));
22282
- if (originalPaths.size !== files.length) throw new Error("Candidate paths alias the same canonical artifact; use one path per artifact");
22283
- files = files.map((file2) => ({ ...file2, path: candidateArtifactPath(candidateId, file2.path) }));
22284
- const overlay = new Map(files.map((file2) => [file2.path, file2.content]));
22285
- const inputs = /* @__PURE__ */ new Map();
22286
- const read = (path, fingerprint = true) => {
22287
- const staged = overlay.get(path);
22288
- if (staged !== void 0) return staged;
22289
- const body = readSafeArtifact(projectRoot, `.cadre/${path}`);
22290
- if (fingerprint) inputs.set(path, contentHash(body));
22291
- return body;
22292
- };
22293
- const project = overlay.has("project.json") || existsSync6(join5(projectRoot, ".cadre/project.json")) ? JSON.parse(read("project.json", false)) : {};
22294
- const learningPaths = new Set(files.filter((file2) => file2.path.split("/").at(-1) === "learning.md").map((file2) => file2.path));
22295
- for (const file2 of files.filter((file3) => file3.path.split("/").at(-1) === "plan.md")) {
22296
- const parent = dirname(file2.path);
22297
- const seed = parent === "." ? "learning.md" : `${parent}/learning.md`;
22298
- const owner = candidateId.replace(/^(?:track|revise|review|revert)-/, "");
22299
- const canonicalSeed = parent === "." ? `tracks/${owner}/learning.md` : seed;
22300
- if (overlay.has(seed)) learningPaths.add(seed);
22301
- else if (existsSync6(join5(projectRoot, ".cadre", canonicalSeed))) {
22302
- learningPaths.add(canonicalSeed);
22303
- overlay.set(`${dirname(canonicalSeed)}/plan.md`, file2.content);
22304
- }
22305
- }
22306
- const changedPatterns = files.some((file2) => /^patterns\/.+\.md$/.test(file2.path));
22307
- if (changedPatterns && existsSync6(join5(projectRoot, ".cadre/tracks"))) {
22308
- for (const entry of readdirSync4(join5(projectRoot, ".cadre/tracks"), { withFileTypes: true })) {
22309
- if (!entry.isDirectory() || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(entry.name)) continue;
22310
- const path = `tracks/${entry.name}/learning.md`;
22311
- if (existsSync6(join5(projectRoot, ".cadre", path))) learningPaths.add(path);
22312
- }
22313
- }
22314
- const historicalPaths = [];
22315
- const learning = [...learningPaths].sort().map((path) => {
22316
- const parent = dirname(path);
22317
- const id2 = path.match(/(?:^|\/)tracks\/([a-z0-9-]+)\//)?.[1] ?? candidateId.replace(/^(?:track|revise|review|revert)-/, "");
22318
- const canonicalParent = parent === "." ? `tracks/${id2}` : parent;
22319
- let historical = path.startsWith("archive/");
22320
- const statePath = `${canonicalParent}/state.json`;
22321
- if (overlay.has(statePath) || existsSync6(join5(projectRoot, ".cadre", statePath))) {
22322
- const state = JSON.parse(read(statePath, false));
22323
- historical ||= ["completed", "archived"].includes(state.status ?? "");
22324
- }
22325
- const stagedPlan = parent === "." ? "plan.md" : `${parent}/plan.md`;
22326
- const planPath = overlay.has(stagedPlan) ? stagedPlan : `${canonicalParent}/plan.md`;
22327
- const graph = overlay.has(planPath) || existsSync6(join5(projectRoot, ".cadre", planPath)) ? parsePlanContent(read(planPath), planPath) : null;
22328
- const reportedPath = originalPaths.get(path) ?? path;
22329
- if (historical) historicalPaths.push(reportedPath);
22330
- const inspected = inspectMemory({
22331
- trackId: id2,
22332
- path: reportedPath,
22333
- body: read(path),
22334
- graph,
22335
- required: project.templateSetVersion === "v3",
22336
- historical,
22337
- readPattern: read
22338
- });
22339
- return {
22340
- path: reportedPath,
22341
- valid: inspected.errors.length === 0 && inspected.stale.length === 0,
22342
- errors: inspected.errors,
22343
- stale: inspected.stale
22344
- };
22345
- });
22346
- return { learning, policy: { templateSetVersion: project.templateSetVersion ?? null, historicalPaths }, inputs: [...inputs].sort(([a], [b]) => a.localeCompare(b)).map(([path, sha2562]) => ({ path, sha256: sha2562 })) };
22347
- }
22348
-
22349
- // src/domain/staged-state.ts
22350
- import { existsSync as existsSync10, readdirSync as readdirSync8 } from "node:fs";
22351
- import { join as join9 } from "node:path";
22352
-
22353
- // src/domain/execution.ts
22354
- import { createHash as createHash3, randomUUID } from "node:crypto";
22355
- import { existsSync as existsSync8, lstatSync as lstatSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync4, readdirSync as readdirSync6, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
22356
- import { basename, dirname as dirname2, join as join7, resolve as resolve6 } from "node:path";
22357
-
22358
21772
  // src/domain/git.ts
22359
21773
  import { spawnSync } from "node:child_process";
22360
21774
  import { realpathSync } from "node:fs";
22361
- import { resolve as resolve4 } from "node:path";
21775
+ import { resolve as resolve3 } from "node:path";
22362
21776
  function gitRoot(projectRoot) {
22363
21777
  const root = realpathSync(safeProjectRoot(projectRoot));
22364
21778
  countGitProcess();
22365
21779
  const result = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: root, encoding: "utf8" });
22366
21780
  if (result.status !== 0) throw new Error((result.stderr || result.stdout || "project is not a Git worktree").trim());
22367
- const detected = realpathSync(resolve4(result.stdout.trim()));
21781
+ const detected = realpathSync(resolve3(result.stdout.trim()));
22368
21782
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
22369
21783
  return root;
22370
21784
  }
@@ -22379,9 +21793,9 @@ function readGitFileAtCommit(projectRoot, revision, path) {
22379
21793
  throw new Error(`Invalid Git file path: ${path}`);
22380
21794
  }
22381
21795
  const root = gitRoot(projectRoot);
22382
- const commit = resolveGitCommit(root, revision);
22383
- const result = spawnSync("git", ["show", `${commit}:${path}`], { cwd: root, encoding: "utf8" });
22384
- if (result.status !== 0) throw new Error(`Git commit ${commit} does not contain ${path}`);
21796
+ const commit2 = resolveGitCommit(root, revision);
21797
+ const result = spawnSync("git", ["show", `${commit2}:${path}`], { cwd: root, encoding: "utf8" });
21798
+ if (result.status !== 0) throw new Error(`Git commit ${commit2} does not contain ${path}`);
22385
21799
  return result.stdout;
22386
21800
  }
22387
21801
  function isGitAncestor(projectRoot, ancestor, descendant = "HEAD") {
@@ -22391,6 +21805,33 @@ function isGitAncestor(projectRoot, ancestor, descendant = "HEAD") {
22391
21805
  encoding: "utf8"
22392
21806
  }).status === 0;
22393
21807
  }
21808
+ function requireReviewedProductUnchanged(projectRoot, reviewedHead, trackId) {
21809
+ const root = gitRoot(projectRoot);
21810
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(trackId)) throw new Error("invalid trackId");
21811
+ const scopes = [
21812
+ [".", ":(exclude).cadre/**"],
21813
+ [
21814
+ ".cadre/workflow.md",
21815
+ ".cadre/guidelines.md",
21816
+ ".cadre/tech-stack.md",
21817
+ ".cadre/product.md",
21818
+ ".cadre/styleguides",
21819
+ ".cadre/patterns",
21820
+ `.cadre/tracks/${trackId}/spec.md`
21821
+ ]
21822
+ ];
21823
+ for (const scope of scopes) for (const args of [
21824
+ ["diff", "--name-only", "-z", reviewedHead, "HEAD", "--", ...scope],
21825
+ ["diff", "--name-only", "-z", reviewedHead, "--", ...scope],
21826
+ ["diff", "--cached", "--name-only", "-z", reviewedHead, "--", ...scope],
21827
+ ["ls-files", "--others", "--exclude-standard", "-z", "--", ...scope]
21828
+ ]) {
21829
+ countGitProcess();
21830
+ const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
21831
+ if (result.status !== 0) throw new Error("Cannot verify reviewed product content");
21832
+ if (result.stdout) throw new Error("Product content changed or verification policy changed after reviewed HEAD; verify and review the current product before completion");
21833
+ }
21834
+ }
22394
21835
  function reachableGitCommits(projectRoot, revisions) {
22395
21836
  let root;
22396
21837
  try {
@@ -22452,6 +21893,230 @@ function readGitBlobs(projectRoot, requests) {
22452
21893
  return values;
22453
21894
  }
22454
21895
 
21896
+ // src/domain/plan.ts
21897
+ import { createHash as createHash2 } from "node:crypto";
21898
+ import { existsSync as existsSync3 } from "node:fs";
21899
+ function dependencyList(value) {
21900
+ const trimmed = value.trim();
21901
+ if (trimmed === "none") return [];
21902
+ return trimmed.split(",").map((entry) => entry.trim()).filter(Boolean);
21903
+ }
21904
+ function graphDigest(graph) {
21905
+ const normalized = {
21906
+ specRevision: graph.specRevision,
21907
+ planRevision: graph.planRevision,
21908
+ phases: graph.phases.map((phase) => ({
21909
+ id: phase.id,
21910
+ title: phase.title,
21911
+ dependencies: phase.dependencies,
21912
+ tasks: phase.tasks.map((task) => ({
21913
+ id: task.id,
21914
+ title: task.title,
21915
+ dependencies: task.dependencies,
21916
+ manualVerification: task.manualVerification
21917
+ }))
21918
+ }))
21919
+ };
21920
+ return createHash2("sha256").update(JSON.stringify(normalized)).digest("hex");
21921
+ }
21922
+ function parsePlanContent(content, sourceLabel, errors = []) {
21923
+ const phases = [];
21924
+ let specRevision = null;
21925
+ let planRevision = null;
21926
+ let currentTask = null;
21927
+ const lines = content.split(/\r?\n/);
21928
+ for (const [index, line] of lines.entries()) {
21929
+ const lineNumber = index + 1;
21930
+ const spec = line.match(/^- Spec revision: (\d+)$/);
21931
+ if (spec) specRevision = Number(spec[1]);
21932
+ const revision = line.match(/^- Plan revision: (\d+)$/);
21933
+ if (revision) planRevision = Number(revision[1]);
21934
+ const phaseMatch = line.match(/^## Phase (\d+): (.+)$/);
21935
+ if (phaseMatch) {
21936
+ const number4 = Number(phaseMatch[1]);
21937
+ phases.push({
21938
+ number: number4,
21939
+ id: `P${number4}`,
21940
+ title: phaseMatch[2].trim(),
21941
+ dependencies: [],
21942
+ dependencyDeclared: false,
21943
+ tasks: [],
21944
+ completionCommit: void 0,
21945
+ line: lineNumber,
21946
+ trackVerification: phaseMatch[2].trim() === "Track-level User Manual Verification"
21947
+ });
21948
+ currentTask = null;
21949
+ continue;
21950
+ }
21951
+ const phaseDependencies = line.match(/^- Phase dependencies: (.+)$/);
21952
+ if (phaseDependencies) {
21953
+ const phase = phases.at(-1);
21954
+ if (!phase) errors.push(`${sourceLabel}:${lineNumber}: phase dependencies appear before a phase`);
21955
+ else if (phase.dependencyDeclared) errors.push(`${sourceLabel}:${lineNumber}: ${phase.id} has duplicate phase dependencies`);
21956
+ else {
21957
+ phase.dependencies = dependencyList(phaseDependencies[1]);
21958
+ phase.dependencyDeclared = true;
21959
+ }
21960
+ continue;
21961
+ }
21962
+ const phaseCommit = line.match(/^- Phase completion commit: (pending|`([0-9a-f]{7,40})`)$/);
21963
+ if (phaseCommit) {
21964
+ const phase = phases.at(-1);
21965
+ if (!phase) errors.push(`${sourceLabel}:${lineNumber}: phase completion commit appears before a phase`);
21966
+ else phase.completionCommit = phaseCommit[1] === "pending" ? null : phaseCommit[2];
21967
+ continue;
21968
+ }
21969
+ const taskMatch = line.match(/^- \[([ xX])\] (T(\d+)\.(\d+)) (.+)$/);
21970
+ if (taskMatch) {
21971
+ const phase = phases.at(-1);
21972
+ if (!phase) {
21973
+ errors.push(`${sourceLabel}:${lineNumber}: task appears before a phase`);
21974
+ continue;
21975
+ }
21976
+ let title = taskMatch[5].trim();
21977
+ let commit2 = null;
21978
+ const marker = title.match(/^(.*?)\s+<!-- commit: ([0-9a-f]{7,40}) -->$/);
21979
+ if (marker) {
21980
+ title = marker[1].trim();
21981
+ commit2 = marker[2];
21982
+ }
21983
+ currentTask = {
21984
+ checked: taskMatch[1].toLowerCase() === "x",
21985
+ id: taskMatch[2],
21986
+ phaseId: `P${taskMatch[3]}`,
21987
+ ordinal: Number(taskMatch[4]),
21988
+ title,
21989
+ commit: commit2,
21990
+ dependencies: [],
21991
+ dependencyDeclared: false,
21992
+ manualVerification: title === "User Manual Verification",
21993
+ line: lineNumber
21994
+ };
21995
+ phase.tasks.push(currentTask);
21996
+ continue;
21997
+ }
21998
+ const taskDependencies = line.match(/^ - Task dependencies: (.+)$/);
21999
+ if (taskDependencies) {
22000
+ if (!currentTask) errors.push(`${sourceLabel}:${lineNumber}: task dependencies do not follow a task`);
22001
+ else if (currentTask.dependencyDeclared) errors.push(`${sourceLabel}:${lineNumber}: ${currentTask.id} has duplicate task dependencies`);
22002
+ else {
22003
+ currentTask.dependencies = dependencyList(taskDependencies[1]);
22004
+ currentTask.dependencyDeclared = true;
22005
+ }
22006
+ }
22007
+ }
22008
+ const graphWithoutDigest = { specRevision, planRevision, phases };
22009
+ return { ...graphWithoutDigest, digest: graphDigest(graphWithoutDigest) };
22010
+ }
22011
+ function parsePlan(path, errors = []) {
22012
+ if (!existsSync3(path)) {
22013
+ errors.push(`${path}: missing plan`);
22014
+ return { specRevision: null, planRevision: null, phases: [], digest: graphDigest({ specRevision: null, planRevision: null, phases: [] }) };
22015
+ }
22016
+ return parsePlanContent(readInspectionText(path, "utf8"), path, errors);
22017
+ }
22018
+ function findCycles(nodes, owner, errors) {
22019
+ const ids = new Set(nodes.map((node) => node.id));
22020
+ const visiting = /* @__PURE__ */ new Set();
22021
+ const visited = /* @__PURE__ */ new Set();
22022
+ const byId = new Map(nodes.map((node) => [node.id, node]));
22023
+ function visit(id2, trail) {
22024
+ if (visiting.has(id2)) {
22025
+ errors.push(`${owner}: dependency cycle ${[...trail, id2].join(" -> ")}`);
22026
+ return;
22027
+ }
22028
+ if (visited.has(id2)) return;
22029
+ visiting.add(id2);
22030
+ for (const dependency of byId.get(id2)?.dependencies ?? []) {
22031
+ if (ids.has(dependency)) visit(dependency, [...trail, id2]);
22032
+ }
22033
+ visiting.delete(id2);
22034
+ visited.add(id2);
22035
+ }
22036
+ for (const node of nodes) visit(node.id, []);
22037
+ }
22038
+ function validatePlanGraph(path, graph, status, errors) {
22039
+ if (!graph.phases.length) {
22040
+ if (!["drafting-spec", "drafting-plan"].includes(status)) errors.push(`${path}: approved plan must contain phases`);
22041
+ return;
22042
+ }
22043
+ if (!Number.isInteger(graph.specRevision) || (graph.specRevision ?? 0) < 1) {
22044
+ errors.push(`${path}: Spec revision must be a positive integer`);
22045
+ }
22046
+ if (!Number.isInteger(graph.planRevision) || (graph.planRevision ?? 0) < 1) {
22047
+ errors.push(`${path}: Plan revision must be a positive integer`);
22048
+ }
22049
+ const phaseIds = new Set(graph.phases.map((phase) => phase.id));
22050
+ const finalPhase = graph.phases.at(-1);
22051
+ graph.phases.forEach((phase, phaseIndex) => {
22052
+ if (phase.number !== phaseIndex + 1) errors.push(`${path}: phases must be sequential from 1`);
22053
+ if (!phase.tasks.length) errors.push(`${path}: ${phase.id} has no tasks`);
22054
+ if (phase.trackVerification) {
22055
+ phase.dependencies = graph.phases.slice(0, phaseIndex).map((previous) => previous.id);
22056
+ if (phase !== finalPhase && (!phase.completionCommit || !phase.tasks.length || phase.tasks.some((task) => !task.checked))) {
22057
+ errors.push(`${path}: historical Track-level User Manual Verification must be completed with commit provenance`);
22058
+ }
22059
+ }
22060
+ if (!phase.trackVerification && !phase.dependencyDeclared) {
22061
+ errors.push(`${path}:${phase.line}: ${phase.id} must declare phase dependencies`);
22062
+ }
22063
+ if (phase.trackVerification && phase.dependencyDeclared) {
22064
+ errors.push(`${path}:${phase.line}: final track verification dependencies are derived and must not be declared`);
22065
+ }
22066
+ if (new Set(phase.dependencies).size !== phase.dependencies.length) {
22067
+ errors.push(`${path}:${phase.line}: ${phase.id} contains duplicate phase dependencies`);
22068
+ }
22069
+ for (const dependency of phase.dependencies) {
22070
+ if (!/^P\d+$/.test(dependency) || !phaseIds.has(dependency)) errors.push(`${path}:${phase.line}: ${phase.id} has unknown phase dependency ${dependency}`);
22071
+ if (dependency === phase.id) errors.push(`${path}:${phase.line}: ${phase.id} cannot depend on itself`);
22072
+ if (dependency === finalPhase.id) errors.push(`${path}:${phase.line}: ${phase.id} cannot depend on final track verification`);
22073
+ }
22074
+ const nonManualTasks = phase.tasks.filter((task) => !task.manualVerification);
22075
+ if (!phase.trackVerification && !nonManualTasks.length) errors.push(`${path}: ${phase.id} has no delivery task`);
22076
+ if (phase.trackVerification && (phase.tasks.length !== 1 || !phase.tasks[0]?.manualVerification)) {
22077
+ errors.push(`${path}: final track verification phase must contain only User Manual Verification`);
22078
+ }
22079
+ phase.tasks.forEach((task, taskIndex) => {
22080
+ if (task.phaseId !== phase.id) errors.push(`${path}:${task.line}: ${task.id} is in the wrong phase`);
22081
+ if (task.ordinal !== taskIndex + 1) errors.push(`${path}:${task.line}: task ordinals must be sequential`);
22082
+ if (task.checked && !task.commit) errors.push(`${path}:${task.line}: completed task ${task.id} has no commit marker`);
22083
+ if (!task.checked && task.commit) errors.push(`${path}:${task.line}: pending task ${task.id} has a commit marker`);
22084
+ if (task.manualVerification) {
22085
+ if (task !== phase.tasks.at(-1)) errors.push(`${path}:${task.line}: User Manual Verification must be the final phase task`);
22086
+ if (task.dependencyDeclared) errors.push(`${path}:${task.line}: ${task.id} dependencies are derived and must not be declared`);
22087
+ task.dependencies = nonManualTasks.map((candidate) => candidate.id);
22088
+ } else if (!task.dependencyDeclared) {
22089
+ errors.push(`${path}:${task.line}: ${task.id} must declare task dependencies`);
22090
+ }
22091
+ if (new Set(task.dependencies).size !== task.dependencies.length) {
22092
+ errors.push(`${path}:${task.line}: ${task.id} contains duplicate task dependencies`);
22093
+ }
22094
+ for (const dependency of task.dependencies) {
22095
+ const target = phase.tasks.find((candidate) => candidate.id === dependency);
22096
+ if (!target) errors.push(`${path}:${task.line}: ${task.id} has unknown or cross-phase task dependency ${dependency}`);
22097
+ if (dependency === task.id) errors.push(`${path}:${task.line}: ${task.id} cannot depend on itself`);
22098
+ if (target?.manualVerification) errors.push(`${path}:${task.line}: ${task.id} cannot depend on manual verification`);
22099
+ }
22100
+ });
22101
+ if (phase.completionCommit === void 0) errors.push(`${path}: ${phase.id} lacks a completion commit field`);
22102
+ const phaseDone = phase.tasks.length > 0 && phase.tasks.every((task) => task.checked);
22103
+ if (phaseDone && !phase.completionCommit) errors.push(`${path}: completed ${phase.id} has no completion commit`);
22104
+ if (!phaseDone && phase.completionCommit) errors.push(`${path}: incomplete ${phase.id} has a completion commit`);
22105
+ findCycles(phase.tasks, `${path}:${phase.id}`, errors);
22106
+ });
22107
+ if (!finalPhase.trackVerification) errors.push(`${path}: final phase must be Track-level User Manual Verification`);
22108
+ findCycles(graph.phases, path, errors);
22109
+ if (["ready_for_review", "completed", "archived"].includes(status)) {
22110
+ const pending = graph.phases.flatMap((phase) => phase.tasks).filter((task) => !task.checked);
22111
+ if (pending.length) errors.push(`${path}: ${status} track has ${pending.length} pending task(s)`);
22112
+ }
22113
+ }
22114
+ function readAndValidatePlan(path, status, errors) {
22115
+ const graph = parsePlan(path, errors);
22116
+ validatePlanGraph(path, graph, status, errors);
22117
+ return graph;
22118
+ }
22119
+
22455
22120
  // src/domain/plan-provenance.ts
22456
22121
  function validatePlanProvenance(root, evidence) {
22457
22122
  const requests = evidence.map((entry) => `${entry.commit}:${entry.path}`);
@@ -22465,8 +22130,8 @@ function validatePlanProvenance(root, evidence) {
22465
22130
  }
22466
22131
 
22467
22132
  // src/domain/tracks-index.ts
22468
- import { existsSync as existsSync7, readFileSync as readFileSync3, readdirSync as readdirSync5 } from "node:fs";
22469
- import { join as join6, resolve as resolve5 } from "node:path";
22133
+ import { existsSync as existsSync4, readFileSync as readFileSync2, readdirSync as readdirSync2 } from "node:fs";
22134
+ import { join as join3, resolve as resolve4 } from "node:path";
22470
22135
  function buildTracks(tracks) {
22471
22136
  const lines = [
22472
22137
  "# Tracks",
@@ -22483,22 +22148,22 @@ function buildTracks(tracks) {
22483
22148
  `;
22484
22149
  }
22485
22150
  function renderTracksWithState(projectRoot, statePath, proposedState) {
22486
- const root = join6(safeProjectRoot(projectRoot), ".cadre");
22487
- const resolvedStatePath = resolve5(statePath);
22151
+ const root = join3(safeProjectRoot(projectRoot), ".cadre");
22152
+ const resolvedStatePath = resolve4(statePath);
22488
22153
  const tracks = [];
22489
22154
  const ids = /* @__PURE__ */ new Set();
22490
22155
  let overrideFound = false;
22491
22156
  for (const directory of ["tracks", "archive"]) {
22492
- const directoryRoot = join6(root, directory);
22493
- if (!existsSync7(directoryRoot)) continue;
22494
- for (const entry of readdirSync5(directoryRoot, { withFileTypes: true }).filter((candidate) => candidate.isDirectory()).sort((left, right) => left.name.localeCompare(right.name))) {
22495
- const path = join6(directoryRoot, entry.name, "state.json");
22157
+ const directoryRoot = join3(root, directory);
22158
+ if (!existsSync4(directoryRoot)) continue;
22159
+ for (const entry of readdirSync2(directoryRoot, { withFileTypes: true }).filter((candidate) => candidate.isDirectory()).sort((left, right) => left.name.localeCompare(right.name))) {
22160
+ const path = join3(directoryRoot, entry.name, "state.json");
22496
22161
  let state;
22497
- if (resolve5(path) === resolvedStatePath) {
22162
+ if (resolve4(path) === resolvedStatePath) {
22498
22163
  overrideFound = true;
22499
22164
  state = proposedState;
22500
22165
  } else {
22501
- state = JSON.parse(readFileSync3(path, "utf8"));
22166
+ state = JSON.parse(readFileSync2(path, "utf8"));
22502
22167
  }
22503
22168
  const id2 = String(state.trackId ?? "");
22504
22169
  if (!id2 || id2 !== entry.name) throw new Error(`invalid track identity at ${path}`);
@@ -22515,10 +22180,10 @@ function renderTracksWithState(projectRoot, statePath, proposedState) {
22515
22180
  }
22516
22181
  if (!overrideFound) throw new Error("execution track state is outside the active track index");
22517
22182
  tracks.sort((left, right) => left.id.localeCompare(right.id));
22518
- const tracksPath = join6(root, "tracks.md");
22183
+ const tracksPath = join3(root, "tracks.md");
22519
22184
  return {
22520
22185
  tracksPath,
22521
- tracksBody: readFileSync3(tracksPath, "utf8"),
22186
+ tracksBody: readFileSync2(tracksPath, "utf8"),
22522
22187
  tracksContent: buildTracks(tracks)
22523
22188
  };
22524
22189
  }
@@ -22536,10 +22201,12 @@ var EXECUTION_NODE_STATUSES = [
22536
22201
  "completed",
22537
22202
  "blocked"
22538
22203
  ];
22539
- var EXECUTION_APPROVAL_MODES = ["governed", "phase", "autonomous"];
22540
22204
  function deriveExecutionStartInput(input) {
22541
22205
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
22542
- const requestedMode = input.requestedMode ?? "parallel";
22206
+ const state = JSON.parse(readSafeArtifact(input.projectRoot, `.cadre/tracks/${input.trackId}/state.json`));
22207
+ const previousId = state.autonomousReview ? state.lastExecution?.executionId : void 0;
22208
+ const previous = previousId ? readExecution(input.projectRoot, input.trackId, previousId) : void 0;
22209
+ const requestedMode = input.requestedMode ?? previous?.requestedMode ?? "parallel";
22543
22210
  return {
22544
22211
  projectRoot: input.projectRoot,
22545
22212
  trackId: input.trackId,
@@ -22547,7 +22214,7 @@ function deriveExecutionStartInput(input) {
22547
22214
  requestedMode,
22548
22215
  effectiveMode: requestedMode,
22549
22216
  ...input.approvalMode ? { approvalMode: input.approvalMode } : {},
22550
- maxWorkers: input.maxWorkers ?? 3,
22217
+ maxWorkers: input.maxWorkers ?? previous?.maxWorkers ?? 3,
22551
22218
  baseCommit: resolveGitCommit(input.projectRoot),
22552
22219
  approvedAt: startedAt
22553
22220
  };
@@ -22563,24 +22230,24 @@ function writeJournalAtomically(path, journal) {
22563
22230
  `);
22564
22231
  }
22565
22232
  function writeTextAtomically(path, content) {
22566
- if (existsSync8(path) && readFileSync4(path, "utf8") === content) return;
22567
- const temporaryPath = join7(dirname2(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
22233
+ if (existsSync5(path) && readFileSync3(path, "utf8") === content) return;
22234
+ const temporaryPath = join4(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
22568
22235
  try {
22569
- writeFileSync2(temporaryPath, content, { flag: "wx" });
22570
- renameSync2(temporaryPath, path);
22236
+ writeFileSync(temporaryPath, content, { flag: "wx" });
22237
+ renameSync(temporaryPath, path);
22571
22238
  } finally {
22572
- if (existsSync8(temporaryPath)) unlinkSync2(temporaryPath);
22239
+ if (existsSync5(temporaryPath)) unlinkSync(temporaryPath);
22573
22240
  }
22574
22241
  }
22575
- function assertIdentifiers(trackId, executionId) {
22242
+ function assertIdentifiers(trackId, executionId2) {
22576
22243
  if (!TRACK_ID.test(trackId)) throw new Error("trackId must be lower-case hyphen-case");
22577
- if (!EXECUTION_ID.test(executionId)) throw new Error("executionId must contain only letters, digits, and hyphens");
22244
+ if (!EXECUTION_ID.test(executionId2)) throw new Error("executionId must contain only letters, digits, and hyphens");
22578
22245
  }
22579
22246
  function activeTrackRoot(projectRoot, trackId) {
22580
- return join7(safeProjectRoot(projectRoot), ".cadre", "tracks", trackId);
22247
+ return join4(safeProjectRoot(projectRoot), ".cadre", "tracks", trackId);
22581
22248
  }
22582
- function journalRelative(executionId) {
22583
- return `executions/execution-${executionId}.json`;
22249
+ function journalRelative(executionId2) {
22250
+ return `executions/execution-${executionId2}.json`;
22584
22251
  }
22585
22252
  function buildNodes(graph) {
22586
22253
  const nodes = {};
@@ -22637,12 +22304,20 @@ function previewExecutionStart(input) {
22637
22304
  throw new Error("an explicitly sequential execution cannot become parallel");
22638
22305
  }
22639
22306
  const trackRoot = activeTrackRoot(input.projectRoot, input.trackId);
22640
- const statePath = join7(trackRoot, "state.json");
22641
- const planPath = join7(trackRoot, "plan.md");
22642
- const stateBody = readFileSync4(statePath, "utf8");
22307
+ const statePath = join4(trackRoot, "state.json");
22308
+ const planPath = join4(trackRoot, "plan.md");
22309
+ const stateBody = readFileSync3(statePath, "utf8");
22643
22310
  const state = JSON.parse(stateBody);
22644
- const approvalMode = input.approvalMode ?? state.lastExecution?.approvalMode ?? "phase";
22645
- if (!EXECUTION_APPROVAL_MODES.includes(approvalMode)) throw new Error("approvalMode must be governed, phase, or autonomous");
22311
+ const inheritedMode = state.lastExecution ? resolveApprovalMode(state.lastExecution, state.approvalModeMigration) : void 0;
22312
+ const approvalMode = input.approvalMode ?? inheritedMode ?? "track";
22313
+ if (!EXECUTION_APPROVAL_MODES.includes(approvalMode)) throw new Error("approvalMode must be governed, phase, track, or autonomous");
22314
+ if (approvalMode === "autonomous" && !SHA.test(state.commits?.spec ?? "")) throw new Error("Autonomous execution requires an approved specification commit");
22315
+ if (state.autonomousReview && approvalMode !== "autonomous") throw new Error("Changing an active Autonomous loop requires an approved refresh that archives its authority in history");
22316
+ if (state.autonomousReview && approvalMode === "autonomous") {
22317
+ requireReviewProgress(state.autonomousReview);
22318
+ if (state.autonomousReview.specCommit !== state.commits?.spec) throw new Error("Autonomous scope changed; obtain a new explicit authorization through refresh");
22319
+ if (state.autonomousReview.checkpoint !== "remediating") throw new Error("Autonomous review must authorize remediation before starting another execution");
22320
+ }
22646
22321
  if (state.trackId !== input.trackId) throw new Error("track state does not match trackId");
22647
22322
  if (!["planned", "in_progress"].includes(state.status)) throw new Error(`track ${input.trackId} is not implementable from ${state.status}`);
22648
22323
  if (state.operation != null) throw new Error(`track ${input.trackId} already has an active operation`);
@@ -22666,7 +22341,7 @@ function previewExecutionStart(input) {
22666
22341
  if (evidenceErrors.length) throw new Error(evidenceErrors.join("\n"));
22667
22342
  const planRevision = graph.planRevision;
22668
22343
  const relativeJournal = journalRelative(input.executionId);
22669
- const journalPath = join7(trackRoot, relativeJournal);
22344
+ const journalPath = join4(trackRoot, relativeJournal);
22670
22345
  const journal = {
22671
22346
  schemaVersion: 1,
22672
22347
  executionId: input.executionId,
@@ -22676,6 +22351,7 @@ function previewExecutionStart(input) {
22676
22351
  requestedMode: input.requestedMode,
22677
22352
  effectiveMode: input.effectiveMode,
22678
22353
  approvalMode,
22354
+ approvalPolicyVersion: APPROVAL_POLICY_VERSION,
22679
22355
  maxWorkers: input.maxWorkers,
22680
22356
  planRevision,
22681
22357
  planCommit: state.commits.plan,
@@ -22687,11 +22363,11 @@ function previewExecutionStart(input) {
22687
22363
  headCommit: null,
22688
22364
  nodes: buildNodes(graph)
22689
22365
  };
22690
- if (existsSync8(journalPath)) {
22691
- if (lstatSync4(journalPath).isSymbolicLink()) throw new Error("refusing an execution journal symbolic link");
22366
+ if (existsSync5(journalPath)) {
22367
+ if (lstatSync3(journalPath).isSymbolicLink()) throw new Error("refusing an execution journal symbolic link");
22692
22368
  let existing;
22693
22369
  try {
22694
- existing = JSON.parse(readFileSync4(journalPath, "utf8"));
22370
+ existing = JSON.parse(readFileSync3(journalPath, "utf8"));
22695
22371
  } catch (error51) {
22696
22372
  throw new Error(`existing execution journal is invalid: ${error51 instanceof Error ? error51.message : String(error51)}`);
22697
22373
  }
@@ -22711,6 +22387,7 @@ function previewExecutionStart(input) {
22711
22387
  journal: relativeJournal,
22712
22388
  mode: input.effectiveMode,
22713
22389
  approvalMode,
22390
+ approvalPolicyVersion: APPROVAL_POLICY_VERSION,
22714
22391
  graphDigest: graph.digest,
22715
22392
  planRevision
22716
22393
  };
@@ -22718,42 +22395,56 @@ function previewExecutionStart(input) {
22718
22395
  ...state,
22719
22396
  status: "in_progress",
22720
22397
  checkpoint: "executing",
22721
- operation
22398
+ operation,
22399
+ ...approvalMode === "autonomous" ? { autonomousReview: state.autonomousReview ? { ...state.autonomousReview, checkpoint: "implementing" } : {
22400
+ policyVersion: 2,
22401
+ originExecutionId: input.executionId,
22402
+ authorizedAt: input.approvedAt,
22403
+ initialBaseCommit: input.baseCommit,
22404
+ specCommit: state.commits.spec,
22405
+ checkpoint: "implementing",
22406
+ findings: []
22407
+ } } : {}
22722
22408
  };
22723
22409
  return {
22724
22410
  journalPath,
22725
22411
  journal,
22726
22412
  statePath,
22727
22413
  state: proposedState,
22728
- digest: hash2({ stateBody, planBody: readFileSync4(planPath, "utf8"), journal, state: proposedState })
22414
+ digest: hash2({ stateBody, planBody: readFileSync3(planPath, "utf8"), journal, state: proposedState })
22729
22415
  };
22730
22416
  }
22731
22417
  function applyExecutionStart(input, proposalDigest, preparedProposal) {
22732
22418
  const proposal = preparedProposal ?? previewExecutionStart(input);
22733
22419
  if (proposal.digest !== proposalDigest) throw new Error("execution proposal is stale; preview it again");
22734
- if (lstatSync4(proposal.statePath).isSymbolicLink()) throw new Error("refusing to start execution through a state symbolic link");
22735
- mkdirSync2(dirname2(proposal.journalPath), { recursive: true });
22736
- if (!existsSync8(proposal.journalPath)) {
22737
- writeFileSync2(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
22420
+ if (lstatSync3(proposal.statePath).isSymbolicLink()) throw new Error("refusing to start execution through a state symbolic link");
22421
+ mkdirSync(dirname(proposal.journalPath), { recursive: true });
22422
+ if (!existsSync5(proposal.journalPath)) {
22423
+ writeFileSync(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
22738
22424
  `);
22739
22425
  }
22740
- writeFileSync2(proposal.statePath, `${JSON.stringify(proposal.state, null, 2)}
22426
+ writeFileSync(proposal.statePath, `${JSON.stringify(proposal.state, null, 2)}
22741
22427
  `);
22742
22428
  return { ...proposal, derivedStatus: deriveExecutionStatus(proposal.journal) };
22743
22429
  }
22744
- function executionPaths(projectRoot, trackId, executionId) {
22745
- assertIdentifiers(trackId, executionId);
22430
+ function executionPaths(projectRoot, trackId, executionId2) {
22431
+ assertIdentifiers(trackId, executionId2);
22746
22432
  const trackRoot = activeTrackRoot(projectRoot, trackId);
22747
- return { statePath: join7(trackRoot, "state.json"), journalPath: join7(trackRoot, journalRelative(executionId)) };
22433
+ return { statePath: join4(trackRoot, "state.json"), journalPath: join4(trackRoot, journalRelative(executionId2)) };
22748
22434
  }
22749
- function readExecution(projectRoot, trackId, executionId) {
22750
- assertIdentifiers(trackId, executionId);
22435
+ function readExecution(projectRoot, trackId, executionId2) {
22436
+ assertIdentifiers(trackId, executionId2);
22751
22437
  const root = safeProjectRoot(projectRoot);
22752
- const locations = ["tracks", "archive"].filter((location2) => existsSync8(join7(root, ".cadre", location2, trackId, journalRelative(executionId))));
22753
- if (!locations.length) throw new CadreError("EXECUTION_NOT_FOUND", `No execution ${executionId} is recorded for track ${trackId}. Read project_status for the persisted executionId; pass that ID, not a journal filename.`);
22754
- if (locations.length !== 1) throw new CadreError("EXECUTION_AMBIGUOUS", `Execution ${executionId} exists in both active and archived locations; reconcile duplicate evidence before continuing.`);
22438
+ const locations = ["tracks", "archive"].filter((location2) => existsSync5(join4(root, ".cadre", location2, trackId, journalRelative(executionId2))));
22439
+ if (!locations.length) throw new CadreError("EXECUTION_NOT_FOUND", `No execution ${executionId2} is recorded for track ${trackId}. Read project_status for the persisted executionId; pass that ID, not a journal filename.`);
22440
+ if (locations.length !== 1) throw new CadreError("EXECUTION_AMBIGUOUS", `Execution ${executionId2} exists in both active and archived locations; reconcile duplicate evidence before continuing.`);
22755
22441
  const location = locations[0];
22756
- return JSON.parse(readSafeArtifact(root, `.cadre/${location}/${trackId}/${journalRelative(executionId)}`));
22442
+ return JSON.parse(readSafeArtifact(root, `.cadre/${location}/${trackId}/${journalRelative(executionId2)}`));
22443
+ }
22444
+ function requireTrackExecutionAuthority(projectRoot, trackId, executionId2) {
22445
+ const journal = readExecution(projectRoot, trackId, executionId2);
22446
+ const state = journal.approvalMode === "autonomous" ? JSON.parse(readSafeArtifact(projectRoot, `.cadre/tracks/${trackId}/state.json`)) : {};
22447
+ return requireExecutionAuthority(journal, state);
22757
22448
  }
22758
22449
  var ALLOWED_TRANSITIONS = {
22759
22450
  pending: ["running", "blocked"],
@@ -22883,8 +22574,11 @@ function previewExecutionNodesUpdate(input) {
22883
22574
  throw new Error("updates must contain 1 through 128 ordered node transitions");
22884
22575
  }
22885
22576
  const { journalPath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
22886
- const currentBody = readFileSync4(journalPath, "utf8");
22577
+ const currentBody = readFileSync3(journalPath, "utf8");
22887
22578
  const journal = JSON.parse(currentBody);
22579
+ if (input.updates.some((update) => update.status !== "blocked" && !(update.status === "completed" && ["integrated", "completed"].includes(journal.nodes[update.nodeId]?.status ?? "")) && !(update.status === "integrated" && journal.nodes[update.nodeId]?.status === "integrated"))) {
22580
+ requireExecutionAuthority(journal, journal.approvalMode === "autonomous" ? JSON.parse(readSafeArtifact(input.projectRoot, `.cadre/tracks/${input.trackId}/state.json`)) : {});
22581
+ }
22888
22582
  for (const update of input.updates) applyNodeTransition(journal, update);
22889
22583
  return { path: journalPath, journal, digest: hash2({ currentBody, journal }) };
22890
22584
  }
@@ -22988,7 +22682,8 @@ function compactExecutionStatus(journal, nodeId) {
22988
22682
  checkpoint: journal.checkpoint,
22989
22683
  requestedMode: journal.requestedMode,
22990
22684
  effectiveMode: journal.effectiveMode,
22991
- approvalMode: journal.approvalMode,
22685
+ approvalMode: journal.approvalMode ?? "governed",
22686
+ approvalPolicyVersion: journal.approvalPolicyVersion ?? 1,
22992
22687
  maxWorkers: journal.maxWorkers,
22993
22688
  planRevision: journal.planRevision,
22994
22689
  startedAt: journal.startedAt,
@@ -23000,8 +22695,8 @@ function compactExecutionStatus(journal, nodeId) {
23000
22695
  derivedStatus
23001
22696
  };
23002
22697
  }
23003
- function executionStatus(projectRoot, trackId, executionId) {
23004
- const journal = readExecution(projectRoot, trackId, executionId);
22698
+ function executionStatus(projectRoot, trackId, executionId2) {
22699
+ const journal = readExecution(projectRoot, trackId, executionId2);
23005
22700
  return { journal, ...deriveExecutionStatus(journal) };
23006
22701
  }
23007
22702
  var EXECUTION_CHECKPOINT_EVENTS = [
@@ -23018,7 +22713,7 @@ function checkpointUpdates(journal, input) {
23018
22713
  if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
23019
22714
  const evidence = input.verification?.trim();
23020
22715
  const authorization = input.authorization?.trim();
23021
- const commit = input.commit;
22716
+ const commit2 = input.commit;
23022
22717
  const updates = [];
23023
22718
  const start = () => {
23024
22719
  if (node.status === "pending" || node.status === "blocked") {
@@ -23047,7 +22742,7 @@ function checkpointUpdates(journal, input) {
23047
22742
  start();
23048
22743
  break;
23049
22744
  case "record_commit":
23050
- if (!commit || !evidence || !authorization) {
22745
+ if (!commit2 || !evidence || !authorization) {
23051
22746
  throw new Error("record_commit requires commit, verification, and authorization");
23052
22747
  }
23053
22748
  if (node.status === "running") {
@@ -23055,20 +22750,20 @@ function checkpointUpdates(journal, input) {
23055
22750
  } else if (node.status !== "awaiting_approval") {
23056
22751
  throw new Error(`${node.id} cannot record a commit from ${node.status}`);
23057
22752
  }
23058
- updates.push({ nodeId: node.id, status: "committed", workerCommit: commit, approval: authorization });
22753
+ updates.push({ nodeId: node.id, status: "committed", workerCommit: commit2, approval: authorization });
23059
22754
  break;
23060
22755
  case "record_integration":
23061
- if (!commit || !evidence) throw new Error("record_integration requires commit and verification");
22756
+ if (!commit2 || !evidence) throw new Error("record_integration requires commit and verification");
23062
22757
  if (node.status === "committed") updates.push({ nodeId: node.id, status: "integrating" });
23063
22758
  else if (node.status !== "integrating" && node.status !== "conflicted" && node.status !== "integrated") {
23064
22759
  throw new Error(`${node.id} cannot record integration from ${node.status}`);
23065
22760
  }
23066
22761
  if (node.status !== "integrated") {
23067
- updates.push({ nodeId: node.id, status: "integrated", mergeCommit: commit, verification: evidence });
22762
+ updates.push({ nodeId: node.id, status: "integrated", mergeCommit: commit2, verification: evidence });
23068
22763
  }
23069
22764
  break;
23070
22765
  case "record_verification":
23071
- if (node.kind !== "manual-verification" || !commit || !evidence || !authorization) {
22766
+ if (node.kind !== "manual-verification" || !commit2 || !evidence || !authorization) {
23072
22767
  throw new Error("record_verification requires a manual-verification node, commit, verification, and authorization");
23073
22768
  }
23074
22769
  if (node.status === "pending") updates.push({ nodeId: node.id, status: "running" });
@@ -23076,9 +22771,9 @@ function checkpointUpdates(journal, input) {
23076
22771
  throw new Error(`${node.id} cannot record verification from ${node.status}`);
23077
22772
  }
23078
22773
  if (node.status !== "awaiting_manual_verification") {
23079
- updates.push({ nodeId: node.id, status: "awaiting_manual_verification", verification: evidence, workerCommit: commit });
22774
+ updates.push({ nodeId: node.id, status: "awaiting_manual_verification", verification: evidence, workerCommit: commit2 });
23080
22775
  }
23081
- updates.push({ nodeId: node.id, status: "completed", workerCommit: commit, approval: authorization });
22776
+ updates.push({ nodeId: node.id, status: "completed", workerCommit: commit2, approval: authorization });
23082
22777
  break;
23083
22778
  case "complete":
23084
22779
  if (node.status === "committed") updates.push({
@@ -23092,14 +22787,14 @@ function checkpointUpdates(journal, input) {
23092
22787
  ...evidence ? { verification: evidence } : {}
23093
22788
  });
23094
22789
  else if (node.kind === "phase" && node.status === "running") {
23095
- if (!commit || !evidence || !authorization) {
22790
+ if (!commit2 || !evidence || !authorization) {
23096
22791
  throw new Error("completing a running phase requires commit, verification, and authorization");
23097
22792
  }
23098
22793
  updates.push(
23099
22794
  { nodeId: node.id, status: "awaiting_approval", verification: evidence },
23100
- { nodeId: node.id, status: "committed", workerCommit: commit, approval: authorization },
22795
+ { nodeId: node.id, status: "committed", workerCommit: commit2, approval: authorization },
23101
22796
  { nodeId: node.id, status: "integrating" },
23102
- { nodeId: node.id, status: "integrated", mergeCommit: commit },
22797
+ { nodeId: node.id, status: "integrated", mergeCommit: commit2 },
23103
22798
  { nodeId: node.id, status: "completed" }
23104
22799
  );
23105
22800
  } else throw new Error(`${node.id} cannot complete from ${node.status}`);
@@ -23186,7 +22881,7 @@ function deriveExecutionFinishInput(input) {
23186
22881
  return { ...input, headCommit: journal.headCommit, completedAt: journal.completedAt };
23187
22882
  }
23188
22883
  const { statePath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
23189
- const state = JSON.parse(readFileSync4(statePath, "utf8"));
22884
+ const state = JSON.parse(readFileSync3(statePath, "utf8"));
23190
22885
  const priorHead = state.lastExecution?.headCommit;
23191
22886
  const priorCompletedAt = state.lastExecution?.completedAt;
23192
22887
  if (state.lastExecution?.executionId === input.executionId && typeof priorHead === "string" && typeof priorCompletedAt === "string") {
@@ -23229,12 +22924,14 @@ function previewExecutionFinish(input) {
23229
22924
  if (!SHA.test(input.headCommit)) throw new Error("headCommit must be a Git commit SHA");
23230
22925
  if (!Number.isFinite(Date.parse(input.completedAt))) throw new Error("completedAt must be an ISO timestamp");
23231
22926
  const { statePath, journalPath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
23232
- const stateBody = readFileSync4(statePath, "utf8");
23233
- const journalBody = readFileSync4(journalPath, "utf8");
22927
+ const stateBody = readFileSync3(statePath, "utf8");
22928
+ const journalBody = readFileSync3(journalPath, "utf8");
23234
22929
  const state = JSON.parse(stateBody);
23235
22930
  const journal = JSON.parse(journalBody);
22931
+ resolveApprovalMode(journal);
23236
22932
  const operation = state.operation;
23237
22933
  const stateAlreadyCompleted = state.status === "ready_for_review" && state.lastExecution?.executionId === input.executionId && state.lastExecution.headCommit === input.headCommit && state.lastExecution.completedAt === input.completedAt;
22934
+ if (!stateAlreadyCompleted) requireExecutionAuthority(journal, state);
23238
22935
  if (!stateAlreadyCompleted && (operation?.action !== "implement" || operation.executionId !== input.executionId)) {
23239
22936
  throw new Error("track does not point to this implementation execution");
23240
22937
  }
@@ -23251,10 +22948,10 @@ function previewExecutionFinish(input) {
23251
22948
  ...Object.values(journal.nodes).flatMap((node) => [node.workerCommit, node.mergeCommit].filter(Boolean))
23252
22949
  ];
23253
22950
  const reachability = reachableGitCommits(input.projectRoot, commits);
23254
- const unreachable = reachability ? commits.filter((commit) => reachability.get(commit) === false) : [];
22951
+ const unreachable = reachability ? commits.filter((commit2) => reachability.get(commit2) === false) : [];
23255
22952
  if (unreachable.length) throw new Error(`execution contains unreachable commits: ${[...new Set(unreachable)].join(", ")}`);
23256
- const planPath = join7(dirname2(statePath), "plan.md");
23257
- const planBody = readFileSync4(planPath, "utf8");
22953
+ const planPath = join4(dirname(statePath), "plan.md");
22954
+ const planBody = readFileSync3(planPath, "utf8");
23258
22955
  const planErrors = [];
23259
22956
  const graph = parsePlanContent(planBody, planPath, planErrors);
23260
22957
  validatePlanGraph(planPath, graph, "in_progress", planErrors);
@@ -23268,8 +22965,8 @@ function previewExecutionFinish(input) {
23268
22965
  validatePlanGraph(planPath, completedGraph, "ready_for_review", completedPlanErrors);
23269
22966
  if (completedPlanErrors.length) throw new Error(completedPlanErrors.join("\n"));
23270
22967
  if (completedGraph.digest !== journal.graphDigest) throw new Error("completed plan changed the approved execution graph");
23271
- const worktreeRoot = join7(safeProjectRoot(input.projectRoot), ".cadre", ".worktrees", input.trackId, input.executionId);
23272
- if (existsSync8(worktreeRoot) && readdirSync6(worktreeRoot).length) {
22968
+ const worktreeRoot = join4(safeProjectRoot(input.projectRoot), ".cadre", ".worktrees", input.trackId, input.executionId);
22969
+ if (existsSync5(worktreeRoot) && readdirSync3(worktreeRoot).length) {
23273
22970
  throw new Error(`execution still has managed worktrees under ${worktreeRoot}`);
23274
22971
  }
23275
22972
  const completedJournal = {
@@ -23284,10 +22981,12 @@ function previewExecutionFinish(input) {
23284
22981
  status: "ready_for_review",
23285
22982
  checkpoint: "ready_for_review",
23286
22983
  operation: null,
22984
+ ...state.autonomousReview && journal.approvalMode === "autonomous" ? { autonomousReview: { ...state.autonomousReview, checkpoint: "reviewing" } } : {},
23287
22985
  lastExecution: {
23288
22986
  executionId: input.executionId,
23289
22987
  journal: journalRelative(input.executionId),
23290
- approvalMode: journal.approvalMode,
22988
+ approvalMode: journal.approvalMode ?? "governed",
22989
+ approvalPolicyVersion: journal.approvalPolicyVersion ?? 1,
23291
22990
  planRevision: journal.planRevision,
23292
22991
  graphDigest: journal.graphDigest,
23293
22992
  headCommit: input.headCommit,
@@ -23323,7 +23022,7 @@ function previewExecutionFinish(input) {
23323
23022
  function applyExecutionFinish(input, proposalDigest, preparedProposal) {
23324
23023
  const proposal = preparedProposal ?? previewExecutionFinish(input);
23325
23024
  if (proposal.digest !== proposalDigest) throw new Error("execution completion proposal is stale; preview it again");
23326
- if (lstatSync4(proposal.journalPath).isSymbolicLink() || lstatSync4(proposal.statePath).isSymbolicLink() || lstatSync4(proposal.planPath).isSymbolicLink() || lstatSync4(proposal.tracksPath).isSymbolicLink()) {
23025
+ if (lstatSync3(proposal.journalPath).isSymbolicLink() || lstatSync3(proposal.statePath).isSymbolicLink() || lstatSync3(proposal.planPath).isSymbolicLink() || lstatSync3(proposal.tracksPath).isSymbolicLink()) {
23327
23026
  throw new Error("refusing to complete execution through a symbolic link");
23328
23027
  }
23329
23028
  writeTextAtomically(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
@@ -23354,12 +23053,12 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23354
23053
  errors.push(`${state.trackId}: invalid execution journal path`);
23355
23054
  return;
23356
23055
  }
23357
- const path = resolve6(trackRoot, relative7);
23358
- if (!path.startsWith(`${resolve6(trackRoot)}/`)) {
23056
+ const path = resolve5(trackRoot, relative7);
23057
+ if (!path.startsWith(`${resolve5(trackRoot)}/`)) {
23359
23058
  errors.push(`${state.trackId}: execution journal escapes track root`);
23360
23059
  return;
23361
23060
  }
23362
- if (!(inspection?.exists ?? existsSync8)(path)) {
23061
+ if (!(inspection?.exists ?? existsSync5)(path)) {
23363
23062
  errors.push(`${state.trackId}: missing execution journal ${relative7}`);
23364
23063
  return;
23365
23064
  }
@@ -23382,6 +23081,7 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23382
23081
  if (!EXECUTION_APPROVAL_MODES.includes(journal.approvalMode ?? "governed")) {
23383
23082
  errors.push(`${state.trackId}: invalid execution approval mode`);
23384
23083
  }
23084
+ if (journal.approvalPolicyVersion != null && ![1, APPROVAL_POLICY_VERSION].includes(journal.approvalPolicyVersion)) errors.push(`${state.trackId}: unsupported approvalPolicyVersion`);
23385
23085
  if (!Number.isInteger(journal.maxWorkers) || journal.maxWorkers < 1 || journal.maxWorkers > 32) errors.push(`${state.trackId}: invalid maxWorkers`);
23386
23086
  const requireCurrentGraph = operation?.action === "implement" || ["ready_for_review", "completed", "archived"].includes(state.status);
23387
23087
  if (graph && requireCurrentGraph && (journal.graphDigest !== graph.digest || journal.planRevision !== graph.planRevision)) {
@@ -23430,7 +23130,7 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23430
23130
  errors.push(`${state.trackId}: integrated execution node ${id2} lacks merge commit evidence`);
23431
23131
  }
23432
23132
  if (node.kind === "manual-verification" && node.status === "completed" && !node.approval) {
23433
- errors.push(`${state.trackId}: completed manual verification ${id2} lacks human approval`);
23133
+ errors.push(`${state.trackId}: completed manual verification ${id2} lacks verification authorization`);
23434
23134
  }
23435
23135
  if (node.kind === "phase" && node.status === "completed") {
23436
23136
  const incompleteTasks = Object.values(journal.nodes).filter(
@@ -23450,11 +23150,11 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23450
23150
  }
23451
23151
  if (operation?.action === "implement" && journal.status !== "in_progress") errors.push(`${state.trackId}: active implement operation requires an in-progress journal`);
23452
23152
  if (operation?.action === "implement") {
23453
- if (operation.executionId !== journal.executionId || operation.graphDigest !== journal.graphDigest || operation.planRevision !== journal.planRevision || String(operation.approvalMode ?? "governed") !== String(journal.approvalMode ?? "governed")) {
23153
+ if (operation.executionId !== journal.executionId || operation.graphDigest !== journal.graphDigest || operation.planRevision !== journal.planRevision || (operation.approvalPolicyVersion ?? 1) !== (journal.approvalPolicyVersion ?? 1) || String(operation.approvalMode ?? "governed") !== String(journal.approvalMode ?? "governed")) {
23454
23154
  errors.push(`${state.trackId}: implement operation does not match its execution journal`);
23455
23155
  }
23456
23156
  } else if (state.lastExecution) {
23457
- 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")) {
23157
+ if (state.lastExecution.executionId !== journal.executionId || state.lastExecution.graphDigest !== journal.graphDigest || state.lastExecution.planRevision !== journal.planRevision || state.lastExecution.headCommit !== journal.headCommit || (state.lastExecution.approvalPolicyVersion ?? 1) !== (journal.approvalPolicyVersion ?? 1) || String(state.lastExecution.approvalMode ?? "governed") !== String(journal.approvalMode ?? "governed")) {
23458
23158
  errors.push(`${state.trackId}: lastExecution does not match its execution journal`);
23459
23159
  }
23460
23160
  }
@@ -23469,16 +23169,575 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23469
23169
  }
23470
23170
  }
23471
23171
 
23172
+ // src/domain/next-step.ts
23173
+ var nextStepSchema = external_exports.strictObject({
23174
+ action: external_exports.enum(["invoke_skill", "await_approval", "blocked"]),
23175
+ plugin: external_exports.literal("cadre"),
23176
+ skill: external_exports.enum(["implement", "review"]).nullable(),
23177
+ projectRoot: external_exports.string(),
23178
+ trackId: external_exports.string(),
23179
+ executionId: external_exports.string().nullable(),
23180
+ prerequisite: external_exports.enum(["implementation_bookkeeping_commit", "review_bookkeeping_commit"]).nullable(),
23181
+ reason: external_exports.string()
23182
+ });
23183
+ function deriveNextStep(projectRoot, state, readiness = {}) {
23184
+ if (!state || ["completed", "archived"].includes(state.status)) return null;
23185
+ const active = state.operation?.action === "implement";
23186
+ const reference = active ? state.operation : state.lastExecution;
23187
+ const step = (action, skill, reason, prerequisite = null) => ({
23188
+ action,
23189
+ plugin: "cadre",
23190
+ skill,
23191
+ projectRoot,
23192
+ trackId: state.trackId,
23193
+ executionId: reference?.executionId ?? null,
23194
+ prerequisite,
23195
+ reason
23196
+ });
23197
+ const blocked = (reason) => step("blocked", null, reason);
23198
+ try {
23199
+ const mode = resolveApprovalMode(reference, active ? void 0 : state.approvalModeMigration);
23200
+ if (mode !== "autonomous" && !state.autonomousReview) return null;
23201
+ if (readiness.errors?.length) return blocked(`Resolve validation errors: ${readiness.errors.join("; ")}`);
23202
+ if (readiness.upgradeRequired) return blocked("Complete the approved runtime/template refresh before continuing.");
23203
+ if (readiness.staleMemory) return blocked("Reassess stale track or dependency guidance before continuing.");
23204
+ if (mode !== "autonomous" || !state.autonomousReview) return blocked("Autonomous routing requires matching persisted mode and loop authority.");
23205
+ const loop = requireReviewProgress(state.autonomousReview);
23206
+ if (loop.specCommit !== state.commits?.spec) return blocked("Autonomous scope changed; obtain explicit authority through refresh/revise.");
23207
+ if (state.operation?.action === "review") {
23208
+ return step("invoke_skill", "review", "Reconcile the journaled review promotion and commits before starting another execution.");
23209
+ }
23210
+ if (state.operation && !active) return blocked(`Finish the pending ${state.operation.action} operation first.`);
23211
+ if (active && state.status === "in_progress" && loop.checkpoint === "implementing") {
23212
+ return step("invoke_skill", "implement", "Resume the existing execution; do not create a duplicate.");
23213
+ }
23214
+ if (!state.operation && state.status === "ready_for_review") {
23215
+ if (loop.checkpoint === "reviewing") {
23216
+ return step("invoke_skill", "review", "Review the complete accumulated implementation in the same task.", "implementation_bookkeeping_commit");
23217
+ }
23218
+ if (loop.checkpoint === "awaiting_approval") {
23219
+ requireCleanAutonomousReview(loop, state.lastExecution ?? {}, []);
23220
+ return step("await_approval", "review", "Revalidate completion evidence with review_complete prepare and obtain explicit approval of its exact proposal.");
23221
+ }
23222
+ }
23223
+ if (!state.operation && state.status === "in_progress" && loop.checkpoint === "remediating") {
23224
+ return step("invoke_skill", "implement", "Start a new execution for the approved remediation graph, preserving prior executions.", "review_bookkeeping_commit");
23225
+ }
23226
+ return blocked("Reconcile the Autonomous checkpoint, lifecycle, and operation before continuing.");
23227
+ } catch (error51) {
23228
+ return blocked(error51 instanceof Error ? error51.message : String(error51));
23229
+ }
23230
+ }
23231
+
23232
+ // src/domain/context.ts
23233
+ import { existsSync as existsSync6, readdirSync as readdirSync4 } from "node:fs";
23234
+ import { join as join5 } from "node:path";
23235
+
23236
+ // src/domain/markdown-context.ts
23237
+ function markdownHeadings(body) {
23238
+ const headings = [];
23239
+ let fence = null;
23240
+ let offset = 0, ambiguous = false;
23241
+ for (const line of body.split(/(?<=\n)/)) {
23242
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)/.exec(line);
23243
+ if (marker) {
23244
+ if (!fence) fence = { character: marker[1][0], length: marker[1].length };
23245
+ else if (marker[1][0] === fence.character && marker[1].length >= fence.length && !marker[2].trim()) fence = null;
23246
+ } else if (!fence) {
23247
+ const heading = /^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*\r?\n?$/.exec(line);
23248
+ if (heading) headings.push({ level: heading[1].length, title: heading[2], offset });
23249
+ if (/^ {0,3}(?:=+|-+)[ \t]*$/.test(line.trimEnd()) || /^\s*<(?!\!--)/.test(line) || /^ {4,}#{1,6}\s/.test(line)) ambiguous = true;
23250
+ }
23251
+ offset += line.length;
23252
+ }
23253
+ return { headings, ambiguous: ambiguous || fence !== null };
23254
+ }
23255
+
23256
+ // src/domain/context.ts
23257
+ var id = external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
23258
+ var contextInputSchema = external_exports.strictObject({
23259
+ projectRoot: external_exports.string().min(1),
23260
+ trackId: id,
23261
+ executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/).optional(),
23262
+ nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/).optional(),
23263
+ maxBytes: external_exports.number().int().min(4096).max(65536).default(16384),
23264
+ cursor: external_exports.string().max(1024).optional(),
23265
+ knownSources: external_exports.array(external_exports.strictObject({
23266
+ path: external_exports.string(),
23267
+ sha256: external_exports.string().regex(/^[0-9a-f]{64}$/),
23268
+ section: external_exports.string(),
23269
+ contentHash: external_exports.string().regex(/^[0-9a-f]{64}$/)
23270
+ })).max(256).default([])
23271
+ });
23272
+ var cursorSchema = external_exports.strictObject({ snapshot: external_exports.string().regex(/^[0-9a-f]{64}$/), source: external_exports.number().int().nonnegative(), offset: external_exports.number().int().nonnegative() });
23273
+ function learningSections(body, phaseIds) {
23274
+ if (!phaseIds || !seedSection(body)) return [{ section: "full learning (conservative)", content: body }];
23275
+ const parsed = markdownHeadings(body), headings = parsed.headings.filter((heading) => heading.level === 2);
23276
+ const matches = headings.filter((heading) => /^Phase \d+: .+$/.test(heading.title));
23277
+ const phaseId = (heading) => `P${/^Phase (\d+):/.exec(heading.title)[1]}`;
23278
+ const present = new Set(matches.map(phaseId));
23279
+ if (parsed.ambiguous || present.size !== matches.length || [...phaseIds].some((phase) => !present.has(phase)) || headings.some((heading) => heading.title !== "Pattern Seed" && !/^Phase \d+: .+$/.test(heading.title))) {
23280
+ return [{ section: "full learning (ambiguous or missing phase context)", content: body }];
23281
+ }
23282
+ const selected = [{ section: "Pattern Seed and general instructions", content: body.slice(0, matches[0]?.offset ?? body.length) }];
23283
+ matches.forEach((match, index) => {
23284
+ if (phaseIds.has(phaseId(match))) selected.push({ section: phaseId(match), content: body.slice(match.offset, matches[index + 1]?.offset ?? body.length) });
23285
+ });
23286
+ return selected;
23287
+ }
23288
+ function collectContext(input) {
23289
+ const root = safeProjectRoot(input.projectRoot), sources = [], errors = [], staleMemory = [];
23290
+ const inputHashes = /* @__PURE__ */ new Map();
23291
+ const read = (path) => {
23292
+ const body = readSafeArtifact(root, path);
23293
+ inputHashes.set(path, contentHash(body));
23294
+ return body;
23295
+ };
23296
+ const add = (path, reason, section = "full") => {
23297
+ const content = read(path);
23298
+ sources.push({ path, sha256: contentHash(content), reason, section, format: "source", content });
23299
+ return content;
23300
+ };
23301
+ for (const path of ["workflow.md", "product.md", "guidelines.md", "tech-stack.md", "patterns/index.md"]) {
23302
+ add(`.cadre/${path}`, "required project instructions and applicability catalog");
23303
+ }
23304
+ const guides = join5(root, ".cadre/styleguides");
23305
+ if (existsSync6(guides)) for (const file2 of readdirSync4(guides).filter((file3) => /^[a-z0-9-]+\.md$/.test(file3)).sort()) {
23306
+ add(`.cadre/styleguides/${file2}`, "project styleguide; retain until applicability is established");
23307
+ }
23308
+ const project = JSON.parse(read(".cadre/project.json"));
23309
+ const locate = (trackId) => {
23310
+ id.parse(trackId);
23311
+ const active = `.cadre/tracks/${trackId}`, archived = `.cadre/archive/${trackId}`;
23312
+ if (existsSync6(join5(root, active, "state.json")) && existsSync6(join5(root, archived, "state.json"))) throw new Error(`duplicate track ${trackId}`);
23313
+ return existsSync6(join5(root, active, "state.json")) ? active : archived;
23314
+ };
23315
+ const trackPath = locate(input.trackId);
23316
+ const stateBody = read(`${trackPath}/state.json`);
23317
+ const state = JSON.parse(stateBody);
23318
+ errors.push(...inspectExecutionBindings(join5(root, trackPath), state));
23319
+ add(`${trackPath}/spec.md`, "complete approved scope and acceptance criteria");
23320
+ const planBody = add(`${trackPath}/plan.md`, "complete plan, including task descriptions and verification requirements");
23321
+ const graph = parsePlanContent(planBody, `${trackPath}/plan.md`, errors);
23322
+ validatePlanGraph(`${trackPath}/plan.md`, graph, state.status, errors);
23323
+ let phases = null;
23324
+ if (input.nodeId) {
23325
+ const phase = graph.phases.find((phase2) => phase2.id === input.nodeId || phase2.tasks.some((task) => task.id === input.nodeId));
23326
+ if (!phase) throw new Error(`unknown plan node ${input.nodeId}`);
23327
+ phases = /* @__PURE__ */ new Set();
23328
+ const visit = (phaseId) => {
23329
+ if (phases.has(phaseId)) return;
23330
+ phases.add(phaseId);
23331
+ const parent = graph.phases.find((phase2) => phase2.id === phaseId);
23332
+ if (!parent) throw new Error(`unknown dependency phase ${phaseId}`);
23333
+ parent.dependencies.forEach(visit);
23334
+ };
23335
+ visit(phase.id);
23336
+ }
23337
+ const patternPaths = /* @__PURE__ */ new Set();
23338
+ let uncertainPatterns = false;
23339
+ const addLearning = (path, trackId, historical, selected, plan) => {
23340
+ const body = read(path);
23341
+ const inspected = inspectMemory({
23342
+ trackId,
23343
+ path,
23344
+ body,
23345
+ graph: plan,
23346
+ required: ["v3", "v4"].includes(project.templateSetVersion ?? ""),
23347
+ historical,
23348
+ readPattern: (path2) => read(`.cadre/${path2}`)
23349
+ });
23350
+ errors.push(...inspected.errors);
23351
+ staleMemory.push(...inspected.stale);
23352
+ if (!inspected.metadata) uncertainPatterns = true;
23353
+ if (!historical) for (const pattern of inspected.metadata?.patterns ?? []) patternPaths.add(pattern.path);
23354
+ for (const section of learningSections(body, selected)) sources.push({
23355
+ path,
23356
+ sha256: contentHash(body),
23357
+ reason: "declared dependency learning and current phase decisions",
23358
+ format: "source",
23359
+ ...section
23360
+ });
23361
+ };
23362
+ addLearning(`${trackPath}/learning.md`, input.trackId, ["completed", "archived"].includes(state.status), phases, graph);
23363
+ const visited = /* @__PURE__ */ new Set([input.trackId]);
23364
+ const visitDependency = (trackId) => {
23365
+ if (visited.has(trackId)) return;
23366
+ visited.add(trackId);
23367
+ const base = locate(trackId);
23368
+ const dependency = JSON.parse(read(`${base}/state.json`));
23369
+ add(`${base}/spec.md`, "declared dependency contract");
23370
+ const plan = parsePlanContent(read(`${base}/plan.md`), `${base}/plan.md`);
23371
+ addLearning(`${base}/learning.md`, trackId, ["completed", "archived"].includes(dependency.status), null, plan);
23372
+ (dependency.dependencies ?? []).forEach(visitDependency);
23373
+ };
23374
+ (state.dependencies ?? []).forEach(visitDependency);
23375
+ if (uncertainPatterns) for (const path of readdirSync4(join5(root, ".cadre/patterns")).filter((path2) => /^[a-z0-9-]+\.md$/.test(path2) && path2 !== "index.md")) {
23376
+ patternPaths.add(`patterns/${path}`);
23377
+ }
23378
+ for (const path of [...patternPaths].sort()) {
23379
+ try {
23380
+ add(`.cadre/${path}`, uncertainPatterns ? "full pattern fallback: applicability metadata unavailable" : "explicit seed reference");
23381
+ } catch (error51) {
23382
+ errors.push(`${path}: ${error51 instanceof Error ? error51.message : String(error51)}`);
23383
+ }
23384
+ }
23385
+ const executionId2 = contextInputSchema.shape.executionId.parse(input.executionId ?? state.operation?.executionId ?? state.lastExecution?.executionId);
23386
+ if (executionId2) {
23387
+ const path = `${trackPath}/executions/execution-${executionId2}.json`, body = read(path);
23388
+ const journal = JSON.parse(body);
23389
+ if (journal.trackId !== input.trackId || journal.executionId !== executionId2) throw new Error("execution identity mismatch");
23390
+ const differentGraph = journal.graphDigest !== graph.digest || journal.planRevision !== graph.planRevision;
23391
+ const historical = differentGraph && ["planned", "in_progress"].includes(state.status) && journal.status === "completed" && state.lastExecution?.executionId === executionId2 && state.lastExecution.journal === `executions/execution-${executionId2}.json` && state.lastExecution.graphDigest === journal.graphDigest && state.lastExecution.planRevision === journal.planRevision && state.lastExecution.headCommit === journal.headCommit;
23392
+ if (differentGraph && !historical) errors.push("execution handoffs belong to a different plan graph; reconcile before use");
23393
+ for (const node of Object.values(journal.nodes)) {
23394
+ if (phases && !phases.has(node.phaseId)) continue;
23395
+ const handoff = node.handoff === void 0 ? null : handoffSchema.parse(node.handoff);
23396
+ if (!handoff && node.id !== input.nodeId) continue;
23397
+ const content = JSON.stringify({
23398
+ nodeId: node.id,
23399
+ handoff,
23400
+ ...historical ? { historical: true, planRevision: journal.planRevision, graphDigest: journal.graphDigest } : {},
23401
+ note: (historical ? "Historical execution; reassess for the current plan. " : "") + (handoff ? "Persisted evidence, not authorization" : "not recorded"),
23402
+ sources: handoff?.sources.map((reference) => ({ ...reference, freshness: sourceFreshness(root, reference, read) })) ?? []
23403
+ });
23404
+ sources.push({
23405
+ path,
23406
+ sha256: contentHash(body),
23407
+ section: node.id,
23408
+ reason: historical ? "historical handoff from retained completed execution; not current execution state" : "persisted handoff; reconcile journal/Git before resuming",
23409
+ format: "handoff",
23410
+ content
23411
+ });
23412
+ }
23413
+ }
23414
+ const identity = {
23415
+ projectRoot: root,
23416
+ trackId: input.trackId,
23417
+ executionId: executionId2 ?? null,
23418
+ nodeId: input.nodeId ?? null,
23419
+ stateHash: contentHash(stateBody),
23420
+ inputs: [...inputHashes].sort(),
23421
+ sources,
23422
+ errors,
23423
+ staleMemory
23424
+ };
23425
+ return { sources, errors, staleMemory, snapshot: contentHash(JSON.stringify(identity)) };
23426
+ }
23427
+ function readContext(raw) {
23428
+ const input = contextInputSchema.parse(raw);
23429
+ return inspectOnce(() => {
23430
+ const collected = collectContext(input), { errors, staleMemory } = collected;
23431
+ const sources = collected.sources.map((source2) => {
23432
+ const hash6 = contentHash(source2.content);
23433
+ const reused = input.knownSources.some((known) => known.path === source2.path && known.sha256 === source2.sha256 && known.section === source2.section && known.contentHash === hash6);
23434
+ return { ...source2, contentHash: hash6, reused, content: reused ? "" : source2.content };
23435
+ });
23436
+ const snapshot = contentHash(JSON.stringify({ sources: collected.snapshot, knownSources: input.knownSources }));
23437
+ const cursor = input.cursor ? cursorSchema.parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8"))) : { snapshot, source: 0, offset: 0 };
23438
+ if (cursor.snapshot !== snapshot) throw new CadreError("CONTEXT_SNAPSHOT_CHANGED", "Required sources changed; restart context_read without a cursor.");
23439
+ if (cursor.source >= sources.length || cursor.offset > sources[cursor.source].content.length) throw new Error("invalid context cursor position");
23440
+ let source = cursor.source, offset = cursor.offset;
23441
+ const page = { snapshot, complete: false, contextReady: false, nextCursor: null, totalSources: sources.length, excerpts: [], errors, staleMemory };
23442
+ const encode3 = () => Buffer.from(JSON.stringify({ snapshot, source, offset })).toString("base64url");
23443
+ while (source < sources.length) {
23444
+ const item = sources[source];
23445
+ let low = 0, high = item.content.length - offset, take = 0;
23446
+ const excerpt = (length) => ({
23447
+ ...item,
23448
+ content: item.content.slice(offset, offset + length),
23449
+ offset,
23450
+ endOffset: offset + length,
23451
+ sourceComplete: offset + length === item.content.length
23452
+ });
23453
+ while (low <= high) {
23454
+ const mid = Math.floor((low + high) / 2);
23455
+ const bytes = Buffer.byteLength(JSON.stringify({ ...page, excerpts: [...page.excerpts, excerpt(mid)], nextCursor: encode3() }));
23456
+ if (bytes <= input.maxBytes - 64) {
23457
+ take = mid;
23458
+ low = mid + 1;
23459
+ } else high = mid - 1;
23460
+ }
23461
+ if (take && /[\uD800-\uDBFF]/.test(item.content[offset + take - 1])) take--;
23462
+ if (!take && item.content.length > offset) break;
23463
+ page.excerpts.push(excerpt(take));
23464
+ offset += take;
23465
+ if (offset === item.content.length) {
23466
+ source++;
23467
+ offset = 0;
23468
+ } else break;
23469
+ }
23470
+ if (!page.excerpts.length) throw new CadreError("CONTEXT_PAGE_TOO_SMALL", "Context findings or metadata exceed the page budget; increase maxBytes and inspect diagnostics.");
23471
+ page.complete = source === sources.length;
23472
+ page.contextReady = page.complete && !errors.length && !staleMemory.length;
23473
+ page.nextCursor = page.complete ? null : encode3();
23474
+ return page;
23475
+ });
23476
+ }
23477
+
23478
+ // src/domain/staged-memory.ts
23479
+ import { existsSync as existsSync8, readdirSync as readdirSync6 } from "node:fs";
23480
+ import { dirname as dirname2, join as join7 } from "node:path";
23481
+
23482
+ // src/domain/staging.ts
23483
+ import {
23484
+ existsSync as existsSync7,
23485
+ lstatSync as lstatSync4,
23486
+ mkdirSync as mkdirSync2,
23487
+ readFileSync as readFileSync4,
23488
+ readdirSync as readdirSync5,
23489
+ renameSync as renameSync2,
23490
+ rmdirSync,
23491
+ unlinkSync as unlinkSync2,
23492
+ writeFileSync as writeFileSync2
23493
+ } from "node:fs";
23494
+ import { isAbsolute, join as join6, relative, resolve as resolve6, sep } from "node:path";
23495
+ var CANDIDATE_STAGE_DIRECTORY = ".cadre/stage";
23496
+ var MAX_CANDIDATE_FILE_BYTES = 1024 * 1024;
23497
+ var MAX_CANDIDATE_TOTAL_BYTES = 8 * 1024 * 1024;
23498
+ var CANDIDATE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
23499
+ function candidateArtifactPath(candidateId, path) {
23500
+ const normalized = normalizeCandidatePath(path);
23501
+ const owner = candidateId.match(/^(?:track|revise|review|revert)-([a-z0-9-]+)$/)?.[1];
23502
+ return owner && !/^(?:tracks|archive|patterns|refreshes)\//.test(normalized) ? `tracks/${owner}/${normalized}` : normalized;
23503
+ }
23504
+ function normalizeCandidateId(candidateId) {
23505
+ if (!CANDIDATE_ID.test(candidateId)) {
23506
+ throw new Error("candidateId must contain lowercase letters, digits, and single hyphens");
23507
+ }
23508
+ return candidateId;
23509
+ }
23510
+ function normalizeCandidatePath(input) {
23511
+ if (!input || isAbsolute(input) || input.includes("\\")) {
23512
+ throw new Error(`Candidate artifact path must be a portable relative path: ${input}`);
23513
+ }
23514
+ const normalized = input.replace(/^\.\//, "");
23515
+ if (normalized === ".cadre" || normalized.startsWith(".cadre/")) {
23516
+ throw new Error(`Candidate paths are relative to the candidate stage, without a .cadre/ prefix: ${input}. Use state.json for the owned track or tracks/<id>/state.json for nested updates.`);
23517
+ }
23518
+ if (!normalized || normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
23519
+ throw new Error(`Candidate artifact path is not canonical: ${input}`);
23520
+ }
23521
+ return normalized;
23522
+ }
23523
+ function candidateStageRoot(projectRootInput, candidateIdInput) {
23524
+ const projectRoot = safeProjectRoot(projectRootInput);
23525
+ const candidateId = normalizeCandidateId(candidateIdInput);
23526
+ const cadreRoot2 = join6(projectRoot, ".cadre");
23527
+ if (!existsSync7(cadreRoot2) || !lstatSync4(cadreRoot2).isDirectory() || lstatSync4(cadreRoot2).isSymbolicLink()) {
23528
+ throw new Error(`Cadre candidate root is unavailable or unsafe: ${cadreRoot2}`);
23529
+ }
23530
+ const gitignorePath = join6(cadreRoot2, ".gitignore");
23531
+ if (!existsSync7(gitignorePath) || !lstatSync4(gitignorePath).isFile() || lstatSync4(gitignorePath).isSymbolicLink()) {
23532
+ throw new Error(`Cadre candidate stage requires a regular ${gitignorePath}`);
23533
+ }
23534
+ if (!readFileSync4(gitignorePath, "utf8").split(/\r?\n/).includes("/stage/")) {
23535
+ throw new Error(`${gitignorePath} must ignore /stage/ before candidate files are written`);
23536
+ }
23537
+ const stageParent = join6(projectRoot, CANDIDATE_STAGE_DIRECTORY);
23538
+ if (existsSync7(stageParent) && lstatSync4(stageParent).isSymbolicLink()) {
23539
+ throw new Error(`Refusing candidate stage through symbolic link: ${stageParent}`);
23540
+ }
23541
+ return join6(stageParent, candidateId);
23542
+ }
23543
+ function prepareCandidateStage(projectRootInput, candidateIdInput, expectedFiles) {
23544
+ const projectRoot = safeProjectRoot(projectRootInput);
23545
+ const candidateId = normalizeCandidateId(candidateIdInput);
23546
+ const normalizedExpected = expectedFiles?.map(normalizeCandidatePath);
23547
+ if (normalizedExpected && new Set(normalizedExpected).size !== normalizedExpected.length) {
23548
+ throw new Error("Candidate expectedFiles contains duplicate paths");
23549
+ }
23550
+ const cadreRoot2 = join6(projectRoot, ".cadre");
23551
+ if (existsSync7(cadreRoot2)) {
23552
+ const stat = lstatSync4(cadreRoot2);
23553
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Unsafe Cadre directory: ${cadreRoot2}`);
23554
+ } else mkdirSync2(cadreRoot2);
23555
+ const gitignorePath = join6(cadreRoot2, ".gitignore");
23556
+ let content = "# Cadre-managed temporary execution worktrees\n/.worktrees/\n\n# Disposable Wisp output\n/wisps/\n";
23557
+ if (existsSync7(gitignorePath)) {
23558
+ const stat = lstatSync4(gitignorePath);
23559
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Unsafe Cadre ignore file: ${gitignorePath}`);
23560
+ content = readFileSync4(gitignorePath, "utf8");
23561
+ }
23562
+ if (!content.split(/\r?\n/).includes("/stage/")) {
23563
+ content = `${content.endsWith("\n") ? content : `${content}
23564
+ `}
23565
+ # Unapproved candidate artifacts
23566
+ /stage/
23567
+ `;
23568
+ const temporaryPath = `${gitignorePath}.${process.pid}.tmp`;
23569
+ try {
23570
+ writeFileSync2(temporaryPath, content, { flag: "wx" });
23571
+ renameSync2(temporaryPath, gitignorePath);
23572
+ } finally {
23573
+ if (existsSync7(temporaryPath)) unlinkSync2(temporaryPath);
23574
+ }
23575
+ }
23576
+ const stagePath = join6(cadreRoot2, "stage", candidateId);
23577
+ mkdirSync2(stagePath, { recursive: true });
23578
+ candidateStageRoot(projectRoot, candidateId);
23579
+ const retainedFiles = listCandidatePaths(projectRoot, candidateId);
23580
+ if (normalizedExpected === void 0) return { stagePath, gitignorePath, retainedFiles, removedFiles: [] };
23581
+ const expected = new Set(normalizedExpected);
23582
+ const removedFiles = retainedFiles.filter((path) => !expected.has(path));
23583
+ for (const path of removedFiles) unlinkSync2(join6(stagePath, path));
23584
+ const pruneEmptyDirectories = (directory) => {
23585
+ for (const entry of readdirSync5(directory, { withFileTypes: true })) {
23586
+ if (entry.isDirectory()) pruneEmptyDirectories(join6(directory, entry.name));
23587
+ }
23588
+ if (directory !== stagePath && readdirSync5(directory).length === 0) rmdirSync(directory);
23589
+ };
23590
+ pruneEmptyDirectories(stagePath);
23591
+ return {
23592
+ stagePath,
23593
+ gitignorePath,
23594
+ retainedFiles: retainedFiles.filter((path) => expected.has(path)),
23595
+ removedFiles
23596
+ };
23597
+ }
23598
+ function assertRegularPath(root, target) {
23599
+ const relation = relative(root, target);
23600
+ if (relation.startsWith("..") || isAbsolute(relation)) {
23601
+ throw new Error(`Candidate artifact escapes its stage: ${target}`);
23602
+ }
23603
+ let current2 = target;
23604
+ while (current2 !== root) {
23605
+ if (!existsSync7(current2)) throw new Error(`Missing candidate artifact: ${target}`);
23606
+ const stat = lstatSync4(current2);
23607
+ if (stat.isSymbolicLink()) throw new Error(`Refusing candidate artifact through symbolic link: ${current2}`);
23608
+ current2 = resolve6(current2, "..");
23609
+ }
23610
+ if (!existsSync7(root)) throw new Error(`Missing candidate stage: ${root}`);
23611
+ const rootStat = lstatSync4(root);
23612
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
23613
+ throw new Error(`Candidate stage is not a regular directory: ${root}`);
23614
+ }
23615
+ const targetStat = lstatSync4(target);
23616
+ if (!targetStat.isFile()) throw new Error(`Candidate artifact is not a regular file: ${target}`);
23617
+ if (targetStat.size > MAX_CANDIDATE_FILE_BYTES) {
23618
+ throw new Error(`Candidate artifact exceeds ${MAX_CANDIDATE_FILE_BYTES} bytes: ${target}`);
23619
+ }
23620
+ }
23621
+ function readCandidateFiles(projectRootInput, candidateIdInput, paths) {
23622
+ const root = candidateStageRoot(projectRootInput, candidateIdInput);
23623
+ const seen = /* @__PURE__ */ new Set();
23624
+ let totalBytes = 0;
23625
+ return paths.map((input) => {
23626
+ const path = normalizeCandidatePath(input);
23627
+ if (seen.has(path)) throw new Error(`Duplicate candidate artifact: ${path}`);
23628
+ seen.add(path);
23629
+ const absolutePath = resolve6(root, path);
23630
+ assertRegularPath(root, absolutePath);
23631
+ const content = readFileSync4(absolutePath, "utf8");
23632
+ totalBytes += Buffer.byteLength(content, "utf8");
23633
+ if (totalBytes > MAX_CANDIDATE_TOTAL_BYTES) {
23634
+ throw new Error(`Candidate stage exceeds ${MAX_CANDIDATE_TOTAL_BYTES} bytes`);
23635
+ }
23636
+ return { path, absolutePath, content };
23637
+ });
23638
+ }
23639
+ function listCandidatePaths(projectRootInput, candidateIdInput) {
23640
+ const root = candidateStageRoot(projectRootInput, candidateIdInput);
23641
+ if (!existsSync7(root)) throw new Error(`Missing candidate stage: ${root}`);
23642
+ const rootStat = lstatSync4(root);
23643
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
23644
+ throw new Error(`Candidate stage is not a regular directory: ${root}`);
23645
+ }
23646
+ const walk2 = (directory) => readdirSync5(directory, { withFileTypes: true }).flatMap((entry) => {
23647
+ const target = join6(directory, entry.name);
23648
+ const stat = lstatSync4(target);
23649
+ if (stat.isSymbolicLink()) throw new Error(`Refusing symbolic link in candidate stage: ${target}`);
23650
+ if (stat.isDirectory()) return walk2(target);
23651
+ if (!stat.isFile()) throw new Error(`Candidate stage contains a non-file entry: ${target}`);
23652
+ return [relative(root, target).split(sep).join("/")];
23653
+ });
23654
+ return walk2(root).sort();
23655
+ }
23656
+
23657
+ // src/domain/staged-memory.ts
23658
+ function inspectStagedMemory(projectRoot, candidateId, files) {
23659
+ const originalPaths = new Map(files.map((file2) => [candidateArtifactPath(candidateId, file2.path), file2.path]));
23660
+ if (originalPaths.size !== files.length) throw new Error("Candidate paths alias the same canonical artifact; use one path per artifact");
23661
+ files = files.map((file2) => ({ ...file2, path: candidateArtifactPath(candidateId, file2.path) }));
23662
+ const overlay = new Map(files.map((file2) => [file2.path, file2.content]));
23663
+ const inputs = /* @__PURE__ */ new Map();
23664
+ const read = (path, fingerprint = true) => {
23665
+ const staged = overlay.get(path);
23666
+ if (staged !== void 0) return staged;
23667
+ const body = readSafeArtifact(projectRoot, `.cadre/${path}`);
23668
+ if (fingerprint) inputs.set(path, contentHash(body));
23669
+ return body;
23670
+ };
23671
+ const project = overlay.has("project.json") || existsSync8(join7(projectRoot, ".cadre/project.json")) ? JSON.parse(read("project.json", false)) : {};
23672
+ const learningPaths = new Set(files.filter((file2) => file2.path.split("/").at(-1) === "learning.md").map((file2) => file2.path));
23673
+ for (const file2 of files.filter((file3) => file3.path.split("/").at(-1) === "plan.md")) {
23674
+ const parent = dirname2(file2.path);
23675
+ const seed = parent === "." ? "learning.md" : `${parent}/learning.md`;
23676
+ const owner = candidateId.replace(/^(?:track|revise|review|revert)-/, "");
23677
+ const canonicalSeed = parent === "." ? `tracks/${owner}/learning.md` : seed;
23678
+ if (overlay.has(seed)) learningPaths.add(seed);
23679
+ else if (existsSync8(join7(projectRoot, ".cadre", canonicalSeed))) {
23680
+ learningPaths.add(canonicalSeed);
23681
+ overlay.set(`${dirname2(canonicalSeed)}/plan.md`, file2.content);
23682
+ }
23683
+ }
23684
+ const changedPatterns = files.some((file2) => /^patterns\/.+\.md$/.test(file2.path));
23685
+ if (changedPatterns && existsSync8(join7(projectRoot, ".cadre/tracks"))) {
23686
+ for (const entry of readdirSync6(join7(projectRoot, ".cadre/tracks"), { withFileTypes: true })) {
23687
+ if (!entry.isDirectory() || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(entry.name)) continue;
23688
+ const path = `tracks/${entry.name}/learning.md`;
23689
+ if (existsSync8(join7(projectRoot, ".cadre", path))) learningPaths.add(path);
23690
+ }
23691
+ }
23692
+ const historicalPaths = [];
23693
+ const learning = [...learningPaths].sort().map((path) => {
23694
+ const parent = dirname2(path);
23695
+ const id2 = path.match(/(?:^|\/)tracks\/([a-z0-9-]+)\//)?.[1] ?? candidateId.replace(/^(?:track|revise|review|revert)-/, "");
23696
+ const canonicalParent = parent === "." ? `tracks/${id2}` : parent;
23697
+ let historical = path.startsWith("archive/");
23698
+ const statePath = `${canonicalParent}/state.json`;
23699
+ if (overlay.has(statePath) || existsSync8(join7(projectRoot, ".cadre", statePath))) {
23700
+ const state = JSON.parse(read(statePath, false));
23701
+ historical ||= ["completed", "archived"].includes(state.status ?? "");
23702
+ }
23703
+ const stagedPlan = parent === "." ? "plan.md" : `${parent}/plan.md`;
23704
+ const planPath = overlay.has(stagedPlan) ? stagedPlan : `${canonicalParent}/plan.md`;
23705
+ const graph = overlay.has(planPath) || existsSync8(join7(projectRoot, ".cadre", planPath)) ? parsePlanContent(read(planPath), planPath) : null;
23706
+ const reportedPath = originalPaths.get(path) ?? path;
23707
+ if (historical) historicalPaths.push(reportedPath);
23708
+ const inspected = inspectMemory({
23709
+ trackId: id2,
23710
+ path: reportedPath,
23711
+ body: read(path),
23712
+ graph,
23713
+ required: ["v3", "v4"].includes(project.templateSetVersion ?? ""),
23714
+ historical,
23715
+ readPattern: read
23716
+ });
23717
+ return {
23718
+ path: reportedPath,
23719
+ valid: inspected.errors.length === 0 && inspected.stale.length === 0,
23720
+ errors: inspected.errors,
23721
+ stale: inspected.stale
23722
+ };
23723
+ });
23724
+ return { learning, policy: { templateSetVersion: project.templateSetVersion ?? null, historicalPaths }, inputs: [...inputs].sort(([a], [b]) => a.localeCompare(b)).map(([path, sha2562]) => ({ path, sha256: sha2562 })) };
23725
+ }
23726
+
23727
+ // src/domain/staged-state.ts
23728
+ import { existsSync as existsSync10, readdirSync as readdirSync8 } from "node:fs";
23729
+ import { join as join9 } from "node:path";
23730
+
23472
23731
  // src/domain/state.ts
23473
23732
  import { createHash as createHash4 } from "node:crypto";
23474
23733
  import { existsSync as existsSync9, lstatSync as lstatSync5, readdirSync as readdirSync7, writeFileSync as writeFileSync3 } from "node:fs";
23475
23734
  import { isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve7 } from "node:path";
23476
23735
 
23477
23736
  // src/domain/version.ts
23478
- var CADRE_RUNTIME_VERSION = "3.7.1";
23479
- var LEGACY_RUNTIME_VERSIONS = ["3.7.0", "3.6.0", "3.5.1", "3.5.0", "3.4.0", "3.3.0"];
23480
- var TEMPLATE_SET_VERSION = "v3";
23481
- var LEGACY_TEMPLATE_SET_VERSIONS = ["v1", "v2"];
23737
+ var CADRE_RUNTIME_VERSION = "3.8.0";
23738
+ var LEGACY_RUNTIME_VERSIONS = ["3.7.1", "3.7.0", "3.6.0", "3.5.1", "3.5.0", "3.4.0", "3.3.0"];
23739
+ var TEMPLATE_SET_VERSION = "v4";
23740
+ var LEGACY_TEMPLATE_SET_VERSIONS = ["v1", "v2", "v3"];
23482
23741
 
23483
23742
  // src/domain/state.ts
23484
23743
  function collectCommitReferences(value, owner, references, commitContext = false) {
@@ -23541,6 +23800,8 @@ function validateOperation(operation, owner, errors, artifactRoot, artifactProgr
23541
23800
  if (!operation.expectedCommit) errors.push(`${owner}: operation expectedCommit is required`);
23542
23801
  if (!Array.isArray(operation.approvedArtifacts) || !operation.approvedArtifacts.length) {
23543
23802
  errors.push(`${owner}: operation approvedArtifacts must be a non-empty array`);
23803
+ } else if (operation.approvedArtifacts.some((path) => typeof path !== "string" || !path || isAbsolute2(path) || path.includes(".."))) {
23804
+ errors.push(`${owner}: operation approvedArtifacts must contain relative path strings; put path/hash objects in approvedArtifactHashes`);
23544
23805
  }
23545
23806
  if (!operation.approvedAt) errors.push(`${owner}: operation approvedAt is required`);
23546
23807
  if (operation.approvalDigest !== void 0 && !/^[0-9a-f]{64}$/.test(operation.approvalDigest)) {
@@ -23639,7 +23900,7 @@ function validateImplementOperation(state, owner, errors) {
23639
23900
  errors.push(`${owner}: implement journal path is invalid`);
23640
23901
  }
23641
23902
  if (!["parallel", "sequential"].includes(String(operation.mode ?? ""))) errors.push(`${owner}: implement mode is invalid`);
23642
- if (!["governed", "phase", "autonomous"].includes(String(operation.approvalMode ?? "governed"))) {
23903
+ if (!["governed", "phase", "track", "autonomous"].includes(String(operation.approvalMode ?? "governed"))) {
23643
23904
  errors.push(`${owner}: implement approvalMode is invalid`);
23644
23905
  }
23645
23906
  if (!/^[0-9a-f]{64}$/.test(String(operation.graphDigest ?? ""))) errors.push(`${owner}: implement graphDigest is invalid`);
@@ -23662,10 +23923,10 @@ function validateRevertOperation(state, owner, errors) {
23662
23923
  if (!operation.targetId || typeof operation.targetId !== "string") {
23663
23924
  errors.push(`${owner}: revert targetId is required`);
23664
23925
  }
23665
- if (!Array.isArray(operation.commits) || !operation.commits.length || operation.commits.some((commit) => !/^[0-9a-f]{7,40}$/.test(String(commit)))) {
23926
+ if (!Array.isArray(operation.commits) || !operation.commits.length || operation.commits.some((commit2) => !/^[0-9a-f]{7,40}$/.test(String(commit2)))) {
23666
23927
  errors.push(`${owner}: revert commits must be a non-empty array of Git commit SHAs`);
23667
23928
  }
23668
- if (!Array.isArray(operation.revertCommits) || operation.revertCommits.some((commit) => !/^[0-9a-f]{7,40}$/.test(String(commit)))) {
23929
+ if (!Array.isArray(operation.revertCommits) || operation.revertCommits.some((commit2) => !/^[0-9a-f]{7,40}$/.test(String(commit2)))) {
23669
23930
  errors.push(`${owner}: revert revertCommits must be an array of Git commit SHAs`);
23670
23931
  }
23671
23932
  }
@@ -23907,6 +24168,7 @@ function validateProjectSnapshot(projectRoot) {
23907
24168
  const state = states.get(track.id);
23908
24169
  collectCommitReferences(state, `${track.id}/state.json`, commitReferences);
23909
24170
  const trackRoot = join8(root, track.location);
24171
+ validateTrackApprovalPolicy(state, errors, warnings);
23910
24172
  if (state.schemaVersion !== 1) errors.push(`${track.id}: unsupported state schemaVersion`);
23911
24173
  if (!state.title || typeof state.title !== "string") errors.push(`${track.id}: title is required`);
23912
24174
  if (!TRACK_TYPES.has(track.type)) errors.push(`${track.id}: type must be feature or bug`);
@@ -23962,7 +24224,7 @@ function validateProjectSnapshot(projectRoot) {
23962
24224
  path: learningPath,
23963
24225
  body: readInspectionText(learningPath, "utf8"),
23964
24226
  graph: planGraph,
23965
- required: project.templateSetVersion === "v3" && !["drafting-spec", "drafting-plan"].includes(track.status),
24227
+ required: ["v3", "v4"].includes(project.templateSetVersion ?? "") && !["drafting-spec", "drafting-plan"].includes(track.status),
23966
24228
  historical: ["completed", "archived"].includes(track.status),
23967
24229
  readPattern: (path) => readSafeArtifact(projectRoot, `.cadre/${path}`)
23968
24230
  });
@@ -24093,6 +24355,13 @@ function validateStagedState(root, candidateId, files, planValidations = []) {
24093
24355
  const read = (path) => overlay.get(path) ?? readSafeArtifact(root, `.cadre/${path}`);
24094
24356
  const parents = /* @__PURE__ */ new Set();
24095
24357
  for (const file2 of files) {
24358
+ const loopMatch = canonical(file2.path).match(/^tracks\/([^/]+)\/reviews\/loop-\d+\.json$/);
24359
+ if (loopMatch && candidateId.startsWith("review-")) {
24360
+ const state = JSON.parse(readSafeArtifact(root, `.cadre/tracks/${loopMatch[1]}/state.json`));
24361
+ if (!state.autonomousReview || state.status !== "ready_for_review") throw new Error("Autonomous remediation requires a ready_for_review track and persisted authority");
24362
+ if (state.autonomousReview.specCommit !== state.commits?.spec) throw new Error("Autonomous scope changed; obtain explicit authorization before remediation");
24363
+ validateAutonomousRemediation(autonomousReviewSchema.parse(state.autonomousReview), JSON.parse(file2.content), state.lastExecution ?? {});
24364
+ }
24096
24365
  if (/(?:^|\/)revisions\//.test(file2.path) && !/(?:^|\/)revisions\/revision-[^/]+\.md$/.test(file2.path)) {
24097
24366
  throw new Error(`Invalid revision artifact ${file2.path}; use revisions/revision-<id>.md before approval`);
24098
24367
  }
@@ -24129,6 +24398,7 @@ function validateStagedState(root, candidateId, files, planValidations = []) {
24129
24398
  for (const key2 of overlay.keys()) if (key2.startsWith(`${parent}/executions/`)) paths.add(key2.slice(`${parent}/executions/`.length));
24130
24399
  const errors = [];
24131
24400
  validateTrackOperation(state, path, errors);
24401
+ validateTrackApprovalPolicy(state, errors);
24132
24402
  const key = (absolute) => absolute.slice(join9(root, ".cadre").length + 1);
24133
24403
  const plan = `${parent}/plan.md`;
24134
24404
  const graph = overlay.has(plan) || existsSync10(join9(root, ".cadre", plan)) ? parsePlanContent(read(plan), plan, errors) : null;
@@ -24201,6 +24471,9 @@ function summarizeTrackState(state) {
24201
24471
  } : null,
24202
24472
  lastExecution: state.lastExecution ?? null,
24203
24473
  commits: state.commits ?? null,
24474
+ approvalModeMigrationRequired: !["completed", "archived"].includes(state.status) && migrationRequired(operation?.action === "implement" ? operation : state.lastExecution, operation?.action === "implement" ? void 0 : state.approvalModeMigration),
24475
+ approvalModeMigration: state.approvalModeMigration ?? null,
24476
+ autonomousReview: state.autonomousReview ?? null,
24204
24477
  historyCount: Array.isArray(state.history) ? state.history.length : 0,
24205
24478
  reviewCycleCount: state.reviewCycles?.length ?? 0
24206
24479
  };
@@ -24226,11 +24499,11 @@ function trackSources(projectRoot, location) {
24226
24499
  }
24227
24500
  function fullProjectTracks(root, tracks, states, plans) {
24228
24501
  return tracks.map((track) => {
24229
- const state = states.get(track.id), executionId = state?.operation?.executionId ?? state?.lastExecution?.executionId;
24502
+ const state = states.get(track.id), executionId2 = state?.operation?.executionId ?? state?.lastExecution?.executionId;
24230
24503
  let execution = null, executionError = null;
24231
- if (typeof executionId === "string") {
24504
+ if (typeof executionId2 === "string") {
24232
24505
  try {
24233
- execution = readExecution(root, track.id, executionId);
24506
+ execution = readExecution(root, track.id, executionId2);
24234
24507
  } catch (error51) {
24235
24508
  executionError = String(error51);
24236
24509
  }
@@ -31691,7 +31964,7 @@ var Protocol = class {
31691
31964
  return;
31692
31965
  }
31693
31966
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
31694
- await new Promise((resolve14) => setTimeout(resolve14, pollInterval));
31967
+ await new Promise((resolve13) => setTimeout(resolve13, pollInterval));
31695
31968
  options?.signal?.throwIfAborted();
31696
31969
  }
31697
31970
  } catch (error51) {
@@ -31708,7 +31981,7 @@ var Protocol = class {
31708
31981
  */
31709
31982
  request(request, resultSchema, options) {
31710
31983
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
31711
- return new Promise((resolve14, reject) => {
31984
+ return new Promise((resolve13, reject) => {
31712
31985
  const earlyReject = (error51) => {
31713
31986
  reject(error51);
31714
31987
  };
@@ -31786,7 +32059,7 @@ var Protocol = class {
31786
32059
  if (!parseResult.success) {
31787
32060
  reject(parseResult.error);
31788
32061
  } else {
31789
- resolve14(parseResult.data);
32062
+ resolve13(parseResult.data);
31790
32063
  }
31791
32064
  } catch (error51) {
31792
32065
  reject(error51);
@@ -32047,12 +32320,12 @@ var Protocol = class {
32047
32320
  }
32048
32321
  } catch {
32049
32322
  }
32050
- return new Promise((resolve14, reject) => {
32323
+ return new Promise((resolve13, reject) => {
32051
32324
  if (signal.aborted) {
32052
32325
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
32053
32326
  return;
32054
32327
  }
32055
- const timeoutId = setTimeout(resolve14, interval);
32328
+ const timeoutId = setTimeout(resolve13, interval);
32056
32329
  signal.addEventListener("abort", () => {
32057
32330
  clearTimeout(timeoutId);
32058
32331
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -33143,7 +33416,7 @@ var McpServer = class {
33143
33416
  let task = createTaskResult.task;
33144
33417
  const pollInterval = task.pollInterval ?? 5e3;
33145
33418
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
33146
- await new Promise((resolve14) => setTimeout(resolve14, pollInterval));
33419
+ await new Promise((resolve13) => setTimeout(resolve13, pollInterval));
33147
33420
  const updatedTask = await extra.taskStore.getTask(taskId);
33148
33421
  if (!updatedTask) {
33149
33422
  throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
@@ -33807,12 +34080,12 @@ var StdioServerTransport = class {
33807
34080
  this.onclose?.();
33808
34081
  }
33809
34082
  send(message) {
33810
- return new Promise((resolve14) => {
34083
+ return new Promise((resolve13) => {
33811
34084
  const json3 = serializeMessage(message);
33812
34085
  if (this._stdout.write(json3)) {
33813
- resolve14();
34086
+ resolve13();
33814
34087
  } else {
33815
- this._stdout.once("drain", resolve14);
34088
+ this._stdout.once("drain", resolve13);
33816
34089
  }
33817
34090
  });
33818
34091
  }
@@ -33820,9 +34093,9 @@ var StdioServerTransport = class {
33820
34093
 
33821
34094
  // src/mcp/server.ts
33822
34095
  import { createHash as createHash9 } from "node:crypto";
33823
- import { existsSync as existsSync16, readFileSync as readFileSync9, readdirSync as readdirSync14 } from "node:fs";
33824
- import { join as join15, resolve as resolve13 } from "node:path";
33825
- import { pathToFileURL } from "node:url";
34096
+ import { existsSync as existsSync16, readFileSync as readFileSync9, readdirSync as readdirSync14, realpathSync as realpathSync3 } from "node:fs";
34097
+ import { join as join15 } from "node:path";
34098
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
33826
34099
 
33827
34100
  // src/domain/init.ts
33828
34101
  import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
@@ -34231,8 +34504,8 @@ function applyProjectInitCandidate(input, proposalDigest) {
34231
34504
  }
34232
34505
  return applyProjectInitAtRoot(materialized, proposal);
34233
34506
  }
34234
- function recordSetupCommit(projectRootInput, commit) {
34235
- if (!/^[0-9a-f]{7,40}$/.test(commit)) throw new Error("commit must be a hexadecimal Git commit SHA");
34507
+ function recordSetupCommit(projectRootInput, commit2) {
34508
+ if (!/^[0-9a-f]{7,40}$/.test(commit2)) throw new Error("commit must be a hexadecimal Git commit SHA");
34236
34509
  const root = safeProjectRoot(projectRootInput);
34237
34510
  const path = join11(root, ".cadre", "project.json");
34238
34511
  const project = JSON.parse(readFileSync6(path, "utf8"));
@@ -34250,15 +34523,15 @@ function recordSetupCommit(projectRootInput, commit) {
34250
34523
  if (hash3(readFileSync6(artifactPath, "utf8")) !== artifact2.sha256) {
34251
34524
  throw new Error(`Approved setup artifact changed before commit recording: ${artifact2.path}`);
34252
34525
  }
34253
- if (hash3(readGitFileAtCommit(root, commit, `.cadre/${artifact2.path}`)) !== artifact2.sha256) {
34526
+ if (hash3(readGitFileAtCommit(root, commit2, `.cadre/${artifact2.path}`)) !== artifact2.sha256) {
34254
34527
  throw new Error(`Setup commit does not contain the approved artifact: ${artifact2.path}`);
34255
34528
  }
34256
34529
  }
34257
34530
  project.setup.status = "completed";
34258
34531
  project.setup.checkpoint = "completed";
34259
- project.setup.commit = commit;
34532
+ project.setup.commit = commit2;
34260
34533
  project.setup.operation = null;
34261
- project.history = [...project.history ?? [], { action: "create", commit }];
34534
+ project.history = [...project.history ?? [], { action: "create", commit: commit2 }];
34262
34535
  writeFileSync4(path, `${JSON.stringify(project, null, 2)}
34263
34536
  `);
34264
34537
  return path;
@@ -34309,9 +34582,9 @@ function assertRepository(projectRoot) {
34309
34582
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
34310
34583
  return root;
34311
34584
  }
34312
- function assertIds(trackId, executionId, nodeId, phaseId) {
34585
+ function assertIds(trackId, executionId2, nodeId, phaseId) {
34313
34586
  if (!TRACK_ID2.test(trackId)) throw new Error("invalid trackId");
34314
- if (!EXECUTION_ID2.test(executionId)) throw new Error("invalid executionId");
34587
+ if (!EXECUTION_ID2.test(executionId2)) throw new Error("invalid executionId");
34315
34588
  if (!PHASE_ID.test(nodeId) && !TASK_ID.test(nodeId)) throw new Error("nodeId must be a phase or task ID");
34316
34589
  if (phaseId != null && !PHASE_ID.test(phaseId)) throw new Error("invalid phaseId");
34317
34590
  const task = nodeId.match(TASK_ID);
@@ -34325,12 +34598,12 @@ function phaseForNode(nodeId) {
34325
34598
  function nodeSlug(nodeId) {
34326
34599
  return nodeId.toLowerCase().replace(".", "-");
34327
34600
  }
34328
- function worktreeIdentity(root, trackId, executionId, nodeId, phaseId) {
34329
- assertIds(trackId, executionId, nodeId, phaseId);
34601
+ function worktreeIdentity(root, trackId, executionId2, nodeId, phaseId) {
34602
+ assertIds(trackId, executionId2, nodeId, phaseId);
34330
34603
  const task = TASK_ID.test(nodeId);
34331
34604
  const resolvedPhaseId = phaseForNode(nodeId);
34332
- const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId}/tasks/${resolvedPhaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId}/phases/${nodeId}`;
34333
- const branch = `cadre/${trackId}/${executionId}/${task ? "task" : "phase"}-${nodeSlug(nodeId)}`;
34605
+ const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId2}/tasks/${resolvedPhaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId2}/phases/${nodeId}`;
34606
+ const branch = `cadre/${trackId}/${executionId2}/${task ? "task" : "phase"}-${nodeSlug(nodeId)}`;
34334
34607
  return { path: join12(root, relativePath), relativePath, branch };
34335
34608
  }
34336
34609
  function branchHead(root, branch) {
@@ -34540,7 +34813,7 @@ function applyWorktreeCleanup(input, proposalDigest, preparedProposal) {
34540
34813
  return { removedPath: proposal.path, removedBranch: proposal.branch };
34541
34814
  }
34542
34815
  function integrationRequiresApproval(input) {
34543
- return (readExecution(input.projectRoot, input.trackId, input.executionId).approvalMode ?? "governed") === "governed";
34816
+ return resolveApprovalMode(readExecution(input.projectRoot, input.trackId, input.executionId)) === "governed";
34544
34817
  }
34545
34818
  function managedWorktreeStatus(projectRoot) {
34546
34819
  const root = assertRepository(projectRoot);
@@ -34619,10 +34892,10 @@ function deriveReviewCompleteInput(input) {
34619
34892
  const validation = requireCurrentProject(input.projectRoot);
34620
34893
  const state = validation.states.get(input.trackId);
34621
34894
  const reviewedHead = state?.lastExecution?.headCommit;
34622
- const executionId = state?.lastExecution?.executionId;
34895
+ const executionId2 = state?.lastExecution?.executionId;
34623
34896
  if (!reviewedHead || !SHA3.test(reviewedHead)) throw new Error(`${input.trackId} has no completed execution head`);
34624
- if (!executionId) throw new Error(`${input.trackId} has no completed execution journal`);
34625
- const execution = executionStatus(input.projectRoot, input.trackId, executionId).journal;
34897
+ if (!executionId2) throw new Error(`${input.trackId} has no completed execution journal`);
34898
+ const execution = executionStatus(input.projectRoot, input.trackId, executionId2).journal;
34626
34899
  if (execution.status !== "completed" || execution.headCommit !== reviewedHead || !SHA3.test(execution.baseCommit)) {
34627
34900
  throw new Error(`${input.trackId} completed execution evidence is inconsistent`);
34628
34901
  }
@@ -34631,13 +34904,13 @@ function deriveReviewCompleteInput(input) {
34631
34904
  }
34632
34905
  const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
34633
34906
  const existingCycle = state.status === "completed" ? state.reviewCycles?.at(-1) : void 0;
34634
- const matchingCycle = existingCycle && existingCycle.outcome === "clean" && existingCycle.executionId === executionId && existingCycle.reviewedHead === reviewedHead && (existingCycle.reviewEvidence ?? existingCycle.approval) === input.approval && JSON.stringify(existingCycle.acceptedRisks ?? []) === JSON.stringify(acceptedRisks) ? existingCycle : void 0;
34907
+ const matchingCycle = existingCycle && existingCycle.outcome === "clean" && existingCycle.executionId === executionId2 && existingCycle.reviewedHead === reviewedHead && (existingCycle.reviewEvidence ?? existingCycle.approval) === input.approval && JSON.stringify(existingCycle.acceptedRisks ?? []) === JSON.stringify(acceptedRisks) ? existingCycle : void 0;
34635
34908
  return {
34636
34909
  projectRoot: input.projectRoot,
34637
34910
  trackId: input.trackId,
34638
34911
  reviewedAt: typeof matchingCycle?.reviewedAt === "string" ? matchingCycle.reviewedAt : (/* @__PURE__ */ new Date()).toISOString(),
34639
34912
  reviewedHead,
34640
- commitRange: `${execution.baseCommit}..${reviewedHead}`,
34913
+ commitRange: `${state?.autonomousReview?.initialBaseCommit ?? execution.baseCommit}..${reviewedHead}`,
34641
34914
  approval: input.approval,
34642
34915
  ...acceptedRisks.length ? { acceptedRisks } : {}
34643
34916
  };
@@ -34662,6 +34935,17 @@ function previewReviewComplete(input) {
34662
34935
  if (!execution?.executionId || !execution.planRevision || !execution.graphDigest || execution.headCommit !== input.reviewedHead) {
34663
34936
  throw new Error("review evidence does not match the current completed execution");
34664
34937
  }
34938
+ const approvalMode = resolveApprovalMode(execution, current2.approvalModeMigration);
34939
+ if (current2.autonomousReview && approvalMode !== "autonomous") {
34940
+ throw new Error("Changing Autonomous authority requires an approved refresh preserving the former loop in history");
34941
+ }
34942
+ if (approvalMode === "autonomous") {
34943
+ if (!current2.autonomousReview) throw new Error("Autonomous completion requires persisted review loop authority");
34944
+ requireCleanAutonomousReview(current2.autonomousReview, execution, input.acceptedRisks ?? []);
34945
+ if (range[1] !== current2.autonomousReview.initialBaseCommit) throw new Error("Autonomous review must cover the cumulative implementation range");
34946
+ if (!isGitAncestor(root, range[1], input.reviewedHead)) throw new Error("Autonomous review baseline is not an ancestor of reviewed HEAD");
34947
+ requireReviewedProductUnchanged(root, input.reviewedHead, input.trackId);
34948
+ }
34665
34949
  const statePath = join13(cadreRoot(root), track.location, "state.json");
34666
34950
  const tracksPath = join13(cadreRoot(root), "tracks.md");
34667
34951
  const stateBody = readFileSync7(statePath, "utf8");
@@ -34686,6 +34970,7 @@ function previewReviewComplete(input) {
34686
34970
  ...current2,
34687
34971
  status: "completed",
34688
34972
  checkpoint: "completed",
34973
+ ...current2.autonomousReview ? { autonomousReview: { ...current2.autonomousReview, checkpoint: "completed" } } : {},
34689
34974
  reviewCycles: [...current2.reviewCycles ?? [], cycle]
34690
34975
  };
34691
34976
  const tracks = validation.tracks.map((candidate) => candidate.id === input.trackId ? { ...candidate, ...state, id: input.trackId, location: `tracks/${input.trackId}` } : candidate);
@@ -35634,6 +35919,7 @@ var executionStatusSchema = external_exports.strictObject({
35634
35919
  requestedMode: external_exports.enum(["parallel", "sequential"]),
35635
35920
  effectiveMode: external_exports.enum(["parallel", "sequential"]),
35636
35921
  approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES),
35922
+ approvalPolicyVersion: external_exports.number().int().optional(),
35637
35923
  maxWorkers: external_exports.number().int(),
35638
35924
  planRevision: external_exports.number().int(),
35639
35925
  startedAt: external_exports.string(),
@@ -35729,6 +36015,7 @@ var stagedTrackStatusSchema = external_exports.strictObject({
35729
36015
  nextAction: external_exports.string()
35730
36016
  });
35731
36017
  var canonicalTrackStatusShape = {
36018
+ nextStep: nextStepSchema.nullable(),
35732
36019
  kind: external_exports.literal("canonical_track"),
35733
36020
  valid: external_exports.boolean(),
35734
36021
  derivedStateCurrent: external_exports.boolean(),
@@ -35856,6 +36143,7 @@ var executionStartOutputSchema = external_exports.strictObject({
35856
36143
  requestedMode: external_exports.enum(["parallel", "sequential"]),
35857
36144
  effectiveMode: external_exports.enum(["parallel", "sequential"]),
35858
36145
  approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES),
36146
+ approvalPolicyVersion: external_exports.number().int().optional(),
35859
36147
  maxWorkers: external_exports.number().int(),
35860
36148
  nodeCount: external_exports.number().int()
35861
36149
  }),
@@ -35869,6 +36157,7 @@ var checkpointOutputSchema = external_exports.strictObject({
35869
36157
  derivedStatus: schedulerSchema
35870
36158
  });
35871
36159
  var executionFinishOutputSchema = external_exports.strictObject({
36160
+ nextStep: nextStepSchema.nullable(),
35872
36161
  ...appliedReceiptBase,
35873
36162
  executionId: external_exports.string(),
35874
36163
  status: external_exports.literal("completed"),
@@ -36202,7 +36491,7 @@ function createCadreServer() {
36202
36491
  derivedStatus: executionSchedulerView(applied.journal, [input.nodeId])
36203
36492
  };
36204
36493
  }
36205
- function recordIntegrationNow(input, commit) {
36494
+ function recordIntegrationNow(input, commit2) {
36206
36495
  const journal = executionStatus(input.projectRoot, input.trackId, input.executionId).journal;
36207
36496
  const node = journal.nodes[input.nodeId];
36208
36497
  if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
@@ -36212,7 +36501,7 @@ function createCadreServer() {
36212
36501
  return applyCheckpointNow({
36213
36502
  ...input,
36214
36503
  event: "record_integration",
36215
- commit,
36504
+ commit: commit2,
36216
36505
  verification: `Integrated ${input.nodeId} into its registered parent worktree.`
36217
36506
  });
36218
36507
  }
@@ -36343,11 +36632,11 @@ function createCadreServer() {
36343
36632
  limit: external_exports.number().int().min(1).max(200).default(50),
36344
36633
  cursor: external_exports.string().max(1024).optional(),
36345
36634
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).optional(),
36346
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/).optional()
36635
+ executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/).nullish().describe("Known persisted execution ID. Omit or use null to select current state; never infer it from trackId.")
36347
36636
  },
36348
36637
  outputSchema: CADRE_MCP_OUTPUT_SCHEMAS[CADRE_MCP_TOOLS.projectStatus],
36349
36638
  annotations: { readOnlyHint: true, openWorldHint: false }
36350
- }, async ({ projectRoot, view, trackId, executionId, detail, statuses, limit, cursor }) => {
36639
+ }, async ({ projectRoot, view, trackId, executionId: executionId2, detail, statuses, limit, cursor }) => {
36351
36640
  try {
36352
36641
  const root = safeProjectRoot(projectRoot);
36353
36642
  const validation = validateProject(root);
@@ -36434,20 +36723,26 @@ function createCadreServer() {
36434
36723
  ...stagedCandidate ? { stagedCandidate } : {},
36435
36724
  warnings: validation.warnings
36436
36725
  };
36726
+ const nextStep = deriveNextStep(root, validation.states.get(trackId), {
36727
+ errors: focused.errors,
36728
+ upgradeRequired: focused.upgradeRequired,
36729
+ staleMemory: focused.staleMemory.length > 0
36730
+ });
36437
36731
  if (view === "track") {
36438
- return result(focused, `${trackId}: ${track.status}; checkpoint=${track.checkpoint ?? "none"}.`);
36732
+ return result({ ...focused, nextStep }, `${trackId}: ${track.status}; checkpoint=${track.checkpoint ?? "none"}.`);
36439
36733
  }
36440
36734
  const planPath = join15(root, ".cadre", track.location, "plan.md");
36441
36735
  const graphErrors = [];
36442
36736
  const graph = validation.plans.get(trackId) ?? parsePlan(planPath, graphErrors);
36443
36737
  validatePlanGraph(planPath, graph, track.status, graphErrors);
36444
- const activeExecutionId = executionId ?? (typeof track.operation?.executionId === "string" ? track.operation.executionId : void 0) ?? track.lastExecution?.executionId;
36738
+ const activeExecutionId = executionId2 ?? (typeof track.operation?.executionId === "string" ? track.operation.executionId : void 0) ?? track.lastExecution?.executionId;
36445
36739
  const executionJournal = activeExecutionId ? executionStatus(root, trackId, activeExecutionId).journal : null;
36446
36740
  const execution = executionJournal ? compactExecutionStatus(executionJournal) : null;
36447
36741
  const worktreeStatus = managedWorktreeStatus(root);
36448
36742
  const trackWorktreeSegment = `${join15(".cadre", ".worktrees", trackId)}/`;
36449
36743
  return result({
36450
36744
  ...focused,
36745
+ nextStep: graphErrors.length ? deriveNextStep(root, validation.states.get(trackId), { errors: graphErrors }) : nextStep,
36451
36746
  graph: { valid: graphErrors.length === 0, graph: detail === "full" ? graph : summarizeGraph(graph), errors: graphErrors },
36452
36747
  execution,
36453
36748
  ...detail === "full" ? { executionJournal } : {},
@@ -36749,9 +37044,9 @@ function createCadreServer() {
36749
37044
  const executionStartSchema = {
36750
37045
  projectRoot: external_exports.string().min(1),
36751
37046
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
36752
- requestedMode: external_exports.enum(["parallel", "sequential"]).optional().default("parallel"),
37047
+ requestedMode: external_exports.enum(["parallel", "sequential"]).optional(),
36753
37048
  approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES).optional(),
36754
- maxWorkers: external_exports.number().int().min(1).max(32).optional().default(3)
37049
+ maxWorkers: external_exports.number().int().min(1).max(32).optional()
36755
37050
  };
36756
37051
  registerTool(CADRE_MCP_TOOLS.executionStart, {
36757
37052
  title: "Start implementation execution",
@@ -36777,6 +37072,7 @@ function createCadreServer() {
36777
37072
  requestedMode: applied.journal.requestedMode,
36778
37073
  effectiveMode: applied.journal.effectiveMode,
36779
37074
  approvalMode: applied.journal.approvalMode,
37075
+ approvalPolicyVersion: applied.journal.approvalPolicyVersion,
36780
37076
  maxWorkers: applied.journal.maxWorkers,
36781
37077
  nodeCount: Object.keys(applied.journal.nodes).length
36782
37078
  },
@@ -36898,6 +37194,7 @@ function createCadreServer() {
36898
37194
  const derived = deriveExecutionFinishInput(input);
36899
37195
  const preview = previewExecutionFinish(derived);
36900
37196
  const applied = applyExecutionFinish(derived, preview.digest, preview);
37197
+ const validation = validateProject(input.projectRoot);
36901
37198
  return result({
36902
37199
  commandStatus: "applied",
36903
37200
  executionId: derived.executionId,
@@ -36906,7 +37203,14 @@ function createCadreServer() {
36906
37203
  headCommit: applied.journal.headCommit,
36907
37204
  digest: preview.digest,
36908
37205
  changedPaths: [applied.journalPath, applied.statePath, applied.planPath, applied.tracksPath],
36909
- changedCount: 4
37206
+ changedCount: 4,
37207
+ nextStep: deriveNextStep(safeProjectRoot(input.projectRoot), validation.states.get(input.trackId), {
37208
+ errors: validation.errors,
37209
+ staleMemory: validation.staleMemory.some((finding) => [
37210
+ input.trackId,
37211
+ ...validation.states.get(input.trackId)?.dependencies ?? []
37212
+ ].includes(finding.trackId))
37213
+ })
36910
37214
  });
36911
37215
  } catch (error51) {
36912
37216
  return failure(error51);
@@ -36928,6 +37232,7 @@ function createCadreServer() {
36928
37232
  try {
36929
37233
  requireCurrentProject2(input.projectRoot);
36930
37234
  requireFreshTrackMemory(input.projectRoot, input.trackId);
37235
+ requireTrackExecutionAuthority(input.projectRoot, input.trackId, input.executionId);
36931
37236
  const preview = previewWorktreeCreate(input);
36932
37237
  const applied = applyWorktreeCreate(input, preview.digest, preview);
36933
37238
  const journal = executionStatus(input.projectRoot, input.trackId, input.executionId).journal;
@@ -36969,6 +37274,7 @@ function createCadreServer() {
36969
37274
  }
36970
37275
  requireCurrentProject2(proposal.input.projectRoot);
36971
37276
  requireFreshTrackMemory(proposal.input.projectRoot, proposal.input.trackId);
37277
+ requireTrackExecutionAuthority(proposal.input.projectRoot, proposal.input.trackId, proposal.input.executionId);
36972
37278
  const applied2 = applyWorktreeIntegration(proposal.input, proposal.digest);
36973
37279
  const checkpoint2 = applied2.status === "integrated" && applied2.mergeCommit ? recordIntegrationNow(proposal.input, applied2.mergeCommit) : {};
36974
37280
  return result({ commandStatus: "applied", ...applied2, ...checkpoint2 }, `Integrated ${proposal.input.nodeId}.`);
@@ -36981,6 +37287,7 @@ function createCadreServer() {
36981
37287
  }
36982
37288
  requireCurrentProject2(integrationInput.projectRoot);
36983
37289
  requireFreshTrackMemory(integrationInput.projectRoot, integrationInput.trackId);
37290
+ requireTrackExecutionAuthority(integrationInput.projectRoot, integrationInput.trackId, integrationInput.executionId);
36984
37291
  if (integrationRequiresApproval(integrationInput)) {
36985
37292
  return proposalResult("worktree_integrate", integrationInput, preview);
36986
37293
  }
@@ -37085,8 +37392,8 @@ function createCadreServer() {
37085
37392
  }, async ({ projectRoot }) => {
37086
37393
  try {
37087
37394
  requireCurrentProject2(projectRoot);
37088
- const commit = resolveGitCommit(projectRoot);
37089
- return result({ path: recordSetupCommit(projectRoot, commit), commit });
37395
+ const commit2 = resolveGitCommit(projectRoot);
37396
+ return result({ path: recordSetupCommit(projectRoot, commit2), commit: commit2 });
37090
37397
  } catch (error51) {
37091
37398
  return failure(error51);
37092
37399
  }
@@ -37131,7 +37438,7 @@ async function runCadreServer() {
37131
37438
  const server = createCadreServer();
37132
37439
  await server.connect(new StdioServerTransport());
37133
37440
  }
37134
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve13(process.argv[1])).href) {
37441
+ if (process.argv[1] && existsSync16(process.argv[1]) && realpathSync3(fileURLToPath2(import.meta.url)) === realpathSync3(process.argv[1])) {
37135
37442
  runCadreServer().catch((error51) => {
37136
37443
  process.stderr.write(`${error51 instanceof Error ? error51.message : String(error51)}
37137
37444
  `);