@adhdev/daemon-standalone 0.9.82-rc.411 → 0.9.82-rc.413

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
@@ -29727,9 +29727,9 @@ var require_dist3 = __commonJS({
29727
29727
  };
29728
29728
  var __copyProps2 = (to, from, except, desc) => {
29729
29729
  if (from && typeof from === "object" || typeof from === "function") {
29730
- for (let key of __getOwnPropNames2(from))
29731
- if (!__hasOwnProp2.call(to, key) && key !== except)
29732
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
29730
+ for (let key2 of __getOwnPropNames2(from))
29731
+ if (!__hasOwnProp2.call(to, key2) && key2 !== except)
29732
+ __defProp2(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc2(from, key2)) || desc.enumerable });
29733
29733
  }
29734
29734
  return to;
29735
29735
  };
@@ -29747,14 +29747,6 @@ var require_dist3 = __commonJS({
29747
29747
  const trimmed = value.trim();
29748
29748
  return MESH_SCHEDULING_STRATEGIES.includes(trimmed) ? trimmed : DEFAULT_MESH_SCHEDULING_STRATEGY;
29749
29749
  }
29750
- function normalizeMeshDistribution(value) {
29751
- if (typeof value !== "string") return DEFAULT_MESH_DISTRIBUTION;
29752
- const trimmed = value.trim();
29753
- return MESH_DISTRIBUTIONS.includes(trimmed) ? trimmed : DEFAULT_MESH_DISTRIBUTION;
29754
- }
29755
- function distributionToStrategy(distribution) {
29756
- return distribution === "spread" ? "least_loaded" : "first_eligible";
29757
- }
29758
29750
  function resolveNodeSchedulingPriority(nodePolicy) {
29759
29751
  const raw = Number(nodePolicy?.schedulingPriority);
29760
29752
  return Number.isFinite(raw) ? raw : 0;
@@ -29843,8 +29835,6 @@ var require_dist3 = __commonJS({
29843
29835
  }
29844
29836
  var MESH_SCHEDULING_STRATEGIES;
29845
29837
  var DEFAULT_MESH_SCHEDULING_STRATEGY;
29846
- var MESH_DISTRIBUTIONS;
29847
- var DEFAULT_MESH_DISTRIBUTION;
29848
29838
  var MESH_CONVERGE_REFINE_TAG;
29849
29839
  var MESH_CONVERGE_FAST_FORWARD_TAG;
29850
29840
  var DEFAULT_MESH_POLICY;
@@ -29864,8 +29854,6 @@ var require_dist3 = __commonJS({
29864
29854
  "priority_only"
29865
29855
  ];
29866
29856
  DEFAULT_MESH_SCHEDULING_STRATEGY = "first_eligible";
29867
- MESH_DISTRIBUTIONS = ["spread", "in_order"];
29868
- DEFAULT_MESH_DISTRIBUTION = "spread";
29869
29857
  MESH_CONVERGE_REFINE_TAG = "converge=refine";
29870
29858
  MESH_CONVERGE_FAST_FORWARD_TAG = "converge=fast_forward";
29871
29859
  DEFAULT_MESH_POLICY = {
@@ -30127,10 +30115,10 @@ var require_dist3 = __commonJS({
30127
30115
  }
30128
30116
  function getDaemonBuildInfo() {
30129
30117
  if (cached2) return cached2;
30130
- const commit = readInjected(true ? "69cd9c459ec9efafe19a05f66899bb791d6e0561" : void 0) ?? "unknown";
30131
- const commitShort = readInjected(true ? "69cd9c45" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30132
- const version2 = readInjected(true ? "0.9.82-rc.411" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30133
- const builtAt = readInjected(true ? "2026-06-28T09:11:57.766Z" : void 0);
30118
+ const commit = readInjected(true ? "7a774e95a82354f5357197b3c84f63e68b5f7a5d" : void 0) ?? "unknown";
30119
+ const commitShort = readInjected(true ? "7a774e95" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30120
+ const version2 = readInjected(true ? "0.9.82-rc.413" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30121
+ const builtAt = readInjected(true ? "2026-06-28T11:49:09.563Z" : void 0);
30134
30122
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
30135
30123
  return cached2;
30136
30124
  }
@@ -30146,18 +30134,18 @@ var require_dist3 = __commonJS({
30146
30134
  function isStringArray(value) {
30147
30135
  return Array.isArray(value) && value.every((v) => typeof v === "string" && v.length > 0);
30148
30136
  }
30149
- function validateTarget(value, key, errors) {
30137
+ function validateTarget(value, key2, errors) {
30150
30138
  if (!isRecord(value)) {
30151
- errors.push(`impactTargets.${key} must be an object`);
30139
+ errors.push(`impactTargets.${key2} must be an object`);
30152
30140
  return void 0;
30153
30141
  }
30154
30142
  const { recommendedCommand } = value;
30155
30143
  if (typeof recommendedCommand !== "string" || !recommendedCommand.length) {
30156
- errors.push(`impactTargets.${key}.recommendedCommand must be a non-empty string`);
30144
+ errors.push(`impactTargets.${key2}.recommendedCommand must be a non-empty string`);
30157
30145
  return void 0;
30158
30146
  }
30159
30147
  for (const k of Object.keys(value)) {
30160
- if (k !== "recommendedCommand") errors.push(`impactTargets.${key}.${k} is not a recognized field (only recommendedCommand)`);
30148
+ if (k !== "recommendedCommand") errors.push(`impactTargets.${key2}.${k} is not a recognized field (only recommendedCommand)`);
30161
30149
  }
30162
30150
  return { recommendedCommand };
30163
30151
  }
@@ -30184,20 +30172,20 @@ var require_dist3 = __commonJS({
30184
30172
  errors.push("impactTargets must be an object");
30185
30173
  } else {
30186
30174
  const targets = {};
30187
- for (const key of Object.keys(raw.impactTargets)) {
30188
- if (key !== "daemon" && key !== "web" && key !== "none") {
30189
- errors.push(`impactTargets.${key} is not a recognized impact kind (daemon|web|none)`);
30175
+ for (const key2 of Object.keys(raw.impactTargets)) {
30176
+ if (key2 !== "daemon" && key2 !== "web" && key2 !== "none") {
30177
+ errors.push(`impactTargets.${key2} is not a recognized impact kind (daemon|web|none)`);
30190
30178
  continue;
30191
30179
  }
30192
- const target = validateTarget(raw.impactTargets[key], key, errors);
30193
- if (target) targets[key] = target;
30180
+ const target = validateTarget(raw.impactTargets[key2], key2, errors);
30181
+ if (target) targets[key2] = target;
30194
30182
  }
30195
30183
  if (Object.keys(targets).length) config2.impactTargets = targets;
30196
30184
  }
30197
30185
  }
30198
- for (const key of Object.keys(raw)) {
30199
- if (!["daemonRuntimePackages", "webOnlyPackages", "nonRuntimeRootFilePatterns", "impactTargets"].includes(key)) {
30200
- errors.push(`unknown config key '${key}'`);
30186
+ for (const key2 of Object.keys(raw)) {
30187
+ if (!["daemonRuntimePackages", "webOnlyPackages", "nonRuntimeRootFilePatterns", "impactTargets"].includes(key2)) {
30188
+ errors.push(`unknown config key '${key2}'`);
30201
30189
  }
30202
30190
  }
30203
30191
  return { valid: errors.length === 0, errors, config: errors.length === 0 ? config2 : void 0 };
@@ -30531,12 +30519,12 @@ var require_dist3 = __commonJS({
30531
30519
  return { config: null, sourceKey: "forced-default" };
30532
30520
  }
30533
30521
  if (options.changeImpactConfig !== void 0) {
30534
- let key = "injected";
30522
+ let key2 = "injected";
30535
30523
  try {
30536
- key = `injected:${JSON.stringify(options.changeImpactConfig)}`;
30524
+ key2 = `injected:${JSON.stringify(options.changeImpactConfig)}`;
30537
30525
  } catch {
30538
30526
  }
30539
- return { config: options.changeImpactConfig, sourceKey: key };
30527
+ return { config: options.changeImpactConfig, sourceKey: key2 };
30540
30528
  }
30541
30529
  if (!repoRoot) {
30542
30530
  return { config: null, sourceKey: "no-repo-root" };
@@ -32115,9 +32103,9 @@ ${error48.message || ""}`;
32115
32103
  ].filter(Boolean)));
32116
32104
  const nextSessionNotificationDismissals = { ...state.sessionNotificationDismissals || {} };
32117
32105
  const nextSessionNotificationUnreadOverrides = { ...state.sessionNotificationUnreadOverrides || {} };
32118
- for (const key of dismissalKeys) {
32119
- nextSessionNotificationDismissals[key] = dismissalId;
32120
- delete nextSessionNotificationUnreadOverrides[key];
32106
+ for (const key2 of dismissalKeys) {
32107
+ nextSessionNotificationDismissals[key2] = dismissalId;
32108
+ delete nextSessionNotificationUnreadOverrides[key2];
32121
32109
  }
32122
32110
  return {
32123
32111
  ...state,
@@ -32134,9 +32122,9 @@ ${error48.message || ""}`;
32134
32122
  ].filter(Boolean)));
32135
32123
  const nextSessionNotificationDismissals = { ...state.sessionNotificationDismissals || {} };
32136
32124
  const nextSessionNotificationUnreadOverrides = { ...state.sessionNotificationUnreadOverrides || {} };
32137
- for (const key of unreadKeys) {
32138
- nextSessionNotificationUnreadOverrides[key] = unreadId;
32139
- delete nextSessionNotificationDismissals[key];
32125
+ for (const key2 of unreadKeys) {
32126
+ nextSessionNotificationUnreadOverrides[key2] = unreadId;
32127
+ delete nextSessionNotificationDismissals[key2];
32140
32128
  }
32141
32129
  return {
32142
32130
  ...state,
@@ -32200,11 +32188,11 @@ ${error48.message || ""}`;
32200
32188
  const nextSessionReadMarkers = { ...prevMarkers };
32201
32189
  const nextSessionNotificationDismissals = { ...state.sessionNotificationDismissals || {} };
32202
32190
  const nextSessionNotificationUnreadOverrides = { ...state.sessionNotificationUnreadOverrides || {} };
32203
- for (const key of readKeys) {
32204
- nextSessionReads[key] = Math.max(prev[key] || 0, seenAt);
32205
- if (nextMarker) nextSessionReadMarkers[key] = nextMarker;
32206
- delete nextSessionNotificationDismissals[key];
32207
- delete nextSessionNotificationUnreadOverrides[key];
32191
+ for (const key2 of readKeys) {
32192
+ nextSessionReads[key2] = Math.max(prev[key2] || 0, seenAt);
32193
+ if (nextMarker) nextSessionReadMarkers[key2] = nextMarker;
32194
+ delete nextSessionNotificationDismissals[key2];
32195
+ delete nextSessionNotificationUnreadOverrides[key2];
32208
32196
  }
32209
32197
  return {
32210
32198
  ...state,
@@ -32905,6 +32893,12 @@ ${error48.message || ""}`;
32905
32893
  }
32906
32894
  return trimmed;
32907
32895
  }
32896
+ function canonicalDaemonId(id) {
32897
+ const core = machineCoreFromDaemonId(id);
32898
+ if (!core) return void 0;
32899
+ if (!core.startsWith("mach_")) return core;
32900
+ return `daemon_${core}`;
32901
+ }
32908
32902
  function daemonIdsEquivalent(a, b) {
32909
32903
  const coreA = machineCoreFromDaemonId(a);
32910
32904
  const coreB = machineCoreFromDaemonId(b);
@@ -33064,8 +33058,8 @@ Default branch: \`${mesh.defaultBranch}\`` : ""}`);
33064
33058
  rules: buildRulesSection(coordinatorCliType),
33065
33059
  toolExposurePreflight: TOOL_EXPOSURE_PREFLIGHT_SECTION
33066
33060
  };
33067
- return template.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g, (m, key) => {
33068
- return Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : m;
33061
+ return template.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g, (m, key2) => {
33062
+ return Object.prototype.hasOwnProperty.call(replacements, key2) ? replacements[key2] : m;
33069
33063
  });
33070
33064
  }
33071
33065
  function buildNodeStatusSection(nodes) {
@@ -34505,6 +34499,31 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
34505
34499
  ]);
34506
34500
  }
34507
34501
  });
34502
+ function key(meshId, taskId) {
34503
+ return `${meshId}::${taskId}`;
34504
+ }
34505
+ function beginTaskDispatchInFlight(meshId, taskId) {
34506
+ if (!meshId || !taskId) return false;
34507
+ const k = key(meshId, taskId);
34508
+ if (inFlight.has(k)) return false;
34509
+ inFlight.add(k);
34510
+ return true;
34511
+ }
34512
+ function isTaskDispatchInFlight(meshId, taskId) {
34513
+ if (!meshId || !taskId) return false;
34514
+ return inFlight.has(key(meshId, taskId));
34515
+ }
34516
+ function endTaskDispatchInFlight(meshId, taskId) {
34517
+ if (!meshId || !taskId) return;
34518
+ inFlight.delete(key(meshId, taskId));
34519
+ }
34520
+ var inFlight;
34521
+ var init_mesh_task_inflight = __esm2({
34522
+ "src/mesh/mesh-task-inflight.ts"() {
34523
+ "use strict";
34524
+ inFlight = /* @__PURE__ */ new Set();
34525
+ }
34526
+ });
34508
34527
  var mesh_work_queue_exports = {};
34509
34528
  __export2(mesh_work_queue_exports, {
34510
34529
  ACTIVE_MESH_QUEUE_STATUSES: () => ACTIVE_MESH_QUEUE_STATUSES,
@@ -34770,14 +34789,14 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
34770
34789
  if (!Array.isArray(raw)) return void 0;
34771
34790
  return raw.find((type) => typeof type === "string" && type.trim())?.trim();
34772
34791
  }
34773
- function readNodeOverride(node, key) {
34792
+ function readNodeOverride(node, key2) {
34774
34793
  const overrides = node?.userOverrides;
34775
34794
  if (!overrides || typeof overrides !== "object" || Array.isArray(overrides)) return null;
34776
- const value = overrides[key];
34795
+ const value = overrides[key2];
34777
34796
  return typeof value === "string" && value.trim() ? value.trim() : null;
34778
34797
  }
34779
- function readNodeReporter(node, key) {
34780
- const value = key === "platform" ? node?.reportedPlatform : node?.reportedArch;
34798
+ function readNodeReporter(node, key2) {
34799
+ const value = key2 === "platform" ? node?.reportedPlatform : node?.reportedArch;
34781
34800
  return typeof value === "string" && value.trim() ? value.trim() : null;
34782
34801
  }
34783
34802
  function buildMeshNodeCapabilityTags(node, providerType) {
@@ -34996,6 +35015,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
34996
35015
  if (!entry) return null;
34997
35016
  entry.status = status;
34998
35017
  MeshRuntimeStore.getInstance().updateQueueEntry(entry);
35018
+ if (status !== "assigned") endTaskDispatchInFlight(meshId, taskId);
34999
35019
  if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, taskId);
35000
35020
  return entry;
35001
35021
  });
@@ -35020,6 +35040,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
35020
35040
  entry.cancelledAt = now;
35021
35041
  if (opts?.reason) entry.cancelReason = opts.reason;
35022
35042
  MeshRuntimeStore.getInstance().updateQueueEntry(entry);
35043
+ endTaskDispatchInFlight(meshId, taskId);
35023
35044
  propagateDependencyFailure(meshId, taskId);
35024
35045
  return entry;
35025
35046
  });
@@ -35029,6 +35050,11 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
35029
35050
  return withQueueLock(meshId, () => {
35030
35051
  const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
35031
35052
  if (!entry) return null;
35053
+ if (!opts?.force && isTaskDispatchInFlight(meshId, taskId)) {
35054
+ LOG2.warn("MeshQueue", `Refusing to requeue task ${taskId} on mesh ${meshId}: it is actively dispatched/generating (single-flight in-flight). Requeueing now would open a duplicate second dispatch into another session. Pass force to override.`);
35055
+ return entry;
35056
+ }
35057
+ endTaskDispatchInFlight(meshId, taskId);
35032
35058
  const currentCount = entry.requeueCount || 0;
35033
35059
  const maxRetries = opts?.maxRetries ?? entry.maxRetries ?? 1;
35034
35060
  if (!opts?.force && currentCount >= maxRetries) {
@@ -35073,6 +35099,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
35073
35099
  delete entry.dispatchTimestamp;
35074
35100
  entry.strandedReclaimCount = reclaims;
35075
35101
  entry.updatedAt = now;
35102
+ endTaskDispatchInFlight(meshId, taskId);
35076
35103
  if (reclaims > MAX_STRANDED_RECLAIMS) {
35077
35104
  entry.status = "failed";
35078
35105
  entry.cancelReason = `stranded_dispatch_unrecovered: reclaimed ${reclaims - 1} time(s) without a confirmed dispatch`;
@@ -35116,6 +35143,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
35116
35143
  }
35117
35144
  entry.status = status;
35118
35145
  store.updateQueueEntry(entry);
35146
+ if (status !== "assigned") endTaskDispatchInFlight(meshId, entry.id);
35119
35147
  if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, entry.id);
35120
35148
  return entry;
35121
35149
  });
@@ -35240,6 +35268,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
35240
35268
  init_logger();
35241
35269
  init_mesh_ledger();
35242
35270
  init_mesh_delivery_policy();
35271
+ init_mesh_task_inflight();
35243
35272
  ACTIVE_MESH_QUEUE_STATUSES = ["pending", "assigned"];
35244
35273
  HISTORICAL_MESH_QUEUE_STATUSES = ["completed", "failed", "cancelled"];
35245
35274
  MESH_TASK_MODES = ["code_change", "validation", "live_debug_readonly", "launch_app", "convergence"];
@@ -36882,6 +36911,9 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36882
36911
  summarizeMissionTasks: () => summarizeMissionTasks,
36883
36912
  upsertMeshMission: () => upsertMeshMission
36884
36913
  });
36914
+ function summarizeGoalForLedger(goal) {
36915
+ return goal.length > LEDGER_GOAL_SUMMARY_MAX ? goal.slice(0, LEDGER_GOAL_SUMMARY_MAX) : goal;
36916
+ }
36885
36917
  function normalizeMissionStatus(value) {
36886
36918
  return MESH_MISSION_STATUSES.includes(value) ? value : "active";
36887
36919
  }
@@ -36894,6 +36926,8 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36894
36926
  const id = typeof input.id === "string" && input.id.trim() ? input.id.trim() : (0, import_crypto7.randomUUID)();
36895
36927
  const store = MeshRuntimeStore.getInstance();
36896
36928
  const existing = store.getMission(meshId, id);
36929
+ const prevStatus = existing ? normalizeMissionStatus(existing.status) : null;
36930
+ const prevGoal = existing?.goal ?? "";
36897
36931
  const record2 = {
36898
36932
  id,
36899
36933
  meshId,
@@ -36903,7 +36937,61 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36903
36937
  };
36904
36938
  store.upsertMission(record2);
36905
36939
  const saved = store.getMission(meshId, id);
36906
- return { ...saved, status: normalizeMissionStatus(saved.status) };
36940
+ const result = { ...saved, status: normalizeMissionStatus(saved.status) };
36941
+ appendMissionLedgerEntries(meshId, {
36942
+ isCreate: !existing,
36943
+ record: result,
36944
+ prevStatus,
36945
+ prevGoal
36946
+ });
36947
+ return result;
36948
+ }
36949
+ function appendMissionLedgerEntries(meshId, args) {
36950
+ const { isCreate, record: record2, prevStatus, prevGoal } = args;
36951
+ try {
36952
+ if (isCreate) {
36953
+ const goal = record2.goal ?? "";
36954
+ appendLedgerEntry(meshId, {
36955
+ kind: "mission_created",
36956
+ payload: {
36957
+ missionId: record2.id,
36958
+ title: record2.title,
36959
+ goalSummary: summarizeGoalForLedger(goal),
36960
+ goalLength: goal.length,
36961
+ goalTruncated: goal.length > LEDGER_GOAL_SUMMARY_MAX,
36962
+ status: record2.status
36963
+ }
36964
+ });
36965
+ return;
36966
+ }
36967
+ if (prevStatus !== null && prevStatus !== record2.status) {
36968
+ appendLedgerEntry(meshId, {
36969
+ kind: "mission_status_changed",
36970
+ payload: {
36971
+ missionId: record2.id,
36972
+ title: record2.title,
36973
+ fromStatus: prevStatus,
36974
+ toStatus: record2.status
36975
+ }
36976
+ });
36977
+ }
36978
+ const nextGoal = record2.goal ?? "";
36979
+ if (nextGoal !== prevGoal) {
36980
+ appendLedgerEntry(meshId, {
36981
+ kind: "mission_goal_updated",
36982
+ payload: {
36983
+ missionId: record2.id,
36984
+ title: record2.title,
36985
+ prevGoalSummary: summarizeGoalForLedger(prevGoal),
36986
+ nextGoalSummary: summarizeGoalForLedger(nextGoal),
36987
+ prevGoalLength: prevGoal.length,
36988
+ nextGoalLength: nextGoal.length,
36989
+ goalTruncated: prevGoal.length > LEDGER_GOAL_SUMMARY_MAX || nextGoal.length > LEDGER_GOAL_SUMMARY_MAX
36990
+ }
36991
+ });
36992
+ }
36993
+ } catch {
36994
+ }
36907
36995
  }
36908
36996
  function getMeshMissions(meshId, statuses) {
36909
36997
  return MeshRuntimeStore.getInstance().getMissions(meshId, statuses).map((m) => ({ ...m, status: normalizeMissionStatus(m.status) }));
@@ -37008,6 +37096,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
37008
37096
  return lines.join("\n");
37009
37097
  }
37010
37098
  var import_crypto7;
37099
+ var LEDGER_GOAL_SUMMARY_MAX;
37011
37100
  var MESH_MISSION_STATUSES;
37012
37101
  var GOAL_PREVIEW_MAX;
37013
37102
  var COMPACT_STATUS_GOAL_PREVIEW_MAX;
@@ -37018,6 +37107,8 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
37018
37107
  init_mesh_runtime_store();
37019
37108
  init_mesh_work_queue();
37020
37109
  init_mesh_task_stats();
37110
+ init_mesh_ledger();
37111
+ LEDGER_GOAL_SUMMARY_MAX = 200;
37021
37112
  MESH_MISSION_STATUSES = ["active", "paused", "completed", "abandoned"];
37022
37113
  GOAL_PREVIEW_MAX = 120;
37023
37114
  COMPACT_STATUS_GOAL_PREVIEW_MAX = 80;
@@ -37243,7 +37334,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
37243
37334
  timestamp: entry.timestamp,
37244
37335
  ...entry.sessionId ? { sessionId: entry.sessionId } : {},
37245
37336
  bootstrap: readRecord3(validationSummary?.bootstrap),
37246
- validation: validationSummary ? Object.fromEntries(Object.entries(validationSummary).filter(([key]) => key !== "bootstrap")) : null,
37337
+ validation: validationSummary ? Object.fromEntries(Object.entries(validationSummary).filter(([key2]) => key2 !== "bootstrap")) : null,
37247
37338
  checkpoint: readRecord3(result?.checkpoint),
37248
37339
  worker: null,
37249
37340
  ...readRecord3(payload.finalBranchConvergenceState) ?? readRecord3(result?.finalBranchConvergenceState) ? { finalBranchConvergenceState: readRecord3(payload.finalBranchConvergenceState) ?? readRecord3(result?.finalBranchConvergenceState) } : {},
@@ -37506,7 +37597,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
37506
37597
  };
37507
37598
  }
37508
37599
  function renderMeshCoordinatorTemplate(template, values) {
37509
- return template.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g, (_, key) => values[key] || "");
37600
+ return template.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g, (_, key2) => values[key2] || "");
37510
37601
  }
37511
37602
  function replaceLegacyCliCommandMcpArgs(command, args) {
37512
37603
  return command.replace(
@@ -37515,9 +37606,9 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
37515
37606
  );
37516
37607
  }
37517
37608
  function resolveHermesCoordinatorHome(meshId, workspace) {
37518
- const key = `${meshId || "mesh"}
37609
+ const key2 = `${meshId || "mesh"}
37519
37610
  ${(0, import_node_path.resolve)(workspace || os42.tmpdir())}`;
37520
- const hash2 = shortHash(key);
37611
+ const hash2 = shortHash(key2);
37521
37612
  return (0, import_node_path.join)(os42.tmpdir(), `adhdev-hermes-mesh-coordinator-${hash2}`);
37522
37613
  }
37523
37614
  function resolveMcpConfigPath(configPath, workspace) {
@@ -37993,9 +38084,9 @@ ${rendered}`, "utf-8");
37993
38084
  const seen = /* @__PURE__ */ new Set();
37994
38085
  const suggestions = [];
37995
38086
  for (const entry of [...collectProjectContextSuggestions(mesh), ...collectPackageScriptSuggestions(workspace)]) {
37996
- const key = `${entry.command} ${(entry.args || []).join(" ")}`.trim();
37997
- if (seen.has(key)) continue;
37998
- seen.add(key);
38087
+ const key2 = `${entry.command} ${(entry.args || []).join(" ")}`.trim();
38088
+ if (seen.has(key2)) continue;
38089
+ seen.add(key2);
37999
38090
  suggestions.push(entry);
38000
38091
  }
38001
38092
  return {
@@ -38491,6 +38582,218 @@ ${rendered}`, "utf-8");
38491
38582
  OUTPUT_SUMMARY_CHARS = 2e3;
38492
38583
  }
38493
38584
  });
38585
+ var mesh_json_config_exports = {};
38586
+ __export2(mesh_json_config_exports, {
38587
+ MESH_JSON_CONFIG_LOCATIONS: () => MESH_JSON_CONFIG_LOCATIONS,
38588
+ MESH_JSON_CONFIG_SCHEMA: () => MESH_JSON_CONFIG_SCHEMA,
38589
+ applyRepoMeshConfig: () => applyRepoMeshConfig,
38590
+ buildMeshJsonConfigScaffold: () => buildMeshJsonConfigScaffold,
38591
+ loadRepoMeshJsonConfig: () => loadRepoMeshJsonConfig,
38592
+ mergeEffectiveCoordinatorConfig: () => mergeEffectiveCoordinatorConfig,
38593
+ mergeEffectiveOperatingNotes: () => mergeEffectiveOperatingNotes,
38594
+ normalizeRepoMeshDeclarativeConfig: () => normalizeRepoMeshDeclarativeConfig,
38595
+ serializeMeshJsonConfigScaffold: () => serializeMeshJsonConfigScaffold
38596
+ });
38597
+ function isRecord3(value) {
38598
+ return !!value && typeof value === "object" && !Array.isArray(value);
38599
+ }
38600
+ function parseConfigText4(path43, text) {
38601
+ if (/\.json$/i.test(path43)) return JSON.parse(text);
38602
+ return yaml4.load(text);
38603
+ }
38604
+ function normalizeOperatingNote(value) {
38605
+ if (!isRecord3(value)) return null;
38606
+ const text = typeof value.text === "string" ? value.text.trim() : "";
38607
+ if (!text) return null;
38608
+ const category = value.category === "provider_quirk" || value.category === "pattern_to_avoid" || value.category === "recovery_lesson" ? value.category : void 0;
38609
+ return {
38610
+ text,
38611
+ ...category ? { category } : {},
38612
+ ...typeof value.createdAt === "string" ? { createdAt: value.createdAt } : {},
38613
+ ...typeof value.sourceCoordinator === "string" ? { sourceCoordinator: value.sourceCoordinator } : {}
38614
+ };
38615
+ }
38616
+ function normalizeRepoMeshDeclarativeConfig(parsed) {
38617
+ const errors = [];
38618
+ if (!isRecord3(parsed)) return { valid: false, errors: ["config must be an object"] };
38619
+ if (parsed.version !== 1) {
38620
+ return { valid: false, errors: [`version must be 1 (got ${JSON.stringify(parsed.version)})`] };
38621
+ }
38622
+ const config2 = { version: 1 };
38623
+ if (parsed.coordinator !== void 0) {
38624
+ if (isRecord3(parsed.coordinator)) {
38625
+ const coord = {};
38626
+ const c = parsed.coordinator;
38627
+ if (typeof c.systemPromptOverride === "string") coord.systemPromptOverride = c.systemPromptOverride;
38628
+ if (typeof c.systemPromptAppend === "string") coord.systemPromptAppend = c.systemPromptAppend;
38629
+ if (Number.isFinite(Number(c.maxPromptChars))) coord.maxPromptChars = Number(c.maxPromptChars);
38630
+ config2.coordinator = coord;
38631
+ } else {
38632
+ errors.push("coordinator must be an object when provided");
38633
+ }
38634
+ }
38635
+ if (parsed.operatingNotes !== void 0) {
38636
+ if (Array.isArray(parsed.operatingNotes)) {
38637
+ const notes = parsed.operatingNotes.map(normalizeOperatingNote).filter((n) => n !== null);
38638
+ if (notes.length) config2.operatingNotes = notes;
38639
+ } else {
38640
+ errors.push("operatingNotes must be an array when provided");
38641
+ }
38642
+ }
38643
+ if (parsed.limits !== void 0) {
38644
+ if (isRecord3(parsed.limits)) {
38645
+ const limits = {};
38646
+ if (Number.isFinite(Number(parsed.limits.maxNoteChars))) limits.maxNoteChars = Number(parsed.limits.maxNoteChars);
38647
+ if (Number.isFinite(Number(parsed.limits.maxNotes))) limits.maxNotes = Number(parsed.limits.maxNotes);
38648
+ if (Object.keys(limits).length) config2.limits = limits;
38649
+ } else {
38650
+ errors.push("limits must be an object when provided");
38651
+ }
38652
+ }
38653
+ return { valid: true, config: config2, errors };
38654
+ }
38655
+ function loadRepoMeshJsonConfig(workspace) {
38656
+ const bases = [];
38657
+ const ws = typeof workspace === "string" ? workspace.trim() : "";
38658
+ if (ws) bases.push(ws);
38659
+ let cwd = "";
38660
+ try {
38661
+ cwd = process.cwd();
38662
+ } catch {
38663
+ }
38664
+ if (cwd && cwd !== ws) bases.push(cwd);
38665
+ for (const base of bases) {
38666
+ for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
38667
+ const configPath = (0, import_path9.join)(base, relative5);
38668
+ if (!(0, import_fs10.existsSync)(configPath)) continue;
38669
+ try {
38670
+ const parsed = parseConfigText4(configPath, (0, import_fs10.readFileSync)(configPath, "utf-8"));
38671
+ const result = normalizeRepoMeshDeclarativeConfig(parsed);
38672
+ if (!result.valid || !result.config) {
38673
+ return { source: relative5, sourceType: "invalid", path: configPath, error: result.errors.join("; ") };
38674
+ }
38675
+ return { config: result.config, source: relative5, sourceType: "repo_file", path: configPath };
38676
+ } catch (error48) {
38677
+ return { source: relative5, sourceType: "invalid", path: configPath, error: error48?.message || String(error48) };
38678
+ }
38679
+ }
38680
+ }
38681
+ return {
38682
+ source: "unavailable",
38683
+ sourceType: "unavailable",
38684
+ error: `No repo mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`
38685
+ };
38686
+ }
38687
+ function mergeEffectiveCoordinatorConfig(repoCoord, localCoord) {
38688
+ const out = { ...localCoord || {} };
38689
+ const localOverride = localCoord?.systemPromptOverride?.trim();
38690
+ const repoOverride = repoCoord?.systemPromptOverride?.trim();
38691
+ if (localOverride) {
38692
+ out.systemPromptOverride = localCoord.systemPromptOverride;
38693
+ } else if (repoOverride) {
38694
+ out.systemPromptOverride = repoCoord.systemPromptOverride;
38695
+ } else {
38696
+ delete out.systemPromptOverride;
38697
+ }
38698
+ const repoAppend = repoCoord?.systemPromptAppend?.trim() ? repoCoord.systemPromptAppend.trim() : "";
38699
+ const localAppendRaw = localCoord?.systemPromptAppend ?? localCoord?.systemPromptSuffix;
38700
+ const localAppend = localAppendRaw?.trim() ? localAppendRaw.trim() : "";
38701
+ const stacked = [repoAppend, localAppend].filter(Boolean).join("\n\n");
38702
+ if (stacked) {
38703
+ out.systemPromptAppend = stacked;
38704
+ delete out.systemPromptSuffix;
38705
+ }
38706
+ return out;
38707
+ }
38708
+ function mergeEffectiveOperatingNotes(repoNotes, ledgerNotes) {
38709
+ const usable = (notes) => Array.isArray(notes) ? notes.filter((n) => n && typeof n.text === "string" && n.text.trim()) : [];
38710
+ const repo = usable(repoNotes);
38711
+ const ledger = usable(ledgerNotes);
38712
+ const ledgerTexts = new Set(ledger.map((n) => n.text.trim()));
38713
+ const repoKept = repo.filter((n) => !ledgerTexts.has(n.text.trim()));
38714
+ const merged = [...repoKept, ...ledger];
38715
+ return merged.length ? merged : void 0;
38716
+ }
38717
+ function applyRepoMeshConfig(mesh, repoConfig) {
38718
+ if (!repoConfig) return mesh;
38719
+ return {
38720
+ ...mesh,
38721
+ coordinator: mergeEffectiveCoordinatorConfig(repoConfig.coordinator, mesh.coordinator)
38722
+ };
38723
+ }
38724
+ function buildMeshJsonConfigScaffold(mesh) {
38725
+ const scaffold = { version: 1 };
38726
+ const coord = {};
38727
+ const override = mesh.coordinator?.systemPromptOverride;
38728
+ if (typeof override === "string" && override.trim()) coord.systemPromptOverride = override;
38729
+ const append = mesh.coordinator?.systemPromptAppend ?? mesh.coordinator?.systemPromptSuffix;
38730
+ if (typeof append === "string" && append.trim()) coord.systemPromptAppend = append;
38731
+ if (Object.keys(coord).length) scaffold.coordinator = coord;
38732
+ return scaffold;
38733
+ }
38734
+ function serializeMeshJsonConfigScaffold(config2) {
38735
+ return JSON.stringify(config2, null, 2);
38736
+ }
38737
+ var import_fs10;
38738
+ var import_path9;
38739
+ var yaml4;
38740
+ var MESH_JSON_CONFIG_LOCATIONS;
38741
+ var MESH_JSON_CONFIG_SCHEMA;
38742
+ var init_mesh_json_config = __esm2({
38743
+ "src/config/mesh-json-config.ts"() {
38744
+ "use strict";
38745
+ import_fs10 = require("fs");
38746
+ import_path9 = require("path");
38747
+ yaml4 = __toESM2(require_js_yaml());
38748
+ MESH_JSON_CONFIG_LOCATIONS = [
38749
+ ".adhdev/mesh.json",
38750
+ ".adhdev/mesh.yaml",
38751
+ ".adhdev/mesh.yml"
38752
+ ];
38753
+ MESH_JSON_CONFIG_SCHEMA = {
38754
+ $schema: "https://json-schema.org/draft/2020-12/schema",
38755
+ title: "ADHDev Repo Mesh Declarative Config",
38756
+ type: "object",
38757
+ additionalProperties: false,
38758
+ required: ["version"],
38759
+ properties: {
38760
+ version: { const: 1 },
38761
+ coordinator: {
38762
+ type: "object",
38763
+ additionalProperties: false,
38764
+ properties: {
38765
+ systemPromptOverride: { type: "string" },
38766
+ systemPromptAppend: { type: "string" },
38767
+ maxPromptChars: { type: "number", minimum: 1 }
38768
+ }
38769
+ },
38770
+ operatingNotes: {
38771
+ type: "array",
38772
+ maxItems: 200,
38773
+ items: {
38774
+ type: "object",
38775
+ additionalProperties: false,
38776
+ required: ["text"],
38777
+ properties: {
38778
+ text: { type: "string", minLength: 1 },
38779
+ category: { enum: ["provider_quirk", "pattern_to_avoid", "recovery_lesson"] },
38780
+ createdAt: { type: "string" },
38781
+ sourceCoordinator: { type: "string" }
38782
+ }
38783
+ }
38784
+ },
38785
+ limits: {
38786
+ type: "object",
38787
+ additionalProperties: false,
38788
+ properties: {
38789
+ maxNoteChars: { type: "number", minimum: 1 },
38790
+ maxNotes: { type: "number", minimum: 1 }
38791
+ }
38792
+ }
38793
+ }
38794
+ };
38795
+ }
38796
+ });
38494
38797
  async function fastForwardMeshNode(args) {
38495
38798
  const workspace = typeof args.workspace === "string" ? args.workspace.trim() : "";
38496
38799
  const nodeId = normalizeOptionalString(args.nodeId);
@@ -39953,9 +40256,9 @@ Next step: ${nextStep}`;
39953
40256
  const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
39954
40257
  if (coordinatorDaemonId) {
39955
40258
  const safeDaemon = coordinatorDaemonId.replace(/[^a-zA-Z0-9_-]/g, "_");
39956
- return (0, import_path9.join)(getLedgerDir(), `${safe}-${safeDaemon}.pending-events.jsonl`);
40259
+ return (0, import_path10.join)(getLedgerDir(), `${safe}-${safeDaemon}.pending-events.jsonl`);
39957
40260
  }
39958
- return (0, import_path9.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
40261
+ return (0, import_path10.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
39959
40262
  }
39960
40263
  function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
39961
40264
  if (!meshId) return [];
@@ -39964,9 +40267,9 @@ Next step: ${nextStep}`;
39964
40267
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
39965
40268
  const events = [];
39966
40269
  for (const path43 of paths) {
39967
- if (!(0, import_fs10.existsSync)(path43)) continue;
40270
+ if (!(0, import_fs11.existsSync)(path43)) continue;
39968
40271
  try {
39969
- const raw = (0, import_fs10.readFileSync)(path43, "utf-8");
40272
+ const raw = (0, import_fs11.readFileSync)(path43, "utf-8");
39970
40273
  const parsed = raw.split("\n").filter(Boolean).flatMap((line) => {
39971
40274
  try {
39972
40275
  return [JSON.parse(line)];
@@ -40041,9 +40344,9 @@ Next step: ${nextStep}`;
40041
40344
  }
40042
40345
  function trimPendingEventsIfNeeded(path43) {
40043
40346
  try {
40044
- if (!(0, import_fs10.existsSync)(path43)) return;
40045
- if ((0, import_fs10.statSync)(path43).size <= MAX_PENDING_EVENTS_BYTES) return;
40046
- const lines = (0, import_fs10.readFileSync)(path43, "utf-8").split("\n").filter(Boolean);
40347
+ if (!(0, import_fs11.existsSync)(path43)) return;
40348
+ if ((0, import_fs11.statSync)(path43).size <= MAX_PENDING_EVENTS_BYTES) return;
40349
+ const lines = (0, import_fs11.readFileSync)(path43, "utf-8").split("\n").filter(Boolean);
40047
40350
  if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
40048
40351
  const dropped = lines.slice(0, lines.length - MAX_PENDING_EVENTS_KEEP);
40049
40352
  for (const line of dropped) {
@@ -40076,7 +40379,7 @@ Next step: ${nextStep}`;
40076
40379
  LOG2.warn("MeshEvents", `Failed to ledger-record trim-dropped ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
40077
40380
  }
40078
40381
  }
40079
- (0, import_fs10.writeFileSync)(path43, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
40382
+ (0, import_fs11.writeFileSync)(path43, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
40080
40383
  } catch {
40081
40384
  }
40082
40385
  }
@@ -40108,7 +40411,7 @@ Next step: ${nextStep}`;
40108
40411
  try {
40109
40412
  const path43 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
40110
40413
  trimPendingEventsIfNeeded(path43);
40111
- (0, import_fs10.appendFileSync)(path43, JSON.stringify(event) + "\n", "utf-8");
40414
+ (0, import_fs11.appendFileSync)(path43, JSON.stringify(event) + "\n", "utf-8");
40112
40415
  } catch (e) {
40113
40416
  if (!sqliteOk) throw e;
40114
40417
  LOG2.warn("MeshEvents", `JSONL append failed for mesh ${event.meshId}; SQLite holds the event: ${e?.message || e}`);
@@ -40122,20 +40425,20 @@ Next step: ${nextStep}`;
40122
40425
  function atomicDrainFile(path43) {
40123
40426
  const tmpPath = `${path43}.draining`;
40124
40427
  try {
40125
- (0, import_fs10.renameSync)(path43, tmpPath);
40428
+ (0, import_fs11.renameSync)(path43, tmpPath);
40126
40429
  } catch {
40127
40430
  return null;
40128
40431
  }
40129
40432
  try {
40130
- const content = (0, import_fs10.readFileSync)(tmpPath, "utf-8");
40433
+ const content = (0, import_fs11.readFileSync)(tmpPath, "utf-8");
40131
40434
  try {
40132
- (0, import_fs10.unlinkSync)(tmpPath);
40435
+ (0, import_fs11.unlinkSync)(tmpPath);
40133
40436
  } catch {
40134
40437
  }
40135
40438
  return content;
40136
40439
  } catch {
40137
40440
  try {
40138
- (0, import_fs10.unlinkSync)(tmpPath);
40441
+ (0, import_fs11.unlinkSync)(tmpPath);
40139
40442
  } catch {
40140
40443
  }
40141
40444
  return null;
@@ -40144,16 +40447,16 @@ Next step: ${nextStep}`;
40144
40447
  function selectiveDrainFile(path43, predicate) {
40145
40448
  const tmpPath = `${path43}.draining`;
40146
40449
  try {
40147
- (0, import_fs10.renameSync)(path43, tmpPath);
40450
+ (0, import_fs11.renameSync)(path43, tmpPath);
40148
40451
  } catch {
40149
40452
  return [];
40150
40453
  }
40151
40454
  let content;
40152
40455
  try {
40153
- content = (0, import_fs10.readFileSync)(tmpPath, "utf-8");
40456
+ content = (0, import_fs11.readFileSync)(tmpPath, "utf-8");
40154
40457
  } catch {
40155
40458
  try {
40156
- (0, import_fs10.unlinkSync)(tmpPath);
40459
+ (0, import_fs11.unlinkSync)(tmpPath);
40157
40460
  } catch {
40158
40461
  }
40159
40462
  return [];
@@ -40176,12 +40479,12 @@ Next step: ${nextStep}`;
40176
40479
  }
40177
40480
  try {
40178
40481
  if (keptLines.length > 0) {
40179
- (0, import_fs10.writeFileSync)(path43, keptLines.join("\n") + "\n", "utf-8");
40482
+ (0, import_fs11.writeFileSync)(path43, keptLines.join("\n") + "\n", "utf-8");
40180
40483
  }
40181
- (0, import_fs10.unlinkSync)(tmpPath);
40484
+ (0, import_fs11.unlinkSync)(tmpPath);
40182
40485
  } catch {
40183
40486
  try {
40184
- if ((0, import_fs10.existsSync)(tmpPath) && !(0, import_fs10.existsSync)(path43)) (0, import_fs10.renameSync)(tmpPath, path43);
40487
+ if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path43)) (0, import_fs11.renameSync)(tmpPath, path43);
40185
40488
  } catch {
40186
40489
  }
40187
40490
  return [];
@@ -40276,14 +40579,14 @@ Next step: ${nextStep}`;
40276
40579
  }
40277
40580
  const paths = coordinatorDaemonId ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
40278
40581
  for (const path43 of paths) {
40279
- if ((0, import_fs10.existsSync)(path43)) try {
40280
- (0, import_fs10.unlinkSync)(path43);
40582
+ if ((0, import_fs11.existsSync)(path43)) try {
40583
+ (0, import_fs11.unlinkSync)(path43);
40281
40584
  } catch {
40282
40585
  }
40283
40586
  }
40284
40587
  }
40285
- var import_fs10;
40286
- var import_path9;
40588
+ var import_fs11;
40589
+ var import_path10;
40287
40590
  var import_crypto8;
40288
40591
  var REFINE_TERMINAL_EVENTS;
40289
40592
  var TERMINAL_COMPLETION_EVENTS;
@@ -40292,8 +40595,8 @@ Next step: ${nextStep}`;
40292
40595
  var init_mesh_events_pending = __esm2({
40293
40596
  "src/mesh/mesh-events-pending.ts"() {
40294
40597
  "use strict";
40295
- import_fs10 = require("fs");
40296
- import_path9 = require("path");
40598
+ import_fs11 = require("fs");
40599
+ import_path10 = require("path");
40297
40600
  import_crypto8 = require("crypto");
40298
40601
  init_logger();
40299
40602
  init_mesh_ledger();
@@ -41070,7 +41373,7 @@ Next step: ${nextStep}`;
41070
41373
  if (isExplicitCommandPath(trimmed)) {
41071
41374
  const expanded = expandHome(trimmed);
41072
41375
  const candidate = path12.isAbsolute(expanded) ? expanded : path12.resolve(expanded);
41073
- return (0, import_fs11.existsSync)(candidate) ? candidate : null;
41376
+ return (0, import_fs12.existsSync)(candidate) ? candidate : null;
41074
41377
  }
41075
41378
  return null;
41076
41379
  }
@@ -41080,7 +41383,7 @@ Next step: ${nextStep}`;
41080
41383
  const whichResult = await execAsync(`${whichCmd} ${shellQuote(command)}`);
41081
41384
  if (whichResult) return whichResult.split("\n")[0];
41082
41385
  const resolved = findBinary(command);
41083
- if (path12.isAbsolute(resolved) && (0, import_fs11.existsSync)(resolved)) return resolved;
41386
+ if (path12.isAbsolute(resolved) && (0, import_fs12.existsSync)(resolved)) return resolved;
41084
41387
  return null;
41085
41388
  }
41086
41389
  function execAsync(cmd, timeoutMs = 5e3) {
@@ -41178,14 +41481,14 @@ Next step: ${nextStep}`;
41178
41481
  var import_child_process2;
41179
41482
  var os62;
41180
41483
  var path12;
41181
- var import_fs11;
41484
+ var import_fs12;
41182
41485
  var init_cli_detector = __esm2({
41183
41486
  "src/detection/cli-detector.ts"() {
41184
41487
  "use strict";
41185
41488
  import_child_process2 = require("child_process");
41186
41489
  os62 = __toESM2(require("os"));
41187
41490
  path12 = __toESM2(require("path"));
41188
- import_fs11 = require("fs");
41491
+ import_fs12 = require("fs");
41189
41492
  init_provider_cli_shared();
41190
41493
  }
41191
41494
  });
@@ -41301,348 +41604,9 @@ Next step: ${nextStep}`;
41301
41604
  "use strict";
41302
41605
  }
41303
41606
  });
41304
- var mesh_json_config_exports = {};
41305
- __export2(mesh_json_config_exports, {
41306
- MESH_JSON_CONFIG_LOCATIONS: () => MESH_JSON_CONFIG_LOCATIONS,
41307
- MESH_JSON_CONFIG_SCHEMA: () => MESH_JSON_CONFIG_SCHEMA,
41308
- __resetMeshJsonConfigCacheForTests: () => __resetMeshJsonConfigCacheForTests,
41309
- applyRepoMeshConfig: () => applyRepoMeshConfig,
41310
- buildMeshJsonConfigScaffold: () => buildMeshJsonConfigScaffold,
41311
- diffPolicyFromDefault: () => diffPolicyFromDefault,
41312
- loadMeshJsonConfig: () => loadMeshJsonConfig,
41313
- loadRepoMeshJsonConfig: () => loadRepoMeshJsonConfig,
41314
- mergeEffectiveCoordinatorConfig: () => mergeEffectiveCoordinatorConfig,
41315
- mergeEffectiveMeshPolicy: () => mergeEffectiveMeshPolicy,
41316
- mergeEffectiveOperatingNotes: () => mergeEffectiveOperatingNotes,
41317
- normalizeRepoMeshDeclarativeConfig: () => normalizeRepoMeshDeclarativeConfig,
41318
- serializeMeshJsonConfigScaffold: () => serializeMeshJsonConfigScaffold,
41319
- validateMeshJsonConfig: () => validateMeshJsonConfig
41320
- });
41321
- function isRecord3(value) {
41322
- return !!value && typeof value === "object" && !Array.isArray(value);
41323
- }
41324
- function parseConfigText4(path43, text) {
41325
- if (/\.json$/i.test(path43)) return JSON.parse(text);
41326
- return yaml4.load(text);
41327
- }
41328
- function normalizeOperatingNote(value) {
41329
- if (!isRecord3(value)) return null;
41330
- const text = typeof value.text === "string" ? value.text.trim() : "";
41331
- if (!text) return null;
41332
- const category = value.category === "provider_quirk" || value.category === "pattern_to_avoid" || value.category === "recovery_lesson" ? value.category : void 0;
41333
- return {
41334
- text,
41335
- ...category ? { category } : {},
41336
- ...typeof value.createdAt === "string" ? { createdAt: value.createdAt } : {},
41337
- ...typeof value.sourceCoordinator === "string" ? { sourceCoordinator: value.sourceCoordinator } : {}
41338
- };
41339
- }
41340
- function normalizeRepoMeshDeclarativeConfig(parsed) {
41341
- const errors = [];
41342
- if (!isRecord3(parsed)) return { valid: false, errors: ["config must be an object"] };
41343
- if (parsed.version !== 1) {
41344
- return { valid: false, errors: [`version must be 1 (got ${JSON.stringify(parsed.version)})`] };
41345
- }
41346
- const config2 = { version: 1 };
41347
- if (parsed.policy !== void 0) {
41348
- if (isRecord3(parsed.policy)) {
41349
- config2.policy = parsed.policy;
41350
- } else {
41351
- errors.push("policy must be an object when provided");
41352
- }
41353
- }
41354
- if (parsed.coordinator !== void 0) {
41355
- if (isRecord3(parsed.coordinator)) {
41356
- const coord = {};
41357
- const c = parsed.coordinator;
41358
- if (typeof c.systemPromptOverride === "string") coord.systemPromptOverride = c.systemPromptOverride;
41359
- if (typeof c.systemPromptAppend === "string") coord.systemPromptAppend = c.systemPromptAppend;
41360
- if (Number.isFinite(Number(c.maxPromptChars))) coord.maxPromptChars = Number(c.maxPromptChars);
41361
- config2.coordinator = coord;
41362
- } else {
41363
- errors.push("coordinator must be an object when provided");
41364
- }
41365
- }
41366
- if (parsed.operatingNotes !== void 0) {
41367
- if (Array.isArray(parsed.operatingNotes)) {
41368
- const notes = parsed.operatingNotes.map(normalizeOperatingNote).filter((n) => n !== null);
41369
- if (notes.length) config2.operatingNotes = notes;
41370
- } else {
41371
- errors.push("operatingNotes must be an array when provided");
41372
- }
41373
- }
41374
- if (parsed.limits !== void 0) {
41375
- if (isRecord3(parsed.limits)) {
41376
- const limits = {};
41377
- if (Number.isFinite(Number(parsed.limits.maxNoteChars))) limits.maxNoteChars = Number(parsed.limits.maxNoteChars);
41378
- if (Number.isFinite(Number(parsed.limits.maxNotes))) limits.maxNotes = Number(parsed.limits.maxNotes);
41379
- if (Object.keys(limits).length) config2.limits = limits;
41380
- } else {
41381
- errors.push("limits must be an object when provided");
41382
- }
41383
- }
41384
- return { valid: true, config: config2, errors };
41385
- }
41386
- function loadRepoMeshJsonConfig(workspace) {
41387
- const bases = [];
41388
- const ws = typeof workspace === "string" ? workspace.trim() : "";
41389
- if (ws) bases.push(ws);
41390
- let cwd = "";
41391
- try {
41392
- cwd = process.cwd();
41393
- } catch {
41394
- }
41395
- if (cwd && cwd !== ws) bases.push(cwd);
41396
- for (const base of bases) {
41397
- for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
41398
- const configPath = (0, import_path10.join)(base, relative5);
41399
- if (!(0, import_fs12.existsSync)(configPath)) continue;
41400
- try {
41401
- const parsed = parseConfigText4(configPath, (0, import_fs12.readFileSync)(configPath, "utf-8"));
41402
- const result = normalizeRepoMeshDeclarativeConfig(parsed);
41403
- if (!result.valid || !result.config) {
41404
- return { source: relative5, sourceType: "invalid", path: configPath, error: result.errors.join("; ") };
41405
- }
41406
- return { config: result.config, source: relative5, sourceType: "repo_file", path: configPath };
41407
- } catch (error48) {
41408
- return { source: relative5, sourceType: "invalid", path: configPath, error: error48?.message || String(error48) };
41409
- }
41410
- }
41411
- }
41412
- return {
41413
- source: "unavailable",
41414
- sourceType: "unavailable",
41415
- error: `No repo mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`
41416
- };
41417
- }
41418
- function deepEqual(a, b) {
41419
- if (a === b) return true;
41420
- try {
41421
- return JSON.stringify(a) === JSON.stringify(b);
41422
- } catch {
41423
- return false;
41424
- }
41607
+ function localCoordinatorDaemonId() {
41608
+ return canonicalDaemonId(readNonEmptyString2(loadConfig2().machineId));
41425
41609
  }
41426
- function diffPolicyFromDefault(local) {
41427
- if (!local || typeof local !== "object") return {};
41428
- const out = {};
41429
- const def = mergeAndNormalizePolicy(void 0, void 0);
41430
- for (const [key, value] of Object.entries(local)) {
41431
- if (value === void 0) continue;
41432
- if (!deepEqual(value, def[key])) out[key] = value;
41433
- }
41434
- return out;
41435
- }
41436
- function mergeEffectiveMeshPolicy(repoPolicy, localPolicy) {
41437
- const repoMerged = mergeAndNormalizePolicy(void 0, repoPolicy);
41438
- const localOverrides = diffPolicyFromDefault(localPolicy);
41439
- return mergeAndNormalizePolicy(repoMerged, localOverrides);
41440
- }
41441
- function mergeEffectiveCoordinatorConfig(repoCoord, localCoord) {
41442
- const out = { ...localCoord || {} };
41443
- const localOverride = localCoord?.systemPromptOverride?.trim();
41444
- const repoOverride = repoCoord?.systemPromptOverride?.trim();
41445
- if (localOverride) {
41446
- out.systemPromptOverride = localCoord.systemPromptOverride;
41447
- } else if (repoOverride) {
41448
- out.systemPromptOverride = repoCoord.systemPromptOverride;
41449
- } else {
41450
- delete out.systemPromptOverride;
41451
- }
41452
- const repoAppend = repoCoord?.systemPromptAppend?.trim() ? repoCoord.systemPromptAppend.trim() : "";
41453
- const localAppendRaw = localCoord?.systemPromptAppend ?? localCoord?.systemPromptSuffix;
41454
- const localAppend = localAppendRaw?.trim() ? localAppendRaw.trim() : "";
41455
- const stacked = [repoAppend, localAppend].filter(Boolean).join("\n\n");
41456
- if (stacked) {
41457
- out.systemPromptAppend = stacked;
41458
- delete out.systemPromptSuffix;
41459
- }
41460
- return out;
41461
- }
41462
- function mergeEffectiveOperatingNotes(repoNotes, ledgerNotes) {
41463
- const usable = (notes) => Array.isArray(notes) ? notes.filter((n) => n && typeof n.text === "string" && n.text.trim()) : [];
41464
- const repo = usable(repoNotes);
41465
- const ledger = usable(ledgerNotes);
41466
- const ledgerTexts = new Set(ledger.map((n) => n.text.trim()));
41467
- const repoKept = repo.filter((n) => !ledgerTexts.has(n.text.trim()));
41468
- const merged = [...repoKept, ...ledger];
41469
- return merged.length ? merged : void 0;
41470
- }
41471
- function applyRepoMeshConfig(mesh, repoConfig) {
41472
- if (!repoConfig) return mesh;
41473
- return {
41474
- ...mesh,
41475
- policy: mergeEffectiveMeshPolicy(repoConfig.policy, mesh.policy),
41476
- coordinator: mergeEffectiveCoordinatorConfig(repoConfig.coordinator, mesh.coordinator)
41477
- };
41478
- }
41479
- function buildMeshJsonConfigScaffold(mesh) {
41480
- const scaffold = {
41481
- version: 1,
41482
- policy: mergeAndNormalizePolicy(void 0, mesh.policy)
41483
- };
41484
- const coord = {};
41485
- const override = mesh.coordinator?.systemPromptOverride;
41486
- if (typeof override === "string" && override.trim()) coord.systemPromptOverride = override;
41487
- const append = mesh.coordinator?.systemPromptAppend ?? mesh.coordinator?.systemPromptSuffix;
41488
- if (typeof append === "string" && append.trim()) coord.systemPromptAppend = append;
41489
- if (Object.keys(coord).length) scaffold.coordinator = coord;
41490
- return scaffold;
41491
- }
41492
- function serializeMeshJsonConfigScaffold(config2) {
41493
- return JSON.stringify(config2, null, 2);
41494
- }
41495
- function validateMeshJsonConfig(raw, source = "inline") {
41496
- const errors = [];
41497
- if (!isRecord3(raw)) {
41498
- return { valid: false, errors: [`${source}: config must be an object`] };
41499
- }
41500
- const config2 = {};
41501
- const policy = raw.policy;
41502
- const schedulingRaw = isRecord3(policy) ? policy.scheduling : void 0;
41503
- if (schedulingRaw !== void 0) {
41504
- if (!isRecord3(schedulingRaw)) {
41505
- errors.push("policy.scheduling must be an object");
41506
- } else {
41507
- const scheduling = {};
41508
- if (schedulingRaw.distribution !== void 0) {
41509
- if (typeof schedulingRaw.distribution !== "string" || !["spread", "in_order"].includes(schedulingRaw.distribution.trim())) {
41510
- errors.push("policy.scheduling.distribution must be 'spread' or 'in_order'");
41511
- } else {
41512
- scheduling.distribution = normalizeMeshDistribution(schedulingRaw.distribution);
41513
- }
41514
- }
41515
- if (schedulingRaw.maxParallel !== void 0) {
41516
- const n = Number(schedulingRaw.maxParallel);
41517
- if (!Number.isFinite(n) || n < MESH_MAX_PARALLEL_TASKS_MIN || n > MESH_MAX_PARALLEL_TASKS_MAX) {
41518
- errors.push(`policy.scheduling.maxParallel must be a number in [${MESH_MAX_PARALLEL_TASKS_MIN}, ${MESH_MAX_PARALLEL_TASKS_MAX}]`);
41519
- } else {
41520
- scheduling.maxParallel = Math.floor(n);
41521
- }
41522
- }
41523
- if (schedulingRaw.readonlyMultiplier !== void 0) {
41524
- const n = Number(schedulingRaw.readonlyMultiplier);
41525
- if (!Number.isFinite(n) || n < 1) {
41526
- errors.push("policy.scheduling.readonlyMultiplier must be a number >= 1");
41527
- } else {
41528
- scheduling.readonlyMultiplier = Math.floor(n);
41529
- }
41530
- }
41531
- for (const key of Object.keys(schedulingRaw)) {
41532
- if (!["distribution", "maxParallel", "readonlyMultiplier"].includes(key)) {
41533
- errors.push(`policy.scheduling.${key} is not a recognized field`);
41534
- }
41535
- }
41536
- if (Object.keys(scheduling).length) config2.scheduling = scheduling;
41537
- }
41538
- }
41539
- return { valid: errors.length === 0, errors, config: errors.length === 0 ? config2 : void 0 };
41540
- }
41541
- function loadMeshJsonConfig(repoRoot) {
41542
- if (!repoRoot) {
41543
- return { source: "unavailable", sourceType: "unavailable", error: "no repo root", sourceKey: "unavailable" };
41544
- }
41545
- for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
41546
- const configPath = (0, import_path10.join)(repoRoot, relative5);
41547
- if (!(0, import_fs12.existsSync)(configPath)) continue;
41548
- let mtimeMs = 0;
41549
- try {
41550
- mtimeMs = (0, import_fs12.statSync)(configPath).mtimeMs;
41551
- } catch {
41552
- mtimeMs = 0;
41553
- }
41554
- const cacheKey = configPath;
41555
- const sourceKey = `file:${configPath}:${mtimeMs}`;
41556
- const cached3 = cache.get(cacheKey);
41557
- if (cached3 && cached3.sourceKey === sourceKey) return cached3.result;
41558
- let result;
41559
- try {
41560
- const text = (0, import_fs12.readFileSync)(configPath, "utf-8");
41561
- const parsed = parseConfigText4(configPath, text);
41562
- const validation = validateMeshJsonConfig(parsed, relative5);
41563
- result = validation.valid ? { config: validation.config, source: relative5, sourceType: "repo_file", path: configPath, sourceKey } : { source: relative5, sourceType: "invalid", path: configPath, error: validation.errors.join("; "), sourceKey: `invalid:${configPath}:${mtimeMs}` };
41564
- } catch (error48) {
41565
- result = { source: relative5, sourceType: "invalid", path: configPath, error: error48?.message || String(error48), sourceKey: `error:${configPath}` };
41566
- }
41567
- cache.set(cacheKey, { sourceKey: result.sourceKey, result });
41568
- return result;
41569
- }
41570
- return {
41571
- source: "unavailable",
41572
- sourceType: "unavailable",
41573
- error: `No .adhdev/mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`,
41574
- sourceKey: "unavailable"
41575
- };
41576
- }
41577
- function __resetMeshJsonConfigCacheForTests() {
41578
- cache.clear();
41579
- }
41580
- var import_fs12;
41581
- var import_path10;
41582
- var yaml4;
41583
- var MESH_JSON_CONFIG_LOCATIONS;
41584
- var MESH_JSON_CONFIG_SCHEMA;
41585
- var cache;
41586
- var init_mesh_json_config = __esm2({
41587
- "src/config/mesh-json-config.ts"() {
41588
- "use strict";
41589
- import_fs12 = require("fs");
41590
- import_path10 = require("path");
41591
- yaml4 = __toESM2(require_js_yaml());
41592
- init_repo_mesh_types();
41593
- MESH_JSON_CONFIG_LOCATIONS = [
41594
- ".adhdev/mesh.json",
41595
- ".adhdev/mesh.yaml",
41596
- ".adhdev/mesh.yml"
41597
- ];
41598
- MESH_JSON_CONFIG_SCHEMA = {
41599
- $schema: "https://json-schema.org/draft/2020-12/schema",
41600
- title: "ADHDev Repo Mesh Declarative Config",
41601
- type: "object",
41602
- additionalProperties: false,
41603
- required: ["version"],
41604
- properties: {
41605
- version: { const: 1 },
41606
- // policy is validated/normalized through mergeAndNormalizePolicy at merge
41607
- // time; the schema here only asserts it is an object.
41608
- policy: { type: "object" },
41609
- coordinator: {
41610
- type: "object",
41611
- additionalProperties: false,
41612
- properties: {
41613
- systemPromptOverride: { type: "string" },
41614
- systemPromptAppend: { type: "string" },
41615
- maxPromptChars: { type: "number", minimum: 1 }
41616
- }
41617
- },
41618
- operatingNotes: {
41619
- type: "array",
41620
- maxItems: 200,
41621
- items: {
41622
- type: "object",
41623
- additionalProperties: false,
41624
- required: ["text"],
41625
- properties: {
41626
- text: { type: "string", minLength: 1 },
41627
- category: { enum: ["provider_quirk", "pattern_to_avoid", "recovery_lesson"] },
41628
- createdAt: { type: "string" },
41629
- sourceCoordinator: { type: "string" }
41630
- }
41631
- }
41632
- },
41633
- limits: {
41634
- type: "object",
41635
- additionalProperties: false,
41636
- properties: {
41637
- maxNoteChars: { type: "number", minimum: 1 },
41638
- maxNotes: { type: "number", minimum: 1 }
41639
- }
41640
- }
41641
- }
41642
- };
41643
- cache = /* @__PURE__ */ new Map();
41644
- }
41645
- });
41646
41610
  function __resetIdleAutoFastForwardForTests() {
41647
41611
  idleAutoFastForwardLastAttempt.clear();
41648
41612
  }
@@ -41728,6 +41692,7 @@ Next step: ${nextStep}`;
41728
41692
  if (timer) clearTimeout(timer);
41729
41693
  LOG2.error("MeshQueue", `Failed to dispatch task via ${ctx.transport} to node ${ctx.nodeId}: ${e?.message}`);
41730
41694
  updateSessionDeliveryStatus(delivery.id, "failed", { lastError: e?.message, incrementAttempt: true });
41695
+ endTaskDispatchInFlight(ctx.meshId, ctx.task.id);
41731
41696
  updateTaskStatus(ctx.meshId, ctx.task.id, "pending");
41732
41697
  try {
41733
41698
  appendLedgerEntry(ctx.meshId, {
@@ -41801,10 +41766,11 @@ Next step: ${nextStep}`;
41801
41766
  return false;
41802
41767
  }
41803
41768
  LOG2.info("MeshQueue", `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
41769
+ beginTaskDispatchInFlight(meshId, task.id);
41804
41770
  if (node?.daemonId && components.dispatchMeshCommand) {
41805
41771
  const isLocalNode = components.cliManager.adapters.has(sessionId);
41806
41772
  if (!isLocalNode) {
41807
- const localDaemonIdForDispatch = readNonEmptyString2(loadConfig2().machineId) || void 0;
41773
+ const localDaemonIdForDispatch = localCoordinatorDaemonId();
41808
41774
  const sourceCoordinatorSessionId = readNonEmptyString2(task.sourceCoordinatorSessionId) || void 0;
41809
41775
  const dispatchMeshCommand = components.dispatchMeshCommand;
41810
41776
  const remoteDaemonId = node.daemonId;
@@ -41843,7 +41809,7 @@ Next step: ${nextStep}`;
41843
41809
  try {
41844
41810
  const inst = components.instanceManager.getInstance(sessionId);
41845
41811
  if (inst && typeof inst.updateSettings === "function") {
41846
- const localDaemonId = readNonEmptyString2(loadConfig2().machineId);
41812
+ const localDaemonId = localCoordinatorDaemonId();
41847
41813
  const localSourceCoordinatorSessionId = readNonEmptyString2(task.sourceCoordinatorSessionId);
41848
41814
  inst.updateSettings({
41849
41815
  meshNodeFor: meshId,
@@ -41868,7 +41834,7 @@ Next step: ${nextStep}`;
41868
41834
  meshId,
41869
41835
  nodeId,
41870
41836
  taskId: task.id,
41871
- ...readNonEmptyString2(loadConfig2().machineId) ? { coordinatorDaemonId: readNonEmptyString2(loadConfig2().machineId) } : {},
41837
+ ...localCoordinatorDaemonId() ? { coordinatorDaemonId: localCoordinatorDaemonId() } : {},
41872
41838
  ...readNonEmptyString2(task.sourceCoordinatorSessionId) ? { coordinatorSessionId: readNonEmptyString2(task.sourceCoordinatorSessionId) } : {}
41873
41839
  }
41874
41840
  }),
@@ -41880,7 +41846,7 @@ Next step: ${nextStep}`;
41880
41846
  task,
41881
41847
  transport: "local",
41882
41848
  ...readNonEmptyString2(task.sourceCoordinatorSessionId) ? { sourceCoordinatorSessionId: readNonEmptyString2(task.sourceCoordinatorSessionId) } : {},
41883
- ...readNonEmptyString2(loadConfig2().machineId) ? { sourceCoordinatorDaemonId: readNonEmptyString2(loadConfig2().machineId) } : {}
41849
+ ...localCoordinatorDaemonId() ? { sourceCoordinatorDaemonId: localCoordinatorDaemonId() } : {}
41884
41850
  }
41885
41851
  );
41886
41852
  return true;
@@ -41962,8 +41928,8 @@ Next step: ${nextStep}`;
41962
41928
  }
41963
41929
  function sweepExpiredCooldowns() {
41964
41930
  const now = Date.now();
41965
- for (const [key, until] of autoLaunchCooldownUntil) {
41966
- if (now >= until) autoLaunchCooldownUntil.delete(key);
41931
+ for (const [key2, until] of autoLaunchCooldownUntil) {
41932
+ if (now >= until) autoLaunchCooldownUntil.delete(key2);
41967
41933
  }
41968
41934
  }
41969
41935
  function normalizeProviderPriority(policy) {
@@ -42009,7 +41975,7 @@ Next step: ${nextStep}`;
42009
41975
  const settings = state.settings || {};
42010
41976
  if (readNonEmptyString2(settings.meshNodeFor) !== meshId) return false;
42011
41977
  const instNodeId = readNonEmptyString2(settings.meshNodeId) || readNonEmptyString2(settings.nodeId);
42012
- if (instNodeId !== nodeId) return false;
41978
+ if (!daemonIdsEquivalent(instNodeId, nodeId)) return false;
42013
41979
  const sessionId = readNonEmptyString2(state.instanceId);
42014
41980
  if (currentSessionId && sessionId === currentSessionId && isIdleSessionState(state)) return false;
42015
41981
  return sessionStateLooksActive(state);
@@ -42041,7 +42007,7 @@ Next step: ${nextStep}`;
42041
42007
  const daemonId = readNonEmptyString2(node?.daemonId);
42042
42008
  if (!daemonId) return { mode: "skip", reason: "remote_auto_launch_unsupported" };
42043
42009
  if (!components.dispatchMeshCommand) return { mode: "skip", reason: "remote_auto_launch_unsupported" };
42044
- const coordinatorDaemonId = readNonEmptyString2(loadConfig2().machineId);
42010
+ const coordinatorDaemonId = localCoordinatorDaemonId();
42045
42011
  if (!coordinatorDaemonId) return { mode: "skip", reason: "remote_auto_launch_no_coordinator_daemon_id" };
42046
42012
  return { mode: "remote", daemonId, coordinatorDaemonId };
42047
42013
  }
@@ -42052,31 +42018,12 @@ Next step: ${nextStep}`;
42052
42018
  return getQueue(meshId, { status: ["assigned"] }).filter(isTaskReadonly).length;
42053
42019
  }
42054
42020
  function nodeHasActiveAssignment(meshId, nodeId) {
42055
- return getQueue(meshId, { status: ["assigned"] }).some((task) => task.assignedNodeId === nodeId);
42021
+ return getQueue(meshId, { status: ["assigned"] }).some((task) => daemonIdsEquivalent(task.assignedNodeId, nodeId));
42056
42022
  }
42057
42023
  function nodeActiveLoad(meshId, nodeId) {
42058
42024
  return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
42059
42025
  }
42060
- function resolveMeshRepoRootForScheduling(mesh) {
42061
- const nodes = Array.isArray(mesh?.nodes) ? mesh.nodes : [];
42062
- const pickRoot = (n) => readNonEmptyString2(n?.repoRoot) || readNonEmptyString2(n?.workspace);
42063
- const base = nodes.find((n) => n?.isLocalWorktree !== true && pickRoot(n));
42064
- if (base) return pickRoot(base);
42065
- const anyNode = nodes.find((n) => pickRoot(n));
42066
- return anyNode ? pickRoot(anyNode) : "";
42067
- }
42068
- function resolveMeshSchedulingOverride(mesh) {
42069
- const repoRoot = resolveMeshRepoRootForScheduling(mesh);
42070
- if (!repoRoot) return void 0;
42071
- try {
42072
- return loadMeshJsonConfig(repoRoot).config?.scheduling;
42073
- } catch {
42074
- return void 0;
42075
- }
42076
- }
42077
42026
  function resolveSchedulingStrategy(mesh) {
42078
- const override = resolveMeshSchedulingOverride(mesh);
42079
- if (override?.distribution) return distributionToStrategy(override.distribution);
42080
42027
  return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
42081
42028
  }
42082
42029
  function orderEligibleNodes(meshId, strategy, nodes, opts) {
@@ -42101,7 +42048,7 @@ Next step: ${nextStep}`;
42101
42048
  });
42102
42049
  }
42103
42050
  function activeProviderAssignedCount(meshId, nodeId, providerType) {
42104
- return getQueue(meshId, { status: ["assigned"] }).filter((task) => task.assignedNodeId === nodeId && task.assignedProviderType === providerType).length;
42051
+ return getQueue(meshId, { status: ["assigned"] }).filter((task) => daemonIdsEquivalent(task.assignedNodeId, nodeId) && task.assignedProviderType === providerType).length;
42105
42052
  }
42106
42053
  function sessionHasActiveAssignment(meshId, sessionId) {
42107
42054
  if (getQueue(meshId, { status: ["assigned"] }).some((task) => task.assignedSessionId === sessionId)) {
@@ -42120,7 +42067,7 @@ Next step: ${nextStep}`;
42120
42067
  const settings = state.settings || {};
42121
42068
  if (readNonEmptyString2(settings.meshNodeFor) !== meshId) return false;
42122
42069
  const instNodeId = readNonEmptyString2(settings.meshNodeId) || readNonEmptyString2(settings.nodeId);
42123
- if (instNodeId !== nodeId) return false;
42070
+ if (!daemonIdsEquivalent(instNodeId, nodeId)) return false;
42124
42071
  const status = readNonEmptyString2(state.status).toLowerCase();
42125
42072
  return !isTerminalSessionStatus(status);
42126
42073
  }).length;
@@ -42219,11 +42166,8 @@ Next step: ${nextStep}`;
42219
42166
  const queue = getQueue(meshId);
42220
42167
  const pending = queue.filter((task) => task.status === "pending");
42221
42168
  if (!pending.length) return false;
42222
- const schedulingOverride = resolveMeshSchedulingOverride(mesh);
42223
- const maxParallelTasks = resolveMaxParallelTasks(
42224
- schedulingOverride?.maxParallel ?? mesh?.policy?.maxParallelTasks
42225
- );
42226
- const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks, schedulingOverride?.readonlyMultiplier);
42169
+ const maxParallelTasks = resolveMaxParallelTasks(mesh?.policy?.maxParallelTasks);
42170
+ const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks);
42227
42171
  for (const task of pending) {
42228
42172
  const isReadonly = isTaskReadonly(task);
42229
42173
  if (isReadonly) {
@@ -42652,12 +42596,12 @@ Next step: ${nextStep}`;
42652
42596
  init_mesh_event_trace();
42653
42597
  init_mesh_warmup_deadline();
42654
42598
  init_repo_mesh_types();
42655
- init_mesh_json_config();
42656
42599
  init_dist();
42657
42600
  init_mesh_events_stale();
42658
42601
  init_mesh_events_utils();
42659
42602
  init_mesh_events_pending();
42660
42603
  init_worktree_bootstrap_config();
42604
+ init_mesh_task_inflight();
42661
42605
  IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1e3;
42662
42606
  idleAutoFastForwardLastAttempt = /* @__PURE__ */ new Map();
42663
42607
  DISPATCH_CONFIRM_TIMEOUT_MS = 12e4;
@@ -42756,8 +42700,8 @@ Next step: ${nextStep}`;
42756
42700
  if (last !== void 0 && now - last < UNROUTABLE_DIAGNOSTIC_DEDUP_MS) return false;
42757
42701
  recentUnroutableDiagnostics.set(dedupKey, now);
42758
42702
  if (recentUnroutableDiagnostics.size > 256) {
42759
- for (const [key, ts2] of recentUnroutableDiagnostics) {
42760
- if (now - ts2 >= UNROUTABLE_DIAGNOSTIC_DEDUP_MS) recentUnroutableDiagnostics.delete(key);
42703
+ for (const [key2, ts2] of recentUnroutableDiagnostics) {
42704
+ if (now - ts2 >= UNROUTABLE_DIAGNOSTIC_DEDUP_MS) recentUnroutableDiagnostics.delete(key2);
42761
42705
  }
42762
42706
  }
42763
42707
  try {
@@ -43019,9 +42963,9 @@ Next step: ${nextStep}`;
43019
42963
  for (const line of stdout.split("\n")) {
43020
42964
  const m = line.match(/^\s*Pages\s+([^:]+):\s+([\d,]+)\s*\.?/);
43021
42965
  if (!m) continue;
43022
- const key = m[1].trim().toLowerCase().replace(/\s+/g, "_");
42966
+ const key2 = m[1].trim().toLowerCase().replace(/\s+/g, "_");
43023
42967
  const n = parseInt(m[2].replace(/,/g, ""), 10);
43024
- if (!Number.isNaN(n)) counts[key] = n;
42968
+ if (!Number.isNaN(n)) counts[key2] = n;
43025
42969
  }
43026
42970
  const free = counts["free"] ?? 0;
43027
42971
  const inactive = counts["inactive"] ?? 0;
@@ -43252,7 +43196,7 @@ Next step: ${nextStep}`;
43252
43196
  if (Array.isArray(value)) return value.map((item) => trimStructuredStrings(item, maxChars));
43253
43197
  if (!value || typeof value !== "object") return value;
43254
43198
  return Object.fromEntries(
43255
- Object.entries(value).map(([key, nested]) => [key, trimStructuredStrings(nested, maxChars)])
43199
+ Object.entries(value).map(([key2, nested]) => [key2, trimStructuredStrings(nested, maxChars)])
43256
43200
  );
43257
43201
  }
43258
43202
  function estimateBytes(value) {
@@ -43841,9 +43785,9 @@ Next step: ${nextStep}`;
43841
43785
  function readStringField(value) {
43842
43786
  return typeof value === "string" ? value.trim().toLowerCase() : "";
43843
43787
  }
43844
- function readRecordField(message, meta3, key) {
43788
+ function readRecordField(message, meta3, key2) {
43845
43789
  const record2 = message;
43846
- return record2[key] ?? meta3?.[key];
43790
+ return record2[key2] ?? meta3?.[key2];
43847
43791
  }
43848
43792
  function readVisibilityField(message, meta3) {
43849
43793
  return readStringField(readRecordField(message, meta3, "visibility"));
@@ -43854,7 +43798,7 @@ Next step: ${nextStep}`;
43854
43798
  }
43855
43799
  function hasBooleanMarker(message, meta3, keys) {
43856
43800
  const record2 = message;
43857
- return keys.some((key) => record2[key] === true || meta3?.[key] === true);
43801
+ return keys.some((key2) => record2[key2] === true || meta3?.[key2] === true);
43858
43802
  }
43859
43803
  function isActivityKind(kind) {
43860
43804
  return kind === "thought" || kind === "tool" || kind === "terminal";
@@ -44058,9 +44002,9 @@ Next step: ${nextStep}`;
44058
44002
  const values = {};
44059
44003
  const explicit = data.controlValues;
44060
44004
  if (explicit && typeof explicit === "object") {
44061
- for (const [key, value] of Object.entries(explicit)) {
44005
+ for (const [key2, value] of Object.entries(explicit)) {
44062
44006
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
44063
- values[key] = value;
44007
+ values[key2] = value;
44064
44008
  }
44065
44009
  }
44066
44010
  }
@@ -44519,26 +44463,26 @@ ${cleanBody}`;
44519
44463
  if (!workspace) return void 0;
44520
44464
  return options.getGitSummaryForWorkspace?.(workspace) || void 0;
44521
44465
  }
44522
- function findCdpManager(cdpManagers, key) {
44523
- const exact = cdpManagers.get(key);
44466
+ function findCdpManager(cdpManagers, key2) {
44467
+ const exact = cdpManagers.get(key2);
44524
44468
  if (exact) return exact.isConnected ? exact : null;
44525
- const prefix = key + "_";
44469
+ const prefix = key2 + "_";
44526
44470
  const matches = [...cdpManagers.entries()].filter(([k, m]) => m.isConnected && k.startsWith(prefix));
44527
44471
  if (matches.length === 1) return matches[0][1];
44528
44472
  return null;
44529
44473
  }
44530
- function hasCdpManager(cdpManagers, key) {
44531
- if (cdpManagers.has(key)) return true;
44532
- const prefix = key + "_";
44474
+ function hasCdpManager(cdpManagers, key2) {
44475
+ if (cdpManagers.has(key2)) return true;
44476
+ const prefix = key2 + "_";
44533
44477
  for (const k of cdpManagers.keys()) {
44534
44478
  if (k.startsWith(prefix)) return true;
44535
44479
  }
44536
44480
  return false;
44537
44481
  }
44538
- function isCdpConnected(cdpManagers, key) {
44539
- const exact = cdpManagers.get(key);
44482
+ function isCdpConnected(cdpManagers, key2) {
44483
+ const exact = cdpManagers.get(key2);
44540
44484
  if (exact?.isConnected) return true;
44541
- const prefix = key + "_";
44485
+ const prefix = key2 + "_";
44542
44486
  for (const [k, m] of cdpManagers.entries()) {
44543
44487
  if (m.isConnected && k.startsWith(prefix)) return true;
44544
44488
  }
@@ -44874,11 +44818,11 @@ ${cleanBody}`;
44874
44818
  String(snapshot.messageUpdatedAt)
44875
44819
  ].join("|");
44876
44820
  }
44877
- function shouldEmitRecentReadDebugLog(cache2, snapshot) {
44821
+ function shouldEmitRecentReadDebugLog(cache, snapshot) {
44878
44822
  const nextSignature = buildRecentReadDebugSignature(snapshot);
44879
- const previousSignature = cache2.get(snapshot.sessionId);
44823
+ const previousSignature = cache.get(snapshot.sessionId);
44880
44824
  if (previousSignature === nextSignature) return false;
44881
- cache2.set(snapshot.sessionId, nextSignature);
44825
+ cache.set(snapshot.sessionId, nextSignature);
44882
44826
  return true;
44883
44827
  }
44884
44828
  function buildDetectedIdeInfos(detectedIdes, cdpManagers) {
@@ -46436,9 +46380,9 @@ ${cleanBody}`;
46436
46380
  for (const event of pending) {
46437
46381
  if (!shouldForceInjectMeshEvent(event.event)) continue;
46438
46382
  const fingerprint = buildPendingEventFingerprint(event);
46439
- const key = `${meshId}::${fingerprint || `${event.event}::${event.nodeId || ""}::${event.queuedAt}`}`;
46440
- if (heldEventLedgerRecorded.has(key)) continue;
46441
- heldEventLedgerRecorded.add(key);
46383
+ const key2 = `${meshId}::${fingerprint || `${event.event}::${event.nodeId || ""}::${event.queuedAt}`}`;
46384
+ if (heldEventLedgerRecorded.has(key2)) continue;
46385
+ heldEventLedgerRecorded.add(key2);
46442
46386
  const finalSummary = readMeshCompletionSummary(event.metadataEvent);
46443
46387
  try {
46444
46388
  appendLedgerEntry(meshId, {
@@ -46459,7 +46403,7 @@ ${cleanBody}`;
46459
46403
  });
46460
46404
  LOG2.info("MeshReconcile", `Ledger-recorded held ${event.event} for mesh ${meshId} (reason ${reason}) \u2014 recoverable from ledger`);
46461
46405
  } catch (e) {
46462
- heldEventLedgerRecorded.delete(key);
46406
+ heldEventLedgerRecorded.delete(key2);
46463
46407
  LOG2.warn("MeshReconcile", `Failed to ledger-record held ${event.event} for mesh ${meshId}: ${e?.message || e}`);
46464
46408
  }
46465
46409
  }
@@ -46924,9 +46868,9 @@ ${cleanBody}`;
46924
46868
  const activeTaskKeys = new Set(
46925
46869
  dispatches.map((d) => readNonEmptyString2(d.taskId)).filter(Boolean).map((taskId) => inFlightSynthKey(mesh.id, taskId))
46926
46870
  );
46927
- for (const key of inFlightAckedHoldState.keys()) {
46928
- if (key.startsWith(`${mesh.id}::`) && !activeTaskKeys.has(key)) {
46929
- inFlightAckedHoldState.delete(key);
46871
+ for (const key2 of inFlightAckedHoldState.keys()) {
46872
+ if (key2.startsWith(`${mesh.id}::`) && !activeTaskKeys.has(key2)) {
46873
+ inFlightAckedHoldState.delete(key2);
46930
46874
  }
46931
46875
  }
46932
46876
  const dispatchMeshCommand = components.dispatchMeshCommand;
@@ -48514,8 +48458,8 @@ ${cleanBody}`;
48514
48458
  label += " " + next.trim();
48515
48459
  j += 1;
48516
48460
  }
48517
- const key = keyTemplate.replace(/\{index\}/g, String(idx));
48518
- buttons.push({ index: idx, label, key, current });
48461
+ const key2 = keyTemplate.replace(/\{index\}/g, String(idx));
48462
+ buttons.push({ index: idx, label, key: key2, current });
48519
48463
  i = j - 1;
48520
48464
  }
48521
48465
  } else {
@@ -48525,8 +48469,8 @@ ${cleanBody}`;
48525
48469
  const idx = Number(m[1]);
48526
48470
  const label = String(m[2] ?? "").trim();
48527
48471
  if (!Number.isFinite(idx) || idx <= 0 || !label) continue;
48528
- const key = keyTemplate.replace(/\{index\}/g, String(idx));
48529
- buttons.push({ index: idx, label, key, current: hasCursorMarker(m[0]) });
48472
+ const key2 = keyTemplate.replace(/\{index\}/g, String(idx));
48473
+ buttons.push({ index: idx, label, key: key2, current: hasCursorMarker(m[0]) });
48530
48474
  }
48531
48475
  }
48532
48476
  const block2 = lastContiguousNumberedBlock(buttons);
@@ -48604,12 +48548,12 @@ ${cleanBody}`;
48604
48548
  return { kind: "elapsed", result, detail: `elapsed ${age}ms / ${cond.elapsed_ms}ms`, remainingMs };
48605
48549
  }
48606
48550
  if (isStable(cond)) {
48607
- const key = regionKey(cond.cursor_above);
48608
- const lastChanged = clock.regionLastChangedAt.get(key) ?? clock.stateEnteredAt;
48551
+ const key2 = regionKey(cond.cursor_above);
48552
+ const lastChanged = clock.regionLastChangedAt.get(key2) ?? clock.stateEnteredAt;
48609
48553
  const stableFor = clock.now - lastChanged;
48610
48554
  const result = stableFor >= cond.stable_ms;
48611
48555
  const remainingMs = result ? 0 : cond.stable_ms - stableFor;
48612
- const where = key === WHOLE_SCREEN ? "screen" : `cursor_above=${cond.cursor_above}`;
48556
+ const where = key2 === WHOLE_SCREEN ? "screen" : `cursor_above=${cond.cursor_above}`;
48613
48557
  return { kind: "stable", result, detail: `stable ${where} ${stableFor}ms / ${cond.stable_ms}ms`, remainingMs };
48614
48558
  }
48615
48559
  if (isRegex(cond) || isChanged(cond)) {
@@ -52544,16 +52488,16 @@ ${lastSnapshot}`;
52544
52488
  }
52545
52489
  function buildFsShim() {
52546
52490
  const shim = {};
52547
- for (const key of FS_READ_ONLY_MEMBERS) {
52548
- if (key === "promises") continue;
52549
- const real = nodeFs[key];
52550
- if (real !== void 0) shim[key] = real;
52491
+ for (const key2 of FS_READ_ONLY_MEMBERS) {
52492
+ if (key2 === "promises") continue;
52493
+ const real = nodeFs[key2];
52494
+ if (real !== void 0) shim[key2] = real;
52551
52495
  }
52552
52496
  const realPromises = nodeFs.promises || {};
52553
52497
  const promisesShim = {};
52554
- for (const key of FS_PROMISES_READ_ONLY_MEMBERS) {
52555
- const real = realPromises[key];
52556
- if (real !== void 0) promisesShim[key] = real;
52498
+ for (const key2 of FS_PROMISES_READ_ONLY_MEMBERS) {
52499
+ const real = realPromises[key2];
52500
+ if (real !== void 0) promisesShim[key2] = real;
52557
52501
  }
52558
52502
  shim.promises = promisesShim;
52559
52503
  return shim;
@@ -52636,10 +52580,10 @@ ${lastSnapshot}`;
52636
52580
  function buildProcessShim() {
52637
52581
  const real = globalThis.process;
52638
52582
  const shim = /* @__PURE__ */ Object.create(null);
52639
- for (const key of Object.keys(real)) {
52640
- if (DANGEROUS_PROCESS_METHODS.has(String(key))) continue;
52583
+ for (const key2 of Object.keys(real)) {
52584
+ if (DANGEROUS_PROCESS_METHODS.has(String(key2))) continue;
52641
52585
  try {
52642
- shim[key] = real[key];
52586
+ shim[key2] = real[key2];
52643
52587
  } catch {
52644
52588
  }
52645
52589
  }
@@ -52975,6 +52919,7 @@ ${lastSnapshot}`;
52975
52919
  buildToolChatMessage: () => buildToolChatMessage,
52976
52920
  buildUserChatMessage: () => buildUserChatMessage,
52977
52921
  cancelTask: () => cancelTask,
52922
+ canonicalDaemonId: () => canonicalDaemonId,
52978
52923
  claimNextTask: () => claimNextTask,
52979
52924
  classifyChatMessageVisibility: () => classifyChatMessageVisibility,
52980
52925
  classifyHotChatSessionsForSubscriptionFlush: () => classifyHotChatSessionsForSubscriptionFlush2,
@@ -53103,6 +53048,7 @@ ${lastSnapshot}`;
53103
53048
  loadMeshCoordinatorRegistry: () => loadMeshCoordinatorRegistry,
53104
53049
  loadMeshRefineConfig: () => loadMeshRefineConfig,
53105
53050
  loadMeshWorktreeBootstrapConfig: () => loadMeshWorktreeBootstrapConfig,
53051
+ loadRepoSettings: () => loadRepoSettings,
53106
53052
  loadState: () => loadState,
53107
53053
  logCommand: () => logCommand,
53108
53054
  machineCoreFromDaemonId: () => machineCoreFromDaemonId,
@@ -53826,10 +53772,10 @@ ${lastSnapshot}`;
53826
53772
  const compactSummary = createGitCompactSummary(status, diffSummary);
53827
53773
  const timestamp = this.now();
53828
53774
  const seq = ++this.seq;
53829
- const key = this.keyForWorkspace(normalized.workspace);
53775
+ const key2 = this.keyForWorkspace(normalized.workspace);
53830
53776
  const update = {
53831
53777
  topic: "workspace.git",
53832
- key,
53778
+ key: key2,
53833
53779
  workspace: normalized.workspace,
53834
53780
  status,
53835
53781
  diffSummary,
@@ -53837,7 +53783,7 @@ ${lastSnapshot}`;
53837
53783
  timestamp
53838
53784
  };
53839
53785
  const cacheEntry = {
53840
- key,
53786
+ key: key2,
53841
53787
  workspace: normalized.workspace,
53842
53788
  status,
53843
53789
  diffSummary,
@@ -53979,11 +53925,11 @@ ${lastSnapshot}`;
53979
53925
  }
53980
53926
  return { path: args.path.trim() };
53981
53927
  }
53982
- function validateSnapshotId(args, key) {
53983
- if (typeof args?.[key] !== "string" || !args[key].trim()) {
53984
- return failure("invalid_args", `${key} must be a non-empty string`);
53928
+ function validateSnapshotId(args, key2) {
53929
+ if (typeof args?.[key2] !== "string" || !args[key2].trim()) {
53930
+ return failure("invalid_args", `${key2} must be a non-empty string`);
53985
53931
  }
53986
- return args[key].trim();
53932
+ return args[key2].trim();
53987
53933
  }
53988
53934
  function parseSnapshotReason(args) {
53989
53935
  if (args?.reason === void 0 || args?.reason === null || args?.reason === "") {
@@ -54455,6 +54401,25 @@ ${lastSnapshot}`;
54455
54401
  init_coordinator_registry();
54456
54402
  init_refine_config();
54457
54403
  init_worktree_bootstrap_config();
54404
+ init_mesh_json_config();
54405
+ init_refine_config();
54406
+ init_worktree_bootstrap_config();
54407
+ init_change_impact_config();
54408
+ function loadRepoSettings(opts) {
54409
+ const workspace = typeof opts.workspace === "string" ? opts.workspace : "";
54410
+ const mesh = opts.mesh;
54411
+ const repoRoot = typeof opts.repoRoot === "string" && opts.repoRoot ? opts.repoRoot : workspace;
54412
+ const meshJson = loadRepoMeshJsonConfig(workspace);
54413
+ return {
54414
+ coordinator: meshJson.config?.coordinator,
54415
+ operatingNotes: meshJson.config?.operatingNotes,
54416
+ limits: meshJson.config?.limits,
54417
+ meshJson,
54418
+ refine: loadMeshRefineConfig(mesh, workspace),
54419
+ worktreeBootstrap: loadMeshWorktreeBootstrapConfig(mesh, workspace),
54420
+ changeImpact: loadChangeImpactConfig(repoRoot)
54421
+ };
54422
+ }
54458
54423
  init_mesh_ledger();
54459
54424
  init_mesh_fast_forward();
54460
54425
  function lastTimestamp(slice) {
@@ -56332,10 +56297,10 @@ ${lastSnapshot}`;
56332
56297
  return events;
56333
56298
  }
56334
56299
  /** Cooldown check — prevent sending the same notification too frequently */
56335
- shouldAlert(key, now) {
56336
- const last = this.lastAlertTime.get(key) || 0;
56300
+ shouldAlert(key2, now) {
56301
+ const last = this.lastAlertTime.get(key2) || 0;
56337
56302
  if (now - last > this.config.alertCooldownSec * 1e3) {
56338
- this.lastAlertTime.set(key, now);
56303
+ this.lastAlertTime.set(key2, now);
56339
56304
  return true;
56340
56305
  }
56341
56306
  return false;
@@ -56379,16 +56344,16 @@ ${lastSnapshot}`;
56379
56344
  var savedHistoryRollupInFlight = /* @__PURE__ */ new Set();
56380
56345
  var BOUNDED_TAIL_CACHE_MAX_ENTRIES = 64;
56381
56346
  var boundedTailReadCache = /* @__PURE__ */ new Map();
56382
- function readBoundedTailCache(key, signature) {
56383
- const cached3 = boundedTailReadCache.get(key);
56347
+ function readBoundedTailCache(key2, signature) {
56348
+ const cached3 = boundedTailReadCache.get(key2);
56384
56349
  if (!cached3 || cached3.signature !== signature) return null;
56385
- boundedTailReadCache.delete(key);
56386
- boundedTailReadCache.set(key, cached3);
56350
+ boundedTailReadCache.delete(key2);
56351
+ boundedTailReadCache.set(key2, cached3);
56387
56352
  return cached3.result;
56388
56353
  }
56389
- function writeBoundedTailCache(key, signature, result) {
56390
- boundedTailReadCache.delete(key);
56391
- boundedTailReadCache.set(key, { signature, result });
56354
+ function writeBoundedTailCache(key2, signature, result) {
56355
+ boundedTailReadCache.delete(key2);
56356
+ boundedTailReadCache.set(key2, { signature, result });
56392
56357
  while (boundedTailReadCache.size > BOUNDED_TAIL_CACHE_MAX_ENTRIES) {
56393
56358
  const oldest = boundedTailReadCache.keys().next().value;
56394
56359
  if (oldest === void 0) break;
@@ -56824,21 +56789,21 @@ ${lastSnapshot}`;
56824
56789
  return shouldScheduleSavedHistoryRollup(size);
56825
56790
  }
56826
56791
  function scheduleSavedHistoryRollup(agentType, historySessionId) {
56827
- const key = `${agentType}:${historySessionId}`;
56828
- if (!historySessionId || savedHistoryRollupInFlight.has(key)) return;
56829
- savedHistoryRollupInFlight.add(key);
56792
+ const key2 = `${agentType}:${historySessionId}`;
56793
+ if (!historySessionId || savedHistoryRollupInFlight.has(key2)) return;
56794
+ savedHistoryRollupInFlight.add(key2);
56830
56795
  setTimeout(() => {
56831
56796
  try {
56832
56797
  new ChatHistoryWriter().compactHistorySession(agentType, historySessionId);
56833
56798
  } finally {
56834
- savedHistoryRollupInFlight.delete(key);
56799
+ savedHistoryRollupInFlight.delete(key2);
56835
56800
  }
56836
56801
  }, 0);
56837
56802
  }
56838
56803
  function scheduleSavedHistoryBackgroundRefresh(agentType, dir) {
56839
- const key = `${agentType}:${dir}`;
56840
- if (savedHistoryBackgroundRefresh.has(key)) return;
56841
- savedHistoryBackgroundRefresh.add(key);
56804
+ const key2 = `${agentType}:${dir}`;
56805
+ if (savedHistoryBackgroundRefresh.has(key2)) return;
56806
+ savedHistoryBackgroundRefresh.add(key2);
56842
56807
  setTimeout(() => {
56843
56808
  try {
56844
56809
  if (!fs6.existsSync(dir)) return;
@@ -56858,7 +56823,7 @@ ${lastSnapshot}`;
56858
56823
  }
56859
56824
  } catch {
56860
56825
  } finally {
56861
- savedHistoryBackgroundRefresh.delete(key);
56826
+ savedHistoryBackgroundRefresh.delete(key2);
56862
56827
  }
56863
56828
  }, 0);
56864
56829
  }
@@ -57624,14 +57589,14 @@ ${lastSnapshot}`;
57624
57589
  return false;
57625
57590
  }
57626
57591
  }
57627
- function getNativeHistoryScriptName(canonicalHistory, key) {
57628
- const configured = canonicalHistory?.scripts?.[key];
57592
+ function getNativeHistoryScriptName(canonicalHistory, key2) {
57593
+ const configured = canonicalHistory?.scripts?.[key2];
57629
57594
  if (typeof configured === "string" && configured.trim()) return configured.trim();
57630
- return key === "readSession" ? "readNativeHistory" : "listNativeHistory";
57595
+ return key2 === "readSession" ? "readNativeHistory" : "listNativeHistory";
57631
57596
  }
57632
- function getProviderNativeHistoryScript(scripts, canonicalHistory, key) {
57597
+ function getProviderNativeHistoryScript(scripts, canonicalHistory, key2) {
57633
57598
  if (!canonicalHistory?.scripts) return null;
57634
- const fn = scripts?.[getNativeHistoryScriptName(canonicalHistory, key)];
57599
+ const fn = scripts?.[getNativeHistoryScriptName(canonicalHistory, key2)];
57635
57600
  return typeof fn === "function" ? fn : null;
57636
57601
  }
57637
57602
  function normalizeProviderNativeHistoryRecords(agentType, historySessionId, records) {
@@ -58355,11 +58320,11 @@ ${effect.notification.body || ""}`.trim();
58355
58320
  throw new Error(`${source}: controlValues must be an object when provided`);
58356
58321
  }
58357
58322
  const normalized = {};
58358
- for (const [key, value] of Object.entries(controlValues)) {
58323
+ for (const [key2, value] of Object.entries(controlValues)) {
58359
58324
  if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
58360
- throw new Error(`${source}: controlValues.${key} must be string, number, or boolean`);
58325
+ throw new Error(`${source}: controlValues.${key2} must be string, number, or boolean`);
58361
58326
  }
58362
- normalized[key] = value;
58327
+ normalized[key2] = value;
58363
58328
  }
58364
58329
  return normalized;
58365
58330
  }
@@ -59106,7 +59071,7 @@ ${effect.notification.body || ""}`.trim();
59106
59071
  for (const [ide, ports] of Object.entries(portMap)) {
59107
59072
  const primaryPort = ports[0];
59108
59073
  const alreadyConnected = [...this.ctx.cdpManagers.entries()].some(
59109
- ([key, m]) => m.isConnected && (key === ide || key.startsWith(ide + "_"))
59074
+ ([key2, m]) => m.isConnected && (key2 === ide || key2.startsWith(ide + "_"))
59110
59075
  );
59111
59076
  if (alreadyConnected) continue;
59112
59077
  if (this.opts.multiWindow) {
@@ -59278,8 +59243,8 @@ ${effect.notification.body || ""}`.trim();
59278
59243
  for (let i = 0; i < targets.length; i++) {
59279
59244
  const target = targets[i];
59280
59245
  let alreadyTracked = false;
59281
- for (const [key, m] of cdpManagers.entries()) {
59282
- if ((key === ide || key.startsWith(`${ide}_`)) && m.targetId === target.id) {
59246
+ for (const [key2, m] of cdpManagers.entries()) {
59247
+ if ((key2 === ide || key2.startsWith(`${ide}_`)) && m.targetId === target.id) {
59283
59248
  alreadyTracked = true;
59284
59249
  break;
59285
59250
  }
@@ -59311,29 +59276,29 @@ ${effect.notification.body || ""}`.trim();
59311
59276
  async pruneStaleManagers(port, ide, targets) {
59312
59277
  const trackedTargetIds = new Set(targets.map((target) => target.id));
59313
59278
  const removals = [];
59314
- for (const [key, manager] of this.config.cdpManagers.entries()) {
59315
- if (!(key === ide || key.startsWith(`${ide}_`))) continue;
59279
+ for (const [key2, manager] of this.config.cdpManagers.entries()) {
59280
+ if (!(key2 === ide || key2.startsWith(`${ide}_`))) continue;
59316
59281
  if (manager.getPort() !== port) continue;
59317
59282
  if (targets.length === 0) {
59318
- removals.push({ key, manager, reason: "ide_closed" });
59283
+ removals.push({ key: key2, manager, reason: "ide_closed" });
59319
59284
  continue;
59320
59285
  }
59321
59286
  if (manager.targetId && !trackedTargetIds.has(manager.targetId)) {
59322
- removals.push({ key, manager, reason: "target_closed" });
59287
+ removals.push({ key: key2, manager, reason: "target_closed" });
59323
59288
  continue;
59324
59289
  }
59325
- if (key === ide && !manager.targetId && targets.length > 1) {
59326
- removals.push({ key, manager, reason: "target_rekeyed" });
59290
+ if (key2 === ide && !manager.targetId && targets.length > 1) {
59291
+ removals.push({ key: key2, manager, reason: "target_rekeyed" });
59327
59292
  }
59328
59293
  }
59329
- for (const { key, manager, reason } of removals) {
59294
+ for (const { key: key2, manager, reason } of removals) {
59330
59295
  try {
59331
59296
  manager.disconnect();
59332
59297
  } catch {
59333
59298
  }
59334
- this.config.cdpManagers.delete(key);
59335
- LOG2.info("IDE", `Detached window: ${key} (${reason})`);
59336
- await this.config.onDisconnected?.(ide, manager, key, reason);
59299
+ this.config.cdpManagers.delete(key2);
59300
+ LOG2.info("IDE", `Detached window: ${key2} (${reason})`);
59301
+ await this.config.onDisconnected?.(ide, manager, key2, reason);
59337
59302
  }
59338
59303
  }
59339
59304
  // ─── Periodic scanning ───
@@ -59637,7 +59602,7 @@ ${effect.notification.body || ""}`.trim();
59637
59602
  if (Array.isArray(value)) return value.map((entry) => sanitizeTraceValue(entry, traceContent));
59638
59603
  if (value && typeof value === "object") {
59639
59604
  return Object.fromEntries(
59640
- Object.entries(value).map(([key, nested]) => [key, sanitizeTraceValue(nested, traceContent)])
59605
+ Object.entries(value).map(([key2, nested]) => [key2, sanitizeTraceValue(nested, traceContent)])
59641
59606
  );
59642
59607
  }
59643
59608
  return value;
@@ -59646,7 +59611,7 @@ ${effect.notification.body || ""}`.trim();
59646
59611
  if (Array.isArray(value)) return value.map((entry) => sanitizeTraceValue(entry, traceContent));
59647
59612
  if (value && typeof value === "object") {
59648
59613
  return Object.fromEntries(
59649
- Object.entries(value).map(([key, nested]) => [key, sanitizeTraceValue(nested, traceContent)])
59614
+ Object.entries(value).map(([key2, nested]) => [key2, sanitizeTraceValue(nested, traceContent)])
59650
59615
  );
59651
59616
  }
59652
59617
  return value;
@@ -59950,8 +59915,8 @@ ${effect.notification.body || ""}`.trim();
59950
59915
  }
59951
59916
  function isSupersetOf(candidate, required2) {
59952
59917
  if (required2.size === 0) return true;
59953
- for (const key of required2) {
59954
- if (!candidate.has(key)) return false;
59918
+ for (const key2 of required2) {
59919
+ if (!candidate.has(key2)) return false;
59955
59920
  }
59956
59921
  return true;
59957
59922
  }
@@ -59962,17 +59927,17 @@ ${effect.notification.body || ""}`.trim();
59962
59927
  var ChatSourceRegistry = class {
59963
59928
  records = /* @__PURE__ */ new Map();
59964
59929
  /** Snapshot of current state for diagnostics. Does not mutate. */
59965
- getState(key) {
59966
- return this.records.get(key)?.state ?? INITIAL_CHAT_SOURCE_STATE;
59930
+ getState(key2) {
59931
+ return this.records.get(key2)?.state ?? INITIAL_CHAT_SOURCE_STATE;
59967
59932
  }
59968
59933
  /** Recent transitions, newest last. Empty array when nothing has happened. */
59969
- getTransitions(key) {
59970
- return this.records.get(key)?.transitions ?? [];
59934
+ getTransitions(key2) {
59935
+ return this.records.get(key2)?.transitions ?? [];
59971
59936
  }
59972
59937
  /** Drop a session. Caller should invoke this when the session is destroyed
59973
59938
  * to avoid unbounded growth across long-lived daemons. */
59974
- clear(key) {
59975
- this.records.delete(key);
59939
+ clear(key2) {
59940
+ this.records.delete(key2);
59976
59941
  }
59977
59942
  /** Drop all sessions. Test helper. */
59978
59943
  clearAll() {
@@ -59984,15 +59949,15 @@ ${effect.notification.body || ""}`.trim();
59984
59949
  * under `key`; callers may treat the decision as authoritative without
59985
59950
  * re-reading.
59986
59951
  */
59987
- observe(key, observation, at = Date.now()) {
59988
- const prev = this.records.get(key);
59952
+ observe(key2, observation, at = Date.now()) {
59953
+ const prev = this.records.get(key2);
59989
59954
  const prevState = prev?.state ?? INITIAL_CHAT_SOURCE_STATE;
59990
59955
  const prevLockedSince = prev?.lockedSince;
59991
59956
  const result = transitionChatSourceState(prevState, observation, at, prevLockedSince);
59992
59957
  const transitions = prev?.transitions ?? [];
59993
59958
  const nextTransitions = appendTransition(transitions, result.transition);
59994
59959
  const lockedSince = result.lockState.lockedSince;
59995
- this.records.set(key, {
59960
+ this.records.set(key2, {
59996
59961
  state: result.next,
59997
59962
  lockedSince,
59998
59963
  transitions: nextTransitions
@@ -60673,8 +60638,8 @@ ${effect.notification.body || ""}`.trim();
60673
60638
  });
60674
60639
  return { ...history, lookup: "workspace" };
60675
60640
  }
60676
- function shouldPreserveReadChatPayloadField(key) {
60677
- return key === "messageSource" || key === "transcriptProvenance";
60641
+ function shouldPreserveReadChatPayloadField(key2) {
60642
+ return key2 === "messageSource" || key2 === "transcriptProvenance";
60678
60643
  }
60679
60644
  function updateMessageSourceReturnedCount(value, returnedMessageCount) {
60680
60645
  if (!value || typeof value !== "object" || Array.isArray(value)) return value;
@@ -60844,7 +60809,7 @@ ${effect.notification.body || ""}`.trim();
60844
60809
  const visibleMessages = includeActivity ? filteredMessages.filter((m) => isUserFacingChatMessage(m) || isActivityChatMessage(m)) : filterUserFacingChatMessages(filteredMessages);
60845
60810
  const sync = buildFullTail(visibleMessages, normalizeReadChatTailLimit(args));
60846
60811
  const hiddenMsgCount = Math.max(0, messages.length - visibleMessages.length);
60847
- const preservedPayloadFields = Object.fromEntries(Object.entries(payload).filter(([key]) => shouldPreserveReadChatPayloadField(key)));
60812
+ const preservedPayloadFields = Object.fromEntries(Object.entries(payload).filter(([key2]) => shouldPreserveReadChatPayloadField(key2)));
60848
60813
  if (preservedPayloadFields.messageSource) {
60849
60814
  preservedPayloadFields.messageSource = updateMessageSourceReturnedCount(preservedPayloadFields.messageSource, sync.messages.length);
60850
60815
  }
@@ -61594,8 +61559,8 @@ ${effect.notification.body || ""}`.trim();
61594
61559
  const record2 = value;
61595
61560
  const result = {};
61596
61561
  const entries = Object.entries(record2).slice(0, normalizedOptions.maxObjectKeys);
61597
- for (const [key, item] of entries) {
61598
- result[key] = sanitizeDebugBundleValue(item, normalizedOptions, depth + 1, key);
61562
+ for (const [key2, item] of entries) {
61563
+ result[key2] = sanitizeDebugBundleValue(item, normalizedOptions, depth + 1, key2);
61599
61564
  }
61600
61565
  const remaining = Object.keys(record2).length - entries.length;
61601
61566
  if (remaining > 0) result.__truncatedKeys = remaining;
@@ -61919,14 +61884,14 @@ ${effect.notification.body || ""}`.trim();
61919
61884
  if (typeof script !== "function") return null;
61920
61885
  return script(text);
61921
61886
  }
61922
- function isRecentDuplicateSend(key) {
61887
+ function isRecentDuplicateSend(key2) {
61923
61888
  const now = Date.now();
61924
61889
  for (const [candidate, ts2] of recentSendByTarget.entries()) {
61925
61890
  if (now - ts2 > RECENT_SEND_WINDOW_MS) recentSendByTarget.delete(candidate);
61926
61891
  }
61927
- const previous = recentSendByTarget.get(key);
61892
+ const previous = recentSendByTarget.get(key2);
61928
61893
  if (previous && now - previous <= RECENT_SEND_WINDOW_MS) return true;
61929
- recentSendByTarget.set(key, now);
61894
+ recentSendByTarget.set(key2, now);
61930
61895
  return false;
61931
61896
  }
61932
61897
  function didProviderConfirmSend(result) {
@@ -62787,23 +62752,23 @@ ${effect.notification.body || ""}`.trim();
62787
62752
  try {
62788
62753
  switch (action) {
62789
62754
  case "input_key": {
62790
- const { type: evType, key, code, text, unmodifiedText, modifiers } = params;
62755
+ const { type: evType, key: key2, code, text, unmodifiedText, modifiers } = params;
62791
62756
  const mod = typeof modifiers === "number" ? modifiers : 0;
62792
- const vk = KEY_TO_VK[key] || (key.length === 1 ? key.charCodeAt(0) : 0);
62757
+ const vk = KEY_TO_VK[key2] || (key2.length === 1 ? key2.charCodeAt(0) : 0);
62793
62758
  if (evType === "char") {
62794
62759
  await h.getCdp().send("Input.dispatchKeyEvent", {
62795
62760
  type: "char",
62796
- key,
62761
+ key: key2,
62797
62762
  code,
62798
- text: text || key,
62799
- unmodifiedText: unmodifiedText || text || key,
62763
+ text: text || key2,
62764
+ unmodifiedText: unmodifiedText || text || key2,
62800
62765
  ...vk ? { windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk } : {},
62801
62766
  ...mod ? { modifiers: mod } : {}
62802
62767
  });
62803
62768
  } else {
62804
62769
  await h.getCdp().send("Input.dispatchKeyEvent", {
62805
62770
  type: "rawKeyDown",
62806
- key,
62771
+ key: key2,
62807
62772
  code,
62808
62773
  ...text ? { text } : {},
62809
62774
  ...vk ? { windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk } : {},
@@ -62811,7 +62776,7 @@ ${effect.notification.body || ""}`.trim();
62811
62776
  });
62812
62777
  await h.getCdp().send("Input.dispatchKeyEvent", {
62813
62778
  type: "keyUp",
62814
- key,
62779
+ key: key2,
62815
62780
  code,
62816
62781
  ...vk ? { windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk } : {},
62817
62782
  ...mod ? { modifiers: mod } : {}
@@ -63202,21 +63167,21 @@ ${effect.notification.body || ""}`.trim();
63202
63167
  }
63203
63168
  async function handleSetProviderSetting(h, args) {
63204
63169
  const loader = h.ctx.providerLoader;
63205
- const { providerType, key, value } = args || {};
63206
- if (!providerType || !key || value === void 0) {
63170
+ const { providerType, key: key2, value } = args || {};
63171
+ if (!providerType || !key2 || value === void 0) {
63207
63172
  return { success: false, error: "providerType, key, and value are required" };
63208
63173
  }
63209
- const result = loader?.setSetting(providerType, key, value);
63174
+ const result = loader?.setSetting(providerType, key2, value);
63210
63175
  if (result) {
63211
63176
  if (h.ctx.instanceManager) {
63212
63177
  const allSettings = loader?.getSettings(providerType) || {};
63213
63178
  const updated = h.ctx.instanceManager.updateInstanceSettings(providerType, allSettings);
63214
- LOG2.info("Command", `[set_provider_setting] ${providerType}.${key}=${JSON.stringify(value)} \u2192 ${updated} instance(s) updated`);
63179
+ LOG2.info("Command", `[set_provider_setting] ${providerType}.${key2}=${JSON.stringify(value)} \u2192 ${updated} instance(s) updated`);
63215
63180
  }
63216
- await h.ctx.onProviderSettingChanged?.(providerType, key, value);
63217
- return { success: true, providerType, key, value };
63181
+ await h.ctx.onProviderSettingChanged?.(providerType, key2, value);
63182
+ return { success: true, providerType, key: key2, value };
63218
63183
  }
63219
- return { success: false, error: `Failed to set ${providerType}.${key} \u2014 invalid key, value, or not a public setting` };
63184
+ return { success: false, error: `Failed to set ${providerType}.${key2} \u2014 invalid key, value, or not a public setting` };
63220
63185
  }
63221
63186
  function handleGetProviderSourceConfig(h, _args) {
63222
63187
  const loader = h.ctx.providerLoader;
@@ -63262,9 +63227,9 @@ ${effect.notification.body || ""}`.trim();
63262
63227
  normalizedArgs.mode = normalizedArgs.value;
63263
63228
  }
63264
63229
  }
63265
- for (const key of ["mode", "model", "message", "action", "button", "text", "sessionId", "value"]) {
63266
- if (key in normalizedArgs && !(key.toUpperCase() in normalizedArgs)) {
63267
- normalizedArgs[key.toUpperCase()] = normalizedArgs[key];
63230
+ for (const key2 of ["mode", "model", "message", "action", "button", "text", "sessionId", "value"]) {
63231
+ if (key2 in normalizedArgs && !(key2.toUpperCase() in normalizedArgs)) {
63232
+ normalizedArgs[key2.toUpperCase()] = normalizedArgs[key2];
63268
63233
  }
63269
63234
  }
63270
63235
  return normalizedArgs;
@@ -63660,10 +63625,10 @@ ${effect.notification.body || ""}`.trim();
63660
63625
  "value"
63661
63626
  ];
63662
63627
  const entries = [];
63663
- for (const key of preferredKeys) {
63664
- if (!(key in args) || args[key] === void 0) continue;
63665
- const value = key === "text" || key === "message" ? `${String(args[key] || "").length} chars` : key === "data" ? `${String(args[key] || "").length} chars` : summarizeLogValue(args[key]);
63666
- entries.push(`${key}=${value}`);
63628
+ for (const key2 of preferredKeys) {
63629
+ if (!(key2 in args) || args[key2] === void 0) continue;
63630
+ const value = key2 === "text" || key2 === "message" ? `${String(args[key2] || "").length} chars` : key2 === "data" ? `${String(args[key2] || "").length} chars` : summarizeLogValue(args[key2]);
63631
+ entries.push(`${key2}=${value}`);
63667
63632
  }
63668
63633
  return entries.length ? entries.join(" ") : "{...}";
63669
63634
  }
@@ -63715,12 +63680,12 @@ ${effect.notification.body || ""}`.trim();
63715
63680
  * Get provider module — _currentProviderType (agentType priority) use.
63716
63681
  */
63717
63682
  getProvider(overrideType) {
63718
- const key = overrideType || this._currentRoute.providerType || this._currentRoute.session?.providerType || this._currentRoute.managerKey;
63719
- if (!key || !this._ctx.providerLoader) return void 0;
63720
- const result = this._ctx.providerLoader.resolve(key);
63683
+ const key2 = overrideType || this._currentRoute.providerType || this._currentRoute.session?.providerType || this._currentRoute.managerKey;
63684
+ if (!key2 || !this._ctx.providerLoader) return void 0;
63685
+ const result = this._ctx.providerLoader.resolve(key2);
63721
63686
  if (result) return result;
63722
- const baseType = key.split("_")[0];
63723
- if (baseType !== key) return this._ctx.providerLoader.resolve(baseType);
63687
+ const baseType = key2.split("_")[0];
63688
+ if (baseType !== key2) return this._ctx.providerLoader.resolve(baseType);
63724
63689
  return void 0;
63725
63690
  }
63726
63691
  /** Get a provider script by name from ProviderLoader. */
@@ -63778,11 +63743,11 @@ ${effect.notification.body || ""}`.trim();
63778
63743
  return this._ctx.adapters.get(target) || null;
63779
63744
  }
63780
63745
  // ─── Private helpers ──────────────────────────────
63781
- inferProviderType(key) {
63782
- if (!key) return void 0;
63783
- const session = this._ctx.sessionRegistry?.get(key);
63746
+ inferProviderType(key2) {
63747
+ if (!key2) return void 0;
63748
+ const session = this._ctx.sessionRegistry?.get(key2);
63784
63749
  if (session?.providerType) return session.providerType;
63785
- return key.split("_")[0];
63750
+ return key2.split("_")[0];
63786
63751
  }
63787
63752
  resolveRoute(args) {
63788
63753
  const targetSessionId = typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : "";
@@ -65468,16 +65433,16 @@ ${formatManifestValidationIssues2(validation.issues)}`,
65468
65433
  const m = matchAppend || matchOverride;
65469
65434
  if (!m) continue;
65470
65435
  const isAppend = !!matchAppend;
65471
- const key = m[1];
65436
+ const key2 = m[1];
65472
65437
  const full = path43.join(dir, name);
65473
65438
  let content = "";
65474
65439
  try {
65475
65440
  content = fs38.readFileSync(full, "utf8");
65476
65441
  } catch {
65477
65442
  }
65478
- if (!entries[key]) entries[key] = { override: "", append: "" };
65479
- if (isAppend) entries[key].append = content;
65480
- else entries[key].override = content;
65443
+ if (!entries[key2]) entries[key2] = { override: "", append: "" };
65444
+ if (isAppend) entries[key2].append = content;
65445
+ else entries[key2].override = content;
65481
65446
  }
65482
65447
  }
65483
65448
  } catch (error48) {
@@ -65489,14 +65454,14 @@ ${formatManifestValidationIssues2(validation.issues)}`,
65489
65454
  const fs38 = await import("fs");
65490
65455
  const path43 = await import("path");
65491
65456
  const os30 = await import("os");
65492
- const key = typeof args?.key === "string" ? args.key.trim() : "";
65457
+ const key2 = typeof args?.key === "string" ? args.key.trim() : "";
65493
65458
  const kind = args?.kind === "append" ? "append" : "override";
65494
65459
  const content = typeof args?.content === "string" ? args.content : "";
65495
- if (!key || !/^[a-zA-Z0-9_.-]+$/.test(key)) {
65460
+ if (!key2 || !/^[a-zA-Z0-9_.-]+$/.test(key2)) {
65496
65461
  return { success: false, error: "key must match [a-zA-Z0-9_.-]+" };
65497
65462
  }
65498
65463
  const dir = path43.join(os30.homedir(), ".adhdev", "coordinator-prompts");
65499
- const filename = kind === "append" ? `${key}.append.md` : `${key}.md`;
65464
+ const filename = kind === "append" ? `${key2}.append.md` : `${key2}.md`;
65500
65465
  const full = path43.join(dir, filename);
65501
65466
  try {
65502
65467
  fs38.mkdirSync(dir, { recursive: true });
@@ -65505,7 +65470,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
65505
65470
  } else if (fs38.existsSync(full)) {
65506
65471
  fs38.unlinkSync(full);
65507
65472
  }
65508
- return { success: true, path: full, kind, key };
65473
+ return { success: true, path: full, kind, key: key2 };
65509
65474
  } catch (error48) {
65510
65475
  return { success: false, error: error48?.message || String(error48) };
65511
65476
  }
@@ -66434,7 +66399,7 @@ ${body}
66434
66399
  {
66435
66400
  name: "key_value_secret",
66436
66401
  pattern: /\b([A-Z0-9_]*(?:SECRET|TOKEN|API[_-]?KEY|PASSWORD|PASSWD|PRIVATE[_-]?KEY|CREDENTIAL|CLIENT[_-]?SECRET)[A-Z0-9_]*)(\s*[:=]\s*)(["']?)([^\s"',;]+)\3/gi,
66437
- replace: (_m, key, delim, quote) => `${key}${delim}${quote}${MASK}${quote}`
66402
+ replace: (_m, key2, delim, quote) => `${key2}${delim}${quote}${MASK}${quote}`
66438
66403
  },
66439
66404
  // Authorization: Bearer <token>
66440
66405
  {
@@ -66764,7 +66729,7 @@ ${body}
66764
66729
  }
66765
66730
  function applyPreLaunchTrust(trust, workingDir) {
66766
66731
  const settingsPath = expandHome2(trust.settings_path);
66767
- const key = trust.key;
66732
+ const key2 = trust.key;
66768
66733
  const real = realWorkspacePath(workingDir);
66769
66734
  try {
66770
66735
  let parsed = {};
@@ -66777,18 +66742,18 @@ ${body}
66777
66742
  }
66778
66743
  }
66779
66744
  }
66780
- const existing = parsed[key];
66745
+ const existing = parsed[key2];
66781
66746
  const list = Array.isArray(existing) ? existing.filter((v) => typeof v === "string") : [];
66782
66747
  if (list.includes(real)) {
66783
66748
  LOG2.debug("pre-launch-trust", `[${trust.settings_path}] ${real} already trusted \u2014 no change`);
66784
66749
  return null;
66785
66750
  }
66786
66751
  list.push(real);
66787
- parsed[key] = list;
66752
+ parsed[key2] = list;
66788
66753
  fs14.mkdirSync(path222.dirname(settingsPath), { recursive: true });
66789
66754
  fs14.writeFileSync(settingsPath, `${JSON.stringify(parsed, null, 2)}
66790
66755
  `, "utf8");
66791
- LOG2.info("pre-launch-trust", `pre-trusted workspace in ${trust.settings_path} (key="${key}")`);
66756
+ LOG2.info("pre-launch-trust", `pre-trusted workspace in ${trust.settings_path} (key="${key2}")`);
66792
66757
  return real;
66793
66758
  } catch (err) {
66794
66759
  LOG2.warn("pre-launch-trust", `failed to pre-trust workspace in ${trust.settings_path}: ${err.message}`);
@@ -68389,8 +68354,8 @@ ${body}
68389
68354
  }
68390
68355
  let end = i;
68391
68356
  while (end < expr.length && expr[end] !== "." && expr[end] !== "[") end += 1;
68392
- const key = expr.slice(i, end);
68393
- cur = cur[key];
68357
+ const key2 = expr.slice(i, end);
68358
+ cur = cur[key2];
68394
68359
  i = end;
68395
68360
  }
68396
68361
  return cur;
@@ -70351,8 +70316,8 @@ ${body}
70351
70316
  /** Drop user-input ack entries older than the dedup window so the map can't grow unbounded. */
70352
70317
  pruneRecentUserInputAcks(now) {
70353
70318
  if (this.recentUserInputAcks.size <= 1) return;
70354
- for (const [key, at] of this.recentUserInputAcks) {
70355
- if (now - at > USER_INPUT_ACK_DEDUP_WINDOW_MS) this.recentUserInputAcks.delete(key);
70319
+ for (const [key2, at] of this.recentUserInputAcks) {
70320
+ if (now - at > USER_INPUT_ACK_DEDUP_WINDOW_MS) this.recentUserInputAcks.delete(key2);
70356
70321
  }
70357
70322
  }
70358
70323
  dispose() {
@@ -71556,8 +71521,8 @@ ${effect.notification.body || ""}`.trim();
71556
71521
  };
71557
71522
  const isRuntimeOverlay = (entry) => {
71558
71523
  if (entry.source !== "runtime") return false;
71559
- const key = typeof entry.runtimeKey === "string" ? entry.runtimeKey.trim().toLowerCase() : "";
71560
- if (key.startsWith("auto_approval:")) return true;
71524
+ const key2 = typeof entry.runtimeKey === "string" ? entry.runtimeKey.trim().toLowerCase() : "";
71525
+ if (key2.startsWith("auto_approval:")) return true;
71561
71526
  return !isUserFacingChatMessage(entry.message);
71562
71527
  };
71563
71528
  const shouldKeepParsedBeforeUntimedRuntime = (message) => {
@@ -73154,16 +73119,16 @@ ${rawInput}` : rawInput;
73154
73119
  function hasCliArg(args, flag) {
73155
73120
  return args.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
73156
73121
  }
73157
- function hasConfigOverride(args, key) {
73122
+ function hasConfigOverride(args, key2) {
73158
73123
  for (let index = 0; index < args.length; index += 1) {
73159
73124
  const arg = args[index];
73160
73125
  const next = args[index + 1];
73161
73126
  if ((arg === "-c" || arg === "--config") && typeof next === "string") {
73162
- if (next === key || next.startsWith(`${key}=`) || next.startsWith(`${key}.`)) return true;
73127
+ if (next === key2 || next.startsWith(`${key2}=`) || next.startsWith(`${key2}.`)) return true;
73163
73128
  }
73164
73129
  if (arg.startsWith("--config=")) {
73165
73130
  const value = arg.slice("--config=".length);
73166
- if (value === key || value.startsWith(`${key}=`) || value.startsWith(`${key}.`)) return true;
73131
+ if (value === key2 || value.startsWith(`${key2}=`) || value.startsWith(`${key2}.`)) return true;
73167
73132
  }
73168
73133
  }
73169
73134
  return false;
@@ -73180,10 +73145,10 @@ ${rawInput}` : rawInput;
73180
73145
  const cliArgs = Array.isArray(input.cliArgs) ? [...input.cliArgs] : [];
73181
73146
  const env2 = { ...input.env || {} };
73182
73147
  const envUnsets = new Set(DEFAULT_COORDINATOR_DELEGATED_ENV_UNSETS);
73183
- for (const key of input.isolation?.env?.unset || []) {
73184
- if (typeof key === "string" && key.trim()) envUnsets.add(key.trim());
73148
+ for (const key2 of input.isolation?.env?.unset || []) {
73149
+ if (typeof key2 === "string" && key2.trim()) envUnsets.add(key2.trim());
73185
73150
  }
73186
- for (const key of envUnsets) env2[key] = "";
73151
+ for (const key2 of envUnsets) env2[key2] = "";
73187
73152
  for (const rule of input.isolation?.args || []) {
73188
73153
  if (!rule || typeof rule !== "object") continue;
73189
73154
  if (rule.mode === "empty_mcp_config") {
@@ -73196,9 +73161,9 @@ ${rawInput}` : rawInput;
73196
73161
  continue;
73197
73162
  }
73198
73163
  if (rule.mode === "config_override") {
73199
- const key = String(rule.dedupeKey || rule.key || "").trim();
73164
+ const key2 = String(rule.dedupeKey || rule.key || "").trim();
73200
73165
  const flag = String(rule.flag || "").trim();
73201
- if (!key || !flag || hasConfigOverride(cliArgs, key)) continue;
73166
+ if (!key2 || !flag || hasConfigOverride(cliArgs, key2)) continue;
73202
73167
  cliArgs.unshift(flag, `${rule.key}=${rule.value}`);
73203
73168
  }
73204
73169
  }
@@ -73404,12 +73369,12 @@ ${rawInput}` : rawInput;
73404
73369
  }
73405
73370
  throw new Error(`No CLI provider found for '${cliType}'. Create a provider.js in providers/cli/${cliType}/`);
73406
73371
  }
73407
- startCliExitMonitor(key, cliType) {
73372
+ startCliExitMonitor(key2, cliType) {
73408
73373
  const sessionRegistry = this.deps.getSessionRegistry?.() || null;
73409
73374
  const instanceManager = this.deps.getInstanceManager();
73410
73375
  const checkStopped = setInterval(() => {
73411
73376
  try {
73412
- const adapter = this.adapters.get(key);
73377
+ const adapter = this.adapters.get(key2);
73413
73378
  if (!adapter) {
73414
73379
  clearInterval(checkStopped);
73415
73380
  return;
@@ -73418,12 +73383,12 @@ ${rawInput}` : rawInput;
73418
73383
  if (status?.status === "stopped" || status?.status === "error") {
73419
73384
  clearInterval(checkStopped);
73420
73385
  setTimeout(() => {
73421
- if (this.adapters.has(key)) {
73422
- this.adapters.delete(key);
73423
- this.deps.removeAgentTracking(key);
73424
- sessionRegistry?.unregisterByInstanceKey(key);
73425
- instanceManager?.removeInstance(key);
73426
- unregisterMeshCoordinator(key);
73386
+ if (this.adapters.has(key2)) {
73387
+ this.adapters.delete(key2);
73388
+ this.deps.removeAgentTracking(key2);
73389
+ sessionRegistry?.unregisterByInstanceKey(key2);
73390
+ instanceManager?.removeInstance(key2);
73391
+ unregisterMeshCoordinator(key2);
73427
73392
  LOG2.info("CLI", `\u{1F9F9} Auto-cleaned ${status.status} CLI: ${cliType}`);
73428
73393
  this.deps.onStatusChange();
73429
73394
  }
@@ -73433,21 +73398,21 @@ ${rawInput}` : rawInput;
73433
73398
  }
73434
73399
  }, 3e3);
73435
73400
  }
73436
- async registerCliInstance(key, normalizedType, cliType, resolvedDir, cliArgs, provider, settings, attachExisting = false, options) {
73401
+ async registerCliInstance(key2, normalizedType, cliType, resolvedDir, cliArgs, provider, settings, attachExisting = false, options) {
73437
73402
  const instanceManager = this.deps.getInstanceManager();
73438
73403
  const sessionRegistry = this.deps.getSessionRegistry?.() || null;
73439
73404
  if (!instanceManager) throw new Error("InstanceManager not available");
73440
73405
  const transportFactory = this.getTransportFactory(
73441
- key,
73406
+ key2,
73442
73407
  normalizedType,
73443
73408
  resolvedDir,
73444
73409
  cliArgs,
73445
73410
  options?.providerSessionId,
73446
73411
  attachExisting
73447
73412
  );
73448
- const cliInstance = new CliProviderInstance(provider, resolvedDir, cliArgs, key, transportFactory, options);
73413
+ const cliInstance = new CliProviderInstance(provider, resolvedDir, cliArgs, key2, transportFactory, options);
73449
73414
  try {
73450
- await instanceManager.addInstance(key, cliInstance, {
73415
+ await instanceManager.addInstance(key2, cliInstance, {
73451
73416
  serverConn: this.deps.getServerConn(),
73452
73417
  settings,
73453
73418
  onPtyData: (data) => {
@@ -73459,8 +73424,8 @@ ${rawInput}` : rawInput;
73459
73424
  parentSessionId: null,
73460
73425
  providerType: normalizedType,
73461
73426
  transport: "pty",
73462
- adapterKey: key,
73463
- instanceKey: key,
73427
+ adapterKey: key2,
73428
+ instanceKey: key2,
73464
73429
  workspace: resolvedDir,
73465
73430
  // attachExisting === true means we're restoring an already-spawned
73466
73431
  // hosted runtime after a daemon restart, not starting a fresh PTY.
@@ -73476,10 +73441,10 @@ ${rawInput}` : rawInput;
73476
73441
  });
73477
73442
  } catch (spawnErr) {
73478
73443
  LOG2.error("CLI", `[${cliType}] Spawn failed: ${spawnErr?.message}`);
73479
- instanceManager.removeInstance(key);
73444
+ instanceManager.removeInstance(key2);
73480
73445
  throw new Error(`Failed to start ${provider.displayName || provider.name || cliType}: ${spawnErr?.message}`);
73481
73446
  }
73482
- this.adapters.set(key, cliInstance.getAdapter());
73447
+ this.adapters.set(key2, cliInstance.getAdapter());
73483
73448
  const launchMeshNodeId = typeof settings?.meshNodeId === "string" ? settings.meshNodeId.trim() : "";
73484
73449
  const launchMeshNodeFor = typeof settings?.meshNodeFor === "string" ? settings.meshNodeFor.trim() : "";
73485
73450
  if (launchMeshNodeId || launchMeshNodeFor) {
@@ -73492,7 +73457,7 @@ ${rawInput}` : rawInput;
73492
73457
  } catch {
73493
73458
  }
73494
73459
  }
73495
- this.startCliExitMonitor(key, cliType);
73460
+ this.startCliExitMonitor(key2, cliType);
73496
73461
  }
73497
73462
  // ─── Session start/management ──────────────────────────────
73498
73463
  async startSession(cliType, workingDir, cliArgs, initialModel, options) {
@@ -73509,11 +73474,11 @@ ${rawInput}` : rawInput;
73509
73474
  Enable and detect this provider from the Machine Providers page before starting a runtime.`
73510
73475
  );
73511
73476
  }
73512
- const key = crypto5.randomUUID();
73477
+ const key2 = crypto5.randomUUID();
73513
73478
  {
73514
73479
  const coordinatorMeshId = options?.settingsOverride?.meshCoordinatorFor;
73515
73480
  if (typeof coordinatorMeshId === "string" && coordinatorMeshId.trim()) {
73516
- options = { ...options, extraEnv: { ...options?.extraEnv || {}, ADHDEV_COORDINATOR_SESSION_ID: key } };
73481
+ options = { ...options, extraEnv: { ...options?.extraEnv || {}, ADHDEV_COORDINATOR_SESSION_ID: key2 } };
73517
73482
  }
73518
73483
  }
73519
73484
  const sessionRegistry = this.deps.getSessionRegistry?.() || null;
@@ -73533,7 +73498,7 @@ ${installInfo}`
73533
73498
  }
73534
73499
  console.log(colorize("cyan", ` \u{1F50C} Starting ACP agent: ${provider.name} (${provider.type}) in ${resolvedDir}`));
73535
73500
  const acpInstance = new AcpProviderInstance(resolvedProvider, resolvedDir, cliArgs);
73536
- await instanceManager2.addInstance(key, acpInstance, {
73501
+ await instanceManager2.addInstance(key2, acpInstance, {
73537
73502
  settings: this.providerLoader.getSettings(normalizedType)
73538
73503
  });
73539
73504
  const sessionId = acpInstance.getInstanceId();
@@ -73542,11 +73507,11 @@ ${installInfo}`
73542
73507
  parentSessionId: null,
73543
73508
  providerType: normalizedType,
73544
73509
  transport: "acp",
73545
- adapterKey: key,
73546
- instanceKey: key,
73510
+ adapterKey: key2,
73511
+ instanceKey: key2,
73547
73512
  workspace: resolvedDir
73548
73513
  });
73549
- this.adapters.set(key, {
73514
+ this.adapters.set(key2, {
73550
73515
  cliType: normalizedType,
73551
73516
  cliName: provider.name,
73552
73517
  workingDir: resolvedDir,
@@ -73554,7 +73519,7 @@ ${installInfo}`
73554
73519
  spawn: async () => {
73555
73520
  },
73556
73521
  shutdown: () => {
73557
- instanceManager2.removeInstance(key);
73522
+ instanceManager2.removeInstance(key2);
73558
73523
  },
73559
73524
  sendMessage: async (text) => {
73560
73525
  const input = normalizeInputEnvelope(text);
@@ -73570,7 +73535,7 @@ ${installInfo}`
73570
73535
  },
73571
73536
  getPartialResponse: () => "",
73572
73537
  cancel: () => {
73573
- instanceManager2.removeInstance(key);
73538
+ instanceManager2.removeInstance(key2);
73574
73539
  },
73575
73540
  isProcessing: () => false,
73576
73541
  isReady: () => true,
@@ -73624,7 +73589,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
73624
73589
  if (provider && instanceManager) {
73625
73590
  const resolvedProvider = this.providerLoader.resolve(cliType, { version: cliInfo.version }) || provider;
73626
73591
  await this.registerCliInstance(
73627
- key,
73592
+ key2,
73628
73593
  normalizedType,
73629
73594
  cliType,
73630
73595
  resolvedDir,
@@ -73654,7 +73619,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
73654
73619
  cliType,
73655
73620
  resolvedDir,
73656
73621
  resolvedCliArgs,
73657
- key,
73622
+ key2,
73658
73623
  sessionBinding.providerSessionId,
73659
73624
  false,
73660
73625
  options?.extraEnv
@@ -73674,9 +73639,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
73674
73639
  const status = adapter.getStatus?.();
73675
73640
  if (status?.status === "stopped" || status?.status === "error") {
73676
73641
  setTimeout(() => {
73677
- if (this.adapters.get(key) === adapter) {
73678
- this.adapters.delete(key);
73679
- this.deps.removeAgentTracking(key);
73642
+ if (this.adapters.get(key2) === adapter) {
73643
+ this.adapters.delete(key2);
73644
+ this.deps.removeAgentTracking(key2);
73680
73645
  LOG2.info("CLI", `\u{1F9F9} Auto-cleaned ${status.status} CLI: ${adapter.cliType}`);
73681
73646
  this.deps.onStatusChange();
73682
73647
  }
@@ -73685,10 +73650,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
73685
73650
  });
73686
73651
  if (typeof adapter.setOnPtyData === "function") {
73687
73652
  adapter.setOnPtyData((data) => {
73688
- this.deps.getP2p()?.broadcastSessionOutput(key, data);
73653
+ this.deps.getP2p()?.broadcastSessionOutput(key2, data);
73689
73654
  });
73690
73655
  }
73691
- this.adapters.set(key, adapter);
73656
+ this.adapters.set(key2, adapter);
73692
73657
  console.log(colorize("green", ` \u2713 CLI started: ${cliInfo.displayName} v${cliInfo.version || "unknown"} in ${resolvedDir}`));
73693
73658
  }
73694
73659
  this.persistRecentActivity({
@@ -73698,20 +73663,20 @@ Run 'adhdev doctor' for detailed diagnostics.`
73698
73663
  providerSessionId: sessionBinding.providerSessionId,
73699
73664
  workspace: resolvedDir,
73700
73665
  summaryMetadata: buildLegacyModelModeSummaryMetadata({ model: initialModel }),
73701
- sessionId: key,
73666
+ sessionId: key2,
73702
73667
  title: provider?.displayName || provider?.name || normalizedType
73703
73668
  });
73704
73669
  this.deps.onStatusChange();
73705
73670
  return {
73706
- runtimeSessionId: key,
73671
+ runtimeSessionId: key2,
73707
73672
  providerSessionId: sessionBinding.providerSessionId
73708
73673
  };
73709
73674
  }
73710
- async stopSession(key) {
73711
- return this.stopSessionWithMode(key, "hard");
73675
+ async stopSession(key2) {
73676
+ return this.stopSessionWithMode(key2, "hard");
73712
73677
  }
73713
- async stopSessionWithMode(key, mode) {
73714
- const adapter = this.adapters.get(key);
73678
+ async stopSessionWithMode(key2, mode) {
73679
+ const adapter = this.adapters.get(key2);
73715
73680
  if (adapter) {
73716
73681
  try {
73717
73682
  if (mode === "save" && typeof adapter.saveAndStop === "function") {
@@ -73722,21 +73687,21 @@ Run 'adhdev doctor' for detailed diagnostics.`
73722
73687
  } catch (e) {
73723
73688
  LOG2.warn("CLI", `Shutdown error for ${adapter.cliType}: ${e?.message} (force-cleaning)`);
73724
73689
  }
73725
- this.adapters.delete(key);
73726
- this.deps.removeAgentTracking(key);
73727
- this.deps.getSessionRegistry?.()?.unregisterByInstanceKey(key);
73728
- this.deps.getInstanceManager()?.removeInstance(key);
73729
- unregisterMeshCoordinator(key);
73690
+ this.adapters.delete(key2);
73691
+ this.deps.removeAgentTracking(key2);
73692
+ this.deps.getSessionRegistry?.()?.unregisterByInstanceKey(key2);
73693
+ this.deps.getInstanceManager()?.removeInstance(key2);
73694
+ unregisterMeshCoordinator(key2);
73730
73695
  LOG2.info("CLI", `\u{1F6D1} Agent stopped: ${adapter.cliType} in ${adapter.workingDir}`);
73731
73696
  this.deps.onStatusChange();
73732
73697
  } else {
73733
73698
  const im = this.deps.getInstanceManager();
73734
73699
  if (im) {
73735
- this.deps.getSessionRegistry?.()?.unregisterByInstanceKey(key);
73736
- im.removeInstance(key);
73737
- this.deps.removeAgentTracking(key);
73738
- unregisterMeshCoordinator(key);
73739
- LOG2.warn("CLI", `\u{1F9F9} Force-removed orphan entry: ${key}`);
73700
+ this.deps.getSessionRegistry?.()?.unregisterByInstanceKey(key2);
73701
+ im.removeInstance(key2);
73702
+ this.deps.removeAgentTracking(key2);
73703
+ unregisterMeshCoordinator(key2);
73704
+ LOG2.warn("CLI", `\u{1F9F9} Force-removed orphan entry: ${key2}`);
73740
73705
  this.deps.onStatusChange();
73741
73706
  }
73742
73707
  }
@@ -73764,8 +73729,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
73764
73729
  for (const r of sessions) {
73765
73730
  if (!r?.runtimeId || !r?.cliType || !r?.workspace) continue;
73766
73731
  restoredRuntimeIds.add(r.runtimeId);
73767
- const key = `${r.workspace}::${r.cliType}`;
73768
- workspaceTypeCounts.set(key, (workspaceTypeCounts.get(key) || 0) + 1);
73732
+ const key2 = `${r.workspace}::${r.cliType}`;
73733
+ workspaceTypeCounts.set(key2, (workspaceTypeCounts.get(key2) || 0) + 1);
73769
73734
  }
73770
73735
  for (const record2 of sessions) {
73771
73736
  if (!record2?.runtimeId || !record2?.cliType || !record2?.workspace) continue;
@@ -74119,7 +74084,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
74119
74084
  });
74120
74085
  }
74121
74086
  if (!found) throw new Error(`CLI agent not running: ${agentType}`);
74122
- const { adapter, key } = found;
74087
+ const { adapter, key: key2 } = found;
74123
74088
  if (action === "send_chat") {
74124
74089
  let currentStatus = getEffectiveAgentSendStatus(adapter);
74125
74090
  if (currentStatus === "starting" && await waitForZeroMessageStartingLaunch(adapter)) {
@@ -74129,7 +74094,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
74129
74094
  }
74130
74095
  const meshContext = args?.meshContext;
74131
74096
  if (meshContext && typeof meshContext === "object" && typeof meshContext.meshId === "string" && meshContext.meshId) {
74132
- const targetInstanceId = key;
74097
+ const targetInstanceId = key2;
74133
74098
  try {
74134
74099
  this.deps.getInstanceManager()?.attachMeshAssignmentToInstance(targetInstanceId, {
74135
74100
  meshId: meshContext.meshId,
@@ -74161,7 +74126,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
74161
74126
  } else {
74162
74127
  await adapter.sendMessage(message);
74163
74128
  }
74164
- const targetInstance = this.deps.getInstanceManager()?.getInstance(key);
74129
+ const targetInstance = this.deps.getInstanceManager()?.getInstance(key2);
74165
74130
  targetInstance?.recordAcknowledgedUserInput?.(input);
74166
74131
  return {
74167
74132
  success: true,
@@ -74173,7 +74138,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
74173
74138
  if (typeof adapter.clearHistory === "function") adapter.clearHistory();
74174
74139
  return { success: true, cleared: true };
74175
74140
  } else if (action === "stop") {
74176
- await this.stopSession(key);
74141
+ await this.stopSession(key2);
74177
74142
  return { success: true, stopped: true };
74178
74143
  }
74179
74144
  throw new Error(`Unknown action: ${action}`);
@@ -74437,9 +74402,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
74437
74402
  } else if (!["ide", "extension", "cli", "acp"].includes(String(provider.category))) {
74438
74403
  errors.push(`Invalid category: ${String(provider.category)}`);
74439
74404
  }
74440
- for (const key of Object.keys(provider)) {
74441
- if (!KNOWN_PROVIDER_FIELDS.has(key)) {
74442
- warnings.push(`Unknown provider field: ${key}`);
74405
+ for (const key2 of Object.keys(provider)) {
74406
+ if (!KNOWN_PROVIDER_FIELDS.has(key2)) {
74407
+ warnings.push(`Unknown provider field: ${key2}`);
74443
74408
  }
74444
74409
  }
74445
74410
  if (provider.disableUpstream !== void 0) {
@@ -74584,10 +74549,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
74584
74549
  return;
74585
74550
  }
74586
74551
  const scriptConfig = scripts;
74587
- for (const key of ["readSession", "listSessions"]) {
74588
- const value = scriptConfig[key];
74552
+ for (const key2 of ["readSession", "listSessions"]) {
74553
+ const value = scriptConfig[key2];
74589
74554
  if (typeof value !== "string" || !value.trim()) {
74590
- errors.push(`nativeHistory.scripts.${key} must be a non-empty string`);
74555
+ errors.push(`nativeHistory.scripts.${key2} must be a non-empty string`);
74591
74556
  }
74592
74557
  }
74593
74558
  }
@@ -74622,10 +74587,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
74622
74587
  if (format !== void 0 && !["claude_mcp_json", "hermes_config_yaml"].includes(String(format))) {
74623
74588
  errors.push("meshCoordinator.mcpConfig.format must be one of: claude_mcp_json, hermes_config_yaml");
74624
74589
  }
74625
- for (const key of ["path", "serverName", "configPathCommand", "instructions", "template"]) {
74626
- const value = config2[key];
74590
+ for (const key2 of ["path", "serverName", "configPathCommand", "instructions", "template"]) {
74591
+ const value = config2[key2];
74627
74592
  if (value !== void 0 && (typeof value !== "string" || !value.trim())) {
74628
- errors.push(`meshCoordinator.mcpConfig.${key} must be a non-empty string when provided`);
74593
+ errors.push(`meshCoordinator.mcpConfig.${key2} must be a non-empty string when provided`);
74629
74594
  }
74630
74595
  }
74631
74596
  if (config2.requiresRestart !== void 0 && typeof config2.requiresRestart !== "boolean") {
@@ -74661,7 +74626,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
74661
74626
  errors.push("meshCoordinator.delegatedWorkerIsolation.env must be an object");
74662
74627
  } else {
74663
74628
  const unset = env2.unset;
74664
- if (unset !== void 0 && (!Array.isArray(unset) || unset.some((key) => typeof key !== "string" || !key.trim()))) {
74629
+ if (unset !== void 0 && (!Array.isArray(unset) || unset.some((key2) => typeof key2 !== "string" || !key2.trim()))) {
74665
74630
  errors.push("meshCoordinator.delegatedWorkerIsolation.env.unset must be an array of non-empty strings");
74666
74631
  }
74667
74632
  }
@@ -74684,16 +74649,16 @@ Run 'adhdev doctor' for detailed diagnostics.`
74684
74649
  errors.push(`${prefix}.mode must be one of: empty_mcp_config, config_override`);
74685
74650
  continue;
74686
74651
  }
74687
- for (const key of mode === "empty_mcp_config" ? ["flag"] : ["flag", "key", "value"]) {
74688
- const value = item[key];
74652
+ for (const key2 of mode === "empty_mcp_config" ? ["flag"] : ["flag", "key", "value"]) {
74653
+ const value = item[key2];
74689
74654
  if (typeof value !== "string" || !value.trim()) {
74690
- errors.push(`${prefix}.${key} must be a non-empty string`);
74655
+ errors.push(`${prefix}.${key2} must be a non-empty string`);
74691
74656
  }
74692
74657
  }
74693
- for (const key of ["strictFlag", "dedupeKey"]) {
74694
- const value = item[key];
74658
+ for (const key2 of ["strictFlag", "dedupeKey"]) {
74659
+ const value = item[key2];
74695
74660
  if (value !== void 0 && (typeof value !== "string" || !value.trim())) {
74696
- errors.push(`${prefix}.${key} must be a non-empty string when provided`);
74661
+ errors.push(`${prefix}.${key2} must be a non-empty string when provided`);
74697
74662
  }
74698
74663
  }
74699
74664
  }
@@ -76900,9 +76865,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
76900
76865
  reload() {
76901
76866
  this.log("Reloading all providers...");
76902
76867
  this.scriptsCache.clear();
76903
- for (const key of Object.keys(require.cache)) {
76904
- if (key.includes("providers") && (key.endsWith(".js") || key.endsWith(".json"))) {
76905
- delete require.cache[key];
76868
+ for (const key2 of Object.keys(require.cache)) {
76869
+ if (key2.includes("providers") && (key2.endsWith(".js") || key2.endsWith(".json"))) {
76870
+ delete require.cache[key2];
76906
76871
  }
76907
76872
  }
76908
76873
  this.loadAll();
@@ -77210,7 +77175,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
77210
77175
  */
77211
77176
  getPublicSettings(type) {
77212
77177
  const settings = this.getSettingsSchema(type);
77213
- return Object.entries(settings).filter(([, def]) => def.public === true).map(([key, def]) => ({ key, ...def }));
77178
+ return Object.entries(settings).filter(([, def]) => def.public === true).map(([key2, def]) => ({ key: key2, ...def }));
77214
77179
  }
77215
77180
  /**
77216
77181
  * Get public settings schema for all providers
@@ -77226,23 +77191,23 @@ Run 'adhdev doctor' for detailed diagnostics.`
77226
77191
  /**
77227
77192
  * Resolved setting value for a provider (default + user override)
77228
77193
  */
77229
- getSettingValue(type, key) {
77194
+ getSettingValue(type, key2) {
77230
77195
  const providerType = this.resolveAlias(type);
77231
77196
  const machineConfig = this.getMachineProviderConfig(providerType);
77232
- if (key === "enabled") {
77197
+ if (key2 === "enabled") {
77233
77198
  return machineConfig.enabled === true;
77234
77199
  }
77235
- if (key === "executablePath") {
77200
+ if (key2 === "executablePath") {
77236
77201
  return machineConfig.executable || "";
77237
77202
  }
77238
- if (key === "executableArgs") {
77203
+ if (key2 === "executableArgs") {
77239
77204
  const args = machineConfig.args;
77240
77205
  return args ? args.map((arg) => /\s/.test(arg) ? JSON.stringify(arg) : arg).join(" ") : "";
77241
77206
  }
77242
- const schemaDef = this.getSettingsSchema(providerType)[key];
77207
+ const schemaDef = this.getSettingsSchema(providerType)[key2];
77243
77208
  const defaultVal = schemaDef ? schemaDef.default : void 0;
77244
77209
  const config2 = this.readConfig();
77245
- const userVal = config2?.providerSettings?.[providerType]?.[key];
77210
+ const userVal = config2?.providerSettings?.[providerType]?.[key2];
77246
77211
  return userVal !== void 0 ? userVal : defaultVal;
77247
77212
  }
77248
77213
  /**
@@ -77252,17 +77217,17 @@ Run 'adhdev doctor' for detailed diagnostics.`
77252
77217
  const providerType = this.resolveAlias(type);
77253
77218
  const settings = this.getSettingsSchema(providerType);
77254
77219
  const result = {};
77255
- for (const [key] of Object.entries(settings)) {
77256
- result[key] = this.getSettingValue(providerType, key);
77220
+ for (const [key2] of Object.entries(settings)) {
77221
+ result[key2] = this.getSettingValue(providerType, key2);
77257
77222
  }
77258
77223
  return result;
77259
77224
  }
77260
77225
  /**
77261
77226
  * Save provider setting value (writes to config.json)
77262
77227
  */
77263
- setSetting(type, key, value) {
77228
+ setSetting(type, key2, value) {
77264
77229
  const providerType = this.resolveAlias(type);
77265
- const schemaDef = this.getSettingsSchema(providerType)[key];
77230
+ const schemaDef = this.getSettingsSchema(providerType)[key2];
77266
77231
  if (!schemaDef) return false;
77267
77232
  if (!schemaDef.public) return false;
77268
77233
  if (schemaDef.type === "boolean" && typeof value !== "boolean") return false;
@@ -77273,13 +77238,13 @@ Run 'adhdev doctor' for detailed diagnostics.`
77273
77238
  if (schemaDef.max !== void 0 && value > schemaDef.max) return false;
77274
77239
  }
77275
77240
  if (schemaDef.type === "select" && schemaDef.options && !schemaDef.options.includes(value)) return false;
77276
- if (key === "enabled") {
77241
+ if (key2 === "enabled") {
77277
77242
  return this.setMachineProviderEnabled(providerType, value);
77278
77243
  }
77279
- if (key === "executablePath") {
77244
+ if (key2 === "executablePath") {
77280
77245
  return this.setMachineProviderConfig(providerType, { executable: value });
77281
77246
  }
77282
- if (key === "executableArgs") {
77247
+ if (key2 === "executableArgs") {
77283
77248
  return this.setMachineProviderConfig(providerType, {
77284
77249
  args: value.trim() ? this.parseArgsSetting(value) : void 0
77285
77250
  });
@@ -77289,17 +77254,17 @@ Run 'adhdev doctor' for detailed diagnostics.`
77289
77254
  try {
77290
77255
  if (!config2.providerSettings) config2.providerSettings = {};
77291
77256
  if (!config2.providerSettings[providerType]) config2.providerSettings[providerType] = {};
77292
- config2.providerSettings[providerType][key] = value;
77257
+ config2.providerSettings[providerType][key2] = value;
77293
77258
  this.writeConfig(config2);
77294
- this.log(`Setting updated: ${providerType}.${key} = ${JSON.stringify(value)}`);
77259
+ this.log(`Setting updated: ${providerType}.${key2} = ${JSON.stringify(value)}`);
77295
77260
  return true;
77296
77261
  } catch (e) {
77297
77262
  this.log(`Failed to save setting: ${e.message}`);
77298
77263
  return false;
77299
77264
  }
77300
77265
  }
77301
- getOptionalStringSetting(type, key) {
77302
- const value = this.getSettingValue(type, key);
77266
+ getOptionalStringSetting(type, key2) {
77267
+ const value = this.getSettingValue(type, key2);
77303
77268
  if (typeof value !== "string") return null;
77304
77269
  const trimmed = value.trim();
77305
77270
  return trimmed ? trimmed : null;
@@ -77479,7 +77444,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
77479
77444
  try {
77480
77445
  let content = fs25.readFileSync(filePath, "utf-8");
77481
77446
  if (args[0] && typeof args[0] === "object") {
77482
- for (const [key, val] of Object.entries(args[0])) {
77447
+ for (const [key2, val] of Object.entries(args[0])) {
77483
77448
  let v = val;
77484
77449
  if (typeof v === "string") {
77485
77450
  if (!v.startsWith('"') && !v.startsWith("'") && !v.startsWith("`")) {
@@ -77488,7 +77453,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
77488
77453
  } else {
77489
77454
  v = JSON.stringify(v);
77490
77455
  }
77491
- const re = new RegExp(`\\$\\{\\s*${key}\\s*\\}`, "g");
77456
+ const re = new RegExp(`\\$\\{\\s*${key2}\\s*\\}`, "g");
77492
77457
  content = content.replace(re, String(v));
77493
77458
  }
77494
77459
  } else if (typeof args[0] === "string") {
@@ -78269,6 +78234,21 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
78269
78234
  init_worktree_bootstrap_config();
78270
78235
  init_mesh_events();
78271
78236
  init_config();
78237
+ async function decideOssCloneSync(ossCtx, worktreeOssSha, sourceSha, rg) {
78238
+ if (!worktreeOssSha || !sourceSha || worktreeOssSha === sourceSha) return "noop";
78239
+ const isAncestor = async (ancestor, descendant) => {
78240
+ try {
78241
+ await rg(ossCtx, ["merge-base", "--is-ancestor", ancestor, descendant], { timeoutMs: 1e4 });
78242
+ return true;
78243
+ } catch (err) {
78244
+ if (err?.exitCode === 1 || err?.code === 1) return false;
78245
+ throw err;
78246
+ }
78247
+ };
78248
+ if (await isAncestor(sourceSha, worktreeOssSha)) return "skip_rewind";
78249
+ if (await isAncestor(worktreeOssSha, sourceSha)) return "advance";
78250
+ return "skip_diverged";
78251
+ }
78272
78252
  var meshCrudHandlers = {
78273
78253
  list_meshes: async (_ctx, _args) => {
78274
78254
  try {
@@ -78359,7 +78339,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
78359
78339
  // entry. This is an export scaffold for the operator to review and commit to
78360
78340
  // the repo, NOT an automatic data migration: nothing is written to disk and
78361
78341
  // meshes.json is untouched. The returned `scaffold` (object) + `scaffoldJson`
78362
- // (2-space text) capture the local policy + coordinator prompt override/append.
78342
+ // (2-space text) capture the coordinator prompt override/append (policy is
78343
+ // machine-local and is intentionally NOT exported into mesh.json).
78363
78344
  export_mesh_json_config: async (_ctx, args) => {
78364
78345
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
78365
78346
  if (!meshId) return { success: false, error: "meshId required" };
@@ -78730,7 +78711,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
78730
78711
  }
78731
78712
  };
78732
78713
  const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
78733
- const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
78714
+ const loadedBootstrap = loadRepoSettings({ workspace: result.worktreePath, mesh }).worktreeBootstrap;
78734
78715
  const runningBootstrapState = {
78735
78716
  status: "running",
78736
78717
  required: loadedBootstrap.config?.required !== false,
@@ -78764,12 +78745,25 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
78764
78745
  const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
78765
78746
  const worktreeOssHeadOut = await rg(ossCtx, ["rev-parse", "HEAD"], { timeoutMs: 1e4 });
78766
78747
  const worktreeOssSha = (typeof worktreeOssHeadOut === "string" ? worktreeOssHeadOut : worktreeOssHeadOut?.stdout ?? "").trim();
78767
- if (worktreeOssSha !== sourceSha) {
78748
+ if (worktreeOssSha && worktreeOssSha !== sourceSha) {
78768
78749
  await rg(ossCtx, ["fetch", `${sourceWorkspace}/oss`, "HEAD"], { timeoutMs: 6e4 });
78769
- await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
78770
- await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
78771
- await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
78772
- console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
78750
+ let ossAction;
78751
+ try {
78752
+ ossAction = await decideOssCloneSync(ossCtx, worktreeOssSha, sourceSha, rg);
78753
+ } catch (decideErr) {
78754
+ ossAction = "skip_diverged";
78755
+ console.warn(`[mesh] oss submodule sync guard could not resolve ancestry (kept fresh worktree HEAD): ${decideErr?.message ?? decideErr}`);
78756
+ }
78757
+ if (ossAction === "advance") {
78758
+ await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
78759
+ await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
78760
+ await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
78761
+ console.log(`[mesh] Advanced oss submodule to newer source HEAD ${sourceSha.slice(0, 8)} in worktree`);
78762
+ } else if (ossAction === "skip_rewind") {
78763
+ console.warn(`[mesh] Skipped oss submodule rewind on clone: source node oss ${sourceSha.slice(0, 8)} is an ancestor of the fresh worktree oss ${worktreeOssSha.slice(0, 8)} \u2014 kept fresher worktree HEAD`);
78764
+ } else if (ossAction === "skip_diverged") {
78765
+ console.warn(`[mesh] Skipped oss submodule sync on clone: source node oss ${sourceSha.slice(0, 8)} diverged from the fresh worktree oss ${worktreeOssSha.slice(0, 8)} \u2014 kept worktree HEAD (coordinator reconciles)`);
78766
+ }
78773
78767
  }
78774
78768
  }
78775
78769
  } catch (ossErr) {
@@ -79199,9 +79193,20 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
79199
79193
  targetNodeId: typeof args?.targetNodeId === "string" ? args.targetNodeId.trim() : void 0,
79200
79194
  targetSessionId: typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : void 0,
79201
79195
  clearTargetNode: args?.clearTargetNode === true,
79202
- clearTargetSession: args?.clearTargetSession !== false
79196
+ clearTargetSession: args?.clearTargetSession !== false,
79197
+ // CANON-IDENTITY: an in-flight (actively-generating) task is refused by
79198
+ // default to avoid a duplicate second dispatch; an explicit operator
79199
+ // force overrides that guard (and the retry cap).
79200
+ force: args?.force === true
79203
79201
  });
79204
79202
  if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
79203
+ if (task.status === "assigned" && args?.force !== true) {
79204
+ return {
79205
+ success: false,
79206
+ error: `Task '${taskId}' is actively dispatched/generating; requeue refused to avoid a duplicate second dispatch. Pass force:true to override, or cancel and re-enqueue.`,
79207
+ task
79208
+ };
79209
+ }
79205
79210
  return { success: true, task };
79206
79211
  } catch (e) {
79207
79212
  return { success: false, error: e.message };
@@ -80706,15 +80711,15 @@ ${ptyResult.output.slice(-2e3)}`);
80706
80711
  function maskArgs(args) {
80707
80712
  if (!args || typeof args !== "object") return void 0;
80708
80713
  const masked = {};
80709
- for (const [key, value] of Object.entries(args)) {
80710
- if (SENSITIVE_KEYS.has(key)) {
80711
- masked[key] = typeof value === "string" ? `[${value.length} chars]` : "[masked]";
80712
- } else if (key.startsWith("_")) {
80713
- masked[key] = value;
80714
+ for (const [key2, value] of Object.entries(args)) {
80715
+ if (SENSITIVE_KEYS.has(key2)) {
80716
+ masked[key2] = typeof value === "string" ? `[${value.length} chars]` : "[masked]";
80717
+ } else if (key2.startsWith("_")) {
80718
+ masked[key2] = value;
80714
80719
  } else if (typeof value === "object" && value !== null) {
80715
- masked[key] = Array.isArray(value) ? `[Array(${value.length})]` : `[Object]`;
80720
+ masked[key2] = Array.isArray(value) ? `[Array(${value.length})]` : `[Object]`;
80716
80721
  } else {
80717
- masked[key] = value;
80722
+ masked[key2] = value;
80718
80723
  }
80719
80724
  }
80720
80725
  return masked;
@@ -81803,23 +81808,23 @@ ${ptyResult.output.slice(-2e3)}`);
81803
81808
  * neither gate is satisfied.
81804
81809
  */
81805
81810
  async probe(daemonId, workspace, probe) {
81806
- const key = this.key(daemonId, workspace);
81807
- const cached3 = this.recent.get(key);
81811
+ const key2 = this.key(daemonId, workspace);
81812
+ const cached3 = this.recent.get(key2);
81808
81813
  if (cached3 && this.now() - cached3.at < this.reuseMs) {
81809
81814
  return cached3.value;
81810
81815
  }
81811
- const existing = this.inflight.get(key);
81816
+ const existing = this.inflight.get(key2);
81812
81817
  if (existing) return existing;
81813
81818
  const pending = (async () => {
81814
81819
  const result = await probe();
81815
- if (result) this.recent.set(key, { at: this.now(), value: result });
81820
+ if (result) this.recent.set(key2, { at: this.now(), value: result });
81816
81821
  return result;
81817
81822
  })();
81818
- this.inflight.set(key, pending);
81823
+ this.inflight.set(key2, pending);
81819
81824
  try {
81820
81825
  return await pending;
81821
81826
  } finally {
81822
- if (this.inflight.get(key) === pending) this.inflight.delete(key);
81827
+ if (this.inflight.get(key2) === pending) this.inflight.delete(key2);
81823
81828
  }
81824
81829
  }
81825
81830
  };
@@ -84511,8 +84516,8 @@ ${mergeTreeErr?.stderr || ""}`;
84511
84516
  if (source !== "refine_mesh_node_async_job") continue;
84512
84517
  const jobId = e.payload?.refineJob?.jobId;
84513
84518
  if (!jobId || terminal.has(`${e.nodeId}:${jobId}`)) continue;
84514
- const key = this.buildRefineJobKey(meshId, e.nodeId);
84515
- if (this.runningRefineJobs.has(key)) continue;
84519
+ const key2 = this.buildRefineJobKey(meshId, e.nodeId);
84520
+ if (this.runningRefineJobs.has(key2)) continue;
84516
84521
  const coordinatorDaemonId = e.payload?.refineJob?.targetCoordinatorDaemonId;
84517
84522
  LOG2.info("Mesh", `[Refinery] Auto-resuming interrupted refine job for node ${e.nodeId} (jobId=${jobId})`);
84518
84523
  void this.startMeshRefineJob(meshId, e.nodeId, {
@@ -85595,7 +85600,7 @@ ${hintLines.join("\n")}` : "",
85595
85600
  }
85596
85601
  }
85597
85602
  async finishMeshRefineBatchJob(handle, orderedNodes, ordering, args) {
85598
- const key = this.buildRefineBatchJobKey(handle.meshId);
85603
+ const key2 = this.buildRefineBatchJobKey(handle.meshId);
85599
85604
  let result;
85600
85605
  try {
85601
85606
  result = await this.runMeshRefineBatchConvergence(handle.meshId, orderedNodes, ordering, args);
@@ -85627,8 +85632,8 @@ ${hintLines.join("\n")}` : "",
85627
85632
  coordinatorDaemonId: handle.targetCoordinatorDaemonId
85628
85633
  });
85629
85634
  const terminal = { ...terminalHandle, result: normalizedResult };
85630
- this.terminalRefineBatchJobs.set(key, terminal);
85631
- this.runningRefineBatchJobs.delete(key);
85635
+ this.terminalRefineBatchJobs.set(key2, terminal);
85636
+ this.runningRefineBatchJobs.delete(key2);
85632
85637
  this.invalidateAggregateMeshStatus(handle.meshId);
85633
85638
  await this.appendRefineBatchJobLedger(isTerminalSuccess ? "task_completed" : "task_failed", terminalHandle, normalizedResult);
85634
85639
  this.queueRefineBatchJobEvent(isTerminalSuccess ? "refine:completed" : "refine:failed", terminalHandle, normalizedResult);
@@ -85652,8 +85657,8 @@ ${hintLines.join("\n")}` : "",
85652
85657
  if (nodeIds.length === 0) {
85653
85658
  return { ...planRecord, success: true, batch: true, dryRun: false, async: false };
85654
85659
  }
85655
- const key = this.buildRefineBatchJobKey(meshId);
85656
- const running = this.runningRefineBatchJobs.get(key);
85660
+ const key2 = this.buildRefineBatchJobKey(meshId);
85661
+ const running = this.runningRefineBatchJobs.get(key2);
85657
85662
  if (running) return { ...running, duplicate: true };
85658
85663
  const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
85659
85664
  const mesh = meshRecord?.mesh;
@@ -85668,7 +85673,7 @@ ${hintLines.join("\n")}` : "",
85668
85673
  };
85669
85674
  const coordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : this.deps.statusInstanceId || void 0;
85670
85675
  const handle = this.buildRefineBatchJobHandle({ meshId, nodeIds, order, coordinatorDaemonId });
85671
- this.runningRefineBatchJobs.set(key, handle);
85676
+ this.runningRefineBatchJobs.set(key2, handle);
85672
85677
  await this.appendRefineBatchJobLedger("task_dispatched", handle);
85673
85678
  this.queueRefineBatchJobEvent("refine:accepted", handle);
85674
85679
  setImmediate(() => {
@@ -85683,7 +85688,7 @@ ${hintLines.join("\n")}` : "",
85683
85688
  };
85684
85689
  }
85685
85690
  async finishMeshRefineJob(handle, args) {
85686
- const key = this.buildRefineJobKey(handle.meshId, handle.targetNodeId);
85691
+ const key2 = this.buildRefineJobKey(handle.meshId, handle.targetNodeId);
85687
85692
  let result;
85688
85693
  try {
85689
85694
  result = await this.executeMeshRefineNodeSynchronously(handle.meshId, handle.targetNodeId, args);
@@ -85751,17 +85756,17 @@ ${hintLines.join("\n")}` : "",
85751
85756
  coordinatorDaemonId: handle.targetCoordinatorDaemonId
85752
85757
  });
85753
85758
  const terminal = { ...terminalHandle, result: normalizedResult };
85754
- this.terminalRefineJobs.set(key, terminal);
85755
- this.runningRefineJobs.delete(key);
85759
+ this.terminalRefineJobs.set(key2, terminal);
85760
+ this.runningRefineJobs.delete(key2);
85756
85761
  this.invalidateAggregateMeshStatus(handle.meshId);
85757
85762
  await this.appendRefineJobLedger(isTerminalSuccess ? "task_completed" : "task_failed", terminalHandle, normalizedResult);
85758
85763
  this.queueRefineJobEvent(isTerminalSuccess ? "refine:completed" : "refine:failed", terminalHandle, normalizedResult);
85759
85764
  }
85760
85765
  async startMeshRefineJob(meshId, nodeId, args) {
85761
- const key = this.buildRefineJobKey(meshId, nodeId);
85762
- const running = this.runningRefineJobs.get(key);
85766
+ const key2 = this.buildRefineJobKey(meshId, nodeId);
85767
+ const running = this.runningRefineJobs.get(key2);
85763
85768
  if (running) return { ...running, duplicate: true };
85764
- const terminal = this.terminalRefineJobs.get(key);
85769
+ const terminal = this.terminalRefineJobs.get(key2);
85765
85770
  const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
85766
85771
  const mesh = meshRecord?.mesh;
85767
85772
  const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
@@ -85769,7 +85774,7 @@ ${hintLines.join("\n")}` : "",
85769
85774
  if (!node.isLocalWorktree || !node.workspace) return { success: false, error: `Refinery requires a local worktree node` };
85770
85775
  const coordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : this.deps.statusInstanceId || void 0;
85771
85776
  const handle = this.buildRefineJobHandle({ meshId, nodeId, node, retryOfJobId: terminal?.jobId, coordinatorDaemonId });
85772
- this.runningRefineJobs.set(key, handle);
85777
+ this.runningRefineJobs.set(key2, handle);
85773
85778
  await this.appendRefineJobLedger("task_dispatched", handle);
85774
85779
  this.queueRefineJobEvent("refine:accepted", handle);
85775
85780
  setImmediate(() => {
@@ -85825,27 +85830,27 @@ ${hintLines.join("\n")}` : "",
85825
85830
  */
85826
85831
  async stopIde(ideType, killProcess = false) {
85827
85832
  const cdpKeysToRemove = [];
85828
- for (const key of this.deps.cdpManagers.keys()) {
85829
- if (key === ideType || key.startsWith(`${ideType}_`)) {
85830
- cdpKeysToRemove.push(key);
85833
+ for (const key2 of this.deps.cdpManagers.keys()) {
85834
+ if (key2 === ideType || key2.startsWith(`${ideType}_`)) {
85835
+ cdpKeysToRemove.push(key2);
85831
85836
  }
85832
85837
  }
85833
- for (const key of cdpKeysToRemove) {
85834
- const cdp = this.deps.cdpManagers.get(key);
85838
+ for (const key2 of cdpKeysToRemove) {
85839
+ const cdp = this.deps.cdpManagers.get(key2);
85835
85840
  if (cdp) {
85836
85841
  try {
85837
85842
  cdp.disconnect();
85838
85843
  } catch {
85839
85844
  }
85840
- this.deps.cdpManagers.delete(key);
85841
- this.deps.sessionRegistry.unregisterByManagerKey(key);
85842
- LOG2.info("StopIDE", `CDP disconnected: ${key}`);
85845
+ this.deps.cdpManagers.delete(key2);
85846
+ this.deps.sessionRegistry.unregisterByManagerKey(key2);
85847
+ LOG2.info("StopIDE", `CDP disconnected: ${key2}`);
85843
85848
  }
85844
85849
  }
85845
85850
  const keysToRemove = [];
85846
- for (const key of this.deps.instanceManager.listInstanceIds()) {
85847
- if (key === `ide:${ideType}` || typeof key === "string" && key.startsWith(`ide:${ideType}_`)) {
85848
- keysToRemove.push(key);
85851
+ for (const key2 of this.deps.instanceManager.listInstanceIds()) {
85852
+ if (key2 === `ide:${ideType}` || typeof key2 === "string" && key2.startsWith(`ide:${ideType}_`)) {
85853
+ keysToRemove.push(key2);
85849
85854
  }
85850
85855
  }
85851
85856
  for (const instanceKey of keysToRemove) {
@@ -90500,9 +90505,9 @@ async (params) => {
90500
90505
  }
90501
90506
  if (Date.now() - lastApprovalTime < 2e3) return;
90502
90507
  if (approvalPatterns.some((p) => p.test(approvalBuffer))) {
90503
- const key = approvalKeys[1] || approvalKeys[0] || "a\r";
90504
- writeFn(key);
90505
- ctx.log(`Auto-Implement auto-approved prompt! Sending: ${JSON.stringify(key)}`);
90508
+ const key2 = approvalKeys[1] || approvalKeys[0] || "a\r";
90509
+ writeFn(key2);
90510
+ ctx.log(`Auto-Implement auto-approved prompt! Sending: ${JSON.stringify(key2)}`);
90506
90511
  sendAutoImplSSE(ctx, { event: "output", data: { chunk: `
90507
90512
  [\u{1F916} ADHDev Auto-Approve] CLI Action Approved
90508
90513
  `, stream: "stdout" } });
@@ -91752,8 +91757,8 @@ data: ${JSON.stringify(msg.data)}
91752
91757
  category: p.category
91753
91758
  }));
91754
91759
  const cdpStatus = {};
91755
- for (const [key, cdp] of this.cdpManagers.entries()) {
91756
- cdpStatus[key] = { connected: cdp.isConnected };
91760
+ for (const [key2, cdp] of this.cdpManagers.entries()) {
91761
+ cdpStatus[key2] = { connected: cdp.isConnected };
91757
91762
  }
91758
91763
  this.json(res, 200, {
91759
91764
  devMode: true,
@@ -92073,16 +92078,16 @@ data: ${JSON.stringify(msg.data)}
92073
92078
  errors.push(...validation.errors);
92074
92079
  warnings.push(...validation.warnings);
92075
92080
  if (config2.settings) {
92076
- for (const [key, val] of Object.entries(config2.settings)) {
92081
+ for (const [key2, val] of Object.entries(config2.settings)) {
92077
92082
  const s2 = val;
92078
- if (!s2.type) errors.push(`settings.${key}: missing type`);
92083
+ if (!s2.type) errors.push(`settings.${key2}: missing type`);
92079
92084
  else if (!["boolean", "number", "string", "select"].includes(s2.type))
92080
- errors.push(`settings.${key}: invalid type '${s2.type}'`);
92081
- if (s2.default === void 0) warnings.push(`settings.${key}: no default value`);
92085
+ errors.push(`settings.${key2}: invalid type '${s2.type}'`);
92086
+ if (s2.default === void 0) warnings.push(`settings.${key2}: no default value`);
92082
92087
  if (s2.type === "number" && s2.min !== void 0 && s2.max !== void 0 && s2.min > s2.max)
92083
- errors.push(`settings.${key}: min (${s2.min}) > max (${s2.max})`);
92088
+ errors.push(`settings.${key2}: min (${s2.min}) > max (${s2.max})`);
92084
92089
  if (s2.type === "select" && (!s2.options || !Array.isArray(s2.options) || s2.options.length === 0))
92085
- errors.push(`settings.${key}: select type requires options[]`);
92090
+ errors.push(`settings.${key2}: select type requires options[]`);
92086
92091
  }
92087
92092
  }
92088
92093
  if (config2.cdpPorts && Array.isArray(config2.cdpPorts)) {
@@ -92860,21 +92865,21 @@ data: ${JSON.stringify(msg.data)}
92860
92865
  function encodeControlLetter(letter) {
92861
92866
  return String.fromCharCode(letter.charCodeAt(0) - 96);
92862
92867
  }
92863
- function encodeShiftedKey(key) {
92864
- if (isLowercaseLetter(key)) return key.toUpperCase();
92865
- if (key.startsWith("ctrl+") && isLowercaseLetter(key.slice(5))) {
92866
- return encodeControlLetter(key.slice(5));
92868
+ function encodeShiftedKey(key2) {
92869
+ if (isLowercaseLetter(key2)) return key2.toUpperCase();
92870
+ if (key2.startsWith("ctrl+") && isLowercaseLetter(key2.slice(5))) {
92871
+ return encodeControlLetter(key2.slice(5));
92867
92872
  }
92868
- if (key.startsWith("alt+") && isLowercaseLetter(key.slice(4))) {
92869
- return `\x1B${key.slice(4).toUpperCase()}`;
92873
+ if (key2.startsWith("alt+") && isLowercaseLetter(key2.slice(4))) {
92874
+ return `\x1B${key2.slice(4).toUpperCase()}`;
92870
92875
  }
92871
- if (key === "tab") return "\x1B[Z";
92872
- if (key in SHIFTED_CSI_KEYS) return SHIFTED_CSI_KEYS[key];
92873
- if (key in BASE_KEY_SEQUENCES) return BASE_KEY_SEQUENCES[key];
92874
- throw new Error(`Unsupported named key: shift+${key}`);
92876
+ if (key2 === "tab") return "\x1B[Z";
92877
+ if (key2 in SHIFTED_CSI_KEYS) return SHIFTED_CSI_KEYS[key2];
92878
+ if (key2 in BASE_KEY_SEQUENCES) return BASE_KEY_SEQUENCES[key2];
92879
+ throw new Error(`Unsupported named key: shift+${key2}`);
92875
92880
  }
92876
- function namedKeyToAnsi(key) {
92877
- const normalized = String(key || "").trim().toLowerCase();
92881
+ function namedKeyToAnsi(key2) {
92882
+ const normalized = String(key2 || "").trim().toLowerCase();
92878
92883
  if (normalized in BASE_KEY_SEQUENCES) return BASE_KEY_SEQUENCES[normalized];
92879
92884
  if (normalized.startsWith("ctrl+") && isLowercaseLetter(normalized.slice(5))) {
92880
92885
  return encodeControlLetter(normalized.slice(5));
@@ -92883,7 +92888,7 @@ data: ${JSON.stringify(msg.data)}
92883
92888
  return `\x1B${normalized.slice(4)}`;
92884
92889
  }
92885
92890
  if (normalized.startsWith("shift+")) return encodeShiftedKey(normalized.slice(6));
92886
- throw new Error(`Unsupported named key: ${key}`);
92891
+ throw new Error(`Unsupported named key: ${key2}`);
92887
92892
  }
92888
92893
  function namedKeysToAnsi(keys) {
92889
92894
  if (!Array.isArray(keys)) throw new Error("keys must be an array");
@@ -93349,19 +93354,19 @@ data: ${JSON.stringify(msg.data)}
93349
93354
  if (!ids) return [];
93350
93355
  return [...ids].map((id) => this.bySessionId.get(id)).filter(Boolean);
93351
93356
  }
93352
- addIndex(index, key, sessionId) {
93353
- let set2 = index.get(key);
93357
+ addIndex(index, key2, sessionId) {
93358
+ let set2 = index.get(key2);
93354
93359
  if (!set2) {
93355
93360
  set2 = /* @__PURE__ */ new Set();
93356
- index.set(key, set2);
93361
+ index.set(key2, set2);
93357
93362
  }
93358
93363
  set2.add(sessionId);
93359
93364
  }
93360
- removeIndex(index, key, sessionId) {
93361
- const set2 = index.get(key);
93365
+ removeIndex(index, key2, sessionId) {
93366
+ const set2 = index.get(key2);
93362
93367
  if (!set2) return;
93363
93368
  set2.delete(sessionId);
93364
- if (set2.size === 0) index.delete(key);
93369
+ if (set2.size === 0) index.delete(key2);
93365
93370
  }
93366
93371
  };
93367
93372
  init_logger();