cadre-ai 1.1.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,7 +38,7 @@ __export(cadre_job_runner_exports, {
38
38
  runJobRunner: () => runJobRunner
39
39
  });
40
40
  module.exports = __toCommonJS(cadre_job_runner_exports);
41
- var import_node_path20 = __toESM(require("node:path"));
41
+ var import_node_path23 = __toESM(require("node:path"));
42
42
 
43
43
  // src/guards.ts
44
44
  function isRecord(value) {
@@ -391,15 +391,15 @@ function appendJsonl(file, value) {
391
391
  }
392
392
 
393
393
  // src/core/application/runtime/plan-docs.ts
394
- var import_node_path17 = __toESM(require("node:path"));
394
+ var import_node_path18 = __toESM(require("node:path"));
395
395
 
396
396
  // src/core/infrastructure/runtime/project-config.ts
397
397
  var import_node_path3 = __toESM(require("node:path"));
398
398
  function loadTopology(root) {
399
399
  const reposPath = import_node_path3.default.join(root, "cadre", "repos.json");
400
- const configPath = import_node_path3.default.join(root, "cadre", "config.json");
400
+ const configPath2 = import_node_path3.default.join(root, "cadre", "config.json");
401
401
  const repos = readJson(reposPath, null);
402
- const config = readJson(configPath, {});
402
+ const config = readJson(configPath2, {});
403
403
  const polyrepo = Boolean(repos && repos.mode === "polyrepo");
404
404
  return {
405
405
  polyrepo,
@@ -453,8 +453,8 @@ function parseCoveragePercent(text) {
453
453
  }
454
454
 
455
455
  // src/core/application/runtime/track-schedule.ts
456
- var import_node_fs9 = __toESM(require("node:fs"));
457
- var import_node_path16 = __toESM(require("node:path"));
456
+ var import_node_fs10 = __toESM(require("node:fs"));
457
+ var import_node_path17 = __toESM(require("node:path"));
458
458
 
459
459
  // src/core/infrastructure/runtime/coverage.ts
460
460
  var import_node_fs3 = __toESM(require("node:fs"));
@@ -552,7 +552,7 @@ function staleInfo(value, now = Date.now()) {
552
552
  }
553
553
 
554
554
  // src/core/application/runtime/repo-resolution.ts
555
- var import_node_path15 = __toESM(require("node:path"));
555
+ var import_node_path16 = __toESM(require("node:path"));
556
556
 
557
557
  // src/lsp/language-registry.ts
558
558
  var import_node_fs4 = __toESM(require("node:fs"));
@@ -570,7 +570,9 @@ var DEFAULT_IGNORES = /* @__PURE__ */ new Set([
570
570
  ".claude",
571
571
  ".cache",
572
572
  ".codex",
573
+ ".copilot",
573
574
  ".dart_tool",
575
+ ".gemini",
574
576
  ".gradle",
575
577
  ".mypy_cache",
576
578
  ".pytest_cache",
@@ -605,7 +607,9 @@ var DEFAULT_IGNORES = /* @__PURE__ */ new Set([
605
607
  ]);
606
608
  var DEFAULT_IGNORE_PATHS = [
607
609
  "plugins/cadre",
608
- "plugins/cadre-claude"
610
+ "plugins/cadre-claude",
611
+ "plugins/cadre-copilot",
612
+ "plugins/cadre-antigravity"
609
613
  ];
610
614
  function normalizeRel(file) {
611
615
  return file.split(import_node_path5.default.sep).join("/");
@@ -742,8 +746,146 @@ function listWorkspaceFiles(root) {
742
746
  return gitFiles.length > 0 ? gitFiles : walkWorkspaceFiles(root);
743
747
  }
744
748
 
745
- // src/core/application/runtime/track-context.ts
749
+ // src/core/application/runtime/branch-set.ts
750
+ var import_node_fs5 = __toESM(require("node:fs"));
746
751
  var import_node_path7 = __toESM(require("node:path"));
752
+ var MONOREPO_REPO_KEY = "root";
753
+ function repoSegment(repo) {
754
+ return safeName(repo === "." ? MONOREPO_REPO_KEY : repo);
755
+ }
756
+ function gitBranch(cwd) {
757
+ const result = runCommand("git", ["branch", "--show-current"], { cwd });
758
+ return result.ok ? result.stdout.trim() || null : null;
759
+ }
760
+ function gitRoot(cwd) {
761
+ const result = runCommand("git", ["rev-parse", "--show-toplevel"], { cwd });
762
+ return result.ok ? import_node_path7.default.resolve(result.stdout.trim() || cwd) : null;
763
+ }
764
+ function branchExists(cwd, branch) {
765
+ return runCommand("git", ["rev-parse", "--verify", "--quiet", branch], { cwd }).ok;
766
+ }
767
+ function taskRepos(root, track) {
768
+ const topology = loadTopology(root);
769
+ if (!topology.polyrepo) return /* @__PURE__ */ new Set([MONOREPO_REPO_KEY]);
770
+ const repos = /* @__PURE__ */ new Set();
771
+ const defaultRepo = asOptionalString(topology.defaultRepo);
772
+ for (const task of parsePlanFile(track.plan_path).tasks || []) {
773
+ const repo = asOptionalString(task.repo) || defaultRepo;
774
+ if (repo) repos.add(repo);
775
+ }
776
+ const metadataRepos = isRecord(track.metadata.repos) ? track.metadata.repos : null;
777
+ if (metadataRepos) {
778
+ for (const [repo, rawInfo] of Object.entries(metadataRepos)) {
779
+ const info = asJsonObject(rawInfo);
780
+ if (info.affected === true || info.git_branch || info.worktree_path) repos.add(repo);
781
+ }
782
+ }
783
+ return repos;
784
+ }
785
+ function branchSetForTrack(root, track, args = {}) {
786
+ const topology = loadTopology(root);
787
+ const requestedRepo = asOptionalString(args.repo);
788
+ const affected = taskRepos(root, track);
789
+ if (topology.polyrepo) {
790
+ const metadataRepos = isRecord(track.metadata.repos) ? track.metadata.repos : {};
791
+ const topoRepos = Array.isArray(topology.repos.repos) ? topology.repos.repos.map(asJsonObject) : [];
792
+ const byName = /* @__PURE__ */ new Map();
793
+ for (const rawRepo of topoRepos) {
794
+ const name = asOptionalString(rawRepo.name);
795
+ if (name) byName.set(name, rawRepo);
796
+ }
797
+ for (const [repo, rawInfo] of Object.entries(metadataRepos)) {
798
+ if (!byName.has(repo)) byName.set(repo, { name: repo, ...asJsonObject(rawInfo) });
799
+ }
800
+ const repoRows = Array.from(byName.values());
801
+ return repoRows.filter((rawRepo) => {
802
+ const repo = asOptionalString(rawRepo.name);
803
+ return Boolean(repo && (!requestedRepo || requestedRepo === repo) && affected.has(repo));
804
+ }).map((rawRepo) => {
805
+ const repo = asString(rawRepo.name);
806
+ const info = {
807
+ submodule_path: asOptionalString(rawRepo.submodule_path) || "",
808
+ base_branch: asOptionalString(rawRepo.default_branch) || asOptionalString(rawRepo.base_branch) || "main",
809
+ ...isRecord(metadataRepos[repo]) ? asJsonObject(metadataRepos[repo]) : {}
810
+ };
811
+ return branchSetEntry(root, track, repo, info, args, true);
812
+ });
813
+ }
814
+ if (requestedRepo && requestedRepo !== "." && requestedRepo !== MONOREPO_REPO_KEY) return [];
815
+ return [branchSetEntry(root, track, MONOREPO_REPO_KEY, {}, args, false)];
816
+ }
817
+ function branchSetEntry(root, track, repo, info, args, polyrepo) {
818
+ const segment = repoSegment(repo);
819
+ const sourceRel = polyrepo ? asOptionalString(info.submodule_path) || "" : ".";
820
+ const sourceRoot = polyrepo && sourceRel ? import_node_path7.default.resolve(root, sourceRel) : root;
821
+ const baseBranch = asOptionalString(args.base) || asOptionalString(info.base_branch) || "main";
822
+ const trackBranch = asOptionalString(args.head) || asOptionalString(args.branch) || asOptionalString(info.git_branch) || asOptionalString(track.metadata.git_branch) || `track/${track.track_id}`;
823
+ const legacyPath = repo === MONOREPO_REPO_KEY ? asOptionalString(track.metadata.worktree_path) : asOptionalString(info.worktree_path);
824
+ const relIntegration = legacyPath || import_node_path7.default.join(".worktrees", "cadre", "tracks", safeName(track.track_id), "integrate", segment);
825
+ const integrationWorktree = import_node_path7.default.resolve(root, relIntegration);
826
+ const workerRoot = import_node_path7.default.resolve(root, ".worktrees", "cadre", "tracks", safeName(track.track_id), "workers", segment);
827
+ const exists = fileExists(integrationWorktree);
828
+ const currentBranch = exists ? gitBranch(integrationWorktree) : null;
829
+ const expectedRoot = gitRoot(sourceRoot);
830
+ const actualRoot = exists ? gitRoot(integrationWorktree) : null;
831
+ const wrongRepo = Boolean(exists && expectedRoot && actualRoot && expectedRoot !== actualRoot);
832
+ const wrongBranch = Boolean(exists && currentBranch && currentBranch !== trackBranch);
833
+ const health = !exists ? "missing" : wrongRepo ? "wrong_repo" : wrongBranch ? "wrong_branch" : "ready";
834
+ return {
835
+ repo,
836
+ repo_segment: segment,
837
+ source_root: sourceRoot,
838
+ source_path: sourceRel,
839
+ base_branch: baseBranch,
840
+ track_branch: trackBranch,
841
+ integration_worktree: integrationWorktree,
842
+ integration_worktree_path: import_node_path7.default.relative(root, integrationWorktree) || ".",
843
+ worker_root: workerRoot,
844
+ worker_root_path: import_node_path7.default.relative(root, workerRoot) || ".",
845
+ affected: true,
846
+ exists,
847
+ current_branch: currentBranch,
848
+ health,
849
+ branch_exists: branchExists(sourceRoot, trackBranch),
850
+ commands: integrationCommands(sourceRoot, integrationWorktree, trackBranch, baseBranch, exists)
851
+ };
852
+ }
853
+ function integrationCommands(sourceRoot, integrationWorktree, branch, base, exists) {
854
+ if (exists) return [];
855
+ return [{
856
+ command: "git",
857
+ args: ["worktree", "add", integrationWorktree, branch],
858
+ fallback_args: ["worktree", "add", "-b", branch, integrationWorktree, base],
859
+ cwd: sourceRoot
860
+ }];
861
+ }
862
+ function ensureIntegrationWorktree(entry) {
863
+ if (entry.exists) {
864
+ if (entry.health !== "ready") return { ok: false, stage: "integration_worktree_health", entry, error: `Integration worktree for ${entry.repo} is ${entry.health}` };
865
+ return { ok: true, entry, created: false };
866
+ }
867
+ import_node_fs5.default.mkdirSync(import_node_path7.default.dirname(entry.integration_worktree), { recursive: true });
868
+ const args = entry.branch_exists ? ["worktree", "add", entry.integration_worktree, entry.track_branch] : ["worktree", "add", "-b", entry.track_branch, entry.integration_worktree, entry.base_branch];
869
+ const result = runCommand("git", args, { cwd: entry.source_root });
870
+ return {
871
+ ok: result.ok,
872
+ entry: { ...entry, exists: result.ok, current_branch: result.ok ? entry.track_branch : entry.current_branch, health: result.ok ? "ready" : entry.health },
873
+ created: result.ok,
874
+ command: { command: "git", args, cwd: entry.source_root },
875
+ result
876
+ };
877
+ }
878
+ function branchSetEntryForRepo(root, track, repo, args = {}) {
879
+ return branchSetForTrack(root, track, { ...args, repo: repo === MONOREPO_REPO_KEY ? void 0 : repo }).find((entry) => entry.repo === repo || repo === "." && entry.repo === MONOREPO_REPO_KEY) || null;
880
+ }
881
+ function taskRepo(root, task, args = {}) {
882
+ const topology = loadTopology(root);
883
+ if (!topology.polyrepo) return MONOREPO_REPO_KEY;
884
+ return asString(args.repo || task?.repo || topology.defaultRepo);
885
+ }
886
+
887
+ // src/core/application/runtime/track-context.ts
888
+ var import_node_path8 = __toESM(require("node:path"));
747
889
  function findTrack(root, trackId) {
748
890
  return listTracks(root).find((item) => item.track_id === trackId) || null;
749
891
  }
@@ -753,9 +895,10 @@ function trackContext(root, trackId) {
753
895
  const topology = loadTopology(root);
754
896
  const plan = parsePlanFile(track.plan_path);
755
897
  const hold = holdInfo(track);
898
+ const branchSet = branchSetForTrack(root, track);
756
899
  const worktrees = [];
757
900
  if (track.metadata.worktree_path) {
758
- const abs = import_node_path7.default.resolve(root, track.metadata.worktree_path);
901
+ const abs = import_node_path8.default.resolve(root, track.metadata.worktree_path);
759
902
  worktrees.push({
760
903
  repo: ".",
761
904
  path: track.metadata.worktree_path,
@@ -773,7 +916,7 @@ function trackContext(root, trackId) {
773
916
  repo,
774
917
  submodule_path: submodulePath,
775
918
  path: worktreePath,
776
- exists: worktreePath ? fileExists(import_node_path7.default.resolve(root, worktreePath)) : false,
919
+ exists: worktreePath ? fileExists(import_node_path8.default.resolve(root, worktreePath)) : false,
777
920
  git_branch: info.git_branch || `track/${track.track_id}`,
778
921
  base_branch: info.base_branch || "main"
779
922
  });
@@ -795,9 +938,9 @@ function trackContext(root, trackId) {
795
938
  owner: track.metadata.owner || null,
796
939
  reviewer: track.metadata.reviewer || null,
797
940
  git_branch: track.metadata.git_branch || `track/${track.track_id}`,
798
- metadata_path: import_node_path7.default.relative(root, track.metadata_path || import_node_path7.default.join(track.dir, "metadata.json")),
799
- plan_path: import_node_path7.default.relative(root, track.plan_path),
800
- spec_path: import_node_path7.default.relative(root, track.spec_path),
941
+ metadata_path: import_node_path8.default.relative(root, track.metadata_path || import_node_path8.default.join(track.dir, "metadata.json")),
942
+ plan_path: import_node_path8.default.relative(root, track.plan_path),
943
+ spec_path: import_node_path8.default.relative(root, track.spec_path),
801
944
  tags: asStringArray(track.metadata.tags),
802
945
  review: track.metadata.review || null,
803
946
  last_coverage: track.metadata.last_coverage ?? null
@@ -805,16 +948,17 @@ function trackContext(root, trackId) {
805
948
  hold,
806
949
  task_counts: taskCounts(plan),
807
950
  plan,
951
+ branch_set: branchSet,
808
952
  worktrees
809
953
  };
810
954
  }
811
955
 
812
956
  // src/core/application/runtime/quality-gates.ts
813
- var import_node_fs8 = __toESM(require("node:fs"));
814
- var import_node_path14 = __toESM(require("node:path"));
957
+ var import_node_fs9 = __toESM(require("node:fs"));
958
+ var import_node_path15 = __toESM(require("node:path"));
815
959
 
816
960
  // src/runtime-paths.ts
817
- var import_node_path8 = __toESM(require("node:path"));
961
+ var import_node_path9 = __toESM(require("node:path"));
818
962
  function unique(values) {
819
963
  return Array.from(new Set(values));
820
964
  }
@@ -822,14 +966,14 @@ function mcpServerPathCandidates(root) {
822
966
  const candidates = [];
823
967
  let dir = __dirname;
824
968
  for (let depth = 0; depth < 8; depth += 1) {
825
- candidates.push(import_node_path8.default.join(dir, "cadre-server.js"));
826
- candidates.push(import_node_path8.default.join(dir, "mcp", "cadre-server.js"));
827
- candidates.push(import_node_path8.default.join(dir, "scripts", "mcp", "cadre-server.js"));
828
- const parent = import_node_path8.default.dirname(dir);
969
+ candidates.push(import_node_path9.default.join(dir, "cadre-server.js"));
970
+ candidates.push(import_node_path9.default.join(dir, "mcp", "cadre-server.js"));
971
+ candidates.push(import_node_path9.default.join(dir, "scripts", "mcp", "cadre-server.js"));
972
+ const parent = import_node_path9.default.dirname(dir);
829
973
  if (parent === dir) break;
830
974
  dir = parent;
831
975
  }
832
- if (root) candidates.push(import_node_path8.default.join(root, "cadre", "scripts", "mcp", "cadre-server.js"));
976
+ if (root) candidates.push(import_node_path9.default.join(root, "cadre", "scripts", "mcp", "cadre-server.js"));
833
977
  return unique(candidates);
834
978
  }
835
979
 
@@ -852,12 +996,12 @@ function lspReview(root, args = {}) {
852
996
  }
853
997
 
854
998
  // src/core/application/runtime/repo-map.ts
855
- var import_node_fs5 = __toESM(require("node:fs"));
856
- var import_node_path10 = __toESM(require("node:path"));
999
+ var import_node_fs6 = __toESM(require("node:fs"));
1000
+ var import_node_path11 = __toESM(require("node:path"));
857
1001
 
858
1002
  // src/core/application/runtime/workspace-cache.ts
859
1003
  var import_node_child_process3 = require("node:child_process");
860
- var import_node_path9 = __toESM(require("node:path"));
1004
+ var import_node_path10 = __toESM(require("node:path"));
861
1005
  var CACHE = /* @__PURE__ */ new Map();
862
1006
  var DEFAULT_TTL_MS = 3e4;
863
1007
  function gitHead(root) {
@@ -870,7 +1014,7 @@ function gitHead(root) {
870
1014
  }
871
1015
  function workspaceCacheKey(root, scope, discriminator = "") {
872
1016
  return JSON.stringify({
873
- root: import_node_path9.default.resolve(root),
1017
+ root: import_node_path10.default.resolve(root),
874
1018
  head: gitHead(root),
875
1019
  scope,
876
1020
  discriminator
@@ -897,8 +1041,12 @@ function isIgnoredRepoMapFile(file) {
897
1041
  if (normalized.startsWith(".agents/")) return true;
898
1042
  if (normalized.startsWith(".claude/")) return true;
899
1043
  if (normalized.startsWith(".claude-plugin/")) return true;
1044
+ if (normalized.startsWith(".copilot/")) return true;
1045
+ if (normalized.startsWith(".gemini/")) return true;
900
1046
  if (normalized.startsWith("plugins/cadre/")) return true;
901
1047
  if (normalized.startsWith("plugins/cadre-claude/")) return true;
1048
+ if (normalized.startsWith("plugins/cadre-copilot/")) return true;
1049
+ if (normalized.startsWith("plugins/cadre-antigravity/")) return true;
902
1050
  return normalized.split("/").some((part) => [".git", "node_modules", "dist", "build", "coverage"].includes(part));
903
1051
  }
904
1052
  function selectedRepoNames(args = {}) {
@@ -927,7 +1075,7 @@ function intelRepoRoots(root, args = {}) {
927
1075
  if (!name || !rel) continue;
928
1076
  entries.push({
929
1077
  repo: name,
930
- root: import_node_path10.default.resolve(root, rel),
1078
+ root: import_node_path11.default.resolve(root, rel),
931
1079
  path: rel,
932
1080
  source: "repos.json"
933
1081
  });
@@ -970,18 +1118,18 @@ function symbolPatternsForLanguage(language) {
970
1118
  );
971
1119
  }
972
1120
  function extractRepoSymbols(root, file, limitPerFile = 40) {
973
- const abs = import_node_path10.default.join(root, file);
1121
+ const abs = import_node_path11.default.join(root, file);
974
1122
  if (!fileExists(abs)) return [];
975
1123
  let stat;
976
1124
  try {
977
- stat = import_node_fs5.default.statSync(abs);
1125
+ stat = import_node_fs6.default.statSync(abs);
978
1126
  } catch {
979
1127
  return [];
980
1128
  }
981
1129
  if (stat.size > 1024 * 1024) return [];
982
1130
  const language = languageForFile(file);
983
1131
  if (!language) return [];
984
- const text = import_node_fs5.default.readFileSync(abs, "utf8");
1132
+ const text = import_node_fs6.default.readFileSync(abs, "utf8");
985
1133
  const patterns = symbolPatternsForLanguage(language);
986
1134
  const symbols = [];
987
1135
  for (const pattern of patterns) {
@@ -1051,8 +1199,8 @@ function repoMap(root, args = {}) {
1051
1199
  }
1052
1200
 
1053
1201
  // src/core/application/runtime/track-mutations.ts
1054
- var import_node_fs7 = __toESM(require("node:fs"));
1055
- var import_node_path13 = __toESM(require("node:path"));
1202
+ var import_node_fs8 = __toESM(require("node:fs"));
1203
+ var import_node_path14 = __toESM(require("node:path"));
1056
1204
 
1057
1205
  // src/core/domain/track-status.ts
1058
1206
  var STATUS_MARKERS = {
@@ -1065,17 +1213,17 @@ var STATUS_MARKERS = {
1065
1213
  var VALID_STATUSES = new Set(Object.keys(STATUS_MARKERS));
1066
1214
 
1067
1215
  // src/core/application/runtime/native-state.ts
1068
- var import_node_fs6 = __toESM(require("node:fs"));
1069
- var import_node_path11 = __toESM(require("node:path"));
1216
+ var import_node_fs7 = __toESM(require("node:fs"));
1217
+ var import_node_path12 = __toESM(require("node:path"));
1070
1218
  function nativeStatePaths(root) {
1071
1219
  return {
1072
- events: import_node_path11.default.join(root, "cadre", "events.jsonl"),
1073
- formulas: import_node_path11.default.join(root, "cadre", "formulas"),
1074
- operations: import_node_path11.default.join(root, "cadre", "operations"),
1075
- messages: import_node_path11.default.join(root, "cadre", "messages"),
1076
- inbox: import_node_path11.default.join(root, "cadre", "messages", "inbox.jsonl"),
1077
- outbox: import_node_path11.default.join(root, "cadre", "messages", "outbox.jsonl"),
1078
- wisps: import_node_path11.default.join(root, "cadre", "local", "wisps")
1220
+ events: import_node_path12.default.join(root, "cadre", "events.jsonl"),
1221
+ formulas: import_node_path12.default.join(root, "cadre", "formulas"),
1222
+ operations: import_node_path12.default.join(root, "cadre", "operations"),
1223
+ messages: import_node_path12.default.join(root, "cadre", "messages"),
1224
+ inbox: import_node_path12.default.join(root, "cadre", "messages", "inbox.jsonl"),
1225
+ outbox: import_node_path12.default.join(root, "cadre", "messages", "outbox.jsonl"),
1226
+ wisps: import_node_path12.default.join(root, "cadre", "local", "wisps")
1079
1227
  };
1080
1228
  }
1081
1229
  function compactStamp(value) {
@@ -1086,16 +1234,16 @@ function nativeId(prefix, payload) {
1086
1234
  return `${prefix}_${compactStamp(recordedAt)}_${textHash(JSON.stringify(payload)).slice(0, 12)}`;
1087
1235
  }
1088
1236
  function ensureCadreLocalIgnored(root) {
1089
- const cadreDir = import_node_path11.default.join(root, "cadre");
1090
- const ignorePath = import_node_path11.default.join(cadreDir, ".gitignore");
1091
- import_node_fs6.default.mkdirSync(cadreDir, { recursive: true });
1092
- const current = fileExists(ignorePath) ? import_node_fs6.default.readFileSync(ignorePath, "utf8") : "";
1237
+ const cadreDir = import_node_path12.default.join(root, "cadre");
1238
+ const ignorePath = import_node_path12.default.join(cadreDir, ".gitignore");
1239
+ import_node_fs7.default.mkdirSync(cadreDir, { recursive: true });
1240
+ const current = fileExists(ignorePath) ? import_node_fs7.default.readFileSync(ignorePath, "utf8") : "";
1093
1241
  const lines = current.split(/\r?\n/).filter(Boolean);
1094
1242
  if (!lines.includes("/local/")) {
1095
1243
  lines.push("/local/");
1096
- import_node_fs6.default.writeFileSync(ignorePath, `${lines.join("\n")}
1244
+ import_node_fs7.default.writeFileSync(ignorePath, `${lines.join("\n")}
1097
1245
  `);
1098
- return import_node_path11.default.relative(root, ignorePath);
1246
+ return import_node_path12.default.relative(root, ignorePath);
1099
1247
  }
1100
1248
  return null;
1101
1249
  }
@@ -1107,17 +1255,17 @@ function ensureNativeState(root) {
1107
1255
  asOptionalString(paths.messages),
1108
1256
  asOptionalString(paths.wisps)
1109
1257
  ].filter((value) => Boolean(value))) {
1110
- import_node_fs6.default.mkdirSync(dir, { recursive: true });
1258
+ import_node_fs7.default.mkdirSync(dir, { recursive: true });
1111
1259
  }
1112
1260
  const ignore_path = ensureCadreLocalIgnored(root);
1113
1261
  return {
1114
1262
  ok: true,
1115
1263
  paths: {
1116
- events: import_node_path11.default.relative(root, String(paths.events)),
1117
- formulas: import_node_path11.default.relative(root, String(paths.formulas)),
1118
- operations: import_node_path11.default.relative(root, String(paths.operations)),
1119
- messages: import_node_path11.default.relative(root, String(paths.messages)),
1120
- wisps: import_node_path11.default.relative(root, String(paths.wisps))
1264
+ events: import_node_path12.default.relative(root, String(paths.events)),
1265
+ formulas: import_node_path12.default.relative(root, String(paths.formulas)),
1266
+ operations: import_node_path12.default.relative(root, String(paths.operations)),
1267
+ messages: import_node_path12.default.relative(root, String(paths.messages)),
1268
+ wisps: import_node_path12.default.relative(root, String(paths.wisps))
1121
1269
  },
1122
1270
  ignore_path
1123
1271
  };
@@ -1136,16 +1284,16 @@ function appendCadreEvent(root, event) {
1136
1284
  recorded_at,
1137
1285
  actor
1138
1286
  };
1139
- const file = import_node_path11.default.join(root, "cadre", "events.jsonl");
1287
+ const file = import_node_path12.default.join(root, "cadre", "events.jsonl");
1140
1288
  appendJsonl(file, entry);
1141
- return { ok: true, path: import_node_path11.default.relative(root, file), event: entry };
1289
+ return { ok: true, path: import_node_path12.default.relative(root, file), event: entry };
1142
1290
  }
1143
1291
 
1144
1292
  // src/core/application/runtime/commit-trace.ts
1145
- var import_node_path12 = __toESM(require("node:path"));
1293
+ var import_node_path13 = __toESM(require("node:path"));
1146
1294
  var DEFAULT_NOTES_REF = "refs/notes/cadre";
1147
1295
  function configured(root) {
1148
- return fileExists(import_node_path12.default.join(root, "cadre", "config.json"));
1296
+ return fileExists(import_node_path13.default.join(root, "cadre", "config.json"));
1149
1297
  }
1150
1298
  function traceability(root) {
1151
1299
  return asJsonObject(loadTopology(root).config.traceability);
@@ -1184,8 +1332,8 @@ function statusEntries(cwd) {
1184
1332
  return entries;
1185
1333
  }
1186
1334
  function beginTrace(cwd) {
1187
- const gitRoot = runCommand("git", ["rev-parse", "--show-toplevel"], { cwd });
1188
- if (!gitRoot.ok) {
1335
+ const gitRoot2 = runCommand("git", ["rev-parse", "--show-toplevel"], { cwd });
1336
+ if (!gitRoot2.ok) {
1189
1337
  return {
1190
1338
  ok: true,
1191
1339
  cwd,
@@ -1195,7 +1343,7 @@ function beginTrace(cwd) {
1195
1343
  reason: "not a git repository"
1196
1344
  };
1197
1345
  }
1198
- const root = gitRoot.stdout.trim() || cwd;
1346
+ const root = gitRoot2.stdout.trim() || cwd;
1199
1347
  const entries = statusEntries(root);
1200
1348
  return {
1201
1349
  ok: true,
@@ -1246,9 +1394,12 @@ function commitTrace(root, args, options) {
1246
1394
  const cwd = options.cwd || root;
1247
1395
  const snapshot = options.before || beginTrace(cwd);
1248
1396
  if (snapshot.skipped) return { ok: true, skipped: true, reason: snapshot.reason || "git unavailable" };
1249
- const gitRoot = asOptionalString(snapshot.git_root) || cwd;
1250
- const after = statusEntries(gitRoot);
1251
- const requestedFiles = options.files ? uniqueFiles(options.files) : changedAfter(snapshot, after).filter((file) => options.kind === "product" ? !isControlPlaneFile2(file) : isControlPlaneFile2(file));
1397
+ const gitRoot2 = asOptionalString(snapshot.git_root) || cwd;
1398
+ const after = statusEntries(gitRoot2);
1399
+ const requestedFiles = options.files ? uniqueFiles(options.files) : uniqueFiles([
1400
+ ...changedAfter(snapshot, after).filter((file) => options.kind === "product" ? !isControlPlaneFile2(file) : isControlPlaneFile2(file)),
1401
+ ...options.includeDirtyFiles || []
1402
+ ]);
1252
1403
  const files = requestedFiles.filter((file) => after[file]);
1253
1404
  if (files.length === 0) return { ok: true, skipped: true, reason: "no changed files to commit" };
1254
1405
  const beforeEntries = asJsonObject(snapshot.entries);
@@ -1263,9 +1414,9 @@ function commitTrace(root, args, options) {
1263
1414
  preexisting_dirty_files: preexisting
1264
1415
  };
1265
1416
  }
1266
- const add = runCommand("git", ["add", "-A", "--", ...files], { cwd: gitRoot });
1417
+ const add = runCommand("git", ["add", "-A", "--", ...files], { cwd: gitRoot2 });
1267
1418
  if (!add.ok) return { ok: false, stage: "git_add", files, add };
1268
- const staged = runCommand("git", ["diff", "--cached", "--quiet"], { cwd: gitRoot });
1419
+ const staged = runCommand("git", ["diff", "--cached", "--quiet"], { cwd: gitRoot2 });
1269
1420
  if (staged.status === 0) return { ok: true, skipped: true, reason: "no staged changes", files };
1270
1421
  const traceId = `trace_${textHash(JSON.stringify({ root, files, now: utcNow(), workflow: options.workflow })).slice(0, 16)}`;
1271
1422
  const type = asOptionalString(args.commitType || args.commit_type) || options.type || (options.kind === "product" ? "feat" : "cadre");
@@ -1291,9 +1442,9 @@ function commitTrace(root, args, options) {
1291
1442
  fullSubject,
1292
1443
  "-m",
1293
1444
  commitBody
1294
- ], { cwd: gitRoot });
1445
+ ], { cwd: gitRoot2 });
1295
1446
  if (!commit.ok) return { ok: false, stage: "git_commit", files, commit };
1296
- const sha = commitSha(gitRoot);
1447
+ const sha = commitSha(gitRoot2);
1297
1448
  const notePayload = {
1298
1449
  version: 1,
1299
1450
  schema: "cadre.commit_trace.v1",
@@ -1311,7 +1462,7 @@ function commitTrace(root, args, options) {
1311
1462
  if (options.kind === "product") notePayload.product_commit_sha = sha;
1312
1463
  if (options.kind === "control") notePayload.control_commit_sha = sha;
1313
1464
  const ref = notesRef(root, args);
1314
- const note = sha && notesEnabled(root) ? writeNote(gitRoot, ref, sha, notePayload) : null;
1465
+ const note = sha && notesEnabled(root) ? writeNote(gitRoot2, ref, sha, notePayload) : null;
1315
1466
  return {
1316
1467
  ok: !note || commandOk(note),
1317
1468
  trace_id: traceId,
@@ -1395,9 +1546,9 @@ function recordTaskResultUnlocked(root, args = {}) {
1395
1546
  return { ok: false, track_id: track.track_id, stage: "plan_json_patch", metadata, plan_json: planPatch };
1396
1547
  }
1397
1548
  const nextPlan = asJsonObject(planPatch.value);
1398
- import_node_fs7.default.writeFileSync(
1549
+ import_node_fs8.default.writeFileSync(
1399
1550
  track.plan_path,
1400
- withGeneratedMarker(import_node_path13.default.relative(root, planJsonPath), "cadre.plan.v1", renderPlanMarkdown(nextPlan))
1551
+ withGeneratedMarker(import_node_path14.default.relative(root, planJsonPath), "cadre.plan.v1", renderPlanMarkdown(nextPlan, import_node_path14.default.relative(root, planJsonPath)))
1401
1552
  );
1402
1553
  return {
1403
1554
  ok: true,
@@ -1442,7 +1593,7 @@ function testCoverage(root, args = {}) {
1442
1593
  let task = null;
1443
1594
  let workingRoot = {
1444
1595
  repo: args.repo || ".",
1445
- path: args.workingRoot ? import_node_path14.default.resolve(root, args.workingRoot) : root,
1596
+ path: args.workingRoot ? import_node_path15.default.resolve(root, args.workingRoot) : root,
1446
1597
  source: args.workingRoot ? "argument.workingRoot" : "project-root"
1447
1598
  };
1448
1599
  if (args.trackId) {
@@ -1503,7 +1654,7 @@ function testCoverage(root, args = {}) {
1503
1654
  commitSha: args.commitSha,
1504
1655
  coverage,
1505
1656
  repo: workingRoot.repo,
1506
- workingRoot: import_node_path14.default.relative(root, workingRoot.path) || "."
1657
+ workingRoot: import_node_path15.default.relative(root, workingRoot.path) || "."
1507
1658
  });
1508
1659
  }
1509
1660
  }
@@ -1543,8 +1694,8 @@ function configuredMachineGateCommand(root, args = {}, workingRoot = root) {
1543
1694
  if (Object.keys(scripts).length > 0) {
1544
1695
  for (const name of ["typecheck", "check", "build", "lint"]) {
1545
1696
  if (scripts[name]) {
1546
- if (fileExists(import_node_path14.default.join(workingRoot, "pnpm-lock.yaml"))) return `pnpm ${name}`;
1547
- if (fileExists(import_node_path14.default.join(workingRoot, "yarn.lock"))) return `yarn ${name}`;
1697
+ if (fileExists(import_node_path15.default.join(workingRoot, "pnpm-lock.yaml"))) return `pnpm ${name}`;
1698
+ if (fileExists(import_node_path15.default.join(workingRoot, "yarn.lock"))) return `yarn ${name}`;
1548
1699
  return `npm run ${name}`;
1549
1700
  }
1550
1701
  }
@@ -1594,7 +1745,7 @@ function reviewMachineGate(root, args = {}) {
1594
1745
  }
1595
1746
  const entries = track ? repoEntriesForTrack(root, track, args) : [{
1596
1747
  repo: args.repo || ".",
1597
- root: args.workingRoot ? import_node_path14.default.resolve(root, args.workingRoot) : root,
1748
+ root: args.workingRoot ? import_node_path15.default.resolve(root, args.workingRoot) : root,
1598
1749
  path: args.workingRoot || ".",
1599
1750
  source: args.workingRoot ? "argument.workingRoot" : "project-root"
1600
1751
  }];
@@ -1639,16 +1790,16 @@ function scanReviewTodos(root, files, limit = 100) {
1639
1790
  ];
1640
1791
  for (const file of files || []) {
1641
1792
  if (isIgnoredRepoMapFile(file)) continue;
1642
- const abs = import_node_path14.default.join(root, file);
1793
+ const abs = import_node_path15.default.join(root, file);
1643
1794
  if (!fileExists(abs)) continue;
1644
1795
  let stat;
1645
1796
  try {
1646
- stat = import_node_fs8.default.statSync(abs);
1797
+ stat = import_node_fs9.default.statSync(abs);
1647
1798
  } catch {
1648
1799
  continue;
1649
1800
  }
1650
1801
  if (stat.size > 1024 * 1024) continue;
1651
- const lines = import_node_fs8.default.readFileSync(abs, "utf8").split(/\r?\n/);
1802
+ const lines = import_node_fs9.default.readFileSync(abs, "utf8").split(/\r?\n/);
1652
1803
  for (let index = 0; index < lines.length && findings.length < limit; index += 1) {
1653
1804
  const line = lines[index] || "";
1654
1805
  if (patterns.some((pattern) => pattern.test(line))) {
@@ -1678,7 +1829,7 @@ function reviewAssist(root, args = {}) {
1678
1829
  source: entry.source,
1679
1830
  ...diffSurface(entry.root, entry.base || base, entry.head || head)
1680
1831
  }));
1681
- const diff = repoDiffs.find((entry) => entry.repo === ".") || diffSurface(root, base, head);
1832
+ const diff = repoDiffs.find((entry) => entry.repo === "root" || entry.repo === ".") || diffSurface(root, base, head);
1682
1833
  const incompleteTasks = [];
1683
1834
  for (const phase of plan.phases) {
1684
1835
  for (const task of phase.tasks) {
@@ -1726,6 +1877,7 @@ function reviewAssist(root, args = {}) {
1726
1877
  head,
1727
1878
  diff,
1728
1879
  repo_diffs: repoDiffs,
1880
+ branch_set: context.branch_set || [],
1729
1881
  task_counts: context.task_counts,
1730
1882
  incomplete_tasks: incompleteTasks,
1731
1883
  coverage: track.metadata.last_coverage ?? null,
@@ -1887,10 +2039,53 @@ function lspImpact(root, args = {}) {
1887
2039
  };
1888
2040
  }
1889
2041
 
2042
+ // src/core/application/runtime/planning.ts
2043
+ function worktreePlan(root, args = {}) {
2044
+ const track = findTrack(root, args.trackId || args.track_id);
2045
+ if (!track) return { ok: false, error: `Track not found: ${args.trackId || args.track_id}` };
2046
+ const repoError = repoEntriesError(root, track, args);
2047
+ if (repoError) return repoError;
2048
+ const topology = loadTopology(root);
2049
+ const branchSet = branchSetForTrack(root, track, args);
2050
+ const execute = args.execute === true;
2051
+ const setup_results = execute ? branchSet.map((entry) => ensureIntegrationWorktree(entry)) : [];
2052
+ const plans = branchSet.map((entry, index) => {
2053
+ const result = setup_results[index];
2054
+ const resultEntry = isRecord(result?.entry) ? asJsonObject(result.entry) : entry;
2055
+ return {
2056
+ repo: entry.repo,
2057
+ source_root: entry.source_root,
2058
+ source_path: entry.source_path,
2059
+ worktree_path: entry.integration_worktree_path,
2060
+ integration_worktree: entry.integration_worktree,
2061
+ worker_root: entry.worker_root,
2062
+ branch: entry.track_branch,
2063
+ base: entry.base_branch,
2064
+ exists: result ? result.ok === true : entry.exists,
2065
+ current_branch: result ? asOptionalString(resultEntry.current_branch) : entry.current_branch,
2066
+ health: result ? asOptionalString(resultEntry.health) || entry.health : entry.health,
2067
+ branch_exists: entry.branch_exists,
2068
+ commands: entry.commands,
2069
+ setup_result: result || null
2070
+ };
2071
+ });
2072
+ return {
2073
+ ok: setup_results.every((result) => result.ok !== false) && branchSet.every((entry) => entry.health === "ready" || entry.health === "missing"),
2074
+ root,
2075
+ track_id: track.track_id,
2076
+ execute,
2077
+ dry_run: !execute,
2078
+ topology: topology.polyrepo ? "polyrepo" : "monorepo",
2079
+ branch_set: branchSet,
2080
+ plans,
2081
+ setup_results
2082
+ };
2083
+ }
2084
+
1890
2085
  // src/core/application/runtime/tech-stack.ts
1891
2086
  function humanReviewConfirmed(args = {}) {
1892
2087
  const rawArgs = args;
1893
- return rawArgs.humanConfirmed === true || rawArgs.human_confirmed === true || rawArgs.userConfirmed === true || rawArgs.user_confirmed === true || rawArgs.confirmed === true;
2088
+ return rawArgs.approvalComplete === true || rawArgs.approval_complete === true;
1894
2089
  }
1895
2090
 
1896
2091
  // src/core/application/runtime/repo-resolution.ts
@@ -1978,62 +2173,65 @@ function repoEntriesError(root, track, args = {}) {
1978
2173
  };
1979
2174
  }
1980
2175
  function resolveTaskWorkingRoot(root, track, task = null, args = {}) {
1981
- if (args.workingRoot) {
1982
- const candidate = import_node_path15.default.isAbsolute(args.workingRoot) ? args.workingRoot : import_node_path15.default.resolve(root, args.workingRoot);
1983
- return { repo: args.repo || task?.repo || ".", path: candidate, source: "argument.workingRoot" };
2176
+ const explicitWorkingRoot = asOptionalString(args.workingRoot || args.workerRoot || args.worker_root || args.worktree);
2177
+ if (explicitWorkingRoot) {
2178
+ const candidate = import_node_path16.default.isAbsolute(explicitWorkingRoot) ? explicitWorkingRoot : import_node_path16.default.resolve(root, explicitWorkingRoot);
2179
+ return { repo: taskRepo(root, task, args), path: candidate, source: "argument.workingRoot" };
2180
+ }
2181
+ const repo = taskRepo(root, task, args);
2182
+ const branchEntry = branchSetEntryForRepo(root, track, repo, args);
2183
+ if (branchEntry && branchEntry.exists && branchEntry.health === "ready") {
2184
+ return {
2185
+ repo: branchEntry.repo,
2186
+ path: branchEntry.integration_worktree,
2187
+ source: "branch-set.integration_worktree",
2188
+ branch_set: branchEntry
2189
+ };
1984
2190
  }
1985
2191
  const topology = loadTopology(root);
1986
2192
  if (topology.polyrepo) {
1987
- const repo = args.repo || task?.repo || topology.defaultRepo;
1988
2193
  const info = typeof repo === "string" ? trackRepoEntries(root, track)[repo] || {} : {};
1989
2194
  if (Object.keys(info).length > 0) {
1990
2195
  const rel = info.worktree_path || info.submodule_path || "";
1991
2196
  return {
2197
+ ok: true,
1992
2198
  repo,
1993
- path: rel ? import_node_path15.default.resolve(root, rel) : root,
1994
- source: info.worktree_path ? "metadata.repos.worktree_path" : "metadata.repos.submodule_path"
2199
+ path: rel ? import_node_path16.default.resolve(root, rel) : root,
2200
+ source: branchEntry ? "branch-set.integration_missing_fallback" : info.worktree_path ? "metadata.repos.worktree_path" : "metadata.repos.submodule_path",
2201
+ ...branchEntry ? { branch_set: branchEntry } : {}
1995
2202
  };
1996
2203
  }
1997
2204
  return unresolvedWorkingRoot(root, track, String(repo || ""), task);
1998
2205
  }
1999
- if (track.metadata.worktree_path) {
2000
- const candidate = import_node_path15.default.resolve(root, track.metadata.worktree_path);
2206
+ if (track.metadata.worktree_path && !branchEntry) {
2207
+ const candidate = import_node_path16.default.resolve(root, track.metadata.worktree_path);
2001
2208
  if (fileExists(candidate)) {
2002
2209
  return { repo: ".", path: candidate, source: "metadata.worktree_path" };
2003
2210
  }
2004
2211
  }
2005
- return { repo: ".", path: root, source: "project-root" };
2212
+ return {
2213
+ ok: true,
2214
+ repo: MONOREPO_REPO_KEY,
2215
+ path: root,
2216
+ source: branchEntry ? "branch-set.integration_missing_fallback" : "project-root",
2217
+ ...branchEntry ? { branch_set: branchEntry } : {}
2218
+ };
2006
2219
  }
2007
2220
  function repoEntriesForTrack(root, track, args = {}) {
2008
- const topology = loadTopology(root);
2009
- if (topology.polyrepo) {
2010
- const repos = trackRepoEntries(root, track);
2011
- return Object.entries(repos).filter(([repo]) => !args.repo || args.repo === repo).map(([repo, rawInfo]) => {
2012
- const info = asJsonObject(rawInfo);
2013
- const rel = info.worktree_path || info.submodule_path || "";
2014
- return {
2015
- repo,
2016
- root: rel ? import_node_path15.default.resolve(root, rel) : root,
2017
- path: rel,
2018
- base: args.base || info.base_branch || "main",
2019
- head: args.head || info.git_branch || track.metadata.git_branch || `track/${track.track_id}`,
2020
- source: info.worktree_path ? "metadata.repos.worktree_path" : "metadata.repos.submodule_path"
2021
- };
2022
- });
2023
- }
2024
- return [{
2025
- repo: args.repo || ".",
2026
- root: args.workingRoot ? import_node_path15.default.resolve(root, args.workingRoot) : root,
2027
- path: args.workingRoot || ".",
2028
- base: args.base || "main",
2029
- head: args.head || track.metadata.git_branch || `track/${track.track_id}`,
2030
- source: args.workingRoot ? "argument.workingRoot" : "project-root"
2031
- }];
2221
+ return branchSetForTrack(root, track, args).map((entry) => ({
2222
+ repo: entry.repo,
2223
+ root: entry.exists && entry.health === "ready" ? entry.integration_worktree : entry.source_root,
2224
+ path: entry.exists && entry.health === "ready" ? entry.integration_worktree_path : entry.source_path,
2225
+ base: entry.base_branch,
2226
+ head: entry.track_branch,
2227
+ source: entry.exists && entry.health === "ready" ? "branch-set.integration_worktree" : "branch-set.source_root",
2228
+ branch_set: entry
2229
+ }));
2032
2230
  }
2033
2231
 
2034
2232
  // src/core/application/runtime/track-schedule.ts
2035
2233
  function workStateForTrack(track) {
2036
- const statePath = import_node_path16.default.join(track.dir, "implement_state.json");
2234
+ const statePath = import_node_path17.default.join(track.dir, "implement_state.json");
2037
2235
  return readJson(statePath, null);
2038
2236
  }
2039
2237
  function holdInfo(track, now = Date.now()) {
@@ -2075,27 +2273,27 @@ function taskCounts(plan) {
2075
2273
  return counts;
2076
2274
  }
2077
2275
  function listTrackDirs(root) {
2078
- const tracksDir = import_node_path16.default.join(root, "cadre", "tracks");
2276
+ const tracksDir = import_node_path17.default.join(root, "cadre", "tracks");
2079
2277
  if (!fileExists(tracksDir)) return [];
2080
- return import_node_fs9.default.readdirSync(tracksDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => import_node_path16.default.join(tracksDir, entry.name)).sort();
2278
+ return import_node_fs10.default.readdirSync(tracksDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => import_node_path17.default.join(tracksDir, entry.name)).sort();
2081
2279
  }
2082
2280
  function listTracks(root) {
2083
2281
  const tracks = [];
2084
2282
  for (const dir of listTrackDirs(root)) {
2085
- const metadataPath = import_node_path16.default.join(dir, "metadata.json");
2283
+ const metadataPath = import_node_path17.default.join(dir, "metadata.json");
2086
2284
  const metadata = readJson(metadataPath, null);
2087
2285
  if (!metadata) continue;
2088
- const trackId = metadata.track_id || import_node_path16.default.basename(dir);
2286
+ const trackId = metadata.track_id || import_node_path17.default.basename(dir);
2089
2287
  tracks.push({
2090
2288
  track_id: trackId,
2091
2289
  dir,
2092
2290
  metadata_path: metadataPath,
2093
- plan_path: import_node_path16.default.join(dir, "plan.md"),
2094
- spec_path: import_node_path16.default.join(dir, "spec.md"),
2095
- plan_json_path: import_node_path16.default.join(dir, "plan.json"),
2096
- spec_json_path: import_node_path16.default.join(dir, "spec.json"),
2097
- learnings_jsonl_path: import_node_path16.default.join(dir, "learnings.jsonl"),
2098
- handoff_json_path: import_node_path16.default.join(dir, "handoff.json"),
2291
+ plan_path: import_node_path17.default.join(dir, "plan.md"),
2292
+ spec_path: import_node_path17.default.join(dir, "spec.md"),
2293
+ plan_json_path: import_node_path17.default.join(dir, "plan.json"),
2294
+ spec_json_path: import_node_path17.default.join(dir, "spec.json"),
2295
+ learnings_jsonl_path: import_node_path17.default.join(dir, "learnings.jsonl"),
2296
+ handoff_json_path: import_node_path17.default.join(dir, "handoff.json"),
2099
2297
  metadata
2100
2298
  });
2101
2299
  }
@@ -2140,6 +2338,10 @@ function withGeneratedMarker(source, schema, body) {
2140
2338
  return `${generatedMarker(source, schema, normalized)}
2141
2339
  ${normalized}`;
2142
2340
  }
2341
+ function appendCanonicalJsonReference(parts, source, heading = "Canonical Source") {
2342
+ const target = source ? `\`${source}\`` : "the canonical JSON file referenced by the generated marker";
2343
+ parts.push(`## ${heading}`, "", `Canonical data lives in ${target}. This Markdown is a generated human-readable projection.`, "");
2344
+ }
2143
2345
  function markerForPlanStatus(status) {
2144
2346
  const normalized = String(status || "pending");
2145
2347
  if (normalized === "completed") return "x";
@@ -2152,11 +2354,11 @@ function markerForPlanStatus(status) {
2152
2354
  // src/core/application/runtime/plan-docs.ts
2153
2355
  var MANUAL_VERIFICATION_TASK_TYPE = "user_manual_verification";
2154
2356
  function trackPlanJsonPath(track) {
2155
- return track.plan_json_path || import_node_path17.default.join(track.dir, "plan.json");
2357
+ return track.plan_json_path || import_node_path18.default.join(track.dir, "plan.json");
2156
2358
  }
2157
2359
  function planJsonPathForPlanPath(file) {
2158
2360
  if (file.endsWith(".json")) return file;
2159
- return import_node_path17.default.join(import_node_path17.default.dirname(file), "plan.json");
2361
+ return import_node_path18.default.join(import_node_path18.default.dirname(file), "plan.json");
2160
2362
  }
2161
2363
  function manualVerificationScope(value) {
2162
2364
  const task = asJsonObject(value);
@@ -2231,7 +2433,7 @@ function planJsonToParsedPlan(raw) {
2231
2433
  });
2232
2434
  return { ok: true, phases, tasks: phases.flatMap((phase) => phase.tasks), warnings: [], errors: [] };
2233
2435
  }
2234
- function renderPlanMarkdown(raw) {
2436
+ function renderPlanMarkdown(raw, canonicalSource) {
2235
2437
  const trackId = asOptionalString(raw.track_id) || "track";
2236
2438
  const parts = [`# Plan: ${trackId}`, ""];
2237
2439
  const parsed = planJsonToParsedPlan(raw);
@@ -2261,16 +2463,445 @@ function renderPlanMarkdown(raw) {
2261
2463
  parts.push("");
2262
2464
  }
2263
2465
  }
2466
+ appendCanonicalJsonReference(parts, canonicalSource);
2264
2467
  return normalizedText(parts.join("\n"));
2265
2468
  }
2266
2469
 
2267
- // src/core/application/runtime/task-completion.ts
2470
+ // src/dap/config.ts
2471
+ var import_node_fs11 = __toESM(require("node:fs"));
2268
2472
  var import_node_path19 = __toESM(require("node:path"));
2473
+ function configPath(root, config) {
2474
+ const rel = config || "cadre/dap.json";
2475
+ return import_node_path19.default.isAbsolute(rel) ? rel : import_node_path19.default.join(root, rel);
2476
+ }
2477
+ function readConfig(file) {
2478
+ try {
2479
+ return asJsonObject(JSON.parse(import_node_fs11.default.readFileSync(file, "utf8")));
2480
+ } catch {
2481
+ return {};
2482
+ }
2483
+ }
2484
+ function substitute(value, tokens) {
2485
+ if (typeof value === "string") {
2486
+ return Object.entries(tokens).reduce((text, [token, replacement]) => text.split(token).join(replacement), value);
2487
+ }
2488
+ if (Array.isArray(value)) return value.map((entry) => substitute(entry, tokens));
2489
+ if (!isRecord(value)) return value;
2490
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, substitute(entry, tokens)]));
2491
+ }
2492
+ function normalizeBreakpoints(root, raw) {
2493
+ if (!Array.isArray(raw)) return [];
2494
+ return raw.map(asJsonObject).flatMap((entry) => {
2495
+ const file = asOptionalString(entry.file) || asOptionalString(entry.path);
2496
+ const line = asNumber(entry.line);
2497
+ if (!file || line < 1) return [];
2498
+ const abs = import_node_path19.default.isAbsolute(file) ? file : import_node_path19.default.join(root, file);
2499
+ return [{
2500
+ ...entry,
2501
+ file: import_node_path19.default.relative(root, abs).split(import_node_path19.default.sep).join("/"),
2502
+ line
2503
+ }];
2504
+ });
2505
+ }
2506
+ function normalizeDapSession(root, args = {}) {
2507
+ const file = configPath(root, args.config);
2508
+ const loaded = readConfig(file);
2509
+ const inlineConfiguration = asJsonObject(args.configuration);
2510
+ const configurationId = asOptionalString(args.configurationId || args.configuration_id || args.id);
2511
+ const configurations = Array.isArray(loaded.configurations) ? loaded.configurations.map(asJsonObject) : [];
2512
+ const configuration = Object.keys(inlineConfiguration).length > 0 ? inlineConfiguration : configurations.find((entry) => asOptionalString(entry.id) === configurationId) || configurations[0] || {};
2513
+ if (Object.keys(configuration).length === 0) return { ok: false, error: "DAP configuration is required" };
2514
+ const adapters = Array.isArray(loaded.adapters) ? loaded.adapters.map(asJsonObject) : [];
2515
+ const adapterId = asOptionalString(configuration.adapterId) || asOptionalString(configuration.adapter_id);
2516
+ const inlineAdapter = asJsonObject(configuration.adapter);
2517
+ const adapter = Object.keys(inlineAdapter).length > 0 ? inlineAdapter : adapters.find((entry) => asOptionalString(entry.id) === adapterId) || {};
2518
+ const command = asOptionalString(adapter.command);
2519
+ if (!command) return { ok: false, error: "DAP adapter command is required" };
2520
+ const request = asOptionalString(configuration.request);
2521
+ if (request !== "launch" && request !== "attach") return { ok: false, error: "DAP configuration request must be launch or attach" };
2522
+ const tokens = {
2523
+ "${workspaceFolder}": root,
2524
+ "${root}": root,
2525
+ "${cwd}": root,
2526
+ "${testCommand}": asOptionalString(args.testCommand || args.test_command) || ""
2527
+ };
2528
+ return {
2529
+ adapter: substitute(adapter, tokens),
2530
+ configuration: substitute(configuration, tokens),
2531
+ request,
2532
+ arguments: substitute(configuration.arguments || configuration.args || {}, tokens),
2533
+ breakpoints: normalizeBreakpoints(root, args.breakpoints || configuration.breakpoints),
2534
+ timeoutMs: Math.max(1e3, Math.min(10 * 60 * 1e3, asNumber(args.timeoutMs, 12e4)))
2535
+ };
2536
+ }
2537
+ function redactDapValue(value) {
2538
+ if (Array.isArray(value)) return value.map(redactDapValue);
2539
+ if (!isRecord(value)) return value;
2540
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
2541
+ const sensitive = /token|password|secret|credential|apikey|api_key|authorization/i.test(key);
2542
+ return [key, sensitive ? "<redacted>" : redactDapValue(entry)];
2543
+ }));
2544
+ }
2545
+
2546
+ // src/dap/snapshot.ts
2547
+ var import_node_path20 = __toESM(require("node:path"));
2548
+
2549
+ // src/dap/client.ts
2550
+ var import_node_child_process4 = require("node:child_process");
2551
+
2552
+ // src/dap/protocol.ts
2553
+ function encodeDapMessage(message) {
2554
+ const body = JSON.stringify(message);
2555
+ return Buffer.from(`Content-Length: ${Buffer.byteLength(body, "utf8")}\r
2556
+ \r
2557
+ ${body}`, "utf8");
2558
+ }
2559
+ var DapMessageBuffer = class {
2560
+ buffer = Buffer.alloc(0);
2561
+ push(chunk) {
2562
+ this.buffer = Buffer.concat([this.buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8")]);
2563
+ const messages = [];
2564
+ while (true) {
2565
+ const headerEnd = this.buffer.indexOf("\r\n\r\n");
2566
+ if (headerEnd === -1) return messages;
2567
+ const header = this.buffer.slice(0, headerEnd).toString("utf8");
2568
+ const lengthMatch = header.match(/Content-Length:\s*(\d+)/i);
2569
+ if (!lengthMatch) {
2570
+ this.buffer = this.buffer.slice(headerEnd + 4);
2571
+ continue;
2572
+ }
2573
+ const length = Number(lengthMatch[1]);
2574
+ const bodyStart = headerEnd + 4;
2575
+ const bodyEnd = bodyStart + length;
2576
+ if (this.buffer.length < bodyEnd) return messages;
2577
+ const rawBody = this.buffer.slice(bodyStart, bodyEnd).toString("utf8");
2578
+ this.buffer = this.buffer.slice(bodyEnd);
2579
+ try {
2580
+ messages.push(asJsonObject(JSON.parse(rawBody)));
2581
+ } catch {
2582
+ }
2583
+ }
2584
+ }
2585
+ };
2586
+
2587
+ // src/dap/client.ts
2588
+ var DapClient = class {
2589
+ constructor(options) {
2590
+ this.options = options;
2591
+ }
2592
+ proc = null;
2593
+ nextSeq = 1;
2594
+ pending = /* @__PURE__ */ new Map();
2595
+ waiters = [];
2596
+ reader = new DapMessageBuffer();
2597
+ stderr = "";
2598
+ events = [];
2599
+ outputs = [];
2600
+ start() {
2601
+ return new Promise((resolve, reject) => {
2602
+ let settled = false;
2603
+ const fail = (error) => {
2604
+ if (!settled) {
2605
+ settled = true;
2606
+ reject(error);
2607
+ }
2608
+ };
2609
+ this.proc = (0, import_node_child_process4.spawn)(this.options.command, this.options.args || [], {
2610
+ cwd: this.options.cwd,
2611
+ stdio: ["pipe", "pipe", "pipe"]
2612
+ });
2613
+ this.proc.once("spawn", () => {
2614
+ if (!settled) {
2615
+ settled = true;
2616
+ resolve();
2617
+ }
2618
+ });
2619
+ this.proc.once("error", (error) => fail(new Error(`Unable to start DAP adapter ${this.options.command}: ${errorMessage(error)}`)));
2620
+ this.proc.stdout.on("data", (chunk) => this.read(chunk));
2621
+ this.proc.stderr.on("data", (chunk) => {
2622
+ this.stderr = `${this.stderr}${chunk.toString("utf8")}`.slice(-(this.options.outputLimit || 8e3));
2623
+ });
2624
+ this.proc.on("exit", (code, signal) => this.rejectAll(signal ? `DAP adapter exited with signal ${signal}` : `DAP adapter exited with code ${code}`));
2625
+ });
2626
+ }
2627
+ read(chunk) {
2628
+ for (const message of this.reader.push(chunk)) this.handleMessage(message);
2629
+ }
2630
+ handleMessage(message) {
2631
+ if (message.type === "response") {
2632
+ const requestSeq = Number(message.request_seq);
2633
+ const pending = this.pending.get(requestSeq);
2634
+ if (!pending) return;
2635
+ this.pending.delete(requestSeq);
2636
+ clearTimeout(pending.timer);
2637
+ if (message.success === false) {
2638
+ pending.reject(new Error(asOptionalString(message.message) || `${message.command || "request"} failed`));
2639
+ } else {
2640
+ pending.resolve(asJsonObject(message.body));
2641
+ }
2642
+ return;
2643
+ }
2644
+ if (message.type === "event") {
2645
+ this.events.push(message);
2646
+ if (message.event === "output") this.outputs.push(message);
2647
+ this.resolveWaiters(message);
2648
+ }
2649
+ }
2650
+ resolveWaiters(message) {
2651
+ const eventName = asOptionalString(message.event);
2652
+ if (!eventName) return;
2653
+ const ready = this.waiters.filter((waiter) => waiter.events.includes(eventName));
2654
+ this.waiters = this.waiters.filter((waiter) => !waiter.events.includes(eventName));
2655
+ for (const waiter of ready) {
2656
+ clearTimeout(waiter.timer);
2657
+ waiter.resolve(message);
2658
+ }
2659
+ }
2660
+ rejectAll(message) {
2661
+ for (const pending of this.pending.values()) {
2662
+ clearTimeout(pending.timer);
2663
+ pending.reject(new Error(message));
2664
+ }
2665
+ this.pending.clear();
2666
+ for (const waiter of this.waiters) {
2667
+ clearTimeout(waiter.timer);
2668
+ waiter.resolve(null);
2669
+ }
2670
+ this.waiters = [];
2671
+ }
2672
+ request(command, args = {}, timeoutMs = this.options.requestTimeoutMs || 1e4) {
2673
+ if (!this.proc) return Promise.reject(new Error("DAP adapter is not running"));
2674
+ const seq = this.nextSeq++;
2675
+ const message = { seq, type: "request", command, arguments: args };
2676
+ return new Promise((resolve, reject) => {
2677
+ const timer = setTimeout(() => {
2678
+ this.pending.delete(seq);
2679
+ reject(new Error(`${command} timed out after ${timeoutMs}ms`));
2680
+ }, timeoutMs);
2681
+ this.pending.set(seq, { resolve, reject, timer });
2682
+ this.proc?.stdin.write(encodeDapMessage(message));
2683
+ });
2684
+ }
2685
+ waitForAny(events, timeoutMs) {
2686
+ const existing = this.events.find((message) => events.includes(asOptionalString(message.event) || ""));
2687
+ if (existing) return Promise.resolve(existing);
2688
+ return new Promise((resolve) => {
2689
+ const timer = setTimeout(() => {
2690
+ this.waiters = this.waiters.filter((waiter) => waiter.resolve !== resolve);
2691
+ resolve(null);
2692
+ }, timeoutMs);
2693
+ this.waiters.push({ events, resolve, timer });
2694
+ });
2695
+ }
2696
+ stderrTail() {
2697
+ return this.stderr;
2698
+ }
2699
+ async shutdown() {
2700
+ try {
2701
+ await this.request("disconnect", { terminateDebuggee: true, restart: false }, 2e3);
2702
+ } catch {
2703
+ }
2704
+ if (this.proc && !this.proc.killed) this.proc.kill("SIGTERM");
2705
+ }
2706
+ };
2707
+
2708
+ // src/dap/snapshot.ts
2709
+ function delay(ms) {
2710
+ return new Promise((resolve) => setTimeout(resolve, ms));
2711
+ }
2712
+ function redactText(value) {
2713
+ return value.replace(/(token|password|secret|api[_-]?key|authorization)(\s*[=:]\s*)\S+/gi, "$1$2<redacted>").slice(-8e3);
2714
+ }
2715
+ function outputEvents(client) {
2716
+ return client.outputs.slice(-50).map((event) => {
2717
+ const body = asJsonObject(event.body);
2718
+ return {
2719
+ category: asOptionalString(body.category) || "console",
2720
+ output: redactText(asOptionalString(body.output) || "")
2721
+ };
2722
+ });
2723
+ }
2724
+ async function requestOptional(client, command, args, timeoutMs = 3e3) {
2725
+ try {
2726
+ return await client.request(command, args, timeoutMs);
2727
+ } catch {
2728
+ return null;
2729
+ }
2730
+ }
2731
+ async function collectVariables(client, variablesReference, limit) {
2732
+ if (variablesReference <= 0) return [];
2733
+ const result = await requestOptional(client, "variables", { variablesReference, start: 0, count: limit });
2734
+ const variables = Array.isArray(result?.variables) ? result.variables.map(asJsonObject) : [];
2735
+ return variables.slice(0, limit).map((variable) => ({
2736
+ name: asOptionalString(variable.name) || "",
2737
+ type: asOptionalString(variable.type) || null,
2738
+ value: redactText(asOptionalString(variable.value) || ""),
2739
+ variablesReference: asNumber(variable.variablesReference)
2740
+ }));
2741
+ }
2742
+ async function collectScopes(client, frameId, variableLimit) {
2743
+ const scopesResult = await requestOptional(client, "scopes", { frameId });
2744
+ const scopes = Array.isArray(scopesResult?.scopes) ? scopesResult.scopes.map(asJsonObject) : [];
2745
+ const collected = [];
2746
+ for (const scope of scopes.slice(0, 6)) {
2747
+ const variablesReference = asNumber(scope.variablesReference);
2748
+ collected.push({
2749
+ name: asOptionalString(scope.name) || "scope",
2750
+ expensive: scope.expensive === true,
2751
+ variables: await collectVariables(client, variablesReference, variableLimit)
2752
+ });
2753
+ }
2754
+ return collected;
2755
+ }
2756
+ async function collectStoppedSnapshot(client, event, args) {
2757
+ const body = asJsonObject(event.body);
2758
+ const frameLimit = Math.max(1, Math.min(50, asNumber(args.limit, 20)));
2759
+ const variableLimit = Math.max(1, Math.min(100, asNumber(args.variableLimit || args.variable_limit, 25)));
2760
+ const threadsResult = await requestOptional(client, "threads", {});
2761
+ const threadIds = asNumber(body.threadId) > 0 ? [asNumber(body.threadId)] : Array.isArray(threadsResult?.threads) ? threadsResult.threads.map(asJsonObject).map((thread) => asNumber(thread.id)).filter(Boolean) : [];
2762
+ const threads = [];
2763
+ for (const threadId of threadIds.slice(0, 8)) {
2764
+ const stack = await requestOptional(client, "stackTrace", { threadId, startFrame: 0, levels: frameLimit });
2765
+ const frames = Array.isArray(stack?.stackFrames) ? stack.stackFrames.map(asJsonObject) : [];
2766
+ const summarizedFrames = [];
2767
+ for (const frame of frames.slice(0, frameLimit)) {
2768
+ const source = asJsonObject(frame.source);
2769
+ const frameId = asNumber(frame.id);
2770
+ summarizedFrames.push({
2771
+ id: frameId,
2772
+ name: asOptionalString(frame.name) || "",
2773
+ file: asOptionalString(source.path) || asOptionalString(source.name) || null,
2774
+ line: asNumber(frame.line),
2775
+ column: asNumber(frame.column),
2776
+ scopes: summarizedFrames.length === 0 ? await collectScopes(client, frameId, variableLimit) : []
2777
+ });
2778
+ }
2779
+ threads.push({ threadId, frames: summarizedFrames });
2780
+ }
2781
+ return {
2782
+ event: "stopped",
2783
+ reason: asOptionalString(body.reason) || null,
2784
+ description: asOptionalString(body.description) || null,
2785
+ thread_id: asNumber(body.threadId) || null,
2786
+ threads
2787
+ };
2788
+ }
2789
+ async function setBreakpoints(client, root, breakpoints) {
2790
+ const groups = /* @__PURE__ */ new Map();
2791
+ for (const breakpoint of breakpoints) {
2792
+ const file = asOptionalString(breakpoint.file);
2793
+ if (!file) continue;
2794
+ const entries = groups.get(file) || [];
2795
+ entries.push(breakpoint);
2796
+ groups.set(file, entries);
2797
+ }
2798
+ const results = [];
2799
+ for (const [file, entries] of groups.entries()) {
2800
+ const abs = import_node_path20.default.isAbsolute(file) ? file : import_node_path20.default.join(root, file);
2801
+ const response = await requestOptional(client, "setBreakpoints", {
2802
+ source: { path: abs },
2803
+ breakpoints: entries.map((entry) => ({
2804
+ line: asNumber(entry.line),
2805
+ condition: asOptionalString(entry.condition),
2806
+ hitCondition: asOptionalString(entry.hitCondition || entry.hit_condition),
2807
+ logMessage: asOptionalString(entry.logMessage || entry.log_message)
2808
+ }))
2809
+ });
2810
+ results.push({
2811
+ file,
2812
+ breakpoints: Array.isArray(response?.breakpoints) ? response.breakpoints.map(asJsonObject) : []
2813
+ });
2814
+ }
2815
+ return results;
2816
+ }
2817
+ async function dapSnapshot(root, args = {}) {
2818
+ const normalized = normalizeDapSession(root, args);
2819
+ if ("ok" in normalized && normalized.ok === false) return normalized;
2820
+ const session = normalized;
2821
+ const command = asOptionalString(session.adapter.command) || "";
2822
+ const adapterArgs = asStringArray(session.adapter.args);
2823
+ const client = new DapClient({
2824
+ command,
2825
+ args: adapterArgs,
2826
+ cwd: root,
2827
+ requestTimeoutMs: asNumber(session.adapter.requestTimeoutMs, 1e4),
2828
+ outputLimit: 8e3
2829
+ });
2830
+ let launchResponse = null;
2831
+ let launchError = null;
2832
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2833
+ try {
2834
+ await client.start();
2835
+ const initialize = await client.request("initialize", {
2836
+ adapterID: asOptionalString(session.adapter.id) || command,
2837
+ clientID: "cadre",
2838
+ clientName: "Cadre",
2839
+ pathFormat: "path",
2840
+ linesStartAt1: true,
2841
+ columnsStartAt1: true,
2842
+ supportsVariableType: true,
2843
+ supportsVariablePaging: true
2844
+ });
2845
+ const initialized = client.waitForAny(["initialized"], Math.min(5e3, session.timeoutMs));
2846
+ const launch = client.request(session.request, session.arguments, session.timeoutMs).then((body) => {
2847
+ launchResponse = body;
2848
+ }).catch((error) => {
2849
+ launchError = errorMessage(error);
2850
+ });
2851
+ await initialized;
2852
+ const breakpointResults = await setBreakpoints(client, root, session.breakpoints);
2853
+ await requestOptional(client, "configurationDone", {}, 3e3);
2854
+ await Promise.race([launch, delay(250)]);
2855
+ if (launchError) throw new Error(launchError);
2856
+ const finalEvent = await client.waitForAny(["stopped", "terminated", "exited"], session.timeoutMs);
2857
+ const snapshot = finalEvent?.event === "stopped" ? await collectStoppedSnapshot(client, finalEvent, args) : {
2858
+ event: asOptionalString(finalEvent?.event) || "timeout",
2859
+ body: finalEvent ? asJsonObject(redactDapValue(asJsonObject(finalEvent.body))) : null
2860
+ };
2861
+ return {
2862
+ ok: finalEvent !== null,
2863
+ root,
2864
+ started_at: startedAt,
2865
+ finished_at: (/* @__PURE__ */ new Date()).toISOString(),
2866
+ adapter: {
2867
+ id: asOptionalString(session.adapter.id) || command,
2868
+ command,
2869
+ args: adapterArgs
2870
+ },
2871
+ request: session.request,
2872
+ configuration: redactDapValue(session.configuration),
2873
+ initialize,
2874
+ launch_response: launchResponse,
2875
+ breakpoints: breakpointResults,
2876
+ snapshot,
2877
+ output: outputEvents(client),
2878
+ adapter_stderr_tail: redactText(client.stderrTail()),
2879
+ error: finalEvent ? void 0 : `DAP snapshot timed out after ${session.timeoutMs}ms`
2880
+ };
2881
+ } catch (error) {
2882
+ return {
2883
+ ok: false,
2884
+ root,
2885
+ started_at: startedAt,
2886
+ finished_at: (/* @__PURE__ */ new Date()).toISOString(),
2887
+ adapter: { command, args: adapterArgs },
2888
+ configuration: redactDapValue(session.configuration),
2889
+ output: outputEvents(client),
2890
+ adapter_stderr_tail: redactText(client.stderrTail()),
2891
+ error: errorMessage(error)
2892
+ };
2893
+ } finally {
2894
+ await client.shutdown();
2895
+ }
2896
+ }
2897
+
2898
+ // src/core/application/runtime/task-completion.ts
2899
+ var import_node_path22 = __toESM(require("node:path"));
2269
2900
 
2270
2901
  // src/core/application/runtime/manual-verification.ts
2271
- var import_node_path18 = __toESM(require("node:path"));
2902
+ var import_node_path21 = __toESM(require("node:path"));
2272
2903
  function completionJournalPath(track) {
2273
- return import_node_path18.default.join(track.dir, "completion_journal.json");
2904
+ return import_node_path21.default.join(track.dir, "completion_journal.json");
2274
2905
  }
2275
2906
  function readCompletionJournal(track) {
2276
2907
  const value = readJson(completionJournalPath(track), { entries: {} });
@@ -2290,7 +2921,7 @@ function patchCompletionJournal(track, key, patcher) {
2290
2921
  journal.entries[key] = patcher({ ...before }, journal);
2291
2922
  journal.updated_at = utcNow();
2292
2923
  writeCompletionJournal(track, journal);
2293
- appendJsonl(import_node_path18.default.join(track.dir, "completion_journal.jsonl"), {
2924
+ appendJsonl(import_node_path21.default.join(track.dir, "completion_journal.jsonl"), {
2294
2925
  key,
2295
2926
  recorded_at: journal.updated_at,
2296
2927
  entry: journal.entries[key]
@@ -2375,7 +3006,7 @@ function prepareManualVerificationCompletion(root, track, task, args, workingRoo
2375
3006
  ok: false,
2376
3007
  dry_run: true,
2377
3008
  blocked: true,
2378
- phase_state: "awaiting_human_review",
3009
+ phase_state: "awaiting_staged_approval",
2379
3010
  stage: "manual_verification_approval",
2380
3011
  track_id: track.track_id,
2381
3012
  task_key: task.task_key,
@@ -2388,7 +3019,7 @@ function prepareManualVerificationCompletion(root, track, task, args, workingRoo
2388
3019
  ok: false,
2389
3020
  dry_run: true,
2390
3021
  blocked: true,
2391
- phase_state: "awaiting_human_review",
3022
+ phase_state: "awaiting_staged_approval",
2392
3023
  stage: "manual_verification_approval",
2393
3024
  track_id: track.track_id,
2394
3025
  task_key: task.task_key,
@@ -2463,6 +3094,18 @@ function completeTaskInner(root, args = {}) {
2463
3094
  reason: workingRoot.error
2464
3095
  };
2465
3096
  }
3097
+ if (workingRoot.source !== "argument.workingRoot" && workingRoot.source !== "branch-set.integration_worktree" && workingRoot.branch_set) {
3098
+ const branchSet = workingRoot.branch_set;
3099
+ return {
3100
+ ok: false,
3101
+ stage: "worktree_setup",
3102
+ blocked: true,
3103
+ working_root: workingRoot,
3104
+ branch_set: branchSet,
3105
+ reason: branchSet.exists ? `Integration worktree for ${branchSet.repo} is ${branchSet.health}; complete_task requires the expected track branch or an explicit worker root` : `Integration worktree for ${branchSet.repo} is missing; run worktree_plan with execute before complete_task or pass an explicit worker root`,
3106
+ worktree_plan: worktreePlan(root, { trackId: track.track_id, repo: branchSet.repo })
3107
+ };
3108
+ }
2466
3109
  const manualVerificationTask = isManualVerificationTaskObject(task);
2467
3110
  const manualVerificationCompletion = manualVerificationTask ? prepareManualVerificationCompletion(root, track, task, args, workingRoot) : null;
2468
3111
  if (manualVerificationCompletion && manualVerificationCompletion.ok === false) return manualVerificationCompletion;
@@ -2568,7 +3211,7 @@ function completeTaskInner(root, args = {}) {
2568
3211
  commitSha: resolvedCommitSha || args.commitSha,
2569
3212
  coverage: coverage.coverage,
2570
3213
  repo: workingRoot.repo,
2571
- workingRoot: import_node_path19.default.relative(root, workingRoot.path) || ".",
3214
+ workingRoot: import_node_path22.default.relative(root, workingRoot.path) || ".",
2572
3215
  ...lastTestRun ? { lastTestRun } : {},
2573
3216
  ...manualVerificationEvidence ? { manualVerificationEvidence } : {}
2574
3217
  });
@@ -2621,13 +3264,15 @@ function completeTaskInner(root, args = {}) {
2621
3264
  subject: `record ${track.track_id} phase ${phaseIndex} task ${taskIndex}`,
2622
3265
  before: controlBefore,
2623
3266
  files: [
2624
- import_node_path19.default.relative(root, track.metadata_path),
2625
- import_node_path19.default.relative(root, track.plan_path),
2626
- import_node_path19.default.relative(root, trackPlanJsonPath(track)),
2627
- import_node_path19.default.relative(root, completionJournalPath(track)),
2628
- import_node_path19.default.relative(root, `${completionJournalPath(track)}l`),
3267
+ import_node_path22.default.relative(root, track.metadata_path),
3268
+ import_node_path22.default.relative(root, track.plan_path),
3269
+ import_node_path22.default.relative(root, trackPlanJsonPath(track)),
3270
+ import_node_path22.default.relative(root, completionJournalPath(track)),
3271
+ import_node_path22.default.relative(root, `${completionJournalPath(track)}l`),
3272
+ import_node_path22.default.relative(root, import_node_path22.default.join(track.dir, "implement_state.json")),
2629
3273
  "cadre/events.jsonl"
2630
3274
  ],
3275
+ allowDirty: true,
2631
3276
  trackId: track.track_id,
2632
3277
  repo: ".",
2633
3278
  note: {
@@ -2654,6 +3299,16 @@ function completeTaskInner(root, args = {}) {
2654
3299
  };
2655
3300
  }
2656
3301
 
3302
+ // src/core/domain/project-skill-policy.ts
3303
+ var PROJECT_SKILL_MAX_FILE_BYTES = 128 * 1024;
3304
+
3305
+ // src/mcp/domain/tool-catalog.ts
3306
+ var SERVER_INSTRUCTIONS = [
3307
+ "Cadre is a packet-led runtime. Call cadre_workflow first for workflows, cadre_action for a packet named by a workflow response, and cadre_read only for a relevant resource URI.",
3308
+ "Pass a root candidate to project-scoped calls. Cadre resolves it internally; setup accepts an uninitialized directory.",
3309
+ "Cadre owns control-plane, provider, worker, approval, merge, and generated projection state."
3310
+ ].join(" ");
3311
+
2657
3312
  // src/cadre-job-runner.ts
2658
3313
  function readStdin() {
2659
3314
  return new Promise((resolve, reject) => {
@@ -2666,7 +3321,7 @@ function readStdin() {
2666
3321
  process.stdin.on("error", reject);
2667
3322
  });
2668
3323
  }
2669
- function runJob(payload) {
3324
+ async function runJob(payload) {
2670
3325
  const root = payload.root || process.cwd();
2671
3326
  const args = asJsonObject(payload.args);
2672
3327
  switch (asOptionalString(payload.type)) {
@@ -2682,6 +3337,8 @@ function runJob(payload) {
2682
3337
  return lspReview(root, args);
2683
3338
  case "lsp_impact":
2684
3339
  return lspImpact(root, args);
3340
+ case "dap_snapshot":
3341
+ return dapSnapshot(root, args);
2685
3342
  default:
2686
3343
  return { ok: false, error: `Unsupported job type: ${payload.type}` };
2687
3344
  }
@@ -2689,11 +3346,11 @@ function runJob(payload) {
2689
3346
  async function runJobRunner() {
2690
3347
  const input = await readStdin();
2691
3348
  const payload = asJsonObject(JSON.parse(input || "{}"));
2692
- const result = runJob(payload);
3349
+ const result = await runJob(payload);
2693
3350
  process.stdout.write(`${JSON.stringify(result, null, 2)}
2694
3351
  `);
2695
3352
  }
2696
- if (["cadre-job-runner.js", "cadre-job-runner.ts"].includes(import_node_path20.default.basename(process.argv[1] || ""))) {
3353
+ if (["cadre-job-runner.js", "cadre-job-runner.ts"].includes(import_node_path23.default.basename(process.argv[1] || ""))) {
2697
3354
  runJobRunner().catch((error) => {
2698
3355
  process.stdout.write(`${JSON.stringify({ ok: false, error: errorMessage(error), stack: error instanceof Error ? error.stack : void 0 }, null, 2)}
2699
3356
  `);