cadre-ai 3.7.0 → 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 +21 -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 +1212 -867
  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 +75 -9
  18. package/skills/revise/SKILL.md +2 -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,259 +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) return;
21753
- if (!Number.isInteger(graph.specRevision) || (graph.specRevision ?? 0) < 1) {
21754
- errors.push(`${path}: Spec revision must be a positive integer`);
21755
- }
21756
- if (!Number.isInteger(graph.planRevision) || (graph.planRevision ?? 0) < 1) {
21757
- errors.push(`${path}: Plan revision must be a positive integer`);
21758
- }
21759
- const phaseIds = new Set(graph.phases.map((phase) => phase.id));
21760
- const finalPhase = graph.phases.at(-1);
21761
- graph.phases.forEach((phase, phaseIndex) => {
21762
- if (phase.number !== phaseIndex + 1) errors.push(`${path}: phases must be sequential from 1`);
21763
- if (!phase.tasks.length) errors.push(`${path}: ${phase.id} has no tasks`);
21764
- if (phase.trackVerification && phase !== finalPhase) {
21765
- errors.push(`${path}: Track-level User Manual Verification must be the final phase`);
21766
- }
21767
- if (!phase.trackVerification && !phase.dependencyDeclared) {
21768
- errors.push(`${path}:${phase.line}: ${phase.id} must declare phase dependencies`);
21769
- }
21770
- if (phase.trackVerification && phase.dependencyDeclared) {
21771
- errors.push(`${path}:${phase.line}: final track verification dependencies are derived and must not be declared`);
21772
- }
21773
- if (new Set(phase.dependencies).size !== phase.dependencies.length) {
21774
- errors.push(`${path}:${phase.line}: ${phase.id} contains duplicate phase dependencies`);
21775
- }
21776
- for (const dependency of phase.dependencies) {
21777
- if (!/^P\d+$/.test(dependency) || !phaseIds.has(dependency)) errors.push(`${path}:${phase.line}: ${phase.id} has unknown phase dependency ${dependency}`);
21778
- if (dependency === phase.id) errors.push(`${path}:${phase.line}: ${phase.id} cannot depend on itself`);
21779
- if (dependency === finalPhase.id) errors.push(`${path}:${phase.line}: ${phase.id} cannot depend on final track verification`);
21780
- }
21781
- const nonManualTasks = phase.tasks.filter((task) => !task.manualVerification);
21782
- if (!phase.trackVerification && !nonManualTasks.length) errors.push(`${path}: ${phase.id} has no delivery task`);
21783
- if (phase.trackVerification && (phase.tasks.length !== 1 || !phase.tasks[0]?.manualVerification)) {
21784
- errors.push(`${path}: final track verification phase must contain only User Manual Verification`);
21785
- }
21786
- phase.tasks.forEach((task, taskIndex) => {
21787
- if (task.phaseId !== phase.id) errors.push(`${path}:${task.line}: ${task.id} is in the wrong phase`);
21788
- if (task.ordinal !== taskIndex + 1) errors.push(`${path}:${task.line}: task ordinals must be sequential`);
21789
- if (task.checked && !task.commit) errors.push(`${path}:${task.line}: completed task ${task.id} has no commit marker`);
21790
- if (!task.checked && task.commit) errors.push(`${path}:${task.line}: pending task ${task.id} has a commit marker`);
21791
- if (task.manualVerification) {
21792
- if (task !== phase.tasks.at(-1)) errors.push(`${path}:${task.line}: User Manual Verification must be the final phase task`);
21793
- if (task.dependencyDeclared) errors.push(`${path}:${task.line}: ${task.id} dependencies are derived and must not be declared`);
21794
- task.dependencies = nonManualTasks.map((candidate) => candidate.id);
21795
- } else if (!task.dependencyDeclared) {
21796
- errors.push(`${path}:${task.line}: ${task.id} must declare task dependencies`);
21797
- }
21798
- if (new Set(task.dependencies).size !== task.dependencies.length) {
21799
- errors.push(`${path}:${task.line}: ${task.id} contains duplicate task dependencies`);
21800
- }
21801
- for (const dependency of task.dependencies) {
21802
- const target = phase.tasks.find((candidate) => candidate.id === dependency);
21803
- if (!target) errors.push(`${path}:${task.line}: ${task.id} has unknown or cross-phase task dependency ${dependency}`);
21804
- if (dependency === task.id) errors.push(`${path}:${task.line}: ${task.id} cannot depend on itself`);
21805
- if (target?.manualVerification) errors.push(`${path}:${task.line}: ${task.id} cannot depend on manual verification`);
21806
- }
21807
- });
21808
- if (phase.completionCommit === void 0) errors.push(`${path}: ${phase.id} lacks a completion commit field`);
21809
- const phaseDone = phase.tasks.length > 0 && phase.tasks.every((task) => task.checked);
21810
- if (phaseDone && !phase.completionCommit) errors.push(`${path}: completed ${phase.id} has no completion commit`);
21811
- if (!phaseDone && phase.completionCommit) errors.push(`${path}: incomplete ${phase.id} has a completion commit`);
21812
- findCycles(phase.tasks, `${path}:${phase.id}`, errors);
21813
- });
21814
- if (!finalPhase.trackVerification) errors.push(`${path}: final phase must be Track-level User Manual Verification`);
21815
- finalPhase.dependencies = graph.phases.slice(0, -1).map((phase) => phase.id);
21816
- findCycles(graph.phases, path, errors);
21817
- if (["ready_for_review", "completed", "archived"].includes(status)) {
21818
- const pending = graph.phases.flatMap((phase) => phase.tasks).filter((task) => !task.checked);
21819
- if (pending.length) errors.push(`${path}: ${status} track has ${pending.length} pending task(s)`);
21820
- }
21821
- }
21822
- function readAndValidatePlan(path, status, errors) {
21823
- const graph = parsePlan(path, errors);
21824
- validatePlanGraph(path, graph, status, errors);
21825
- return graph;
21826
- }
21827
-
21828
- // src/domain/markdown-context.ts
21829
- function markdownHeadings(body) {
21830
- const headings = [];
21831
- let fence = null;
21832
- let offset = 0, ambiguous = false;
21833
- for (const line of body.split(/(?<=\n)/)) {
21834
- const marker = /^ {0,3}(`{3,}|~{3,})(.*)/.exec(line);
21835
- if (marker) {
21836
- if (!fence) fence = { character: marker[1][0], length: marker[1].length };
21837
- else if (marker[1][0] === fence.character && marker[1].length >= fence.length && !marker[2].trim()) fence = null;
21838
- } else if (!fence) {
21839
- const heading = /^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*\r?\n?$/.exec(line);
21840
- if (heading) headings.push({ level: heading[1].length, title: heading[2], offset });
21841
- if (/^ {0,3}(?:=+|-+)[ \t]*$/.test(line.trimEnd()) || /^\s*<(?!\!--)/.test(line) || /^ {4,}#{1,6}\s/.test(line)) ambiguous = true;
21842
- }
21843
- offset += line.length;
21844
- }
21845
- return { headings, ambiguous: ambiguous || fence !== null };
21846
- }
21847
-
21848
21747
  // src/domain/execution-evidence.ts
21849
- import { existsSync as existsSync3, lstatSync as lstatSync2, readdirSync } from "node:fs";
21748
+ import { existsSync as existsSync2, lstatSync as lstatSync2, readdirSync } from "node:fs";
21850
21749
  import { join as join2 } from "node:path";
21851
21750
  function inspectExecutionBindings(trackRoot, state, read = (path) => readInspectionJson(path), paths) {
21852
21751
  const directory = join2(trackRoot, "executions");
21853
- if (existsSync3(directory) && lstatSync2(directory).isSymbolicLink()) return ["unsafe execution directory symbolic link"];
21854
- 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)) : []);
21855
21754
  const references = [state.operation, state.lastExecution].filter(Boolean);
21856
21755
  const errors = [];
21857
21756
  for (const file2 of journals) {
21858
21757
  try {
21859
21758
  const absolute = join2(directory, file2);
21860
21759
  if (!/^execution-[^/\\]+\.json$/.test(file2)) throw new Error("unsafe execution journal path");
21861
- 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");
21862
21761
  const journal = read(absolute);
21863
21762
  if (journal.status === "in_progress" && !references.some((reference) => reference?.executionId === journal.executionId && reference?.journal === `executions/${file2}`)) {
21864
21763
  errors.push(`orphaned in-progress execution ${file2}; retain its executionId/journal binding during repair and resume from persisted checkpoints`);
@@ -21870,487 +21769,16 @@ function inspectExecutionBindings(trackRoot, state, read = (path) => readInspect
21870
21769
  return errors;
21871
21770
  }
21872
21771
 
21873
- // src/domain/context.ts
21874
- var id = external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
21875
- var contextInputSchema = external_exports.strictObject({
21876
- projectRoot: external_exports.string().min(1),
21877
- trackId: id,
21878
- executionId: external_exports.string().regex(/^[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*$/).optional(),
21879
- nodeId: external_exports.string().regex(/^(?:P\d+|T\d+\.\d+)$/).optional(),
21880
- maxBytes: external_exports.number().int().min(4096).max(65536).default(16384),
21881
- cursor: external_exports.string().max(1024).optional(),
21882
- knownSources: external_exports.array(external_exports.strictObject({
21883
- path: external_exports.string(),
21884
- sha256: external_exports.string().regex(/^[0-9a-f]{64}$/),
21885
- section: external_exports.string(),
21886
- contentHash: external_exports.string().regex(/^[0-9a-f]{64}$/)
21887
- })).max(256).default([])
21888
- });
21889
- 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() });
21890
- function learningSections(body, phaseIds) {
21891
- if (!phaseIds || !seedSection(body)) return [{ section: "full learning (conservative)", content: body }];
21892
- const parsed = markdownHeadings(body), headings = parsed.headings.filter((heading) => heading.level === 2);
21893
- const matches = headings.filter((heading) => /^Phase \d+: .+$/.test(heading.title));
21894
- const phaseId = (heading) => `P${/^Phase (\d+):/.exec(heading.title)[1]}`;
21895
- const present = new Set(matches.map(phaseId));
21896
- 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))) {
21897
- return [{ section: "full learning (ambiguous or missing phase context)", content: body }];
21898
- }
21899
- const selected = [{ section: "Pattern Seed and general instructions", content: body.slice(0, matches[0]?.offset ?? body.length) }];
21900
- matches.forEach((match, index) => {
21901
- if (phaseIds.has(phaseId(match))) selected.push({ section: phaseId(match), content: body.slice(match.offset, matches[index + 1]?.offset ?? body.length) });
21902
- });
21903
- return selected;
21904
- }
21905
- function collectContext(input) {
21906
- const root = safeProjectRoot(input.projectRoot), sources = [], errors = [], staleMemory = [];
21907
- const inputHashes = /* @__PURE__ */ new Map();
21908
- const read = (path) => {
21909
- const body = readSafeArtifact(root, path);
21910
- inputHashes.set(path, contentHash(body));
21911
- return body;
21912
- };
21913
- const add = (path, reason, section = "full") => {
21914
- const content = read(path);
21915
- sources.push({ path, sha256: contentHash(content), reason, section, format: "source", content });
21916
- return content;
21917
- };
21918
- for (const path of ["workflow.md", "product.md", "guidelines.md", "tech-stack.md", "patterns/index.md"]) {
21919
- add(`.cadre/${path}`, "required project instructions and applicability catalog");
21920
- }
21921
- const guides = join3(root, ".cadre/styleguides");
21922
- if (existsSync4(guides)) for (const file2 of readdirSync2(guides).filter((file3) => /^[a-z0-9-]+\.md$/.test(file3)).sort()) {
21923
- add(`.cadre/styleguides/${file2}`, "project styleguide; retain until applicability is established");
21924
- }
21925
- const project = JSON.parse(read(".cadre/project.json"));
21926
- const locate = (trackId) => {
21927
- id.parse(trackId);
21928
- const active = `.cadre/tracks/${trackId}`, archived = `.cadre/archive/${trackId}`;
21929
- if (existsSync4(join3(root, active, "state.json")) && existsSync4(join3(root, archived, "state.json"))) throw new Error(`duplicate track ${trackId}`);
21930
- return existsSync4(join3(root, active, "state.json")) ? active : archived;
21931
- };
21932
- const trackPath = locate(input.trackId);
21933
- const stateBody = read(`${trackPath}/state.json`);
21934
- const state = JSON.parse(stateBody);
21935
- errors.push(...inspectExecutionBindings(join3(root, trackPath), state));
21936
- add(`${trackPath}/spec.md`, "complete approved scope and acceptance criteria");
21937
- const planBody = add(`${trackPath}/plan.md`, "complete plan, including task descriptions and verification requirements");
21938
- const graph = parsePlanContent(planBody, `${trackPath}/plan.md`, errors);
21939
- validatePlanGraph(`${trackPath}/plan.md`, graph, state.status, errors);
21940
- let phases = null;
21941
- if (input.nodeId) {
21942
- const phase = graph.phases.find((phase2) => phase2.id === input.nodeId || phase2.tasks.some((task) => task.id === input.nodeId));
21943
- if (!phase) throw new Error(`unknown plan node ${input.nodeId}`);
21944
- phases = /* @__PURE__ */ new Set();
21945
- const visit = (phaseId) => {
21946
- if (phases.has(phaseId)) return;
21947
- phases.add(phaseId);
21948
- const parent = graph.phases.find((phase2) => phase2.id === phaseId);
21949
- if (!parent) throw new Error(`unknown dependency phase ${phaseId}`);
21950
- parent.dependencies.forEach(visit);
21951
- };
21952
- visit(phase.id);
21953
- }
21954
- const patternPaths = /* @__PURE__ */ new Set();
21955
- let uncertainPatterns = false;
21956
- const addLearning = (path, trackId, historical, selected, plan) => {
21957
- const body = read(path);
21958
- const inspected = inspectMemory({
21959
- trackId,
21960
- path,
21961
- body,
21962
- graph: plan,
21963
- required: project.templateSetVersion === "v3",
21964
- historical,
21965
- readPattern: (path2) => read(`.cadre/${path2}`)
21966
- });
21967
- errors.push(...inspected.errors);
21968
- staleMemory.push(...inspected.stale);
21969
- if (!inspected.metadata) uncertainPatterns = true;
21970
- if (!historical) for (const pattern of inspected.metadata?.patterns ?? []) patternPaths.add(pattern.path);
21971
- for (const section of learningSections(body, selected)) sources.push({
21972
- path,
21973
- sha256: contentHash(body),
21974
- reason: "declared dependency learning and current phase decisions",
21975
- format: "source",
21976
- ...section
21977
- });
21978
- };
21979
- addLearning(`${trackPath}/learning.md`, input.trackId, ["completed", "archived"].includes(state.status), phases, graph);
21980
- const visited = /* @__PURE__ */ new Set([input.trackId]);
21981
- const visitDependency = (trackId) => {
21982
- if (visited.has(trackId)) return;
21983
- visited.add(trackId);
21984
- const base = locate(trackId);
21985
- const dependency = JSON.parse(read(`${base}/state.json`));
21986
- add(`${base}/spec.md`, "declared dependency contract");
21987
- const plan = parsePlanContent(read(`${base}/plan.md`), `${base}/plan.md`);
21988
- addLearning(`${base}/learning.md`, trackId, ["completed", "archived"].includes(dependency.status), null, plan);
21989
- (dependency.dependencies ?? []).forEach(visitDependency);
21990
- };
21991
- (state.dependencies ?? []).forEach(visitDependency);
21992
- if (uncertainPatterns) for (const path of readdirSync2(join3(root, ".cadre/patterns")).filter((path2) => /^[a-z0-9-]+\.md$/.test(path2) && path2 !== "index.md")) {
21993
- patternPaths.add(`patterns/${path}`);
21994
- }
21995
- for (const path of [...patternPaths].sort()) {
21996
- try {
21997
- add(`.cadre/${path}`, uncertainPatterns ? "full pattern fallback: applicability metadata unavailable" : "explicit seed reference");
21998
- } catch (error51) {
21999
- errors.push(`${path}: ${error51 instanceof Error ? error51.message : String(error51)}`);
22000
- }
22001
- }
22002
- const executionId = input.executionId ?? state.operation?.executionId ?? state.lastExecution?.executionId;
22003
- if (executionId) {
22004
- contextInputSchema.shape.executionId.parse(executionId);
22005
- const path = `${trackPath}/executions/execution-${executionId}.json`, body = read(path);
22006
- const journal = JSON.parse(body);
22007
- if (journal.trackId !== input.trackId || journal.executionId !== executionId) throw new Error("execution identity mismatch");
22008
- if (journal.graphDigest !== graph.digest) errors.push("execution handoffs belong to a different plan graph; reconcile before use");
22009
- for (const node of Object.values(journal.nodes)) {
22010
- if (phases && !phases.has(node.phaseId)) continue;
22011
- const handoff = node.handoff === void 0 ? null : handoffSchema.parse(node.handoff);
22012
- if (!handoff && node.id !== input.nodeId) continue;
22013
- const content = JSON.stringify({
22014
- nodeId: node.id,
22015
- handoff,
22016
- note: handoff ? "Persisted evidence, not authorization" : "not recorded",
22017
- sources: handoff?.sources.map((reference) => ({ ...reference, freshness: sourceFreshness(root, reference, read) })) ?? []
22018
- });
22019
- sources.push({ path, sha256: contentHash(body), section: node.id, reason: "persisted handoff; reconcile journal/Git before resuming", format: "handoff", content });
22020
- }
22021
- }
22022
- const identity = {
22023
- projectRoot: root,
22024
- trackId: input.trackId,
22025
- executionId: executionId ?? null,
22026
- nodeId: input.nodeId ?? null,
22027
- stateHash: contentHash(stateBody),
22028
- inputs: [...inputHashes].sort(),
22029
- sources,
22030
- errors,
22031
- staleMemory
22032
- };
22033
- return { sources, errors, staleMemory, snapshot: contentHash(JSON.stringify(identity)) };
22034
- }
22035
- function readContext(raw) {
22036
- const input = contextInputSchema.parse(raw);
22037
- return inspectOnce(() => {
22038
- const collected = collectContext(input), { errors, staleMemory } = collected;
22039
- const sources = collected.sources.map((source2) => {
22040
- const hash6 = contentHash(source2.content);
22041
- const reused = input.knownSources.some((known) => known.path === source2.path && known.sha256 === source2.sha256 && known.section === source2.section && known.contentHash === hash6);
22042
- return { ...source2, contentHash: hash6, reused, content: reused ? "" : source2.content };
22043
- });
22044
- const snapshot = contentHash(JSON.stringify({ sources: collected.snapshot, knownSources: input.knownSources }));
22045
- const cursor = input.cursor ? cursorSchema.parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8"))) : { snapshot, source: 0, offset: 0 };
22046
- if (cursor.snapshot !== snapshot) throw new CadreError("CONTEXT_SNAPSHOT_CHANGED", "Required sources changed; restart context_read without a cursor.");
22047
- if (cursor.source >= sources.length || cursor.offset > sources[cursor.source].content.length) throw new Error("invalid context cursor position");
22048
- let source = cursor.source, offset = cursor.offset;
22049
- const page = { snapshot, complete: false, contextReady: false, nextCursor: null, totalSources: sources.length, excerpts: [], errors, staleMemory };
22050
- const encode3 = () => Buffer.from(JSON.stringify({ snapshot, source, offset })).toString("base64url");
22051
- while (source < sources.length) {
22052
- const item = sources[source];
22053
- let low = 0, high = item.content.length - offset, take = 0;
22054
- const excerpt = (length) => ({
22055
- ...item,
22056
- content: item.content.slice(offset, offset + length),
22057
- offset,
22058
- endOffset: offset + length,
22059
- sourceComplete: offset + length === item.content.length
22060
- });
22061
- while (low <= high) {
22062
- const mid = Math.floor((low + high) / 2);
22063
- const bytes = Buffer.byteLength(JSON.stringify({ ...page, excerpts: [...page.excerpts, excerpt(mid)], nextCursor: encode3() }));
22064
- if (bytes <= input.maxBytes - 64) {
22065
- take = mid;
22066
- low = mid + 1;
22067
- } else high = mid - 1;
22068
- }
22069
- if (take && /[\uD800-\uDBFF]/.test(item.content[offset + take - 1])) take--;
22070
- if (!take && item.content.length > offset) break;
22071
- page.excerpts.push(excerpt(take));
22072
- offset += take;
22073
- if (offset === item.content.length) {
22074
- source++;
22075
- offset = 0;
22076
- } else break;
22077
- }
22078
- if (!page.excerpts.length) throw new CadreError("CONTEXT_PAGE_TOO_SMALL", "Context findings or metadata exceed the page budget; increase maxBytes and inspect diagnostics.");
22079
- page.complete = source === sources.length;
22080
- page.contextReady = page.complete && !errors.length && !staleMemory.length;
22081
- page.nextCursor = page.complete ? null : encode3();
22082
- return page;
22083
- });
22084
- }
22085
-
22086
- // src/domain/staged-memory.ts
22087
- import { existsSync as existsSync6, readdirSync as readdirSync4 } from "node:fs";
22088
- import { dirname, join as join5 } from "node:path";
22089
-
22090
- // src/domain/staging.ts
22091
- import {
22092
- existsSync as existsSync5,
22093
- lstatSync as lstatSync3,
22094
- mkdirSync,
22095
- readFileSync as readFileSync2,
22096
- readdirSync as readdirSync3,
22097
- renameSync,
22098
- rmdirSync,
22099
- unlinkSync,
22100
- writeFileSync
22101
- } from "node:fs";
22102
- import { isAbsolute, join as join4, relative, resolve as resolve3, sep } from "node:path";
22103
- var CANDIDATE_STAGE_DIRECTORY = ".cadre/stage";
22104
- var MAX_CANDIDATE_FILE_BYTES = 1024 * 1024;
22105
- var MAX_CANDIDATE_TOTAL_BYTES = 8 * 1024 * 1024;
22106
- var CANDIDATE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
22107
- function candidateArtifactPath(candidateId, path) {
22108
- const normalized = normalizeCandidatePath(path);
22109
- const owner = candidateId.match(/^(?:track|revise|review|revert)-([a-z0-9-]+)$/)?.[1];
22110
- return owner && !/^(?:tracks|archive|patterns|refreshes)\//.test(normalized) ? `tracks/${owner}/${normalized}` : normalized;
22111
- }
22112
- function normalizeCandidateId(candidateId) {
22113
- if (!CANDIDATE_ID.test(candidateId)) {
22114
- throw new Error("candidateId must contain lowercase letters, digits, and single hyphens");
22115
- }
22116
- return candidateId;
22117
- }
22118
- function normalizeCandidatePath(input) {
22119
- if (!input || isAbsolute(input) || input.includes("\\")) {
22120
- throw new Error(`Candidate artifact path must be a portable relative path: ${input}`);
22121
- }
22122
- const normalized = input.replace(/^\.\//, "");
22123
- if (normalized === ".cadre" || normalized.startsWith(".cadre/")) {
22124
- 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.`);
22125
- }
22126
- if (!normalized || normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
22127
- throw new Error(`Candidate artifact path is not canonical: ${input}`);
22128
- }
22129
- return normalized;
22130
- }
22131
- function candidateStageRoot(projectRootInput, candidateIdInput) {
22132
- const projectRoot = safeProjectRoot(projectRootInput);
22133
- const candidateId = normalizeCandidateId(candidateIdInput);
22134
- const cadreRoot2 = join4(projectRoot, ".cadre");
22135
- if (!existsSync5(cadreRoot2) || !lstatSync3(cadreRoot2).isDirectory() || lstatSync3(cadreRoot2).isSymbolicLink()) {
22136
- throw new Error(`Cadre candidate root is unavailable or unsafe: ${cadreRoot2}`);
22137
- }
22138
- const gitignorePath = join4(cadreRoot2, ".gitignore");
22139
- if (!existsSync5(gitignorePath) || !lstatSync3(gitignorePath).isFile() || lstatSync3(gitignorePath).isSymbolicLink()) {
22140
- throw new Error(`Cadre candidate stage requires a regular ${gitignorePath}`);
22141
- }
22142
- if (!readFileSync2(gitignorePath, "utf8").split(/\r?\n/).includes("/stage/")) {
22143
- throw new Error(`${gitignorePath} must ignore /stage/ before candidate files are written`);
22144
- }
22145
- const stageParent = join4(projectRoot, CANDIDATE_STAGE_DIRECTORY);
22146
- if (existsSync5(stageParent) && lstatSync3(stageParent).isSymbolicLink()) {
22147
- throw new Error(`Refusing candidate stage through symbolic link: ${stageParent}`);
22148
- }
22149
- return join4(stageParent, candidateId);
22150
- }
22151
- function prepareCandidateStage(projectRootInput, candidateIdInput, expectedFiles) {
22152
- const projectRoot = safeProjectRoot(projectRootInput);
22153
- const candidateId = normalizeCandidateId(candidateIdInput);
22154
- const normalizedExpected = expectedFiles?.map(normalizeCandidatePath);
22155
- if (normalizedExpected && new Set(normalizedExpected).size !== normalizedExpected.length) {
22156
- throw new Error("Candidate expectedFiles contains duplicate paths");
22157
- }
22158
- const cadreRoot2 = join4(projectRoot, ".cadre");
22159
- if (existsSync5(cadreRoot2)) {
22160
- const stat = lstatSync3(cadreRoot2);
22161
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Unsafe Cadre directory: ${cadreRoot2}`);
22162
- } else mkdirSync(cadreRoot2);
22163
- const gitignorePath = join4(cadreRoot2, ".gitignore");
22164
- let content = "# Cadre-managed temporary execution worktrees\n/.worktrees/\n\n# Disposable Wisp output\n/wisps/\n";
22165
- if (existsSync5(gitignorePath)) {
22166
- const stat = lstatSync3(gitignorePath);
22167
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Unsafe Cadre ignore file: ${gitignorePath}`);
22168
- content = readFileSync2(gitignorePath, "utf8");
22169
- }
22170
- if (!content.split(/\r?\n/).includes("/stage/")) {
22171
- content = `${content.endsWith("\n") ? content : `${content}
22172
- `}
22173
- # Unapproved candidate artifacts
22174
- /stage/
22175
- `;
22176
- const temporaryPath = `${gitignorePath}.${process.pid}.tmp`;
22177
- try {
22178
- writeFileSync(temporaryPath, content, { flag: "wx" });
22179
- renameSync(temporaryPath, gitignorePath);
22180
- } finally {
22181
- if (existsSync5(temporaryPath)) unlinkSync(temporaryPath);
22182
- }
22183
- }
22184
- const stagePath = join4(cadreRoot2, "stage", candidateId);
22185
- mkdirSync(stagePath, { recursive: true });
22186
- candidateStageRoot(projectRoot, candidateId);
22187
- const retainedFiles = listCandidatePaths(projectRoot, candidateId);
22188
- if (normalizedExpected === void 0) return { stagePath, gitignorePath, retainedFiles, removedFiles: [] };
22189
- const expected = new Set(normalizedExpected);
22190
- const removedFiles = retainedFiles.filter((path) => !expected.has(path));
22191
- for (const path of removedFiles) unlinkSync(join4(stagePath, path));
22192
- const pruneEmptyDirectories = (directory) => {
22193
- for (const entry of readdirSync3(directory, { withFileTypes: true })) {
22194
- if (entry.isDirectory()) pruneEmptyDirectories(join4(directory, entry.name));
22195
- }
22196
- if (directory !== stagePath && readdirSync3(directory).length === 0) rmdirSync(directory);
22197
- };
22198
- pruneEmptyDirectories(stagePath);
22199
- return {
22200
- stagePath,
22201
- gitignorePath,
22202
- retainedFiles: retainedFiles.filter((path) => expected.has(path)),
22203
- removedFiles
22204
- };
22205
- }
22206
- function assertRegularPath(root, target) {
22207
- const relation = relative(root, target);
22208
- if (relation.startsWith("..") || isAbsolute(relation)) {
22209
- throw new Error(`Candidate artifact escapes its stage: ${target}`);
22210
- }
22211
- let current2 = target;
22212
- while (current2 !== root) {
22213
- if (!existsSync5(current2)) throw new Error(`Missing candidate artifact: ${target}`);
22214
- const stat = lstatSync3(current2);
22215
- if (stat.isSymbolicLink()) throw new Error(`Refusing candidate artifact through symbolic link: ${current2}`);
22216
- current2 = resolve3(current2, "..");
22217
- }
22218
- if (!existsSync5(root)) throw new Error(`Missing candidate stage: ${root}`);
22219
- const rootStat = lstatSync3(root);
22220
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
22221
- throw new Error(`Candidate stage is not a regular directory: ${root}`);
22222
- }
22223
- const targetStat = lstatSync3(target);
22224
- if (!targetStat.isFile()) throw new Error(`Candidate artifact is not a regular file: ${target}`);
22225
- if (targetStat.size > MAX_CANDIDATE_FILE_BYTES) {
22226
- throw new Error(`Candidate artifact exceeds ${MAX_CANDIDATE_FILE_BYTES} bytes: ${target}`);
22227
- }
22228
- }
22229
- function readCandidateFiles(projectRootInput, candidateIdInput, paths) {
22230
- const root = candidateStageRoot(projectRootInput, candidateIdInput);
22231
- const seen = /* @__PURE__ */ new Set();
22232
- let totalBytes = 0;
22233
- return paths.map((input) => {
22234
- const path = normalizeCandidatePath(input);
22235
- if (seen.has(path)) throw new Error(`Duplicate candidate artifact: ${path}`);
22236
- seen.add(path);
22237
- const absolutePath = resolve3(root, path);
22238
- assertRegularPath(root, absolutePath);
22239
- const content = readFileSync2(absolutePath, "utf8");
22240
- totalBytes += Buffer.byteLength(content, "utf8");
22241
- if (totalBytes > MAX_CANDIDATE_TOTAL_BYTES) {
22242
- throw new Error(`Candidate stage exceeds ${MAX_CANDIDATE_TOTAL_BYTES} bytes`);
22243
- }
22244
- return { path, absolutePath, content };
22245
- });
22246
- }
22247
- function listCandidatePaths(projectRootInput, candidateIdInput) {
22248
- const root = candidateStageRoot(projectRootInput, candidateIdInput);
22249
- if (!existsSync5(root)) throw new Error(`Missing candidate stage: ${root}`);
22250
- const rootStat = lstatSync3(root);
22251
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
22252
- throw new Error(`Candidate stage is not a regular directory: ${root}`);
22253
- }
22254
- const walk2 = (directory) => readdirSync3(directory, { withFileTypes: true }).flatMap((entry) => {
22255
- const target = join4(directory, entry.name);
22256
- const stat = lstatSync3(target);
22257
- if (stat.isSymbolicLink()) throw new Error(`Refusing symbolic link in candidate stage: ${target}`);
22258
- if (stat.isDirectory()) return walk2(target);
22259
- if (!stat.isFile()) throw new Error(`Candidate stage contains a non-file entry: ${target}`);
22260
- return [relative(root, target).split(sep).join("/")];
22261
- });
22262
- return walk2(root).sort();
22263
- }
22264
-
22265
- // src/domain/staged-memory.ts
22266
- function inspectStagedMemory(projectRoot, candidateId, files) {
22267
- const originalPaths = new Map(files.map((file2) => [candidateArtifactPath(candidateId, file2.path), file2.path]));
22268
- if (originalPaths.size !== files.length) throw new Error("Candidate paths alias the same canonical artifact; use one path per artifact");
22269
- files = files.map((file2) => ({ ...file2, path: candidateArtifactPath(candidateId, file2.path) }));
22270
- const overlay = new Map(files.map((file2) => [file2.path, file2.content]));
22271
- const inputs = /* @__PURE__ */ new Map();
22272
- const read = (path, fingerprint = true) => {
22273
- const staged = overlay.get(path);
22274
- if (staged !== void 0) return staged;
22275
- const body = readSafeArtifact(projectRoot, `.cadre/${path}`);
22276
- if (fingerprint) inputs.set(path, contentHash(body));
22277
- return body;
22278
- };
22279
- const project = overlay.has("project.json") || existsSync6(join5(projectRoot, ".cadre/project.json")) ? JSON.parse(read("project.json", false)) : {};
22280
- const learningPaths = new Set(files.filter((file2) => file2.path.split("/").at(-1) === "learning.md").map((file2) => file2.path));
22281
- for (const file2 of files.filter((file3) => file3.path.split("/").at(-1) === "plan.md")) {
22282
- const parent = dirname(file2.path);
22283
- const seed = parent === "." ? "learning.md" : `${parent}/learning.md`;
22284
- const owner = candidateId.replace(/^(?:track|revise|review|revert)-/, "");
22285
- const canonicalSeed = parent === "." ? `tracks/${owner}/learning.md` : seed;
22286
- if (overlay.has(seed)) learningPaths.add(seed);
22287
- else if (existsSync6(join5(projectRoot, ".cadre", canonicalSeed))) {
22288
- learningPaths.add(canonicalSeed);
22289
- overlay.set(`${dirname(canonicalSeed)}/plan.md`, file2.content);
22290
- }
22291
- }
22292
- const changedPatterns = files.some((file2) => /^patterns\/.+\.md$/.test(file2.path));
22293
- if (changedPatterns && existsSync6(join5(projectRoot, ".cadre/tracks"))) {
22294
- for (const entry of readdirSync4(join5(projectRoot, ".cadre/tracks"), { withFileTypes: true })) {
22295
- if (!entry.isDirectory() || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(entry.name)) continue;
22296
- const path = `tracks/${entry.name}/learning.md`;
22297
- if (existsSync6(join5(projectRoot, ".cadre", path))) learningPaths.add(path);
22298
- }
22299
- }
22300
- const historicalPaths = [];
22301
- const learning = [...learningPaths].sort().map((path) => {
22302
- const parent = dirname(path);
22303
- const id2 = path.match(/(?:^|\/)tracks\/([a-z0-9-]+)\//)?.[1] ?? candidateId.replace(/^(?:track|revise|review|revert)-/, "");
22304
- const canonicalParent = parent === "." ? `tracks/${id2}` : parent;
22305
- let historical = path.startsWith("archive/");
22306
- const statePath = `${canonicalParent}/state.json`;
22307
- if (overlay.has(statePath) || existsSync6(join5(projectRoot, ".cadre", statePath))) {
22308
- const state = JSON.parse(read(statePath, false));
22309
- historical ||= ["completed", "archived"].includes(state.status ?? "");
22310
- }
22311
- const stagedPlan = parent === "." ? "plan.md" : `${parent}/plan.md`;
22312
- const planPath = overlay.has(stagedPlan) ? stagedPlan : `${canonicalParent}/plan.md`;
22313
- const graph = overlay.has(planPath) || existsSync6(join5(projectRoot, ".cadre", planPath)) ? parsePlanContent(read(planPath), planPath) : null;
22314
- const reportedPath = originalPaths.get(path) ?? path;
22315
- if (historical) historicalPaths.push(reportedPath);
22316
- const inspected = inspectMemory({
22317
- trackId: id2,
22318
- path: reportedPath,
22319
- body: read(path),
22320
- graph,
22321
- required: project.templateSetVersion === "v3",
22322
- historical,
22323
- readPattern: read
22324
- });
22325
- return {
22326
- path: reportedPath,
22327
- valid: inspected.errors.length === 0 && inspected.stale.length === 0,
22328
- errors: inspected.errors,
22329
- stale: inspected.stale
22330
- };
22331
- });
22332
- return { learning, policy: { templateSetVersion: project.templateSetVersion ?? null, historicalPaths }, inputs: [...inputs].sort(([a], [b]) => a.localeCompare(b)).map(([path, sha2562]) => ({ path, sha256: sha2562 })) };
22333
- }
22334
-
22335
- // src/domain/staged-state.ts
22336
- import { existsSync as existsSync10, readdirSync as readdirSync8 } from "node:fs";
22337
- import { join as join9 } from "node:path";
22338
-
22339
- // src/domain/execution.ts
22340
- import { createHash as createHash3, randomUUID } from "node:crypto";
22341
- 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";
22342
- import { basename, dirname as dirname2, join as join7, resolve as resolve6 } from "node:path";
22343
-
22344
21772
  // src/domain/git.ts
22345
21773
  import { spawnSync } from "node:child_process";
22346
21774
  import { realpathSync } from "node:fs";
22347
- import { resolve as resolve4 } from "node:path";
21775
+ import { resolve as resolve3 } from "node:path";
22348
21776
  function gitRoot(projectRoot) {
22349
21777
  const root = realpathSync(safeProjectRoot(projectRoot));
22350
21778
  countGitProcess();
22351
21779
  const result = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: root, encoding: "utf8" });
22352
21780
  if (result.status !== 0) throw new Error((result.stderr || result.stdout || "project is not a Git worktree").trim());
22353
- const detected = realpathSync(resolve4(result.stdout.trim()));
21781
+ const detected = realpathSync(resolve3(result.stdout.trim()));
22354
21782
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
22355
21783
  return root;
22356
21784
  }
@@ -22365,9 +21793,9 @@ function readGitFileAtCommit(projectRoot, revision, path) {
22365
21793
  throw new Error(`Invalid Git file path: ${path}`);
22366
21794
  }
22367
21795
  const root = gitRoot(projectRoot);
22368
- const commit = resolveGitCommit(root, revision);
22369
- const result = spawnSync("git", ["show", `${commit}:${path}`], { cwd: root, encoding: "utf8" });
22370
- 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}`);
22371
21799
  return result.stdout;
22372
21800
  }
22373
21801
  function isGitAncestor(projectRoot, ancestor, descendant = "HEAD") {
@@ -22377,6 +21805,33 @@ function isGitAncestor(projectRoot, ancestor, descendant = "HEAD") {
22377
21805
  encoding: "utf8"
22378
21806
  }).status === 0;
22379
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
+ }
22380
21835
  function reachableGitCommits(projectRoot, revisions) {
22381
21836
  let root;
22382
21837
  try {
@@ -22438,6 +21893,230 @@ function readGitBlobs(projectRoot, requests) {
22438
21893
  return values;
22439
21894
  }
22440
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
+
22441
22120
  // src/domain/plan-provenance.ts
22442
22121
  function validatePlanProvenance(root, evidence) {
22443
22122
  const requests = evidence.map((entry) => `${entry.commit}:${entry.path}`);
@@ -22451,8 +22130,8 @@ function validatePlanProvenance(root, evidence) {
22451
22130
  }
22452
22131
 
22453
22132
  // src/domain/tracks-index.ts
22454
- import { existsSync as existsSync7, readFileSync as readFileSync3, readdirSync as readdirSync5 } from "node:fs";
22455
- 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";
22456
22135
  function buildTracks(tracks) {
22457
22136
  const lines = [
22458
22137
  "# Tracks",
@@ -22469,22 +22148,22 @@ function buildTracks(tracks) {
22469
22148
  `;
22470
22149
  }
22471
22150
  function renderTracksWithState(projectRoot, statePath, proposedState) {
22472
- const root = join6(safeProjectRoot(projectRoot), ".cadre");
22473
- const resolvedStatePath = resolve5(statePath);
22151
+ const root = join3(safeProjectRoot(projectRoot), ".cadre");
22152
+ const resolvedStatePath = resolve4(statePath);
22474
22153
  const tracks = [];
22475
22154
  const ids = /* @__PURE__ */ new Set();
22476
22155
  let overrideFound = false;
22477
22156
  for (const directory of ["tracks", "archive"]) {
22478
- const directoryRoot = join6(root, directory);
22479
- if (!existsSync7(directoryRoot)) continue;
22480
- for (const entry of readdirSync5(directoryRoot, { withFileTypes: true }).filter((candidate) => candidate.isDirectory()).sort((left, right) => left.name.localeCompare(right.name))) {
22481
- 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");
22482
22161
  let state;
22483
- if (resolve5(path) === resolvedStatePath) {
22162
+ if (resolve4(path) === resolvedStatePath) {
22484
22163
  overrideFound = true;
22485
22164
  state = proposedState;
22486
22165
  } else {
22487
- state = JSON.parse(readFileSync3(path, "utf8"));
22166
+ state = JSON.parse(readFileSync2(path, "utf8"));
22488
22167
  }
22489
22168
  const id2 = String(state.trackId ?? "");
22490
22169
  if (!id2 || id2 !== entry.name) throw new Error(`invalid track identity at ${path}`);
@@ -22501,10 +22180,10 @@ function renderTracksWithState(projectRoot, statePath, proposedState) {
22501
22180
  }
22502
22181
  if (!overrideFound) throw new Error("execution track state is outside the active track index");
22503
22182
  tracks.sort((left, right) => left.id.localeCompare(right.id));
22504
- const tracksPath = join6(root, "tracks.md");
22183
+ const tracksPath = join3(root, "tracks.md");
22505
22184
  return {
22506
22185
  tracksPath,
22507
- tracksBody: readFileSync3(tracksPath, "utf8"),
22186
+ tracksBody: readFileSync2(tracksPath, "utf8"),
22508
22187
  tracksContent: buildTracks(tracks)
22509
22188
  };
22510
22189
  }
@@ -22522,10 +22201,12 @@ var EXECUTION_NODE_STATUSES = [
22522
22201
  "completed",
22523
22202
  "blocked"
22524
22203
  ];
22525
- var EXECUTION_APPROVAL_MODES = ["governed", "phase", "autonomous"];
22526
22204
  function deriveExecutionStartInput(input) {
22527
22205
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
22528
- 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";
22529
22210
  return {
22530
22211
  projectRoot: input.projectRoot,
22531
22212
  trackId: input.trackId,
@@ -22533,7 +22214,7 @@ function deriveExecutionStartInput(input) {
22533
22214
  requestedMode,
22534
22215
  effectiveMode: requestedMode,
22535
22216
  ...input.approvalMode ? { approvalMode: input.approvalMode } : {},
22536
- maxWorkers: input.maxWorkers ?? 3,
22217
+ maxWorkers: input.maxWorkers ?? previous?.maxWorkers ?? 3,
22537
22218
  baseCommit: resolveGitCommit(input.projectRoot),
22538
22219
  approvedAt: startedAt
22539
22220
  };
@@ -22549,24 +22230,24 @@ function writeJournalAtomically(path, journal) {
22549
22230
  `);
22550
22231
  }
22551
22232
  function writeTextAtomically(path, content) {
22552
- if (existsSync8(path) && readFileSync4(path, "utf8") === content) return;
22553
- 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`);
22554
22235
  try {
22555
- writeFileSync2(temporaryPath, content, { flag: "wx" });
22556
- renameSync2(temporaryPath, path);
22236
+ writeFileSync(temporaryPath, content, { flag: "wx" });
22237
+ renameSync(temporaryPath, path);
22557
22238
  } finally {
22558
- if (existsSync8(temporaryPath)) unlinkSync2(temporaryPath);
22239
+ if (existsSync5(temporaryPath)) unlinkSync(temporaryPath);
22559
22240
  }
22560
22241
  }
22561
- function assertIdentifiers(trackId, executionId) {
22242
+ function assertIdentifiers(trackId, executionId2) {
22562
22243
  if (!TRACK_ID.test(trackId)) throw new Error("trackId must be lower-case hyphen-case");
22563
- 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");
22564
22245
  }
22565
22246
  function activeTrackRoot(projectRoot, trackId) {
22566
- return join7(safeProjectRoot(projectRoot), ".cadre", "tracks", trackId);
22247
+ return join4(safeProjectRoot(projectRoot), ".cadre", "tracks", trackId);
22567
22248
  }
22568
- function journalRelative(executionId) {
22569
- return `executions/execution-${executionId}.json`;
22249
+ function journalRelative(executionId2) {
22250
+ return `executions/execution-${executionId2}.json`;
22570
22251
  }
22571
22252
  function buildNodes(graph) {
22572
22253
  const nodes = {};
@@ -22623,12 +22304,20 @@ function previewExecutionStart(input) {
22623
22304
  throw new Error("an explicitly sequential execution cannot become parallel");
22624
22305
  }
22625
22306
  const trackRoot = activeTrackRoot(input.projectRoot, input.trackId);
22626
- const statePath = join7(trackRoot, "state.json");
22627
- const planPath = join7(trackRoot, "plan.md");
22628
- 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");
22629
22310
  const state = JSON.parse(stateBody);
22630
- const approvalMode = input.approvalMode ?? state.lastExecution?.approvalMode ?? "phase";
22631
- 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
+ }
22632
22321
  if (state.trackId !== input.trackId) throw new Error("track state does not match trackId");
22633
22322
  if (!["planned", "in_progress"].includes(state.status)) throw new Error(`track ${input.trackId} is not implementable from ${state.status}`);
22634
22323
  if (state.operation != null) throw new Error(`track ${input.trackId} already has an active operation`);
@@ -22652,7 +22341,7 @@ function previewExecutionStart(input) {
22652
22341
  if (evidenceErrors.length) throw new Error(evidenceErrors.join("\n"));
22653
22342
  const planRevision = graph.planRevision;
22654
22343
  const relativeJournal = journalRelative(input.executionId);
22655
- const journalPath = join7(trackRoot, relativeJournal);
22344
+ const journalPath = join4(trackRoot, relativeJournal);
22656
22345
  const journal = {
22657
22346
  schemaVersion: 1,
22658
22347
  executionId: input.executionId,
@@ -22662,6 +22351,7 @@ function previewExecutionStart(input) {
22662
22351
  requestedMode: input.requestedMode,
22663
22352
  effectiveMode: input.effectiveMode,
22664
22353
  approvalMode,
22354
+ approvalPolicyVersion: APPROVAL_POLICY_VERSION,
22665
22355
  maxWorkers: input.maxWorkers,
22666
22356
  planRevision,
22667
22357
  planCommit: state.commits.plan,
@@ -22673,11 +22363,11 @@ function previewExecutionStart(input) {
22673
22363
  headCommit: null,
22674
22364
  nodes: buildNodes(graph)
22675
22365
  };
22676
- if (existsSync8(journalPath)) {
22677
- 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");
22678
22368
  let existing;
22679
22369
  try {
22680
- existing = JSON.parse(readFileSync4(journalPath, "utf8"));
22370
+ existing = JSON.parse(readFileSync3(journalPath, "utf8"));
22681
22371
  } catch (error51) {
22682
22372
  throw new Error(`existing execution journal is invalid: ${error51 instanceof Error ? error51.message : String(error51)}`);
22683
22373
  }
@@ -22697,6 +22387,7 @@ function previewExecutionStart(input) {
22697
22387
  journal: relativeJournal,
22698
22388
  mode: input.effectiveMode,
22699
22389
  approvalMode,
22390
+ approvalPolicyVersion: APPROVAL_POLICY_VERSION,
22700
22391
  graphDigest: graph.digest,
22701
22392
  planRevision
22702
22393
  };
@@ -22704,42 +22395,56 @@ function previewExecutionStart(input) {
22704
22395
  ...state,
22705
22396
  status: "in_progress",
22706
22397
  checkpoint: "executing",
22707
- 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
+ } } : {}
22708
22408
  };
22709
22409
  return {
22710
22410
  journalPath,
22711
22411
  journal,
22712
22412
  statePath,
22713
22413
  state: proposedState,
22714
- digest: hash2({ stateBody, planBody: readFileSync4(planPath, "utf8"), journal, state: proposedState })
22414
+ digest: hash2({ stateBody, planBody: readFileSync3(planPath, "utf8"), journal, state: proposedState })
22715
22415
  };
22716
22416
  }
22717
22417
  function applyExecutionStart(input, proposalDigest, preparedProposal) {
22718
22418
  const proposal = preparedProposal ?? previewExecutionStart(input);
22719
22419
  if (proposal.digest !== proposalDigest) throw new Error("execution proposal is stale; preview it again");
22720
- if (lstatSync4(proposal.statePath).isSymbolicLink()) throw new Error("refusing to start execution through a state symbolic link");
22721
- mkdirSync2(dirname2(proposal.journalPath), { recursive: true });
22722
- if (!existsSync8(proposal.journalPath)) {
22723
- 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)}
22724
22424
  `);
22725
22425
  }
22726
- writeFileSync2(proposal.statePath, `${JSON.stringify(proposal.state, null, 2)}
22426
+ writeFileSync(proposal.statePath, `${JSON.stringify(proposal.state, null, 2)}
22727
22427
  `);
22728
22428
  return { ...proposal, derivedStatus: deriveExecutionStatus(proposal.journal) };
22729
22429
  }
22730
- function executionPaths(projectRoot, trackId, executionId) {
22731
- assertIdentifiers(trackId, executionId);
22430
+ function executionPaths(projectRoot, trackId, executionId2) {
22431
+ assertIdentifiers(trackId, executionId2);
22732
22432
  const trackRoot = activeTrackRoot(projectRoot, trackId);
22733
- return { statePath: join7(trackRoot, "state.json"), journalPath: join7(trackRoot, journalRelative(executionId)) };
22433
+ return { statePath: join4(trackRoot, "state.json"), journalPath: join4(trackRoot, journalRelative(executionId2)) };
22734
22434
  }
22735
- function readExecution(projectRoot, trackId, executionId) {
22736
- assertIdentifiers(trackId, executionId);
22435
+ function readExecution(projectRoot, trackId, executionId2) {
22436
+ assertIdentifiers(trackId, executionId2);
22737
22437
  const root = safeProjectRoot(projectRoot);
22738
- const locations = ["tracks", "archive"].filter((location2) => existsSync8(join7(root, ".cadre", location2, trackId, journalRelative(executionId))));
22739
- 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.`);
22740
- 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.`);
22741
22441
  const location = locations[0];
22742
- 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);
22743
22448
  }
22744
22449
  var ALLOWED_TRANSITIONS = {
22745
22450
  pending: ["running", "blocked"],
@@ -22869,8 +22574,11 @@ function previewExecutionNodesUpdate(input) {
22869
22574
  throw new Error("updates must contain 1 through 128 ordered node transitions");
22870
22575
  }
22871
22576
  const { journalPath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
22872
- const currentBody = readFileSync4(journalPath, "utf8");
22577
+ const currentBody = readFileSync3(journalPath, "utf8");
22873
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
+ }
22874
22582
  for (const update of input.updates) applyNodeTransition(journal, update);
22875
22583
  return { path: journalPath, journal, digest: hash2({ currentBody, journal }) };
22876
22584
  }
@@ -22974,7 +22682,8 @@ function compactExecutionStatus(journal, nodeId) {
22974
22682
  checkpoint: journal.checkpoint,
22975
22683
  requestedMode: journal.requestedMode,
22976
22684
  effectiveMode: journal.effectiveMode,
22977
- approvalMode: journal.approvalMode,
22685
+ approvalMode: journal.approvalMode ?? "governed",
22686
+ approvalPolicyVersion: journal.approvalPolicyVersion ?? 1,
22978
22687
  maxWorkers: journal.maxWorkers,
22979
22688
  planRevision: journal.planRevision,
22980
22689
  startedAt: journal.startedAt,
@@ -22986,8 +22695,8 @@ function compactExecutionStatus(journal, nodeId) {
22986
22695
  derivedStatus
22987
22696
  };
22988
22697
  }
22989
- function executionStatus(projectRoot, trackId, executionId) {
22990
- const journal = readExecution(projectRoot, trackId, executionId);
22698
+ function executionStatus(projectRoot, trackId, executionId2) {
22699
+ const journal = readExecution(projectRoot, trackId, executionId2);
22991
22700
  return { journal, ...deriveExecutionStatus(journal) };
22992
22701
  }
22993
22702
  var EXECUTION_CHECKPOINT_EVENTS = [
@@ -23004,7 +22713,7 @@ function checkpointUpdates(journal, input) {
23004
22713
  if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
23005
22714
  const evidence = input.verification?.trim();
23006
22715
  const authorization = input.authorization?.trim();
23007
- const commit = input.commit;
22716
+ const commit2 = input.commit;
23008
22717
  const updates = [];
23009
22718
  const start = () => {
23010
22719
  if (node.status === "pending" || node.status === "blocked") {
@@ -23033,7 +22742,7 @@ function checkpointUpdates(journal, input) {
23033
22742
  start();
23034
22743
  break;
23035
22744
  case "record_commit":
23036
- if (!commit || !evidence || !authorization) {
22745
+ if (!commit2 || !evidence || !authorization) {
23037
22746
  throw new Error("record_commit requires commit, verification, and authorization");
23038
22747
  }
23039
22748
  if (node.status === "running") {
@@ -23041,20 +22750,20 @@ function checkpointUpdates(journal, input) {
23041
22750
  } else if (node.status !== "awaiting_approval") {
23042
22751
  throw new Error(`${node.id} cannot record a commit from ${node.status}`);
23043
22752
  }
23044
- updates.push({ nodeId: node.id, status: "committed", workerCommit: commit, approval: authorization });
22753
+ updates.push({ nodeId: node.id, status: "committed", workerCommit: commit2, approval: authorization });
23045
22754
  break;
23046
22755
  case "record_integration":
23047
- 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");
23048
22757
  if (node.status === "committed") updates.push({ nodeId: node.id, status: "integrating" });
23049
22758
  else if (node.status !== "integrating" && node.status !== "conflicted" && node.status !== "integrated") {
23050
22759
  throw new Error(`${node.id} cannot record integration from ${node.status}`);
23051
22760
  }
23052
22761
  if (node.status !== "integrated") {
23053
- updates.push({ nodeId: node.id, status: "integrated", mergeCommit: commit, verification: evidence });
22762
+ updates.push({ nodeId: node.id, status: "integrated", mergeCommit: commit2, verification: evidence });
23054
22763
  }
23055
22764
  break;
23056
22765
  case "record_verification":
23057
- if (node.kind !== "manual-verification" || !commit || !evidence || !authorization) {
22766
+ if (node.kind !== "manual-verification" || !commit2 || !evidence || !authorization) {
23058
22767
  throw new Error("record_verification requires a manual-verification node, commit, verification, and authorization");
23059
22768
  }
23060
22769
  if (node.status === "pending") updates.push({ nodeId: node.id, status: "running" });
@@ -23062,9 +22771,9 @@ function checkpointUpdates(journal, input) {
23062
22771
  throw new Error(`${node.id} cannot record verification from ${node.status}`);
23063
22772
  }
23064
22773
  if (node.status !== "awaiting_manual_verification") {
23065
- 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 });
23066
22775
  }
23067
- updates.push({ nodeId: node.id, status: "completed", workerCommit: commit, approval: authorization });
22776
+ updates.push({ nodeId: node.id, status: "completed", workerCommit: commit2, approval: authorization });
23068
22777
  break;
23069
22778
  case "complete":
23070
22779
  if (node.status === "committed") updates.push({
@@ -23078,14 +22787,14 @@ function checkpointUpdates(journal, input) {
23078
22787
  ...evidence ? { verification: evidence } : {}
23079
22788
  });
23080
22789
  else if (node.kind === "phase" && node.status === "running") {
23081
- if (!commit || !evidence || !authorization) {
22790
+ if (!commit2 || !evidence || !authorization) {
23082
22791
  throw new Error("completing a running phase requires commit, verification, and authorization");
23083
22792
  }
23084
22793
  updates.push(
23085
22794
  { nodeId: node.id, status: "awaiting_approval", verification: evidence },
23086
- { nodeId: node.id, status: "committed", workerCommit: commit, approval: authorization },
22795
+ { nodeId: node.id, status: "committed", workerCommit: commit2, approval: authorization },
23087
22796
  { nodeId: node.id, status: "integrating" },
23088
- { nodeId: node.id, status: "integrated", mergeCommit: commit },
22797
+ { nodeId: node.id, status: "integrated", mergeCommit: commit2 },
23089
22798
  { nodeId: node.id, status: "completed" }
23090
22799
  );
23091
22800
  } else throw new Error(`${node.id} cannot complete from ${node.status}`);
@@ -23172,7 +22881,7 @@ function deriveExecutionFinishInput(input) {
23172
22881
  return { ...input, headCommit: journal.headCommit, completedAt: journal.completedAt };
23173
22882
  }
23174
22883
  const { statePath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
23175
- const state = JSON.parse(readFileSync4(statePath, "utf8"));
22884
+ const state = JSON.parse(readFileSync3(statePath, "utf8"));
23176
22885
  const priorHead = state.lastExecution?.headCommit;
23177
22886
  const priorCompletedAt = state.lastExecution?.completedAt;
23178
22887
  if (state.lastExecution?.executionId === input.executionId && typeof priorHead === "string" && typeof priorCompletedAt === "string") {
@@ -23215,12 +22924,14 @@ function previewExecutionFinish(input) {
23215
22924
  if (!SHA.test(input.headCommit)) throw new Error("headCommit must be a Git commit SHA");
23216
22925
  if (!Number.isFinite(Date.parse(input.completedAt))) throw new Error("completedAt must be an ISO timestamp");
23217
22926
  const { statePath, journalPath } = executionPaths(input.projectRoot, input.trackId, input.executionId);
23218
- const stateBody = readFileSync4(statePath, "utf8");
23219
- const journalBody = readFileSync4(journalPath, "utf8");
22927
+ const stateBody = readFileSync3(statePath, "utf8");
22928
+ const journalBody = readFileSync3(journalPath, "utf8");
23220
22929
  const state = JSON.parse(stateBody);
23221
22930
  const journal = JSON.parse(journalBody);
22931
+ resolveApprovalMode(journal);
23222
22932
  const operation = state.operation;
23223
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);
23224
22935
  if (!stateAlreadyCompleted && (operation?.action !== "implement" || operation.executionId !== input.executionId)) {
23225
22936
  throw new Error("track does not point to this implementation execution");
23226
22937
  }
@@ -23237,10 +22948,10 @@ function previewExecutionFinish(input) {
23237
22948
  ...Object.values(journal.nodes).flatMap((node) => [node.workerCommit, node.mergeCommit].filter(Boolean))
23238
22949
  ];
23239
22950
  const reachability = reachableGitCommits(input.projectRoot, commits);
23240
- const unreachable = reachability ? commits.filter((commit) => reachability.get(commit) === false) : [];
22951
+ const unreachable = reachability ? commits.filter((commit2) => reachability.get(commit2) === false) : [];
23241
22952
  if (unreachable.length) throw new Error(`execution contains unreachable commits: ${[...new Set(unreachable)].join(", ")}`);
23242
- const planPath = join7(dirname2(statePath), "plan.md");
23243
- const planBody = readFileSync4(planPath, "utf8");
22953
+ const planPath = join4(dirname(statePath), "plan.md");
22954
+ const planBody = readFileSync3(planPath, "utf8");
23244
22955
  const planErrors = [];
23245
22956
  const graph = parsePlanContent(planBody, planPath, planErrors);
23246
22957
  validatePlanGraph(planPath, graph, "in_progress", planErrors);
@@ -23254,8 +22965,8 @@ function previewExecutionFinish(input) {
23254
22965
  validatePlanGraph(planPath, completedGraph, "ready_for_review", completedPlanErrors);
23255
22966
  if (completedPlanErrors.length) throw new Error(completedPlanErrors.join("\n"));
23256
22967
  if (completedGraph.digest !== journal.graphDigest) throw new Error("completed plan changed the approved execution graph");
23257
- const worktreeRoot = join7(safeProjectRoot(input.projectRoot), ".cadre", ".worktrees", input.trackId, input.executionId);
23258
- 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) {
23259
22970
  throw new Error(`execution still has managed worktrees under ${worktreeRoot}`);
23260
22971
  }
23261
22972
  const completedJournal = {
@@ -23270,10 +22981,12 @@ function previewExecutionFinish(input) {
23270
22981
  status: "ready_for_review",
23271
22982
  checkpoint: "ready_for_review",
23272
22983
  operation: null,
22984
+ ...state.autonomousReview && journal.approvalMode === "autonomous" ? { autonomousReview: { ...state.autonomousReview, checkpoint: "reviewing" } } : {},
23273
22985
  lastExecution: {
23274
22986
  executionId: input.executionId,
23275
22987
  journal: journalRelative(input.executionId),
23276
- approvalMode: journal.approvalMode,
22988
+ approvalMode: journal.approvalMode ?? "governed",
22989
+ approvalPolicyVersion: journal.approvalPolicyVersion ?? 1,
23277
22990
  planRevision: journal.planRevision,
23278
22991
  graphDigest: journal.graphDigest,
23279
22992
  headCommit: input.headCommit,
@@ -23309,7 +23022,7 @@ function previewExecutionFinish(input) {
23309
23022
  function applyExecutionFinish(input, proposalDigest, preparedProposal) {
23310
23023
  const proposal = preparedProposal ?? previewExecutionFinish(input);
23311
23024
  if (proposal.digest !== proposalDigest) throw new Error("execution completion proposal is stale; preview it again");
23312
- 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()) {
23313
23026
  throw new Error("refusing to complete execution through a symbolic link");
23314
23027
  }
23315
23028
  writeTextAtomically(proposal.journalPath, `${JSON.stringify(proposal.journal, null, 2)}
@@ -23340,12 +23053,12 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23340
23053
  errors.push(`${state.trackId}: invalid execution journal path`);
23341
23054
  return;
23342
23055
  }
23343
- const path = resolve6(trackRoot, relative7);
23344
- if (!path.startsWith(`${resolve6(trackRoot)}/`)) {
23056
+ const path = resolve5(trackRoot, relative7);
23057
+ if (!path.startsWith(`${resolve5(trackRoot)}/`)) {
23345
23058
  errors.push(`${state.trackId}: execution journal escapes track root`);
23346
23059
  return;
23347
23060
  }
23348
- if (!(inspection?.exists ?? existsSync8)(path)) {
23061
+ if (!(inspection?.exists ?? existsSync5)(path)) {
23349
23062
  errors.push(`${state.trackId}: missing execution journal ${relative7}`);
23350
23063
  return;
23351
23064
  }
@@ -23368,6 +23081,7 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23368
23081
  if (!EXECUTION_APPROVAL_MODES.includes(journal.approvalMode ?? "governed")) {
23369
23082
  errors.push(`${state.trackId}: invalid execution approval mode`);
23370
23083
  }
23084
+ if (journal.approvalPolicyVersion != null && ![1, APPROVAL_POLICY_VERSION].includes(journal.approvalPolicyVersion)) errors.push(`${state.trackId}: unsupported approvalPolicyVersion`);
23371
23085
  if (!Number.isInteger(journal.maxWorkers) || journal.maxWorkers < 1 || journal.maxWorkers > 32) errors.push(`${state.trackId}: invalid maxWorkers`);
23372
23086
  const requireCurrentGraph = operation?.action === "implement" || ["ready_for_review", "completed", "archived"].includes(state.status);
23373
23087
  if (graph && requireCurrentGraph && (journal.graphDigest !== graph.digest || journal.planRevision !== graph.planRevision)) {
@@ -23416,7 +23130,7 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23416
23130
  errors.push(`${state.trackId}: integrated execution node ${id2} lacks merge commit evidence`);
23417
23131
  }
23418
23132
  if (node.kind === "manual-verification" && node.status === "completed" && !node.approval) {
23419
- errors.push(`${state.trackId}: completed manual verification ${id2} lacks human approval`);
23133
+ errors.push(`${state.trackId}: completed manual verification ${id2} lacks verification authorization`);
23420
23134
  }
23421
23135
  if (node.kind === "phase" && node.status === "completed") {
23422
23136
  const incompleteTasks = Object.values(journal.nodes).filter(
@@ -23436,11 +23150,11 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23436
23150
  }
23437
23151
  if (operation?.action === "implement" && journal.status !== "in_progress") errors.push(`${state.trackId}: active implement operation requires an in-progress journal`);
23438
23152
  if (operation?.action === "implement") {
23439
- 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")) {
23440
23154
  errors.push(`${state.trackId}: implement operation does not match its execution journal`);
23441
23155
  }
23442
23156
  } else if (state.lastExecution) {
23443
- 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")) {
23444
23158
  errors.push(`${state.trackId}: lastExecution does not match its execution journal`);
23445
23159
  }
23446
23160
  }
@@ -23455,16 +23169,575 @@ function validateExecutionJournal(trackRoot, state, graph, errors, inspection) {
23455
23169
  }
23456
23170
  }
23457
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
+
23458
23731
  // src/domain/state.ts
23459
23732
  import { createHash as createHash4 } from "node:crypto";
23460
23733
  import { existsSync as existsSync9, lstatSync as lstatSync5, readdirSync as readdirSync7, writeFileSync as writeFileSync3 } from "node:fs";
23461
23734
  import { isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve7 } from "node:path";
23462
23735
 
23463
23736
  // src/domain/version.ts
23464
- var CADRE_RUNTIME_VERSION = "3.7.0";
23465
- var LEGACY_RUNTIME_VERSIONS = ["3.6.0", "3.5.1", "3.5.0", "3.4.0", "3.3.0"];
23466
- var TEMPLATE_SET_VERSION = "v3";
23467
- 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"];
23468
23741
 
23469
23742
  // src/domain/state.ts
23470
23743
  function collectCommitReferences(value, owner, references, commitContext = false) {
@@ -23527,6 +23800,8 @@ function validateOperation(operation, owner, errors, artifactRoot, artifactProgr
23527
23800
  if (!operation.expectedCommit) errors.push(`${owner}: operation expectedCommit is required`);
23528
23801
  if (!Array.isArray(operation.approvedArtifacts) || !operation.approvedArtifacts.length) {
23529
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`);
23530
23805
  }
23531
23806
  if (!operation.approvedAt) errors.push(`${owner}: operation approvedAt is required`);
23532
23807
  if (operation.approvalDigest !== void 0 && !/^[0-9a-f]{64}$/.test(operation.approvalDigest)) {
@@ -23625,7 +23900,7 @@ function validateImplementOperation(state, owner, errors) {
23625
23900
  errors.push(`${owner}: implement journal path is invalid`);
23626
23901
  }
23627
23902
  if (!["parallel", "sequential"].includes(String(operation.mode ?? ""))) errors.push(`${owner}: implement mode is invalid`);
23628
- if (!["governed", "phase", "autonomous"].includes(String(operation.approvalMode ?? "governed"))) {
23903
+ if (!["governed", "phase", "track", "autonomous"].includes(String(operation.approvalMode ?? "governed"))) {
23629
23904
  errors.push(`${owner}: implement approvalMode is invalid`);
23630
23905
  }
23631
23906
  if (!/^[0-9a-f]{64}$/.test(String(operation.graphDigest ?? ""))) errors.push(`${owner}: implement graphDigest is invalid`);
@@ -23648,10 +23923,10 @@ function validateRevertOperation(state, owner, errors) {
23648
23923
  if (!operation.targetId || typeof operation.targetId !== "string") {
23649
23924
  errors.push(`${owner}: revert targetId is required`);
23650
23925
  }
23651
- 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)))) {
23652
23927
  errors.push(`${owner}: revert commits must be a non-empty array of Git commit SHAs`);
23653
23928
  }
23654
- 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)))) {
23655
23930
  errors.push(`${owner}: revert revertCommits must be an array of Git commit SHAs`);
23656
23931
  }
23657
23932
  }
@@ -23893,6 +24168,7 @@ function validateProjectSnapshot(projectRoot) {
23893
24168
  const state = states.get(track.id);
23894
24169
  collectCommitReferences(state, `${track.id}/state.json`, commitReferences);
23895
24170
  const trackRoot = join8(root, track.location);
24171
+ validateTrackApprovalPolicy(state, errors, warnings);
23896
24172
  if (state.schemaVersion !== 1) errors.push(`${track.id}: unsupported state schemaVersion`);
23897
24173
  if (!state.title || typeof state.title !== "string") errors.push(`${track.id}: title is required`);
23898
24174
  if (!TRACK_TYPES.has(track.type)) errors.push(`${track.id}: type must be feature or bug`);
@@ -23948,7 +24224,7 @@ function validateProjectSnapshot(projectRoot) {
23948
24224
  path: learningPath,
23949
24225
  body: readInspectionText(learningPath, "utf8"),
23950
24226
  graph: planGraph,
23951
- 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),
23952
24228
  historical: ["completed", "archived"].includes(track.status),
23953
24229
  readPattern: (path) => readSafeArtifact(projectRoot, `.cadre/${path}`)
23954
24230
  });
@@ -24071,13 +24347,21 @@ function writeTracks(projectRoot, proposalDigest, preparedPreview) {
24071
24347
  }
24072
24348
 
24073
24349
  // src/domain/staged-state.ts
24074
- function validateStagedState(root, candidateId, files) {
24350
+ function validateStagedState(root, candidateId, files, planValidations = []) {
24075
24351
  const canonical = (path) => candidateArtifactPath(candidateId, path);
24352
+ const targets = new Map(planValidations.map((validation) => [canonical(validation.path), validation.targetStatus]));
24076
24353
  const overlay = new Map(files.map((file2) => [canonical(file2.path), file2.content]));
24077
24354
  if (overlay.size !== files.length) throw new Error("Candidate paths alias the same canonical artifact; use one path per artifact");
24078
24355
  const read = (path) => overlay.get(path) ?? readSafeArtifact(root, `.cadre/${path}`);
24079
24356
  const parents = /* @__PURE__ */ new Set();
24080
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
+ }
24081
24365
  if (/(?:^|\/)revisions\//.test(file2.path) && !/(?:^|\/)revisions\/revision-[^/]+\.md$/.test(file2.path)) {
24082
24366
  throw new Error(`Invalid revision artifact ${file2.path}; use revisions/revision-<id>.md before approval`);
24083
24367
  }
@@ -24114,15 +24398,39 @@ function validateStagedState(root, candidateId, files) {
24114
24398
  for (const key2 of overlay.keys()) if (key2.startsWith(`${parent}/executions/`)) paths.add(key2.slice(`${parent}/executions/`.length));
24115
24399
  const errors = [];
24116
24400
  validateTrackOperation(state, path, errors);
24401
+ validateTrackApprovalPolicy(state, errors);
24117
24402
  const key = (absolute) => absolute.slice(join9(root, ".cadre").length + 1);
24118
24403
  const plan = `${parent}/plan.md`;
24119
- const graph = overlay.has(plan) || existsSync10(join9(root, ".cadre", plan)) ? parsePlanContent(read(plan), plan) : null;
24120
- if (graph) validatePlanGraph(plan, graph, state.status, errors);
24121
- validateExecutionJournal(join9(root, ".cadre", parent), state, graph, errors, {
24404
+ const graph = overlay.has(plan) || existsSync10(join9(root, ".cadre", plan)) ? parsePlanContent(read(plan), plan, errors) : null;
24405
+ const target = targets.get(plan) ?? state.status;
24406
+ const inspection = {
24122
24407
  read: (absolute) => JSON.parse(read(key(absolute))),
24123
24408
  exists: (absolute) => overlay.has(key(absolute)) || existsSync10(absolute),
24124
24409
  journalPaths: [...paths]
24125
- });
24410
+ };
24411
+ if (overlay.has(path) && target !== state.status) {
24412
+ errors.push(`${path}: staged status ${state.status} conflicts with plan targetStatus ${target}`);
24413
+ }
24414
+ let proposedState = state;
24415
+ if (!overlay.has(path) && target !== state.status) {
24416
+ const workflow = candidateId.split("-")[0];
24417
+ const allowed = workflow === "review" && state.status === "ready_for_review" && target === "in_progress" || workflow === "revise" && ["planned", "in_progress", "ready_for_review"].includes(state.status) && ["planned", "in_progress"].includes(target) || workflow === "track" && ["drafting-spec", "drafting-plan"].includes(state.status) && target === "planned";
24418
+ if (!allowed) errors.push(`${path}: cannot infer ${state.status} -> ${target}; include the proposed state in the candidate`);
24419
+ else {
24420
+ const previous = ["drafting-spec", "drafting-plan"].includes(state.status) ? null : parsePlanContent(readSafeArtifact(root, `.cadre/${plan}`), plan, errors);
24421
+ if (previous) validatePlanGraph(plan, previous, state.status, errors);
24422
+ validateExecutionJournal(join9(root, ".cadre", parent), state, previous, errors);
24423
+ proposedState = { ...state, status: target };
24424
+ }
24425
+ }
24426
+ if (existsSync10(join9(root, ".cadre", path))) {
24427
+ const previous = JSON.parse(readSafeArtifact(root, `.cadre/${path}`));
24428
+ if (["completed", "archived"].includes(previous.status) && !["completed", "archived"].includes(target)) {
24429
+ errors.push(`${path}: terminal tracks cannot be reopened; propose a successor track`);
24430
+ }
24431
+ }
24432
+ if (graph) validatePlanGraph(plan, graph, target, errors);
24433
+ validateExecutionJournal(join9(root, ".cadre", parent), proposedState, graph, errors, inspection);
24126
24434
  if (errors.length) throw new Error(`${path}: ${errors.join("; ")}`);
24127
24435
  }
24128
24436
  }
@@ -24163,6 +24471,9 @@ function summarizeTrackState(state) {
24163
24471
  } : null,
24164
24472
  lastExecution: state.lastExecution ?? null,
24165
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,
24166
24477
  historyCount: Array.isArray(state.history) ? state.history.length : 0,
24167
24478
  reviewCycleCount: state.reviewCycles?.length ?? 0
24168
24479
  };
@@ -24188,11 +24499,11 @@ function trackSources(projectRoot, location) {
24188
24499
  }
24189
24500
  function fullProjectTracks(root, tracks, states, plans) {
24190
24501
  return tracks.map((track) => {
24191
- 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;
24192
24503
  let execution = null, executionError = null;
24193
- if (typeof executionId === "string") {
24504
+ if (typeof executionId2 === "string") {
24194
24505
  try {
24195
- execution = readExecution(root, track.id, executionId);
24506
+ execution = readExecution(root, track.id, executionId2);
24196
24507
  } catch (error51) {
24197
24508
  executionError = String(error51);
24198
24509
  }
@@ -31653,7 +31964,7 @@ var Protocol = class {
31653
31964
  return;
31654
31965
  }
31655
31966
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
31656
- await new Promise((resolve14) => setTimeout(resolve14, pollInterval));
31967
+ await new Promise((resolve13) => setTimeout(resolve13, pollInterval));
31657
31968
  options?.signal?.throwIfAborted();
31658
31969
  }
31659
31970
  } catch (error51) {
@@ -31670,7 +31981,7 @@ var Protocol = class {
31670
31981
  */
31671
31982
  request(request, resultSchema, options) {
31672
31983
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
31673
- return new Promise((resolve14, reject) => {
31984
+ return new Promise((resolve13, reject) => {
31674
31985
  const earlyReject = (error51) => {
31675
31986
  reject(error51);
31676
31987
  };
@@ -31748,7 +32059,7 @@ var Protocol = class {
31748
32059
  if (!parseResult.success) {
31749
32060
  reject(parseResult.error);
31750
32061
  } else {
31751
- resolve14(parseResult.data);
32062
+ resolve13(parseResult.data);
31752
32063
  }
31753
32064
  } catch (error51) {
31754
32065
  reject(error51);
@@ -32009,12 +32320,12 @@ var Protocol = class {
32009
32320
  }
32010
32321
  } catch {
32011
32322
  }
32012
- return new Promise((resolve14, reject) => {
32323
+ return new Promise((resolve13, reject) => {
32013
32324
  if (signal.aborted) {
32014
32325
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
32015
32326
  return;
32016
32327
  }
32017
- const timeoutId = setTimeout(resolve14, interval);
32328
+ const timeoutId = setTimeout(resolve13, interval);
32018
32329
  signal.addEventListener("abort", () => {
32019
32330
  clearTimeout(timeoutId);
32020
32331
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -33105,7 +33416,7 @@ var McpServer = class {
33105
33416
  let task = createTaskResult.task;
33106
33417
  const pollInterval = task.pollInterval ?? 5e3;
33107
33418
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
33108
- await new Promise((resolve14) => setTimeout(resolve14, pollInterval));
33419
+ await new Promise((resolve13) => setTimeout(resolve13, pollInterval));
33109
33420
  const updatedTask = await extra.taskStore.getTask(taskId);
33110
33421
  if (!updatedTask) {
33111
33422
  throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
@@ -33769,12 +34080,12 @@ var StdioServerTransport = class {
33769
34080
  this.onclose?.();
33770
34081
  }
33771
34082
  send(message) {
33772
- return new Promise((resolve14) => {
34083
+ return new Promise((resolve13) => {
33773
34084
  const json3 = serializeMessage(message);
33774
34085
  if (this._stdout.write(json3)) {
33775
- resolve14();
34086
+ resolve13();
33776
34087
  } else {
33777
- this._stdout.once("drain", resolve14);
34088
+ this._stdout.once("drain", resolve13);
33778
34089
  }
33779
34090
  });
33780
34091
  }
@@ -33782,9 +34093,9 @@ var StdioServerTransport = class {
33782
34093
 
33783
34094
  // src/mcp/server.ts
33784
34095
  import { createHash as createHash9 } from "node:crypto";
33785
- import { existsSync as existsSync16, readFileSync as readFileSync9, readdirSync as readdirSync14 } from "node:fs";
33786
- import { join as join15, resolve as resolve13 } from "node:path";
33787
- 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";
33788
34099
 
33789
34100
  // src/domain/init.ts
33790
34101
  import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
@@ -34193,8 +34504,8 @@ function applyProjectInitCandidate(input, proposalDigest) {
34193
34504
  }
34194
34505
  return applyProjectInitAtRoot(materialized, proposal);
34195
34506
  }
34196
- function recordSetupCommit(projectRootInput, commit) {
34197
- 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");
34198
34509
  const root = safeProjectRoot(projectRootInput);
34199
34510
  const path = join11(root, ".cadre", "project.json");
34200
34511
  const project = JSON.parse(readFileSync6(path, "utf8"));
@@ -34212,15 +34523,15 @@ function recordSetupCommit(projectRootInput, commit) {
34212
34523
  if (hash3(readFileSync6(artifactPath, "utf8")) !== artifact2.sha256) {
34213
34524
  throw new Error(`Approved setup artifact changed before commit recording: ${artifact2.path}`);
34214
34525
  }
34215
- if (hash3(readGitFileAtCommit(root, commit, `.cadre/${artifact2.path}`)) !== artifact2.sha256) {
34526
+ if (hash3(readGitFileAtCommit(root, commit2, `.cadre/${artifact2.path}`)) !== artifact2.sha256) {
34216
34527
  throw new Error(`Setup commit does not contain the approved artifact: ${artifact2.path}`);
34217
34528
  }
34218
34529
  }
34219
34530
  project.setup.status = "completed";
34220
34531
  project.setup.checkpoint = "completed";
34221
- project.setup.commit = commit;
34532
+ project.setup.commit = commit2;
34222
34533
  project.setup.operation = null;
34223
- project.history = [...project.history ?? [], { action: "create", commit }];
34534
+ project.history = [...project.history ?? [], { action: "create", commit: commit2 }];
34224
34535
  writeFileSync4(path, `${JSON.stringify(project, null, 2)}
34225
34536
  `);
34226
34537
  return path;
@@ -34271,9 +34582,9 @@ function assertRepository(projectRoot) {
34271
34582
  if (detected !== root) throw new Error(`project root ${root} is not the Git worktree root ${detected}`);
34272
34583
  return root;
34273
34584
  }
34274
- function assertIds(trackId, executionId, nodeId, phaseId) {
34585
+ function assertIds(trackId, executionId2, nodeId, phaseId) {
34275
34586
  if (!TRACK_ID2.test(trackId)) throw new Error("invalid trackId");
34276
- if (!EXECUTION_ID2.test(executionId)) throw new Error("invalid executionId");
34587
+ if (!EXECUTION_ID2.test(executionId2)) throw new Error("invalid executionId");
34277
34588
  if (!PHASE_ID.test(nodeId) && !TASK_ID.test(nodeId)) throw new Error("nodeId must be a phase or task ID");
34278
34589
  if (phaseId != null && !PHASE_ID.test(phaseId)) throw new Error("invalid phaseId");
34279
34590
  const task = nodeId.match(TASK_ID);
@@ -34287,12 +34598,12 @@ function phaseForNode(nodeId) {
34287
34598
  function nodeSlug(nodeId) {
34288
34599
  return nodeId.toLowerCase().replace(".", "-");
34289
34600
  }
34290
- function worktreeIdentity(root, trackId, executionId, nodeId, phaseId) {
34291
- assertIds(trackId, executionId, nodeId, phaseId);
34601
+ function worktreeIdentity(root, trackId, executionId2, nodeId, phaseId) {
34602
+ assertIds(trackId, executionId2, nodeId, phaseId);
34292
34603
  const task = TASK_ID.test(nodeId);
34293
34604
  const resolvedPhaseId = phaseForNode(nodeId);
34294
- const relativePath = task ? `.cadre/.worktrees/${trackId}/${executionId}/tasks/${resolvedPhaseId}--${nodeSlug(nodeId)}` : `.cadre/.worktrees/${trackId}/${executionId}/phases/${nodeId}`;
34295
- 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)}`;
34296
34607
  return { path: join12(root, relativePath), relativePath, branch };
34297
34608
  }
34298
34609
  function branchHead(root, branch) {
@@ -34502,7 +34813,7 @@ function applyWorktreeCleanup(input, proposalDigest, preparedProposal) {
34502
34813
  return { removedPath: proposal.path, removedBranch: proposal.branch };
34503
34814
  }
34504
34815
  function integrationRequiresApproval(input) {
34505
- return (readExecution(input.projectRoot, input.trackId, input.executionId).approvalMode ?? "governed") === "governed";
34816
+ return resolveApprovalMode(readExecution(input.projectRoot, input.trackId, input.executionId)) === "governed";
34506
34817
  }
34507
34818
  function managedWorktreeStatus(projectRoot) {
34508
34819
  const root = assertRepository(projectRoot);
@@ -34581,10 +34892,10 @@ function deriveReviewCompleteInput(input) {
34581
34892
  const validation = requireCurrentProject(input.projectRoot);
34582
34893
  const state = validation.states.get(input.trackId);
34583
34894
  const reviewedHead = state?.lastExecution?.headCommit;
34584
- const executionId = state?.lastExecution?.executionId;
34895
+ const executionId2 = state?.lastExecution?.executionId;
34585
34896
  if (!reviewedHead || !SHA3.test(reviewedHead)) throw new Error(`${input.trackId} has no completed execution head`);
34586
- if (!executionId) throw new Error(`${input.trackId} has no completed execution journal`);
34587
- 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;
34588
34899
  if (execution.status !== "completed" || execution.headCommit !== reviewedHead || !SHA3.test(execution.baseCommit)) {
34589
34900
  throw new Error(`${input.trackId} completed execution evidence is inconsistent`);
34590
34901
  }
@@ -34593,13 +34904,13 @@ function deriveReviewCompleteInput(input) {
34593
34904
  }
34594
34905
  const acceptedRisks = (input.acceptedRisks ?? []).map((risk) => risk.trim()).filter(Boolean);
34595
34906
  const existingCycle = state.status === "completed" ? state.reviewCycles?.at(-1) : void 0;
34596
- 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;
34597
34908
  return {
34598
34909
  projectRoot: input.projectRoot,
34599
34910
  trackId: input.trackId,
34600
34911
  reviewedAt: typeof matchingCycle?.reviewedAt === "string" ? matchingCycle.reviewedAt : (/* @__PURE__ */ new Date()).toISOString(),
34601
34912
  reviewedHead,
34602
- commitRange: `${execution.baseCommit}..${reviewedHead}`,
34913
+ commitRange: `${state?.autonomousReview?.initialBaseCommit ?? execution.baseCommit}..${reviewedHead}`,
34603
34914
  approval: input.approval,
34604
34915
  ...acceptedRisks.length ? { acceptedRisks } : {}
34605
34916
  };
@@ -34624,6 +34935,17 @@ function previewReviewComplete(input) {
34624
34935
  if (!execution?.executionId || !execution.planRevision || !execution.graphDigest || execution.headCommit !== input.reviewedHead) {
34625
34936
  throw new Error("review evidence does not match the current completed execution");
34626
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
+ }
34627
34949
  const statePath = join13(cadreRoot(root), track.location, "state.json");
34628
34950
  const tracksPath = join13(cadreRoot(root), "tracks.md");
34629
34951
  const stateBody = readFileSync7(statePath, "utf8");
@@ -34648,6 +34970,7 @@ function previewReviewComplete(input) {
34648
34970
  ...current2,
34649
34971
  status: "completed",
34650
34972
  checkpoint: "completed",
34973
+ ...current2.autonomousReview ? { autonomousReview: { ...current2.autonomousReview, checkpoint: "completed" } } : {},
34651
34974
  reviewCycles: [...current2.reviewCycles ?? [], cycle]
34652
34975
  };
34653
34976
  const tracks = validation.tracks.map((candidate) => candidate.id === input.trackId ? { ...candidate, ...state, id: input.trackId, location: `tracks/${input.trackId}` } : candidate);
@@ -35596,6 +35919,7 @@ var executionStatusSchema = external_exports.strictObject({
35596
35919
  requestedMode: external_exports.enum(["parallel", "sequential"]),
35597
35920
  effectiveMode: external_exports.enum(["parallel", "sequential"]),
35598
35921
  approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES),
35922
+ approvalPolicyVersion: external_exports.number().int().optional(),
35599
35923
  maxWorkers: external_exports.number().int(),
35600
35924
  planRevision: external_exports.number().int(),
35601
35925
  startedAt: external_exports.string(),
@@ -35691,6 +36015,7 @@ var stagedTrackStatusSchema = external_exports.strictObject({
35691
36015
  nextAction: external_exports.string()
35692
36016
  });
35693
36017
  var canonicalTrackStatusShape = {
36018
+ nextStep: nextStepSchema.nullable(),
35694
36019
  kind: external_exports.literal("canonical_track"),
35695
36020
  valid: external_exports.boolean(),
35696
36021
  derivedStateCurrent: external_exports.boolean(),
@@ -35818,6 +36143,7 @@ var executionStartOutputSchema = external_exports.strictObject({
35818
36143
  requestedMode: external_exports.enum(["parallel", "sequential"]),
35819
36144
  effectiveMode: external_exports.enum(["parallel", "sequential"]),
35820
36145
  approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES),
36146
+ approvalPolicyVersion: external_exports.number().int().optional(),
35821
36147
  maxWorkers: external_exports.number().int(),
35822
36148
  nodeCount: external_exports.number().int()
35823
36149
  }),
@@ -35831,6 +36157,7 @@ var checkpointOutputSchema = external_exports.strictObject({
35831
36157
  derivedStatus: schedulerSchema
35832
36158
  });
35833
36159
  var executionFinishOutputSchema = external_exports.strictObject({
36160
+ nextStep: nextStepSchema.nullable(),
35834
36161
  ...appliedReceiptBase,
35835
36162
  executionId: external_exports.string(),
35836
36163
  status: external_exports.literal("completed"),
@@ -36164,7 +36491,7 @@ function createCadreServer() {
36164
36491
  derivedStatus: executionSchedulerView(applied.journal, [input.nodeId])
36165
36492
  };
36166
36493
  }
36167
- function recordIntegrationNow(input, commit) {
36494
+ function recordIntegrationNow(input, commit2) {
36168
36495
  const journal = executionStatus(input.projectRoot, input.trackId, input.executionId).journal;
36169
36496
  const node = journal.nodes[input.nodeId];
36170
36497
  if (!node) throw new Error(`unknown execution node ${input.nodeId}`);
@@ -36174,7 +36501,7 @@ function createCadreServer() {
36174
36501
  return applyCheckpointNow({
36175
36502
  ...input,
36176
36503
  event: "record_integration",
36177
- commit,
36504
+ commit: commit2,
36178
36505
  verification: `Integrated ${input.nodeId} into its registered parent worktree.`
36179
36506
  });
36180
36507
  }
@@ -36305,11 +36632,11 @@ function createCadreServer() {
36305
36632
  limit: external_exports.number().int().min(1).max(200).default(50),
36306
36633
  cursor: external_exports.string().max(1024).optional(),
36307
36634
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).optional(),
36308
- 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.")
36309
36636
  },
36310
36637
  outputSchema: CADRE_MCP_OUTPUT_SCHEMAS[CADRE_MCP_TOOLS.projectStatus],
36311
36638
  annotations: { readOnlyHint: true, openWorldHint: false }
36312
- }, async ({ projectRoot, view, trackId, executionId, detail, statuses, limit, cursor }) => {
36639
+ }, async ({ projectRoot, view, trackId, executionId: executionId2, detail, statuses, limit, cursor }) => {
36313
36640
  try {
36314
36641
  const root = safeProjectRoot(projectRoot);
36315
36642
  const validation = validateProject(root);
@@ -36396,20 +36723,26 @@ function createCadreServer() {
36396
36723
  ...stagedCandidate ? { stagedCandidate } : {},
36397
36724
  warnings: validation.warnings
36398
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
+ });
36399
36731
  if (view === "track") {
36400
- return result(focused, `${trackId}: ${track.status}; checkpoint=${track.checkpoint ?? "none"}.`);
36732
+ return result({ ...focused, nextStep }, `${trackId}: ${track.status}; checkpoint=${track.checkpoint ?? "none"}.`);
36401
36733
  }
36402
36734
  const planPath = join15(root, ".cadre", track.location, "plan.md");
36403
36735
  const graphErrors = [];
36404
36736
  const graph = validation.plans.get(trackId) ?? parsePlan(planPath, graphErrors);
36405
36737
  validatePlanGraph(planPath, graph, track.status, graphErrors);
36406
- 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;
36407
36739
  const executionJournal = activeExecutionId ? executionStatus(root, trackId, activeExecutionId).journal : null;
36408
36740
  const execution = executionJournal ? compactExecutionStatus(executionJournal) : null;
36409
36741
  const worktreeStatus = managedWorktreeStatus(root);
36410
36742
  const trackWorktreeSegment = `${join15(".cadre", ".worktrees", trackId)}/`;
36411
36743
  return result({
36412
36744
  ...focused,
36745
+ nextStep: graphErrors.length ? deriveNextStep(root, validation.states.get(trackId), { errors: graphErrors }) : nextStep,
36413
36746
  graph: { valid: graphErrors.length === 0, graph: detail === "full" ? graph : summarizeGraph(graph), errors: graphErrors },
36414
36747
  execution,
36415
36748
  ...detail === "full" ? { executionJournal } : {},
@@ -36471,7 +36804,6 @@ function createCadreServer() {
36471
36804
  try {
36472
36805
  const root = safeProjectRoot(projectRoot);
36473
36806
  const candidates = readCandidateFiles(root, candidateId, files);
36474
- validateStagedState(root, candidateId, candidates);
36475
36807
  const manifest = candidateManifest(candidates);
36476
36808
  const actualPaths = listCandidatePaths(root, candidateId);
36477
36809
  const expectedPaths = manifest.map((file2) => file2.path);
@@ -36502,6 +36834,7 @@ function createCadreServer() {
36502
36834
  `Candidate planValidations must exactly match staged plan files; expected ${candidatePlanPaths.join(", ") || "none"}, found ${validationPaths.join(", ") || "none"}`
36503
36835
  );
36504
36836
  }
36837
+ validateStagedState(root, candidateId, candidates, normalizedPlanValidations);
36505
36838
  const plans = normalizedPlanValidations.map((validation) => {
36506
36839
  const candidate = candidates.find((file2) => file2.path === validation.path);
36507
36840
  if (Buffer.byteLength(candidate.content, "utf8") > MAX_DRAFT_PLAN_CHARACTERS) {
@@ -36711,9 +37044,9 @@ function createCadreServer() {
36711
37044
  const executionStartSchema = {
36712
37045
  projectRoot: external_exports.string().min(1),
36713
37046
  trackId: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
36714
- requestedMode: external_exports.enum(["parallel", "sequential"]).optional().default("parallel"),
37047
+ requestedMode: external_exports.enum(["parallel", "sequential"]).optional(),
36715
37048
  approvalMode: external_exports.enum(EXECUTION_APPROVAL_MODES).optional(),
36716
- maxWorkers: external_exports.number().int().min(1).max(32).optional().default(3)
37049
+ maxWorkers: external_exports.number().int().min(1).max(32).optional()
36717
37050
  };
36718
37051
  registerTool(CADRE_MCP_TOOLS.executionStart, {
36719
37052
  title: "Start implementation execution",
@@ -36739,6 +37072,7 @@ function createCadreServer() {
36739
37072
  requestedMode: applied.journal.requestedMode,
36740
37073
  effectiveMode: applied.journal.effectiveMode,
36741
37074
  approvalMode: applied.journal.approvalMode,
37075
+ approvalPolicyVersion: applied.journal.approvalPolicyVersion,
36742
37076
  maxWorkers: applied.journal.maxWorkers,
36743
37077
  nodeCount: Object.keys(applied.journal.nodes).length
36744
37078
  },
@@ -36860,6 +37194,7 @@ function createCadreServer() {
36860
37194
  const derived = deriveExecutionFinishInput(input);
36861
37195
  const preview = previewExecutionFinish(derived);
36862
37196
  const applied = applyExecutionFinish(derived, preview.digest, preview);
37197
+ const validation = validateProject(input.projectRoot);
36863
37198
  return result({
36864
37199
  commandStatus: "applied",
36865
37200
  executionId: derived.executionId,
@@ -36868,7 +37203,14 @@ function createCadreServer() {
36868
37203
  headCommit: applied.journal.headCommit,
36869
37204
  digest: preview.digest,
36870
37205
  changedPaths: [applied.journalPath, applied.statePath, applied.planPath, applied.tracksPath],
36871
- 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
+ })
36872
37214
  });
36873
37215
  } catch (error51) {
36874
37216
  return failure(error51);
@@ -36890,6 +37232,7 @@ function createCadreServer() {
36890
37232
  try {
36891
37233
  requireCurrentProject2(input.projectRoot);
36892
37234
  requireFreshTrackMemory(input.projectRoot, input.trackId);
37235
+ requireTrackExecutionAuthority(input.projectRoot, input.trackId, input.executionId);
36893
37236
  const preview = previewWorktreeCreate(input);
36894
37237
  const applied = applyWorktreeCreate(input, preview.digest, preview);
36895
37238
  const journal = executionStatus(input.projectRoot, input.trackId, input.executionId).journal;
@@ -36931,6 +37274,7 @@ function createCadreServer() {
36931
37274
  }
36932
37275
  requireCurrentProject2(proposal.input.projectRoot);
36933
37276
  requireFreshTrackMemory(proposal.input.projectRoot, proposal.input.trackId);
37277
+ requireTrackExecutionAuthority(proposal.input.projectRoot, proposal.input.trackId, proposal.input.executionId);
36934
37278
  const applied2 = applyWorktreeIntegration(proposal.input, proposal.digest);
36935
37279
  const checkpoint2 = applied2.status === "integrated" && applied2.mergeCommit ? recordIntegrationNow(proposal.input, applied2.mergeCommit) : {};
36936
37280
  return result({ commandStatus: "applied", ...applied2, ...checkpoint2 }, `Integrated ${proposal.input.nodeId}.`);
@@ -36943,6 +37287,7 @@ function createCadreServer() {
36943
37287
  }
36944
37288
  requireCurrentProject2(integrationInput.projectRoot);
36945
37289
  requireFreshTrackMemory(integrationInput.projectRoot, integrationInput.trackId);
37290
+ requireTrackExecutionAuthority(integrationInput.projectRoot, integrationInput.trackId, integrationInput.executionId);
36946
37291
  if (integrationRequiresApproval(integrationInput)) {
36947
37292
  return proposalResult("worktree_integrate", integrationInput, preview);
36948
37293
  }
@@ -37047,8 +37392,8 @@ function createCadreServer() {
37047
37392
  }, async ({ projectRoot }) => {
37048
37393
  try {
37049
37394
  requireCurrentProject2(projectRoot);
37050
- const commit = resolveGitCommit(projectRoot);
37051
- return result({ path: recordSetupCommit(projectRoot, commit), commit });
37395
+ const commit2 = resolveGitCommit(projectRoot);
37396
+ return result({ path: recordSetupCommit(projectRoot, commit2), commit: commit2 });
37052
37397
  } catch (error51) {
37053
37398
  return failure(error51);
37054
37399
  }
@@ -37093,7 +37438,7 @@ async function runCadreServer() {
37093
37438
  const server = createCadreServer();
37094
37439
  await server.connect(new StdioServerTransport());
37095
37440
  }
37096
- 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])) {
37097
37442
  runCadreServer().catch((error51) => {
37098
37443
  process.stderr.write(`${error51 instanceof Error ? error51.message : String(error51)}
37099
37444
  `);