@adhdev/daemon-standalone 1.0.49-rc.11 → 1.0.49-rc.12

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.
package/dist/index.js CHANGED
@@ -36552,8 +36552,8 @@ var require_dist3 = __commonJS({
36552
36552
  function isRecord(value) {
36553
36553
  return !!value && typeof value === "object" && !Array.isArray(value);
36554
36554
  }
36555
- function parseConfigText(path55, text) {
36556
- if (/\.json$/i.test(path55)) return JSON.parse(text);
36555
+ function parseConfigText(path56, text) {
36556
+ if (/\.json$/i.test(path56)) return JSON.parse(text);
36557
36557
  return yaml.load(text);
36558
36558
  }
36559
36559
  function normalizeOperatingNote(value) {
@@ -37056,10 +37056,10 @@ var require_dist3 = __commonJS({
37056
37056
  }
37057
37057
  function getDaemonBuildInfo() {
37058
37058
  if (cached2) return cached2;
37059
- const commit = readInjected(true ? "a21460656698fe5b5567132109fe159f8ae2c56b" : void 0) ?? "unknown";
37060
- const commitShort = readInjected(true ? "a2146065" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
37061
- const version2 = readInjected(true ? "1.0.49-rc.11" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
37062
- const builtAt = readInjected(true ? "2026-08-15T02:43:45.229Z" : void 0);
37059
+ const commit = readInjected(true ? "d20b4ad708551ef7198efd44a123bcb981b62fb1" : void 0) ?? "unknown";
37060
+ const commitShort = readInjected(true ? "d20b4ad7" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
37061
+ const version2 = readInjected(true ? "1.0.49-rc.12" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
37062
+ const builtAt = readInjected(true ? "2026-08-15T07:08:42.502Z" : void 0);
37063
37063
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
37064
37064
  return cached2;
37065
37065
  }
@@ -37131,8 +37131,8 @@ var require_dist3 = __commonJS({
37131
37131
  }
37132
37132
  return { valid: errors.length === 0, errors, config: errors.length === 0 ? config2 : void 0 };
37133
37133
  }
37134
- function parseConfigText2(path55, text) {
37135
- if (/\.json$/i.test(path55)) return JSON.parse(text);
37134
+ function parseConfigText2(path56, text) {
37135
+ if (/\.json$/i.test(path56)) return JSON.parse(text);
37136
37136
  return yaml2.load(text);
37137
37137
  }
37138
37138
  function loadChangeImpactConfig(repoRoot) {
@@ -37833,20 +37833,20 @@ var require_dist3 = __commonJS({
37833
37833
  try {
37834
37834
  const paths = await readSubmodulePaths(repo, options);
37835
37835
  const ignoreSet = new Set(options.submoduleIgnorePaths || []);
37836
- const visiblePaths = paths.filter((path55) => !ignoreSet.has(path55));
37836
+ const visiblePaths = paths.filter((path56) => !ignoreSet.has(path56));
37837
37837
  const expectedByPath = await readGitlinkExpectedShas(repo, visiblePaths, options);
37838
37838
  const lastCheckedAt = Date.now();
37839
37839
  const headOidByPath = /* @__PURE__ */ new Map();
37840
37840
  const submodules = await Promise.all(
37841
- visiblePaths.map(async (path55) => {
37842
- const repoPath = repo.repoRoot + "/" + path55;
37843
- const expected = expectedByPath.get(path55) ?? null;
37841
+ visiblePaths.map(async (path56) => {
37842
+ const repoPath = repo.repoRoot + "/" + path56;
37843
+ const expected = expectedByPath.get(path56) ?? null;
37844
37844
  const worktree = await readSubmoduleWorktreeStatus(repo, repoPath, options);
37845
37845
  const actual = worktree.headOid;
37846
- if (actual) headOidByPath.set(path55, actual);
37846
+ if (actual) headOidByPath.set(path56, actual);
37847
37847
  const outOfSync = actual === null ? true : expected !== null && expected !== actual;
37848
37848
  return {
37849
- path: path55,
37849
+ path: path56,
37850
37850
  // Prefer the recorded gitlink SHA (matches the legacy column); fall back
37851
37851
  // to the checked-out SHA so the field is never empty when both are known.
37852
37852
  commit: expected ?? actual ?? "",
@@ -40848,11 +40848,11 @@ child.on('exit', () => process.exit(0));
40848
40848
  }
40849
40849
  function windowsExtraBinDirs() {
40850
40850
  const dirs = [];
40851
- const fs57 = require("fs");
40851
+ const fs58 = require("fs");
40852
40852
  const push = (dir) => {
40853
40853
  if (!dir) return;
40854
40854
  try {
40855
- if (fs57.existsSync(dir)) dirs.push(dir);
40855
+ if (fs58.existsSync(dir)) dirs.push(dir);
40856
40856
  } catch {
40857
40857
  }
40858
40858
  };
@@ -40868,12 +40868,12 @@ child.on('exit', () => process.exit(0));
40868
40868
  }
40869
40869
  function unixExtraBinDirs() {
40870
40870
  const dirs = [];
40871
- const fs57 = require("fs");
40871
+ const fs58 = require("fs");
40872
40872
  const home = os42.homedir();
40873
40873
  const push = (dir) => {
40874
40874
  if (!dir) return;
40875
40875
  try {
40876
- if (fs57.existsSync(dir)) dirs.push(dir);
40876
+ if (fs58.existsSync(dir)) dirs.push(dir);
40877
40877
  } catch {
40878
40878
  }
40879
40879
  };
@@ -40912,9 +40912,9 @@ child.on('exit', () => process.exit(0));
40912
40912
  for (const ext of exes) {
40913
40913
  const fullPath = path8.join(p, trimmed + ext);
40914
40914
  try {
40915
- const fs57 = require("fs");
40916
- if (fs57.existsSync(fullPath)) {
40917
- const stat2 = fs57.statSync(fullPath);
40915
+ const fs58 = require("fs");
40916
+ if (fs58.existsSync(fullPath)) {
40917
+ const stat2 = fs58.statSync(fullPath);
40918
40918
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
40919
40919
  return fullPath;
40920
40920
  }
@@ -40928,12 +40928,12 @@ child.on('exit', () => process.exit(0));
40928
40928
  function isScriptBinary(binaryPath) {
40929
40929
  if (!path8.isAbsolute(binaryPath)) return false;
40930
40930
  try {
40931
- const fs57 = require("fs");
40932
- const resolved = fs57.realpathSync(binaryPath);
40931
+ const fs58 = require("fs");
40932
+ const resolved = fs58.realpathSync(binaryPath);
40933
40933
  const head = Buffer.alloc(8);
40934
- const fd = fs57.openSync(resolved, "r");
40935
- fs57.readSync(fd, head, 0, 8, 0);
40936
- fs57.closeSync(fd);
40934
+ const fd = fs58.openSync(resolved, "r");
40935
+ fs58.readSync(fd, head, 0, 8, 0);
40936
+ fs58.closeSync(fd);
40937
40937
  let i = 0;
40938
40938
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
40939
40939
  return head[i] === 35 && head[i + 1] === 33;
@@ -40944,12 +40944,12 @@ child.on('exit', () => process.exit(0));
40944
40944
  function looksLikeMachOOrElf(filePath) {
40945
40945
  if (!path8.isAbsolute(filePath)) return false;
40946
40946
  try {
40947
- const fs57 = require("fs");
40948
- const resolved = fs57.realpathSync(filePath);
40947
+ const fs58 = require("fs");
40948
+ const resolved = fs58.realpathSync(filePath);
40949
40949
  const buf = Buffer.alloc(8);
40950
- const fd = fs57.openSync(resolved, "r");
40951
- fs57.readSync(fd, buf, 0, 8, 0);
40952
- fs57.closeSync(fd);
40950
+ const fd = fs58.openSync(resolved, "r");
40951
+ fs58.readSync(fd, buf, 0, 8, 0);
40952
+ fs58.closeSync(fd);
40953
40953
  let i = 0;
40954
40954
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
40955
40955
  const b = buf.subarray(i);
@@ -42378,12 +42378,12 @@ ${error48.message || ""}`;
42378
42378
  if (!Array.isArray(value)) return void 0;
42379
42379
  const submodules = value.map((entry) => {
42380
42380
  const submodule = readRecord(entry);
42381
- const path55 = readString2(submodule.path);
42381
+ const path56 = readString2(submodule.path);
42382
42382
  const commit = readString2(submodule.commit);
42383
- const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path55);
42384
- if (!path55 || !commit) return null;
42383
+ const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path56);
42384
+ if (!path56 || !commit) return null;
42385
42385
  const result = {
42386
- path: path55,
42386
+ path: path56,
42387
42387
  commit,
42388
42388
  dirty: readBoolean(submodule.dirty) ?? false,
42389
42389
  outOfSync: readBoolean(submodule.outOfSync, submodule.out_of_sync) ?? false,
@@ -42965,6 +42965,7 @@ ${error48.message || ""}`;
42965
42965
  "mesh_status",
42966
42966
  "mesh_list_nodes",
42967
42967
  "mesh_enqueue_task",
42968
+ "mesh_enqueue_batch",
42968
42969
  "mesh_view_queue",
42969
42970
  "mesh_queue_cancel",
42970
42971
  "mesh_queue_requeue",
@@ -43158,10 +43159,10 @@ ${error48.message || ""}`;
43158
43159
  return (0, import_path5.join)(getConfigDir2(), "meshes.json");
43159
43160
  }
43160
43161
  function loadMeshConfig(options = {}) {
43161
- const path55 = getMeshConfigPath();
43162
- if (!(0, import_fs5.existsSync)(path55)) return { meshes: [] };
43162
+ const path56 = getMeshConfigPath();
43163
+ if (!(0, import_fs5.existsSync)(path56)) return { meshes: [] };
43163
43164
  try {
43164
- const raw = JSON.parse((0, import_fs5.readFileSync)(path55, "utf-8"));
43165
+ const raw = JSON.parse((0, import_fs5.readFileSync)(path56, "utf-8"));
43165
43166
  if (!raw || !Array.isArray(raw.meshes)) return { meshes: [] };
43166
43167
  const config2 = raw;
43167
43168
  const migrated = migrateLoadedMeshConfig(config2);
@@ -43259,8 +43260,8 @@ ${error48.message || ""}`;
43259
43260
  return tags.length ? tags : void 0;
43260
43261
  }
43261
43262
  function saveMeshConfig(config2) {
43262
- const path55 = getMeshConfigPath();
43263
- (0, import_fs5.writeFileSync)(path55, JSON.stringify(config2, null, 2), { encoding: "utf-8", mode: 384 });
43263
+ const path56 = getMeshConfigPath();
43264
+ (0, import_fs5.writeFileSync)(path56, JSON.stringify(config2, null, 2), { encoding: "utf-8", mode: 384 });
43264
43265
  }
43265
43266
  function normalizeRepoIdentity(remoteUrl) {
43266
43267
  let identity = remoteUrl.trim().replace(/[?#].*$/, "").replace(/\/+$/, "");
@@ -43268,8 +43269,8 @@ ${error48.message || ""}`;
43268
43269
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(identity)) {
43269
43270
  try {
43270
43271
  const url2 = new URL(identity);
43271
- const path55 = decodeURIComponent(url2.pathname).replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
43272
- if (url2.hostname && path55) return `${url2.hostname.toLowerCase()}/${path55}`;
43272
+ const path56 = decodeURIComponent(url2.pathname).replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
43273
+ if (url2.hostname && path56) return `${url2.hostname.toLowerCase()}/${path56}`;
43273
43274
  } catch {
43274
43275
  }
43275
43276
  }
@@ -45927,59 +45928,59 @@ Next step: ${nextStep}`;
45927
45928
  function isNonEmptyString(value) {
45928
45929
  return typeof value === "string" && value.length > 0;
45929
45930
  }
45930
- function assertCoordinatorIdentity(raw, path55) {
45931
+ function assertCoordinatorIdentity(raw, path56) {
45931
45932
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
45932
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path55, "must be an object");
45933
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path56, "must be an object");
45933
45934
  }
45934
45935
  const obj = raw;
45935
45936
  if (!isNonEmptyString(obj.daemonId)) {
45936
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.daemonId`, "must be a non-empty string");
45937
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.daemonId`, "must be a non-empty string");
45937
45938
  }
45938
45939
  if (!isNonEmptyString(obj.coordinatorRunId)) {
45939
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.coordinatorRunId`, "must be a non-empty string");
45940
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.coordinatorRunId`, "must be a non-empty string");
45940
45941
  }
45941
45942
  const sessionId = obj.sessionId;
45942
45943
  if (sessionId !== void 0 && !isNonEmptyString(sessionId)) {
45943
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.sessionId`, "must be a non-empty string when provided");
45944
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.sessionId`, "must be a non-empty string when provided");
45944
45945
  }
45945
45946
  return sessionId !== void 0 ? { daemonId: obj.daemonId, coordinatorRunId: obj.coordinatorRunId, sessionId } : { daemonId: obj.daemonId, coordinatorRunId: obj.coordinatorRunId };
45946
45947
  }
45947
- function assertPendingMeshCoordinatorEventV2(raw, path55 = "$") {
45948
+ function assertPendingMeshCoordinatorEventV2(raw, path56 = "$") {
45948
45949
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
45949
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path55, "must be an object");
45950
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path56, "must be an object");
45950
45951
  }
45951
45952
  const obj = raw;
45952
45953
  if (!isSupportedMeshProtocolVersion(obj.protocolVersion)) {
45953
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.protocolVersion`, `must be one of ${SUPPORTED_MESH_PROTOCOL_VERSIONS.join(", ")}`);
45954
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.protocolVersion`, `must be one of ${SUPPORTED_MESH_PROTOCOL_VERSIONS.join(", ")}`);
45954
45955
  }
45955
45956
  if (!isNonEmptyString(obj.eventId)) {
45956
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.eventId`, "must be a non-empty string");
45957
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.eventId`, "must be a non-empty string");
45957
45958
  }
45958
45959
  if (!isMeshEventScope(obj.scope)) {
45959
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.scope`, `must be one of ${MESH_EVENT_SCOPES.join(", ")}`);
45960
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.scope`, `must be one of ${MESH_EVENT_SCOPES.join(", ")}`);
45960
45961
  }
45961
45962
  if (!isNonEmptyString(obj.event)) {
45962
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.event`, "must be a non-empty string");
45963
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.event`, "must be a non-empty string");
45963
45964
  }
45964
45965
  if (!isNonEmptyString(obj.meshId)) {
45965
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.meshId`, "must be a non-empty string");
45966
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.meshId`, "must be a non-empty string");
45966
45967
  }
45967
- const dispatchedBy = assertCoordinatorIdentity(obj.dispatchedBy, `${path55}.dispatchedBy`);
45968
+ const dispatchedBy = assertCoordinatorIdentity(obj.dispatchedBy, `${path56}.dispatchedBy`);
45968
45969
  if (obj.scope === "unicast") {
45969
45970
  if (!obj.intendedFor) {
45970
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.intendedFor`, "unicast scope requires intendedFor");
45971
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.intendedFor`, "unicast scope requires intendedFor");
45971
45972
  }
45972
45973
  } else if (obj.intendedFor !== void 0) {
45973
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.intendedFor`, "only unicast scope may set intendedFor");
45974
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.intendedFor`, "only unicast scope may set intendedFor");
45974
45975
  }
45975
- const intendedFor = obj.intendedFor ? assertCoordinatorIdentity(obj.intendedFor, `${path55}.intendedFor`) : void 0;
45976
+ const intendedFor = obj.intendedFor ? assertCoordinatorIdentity(obj.intendedFor, `${path56}.intendedFor`) : void 0;
45976
45977
  const metadata = obj.metadataEvent && typeof obj.metadataEvent === "object" && !Array.isArray(obj.metadataEvent) ? obj.metadataEvent : null;
45977
45978
  if (!metadata) {
45978
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.metadataEvent`, "must be an object");
45979
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.metadataEvent`, "must be an object");
45979
45980
  }
45980
45981
  const queuedAt = typeof obj.queuedAt === "number" && Number.isFinite(obj.queuedAt) ? obj.queuedAt : null;
45981
45982
  if (queuedAt === null) {
45982
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path55}.queuedAt`, "must be a finite number");
45983
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path56}.queuedAt`, "must be a finite number");
45983
45984
  }
45984
45985
  return {
45985
45986
  event: obj.event,
@@ -47168,6 +47169,7 @@ Next step: ${nextStep}`;
47168
47169
  __export2(mesh_work_queue_exports, {
47169
47170
  ACTIVE_MESH_QUEUE_STATUSES: () => ACTIVE_MESH_QUEUE_STATUSES,
47170
47171
  HISTORICAL_MESH_QUEUE_STATUSES: () => HISTORICAL_MESH_QUEUE_STATUSES,
47172
+ MESH_TASK_GRAPH_MAX_TASKS: () => MESH_TASK_GRAPH_MAX_TASKS,
47171
47173
  MESH_TASK_MODES: () => MESH_TASK_MODES,
47172
47174
  MESH_TASK_PRIORITIES: () => MESH_TASK_PRIORITIES,
47173
47175
  NOT_BEFORE_RELATIVE_THRESHOLD_MS: () => NOT_BEFORE_RELATIVE_THRESHOLD_MS,
@@ -47186,6 +47188,7 @@ Next step: ${nextStep}`;
47186
47188
  deleteDirectDispatchesByTaskId: () => deleteDirectDispatchesByTaskId,
47187
47189
  describeTaskDependencyState: () => describeTaskDependencyState,
47188
47190
  enqueueTask: () => enqueueTask,
47191
+ enqueueTaskGraph: () => enqueueTaskGraph,
47189
47192
  expireTaskTargetPin: () => expireTaskTargetPin,
47190
47193
  formatMeshTaskModeViolations: () => formatMeshTaskModeViolations,
47191
47194
  getActiveDirectDispatches: () => getActiveDirectDispatches,
@@ -47573,11 +47576,11 @@ Next step: ${nextStep}`;
47573
47576
  const pinnedProvider = typeof providerType === "string" && providerType.trim() ? providerType.trim() : void 0;
47574
47577
  const providerTags = pinnedProvider ? [pinnedProvider] : readNodeProviderTypes(node?.policy);
47575
47578
  const worktreeBranch = typeof node?.worktreeBranch === "string" && node.worktreeBranch.trim() ? node.worktreeBranch.trim() : null;
47576
- const os30 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
47579
+ const os31 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
47577
47580
  const arch2 = readNodeOverride(node, "arch") ?? readNodeReporter(node, "arch") ?? process.arch;
47578
47581
  return normalizeMeshCapabilityTags([
47579
47582
  ...Array.isArray(node?.capabilities) ? node.capabilities : [],
47580
- `os=${os30}`,
47583
+ `os=${os31}`,
47581
47584
  `arch=${arch2}`,
47582
47585
  ...providerTags.map((p) => `provider=${p}`),
47583
47586
  // Worktree nodes automatically expose a "worktree=<branch>" tag so that
@@ -47744,6 +47747,48 @@ Next step: ${nextStep}`;
47744
47747
  scheduleMissionCloseCandidateCheck(meshId, [result]);
47745
47748
  return result;
47746
47749
  }
47750
+ function enqueueTaskGraph(meshId, specs, opts) {
47751
+ requireMeshHostQueueOwner(opts);
47752
+ if (!Array.isArray(specs) || specs.length === 0) {
47753
+ throw new Error("empty_task_graph: enqueueTaskGraph requires at least one task spec");
47754
+ }
47755
+ if (specs.length > MESH_TASK_GRAPH_MAX_TASKS) {
47756
+ throw new Error(`task_graph_too_large: ${specs.length} tasks exceeds the ${MESH_TASK_GRAPH_MAX_TASKS}-task cap for one atomic enqueue`);
47757
+ }
47758
+ const ids = specs.map(() => (0, import_crypto8.randomUUID)());
47759
+ const idByRef = /* @__PURE__ */ new Map();
47760
+ specs.forEach((spec, i) => {
47761
+ const ref = typeof spec.ref === "string" ? spec.ref.trim() : "";
47762
+ if (!ref) return;
47763
+ if (idByRef.has(ref)) {
47764
+ throw new Error(`duplicate_task_ref: ref '${ref}' is used by more than one task in this batch`);
47765
+ }
47766
+ idByRef.set(ref, ids[i]);
47767
+ });
47768
+ const store = MeshRuntimeStore.getInstance();
47769
+ return withQueueLock(meshId, () => {
47770
+ const inserted = [];
47771
+ specs.forEach((spec, i) => {
47772
+ const { ref, message, ...taskOpts } = spec;
47773
+ const label = ref ? `'${ref}'` : `#${i}`;
47774
+ const dependsOn = normalizeDependsOn(spec.dependsOn).map((dep) => {
47775
+ const mapped = idByRef.get(dep);
47776
+ if (mapped) return mapped;
47777
+ if (store.findQueueEntryById(meshId, dep)) return dep;
47778
+ throw new Error(
47779
+ `unknown_dependency: task ${label} depends on '${dep}', which is neither a ref in this batch nor an existing task id` + (idByRef.size ? ` (batch refs: ${[...idByRef.keys()].join(", ")})` : "")
47780
+ );
47781
+ });
47782
+ inserted.push(enqueueTask(meshId, message, {
47783
+ ...taskOpts,
47784
+ dependsOn,
47785
+ id: ids[i],
47786
+ ...opts?.ownerRole ? { ownerRole: opts.ownerRole } : {}
47787
+ }));
47788
+ });
47789
+ return inserted;
47790
+ });
47791
+ }
47747
47792
  function recordDirectDispatchTask(meshId, message, opts) {
47748
47793
  const missionId = typeof opts.missionId === "string" ? opts.missionId.trim() : "";
47749
47794
  const taskId = typeof opts.id === "string" ? opts.id.trim() : "";
@@ -48195,6 +48240,7 @@ Next step: ${nextStep}`;
48195
48240
  var EVIDENCE_ONLY_WRAPPERS;
48196
48241
  var GIT_MUTATION_SUBCOMMANDS;
48197
48242
  var GIT_STASH_READONLY_SUBCOMMANDS;
48243
+ var MESH_TASK_GRAPH_MAX_TASKS;
48198
48244
  var DEPENDENCY_FAILURE_TERMINALS;
48199
48245
  var TERMINAL_TASK_STATUSES;
48200
48246
  var lastCancelledTaskAssignment;
@@ -48271,6 +48317,7 @@ Next step: ${nextStep}`;
48271
48317
  "prune"
48272
48318
  ]);
48273
48319
  GIT_STASH_READONLY_SUBCOMMANDS = /* @__PURE__ */ new Set(["list", "show"]);
48320
+ MESH_TASK_GRAPH_MAX_TASKS = 50;
48274
48321
  DEPENDENCY_FAILURE_TERMINALS = /* @__PURE__ */ new Set(["failed", "cancelled"]);
48275
48322
  TERMINAL_TASK_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
48276
48323
  lastCancelledTaskAssignment = /* @__PURE__ */ new Map();
@@ -49050,10 +49097,10 @@ Next step: ${nextStep}`;
49050
49097
  this.migratedMeshIds.add(meshId);
49051
49098
  const count = this.db.prepare("SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?").get(meshId);
49052
49099
  if (count.count > 0) return;
49053
- const path55 = legacyQueuePath(meshId);
49054
- if (!(0, import_fs6.existsSync)(path55)) return;
49100
+ const path56 = legacyQueuePath(meshId);
49101
+ if (!(0, import_fs6.existsSync)(path56)) return;
49055
49102
  try {
49056
- const entries = JSON.parse((0, import_fs6.readFileSync)(path55, "utf-8"));
49103
+ const entries = JSON.parse((0, import_fs6.readFileSync)(path56, "utf-8"));
49057
49104
  if (!Array.isArray(entries)) return;
49058
49105
  const insert = this.db.prepare(`
49059
49106
  INSERT OR REPLACE INTO mesh_queue (
@@ -51185,10 +51232,10 @@ Next step: ${nextStep}`;
51185
51232
  }
51186
51233
  }
51187
51234
  function readArchivedCounts(meshId) {
51188
- const path55 = getArchivedCountsPath(meshId);
51189
- if (!(0, import_fs7.existsSync)(path55)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
51235
+ const path56 = getArchivedCountsPath(meshId);
51236
+ if (!(0, import_fs7.existsSync)(path56)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
51190
51237
  try {
51191
- return JSON.parse((0, import_fs7.readFileSync)(path55, "utf-8"));
51238
+ return JSON.parse((0, import_fs7.readFileSync)(path56, "utf-8"));
51192
51239
  } catch {
51193
51240
  return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
51194
51241
  }
@@ -52638,7 +52685,7 @@ ${rules.join("\n")}`;
52638
52685
  - **Match concurrency to task kind.** Read-only investigation (\`live_debug_readonly\`) carries no isolation or merge cost and is exempt from the one-write-per-node limit: dispatch every independent read-only task at once, up to the read-only cap shown in Policy \u2014 they need neither a free node nor a worktree. Write tasks (\`code_change\`) are limited to ONE active task per node and each needs its OWN branch workspace, so clone a worktree per write task rather than queueing them onto one node \u2014 **or spreading them across base nodes, which is NOT a substitute**: a mesh with four base nodes still has zero branch isolation, because each base node is one shared checkout of the same branch. Ramp up cautiously only when tasks share a base branch or a submodule pointer, where landing order actually matters. Never launch a second session onto work already in flight for the same issue, and never duplicate a session because \`mesh_read_chat\` shows no final message while tool/terminal activity is ongoing. All of this is about *unrelated* work running side by side; it does not mean splitting one line of work across sessions \u2014 successive stages of the same investigation belong in the session that already has the context (see Workflow 3f).
52639
52686
  - **Check history first.** Call \`mesh_task_history\` at session start to avoid duplicate work and inform recovery. On failure, read task history before retrying.
52640
52687
  - **Don't reopen already-done work after a resume.** Before reopening a reported issue after context compaction or session resume, check current git state and recent session context. If another session has already completed the work, continue from the existing diff/commit instead of starting a duplicate investigation.
52641
- - **Sequence shared-base-moving merges.** Parallel dispatch is encouraged, but merging one worktree can advance another in-flight worktree's base \u2014 especially a shared submodule pointer \u2014 turning a clean fast-forward into a diverged rebase (patch-equivalence correctly blocks this). Before merging an in-flight worktree while siblings are also in flight, land in an intentional order, re-clone long-running worktrees from the advanced base, or expect to manually rebase + ff-only the laggards; merging an independent fix mid-flight can strand siblings into a rebase.
52688
+ - **Sequence shared-base-moving merges \u2014 use \`mesh_refine_batch\` for two or more.** Merging one worktree advances another in-flight worktree's base \u2014 especially a shared submodule pointer \u2014 turning a clean fast-forward into a diverged rebase. When you have 2+ sibling worktrees to land, pass them to \`mesh_refine_batch\` (dry-run first) instead of calling \`mesh_refine_node\` once per node: it picks a conflict-aware order (non-submodule first, submodule-touching serialized last), and because each node re-resolves the base and auto-rebases before its own gates, siblings that fall behind are rebased for you rather than by hand. It also avoids the \`base_locked\` contention that concurrent single-node refines cause. It is not a conflict solver \u2014 a real content or submodule conflict still lands that node in \`blocked_review\` for manual resolution while the rest of the batch proceeds. Only drop to per-node \`mesh_refine_node\` for a single branch, or to hand-resolve a node the batch reported blocked.
52642
52689
  - **Converge branches.** After worktree tasks: refine/fast-forward, or classify as \`pushed_feature_branch_needs_merge\` / \`blocked_review\` / \`cleanup_candidate\` / \`not_mergeable\`. Clean up with \`mesh_remove_node\`.
52643
52690
  - **Refinery is config-driven.** \`mesh_refine_node\` must run validation from \`.adhdev/refine.{json,yaml,yml}\` or \`repo-mesh.refine.*\`. Heuristics are scaffolding only.
52644
52691
  - **Submodule reachability = publish-needed.** \`submodule_reachability_failed\` \u2192 classify as \`blocked_review\`, request user approval to push to submodule main, then rerun \`mesh_refine_node\`.
@@ -52688,6 +52735,7 @@ When you compose the task message you dispatch to a node, include this requireme
52688
52735
  | \`mesh_status\` | Check all nodes' health, git state, active sessions, and branch convergence |
52689
52736
  | \`mesh_list_nodes\` | List nodes with workspace paths |
52690
52737
  | \`mesh_enqueue_task\` | Add a task to the pull-based work queue; idle nodes auto-claim |
52738
+ | \`mesh_enqueue_batch\` | Atomically enqueue a dependency-wired SET of tasks (all-or-nothing \u2014 a mid-batch error rolls the whole batch back); \`depends_on\` may name batch-local \`ref\` labels, forward references allowed |
52691
52739
  | \`mesh_view_queue\` | View queue status \u2014 pending, assigned, completed, failed, cancelled tasks |
52692
52740
  | \`mesh_queue_cancel\` | Cancel a queue task without deleting audit history |
52693
52741
  | \`mesh_queue_requeue\` | Return a task to pending for retry; clears stale session targets |
@@ -52745,7 +52793,7 @@ Before doing any coordinator work, confirm that the actual callable tool list in
52745
52793
  WORKFLOW_SECTION = `## Orchestration Workflow
52746
52794
 
52747
52795
  1. **Assess** \u2014 Call \`mesh_status\` to see which nodes are healthy and available. Check \`mesh_task_history\` to understand what has already been done in this mesh \u2014 previous delegations, completions, and failures.
52748
- 2. **Plan** \u2014 Decompose the user's request into independent tasks for parallel execution, or sequential tasks when dependencies exist. If \`mesh_task_history\` shows a recent failure for a task, decide whether to retry or reassign. **For multi-task work, create a mission first**: call \`mesh_mission_upsert\` with a title and goal, then attach every enqueued task with \`mission_id\`. Express "B after A" ordering with \`depends_on\` on the queue task instead of waiting and polling \u2014 the system claims dependents automatically when their dependencies complete. When the mission's outcome is decided, update its status (\`completed\`/\`abandoned\`) via \`mesh_mission_upsert\`. If the prompt already shows an **Active Mission**, continue it from its current task state \u2014 do not re-enqueue tasks that already exist.
52796
+ 2. **Plan** \u2014 Decompose the user's request into independent tasks for parallel execution, or sequential tasks when dependencies exist. If \`mesh_task_history\` shows a recent failure for a task, decide whether to retry or reassign. **For multi-task work, create a mission first**: call \`mesh_mission_upsert\` with a title and goal, then attach every enqueued task with \`mission_id\`. Express "B after A" ordering with \`depends_on\` on the queue task instead of waiting and polling \u2014 the system claims dependents automatically when their dependencies complete. When the plan is a multi-task graph, submit it with ONE \`mesh_enqueue_batch\` call instead of N sequential enqueues: the batch inserts atomically (a mid-batch error such as a cycle or bad difficulty rolls the whole set back, so no half-registered chain), and each task's \`depends_on\` may name sibling tasks by their batch-local \`ref\` label, forward references included. When the mission's outcome is decided, update its status (\`completed\`/\`abandoned\`) via \`mesh_mission_upsert\`. If the prompt already shows an **Active Mission**, continue it from its current task state \u2014 do not re-enqueue tasks that already exist.
52749
52797
  3. **Queue / Delegate** \u2014 The Mesh uses an autonomous pull-based Work Queue:
52750
52798
  a. **General Tasks**: Enqueue tasks using \`mesh_enqueue_task\`. Idle node agents will automatically pull tasks from the queue and begin working.
52751
52799
  b. **Node Preparation**: Reuse an existing idle session on the correct node/provider before launching a new chat/session. Call \`mesh_launch_session\` only when no suitable session exists, when the user explicitly asks for a fresh provider/session, or when branch/worktree isolation requires it. **A node is not limited to one live session for read-only work** \u2014 \`readonly\`/\`live_debug_readonly\` tasks are exempt from the one-active-per-node invariant, so the SAME node can auto-launch multiple concurrent read-only sessions with no worktree needed. Cloning a worktree costs roughly 10 seconds, so it is cheap enough to create one whenever write work needs a free node; use it for branch isolation, for parallel write tasks (one active write per node), or when a node's read-only queue is deep enough that a second node would clearly finish faster \u2014 call \`mesh_clone_node\` to create the worktree node first.
@@ -52762,7 +52810,7 @@ Before doing any coordinator work, confirm that the actual callable tool list in
52762
52810
  4. **Monitor** \u2014 Prefer event-driven completion/status notifications. Do **not** poll \`mesh_read_chat\` repeatedly. Do **not** repeatedly call \`mesh_status\` or \`mesh_view_queue\` just to wait for assigned/generating work. After dispatching a direct or queued task, send one progress update with the task/session handle, then stop. Wait for \`pendingCoordinatorEvents\` or another completion/approval/status signal, an explicit user status request, or a real timeout/stall signal before reading status/chat/queue again. Use at most one compact \`mesh_read_chat\` check after a terminal signal. Handle approvals via \`mesh_approve\`. **Proactively parallelize new work.** When the user reports a new bug or asks for new work, start it immediately if it is independent of in-flight tasks and there is headroom under \`maxParallelTasks\` \u2014 do not wait for a current task to finish or for the user to prompt you to parallelize. Read-only diagnosis (\`live_debug_readonly\`) has no isolation or merge cost, so dispatch it in parallel right away. The no-polling / concurrency-limit rules constrain *re-checking or duplicating already-dispatched work*; they are **not** a reason to defer starting a new, independent task.
52763
52811
  5. **Verify** \u2014 When a task reports completion or git work is visible, call \`mesh_git_status\` to verify changes were made.
52764
52812
  6. **Checkpoint** \u2014 Call \`mesh_checkpoint\` to save the work.
52765
- 7. **Converge branches** \u2014 Before marking any task complete, classify every touched node/branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. Use \`mesh_status\` branchConvergenceSummary. For obvious clean branch catch-up (ahead 0, behind > 0, upstream fresh, no dirty/stash/submodule issues), use \`mesh_fast_forward_node\` dry-run first and execute only when explicitly safe/approved; this avoids consuming an agent session. Use \`mesh_refine_node\` for clean worktree branches when safe. Before/refine merging root commits that contain submodule gitlink changes, require each submodule commit to be reachable from the configured submodule remote main branch, not merely present on a feature ref or local checkout. If \`mesh_refine_node\` returns \`submodule_reachability_failed\` or publish-required evidence, keep the public convergence bucket as \`blocked_review\`; unless \`allowAutoPublishSubmoduleMainCommits\` is explicitly enabled and Refinery reports successful non-force publish plus post-publish verification, ask the user for explicit approval to push/publish the unreachable submodule commit(s) to submodule main, then rerun \`mesh_refine_node\`. Do not merge the root branch until the submodule commit(s) are reachable from submodule origin/main. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.
52813
+ 7. **Converge branches** \u2014 Before marking any task complete, classify every touched node/branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. Use \`mesh_status\` branchConvergenceSummary. For obvious clean branch catch-up (ahead 0, behind > 0, upstream fresh, no dirty/stash/submodule issues), use \`mesh_fast_forward_node\` dry-run first and execute only when explicitly safe/approved; this avoids consuming an agent session. Use \`mesh_refine_node\` for clean worktree branches when safe \u2014 but when 2+ sibling worktrees share a base, converge them with \`mesh_refine_batch\` rather than repeated single-node calls (see the sequencing rule in Rules). Before/refine merging root commits that contain submodule gitlink changes, require each submodule commit to be reachable from the configured submodule remote main branch, not merely present on a feature ref or local checkout. If \`mesh_refine_node\` returns \`submodule_reachability_failed\` or publish-required evidence, keep the public convergence bucket as \`blocked_review\`; unless \`allowAutoPublishSubmoduleMainCommits\` is explicitly enabled and Refinery reports successful non-force publish plus post-publish verification, ask the user for explicit approval to push/publish the unreachable submodule commit(s) to submodule main, then rerun \`mesh_refine_node\`. Do not merge the root branch until the submodule commit(s) are reachable from submodule origin/main. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.
52766
52814
  8. **Clean up** \u2014 Remove worktree nodes via \`mesh_remove_node\` after their work is merged or no longer needed.
52767
52815
  9. **Report** \u2014 Summarize what was done, what changed, any issues, and the branch convergence state.
52768
52816
 
@@ -53247,8 +53295,8 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
53247
53295
  if (rejectedCommands.length) errors.push("one or more validation commands are invalid");
53248
53296
  return { valid: errors.length === 0, errors, bootstrapCommands, commands, rejectedCommands, bootstrapMode, deprecationWarnings };
53249
53297
  }
53250
- function parseConfigText3(path55, text) {
53251
- if (/\.json$/i.test(path55)) return JSON.parse(text);
53298
+ function parseConfigText3(path56, text) {
53299
+ if (/\.json$/i.test(path56)) return JSON.parse(text);
53252
53300
  return yaml3.load(text);
53253
53301
  }
53254
53302
  function loadMeshRefineConfig(mesh, workspace) {
@@ -53674,8 +53722,8 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
53674
53722
  const lines = porcelain.split(/\r?\n/).filter((line) => line.length > 0);
53675
53723
  for (const line of lines) {
53676
53724
  const status = line.slice(0, 2);
53677
- const path55 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
53678
- const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path55);
53725
+ const path56 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
53726
+ const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path56);
53679
53727
  if (!isGitlinkPointerMove) return false;
53680
53728
  }
53681
53729
  return true;
@@ -53710,8 +53758,8 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
53710
53758
  if (node?.worktreeBootstrap?.status !== "running") return false;
53711
53759
  return !isWorktreeBootstrapStaleRunning(node, nowMs);
53712
53760
  }
53713
- function parseConfigText4(path55, text) {
53714
- if (/\.json$/i.test(path55)) return JSON.parse(text);
53761
+ function parseConfigText4(path56, text) {
53762
+ if (/\.json$/i.test(path56)) return JSON.parse(text);
53715
53763
  return yaml4.load(text);
53716
53764
  }
53717
53765
  function truncateOutput(value) {
@@ -54065,8 +54113,8 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
54065
54113
  }
54066
54114
  const serverName = mcpConfig.serverName?.trim() || DEFAULT_SERVER_NAME;
54067
54115
  if (mcpConfig.mode === "auto_import") {
54068
- const path55 = mcpConfig.path?.trim();
54069
- if (!path55) {
54116
+ const path56 = mcpConfig.path?.trim();
54117
+ if (!path56) {
54070
54118
  return { kind: "unsupported", reason: "Provider auto-import MCP config is missing a config path" };
54071
54119
  }
54072
54120
  const mcpServer = resolveAdhdevMcpServerLaunch({
@@ -54086,7 +54134,7 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
54086
54134
  return {
54087
54135
  kind: "auto_import",
54088
54136
  serverName,
54089
- configPath: resolveMcpConfigPath(path55, workspace),
54137
+ configPath: resolveMcpConfigPath(path56, workspace),
54090
54138
  configFormat: mcpConfig.format,
54091
54139
  mcpServer
54092
54140
  };
@@ -54300,8 +54348,8 @@ ${rendered}`, "utf-8");
54300
54348
  if (!(0, import_node_fs3.existsSync)(filePath)) return;
54301
54349
  if (owned) {
54302
54350
  try {
54303
- const fs57 = require("fs");
54304
- fs57.unlinkSync(filePath);
54351
+ const fs58 = require("fs");
54352
+ fs58.unlinkSync(filePath);
54305
54353
  } catch {
54306
54354
  }
54307
54355
  return;
@@ -54314,8 +54362,8 @@ ${rendered}`, "utf-8");
54314
54362
  const remaining = (existing.slice(0, openIdx) + existing.slice(closeIdx + CLOSE.length)).replace(/^\s*\n+/, "").replace(/\n+\s*$/, "");
54315
54363
  if (!remaining.trim()) {
54316
54364
  try {
54317
- const fs57 = require("fs");
54318
- fs57.unlinkSync(filePath);
54365
+ const fs58 = require("fs");
54366
+ fs58.unlinkSync(filePath);
54319
54367
  } catch {
54320
54368
  }
54321
54369
  } else {
@@ -54430,10 +54478,10 @@ ${rendered}`, "utf-8");
54430
54478
  return (0, import_path11.join)(getDaemonDataDir(), "mesh-coordinators.json");
54431
54479
  }
54432
54480
  function loadMeshCoordinatorRegistry() {
54433
- const path55 = getRegistryPath();
54434
- if (!(0, import_fs12.existsSync)(path55)) return;
54481
+ const path56 = getRegistryPath();
54482
+ if (!(0, import_fs12.existsSync)(path56)) return;
54435
54483
  try {
54436
- const raw = JSON.parse((0, import_fs12.readFileSync)(path55, "utf-8"));
54484
+ const raw = JSON.parse((0, import_fs12.readFileSync)(path56, "utf-8"));
54437
54485
  if (!Array.isArray(raw)) return;
54438
54486
  _registry.clear();
54439
54487
  for (const entry of raw) {
@@ -61273,6 +61321,102 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
61273
61321
  MAX_TRACKED_CLONED_NODES = 512;
61274
61322
  }
61275
61323
  });
61324
+ function quotaClaimBlockKey(meshId, observation) {
61325
+ return `${meshId}:${observation.nodeId}:${observation.sessionId}:${observation.providerType}`;
61326
+ }
61327
+ function quotaClaimBlockDescription(providerType, block2) {
61328
+ if (block2.reason === PROVIDER_QUOTA_EXHAUSTED_SKIP_REASON) {
61329
+ return `provider '${providerType}' reported quota exhausted`;
61330
+ }
61331
+ return `provider '${providerType}' had ${block2.remainingPercent.toFixed(1)}% ${block2.window} quota remaining (< ${block2.thresholdPercent}% threshold)`;
61332
+ }
61333
+ function rememberBounded(map3, key2, value) {
61334
+ map3.set(key2, value);
61335
+ if (map3.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
61336
+ const oldest = map3.keys().next().value;
61337
+ if (oldest !== void 0) map3.delete(oldest);
61338
+ }
61339
+ }
61340
+ function logQuotaClaimBlockTransition(meshId, observation) {
61341
+ const key2 = quotaClaimBlockKey(meshId, observation);
61342
+ const fingerprint = `${observation.block.reason}:${observation.block.window}:${observation.block.remainingPercent}:${observation.block.thresholdPercent}`;
61343
+ if (lastQuotaClaimBlockLog.get(key2) === fingerprint) return;
61344
+ rememberBounded(lastQuotaClaimBlockLog, key2, fingerprint);
61345
+ LOG2.info("MeshQueue", `QUOTA GATE: deferring queue claim for node ${observation.nodeId} (${observation.sessionId}): ${quotaClaimBlockDescription(observation.providerType, observation.block)} \u2014 trying remaining provider candidates; the task stays pending only if none can claim`);
61346
+ }
61347
+ function clearQuotaClaimBlockState(meshId, nodeId, sessionId, providerType) {
61348
+ lastQuotaClaimBlockLog.delete(quotaClaimBlockKey(meshId, { nodeId, sessionId, providerType }));
61349
+ }
61350
+ function logQuotaClaimFallbackSuccess(blocked, taskId, winner) {
61351
+ if (!blocked.length) return;
61352
+ const detail = blocked.map((item) => quotaClaimBlockDescription(item.providerType, item.block)).join("; ");
61353
+ LOG2.info("MeshQueue", `QUOTA GATE: queue claim fallback succeeded for task ${taskId}: ${detail} \u2192 provider '${winner.providerType}' claimed on node ${winner.nodeId} (${winner.sessionId})`);
61354
+ }
61355
+ function logAllQuotaClaimCandidatesBlocked(meshId, trace, pendingTaskIds) {
61356
+ if (!trace.blocked.length || trace.clear > 0 || trace.blocked.length !== trace.evaluated) return;
61357
+ const detail = trace.blocked.map((item) => `${item.nodeId}/${quotaClaimBlockDescription(item.providerType, item.block)}`).join("; ");
61358
+ const fingerprint = `${pendingTaskIds.slice().sort().join(",")}|${detail}`;
61359
+ if (lastAllQuotaClaimBlockedLog.get(meshId) === fingerprint) return;
61360
+ rememberBounded(lastAllQuotaClaimBlockedLog, meshId, fingerprint);
61361
+ LOG2.info("MeshQueue", `QUOTA GATE: every idle provider candidate was quota-gated for mesh ${meshId} (${detail}); task(s) ${pendingTaskIds.join(", ") || "pending"} remain queued until a quota window resets`);
61362
+ }
61363
+ function clearAllQuotaClaimCandidatesBlockedState(meshId) {
61364
+ lastAllQuotaClaimBlockedLog.delete(meshId);
61365
+ }
61366
+ function logAutoLaunchQuotaFallbackSuccess(resolved, taskId, nodeId, sessionId) {
61367
+ if (!resolved.providerType || !resolved.quotaGated?.length) return;
61368
+ const detail = resolved.quotaGated.map((item) => quotaClaimBlockDescription(item.providerType, item.block)).join("; ");
61369
+ LOG2.info("MeshQueue", `QUOTA GATE: auto-launch fallback succeeded for task ${taskId} on node ${nodeId}: ${detail} \u2192 spawned provider '${resolved.providerType}'${sessionId ? ` (${sessionId})` : ""}`);
61370
+ }
61371
+ function recordAutoLaunchEvent(meshId, args) {
61372
+ const dedupKey = `${meshId}:${args.taskId}`;
61373
+ const currentSig = `${args.phase}|${args.reason || ""}`;
61374
+ if (args.phase === "skipped" && lastAutoLaunchLedgerKey.get(dedupKey) === currentSig) {
61375
+ return;
61376
+ }
61377
+ lastAutoLaunchLedgerKey.set(dedupKey, currentSig);
61378
+ if (lastAutoLaunchLedgerKey.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
61379
+ const oldest = lastAutoLaunchLedgerKey.keys().next().value;
61380
+ if (oldest !== void 0) lastAutoLaunchLedgerKey.delete(oldest);
61381
+ }
61382
+ try {
61383
+ appendLedgerEntry(meshId, {
61384
+ kind: "session_auto_launch",
61385
+ nodeId: args.nodeId,
61386
+ sessionId: args.sessionId,
61387
+ providerType: args.providerType,
61388
+ // (B) promote taskId so this entry joins the task lifecycle timeline.
61389
+ ...args.taskId ? { taskId: args.taskId } : {},
61390
+ payload: {
61391
+ phase: args.phase,
61392
+ taskId: args.taskId,
61393
+ reason: args.reason,
61394
+ error: args.error,
61395
+ // (D) resolved execution profile for the spawned worker.
61396
+ ...args.model ? { resolvedModel: args.model } : {},
61397
+ ...args.thinkingLevel ? { resolvedThinkingLevel: args.thinkingLevel } : {}
61398
+ }
61399
+ });
61400
+ } catch (e) {
61401
+ LOG2.warn("MeshQueue", `Failed to record auto-launch ledger event: ${e?.message || e}`);
61402
+ }
61403
+ }
61404
+ var lastQuotaClaimBlockLog;
61405
+ var lastAllQuotaClaimBlockedLog;
61406
+ var lastAutoLaunchLedgerKey;
61407
+ var AUTO_LAUNCH_LEDGER_DEDUP_MAX;
61408
+ var init_mesh_queue_observability = __esm2({
61409
+ "src/mesh/mesh-queue-observability.ts"() {
61410
+ "use strict";
61411
+ init_logger();
61412
+ init_mesh_ledger();
61413
+ init_mesh_quota_routing();
61414
+ lastQuotaClaimBlockLog = /* @__PURE__ */ new Map();
61415
+ lastAllQuotaClaimBlockedLog = /* @__PURE__ */ new Map();
61416
+ lastAutoLaunchLedgerKey = /* @__PURE__ */ new Map();
61417
+ AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2e3;
61418
+ }
61419
+ });
61276
61420
  function isActionableSkipReason(reason) {
61277
61421
  if (!reason) return false;
61278
61422
  return ACTIONABLE_SKIP_REASON_PREFIXES.some((prefix) => reason === prefix || reason.startsWith(prefix));
@@ -61358,8 +61502,8 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
61358
61502
  nextAction: "Launch a session on that node yourself with mesh_launch_session, or ensure the remote daemon is connected over P2P."
61359
61503
  };
61360
61504
  if (reason.startsWith("provider") || reason === "missing_provider_priority") return {
61361
- summary: "the node has no usable provider for this task (provider priority missing/unusable, or the provider loader is unavailable)",
61362
- nextAction: "Check the node's providerPriority policy and that the required CLI/ACP provider is installed and enabled on that machine."
61505
+ summary: `the current provider scan found no usable provider for this task (provider priority missing/unusable, or the provider loader is unavailable; ${reason})`,
61506
+ nextAction: "Check the node's providerPriority policy and that the required CLI/ACP provider is installed and enabled on that machine. Quota-gated candidates use a separate, self-resolving reason and are not proof of this configuration blocker."
61363
61507
  };
61364
61508
  if (reason === "dirty_workspace") return {
61365
61509
  summary: "the node's workspace is dirty, so auto-launch is blocked to avoid clobbering uncommitted changes",
@@ -61408,7 +61552,8 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
61408
61552
  const nodeLabel = readNonEmptyString(nodeId) || readNonEmptyString(task?.targetNodeId);
61409
61553
  const evidence = reason === "target_session_pin_expired" ? resolveTaskDeliveryEvidence(meshId, taskId) : void 0;
61410
61554
  const { summary, nextAction } = actionableSkipGuidance(reason, evidence);
61411
- const closing = reason === "target_session_pin_expired" ? "The stale pin has already been cleared, so the task is now claimable by any compatible session \u2014 the action above is about the session it was originally addressed to." : "This is an actionable blocker \u2014 it will NOT clear on its own; the task stays pending until you resolve it.";
61555
+ const providerAvailabilityResult = reason.startsWith("provider") || reason === "missing_provider_priority";
61556
+ const closing = reason === "target_session_pin_expired" ? "The stale pin has already been cleared, so the task is now claimable by any compatible session \u2014 the action above is about the session it was originally addressed to." : providerAvailabilityResult ? "This result needs action if it persists: a later provider-status refresh or an already-starting usable session can clear it, but a genuinely missing, disabled, or misconfigured provider will keep the task pending until you fix that configuration." : "This is an actionable blocker \u2014 it will NOT clear on its own; the task stays pending until you resolve it.";
61412
61557
  const coordinatorMessage = `[System] A queued mesh task${nodeLabel ? ` for node ${nodeLabel}` : ""} is not being dispatched because ${summary}. ${nextAction} ${closing}`;
61413
61558
  try {
61414
61559
  queuePendingMeshCoordinatorEvent({
@@ -61451,6 +61596,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
61451
61596
  init_config();
61452
61597
  init_slot_model_enforcement();
61453
61598
  init_mesh_queue_assignment();
61599
+ init_mesh_queue_observability();
61454
61600
  ACTIONABLE_SKIP_REASON_PREFIXES = [
61455
61601
  "target_node_id_unmatched",
61456
61602
  "no_node_satisfies_required_tags",
@@ -61981,7 +62127,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
61981
62127
  return void 0;
61982
62128
  }
61983
62129
  }
61984
- function tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType, routingDecision) {
62130
+ function tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType, routingDecision, quotaClaimTrace) {
61985
62131
  const mesh = getMeshWithCache(components, meshId);
61986
62132
  const node = mesh?.nodes.find((n) => meshNodeIdMatches(n, nodeId));
61987
62133
  if (routingDecision?.source !== "autoLaunch") {
@@ -61992,14 +62138,15 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
61992
62138
  return false;
61993
62139
  }
61994
62140
  const quotaClaimBlock = evaluateProviderQuotaGate(node, providerType, mesh?.policy?.quotaRouting ?? null, Date.now(), mesh);
62141
+ if (quotaClaimTrace) quotaClaimTrace.evaluated += 1;
61995
62142
  if (quotaClaimBlock) {
61996
- if (quotaClaimBlock.reason === PROVIDER_QUOTA_EXHAUSTED_SKIP_REASON) {
61997
- LOG2.info("MeshQueue", `QUOTA GATE: deferring queue claim for node ${nodeId} (${sessionId}): provider '${providerType}' reported its quota EXHAUSTED \u2014 task left pending until the quota resets`);
61998
- } else {
61999
- LOG2.info("MeshQueue", `QUOTA GATE: deferring queue claim for node ${nodeId} (${sessionId}): provider '${providerType}' has ${quotaClaimBlock.remainingPercent.toFixed(1)}% ${quotaClaimBlock.window} quota remaining (< ${quotaClaimBlock.thresholdPercent}% threshold) \u2014 task left pending until the window resets`);
62000
- }
62143
+ const observation = { nodeId, sessionId, providerType, block: quotaClaimBlock };
62144
+ logQuotaClaimBlockTransition(meshId, observation);
62145
+ quotaClaimTrace?.blocked.push(observation);
62001
62146
  return false;
62002
62147
  }
62148
+ clearQuotaClaimBlockState(meshId, nodeId, sessionId, providerType);
62149
+ if (quotaClaimTrace) quotaClaimTrace.clear += 1;
62003
62150
  const inlineBootstrapNode = (() => {
62004
62151
  try {
62005
62152
  const inlineMesh = components.router?.getCachedInlineMesh?.(meshId);
@@ -62058,6 +62205,12 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
62058
62205
  if (!task) {
62059
62206
  return false;
62060
62207
  }
62208
+ if (quotaClaimTrace?.blocked.length) {
62209
+ logQuotaClaimFallbackSuccess(quotaClaimTrace.blocked, task.id, { nodeId, sessionId, providerType });
62210
+ quotaClaimTrace.blocked = [];
62211
+ quotaClaimTrace.evaluated = 0;
62212
+ quotaClaimTrace.clear = 0;
62213
+ }
62061
62214
  const terminal = findTerminalLedgerEvidenceForTask({
62062
62215
  meshId,
62063
62216
  taskId: task.id
@@ -62406,39 +62559,6 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
62406
62559
  return true;
62407
62560
  });
62408
62561
  }
62409
- function recordAutoLaunchEvent(meshId, args) {
62410
- const dedupKey = `${meshId}:${args.taskId}`;
62411
- const currentSig = `${args.phase}|${args.reason || ""}`;
62412
- if (args.phase === "skipped" && lastAutoLaunchLedgerKey.get(dedupKey) === currentSig) {
62413
- return;
62414
- }
62415
- lastAutoLaunchLedgerKey.set(dedupKey, currentSig);
62416
- if (lastAutoLaunchLedgerKey.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
62417
- const oldest = lastAutoLaunchLedgerKey.keys().next().value;
62418
- if (oldest !== void 0) lastAutoLaunchLedgerKey.delete(oldest);
62419
- }
62420
- try {
62421
- appendLedgerEntry(meshId, {
62422
- kind: "session_auto_launch",
62423
- nodeId: args.nodeId,
62424
- sessionId: args.sessionId,
62425
- providerType: args.providerType,
62426
- // (B) promote taskId so this entry joins the task lifecycle timeline.
62427
- ...args.taskId ? { taskId: args.taskId } : {},
62428
- payload: {
62429
- phase: args.phase,
62430
- taskId: args.taskId,
62431
- reason: args.reason,
62432
- error: args.error,
62433
- // (D) resolved execution profile for the spawned worker.
62434
- ...args.model ? { resolvedModel: args.model } : {},
62435
- ...args.thinkingLevel ? { resolvedThinkingLevel: args.thinkingLevel } : {}
62436
- }
62437
- });
62438
- } catch (e) {
62439
- LOG2.warn("MeshQueue", `Failed to record auto-launch ledger event: ${e?.message || e}`);
62440
- }
62441
- }
62442
62562
  function markAutoLaunch(meshId, taskId, args) {
62443
62563
  recordTaskAutoLaunch(meshId, taskId, {
62444
62564
  status: args.status,
@@ -62538,6 +62658,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
62538
62658
  });
62539
62659
  return {
62540
62660
  providerType: winner.providerType,
62661
+ ...ranked.gated.length ? { quotaGated: ranked.gated } : {},
62541
62662
  ...winner.slot.model ? { model: winner.slot.model } : {},
62542
62663
  ...winner.slot.thinkingLevel ? { thinkingLevel: winner.slot.thinkingLevel } : {},
62543
62664
  // The slot that won selection. Returned so the caller can enforce
@@ -62857,6 +62978,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
62857
62978
  }
62858
62979
  const remoteSessionId = readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.id) || readNonEmptyString(payload.runtimeSessionId);
62859
62980
  markAutoLaunch(meshId, task.id, { status: "completed", nodeId, providerType: resolved.providerType, sessionId: remoteSessionId || void 0, ...effectiveModel ? { model: effectiveModel } : {}, ...effectiveThinkingLevel ? { thinkingLevel: effectiveThinkingLevel } : {} });
62981
+ logAutoLaunchQuotaFallbackSuccess(resolved, task.id, nodeId, remoteSessionId || void 0);
62860
62982
  autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
62861
62983
  sweepExpiredCooldowns();
62862
62984
  return true;
@@ -62887,6 +63009,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
62887
63009
  return false;
62888
63010
  }
62889
63011
  markAutoLaunch(meshId, task.id, { status: "completed", nodeId, providerType: resolved.providerType, sessionId, ...effectiveModel ? { model: effectiveModel } : {}, ...effectiveThinkingLevel ? { thinkingLevel: effectiveThinkingLevel } : {} });
63012
+ logAutoLaunchQuotaFallbackSuccess(resolved, task.id, nodeId, sessionId);
62890
63013
  await waitForLocalSessionReady(components, sessionId);
62891
63014
  const requiredTags = Array.isArray(task.requiredTags) ? task.requiredTags.filter((t) => !!t) : [];
62892
63015
  const routingDecision = {
@@ -62995,8 +63118,9 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
62995
63118
  remoteCandidates.push({ nodeId: idle.nodeId, sessionId: idle.sessionId, providerType: idle.providerType, origin: "remote", node });
62996
63119
  }
62997
63120
  }
63121
+ const quotaClaimTrace = { blocked: [], evaluated: 0, clear: 0 };
62998
63122
  const assignIdleCandidate = (candidate) => {
62999
- const assigned = tryAssignQueueTask(components, meshId, candidate.nodeId, candidate.sessionId, candidate.providerType);
63123
+ const assigned = tryAssignQueueTask(components, meshId, candidate.nodeId, candidate.sessionId, candidate.providerType, void 0, quotaClaimTrace);
63000
63124
  if (assigned && candidate.origin === "remote") {
63001
63125
  try {
63002
63126
  MeshRuntimeStore.getInstance().deleteRemoteIdleSession(meshId, candidate.nodeId, candidate.sessionId);
@@ -63039,6 +63163,11 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
63039
63163
  nodeId: task.assignedNodeId,
63040
63164
  sessionId: task.assignedSessionId
63041
63165
  }));
63166
+ if (newlyAssignedTasks.length === 0 && !autoLaunchStarted) {
63167
+ logAllQuotaClaimCandidatesBlocked(meshId, quotaClaimTrace, afterQueue.filter((task) => task.status === "pending").map((task) => task.id));
63168
+ } else {
63169
+ clearAllQuotaClaimCandidatesBlockedState(meshId);
63170
+ }
63042
63171
  const autoLaunchPending = autoLaunchStarted || afterQueue.some((task) => {
63043
63172
  if (task.status !== "pending") return false;
63044
63173
  const al = task.autoLaunch;
@@ -63090,8 +63219,6 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
63090
63219
  var AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES;
63091
63220
  var AUTO_LAUNCH_REMOTE_IDLE_TTL_MS;
63092
63221
  var autoLaunchAwaitClaimBackoff;
63093
- var lastAutoLaunchLedgerKey;
63094
- var AUTO_LAUNCH_LEDGER_DEDUP_MAX;
63095
63222
  var init_mesh_queue_assignment = __esm2({
63096
63223
  "src/mesh/mesh-queue-assignment.ts"() {
63097
63224
  "use strict";
@@ -63124,6 +63251,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
63124
63251
  init_mesh_auto_fast_forward();
63125
63252
  init_mesh_skip_notify();
63126
63253
  init_mesh_scheduling_fitness();
63254
+ init_mesh_queue_observability();
63127
63255
  init_mesh_auto_fast_forward();
63128
63256
  init_mesh_skip_notify();
63129
63257
  init_mesh_scheduling_fitness();
@@ -63140,8 +63268,6 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
63140
63268
  AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES = 2;
63141
63269
  AUTO_LAUNCH_REMOTE_IDLE_TTL_MS = 5 * 60 * 1e3;
63142
63270
  autoLaunchAwaitClaimBackoff = /* @__PURE__ */ new Map();
63143
- lastAutoLaunchLedgerKey = /* @__PURE__ */ new Map();
63144
- AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2e3;
63145
63271
  }
63146
63272
  });
63147
63273
  function readSettings(state) {
@@ -67360,12 +67486,12 @@ ${cleanBody}`;
67360
67486
  return !liveePaths.has(norm);
67361
67487
  });
67362
67488
  }
67363
- function safeUnlink(path55) {
67489
+ function safeUnlink(path56) {
67364
67490
  try {
67365
- (0, import_fs16.unlinkSync)(path55);
67491
+ (0, import_fs16.unlinkSync)(path56);
67366
67492
  return true;
67367
67493
  } catch (e) {
67368
- LOG2.warn("DiskRetention", `Failed to delete ${path55}: ${e?.message || e}`);
67494
+ LOG2.warn("DiskRetention", `Failed to delete ${path56}: ${e?.message || e}`);
67369
67495
  return false;
67370
67496
  }
67371
67497
  }
@@ -67379,10 +67505,10 @@ ${cleanBody}`;
67379
67505
  return [];
67380
67506
  }
67381
67507
  for (const name of names) {
67382
- const path55 = (0, import_path14.join)(dir, name);
67508
+ const path56 = (0, import_path14.join)(dir, name);
67383
67509
  try {
67384
- const st = (0, import_fs16.statSync)(path55);
67385
- if (st.isFile()) out.push({ path: path55, mtimeMs: st.mtimeMs });
67510
+ const st = (0, import_fs16.statSync)(path56);
67511
+ if (st.isFile()) out.push({ path: path56, mtimeMs: st.mtimeMs });
67386
67512
  } catch {
67387
67513
  }
67388
67514
  }
@@ -70568,54 +70694,54 @@ ${cleanBody}`;
70568
70694
  }
70569
70695
  return errs;
70570
70696
  }
70571
- function validateCondition(c, sectionIds, path55) {
70697
+ function validateCondition(c, sectionIds, path56) {
70572
70698
  const errs = [];
70573
70699
  const w = c;
70574
70700
  if ("all" in w) {
70575
- w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path55}.all[${i}]`)));
70701
+ w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path56}.all[${i}]`)));
70576
70702
  return errs;
70577
70703
  }
70578
70704
  if ("any" in w) {
70579
- w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path55}.any[${i}]`)));
70705
+ w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path56}.any[${i}]`)));
70580
70706
  return errs;
70581
70707
  }
70582
70708
  if ("not" in w) {
70583
- errs.push(...validateCondition(w.not, sectionIds, `${path55}.not`));
70709
+ errs.push(...validateCondition(w.not, sectionIds, `${path56}.not`));
70584
70710
  return errs;
70585
70711
  }
70586
70712
  if ("matches" in w) {
70587
- if (w.section && !sectionIds.has(w.section)) errs.push(`${path55}.section "${w.section}" unknown`);
70713
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path56}.section "${w.section}" unknown`);
70588
70714
  try {
70589
70715
  new RegExp(w.matches, w.flags ?? "i");
70590
70716
  } catch (e) {
70591
- errs.push(`${path55}.matches invalid regex: ${e.message}`);
70717
+ errs.push(`${path56}.matches invalid regex: ${e.message}`);
70592
70718
  }
70593
70719
  return errs;
70594
70720
  }
70595
70721
  if ("cursor_above" in w && "changed" in w) return errs;
70596
70722
  if ("signal" in w) {
70597
- if (typeof w.signal !== "string" || !w.signal.trim()) errs.push(`${path55}.signal must be a non-empty string`);
70598
- if (w.equals !== void 0 && typeof w.equals !== "boolean") errs.push(`${path55}.equals must be a boolean`);
70723
+ if (typeof w.signal !== "string" || !w.signal.trim()) errs.push(`${path56}.signal must be a non-empty string`);
70724
+ if (w.equals !== void 0 && typeof w.equals !== "boolean") errs.push(`${path56}.equals must be a boolean`);
70599
70725
  return errs;
70600
70726
  }
70601
70727
  if ("elapsed_ms" in w) {
70602
- if (typeof w.elapsed_ms !== "number") errs.push(`${path55}.elapsed_ms must be a number`);
70728
+ if (typeof w.elapsed_ms !== "number") errs.push(`${path56}.elapsed_ms must be a number`);
70603
70729
  return errs;
70604
70730
  }
70605
70731
  if ("stable_ms" in w) {
70606
- if (typeof w.stable_ms !== "number") errs.push(`${path55}.stable_ms must be a number`);
70607
- if (w.section && !sectionIds.has(w.section)) errs.push(`${path55}.section "${w.section}" unknown`);
70732
+ if (typeof w.stable_ms !== "number") errs.push(`${path56}.stable_ms must be a number`);
70733
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path56}.section "${w.section}" unknown`);
70608
70734
  if (w.ignore_lines !== void 0) {
70609
- if (typeof w.ignore_lines !== "string") errs.push(`${path55}.ignore_lines must be a string`);
70735
+ if (typeof w.ignore_lines !== "string") errs.push(`${path56}.ignore_lines must be a string`);
70610
70736
  else try {
70611
70737
  new RegExp(w.ignore_lines, "m");
70612
70738
  } catch (e) {
70613
- errs.push(`${path55}.ignore_lines invalid regex: ${e.message}`);
70739
+ errs.push(`${path56}.ignore_lines invalid regex: ${e.message}`);
70614
70740
  }
70615
70741
  }
70616
70742
  return errs;
70617
70743
  }
70618
- errs.push(`${path55} is not a recognized condition`);
70744
+ errs.push(`${path56} is not a recognized condition`);
70619
70745
  return errs;
70620
70746
  }
70621
70747
  var fs17;
@@ -73177,8 +73303,8 @@ ${cleanBody}`;
73177
73303
  let cwd = options.cwd;
73178
73304
  if (cwd) {
73179
73305
  try {
73180
- const fs57 = require("fs");
73181
- const stat2 = fs57.statSync(cwd);
73306
+ const fs58 = require("fs");
73307
+ const stat2 = fs58.statSync(cwd);
73182
73308
  if (!stat2.isDirectory()) cwd = os15.homedir();
73183
73309
  } catch {
73184
73310
  cwd = os15.homedir();
@@ -78506,7 +78632,7 @@ ${lastSnapshot}`;
78506
78632
  }
78507
78633
  function canonicalize(p) {
78508
78634
  try {
78509
- const resolved = path45.resolve(p);
78635
+ const resolved = path46.resolve(p);
78510
78636
  try {
78511
78637
  return nodeFs.realpathSync.native ? nodeFs.realpathSync.native(resolved) : nodeFs.realpathSync(resolved);
78512
78638
  } catch {
@@ -78526,7 +78652,7 @@ ${lastSnapshot}`;
78526
78652
  }
78527
78653
  for (const root of _gatedRoots) {
78528
78654
  if (normalized === root.rootPath) return root;
78529
- if (normalized.startsWith(root.rootPath + path45.sep)) return root;
78655
+ if (normalized.startsWith(root.rootPath + path46.sep)) return root;
78530
78656
  }
78531
78657
  return null;
78532
78658
  }
@@ -78545,16 +78671,16 @@ ${lastSnapshot}`;
78545
78671
  };
78546
78672
  }
78547
78673
  function gatedRequire(request, parent, isMain, gated, originalLoad) {
78548
- if (request.startsWith("./") || request.startsWith("../") || path45.isAbsolute(request)) {
78674
+ if (request.startsWith("./") || request.startsWith("../") || path46.isAbsolute(request)) {
78549
78675
  let resolved;
78550
78676
  try {
78551
- const callerRequire = parent?.filename ? (0, import_node_module2.createRequire)(parent.filename) : (0, import_node_module2.createRequire)(path45.join(gated.rootPath, "__entry__.js"));
78677
+ const callerRequire = parent?.filename ? (0, import_node_module2.createRequire)(parent.filename) : (0, import_node_module2.createRequire)(path46.join(gated.rootPath, "__entry__.js"));
78552
78678
  resolved = callerRequire.resolve(request);
78553
78679
  } catch {
78554
78680
  return originalLoad.call(this, request, parent, isMain);
78555
78681
  }
78556
78682
  const resolvedCanon = canonicalize(resolved) || resolved;
78557
- if (!(resolvedCanon === gated.rootPath || resolvedCanon.startsWith(gated.rootPath + path45.sep))) {
78683
+ if (!(resolvedCanon === gated.rootPath || resolvedCanon.startsWith(gated.rootPath + path46.sep))) {
78558
78684
  denyRequire(request, parent, `relative path escapes provider root (resolved to ${resolvedCanon})`);
78559
78685
  }
78560
78686
  return originalLoad.call(this, request, parent, isMain);
@@ -78578,7 +78704,7 @@ ${lastSnapshot}`;
78578
78704
  err.callerFilename = caller;
78579
78705
  throw err;
78580
78706
  }
78581
- var path45;
78707
+ var path46;
78582
78708
  var import_node_module2;
78583
78709
  var nodeFs;
78584
78710
  var nodeChildProcess;
@@ -78599,7 +78725,7 @@ ${lastSnapshot}`;
78599
78725
  var init_require_whitelist = __esm2({
78600
78726
  "src/providers/sdk/v1/sandbox/require-whitelist.ts"() {
78601
78727
  "use strict";
78602
- path45 = __toESM2(require("path"));
78728
+ path46 = __toESM2(require("path"));
78603
78729
  import_node_module2 = require("module");
78604
78730
  nodeFs = __toESM2(require("fs"));
78605
78731
  nodeChildProcess = __toESM2(require("child_process"));
@@ -79325,7 +79451,7 @@ ${lastSnapshot}`;
79325
79451
  return _cliValidator;
79326
79452
  }
79327
79453
  function formatIssue(err) {
79328
- const path55 = err.instancePath || "";
79454
+ const path56 = err.instancePath || "";
79329
79455
  const params = err.params;
79330
79456
  let message = err.message || "validation failed";
79331
79457
  let allowed;
@@ -79343,7 +79469,7 @@ ${lastSnapshot}`;
79343
79469
  } else if (err.keyword === "type") {
79344
79470
  message = `must be ${params.type}`;
79345
79471
  }
79346
- return { path: path55, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
79472
+ return { path: path56, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
79347
79473
  }
79348
79474
  function validateCliProviderManifest(manifest) {
79349
79475
  const validator = getCliValidator();
@@ -79454,6 +79580,7 @@ ${lastSnapshot}`;
79454
79580
  MESH_REFINE_CONFIG_LOCATIONS: () => MESH_REFINE_CONFIG_LOCATIONS,
79455
79581
  MESH_REFINE_CONFIG_SCHEMA: () => MESH_REFINE_CONFIG_SCHEMA,
79456
79582
  MESH_SCHEDULING_STRATEGIES: () => MESH_SCHEDULING_STRATEGIES,
79583
+ MESH_TASK_GRAPH_MAX_TASKS: () => MESH_TASK_GRAPH_MAX_TASKS,
79457
79584
  MESH_TASK_PRIORITIES: () => MESH_TASK_PRIORITIES,
79458
79585
  MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS: () => MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS,
79459
79586
  MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA: () => MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA,
@@ -79588,6 +79715,7 @@ ${lastSnapshot}`;
79588
79715
  drainPendingMeshCoordinatorEvents: () => drainPendingMeshCoordinatorEvents,
79589
79716
  encodeDuplicateMeshDispatchCode: () => encodeDuplicateMeshDispatchCode,
79590
79717
  enqueueTask: () => enqueueTask,
79718
+ enqueueTaskGraph: () => enqueueTaskGraph,
79591
79719
  ensureSessionHostReady: () => ensureSessionHostReady2,
79592
79720
  evaluateFsm: () => evaluateFsm,
79593
79721
  evaluateProviderQuotaGate: () => evaluateProviderQuotaGate,
@@ -81071,8 +81199,8 @@ ${lastSnapshot}`;
81071
81199
  throw new Error(stderr || error48?.message || `git ${args[0]} failed`);
81072
81200
  }
81073
81201
  }
81074
- async function canonicalPath(path55) {
81075
- const absolute = (0, import_node_path2.resolve)(path55);
81202
+ async function canonicalPath(path56) {
81203
+ const absolute = (0, import_node_path2.resolve)(path56);
81076
81204
  try {
81077
81205
  return await (0, import_promises4.realpath)(absolute);
81078
81206
  } catch {
@@ -81595,51 +81723,51 @@ ${lastSnapshot}`;
81595
81723
  }
81596
81724
  var usageFileCache = /* @__PURE__ */ new Map();
81597
81725
  function readUsageFile(meshId) {
81598
- const path55 = getUsagePath(meshId);
81726
+ const path56 = getUsagePath(meshId);
81599
81727
  let stat2;
81600
81728
  try {
81601
- const s2 = (0, import_fs13.statSync)(path55);
81729
+ const s2 = (0, import_fs13.statSync)(path56);
81602
81730
  stat2 = { mtimeMs: s2.mtimeMs, size: s2.size };
81603
81731
  } catch {
81604
- usageFileCache.delete(path55);
81732
+ usageFileCache.delete(path56);
81605
81733
  return emptyFile(meshId);
81606
81734
  }
81607
- const cached5 = usageFileCache.get(path55);
81735
+ const cached5 = usageFileCache.get(path56);
81608
81736
  if (cached5 && cached5.mtimeMs === stat2.mtimeMs && cached5.size === stat2.size) {
81609
81737
  return cached5.file;
81610
81738
  }
81611
81739
  try {
81612
- const parsed = JSON.parse((0, import_fs13.readFileSync)(path55, "utf-8"));
81740
+ const parsed = JSON.parse((0, import_fs13.readFileSync)(path56, "utf-8"));
81613
81741
  if (!parsed || typeof parsed !== "object" || !parsed.sessions) {
81614
- usageFileCache.delete(path55);
81742
+ usageFileCache.delete(path56);
81615
81743
  return emptyFile(meshId);
81616
81744
  }
81617
- usageFileCache.set(path55, { file: parsed, mtimeMs: stat2.mtimeMs, size: stat2.size });
81745
+ usageFileCache.set(path56, { file: parsed, mtimeMs: stat2.mtimeMs, size: stat2.size });
81618
81746
  return parsed;
81619
81747
  } catch {
81620
- usageFileCache.delete(path55);
81748
+ usageFileCache.delete(path56);
81621
81749
  return emptyFile(meshId);
81622
81750
  }
81623
81751
  }
81624
81752
  function writeUsageFile(meshId, file2) {
81625
- const path55 = getUsagePath(meshId);
81626
- const tmp = `${path55}.tmp`;
81753
+ const path56 = getUsagePath(meshId);
81754
+ const tmp = `${path56}.tmp`;
81627
81755
  (0, import_fs13.writeFileSync)(tmp, JSON.stringify(file2), { encoding: "utf-8", mode: 384 });
81628
81756
  try {
81629
- (0, import_fs13.renameSync)(tmp, path55);
81757
+ (0, import_fs13.renameSync)(tmp, path56);
81630
81758
  } catch (e) {
81631
81759
  try {
81632
81760
  (0, import_fs13.unlinkSync)(tmp);
81633
81761
  } catch {
81634
81762
  }
81635
- usageFileCache.delete(path55);
81763
+ usageFileCache.delete(path56);
81636
81764
  throw e;
81637
81765
  }
81638
81766
  try {
81639
- const s2 = (0, import_fs13.statSync)(path55);
81640
- usageFileCache.set(path55, { file: file2, mtimeMs: s2.mtimeMs, size: s2.size });
81767
+ const s2 = (0, import_fs13.statSync)(path56);
81768
+ usageFileCache.set(path56, { file: file2, mtimeMs: s2.mtimeMs, size: s2.size });
81641
81769
  } catch {
81642
- usageFileCache.delete(path55);
81770
+ usageFileCache.delete(path56);
81643
81771
  }
81644
81772
  }
81645
81773
  function foldIntoRollup(rollup, entry) {
@@ -82133,19 +82261,19 @@ ${lastSnapshot}`;
82133
82261
  return null;
82134
82262
  }
82135
82263
  async function detectIDEs(providerLoader) {
82136
- const os30 = (0, import_os3.platform)();
82264
+ const os31 = (0, import_os3.platform)();
82137
82265
  const results = [];
82138
82266
  for (const def of getMergedDefinitions()) {
82139
82267
  const cliPath = findCliCommand(providerLoader?.getIdeCliCommand(def.id, def.cli) || def.cli);
82140
- const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os30] || []) || []);
82268
+ const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os31] || []) || []);
82141
82269
  let resolvedCli = cliPath;
82142
- if (!resolvedCli && appPath && os30 === "darwin") {
82270
+ if (!resolvedCli && appPath && os31 === "darwin") {
82143
82271
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
82144
82272
  if ((0, import_fs17.existsSync)(bundledCli)) resolvedCli = bundledCli;
82145
82273
  }
82146
- if (!resolvedCli && appPath && os30 === "win32") {
82147
- const { dirname: dirname23 } = await import("path");
82148
- const appDir = dirname23(appPath);
82274
+ if (!resolvedCli && appPath && os31 === "win32") {
82275
+ const { dirname: dirname24 } = await import("path");
82276
+ const appDir = dirname24(appPath);
82149
82277
  const candidates = [
82150
82278
  `${appDir}\\\\bin\\\\${def.cli}.cmd`,
82151
82279
  `${appDir}\\\\bin\\\\${def.cli}`,
@@ -82160,7 +82288,7 @@ ${lastSnapshot}`;
82160
82288
  }
82161
82289
  }
82162
82290
  }
82163
- const installed = os30 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
82291
+ const installed = os31 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
82164
82292
  const version2 = null;
82165
82293
  results.push({
82166
82294
  id: def.id,
@@ -90383,8 +90511,8 @@ ${effect.notification.body || ""}`.trim();
90383
90511
  * own upstream cache and never writes into another instance's store.
90384
90512
  */
90385
90513
  getUpstreamInstallRoot() {
90386
- const path55 = require("path");
90387
- return path55.join(getConfigDir2(), "providers", ".upstream");
90514
+ const path56 = require("path");
90515
+ return path56.join(getConfigDir2(), "providers", ".upstream");
90388
90516
  }
90389
90517
  /**
90390
90518
  * Install (activate) a provider from the VERIFIED CHANNEL.
@@ -90467,19 +90595,19 @@ ${effect.notification.body || ""}`.trim();
90467
90595
  if (!["cli", "ide", "extension", "acp"].includes(category)) {
90468
90596
  return { success: false, error: `unknown category: ${category}` };
90469
90597
  }
90470
- const fs57 = require("fs");
90471
- const path55 = require("path");
90598
+ const fs58 = require("fs");
90599
+ const path56 = require("path");
90472
90600
  try {
90473
90601
  const installRoot = this.getUpstreamInstallRoot();
90474
- const installRootResolved = path55.resolve(installRoot);
90475
- const targetDir = path55.resolve(path55.join(installRoot, category, type2));
90476
- if (!targetDir.startsWith(installRootResolved + path55.sep)) {
90602
+ const installRootResolved = path56.resolve(installRoot);
90603
+ const targetDir = path56.resolve(path56.join(installRoot, category, type2));
90604
+ if (!targetDir.startsWith(installRootResolved + path56.sep)) {
90477
90605
  return { success: false, error: "refusing to delete outside upstream root" };
90478
90606
  }
90479
- if (!fs57.existsSync(targetDir)) {
90607
+ if (!fs58.existsSync(targetDir)) {
90480
90608
  return { success: false, error: "not installed" };
90481
90609
  }
90482
- fs57.rmSync(targetDir, { recursive: true, force: true });
90610
+ fs58.rmSync(targetDir, { recursive: true, force: true });
90483
90611
  try {
90484
90612
  this._ctx.providerLoader?.deactivateVerifiedChannel?.(type2);
90485
90613
  } catch {
@@ -90499,28 +90627,28 @@ ${effect.notification.body || ""}`.trim();
90499
90627
  * the UI and by the update checker.
90500
90628
  */
90501
90629
  handleListInstalledProviders(_args) {
90502
- const fs57 = require("fs");
90503
- const path55 = require("path");
90630
+ const fs58 = require("fs");
90631
+ const path56 = require("path");
90504
90632
  const installRoot = this.getUpstreamInstallRoot();
90505
- if (!fs57.existsSync(installRoot)) return { success: true, providers: [] };
90633
+ if (!fs58.existsSync(installRoot)) return { success: true, providers: [] };
90506
90634
  const CATEGORIES = ["cli", "ide", "extension", "acp"];
90507
90635
  const items = [];
90508
90636
  for (const category of CATEGORIES) {
90509
- const categoryDir = path55.join(installRoot, category);
90510
- if (!fs57.existsSync(categoryDir)) continue;
90637
+ const categoryDir = path56.join(installRoot, category);
90638
+ if (!fs58.existsSync(categoryDir)) continue;
90511
90639
  let entries;
90512
90640
  try {
90513
- entries = fs57.readdirSync(categoryDir);
90641
+ entries = fs58.readdirSync(categoryDir);
90514
90642
  } catch {
90515
90643
  continue;
90516
90644
  }
90517
90645
  for (const type2 of entries) {
90518
- const v1Path = path55.join(categoryDir, type2, "provider.v1.json");
90519
- const v0Path = path55.join(categoryDir, type2, "provider.json");
90520
- const manifestPath = fs57.existsSync(v1Path) ? v1Path : fs57.existsSync(v0Path) ? v0Path : null;
90646
+ const v1Path = path56.join(categoryDir, type2, "provider.v1.json");
90647
+ const v0Path = path56.join(categoryDir, type2, "provider.json");
90648
+ const manifestPath = fs58.existsSync(v1Path) ? v1Path : fs58.existsSync(v0Path) ? v0Path : null;
90521
90649
  if (!manifestPath) continue;
90522
90650
  try {
90523
- const m = JSON.parse(fs57.readFileSync(manifestPath, "utf-8"));
90651
+ const m = JSON.parse(fs58.readFileSync(manifestPath, "utf-8"));
90524
90652
  const modelOptions = Array.isArray(m.modelOptions) ? m.modelOptions.filter((x) => typeof x === "string" && !!x.trim()) : [];
90525
90653
  const thinkingLevelOptions = Array.isArray(m.thinkingLevelOptions) ? m.thinkingLevelOptions.filter((x) => typeof x === "string" && !!x.trim()) : [];
90526
90654
  items.push({
@@ -90741,8 +90869,8 @@ ${effect.notification.body || ""}`.trim();
90741
90869
  if (!/^@[a-z0-9_-]+$/i.test(requestedName)) {
90742
90870
  return { success: false, error: "name must match @[a-z0-9_-]+" };
90743
90871
  }
90744
- const fs57 = require("fs");
90745
- const path55 = require("path");
90872
+ const fs58 = require("fs");
90873
+ const path56 = require("path");
90746
90874
  const { spawnSync: spawnSync3 } = require("child_process");
90747
90875
  const file2 = ext.loadExternalSources();
90748
90876
  if (file2.sources.some((s2) => s2.name === requestedName)) {
@@ -90751,9 +90879,9 @@ ${effect.notification.body || ""}`.trim();
90751
90879
  if (file2.sources.some((s2) => s2.url === url2 && s2.ref === ref)) {
90752
90880
  return { success: false, error: `source url+ref already registered (use a different name to track another ref)` };
90753
90881
  }
90754
- const sourceDir = path55.join(ext.externalRoot(), requestedName);
90755
- if (!fs57.existsSync(ext.externalRoot())) fs57.mkdirSync(ext.externalRoot(), { recursive: true });
90756
- if (fs57.existsSync(sourceDir)) {
90882
+ const sourceDir = path56.join(ext.externalRoot(), requestedName);
90883
+ if (!fs58.existsSync(ext.externalRoot())) fs58.mkdirSync(ext.externalRoot(), { recursive: true });
90884
+ if (fs58.existsSync(sourceDir)) {
90757
90885
  return { success: false, error: `directory already exists: ${sourceDir} (rename or remove first)` };
90758
90886
  }
90759
90887
  const clone2 = spawnSync3("git", ["clone", "--depth=1", "--branch", ref, "--", url2, sourceDir], {
@@ -90763,7 +90891,7 @@ ${effect.notification.body || ""}`.trim();
90763
90891
  });
90764
90892
  if (clone2.status !== 0) {
90765
90893
  try {
90766
- fs57.rmSync(sourceDir, { recursive: true, force: true });
90894
+ fs58.rmSync(sourceDir, { recursive: true, force: true });
90767
90895
  } catch {
90768
90896
  }
90769
90897
  return { success: false, error: `git clone failed: ${(clone2.stderr || clone2.stdout || "").trim() || "unknown error"}` };
@@ -90807,15 +90935,15 @@ ${effect.notification.body || ""}`.trim();
90807
90935
  const name = typeof args?.name === "string" ? args.name.trim() : "";
90808
90936
  if (!name) return { success: false, error: "name is required" };
90809
90937
  const ext = (init_external_sources(), __toCommonJS2(external_sources_exports));
90810
- const fs57 = require("fs");
90811
- const path55 = require("path");
90938
+ const fs58 = require("fs");
90939
+ const path56 = require("path");
90812
90940
  const file2 = ext.loadExternalSources();
90813
90941
  const match = file2.sources.find((s2) => s2.name === name);
90814
90942
  if (!match) return { success: false, error: `source "${name}" not registered` };
90815
- const sourceDir = path55.join(ext.externalRoot(), name);
90816
- if (fs57.existsSync(sourceDir)) {
90943
+ const sourceDir = path56.join(ext.externalRoot(), name);
90944
+ if (fs58.existsSync(sourceDir)) {
90817
90945
  try {
90818
- fs57.rmSync(sourceDir, { recursive: true, force: true });
90946
+ fs58.rmSync(sourceDir, { recursive: true, force: true });
90819
90947
  } catch (e) {
90820
90948
  return { success: false, error: `failed to delete ${sourceDir}: ${e?.message || e}` };
90821
90949
  }
@@ -92982,6 +93110,7 @@ ${marker}`,
92982
93110
  }
92983
93111
  init_snapshot2();
92984
93112
  init_build_info();
93113
+ init_track_identity();
92985
93114
  init_coordinator_registry();
92986
93115
  init_types();
92987
93116
  init_deps();
@@ -93011,7 +93140,11 @@ ${marker}`,
93011
93140
  return {
93012
93141
  success: true,
93013
93142
  status: snapshot,
93014
- daemonBuild: getDaemonBuildInfo(),
93143
+ // `track` is reported by the daemon that answered this command. It
93144
+ // must travel explicitly: version strings do not identify a release
93145
+ // track (stable can legitimately publish an rc), and an older daemon
93146
+ // that omits this field must remain "unknown" to remote consumers.
93147
+ daemonBuild: { ...getDaemonBuildInfo(), track: TRACK },
93015
93148
  upgradeFailure: readUpgradeFailureNotice(),
93016
93149
  providerChannelStaleness: ctx.deps.providerLoader?.getChannelStalenessSnapshot?.() ?? null
93017
93150
  };
@@ -93135,24 +93268,24 @@ ${marker}`,
93135
93268
  }
93136
93269
  },
93137
93270
  list_coordinator_prompts: async (_ctx, _args) => {
93138
- const fs57 = await import("fs");
93139
- const path55 = await import("path");
93271
+ const fs58 = await import("fs");
93272
+ const path56 = await import("path");
93140
93273
  const { getConfigDir: getConfigDir22 } = await Promise.resolve().then(() => (init_config(), config_exports));
93141
- const dir = path55.join(getConfigDir22(), "coordinator-prompts");
93274
+ const dir = path56.join(getConfigDir22(), "coordinator-prompts");
93142
93275
  const entries = {};
93143
93276
  try {
93144
- if (fs57.existsSync(dir)) {
93145
- for (const name of fs57.readdirSync(dir)) {
93277
+ if (fs58.existsSync(dir)) {
93278
+ for (const name of fs58.readdirSync(dir)) {
93146
93279
  const matchOverride = name.match(/^([a-zA-Z0-9_.-]+)\.md$/);
93147
93280
  const matchAppend = name.match(/^([a-zA-Z0-9_.-]+)\.append\.md$/);
93148
93281
  const m = matchAppend || matchOverride;
93149
93282
  if (!m) continue;
93150
93283
  const isAppend = !!matchAppend;
93151
93284
  const key2 = m[1];
93152
- const full = path55.join(dir, name);
93285
+ const full = path56.join(dir, name);
93153
93286
  let content = "";
93154
93287
  try {
93155
- content = fs57.readFileSync(full, "utf8");
93288
+ content = fs58.readFileSync(full, "utf8");
93156
93289
  } catch {
93157
93290
  }
93158
93291
  if (!entries[key2]) entries[key2] = { override: "", append: "" };
@@ -93166,8 +93299,8 @@ ${marker}`,
93166
93299
  return { success: true, dir, entries };
93167
93300
  },
93168
93301
  write_coordinator_prompt: async (_ctx, args) => {
93169
- const fs57 = await import("fs");
93170
- const path55 = await import("path");
93302
+ const fs58 = await import("fs");
93303
+ const path56 = await import("path");
93171
93304
  const { getConfigDir: getConfigDir22 } = await Promise.resolve().then(() => (init_config(), config_exports));
93172
93305
  const key2 = typeof args?.key === "string" ? args.key.trim() : "";
93173
93306
  const kind = args?.kind === "append" ? "append" : "override";
@@ -93175,15 +93308,15 @@ ${marker}`,
93175
93308
  if (!key2 || !/^[a-zA-Z0-9_.-]+$/.test(key2)) {
93176
93309
  return { success: false, error: "key must match [a-zA-Z0-9_.-]+" };
93177
93310
  }
93178
- const dir = path55.join(getConfigDir22(), "coordinator-prompts");
93311
+ const dir = path56.join(getConfigDir22(), "coordinator-prompts");
93179
93312
  const filename = kind === "append" ? `${key2}.append.md` : `${key2}.md`;
93180
- const full = path55.join(dir, filename);
93313
+ const full = path56.join(dir, filename);
93181
93314
  try {
93182
- fs57.mkdirSync(dir, { recursive: true });
93315
+ fs58.mkdirSync(dir, { recursive: true });
93183
93316
  if (content.trim()) {
93184
- fs57.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
93185
- } else if (fs57.existsSync(full)) {
93186
- fs57.unlinkSync(full);
93317
+ fs58.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
93318
+ } else if (fs58.existsSync(full)) {
93319
+ fs58.unlinkSync(full);
93187
93320
  }
93188
93321
  return { success: true, path: full, kind, key: key2 };
93189
93322
  } catch (error48) {
@@ -104529,10 +104662,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
104529
104662
  };
104530
104663
  var import_child_process12 = require("child_process");
104531
104664
  var net3 = __toESM2(require("net"));
104532
- var os26 = __toESM2(require("os"));
104665
+ var os27 = __toESM2(require("os"));
104666
+ var path48 = __toESM2(require("path"));
104667
+ var fs43 = __toESM2(require("fs"));
104533
104668
  var path47 = __toESM2(require("path"));
104534
- var fs422 = __toESM2(require("fs"));
104535
- var path46 = __toESM2(require("path"));
104536
104669
  var chokidar = __toESM2(require_chokidar());
104537
104670
  init_logger();
104538
104671
  init_auto_approve_modes();
@@ -104998,9 +105131,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
104998
105131
  init_external_sources();
104999
105132
  init_config();
105000
105133
  init_native_history_executor();
105001
- var fs37 = __toESM2(require("fs"));
105002
- var os25 = __toESM2(require("os"));
105003
- var path41 = __toESM2(require("path"));
105134
+ var fs38 = __toESM2(require("fs"));
105135
+ var os26 = __toESM2(require("os"));
105136
+ var path422 = __toESM2(require("path"));
105004
105137
  var fs33 = __toESM2(require("fs"));
105005
105138
  var path37 = __toESM2(require("path"));
105006
105139
  init_usage_normalize();
@@ -105183,17 +105316,17 @@ Run 'adhdev doctor' for detailed diagnostics.`
105183
105316
  }
105184
105317
  function readSession(sessionPath) {
105185
105318
  if (!sessionPath || !path37.isAbsolute(sessionPath)) return null;
105186
- const basename19 = path37.basename(sessionPath, ".jsonl");
105187
- if (!isSafeSessionId(basename19)) return null;
105319
+ const basename20 = path37.basename(sessionPath, ".jsonl");
105320
+ if (!isSafeSessionId(basename20)) return null;
105188
105321
  if (!fs33.existsSync(sessionPath)) return null;
105189
105322
  const sourceMtimeMs = statMtimeMs(sessionPath);
105190
- const { messages, usageRecords } = parseTranscriptFile(sessionPath, basename19);
105323
+ const { messages, usageRecords } = parseTranscriptFile(sessionPath, basename20);
105191
105324
  if (messages.length === 0) return null;
105192
105325
  const firstSystem = messages.find((m) => m.kind === "session_start");
105193
105326
  const workspace = firstSystem?.workspace || firstSystem?.content || void 0;
105194
105327
  const session = {
105195
105328
  messages,
105196
- providerSessionId: basename19,
105329
+ providerSessionId: basename20,
105197
105330
  source: "provider-native",
105198
105331
  sourcePath: sessionPath,
105199
105332
  sourceMtimeMs,
@@ -105202,7 +105335,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
105202
105335
  };
105203
105336
  if (usageRecords.length > 0) {
105204
105337
  session.usage = foldUsageRecords(usageRecords, {
105205
- providerSessionId: basename19,
105338
+ providerSessionId: basename20,
105206
105339
  agent: "claude-cli"
105207
105340
  });
105208
105341
  }
@@ -105497,8 +105630,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
105497
105630
  if (!fs34.existsSync(sessionPath)) return null;
105498
105631
  const meta3 = readSessionMeta(sessionPath);
105499
105632
  const metaId = String(meta3?.id ?? "").trim();
105500
- const basename19 = path38.basename(sessionPath, ".jsonl");
105501
- const uuidMatch = basename19.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
105633
+ const basename20 = path38.basename(sessionPath, ".jsonl");
105634
+ const uuidMatch = basename20.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
105502
105635
  const filenameUuid2 = uuidMatch ? uuidMatch[1] : "";
105503
105636
  if (metaId && filenameUuid2 && metaId !== filenameUuid2) return null;
105504
105637
  const sessionId = metaId || filenameUuid2;
@@ -106398,6 +106531,240 @@ Run 'adhdev doctor' for detailed diagnostics.`
106398
106531
  if (s2 === "tool" || s2 === "tool_result" || s2 === "function") return "assistant";
106399
106532
  return "system";
106400
106533
  }
106534
+ var fs37 = __toESM2(require("fs"));
106535
+ var path41 = __toESM2(require("path"));
106536
+ var os25 = __toESM2(require("os"));
106537
+ function grokSessionsRoot() {
106538
+ const home = process.env.GROK_HOME && process.env.GROK_HOME.trim() ? process.env.GROK_HOME.trim() : path41.join(os25.homedir(), ".grok");
106539
+ return path41.join(home, "sessions");
106540
+ }
106541
+ function encodeWorkspaceDir(workspace) {
106542
+ return encodeURIComponent(workspace);
106543
+ }
106544
+ function statMtimeMs5(filePath) {
106545
+ try {
106546
+ return fs37.statSync(filePath).mtimeMs;
106547
+ } catch {
106548
+ return 0;
106549
+ }
106550
+ }
106551
+ function isUuidLike2(value) {
106552
+ return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(value);
106553
+ }
106554
+ function workspaceCandidates(workspace) {
106555
+ const out = [workspace];
106556
+ try {
106557
+ const real = fs37.realpathSync(workspace);
106558
+ if (real && real !== workspace) out.push(real);
106559
+ } catch {
106560
+ }
106561
+ return out;
106562
+ }
106563
+ function resolveGrokPath(workspace, sessionId) {
106564
+ if (!sessionId || !isUuidLike2(sessionId)) return null;
106565
+ const root = grokSessionsRoot();
106566
+ if (!fs37.existsSync(root)) return null;
106567
+ for (const candidate of workspaceCandidates(workspace || "")) {
106568
+ if (!candidate) continue;
106569
+ const file2 = path41.join(root, encodeWorkspaceDir(candidate), sessionId, "chat_history.jsonl");
106570
+ if (fs37.existsSync(file2)) return file2;
106571
+ }
106572
+ let entries = [];
106573
+ try {
106574
+ entries = fs37.readdirSync(root, { withFileTypes: true });
106575
+ } catch {
106576
+ return null;
106577
+ }
106578
+ for (const entry of entries) {
106579
+ if (!entry.isDirectory()) continue;
106580
+ const file2 = path41.join(root, entry.name, sessionId, "chat_history.jsonl");
106581
+ if (fs37.existsSync(file2)) return file2;
106582
+ }
106583
+ return null;
106584
+ }
106585
+ var USER_QUERY_RE = /<user_query>\s*([\s\S]*?)\s*<\/user_query>/;
106586
+ function unwrapUserQuery(text) {
106587
+ const match = USER_QUERY_RE.exec(text);
106588
+ if (match) return match[1].trim();
106589
+ return text.trim();
106590
+ }
106591
+ function blocksToText(content) {
106592
+ if (typeof content === "string") return content;
106593
+ if (!Array.isArray(content)) return "";
106594
+ const parts = [];
106595
+ for (const block2 of content) {
106596
+ if (!block2 || typeof block2 !== "object") continue;
106597
+ const record2 = block2;
106598
+ if (typeof record2.text === "string") parts.push(record2.text);
106599
+ else if (record2.type === "image") parts.push("[image]");
106600
+ }
106601
+ return parts.join("\n");
106602
+ }
106603
+ function parseGrokRecord(raw) {
106604
+ if (!raw || typeof raw !== "object") return null;
106605
+ const record2 = raw;
106606
+ const type2 = typeof record2.type === "string" ? record2.type : "";
106607
+ if (type2 === "system") return null;
106608
+ if (type2 === "reasoning") return null;
106609
+ if (type2 === "user") {
106610
+ if (typeof record2.synthetic_reason === "string" && record2.synthetic_reason) return null;
106611
+ const text = unwrapUserQuery(blocksToText(record2.content));
106612
+ if (!text) return null;
106613
+ return { role: "user", content: text, kind: "standard" };
106614
+ }
106615
+ if (type2 === "assistant") {
106616
+ const text = blocksToText(record2.content).trim();
106617
+ const toolCalls = Array.isArray(record2.tool_calls) ? record2.tool_calls : [];
106618
+ if (!text) {
106619
+ if (toolCalls.length === 0) return null;
106620
+ const names = toolCalls.map((call) => call && typeof call === "object" ? call.name : null).filter((name) => typeof name === "string" && name.length > 0);
106621
+ const label = names.length > 0 ? names.join(", ") : "tool";
106622
+ return { role: "assistant", content: `[tool: ${label}]`, kind: "tool" };
106623
+ }
106624
+ return { role: "assistant", content: text, kind: "standard" };
106625
+ }
106626
+ if (type2 === "tool_result") {
106627
+ const text = blocksToText(record2.content).trim();
106628
+ if (!text) return null;
106629
+ return { role: "assistant", content: text, kind: "tool" };
106630
+ }
106631
+ return null;
106632
+ }
106633
+ function readSessionCreatedAtMs(sessionDir) {
106634
+ try {
106635
+ const summary = JSON.parse(fs37.readFileSync(path41.join(sessionDir, "summary.json"), "utf8"));
106636
+ const created = summary?.created_at;
106637
+ if (typeof created === "string") {
106638
+ const parsed = Date.parse(created);
106639
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
106640
+ }
106641
+ } catch {
106642
+ }
106643
+ return 0;
106644
+ }
106645
+ function readSession5(sourcePath, sessionId, workspace) {
106646
+ let text;
106647
+ try {
106648
+ text = fs37.readFileSync(sourcePath, "utf8");
106649
+ } catch {
106650
+ return null;
106651
+ }
106652
+ const sessionDir = path41.dirname(sourcePath);
106653
+ const providerSessionId = path41.basename(sessionDir);
106654
+ const sourceMtimeMs = statMtimeMs5(sourcePath);
106655
+ const parsed = [];
106656
+ for (const line of text.split("\n")) {
106657
+ const trimmed = line.trim();
106658
+ if (!trimmed) continue;
106659
+ let record2;
106660
+ try {
106661
+ record2 = JSON.parse(trimmed);
106662
+ } catch {
106663
+ continue;
106664
+ }
106665
+ const message = parseGrokRecord(record2);
106666
+ if (message) parsed.push(message);
106667
+ }
106668
+ const startMs = readSessionCreatedAtMs(sessionDir) || sourceMtimeMs;
106669
+ const endMs = Math.max(sourceMtimeMs, startMs);
106670
+ const span = endMs - startMs;
106671
+ const step = parsed.length > 1 ? Math.floor(span / (parsed.length - 1)) : 0;
106672
+ const messages = parsed.map((message, index) => {
106673
+ const receivedAt = parsed.length > 1 ? startMs + step * index : endMs;
106674
+ return {
106675
+ ts: new Date(receivedAt).toISOString(),
106676
+ receivedAt,
106677
+ role: message.role,
106678
+ content: message.content,
106679
+ kind: message.kind,
106680
+ agent: "grok-cli",
106681
+ historySessionId: sessionId || providerSessionId,
106682
+ ...workspace ? { workspace } : {},
106683
+ providerUnitKey: `${providerSessionId}:${index}`
106684
+ };
106685
+ });
106686
+ return {
106687
+ messages,
106688
+ providerSessionId,
106689
+ source: "provider-native",
106690
+ sourcePath,
106691
+ sourceMtimeMs,
106692
+ nativeHistoryCoverage: "full",
106693
+ ...workspace ? { workspace } : {}
106694
+ };
106695
+ }
106696
+ function listSessions(workspace, limit = 50) {
106697
+ const root = grokSessionsRoot();
106698
+ if (!fs37.existsSync(root)) return [];
106699
+ const dirs = [];
106700
+ for (const candidate of workspaceCandidates(workspace || "")) {
106701
+ if (!candidate) continue;
106702
+ const dir = path41.join(root, encodeWorkspaceDir(candidate));
106703
+ if (fs37.existsSync(dir)) dirs.push(dir);
106704
+ }
106705
+ if (dirs.length === 0) return [];
106706
+ const out = [];
106707
+ for (const dir of dirs) {
106708
+ let entries = [];
106709
+ try {
106710
+ entries = fs37.readdirSync(dir, { withFileTypes: true });
106711
+ } catch {
106712
+ continue;
106713
+ }
106714
+ for (const entry of entries) {
106715
+ if (!entry.isDirectory() || !isUuidLike2(entry.name)) continue;
106716
+ const sourcePath = path41.join(dir, entry.name, "chat_history.jsonl");
106717
+ if (!fs37.existsSync(sourcePath)) continue;
106718
+ const session = readSession5(sourcePath, entry.name, workspace);
106719
+ if (!session || session.messages.length === 0) continue;
106720
+ const first = session.messages[0];
106721
+ const last = session.messages[session.messages.length - 1];
106722
+ const firstUser = session.messages.find(
106723
+ (m) => m.role === "user" && !m.content.startsWith("<user_info>")
106724
+ ) ?? session.messages.find((m) => m.role === "user");
106725
+ out.push({
106726
+ historySessionId: entry.name,
106727
+ sessionId: entry.name,
106728
+ sourcePath,
106729
+ sourceMtimeMs: session.sourceMtimeMs,
106730
+ messageCount: session.messages.length,
106731
+ firstMessageAt: first.receivedAt,
106732
+ lastMessageAt: last.receivedAt,
106733
+ ...firstUser ? { sessionTitle: firstUser.content.slice(0, 80) } : {},
106734
+ ...firstUser ? { preview: firstUser.content.slice(0, 200) } : {},
106735
+ ...workspace ? { workspace } : {},
106736
+ agent: "grok-cli",
106737
+ source: "provider-native",
106738
+ nativeHistoryCoverage: "full"
106739
+ });
106740
+ }
106741
+ }
106742
+ out.sort((a, b) => b.sourceMtimeMs - a.sourceMtimeMs);
106743
+ return out.slice(0, limit);
106744
+ }
106745
+ function listSessionsAllWorkspaces(limit = 50) {
106746
+ const root = grokSessionsRoot();
106747
+ if (!fs37.existsSync(root)) return [];
106748
+ let dirs = [];
106749
+ try {
106750
+ dirs = fs37.readdirSync(root, { withFileTypes: true });
106751
+ } catch {
106752
+ return [];
106753
+ }
106754
+ const out = [];
106755
+ for (const dir of dirs) {
106756
+ if (!dir.isDirectory()) continue;
106757
+ let workspace = "";
106758
+ try {
106759
+ workspace = decodeURIComponent(dir.name);
106760
+ } catch {
106761
+ continue;
106762
+ }
106763
+ out.push(...listSessions(workspace, limit));
106764
+ }
106765
+ out.sort((a, b) => b.sourceMtimeMs - a.sourceMtimeMs);
106766
+ return out.slice(0, limit);
106767
+ }
106401
106768
  init_constants();
106402
106769
  function createNativeHistoryDispatcher(reader) {
106403
106770
  return (input) => {
@@ -106412,7 +106779,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106412
106779
  const ownerConfirmed = reader === "antigravity-cli" ? resolved?.ownerConfirmed === true : void 0;
106413
106780
  if (input.forceRefresh === true || input.args?.forceRefresh === true) {
106414
106781
  try {
106415
- fs37.statSync(sourcePath);
106782
+ fs38.statSync(sourcePath);
106416
106783
  } catch {
106417
106784
  }
106418
106785
  }
@@ -106463,14 +106830,21 @@ Run 'adhdev doctor' for detailed diagnostics.`
106463
106830
  const p = resolveHermesPath(workspace, sessionId);
106464
106831
  return p ? { path: p } : null;
106465
106832
  }
106833
+ // grok stores per-cwd like claude, but keyed by the url-encoded cwd and
106834
+ // with the uuid as a DIRECTORY (…/<uuid>/chat_history.jsonl) rather than
106835
+ // the filename, so resolution lives in the reader module.
106836
+ case "grok-cli": {
106837
+ const p = resolveGrokPath(workspace, sessionId);
106838
+ return p ? { path: p } : null;
106839
+ }
106466
106840
  }
106467
106841
  }
106468
106842
  function resolveClaudePath(workspace, sessionId) {
106469
- const dir = path41.join(os25.homedir(), ".claude", "projects", cwdAsDashes(workspace));
106470
- if (!fs37.existsSync(dir)) return null;
106843
+ const dir = path422.join(os26.homedir(), ".claude", "projects", cwdAsDashes(workspace));
106844
+ if (!fs38.existsSync(dir)) return null;
106471
106845
  if (sessionId) {
106472
- const candidate = path41.join(dir, `${sessionId}.jsonl`);
106473
- if (fs37.existsSync(candidate)) return candidate;
106846
+ const candidate = path422.join(dir, `${sessionId}.jsonl`);
106847
+ if (fs38.existsSync(candidate)) return candidate;
106474
106848
  }
106475
106849
  return null;
106476
106850
  }
@@ -106482,7 +106856,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106482
106856
  return findCodexPathByRuntime(root, workspace, sessionStartedAtMs);
106483
106857
  }
106484
106858
  function findCodexPathBySessionId(root, sessionId) {
106485
- if (!fs37.existsSync(root)) return null;
106859
+ if (!fs38.existsSync(root)) return null;
106486
106860
  const needle = sessionId.toLowerCase();
106487
106861
  const matches = [];
106488
106862
  const stack = [root];
@@ -106490,12 +106864,12 @@ Run 'adhdev doctor' for detailed diagnostics.`
106490
106864
  const current = stack.pop();
106491
106865
  let entries = [];
106492
106866
  try {
106493
- entries = fs37.readdirSync(current, { withFileTypes: true });
106867
+ entries = fs38.readdirSync(current, { withFileTypes: true });
106494
106868
  } catch {
106495
106869
  continue;
106496
106870
  }
106497
106871
  for (const entry of entries) {
106498
- const entryPath = path41.join(current, entry.name);
106872
+ const entryPath = path422.join(current, entry.name);
106499
106873
  if (entry.isDirectory()) {
106500
106874
  stack.push(entryPath);
106501
106875
  continue;
@@ -106510,7 +106884,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106510
106884
  return matches[0]?.p ?? null;
106511
106885
  }
106512
106886
  function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
106513
- if (!fs37.existsSync(root) || !workspace) return null;
106887
+ if (!fs38.existsSync(root) || !workspace) return null;
106514
106888
  const workspaceResolved = resolveRealPath(workspace);
106515
106889
  const cutoff = Date.now() - RECENT_WINDOW_MS;
106516
106890
  const matches = [];
@@ -106519,12 +106893,12 @@ Run 'adhdev doctor' for detailed diagnostics.`
106519
106893
  const current = stack.pop();
106520
106894
  let entries = [];
106521
106895
  try {
106522
- entries = fs37.readdirSync(current, { withFileTypes: true });
106896
+ entries = fs38.readdirSync(current, { withFileTypes: true });
106523
106897
  } catch {
106524
106898
  continue;
106525
106899
  }
106526
106900
  for (const entry of entries) {
106527
- const entryPath = path41.join(current, entry.name);
106901
+ const entryPath = path422.join(current, entry.name);
106528
106902
  if (entry.isDirectory()) {
106529
106903
  stack.push(entryPath);
106530
106904
  continue;
@@ -106544,10 +106918,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
106544
106918
  }
106545
106919
  function readCodexSessionMeta(filePath) {
106546
106920
  try {
106547
- const fd = fs37.openSync(filePath, "r");
106921
+ const fd = fs38.openSync(filePath, "r");
106548
106922
  try {
106549
106923
  const buffer = Buffer.alloc(8192);
106550
- const bytes = fs37.readSync(fd, buffer, 0, buffer.length, 0);
106924
+ const bytes = fs38.readSync(fd, buffer, 0, buffer.length, 0);
106551
106925
  if (bytes <= 0) return null;
106552
106926
  const text = buffer.subarray(0, bytes).toString("utf8");
106553
106927
  const firstLine = text.slice(0, text.indexOf("\n") >= 0 ? text.indexOf("\n") : text.length).trim();
@@ -106562,7 +106936,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106562
106936
  timestampMs: Number.isFinite(timestampMs) ? timestampMs : void 0
106563
106937
  };
106564
106938
  } finally {
106565
- fs37.closeSync(fd);
106939
+ fs38.closeSync(fd);
106566
106940
  }
106567
106941
  } catch {
106568
106942
  return null;
@@ -106570,7 +106944,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106570
106944
  }
106571
106945
  function resolveRealPath(value) {
106572
106946
  try {
106573
- return fs37.realpathSync(value);
106947
+ return fs38.realpathSync(value);
106574
106948
  } catch {
106575
106949
  return value;
106576
106950
  }
@@ -106588,24 +106962,24 @@ Run 'adhdev doctor' for detailed diagnostics.`
106588
106962
  }
106589
106963
  var AGY_SPAWN_CLAIM_GRACE_MS = 2e3;
106590
106964
  function resolveAntigravityPath(workspace, sessionId, sessionStartedAtMs, instanceId) {
106591
- const agyRoot = path41.join(os25.homedir(), ".gemini", "antigravity-cli");
106965
+ const agyRoot = path422.join(os26.homedir(), ".gemini", "antigravity-cli");
106592
106966
  const owner = antigravityOwnerToken(workspace, sessionStartedAtMs, instanceId);
106593
106967
  if (sessionId && isUuidLikeSessionId2(sessionId)) {
106594
- const dbPath = path41.join(agyRoot, "conversations", `${sessionId}.db`);
106595
- if (fs37.existsSync(dbPath)) {
106968
+ const dbPath = path422.join(agyRoot, "conversations", `${sessionId}.db`);
106969
+ if (fs38.existsSync(dbPath)) {
106596
106970
  if (owner) claimAntigravityConversation(sessionId, owner);
106597
106971
  return { path: dbPath, ownerConfirmed: true };
106598
106972
  }
106599
106973
  }
106600
- const brainRoot2 = path41.join(agyRoot, "brain");
106601
- if (fs37.existsSync(brainRoot2)) {
106974
+ const brainRoot2 = path422.join(agyRoot, "brain");
106975
+ if (fs38.existsSync(brainRoot2)) {
106602
106976
  const cutoff = spawnAwareCutoff(sessionStartedAtMs);
106603
106977
  const nonEmptyBrain = (uuid3, p) => {
106604
- const t = path41.join(p, ".system_generated", "logs", "transcript.jsonl");
106605
- return fs37.existsSync(t) && safeSize(t) > 0 ? t : null;
106978
+ const t = path422.join(p, ".system_generated", "logs", "transcript.jsonl");
106979
+ return fs38.existsSync(t) && safeSize(t) > 0 ? t : null;
106606
106980
  };
106607
- const all = fs37.readdirSync(brainRoot2, { withFileTypes: true }).filter((e) => e.isDirectory() && isUuidLikeSessionId2(e.name)).filter((e) => !isAntigravityConversationClaimedByOther(e.name, owner)).map((e) => {
106608
- const p = path41.join(brainRoot2, e.name);
106981
+ const all = fs38.readdirSync(brainRoot2, { withFileTypes: true }).filter((e) => e.isDirectory() && isUuidLikeSessionId2(e.name)).filter((e) => !isAntigravityConversationClaimedByOther(e.name, owner)).map((e) => {
106982
+ const p = path422.join(brainRoot2, e.name);
106609
106983
  return { uuid: e.name, p, mtime: safeMtime(p), birth: safeBirthtime(p) };
106610
106984
  }).filter((e) => e.mtime >= cutoff);
106611
106985
  let ordered = [];
@@ -106624,7 +106998,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106624
106998
  }
106625
106999
  }
106626
107000
  }
106627
- const convRoot = path41.join(agyRoot, "conversations");
107001
+ const convRoot = path422.join(agyRoot, "conversations");
106628
107002
  const picked = pickUnboundConversationDb(convRoot, sessionStartedAtMs, owner);
106629
107003
  if (picked) {
106630
107004
  if (owner) claimAntigravityConversation(picked.uuid, owner);
@@ -106635,7 +107009,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106635
107009
  function pickUnboundConversationDb(convRoot, sessionFloorMs, owner) {
106636
107010
  let entries = [];
106637
107011
  try {
106638
- entries = fs37.readdirSync(convRoot, { withFileTypes: true });
107012
+ entries = fs38.readdirSync(convRoot, { withFileTypes: true });
106639
107013
  } catch {
106640
107014
  return null;
106641
107015
  }
@@ -106648,7 +107022,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106648
107022
  if (!match || !isUuidLikeSessionId2(match[1])) continue;
106649
107023
  const uuid3 = match[1];
106650
107024
  if (isAntigravityConversationClaimedByOther(uuid3, owner)) continue;
106651
- const p = path41.join(convRoot, entry.name);
107025
+ const p = path422.join(convRoot, entry.name);
106652
107026
  const mtime = safeMtime(p);
106653
107027
  if (applyRecencyCutoff && mtime < recencyCutoff) continue;
106654
107028
  candidates.push({ path: p, uuid: uuid3, mtime, birth: safeBirthtime(p) });
@@ -106672,10 +107046,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
106672
107046
  function resolveHermesPath(workspace, sessionId) {
106673
107047
  void workspace;
106674
107048
  void sessionId;
106675
- const dbPath = path41.join(os25.homedir(), ".hermes", "state.db");
106676
- if (fs37.existsSync(dbPath)) return dbPath;
106677
- const dir = path41.join(os25.homedir(), ".hermes", "sessions");
106678
- if (!fs37.existsSync(dir)) return null;
107049
+ const dbPath = path422.join(os26.homedir(), ".hermes", "state.db");
107050
+ if (fs38.existsSync(dbPath)) return dbPath;
107051
+ const dir = path422.join(os26.homedir(), ".hermes", "sessions");
107052
+ if (!fs38.existsSync(dir)) return null;
106679
107053
  return newestRecentFile2(dir, /^session_.*\.json$/);
106680
107054
  }
106681
107055
  function readByReader(reader, sourcePath, sessionId, workspace, requestedProviderSid) {
@@ -106693,6 +107067,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
106693
107067
  // per-session file upstream, so they need no equivalent pin here.
106694
107068
  case "hermes-cli":
106695
107069
  return readSession4(sourcePath, requestedProviderSid || void 0);
107070
+ case "grok-cli":
107071
+ return readSession5(sourcePath, sessionId, workspace || void 0);
106696
107072
  }
106697
107073
  }
106698
107074
  function cwdAsDashes(cwd) {
@@ -106700,7 +107076,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106700
107076
  return cwd.replace(/\//g, "-");
106701
107077
  }
106702
107078
  function codexSessionsRoot() {
106703
- return path41.join(os25.homedir(), ".codex", "sessions");
107079
+ return path422.join(os26.homedir(), ".codex", "sessions");
106704
107080
  }
106705
107081
  function isUuidLikeSessionId2(sessionId) {
106706
107082
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId);
@@ -106712,7 +107088,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106712
107088
  function newestRecentFile2(dir, pattern) {
106713
107089
  try {
106714
107090
  const cutoff = Date.now() - RECENT_WINDOW_MS;
106715
- const entries = fs37.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && pattern.test(e.name)).map((e) => ({ p: path41.join(dir, e.name), mtime: safeMtime(path41.join(dir, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
107091
+ const entries = fs38.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && pattern.test(e.name)).map((e) => ({ p: path422.join(dir, e.name), mtime: safeMtime(path422.join(dir, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
106716
107092
  return entries[0]?.p ?? null;
106717
107093
  } catch {
106718
107094
  return null;
@@ -106720,14 +107096,14 @@ Run 'adhdev doctor' for detailed diagnostics.`
106720
107096
  }
106721
107097
  function safeMtime(p) {
106722
107098
  try {
106723
- return Math.floor(fs37.statSync(p).mtimeMs);
107099
+ return Math.floor(fs38.statSync(p).mtimeMs);
106724
107100
  } catch {
106725
107101
  return 0;
106726
107102
  }
106727
107103
  }
106728
107104
  function safeBirthtime(p) {
106729
107105
  try {
106730
- const st = fs37.statSync(p);
107106
+ const st = fs38.statSync(p);
106731
107107
  const birth = Math.floor(st.birthtimeMs);
106732
107108
  return birth > 0 ? birth : Math.floor(st.mtimeMs);
106733
107109
  } catch {
@@ -106736,11 +107112,20 @@ Run 'adhdev doctor' for detailed diagnostics.`
106736
107112
  }
106737
107113
  function safeSize(p) {
106738
107114
  try {
106739
- return fs37.statSync(p).size;
107115
+ return fs38.statSync(p).size;
106740
107116
  } catch {
106741
107117
  return 0;
106742
107118
  }
106743
107119
  }
107120
+ function createNativeHistoryListDispatcher(reader) {
107121
+ if (reader !== "grok-cli") return null;
107122
+ return (input) => {
107123
+ const limitRaw = input.args?.limit;
107124
+ const limit = typeof limitRaw === "number" && limitRaw > 0 ? Math.floor(limitRaw) : 50;
107125
+ const sessions = input.workspace ? listSessions(input.workspace, limit) : listSessionsAllWorkspaces(limit);
107126
+ return { sessions };
107127
+ };
107128
+ }
106744
107129
  function normalizeRole2(r) {
106745
107130
  const s2 = String(r ?? "").toLowerCase();
106746
107131
  if (s2 === "user" || s2 === "human") return "user";
@@ -106810,8 +107195,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
106810
107195
  }
106811
107196
  return { activatable, skipped };
106812
107197
  }
106813
- var fs38 = __toESM2(require("fs"));
106814
- var path422 = __toESM2(require("path"));
107198
+ var fs39 = __toESM2(require("fs"));
107199
+ var path43 = __toESM2(require("path"));
106815
107200
  var crypto8 = __toESM2(require("crypto"));
106816
107201
  init_config();
106817
107202
  var ProviderChannelStore = class _ProviderChannelStore {
@@ -106824,19 +107209,19 @@ Run 'adhdev doctor' for detailed diagnostics.`
106824
107209
  }
106825
107210
  /** Default store root, resolved through the config-dir abstraction. */
106826
107211
  static defaultRoot() {
106827
- return path422.join(getConfigDir2(), "providers", ".store");
107212
+ return path43.join(getConfigDir2(), "providers", ".store");
106828
107213
  }
106829
107214
  get objectsDir() {
106830
- return path422.join(this.rootDir, "objects");
107215
+ return path43.join(this.rootDir, "objects");
106831
107216
  }
106832
107217
  get stagingDir() {
106833
- return path422.join(this.rootDir, "staging");
107218
+ return path43.join(this.rootDir, "staging");
106834
107219
  }
106835
107220
  activeDir(channel) {
106836
- return path422.join(this.rootDir, "active", channel);
107221
+ return path43.join(this.rootDir, "active", channel);
106837
107222
  }
106838
107223
  pointerPath(channel, providerType) {
106839
- return path422.join(this.activeDir(channel), `${providerType}.json`);
107224
+ return path43.join(this.activeDir(channel), `${providerType}.json`);
106840
107225
  }
106841
107226
  log(msg) {
106842
107227
  this.logFn(`[ProviderChannelStore] ${msg}`);
@@ -106844,14 +107229,14 @@ Run 'adhdev doctor' for detailed diagnostics.`
106844
107229
  // ─── Staging ─────────────────────────────────────────────
106845
107230
  /** Create a fresh staging directory. Caller must clean it up (or gc will). */
106846
107231
  createStagingDir(kind) {
106847
- const dir = path422.join(this.stagingDir, `${kind}-${process.pid}-${crypto8.randomBytes(6).toString("hex")}`);
106848
- fs38.mkdirSync(dir, { recursive: true });
107232
+ const dir = path43.join(this.stagingDir, `${kind}-${process.pid}-${crypto8.randomBytes(6).toString("hex")}`);
107233
+ fs39.mkdirSync(dir, { recursive: true });
106849
107234
  return dir;
106850
107235
  }
106851
107236
  removeStagingDir(dir) {
106852
- if (!dir.startsWith(this.stagingDir + path422.sep)) return;
107237
+ if (!dir.startsWith(this.stagingDir + path43.sep)) return;
106853
107238
  try {
106854
- fs38.rmSync(dir, { recursive: true, force: true });
107239
+ fs39.rmSync(dir, { recursive: true, force: true });
106855
107240
  } catch {
106856
107241
  }
106857
107242
  }
@@ -106863,11 +107248,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
106863
107248
  return digest.slice("sha256:".length);
106864
107249
  }
106865
107250
  getObjectDir(digest) {
106866
- return path422.join(this.objectsDir, _ProviderChannelStore.objectName(digest));
107251
+ return path43.join(this.objectsDir, _ProviderChannelStore.objectName(digest));
106867
107252
  }
106868
107253
  hasObject(digest) {
106869
107254
  try {
106870
- return fs38.statSync(this.getObjectDir(digest)).isDirectory();
107255
+ return fs39.statSync(this.getObjectDir(digest)).isDirectory();
106871
107256
  } catch {
106872
107257
  return false;
106873
107258
  }
@@ -106885,8 +107270,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
106885
107270
  this.removeStagingDir(stagedObjectDir);
106886
107271
  return objectDir;
106887
107272
  }
106888
- fs38.mkdirSync(this.objectsDir, { recursive: true });
106889
- fs38.renameSync(stagedObjectDir, objectDir);
107273
+ fs39.mkdirSync(this.objectsDir, { recursive: true });
107274
+ fs39.renameSync(stagedObjectDir, objectDir);
106890
107275
  return objectDir;
106891
107276
  }
106892
107277
  // ─── Pointers ────────────────────────────────────────────
@@ -106898,10 +107283,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
106898
107283
  */
106899
107284
  getPointer(channel, providerType) {
106900
107285
  const file2 = this.pointerPath(channel, providerType);
106901
- if (!fs38.existsSync(file2)) return null;
107286
+ if (!fs39.existsSync(file2)) return null;
106902
107287
  let parsed;
106903
107288
  try {
106904
- parsed = JSON.parse(fs38.readFileSync(file2, "utf-8"));
107289
+ parsed = JSON.parse(fs39.readFileSync(file2, "utf-8"));
106905
107290
  } catch (e) {
106906
107291
  throw new ProviderChannelError(
106907
107292
  "STORE_CORRUPT",
@@ -106929,7 +107314,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106929
107314
  const dir = this.activeDir(channel);
106930
107315
  let files = [];
106931
107316
  try {
106932
- files = fs38.readdirSync(dir).filter((f) => f.endsWith(".json"));
107317
+ files = fs39.readdirSync(dir).filter((f) => f.endsWith(".json"));
106933
107318
  } catch {
106934
107319
  return { pointers, errors };
106935
107320
  }
@@ -106950,7 +107335,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
106950
107335
  const activations = [];
106951
107336
  for (const pointer of pointers.values()) {
106952
107337
  const objectDir = this.getObjectDir(pointer.active.digest);
106953
- if (!fs38.existsSync(objectDir)) {
107338
+ if (!fs39.existsSync(objectDir)) {
106954
107339
  errors.push(new ProviderChannelError(
106955
107340
  "STORE_CORRUPT",
106956
107341
  `active object ${pointer.active.digest} for "${pointer.active.providerType}" is missing \u2014 skipping (fail closed)`,
@@ -107019,9 +107404,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
107019
107404
  /** Remove an activation pointer (e.g. provider uninstalled). */
107020
107405
  removePointer(channel, providerType) {
107021
107406
  const file2 = this.pointerPath(channel, providerType);
107022
- if (!fs38.existsSync(file2)) return false;
107407
+ if (!fs39.existsSync(file2)) return false;
107023
107408
  try {
107024
- fs38.rmSync(file2, { force: true });
107409
+ fs39.rmSync(file2, { force: true });
107025
107410
  return true;
107026
107411
  } catch {
107027
107412
  return false;
@@ -107029,11 +107414,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
107029
107414
  }
107030
107415
  writePointerAtomic(channel, providerType, pointer) {
107031
107416
  const dir = this.activeDir(channel);
107032
- fs38.mkdirSync(dir, { recursive: true });
107417
+ fs39.mkdirSync(dir, { recursive: true });
107033
107418
  const file2 = this.pointerPath(channel, providerType);
107034
- const tmp = path422.join(dir, `.${providerType}.${process.pid}.${crypto8.randomBytes(4).toString("hex")}.tmp`);
107035
- fs38.writeFileSync(tmp, JSON.stringify(pointer, null, 2), "utf-8");
107036
- fs38.renameSync(tmp, file2);
107419
+ const tmp = path43.join(dir, `.${providerType}.${process.pid}.${crypto8.randomBytes(4).toString("hex")}.tmp`);
107420
+ fs39.writeFileSync(tmp, JSON.stringify(pointer, null, 2), "utf-8");
107421
+ fs39.renameSync(tmp, file2);
107037
107422
  }
107038
107423
  // ─── GC (N=2 retention) ──────────────────────────────────
107039
107424
  /**
@@ -107049,13 +107434,13 @@ Run 'adhdev doctor' for detailed diagnostics.`
107049
107434
  const dir = this.activeDir(channel);
107050
107435
  let files = [];
107051
107436
  try {
107052
- files = fs38.readdirSync(dir).filter((f) => f.endsWith(".json"));
107437
+ files = fs39.readdirSync(dir).filter((f) => f.endsWith(".json"));
107053
107438
  } catch {
107054
107439
  continue;
107055
107440
  }
107056
107441
  for (const file2 of files) {
107057
107442
  try {
107058
- const parsed = JSON.parse(fs38.readFileSync(path422.join(dir, file2), "utf-8"));
107443
+ const parsed = JSON.parse(fs39.readFileSync(path43.join(dir, file2), "utf-8"));
107059
107444
  if (typeof parsed?.active?.digest === "string") referenced.add(parsed.active.digest);
107060
107445
  if (typeof parsed?.previous?.digest === "string") referenced.add(parsed.previous.digest);
107061
107446
  } catch {
@@ -107065,7 +107450,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107065
107450
  const removedObjects = [];
107066
107451
  let objectNames = [];
107067
107452
  try {
107068
- objectNames = fs38.readdirSync(this.objectsDir);
107453
+ objectNames = fs39.readdirSync(this.objectsDir);
107069
107454
  } catch {
107070
107455
  objectNames = [];
107071
107456
  }
@@ -107073,7 +107458,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107073
107458
  const digest = `sha256:${name}`;
107074
107459
  if (referenced.has(digest)) continue;
107075
107460
  try {
107076
- fs38.rmSync(path422.join(this.objectsDir, name), { recursive: true, force: true });
107461
+ fs39.rmSync(path43.join(this.objectsDir, name), { recursive: true, force: true });
107077
107462
  removedObjects.push(digest);
107078
107463
  } catch {
107079
107464
  }
@@ -107081,13 +107466,13 @@ Run 'adhdev doctor' for detailed diagnostics.`
107081
107466
  let removedStaging = 0;
107082
107467
  let stagingEntries = [];
107083
107468
  try {
107084
- stagingEntries = fs38.readdirSync(this.stagingDir);
107469
+ stagingEntries = fs39.readdirSync(this.stagingDir);
107085
107470
  } catch {
107086
107471
  stagingEntries = [];
107087
107472
  }
107088
107473
  for (const name of stagingEntries) {
107089
107474
  try {
107090
- fs38.rmSync(path422.join(this.stagingDir, name), { recursive: true, force: true });
107475
+ fs39.rmSync(path43.join(this.stagingDir, name), { recursive: true, force: true });
107091
107476
  removedStaging++;
107092
107477
  } catch {
107093
107478
  }
@@ -107098,10 +107483,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
107098
107483
  return { removedObjects, removedStaging };
107099
107484
  }
107100
107485
  };
107101
- var fs41 = __toESM2(require("fs"));
107486
+ var fs422 = __toESM2(require("fs"));
107487
+ var path45 = __toESM2(require("path"));
107488
+ var fs40 = __toESM2(require("fs"));
107102
107489
  var path44 = __toESM2(require("path"));
107103
- var fs39 = __toESM2(require("fs"));
107104
- var path43 = __toESM2(require("path"));
107105
107490
  var import_crypto12 = require("crypto");
107106
107491
  var TREE_DIGEST_ALGORITHM = "adhdev-provider-tree-sha256-v1";
107107
107492
  function computeProviderTreeDigest(rootDir, providerType) {
@@ -107117,8 +107502,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
107117
107502
  relPaths.sort();
107118
107503
  const hash2 = (0, import_crypto12.createHash)("sha256");
107119
107504
  for (const relPath of relPaths) {
107120
- const absPath = path43.join(rootDir, ...relPath.split("/"));
107121
- const bytes = fs39.readFileSync(absPath);
107505
+ const absPath = path44.join(rootDir, ...relPath.split("/"));
107506
+ const bytes = fs40.readFileSync(absPath);
107122
107507
  hash2.update(relPath, "utf8");
107123
107508
  hash2.update("\0");
107124
107509
  hash2.update(String(bytes.length), "utf8");
@@ -107130,7 +107515,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107130
107515
  function collectRegularFiles(rootDir, dir, out, providerType) {
107131
107516
  let entries;
107132
107517
  try {
107133
- entries = fs39.readdirSync(dir, { withFileTypes: true });
107518
+ entries = fs40.readdirSync(dir, { withFileTypes: true });
107134
107519
  } catch (e) {
107135
107520
  throw new ProviderChannelError(
107136
107521
  "ENTRY_TREE_INVALID",
@@ -107139,7 +107524,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107139
107524
  );
107140
107525
  }
107141
107526
  for (const entry of entries) {
107142
- const abs = path43.join(dir, entry.name);
107527
+ const abs = path44.join(dir, entry.name);
107143
107528
  if (entry.isDirectory()) {
107144
107529
  collectRegularFiles(rootDir, abs, out, providerType);
107145
107530
  continue;
@@ -107151,16 +107536,16 @@ Run 'adhdev doctor' for detailed diagnostics.`
107151
107536
  providerType
107152
107537
  );
107153
107538
  }
107154
- const rel = path43.relative(rootDir, abs).split(path43.sep).join("/");
107539
+ const rel = path44.relative(rootDir, abs).split(path44.sep).join("/");
107155
107540
  out.push(rel);
107156
107541
  }
107157
107542
  }
107158
- var fs40 = __toESM2(require("fs"));
107543
+ var fs41 = __toESM2(require("fs"));
107159
107544
  var zlib = __toESM2(require("zlib"));
107160
107545
  var import_promises5 = require("stream/promises");
107161
107546
  async function extractTarballGz(tarPath, destDir) {
107162
107547
  const tarFs = require_tar_fs();
107163
- await (0, import_promises5.pipeline)(fs40.createReadStream(tarPath), zlib.createGunzip(), tarFs.extract(destDir));
107548
+ await (0, import_promises5.pipeline)(fs41.createReadStream(tarPath), zlib.createGunzip(), tarFs.extract(destDir));
107164
107549
  }
107165
107550
  var REGISTRY_LIST_LIMIT = 100;
107166
107551
  var ProviderChannelRuntime = class {
@@ -107281,9 +107666,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
107281
107666
  }
107282
107667
  const stagingRoot = this.store.createStagingDir("sync");
107283
107668
  try {
107284
- const tarPath = path44.join(stagingRoot, "providers.tar.gz");
107285
- const extractDir = path44.join(stagingRoot, "repo");
107286
- fs41.mkdirSync(extractDir, { recursive: true });
107669
+ const tarPath = path45.join(stagingRoot, "providers.tar.gz");
107670
+ const extractDir = path45.join(stagingRoot, "repo");
107671
+ fs422.mkdirSync(extractDir, { recursive: true });
107287
107672
  try {
107288
107673
  await this.downloadFile(this.providerTarballUrl, tarPath);
107289
107674
  await this.extractTarball(tarPath, extractDir);
@@ -107340,9 +107725,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
107340
107725
  const objStaging = this.store.createStagingDir(`obj-${entry.providerType}`);
107341
107726
  let relDir;
107342
107727
  try {
107343
- relDir = path44.relative(repoRoot, artifactDir).split(path44.sep).join("/");
107344
- fs41.mkdirSync(path44.join(objStaging, entry.category), { recursive: true });
107345
- fs41.renameSync(artifactDir, path44.join(objStaging, entry.category, path44.basename(artifactDir)));
107728
+ relDir = path45.relative(repoRoot, artifactDir).split(path45.sep).join("/");
107729
+ fs422.mkdirSync(path45.join(objStaging, entry.category), { recursive: true });
107730
+ fs422.renameSync(artifactDir, path45.join(objStaging, entry.category, path45.basename(artifactDir)));
107346
107731
  } catch (e) {
107347
107732
  this.store.removeStagingDir(objStaging);
107348
107733
  return { code: "TRANSPORT_FAILED", message: `failed to stage artifact tree: ${e?.message || e}`, providerType: entry.providerType };
@@ -107381,31 +107766,31 @@ Run 'adhdev doctor' for detailed diagnostics.`
107381
107766
  function findTarballRepoRoot(extractDir) {
107382
107767
  let entries;
107383
107768
  try {
107384
- entries = fs41.readdirSync(extractDir, { withFileTypes: true });
107769
+ entries = fs422.readdirSync(extractDir, { withFileTypes: true });
107385
107770
  } catch {
107386
107771
  return null;
107387
107772
  }
107388
107773
  const dirs = entries.filter((e) => e.isDirectory());
107389
107774
  if (dirs.length !== 1) return null;
107390
- return path44.join(extractDir, dirs[0].name);
107775
+ return path45.join(extractDir, dirs[0].name);
107391
107776
  }
107392
107777
  function locateArtifactDir(repoRoot, entry) {
107393
- const categoryDir = path44.join(repoRoot, entry.category);
107778
+ const categoryDir = path45.join(repoRoot, entry.category);
107394
107779
  let candidates;
107395
107780
  try {
107396
- candidates = fs41.readdirSync(categoryDir, { withFileTypes: true });
107781
+ candidates = fs422.readdirSync(categoryDir, { withFileTypes: true });
107397
107782
  } catch {
107398
107783
  return null;
107399
107784
  }
107400
107785
  for (const candidate of candidates) {
107401
107786
  if (!candidate.isDirectory()) continue;
107402
107787
  if (candidate.name.startsWith("_") || candidate.name.startsWith(".")) continue;
107403
- const dir = path44.join(categoryDir, candidate.name);
107788
+ const dir = path45.join(categoryDir, candidate.name);
107404
107789
  for (const manifestName of ["provider.v1.json", "provider.json"]) {
107405
- const manifestPath = path44.join(dir, manifestName);
107790
+ const manifestPath = path45.join(dir, manifestName);
107406
107791
  try {
107407
- if (!fs41.existsSync(manifestPath)) continue;
107408
- const manifest = JSON.parse(fs41.readFileSync(manifestPath, "utf-8"));
107792
+ if (!fs422.existsSync(manifestPath)) continue;
107793
+ const manifest = JSON.parse(fs422.readFileSync(manifestPath, "utf-8"));
107409
107794
  if (manifest?.type === entry.providerType) return dir;
107410
107795
  break;
107411
107796
  } catch {
@@ -107422,14 +107807,14 @@ Run 'adhdev doctor' for detailed diagnostics.`
107422
107807
  const scan = (dir) => {
107423
107808
  let entries;
107424
107809
  try {
107425
- entries = fs41.readdirSync(dir, { withFileTypes: true });
107810
+ entries = fs422.readdirSync(dir, { withFileTypes: true });
107426
107811
  } catch {
107427
107812
  return;
107428
107813
  }
107429
107814
  const manifest = entries.find((e) => e.isFile() && (e.name === "provider.v1.json" || e.name === "provider.json"));
107430
107815
  if (manifest) {
107431
107816
  try {
107432
- const parsed = JSON.parse(fs41.readFileSync(path44.join(dir, manifest.name), "utf-8"));
107817
+ const parsed = JSON.parse(fs422.readFileSync(path45.join(dir, manifest.name), "utf-8"));
107433
107818
  if (typeof parsed?.type === "string" && parsed.type.trim()) targets.add(parsed.type);
107434
107819
  } catch {
107435
107820
  }
@@ -107438,7 +107823,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107438
107823
  for (const entry of entries) {
107439
107824
  if (!entry.isDirectory()) continue;
107440
107825
  if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
107441
- scan(path44.join(dir, entry.name));
107826
+ scan(path45.join(dir, entry.name));
107442
107827
  }
107443
107828
  };
107444
107829
  scan(upstreamDir);
@@ -107446,7 +107831,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107446
107831
  }
107447
107832
  function pathEnvDiagnostic() {
107448
107833
  const raw = process.env.PATH ?? "";
107449
- const entries = raw.split(path44.delimiter).filter((e) => e.length > 0);
107834
+ const entries = raw.split(path45.delimiter).filter((e) => e.length > 0);
107450
107835
  const hasSystem32 = entries.some((e) => /system32$/i.test(e.replace(/[\\/]+$/, "")));
107451
107836
  return `platform=${process.platform} pathEntries=${entries.length} system32InPath=${hasSystem32}`;
107452
107837
  }
@@ -107494,7 +107879,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107494
107879
  reject(new Error(`HTTP ${res.statusCode}`));
107495
107880
  return;
107496
107881
  }
107497
- const ws = fs41.createWriteStream(destPath);
107882
+ const ws = fs422.createWriteStream(destPath);
107498
107883
  res.pipe(ws);
107499
107884
  ws.on("finish", () => {
107500
107885
  ws.close();
@@ -107637,9 +108022,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
107637
108022
  static siblingRefusalLogged = /* @__PURE__ */ new Set();
107638
108023
  static looksLikeProviderRoot(candidate) {
107639
108024
  try {
107640
- if (!fs422.existsSync(candidate) || !fs422.statSync(candidate).isDirectory()) return false;
108025
+ if (!fs43.existsSync(candidate) || !fs43.statSync(candidate).isDirectory()) return false;
107641
108026
  return ["ide", "extension", "cli", "acp"].some(
107642
- (category) => fs422.existsSync(path46.join(candidate, category))
108027
+ (category) => fs43.existsSync(path47.join(candidate, category))
107643
108028
  );
107644
108029
  } catch {
107645
108030
  return false;
@@ -107647,20 +108032,20 @@ Run 'adhdev doctor' for detailed diagnostics.`
107647
108032
  }
107648
108033
  static hasProviderRootMarker(candidate) {
107649
108034
  try {
107650
- return fs422.existsSync(path46.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
108035
+ return fs43.existsSync(path47.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
107651
108036
  } catch {
107652
108037
  return false;
107653
108038
  }
107654
108039
  }
107655
108040
  detectDefaultUserDir() {
107656
- const fallback = path46.join(getConfigDir2(), "providers");
108041
+ const fallback = path47.join(getConfigDir2(), "providers");
107657
108042
  const envOptIn = process.env[_ProviderLoader.SIBLING_ENV_VAR] === "1";
107658
108043
  const visited = /* @__PURE__ */ new Set();
107659
108044
  for (const start of this.probeStarts) {
107660
- let current = path46.resolve(start);
108045
+ let current = path47.resolve(start);
107661
108046
  while (!visited.has(current)) {
107662
108047
  visited.add(current);
107663
- const siblingCandidate = path46.join(path46.dirname(current), _ProviderLoader.REPO_PROVIDER_DIRNAME);
108048
+ const siblingCandidate = path47.join(path47.dirname(current), _ProviderLoader.REPO_PROVIDER_DIRNAME);
107664
108049
  if (_ProviderLoader.looksLikeProviderRoot(siblingCandidate)) {
107665
108050
  const hasMarker = _ProviderLoader.hasProviderRootMarker(siblingCandidate);
107666
108051
  if (envOptIn || hasMarker) {
@@ -107697,7 +108082,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107697
108082
  }
107698
108083
  }
107699
108084
  }
107700
- const parent = path46.dirname(current);
108085
+ const parent = path47.dirname(current);
107701
108086
  if (parent === current) break;
107702
108087
  current = parent;
107703
108088
  }
@@ -107713,11 +108098,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
107713
108098
  this.channelStore = options?.channelStore === null ? null : options?.channelStore ?? new ProviderChannelStore(ProviderChannelStore.defaultRoot(), this.logFn);
107714
108099
  this.channelSyncIO = options?.channelSyncIO;
107715
108100
  this.daemonVersion = (options?.daemonVersion || "").trim().replace(/^v/, "");
107716
- this.defaultProvidersDir = path46.join(getConfigDir2(), "providers");
108101
+ this.defaultProvidersDir = path47.join(getConfigDir2(), "providers");
107717
108102
  const detected = this.detectDefaultUserDir();
107718
108103
  this.userDir = detected.path;
107719
108104
  this.userDirSource = detected.source;
107720
- this.upstreamDir = path46.join(this.defaultProvidersDir, ".upstream");
108105
+ this.upstreamDir = path47.join(this.defaultProvidersDir, ".upstream");
107721
108106
  this.disableUpstream = false;
107722
108107
  this.applySourceConfig({
107723
108108
  userDir: options?.userDir,
@@ -107729,14 +108114,14 @@ Run 'adhdev doctor' for detailed diagnostics.`
107729
108114
  migrateMarketplaceDirToExternal() {
107730
108115
  try {
107731
108116
  const configDir = getConfigDir2();
107732
- const oldDir = path46.join(configDir, "marketplace");
107733
- const newDir = path46.join(configDir, "external");
107734
- if (!fs422.existsSync(oldDir)) return;
107735
- if (fs422.existsSync(newDir)) {
108117
+ const oldDir = path47.join(configDir, "marketplace");
108118
+ const newDir = path47.join(configDir, "external");
108119
+ if (!fs43.existsSync(oldDir)) return;
108120
+ if (fs43.existsSync(newDir)) {
107736
108121
  this.log(`Migration skipped: both ~/.adhdev/marketplace and ~/.adhdev/external exist (marketplace dir is now inert and can be removed manually).`);
107737
108122
  return;
107738
108123
  }
107739
- fs422.renameSync(oldDir, newDir);
108124
+ fs43.renameSync(oldDir, newDir);
107740
108125
  this.log(`Migrated ~/.adhdev/marketplace \u2192 ~/.adhdev/external (one-time rename after provider source-layer cleanup).`);
107741
108126
  } catch (e) {
107742
108127
  this.log(`Marketplace\u2192external migration failed: ${e?.message || e}`);
@@ -107766,7 +108151,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107766
108151
  * Highest-priority editable overrides come first.
107767
108152
  */
107768
108153
  getProviderRoots() {
107769
- const externalDir = path46.join(getConfigDir2(), "external");
108154
+ const externalDir = path47.join(getConfigDir2(), "external");
107770
108155
  return [this.userDir, externalDir, ...this.channelObjectRoots, this.upstreamDir];
107771
108156
  }
107772
108157
  getSourceConfig() {
@@ -107794,7 +108179,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107794
108179
  this.userDir = detected.path;
107795
108180
  this.userDirSource = detected.source;
107796
108181
  }
107797
- this.upstreamDir = path46.join(this.defaultProvidersDir, ".upstream");
108182
+ this.upstreamDir = path47.join(this.defaultProvidersDir, ".upstream");
107798
108183
  this.disableUpstream = this.sourceMode === "no-upstream";
107799
108184
  if (this.explicitProviderDir) {
107800
108185
  this.log(`Config 'providerDir' applied: ${this.userDir}`);
@@ -107808,7 +108193,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107808
108193
  * Canonical provider directory shape for a given root.
107809
108194
  */
107810
108195
  getProviderDir(root, category, type2) {
107811
- return path46.join(root, category, type2);
108196
+ return path47.join(root, category, type2);
107812
108197
  }
107813
108198
  /**
107814
108199
  * Canonical user override directory for a provider.
@@ -107835,7 +108220,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107835
108220
  resolveProviderFile(type2, ...segments) {
107836
108221
  const dir = this.findProviderDirInternal(type2);
107837
108222
  if (!dir) return null;
107838
- return path46.join(dir, ...segments);
108223
+ return path47.join(dir, ...segments);
107839
108224
  }
107840
108225
  /**
107841
108226
  * Load all providers (3-tier priority)
@@ -107856,7 +108241,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107856
108241
  this.providers.clear();
107857
108242
  this.providerAvailability.clear();
107858
108243
  let upstreamCount = 0;
107859
- if (!this.disableUpstream && fs422.existsSync(this.upstreamDir)) {
108244
+ if (!this.disableUpstream && fs43.existsSync(this.upstreamDir)) {
107860
108245
  upstreamCount = this.loadDir(this.upstreamDir);
107861
108246
  if (upstreamCount > 0) {
107862
108247
  this.log(`Loaded ${upstreamCount} upstream providers (auto-updated)`);
@@ -107865,11 +108250,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
107865
108250
  this.log("Upstream loading disabled (sourceMode=no-upstream)");
107866
108251
  }
107867
108252
  this.loadVerifiedChannelActivations();
107868
- const externalDir = path46.join(getConfigDir2(), "external");
107869
- if (fs422.existsSync(externalDir)) {
108253
+ const externalDir = path47.join(getConfigDir2(), "external");
108254
+ if (fs43.existsSync(externalDir)) {
107870
108255
  const rootEntries = (() => {
107871
108256
  try {
107872
- return fs422.readdirSync(externalDir, { withFileTypes: true });
108257
+ return fs43.readdirSync(externalDir, { withFileTypes: true });
107873
108258
  } catch {
107874
108259
  return [];
107875
108260
  }
@@ -107887,7 +108272,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107887
108272
  const ambiguousTypes = [];
107888
108273
  for (const sourceEntry of rootEntries) {
107889
108274
  if (!sourceEntry.isDirectory()) continue;
107890
- const sourceDir = path46.join(externalDir, sourceEntry.name);
108275
+ const sourceDir = path47.join(externalDir, sourceEntry.name);
107891
108276
  const sourceLoaded = this.loadDir(sourceDir);
107892
108277
  if (sourceLoaded > 0) {
107893
108278
  totalLoaded += sourceLoaded;
@@ -107903,7 +108288,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107903
108288
  ambiguousTypes.push({ type: type2, chosen: resolved.source ?? "?", candidates: resolved.candidates });
107904
108289
  }
107905
108290
  if (resolved.source && resolved.source !== "?") {
107906
- const sourceDir = path46.join(externalDir, resolved.source);
108291
+ const sourceDir = path47.join(externalDir, resolved.source);
107907
108292
  const reloadCount = this.loadDir(sourceDir);
107908
108293
  if (reloadCount === 0) {
107909
108294
  this.log(`Active source "${resolved.source}" no longer provides ${type2}`);
@@ -107918,7 +108303,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
107918
108303
  }
107919
108304
  }
107920
108305
  }
107921
- if (fs422.existsSync(this.userDir)) {
108306
+ if (fs43.existsSync(this.userDir)) {
107922
108307
  const userCount = this.loadDir(this.userDir, [".upstream"]);
107923
108308
  if (userCount > 0) {
107924
108309
  this.log(`Loaded ${userCount} user custom providers (never auto-updated)`);
@@ -108056,18 +108441,18 @@ Run 'adhdev doctor' for detailed diagnostics.`
108056
108441
  if (this.countVerifiedChannelPointers() > 0) return null;
108057
108442
  if (this.hasUpstream()) return this.syncVerifiedChannel();
108058
108443
  try {
108059
- fs422.mkdirSync(this.defaultProvidersDir, { recursive: true });
108444
+ fs43.mkdirSync(this.defaultProvidersDir, { recursive: true });
108060
108445
  } catch {
108061
108446
  }
108062
108447
  return this.syncVerifiedChannel({ bootstrapAll: true });
108063
108448
  }
108064
108449
  /** Stamp path recording which daemon version last ran a successful verified sync. */
108065
108450
  channelActivationStampPath() {
108066
- return path46.join(this.defaultProvidersDir, ".channel-activation-stamp.json");
108451
+ return path47.join(this.defaultProvidersDir, ".channel-activation-stamp.json");
108067
108452
  }
108068
108453
  readChannelActivationStamp() {
108069
108454
  try {
108070
- return JSON.parse(fs422.readFileSync(this.channelActivationStampPath(), "utf-8"));
108455
+ return JSON.parse(fs43.readFileSync(this.channelActivationStampPath(), "utf-8"));
108071
108456
  } catch {
108072
108457
  return null;
108073
108458
  }
@@ -108075,8 +108460,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
108075
108460
  writeChannelActivationStamp() {
108076
108461
  if (!this.daemonVersion) return;
108077
108462
  try {
108078
- fs422.mkdirSync(this.defaultProvidersDir, { recursive: true });
108079
- fs422.writeFileSync(this.channelActivationStampPath(), JSON.stringify({
108463
+ fs43.mkdirSync(this.defaultProvidersDir, { recursive: true });
108464
+ fs43.writeFileSync(this.channelActivationStampPath(), JSON.stringify({
108080
108465
  daemonVersion: this.daemonVersion,
108081
108466
  channel: this.channel,
108082
108467
  syncedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -108220,10 +108605,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
108220
108605
  * Check if upstream directory exists and has providers.
108221
108606
  */
108222
108607
  hasUpstream() {
108223
- if (!fs422.existsSync(this.upstreamDir)) return false;
108608
+ if (!fs43.existsSync(this.upstreamDir)) return false;
108224
108609
  try {
108225
- return fs422.readdirSync(this.upstreamDir).some(
108226
- (d) => fs422.statSync(path46.join(this.upstreamDir, d)).isDirectory()
108610
+ return fs43.readdirSync(this.upstreamDir).some(
108611
+ (d) => fs43.statSync(path47.join(this.upstreamDir, d)).isDirectory()
108227
108612
  );
108228
108613
  } catch {
108229
108614
  return false;
@@ -108771,8 +109156,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
108771
109156
  resolved._resolvedScriptDir = entry.scriptDir;
108772
109157
  resolved._resolvedScriptsSource = `compatibility:${entry.ideVersion}`;
108773
109158
  if (providerDir) {
108774
- const fullDir = path46.join(providerDir, entry.scriptDir);
108775
- resolved._resolvedScriptsPath = fs422.existsSync(path46.join(fullDir, "scripts.js")) ? path46.join(fullDir, "scripts.js") : fullDir;
109159
+ const fullDir = path47.join(providerDir, entry.scriptDir);
109160
+ resolved._resolvedScriptsPath = fs43.existsSync(path47.join(fullDir, "scripts.js")) ? path47.join(fullDir, "scripts.js") : fullDir;
108776
109161
  }
108777
109162
  matched = true;
108778
109163
  }
@@ -108790,8 +109175,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
108790
109175
  resolved._resolvedScriptDir = base.defaultScriptDir;
108791
109176
  resolved._resolvedScriptsSource = "defaultScriptDir:version_miss";
108792
109177
  if (providerDir) {
108793
- const fullDir = path46.join(providerDir, base.defaultScriptDir);
108794
- resolved._resolvedScriptsPath = fs422.existsSync(path46.join(fullDir, "scripts.js")) ? path46.join(fullDir, "scripts.js") : fullDir;
109178
+ const fullDir = path47.join(providerDir, base.defaultScriptDir);
109179
+ resolved._resolvedScriptsPath = fs43.existsSync(path47.join(fullDir, "scripts.js")) ? path47.join(fullDir, "scripts.js") : fullDir;
108795
109180
  }
108796
109181
  }
108797
109182
  resolved._versionWarning = `Version ${currentVersion} not in compatibility matrix. Using default scripts.`;
@@ -108808,8 +109193,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
108808
109193
  resolved._resolvedScriptDir = dirOverride;
108809
109194
  resolved._resolvedScriptsSource = `versions:${range}`;
108810
109195
  if (providerDir) {
108811
- const fullDir = path46.join(providerDir, dirOverride);
108812
- resolved._resolvedScriptsPath = fs422.existsSync(path46.join(fullDir, "scripts.js")) ? path46.join(fullDir, "scripts.js") : fullDir;
109196
+ const fullDir = path47.join(providerDir, dirOverride);
109197
+ resolved._resolvedScriptsPath = fs43.existsSync(path47.join(fullDir, "scripts.js")) ? path47.join(fullDir, "scripts.js") : fullDir;
108813
109198
  }
108814
109199
  }
108815
109200
  } else if (override.scripts) {
@@ -108825,8 +109210,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
108825
109210
  resolved._resolvedScriptDir = base.defaultScriptDir;
108826
109211
  resolved._resolvedScriptsSource = "defaultScriptDir:no_version";
108827
109212
  if (providerDir) {
108828
- const fullDir = path46.join(providerDir, base.defaultScriptDir);
108829
- resolved._resolvedScriptsPath = fs422.existsSync(path46.join(fullDir, "scripts.js")) ? path46.join(fullDir, "scripts.js") : fullDir;
109213
+ const fullDir = path47.join(providerDir, base.defaultScriptDir);
109214
+ resolved._resolvedScriptsPath = fs43.existsSync(path47.join(fullDir, "scripts.js")) ? path47.join(fullDir, "scripts.js") : fullDir;
108830
109215
  }
108831
109216
  }
108832
109217
  }
@@ -108843,13 +109228,13 @@ Run 'adhdev doctor' for detailed diagnostics.`
108843
109228
  if (providerDir2) {
108844
109229
  for (const [scriptName, override] of Object.entries(base.overrides)) {
108845
109230
  if (!override || typeof override.path !== "string") continue;
108846
- const fullPath = path46.join(providerDir2, override.path);
108847
- if (!fs422.existsSync(fullPath)) {
109231
+ const fullPath = path47.join(providerDir2, override.path);
109232
+ if (!fs43.existsSync(fullPath)) {
108848
109233
  this.log(` [overrides] ${base.type}: ${scriptName} path not found: ${fullPath}`);
108849
109234
  continue;
108850
109235
  }
108851
109236
  try {
108852
- registerProviderScriptRootSafely(path46.dirname(path46.dirname(providerDir2)));
109237
+ registerProviderScriptRootSafely(path47.dirname(path47.dirname(providerDir2)));
108853
109238
  delete require.cache[require.resolve(fullPath)];
108854
109239
  const fn = require(fullPath);
108855
109240
  const target = typeof fn === "function" ? fn : fn && fn[scriptName];
@@ -108874,25 +109259,25 @@ Run 'adhdev doctor' for detailed diagnostics.`
108874
109259
  }
108875
109260
  if (providerDir) {
108876
109261
  try {
108877
- const fs57 = require("fs");
108878
- const path55 = require("path");
109262
+ const fs58 = require("fs");
109263
+ const path56 = require("path");
108879
109264
  const candidates = [];
108880
109265
  if (Array.isArray(base.compatibility)) {
108881
109266
  for (const entry of base.compatibility) {
108882
109267
  if (typeof entry?.spec !== "string") continue;
108883
109268
  const matches = !entry.ideVersion || currentVersion && this.matchesVersion(currentVersion, entry.ideVersion) || !currentVersion;
108884
- if (matches) candidates.push(path55.join(providerDir, entry.spec));
109269
+ if (matches) candidates.push(path56.join(providerDir, entry.spec));
108885
109270
  }
108886
109271
  }
108887
- candidates.push(path55.join(providerDir, "specs", "default.json"));
108888
- candidates.push(path55.join(providerDir, "spec.json"));
108889
- const specPath = candidates.find((p) => fs57.existsSync(p));
109272
+ candidates.push(path56.join(providerDir, "specs", "default.json"));
109273
+ candidates.push(path56.join(providerDir, "spec.json"));
109274
+ const specPath = candidates.find((p) => fs58.existsSync(p));
108890
109275
  let nh;
108891
109276
  if (specPath) {
108892
109277
  resolved._resolvedSpecPath = specPath;
108893
109278
  let specControls;
108894
109279
  try {
108895
- const rawSpec = JSON.parse(fs57.readFileSync(specPath, "utf8"));
109280
+ const rawSpec = JSON.parse(fs58.readFileSync(specPath, "utf8"));
108896
109281
  specControls = rawSpec.control_bar;
108897
109282
  nh = rawSpec.native_history;
108898
109283
  } catch {
@@ -108934,10 +109319,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
108934
109319
  lister = (input) => executeNativeHistoryList(nh, input);
108935
109320
  }
108936
109321
  } else if (nh.override_path) {
108937
- const overrideFile = path55.resolve(providerDir, nh.override_path);
108938
- if (fs57.existsSync(overrideFile)) {
109322
+ const overrideFile = path56.resolve(providerDir, nh.override_path);
109323
+ if (fs58.existsSync(overrideFile)) {
108939
109324
  try {
108940
- registerProviderScriptRootSafely(path55.dirname(path55.dirname(providerDir)));
109325
+ registerProviderScriptRootSafely(path56.dirname(path56.dirname(providerDir)));
108941
109326
  delete require.cache[require.resolve(overrideFile)];
108942
109327
  const mod = require(overrideFile);
108943
109328
  const fn = typeof mod === "function" ? mod : mod && typeof mod.default === "function" ? mod.default : null;
@@ -108952,6 +109337,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
108952
109337
  const dispatch = createNativeHistoryDispatcher(nh.reader);
108953
109338
  format = nh.reader;
108954
109339
  reader = (input) => dispatch(input);
109340
+ const listDispatch = createNativeHistoryListDispatcher(nh.reader);
109341
+ if (listDispatch) lister = (input) => listDispatch(input);
108955
109342
  }
108956
109343
  if (reader) {
108957
109344
  resolved.scripts = { ...resolved.scripts || {} };
@@ -108985,16 +109372,16 @@ Run 'adhdev doctor' for detailed diagnostics.`
108985
109372
  this.debugLog(`[loadScriptsFromDir] ${type2}: providerDir not found`);
108986
109373
  return null;
108987
109374
  }
108988
- const dir = path46.join(providerDir, scriptDir);
108989
- if (!fs422.existsSync(dir)) {
109375
+ const dir = path47.join(providerDir, scriptDir);
109376
+ if (!fs43.existsSync(dir)) {
108990
109377
  this.debugLog(`[loadScriptsFromDir] ${type2}: dir not found: ${dir}`);
108991
109378
  return null;
108992
109379
  }
108993
- registerProviderScriptRootSafely(path46.dirname(path46.dirname(providerDir)));
109380
+ registerProviderScriptRootSafely(path47.dirname(path47.dirname(providerDir)));
108994
109381
  const cached5 = this.scriptsCache.get(dir);
108995
109382
  if (cached5) return cached5;
108996
- const scriptsJs = path46.join(dir, "scripts.js");
108997
- if (fs422.existsSync(scriptsJs)) {
109383
+ const scriptsJs = path47.join(dir, "scripts.js");
109384
+ if (fs43.existsSync(scriptsJs)) {
108998
109385
  try {
108999
109386
  delete require.cache[require.resolve(scriptsJs)];
109000
109387
  const loaded = require(scriptsJs);
@@ -109015,9 +109402,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
109015
109402
  watch() {
109016
109403
  this.stopWatch();
109017
109404
  const watchDir = (dir) => {
109018
- if (!fs422.existsSync(dir)) {
109405
+ if (!fs43.existsSync(dir)) {
109019
109406
  try {
109020
- fs422.mkdirSync(dir, { recursive: true });
109407
+ fs43.mkdirSync(dir, { recursive: true });
109021
109408
  } catch {
109022
109409
  return;
109023
109410
  }
@@ -109038,7 +109425,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
109038
109425
  if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
109039
109426
  if (reloadTimer) clearTimeout(reloadTimer);
109040
109427
  reloadTimer = setTimeout(() => {
109041
- this.log(`File changed: ${path46.basename(filePath)}, reloading...`);
109428
+ this.log(`File changed: ${path47.basename(filePath)}, reloading...`);
109042
109429
  this.reload();
109043
109430
  }, 300);
109044
109431
  }
@@ -109080,15 +109467,15 @@ Run 'adhdev doctor' for detailed diagnostics.`
109080
109467
  }
109081
109468
  /** Count provider files (provider.v1.json or provider.json — at most one per dir). */
109082
109469
  countProviders(dir) {
109083
- if (!fs422.existsSync(dir)) return 0;
109470
+ if (!fs43.existsSync(dir)) return 0;
109084
109471
  let count = 0;
109085
109472
  const scan = (d) => {
109086
109473
  try {
109087
- const entries = fs422.readdirSync(d, { withFileTypes: true });
109474
+ const entries = fs43.readdirSync(d, { withFileTypes: true });
109088
109475
  const hasManifest = entries.some((e) => e.name === "provider.v1.json" || e.name === "provider.json");
109089
109476
  if (hasManifest) count++;
109090
109477
  for (const entry of entries) {
109091
- if (entry.isDirectory()) scan(path46.join(d, entry.name));
109478
+ if (entry.isDirectory()) scan(path47.join(d, entry.name));
109092
109479
  }
109093
109480
  } catch {
109094
109481
  }
@@ -109314,13 +109701,13 @@ Run 'adhdev doctor' for detailed diagnostics.`
109314
109701
  if (!provider) return null;
109315
109702
  const cat = provider.category;
109316
109703
  const searchRoots = this.getProviderRoots();
109317
- const hasManifest = (dir) => fs422.existsSync(path46.join(dir, "provider.v1.json")) || fs422.existsSync(path46.join(dir, "provider.json"));
109704
+ const hasManifest = (dir) => fs43.existsSync(path47.join(dir, "provider.v1.json")) || fs43.existsSync(path47.join(dir, "provider.json"));
109318
109705
  const readManifestType = (dir) => {
109319
109706
  for (const file2 of ["provider.v1.json", "provider.json"]) {
109320
- const p = path46.join(dir, file2);
109321
- if (!fs422.existsSync(p)) continue;
109707
+ const p = path47.join(dir, file2);
109708
+ if (!fs43.existsSync(p)) continue;
109322
109709
  try {
109323
- const data = JSON.parse(fs422.readFileSync(p, "utf-8"));
109710
+ const data = JSON.parse(fs43.readFileSync(p, "utf-8"));
109324
109711
  if (typeof data?.type === "string") return data.type;
109325
109712
  } catch {
109326
109713
  }
@@ -109328,15 +109715,15 @@ Run 'adhdev doctor' for detailed diagnostics.`
109328
109715
  return null;
109329
109716
  };
109330
109717
  for (const root of searchRoots) {
109331
- if (!fs422.existsSync(root)) continue;
109718
+ if (!fs43.existsSync(root)) continue;
109332
109719
  const candidate = this.getProviderDir(root, cat, type2);
109333
109720
  if (hasManifest(candidate)) return candidate;
109334
- const catDir = path46.join(root, cat);
109335
- if (fs422.existsSync(catDir)) {
109721
+ const catDir = path47.join(root, cat);
109722
+ if (fs43.existsSync(catDir)) {
109336
109723
  try {
109337
- for (const entry of fs422.readdirSync(catDir, { withFileTypes: true })) {
109724
+ for (const entry of fs43.readdirSync(catDir, { withFileTypes: true })) {
109338
109725
  if (!entry.isDirectory()) continue;
109339
- const entryDir = path46.join(catDir, entry.name);
109726
+ const entryDir = path47.join(catDir, entry.name);
109340
109727
  const manifestType = readManifestType(entryDir);
109341
109728
  if (manifestType === type2) return entryDir;
109342
109729
  }
@@ -109352,8 +109739,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
109352
109739
  * (template substitution is NOT applied here — scripts.js handles that)
109353
109740
  */
109354
109741
  buildScriptWrappersFromDir(dir) {
109355
- const scriptsJs = path46.join(dir, "scripts.js");
109356
- if (fs422.existsSync(scriptsJs)) {
109742
+ const scriptsJs = path47.join(dir, "scripts.js");
109743
+ if (fs43.existsSync(scriptsJs)) {
109357
109744
  try {
109358
109745
  delete require.cache[require.resolve(scriptsJs)];
109359
109746
  return require(scriptsJs);
@@ -109363,13 +109750,13 @@ Run 'adhdev doctor' for detailed diagnostics.`
109363
109750
  const toCamel = (name) => name.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
109364
109751
  const result = {};
109365
109752
  try {
109366
- for (const file2 of fs422.readdirSync(dir)) {
109753
+ for (const file2 of fs43.readdirSync(dir)) {
109367
109754
  if (!file2.endsWith(".js")) continue;
109368
109755
  const scriptName = toCamel(file2.replace(".js", ""));
109369
- const filePath = path46.join(dir, file2);
109756
+ const filePath = path47.join(dir, file2);
109370
109757
  result[scriptName] = (...args) => {
109371
109758
  try {
109372
- let content = fs422.readFileSync(filePath, "utf-8");
109759
+ let content = fs43.readFileSync(filePath, "utf-8");
109373
109760
  if (args[0] && typeof args[0] === "object") {
109374
109761
  for (const [key2, val] of Object.entries(args[0])) {
109375
109762
  let v = val;
@@ -109415,12 +109802,12 @@ Run 'adhdev doctor' for detailed diagnostics.`
109415
109802
  * Structure: dir/category/agent-name/provider.{json,js}
109416
109803
  */
109417
109804
  loadDir(dir, excludeDirs) {
109418
- if (!fs422.existsSync(dir)) return 0;
109805
+ if (!fs43.existsSync(dir)) return 0;
109419
109806
  let count = 0;
109420
109807
  const scan = (d) => {
109421
109808
  let entries;
109422
109809
  try {
109423
- entries = fs422.readdirSync(d, { withFileTypes: true });
109810
+ entries = fs43.readdirSync(d, { withFileTypes: true });
109424
109811
  } catch {
109425
109812
  return;
109426
109813
  }
@@ -109428,9 +109815,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
109428
109815
  const hasJson = entries.some((e) => e.name === "provider.json");
109429
109816
  if (hasV1 || hasJson) {
109430
109817
  const manifestFile = hasV1 ? "provider.v1.json" : "provider.json";
109431
- const jsonPath = path46.join(d, manifestFile);
109818
+ const jsonPath = path47.join(d, manifestFile);
109432
109819
  try {
109433
- const raw = fs422.readFileSync(jsonPath, "utf-8");
109820
+ const raw = fs43.readFileSync(jsonPath, "utf-8");
109434
109821
  const mod = JSON.parse(raw);
109435
109822
  if (hasV1 && mod?.category === "cli") {
109436
109823
  try {
@@ -109468,10 +109855,10 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109468
109855
  this.log(`\u26A0 Invalid provider at ${jsonPath}: ${validation.errors.join("; ")}`);
109469
109856
  } else {
109470
109857
  const hasCompatibility = Array.isArray(normalizedProvider.compatibility);
109471
- const scriptsPath = path46.join(d, "scripts.js");
109472
- if (!hasCompatibility && fs422.existsSync(scriptsPath)) {
109858
+ const scriptsPath = path47.join(d, "scripts.js");
109859
+ if (!hasCompatibility && fs43.existsSync(scriptsPath)) {
109473
109860
  try {
109474
- registerProviderScriptRootSafely(path46.dirname(path46.dirname(d)));
109861
+ registerProviderScriptRootSafely(path47.dirname(path47.dirname(d)));
109475
109862
  delete require.cache[require.resolve(scriptsPath)];
109476
109863
  const scripts = require(scriptsPath);
109477
109864
  normalizedProvider.scripts = scripts;
@@ -109479,8 +109866,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109479
109866
  this.log(`\u26A0 Failed to load scripts: ${scriptsPath}: ${e.message}`);
109480
109867
  }
109481
109868
  }
109482
- const externalDirAbs = path46.join(getConfigDir2(), "external");
109483
- const isChannelStoreObject = d.includes(`${path46.sep}.store${path46.sep}`);
109869
+ const externalDirAbs = path47.join(getConfigDir2(), "external");
109870
+ const isChannelStoreObject = d.includes(`${path47.sep}.store${path47.sep}`);
109484
109871
  const layer = d.startsWith(externalDirAbs) ? "external" : d.startsWith(this.userDir) && !d.includes(".upstream") && !isChannelStoreObject ? "user" : "upstream";
109485
109872
  try {
109486
109873
  const { inspectManifestShape: inspectManifestShape2, classifyTrust: classifyTrust2 } = (init_provider_trust(), __toCommonJS2(provider_trust_exports));
@@ -109490,8 +109877,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109490
109877
  normalizedProvider._sourceTrust = trust;
109491
109878
  normalizedProvider._manifestShape = shape;
109492
109879
  if (layer === "external") {
109493
- const rel = path46.relative(externalDirAbs, d);
109494
- const firstSeg = rel.split(path46.sep)[0];
109880
+ const rel = path47.relative(externalDirAbs, d);
109881
+ const firstSeg = rel.split(path47.sep)[0];
109495
109882
  if (firstSeg && firstSeg !== "..") normalizedProvider._sourceName = firstSeg;
109496
109883
  }
109497
109884
  } catch {
@@ -109516,7 +109903,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109516
109903
  if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
109517
109904
  if (d === dir && entry.name === "examples") continue;
109518
109905
  if (excludeDirs && d === dir && excludeDirs.includes(entry.name)) continue;
109519
- scan(path46.join(d, entry.name));
109906
+ scan(path47.join(d, entry.name));
109520
109907
  }
109521
109908
  }
109522
109909
  };
@@ -109719,7 +110106,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109719
110106
  });
109720
110107
  }
109721
110108
  async function killIdeProcess(ideId) {
109722
- const plat = os26.platform();
110109
+ const plat = os27.platform();
109723
110110
  const appName = getMacAppIdentifiers()[ideId];
109724
110111
  const winProcesses = getWinProcessNames()[ideId];
109725
110112
  try {
@@ -109780,7 +110167,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109780
110167
  }
109781
110168
  }
109782
110169
  async function isIdeRunning(ideId) {
109783
- const plat = os26.platform();
110170
+ const plat = os27.platform();
109784
110171
  try {
109785
110172
  if (plat === "darwin") {
109786
110173
  const appName = getMacAppIdentifiers()[ideId];
@@ -109835,7 +110222,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109835
110222
  }
109836
110223
  }
109837
110224
  async function detectCurrentWorkspace(ideId) {
109838
- const plat = os26.platform();
110225
+ const plat = os27.platform();
109839
110226
  if (plat === "darwin") {
109840
110227
  try {
109841
110228
  const appName = getMacAppIdentifiers()[ideId];
@@ -109850,17 +110237,17 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109850
110237
  }
109851
110238
  } else if (plat === "win32") {
109852
110239
  try {
109853
- const fs57 = require("fs");
110240
+ const fs58 = require("fs");
109854
110241
  const appNameMap = getMacAppIdentifiers();
109855
110242
  const appName = appNameMap[ideId];
109856
110243
  if (appName) {
109857
- const storagePath = path47.join(
109858
- process.env.APPDATA || path47.join(os26.homedir(), "AppData", "Roaming"),
110244
+ const storagePath = path48.join(
110245
+ process.env.APPDATA || path48.join(os27.homedir(), "AppData", "Roaming"),
109859
110246
  appName,
109860
110247
  "storage.json"
109861
110248
  );
109862
- if (fs57.existsSync(storagePath)) {
109863
- const data = JSON.parse(fs57.readFileSync(storagePath, "utf-8"));
110249
+ if (fs58.existsSync(storagePath)) {
110250
+ const data = JSON.parse(fs58.readFileSync(storagePath, "utf-8"));
109864
110251
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
109865
110252
  if (workspaces.length > 0) {
109866
110253
  const recent = workspaces[0];
@@ -109877,7 +110264,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
109877
110264
  return void 0;
109878
110265
  }
109879
110266
  async function launchWithCdp(options = {}) {
109880
- const platform10 = os26.platform();
110267
+ const platform10 = os27.platform();
109881
110268
  let targetIde;
109882
110269
  const ides = await detectIDEs(getProviderLoader());
109883
110270
  if (options.ideId) {
@@ -110440,11 +110827,11 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
110440
110827
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
110441
110828
  } = await Promise.resolve().then(() => (init_mesh_json_config(), mesh_json_config_exports));
110442
110829
  const { mkdirSync: mkdirSync31, writeFileSync: writeFileSync31 } = await import("fs");
110443
- const { dirname: dirname23, join: join64 } = await import("path");
110830
+ const { dirname: dirname24, join: join65 } = await import("path");
110444
110831
  const scaffold = buildMeshJsonConfigScaffold2(mesh);
110445
110832
  const scaffoldJson = serializeMeshJsonConfigScaffold2(scaffold);
110446
110833
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
110447
- const absolutePath = join64(workspace, relativePath);
110834
+ const absolutePath = join65(workspace, relativePath);
110448
110835
  const validation = normalizeRepoMeshDeclarativeConfig2(scaffold);
110449
110836
  if (!validation.valid) {
110450
110837
  return { success: false, meshId, error: `invalid mesh.json scaffold: ${validation.errors.join("; ")}` };
@@ -110480,7 +110867,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
110480
110867
  note: "Dry-run: nothing written. Re-run with write=true to persist to the repo (commit target). meshes.json is untouched."
110481
110868
  };
110482
110869
  }
110483
- mkdirSync31(dirname23(absolutePath), { recursive: true });
110870
+ mkdirSync31(dirname24(absolutePath), { recursive: true });
110484
110871
  writeFileSync31(absolutePath, `${scaffoldJson}
110485
110872
  `, "utf-8");
110486
110873
  return {
@@ -110550,18 +110937,18 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
110550
110937
  normalizeRepoMeshDeclarativeConfig: normalizeRepoMeshDeclarativeConfig2,
110551
110938
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
110552
110939
  } = await Promise.resolve().then(() => (init_mesh_json_config(), mesh_json_config_exports));
110553
- const { existsSync: existsSync63, readFileSync: readFileSync53, mkdirSync: mkdirSync31, writeFileSync: writeFileSync31 } = await import("fs");
110554
- const { dirname: dirname23, join: join64 } = await import("path");
110940
+ const { existsSync: existsSync65, readFileSync: readFileSync54, mkdirSync: mkdirSync31, writeFileSync: writeFileSync31 } = await import("fs");
110941
+ const { dirname: dirname24, join: join65 } = await import("path");
110555
110942
  const yaml6 = await Promise.resolve().then(() => (init_js_yaml(), js_yaml_exports));
110556
110943
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
110557
110944
  let baseDoc = { version: 1 };
110558
- let existingPath = join64(workspace, relativePath);
110945
+ let existingPath = join65(workspace, relativePath);
110559
110946
  let existedAsYaml = false;
110560
110947
  for (const relative8 of MESH_JSON_CONFIG_LOCATIONS2) {
110561
- const candidate = join64(workspace, relative8);
110562
- if (!existsSync63(candidate)) continue;
110948
+ const candidate = join65(workspace, relative8);
110949
+ if (!existsSync65(candidate)) continue;
110563
110950
  try {
110564
- const text = readFileSync53(candidate, "utf-8");
110951
+ const text = readFileSync54(candidate, "utf-8");
110565
110952
  const parsed = /\.json$/i.test(candidate) ? JSON.parse(text) : yaml6.load(text);
110566
110953
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
110567
110954
  baseDoc = parsed;
@@ -110615,7 +111002,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
110615
111002
  note: "Dry-run: nothing written. Re-run with write=true to persist. Only the providerDefaults zone is merged; other repo zones are preserved."
110616
111003
  };
110617
111004
  }
110618
- mkdirSync31(dirname23(absolutePath), { recursive: true });
111005
+ mkdirSync31(dirname24(absolutePath), { recursive: true });
110619
111006
  writeFileSync31(absolutePath, serialized, "utf-8");
110620
111007
  return {
110621
111008
  success: true,
@@ -111977,6 +112364,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
111977
112364
  };
111978
112365
  init_dist();
111979
112366
  init_logger();
112367
+ init_track_identity();
111980
112368
  init_mesh_turn_presentation();
111981
112369
  init_state_store();
111982
112370
  var RESTART_BLOCKING_STATES = /* @__PURE__ */ new Set(["generating", "waiting_approval", "waiting_choice", "finalizing", "starting"]);
@@ -112040,6 +112428,16 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
112040
112428
  function normalizeRestartMode(value) {
112041
112429
  return value === "restart" ? "restart" : "upgrade";
112042
112430
  }
112431
+ function withRestartTargetDaemon(result, selfDaemonId) {
112432
+ return {
112433
+ ...result,
112434
+ restartTargetDaemon: {
112435
+ daemonId: selfDaemonId || "unknown",
112436
+ track: TRACK,
112437
+ npmTag: IDENTITY.npmTag
112438
+ }
112439
+ };
112440
+ }
112043
112441
  function restartWarnings(args) {
112044
112442
  const warnings = [];
112045
112443
  if (args.forced) {
@@ -112181,6 +112579,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
112181
112579
  nodeDaemonId = typeof node?.daemonId === "string" ? node.daemonId.trim() : void 0;
112182
112580
  }
112183
112581
  const selfDaemonId = ctx.deps.statusInstanceId;
112582
+ const finishHere = (result) => withRestartTargetDaemon(result, selfDaemonId);
112184
112583
  const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
112185
112584
  if (isRemote && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
112186
112585
  const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "restart_daemon_node", {
@@ -112193,26 +112592,26 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
112193
112592
  if (args?.cancelWhenIdle === true) {
112194
112593
  const had = pendingDeferredRestarts.has(scheduleKey);
112195
112594
  clearPendingDeferredRestart(scheduleKey);
112196
- return { success: true, restarted: false, cancelled: had, deferredRestart: null };
112595
+ return finishHere({ success: true, restarted: false, cancelled: had, deferredRestart: null });
112197
112596
  }
112198
112597
  if (args?.whenIdleStatus === true) {
112199
- return { success: true, restarted: false, deferredRestart: deferredRestartInfo(scheduleKey) };
112598
+ return finishHere({ success: true, restarted: false, deferredRestart: deferredRestartInfo(scheduleKey) });
112200
112599
  }
112201
112600
  const blocking = collectBlockingSessions(ctx.deps, meshId);
112202
112601
  if (blocking.length > 0) {
112203
112602
  if (args?.force === true) {
112204
112603
  LOG2.warn("MeshRestart", `force restart over ${blocking.length} blocking session(s): ${blocking.map((b) => `${b.instanceId || "?"}(${b.status})`).join(", ")} \u2014 pendingOutboundQueue will be lost`);
112205
- return executeRestart(ctx.deps, args, { forced: true });
112604
+ return finishHere(await executeRestart(ctx.deps, args, { forced: true }));
112206
112605
  }
112207
112606
  const foreignBlocking = blocking.filter((b) => !b.selfCoordinator || b.pendingOutbound);
112208
112607
  if (args?.selfOnly === true && foreignBlocking.length === 0) {
112209
112608
  LOG2.info("MeshRestart", `selfOnly restart: waiving ${blocking.length} self-coordinator session(s) for mesh ${meshId}`);
112210
- return executeRestart(ctx.deps, args, { forced: false });
112609
+ return finishHere(await executeRestart(ctx.deps, args, { forced: false }));
112211
112610
  }
112212
112611
  if (args?.whenIdle === true) {
112213
- return scheduleDeferredRestart(ctx.deps, args, meshId, nodeId);
112612
+ return finishHere(scheduleDeferredRestart(ctx.deps, args, meshId, nodeId));
112214
112613
  }
112215
- return {
112614
+ return finishHere({
112216
112615
  success: false,
112217
112616
  restarted: false,
112218
112617
  code: "blocking_sessions",
@@ -112224,9 +112623,9 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
112224
112623
  whenIdle: "schedule the restart to run automatically once the daemon goes idle (safest)"
112225
112624
  },
112226
112625
  deferredRestart: deferredRestartInfo(scheduleKey)
112227
- };
112626
+ });
112228
112627
  }
112229
- return executeRestart(ctx.deps, args, { forced: false });
112628
+ return finishHere(await executeRestart(ctx.deps, args, { forced: false }));
112230
112629
  }
112231
112630
  };
112232
112631
  init_cli_detector();
@@ -112379,7 +112778,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
112379
112778
  }
112380
112779
  };
112381
112780
  var import_path16 = require("path");
112382
- var fs43 = __toESM2(require("fs"));
112781
+ var fs44 = __toESM2(require("fs"));
112383
112782
  init_logger();
112384
112783
  init_mesh_host_ownership();
112385
112784
  init_coordinator_registry();
@@ -112660,15 +113059,15 @@ ${ptyResult.output.slice(-2e3)}`);
112660
113059
  }
112661
113060
  if (cliType === "codex-cli") {
112662
113061
  const repoMcpConfigPath = (0, import_path16.join)(workspace, ".mcp.json");
112663
- if (fs43.existsSync(repoMcpConfigPath)) {
113062
+ if (fs44.existsSync(repoMcpConfigPath)) {
112664
113063
  try {
112665
113064
  const repoMcpConfig = parseMeshCoordinatorMcpConfig(
112666
- fs43.readFileSync(repoMcpConfigPath, "utf-8"),
113065
+ fs44.readFileSync(repoMcpConfigPath, "utf-8"),
112667
113066
  "claude_mcp_json"
112668
113067
  );
112669
113068
  const existingServers2 = repoMcpConfig.mcpServers;
112670
113069
  if (existingServers2 && typeof existingServers2 === "object" && !Array.isArray(existingServers2) && existingServers2[coordinatorSetup.serverName]) {
112671
- fs43.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
113070
+ fs44.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
112672
113071
  ...repoMcpConfig,
112673
113072
  mcpServers: {
112674
113073
  ...existingServers2,
@@ -112831,8 +113230,8 @@ ${ptyResult.output.slice(-2e3)}`);
112831
113230
  workspace
112832
113231
  };
112833
113232
  }
112834
- const { existsSync: existsSync63, readFileSync: readFileSync53, writeFileSync: writeFileSync31, copyFileSync: copyFileSync3, mkdirSync: mkdirSync31 } = await import("fs");
112835
- const { dirname: dirname23 } = await import("path");
113233
+ const { existsSync: existsSync65, readFileSync: readFileSync54, writeFileSync: writeFileSync31, copyFileSync: copyFileSync3, mkdirSync: mkdirSync31 } = await import("fs");
113234
+ const { dirname: dirname24 } = await import("path");
112836
113235
  const mcpConfigPath = coordinatorSetup.configPath;
112837
113236
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
112838
113237
  let hermesBaseConfig = null;
@@ -112869,21 +113268,21 @@ ${ptyResult.output.slice(-2e3)}`);
112869
113268
  ...mcpServerEnv ? { env: mcpServerEnv } : {}
112870
113269
  });
112871
113270
  try {
112872
- mkdirSync31(dirname23(mcpConfigPath), { recursive: true });
113271
+ mkdirSync31(dirname24(mcpConfigPath), { recursive: true });
112873
113272
  } catch (error48) {
112874
113273
  const message = `Could not prepare MCP config path for automatic setup: ${error48?.message || error48}`;
112875
113274
  LOG2.error("MeshCoordinator", message);
112876
113275
  if (hermesManualFallback) return returnManualFallback(message);
112877
113276
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
112878
113277
  }
112879
- const hadExistingMcpConfig = existsSync63(mcpConfigPath);
113278
+ const hadExistingMcpConfig = existsSync65(mcpConfigPath);
112880
113279
  let existingMcpConfig = hermesBaseConfig?.config || {};
112881
113280
  if (hermesBaseConfig) {
112882
- copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname23(mcpConfigPath));
113281
+ copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname24(mcpConfigPath));
112883
113282
  }
112884
113283
  if (hadExistingMcpConfig) {
112885
113284
  try {
112886
- const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync53(mcpConfigPath, "utf-8"), configFormat);
113285
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync54(mcpConfigPath, "utf-8"), configFormat);
112887
113286
  const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
112888
113287
  existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
112889
113288
  copyFileSync3(mcpConfigPath, mcpConfigPath + ".backup");
@@ -112917,7 +113316,7 @@ ${ptyResult.output.slice(-2e3)}`);
112917
113316
  const cliArgs = [];
112918
113317
  const launchEnv = {};
112919
113318
  if (configFormat === "hermes_config_yaml") {
112920
- launchEnv.HERMES_HOME = dirname23(mcpConfigPath);
113319
+ launchEnv.HERMES_HOME = dirname24(mcpConfigPath);
112921
113320
  launchEnv.HERMES_IGNORE_USER_CONFIG = "";
112922
113321
  }
112923
113322
  let autoImportContextFilePath;
@@ -113037,7 +113436,7 @@ ${ptyResult.output.slice(-2e3)}`);
113037
113436
  }
113038
113437
  }
113039
113438
  };
113040
- var fs44 = __toESM2(require("fs"));
113439
+ var fs45 = __toESM2(require("fs"));
113041
113440
  var import_os4 = require("os");
113042
113441
  init_config();
113043
113442
  init_git_status();
@@ -113085,10 +113484,10 @@ ${ptyResult.output.slice(-2e3)}`);
113085
113484
  }
113086
113485
  }
113087
113486
  function readRecord7(repoRoot) {
113088
- const path55 = (0, import_node_path4.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
113089
- if (!(0, import_node_fs4.existsSync)(path55)) return null;
113487
+ const path56 = (0, import_node_path4.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
113488
+ if (!(0, import_node_fs4.existsSync)(path56)) return null;
113090
113489
  try {
113091
- const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path55, "utf8"));
113490
+ const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path56, "utf8"));
113092
113491
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
113093
113492
  } catch {
113094
113493
  return null;
@@ -113406,7 +113805,7 @@ ${ptyResult.output.slice(-2e3)}`);
113406
113805
  }
113407
113806
  }
113408
113807
  if (workspace) {
113409
- if (!fs44.existsSync(workspace)) {
113808
+ if (!fs45.existsSync(workspace)) {
113410
113809
  const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
113411
113810
  let remoteProbeApplied = false;
113412
113811
  if (inlineTransitGit) {
@@ -113545,7 +113944,7 @@ ${ptyResult.output.slice(-2e3)}`);
113545
113944
  const pendingRetentionCounters2 = { ...getPendingRetentionCounters() };
113546
113945
  const turnPresentationCounters = getTurnPresentationMetrics();
113547
113946
  const previewFreshness = (() => {
113548
- const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs44.existsSync(candidate));
113947
+ const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs45.existsSync(candidate));
113549
113948
  return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
113550
113949
  })();
113551
113950
  const asyncRefineJobs = buildMeshAsyncRefineJobs({
@@ -113677,7 +114076,7 @@ ${ptyResult.output.slice(-2e3)}`);
113677
114076
  const { deriveMeshReviewInboxItems: deriveMeshReviewInboxItems2 } = await Promise.resolve().then(() => (init_mesh_review_inbox(), mesh_review_inbox_exports));
113678
114077
  const { readLedgerEntries: readLedgerEntries2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
113679
114078
  const { getGitDiffSummary: getGitDiffSummary2 } = await Promise.resolve().then(() => (init_git_diff(), git_diff_exports));
113680
- const { existsSync: existsSync63 } = await import("fs");
114079
+ const { existsSync: existsSync65 } = await import("fs");
113681
114080
  const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
113682
114081
  const mesh = meshRecord?.mesh;
113683
114082
  if (!mesh) return { success: false, error: "Mesh not found" };
@@ -113696,7 +114095,7 @@ ${ptyResult.output.slice(-2e3)}`);
113696
114095
  const derivation = deriveMeshReviewInboxItems2({ nodes: nodeStatuses, ledgerEntries });
113697
114096
  for (const item of derivation.items) {
113698
114097
  const workspace = item.workspace;
113699
- if (!workspace || !existsSync63(workspace)) continue;
114098
+ if (!workspace || !existsSync65(workspace)) continue;
113700
114099
  const baseRef = item.defaultBranch ? `origin/${item.defaultBranch}` : "origin/main";
113701
114100
  try {
113702
114101
  const diffResult = await getGitDiffSummary2(workspace, { baseRef, maxFiles: 100 });
@@ -113743,8 +114142,8 @@ ${ptyResult.output.slice(-2e3)}`);
113743
114142
  );
113744
114143
  init_dist();
113745
114144
  init_logger();
113746
- var fs45 = __toESM2(require("fs"));
113747
- var path48 = __toESM2(require("path"));
114145
+ var fs46 = __toESM2(require("fs"));
114146
+ var path49 = __toESM2(require("path"));
113748
114147
  init_config_dir();
113749
114148
  var MAX_FILE_SIZE = 5 * 1024 * 1024;
113750
114149
  var MAX_DAYS = 7;
@@ -113789,10 +114188,10 @@ ${ptyResult.output.slice(-2e3)}`);
113789
114188
  const dirChanged = dir !== currentDir;
113790
114189
  currentDate2 = today;
113791
114190
  currentDir = dir;
113792
- currentFile = path48.join(dir, `commands-${today}.jsonl`);
114191
+ currentFile = path49.join(dir, `commands-${today}.jsonl`);
113793
114192
  if (dirChanged) {
113794
114193
  try {
113795
- fs45.mkdirSync(dir, { recursive: true });
114194
+ fs46.mkdirSync(dir, { recursive: true });
113796
114195
  } catch {
113797
114196
  }
113798
114197
  cleanOldFiles();
@@ -113800,7 +114199,7 @@ ${ptyResult.output.slice(-2e3)}`);
113800
114199
  }
113801
114200
  function cleanOldFiles() {
113802
114201
  try {
113803
- const files = fs45.readdirSync(currentDir).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
114202
+ const files = fs46.readdirSync(currentDir).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
113804
114203
  const cutoff = /* @__PURE__ */ new Date();
113805
114204
  cutoff.setDate(cutoff.getDate() - MAX_DAYS);
113806
114205
  const cutoffStr = cutoff.toISOString().slice(0, 10);
@@ -113808,7 +114207,7 @@ ${ptyResult.output.slice(-2e3)}`);
113808
114207
  const dateMatch = file2.match(/commands-(\d{4}-\d{2}-\d{2})/);
113809
114208
  if (dateMatch && dateMatch[1] < cutoffStr) {
113810
114209
  try {
113811
- fs45.unlinkSync(path48.join(currentDir, file2));
114210
+ fs46.unlinkSync(path49.join(currentDir, file2));
113812
114211
  } catch {
113813
114212
  }
113814
114213
  }
@@ -113818,14 +114217,14 @@ ${ptyResult.output.slice(-2e3)}`);
113818
114217
  }
113819
114218
  function checkSize() {
113820
114219
  try {
113821
- const stat2 = fs45.statSync(currentFile);
114220
+ const stat2 = fs46.statSync(currentFile);
113822
114221
  if (stat2.size > MAX_FILE_SIZE) {
113823
114222
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
113824
114223
  try {
113825
- fs45.unlinkSync(backup);
114224
+ fs46.unlinkSync(backup);
113826
114225
  } catch {
113827
114226
  }
113828
- fs45.renameSync(currentFile, backup);
114227
+ fs46.renameSync(currentFile, backup);
113829
114228
  }
113830
114229
  } catch {
113831
114230
  }
@@ -113858,15 +114257,15 @@ ${ptyResult.output.slice(-2e3)}`);
113858
114257
  ...entry.error ? { err: entry.error } : {},
113859
114258
  ...entry.durationMs !== void 0 ? { ms: entry.durationMs } : {}
113860
114259
  });
113861
- fs45.appendFileSync(currentFile, line + "\n");
114260
+ fs46.appendFileSync(currentFile, line + "\n");
113862
114261
  } catch {
113863
114262
  }
113864
114263
  }
113865
114264
  function getRecentCommands(count = 50) {
113866
114265
  try {
113867
114266
  refreshCurrentFile();
113868
- if (!fs45.existsSync(currentFile)) return [];
113869
- const content = fs45.readFileSync(currentFile, "utf-8");
114267
+ if (!fs46.existsSync(currentFile)) return [];
114268
+ const content = fs46.readFileSync(currentFile, "utf-8");
113870
114269
  const lines = content.trim().split("\n").filter(Boolean);
113871
114270
  return lines.slice(-count).map((line) => {
113872
114271
  try {
@@ -113891,9 +114290,10 @@ ${ptyResult.output.slice(-2e3)}`);
113891
114290
  }
113892
114291
  init_debug_trace();
113893
114292
  init_mesh_host_ownership();
113894
- var fs49 = __toESM2(require("fs"));
114293
+ var fs50 = __toESM2(require("fs"));
113895
114294
  init_mesh_node_identity();
113896
114295
  var import_node_child_process10 = require("child_process");
114296
+ var import_node_fs6 = require("fs");
113897
114297
  init_logger();
113898
114298
  init_debug_trace();
113899
114299
  init_dist();
@@ -113907,9 +114307,9 @@ ${ptyResult.output.slice(-2e3)}`);
113907
114307
  var execFileAsync4 = (0, import_node_util5.promisify)(import_node_child_process7.execFile);
113908
114308
  var GIT = process.platform === "win32" ? resolveWin32Executable("git") : "git";
113909
114309
  var MAX_CHANGED_FILES2 = 500;
113910
- function topLevel(path55) {
113911
- const slash = path55.indexOf("/");
113912
- return slash === -1 ? path55 : path55.slice(0, slash);
114310
+ function topLevel(path56) {
114311
+ const slash = path56.indexOf("/");
114312
+ return slash === -1 ? path56 : path56.slice(0, slash);
113913
114313
  }
113914
114314
  async function analyzeMeshRefineNodeChangeArea(args) {
113915
114315
  const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
@@ -114012,27 +114412,27 @@ ${ptyResult.output.slice(-2e3)}`);
114012
114412
  return false;
114013
114413
  }
114014
114414
  }
114015
- async function assessScope(cwd, path55, baseRef, branchRef) {
114415
+ async function assessScope(cwd, path56, baseRef, branchRef) {
114016
114416
  try {
114017
- if (!(0, import_node_fs5.existsSync)(cwd)) return { path: path55, verdict: "unknown", error: `path does not exist: ${cwd}` };
114417
+ if (!(0, import_node_fs5.existsSync)(cwd)) return { path: path56, verdict: "unknown", error: `path does not exist: ${cwd}` };
114018
114418
  const liveBaseHead = await git2(cwd, ["rev-parse", baseRef]);
114019
114419
  const branchHead = await git2(cwd, ["rev-parse", branchRef]);
114020
114420
  if (!liveBaseHead || !branchHead) {
114021
- return { path: path55, verdict: "unknown", error: "could not resolve base or branch head" };
114421
+ return { path: path56, verdict: "unknown", error: "could not resolve base or branch head" };
114022
114422
  }
114023
114423
  if (await isAncestor(cwd, liveBaseHead, branchHead)) {
114024
- return { path: path55, verdict: "clear", liveBaseHead };
114424
+ return { path: path56, verdict: "clear", liveBaseHead };
114025
114425
  }
114026
114426
  let mergeBase;
114027
114427
  try {
114028
114428
  mergeBase = await git2(cwd, ["merge-base", liveBaseHead, branchHead]);
114029
114429
  } catch {
114030
- return { path: path55, verdict: "unknown", liveBaseHead, error: "no common merge base" };
114430
+ return { path: path56, verdict: "unknown", liveBaseHead, error: "no common merge base" };
114031
114431
  }
114032
- if (!mergeBase) return { path: path55, verdict: "unknown", liveBaseHead, error: "empty merge base" };
114033
- return { path: path55, verdict: "diverged", liveBaseHead, mergeBase };
114432
+ if (!mergeBase) return { path: path56, verdict: "unknown", liveBaseHead, error: "empty merge base" };
114433
+ return { path: path56, verdict: "diverged", liveBaseHead, mergeBase };
114034
114434
  } catch (e) {
114035
- return { path: path55, verdict: "unknown", error: e?.message || String(e) };
114435
+ return { path: path56, verdict: "unknown", error: e?.message || String(e) };
114036
114436
  }
114037
114437
  }
114038
114438
  async function resolveSubmodulePaths(repoRoot) {
@@ -114104,6 +114504,58 @@ ${ptyResult.output.slice(-2e3)}`);
114104
114504
  const verdict = scopes.some((s2) => s2.verdict === "diverged") ? "diverged" : scopes.some((s2) => s2.verdict === "unknown") ? "unknown" : "clear";
114105
114505
  return { verdict, scopes, touchedSubmodulePaths, durationMs: Date.now() - started };
114106
114506
  }
114507
+ function classifyRefineTerminal(result) {
114508
+ const refineCode = typeof result.code === "string" ? result.code : "";
114509
+ const landing = extractRefineMergeLanding(result);
114510
+ const isPostMergeWarning = result.success !== true && landing.merged && landing.pushed;
114511
+ const kind = result.success === true ? "completed" : isPostMergeWarning ? "completed_with_warnings" : refineCode === "blocked_review" || refineCode === "worktree_missing" ? "blocked_review" : refineCode === "validation_failed" || refineCode === "validation_dependencies_missing" || refineCode === "missing_dependencies" || refineCode === "dependency_bootstrap_failed" || refineCode === "spawn_resolution_failed" || refineCode === "validation_unavailable" || refineCode === "output_limit_exceeded" ? "validation_failed" : refineCode === "submodule_reachability_failed" ? "submodule_reachability_failed" : refineCode === "merge_failed" || refineCode === "patch_equivalence_failed" || refineCode === "needs_rebase" || refineCode === "needs_rebase_with_conflicts" ? "merge_failed" : refineCode === "cleanup_failed" ? "cleanup_failed" : "merge_failed";
114512
+ const clean = kind === "completed";
114513
+ return { kind, landing, isPostMergeWarning, converged: clean || isPostMergeWarning, clean };
114514
+ }
114515
+ function refineTerminalNextStep(kind) {
114516
+ switch (kind) {
114517
+ case "blocked_review":
114518
+ return "Request user review/approval before attempting to merge again.";
114519
+ case "validation_failed":
114520
+ return "Fix failing tests or configure validation.bootstrapCommands and retry mesh_refine_node.";
114521
+ case "submodule_reachability_failed":
114522
+ return "Push unreachable submodule commits to origin/main, then retry mesh_refine_node.";
114523
+ case "merge_failed":
114524
+ return "Resolve merge conflicts or patch equivalence issues, then retry mesh_refine_node.";
114525
+ case "cleanup_failed":
114526
+ return "Manually remove the worktree and retry or use mesh_remove_node.";
114527
+ case "completed_with_warnings":
114528
+ return "The merge IS on origin \u2014 do NOT re-run mesh_refine_node. Only the post-merge step below needs attention (worktree cleanup / submodule alignment); treat the branch as merged_to_main.";
114529
+ default:
114530
+ return "Inspect refineStages for the failing stage and retry.";
114531
+ }
114532
+ }
114533
+ function buildRefineWorktreeMissingResult(nodeId, workspace, refineStages) {
114534
+ return {
114535
+ success: false,
114536
+ code: "worktree_missing",
114537
+ convergenceStatus: "blocked_review",
114538
+ // Never auto-retried: re-running cannot recreate the worktree, and the node has
114539
+ // most likely already converged.
114540
+ retryable: false,
114541
+ workspaceMissing: true,
114542
+ error: `The worktree directory for node '${nodeId}' no longer exists (${workspace}); nothing was merged by this run. Worktree removal is the final step of a SUCCESSFUL refine, so this node was most likely already merged and cleaned up by an earlier job \u2014 verify with 'git -C <repoRoot> log --oneline' before acting. Do NOT re-run refine to "fix" this.`,
114543
+ nextStep: "Verify whether the branch already merged into the base (it most likely did). If so, treat the node as merged_to_main and remove it from the mesh; only re-clone if the work is genuinely missing.",
114544
+ refineStages,
114545
+ finalBranchConvergenceState: {
114546
+ baseBranch: void 0,
114547
+ merged: false,
114548
+ removed: true,
114549
+ status: "blocked_review"
114550
+ }
114551
+ };
114552
+ }
114553
+ function extractRefineMergeLanding(result) {
114554
+ const fbcs = result.finalBranchConvergenceState && typeof result.finalBranchConvergenceState === "object" ? result.finalBranchConvergenceState : void 0;
114555
+ const merged = result.merged === true || result.mergedLocal === true || fbcs?.merged === true;
114556
+ const pushed = result.pushed === true || fbcs?.pushed === true;
114557
+ return { merged: !!merged, pushed: !!pushed && !!merged };
114558
+ }
114107
114559
  init_repo_mesh_types();
114108
114560
  init_git_status();
114109
114561
  init_git_locale();
@@ -114112,7 +114564,7 @@ ${ptyResult.output.slice(-2e3)}`);
114112
114564
  init_refine_config();
114113
114565
  init_worktree_bootstrap_config();
114114
114566
  var import_path17 = require("path");
114115
- var fs46 = __toESM2(require("fs"));
114567
+ var fs47 = __toESM2(require("fs"));
114116
114568
  var import_node_child_process9 = require("child_process");
114117
114569
  init_resolve_executable();
114118
114570
  var GIT3 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
@@ -114141,12 +114593,12 @@ ${tail}`;
114141
114593
  function writeValidationFailureLog(workspace, index, candidate, streams, now = () => /* @__PURE__ */ new Date()) {
114142
114594
  try {
114143
114595
  const dir = (0, import_path17.join)(workspace, REFINE_VALIDATION_LOG_DIR);
114144
- fs46.mkdirSync(dir, { recursive: true });
114596
+ fs47.mkdirSync(dir, { recursive: true });
114145
114597
  const stamp = now().toISOString().replace(/[:.]/g, "-");
114146
114598
  const file2 = (0, import_path17.join)(dir, `refine-${stamp}-${index}.log`);
114147
114599
  const asText = (v) => typeof v === "string" ? v : v == null ? "" : String(v);
114148
114600
  const shown = candidate.displayCommand || [candidate.command, ...candidate.args || []].join(" ");
114149
- fs46.writeFileSync(
114601
+ fs47.writeFileSync(
114150
114602
  file2,
114151
114603
  `# refine validation failure
114152
114604
  # command: ${shown}
@@ -114223,7 +114675,7 @@ ${asText(streams.stderr)}
114223
114675
  const { execFileSync: execFileSync12 } = await import("child_process");
114224
114676
  const diffArgs = ["diff", "--patch", "--full-index", fromRef, toRef];
114225
114677
  if (excludePaths.length > 0) {
114226
- diffArgs.push("--", ".", ...excludePaths.map((path55) => `:(exclude)${path55}`));
114678
+ diffArgs.push("--", ".", ...excludePaths.map((path56) => `:(exclude)${path56}`));
114227
114679
  }
114228
114680
  const diff = execFileSync12(GIT3, diffArgs, {
114229
114681
  cwd,
@@ -114568,9 +115020,9 @@ ${mergeTreeErr?.stderr || ""}`;
114568
115020
  if (!trimmed) continue;
114569
115021
  if (trimmed.startsWith("+")) {
114570
115022
  const parts = trimmed.slice(1).trim().split(/\s+/);
114571
- const path55 = parts[1] || parts[0] || "(unknown)";
115023
+ const path56 = parts[1] || parts[0] || "(unknown)";
114572
115024
  submoduleHints.push({
114573
- path: path55,
115025
+ path: path56,
114574
115026
  reason: "submodule checked-out commit differs from the committed gitlink (pointer bump not committed on the root branch)"
114575
115027
  });
114576
115028
  }
@@ -114600,10 +115052,10 @@ ${mergeTreeErr?.stderr || ""}`;
114600
115052
  }
114601
115053
  function buildPatchEquivalenceSubmoduleConflictHint(repoRoot, baseHead, branchHead, output) {
114602
115054
  if (!/(submodule|160000)/i.test(output) || !/(conflict|failed to merge)/i.test(output)) return void 0;
114603
- const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path55) => ({
114604
- path: path55,
114605
- baseCommit: readTreeObject(repoRoot, baseHead, path55),
114606
- branchCommit: readTreeObject(repoRoot, branchHead, path55)
115055
+ const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path56) => ({
115056
+ path: path56,
115057
+ baseCommit: readTreeObject(repoRoot, baseHead, path56),
115058
+ branchCommit: readTreeObject(repoRoot, branchHead, path56)
114607
115059
  }));
114608
115060
  if (conflicts.length === 0) return void 0;
114609
115061
  return {
@@ -114629,11 +115081,11 @@ ${mergeTreeErr?.stderr || ""}`;
114629
115081
  if (!line.trim()) continue;
114630
115082
  const metaAndPath = line.split(" ");
114631
115083
  const meta3 = metaAndPath[0] || "";
114632
- const path55 = metaAndPath[metaAndPath.length - 1]?.trim();
114633
- if (!path55) continue;
115084
+ const path56 = metaAndPath[metaAndPath.length - 1]?.trim();
115085
+ if (!path56) continue;
114634
115086
  const parts = meta3.split(/\s+/);
114635
115087
  if (parts[0]?.includes("160000") || parts[1]?.includes("160000")) {
114636
- paths.add(path55);
115088
+ paths.add(path56);
114637
115089
  }
114638
115090
  }
114639
115091
  return [...paths].sort();
@@ -114641,9 +115093,9 @@ ${mergeTreeErr?.stderr || ""}`;
114641
115093
  return [];
114642
115094
  }
114643
115095
  }
114644
- function readTreeObject(repoRoot, ref, path55) {
115096
+ function readTreeObject(repoRoot, ref, path56) {
114645
115097
  try {
114646
- const output = (0, import_node_child_process9.execFileSync)(GIT3, ["ls-tree", ref, "--", path55], {
115098
+ const output = (0, import_node_child_process9.execFileSync)(GIT3, ["ls-tree", ref, "--", path56], {
114647
115099
  cwd: repoRoot,
114648
115100
  encoding: "utf8",
114649
115101
  maxBuffer: 1024 * 1024
@@ -114666,7 +115118,7 @@ ${mergeTreeErr?.stderr || ""}`;
114666
115118
  if (!baseCommit || !branchCommit) return false;
114667
115119
  if (baseCommit === branchCommit) return true;
114668
115120
  try {
114669
- if (!fs46.existsSync(submoduleRepoPath)) return false;
115121
+ if (!fs47.existsSync(submoduleRepoPath)) return false;
114670
115122
  (0, import_node_child_process9.execFileSync)(GIT3, ["cat-file", "-e", `${baseCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
114671
115123
  (0, import_node_child_process9.execFileSync)(GIT3, ["cat-file", "-e", `${branchCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
114672
115124
  (0, import_node_child_process9.execFileSync)(GIT3, ["merge-base", "--is-ancestor", baseCommit, branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
@@ -114688,12 +115140,12 @@ ${mergeTreeErr?.stderr || ""}`;
114688
115140
  if (!line.trim()) continue;
114689
115141
  const metaAndPath = line.split(" ");
114690
115142
  const meta3 = metaAndPath[0] || "";
114691
- const path55 = metaAndPath[metaAndPath.length - 1]?.trim();
114692
- if (!path55 || seen.has(path55)) continue;
114693
- seen.add(path55);
115143
+ const path56 = metaAndPath[metaAndPath.length - 1]?.trim();
115144
+ if (!path56 || seen.has(path56)) continue;
115145
+ seen.add(path56);
114694
115146
  const parts = meta3.split(/\s+/);
114695
115147
  const isGitlink = !!(parts[0]?.includes("160000") || parts[1]?.includes("160000"));
114696
- result.push({ path: path55, isGitlink });
115148
+ result.push({ path: path56, isGitlink });
114697
115149
  }
114698
115150
  return result;
114699
115151
  } catch {
@@ -114701,28 +115153,28 @@ ${mergeTreeErr?.stderr || ""}`;
114701
115153
  }
114702
115154
  }
114703
115155
  function collectFastForwardGitlinkPaths(repoRoot, baseHead, branchHead) {
114704
- return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path55) => {
114705
- const baseCommit = readTreeObject(repoRoot, baseHead, path55);
114706
- const branchCommit = readTreeObject(repoRoot, branchHead, path55);
115156
+ return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path56) => {
115157
+ const baseCommit = readTreeObject(repoRoot, baseHead, path56);
115158
+ const branchCommit = readTreeObject(repoRoot, branchHead, path56);
114707
115159
  if (!baseCommit || !branchCommit) return false;
114708
- return isSubmoduleFastForward((0, import_path17.resolve)(repoRoot, path55), baseCommit, branchCommit);
115160
+ return isSubmoduleFastForward((0, import_path17.resolve)(repoRoot, path56), baseCommit, branchCommit);
114709
115161
  });
114710
115162
  }
114711
115163
  function collectTrivialFastForwardGitlinkResolutions(worktreeRoot, baseRepoRoot, baseHead, branchHead) {
114712
115164
  const resolutions = [];
114713
- for (const path55 of readChangedGitlinkPaths(worktreeRoot, baseHead, branchHead)) {
114714
- const baseCommit = readTreeObject(baseRepoRoot, baseHead, path55);
114715
- const branchCommit = readTreeObject(worktreeRoot, branchHead, path55);
115165
+ for (const path56 of readChangedGitlinkPaths(worktreeRoot, baseHead, branchHead)) {
115166
+ const baseCommit = readTreeObject(baseRepoRoot, baseHead, path56);
115167
+ const branchCommit = readTreeObject(worktreeRoot, branchHead, path56);
114716
115168
  if (!baseCommit || !branchCommit) continue;
114717
- const submoduleRepoPath = (0, import_path17.resolve)(worktreeRoot, path55);
114718
- ensureSubmoduleCommitLocal(submoduleRepoPath, (0, import_path17.resolve)(baseRepoRoot, path55), baseCommit);
115169
+ const submoduleRepoPath = (0, import_path17.resolve)(worktreeRoot, path56);
115170
+ ensureSubmoduleCommitLocal(submoduleRepoPath, (0, import_path17.resolve)(baseRepoRoot, path56), baseCommit);
114719
115171
  if (baseCommit === branchCommit) {
114720
115172
  continue;
114721
115173
  }
114722
115174
  if (isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit)) {
114723
- resolutions.push({ path: path55, rebasedCommit: branchCommit });
115175
+ resolutions.push({ path: path56, rebasedCommit: branchCommit });
114724
115176
  } else if (isSubmoduleFastForward(submoduleRepoPath, branchCommit, baseCommit)) {
114725
- resolutions.push({ path: path55, rebasedCommit: baseCommit });
115177
+ resolutions.push({ path: path56, rebasedCommit: baseCommit });
114726
115178
  }
114727
115179
  }
114728
115180
  return resolutions;
@@ -114730,7 +115182,7 @@ ${mergeTreeErr?.stderr || ""}`;
114730
115182
  function isSubmoduleDivergedSibling(submoduleRepoPath, baseCommit, branchCommit) {
114731
115183
  if (!baseCommit || !branchCommit || baseCommit === branchCommit) return false;
114732
115184
  try {
114733
- if (!fs46.existsSync(submoduleRepoPath)) return false;
115185
+ if (!fs47.existsSync(submoduleRepoPath)) return false;
114734
115186
  (0, import_node_child_process9.execFileSync)(GIT3, ["cat-file", "-e", `${baseCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
114735
115187
  (0, import_node_child_process9.execFileSync)(GIT3, ["cat-file", "-e", `${branchCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
114736
115188
  } catch {
@@ -114802,7 +115254,7 @@ ${mergeTreeErr?.stderr || ""}`;
114802
115254
  } catch {
114803
115255
  }
114804
115256
  try {
114805
- if (!fs46.existsSync(submoduleRepoPath) || !fs46.existsSync(baseSubmoduleRepoPath)) return;
115257
+ if (!fs47.existsSync(submoduleRepoPath) || !fs47.existsSync(baseSubmoduleRepoPath)) return;
114806
115258
  (0, import_node_child_process9.execFileSync)(GIT3, ["-c", "protocol.file.allow=always", "fetch", "-q", baseSubmoduleRepoPath, "+refs/heads/*:refs/adhdev-refine-base/*"], {
114807
115259
  cwd: submoduleRepoPath,
114808
115260
  stdio: ["ignore", "ignore", "pipe"]
@@ -114818,15 +115270,15 @@ ${mergeTreeErr?.stderr || ""}`;
114818
115270
  const gitlinks = [];
114819
115271
  const resolutions = [];
114820
115272
  let sawDiverged = false;
114821
- for (const path55 of changed) {
114822
- const baseCommit = readTreeObject(baseRepoRoot, baseHead, path55);
114823
- const branchCommit = readTreeObject(worktreeRoot, branchHead, path55);
114824
- const submoduleRepoPath = (0, import_path17.resolve)(worktreeRoot, path55);
115273
+ for (const path56 of changed) {
115274
+ const baseCommit = readTreeObject(baseRepoRoot, baseHead, path56);
115275
+ const branchCommit = readTreeObject(worktreeRoot, branchHead, path56);
115276
+ const submoduleRepoPath = (0, import_path17.resolve)(worktreeRoot, path56);
114825
115277
  if (baseCommit) {
114826
- ensureSubmoduleCommitLocal(submoduleRepoPath, (0, import_path17.resolve)(baseRepoRoot, path55), baseCommit);
115278
+ ensureSubmoduleCommitLocal(submoduleRepoPath, (0, import_path17.resolve)(baseRepoRoot, path56), baseCommit);
114827
115279
  }
114828
115280
  if (!baseCommit || !branchCommit || !isSubmoduleDivergedSibling(submoduleRepoPath, baseCommit, branchCommit)) {
114829
- gitlinks.push({ path: path55, baseCommit, branchCommit, action: "skipped_not_diverged" });
115281
+ gitlinks.push({ path: path56, baseCommit, branchCommit, action: "skipped_not_diverged" });
114830
115282
  continue;
114831
115283
  }
114832
115284
  sawDiverged = true;
@@ -114841,8 +115293,8 @@ ${mergeTreeErr?.stderr || ""}`;
114841
115293
  (0, import_node_child_process9.execFileSync)(GIT3, ["checkout", "-q", "--detach", publishedEquivalent], { cwd: submoduleRepoPath, stdio: ["ignore", "ignore", "pipe"] });
114842
115294
  } catch {
114843
115295
  }
114844
- gitlinks.push({ path: path55, baseCommit, branchCommit, rebasedCommit: publishedEquivalent, action: "converged_to_published" });
114845
- resolutions.push({ path: path55, baseCommit, branchCommit, rebasedCommit: publishedEquivalent });
115296
+ gitlinks.push({ path: path56, baseCommit, branchCommit, rebasedCommit: publishedEquivalent, action: "converged_to_published" });
115297
+ resolutions.push({ path: path56, baseCommit, branchCommit, rebasedCommit: publishedEquivalent });
114846
115298
  continue;
114847
115299
  }
114848
115300
  let rebasedCommit;
@@ -114859,7 +115311,7 @@ ${mergeTreeErr?.stderr || ""}`;
114859
115311
  (0, import_node_child_process9.execFileSync)(GIT3, ["checkout", "-q", "--detach", branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
114860
115312
  } catch {
114861
115313
  }
114862
- gitlinks.push({ path: path55, baseCommit, branchCommit, action: "rebase_conflict" });
115314
+ gitlinks.push({ path: path56, baseCommit, branchCommit, action: "rebase_conflict" });
114863
115315
  return { converged: false, reason: "rebase_conflict", resolutions: [], gitlinks };
114864
115316
  }
114865
115317
  const branchWorkSurvived = (() => {
@@ -114881,11 +115333,11 @@ ${mergeTreeErr?.stderr || ""}`;
114881
115333
  (0, import_node_child_process9.execFileSync)(GIT3, ["checkout", "-q", "--detach", branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
114882
115334
  } catch {
114883
115335
  }
114884
- gitlinks.push({ path: path55, baseCommit, branchCommit, rebasedCommit, action: "rebase_dropped_branch_commits" });
115336
+ gitlinks.push({ path: path56, baseCommit, branchCommit, rebasedCommit, action: "rebase_dropped_branch_commits" });
114885
115337
  return { converged: false, reason: "rebase_dropped_branch_commits", resolutions: [], gitlinks };
114886
115338
  }
114887
- gitlinks.push({ path: path55, baseCommit, branchCommit, rebasedCommit, action: "rebased" });
114888
- resolutions.push({ path: path55, baseCommit, branchCommit, rebasedCommit });
115339
+ gitlinks.push({ path: path56, baseCommit, branchCommit, rebasedCommit, action: "rebased" });
115340
+ resolutions.push({ path: path56, baseCommit, branchCommit, rebasedCommit });
114889
115341
  }
114890
115342
  if (!sawDiverged) {
114891
115343
  return { converged: false, reason: "not_diverged", resolutions: [], gitlinks };
@@ -114971,12 +115423,12 @@ ${mergeTreeErr?.stderr || ""}`;
114971
115423
  return { ok: true, branchHead };
114972
115424
  }
114973
115425
  function evaluateGitlinkTrivialFastForward(repoRoot, baseHead, branchHead) {
114974
- const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path55) => {
114975
- const baseCommit = readTreeObject(repoRoot, baseHead, path55);
114976
- const branchCommit = readTreeObject(repoRoot, branchHead, path55);
114977
- const submoduleRepoPath = (0, import_path17.resolve)(repoRoot, path55);
115426
+ const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path56) => {
115427
+ const baseCommit = readTreeObject(repoRoot, baseHead, path56);
115428
+ const branchCommit = readTreeObject(repoRoot, branchHead, path56);
115429
+ const submoduleRepoPath = (0, import_path17.resolve)(repoRoot, path56);
114978
115430
  const fastForward = !!baseCommit && !!branchCommit && isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit);
114979
- return { path: path55, baseCommit, branchCommit, fastForward };
115431
+ return { path: path56, baseCommit, branchCommit, fastForward };
114980
115432
  });
114981
115433
  if (changedGitlinks.length === 0) {
114982
115434
  return { trivial: false, reason: "no_changed_gitlinks", gitlinks: changedGitlinks };
@@ -115027,7 +115479,7 @@ ${mergeTreeErr?.stderr || ""}`;
115027
115479
  maxBuffer: 1024 * 1024
115028
115480
  }).trim();
115029
115481
  if (!tree) return void 0;
115030
- const updates = paths.map((path55) => `160000 commit ${placeholderCommit} ${path55}`).join("\n");
115482
+ const updates = paths.map((path56) => `160000 commit ${placeholderCommit} ${path56}`).join("\n");
115031
115483
  if (!updates) return tree;
115032
115484
  const tmpIndex = (0, import_path17.join)(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
115033
115485
  const env2 = { ...process.env, GIT_INDEX_FILE: tmpIndex };
@@ -115045,7 +115497,7 @@ ${mergeTreeErr?.stderr || ""}`;
115045
115497
  return newTree || void 0;
115046
115498
  } finally {
115047
115499
  try {
115048
- fs46.rmSync(tmpIndex, { force: true });
115500
+ fs47.rmSync(tmpIndex, { force: true });
115049
115501
  } catch {
115050
115502
  }
115051
115503
  }
@@ -115120,7 +115572,7 @@ ${mergeTreeErr?.stderr || ""}`;
115120
115572
  return newTree || void 0;
115121
115573
  } finally {
115122
115574
  try {
115123
- fs46.rmSync(tmpIndex, { force: true });
115575
+ fs47.rmSync(tmpIndex, { force: true });
115124
115576
  } catch {
115125
115577
  }
115126
115578
  }
@@ -115130,7 +115582,7 @@ ${mergeTreeErr?.stderr || ""}`;
115130
115582
  }
115131
115583
  async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, currentHead, options = {}) {
115132
115584
  const startedAt = Date.now();
115133
- const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path55) => !(options.submoduleIgnorePaths || []).includes(path55));
115585
+ const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path56) => !(options.submoduleIgnorePaths || []).includes(path56));
115134
115586
  const preStatus = await getGitRepoStatus(repoRoot, {
115135
115587
  includeSubmodules: true,
115136
115588
  submoduleIgnorePaths: options.submoduleIgnorePaths,
@@ -115177,7 +115629,7 @@ ${mergeTreeErr?.stderr || ""}`;
115177
115629
  changedGitlinkPaths,
115178
115630
  outOfSyncPaths,
115179
115631
  updatedPaths: updatePaths,
115180
- verifiedPaths: updatePaths.filter((path55) => !remaining.some((submodule) => submodule.path === path55)),
115632
+ verifiedPaths: updatePaths.filter((path56) => !remaining.some((submodule) => submodule.path === path56)),
115181
115633
  durationMs: Date.now() - startedAt,
115182
115634
  command: `git ${commandArgs.join(" ")}`,
115183
115635
  stdout: truncateValidationOutput(result.stdout),
@@ -115232,7 +115684,7 @@ ${mergeTreeErr?.stderr || ""}`;
115232
115684
  return { stdout: String(stdout || ""), stderr: String(stderr || ""), refspec };
115233
115685
  };
115234
115686
  const importCommitFromWorktreeSubmodule = async (submodulePath, worktreeSubmodulePath, commit) => {
115235
- if (!fs46.existsSync(worktreeSubmodulePath)) return false;
115687
+ if (!fs47.existsSync(worktreeSubmodulePath)) return false;
115236
115688
  try {
115237
115689
  await runGit3(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
115238
115690
  } catch {
@@ -115269,7 +115721,7 @@ ${mergeTreeErr?.stderr || ""}`;
115269
115721
  };
115270
115722
  let submoduleDefaultBranch = "main";
115271
115723
  try {
115272
- if (!fs46.existsSync(submodulePath)) {
115724
+ if (!fs47.existsSync(submodulePath)) {
115273
115725
  entry.error = `Submodule checkout missing at ${gitlink.path}`;
115274
115726
  entry.publishRequired = true;
115275
115727
  if (options.allowAutoPublishSubmoduleMainCommits === true) {
@@ -115522,9 +115974,9 @@ ${mergeTreeErr?.stderr || ""}`;
115522
115974
  return ["npm", "pnpm", "yarn", "bun"].includes(command) && candidate.args.some((arg) => arg === "run" || arg === "test" || arg === "exec");
115523
115975
  };
115524
115976
  const dependenciesLikelyMissing = (cwd) => {
115525
- if (!fs46.existsSync((0, import_path17.join)(cwd, "package.json"))) return false;
115526
- if (fs46.existsSync((0, import_path17.join)(cwd, "node_modules"))) return false;
115527
- return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs46.existsSync((0, import_path17.join)(cwd, lock)));
115977
+ if (!fs47.existsSync((0, import_path17.join)(cwd, "package.json"))) return false;
115978
+ if (fs47.existsSync((0, import_path17.join)(cwd, "node_modules"))) return false;
115979
+ return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs47.existsSync((0, import_path17.join)(cwd, lock)));
115528
115980
  };
115529
115981
  const needsNodeModules = (candidate, cwd) => isPackageManagerValidation(candidate) && dependenciesLikelyMissing(cwd);
115530
115982
  const isDaemonScopedCommand = (candidate) => {
@@ -115754,7 +116206,16 @@ ${mergeTreeErr?.stderr || ""}`;
115754
116206
  "conflictPaths",
115755
116207
  "branchRefWarning",
115756
116208
  "residueWarning",
115757
- "branchRefDeleted"
116209
+ "branchRefDeleted",
116210
+ // GHOST-FAILURE: merge-landing facts. The coordinator sees ONLY this slim
116211
+ // result; without these it cannot tell a pre-merge failure (nothing landed)
116212
+ // from a post-merge one (the change IS on origin) without a manual git check.
116213
+ "merged",
116214
+ "mergedLocal",
116215
+ "pushed",
116216
+ "mergedSha",
116217
+ "postMergeWarning",
116218
+ "refineLanding"
115758
116219
  ]) {
115759
116220
  if (result[key2] !== void 0) slim[key2] = result[key2];
115760
116221
  }
@@ -116039,6 +116500,13 @@ ${mergeTreeErr?.stderr || ""}`;
116039
116500
  if (!node.isLocalWorktree || !node.workspace) {
116040
116501
  return { kind: "terminal", result: { success: false, error: `Refinery requires a local worktree node`, refineStages } };
116041
116502
  }
116503
+ if (!(0, import_node_fs6.existsSync)(node.workspace)) {
116504
+ recordMeshRefineStage(refineStages, "resolve_refs", "failed", Date.now(), {
116505
+ workspace: node.workspace,
116506
+ workspaceMissing: true
116507
+ });
116508
+ return { kind: "terminal", result: buildRefineWorktreeMissingResult(nodeId, node.workspace, refineStages) };
116509
+ }
116042
116510
  const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => meshNodeIdMatches(n, node.clonedFromNodeId)) : mesh?.nodes.find((n) => !n.isLocalWorktree);
116043
116511
  const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
116044
116512
  if (!repoRoot) return { kind: "terminal", result: { success: false, error: "Source node repoRoot not found", refineStages } };
@@ -117576,11 +118044,10 @@ ${e?.stderr || ""}`;
117576
118044
  }
117577
118045
  const completedAt = (/* @__PURE__ */ new Date()).toISOString();
117578
118046
  const refineCode = typeof result.code === "string" ? result.code : "";
117579
- const refineTerminalKind = result.success === true ? "completed" : refineCode === "blocked_review" ? "blocked_review" : refineCode === "validation_failed" || refineCode === "validation_dependencies_missing" || refineCode === "missing_dependencies" || refineCode === "dependency_bootstrap_failed" || refineCode === "spawn_resolution_failed" || refineCode === "validation_unavailable" || refineCode === "output_limit_exceeded" ? "validation_failed" : refineCode === "submodule_reachability_failed" ? "submodule_reachability_failed" : refineCode === "merge_failed" || refineCode === "patch_equivalence_failed" || refineCode === "needs_rebase" || refineCode === "needs_rebase_with_conflicts" ? "merge_failed" : refineCode === "cleanup_failed" ? "cleanup_failed" : "merge_failed";
117580
- const isTerminalSuccess = refineTerminalKind === "completed";
117581
- const blockerContext = isTerminalSuccess ? void 0 : (() => {
118047
+ const { kind: refineTerminalKind, landing, isPostMergeWarning, converged: isTerminalConverged, clean: isTerminalClean } = classifyRefineTerminal(result);
118048
+ const blockerContext = isTerminalClean ? void 0 : (() => {
117582
118049
  const code = typeof result.code === "string" ? result.code : refineTerminalKind;
117583
- const stage = refineTerminalKind === "validation_failed" ? "validation" : refineTerminalKind === "submodule_reachability_failed" ? "submodule_reachability" : refineCode === "patch_equivalence_failed" ? "patch_equivalence" : refineCode === "needs_rebase" || refineCode === "needs_rebase_with_conflicts" ? "patch_equivalence" : refineTerminalKind === "merge_failed" ? "merge" : refineTerminalKind === "cleanup_failed" ? "cleanup" : "unknown";
118050
+ const stage = refineTerminalKind === "validation_failed" ? "validation" : refineTerminalKind === "submodule_reachability_failed" ? "submodule_reachability" : refineCode === "patch_equivalence_failed" ? "patch_equivalence" : refineCode === "needs_rebase" || refineCode === "needs_rebase_with_conflicts" ? "patch_equivalence" : refineTerminalKind === "merge_failed" ? "merge" : refineTerminalKind === "cleanup_failed" ? "cleanup" : refineTerminalKind === "completed_with_warnings" ? refineCode === "post_merge_submodule_alignment_failed" ? "submodule_alignment" : "cleanup" : "unknown";
117584
118051
  const ctx = {
117585
118052
  stage,
117586
118053
  reason: code,
@@ -117628,14 +118095,23 @@ ${e?.stderr || ""}`;
117628
118095
  ...result,
117629
118096
  terminalKind: refineTerminalKind,
117630
118097
  ...blockerContext ? { blockerContext } : {},
117631
- ...result.nextStep === void 0 && !isTerminalSuccess ? {
117632
- nextStep: refineTerminalKind === "blocked_review" ? "Request user review/approval before attempting to merge again." : refineTerminalKind === "validation_failed" ? "Fix failing tests or configure validation.bootstrapCommands and retry mesh_refine_node." : refineTerminalKind === "submodule_reachability_failed" ? "Push unreachable submodule commits to origin/main, then retry mesh_refine_node." : refineTerminalKind === "merge_failed" ? "Resolve merge conflicts or patch equivalence issues, then retry mesh_refine_node." : refineTerminalKind === "cleanup_failed" ? "Manually remove the worktree and retry or use mesh_remove_node." : "Inspect refineStages for the failing stage and retry."
118098
+ ...result.nextStep === void 0 && !isTerminalClean ? { nextStep: refineTerminalNextStep(refineTerminalKind) } : {},
118099
+ // GHOST-FAILURE: explicit machine-readable landing verdict, present on EVERY
118100
+ // terminal result (plain failures read merged:false) so a coordinator never
118101
+ // has to run `git log` to tell whether the work landed.
118102
+ refineLanding: {
118103
+ merged: landing.merged,
118104
+ pushed: landing.pushed,
118105
+ converged: isTerminalConverged
118106
+ },
118107
+ ...isPostMergeWarning ? {
118108
+ postMergeWarning: `Merge landed and was pushed to origin/${typeof result.into === "string" ? result.into : "base"}, but a post-merge step failed (${refineCode || "unknown"}). This node is CONVERGED \u2014 do not re-refine it.`
117633
118109
  } : {}
117634
118110
  };
117635
118111
  const terminalHandle = buildRefineJobHandle(self, {
117636
118112
  meshId: handle.meshId,
117637
118113
  nodeId: handle.targetNodeId,
117638
- status: isTerminalSuccess ? "completed" : "failed",
118114
+ status: isTerminalConverged ? "completed" : "failed",
117639
118115
  startedAt: handle.startedAt,
117640
118116
  completedAt,
117641
118117
  jobId: handle.jobId,
@@ -117653,8 +118129,8 @@ ${e?.stderr || ""}`;
117653
118129
  self.terminalRefineJobs.set(key2, terminal);
117654
118130
  self.runningRefineJobs.delete(key2);
117655
118131
  self.invalidateAggregateMeshStatus(handle.meshId);
117656
- await appendRefineJobLedger(self, isTerminalSuccess ? "task_completed" : "task_failed", terminalHandle, normalizedResult);
117657
- queueRefineJobEvent(self, isTerminalSuccess ? "refine:completed" : "refine:failed", terminalHandle, normalizedResult);
118132
+ await appendRefineJobLedger(self, isTerminalConverged ? "task_completed" : "task_failed", terminalHandle, normalizedResult);
118133
+ queueRefineJobEvent(self, isTerminalConverged ? "refine:completed" : "refine:failed", terminalHandle, normalizedResult);
117658
118134
  }
117659
118135
  async function recordRefineAcceptBaseDivergence(self, handle, node) {
117660
118136
  try {
@@ -117721,7 +118197,7 @@ ${e?.stderr || ""}`;
117721
118197
  });
117722
118198
  return handle;
117723
118199
  }
117724
- var fs47 = __toESM2(require("fs"));
118200
+ var fs48 = __toESM2(require("fs"));
117725
118201
  var import_node_os2 = require("os");
117726
118202
  var import_path18 = require("path");
117727
118203
  init_logger();
@@ -117777,14 +118253,14 @@ ${e?.stderr || ""}`;
117777
118253
  return false;
117778
118254
  }
117779
118255
  async function bestEffortRemoveWorktreeDir(self, dir) {
117780
- if (!dir || !fs47.existsSync(dir)) return { removed: true, residue: false };
118256
+ if (!dir || !fs48.existsSync(dir)) return { removed: true, residue: false };
117781
118257
  const sleep3 = (ms) => new Promise((resolve30) => setTimeout(resolve30, ms));
117782
118258
  const ABSORB = /* @__PURE__ */ new Set(["EINVAL", "EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);
117783
118259
  let lastErr;
117784
118260
  for (let attempt = 0; attempt < 4; attempt++) {
117785
118261
  try {
117786
- fs47.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
117787
- if (!fs47.existsSync(dir)) return { removed: true, residue: false };
118262
+ fs48.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
118263
+ if (!fs48.existsSync(dir)) return { removed: true, residue: false };
117788
118264
  lastErr = new Error("directory still present after rmSync");
117789
118265
  } catch (e) {
117790
118266
  lastErr = e;
@@ -117795,7 +118271,7 @@ ${e?.stderr || ""}`;
117795
118271
  }
117796
118272
  await sleep3(150 * (attempt + 1));
117797
118273
  }
117798
- return fs47.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
118274
+ return fs48.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
117799
118275
  }
117800
118276
  async function precheckLocalWorktreeRemovable(self, args) {
117801
118277
  const sessionPreservedNote = " The delegated session was left running (not stopped) \u2014 resolve the issue and retry mesh_remove_node.";
@@ -117808,10 +118284,10 @@ ${e?.stderr || ""}`;
117808
118284
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains." + sessionPreservedNote
117809
118285
  };
117810
118286
  }
117811
- if (!fs47.existsSync(workspace)) return { ok: true };
118287
+ if (!fs48.existsSync(workspace)) return { ok: true };
117812
118288
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
117813
118289
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
117814
- if (!repoRoot || !fs47.existsSync(repoRoot)) {
118290
+ if (!repoRoot || !fs48.existsSync(repoRoot)) {
117815
118291
  return {
117816
118292
  ok: false,
117817
118293
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -117831,7 +118307,7 @@ ${e?.stderr || ""}`;
117831
118307
  const normalizePath2 = (value) => {
117832
118308
  const resolved = (0, import_path18.resolve)(value);
117833
118309
  try {
117834
- return fs47.realpathSync(resolved);
118310
+ return fs48.realpathSync(resolved);
117835
118311
  } catch {
117836
118312
  return resolved;
117837
118313
  }
@@ -117902,13 +118378,13 @@ ${e?.stderr || ""}`;
117902
118378
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains."
117903
118379
  };
117904
118380
  }
117905
- const worktreeExists = fs47.existsSync(workspace);
118381
+ const worktreeExists = fs48.existsSync(workspace);
117906
118382
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
117907
118383
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
117908
118384
  if (!worktreeExists) {
117909
118385
  return { success: true, skipped: true, removedPath: workspace, repoRoot: repoRoot || void 0, reason: "worktree_path_missing" };
117910
118386
  }
117911
- if (!repoRoot || !fs47.existsSync(repoRoot)) {
118387
+ if (!repoRoot || !fs48.existsSync(repoRoot)) {
117912
118388
  return {
117913
118389
  success: false,
117914
118390
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -117928,7 +118404,7 @@ ${e?.stderr || ""}`;
117928
118404
  const normalizePath2 = (value) => {
117929
118405
  const resolved = (0, import_path18.resolve)(value);
117930
118406
  try {
117931
- return fs47.realpathSync(resolved);
118407
+ return fs48.realpathSync(resolved);
117932
118408
  } catch {
117933
118409
  return resolved;
117934
118410
  }
@@ -118575,7 +119051,7 @@ ${e?.stderr || ""}`;
118575
119051
  var yaml5 = __toESM2(require_js_yaml());
118576
119052
  var import_os5 = require("os");
118577
119053
  var import_path19 = require("path");
118578
- var fs48 = __toESM2(require("fs"));
119054
+ var fs49 = __toESM2(require("fs"));
118579
119055
  var MESH_COORDINATOR_AUTO_IMPORT_FORMATS = ["claude_mcp_json", "hermes_config_yaml", "opencode_json"];
118580
119056
  function isSupportedMeshCoordinatorConfigFormat(format) {
118581
119057
  return MESH_COORDINATOR_AUTO_IMPORT_FORMATS.includes(format);
@@ -118620,9 +119096,9 @@ ${e?.stderr || ""}`;
118620
119096
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
118621
119097
  const sourceHome = resolveHermesUserHome();
118622
119098
  const sourceConfigPath = (0, import_path19.join)(sourceHome, "config.yaml");
118623
- if (!fs48.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
119099
+ if (!fs49.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
118624
119100
  if ((0, import_path19.resolve)(sourceConfigPath) === (0, import_path19.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
118625
- const parsed = parseMeshCoordinatorMcpConfig(fs48.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
119101
+ const parsed = parseMeshCoordinatorMcpConfig(fs49.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
118626
119102
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
118627
119103
  return { config: baseConfig, sourceHome, sourceConfigPath };
118628
119104
  }
@@ -118659,9 +119135,9 @@ ${e?.stderr || ""}`;
118659
119135
  for (const fileName of [".env", "auth.json"]) {
118660
119136
  const sourcePath = (0, import_path19.join)(sourceHome, fileName);
118661
119137
  const targetPath = (0, import_path19.join)(targetHome, fileName);
118662
- if (!fs48.existsSync(sourcePath)) continue;
119138
+ if (!fs49.existsSync(sourcePath)) continue;
118663
119139
  try {
118664
- fs48.copyFileSync(sourcePath, targetPath);
119140
+ fs49.copyFileSync(sourcePath, targetPath);
118665
119141
  } catch (error48) {
118666
119142
  LOG2.warn("MeshCoordinator", `Could not copy Hermes ${fileName} into isolated coordinator home: ${error48?.message || error48}`);
118667
119143
  }
@@ -119176,7 +119652,7 @@ ${e?.stderr || ""}`;
119176
119652
  const nodeId = readInlineMeshNodeId(node);
119177
119653
  if (!nodeId || !tombstones.has(nodeId)) return true;
119178
119654
  const workspace = readStringValue(node?.workspace);
119179
- if (workspace && fs49.existsSync(workspace)) {
119655
+ if (workspace && fs50.existsSync(workspace)) {
119180
119656
  tombstones.delete(nodeId);
119181
119657
  return true;
119182
119658
  }
@@ -121196,14 +121672,14 @@ ${e?.stderr || ""}`;
121196
121672
  };
121197
121673
  init_io_contracts();
121198
121674
  init_chat_message_normalization();
121199
- var fs50 = __toESM2(require("fs"));
121200
- var path49 = __toESM2(require("path"));
121201
- var os27 = __toESM2(require("os"));
121675
+ var fs51 = __toESM2(require("fs"));
121676
+ var path50 = __toESM2(require("path"));
121677
+ var os28 = __toESM2(require("os"));
121202
121678
  var import_os6 = require("os");
121203
121679
  init_config();
121204
121680
  var import_child_process13 = require("child_process");
121205
121681
  function getArchivePath2() {
121206
- return path49.join(getConfigDir2(), "version-history.json");
121682
+ return path50.join(getConfigDir2(), "version-history.json");
121207
121683
  }
121208
121684
  var MAX_ENTRIES_PER_PROVIDER = 20;
121209
121685
  var VersionArchive = class {
@@ -121213,8 +121689,8 @@ ${e?.stderr || ""}`;
121213
121689
  }
121214
121690
  load() {
121215
121691
  try {
121216
- if (fs50.existsSync(getArchivePath2())) {
121217
- this.history = JSON.parse(fs50.readFileSync(getArchivePath2(), "utf-8"));
121692
+ if (fs51.existsSync(getArchivePath2())) {
121693
+ this.history = JSON.parse(fs51.readFileSync(getArchivePath2(), "utf-8"));
121218
121694
  }
121219
121695
  } catch {
121220
121696
  this.history = {};
@@ -121251,8 +121727,8 @@ ${e?.stderr || ""}`;
121251
121727
  }
121252
121728
  save() {
121253
121729
  try {
121254
- fs50.mkdirSync(path49.dirname(getArchivePath2()), { recursive: true });
121255
- fs50.writeFileSync(getArchivePath2(), JSON.stringify(this.history, null, 2));
121730
+ fs51.mkdirSync(path50.dirname(getArchivePath2()), { recursive: true });
121731
+ fs51.writeFileSync(getArchivePath2(), JSON.stringify(this.history, null, 2));
121256
121732
  } catch {
121257
121733
  }
121258
121734
  }
@@ -121275,10 +121751,10 @@ ${e?.stderr || ""}`;
121275
121751
  for (const p of paths) {
121276
121752
  if (!p) continue;
121277
121753
  for (const ext of exes) {
121278
- const fullPath = path49.join(p, name + ext);
121754
+ const fullPath = path50.join(p, name + ext);
121279
121755
  try {
121280
- if (fs50.existsSync(fullPath)) {
121281
- const stat2 = fs50.statSync(fullPath);
121756
+ if (fs51.existsSync(fullPath)) {
121757
+ const stat2 = fs51.statSync(fullPath);
121282
121758
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
121283
121759
  return fullPath;
121284
121760
  }
@@ -121323,19 +121799,19 @@ ${e?.stderr || ""}`;
121323
121799
  function checkPathExists2(paths) {
121324
121800
  for (const p of paths) {
121325
121801
  if (p.includes("*")) {
121326
- const home = os27.homedir();
121327
- const resolved = p.replace(/\*/g, home.split(path49.sep).pop() || "");
121328
- if (fs50.existsSync(resolved)) return resolved;
121802
+ const home = os28.homedir();
121803
+ const resolved = p.replace(/\*/g, home.split(path50.sep).pop() || "");
121804
+ if (fs51.existsSync(resolved)) return resolved;
121329
121805
  } else {
121330
- if (fs50.existsSync(p)) return p;
121806
+ if (fs51.existsSync(p)) return p;
121331
121807
  }
121332
121808
  }
121333
121809
  return null;
121334
121810
  }
121335
121811
  async function getMacAppVersion(appPath) {
121336
121812
  if ((0, import_os6.platform)() !== "darwin" || !appPath.endsWith(".app")) return null;
121337
- const plistPath = path49.join(appPath, "Contents", "Info.plist");
121338
- if (!fs50.existsSync(plistPath)) return null;
121813
+ const plistPath = path50.join(appPath, "Contents", "Info.plist");
121814
+ if (!fs51.existsSync(plistPath)) return null;
121339
121815
  const raw = await runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
121340
121816
  return raw || null;
121341
121817
  }
@@ -121361,8 +121837,8 @@ ${e?.stderr || ""}`;
121361
121837
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
121362
121838
  let resolvedBin = cliBin;
121363
121839
  if (!resolvedBin && appPath && currentOs === "darwin") {
121364
- const bundled = path49.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
121365
- if (provider.cli && fs50.existsSync(bundled)) resolvedBin = bundled;
121840
+ const bundled = path50.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
121841
+ if (provider.cli && fs51.existsSync(bundled)) resolvedBin = bundled;
121366
121842
  }
121367
121843
  info.installed = !!(appPath || resolvedBin);
121368
121844
  info.path = appPath || null;
@@ -121408,8 +121884,8 @@ ${e?.stderr || ""}`;
121408
121884
  return results;
121409
121885
  }
121410
121886
  var http3 = __toESM2(require("http"));
121411
- var fs54 = __toESM2(require("fs"));
121412
- var path53 = __toESM2(require("path"));
121887
+ var fs55 = __toESM2(require("fs"));
121888
+ var path54 = __toESM2(require("path"));
121413
121889
  init_config();
121414
121890
  function generateFiles(type2, name, category, opts = {}) {
121415
121891
  const { cdpPorts, cli, processName, installPath, binary: binary2, extensionId, version: version2 = "0.1" } = opts;
@@ -121754,8 +122230,8 @@ async (params) => {
121754
122230
  }
121755
122231
  init_logger();
121756
122232
  init_builders();
121757
- var fs51 = __toESM2(require("fs"));
121758
- var path50 = __toESM2(require("path"));
122233
+ var fs52 = __toESM2(require("fs"));
122234
+ var path51 = __toESM2(require("path"));
121759
122235
  init_logger();
121760
122236
  async function handleCdpEvaluate(ctx, req, res) {
121761
122237
  const body = await ctx.readBody(req);
@@ -121934,18 +122410,18 @@ async (params) => {
121934
122410
  return;
121935
122411
  }
121936
122412
  let scriptsPath = "";
121937
- const directScripts = path50.join(dir, "scripts.js");
121938
- if (fs51.existsSync(directScripts)) {
122413
+ const directScripts = path51.join(dir, "scripts.js");
122414
+ if (fs52.existsSync(directScripts)) {
121939
122415
  scriptsPath = directScripts;
121940
122416
  } else {
121941
- const scriptsDir = path50.join(dir, "scripts");
121942
- if (fs51.existsSync(scriptsDir)) {
121943
- const versions = fs51.readdirSync(scriptsDir).filter((d) => {
121944
- return fs51.statSync(path50.join(scriptsDir, d)).isDirectory();
122417
+ const scriptsDir = path51.join(dir, "scripts");
122418
+ if (fs52.existsSync(scriptsDir)) {
122419
+ const versions = fs52.readdirSync(scriptsDir).filter((d) => {
122420
+ return fs52.statSync(path51.join(scriptsDir, d)).isDirectory();
121945
122421
  }).sort().reverse();
121946
122422
  for (const ver of versions) {
121947
- const p = path50.join(scriptsDir, ver, "scripts.js");
121948
- if (fs51.existsSync(p)) {
122423
+ const p = path51.join(scriptsDir, ver, "scripts.js");
122424
+ if (fs52.existsSync(p)) {
121949
122425
  scriptsPath = p;
121950
122426
  break;
121951
122427
  }
@@ -121957,7 +122433,7 @@ async (params) => {
121957
122433
  return;
121958
122434
  }
121959
122435
  try {
121960
- const source = fs51.readFileSync(scriptsPath, "utf-8");
122436
+ const source = fs52.readFileSync(scriptsPath, "utf-8");
121961
122437
  const hints = {};
121962
122438
  const funcRegex = /module\.exports\.(\w+)\s*=\s*function\s+\w+\s*\(params\)/g;
121963
122439
  let match;
@@ -122770,8 +123246,8 @@ async (params) => {
122770
123246
  ctx.json(res, 500, { error: `DOM context collection failed: ${e.message}` });
122771
123247
  }
122772
123248
  }
122773
- var fs52 = __toESM2(require("fs"));
122774
- var path51 = __toESM2(require("path"));
123249
+ var fs53 = __toESM2(require("fs"));
123250
+ var path522 = __toESM2(require("path"));
122775
123251
  function slugifyFixtureName(value) {
122776
123252
  const normalized = String(value || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
122777
123253
  return normalized || `fixture-${Date.now()}`;
@@ -122781,15 +123257,15 @@ async (params) => {
122781
123257
  if (!providerDir) {
122782
123258
  throw new Error(`Provider directory not found for '${type2}'`);
122783
123259
  }
122784
- return path51.join(providerDir, "fixtures");
123260
+ return path522.join(providerDir, "fixtures");
122785
123261
  }
122786
123262
  function readCliFixture(ctx, type2, name) {
122787
123263
  const fixtureDir = getCliFixtureDir(ctx, type2);
122788
- const filePath = path51.join(fixtureDir, `${name}.json`);
122789
- if (!fs52.existsSync(filePath)) {
123264
+ const filePath = path522.join(fixtureDir, `${name}.json`);
123265
+ if (!fs53.existsSync(filePath)) {
122790
123266
  throw new Error(`Fixture not found: ${filePath}`);
122791
123267
  }
122792
- return JSON.parse(fs52.readFileSync(filePath, "utf-8"));
123268
+ return JSON.parse(fs53.readFileSync(filePath, "utf-8"));
122793
123269
  }
122794
123270
  function getExerciseTranscriptText(result) {
122795
123271
  const parts = [];
@@ -123534,7 +124010,7 @@ async (params) => {
123534
124010
  return;
123535
124011
  }
123536
124012
  const fixtureDir = getCliFixtureDir(ctx, type2);
123537
- fs52.mkdirSync(fixtureDir, { recursive: true });
124013
+ fs53.mkdirSync(fixtureDir, { recursive: true });
123538
124014
  const name = slugifyFixtureName(String(body?.name || `${type2}-${Date.now()}`));
123539
124015
  const result = await runCliExerciseInternal(ctx, { ...request, type: type2 });
123540
124016
  const fixture = {
@@ -123561,8 +124037,8 @@ async (params) => {
123561
124037
  },
123562
124038
  notes: typeof body?.notes === "string" ? body.notes : void 0
123563
124039
  };
123564
- const filePath = path51.join(fixtureDir, `${name}.json`);
123565
- fs52.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
124040
+ const filePath = path522.join(fixtureDir, `${name}.json`);
124041
+ fs53.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
123566
124042
  ctx.json(res, 200, {
123567
124043
  saved: true,
123568
124044
  name,
@@ -123580,14 +124056,14 @@ async (params) => {
123580
124056
  async function handleCliFixtureList(ctx, type2, _req, res) {
123581
124057
  try {
123582
124058
  const fixtureDir = getCliFixtureDir(ctx, type2);
123583
- if (!fs52.existsSync(fixtureDir)) {
124059
+ if (!fs53.existsSync(fixtureDir)) {
123584
124060
  ctx.json(res, 200, { fixtures: [], count: 0 });
123585
124061
  return;
123586
124062
  }
123587
- const fixtures = fs52.readdirSync(fixtureDir).filter((file2) => file2.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file2) => {
123588
- const fullPath = path51.join(fixtureDir, file2);
124063
+ const fixtures = fs53.readdirSync(fixtureDir).filter((file2) => file2.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file2) => {
124064
+ const fullPath = path522.join(fixtureDir, file2);
123589
124065
  try {
123590
- const raw = JSON.parse(fs52.readFileSync(fullPath, "utf-8"));
124066
+ const raw = JSON.parse(fs53.readFileSync(fullPath, "utf-8"));
123591
124067
  return {
123592
124068
  name: raw.name || file2.replace(/\.json$/i, ""),
123593
124069
  path: fullPath,
@@ -123718,9 +124194,9 @@ async (params) => {
123718
124194
  ctx.json(res, 500, { error: `Raw send failed: ${e.message}` });
123719
124195
  }
123720
124196
  }
123721
- var fs53 = __toESM2(require("fs"));
123722
- var path522 = __toESM2(require("path"));
123723
- var os28 = __toESM2(require("os"));
124197
+ var fs54 = __toESM2(require("fs"));
124198
+ var path53 = __toESM2(require("path"));
124199
+ var os29 = __toESM2(require("os"));
123724
124200
  var import_session_host_core11 = require_dist();
123725
124201
  function getAutoImplPid(ctx) {
123726
124202
  const pid = ctx.autoImplProcess?.pid;
@@ -123767,38 +124243,38 @@ async (params) => {
123767
124243
  return fallback?.type || null;
123768
124244
  }
123769
124245
  function getLatestScriptVersionDir(scriptsDir) {
123770
- if (!fs53.existsSync(scriptsDir)) return null;
123771
- const versions = fs53.readdirSync(scriptsDir).filter((d) => {
124246
+ if (!fs54.existsSync(scriptsDir)) return null;
124247
+ const versions = fs54.readdirSync(scriptsDir).filter((d) => {
123772
124248
  try {
123773
- return fs53.statSync(path522.join(scriptsDir, d)).isDirectory();
124249
+ return fs54.statSync(path53.join(scriptsDir, d)).isDirectory();
123774
124250
  } catch {
123775
124251
  return false;
123776
124252
  }
123777
124253
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
123778
124254
  if (versions.length === 0) return null;
123779
- return path522.join(scriptsDir, versions[0]);
124255
+ return path53.join(scriptsDir, versions[0]);
123780
124256
  }
123781
124257
  function resolveAutoImplWritableProviderDir(ctx, category, type2, requestedDir) {
123782
- const canonicalUserDir = path522.resolve(ctx.providerLoader.getUserProviderDir(category, type2));
123783
- const desiredDir = requestedDir ? path522.resolve(requestedDir) : canonicalUserDir;
123784
- const upstreamRoot = path522.resolve(ctx.providerLoader.getUpstreamDir());
123785
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path522.sep}`)) {
124258
+ const canonicalUserDir = path53.resolve(ctx.providerLoader.getUserProviderDir(category, type2));
124259
+ const desiredDir = requestedDir ? path53.resolve(requestedDir) : canonicalUserDir;
124260
+ const upstreamRoot = path53.resolve(ctx.providerLoader.getUpstreamDir());
124261
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path53.sep}`)) {
123786
124262
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
123787
124263
  }
123788
- if (path522.basename(desiredDir) !== type2) {
124264
+ if (path53.basename(desiredDir) !== type2) {
123789
124265
  return { dir: null, reason: `Requested writable provider directory must end with '${type2}': ${desiredDir}` };
123790
124266
  }
123791
124267
  const sourceDir = ctx.findProviderDir(type2);
123792
124268
  if (!sourceDir) {
123793
124269
  return { dir: null, reason: `Provider source directory not found for '${type2}'` };
123794
124270
  }
123795
- if (!fs53.existsSync(desiredDir)) {
123796
- fs53.mkdirSync(path522.dirname(desiredDir), { recursive: true });
123797
- fs53.cpSync(sourceDir, desiredDir, { recursive: true });
124271
+ if (!fs54.existsSync(desiredDir)) {
124272
+ fs54.mkdirSync(path53.dirname(desiredDir), { recursive: true });
124273
+ fs54.cpSync(sourceDir, desiredDir, { recursive: true });
123798
124274
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
123799
124275
  }
123800
- const providerJson = path522.join(desiredDir, "provider.json");
123801
- if (!fs53.existsSync(providerJson)) {
124276
+ const providerJson = path53.join(desiredDir, "provider.json");
124277
+ if (!fs54.existsSync(providerJson)) {
123802
124278
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
123803
124279
  }
123804
124280
  return { dir: desiredDir };
@@ -123806,15 +124282,15 @@ async (params) => {
123806
124282
  function loadAutoImplReferenceScripts(ctx, referenceType) {
123807
124283
  if (!referenceType) return {};
123808
124284
  const refDir = ctx.findProviderDir(referenceType);
123809
- if (!refDir || !fs53.existsSync(refDir)) return {};
124285
+ if (!refDir || !fs54.existsSync(refDir)) return {};
123810
124286
  const referenceScripts = {};
123811
- const scriptsDir = path522.join(refDir, "scripts");
124287
+ const scriptsDir = path53.join(refDir, "scripts");
123812
124288
  const latestDir = getLatestScriptVersionDir(scriptsDir);
123813
124289
  if (!latestDir) return referenceScripts;
123814
- for (const file2 of fs53.readdirSync(latestDir)) {
124290
+ for (const file2 of fs54.readdirSync(latestDir)) {
123815
124291
  if (!file2.endsWith(".js")) continue;
123816
124292
  try {
123817
- referenceScripts[file2] = fs53.readFileSync(path522.join(latestDir, file2), "utf-8");
124293
+ referenceScripts[file2] = fs54.readFileSync(path53.join(latestDir, file2), "utf-8");
123818
124294
  } catch {
123819
124295
  }
123820
124296
  }
@@ -123922,16 +124398,16 @@ async (params) => {
123922
124398
  });
123923
124399
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
123924
124400
  const prompt = buildAutoImplPrompt(ctx, type2, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
123925
- const tmpDir = path522.join(os28.tmpdir(), "adhdev-autoimpl");
123926
- if (!fs53.existsSync(tmpDir)) fs53.mkdirSync(tmpDir, { recursive: true });
123927
- const promptFile = path522.join(tmpDir, `prompt-${type2}-${Date.now()}.md`);
123928
- fs53.writeFileSync(promptFile, prompt, "utf-8");
124401
+ const tmpDir = path53.join(os29.tmpdir(), "adhdev-autoimpl");
124402
+ if (!fs54.existsSync(tmpDir)) fs54.mkdirSync(tmpDir, { recursive: true });
124403
+ const promptFile = path53.join(tmpDir, `prompt-${type2}-${Date.now()}.md`);
124404
+ fs54.writeFileSync(promptFile, prompt, "utf-8");
123929
124405
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
123930
124406
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
123931
124407
  const spawn7 = agentProvider?.spawn;
123932
124408
  if (!spawn7?.command) {
123933
124409
  try {
123934
- fs53.unlinkSync(promptFile);
124410
+ fs54.unlinkSync(promptFile);
123935
124411
  } catch {
123936
124412
  }
123937
124413
  ctx.json(res, 400, { error: `Agent '${agent}' has no spawn config. Select a CLI provider with a spawn configuration.` });
@@ -124033,7 +124509,7 @@ async (params) => {
124033
124509
  } catch {
124034
124510
  }
124035
124511
  try {
124036
- fs53.unlinkSync(promptFile);
124512
+ fs54.unlinkSync(promptFile);
124037
124513
  } catch {
124038
124514
  }
124039
124515
  ctx.log(`Auto-implement (ACP) ${success2 ? "completed" : "failed"}: ${type2} (exit: ${code})`);
@@ -124077,7 +124553,7 @@ async (params) => {
124077
124553
  const interactiveFlags = ["--yolo", "--interactive", "-i"];
124078
124554
  const baseArgs = [...spawn7.args || []].filter((a) => !interactiveFlags.includes(a));
124079
124555
  let shellCmd;
124080
- const isWin = os28.platform() === "win32";
124556
+ const isWin = os29.platform() === "win32";
124081
124557
  const escapeArg = (a) => isWin ? `"${a.replace(/"/g, '""')}"` : `'${a.replace(/'/g, "'\\''")}'`;
124082
124558
  const promptMode = autoImpl?.promptMode ?? "stdin";
124083
124559
  const extraArgs = autoImpl?.extraArgs ?? [];
@@ -124116,7 +124592,7 @@ async (params) => {
124116
124592
  try {
124117
124593
  const pty = require("node-pty");
124118
124594
  ctx.log(`Auto-implement spawn (PTY): ${shellCmd}`);
124119
- const isWin2 = os28.platform() === "win32";
124595
+ const isWin2 = os29.platform() === "win32";
124120
124596
  child = pty.spawn(isWin2 ? "cmd.exe" : process.env.SHELL || "/bin/zsh", [isWin2 ? "/c" : "-c", shellCmd], {
124121
124597
  name: "xterm-256color",
124122
124598
  cols: import_session_host_core11.DEFAULT_SESSION_HOST_COLS,
@@ -124259,7 +124735,7 @@ async (params) => {
124259
124735
  }
124260
124736
  });
124261
124737
  try {
124262
- fs53.unlinkSync(promptFile);
124738
+ fs54.unlinkSync(promptFile);
124263
124739
  } catch {
124264
124740
  }
124265
124741
  ctx.log(`Auto-implement ${success2 ? "completed" : "failed"}: ${type2} (exit: ${code})${verificationSummary ? ` verify=${verificationSummary.pass ? "pass" : "fail"}` : ""}`);
@@ -124356,7 +124832,7 @@ async (params) => {
124356
124832
  setMode: "set_mode.js"
124357
124833
  };
124358
124834
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
124359
- const scriptsDir = path522.join(providerDir, "scripts");
124835
+ const scriptsDir = path53.join(providerDir, "scripts");
124360
124836
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
124361
124837
  if (latestScriptsDir) {
124362
124838
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -124364,10 +124840,10 @@ async (params) => {
124364
124840
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
124365
124841
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
124366
124842
  lines.push("");
124367
- for (const file2 of fs53.readdirSync(latestScriptsDir)) {
124843
+ for (const file2 of fs54.readdirSync(latestScriptsDir)) {
124368
124844
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
124369
124845
  try {
124370
- const content = fs53.readFileSync(path522.join(latestScriptsDir, file2), "utf-8");
124846
+ const content = fs54.readFileSync(path53.join(latestScriptsDir, file2), "utf-8");
124371
124847
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
124372
124848
  lines.push("```javascript");
124373
124849
  lines.push(content);
@@ -124377,14 +124853,14 @@ async (params) => {
124377
124853
  }
124378
124854
  }
124379
124855
  }
124380
- const refFiles = fs53.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
124856
+ const refFiles = fs54.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
124381
124857
  if (refFiles.length > 0) {
124382
124858
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
124383
124859
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
124384
124860
  lines.push("");
124385
124861
  for (const file2 of refFiles) {
124386
124862
  try {
124387
- const content = fs53.readFileSync(path522.join(latestScriptsDir, file2), "utf-8");
124863
+ const content = fs54.readFileSync(path53.join(latestScriptsDir, file2), "utf-8");
124388
124864
  lines.push(`### \`${file2}\` \u{1F512}`);
124389
124865
  lines.push("```javascript");
124390
124866
  lines.push(content);
@@ -124425,11 +124901,11 @@ async (params) => {
124425
124901
  lines.push("");
124426
124902
  }
124427
124903
  }
124428
- const docsDir = path522.join(providerDir, "../../docs");
124904
+ const docsDir = path53.join(providerDir, "../../docs");
124429
124905
  const loadGuide = (name) => {
124430
124906
  try {
124431
- const p = path522.join(docsDir, name);
124432
- if (fs53.existsSync(p)) return fs53.readFileSync(p, "utf-8");
124907
+ const p = path53.join(docsDir, name);
124908
+ if (fs54.existsSync(p)) return fs54.readFileSync(p, "utf-8");
124433
124909
  } catch {
124434
124910
  }
124435
124911
  return null;
@@ -124665,7 +125141,7 @@ async (params) => {
124665
125141
  parseApproval: "parse_approval.js"
124666
125142
  };
124667
125143
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
124668
- const scriptsDir = path522.join(providerDir, "scripts");
125144
+ const scriptsDir = path53.join(providerDir, "scripts");
124669
125145
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
124670
125146
  if (latestScriptsDir) {
124671
125147
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -124673,11 +125149,11 @@ async (params) => {
124673
125149
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
124674
125150
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
124675
125151
  lines.push("");
124676
- for (const file2 of fs53.readdirSync(latestScriptsDir)) {
125152
+ for (const file2 of fs54.readdirSync(latestScriptsDir)) {
124677
125153
  if (!file2.endsWith(".js")) continue;
124678
125154
  if (!targetFileNames.has(file2)) continue;
124679
125155
  try {
124680
- const content = fs53.readFileSync(path522.join(latestScriptsDir, file2), "utf-8");
125156
+ const content = fs54.readFileSync(path53.join(latestScriptsDir, file2), "utf-8");
124681
125157
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
124682
125158
  lines.push("```javascript");
124683
125159
  lines.push(content);
@@ -124686,14 +125162,14 @@ async (params) => {
124686
125162
  } catch {
124687
125163
  }
124688
125164
  }
124689
- const refFiles = fs53.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
125165
+ const refFiles = fs54.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
124690
125166
  if (refFiles.length > 0) {
124691
125167
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
124692
125168
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
124693
125169
  lines.push("");
124694
125170
  for (const file2 of refFiles) {
124695
125171
  try {
124696
- const content = fs53.readFileSync(path522.join(latestScriptsDir, file2), "utf-8");
125172
+ const content = fs54.readFileSync(path53.join(latestScriptsDir, file2), "utf-8");
124697
125173
  lines.push(`### \`${file2}\` \u{1F512}`);
124698
125174
  lines.push("```javascript");
124699
125175
  lines.push(content);
@@ -124726,11 +125202,11 @@ async (params) => {
124726
125202
  lines.push("");
124727
125203
  }
124728
125204
  }
124729
- const docsDir = path522.join(providerDir, "../../docs");
125205
+ const docsDir = path53.join(providerDir, "../../docs");
124730
125206
  const loadGuide = (name) => {
124731
125207
  try {
124732
- const p = path522.join(docsDir, name);
124733
- if (fs53.existsSync(p)) return fs53.readFileSync(p, "utf-8");
125208
+ const p = path53.join(docsDir, name);
125209
+ if (fs54.existsSync(p)) return fs54.readFileSync(p, "utf-8");
124734
125210
  } catch {
124735
125211
  }
124736
125212
  return null;
@@ -125174,8 +125650,8 @@ data: ${JSON.stringify(msg.data)}
125174
125650
  }
125175
125651
  getEndpointList() {
125176
125652
  return this.routes.map((r) => {
125177
- const path55 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
125178
- return `${r.method.padEnd(5)} ${path55}`;
125653
+ const path56 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
125654
+ return `${r.method.padEnd(5)} ${path56}`;
125179
125655
  });
125180
125656
  }
125181
125657
  async start(port = DEV_SERVER_PORT) {
@@ -125463,12 +125939,12 @@ data: ${JSON.stringify(msg.data)}
125463
125939
  // ─── DevConsole SPA ───
125464
125940
  getConsoleDistDir() {
125465
125941
  const candidates = [
125466
- path53.resolve(__dirname, "../../web-devconsole/dist"),
125467
- path53.resolve(__dirname, "../../../web-devconsole/dist"),
125468
- path53.join(process.cwd(), "packages/web-devconsole/dist")
125942
+ path54.resolve(__dirname, "../../web-devconsole/dist"),
125943
+ path54.resolve(__dirname, "../../../web-devconsole/dist"),
125944
+ path54.join(process.cwd(), "packages/web-devconsole/dist")
125469
125945
  ];
125470
125946
  for (const dir of candidates) {
125471
- if (fs54.existsSync(path53.join(dir, "index.html"))) return dir;
125947
+ if (fs55.existsSync(path54.join(dir, "index.html"))) return dir;
125472
125948
  }
125473
125949
  return null;
125474
125950
  }
@@ -125478,9 +125954,9 @@ data: ${JSON.stringify(msg.data)}
125478
125954
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
125479
125955
  return;
125480
125956
  }
125481
- const htmlPath = path53.join(distDir, "index.html");
125957
+ const htmlPath = path54.join(distDir, "index.html");
125482
125958
  try {
125483
- const html = fs54.readFileSync(htmlPath, "utf-8");
125959
+ const html = fs55.readFileSync(htmlPath, "utf-8");
125484
125960
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
125485
125961
  res.end(html);
125486
125962
  } catch (e) {
@@ -125503,15 +125979,15 @@ data: ${JSON.stringify(msg.data)}
125503
125979
  this.json(res, 404, { error: "Not found" });
125504
125980
  return;
125505
125981
  }
125506
- const safePath = path53.normalize(pathname).replace(/^\.\.\//, "");
125507
- const filePath = path53.join(distDir, safePath);
125982
+ const safePath = path54.normalize(pathname).replace(/^\.\.\//, "");
125983
+ const filePath = path54.join(distDir, safePath);
125508
125984
  if (!filePath.startsWith(distDir)) {
125509
125985
  this.json(res, 403, { error: "Forbidden" });
125510
125986
  return;
125511
125987
  }
125512
125988
  try {
125513
- const content = fs54.readFileSync(filePath);
125514
- const ext = path53.extname(filePath);
125989
+ const content = fs55.readFileSync(filePath);
125990
+ const ext = path54.extname(filePath);
125515
125991
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
125516
125992
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
125517
125993
  res.end(content);
@@ -125619,14 +126095,14 @@ data: ${JSON.stringify(msg.data)}
125619
126095
  const files = [];
125620
126096
  const scan = (d, prefix) => {
125621
126097
  try {
125622
- for (const entry of fs54.readdirSync(d, { withFileTypes: true })) {
126098
+ for (const entry of fs55.readdirSync(d, { withFileTypes: true })) {
125623
126099
  if (entry.name.startsWith(".") || entry.name.endsWith(".bak")) continue;
125624
126100
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
125625
126101
  if (entry.isDirectory()) {
125626
126102
  files.push({ path: rel, size: 0, type: "dir" });
125627
- scan(path53.join(d, entry.name), rel);
126103
+ scan(path54.join(d, entry.name), rel);
125628
126104
  } else {
125629
- const stat2 = fs54.statSync(path53.join(d, entry.name));
126105
+ const stat2 = fs55.statSync(path54.join(d, entry.name));
125630
126106
  files.push({ path: rel, size: stat2.size, type: "file" });
125631
126107
  }
125632
126108
  }
@@ -125649,16 +126125,16 @@ data: ${JSON.stringify(msg.data)}
125649
126125
  this.json(res, 404, { error: `Provider directory not found: ${type2}` });
125650
126126
  return;
125651
126127
  }
125652
- const fullPath = path53.resolve(dir, path53.normalize(filePath));
126128
+ const fullPath = path54.resolve(dir, path54.normalize(filePath));
125653
126129
  if (!fullPath.startsWith(dir)) {
125654
126130
  this.json(res, 403, { error: "Forbidden" });
125655
126131
  return;
125656
126132
  }
125657
- if (!fs54.existsSync(fullPath) || fs54.statSync(fullPath).isDirectory()) {
126133
+ if (!fs55.existsSync(fullPath) || fs55.statSync(fullPath).isDirectory()) {
125658
126134
  this.json(res, 404, { error: `File not found: ${filePath}` });
125659
126135
  return;
125660
126136
  }
125661
- const content = fs54.readFileSync(fullPath, "utf-8");
126137
+ const content = fs55.readFileSync(fullPath, "utf-8");
125662
126138
  this.json(res, 200, { type: type2, path: filePath, content, lines: content.split("\n").length });
125663
126139
  }
125664
126140
  /** POST /api/providers/:type/file — write a file { path, content } */
@@ -125674,15 +126150,15 @@ data: ${JSON.stringify(msg.data)}
125674
126150
  this.json(res, 404, { error: `Provider directory not found: ${type2}` });
125675
126151
  return;
125676
126152
  }
125677
- const fullPath = path53.resolve(dir, path53.normalize(filePath));
126153
+ const fullPath = path54.resolve(dir, path54.normalize(filePath));
125678
126154
  if (!fullPath.startsWith(dir)) {
125679
126155
  this.json(res, 403, { error: "Forbidden" });
125680
126156
  return;
125681
126157
  }
125682
126158
  try {
125683
- if (fs54.existsSync(fullPath)) fs54.copyFileSync(fullPath, fullPath + ".bak");
125684
- fs54.mkdirSync(path53.dirname(fullPath), { recursive: true });
125685
- fs54.writeFileSync(fullPath, content, "utf-8");
126159
+ if (fs55.existsSync(fullPath)) fs55.copyFileSync(fullPath, fullPath + ".bak");
126160
+ fs55.mkdirSync(path54.dirname(fullPath), { recursive: true });
126161
+ fs55.writeFileSync(fullPath, content, "utf-8");
125686
126162
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
125687
126163
  this.providerLoader.reload();
125688
126164
  this.json(res, 200, { saved: true, path: filePath, chars: content.length });
@@ -125698,9 +126174,9 @@ data: ${JSON.stringify(msg.data)}
125698
126174
  return;
125699
126175
  }
125700
126176
  for (const name of ["scripts.js", "provider.json"]) {
125701
- const p = path53.join(dir, name);
125702
- if (fs54.existsSync(p)) {
125703
- const source = fs54.readFileSync(p, "utf-8");
126177
+ const p = path54.join(dir, name);
126178
+ if (fs55.existsSync(p)) {
126179
+ const source = fs55.readFileSync(p, "utf-8");
125704
126180
  this.json(res, 200, { type: type2, path: p, source, lines: source.split("\n").length });
125705
126181
  return;
125706
126182
  }
@@ -125719,11 +126195,11 @@ data: ${JSON.stringify(msg.data)}
125719
126195
  this.json(res, 404, { error: `Provider not found: ${type2}` });
125720
126196
  return;
125721
126197
  }
125722
- const target = fs54.existsSync(path53.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
125723
- const targetPath = path53.join(dir, target);
126198
+ const target = fs55.existsSync(path54.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
126199
+ const targetPath = path54.join(dir, target);
125724
126200
  try {
125725
- if (fs54.existsSync(targetPath)) fs54.copyFileSync(targetPath, targetPath + ".bak");
125726
- fs54.writeFileSync(targetPath, source, "utf-8");
126201
+ if (fs55.existsSync(targetPath)) fs55.copyFileSync(targetPath, targetPath + ".bak");
126202
+ fs55.writeFileSync(targetPath, source, "utf-8");
125727
126203
  this.log(`Saved provider: ${targetPath} (${source.length} chars)`);
125728
126204
  this.providerLoader.reload();
125729
126205
  this.json(res, 200, { saved: true, path: targetPath, chars: source.length });
@@ -125867,21 +126343,21 @@ data: ${JSON.stringify(msg.data)}
125867
126343
  }
125868
126344
  let targetDir;
125869
126345
  targetDir = this.providerLoader.getUserProviderDir(category, type2);
125870
- const jsonPath = path53.join(targetDir, "provider.json");
125871
- if (fs54.existsSync(jsonPath)) {
126346
+ const jsonPath = path54.join(targetDir, "provider.json");
126347
+ if (fs55.existsSync(jsonPath)) {
125872
126348
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
125873
126349
  return;
125874
126350
  }
125875
126351
  try {
125876
126352
  const result = generateFiles(type2, name, category, { cdpPorts, cli, processName, installPath, binary: binary2, extensionId, version: version2, osPaths, processNames });
125877
- fs54.mkdirSync(targetDir, { recursive: true });
125878
- fs54.writeFileSync(jsonPath, result["provider.json"], "utf-8");
126353
+ fs55.mkdirSync(targetDir, { recursive: true });
126354
+ fs55.writeFileSync(jsonPath, result["provider.json"], "utf-8");
125879
126355
  const createdFiles = ["provider.json"];
125880
126356
  if (result.files) {
125881
126357
  for (const [relPath, content] of Object.entries(result.files)) {
125882
- const fullPath = path53.join(targetDir, relPath);
125883
- fs54.mkdirSync(path53.dirname(fullPath), { recursive: true });
125884
- fs54.writeFileSync(fullPath, content, "utf-8");
126358
+ const fullPath = path54.join(targetDir, relPath);
126359
+ fs55.mkdirSync(path54.dirname(fullPath), { recursive: true });
126360
+ fs55.writeFileSync(fullPath, content, "utf-8");
125885
126361
  createdFiles.push(relPath);
125886
126362
  }
125887
126363
  }
@@ -125930,38 +126406,38 @@ data: ${JSON.stringify(msg.data)}
125930
126406
  }
125931
126407
  // ─── Phase 2: Auto-Implement Backend ───
125932
126408
  getLatestScriptVersionDir(scriptsDir) {
125933
- if (!fs54.existsSync(scriptsDir)) return null;
125934
- const versions = fs54.readdirSync(scriptsDir).filter((d) => {
126409
+ if (!fs55.existsSync(scriptsDir)) return null;
126410
+ const versions = fs55.readdirSync(scriptsDir).filter((d) => {
125935
126411
  try {
125936
- return fs54.statSync(path53.join(scriptsDir, d)).isDirectory();
126412
+ return fs55.statSync(path54.join(scriptsDir, d)).isDirectory();
125937
126413
  } catch {
125938
126414
  return false;
125939
126415
  }
125940
126416
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
125941
126417
  if (versions.length === 0) return null;
125942
- return path53.join(scriptsDir, versions[0]);
126418
+ return path54.join(scriptsDir, versions[0]);
125943
126419
  }
125944
126420
  resolveAutoImplWritableProviderDir(category, type2, requestedDir) {
125945
- const canonicalUserDir = path53.resolve(this.providerLoader.getUserProviderDir(category, type2));
125946
- const desiredDir = requestedDir ? path53.resolve(requestedDir) : canonicalUserDir;
125947
- const upstreamRoot = path53.resolve(this.providerLoader.getUpstreamDir());
125948
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path53.sep}`)) {
126421
+ const canonicalUserDir = path54.resolve(this.providerLoader.getUserProviderDir(category, type2));
126422
+ const desiredDir = requestedDir ? path54.resolve(requestedDir) : canonicalUserDir;
126423
+ const upstreamRoot = path54.resolve(this.providerLoader.getUpstreamDir());
126424
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path54.sep}`)) {
125949
126425
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
125950
126426
  }
125951
- if (path53.basename(desiredDir) !== type2) {
126427
+ if (path54.basename(desiredDir) !== type2) {
125952
126428
  return { dir: null, reason: `Requested writable provider directory must end with '${type2}': ${desiredDir}` };
125953
126429
  }
125954
126430
  const sourceDir = this.findProviderDir(type2);
125955
126431
  if (!sourceDir) {
125956
126432
  return { dir: null, reason: `Provider source directory not found for '${type2}'` };
125957
126433
  }
125958
- if (!fs54.existsSync(desiredDir)) {
125959
- fs54.mkdirSync(path53.dirname(desiredDir), { recursive: true });
125960
- fs54.cpSync(sourceDir, desiredDir, { recursive: true });
126434
+ if (!fs55.existsSync(desiredDir)) {
126435
+ fs55.mkdirSync(path54.dirname(desiredDir), { recursive: true });
126436
+ fs55.cpSync(sourceDir, desiredDir, { recursive: true });
125961
126437
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
125962
126438
  }
125963
- const providerJson = path53.join(desiredDir, "provider.json");
125964
- if (!fs54.existsSync(providerJson)) {
126439
+ const providerJson = path54.join(desiredDir, "provider.json");
126440
+ if (!fs55.existsSync(providerJson)) {
125965
126441
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
125966
126442
  }
125967
126443
  return { dir: desiredDir };
@@ -126771,9 +127247,9 @@ data: ${JSON.stringify(msg.data)}
126771
127247
  }
126772
127248
  }
126773
127249
  var import_child_process14 = require("child_process");
126774
- var fs55 = __toESM2(require("fs"));
126775
- var os29 = __toESM2(require("os"));
126776
- var path54 = __toESM2(require("path"));
127250
+ var fs56 = __toESM2(require("fs"));
127251
+ var os30 = __toESM2(require("os"));
127252
+ var path55 = __toESM2(require("path"));
126777
127253
  var import_session_host_core15 = require_dist();
126778
127254
  init_logger();
126779
127255
  init_runtime_defaults();
@@ -126793,18 +127269,18 @@ data: ${JSON.stringify(msg.data)}
126793
127269
  function resolveEntry() {
126794
127270
  if (options.resolveEntryOverride) return options.resolveEntryOverride();
126795
127271
  const packagedCandidates = [
126796
- path54.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
126797
- path54.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
127272
+ path55.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
127273
+ path55.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
126798
127274
  ];
126799
127275
  for (const candidate of packagedCandidates) {
126800
- if (fs55.existsSync(candidate)) {
127276
+ if (fs56.existsSync(candidate)) {
126801
127277
  return candidate;
126802
127278
  }
126803
127279
  }
126804
127280
  return require.resolve("@adhdev/session-host-daemon");
126805
127281
  }
126806
127282
  function pathsEquivalent(left, right) {
126807
- return path54.resolve(left).toLowerCase() === path54.resolve(right).toLowerCase();
127283
+ return path55.resolve(left).toLowerCase() === path55.resolve(right).toLowerCase();
126808
127284
  }
126809
127285
  function getRunningSessionHostScriptPath(pid) {
126810
127286
  const commandLine = getProcessCommandLine(pid);
@@ -126812,13 +127288,13 @@ data: ${JSON.stringify(msg.data)}
126812
127288
  return parseNodeScriptPath(commandLine);
126813
127289
  }
126814
127290
  function getPidFile() {
126815
- return path54.join(instance().configDir, `${appName}-session-host.pid`);
127291
+ return path55.join(instance().configDir, `${appName}-session-host.pid`);
126816
127292
  }
126817
127293
  function getPid() {
126818
127294
  try {
126819
127295
  const pidFile = getPidFile();
126820
- if (!fs55.existsSync(pidFile)) return null;
126821
- const pid = Number.parseInt(fs55.readFileSync(pidFile, "utf8").trim(), 10);
127296
+ if (!fs56.existsSync(pidFile)) return null;
127297
+ const pid = Number.parseInt(fs56.readFileSync(pidFile, "utf8").trim(), 10);
126822
127298
  return Number.isFinite(pid) ? pid : null;
126823
127299
  } catch {
126824
127300
  return null;
@@ -126844,7 +127320,7 @@ data: ${JSON.stringify(msg.data)}
126844
127320
  }
126845
127321
  let portableNode = null;
126846
127322
  try {
126847
- portableNode = findPortableNode22(os29.homedir(), process.execPath, resolveInstanceDir());
127323
+ portableNode = findPortableNode22(os30.homedir(), process.execPath, resolveInstanceDir());
126848
127324
  } catch (error48) {
126849
127325
  LOG2.warn(
126850
127326
  "SessionHost",
@@ -126868,7 +127344,7 @@ data: ${JSON.stringify(msg.data)}
126868
127344
  if (markerIndex === -1) return;
126869
127345
  const activePrefix = entry.slice(0, markerIndex);
126870
127346
  const candidates = resolveConptyPrebuildCandidates(activePrefix);
126871
- const found = candidates.find((candidate) => fs55.existsSync(candidate));
127347
+ const found = candidates.find((candidate) => fs56.existsSync(candidate));
126872
127348
  if (!found) {
126873
127349
  throw new Error(
126874
127350
  `conpty.node missing at boot despite passing the install-time gate \u2014 likely deleted post-install (checked: ${candidates.join(", ")}). Every session-host spawn would crash requiring node-pty; refusing to spawn.`
@@ -126883,9 +127359,9 @@ data: ${JSON.stringify(msg.data)}
126883
127359
  let stdio = "ignore";
126884
127360
  let logFd = null;
126885
127361
  if (options.spawnStdio === "logfile") {
126886
- const logDir = path54.join(instance().configDir, "logs");
126887
- fs55.mkdirSync(logDir, { recursive: true });
126888
- logFd = fs55.openSync(path54.join(logDir, "session-host.log"), "a");
127362
+ const logDir = path55.join(instance().configDir, "logs");
127363
+ fs56.mkdirSync(logDir, { recursive: true });
127364
+ logFd = fs56.openSync(path55.join(logDir, "session-host.log"), "a");
126889
127365
  stdio = ["ignore", logFd, logFd];
126890
127366
  }
126891
127367
  const child = (0, import_child_process14.spawn)(nodeExecutable, [entry], {
@@ -126897,7 +127373,7 @@ data: ${JSON.stringify(msg.data)}
126897
127373
  child.unref();
126898
127374
  if (logFd !== null) {
126899
127375
  try {
126900
- fs55.closeSync(logFd);
127376
+ fs56.closeSync(logFd);
126901
127377
  } catch {
126902
127378
  }
126903
127379
  }
@@ -126915,8 +127391,8 @@ data: ${JSON.stringify(msg.data)}
126915
127391
  const pidFile = getPidFile();
126916
127392
  let keepPidFile = false;
126917
127393
  try {
126918
- if (fs55.existsSync(pidFile)) {
126919
- const pid = Number.parseInt(fs55.readFileSync(pidFile, "utf8").trim(), 10);
127394
+ if (fs56.existsSync(pidFile)) {
127395
+ const pid = Number.parseInt(fs56.readFileSync(pidFile, "utf8").trim(), 10);
126920
127396
  if (Number.isFinite(pid) && pid !== process.pid) {
126921
127397
  const managed = isManagedPid(pid);
126922
127398
  if (managed) {
@@ -126936,7 +127412,7 @@ data: ${JSON.stringify(msg.data)}
126936
127412
  } finally {
126937
127413
  if (!keepPidFile) {
126938
127414
  try {
126939
- fs55.unlinkSync(pidFile);
127415
+ fs56.unlinkSync(pidFile);
126940
127416
  } catch {
126941
127417
  }
126942
127418
  }
@@ -126972,7 +127448,7 @@ data: ${JSON.stringify(msg.data)}
126972
127448
  }
126973
127449
  if (!reported) return;
126974
127450
  if (pathsEquivalent(reported, currentEntry)) return;
126975
- const reportedExists = fs55.existsSync(reported);
127451
+ const reportedExists = fs56.existsSync(reported);
126976
127452
  LOG2.warn(
126977
127453
  "SessionHost",
126978
127454
  `Reachable session-host reports it is running from ${reported}${reportedExists ? "" : " (which no longer exists)"}, but this install runs from ${currentEntry}. That host would fail every create_session loading node-pty from its own prefix; stopping it so a current one is spawned in its place.`
@@ -127199,8 +127675,8 @@ data: ${JSON.stringify(msg.data)}
127199
127675
  const res = await fetch(extension.vsixUrl);
127200
127676
  if (res.ok) {
127201
127677
  const buffer = Buffer.from(await res.arrayBuffer());
127202
- const fs57 = await import("fs");
127203
- fs57.writeFileSync(vsixPath, buffer);
127678
+ const fs58 = await import("fs");
127679
+ fs58.writeFileSync(vsixPath, buffer);
127204
127680
  return new Promise((resolve30) => {
127205
127681
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
127206
127682
  (0, import_child_process15.exec)(cmd, { timeout: 6e4 }, (error48, _stdout, stderr) => {
@@ -127424,11 +127900,11 @@ data: ${JSON.stringify(msg.data)}
127424
127900
  }
127425
127901
  for (const name of names) {
127426
127902
  if (!isPendingEventsFile(name)) continue;
127427
- const path55 = (0, import_path20.join)(dir, name);
127903
+ const path56 = (0, import_path20.join)(dir, name);
127428
127904
  result.filesScanned++;
127429
- const claimed = `${path55}.migrating`;
127905
+ const claimed = `${path56}.migrating`;
127430
127906
  try {
127431
- (0, import_fs19.renameSync)(path55, claimed);
127907
+ (0, import_fs19.renameSync)(path56, claimed);
127432
127908
  } catch {
127433
127909
  continue;
127434
127910
  }
@@ -127438,7 +127914,7 @@ data: ${JSON.stringify(msg.data)}
127438
127914
  } catch (e) {
127439
127915
  LOG2.warn("MeshEvents", `Pending-events migration: cannot read ${name}; leaving it for the next boot: ${e?.message || e}`);
127440
127916
  try {
127441
- (0, import_fs19.renameSync)(claimed, path55);
127917
+ (0, import_fs19.renameSync)(claimed, path56);
127442
127918
  } catch {
127443
127919
  }
127444
127920
  result.filesRetained++;
@@ -127453,7 +127929,7 @@ data: ${JSON.stringify(msg.data)}
127453
127929
  }
127454
127930
  if (!allImported) {
127455
127931
  try {
127456
- (0, import_fs19.renameSync)(claimed, path55);
127932
+ (0, import_fs19.renameSync)(claimed, path56);
127457
127933
  } catch {
127458
127934
  }
127459
127935
  result.filesRetained++;
@@ -128049,10 +128525,10 @@ ${upgradeFailureNotice.notice}${supersededHint}`);
128049
128525
  init_parse_approval();
128050
128526
  init_visible_region();
128051
128527
  init_parse_session();
128052
- var import_node_fs6 = require("fs");
128528
+ var import_node_fs7 = require("fs");
128053
128529
  var import_node_path6 = require("path");
128054
128530
  init_provider_cli_shared();
128055
- var import_node_fs7 = require("fs");
128531
+ var import_node_fs8 = require("fs");
128056
128532
  var import_node_path7 = require("path");
128057
128533
  init_manifest();
128058
128534
  var V1_PRIMITIVE_CATALOG = Object.freeze({
@@ -128125,7 +128601,7 @@ ${upgradeFailureNotice.notice}${supersededHint}`);
128125
128601
  Object.values(V1_PRIMITIVE_CATALOG).flat()
128126
128602
  );
128127
128603
  var V1_CONTRACT_VERSION = "1.0.0";
128128
- var fs56 = __toESM2(require("fs"));
128604
+ var fs57 = __toESM2(require("fs"));
128129
128605
  var import_chalk2 = __toESM2((init_source(), __toCommonJS(source_exports)));
128130
128606
  init_dist();
128131
128607
  var CLAUDE_NO_API_LINE = "Claude has no quota API \u2014 adhdev borrows your statusLine to read it.";
@@ -128236,7 +128712,7 @@ ${upgradeFailureNotice.notice}${supersededHint}`);
128236
128712
  console.log(import_chalk2.default.gray(` Backup: ${status.paths.backupFile}`));
128237
128713
  let snapshotMtimeMs = null;
128238
128714
  try {
128239
- snapshotMtimeMs = fs56.statSync(status.paths.snapshotFile).mtimeMs;
128715
+ snapshotMtimeMs = fs57.statSync(status.paths.snapshotFile).mtimeMs;
128240
128716
  } catch {
128241
128717
  }
128242
128718
  console.log(import_chalk2.default.gray(