@adhdev/daemon-core 0.9.82-rc.365 → 0.9.82-rc.366

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.mjs CHANGED
@@ -311,10 +311,10 @@ function readInjected(value) {
311
311
  }
312
312
  function getDaemonBuildInfo() {
313
313
  if (cached) return cached;
314
- const commit = readInjected(true ? "fe24f3fb158efc949e806b79bca2479b1c29d753" : void 0) ?? "unknown";
315
- const commitShort = readInjected(true ? "fe24f3fb" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
316
- const version = readInjected(true ? "0.9.82-rc.365" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
317
- const builtAt = readInjected(true ? "2026-06-24T00:47:57.092Z" : void 0);
314
+ const commit = readInjected(true ? "c2224ab0c9d05e85b4cbf88e4fc696f3733ec397" : void 0) ?? "unknown";
315
+ const commitShort = readInjected(true ? "c2224ab0" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
316
+ const version = readInjected(true ? "0.9.82-rc.366" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
317
+ const builtAt = readInjected(true ? "2026-06-24T02:22:36.214Z" : void 0);
318
318
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
319
319
  return cached;
320
320
  }
@@ -7228,8 +7228,8 @@ function stripCoordinatorWrapperFile(filePath) {
7228
7228
  const remaining = (existing.slice(0, openIdx) + existing.slice(closeIdx + CLOSE.length)).replace(/^\s*\n+/, "").replace(/\n+\s*$/, "");
7229
7229
  if (!remaining.trim()) {
7230
7230
  try {
7231
- const fs33 = __require("fs");
7232
- fs33.unlinkSync(filePath);
7231
+ const fs35 = __require("fs");
7232
+ fs35.unlinkSync(filePath);
7233
7233
  } catch {
7234
7234
  }
7235
7235
  } else {
@@ -9669,9 +9669,9 @@ function findBinary(name) {
9669
9669
  for (const ext of exes) {
9670
9670
  const fullPath = path11.join(p, trimmed + ext);
9671
9671
  try {
9672
- const fs33 = __require("fs");
9673
- if (fs33.existsSync(fullPath)) {
9674
- const stat2 = fs33.statSync(fullPath);
9672
+ const fs35 = __require("fs");
9673
+ if (fs35.existsSync(fullPath)) {
9674
+ const stat2 = fs35.statSync(fullPath);
9675
9675
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
9676
9676
  return fullPath;
9677
9677
  }
@@ -9685,12 +9685,12 @@ function findBinary(name) {
9685
9685
  function isScriptBinary(binaryPath) {
9686
9686
  if (!path11.isAbsolute(binaryPath)) return false;
9687
9687
  try {
9688
- const fs33 = __require("fs");
9689
- const resolved = fs33.realpathSync(binaryPath);
9688
+ const fs35 = __require("fs");
9689
+ const resolved = fs35.realpathSync(binaryPath);
9690
9690
  const head = Buffer.alloc(8);
9691
- const fd = fs33.openSync(resolved, "r");
9692
- fs33.readSync(fd, head, 0, 8, 0);
9693
- fs33.closeSync(fd);
9691
+ const fd = fs35.openSync(resolved, "r");
9692
+ fs35.readSync(fd, head, 0, 8, 0);
9693
+ fs35.closeSync(fd);
9694
9694
  let i = 0;
9695
9695
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
9696
9696
  return head[i] === 35 && head[i + 1] === 33;
@@ -9701,12 +9701,12 @@ function isScriptBinary(binaryPath) {
9701
9701
  function looksLikeMachOOrElf(filePath) {
9702
9702
  if (!path11.isAbsolute(filePath)) return false;
9703
9703
  try {
9704
- const fs33 = __require("fs");
9705
- const resolved = fs33.realpathSync(filePath);
9704
+ const fs35 = __require("fs");
9705
+ const resolved = fs35.realpathSync(filePath);
9706
9706
  const buf = Buffer.alloc(8);
9707
- const fd = fs33.openSync(resolved, "r");
9708
- fs33.readSync(fd, buf, 0, 8, 0);
9709
- fs33.closeSync(fd);
9707
+ const fd = fs35.openSync(resolved, "r");
9708
+ fs35.readSync(fd, buf, 0, 8, 0);
9709
+ fs35.closeSync(fd);
9710
9710
  let i = 0;
9711
9711
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
9712
9712
  const b = buf.subarray(i);
@@ -13492,6 +13492,13 @@ async function triggerMeshQueue(components, meshId) {
13492
13492
  nodeId: task.assignedNodeId,
13493
13493
  sessionId: task.assignedSessionId
13494
13494
  }));
13495
+ const autoLaunchPending = autoLaunchStarted || afterQueue.some((task) => {
13496
+ if (task.status !== "pending") return false;
13497
+ const al = task.autoLaunch;
13498
+ if (!al || al.status !== "started" && al.status !== "completed") return false;
13499
+ const launchedAtMs = Date.parse(al.updatedAt);
13500
+ return Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS;
13501
+ });
13495
13502
  return {
13496
13503
  success: true,
13497
13504
  meshId,
@@ -13505,7 +13512,11 @@ async function triggerMeshQueue(components, meshId) {
13505
13512
  remoteIdleSessionsChecked,
13506
13513
  skippedSessions,
13507
13514
  autoLaunchStarted,
13508
- ...pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchStarted ? { noIdleMeshSessionAvailable: true } : {}
13515
+ ...autoLaunchPending ? { autoLaunchPending: true } : {},
13516
+ // Only report "no idle session, go launch one" when nothing is already on its way.
13517
+ // A pending auto-launch (this tick or a prior still-converging one) means a session
13518
+ // WILL claim shortly, so it is not a no-session-available situation.
13519
+ ...pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchPending ? { noIdleMeshSessionAvailable: true } : {}
13509
13520
  };
13510
13521
  }
13511
13522
  async function maybeAutoFastForwardIdleNode(components, args) {
@@ -16472,8 +16483,8 @@ var init_pty_transport = __esm({
16472
16483
  let cwd = options.cwd;
16473
16484
  if (cwd) {
16474
16485
  try {
16475
- const fs33 = __require("fs");
16476
- const stat2 = fs33.statSync(cwd);
16486
+ const fs35 = __require("fs");
16487
+ const stat2 = fs35.statSync(cwd);
16477
16488
  if (!stat2.isDirectory()) cwd = os14.homedir();
16478
16489
  } catch {
16479
16490
  cwd = os14.homedir();
@@ -31999,7 +32010,7 @@ var DaemonCommandHandler = class {
31999
32010
  return { success: false, error: "invalid type" };
32000
32011
  }
32001
32012
  const https = __require("https");
32002
- const fs33 = __require("fs");
32013
+ const fs35 = __require("fs");
32003
32014
  const path42 = __require("path");
32004
32015
  const crypto6 = __require("crypto");
32005
32016
  const REGISTRY = "https://api.adhf.dev/api/v1/registry";
@@ -32043,7 +32054,7 @@ var DaemonCommandHandler = class {
32043
32054
  if (!targetDir.startsWith(installRootResolved + path42.sep)) {
32044
32055
  return { success: false, error: "install path escaped upstream root" };
32045
32056
  }
32046
- fs33.mkdirSync(targetDir, { recursive: true });
32057
+ fs35.mkdirSync(targetDir, { recursive: true });
32047
32058
  let manifestProbe = {};
32048
32059
  try {
32049
32060
  manifestProbe = JSON.parse(manifestBody);
@@ -32068,7 +32079,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32068
32079
  }
32069
32080
  const targetFile = isV1 ? "provider.v1.json" : "provider.json";
32070
32081
  const targetPath = path42.join(targetDir, targetFile);
32071
- fs33.writeFileSync(targetPath, manifestBody, "utf-8");
32082
+ fs35.writeFileSync(targetPath, manifestBody, "utf-8");
32072
32083
  const manifestJson = JSON.parse(manifestBody);
32073
32084
  const scriptFetch = await this.fetchProviderSources(
32074
32085
  manifestJson,
@@ -32138,7 +32149,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32138
32149
  const repo = source.repo;
32139
32150
  const ref = source.ref;
32140
32151
  const https = __require("https");
32141
- const fs33 = __require("fs");
32152
+ const fs35 = __require("fs");
32142
32153
  const path42 = __require("path");
32143
32154
  function fetchJson(url, timeoutMs) {
32144
32155
  return new Promise((resolve24, reject) => {
@@ -32222,8 +32233,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32222
32233
  const relInside = entry.path.startsWith(sharedDirRel + "/") ? entry.path.slice(sharedDirRel.length + 1) : entry.path;
32223
32234
  const outPath = path42.resolve(path42.join(sharedTargetDir, relInside));
32224
32235
  if (!outPath.startsWith(path42.resolve(sharedTargetDir) + path42.sep)) continue;
32225
- fs33.mkdirSync(path42.dirname(outPath), { recursive: true });
32226
- fs33.writeFileSync(outPath, body);
32236
+ fs35.mkdirSync(path42.dirname(outPath), { recursive: true });
32237
+ fs35.writeFileSync(outPath, body);
32227
32238
  fetchedCount++;
32228
32239
  } catch (e) {
32229
32240
  errors.push(`fetch shared ${entry.path}: ${e?.message ?? e}`);
@@ -32261,8 +32272,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32261
32272
  errors.push(`refusing to write outside targetDir: ${entry.path}`);
32262
32273
  continue;
32263
32274
  }
32264
- fs33.mkdirSync(path42.dirname(outPath), { recursive: true });
32265
- fs33.writeFileSync(outPath, body);
32275
+ fs35.mkdirSync(path42.dirname(outPath), { recursive: true });
32276
+ fs35.writeFileSync(outPath, body);
32266
32277
  fetchedCount++;
32267
32278
  } catch (e) {
32268
32279
  errors.push(`fetch ${entry.path}: ${e?.message ?? e}`);
@@ -32290,7 +32301,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32290
32301
  if (!["cli", "ide", "extension", "acp"].includes(category)) {
32291
32302
  return { success: false, error: `unknown category: ${category}` };
32292
32303
  }
32293
- const fs33 = __require("fs");
32304
+ const fs35 = __require("fs");
32294
32305
  const path42 = __require("path");
32295
32306
  try {
32296
32307
  const installRoot = this.getUpstreamInstallRoot();
@@ -32299,10 +32310,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32299
32310
  if (!targetDir.startsWith(installRootResolved + path42.sep)) {
32300
32311
  return { success: false, error: "refusing to delete outside upstream root" };
32301
32312
  }
32302
- if (!fs33.existsSync(targetDir)) {
32313
+ if (!fs35.existsSync(targetDir)) {
32303
32314
  return { success: false, error: "not installed" };
32304
32315
  }
32305
- fs33.rmSync(targetDir, { recursive: true, force: true });
32316
+ fs35.rmSync(targetDir, { recursive: true, force: true });
32306
32317
  if (this._ctx.providerLoader) {
32307
32318
  this._ctx.providerLoader.reload();
32308
32319
  this._ctx.providerLoader.registerToDetector();
@@ -32318,28 +32329,28 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32318
32329
  * the UI and by the update checker.
32319
32330
  */
32320
32331
  handleListInstalledProviders(_args) {
32321
- const fs33 = __require("fs");
32332
+ const fs35 = __require("fs");
32322
32333
  const path42 = __require("path");
32323
32334
  const installRoot = this.getUpstreamInstallRoot();
32324
- if (!fs33.existsSync(installRoot)) return { success: true, providers: [] };
32335
+ if (!fs35.existsSync(installRoot)) return { success: true, providers: [] };
32325
32336
  const CATEGORIES = ["cli", "ide", "extension", "acp"];
32326
32337
  const items = [];
32327
32338
  for (const category of CATEGORIES) {
32328
32339
  const categoryDir = path42.join(installRoot, category);
32329
- if (!fs33.existsSync(categoryDir)) continue;
32340
+ if (!fs35.existsSync(categoryDir)) continue;
32330
32341
  let entries;
32331
32342
  try {
32332
- entries = fs33.readdirSync(categoryDir);
32343
+ entries = fs35.readdirSync(categoryDir);
32333
32344
  } catch {
32334
32345
  continue;
32335
32346
  }
32336
32347
  for (const type of entries) {
32337
32348
  const v1Path = path42.join(categoryDir, type, "provider.v1.json");
32338
32349
  const v0Path = path42.join(categoryDir, type, "provider.json");
32339
- const manifestPath = fs33.existsSync(v1Path) ? v1Path : fs33.existsSync(v0Path) ? v0Path : null;
32350
+ const manifestPath = fs35.existsSync(v1Path) ? v1Path : fs35.existsSync(v0Path) ? v0Path : null;
32340
32351
  if (!manifestPath) continue;
32341
32352
  try {
32342
- const m = JSON.parse(fs33.readFileSync(manifestPath, "utf-8"));
32353
+ const m = JSON.parse(fs35.readFileSync(manifestPath, "utf-8"));
32343
32354
  items.push({
32344
32355
  type,
32345
32356
  category,
@@ -32450,7 +32461,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32450
32461
  if (!/^@[a-z0-9_-]+$/i.test(requestedName)) {
32451
32462
  return { success: false, error: "name must match @[a-z0-9_-]+" };
32452
32463
  }
32453
- const fs33 = __require("fs");
32464
+ const fs35 = __require("fs");
32454
32465
  const path42 = __require("path");
32455
32466
  const { spawnSync: spawnSync2 } = __require("child_process");
32456
32467
  const file = ext.loadExternalSources();
@@ -32461,8 +32472,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32461
32472
  return { success: false, error: `source url+ref already registered (use a different name to track another ref)` };
32462
32473
  }
32463
32474
  const sourceDir = path42.join(ext.externalRoot(), requestedName);
32464
- if (!fs33.existsSync(ext.externalRoot())) fs33.mkdirSync(ext.externalRoot(), { recursive: true });
32465
- if (fs33.existsSync(sourceDir)) {
32475
+ if (!fs35.existsSync(ext.externalRoot())) fs35.mkdirSync(ext.externalRoot(), { recursive: true });
32476
+ if (fs35.existsSync(sourceDir)) {
32466
32477
  return { success: false, error: `directory already exists: ${sourceDir} (rename or remove first)` };
32467
32478
  }
32468
32479
  const clone = spawnSync2("git", ["clone", "--depth=1", "--branch", ref, "--", url, sourceDir], {
@@ -32472,7 +32483,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32472
32483
  });
32473
32484
  if (clone.status !== 0) {
32474
32485
  try {
32475
- fs33.rmSync(sourceDir, { recursive: true, force: true });
32486
+ fs35.rmSync(sourceDir, { recursive: true, force: true });
32476
32487
  } catch {
32477
32488
  }
32478
32489
  return { success: false, error: `git clone failed: ${(clone.stderr || clone.stdout || "").trim() || "unknown error"}` };
@@ -32516,15 +32527,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
32516
32527
  const name = typeof args?.name === "string" ? args.name.trim() : "";
32517
32528
  if (!name) return { success: false, error: "name is required" };
32518
32529
  const ext = (init_external_sources(), __toCommonJS(external_sources_exports));
32519
- const fs33 = __require("fs");
32530
+ const fs35 = __require("fs");
32520
32531
  const path42 = __require("path");
32521
32532
  const file = ext.loadExternalSources();
32522
32533
  const match = file.sources.find((s2) => s2.name === name);
32523
32534
  if (!match) return { success: false, error: `source "${name}" not registered` };
32524
32535
  const sourceDir = path42.join(ext.externalRoot(), name);
32525
- if (fs33.existsSync(sourceDir)) {
32536
+ if (fs35.existsSync(sourceDir)) {
32526
32537
  try {
32527
- fs33.rmSync(sourceDir, { recursive: true, force: true });
32538
+ fs35.rmSync(sourceDir, { recursive: true, force: true });
32528
32539
  } catch (e) {
32529
32540
  return { success: false, error: `failed to delete ${sourceDir}: ${e?.message || e}` };
32530
32541
  }
@@ -33305,14 +33316,14 @@ var statusMetaHandlers = {
33305
33316
  // src/commands/low-family/coordinator-prompt.ts
33306
33317
  var coordinatorPromptHandlers = {
33307
33318
  list_coordinator_prompts: async (_ctx, _args) => {
33308
- const fs33 = await import("fs");
33319
+ const fs35 = await import("fs");
33309
33320
  const path42 = await import("path");
33310
33321
  const os30 = await import("os");
33311
33322
  const dir = path42.join(os30.homedir(), ".adhdev", "coordinator-prompts");
33312
33323
  const entries = {};
33313
33324
  try {
33314
- if (fs33.existsSync(dir)) {
33315
- for (const name of fs33.readdirSync(dir)) {
33325
+ if (fs35.existsSync(dir)) {
33326
+ for (const name of fs35.readdirSync(dir)) {
33316
33327
  const matchOverride = name.match(/^([a-zA-Z0-9_.-]+)\.md$/);
33317
33328
  const matchAppend = name.match(/^([a-zA-Z0-9_.-]+)\.append\.md$/);
33318
33329
  const m = matchAppend || matchOverride;
@@ -33322,7 +33333,7 @@ var coordinatorPromptHandlers = {
33322
33333
  const full = path42.join(dir, name);
33323
33334
  let content = "";
33324
33335
  try {
33325
- content = fs33.readFileSync(full, "utf8");
33336
+ content = fs35.readFileSync(full, "utf8");
33326
33337
  } catch {
33327
33338
  }
33328
33339
  if (!entries[key]) entries[key] = { override: "", append: "" };
@@ -33336,7 +33347,7 @@ var coordinatorPromptHandlers = {
33336
33347
  return { success: true, dir, entries };
33337
33348
  },
33338
33349
  write_coordinator_prompt: async (_ctx, args) => {
33339
- const fs33 = await import("fs");
33350
+ const fs35 = await import("fs");
33340
33351
  const path42 = await import("path");
33341
33352
  const os30 = await import("os");
33342
33353
  const key = typeof args?.key === "string" ? args.key.trim() : "";
@@ -33349,11 +33360,11 @@ var coordinatorPromptHandlers = {
33349
33360
  const filename = kind === "append" ? `${key}.append.md` : `${key}.md`;
33350
33361
  const full = path42.join(dir, filename);
33351
33362
  try {
33352
- fs33.mkdirSync(dir, { recursive: true });
33363
+ fs35.mkdirSync(dir, { recursive: true });
33353
33364
  if (content.trim()) {
33354
- fs33.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
33355
- } else if (fs33.existsSync(full)) {
33356
- fs33.unlinkSync(full);
33365
+ fs35.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
33366
+ } else if (fs35.existsSync(full)) {
33367
+ fs35.unlinkSync(full);
33357
33368
  }
33358
33369
  return { success: true, path: full, kind, key };
33359
33370
  } catch (error) {
@@ -41378,7 +41389,17 @@ Run 'adhdev doctor' for detailed diagnostics.`
41378
41389
  continue;
41379
41390
  }
41380
41391
  const restoredSettings = { ...this.providerLoader.getSettings(normalizedType) };
41381
- const coordinatorEntry = getCoordinatorForSession(record.runtimeId);
41392
+ let coordinatorEntry = getCoordinatorForSession(record.runtimeId);
41393
+ if (!coordinatorEntry?.meshId && record.workspace) {
41394
+ const workspaceCoordinators = listCoordinatorsForWorkspace(record.workspace).filter((e) => e.meshId && (!e.cliType || e.cliType === record.cliType));
41395
+ if (workspaceCoordinators.length === 1) {
41396
+ coordinatorEntry = workspaceCoordinators[0];
41397
+ LOG.info(
41398
+ "CLI",
41399
+ `\u21BB Rebound coordinator mark by workspace for ${record.runtimeKey || record.runtimeId} (mesh ${coordinatorEntry.meshId} @ ${record.workspace}); registry key did not match runtimeId`
41400
+ );
41401
+ }
41402
+ }
41382
41403
  if (coordinatorEntry?.meshId) {
41383
41404
  restoredSettings.meshCoordinatorFor = coordinatorEntry.meshId;
41384
41405
  }
@@ -44289,7 +44310,7 @@ var ProviderLoader = class _ProviderLoader {
44289
44310
  }
44290
44311
  if (providerDir) {
44291
44312
  try {
44292
- const fs33 = __require("fs");
44313
+ const fs35 = __require("fs");
44293
44314
  const path42 = __require("path");
44294
44315
  const candidates = [];
44295
44316
  if (Array.isArray(base.compatibility)) {
@@ -44301,13 +44322,13 @@ var ProviderLoader = class _ProviderLoader {
44301
44322
  }
44302
44323
  candidates.push(path42.join(providerDir, "specs", "default.json"));
44303
44324
  candidates.push(path42.join(providerDir, "spec.json"));
44304
- const specPath = candidates.find((p) => fs33.existsSync(p));
44325
+ const specPath = candidates.find((p) => fs35.existsSync(p));
44305
44326
  if (specPath) {
44306
44327
  resolved._resolvedSpecPath = specPath;
44307
44328
  let specControls;
44308
44329
  let nh;
44309
44330
  try {
44310
- const rawSpec = JSON.parse(fs33.readFileSync(specPath, "utf8"));
44331
+ const rawSpec = JSON.parse(fs35.readFileSync(specPath, "utf8"));
44311
44332
  specControls = rawSpec.control_bar;
44312
44333
  nh = rawSpec.native_history;
44313
44334
  } catch {
@@ -44339,7 +44360,7 @@ var ProviderLoader = class _ProviderLoader {
44339
44360
  reader = (input) => executeNativeHistory(nh, input);
44340
44361
  } else if (nh.override_path) {
44341
44362
  const overrideFile = path42.resolve(providerDir, nh.override_path);
44342
- if (fs33.existsSync(overrideFile)) {
44363
+ if (fs35.existsSync(overrideFile)) {
44343
44364
  try {
44344
44365
  registerProviderScriptRootSafely(path42.dirname(path42.dirname(providerDir)));
44345
44366
  delete __require.cache[__require.resolve(overrideFile)];
@@ -44886,8 +44907,8 @@ var ProviderLoader = class _ProviderLoader {
44886
44907
  }
44887
44908
  }
44888
44909
  writeConfig(config) {
44889
- const { saveConfig: saveConfig3 } = (init_config(), __toCommonJS(config_exports));
44890
- saveConfig3(config);
44910
+ const { saveConfig: saveConfig2 } = (init_config(), __toCommonJS(config_exports));
44911
+ saveConfig2(config);
44891
44912
  }
44892
44913
  getPlatformVersionCommand(versionCommand) {
44893
44914
  if (!versionCommand) return void 0;
@@ -45524,7 +45545,7 @@ async function detectCurrentWorkspace(ideId) {
45524
45545
  }
45525
45546
  } else if (plat === "win32") {
45526
45547
  try {
45527
- const fs33 = __require("fs");
45548
+ const fs35 = __require("fs");
45528
45549
  const appNameMap = getMacAppIdentifiers();
45529
45550
  const appName = appNameMap[ideId];
45530
45551
  if (appName) {
@@ -45533,8 +45554,8 @@ async function detectCurrentWorkspace(ideId) {
45533
45554
  appName,
45534
45555
  "storage.json"
45535
45556
  );
45536
- if (fs33.existsSync(storagePath)) {
45537
- const data = JSON.parse(fs33.readFileSync(storagePath, "utf-8"));
45557
+ if (fs35.existsSync(storagePath)) {
45558
+ const data = JSON.parse(fs35.readFileSync(storagePath, "utf-8"));
45538
45559
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
45539
45560
  if (workspaces.length > 0) {
45540
45561
  const recent = workspaces[0];
@@ -47045,15 +47066,1054 @@ var medFamilyRegistry = new Map(
47045
47066
  })
47046
47067
  );
47047
47068
 
47048
- // src/commands/router.ts
47069
+ // src/commands/high-family/mesh-events.ts
47070
+ init_mesh_events();
47071
+ var meshEventsHandlers = {
47072
+ mesh_forward_event: async (ctx, args) => {
47073
+ return handleMeshForwardEvent({ instanceManager: ctx.deps.instanceManager }, args);
47074
+ },
47075
+ get_pending_mesh_events: async (_ctx, args) => {
47076
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47077
+ const coordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : void 0;
47078
+ const events = drainPendingMeshCoordinatorEvents(meshId || void 0, coordinatorDaemonId);
47079
+ return { success: true, events };
47080
+ },
47081
+ interactive_prompt_response: async (ctx, args) => {
47082
+ const sessionId = typeof args?.targetSessionId === "string" && args.targetSessionId.trim() ? args.targetSessionId.trim() : typeof args?.sessionId === "string" && args.sessionId.trim() ? args.sessionId.trim() : "";
47083
+ if (!sessionId) return { success: false, error: "targetSessionId required" };
47084
+ const response = normalizeInteractivePromptResponse(args?.response ?? args);
47085
+ const instance = ctx.deps.instanceManager.getInstance(sessionId);
47086
+ if (!instance) return { success: false, error: `No running instance for session ${sessionId}` };
47087
+ ctx.deps.instanceManager.sendEvent(sessionId, "interactive_prompt_response", response);
47088
+ return { success: true };
47089
+ }
47090
+ };
47091
+
47092
+ // src/commands/high-family/mesh-coordinator-launch.ts
47093
+ init_logger();
47094
+ init_mesh_host_ownership();
47095
+ init_coordinator_registry();
47096
+ import { join as pathJoin } from "path";
47097
+ import * as fs26 from "fs";
47098
+ init_mesh_coordinator();
47099
+ init_dist();
47100
+ var meshCoordinatorLaunchHandlers = {
47101
+ launch_mesh_coordinator: async (ctx, args) => {
47102
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47103
+ let cliType = typeof args?.cliType === "string" ? args.cliType.trim() : "";
47104
+ const extraSystemPrompt = typeof args?.extraSystemPrompt === "string" ? args.extraSystemPrompt.trim() : "";
47105
+ if (!meshId) return { success: false, error: "meshId required" };
47106
+ try {
47107
+ const { buildCoordinatorSystemPrompt: buildCoordinatorSystemPrompt2 } = await Promise.resolve().then(() => (init_coordinator_prompt(), coordinator_prompt_exports));
47108
+ const { buildMissionPromptSection: buildMissionPromptSection2 } = await Promise.resolve().then(() => (init_mesh_missions(), mesh_missions_exports));
47109
+ const buildMissionSectionBestEffort = (id) => {
47110
+ try {
47111
+ return buildMissionPromptSection2(id);
47112
+ } catch {
47113
+ return "";
47114
+ }
47115
+ };
47116
+ let mesh;
47117
+ if (args?.inlineMesh && typeof args.inlineMesh === "object") {
47118
+ mesh = args.inlineMesh;
47119
+ ctx.inlineMeshCache.set(meshId, mesh);
47120
+ } else {
47121
+ const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
47122
+ mesh = getMesh2(meshId);
47123
+ }
47124
+ if (!mesh) return { success: false, error: "Mesh not found" };
47125
+ const meshHost = resolveMeshHostStatus(mesh);
47126
+ if (!meshHost.canOwnCoordinator) {
47127
+ return {
47128
+ success: false,
47129
+ ...buildMeshHostRequiredFailure(mesh, "coordinator launch"),
47130
+ meshId,
47131
+ cliType
47132
+ };
47133
+ }
47134
+ if (!Array.isArray(mesh.nodes) || mesh.nodes.length === 0) return { success: false, error: "No nodes in mesh" };
47135
+ const requestedCoordinatorNodeId = typeof args?.coordinatorNodeId === "string" ? args.coordinatorNodeId.trim() : "";
47136
+ const preferredCoordinatorNodeId = requestedCoordinatorNodeId || (typeof mesh.coordinator?.preferredNodeId === "string" ? mesh.coordinator.preferredNodeId.trim() : "");
47137
+ const coordinatorNode = preferredCoordinatorNodeId ? mesh.nodes.find((node) => node?.id === preferredCoordinatorNodeId || node?.nodeId === preferredCoordinatorNodeId) : mesh.nodes[0];
47138
+ if (!coordinatorNode) {
47139
+ return {
47140
+ success: false,
47141
+ code: "mesh_coordinator_node_not_found",
47142
+ error: `Coordinator node ${preferredCoordinatorNodeId} was not found in mesh`,
47143
+ meshId,
47144
+ cliType
47145
+ };
47146
+ }
47147
+ const sessionHostRecords = ctx.deps.sessionHostControl?.listSessions ? await ctx.deps.sessionHostControl.listSessions().catch(() => []) : [];
47148
+ const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
47149
+ const workspace = readLiveMeshNodeWorkspace({
47150
+ meshId,
47151
+ nodeId: String(normalizeMeshNodeId(coordinatorNode) || preferredCoordinatorNodeId || ""),
47152
+ liveSessionRecords: liveMeshSessions,
47153
+ allowCoordinatorSession: true
47154
+ }) || (typeof coordinatorNode.workspace === "string" ? coordinatorNode.workspace.trim() : "");
47155
+ if (!workspace) return { success: false, error: "Coordinator node workspace required", meshId, cliType };
47156
+ if (!cliType) {
47157
+ const resolved = await resolveProviderTypeFromPriority({
47158
+ nodeId: String(normalizeMeshNodeId(coordinatorNode) || preferredCoordinatorNodeId || "coordinator"),
47159
+ providerPriority: readProviderPriorityFromPolicy(coordinatorNode.policy),
47160
+ providerLoader: ctx.deps.providerLoader,
47161
+ onStatusChange: ctx.deps.onStatusChange
47162
+ });
47163
+ if (!resolved.providerType) {
47164
+ return {
47165
+ success: false,
47166
+ code: "mesh_coordinator_provider_priority_unusable",
47167
+ error: resolved.error || "No usable provider found from node providerPriority",
47168
+ meshId,
47169
+ cliType,
47170
+ workspace
47171
+ };
47172
+ }
47173
+ cliType = resolved.providerType;
47174
+ }
47175
+ const providerMeta = ctx.deps.providerLoader.resolve?.(cliType) || ctx.deps.providerLoader.getMeta(cliType);
47176
+ const coordinatorSetup = resolveMeshCoordinatorSetup({
47177
+ provider: providerMeta,
47178
+ cliType,
47179
+ meshId,
47180
+ workspace
47181
+ });
47182
+ if (coordinatorSetup.kind === "unsupported") {
47183
+ return {
47184
+ success: false,
47185
+ code: "mesh_coordinator_unsupported",
47186
+ error: coordinatorSetup.reason,
47187
+ meshId,
47188
+ cliType,
47189
+ workspace
47190
+ };
47191
+ }
47192
+ if (coordinatorSetup.kind === "manual") {
47193
+ return {
47194
+ success: false,
47195
+ code: "mesh_coordinator_manual_mcp_setup_required",
47196
+ error: coordinatorSetup.instructions,
47197
+ meshId,
47198
+ cliType,
47199
+ workspace,
47200
+ meshCoordinatorSetup: coordinatorSetup
47201
+ };
47202
+ }
47203
+ if (coordinatorSetup.kind === "cli_command") {
47204
+ let cliCmdSystemPrompt = "";
47205
+ try {
47206
+ cliCmdSystemPrompt = buildCoordinatorSystemPrompt2({ mesh, coordinatorCliType: cliType, userInstruction: extraSystemPrompt || void 0, missionSection: buildMissionSectionBestEffort(mesh.id) });
47207
+ } catch (error) {
47208
+ const message = error?.message || String(error);
47209
+ LOG.error("MeshCoordinator", `Failed to build coordinator prompt: ${message}`);
47210
+ return {
47211
+ success: false,
47212
+ code: "mesh_coordinator_prompt_failed",
47213
+ error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
47214
+ meshId,
47215
+ cliType,
47216
+ workspace
47217
+ };
47218
+ }
47219
+ let mcpRegistrationOk = false;
47220
+ let mcpRegistrationFailure = null;
47221
+ try {
47222
+ const { buildMeshCoordinatorRegistrationPlan: buildMeshCoordinatorRegistrationPlan2, execUnderPty: execUnderPty2 } = await Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports));
47223
+ const registrationPlan = buildMeshCoordinatorRegistrationPlan2(
47224
+ cliType,
47225
+ coordinatorSetup.serverName,
47226
+ coordinatorSetup.command
47227
+ );
47228
+ for (const step of registrationPlan) {
47229
+ const renderedCommand = [step.command, ...step.args].join(" ");
47230
+ LOG.info("MeshCoordinator", `Running MCP ${step.label} (pty): ${renderedCommand}`);
47231
+ const ptyResult = await execUnderPty2(step.command, step.args, { cwd: workspace, timeoutMs: 2e4 });
47232
+ if (ptyResult.exitCode === 0 && !ptyResult.timedOut) {
47233
+ if (step.required) mcpRegistrationOk = true;
47234
+ continue;
47235
+ }
47236
+ LOG.warn("MeshCoordinator", `MCP ${step.label} failed exit=${ptyResult.exitCode} signal=${ptyResult.signal} timedOut=${ptyResult.timedOut} \u2014 output:
47237
+ ${ptyResult.output.slice(-2e3)}`);
47238
+ if (step.required) {
47239
+ mcpRegistrationFailure = {
47240
+ command: renderedCommand,
47241
+ output: ptyResult.output.slice(-2e3),
47242
+ exitCode: ptyResult.exitCode,
47243
+ signal: ptyResult.signal,
47244
+ timedOut: ptyResult.timedOut
47245
+ };
47246
+ break;
47247
+ }
47248
+ }
47249
+ } catch (error) {
47250
+ LOG.warn("MeshCoordinator", `MCP registration command failed: ${error?.message || error}`);
47251
+ mcpRegistrationFailure = {
47252
+ command: coordinatorSetup.command,
47253
+ output: error?.message || String(error),
47254
+ exitCode: null,
47255
+ signal: null,
47256
+ timedOut: false
47257
+ };
47258
+ }
47259
+ if (!mcpRegistrationOk) {
47260
+ return {
47261
+ success: false,
47262
+ code: "mesh_coordinator_mcp_registration_failed",
47263
+ error: `Could not register ${coordinatorSetup.serverName}; coordinator session was not launched`,
47264
+ meshId,
47265
+ cliType,
47266
+ workspace,
47267
+ registration: mcpRegistrationFailure
47268
+ };
47269
+ }
47270
+ if (cliType === "codex-cli") {
47271
+ const repoMcpConfigPath = pathJoin(workspace, ".mcp.json");
47272
+ if (fs26.existsSync(repoMcpConfigPath)) {
47273
+ try {
47274
+ const repoMcpConfig = parseMeshCoordinatorMcpConfig(
47275
+ fs26.readFileSync(repoMcpConfigPath, "utf-8"),
47276
+ "claude_mcp_json"
47277
+ );
47278
+ const existingServers2 = repoMcpConfig.mcpServers;
47279
+ if (existingServers2 && typeof existingServers2 === "object" && !Array.isArray(existingServers2) && existingServers2[coordinatorSetup.serverName]) {
47280
+ fs26.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
47281
+ ...repoMcpConfig,
47282
+ mcpServers: {
47283
+ ...existingServers2,
47284
+ [coordinatorSetup.serverName]: coordinatorSetup.mcpServer
47285
+ }
47286
+ }, "claude_mcp_json"), "utf-8");
47287
+ LOG.info("MeshCoordinator", `Refreshed repo-local ${repoMcpConfigPath} entry for ${coordinatorSetup.serverName}`);
47288
+ }
47289
+ } catch (error) {
47290
+ return {
47291
+ success: false,
47292
+ code: "mesh_coordinator_config_write_failed",
47293
+ error: `Could not refresh repo-local MCP config: ${error?.message || error}`,
47294
+ meshId,
47295
+ cliType,
47296
+ workspace
47297
+ };
47298
+ }
47299
+ }
47300
+ }
47301
+ const cliCmdArgs = [];
47302
+ const cliCmdEnv = {};
47303
+ let cliCmdContextFilePath;
47304
+ if (cliCmdSystemPrompt) {
47305
+ const { applyMeshCoordinatorSystemPromptInjection: applyMeshCoordinatorSystemPromptInjection2 } = await Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports));
47306
+ const effect = applyMeshCoordinatorSystemPromptInjection2(
47307
+ cliCmdSystemPrompt,
47308
+ providerMeta?.meshCoordinator?.systemPromptInjection,
47309
+ { cliArgs: cliCmdArgs, launchEnv: cliCmdEnv, workspace, cliType }
47310
+ );
47311
+ cliCmdContextFilePath = effect.contextFilePath;
47312
+ }
47313
+ const cliCmdLaunch = await ctx.deps.cliManager.handleCliCommand("launch_cli", {
47314
+ cliType,
47315
+ dir: workspace,
47316
+ cliArgs: cliCmdArgs.length > 0 ? cliCmdArgs : void 0,
47317
+ env: Object.keys(cliCmdEnv).length > 0 ? cliCmdEnv : void 0,
47318
+ settings: { meshCoordinatorFor: meshId }
47319
+ });
47320
+ if (cliCmdLaunch?.success && cliCmdContextFilePath) {
47321
+ const stripPath = cliCmdContextFilePath;
47322
+ setTimeout(() => {
47323
+ void Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports)).then(({ stripCoordinatorWrapperFile: stripCoordinatorWrapperFile2 }) => {
47324
+ stripCoordinatorWrapperFile2(stripPath);
47325
+ LOG.info("MeshCoordinator", `Stripped wrapper from ${stripPath} after launch settle (cli_command)`);
47326
+ }).catch(() => {
47327
+ });
47328
+ }, 5e3);
47329
+ }
47330
+ if (!cliCmdLaunch?.success) {
47331
+ return { success: false, error: cliCmdLaunch?.error || "Failed to launch CLI session" };
47332
+ }
47333
+ LOG.info("MeshCoordinator", `Launched ${cliType} coordinator (cli_command) for mesh ${meshId}`);
47334
+ const cliCmdSessionId = cliCmdLaunch.sessionId || cliCmdLaunch.id;
47335
+ if (cliCmdSessionId) {
47336
+ const cliCmdInjectionDecl = providerMeta?.meshCoordinator?.systemPromptInjection;
47337
+ registerMeshCoordinator({
47338
+ meshId,
47339
+ sessionId: cliCmdSessionId,
47340
+ workspace,
47341
+ startedAt: Date.now(),
47342
+ cliType,
47343
+ systemPrompt: cliCmdSystemPrompt || void 0,
47344
+ extraSystemPrompt: extraSystemPrompt || void 0,
47345
+ injection: cliCmdInjectionDecl ? {
47346
+ mode: cliCmdInjectionDecl.mode,
47347
+ target: "flag" in cliCmdInjectionDecl ? cliCmdInjectionDecl.flag : "name" in cliCmdInjectionDecl ? cliCmdInjectionDecl.name : "path" in cliCmdInjectionDecl ? cliCmdInjectionDecl.path : void 0
47348
+ } : void 0
47349
+ });
47350
+ }
47351
+ try {
47352
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
47353
+ appendLedgerEntry2(meshId, {
47354
+ kind: "coordinator_started",
47355
+ sessionId: cliCmdSessionId,
47356
+ providerType: cliType,
47357
+ payload: { workspace }
47358
+ });
47359
+ } catch {
47360
+ }
47361
+ return {
47362
+ success: true,
47363
+ meshId,
47364
+ cliType,
47365
+ workspace,
47366
+ sessionId: cliCmdSessionId,
47367
+ mcpRegistered: mcpRegistrationOk
47368
+ };
47369
+ }
47370
+ const configFormat = coordinatorSetup.configFormat;
47371
+ if (configFormat !== "claude_mcp_json" && configFormat !== "hermes_config_yaml") {
47372
+ return {
47373
+ success: false,
47374
+ code: "mesh_coordinator_unsupported",
47375
+ error: `Unsupported auto-import MCP config format: ${String(coordinatorSetup.configFormat)}`,
47376
+ meshId,
47377
+ cliType,
47378
+ workspace
47379
+ };
47380
+ }
47381
+ let systemPrompt = "";
47382
+ try {
47383
+ systemPrompt = buildCoordinatorSystemPrompt2({ mesh, coordinatorCliType: cliType, userInstruction: extraSystemPrompt || void 0, missionSection: buildMissionSectionBestEffort(mesh.id) });
47384
+ } catch (error) {
47385
+ const message = error?.message || String(error);
47386
+ LOG.error("MeshCoordinator", `Failed to build coordinator prompt: ${message}`);
47387
+ return {
47388
+ success: false,
47389
+ code: "mesh_coordinator_prompt_failed",
47390
+ error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
47391
+ meshId,
47392
+ cliType,
47393
+ workspace
47394
+ };
47395
+ }
47396
+ const { existsSync: existsSync49, readFileSync: readFileSync39, writeFileSync: writeFileSync24, copyFileSync: copyFileSync4, mkdirSync: mkdirSync21 } = await import("fs");
47397
+ const { dirname: dirname17 } = await import("path");
47398
+ const mcpConfigPath = coordinatorSetup.configPath;
47399
+ const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
47400
+ let hermesBaseConfig = null;
47401
+ if (hermesManualFallback) {
47402
+ try {
47403
+ hermesBaseConfig = loadHermesCoordinatorBaseConfig(mcpConfigPath);
47404
+ } catch (error) {
47405
+ const message = `Failed to parse Hermes base config for automatic coordinator setup: ${error?.message || error}`;
47406
+ LOG.error("MeshCoordinator", message);
47407
+ return { success: false, code: "mesh_coordinator_config_parse_failed", error: message, meshId, cliType, workspace };
47408
+ }
47409
+ }
47410
+ const returnManualFallback = (message) => ({
47411
+ success: false,
47412
+ code: "mesh_coordinator_manual_mcp_setup_required",
47413
+ error: message,
47414
+ meshId,
47415
+ cliType,
47416
+ workspace,
47417
+ meshCoordinatorSetup: hermesManualFallback
47418
+ });
47419
+ const mcpServerEntry = {
47420
+ command: coordinatorSetup.mcpServer.command,
47421
+ args: coordinatorSetup.mcpServer.args
47422
+ };
47423
+ if (args?.inlineMesh) {
47424
+ const modeArgIndex = coordinatorSetup.mcpServer.args.findIndex((value) => value === "--mode");
47425
+ const mcpTransport = modeArgIndex >= 0 ? coordinatorSetup.mcpServer.args[modeArgIndex + 1] : "ipc";
47426
+ mcpServerEntry.env = {
47427
+ ADHDEV_INLINE_MESH: JSON.stringify(mesh),
47428
+ ADHDEV_MCP_TRANSPORT: mcpTransport === "local" ? "local" : "ipc"
47429
+ };
47430
+ }
47431
+ try {
47432
+ mkdirSync21(dirname17(mcpConfigPath), { recursive: true });
47433
+ } catch (error) {
47434
+ const message = `Could not prepare MCP config path for automatic setup: ${error?.message || error}`;
47435
+ LOG.error("MeshCoordinator", message);
47436
+ if (hermesManualFallback) return returnManualFallback(message);
47437
+ return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
47438
+ }
47439
+ const hadExistingMcpConfig = existsSync49(mcpConfigPath);
47440
+ let existingMcpConfig = hermesBaseConfig?.config || {};
47441
+ if (hermesBaseConfig) {
47442
+ copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname17(mcpConfigPath));
47443
+ }
47444
+ if (hadExistingMcpConfig) {
47445
+ try {
47446
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync39(mcpConfigPath, "utf-8"), configFormat);
47447
+ const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
47448
+ existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
47449
+ copyFileSync4(mcpConfigPath, mcpConfigPath + ".backup");
47450
+ } catch (error) {
47451
+ LOG.error("MeshCoordinator", `Failed to parse existing MCP config ${mcpConfigPath}: ${error?.message || error}`);
47452
+ return {
47453
+ success: false,
47454
+ code: "mesh_coordinator_config_parse_failed",
47455
+ error: `Failed to parse existing MCP config at ${mcpConfigPath}`
47456
+ };
47457
+ }
47458
+ }
47459
+ const mcpServersKey = getMcpServersKey(configFormat);
47460
+ const existingServers = existingMcpConfig[mcpServersKey];
47461
+ const mcpConfig = {
47462
+ ...existingMcpConfig,
47463
+ [mcpServersKey]: {
47464
+ ...existingServers && typeof existingServers === "object" && !Array.isArray(existingServers) ? existingServers : {},
47465
+ [coordinatorSetup.serverName]: mcpServerEntry
47466
+ }
47467
+ };
47468
+ try {
47469
+ writeFileSync24(mcpConfigPath, serializeMeshCoordinatorMcpConfig(mcpConfig, configFormat), "utf-8");
47470
+ } catch (error) {
47471
+ const message = `Could not write MCP config for automatic setup: ${error?.message || error}`;
47472
+ LOG.error("MeshCoordinator", message);
47473
+ if (hermesManualFallback) return returnManualFallback(message);
47474
+ return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
47475
+ }
47476
+ LOG.info("MeshCoordinator", `Wrote ${mcpConfigPath} with ${coordinatorSetup.serverName} server`);
47477
+ const cliArgs = [];
47478
+ const launchEnv = {};
47479
+ if (configFormat === "hermes_config_yaml") {
47480
+ launchEnv.HERMES_HOME = dirname17(mcpConfigPath);
47481
+ launchEnv.HERMES_IGNORE_USER_CONFIG = "";
47482
+ }
47483
+ let autoImportContextFilePath;
47484
+ if (systemPrompt) {
47485
+ const { applyMeshCoordinatorSystemPromptInjection: applyMeshCoordinatorSystemPromptInjection2 } = await Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports));
47486
+ const effect = applyMeshCoordinatorSystemPromptInjection2(
47487
+ systemPrompt,
47488
+ providerMeta?.meshCoordinator?.systemPromptInjection,
47489
+ { cliArgs, launchEnv, workspace, cliType }
47490
+ );
47491
+ autoImportContextFilePath = effect.contextFilePath;
47492
+ }
47493
+ if (cliType === "claude-cli") {
47494
+ cliArgs.push("--mcp-config", coordinatorSetup.configPath);
47495
+ }
47496
+ const launchResult = await ctx.deps.cliManager.handleCliCommand("launch_cli", {
47497
+ cliType,
47498
+ dir: workspace,
47499
+ cliArgs: cliArgs.length > 0 ? cliArgs : void 0,
47500
+ env: Object.keys(launchEnv).length > 0 ? launchEnv : void 0,
47501
+ settings: {
47502
+ meshCoordinatorFor: meshId
47503
+ }
47504
+ });
47505
+ if (launchResult?.success && autoImportContextFilePath) {
47506
+ const stripPath = autoImportContextFilePath;
47507
+ setTimeout(() => {
47508
+ void Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports)).then(({ stripCoordinatorWrapperFile: stripCoordinatorWrapperFile2 }) => {
47509
+ stripCoordinatorWrapperFile2(stripPath);
47510
+ LOG.info("MeshCoordinator", `Stripped wrapper from ${stripPath} after launch settle (auto_import)`);
47511
+ }).catch(() => {
47512
+ });
47513
+ }, 5e3);
47514
+ }
47515
+ if (!launchResult?.success) {
47516
+ return { success: false, error: launchResult?.error || "Failed to launch CLI session" };
47517
+ }
47518
+ LOG.info("MeshCoordinator", `Launched ${cliType} coordinator for mesh ${meshId} in ${workspace}`);
47519
+ const launchSessionId = launchResult.sessionId || launchResult.id;
47520
+ if (launchSessionId) {
47521
+ const autoImportInjectionDecl = providerMeta?.meshCoordinator?.systemPromptInjection;
47522
+ registerMeshCoordinator({
47523
+ meshId,
47524
+ sessionId: launchSessionId,
47525
+ workspace,
47526
+ startedAt: Date.now(),
47527
+ cliType,
47528
+ systemPrompt: systemPrompt || void 0,
47529
+ extraSystemPrompt: extraSystemPrompt || void 0,
47530
+ mcpConfigPath,
47531
+ injection: autoImportInjectionDecl ? {
47532
+ mode: autoImportInjectionDecl.mode,
47533
+ target: "flag" in autoImportInjectionDecl ? autoImportInjectionDecl.flag : "name" in autoImportInjectionDecl ? autoImportInjectionDecl.name : "path" in autoImportInjectionDecl ? autoImportInjectionDecl.path : void 0
47534
+ } : void 0
47535
+ });
47536
+ }
47537
+ try {
47538
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
47539
+ appendLedgerEntry2(meshId, {
47540
+ kind: "coordinator_started",
47541
+ sessionId: launchSessionId,
47542
+ providerType: cliType,
47543
+ payload: { workspace }
47544
+ });
47545
+ } catch {
47546
+ }
47547
+ return {
47548
+ success: true,
47549
+ meshId,
47550
+ cliType,
47551
+ workspace,
47552
+ sessionId: launchSessionId,
47553
+ mcpConfigWritten: true
47554
+ };
47555
+ } catch (e) {
47556
+ LOG.error("MeshCoordinator", `Failed: ${e.message}`);
47557
+ return { success: false, error: e.message };
47558
+ }
47559
+ }
47560
+ };
47561
+
47562
+ // src/commands/high-family/mesh-status.ts
47049
47563
  init_config();
47564
+ init_git_status();
47565
+ init_dist();
47566
+ init_mesh_events();
47567
+ init_mesh_routing();
47568
+ init_mesh_host_ownership();
47569
+ import * as fs27 from "fs";
47570
+ import { hostname as osHostname } from "os";
47571
+
47572
+ // src/mesh/preview-freshness.ts
47573
+ import { execFileSync as execFileSync5 } from "child_process";
47574
+ import { existsSync as existsSync39, readFileSync as readFileSync29 } from "fs";
47575
+ import { resolve as resolve19 } from "path";
47576
+ var PREVIEW_DEPLOY_RECORD = ".adhdev/preview-deploy.json";
47577
+ function runGit2(repoRoot, args) {
47578
+ try {
47579
+ return execFileSync5("git", args, {
47580
+ cwd: repoRoot,
47581
+ encoding: "utf8",
47582
+ stdio: ["ignore", "pipe", "ignore"],
47583
+ timeout: 5e3
47584
+ }).trim();
47585
+ } catch {
47586
+ return "";
47587
+ }
47588
+ }
47589
+ function readRecord5(repoRoot) {
47590
+ const path42 = resolve19(repoRoot, PREVIEW_DEPLOY_RECORD);
47591
+ if (!existsSync39(path42)) return null;
47592
+ try {
47593
+ const parsed = JSON.parse(readFileSync29(path42, "utf8"));
47594
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
47595
+ } catch {
47596
+ return null;
47597
+ }
47598
+ }
47599
+ function normalizeCommit(value) {
47600
+ return typeof value === "string" && /^[0-9a-f]{7,40}$/i.test(value.trim()) ? value.trim() : null;
47601
+ }
47602
+ function readTargetFreshness(record, currentCommit) {
47603
+ const targets = record?.targets && typeof record.targets === "object" && !Array.isArray(record.targets) ? record.targets : {};
47604
+ const result = {};
47605
+ for (const targetName of ["npm", "server", "web"]) {
47606
+ const targetRecord = targets[targetName] && typeof targets[targetName] === "object" && !Array.isArray(targets[targetName]) ? targets[targetName] : {};
47607
+ const commit = normalizeCommit(targetRecord.commit);
47608
+ result[targetName] = {
47609
+ commit,
47610
+ deployedAt: typeof targetRecord.deployedAt === "string" ? targetRecord.deployedAt : void 0,
47611
+ status: commit && currentCommit ? commit === currentCommit ? "fresh" : "stale" : "unknown"
47612
+ };
47613
+ }
47614
+ return result;
47615
+ }
47616
+ function readCurrentMainCommit(repoRoot) {
47617
+ const originMain = runGit2(repoRoot, ["rev-parse", "--verify", "origin/main^{commit}"]);
47618
+ if (originMain) {
47619
+ return { currentMainCommit: originMain, currentMainCommitSource: "origin/main" };
47620
+ }
47621
+ const head = runGit2(repoRoot, ["rev-parse", "--verify", "HEAD"]);
47622
+ if (head) {
47623
+ return { currentMainCommit: head, currentMainCommitSource: "HEAD" };
47624
+ }
47625
+ return { currentMainCommit: null, currentMainCommitSource: "unknown" };
47626
+ }
47627
+ function buildPreviewFreshness(repoRoot) {
47628
+ const current = readCurrentMainCommit(repoRoot);
47629
+ const record = readRecord5(repoRoot);
47630
+ const lastPreviewCommit = normalizeCommit(record?.lastPreviewCommit);
47631
+ const targets = readTargetFreshness(record, current.currentMainCommit);
47632
+ let status = "unknown";
47633
+ let nextAction = "Run npm run deploy:preview from the current main commit, then smoke preview.";
47634
+ if (lastPreviewCommit && current.currentMainCommit) {
47635
+ status = lastPreviewCommit === current.currentMainCommit ? "fresh" : "stale";
47636
+ nextAction = status === "fresh" ? "No preview deploy action needed." : "Run npm run deploy:preview from origin/main, then smoke preview.";
47637
+ } else if (!current.currentMainCommit) {
47638
+ nextAction = "Resolve the current main commit before judging preview freshness.";
47639
+ }
47640
+ return {
47641
+ status,
47642
+ lastPreviewCommit,
47643
+ currentMainCommit: current.currentMainCommit,
47644
+ currentMainCommitSource: current.currentMainCommitSource,
47645
+ recordPath: PREVIEW_DEPLOY_RECORD,
47646
+ lastDeployedAt: typeof record?.updatedAt === "string" ? record.updatedAt : void 0,
47647
+ lastTarget: typeof record?.target === "string" ? record.target : void 0,
47648
+ previewVersion: typeof record?.previewVersion === "string" ? record.previewVersion : void 0,
47649
+ targets,
47650
+ nextAction
47651
+ };
47652
+ }
47653
+
47654
+ // src/commands/high-family/mesh-status.ts
47655
+ init_mesh_refine_status();
47656
+ var meshStatusHandlers = {
47657
+ mesh_status: async (ctx, args) => {
47658
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47659
+ if (!meshId) return { success: false, error: "meshId required" };
47660
+ try {
47661
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
47662
+ const mesh = meshRecord?.mesh;
47663
+ if (!mesh) return { success: false, error: "Mesh not found" };
47664
+ const meshHost = resolveMeshHostStatus(mesh);
47665
+ const refreshRequested = args?.refresh === true || args?.forceRefresh === true;
47666
+ const verboseMissions = args?.verbose === true || args?.compact === false;
47667
+ const peekScope = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : ctx.deps.statusInstanceId || void 0;
47668
+ const pendingCoordinatorEventCount = getPendingMeshCoordinatorEvents(meshId, peekScope).length;
47669
+ const hadAggregateCache = ctx.aggregateMeshStatusCache.has(meshId);
47670
+ if (!refreshRequested && !verboseMissions && pendingCoordinatorEventCount === 0) {
47671
+ const cachedStatus = ctx.getCachedAggregateMeshStatus(meshId, mesh, { requireDirectPeerTruth: args?.requireDirectPeerTruth === true });
47672
+ if (cachedStatus) {
47673
+ logRepoMeshStatusDebug("return_cached", {
47674
+ meshId,
47675
+ command: "mesh_status",
47676
+ refreshRequested,
47677
+ summary: summarizeRepoMeshStatusDebug(cachedStatus)
47678
+ });
47679
+ return cachedStatus;
47680
+ }
47681
+ }
47682
+ const refreshReason = refreshRequested ? "explicit_refresh" : pendingCoordinatorEventCount > 0 ? "pending_coordinator_events" : hadAggregateCache ? "stale_pending_cache_refresh" : "cold_cache_miss";
47683
+ const { getMeshQueueStats: getMeshQueueStats2, getQueue: getQueue2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
47684
+ const queue = getQueue2(meshId);
47685
+ const queueSummary = getMeshQueueStats2(meshId);
47686
+ const { readLedgerEntries: readLedgerEntries2, getLedgerSummary: getLedgerSummary2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
47687
+ const ledgerEntries = readLedgerEntries2(meshId, { tail: 20 });
47688
+ const asyncRefineLedgerEntries = readLedgerEntries2(meshId, { tail: 100 });
47689
+ const ledgerSummary = getLedgerSummary2(meshId);
47690
+ const sessionHostRecords = ctx.deps.sessionHostControl?.listSessions ? await ctx.deps.sessionHostControl.listSessions().catch(() => []) : [];
47691
+ const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
47692
+ const localMachineId = loadConfig().machineId || "";
47693
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
47694
+ const meshGitProbeCache = ctx.meshGitProbeCache;
47695
+ const directTruth = requireDirectPeerTruth ? await hydrateInlineMeshDirectTruth({
47696
+ mesh,
47697
+ meshSource: meshRecord.source,
47698
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
47699
+ getMeshPeerConnectionStatus: ctx.deps.getMeshPeerConnectionStatus,
47700
+ statusInstanceId: ctx.deps.statusInstanceId,
47701
+ localMachineId,
47702
+ // Standing-state model: only an explicit refresh fans
47703
+ // out a blocking peer git probe. Default loads return
47704
+ // held truth so one slow peer can't block the graph.
47705
+ probeRemotePeers: refreshRequested,
47706
+ probeCache: meshGitProbeCache
47707
+ }) : {
47708
+ directEvidenceCount: 0,
47709
+ localConfirmedCount: 0,
47710
+ peerAttemptedCount: 0,
47711
+ peerConfirmedCount: 0,
47712
+ standingEvidenceCount: 0,
47713
+ unavailableNodeIds: [],
47714
+ deadNodeIds: []
47715
+ };
47716
+ const passivePeerTruthNotAttempted = requireDirectPeerTruth && !refreshRequested && directTruth.directEvidenceCount > 0 && directTruth.peerAttemptedCount === 0;
47717
+ const effectiveDirectTruth = passivePeerTruthNotAttempted ? { ...directTruth, unavailableNodeIds: [] } : directTruth;
47718
+ const unavailableDirectTruthNodeIds = new Set(effectiveDirectTruth.unavailableNodeIds);
47719
+ const unavailableNodesAreOnlyRemovedWorktrees = unavailableDirectTruthNodeIds.size > 0 && Array.isArray(mesh.nodes) && mesh.nodes.filter((node) => unavailableDirectTruthNodeIds.has(normalizeMeshNodeId(node) ?? "")).every((node) => node?.isLocalWorktree === true);
47720
+ const directTruthSatisfied = !requireDirectPeerTruth || !refreshRequested || effectiveDirectTruth.directEvidenceCount > 0 && (effectiveDirectTruth.unavailableNodeIds.length === 0 || unavailableNodesAreOnlyRemovedWorktrees);
47721
+ if (requireDirectPeerTruth && refreshRequested && !directTruthSatisfied) {
47722
+ const failureResult = {
47723
+ success: false,
47724
+ code: "mesh_direct_peer_truth_unavailable",
47725
+ error: "Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct mesh_status probes succeed.",
47726
+ sourceOfTruth: {
47727
+ membership: meshRecord.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
47728
+ coordinatorOwnsLiveTruth: false,
47729
+ currentStatus: "direct_peer_truth_unavailable",
47730
+ directPeerTruth: {
47731
+ required: true,
47732
+ satisfied: false,
47733
+ directEvidenceCount: directTruth.directEvidenceCount,
47734
+ localConfirmedCount: directTruth.localConfirmedCount,
47735
+ peerAttemptedCount: directTruth.peerAttemptedCount,
47736
+ peerConfirmedCount: directTruth.peerConfirmedCount,
47737
+ unavailableNodeIds: directTruth.unavailableNodeIds
47738
+ }
47739
+ }
47740
+ };
47741
+ logRepoMeshStatusDebug("direct_truth_unavailable", {
47742
+ meshId,
47743
+ command: "mesh_status",
47744
+ refreshRequested,
47745
+ meshSource: meshRecord.source,
47746
+ directTruth
47747
+ });
47748
+ return failureResult;
47749
+ }
47750
+ const directTruthUnavailableNodeIds = new Set(effectiveDirectTruth.unavailableNodeIds);
47751
+ const coordinatorHostname = osHostname();
47752
+ const selectedCoordinatorNodeId = readStringValue(
47753
+ mesh.coordinator?.preferredNodeId,
47754
+ normalizeMeshNodeId(mesh.nodes?.[0])
47755
+ );
47756
+ const inlineCoordinatorNodeId = meshRecord?.inline && Array.isArray(mesh.nodes) ? selectedCoordinatorNodeId : void 0;
47757
+ const refreshedAt = (/* @__PURE__ */ new Date()).toISOString();
47758
+ const nodeStatuses = [];
47759
+ for (const [nodeIndex, node] of (mesh.nodes || []).entries()) {
47760
+ const nodeId = normalizeMeshNodeId(node) ?? "";
47761
+ const daemonId = readStringValue(node.daemonId);
47762
+ const nodeMachineId = readMeshNodeMachineId(node);
47763
+ const nodeHostname = readMeshNodeHostname(node);
47764
+ const providerPriority = readProviderPriorityFromPolicy(node.policy);
47765
+ const configuredCoordinatorNode = Boolean(
47766
+ nodeId && selectedCoordinatorNodeId && nodeId === selectedCoordinatorNodeId
47767
+ );
47768
+ const sparseConfiguredCoordinatorNode = configuredCoordinatorNode && !daemonId && !nodeMachineId && !nodeHostname;
47769
+ const isSelfNode = Boolean(
47770
+ nodeId && inlineCoordinatorNodeId && nodeId === inlineCoordinatorNodeId
47771
+ ) || Boolean(
47772
+ daemonId && (daemonIdsEquivalent(daemonId, localMachineId) || daemonIdsEquivalent(daemonId, ctx.deps.statusInstanceId))
47773
+ ) || Boolean(meshRecord?.inline && nodeIndex === 0) || sparseConfiguredCoordinatorNode;
47774
+ const machineIdentity = buildMeshNodeMachineIdentity(node, {
47775
+ localMachineId,
47776
+ localDaemonId: ctx.deps.statusInstanceId,
47777
+ coordinatorHostname,
47778
+ isSelfNode
47779
+ });
47780
+ const status = {
47781
+ nodeId,
47782
+ machineLabel: buildMeshNodeDisplayLabel(node, nodeId, providerPriority),
47783
+ labelSource: readStringValue(node.machineLabel, node.machine_label, node.machineNickname, node.machine_nickname, node.alias) ? "explicit_metadata" : "workspace_host_provider_context",
47784
+ workspace: node.workspace,
47785
+ repoRoot: node.repoRoot,
47786
+ isLocalWorktree: node.isLocalWorktree,
47787
+ worktreeBranch: node.worktreeBranch,
47788
+ role: normalizeMeshDaemonRole(node.role) || (meshHost.hostNodeId && nodeId === meshHost.hostNodeId ? "host" : void 0),
47789
+ daemonId,
47790
+ machineId: nodeMachineId || node.machineId,
47791
+ machine: machineIdentity,
47792
+ machineStatus: node.machineStatus,
47793
+ health: "unknown",
47794
+ providers: node.providers || [],
47795
+ providerPriority,
47796
+ activeSessions: [],
47797
+ activeSessionDetails: [],
47798
+ launchReady: false
47799
+ };
47800
+ if (isSelfNode) {
47801
+ status.connection = {
47802
+ perspective: "selected_coordinator",
47803
+ source: "mesh_peer_status",
47804
+ state: "self",
47805
+ transport: "local",
47806
+ reported: true,
47807
+ reason: "Selected coordinator daemon",
47808
+ lastStateChangeAt: refreshedAt
47809
+ };
47810
+ } else if (daemonId) {
47811
+ const connection = ctx.deps.getMeshPeerConnectionStatus?.(daemonId);
47812
+ status.connection = connection ?? {
47813
+ perspective: "selected_coordinator",
47814
+ source: "not_reported",
47815
+ state: "unknown",
47816
+ transport: "unknown",
47817
+ reported: false,
47818
+ reason: "No live mesh peer telemetry reported by the selected coordinator yet."
47819
+ };
47820
+ } else {
47821
+ status.connection = {
47822
+ perspective: "selected_coordinator",
47823
+ source: "not_reported",
47824
+ state: "unknown",
47825
+ transport: "unknown",
47826
+ reported: false,
47827
+ reason: "Node has no daemon id, so mesh transport cannot be reported from the selected coordinator."
47828
+ };
47829
+ }
47830
+ const matchedLiveSessionRecords = collectLiveMeshSessionRecords({
47831
+ meshId,
47832
+ node,
47833
+ nodeId,
47834
+ liveSessionRecords: liveMeshSessions,
47835
+ allowCoordinatorSession: nodeId === selectedCoordinatorNodeId
47836
+ });
47837
+ const workspace = readLiveMeshNodeWorkspace({
47838
+ meshId,
47839
+ nodeId,
47840
+ liveSessionRecords: matchedLiveSessionRecords,
47841
+ allowCoordinatorSession: nodeId === selectedCoordinatorNodeId
47842
+ }) || (typeof node.workspace === "string" ? node.workspace : "");
47843
+ status.workspace = workspace || node.workspace;
47844
+ if (matchedLiveSessionRecords.length > 0) {
47845
+ const sessionIds = matchedLiveSessionRecords.map((record) => typeof record?.sessionId === "string" ? record.sessionId : "").filter(Boolean);
47846
+ const providerTypes = matchedLiveSessionRecords.map((record) => readStringValue(record?.providerType)).filter(Boolean);
47847
+ status.activeSessions = sessionIds;
47848
+ status.activeSessionDetails = matchedLiveSessionRecords.map(summarizeMeshSessionRecord);
47849
+ if (providerTypes.length > 0) {
47850
+ status.providers = Array.from(/* @__PURE__ */ new Set([...Array.isArray(status.providers) ? status.providers : [], ...providerTypes]));
47851
+ }
47852
+ }
47853
+ if (workspace) {
47854
+ if (!fs27.existsSync(workspace)) {
47855
+ const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
47856
+ let remoteProbeApplied = false;
47857
+ if (inlineTransitGit) {
47858
+ status.git = inlineTransitGit;
47859
+ status.health = inlineTransitGit.isGitRepo ? deriveMeshNodeHealthFromGit(inlineTransitGit) : "degraded";
47860
+ const connection = readObjectRecord(status.connection);
47861
+ const connectionState = readStringValue(connection.state);
47862
+ const connectionReported = readBooleanValue(connection.reported) ?? false;
47863
+ if (!connectionReported || connectionState === "unknown") {
47864
+ status.connection = buildLivePeerGitConnection(connection, refreshedAt);
47865
+ }
47866
+ remoteProbeApplied = true;
47867
+ } else if (refreshRequested && !isSelfNode && daemonId && ctx.deps.dispatchMeshCommand && !directTruthUnavailableNodeIds.has(nodeId)) {
47868
+ const runNodeProbe = () => probeRemoteMeshGitStatusWithRetry({
47869
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
47870
+ daemonId,
47871
+ workspace,
47872
+ timeoutMs: MESH_DIRECT_PROBE_TIMEOUT_MS,
47873
+ retryTimeoutMs: MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS,
47874
+ getConnection: ctx.deps.getMeshPeerConnectionStatus,
47875
+ onConnection: (connection) => {
47876
+ status.connection = connection;
47877
+ }
47878
+ });
47879
+ const remoteGit = await meshGitProbeCache.probe(daemonId, workspace, runNodeProbe);
47880
+ if (remoteGit) {
47881
+ status.git = remoteGit;
47882
+ status.health = remoteGit.isGitRepo ? deriveMeshNodeHealthFromGit(remoteGit) : "degraded";
47883
+ const connection = readObjectRecord(status.connection);
47884
+ const connectionState = readStringValue(connection.state);
47885
+ const connectionReported = readBooleanValue(connection.reported) ?? false;
47886
+ if (!connectionReported || connectionState === "unknown") {
47887
+ status.connection = buildLivePeerGitConnection(connection, refreshedAt);
47888
+ }
47889
+ const reporter = recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
47890
+ persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
47891
+ remoteProbeApplied = true;
47892
+ }
47893
+ }
47894
+ if (!remoteProbeApplied) {
47895
+ const connectionState = readStringValue(status.connection?.state);
47896
+ const pendingPeerGitProbe = !inlineTransitGit && !isSelfNode && !!daemonId && (readStringValue(status.machineStatus) === "online" || readStringValue(status.health) === "online" || connectionState === "connecting" || connectionState === "connected" || connectionState === "unknown");
47897
+ if (pendingPeerGitProbe) {
47898
+ status.gitProbePending = true;
47899
+ status.health = "unknown";
47900
+ }
47901
+ if (applyCachedInlineMeshNodeStatus(
47902
+ status,
47903
+ node,
47904
+ pendingPeerGitProbe ? { skipGit: true, skipError: true, skipHealth: true } : void 0
47905
+ )) {
47906
+ applyInlineMeshBranchConvergence(mesh, node, status);
47907
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
47908
+ nodeStatuses.push(status);
47909
+ continue;
47910
+ }
47911
+ if (meshRecord?.source === "inline_cache" && !isSelfNode) {
47912
+ applyInlineMeshBranchConvergence(mesh, node, status);
47913
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
47914
+ nodeStatuses.push(status);
47915
+ continue;
47916
+ }
47917
+ }
47918
+ } else {
47919
+ try {
47920
+ const gitStatus = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
47921
+ status.git = gitStatus;
47922
+ const reporter = recordInlineMeshDirectGitTruth(node, gitStatus, "selected_coordinator_local_git");
47923
+ persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
47924
+ if (gitStatus.isGitRepo) {
47925
+ status.health = deriveMeshNodeHealthFromGit(gitStatus);
47926
+ } else {
47927
+ status.health = "degraded";
47928
+ if (gitStatus.error && !status.error) status.error = gitStatus.error;
47929
+ }
47930
+ } catch {
47931
+ if (!applyCachedInlineMeshNodeStatus(status, node)) {
47932
+ status.health = "degraded";
47933
+ }
47934
+ }
47935
+ }
47936
+ } else {
47937
+ applyCachedInlineMeshNodeStatus(status, node);
47938
+ }
47939
+ applyInlineMeshBranchConvergence(mesh, node, status);
47940
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
47941
+ nodeStatuses.push(status);
47942
+ }
47943
+ const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : ctx.deps.statusInstanceId || void 0;
47944
+ const pendingCoordinatorEvents = getPendingMeshCoordinatorEvents(meshId, callerCoordinatorDaemonId);
47945
+ const unroutableDeliveries = getRecentUnroutableDeliveries();
47946
+ const previewFreshness = (() => {
47947
+ const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs27.existsSync(candidate));
47948
+ return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
47949
+ })();
47950
+ const asyncRefineJobs = buildMeshAsyncRefineJobs({
47951
+ meshId,
47952
+ ledgerEntries: asyncRefineLedgerEntries,
47953
+ pendingEvents: [...pendingCoordinatorEvents]
47954
+ });
47955
+ const historicalSessions = buildHistoricalMeshSessions({
47956
+ meshId,
47957
+ nodes: mesh.nodes || [],
47958
+ liveSessionRecords: liveMeshSessions
47959
+ });
47960
+ const { getMeshStatusMissionSummaries: getMeshStatusMissionSummaries2 } = await Promise.resolve().then(() => (init_mesh_missions(), mesh_missions_exports));
47961
+ const missions = getMeshStatusMissionSummaries2(meshId, { verbose: verboseMissions, withStats: true });
47962
+ const statusResult = {
47963
+ success: true,
47964
+ meshId: mesh.id,
47965
+ meshName: mesh.name,
47966
+ repoIdentity: mesh.repoIdentity,
47967
+ defaultBranch: mesh.defaultBranch,
47968
+ refreshedAt,
47969
+ meshHost,
47970
+ sourceOfTruth: {
47971
+ membership: meshRecord?.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord?.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
47972
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
47973
+ meshHost: {
47974
+ owner: "mesh_host_daemon",
47975
+ localRole: meshHost.role,
47976
+ hostDaemonId: meshHost.hostDaemonId,
47977
+ hostNodeId: meshHost.hostNodeId,
47978
+ hostAddress: meshHost.hostAddress
47979
+ },
47980
+ ...requireDirectPeerTruth ? {
47981
+ currentStatus: directTruthSatisfied ? "live_git_and_session_probes" : "direct_peer_truth_unavailable",
47982
+ directPeerTruth: {
47983
+ required: true,
47984
+ satisfied: directTruthSatisfied,
47985
+ directEvidenceCount: effectiveDirectTruth.directEvidenceCount,
47986
+ localConfirmedCount: effectiveDirectTruth.localConfirmedCount,
47987
+ peerAttemptedCount: effectiveDirectTruth.peerAttemptedCount,
47988
+ peerConfirmedCount: effectiveDirectTruth.peerConfirmedCount,
47989
+ unavailableNodeIds: effectiveDirectTruth.unavailableNodeIds,
47990
+ partialNodeFailures: effectiveDirectTruth.unavailableNodeIds
47991
+ }
47992
+ } : {},
47993
+ historicalEvidenceOnly: ["recoveryHints", "ledger.summary", "queue.summary", "historicalSessions"]
47994
+ },
47995
+ branchConvergenceSummary: summarizeInlineMeshBranchConvergence(nodeStatuses),
47996
+ ...previewFreshness ? { previewFreshness, deployFreshness: previewFreshness } : {},
47997
+ nodes: nodeStatuses,
47998
+ queue: { tasks: queue, summary: queueSummary },
47999
+ ledger: { entries: ledgerEntries, summary: ledgerSummary },
48000
+ ...missions.length > 0 ? { missions } : {},
48001
+ ...asyncRefineJobs.length > 0 ? { asyncRefineJobs } : {},
48002
+ ...historicalSessions ? { historicalSessions } : {},
48003
+ ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
48004
+ ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {},
48005
+ activeRefineJobs: Array.from(ctx.runningRefineJobs.values()).filter((job) => job.meshId === meshId).map((job) => ({
48006
+ jobId: job.jobId,
48007
+ nodeId: job.targetNodeId,
48008
+ workspace: job.workspace,
48009
+ startedAt: job.startedAt,
48010
+ status: job.status,
48011
+ targetCoordinatorDaemonId: job.targetCoordinatorDaemonId
48012
+ }))
48013
+ };
48014
+ const { pendingCoordinatorEvents: _pendingCoordinatorEvents, unroutableDeliveries: _unroutableDeliveries, ...cacheableStatusResult } = statusResult;
48015
+ const rememberedStatus = verboseMissions ? cacheableStatusResult : ctx.rememberAggregateMeshStatus(meshId, cacheableStatusResult, refreshReason);
48016
+ const returnedStatus = {
48017
+ ...rememberedStatus,
48018
+ ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
48019
+ ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {}
48020
+ };
48021
+ logRepoMeshStatusDebug("return_live", {
48022
+ meshId,
48023
+ command: "mesh_status",
48024
+ refreshRequested,
48025
+ refreshReason,
48026
+ meshSource: meshRecord.source,
48027
+ directTruth,
48028
+ summary: summarizeRepoMeshStatusDebug(returnedStatus)
48029
+ });
48030
+ return returnedStatus;
48031
+ } catch (e) {
48032
+ return { success: false, error: e.message };
48033
+ }
48034
+ },
48035
+ get_mesh_review_inbox: async (ctx, args) => {
48036
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
48037
+ if (!meshId) return { success: false, error: "meshId required" };
48038
+ try {
48039
+ const { deriveMeshReviewInboxItems: deriveMeshReviewInboxItems2 } = await Promise.resolve().then(() => (init_mesh_review_inbox(), mesh_review_inbox_exports));
48040
+ const { readLedgerEntries: readLedgerEntries2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
48041
+ const { getGitDiffSummary: getGitDiffSummary2 } = await Promise.resolve().then(() => (init_git_diff(), git_diff_exports));
48042
+ const { existsSync: existsSync49 } = await import("fs");
48043
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
48044
+ const mesh = meshRecord?.mesh;
48045
+ if (!mesh) return { success: false, error: "Mesh not found" };
48046
+ const inlineNodes = args?.inlineMesh && Array.isArray(args.inlineMesh?.nodes) ? args.inlineMesh.nodes : null;
48047
+ let cachedStatus = !inlineNodes ? ctx.getCachedAggregateMeshStatus(meshId, mesh, {}) : null;
48048
+ if (!cachedStatus && !inlineNodes) {
48049
+ const freshStatus = await ctx.execute("mesh_status", {
48050
+ meshId,
48051
+ inlineMesh: args?.inlineMesh,
48052
+ refresh: true
48053
+ }, "get_mesh_review_inbox");
48054
+ cachedStatus = freshStatus?.success !== false ? freshStatus : null;
48055
+ }
48056
+ const nodeStatuses = inlineNodes ? inlineNodes : Array.isArray(cachedStatus?.nodes) ? cachedStatus.nodes : Array.isArray(mesh.nodes) ? mesh.nodes : [];
48057
+ const ledgerEntries = readLedgerEntries2(meshId, { tail: 300 });
48058
+ const derivation = deriveMeshReviewInboxItems2({ nodes: nodeStatuses, ledgerEntries });
48059
+ for (const item of derivation.items) {
48060
+ const workspace = item.workspace;
48061
+ if (!workspace || !existsSync49(workspace)) continue;
48062
+ const baseRef = item.defaultBranch ? `origin/${item.defaultBranch}` : "origin/main";
48063
+ try {
48064
+ const diffResult = await getGitDiffSummary2(workspace, { baseRef, maxFiles: 100 });
48065
+ if (diffResult.isGitRepo) {
48066
+ item.diffSummary = {
48067
+ baseRef,
48068
+ files: diffResult.files.map((f) => ({
48069
+ path: f.path,
48070
+ status: f.status,
48071
+ insertions: f.insertions,
48072
+ deletions: f.deletions,
48073
+ binary: f.binary,
48074
+ oldPath: f.oldPath
48075
+ })),
48076
+ totalFiles: diffResult.files.length,
48077
+ totalInsertions: diffResult.totalInsertions,
48078
+ totalDeletions: diffResult.totalDeletions,
48079
+ truncated: diffResult.truncated,
48080
+ ...diffResult.error ? { error: diffResult.error } : {}
48081
+ };
48082
+ }
48083
+ } catch {
48084
+ item.diffSummary = null;
48085
+ }
48086
+ }
48087
+ return {
48088
+ success: true,
48089
+ meshId,
48090
+ inbox: derivation.items,
48091
+ remoteNodesExcluded: derivation.remoteNodesExcluded,
48092
+ excludedRemoteNodeIds: derivation.excludedRemoteNodeIds
48093
+ };
48094
+ } catch (e) {
48095
+ return { success: false, error: e.message };
48096
+ }
48097
+ }
48098
+ };
48099
+
48100
+ // src/commands/high-family/index.ts
48101
+ var highFamilyRegistry = new Map(
48102
+ Object.entries({
48103
+ ...meshEventsHandlers,
48104
+ ...meshCoordinatorLaunchHandlers,
48105
+ ...meshStatusHandlers
48106
+ })
48107
+ );
48108
+
48109
+ // src/commands/router.ts
47050
48110
  init_cli_detector();
47051
48111
  init_git_status();
47052
48112
  init_dist();
47053
48113
  init_logger();
47054
48114
 
47055
48115
  // src/logging/command-log.ts
47056
- import * as fs26 from "fs";
48116
+ import * as fs28 from "fs";
47057
48117
  import * as path36 from "path";
47058
48118
  import * as os27 from "os";
47059
48119
  var ADHDEV_HOME2 = process.env.ADHDEV_CONFIG_DIR && process.env.ADHDEV_CONFIG_DIR.trim() ? process.env.ADHDEV_CONFIG_DIR.trim() : path36.join(os27.homedir(), ".adhdev");
@@ -47061,7 +48121,7 @@ var LOG_DIR2 = path36.join(ADHDEV_HOME2, "logs");
47061
48121
  var MAX_FILE_SIZE = 5 * 1024 * 1024;
47062
48122
  var MAX_DAYS = 7;
47063
48123
  try {
47064
- fs26.mkdirSync(LOG_DIR2, { recursive: true });
48124
+ fs28.mkdirSync(LOG_DIR2, { recursive: true });
47065
48125
  } catch {
47066
48126
  }
47067
48127
  var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
@@ -47107,7 +48167,7 @@ function checkRotation() {
47107
48167
  }
47108
48168
  function cleanOldFiles() {
47109
48169
  try {
47110
- const files = fs26.readdirSync(LOG_DIR2).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
48170
+ const files = fs28.readdirSync(LOG_DIR2).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
47111
48171
  const cutoff = /* @__PURE__ */ new Date();
47112
48172
  cutoff.setDate(cutoff.getDate() - MAX_DAYS);
47113
48173
  const cutoffStr = cutoff.toISOString().slice(0, 10);
@@ -47115,7 +48175,7 @@ function cleanOldFiles() {
47115
48175
  const dateMatch = file.match(/commands-(\d{4}-\d{2}-\d{2})/);
47116
48176
  if (dateMatch && dateMatch[1] < cutoffStr) {
47117
48177
  try {
47118
- fs26.unlinkSync(path36.join(LOG_DIR2, file));
48178
+ fs28.unlinkSync(path36.join(LOG_DIR2, file));
47119
48179
  } catch {
47120
48180
  }
47121
48181
  }
@@ -47125,14 +48185,14 @@ function cleanOldFiles() {
47125
48185
  }
47126
48186
  function checkSize() {
47127
48187
  try {
47128
- const stat2 = fs26.statSync(currentFile);
48188
+ const stat2 = fs28.statSync(currentFile);
47129
48189
  if (stat2.size > MAX_FILE_SIZE) {
47130
48190
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
47131
48191
  try {
47132
- fs26.unlinkSync(backup);
48192
+ fs28.unlinkSync(backup);
47133
48193
  } catch {
47134
48194
  }
47135
- fs26.renameSync(currentFile, backup);
48195
+ fs28.renameSync(currentFile, backup);
47136
48196
  }
47137
48197
  } catch {
47138
48198
  }
@@ -47165,14 +48225,14 @@ function logCommand(entry) {
47165
48225
  ...entry.error ? { err: entry.error } : {},
47166
48226
  ...entry.durationMs !== void 0 ? { ms: entry.durationMs } : {}
47167
48227
  });
47168
- fs26.appendFileSync(currentFile, line + "\n");
48228
+ fs28.appendFileSync(currentFile, line + "\n");
47169
48229
  } catch {
47170
48230
  }
47171
48231
  }
47172
48232
  function getRecentCommands(count = 50) {
47173
48233
  try {
47174
- if (!fs26.existsSync(currentFile)) return [];
47175
- const content = fs26.readFileSync(currentFile, "utf-8");
48234
+ if (!fs28.existsSync(currentFile)) return [];
48235
+ const content = fs28.readFileSync(currentFile, "utf-8");
47176
48236
  const lines = content.trim().split("\n").filter(Boolean);
47177
48237
  return lines.slice(-count).map((line) => {
47178
48238
  try {
@@ -47199,10 +48259,7 @@ cleanOldFiles();
47199
48259
 
47200
48260
  // src/commands/router.ts
47201
48261
  import * as yaml4 from "js-yaml";
47202
- init_mesh_coordinator();
47203
- init_coordinator_registry();
47204
48262
  init_mesh_events();
47205
- init_mesh_routing();
47206
48263
  init_mesh_host_ownership();
47207
48264
 
47208
48265
  // src/mesh/mesh-refine-batch.ts
@@ -47292,95 +48349,12 @@ function orderMeshRefineBatchNodes(changeAreas) {
47292
48349
  return { order: ranked.map((a) => a.nodeId), changeAreas: areaById, rationale };
47293
48350
  }
47294
48351
 
47295
- // src/mesh/preview-freshness.ts
47296
- import { execFileSync as execFileSync5 } from "child_process";
47297
- import { existsSync as existsSync39, readFileSync as readFileSync29 } from "fs";
47298
- import { resolve as resolve19 } from "path";
47299
- var PREVIEW_DEPLOY_RECORD = ".adhdev/preview-deploy.json";
47300
- function runGit2(repoRoot, args) {
47301
- try {
47302
- return execFileSync5("git", args, {
47303
- cwd: repoRoot,
47304
- encoding: "utf8",
47305
- stdio: ["ignore", "pipe", "ignore"],
47306
- timeout: 5e3
47307
- }).trim();
47308
- } catch {
47309
- return "";
47310
- }
47311
- }
47312
- function readRecord5(repoRoot) {
47313
- const path42 = resolve19(repoRoot, PREVIEW_DEPLOY_RECORD);
47314
- if (!existsSync39(path42)) return null;
47315
- try {
47316
- const parsed = JSON.parse(readFileSync29(path42, "utf8"));
47317
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
47318
- } catch {
47319
- return null;
47320
- }
47321
- }
47322
- function normalizeCommit(value) {
47323
- return typeof value === "string" && /^[0-9a-f]{7,40}$/i.test(value.trim()) ? value.trim() : null;
47324
- }
47325
- function readTargetFreshness(record, currentCommit) {
47326
- const targets = record?.targets && typeof record.targets === "object" && !Array.isArray(record.targets) ? record.targets : {};
47327
- const result = {};
47328
- for (const targetName of ["npm", "server", "web"]) {
47329
- const targetRecord = targets[targetName] && typeof targets[targetName] === "object" && !Array.isArray(targets[targetName]) ? targets[targetName] : {};
47330
- const commit = normalizeCommit(targetRecord.commit);
47331
- result[targetName] = {
47332
- commit,
47333
- deployedAt: typeof targetRecord.deployedAt === "string" ? targetRecord.deployedAt : void 0,
47334
- status: commit && currentCommit ? commit === currentCommit ? "fresh" : "stale" : "unknown"
47335
- };
47336
- }
47337
- return result;
47338
- }
47339
- function readCurrentMainCommit(repoRoot) {
47340
- const originMain = runGit2(repoRoot, ["rev-parse", "--verify", "origin/main^{commit}"]);
47341
- if (originMain) {
47342
- return { currentMainCommit: originMain, currentMainCommitSource: "origin/main" };
47343
- }
47344
- const head = runGit2(repoRoot, ["rev-parse", "--verify", "HEAD"]);
47345
- if (head) {
47346
- return { currentMainCommit: head, currentMainCommitSource: "HEAD" };
47347
- }
47348
- return { currentMainCommit: null, currentMainCommitSource: "unknown" };
47349
- }
47350
- function buildPreviewFreshness(repoRoot) {
47351
- const current = readCurrentMainCommit(repoRoot);
47352
- const record = readRecord5(repoRoot);
47353
- const lastPreviewCommit = normalizeCommit(record?.lastPreviewCommit);
47354
- const targets = readTargetFreshness(record, current.currentMainCommit);
47355
- let status = "unknown";
47356
- let nextAction = "Run npm run deploy:preview from the current main commit, then smoke preview.";
47357
- if (lastPreviewCommit && current.currentMainCommit) {
47358
- status = lastPreviewCommit === current.currentMainCommit ? "fresh" : "stale";
47359
- nextAction = status === "fresh" ? "No preview deploy action needed." : "Run npm run deploy:preview from origin/main, then smoke preview.";
47360
- } else if (!current.currentMainCommit) {
47361
- nextAction = "Resolve the current main commit before judging preview freshness.";
47362
- }
47363
- return {
47364
- status,
47365
- lastPreviewCommit,
47366
- currentMainCommit: current.currentMainCommit,
47367
- currentMainCommitSource: current.currentMainCommitSource,
47368
- recordPath: PREVIEW_DEPLOY_RECORD,
47369
- lastDeployedAt: typeof record?.updatedAt === "string" ? record.updatedAt : void 0,
47370
- lastTarget: typeof record?.target === "string" ? record.target : void 0,
47371
- previewVersion: typeof record?.previewVersion === "string" ? record.previewVersion : void 0,
47372
- targets,
47373
- nextAction
47374
- };
47375
- }
47376
-
47377
48352
  // src/commands/router.ts
47378
- init_mesh_refine_status();
47379
48353
  init_mesh_work_queue();
47380
48354
  init_repo_mesh_types();
47381
- import { homedir as homedir26, hostname as osHostname } from "os";
47382
- import { basename as pathBasename, join as pathJoin, resolve as pathResolve2 } from "path";
47383
- import * as fs27 from "fs";
48355
+ import { homedir as homedir26 } from "os";
48356
+ import { basename as pathBasename, join as pathJoin2, resolve as pathResolve2 } from "path";
48357
+ import * as fs29 from "fs";
47384
48358
  import { execFileSync as execFileSync6 } from "child_process";
47385
48359
  init_resolve_executable();
47386
48360
  function readProviderPriorityFromPolicy(policy) {
@@ -47728,7 +48702,7 @@ function isDeadLocalWorktreeNode(node) {
47728
48702
  if (node?.isLocalWorktree !== true) return false;
47729
48703
  const workspace = readStringValue(node?.workspace);
47730
48704
  if (!workspace) return false;
47731
- return !fs27.existsSync(workspace);
48705
+ return !fs29.existsSync(workspace);
47732
48706
  }
47733
48707
  function foldMeshNodeIdentityToCanonical(node) {
47734
48708
  if (!node || typeof node !== "object" || Array.isArray(node)) return node;
@@ -47976,7 +48950,7 @@ function summarizeInlineMeshBranchConvergence(nodes) {
47976
48950
  const followUps = nodes.filter((node) => {
47977
48951
  if (readObjectRecord(node.branchConvergence).needsConvergence !== true) return false;
47978
48952
  const workspace = typeof node.workspace === "string" ? node.workspace : "";
47979
- if (workspace && !fs27.existsSync(workspace)) return false;
48953
+ if (workspace && !fs29.existsSync(workspace)) return false;
47980
48954
  return true;
47981
48955
  }).map((node) => {
47982
48956
  const convergence = readObjectRecord(node.branchConvergence);
@@ -48284,7 +49258,7 @@ async function hydrateInlineMeshDirectTruth(args) {
48284
49258
  if (!isSelfNode && daemonId) unavailableNodeIds.push(nodeId);
48285
49259
  continue;
48286
49260
  }
48287
- if (fs27.existsSync(workspace)) {
49261
+ if (fs29.existsSync(workspace)) {
48288
49262
  try {
48289
49263
  const localGit = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
48290
49264
  if (localGit?.isGitRepo) {
@@ -48392,7 +49366,7 @@ function readLiveMeshNodeWorkspace(args) {
48392
49366
  }
48393
49367
  function collectLiveMeshSessionRecords(args) {
48394
49368
  const nodeWorkspace = readStringValue(args.node?.workspace);
48395
- const nodeIsMissingLocalWorktree = args.node?.isLocalWorktree === true && !!nodeWorkspace && !fs27.existsSync(nodeWorkspace);
49369
+ const nodeIsMissingLocalWorktree = args.node?.isLocalWorktree === true && !!nodeWorkspace && !fs29.existsSync(nodeWorkspace);
48396
49370
  const matches = args.liveSessionRecords.filter((record) => {
48397
49371
  const recordNodeId = readStringValue(record?.meta?.meshNodeId);
48398
49372
  if (recordNodeId && recordNodeId !== args.nodeId) return false;
@@ -48419,7 +49393,7 @@ function buildHistoricalMeshSessions(args) {
48419
49393
  const workspace = readStringValue(node?.workspace);
48420
49394
  if (nodeId) liveNodeIds.add(nodeId);
48421
49395
  if (workspace) liveWorkspaces.add(workspace);
48422
- if (nodeId && node?.isLocalWorktree === true && workspace && !fs27.existsSync(workspace)) {
49396
+ if (nodeId && node?.isLocalWorktree === true && workspace && !fs29.existsSync(workspace)) {
48423
49397
  missingLocalWorktreeNodeIds.add(nodeId);
48424
49398
  }
48425
49399
  }
@@ -48855,7 +49829,7 @@ function isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit) {
48855
49829
  if (!baseCommit || !branchCommit) return false;
48856
49830
  if (baseCommit === branchCommit) return true;
48857
49831
  try {
48858
- if (!fs27.existsSync(submoduleRepoPath)) return false;
49832
+ if (!fs29.existsSync(submoduleRepoPath)) return false;
48859
49833
  execFileSync6("git", ["cat-file", "-e", `${baseCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
48860
49834
  execFileSync6("git", ["cat-file", "-e", `${branchCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
48861
49835
  execFileSync6("git", ["merge-base", "--is-ancestor", baseCommit, branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
@@ -48956,7 +49930,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
48956
49930
  if (!tree) return void 0;
48957
49931
  const updates = paths.map((path42) => `160000 commit ${placeholderCommit} ${path42}`).join("\n");
48958
49932
  if (!updates) return tree;
48959
- const tmpIndex = pathJoin(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
49933
+ const tmpIndex = pathJoin2(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
48960
49934
  const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
48961
49935
  try {
48962
49936
  execFileSync6("git", ["read-tree", tree], { cwd: repoRoot, env, stdio: "ignore" });
@@ -48972,7 +49946,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
48972
49946
  return newTree || void 0;
48973
49947
  } finally {
48974
49948
  try {
48975
- fs27.rmSync(tmpIndex, { force: true });
49949
+ fs29.rmSync(tmpIndex, { force: true });
48976
49950
  } catch {
48977
49951
  }
48978
49952
  }
@@ -49031,7 +50005,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
49031
50005
  if (!contentTree) return void 0;
49032
50006
  const updates = branchGitlinks.map((entry) => `160000 commit ${entry.branchCommit} ${entry.path}`).join("\n");
49033
50007
  if (!updates) return contentTree;
49034
- const tmpIndex = pathJoin(resolveGitDir(repoRoot), `adhdev-refine-ff-${baseHead.slice(0, 12)}-${branchHead.slice(0, 12)}.index`);
50008
+ const tmpIndex = pathJoin2(resolveGitDir(repoRoot), `adhdev-refine-ff-${baseHead.slice(0, 12)}-${branchHead.slice(0, 12)}.index`);
49035
50009
  const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
49036
50010
  try {
49037
50011
  execFileSync6("git", ["read-tree", contentTree], { cwd: repoRoot, env, stdio: "ignore" });
@@ -49047,7 +50021,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
49047
50021
  return newTree || void 0;
49048
50022
  } finally {
49049
50023
  try {
49050
- fs27.rmSync(tmpIndex, { force: true });
50024
+ fs29.rmSync(tmpIndex, { force: true });
49051
50025
  } catch {
49052
50026
  }
49053
50027
  }
@@ -49153,7 +50127,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
49153
50127
  return { stdout: String(stdout || ""), stderr: String(stderr || ""), refspec };
49154
50128
  };
49155
50129
  const importCommitFromWorktreeSubmodule = async (submodulePath, worktreeSubmodulePath, commit) => {
49156
- if (!fs27.existsSync(worktreeSubmodulePath)) return false;
50130
+ if (!fs29.existsSync(worktreeSubmodulePath)) return false;
49157
50131
  try {
49158
50132
  await runGit3(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
49159
50133
  } catch {
@@ -49176,7 +50150,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
49176
50150
  reachable: false
49177
50151
  };
49178
50152
  try {
49179
- if (!fs27.existsSync(submodulePath)) {
50153
+ if (!fs29.existsSync(submodulePath)) {
49180
50154
  entry.error = `Submodule checkout missing at ${gitlink.path}`;
49181
50155
  entry.publishRequired = true;
49182
50156
  if (options.allowAutoPublishSubmoduleMainCommits === true) {
@@ -49413,9 +50387,9 @@ async function runMeshRefineValidationGate(mesh, workspace, opts) {
49413
50387
  return ["npm", "pnpm", "yarn", "bun"].includes(command) && candidate.args.some((arg) => arg === "run" || arg === "test" || arg === "exec");
49414
50388
  };
49415
50389
  const dependenciesLikelyMissing = (cwd) => {
49416
- if (!fs27.existsSync(pathJoin(cwd, "package.json"))) return false;
49417
- if (fs27.existsSync(pathJoin(cwd, "node_modules"))) return false;
49418
- return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs27.existsSync(pathJoin(cwd, lock)));
50390
+ if (!fs29.existsSync(pathJoin2(cwd, "package.json"))) return false;
50391
+ if (fs29.existsSync(pathJoin2(cwd, "node_modules"))) return false;
50392
+ return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs29.existsSync(pathJoin2(cwd, lock)));
49419
50393
  };
49420
50394
  if (runLegacyBootstrapCommands) {
49421
50395
  summary.bootstrap = { stage: "legacy" };
@@ -49520,14 +50494,14 @@ function serializeMeshCoordinatorMcpConfig(config, format) {
49520
50494
  }
49521
50495
  function resolveHermesUserHome() {
49522
50496
  const explicitHome = process.env.HERMES_HOME?.trim();
49523
- return explicitHome || pathJoin(homedir26(), ".hermes");
50497
+ return explicitHome || pathJoin2(homedir26(), ".hermes");
49524
50498
  }
49525
50499
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
49526
50500
  const sourceHome = resolveHermesUserHome();
49527
- const sourceConfigPath = pathJoin(sourceHome, "config.yaml");
49528
- if (!fs27.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
50501
+ const sourceConfigPath = pathJoin2(sourceHome, "config.yaml");
50502
+ if (!fs29.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
49529
50503
  if (pathResolve2(sourceConfigPath) === pathResolve2(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
49530
- const parsed = parseMeshCoordinatorMcpConfig(fs27.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
50504
+ const parsed = parseMeshCoordinatorMcpConfig(fs29.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
49531
50505
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
49532
50506
  return { config: baseConfig, sourceHome, sourceConfigPath };
49533
50507
  }
@@ -49562,11 +50536,11 @@ function stripHermesCoordinatorTempModelProviderOverrides(config) {
49562
50536
  function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
49563
50537
  if (pathResolve2(sourceHome) === pathResolve2(targetHome)) return;
49564
50538
  for (const fileName of [".env", "auth.json"]) {
49565
- const sourcePath = pathJoin(sourceHome, fileName);
49566
- const targetPath = pathJoin(targetHome, fileName);
49567
- if (!fs27.existsSync(sourcePath)) continue;
50539
+ const sourcePath = pathJoin2(sourceHome, fileName);
50540
+ const targetPath = pathJoin2(targetHome, fileName);
50541
+ if (!fs29.existsSync(sourcePath)) continue;
49568
50542
  try {
49569
- fs27.copyFileSync(sourcePath, targetPath);
50543
+ fs29.copyFileSync(sourcePath, targetPath);
49570
50544
  } catch (error) {
49571
50545
  LOG.warn("MeshCoordinator", `Could not copy Hermes ${fileName} into isolated coordinator home: ${error?.message || error}`);
49572
50546
  }
@@ -49958,6 +50932,29 @@ var DaemonCommandRouter = class {
49958
50932
  };
49959
50933
  return ctx;
49960
50934
  }
50935
+ /**
50936
+ * Build the HighFamilyContext handed to RF-ROUTER HIGH family handlers. Binds
50937
+ * the router-private collaborators those handlers need (mesh resolution, the
50938
+ * aggregate-status memory cache + its bound read/write helpers, the
50939
+ * running-refine-job table, inline-mesh + git-probe caches, and the router's
50940
+ * own `execute` for the get_mesh_review_inbox mesh_status re-entry). HIGH
50941
+ * handlers reach more router-owned state than MED, but the binding shape is
50942
+ * the same: bound methods + direct field references, none reachable from
50943
+ * `deps`.
50944
+ */
50945
+ buildHighFamilyContext() {
50946
+ return {
50947
+ deps: this.deps,
50948
+ getMeshForCommand: this.getMeshForCommand.bind(this),
50949
+ getCachedAggregateMeshStatus: this.getCachedAggregateMeshStatus.bind(this),
50950
+ rememberAggregateMeshStatus: this.rememberAggregateMeshStatus.bind(this),
50951
+ execute: this.execute.bind(this),
50952
+ aggregateMeshStatusCache: this.aggregateMeshStatusCache,
50953
+ runningRefineJobs: this.runningRefineJobs,
50954
+ inlineMeshCache: this.inlineMeshCache,
50955
+ meshGitProbeCache: this.meshGitProbeCache
50956
+ };
50957
+ }
49961
50958
  async requireMeshHostMutationOwner(meshId, inlineMesh, operation) {
49962
50959
  const meshRecord = await this.getMeshForCommand(meshId, inlineMesh, { preferInline: true });
49963
50960
  const mesh = meshRecord?.mesh;
@@ -50015,7 +51012,7 @@ var DaemonCommandRouter = class {
50015
51012
  const nodeId = readInlineMeshNodeId(node);
50016
51013
  if (!nodeId || !tombstones.has(nodeId)) return true;
50017
51014
  const workspace = readStringValue(node?.workspace);
50018
- if (workspace && fs27.existsSync(workspace)) {
51015
+ if (workspace && fs29.existsSync(workspace)) {
50019
51016
  tombstones.delete(nodeId);
50020
51017
  return true;
50021
51018
  }
@@ -50050,14 +51047,14 @@ var DaemonCommandRouter = class {
50050
51047
  * to give handles time to release, and reports whether residue remains.
50051
51048
  */
50052
51049
  async bestEffortRemoveWorktreeDir(dir) {
50053
- if (!dir || !fs27.existsSync(dir)) return { removed: true, residue: false };
51050
+ if (!dir || !fs29.existsSync(dir)) return { removed: true, residue: false };
50054
51051
  const sleep3 = (ms) => new Promise((resolve24) => setTimeout(resolve24, ms));
50055
51052
  const ABSORB = /* @__PURE__ */ new Set(["EINVAL", "EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);
50056
51053
  let lastErr;
50057
51054
  for (let attempt = 0; attempt < 4; attempt++) {
50058
51055
  try {
50059
- fs27.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
50060
- if (!fs27.existsSync(dir)) return { removed: true, residue: false };
51056
+ fs29.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
51057
+ if (!fs29.existsSync(dir)) return { removed: true, residue: false };
50061
51058
  lastErr = new Error("directory still present after rmSync");
50062
51059
  } catch (e) {
50063
51060
  lastErr = e;
@@ -50068,7 +51065,7 @@ var DaemonCommandRouter = class {
50068
51065
  }
50069
51066
  await sleep3(150 * (attempt + 1));
50070
51067
  }
50071
- return fs27.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
51068
+ return fs29.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
50072
51069
  }
50073
51070
  async cleanupLocalWorktreeNode(args) {
50074
51071
  const workspace = typeof args.node?.workspace === "string" ? args.node.workspace.trim() : "";
@@ -50080,13 +51077,13 @@ var DaemonCommandRouter = class {
50080
51077
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains."
50081
51078
  };
50082
51079
  }
50083
- const worktreeExists = fs27.existsSync(workspace);
51080
+ const worktreeExists = fs29.existsSync(workspace);
50084
51081
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
50085
51082
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
50086
51083
  if (!worktreeExists) {
50087
51084
  return { success: true, skipped: true, removedPath: workspace, repoRoot: repoRoot || void 0, reason: "worktree_path_missing" };
50088
51085
  }
50089
- if (!repoRoot || !fs27.existsSync(repoRoot)) {
51086
+ if (!repoRoot || !fs29.existsSync(repoRoot)) {
50090
51087
  return {
50091
51088
  success: false,
50092
51089
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -50106,7 +51103,7 @@ var DaemonCommandRouter = class {
50106
51103
  const normalizePath = (value) => {
50107
51104
  const resolved = pathResolve2(value);
50108
51105
  try {
50109
- return fs27.realpathSync(resolved);
51106
+ return fs29.realpathSync(resolved);
50110
51107
  } catch {
50111
51108
  return resolved;
50112
51109
  }
@@ -50701,196 +51698,242 @@ var DaemonCommandRouter = class {
50701
51698
  LOG.warn("Mesh", `[Refinery] resumePendingRefineJobsOnStartup failed: ${e?.message || e}`);
50702
51699
  }
50703
51700
  }
51701
+ /**
51702
+ * Synchronous refinery for a single worktree node — the gate pipeline that
51703
+ * validates, preflights (patch-equivalence / submodule-reachability /
51704
+ * no-op), merges, aligns submodules, cleans up the worktree node and
51705
+ * (optionally) pushes. The body is a flat sequence of stage methods; each
51706
+ * stage either returns a terminal CommandRouterResult (gate failure or a
51707
+ * successful already-merged short-circuit) or `continue` with the extended
51708
+ * context. Behavior — stage order, every early-exit, and every result shape —
51709
+ * is identical to the previous single inlined body.
51710
+ */
50704
51711
  async executeMeshRefineNodeSynchronously(meshId, nodeId, args) {
50705
51712
  const refineStages = [];
50706
51713
  try {
50707
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
50708
- const mesh = meshRecord?.mesh;
50709
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
50710
- if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh`, refineStages };
50711
- if (!node.isLocalWorktree || !node.workspace) {
50712
- return { success: false, error: `Refinery requires a local worktree node`, refineStages };
50713
- }
50714
- const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => meshNodeIdMatches(n, node.clonedFromNodeId)) : mesh?.nodes.find((n) => !n.isLocalWorktree);
50715
- const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
50716
- if (!repoRoot) return { success: false, error: "Source node repoRoot not found", refineStages };
50717
- const { execFile: execFile5 } = await import("child_process");
50718
- const { promisify: promisify8 } = await import("util");
50719
- const execFileAsync4 = promisify8(execFile5);
50720
- const resolveStarted = Date.now();
50721
- const { stdout: branchStdout } = await execFileAsync4("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8" });
50722
- const branch = branchStdout.trim();
50723
- if (!branch) return { success: false, error: "Could not determine branch of the worktree node", refineStages };
50724
- const { stdout: baseBranchStdout } = await execFileAsync4("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8" });
50725
- const baseBranch = baseBranchStdout.trim();
50726
- let fetchWarning;
50727
- try {
50728
- await execFileAsync4("git", ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8" });
50729
- } catch (e) {
50730
- fetchWarning = `git fetch origin ${baseBranch} failed (proceeding with local HEAD): ${e?.message}`;
50731
- }
50732
- let baseHeadRaw;
50733
- try {
50734
- const { stdout } = await execFileAsync4("git", ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8" });
50735
- baseHeadRaw = stdout.trim();
50736
- } catch {
50737
- const { stdout: localHead } = await execFileAsync4("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" });
50738
- baseHeadRaw = localHead.trim();
50739
- }
50740
- const { stdout: branchHeadStdout } = await execFileAsync4("git", ["rev-parse", branch], { cwd: node.workspace, encoding: "utf8" });
50741
- const baseHead = baseHeadRaw;
50742
- let branchHead = branchHeadStdout.trim();
50743
- recordMeshRefineStage(refineStages, "resolve_refs", "passed", resolveStarted, { branch, baseBranch, baseHead, branchHead, ...fetchWarning ? { fetchWarning } : {} });
50744
- const validationStarted = Date.now();
50745
- const validationSummary = await runMeshRefineValidationGate(mesh, node.workspace, {
50746
- // M2-2: consume the node's persisted bootstrap state; persist re-runs.
50747
- persistedBootstrapState: node.worktreeBootstrap,
50748
- onBootstrapStateChange: (state) => {
50749
- node.worktreeBootstrap = state;
50750
- void Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports)).then(({ updateNode: updateNode2 }) => updateNode2(mesh.id, node.id, { worktreeBootstrap: state })).catch(() => {
50751
- });
50752
- }
50753
- });
50754
- recordMeshRefineStage(
51714
+ const resolved = await this.refineResolveRefsStage(meshId, nodeId, args, refineStages);
51715
+ if (resolved.kind === "terminal") return resolved.result;
51716
+ const ctx = resolved.ctx;
51717
+ const validation = await this.refineValidationStage(ctx);
51718
+ if (validation.kind === "terminal") return validation.result;
51719
+ const patchEquivalence = await this.refinePatchEquivalenceStage(ctx);
51720
+ if (patchEquivalence.kind === "terminal") return patchEquivalence.result;
51721
+ const submoduleReachability = await this.refineSubmoduleReachabilityStage(ctx);
51722
+ if (submoduleReachability.kind === "terminal") return submoduleReachability.result;
51723
+ const effectiveDiff = await this.refineEffectiveDiffStage(ctx);
51724
+ if (effectiveDiff.kind === "terminal") return effectiveDiff.result;
51725
+ const merge = await this.refineMergeAndFinalizeStage(ctx);
51726
+ return merge.result;
51727
+ } catch (e) {
51728
+ return { success: false, error: e.message, refineStages };
51729
+ }
51730
+ }
51731
+ /**
51732
+ * resolve_refs stage: resolve the mesh / worktree node / source node /
51733
+ * repoRoot, then the worktree branch, base branch, fetched base head and
51734
+ * branch head. Seeds the RefineContext consumed by every later stage.
51735
+ */
51736
+ async refineResolveRefsStage(meshId, nodeId, args, refineStages) {
51737
+ const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51738
+ const mesh = meshRecord?.mesh;
51739
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51740
+ if (!node) return { kind: "terminal", result: { success: false, error: `Node '${nodeId}' not found in mesh`, refineStages } };
51741
+ if (!node.isLocalWorktree || !node.workspace) {
51742
+ return { kind: "terminal", result: { success: false, error: `Refinery requires a local worktree node`, refineStages } };
51743
+ }
51744
+ const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => meshNodeIdMatches(n, node.clonedFromNodeId)) : mesh?.nodes.find((n) => !n.isLocalWorktree);
51745
+ const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
51746
+ if (!repoRoot) return { kind: "terminal", result: { success: false, error: "Source node repoRoot not found", refineStages } };
51747
+ const { execFile: execFile5 } = await import("child_process");
51748
+ const { promisify: promisify8 } = await import("util");
51749
+ const execFileAsync4 = promisify8(execFile5);
51750
+ const resolveStarted = Date.now();
51751
+ const { stdout: branchStdout } = await execFileAsync4("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8" });
51752
+ const branch = branchStdout.trim();
51753
+ if (!branch) return { kind: "terminal", result: { success: false, error: "Could not determine branch of the worktree node", refineStages } };
51754
+ const { stdout: baseBranchStdout } = await execFileAsync4("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8" });
51755
+ const baseBranch = baseBranchStdout.trim();
51756
+ let fetchWarning;
51757
+ try {
51758
+ await execFileAsync4("git", ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8" });
51759
+ } catch (e) {
51760
+ fetchWarning = `git fetch origin ${baseBranch} failed (proceeding with local HEAD): ${e?.message}`;
51761
+ }
51762
+ let baseHeadRaw;
51763
+ try {
51764
+ const { stdout } = await execFileAsync4("git", ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8" });
51765
+ baseHeadRaw = stdout.trim();
51766
+ } catch {
51767
+ const { stdout: localHead } = await execFileAsync4("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" });
51768
+ baseHeadRaw = localHead.trim();
51769
+ }
51770
+ const { stdout: branchHeadStdout } = await execFileAsync4("git", ["rev-parse", branch], { cwd: node.workspace, encoding: "utf8" });
51771
+ const baseHead = baseHeadRaw;
51772
+ const branchHead = branchHeadStdout.trim();
51773
+ recordMeshRefineStage(refineStages, "resolve_refs", "passed", resolveStarted, { branch, baseBranch, baseHead, branchHead, ...fetchWarning ? { fetchWarning } : {} });
51774
+ return {
51775
+ kind: "continue",
51776
+ ctx: {
51777
+ meshId,
51778
+ nodeId,
51779
+ args,
50755
51780
  refineStages,
50756
- "validation",
50757
- validationSummary.status === "passed" ? "passed" : validationSummary.status === "failed" ? "failed" : "skipped",
50758
- validationStarted,
50759
- { validationStatus: validationSummary.status, commandsRun: validationSummary.commandsRun.length }
50760
- );
50761
- if (validationSummary.status === "failed") {
50762
- const firstFailedCmd = Array.isArray(validationSummary.commandsRun) ? validationSummary.commandsRun.find((c) => c.success === false) : void 0;
50763
- const buildValidationFailedError = () => {
50764
- const base = validationSummary.failureCode === "missing_dependencies" ? "Refinery validation dependencies are missing; merge/refine was not attempted. Configure validation.bootstrapCommands if Refinery should bootstrap dependencies before validation." : validationSummary.failureCode === "dependency_bootstrap_failed" ? "Refinery dependency/bootstrap command failed; merge/refine was not attempted." : validationSummary.failureCode === "spawn_resolution_failed" ? validationSummary.spawnResolutionError || "Refinery validation command could not be spawned (executable not found); merge/refine was not attempted." : "Refinery validation gate failed; merge/refine was not attempted.";
50765
- if (!firstFailedCmd) return base;
50766
- const cmdName = typeof firstFailedCmd.displayCommand === "string" ? firstFailedCmd.displayCommand : typeof firstFailedCmd.command === "string" ? [firstFailedCmd.command, ...Array.isArray(firstFailedCmd.args) ? firstFailedCmd.args : []].join(" ").trim() : typeof firstFailedCmd.cmd === "string" ? firstFailedCmd.cmd : "";
50767
- const rawOutput = [firstFailedCmd.stdout, firstFailedCmd.stderr, firstFailedCmd.output].filter((s2) => typeof s2 === "string" && s2.length > 0).join("\n");
50768
- const tail = rawOutput.length > 800 ? rawOutput.slice(-800) : rawOutput;
50769
- return [
50770
- base,
50771
- cmdName ? `First failing command: ${cmdName}` : "",
50772
- tail ? `Output (tail):
51781
+ execFileAsync: execFileAsync4,
51782
+ mesh,
51783
+ node,
51784
+ sourceNode,
51785
+ repoRoot,
51786
+ branch,
51787
+ baseBranch,
51788
+ baseHead,
51789
+ branchHead,
51790
+ validationSummary: void 0,
51791
+ patchEquivalence: void 0,
51792
+ submoduleReachability: void 0
51793
+ }
51794
+ };
51795
+ }
51796
+ /**
51797
+ * validation stage: run the refinery validation gate (typecheck / test /
51798
+ * lint / build per node config) and block on failure or when no allowlisted
51799
+ * command was available. On pass, stores the summary on the context.
51800
+ */
51801
+ async refineValidationStage(ctx) {
51802
+ const { mesh, node, branch, baseBranch, refineStages } = ctx;
51803
+ const validationStarted = Date.now();
51804
+ const validationSummary = await runMeshRefineValidationGate(mesh, node.workspace, {
51805
+ // M2-2: consume the node's persisted bootstrap state; persist re-runs.
51806
+ persistedBootstrapState: node.worktreeBootstrap,
51807
+ onBootstrapStateChange: (state) => {
51808
+ node.worktreeBootstrap = state;
51809
+ void Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports)).then(({ updateNode: updateNode2 }) => updateNode2(mesh.id, node.id, { worktreeBootstrap: state })).catch(() => {
51810
+ });
51811
+ }
51812
+ });
51813
+ ctx.validationSummary = validationSummary;
51814
+ recordMeshRefineStage(
51815
+ refineStages,
51816
+ "validation",
51817
+ validationSummary.status === "passed" ? "passed" : validationSummary.status === "failed" ? "failed" : "skipped",
51818
+ validationStarted,
51819
+ { validationStatus: validationSummary.status, commandsRun: validationSummary.commandsRun.length }
51820
+ );
51821
+ if (validationSummary.status === "failed") {
51822
+ const firstFailedCmd = Array.isArray(validationSummary.commandsRun) ? validationSummary.commandsRun.find((c) => c.success === false) : void 0;
51823
+ const buildValidationFailedError = () => {
51824
+ const base = validationSummary.failureCode === "missing_dependencies" ? "Refinery validation dependencies are missing; merge/refine was not attempted. Configure validation.bootstrapCommands if Refinery should bootstrap dependencies before validation." : validationSummary.failureCode === "dependency_bootstrap_failed" ? "Refinery dependency/bootstrap command failed; merge/refine was not attempted." : validationSummary.failureCode === "spawn_resolution_failed" ? validationSummary.spawnResolutionError || "Refinery validation command could not be spawned (executable not found); merge/refine was not attempted." : "Refinery validation gate failed; merge/refine was not attempted.";
51825
+ if (!firstFailedCmd) return base;
51826
+ const cmdName = typeof firstFailedCmd.displayCommand === "string" ? firstFailedCmd.displayCommand : typeof firstFailedCmd.command === "string" ? [firstFailedCmd.command, ...Array.isArray(firstFailedCmd.args) ? firstFailedCmd.args : []].join(" ").trim() : typeof firstFailedCmd.cmd === "string" ? firstFailedCmd.cmd : "";
51827
+ const rawOutput = [firstFailedCmd.stdout, firstFailedCmd.stderr, firstFailedCmd.output].filter((s2) => typeof s2 === "string" && s2.length > 0).join("\n");
51828
+ const tail = rawOutput.length > 800 ? rawOutput.slice(-800) : rawOutput;
51829
+ return [
51830
+ base,
51831
+ cmdName ? `First failing command: ${cmdName}` : "",
51832
+ tail ? `Output (tail):
50773
51833
  ${tail}` : ""
50774
- ].filter(Boolean).join("\n");
50775
- };
50776
- return {
50777
- success: false,
50778
- code: validationSummary.failureCode || "validation_failed",
50779
- convergenceStatus: "blocked_review",
50780
- error: buildValidationFailedError(),
51834
+ ].filter(Boolean).join("\n");
51835
+ };
51836
+ return { kind: "terminal", result: {
51837
+ success: false,
51838
+ code: validationSummary.failureCode || "validation_failed",
51839
+ convergenceStatus: "blocked_review",
51840
+ error: buildValidationFailedError(),
51841
+ branch,
51842
+ into: baseBranch,
51843
+ validationSummary,
51844
+ refineStages,
51845
+ finalBranchConvergenceState: {
50781
51846
  branch,
50782
- into: baseBranch,
50783
- validationSummary,
50784
- refineStages,
50785
- finalBranchConvergenceState: {
50786
- branch,
50787
- baseBranch,
50788
- merged: false,
50789
- removed: false,
50790
- validation: "failed",
50791
- status: "blocked_review"
50792
- }
50793
- };
50794
- }
50795
- if (validationSummary.status === "skipped") {
50796
- return {
50797
- success: false,
50798
- code: "validation_unavailable",
50799
- convergenceStatus: "blocked_review",
50800
- error: "Refinery validation gate is required but no allowlisted validation command was available; merge/refine was not attempted.",
51847
+ baseBranch,
51848
+ merged: false,
51849
+ removed: false,
51850
+ validation: "failed",
51851
+ status: "blocked_review"
51852
+ }
51853
+ } };
51854
+ }
51855
+ if (validationSummary.status === "skipped") {
51856
+ return { kind: "terminal", result: {
51857
+ success: false,
51858
+ code: "validation_unavailable",
51859
+ convergenceStatus: "blocked_review",
51860
+ error: "Refinery validation gate is required but no allowlisted validation command was available; merge/refine was not attempted.",
51861
+ branch,
51862
+ into: baseBranch,
51863
+ validationSummary,
51864
+ refineStages,
51865
+ finalBranchConvergenceState: {
50801
51866
  branch,
50802
- into: baseBranch,
50803
- validationSummary,
50804
- refineStages,
50805
- finalBranchConvergenceState: {
50806
- branch,
50807
- baseBranch,
50808
- merged: false,
50809
- removed: false,
50810
- validation: "unavailable",
50811
- status: "blocked_review"
50812
- }
50813
- };
51867
+ baseBranch,
51868
+ merged: false,
51869
+ removed: false,
51870
+ validation: "unavailable",
51871
+ status: "blocked_review"
51872
+ }
51873
+ } };
51874
+ }
51875
+ return { kind: "continue", ctx };
51876
+ }
51877
+ /**
51878
+ * patch_equivalence stage: preflight that the worktree branch's cumulative
51879
+ * patch is equivalent to base+branch. On a "behind base" branch, auto-rebase
51880
+ * once and re-check; on an empty merge-tree with real branch changes, treat as
51881
+ * already-merged-via-another-path and short-circuit to cleanup. Mutates the
51882
+ * context's branchHead (after rebase) and patchEquivalence (rebased gate).
51883
+ */
51884
+ async refinePatchEquivalenceStage(ctx) {
51885
+ const { meshId, nodeId, args, repoRoot, baseHead, node, branch, baseBranch, validationSummary, refineStages, execFileAsync: execFileAsync4 } = ctx;
51886
+ let branchHead = ctx.branchHead;
51887
+ const patchEquivalenceStarted = Date.now();
51888
+ let patchEquivalence = await runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead);
51889
+ recordMeshRefineStage(refineStages, "patch_equivalence", patchEquivalence.status, patchEquivalenceStarted, {
51890
+ equivalent: patchEquivalence.equivalent,
51891
+ expectedPatchId: patchEquivalence.expectedPatchId,
51892
+ actualPatchId: patchEquivalence.actualPatchId,
51893
+ error: patchEquivalence.error,
51894
+ actionableHint: patchEquivalence.actionableHint
51895
+ });
51896
+ if (!patchEquivalence.equivalent) {
51897
+ let didAutoRebase = false;
51898
+ let isBehindBase = false;
51899
+ try {
51900
+ execFileSync6("git", ["merge-base", "--is-ancestor", branchHead, baseHead], {
51901
+ cwd: node.workspace,
51902
+ stdio: "ignore"
51903
+ });
51904
+ isBehindBase = true;
51905
+ } catch {
50814
51906
  }
50815
- const patchEquivalenceStarted = Date.now();
50816
- let patchEquivalence = await runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead);
50817
- recordMeshRefineStage(refineStages, "patch_equivalence", patchEquivalence.status, patchEquivalenceStarted, {
50818
- equivalent: patchEquivalence.equivalent,
50819
- expectedPatchId: patchEquivalence.expectedPatchId,
50820
- actualPatchId: patchEquivalence.actualPatchId,
50821
- error: patchEquivalence.error,
50822
- actionableHint: patchEquivalence.actionableHint
50823
- });
50824
- if (!patchEquivalence.equivalent) {
50825
- let didAutoRebase = false;
50826
- let isBehindBase = false;
51907
+ if (isBehindBase) {
51908
+ const autoRebaseStarted = Date.now();
50827
51909
  try {
50828
- execFileSync6("git", ["merge-base", "--is-ancestor", branchHead, baseHead], {
51910
+ execFileSync6("git", ["rebase", baseHead], {
50829
51911
  cwd: node.workspace,
50830
- stdio: "ignore"
51912
+ stdio: ["ignore", "pipe", "pipe"]
50831
51913
  });
50832
- isBehindBase = true;
50833
- } catch {
50834
- }
50835
- if (isBehindBase) {
50836
- const autoRebaseStarted = Date.now();
50837
- try {
50838
- execFileSync6("git", ["rebase", baseHead], {
50839
- cwd: node.workspace,
50840
- stdio: ["ignore", "pipe", "pipe"]
50841
- });
50842
- const { stdout: rebasedHeadStdout } = await execFileAsync4("git", ["rev-parse", "HEAD"], { cwd: node.workspace, encoding: "utf8" });
50843
- branchHead = rebasedHeadStdout.trim();
50844
- const rebasedPatchEquivalence = await runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead);
50845
- recordMeshRefineStage(refineStages, "patch_equivalence_after_auto_rebase", rebasedPatchEquivalence.status, autoRebaseStarted, {
50846
- equivalent: rebasedPatchEquivalence.equivalent,
50847
- expectedPatchId: rebasedPatchEquivalence.expectedPatchId,
50848
- actualPatchId: rebasedPatchEquivalence.actualPatchId,
50849
- error: rebasedPatchEquivalence.error,
50850
- rebasedBranchHead: branchHead
50851
- });
50852
- if (rebasedPatchEquivalence.equivalent) {
50853
- patchEquivalence = rebasedPatchEquivalence;
50854
- didAutoRebase = true;
50855
- } else {
50856
- return {
50857
- success: false,
50858
- code: "needs_rebase",
50859
- convergenceStatus: "blocked_review",
50860
- error: "Branch was rebased onto base but patch equivalence still failed; manual intervention required.",
50861
- branch,
50862
- into: baseBranch,
50863
- validationSummary,
50864
- patchEquivalence: rebasedPatchEquivalence,
50865
- refineStages,
50866
- finalBranchConvergenceState: {
50867
- branch,
50868
- baseBranch,
50869
- merged: false,
50870
- removed: false,
50871
- validation: "passed",
50872
- patchEquivalence: "failed",
50873
- status: "blocked_review"
50874
- }
50875
- };
50876
- }
50877
- } catch (rebaseErr) {
50878
- try {
50879
- execFileSync6("git", ["rebase", "--abort"], { cwd: node.workspace, stdio: "ignore" });
50880
- } catch {
50881
- }
50882
- recordMeshRefineStage(refineStages, "patch_equivalence_after_auto_rebase", "failed", autoRebaseStarted, {
50883
- error: rebaseErr?.message || String(rebaseErr)
50884
- });
50885
- return {
51914
+ const { stdout: rebasedHeadStdout } = await execFileAsync4("git", ["rev-parse", "HEAD"], { cwd: node.workspace, encoding: "utf8" });
51915
+ branchHead = rebasedHeadStdout.trim();
51916
+ const rebasedPatchEquivalence = await runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead);
51917
+ recordMeshRefineStage(refineStages, "patch_equivalence_after_auto_rebase", rebasedPatchEquivalence.status, autoRebaseStarted, {
51918
+ equivalent: rebasedPatchEquivalence.equivalent,
51919
+ expectedPatchId: rebasedPatchEquivalence.expectedPatchId,
51920
+ actualPatchId: rebasedPatchEquivalence.actualPatchId,
51921
+ error: rebasedPatchEquivalence.error,
51922
+ rebasedBranchHead: branchHead
51923
+ });
51924
+ if (rebasedPatchEquivalence.equivalent) {
51925
+ patchEquivalence = rebasedPatchEquivalence;
51926
+ didAutoRebase = true;
51927
+ } else {
51928
+ return { kind: "terminal", result: {
50886
51929
  success: false,
50887
- code: "needs_rebase_with_conflicts",
51930
+ code: "needs_rebase",
50888
51931
  convergenceStatus: "blocked_review",
50889
- error: "Branch is behind base and auto-rebase failed due to conflicts; resolve conflicts manually and retry.",
51932
+ error: "Branch was rebased onto base but patch equivalence still failed; manual intervention required.",
50890
51933
  branch,
50891
51934
  into: baseBranch,
50892
51935
  validationSummary,
50893
- patchEquivalence,
51936
+ patchEquivalence: rebasedPatchEquivalence,
50894
51937
  refineStages,
50895
51938
  finalBranchConvergenceState: {
50896
51939
  branch,
@@ -50901,16 +51944,21 @@ ${tail}` : ""
50901
51944
  patchEquivalence: "failed",
50902
51945
  status: "blocked_review"
50903
51946
  }
50904
- };
51947
+ } };
50905
51948
  }
50906
- }
50907
- const alreadyMergedViaOtherPath = !patchEquivalence.actualPatchId && !!patchEquivalence.expectedPatchId;
50908
- if (!didAutoRebase && !alreadyMergedViaOtherPath) {
50909
- return {
51949
+ } catch (rebaseErr) {
51950
+ try {
51951
+ execFileSync6("git", ["rebase", "--abort"], { cwd: node.workspace, stdio: "ignore" });
51952
+ } catch {
51953
+ }
51954
+ recordMeshRefineStage(refineStages, "patch_equivalence_after_auto_rebase", "failed", autoRebaseStarted, {
51955
+ error: rebaseErr?.message || String(rebaseErr)
51956
+ });
51957
+ return { kind: "terminal", result: {
50910
51958
  success: false,
50911
- code: "patch_equivalence_failed",
51959
+ code: "needs_rebase_with_conflicts",
50912
51960
  convergenceStatus: "blocked_review",
50913
- error: "Refinery patch-equivalence preflight failed; merge/refine was not attempted.",
51961
+ error: "Branch is behind base and auto-rebase failed due to conflicts; resolve conflicts manually and retry.",
50914
51962
  branch,
50915
51963
  into: baseBranch,
50916
51964
  validationSummary,
@@ -50925,188 +51973,20 @@ ${tail}` : ""
50925
51973
  patchEquivalence: "failed",
50926
51974
  status: "blocked_review"
50927
51975
  }
50928
- };
50929
- }
50930
- if (!didAutoRebase && alreadyMergedViaOtherPath) {
50931
- recordMeshRefineStage(refineStages, "merge", "skipped", Date.now(), {
50932
- reason: "already_merged_via_other_path",
50933
- note: "actualPatchId is empty; branch content is already present in base via a different commit path"
50934
- });
50935
- const cleanupStarted2 = Date.now();
50936
- const removeResult2 = await this.execute("remove_mesh_node", {
50937
- meshId,
50938
- nodeId,
50939
- sessionCleanupMode: "preserve",
50940
- inlineMesh: args?.inlineMesh
50941
- });
50942
- recordMeshRefineStage(refineStages, "cleanup", removeResult2?.success === false ? "failed" : "passed", cleanupStarted2, {
50943
- removed: removeResult2?.removed,
50944
- code: removeResult2?.code,
50945
- error: removeResult2?.error
50946
- });
50947
- try {
50948
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
50949
- appendLedgerEntry2(meshId, {
50950
- kind: "node_removed",
50951
- nodeId,
50952
- payload: { alreadyMergedViaOtherPath: true, branch, into: baseBranch, validationSummary, patchEquivalence }
50953
- });
50954
- } catch {
50955
- }
50956
- return {
50957
- success: removeResult2?.success !== false,
50958
- code: "already_merged",
50959
- merged: false,
50960
- alreadyMergedViaOtherPath: true,
50961
- branch,
50962
- into: baseBranch,
50963
- removeResult: removeResult2,
50964
- validationSummary,
50965
- patchEquivalence,
50966
- refineStages,
50967
- finalBranchConvergenceState: {
50968
- branch: baseBranch,
50969
- mergedBranch: branch,
50970
- baseBranch,
50971
- merged: false,
50972
- alreadyMergedViaOtherPath: true,
50973
- removed: removeResult2?.success !== false,
50974
- validation: "passed",
50975
- patchEquivalence: "already_merged",
50976
- status: removeResult2?.success === false ? "merged_cleanup_failed" : "merged_to_main"
50977
- }
50978
- };
51976
+ } };
50979
51977
  }
50980
51978
  }
50981
- const submoduleReachabilityStarted = Date.now();
50982
- const autoPublishSubmoduleMainCommits = resolveRefineryAutoPublishSubmoduleMainCommits(mesh, node.workspace);
50983
- const submoduleReachability = await runMeshRefineSubmoduleReachabilityGate(repoRoot, patchEquivalence.mergedTree || branchHead, {
50984
- allowAutoPublishSubmoduleMainCommits: autoPublishSubmoduleMainCommits.enabled,
50985
- autoPublishPolicySource: autoPublishSubmoduleMainCommits.source,
50986
- worktreeRoot: node.workspace
50987
- });
50988
- recordMeshRefineStage(refineStages, "submodule_reachability", submoduleReachability.status, submoduleReachabilityStarted, {
50989
- checked: submoduleReachability.checked,
50990
- autoPublishAllowed: submoduleReachability.autoPublishAllowed,
50991
- autoPublishPolicySource: submoduleReachability.autoPublishPolicySource,
50992
- autoPublished: submoduleReachability.entries.filter((entry) => entry.autoPublishAttempted).map((entry) => ({
50993
- path: entry.path,
50994
- commit: entry.commit,
50995
- remote: entry.remote,
50996
- remoteUrl: entry.remoteUrl,
50997
- remoteMainBranch: entry.remoteMainBranch,
50998
- refspec: entry.autoPublishRefspec,
50999
- succeeded: entry.autoPublishSucceeded,
51000
- verified: entry.autoPublishVerified,
51001
- remoteMainReachable: entry.remoteMainReachable,
51002
- error: entry.error
51003
- })),
51004
- autoPublishSkipped: submoduleReachability.entries.filter((entry) => entry.autoPublishAllowed === true && entry.autoPublishAttempted !== true).map((entry) => ({
51005
- path: entry.path,
51006
- commit: entry.commit,
51007
- remote: entry.remote,
51008
- remoteUrl: entry.remoteUrl,
51009
- remoteMainBranch: entry.remoteMainBranch,
51010
- reason: entry.autoPublishSkippedReason || entry.error || "auto-publish was allowed but no publish attempt was possible"
51011
- })),
51012
- unreachable: submoduleReachability.unreachable.map((entry) => ({
51013
- path: entry.path,
51014
- commit: entry.commit,
51015
- publishRequired: entry.publishRequired === true,
51016
- autoPublishAllowed: entry.autoPublishAllowed,
51017
- autoPublishAttempted: entry.autoPublishAttempted,
51018
- autoPublishSucceeded: entry.autoPublishSucceeded,
51019
- autoPublishVerified: entry.autoPublishVerified,
51020
- autoPublishRefspec: entry.autoPublishRefspec,
51021
- autoPublishSkippedReason: entry.autoPublishSkippedReason,
51022
- remote: entry.remote,
51023
- remoteUrl: entry.remoteUrl,
51024
- remoteReachable: entry.remoteReachable,
51025
- remoteMainBranch: entry.remoteMainBranch,
51026
- remoteMainReachable: entry.remoteMainReachable,
51027
- error: entry.error
51028
- })),
51029
- error: submoduleReachability.error
51030
- });
51031
- if (submoduleReachability.status === "failed") {
51032
- const nextStep = buildSubmodulePublishRequiredNextStep(submoduleReachability.unreachable);
51033
- return {
51034
- success: false,
51035
- code: "submodule_reachability_failed",
51036
- convergenceStatus: "blocked_review",
51037
- publishRequired: true,
51038
- blockedReason: "submodule_publish_required",
51039
- error: "Refinery submodule reachability preflight failed because one or more submodule gitlink commits are not reachable from their configured remote main branch; merge/refine cleanup was not attempted.",
51040
- nextStep,
51041
- nextSteps: [
51042
- "Ask the user for explicit approval before pushing or publishing any submodule commit.",
51043
- "Push/publish each unreachable submodule commit to the configured submodule remote main branch shown in the evidence.",
51044
- "Rerun mesh_refine_node after remote reachability is confirmed.",
51045
- "Do not merge the root branch until every submodule gitlink commit is reachable from submodule origin/main."
51046
- ],
51047
- unreachableSubmoduleCommits: submoduleReachability.unreachable.map((entry) => ({
51048
- path: entry.path,
51049
- commit: entry.commit,
51050
- remote: entry.remote,
51051
- remoteUrl: entry.remoteUrl,
51052
- remoteReachable: entry.remoteReachable,
51053
- remoteMainBranch: entry.remoteMainBranch,
51054
- remoteMainReachable: entry.remoteMainReachable,
51055
- autoPublishAllowed: entry.autoPublishAllowed,
51056
- autoPublishAttempted: entry.autoPublishAttempted,
51057
- autoPublishSucceeded: entry.autoPublishSucceeded,
51058
- autoPublishVerified: entry.autoPublishVerified,
51059
- autoPublishRefspec: entry.autoPublishRefspec,
51060
- autoPublishSkippedReason: entry.autoPublishSkippedReason,
51061
- error: entry.error
51062
- })),
51063
- branch,
51064
- into: baseBranch,
51065
- validationSummary,
51066
- patchEquivalence,
51067
- submoduleReachability,
51068
- refineStages,
51069
- finalBranchConvergenceState: {
51070
- branch,
51071
- baseBranch,
51072
- merged: false,
51073
- removed: false,
51074
- validation: "passed",
51075
- patchEquivalence: "passed",
51076
- submoduleReachability: "failed",
51077
- status: "blocked_review",
51078
- reason: "submodule_publish_required",
51079
- nextStep
51080
- }
51081
- };
51082
- }
51083
- const effectiveDiffStarted = Date.now();
51084
- const effectiveDiff = await runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead);
51085
- recordMeshRefineStage(refineStages, "effective_diff", effectiveDiff.status, effectiveDiffStarted, {
51086
- hasEffectiveDiff: effectiveDiff.hasEffectiveDiff,
51087
- changedPaths: effectiveDiff.changedPaths,
51088
- submoduleHints: effectiveDiff.submoduleHints,
51089
- ...effectiveDiff.error ? { error: effectiveDiff.error } : {}
51090
- });
51091
- if (effectiveDiff.status === "failed" && !effectiveDiff.hasEffectiveDiff) {
51092
- const hintLines = (effectiveDiff.submoduleHints || []).map((h) => ` - ${h.path}: ${h.reason}`);
51093
- const message = [
51094
- `Refinery no-op guard: branch '${branch}' has no effective root-tree diff against '${baseBranch}' (${baseHead.slice(0, 12)}); nothing would merge.`,
51095
- "This usually means a submodule (e.g. oss) has commits but the root branch never committed the gitlink (pointer) bump, so the merge would be a silent no-op while the real change never reaches main.",
51096
- hintLines.length ? `Submodules with uncommitted pointer bumps:
51097
- ${hintLines.join("\n")}` : "",
51098
- `Fix: commit the submodule pointer bump on '${branch}' (git add <submodule-path> && git commit), then re-run refine.`
51099
- ].filter(Boolean).join("\n");
51100
- return {
51979
+ const alreadyMergedViaOtherPath = !patchEquivalence.actualPatchId && !!patchEquivalence.expectedPatchId;
51980
+ if (!didAutoRebase && !alreadyMergedViaOtherPath) {
51981
+ return { kind: "terminal", result: {
51101
51982
  success: false,
51102
- code: "no_effective_diff",
51983
+ code: "patch_equivalence_failed",
51103
51984
  convergenceStatus: "blocked_review",
51104
- error: message,
51985
+ error: "Refinery patch-equivalence preflight failed; merge/refine was not attempted.",
51105
51986
  branch,
51106
51987
  into: baseBranch,
51107
51988
  validationSummary,
51108
51989
  patchEquivalence,
51109
- effectiveDiff,
51110
51990
  refineStages,
51111
51991
  finalBranchConvergenceState: {
51112
51992
  branch,
@@ -51114,190 +51994,378 @@ ${hintLines.join("\n")}` : "",
51114
51994
  merged: false,
51115
51995
  removed: false,
51116
51996
  validation: "passed",
51117
- patchEquivalence: "passed",
51118
- effectiveDiff: "no_effective_diff",
51119
- status: "blocked_review",
51120
- reason: "no_effective_diff",
51121
- ...effectiveDiff.submoduleHints?.length ? { submoduleHints: effectiveDiff.submoduleHints } : {}
51997
+ patchEquivalence: "failed",
51998
+ status: "blocked_review"
51122
51999
  }
51123
- };
52000
+ } };
51124
52001
  }
51125
- let mergeResult;
51126
- const mergeStarted = Date.now();
51127
- try {
51128
- const result = await execFileAsync4("git", ["merge", "--no-ff", branch, "-m", `Auto-merge branch '${branch}' via Refinery`], { cwd: repoRoot, encoding: "utf8" });
51129
- mergeResult = {
51130
- stdout: truncateValidationOutput(result.stdout),
51131
- stderr: truncateValidationOutput(result.stderr),
51132
- durationMs: Date.now() - mergeStarted
51133
- };
51134
- recordMeshRefineStage(refineStages, "merge", "passed", mergeStarted, mergeResult);
51135
- } catch (e) {
51136
- recordMeshRefineStage(refineStages, "merge", "failed", mergeStarted, {
51137
- error: e?.message || String(e),
51138
- stdout: truncateValidationOutput(e?.stdout),
51139
- stderr: truncateValidationOutput(e?.stderr)
52002
+ if (!didAutoRebase && alreadyMergedViaOtherPath) {
52003
+ recordMeshRefineStage(refineStages, "merge", "skipped", Date.now(), {
52004
+ reason: "already_merged_via_other_path",
52005
+ note: "actualPatchId is empty; branch content is already present in base via a different commit path"
51140
52006
  });
51141
- return {
51142
- success: false,
51143
- error: `Merge failed (conflicts?): ${e.message}`,
51144
- validationSummary,
51145
- patchEquivalence,
51146
- refineStages,
51147
- finalBranchConvergenceState: {
51148
- branch,
51149
- baseBranch,
51150
- merged: false,
51151
- removed: false,
51152
- validation: "passed",
51153
- patchEquivalence: "passed",
51154
- status: "not_mergeable"
51155
- }
51156
- };
51157
- }
51158
- const submoduleAlignmentStarted = Date.now();
51159
- const submoduleAlignment = await alignRefinerySubmodulesAfterMerge(repoRoot, baseHead, "HEAD", {
51160
- submoduleIgnorePaths: Array.isArray(sourceNode?.policy?.submoduleIgnorePaths) ? sourceNode.policy.submoduleIgnorePaths.filter((value) => typeof value === "string") : void 0
51161
- });
51162
- if (submoduleAlignment.status !== "skipped") {
51163
- recordMeshRefineStage(refineStages, "submodule_alignment", submoduleAlignment.status, submoduleAlignmentStarted, {
51164
- changedGitlinkPaths: submoduleAlignment.changedGitlinkPaths,
51165
- outOfSyncPaths: submoduleAlignment.outOfSyncPaths,
51166
- updatedPaths: submoduleAlignment.updatedPaths,
51167
- verifiedPaths: submoduleAlignment.verifiedPaths,
51168
- command: submoduleAlignment.command,
51169
- error: submoduleAlignment.error
52007
+ const cleanupStarted = Date.now();
52008
+ const removeResult = await this.execute("remove_mesh_node", {
52009
+ meshId,
52010
+ nodeId,
52011
+ sessionCleanupMode: "preserve",
52012
+ inlineMesh: args?.inlineMesh
51170
52013
  });
51171
- }
51172
- if (submoduleAlignment.status === "failed") {
51173
- return {
51174
- success: false,
51175
- code: "post_merge_submodule_alignment_failed",
51176
- error: "Refinery merge completed but post-merge submodule checkout alignment failed; run the reported git submodule update command and re-check base workspace status.",
51177
- merged: true,
52014
+ recordMeshRefineStage(refineStages, "cleanup", removeResult?.success === false ? "failed" : "passed", cleanupStarted, {
52015
+ removed: removeResult?.removed,
52016
+ code: removeResult?.code,
52017
+ error: removeResult?.error
52018
+ });
52019
+ try {
52020
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
52021
+ appendLedgerEntry2(meshId, {
52022
+ kind: "node_removed",
52023
+ nodeId,
52024
+ payload: { alreadyMergedViaOtherPath: true, branch, into: baseBranch, validationSummary, patchEquivalence }
52025
+ });
52026
+ } catch {
52027
+ }
52028
+ return { kind: "terminal", result: {
52029
+ success: removeResult?.success !== false,
52030
+ code: "already_merged",
52031
+ merged: false,
52032
+ alreadyMergedViaOtherPath: true,
51178
52033
  branch,
51179
52034
  into: baseBranch,
52035
+ removeResult,
51180
52036
  validationSummary,
51181
52037
  patchEquivalence,
51182
- submoduleReachability,
51183
- submoduleAlignment,
51184
- mergeResult,
51185
52038
  refineStages,
51186
52039
  finalBranchConvergenceState: {
51187
52040
  branch: baseBranch,
51188
52041
  mergedBranch: branch,
51189
52042
  baseBranch,
51190
- merged: true,
51191
- removed: false,
52043
+ merged: false,
52044
+ alreadyMergedViaOtherPath: true,
52045
+ removed: removeResult?.success !== false,
51192
52046
  validation: "passed",
51193
- patchEquivalence: "passed",
51194
- submoduleReachability: "passed",
51195
- submoduleAlignment: "failed",
51196
- status: "post_merge_alignment_failed",
51197
- nextStep: submoduleAlignment.command || "Run git submodule update --init --recursive for the reported path(s), then re-check base workspace status."
52047
+ patchEquivalence: "already_merged",
52048
+ status: removeResult?.success === false ? "merged_cleanup_failed" : "merged_to_main"
51198
52049
  }
51199
- };
52050
+ } };
51200
52051
  }
51201
- const cleanupStarted = Date.now();
51202
- const refineSessionCleanupMode = this.normalizeMeshSessionCleanupMode(
51203
- mesh?.policy?.sessionCleanupOnNodeRemove
51204
- );
51205
- let refineSessionIds;
51206
- if (refineSessionCleanupMode !== "preserve" && this.deps.sessionHostControl) {
51207
- try {
51208
- const liveSessions = await this.deps.sessionHostControl.listSessions();
51209
- const workspace = typeof node.workspace === "string" ? node.workspace : "";
51210
- refineSessionIds = liveSessions.filter((record) => {
51211
- const sid = typeof record?.sessionId === "string" ? record.sessionId : "";
51212
- if (!sid) return false;
51213
- if (readStringValue(record?.meta?.meshCoordinatorFor) === meshId) return false;
51214
- const boundToNode = readStringValue(record?.meta?.meshNodeId) === nodeId;
51215
- const matchedByWorkspace = !!workspace && record?.workspace === workspace;
51216
- return boundToNode || matchedByWorkspace;
51217
- }).map((record) => String(record.sessionId));
51218
- } catch {
51219
- refineSessionIds = void 0;
52052
+ }
52053
+ ctx.branchHead = branchHead;
52054
+ ctx.patchEquivalence = patchEquivalence;
52055
+ return { kind: "continue", ctx };
52056
+ }
52057
+ /**
52058
+ * submodule_reachability stage: verify every submodule gitlink commit that
52059
+ * would land via the merge is reachable from its configured remote main
52060
+ * branch (optionally auto-publishing when policy allows). Blocks the merge
52061
+ * when any commit is unreachable. Stores the result on the context.
52062
+ */
52063
+ async refineSubmoduleReachabilityStage(ctx) {
52064
+ const { mesh, node, repoRoot, branch, baseBranch, branchHead, validationSummary, patchEquivalence, refineStages } = ctx;
52065
+ const submoduleReachabilityStarted = Date.now();
52066
+ const autoPublishSubmoduleMainCommits = resolveRefineryAutoPublishSubmoduleMainCommits(mesh, node.workspace);
52067
+ const submoduleReachability = await runMeshRefineSubmoduleReachabilityGate(repoRoot, patchEquivalence.mergedTree || branchHead, {
52068
+ allowAutoPublishSubmoduleMainCommits: autoPublishSubmoduleMainCommits.enabled,
52069
+ autoPublishPolicySource: autoPublishSubmoduleMainCommits.source,
52070
+ worktreeRoot: node.workspace
52071
+ });
52072
+ recordMeshRefineStage(refineStages, "submodule_reachability", submoduleReachability.status, submoduleReachabilityStarted, {
52073
+ checked: submoduleReachability.checked,
52074
+ autoPublishAllowed: submoduleReachability.autoPublishAllowed,
52075
+ autoPublishPolicySource: submoduleReachability.autoPublishPolicySource,
52076
+ autoPublished: submoduleReachability.entries.filter((entry) => entry.autoPublishAttempted).map((entry) => ({
52077
+ path: entry.path,
52078
+ commit: entry.commit,
52079
+ remote: entry.remote,
52080
+ remoteUrl: entry.remoteUrl,
52081
+ remoteMainBranch: entry.remoteMainBranch,
52082
+ refspec: entry.autoPublishRefspec,
52083
+ succeeded: entry.autoPublishSucceeded,
52084
+ verified: entry.autoPublishVerified,
52085
+ remoteMainReachable: entry.remoteMainReachable,
52086
+ error: entry.error
52087
+ })),
52088
+ autoPublishSkipped: submoduleReachability.entries.filter((entry) => entry.autoPublishAllowed === true && entry.autoPublishAttempted !== true).map((entry) => ({
52089
+ path: entry.path,
52090
+ commit: entry.commit,
52091
+ remote: entry.remote,
52092
+ remoteUrl: entry.remoteUrl,
52093
+ remoteMainBranch: entry.remoteMainBranch,
52094
+ reason: entry.autoPublishSkippedReason || entry.error || "auto-publish was allowed but no publish attempt was possible"
52095
+ })),
52096
+ unreachable: submoduleReachability.unreachable.map((entry) => ({
52097
+ path: entry.path,
52098
+ commit: entry.commit,
52099
+ publishRequired: entry.publishRequired === true,
52100
+ autoPublishAllowed: entry.autoPublishAllowed,
52101
+ autoPublishAttempted: entry.autoPublishAttempted,
52102
+ autoPublishSucceeded: entry.autoPublishSucceeded,
52103
+ autoPublishVerified: entry.autoPublishVerified,
52104
+ autoPublishRefspec: entry.autoPublishRefspec,
52105
+ autoPublishSkippedReason: entry.autoPublishSkippedReason,
52106
+ remote: entry.remote,
52107
+ remoteUrl: entry.remoteUrl,
52108
+ remoteReachable: entry.remoteReachable,
52109
+ remoteMainBranch: entry.remoteMainBranch,
52110
+ remoteMainReachable: entry.remoteMainReachable,
52111
+ error: entry.error
52112
+ })),
52113
+ error: submoduleReachability.error
52114
+ });
52115
+ if (submoduleReachability.status === "failed") {
52116
+ const nextStep = buildSubmodulePublishRequiredNextStep(submoduleReachability.unreachable);
52117
+ return { kind: "terminal", result: {
52118
+ success: false,
52119
+ code: "submodule_reachability_failed",
52120
+ convergenceStatus: "blocked_review",
52121
+ publishRequired: true,
52122
+ blockedReason: "submodule_publish_required",
52123
+ error: "Refinery submodule reachability preflight failed because one or more submodule gitlink commits are not reachable from their configured remote main branch; merge/refine cleanup was not attempted.",
52124
+ nextStep,
52125
+ nextSteps: [
52126
+ "Ask the user for explicit approval before pushing or publishing any submodule commit.",
52127
+ "Push/publish each unreachable submodule commit to the configured submodule remote main branch shown in the evidence.",
52128
+ "Rerun mesh_refine_node after remote reachability is confirmed.",
52129
+ "Do not merge the root branch until every submodule gitlink commit is reachable from submodule origin/main."
52130
+ ],
52131
+ unreachableSubmoduleCommits: submoduleReachability.unreachable.map((entry) => ({
52132
+ path: entry.path,
52133
+ commit: entry.commit,
52134
+ remote: entry.remote,
52135
+ remoteUrl: entry.remoteUrl,
52136
+ remoteReachable: entry.remoteReachable,
52137
+ remoteMainBranch: entry.remoteMainBranch,
52138
+ remoteMainReachable: entry.remoteMainReachable,
52139
+ autoPublishAllowed: entry.autoPublishAllowed,
52140
+ autoPublishAttempted: entry.autoPublishAttempted,
52141
+ autoPublishSucceeded: entry.autoPublishSucceeded,
52142
+ autoPublishVerified: entry.autoPublishVerified,
52143
+ autoPublishRefspec: entry.autoPublishRefspec,
52144
+ autoPublishSkippedReason: entry.autoPublishSkippedReason,
52145
+ error: entry.error
52146
+ })),
52147
+ branch,
52148
+ into: baseBranch,
52149
+ validationSummary,
52150
+ patchEquivalence,
52151
+ submoduleReachability,
52152
+ refineStages,
52153
+ finalBranchConvergenceState: {
52154
+ branch,
52155
+ baseBranch,
52156
+ merged: false,
52157
+ removed: false,
52158
+ validation: "passed",
52159
+ patchEquivalence: "passed",
52160
+ submoduleReachability: "failed",
52161
+ status: "blocked_review",
52162
+ reason: "submodule_publish_required",
52163
+ nextStep
51220
52164
  }
51221
- }
51222
- const removeResult = await this.execute("remove_mesh_node", {
51223
- meshId,
51224
- nodeId,
51225
- sessionCleanupMode: refineSessionCleanupMode,
51226
- ...refineSessionIds && refineSessionIds.length > 0 ? { sessionIds: refineSessionIds } : {},
51227
- inlineMesh: args?.inlineMesh
52165
+ } };
52166
+ }
52167
+ ctx.submoduleReachability = submoduleReachability;
52168
+ return { kind: "continue", ctx };
52169
+ }
52170
+ /**
52171
+ * effective_diff stage (no-op guard): block a silent no-op merge where the
52172
+ * branch produces no effective root-tree diff against base — typically a
52173
+ * submodule that has commits but whose root-level gitlink (pointer) bump was
52174
+ * never committed, so the merge would land nothing real on main.
52175
+ */
52176
+ async refineEffectiveDiffStage(ctx) {
52177
+ const { repoRoot, baseHead, branchHead, branch, baseBranch, validationSummary, patchEquivalence, refineStages } = ctx;
52178
+ const effectiveDiffStarted = Date.now();
52179
+ const effectiveDiff = await runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead);
52180
+ recordMeshRefineStage(refineStages, "effective_diff", effectiveDiff.status, effectiveDiffStarted, {
52181
+ hasEffectiveDiff: effectiveDiff.hasEffectiveDiff,
52182
+ changedPaths: effectiveDiff.changedPaths,
52183
+ submoduleHints: effectiveDiff.submoduleHints,
52184
+ ...effectiveDiff.error ? { error: effectiveDiff.error } : {}
52185
+ });
52186
+ if (effectiveDiff.status === "failed" && !effectiveDiff.hasEffectiveDiff) {
52187
+ const hintLines = (effectiveDiff.submoduleHints || []).map((h) => ` - ${h.path}: ${h.reason}`);
52188
+ const message = [
52189
+ `Refinery no-op guard: branch '${branch}' has no effective root-tree diff against '${baseBranch}' (${baseHead.slice(0, 12)}); nothing would merge.`,
52190
+ "This usually means a submodule (e.g. oss) has commits but the root branch never committed the gitlink (pointer) bump, so the merge would be a silent no-op while the real change never reaches main.",
52191
+ hintLines.length ? `Submodules with uncommitted pointer bumps:
52192
+ ${hintLines.join("\n")}` : "",
52193
+ `Fix: commit the submodule pointer bump on '${branch}' (git add <submodule-path> && git commit), then re-run refine.`
52194
+ ].filter(Boolean).join("\n");
52195
+ return { kind: "terminal", result: {
52196
+ success: false,
52197
+ code: "no_effective_diff",
52198
+ convergenceStatus: "blocked_review",
52199
+ error: message,
52200
+ branch,
52201
+ into: baseBranch,
52202
+ validationSummary,
52203
+ patchEquivalence,
52204
+ effectiveDiff,
52205
+ refineStages,
52206
+ finalBranchConvergenceState: {
52207
+ branch,
52208
+ baseBranch,
52209
+ merged: false,
52210
+ removed: false,
52211
+ validation: "passed",
52212
+ patchEquivalence: "passed",
52213
+ effectiveDiff: "no_effective_diff",
52214
+ status: "blocked_review",
52215
+ reason: "no_effective_diff",
52216
+ ...effectiveDiff.submoduleHints?.length ? { submoduleHints: effectiveDiff.submoduleHints } : {}
52217
+ }
52218
+ } };
52219
+ }
52220
+ return { kind: "continue", ctx };
52221
+ }
52222
+ /**
52223
+ * merge + finalize stage: perform the --no-ff merge, align submodule
52224
+ * checkouts after merge, clean up (remove) the worktree node per policy,
52225
+ * append the refinery ledger entry, and (unless approval is required) push the
52226
+ * base branch. Always terminal — produces the final CommandRouterResult.
52227
+ */
52228
+ async refineMergeAndFinalizeStage(ctx) {
52229
+ const { meshId, nodeId, args, repoRoot, baseHead, node, branch, baseBranch, sourceNode, validationSummary, patchEquivalence, submoduleReachability, mesh, refineStages, execFileAsync: execFileAsync4 } = ctx;
52230
+ let mergeResult;
52231
+ const mergeStarted = Date.now();
52232
+ try {
52233
+ const result = await execFileAsync4("git", ["merge", "--no-ff", branch, "-m", `Auto-merge branch '${branch}' via Refinery`], { cwd: repoRoot, encoding: "utf8" });
52234
+ mergeResult = {
52235
+ stdout: truncateValidationOutput(result.stdout),
52236
+ stderr: truncateValidationOutput(result.stderr),
52237
+ durationMs: Date.now() - mergeStarted
52238
+ };
52239
+ recordMeshRefineStage(refineStages, "merge", "passed", mergeStarted, mergeResult);
52240
+ } catch (e) {
52241
+ recordMeshRefineStage(refineStages, "merge", "failed", mergeStarted, {
52242
+ error: e?.message || String(e),
52243
+ stdout: truncateValidationOutput(e?.stdout),
52244
+ stderr: truncateValidationOutput(e?.stderr)
51228
52245
  });
51229
- recordMeshRefineStage(refineStages, "cleanup", removeResult?.success === false ? "failed" : "passed", cleanupStarted, {
51230
- removed: removeResult?.removed,
51231
- code: removeResult?.code,
51232
- error: removeResult?.error
52246
+ return { kind: "terminal", result: {
52247
+ success: false,
52248
+ error: `Merge failed (conflicts?): ${e.message}`,
52249
+ validationSummary,
52250
+ patchEquivalence,
52251
+ refineStages,
52252
+ finalBranchConvergenceState: {
52253
+ branch,
52254
+ baseBranch,
52255
+ merged: false,
52256
+ removed: false,
52257
+ validation: "passed",
52258
+ patchEquivalence: "passed",
52259
+ status: "not_mergeable"
52260
+ }
52261
+ } };
52262
+ }
52263
+ const submoduleAlignmentStarted = Date.now();
52264
+ const submoduleAlignment = await alignRefinerySubmodulesAfterMerge(repoRoot, baseHead, "HEAD", {
52265
+ submoduleIgnorePaths: Array.isArray(sourceNode?.policy?.submoduleIgnorePaths) ? sourceNode.policy.submoduleIgnorePaths.filter((value) => typeof value === "string") : void 0
52266
+ });
52267
+ if (submoduleAlignment.status !== "skipped") {
52268
+ recordMeshRefineStage(refineStages, "submodule_alignment", submoduleAlignment.status, submoduleAlignmentStarted, {
52269
+ changedGitlinkPaths: submoduleAlignment.changedGitlinkPaths,
52270
+ outOfSyncPaths: submoduleAlignment.outOfSyncPaths,
52271
+ updatedPaths: submoduleAlignment.updatedPaths,
52272
+ verifiedPaths: submoduleAlignment.verifiedPaths,
52273
+ command: submoduleAlignment.command,
52274
+ error: submoduleAlignment.error
51233
52275
  });
51234
- let ledgerError;
51235
- const ledgerStarted = Date.now();
51236
- try {
51237
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
51238
- appendLedgerEntry2(meshId, {
51239
- kind: "node_removed",
51240
- nodeId,
51241
- payload: { refined: true, mergedBranch: branch, into: baseBranch, validationSummary, patchEquivalence, submoduleReachability, submoduleAlignment }
51242
- });
51243
- recordMeshRefineStage(refineStages, "ledger", "passed", ledgerStarted);
51244
- } catch (e) {
51245
- ledgerError = e?.message || String(e);
51246
- recordMeshRefineStage(refineStages, "ledger", "failed", ledgerStarted, { error: ledgerError });
51247
- }
51248
- const finalBranchConvergenceState = {
51249
- branch: baseBranch,
51250
- mergedBranch: branch,
51251
- baseBranch,
52276
+ }
52277
+ if (submoduleAlignment.status === "failed") {
52278
+ return { kind: "terminal", result: {
52279
+ success: false,
52280
+ code: "post_merge_submodule_alignment_failed",
52281
+ error: "Refinery merge completed but post-merge submodule checkout alignment failed; run the reported git submodule update command and re-check base workspace status.",
51252
52282
  merged: true,
51253
- removed: removeResult?.success !== false,
51254
- validation: "passed",
51255
- patchEquivalence: "passed",
51256
- submoduleAlignment: submoduleAlignment.status,
51257
- status: removeResult?.success === false ? "merged_cleanup_failed" : "merged"
51258
- };
51259
- if (removeResult?.success === false) {
51260
- return {
51261
- success: false,
51262
- code: "cleanup_failed",
51263
- error: "Refinery merge completed but worktree cleanup failed; manual cleanup/retry is required.",
52283
+ branch,
52284
+ into: baseBranch,
52285
+ validationSummary,
52286
+ patchEquivalence,
52287
+ submoduleReachability,
52288
+ submoduleAlignment,
52289
+ mergeResult,
52290
+ refineStages,
52291
+ finalBranchConvergenceState: {
52292
+ branch: baseBranch,
52293
+ mergedBranch: branch,
52294
+ baseBranch,
51264
52295
  merged: true,
51265
- branch,
51266
- into: baseBranch,
51267
- removeResult,
51268
- validationSummary,
51269
- patchEquivalence,
51270
- submoduleReachability,
51271
- submoduleAlignment,
51272
- mergeResult,
51273
- refineStages,
51274
- ...ledgerError ? { ledgerError } : {},
51275
- finalBranchConvergenceState
51276
- };
51277
- }
51278
- const requireApprovalForPush = mesh?.policy?.requireApprovalForPush ?? DEFAULT_MESH_POLICY.requireApprovalForPush;
51279
- let pushResult;
51280
- if (!requireApprovalForPush) {
51281
- const pushStarted = Date.now();
51282
- try {
51283
- await execFileAsync4("git", ["push", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8" });
51284
- pushResult = { pushed: true, remote: "origin", branch: baseBranch, durationMs: Date.now() - pushStarted };
51285
- recordMeshRefineStage(refineStages, "push", "passed", pushStarted, pushResult);
51286
- finalBranchConvergenceState.status = "merged_pushed";
51287
- } catch (e) {
51288
- pushResult = {
51289
- pushed: false,
51290
- remote: "origin",
51291
- branch: baseBranch,
51292
- error: e?.message || String(e),
51293
- stderr: e?.stderr,
51294
- durationMs: Date.now() - pushStarted
51295
- };
51296
- recordMeshRefineStage(refineStages, "push", "failed", pushStarted, pushResult);
51297
- }
52296
+ removed: false,
52297
+ validation: "passed",
52298
+ patchEquivalence: "passed",
52299
+ submoduleReachability: "passed",
52300
+ submoduleAlignment: "failed",
52301
+ status: "post_merge_alignment_failed",
52302
+ nextStep: submoduleAlignment.command || "Run git submodule update --init --recursive for the reported path(s), then re-check base workspace status."
52303
+ }
52304
+ } };
52305
+ }
52306
+ const cleanupStarted = Date.now();
52307
+ const refineSessionCleanupMode = this.normalizeMeshSessionCleanupMode(
52308
+ mesh?.policy?.sessionCleanupOnNodeRemove
52309
+ );
52310
+ let refineSessionIds;
52311
+ if (refineSessionCleanupMode !== "preserve" && this.deps.sessionHostControl) {
52312
+ try {
52313
+ const liveSessions = await this.deps.sessionHostControl.listSessions();
52314
+ const workspace = typeof node.workspace === "string" ? node.workspace : "";
52315
+ refineSessionIds = liveSessions.filter((record) => {
52316
+ const sid = typeof record?.sessionId === "string" ? record.sessionId : "";
52317
+ if (!sid) return false;
52318
+ if (readStringValue(record?.meta?.meshCoordinatorFor) === meshId) return false;
52319
+ const boundToNode = readStringValue(record?.meta?.meshNodeId) === nodeId;
52320
+ const matchedByWorkspace = !!workspace && record?.workspace === workspace;
52321
+ return boundToNode || matchedByWorkspace;
52322
+ }).map((record) => String(record.sessionId));
52323
+ } catch {
52324
+ refineSessionIds = void 0;
51298
52325
  }
51299
- return {
51300
- success: true,
52326
+ }
52327
+ const removeResult = await this.execute("remove_mesh_node", {
52328
+ meshId,
52329
+ nodeId,
52330
+ sessionCleanupMode: refineSessionCleanupMode,
52331
+ ...refineSessionIds && refineSessionIds.length > 0 ? { sessionIds: refineSessionIds } : {},
52332
+ inlineMesh: args?.inlineMesh
52333
+ });
52334
+ recordMeshRefineStage(refineStages, "cleanup", removeResult?.success === false ? "failed" : "passed", cleanupStarted, {
52335
+ removed: removeResult?.removed,
52336
+ code: removeResult?.code,
52337
+ error: removeResult?.error
52338
+ });
52339
+ let ledgerError;
52340
+ const ledgerStarted = Date.now();
52341
+ try {
52342
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
52343
+ appendLedgerEntry2(meshId, {
52344
+ kind: "node_removed",
52345
+ nodeId,
52346
+ payload: { refined: true, mergedBranch: branch, into: baseBranch, validationSummary, patchEquivalence, submoduleReachability, submoduleAlignment }
52347
+ });
52348
+ recordMeshRefineStage(refineStages, "ledger", "passed", ledgerStarted);
52349
+ } catch (e) {
52350
+ ledgerError = e?.message || String(e);
52351
+ recordMeshRefineStage(refineStages, "ledger", "failed", ledgerStarted, { error: ledgerError });
52352
+ }
52353
+ const finalBranchConvergenceState = {
52354
+ branch: baseBranch,
52355
+ mergedBranch: branch,
52356
+ baseBranch,
52357
+ merged: true,
52358
+ removed: removeResult?.success !== false,
52359
+ validation: "passed",
52360
+ patchEquivalence: "passed",
52361
+ submoduleAlignment: submoduleAlignment.status,
52362
+ status: removeResult?.success === false ? "merged_cleanup_failed" : "merged"
52363
+ };
52364
+ if (removeResult?.success === false) {
52365
+ return { kind: "terminal", result: {
52366
+ success: false,
52367
+ code: "cleanup_failed",
52368
+ error: "Refinery merge completed but worktree cleanup failed; manual cleanup/retry is required.",
51301
52369
  merged: true,
51302
52370
  branch,
51303
52371
  into: baseBranch,
@@ -51309,17 +52377,51 @@ ${hintLines.join("\n")}` : "",
51309
52377
  mergeResult,
51310
52378
  refineStages,
51311
52379
  ...ledgerError ? { ledgerError } : {},
51312
- finalBranchConvergenceState,
51313
- // Push outcome or readiness info for coordinator.
51314
- ...pushResult ? { pushResult } : {
51315
- pushReady: true,
51316
- pushCommand: `git push origin ${baseBranch}`,
51317
- pushNote: "requireApprovalForPush is enabled \u2014 run the push command or obtain user approval before pushing."
51318
- }
51319
- };
51320
- } catch (e) {
51321
- return { success: false, error: e.message, refineStages };
52380
+ finalBranchConvergenceState
52381
+ } };
52382
+ }
52383
+ const requireApprovalForPush = mesh?.policy?.requireApprovalForPush ?? DEFAULT_MESH_POLICY.requireApprovalForPush;
52384
+ let pushResult;
52385
+ if (!requireApprovalForPush) {
52386
+ const pushStarted = Date.now();
52387
+ try {
52388
+ await execFileAsync4("git", ["push", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8" });
52389
+ pushResult = { pushed: true, remote: "origin", branch: baseBranch, durationMs: Date.now() - pushStarted };
52390
+ recordMeshRefineStage(refineStages, "push", "passed", pushStarted, pushResult);
52391
+ finalBranchConvergenceState.status = "merged_pushed";
52392
+ } catch (e) {
52393
+ pushResult = {
52394
+ pushed: false,
52395
+ remote: "origin",
52396
+ branch: baseBranch,
52397
+ error: e?.message || String(e),
52398
+ stderr: e?.stderr,
52399
+ durationMs: Date.now() - pushStarted
52400
+ };
52401
+ recordMeshRefineStage(refineStages, "push", "failed", pushStarted, pushResult);
52402
+ }
51322
52403
  }
52404
+ return { kind: "terminal", result: {
52405
+ success: true,
52406
+ merged: true,
52407
+ branch,
52408
+ into: baseBranch,
52409
+ removeResult,
52410
+ validationSummary,
52411
+ patchEquivalence,
52412
+ submoduleReachability,
52413
+ submoduleAlignment,
52414
+ mergeResult,
52415
+ refineStages,
52416
+ ...ledgerError ? { ledgerError } : {},
52417
+ finalBranchConvergenceState,
52418
+ // Push outcome or readiness info for coordinator.
52419
+ ...pushResult ? { pushResult } : {
52420
+ pushReady: true,
52421
+ pushCommand: `git push origin ${baseBranch}`,
52422
+ pushNote: "requireApprovalForPush is enabled \u2014 run the push command or obtain user approval before pushing."
52423
+ }
52424
+ } };
51323
52425
  }
51324
52426
  /**
51325
52427
  * Batch refinery: converge multiple sibling worktree nodes onto the base branch
@@ -51877,929 +52979,9 @@ ${hintLines.join("\n")}` : "",
51877
52979
  if (medFamilyHandler) {
51878
52980
  return await medFamilyHandler(this.buildMedFamilyContext(), args);
51879
52981
  }
51880
- switch (cmd) {
51881
- // ─── CLI / ACP commands ───
51882
- case "mesh_forward_event": {
51883
- return handleMeshForwardEvent({ instanceManager: this.deps.instanceManager }, args);
51884
- }
51885
- case "get_pending_mesh_events": {
51886
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51887
- const coordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : void 0;
51888
- const events = drainPendingMeshCoordinatorEvents(meshId || void 0, coordinatorDaemonId);
51889
- return { success: true, events };
51890
- }
51891
- case "interactive_prompt_response": {
51892
- const sessionId = typeof args?.targetSessionId === "string" && args.targetSessionId.trim() ? args.targetSessionId.trim() : typeof args?.sessionId === "string" && args.sessionId.trim() ? args.sessionId.trim() : "";
51893
- if (!sessionId) return { success: false, error: "targetSessionId required" };
51894
- const response = normalizeInteractivePromptResponse(args?.response ?? args);
51895
- const instance = this.deps.instanceManager.getInstance(sessionId);
51896
- if (!instance) return { success: false, error: `No running instance for session ${sessionId}` };
51897
- this.deps.instanceManager.sendEvent(sessionId, "interactive_prompt_response", response);
51898
- return { success: true };
51899
- }
51900
- // ─── Mesh Coordinator Launch ───
51901
- case "launch_mesh_coordinator": {
51902
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51903
- let cliType = typeof args?.cliType === "string" ? args.cliType.trim() : "";
51904
- const extraSystemPrompt = typeof args?.extraSystemPrompt === "string" ? args.extraSystemPrompt.trim() : "";
51905
- if (!meshId) return { success: false, error: "meshId required" };
51906
- try {
51907
- const { buildCoordinatorSystemPrompt: buildCoordinatorSystemPrompt2 } = await Promise.resolve().then(() => (init_coordinator_prompt(), coordinator_prompt_exports));
51908
- const { buildMissionPromptSection: buildMissionPromptSection2 } = await Promise.resolve().then(() => (init_mesh_missions(), mesh_missions_exports));
51909
- const buildMissionSectionBestEffort = (id) => {
51910
- try {
51911
- return buildMissionPromptSection2(id);
51912
- } catch {
51913
- return "";
51914
- }
51915
- };
51916
- let mesh;
51917
- if (args?.inlineMesh && typeof args.inlineMesh === "object") {
51918
- mesh = args.inlineMesh;
51919
- this.inlineMeshCache.set(meshId, mesh);
51920
- } else {
51921
- const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51922
- mesh = getMesh2(meshId);
51923
- }
51924
- if (!mesh) return { success: false, error: "Mesh not found" };
51925
- const meshHost = resolveMeshHostStatus(mesh);
51926
- if (!meshHost.canOwnCoordinator) {
51927
- return {
51928
- success: false,
51929
- ...buildMeshHostRequiredFailure(mesh, "coordinator launch"),
51930
- meshId,
51931
- cliType
51932
- };
51933
- }
51934
- if (!Array.isArray(mesh.nodes) || mesh.nodes.length === 0) return { success: false, error: "No nodes in mesh" };
51935
- const requestedCoordinatorNodeId = typeof args?.coordinatorNodeId === "string" ? args.coordinatorNodeId.trim() : "";
51936
- const preferredCoordinatorNodeId = requestedCoordinatorNodeId || (typeof mesh.coordinator?.preferredNodeId === "string" ? mesh.coordinator.preferredNodeId.trim() : "");
51937
- const coordinatorNode = preferredCoordinatorNodeId ? mesh.nodes.find((node) => node?.id === preferredCoordinatorNodeId || node?.nodeId === preferredCoordinatorNodeId) : mesh.nodes[0];
51938
- if (!coordinatorNode) {
51939
- return {
51940
- success: false,
51941
- code: "mesh_coordinator_node_not_found",
51942
- error: `Coordinator node ${preferredCoordinatorNodeId} was not found in mesh`,
51943
- meshId,
51944
- cliType
51945
- };
51946
- }
51947
- const sessionHostRecords = this.deps.sessionHostControl?.listSessions ? await this.deps.sessionHostControl.listSessions().catch(() => []) : [];
51948
- const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
51949
- const workspace = readLiveMeshNodeWorkspace({
51950
- meshId,
51951
- nodeId: String(normalizeMeshNodeId(coordinatorNode) || preferredCoordinatorNodeId || ""),
51952
- liveSessionRecords: liveMeshSessions,
51953
- allowCoordinatorSession: true
51954
- }) || (typeof coordinatorNode.workspace === "string" ? coordinatorNode.workspace.trim() : "");
51955
- if (!workspace) return { success: false, error: "Coordinator node workspace required", meshId, cliType };
51956
- if (!cliType) {
51957
- const resolved = await resolveProviderTypeFromPriority({
51958
- nodeId: String(normalizeMeshNodeId(coordinatorNode) || preferredCoordinatorNodeId || "coordinator"),
51959
- providerPriority: readProviderPriorityFromPolicy(coordinatorNode.policy),
51960
- providerLoader: this.deps.providerLoader,
51961
- onStatusChange: this.deps.onStatusChange
51962
- });
51963
- if (!resolved.providerType) {
51964
- return {
51965
- success: false,
51966
- code: "mesh_coordinator_provider_priority_unusable",
51967
- error: resolved.error || "No usable provider found from node providerPriority",
51968
- meshId,
51969
- cliType,
51970
- workspace
51971
- };
51972
- }
51973
- cliType = resolved.providerType;
51974
- }
51975
- const providerMeta = this.deps.providerLoader.resolve?.(cliType) || this.deps.providerLoader.getMeta(cliType);
51976
- const coordinatorSetup = resolveMeshCoordinatorSetup({
51977
- provider: providerMeta,
51978
- cliType,
51979
- meshId,
51980
- workspace
51981
- });
51982
- if (coordinatorSetup.kind === "unsupported") {
51983
- return {
51984
- success: false,
51985
- code: "mesh_coordinator_unsupported",
51986
- error: coordinatorSetup.reason,
51987
- meshId,
51988
- cliType,
51989
- workspace
51990
- };
51991
- }
51992
- if (coordinatorSetup.kind === "manual") {
51993
- return {
51994
- success: false,
51995
- code: "mesh_coordinator_manual_mcp_setup_required",
51996
- error: coordinatorSetup.instructions,
51997
- meshId,
51998
- cliType,
51999
- workspace,
52000
- meshCoordinatorSetup: coordinatorSetup
52001
- };
52002
- }
52003
- if (coordinatorSetup.kind === "cli_command") {
52004
- let cliCmdSystemPrompt = "";
52005
- try {
52006
- cliCmdSystemPrompt = buildCoordinatorSystemPrompt2({ mesh, coordinatorCliType: cliType, userInstruction: extraSystemPrompt || void 0, missionSection: buildMissionSectionBestEffort(mesh.id) });
52007
- } catch (error) {
52008
- const message = error?.message || String(error);
52009
- LOG.error("MeshCoordinator", `Failed to build coordinator prompt: ${message}`);
52010
- return {
52011
- success: false,
52012
- code: "mesh_coordinator_prompt_failed",
52013
- error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
52014
- meshId,
52015
- cliType,
52016
- workspace
52017
- };
52018
- }
52019
- let mcpRegistrationOk = false;
52020
- let mcpRegistrationFailure = null;
52021
- try {
52022
- const { buildMeshCoordinatorRegistrationPlan: buildMeshCoordinatorRegistrationPlan2, execUnderPty: execUnderPty2 } = await Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports));
52023
- const registrationPlan = buildMeshCoordinatorRegistrationPlan2(
52024
- cliType,
52025
- coordinatorSetup.serverName,
52026
- coordinatorSetup.command
52027
- );
52028
- for (const step of registrationPlan) {
52029
- const renderedCommand = [step.command, ...step.args].join(" ");
52030
- LOG.info("MeshCoordinator", `Running MCP ${step.label} (pty): ${renderedCommand}`);
52031
- const ptyResult = await execUnderPty2(step.command, step.args, { cwd: workspace, timeoutMs: 2e4 });
52032
- if (ptyResult.exitCode === 0 && !ptyResult.timedOut) {
52033
- if (step.required) mcpRegistrationOk = true;
52034
- continue;
52035
- }
52036
- LOG.warn("MeshCoordinator", `MCP ${step.label} failed exit=${ptyResult.exitCode} signal=${ptyResult.signal} timedOut=${ptyResult.timedOut} \u2014 output:
52037
- ${ptyResult.output.slice(-2e3)}`);
52038
- if (step.required) {
52039
- mcpRegistrationFailure = {
52040
- command: renderedCommand,
52041
- output: ptyResult.output.slice(-2e3),
52042
- exitCode: ptyResult.exitCode,
52043
- signal: ptyResult.signal,
52044
- timedOut: ptyResult.timedOut
52045
- };
52046
- break;
52047
- }
52048
- }
52049
- } catch (error) {
52050
- LOG.warn("MeshCoordinator", `MCP registration command failed: ${error?.message || error}`);
52051
- mcpRegistrationFailure = {
52052
- command: coordinatorSetup.command,
52053
- output: error?.message || String(error),
52054
- exitCode: null,
52055
- signal: null,
52056
- timedOut: false
52057
- };
52058
- }
52059
- if (!mcpRegistrationOk) {
52060
- return {
52061
- success: false,
52062
- code: "mesh_coordinator_mcp_registration_failed",
52063
- error: `Could not register ${coordinatorSetup.serverName}; coordinator session was not launched`,
52064
- meshId,
52065
- cliType,
52066
- workspace,
52067
- registration: mcpRegistrationFailure
52068
- };
52069
- }
52070
- if (cliType === "codex-cli") {
52071
- const repoMcpConfigPath = pathJoin(workspace, ".mcp.json");
52072
- if (fs27.existsSync(repoMcpConfigPath)) {
52073
- try {
52074
- const repoMcpConfig = parseMeshCoordinatorMcpConfig(
52075
- fs27.readFileSync(repoMcpConfigPath, "utf-8"),
52076
- "claude_mcp_json"
52077
- );
52078
- const existingServers2 = repoMcpConfig.mcpServers;
52079
- if (existingServers2 && typeof existingServers2 === "object" && !Array.isArray(existingServers2) && existingServers2[coordinatorSetup.serverName]) {
52080
- fs27.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
52081
- ...repoMcpConfig,
52082
- mcpServers: {
52083
- ...existingServers2,
52084
- [coordinatorSetup.serverName]: coordinatorSetup.mcpServer
52085
- }
52086
- }, "claude_mcp_json"), "utf-8");
52087
- LOG.info("MeshCoordinator", `Refreshed repo-local ${repoMcpConfigPath} entry for ${coordinatorSetup.serverName}`);
52088
- }
52089
- } catch (error) {
52090
- return {
52091
- success: false,
52092
- code: "mesh_coordinator_config_write_failed",
52093
- error: `Could not refresh repo-local MCP config: ${error?.message || error}`,
52094
- meshId,
52095
- cliType,
52096
- workspace
52097
- };
52098
- }
52099
- }
52100
- }
52101
- const cliCmdArgs = [];
52102
- const cliCmdEnv = {};
52103
- let cliCmdContextFilePath;
52104
- if (cliCmdSystemPrompt) {
52105
- const { applyMeshCoordinatorSystemPromptInjection: applyMeshCoordinatorSystemPromptInjection2 } = await Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports));
52106
- const effect = applyMeshCoordinatorSystemPromptInjection2(
52107
- cliCmdSystemPrompt,
52108
- providerMeta?.meshCoordinator?.systemPromptInjection,
52109
- { cliArgs: cliCmdArgs, launchEnv: cliCmdEnv, workspace, cliType }
52110
- );
52111
- cliCmdContextFilePath = effect.contextFilePath;
52112
- }
52113
- const cliCmdLaunch = await this.deps.cliManager.handleCliCommand("launch_cli", {
52114
- cliType,
52115
- dir: workspace,
52116
- cliArgs: cliCmdArgs.length > 0 ? cliCmdArgs : void 0,
52117
- env: Object.keys(cliCmdEnv).length > 0 ? cliCmdEnv : void 0,
52118
- settings: { meshCoordinatorFor: meshId }
52119
- });
52120
- if (cliCmdLaunch?.success && cliCmdContextFilePath) {
52121
- const stripPath = cliCmdContextFilePath;
52122
- setTimeout(() => {
52123
- void Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports)).then(({ stripCoordinatorWrapperFile: stripCoordinatorWrapperFile2 }) => {
52124
- stripCoordinatorWrapperFile2(stripPath);
52125
- LOG.info("MeshCoordinator", `Stripped wrapper from ${stripPath} after launch settle (cli_command)`);
52126
- }).catch(() => {
52127
- });
52128
- }, 5e3);
52129
- }
52130
- if (!cliCmdLaunch?.success) {
52131
- return { success: false, error: cliCmdLaunch?.error || "Failed to launch CLI session" };
52132
- }
52133
- LOG.info("MeshCoordinator", `Launched ${cliType} coordinator (cli_command) for mesh ${meshId}`);
52134
- const cliCmdSessionId = cliCmdLaunch.sessionId || cliCmdLaunch.id;
52135
- if (cliCmdSessionId) {
52136
- const cliCmdInjectionDecl = providerMeta?.meshCoordinator?.systemPromptInjection;
52137
- registerMeshCoordinator({
52138
- meshId,
52139
- sessionId: cliCmdSessionId,
52140
- workspace,
52141
- startedAt: Date.now(),
52142
- cliType,
52143
- systemPrompt: cliCmdSystemPrompt || void 0,
52144
- extraSystemPrompt: extraSystemPrompt || void 0,
52145
- injection: cliCmdInjectionDecl ? {
52146
- mode: cliCmdInjectionDecl.mode,
52147
- target: "flag" in cliCmdInjectionDecl ? cliCmdInjectionDecl.flag : "name" in cliCmdInjectionDecl ? cliCmdInjectionDecl.name : "path" in cliCmdInjectionDecl ? cliCmdInjectionDecl.path : void 0
52148
- } : void 0
52149
- });
52150
- }
52151
- try {
52152
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
52153
- appendLedgerEntry2(meshId, {
52154
- kind: "coordinator_started",
52155
- sessionId: cliCmdSessionId,
52156
- providerType: cliType,
52157
- payload: { workspace }
52158
- });
52159
- } catch {
52160
- }
52161
- return {
52162
- success: true,
52163
- meshId,
52164
- cliType,
52165
- workspace,
52166
- sessionId: cliCmdSessionId,
52167
- mcpRegistered: mcpRegistrationOk
52168
- };
52169
- }
52170
- const configFormat = coordinatorSetup.configFormat;
52171
- if (configFormat !== "claude_mcp_json" && configFormat !== "hermes_config_yaml") {
52172
- return {
52173
- success: false,
52174
- code: "mesh_coordinator_unsupported",
52175
- error: `Unsupported auto-import MCP config format: ${String(coordinatorSetup.configFormat)}`,
52176
- meshId,
52177
- cliType,
52178
- workspace
52179
- };
52180
- }
52181
- let systemPrompt = "";
52182
- try {
52183
- systemPrompt = buildCoordinatorSystemPrompt2({ mesh, coordinatorCliType: cliType, userInstruction: extraSystemPrompt || void 0, missionSection: buildMissionSectionBestEffort(mesh.id) });
52184
- } catch (error) {
52185
- const message = error?.message || String(error);
52186
- LOG.error("MeshCoordinator", `Failed to build coordinator prompt: ${message}`);
52187
- return {
52188
- success: false,
52189
- code: "mesh_coordinator_prompt_failed",
52190
- error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
52191
- meshId,
52192
- cliType,
52193
- workspace
52194
- };
52195
- }
52196
- const { existsSync: existsSync47, readFileSync: readFileSync38, writeFileSync: writeFileSync24, copyFileSync: copyFileSync4, mkdirSync: mkdirSync21 } = await import("fs");
52197
- const { dirname: dirname17 } = await import("path");
52198
- const mcpConfigPath = coordinatorSetup.configPath;
52199
- const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
52200
- let hermesBaseConfig = null;
52201
- if (hermesManualFallback) {
52202
- try {
52203
- hermesBaseConfig = loadHermesCoordinatorBaseConfig(mcpConfigPath);
52204
- } catch (error) {
52205
- const message = `Failed to parse Hermes base config for automatic coordinator setup: ${error?.message || error}`;
52206
- LOG.error("MeshCoordinator", message);
52207
- return { success: false, code: "mesh_coordinator_config_parse_failed", error: message, meshId, cliType, workspace };
52208
- }
52209
- }
52210
- const returnManualFallback = (message) => ({
52211
- success: false,
52212
- code: "mesh_coordinator_manual_mcp_setup_required",
52213
- error: message,
52214
- meshId,
52215
- cliType,
52216
- workspace,
52217
- meshCoordinatorSetup: hermesManualFallback
52218
- });
52219
- const mcpServerEntry = {
52220
- command: coordinatorSetup.mcpServer.command,
52221
- args: coordinatorSetup.mcpServer.args
52222
- };
52223
- if (args?.inlineMesh) {
52224
- const modeArgIndex = coordinatorSetup.mcpServer.args.findIndex((value) => value === "--mode");
52225
- const mcpTransport = modeArgIndex >= 0 ? coordinatorSetup.mcpServer.args[modeArgIndex + 1] : "ipc";
52226
- mcpServerEntry.env = {
52227
- ADHDEV_INLINE_MESH: JSON.stringify(mesh),
52228
- ADHDEV_MCP_TRANSPORT: mcpTransport === "local" ? "local" : "ipc"
52229
- };
52230
- }
52231
- try {
52232
- mkdirSync21(dirname17(mcpConfigPath), { recursive: true });
52233
- } catch (error) {
52234
- const message = `Could not prepare MCP config path for automatic setup: ${error?.message || error}`;
52235
- LOG.error("MeshCoordinator", message);
52236
- if (hermesManualFallback) return returnManualFallback(message);
52237
- return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
52238
- }
52239
- const hadExistingMcpConfig = existsSync47(mcpConfigPath);
52240
- let existingMcpConfig = hermesBaseConfig?.config || {};
52241
- if (hermesBaseConfig) {
52242
- copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname17(mcpConfigPath));
52243
- }
52244
- if (hadExistingMcpConfig) {
52245
- try {
52246
- const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync38(mcpConfigPath, "utf-8"), configFormat);
52247
- const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
52248
- existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
52249
- copyFileSync4(mcpConfigPath, mcpConfigPath + ".backup");
52250
- } catch (error) {
52251
- LOG.error("MeshCoordinator", `Failed to parse existing MCP config ${mcpConfigPath}: ${error?.message || error}`);
52252
- return {
52253
- success: false,
52254
- code: "mesh_coordinator_config_parse_failed",
52255
- error: `Failed to parse existing MCP config at ${mcpConfigPath}`
52256
- };
52257
- }
52258
- }
52259
- const mcpServersKey = getMcpServersKey(configFormat);
52260
- const existingServers = existingMcpConfig[mcpServersKey];
52261
- const mcpConfig = {
52262
- ...existingMcpConfig,
52263
- [mcpServersKey]: {
52264
- ...existingServers && typeof existingServers === "object" && !Array.isArray(existingServers) ? existingServers : {},
52265
- [coordinatorSetup.serverName]: mcpServerEntry
52266
- }
52267
- };
52268
- try {
52269
- writeFileSync24(mcpConfigPath, serializeMeshCoordinatorMcpConfig(mcpConfig, configFormat), "utf-8");
52270
- } catch (error) {
52271
- const message = `Could not write MCP config for automatic setup: ${error?.message || error}`;
52272
- LOG.error("MeshCoordinator", message);
52273
- if (hermesManualFallback) return returnManualFallback(message);
52274
- return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
52275
- }
52276
- LOG.info("MeshCoordinator", `Wrote ${mcpConfigPath} with ${coordinatorSetup.serverName} server`);
52277
- const cliArgs = [];
52278
- const launchEnv = {};
52279
- if (configFormat === "hermes_config_yaml") {
52280
- launchEnv.HERMES_HOME = dirname17(mcpConfigPath);
52281
- launchEnv.HERMES_IGNORE_USER_CONFIG = "";
52282
- }
52283
- let autoImportContextFilePath;
52284
- if (systemPrompt) {
52285
- const { applyMeshCoordinatorSystemPromptInjection: applyMeshCoordinatorSystemPromptInjection2 } = await Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports));
52286
- const effect = applyMeshCoordinatorSystemPromptInjection2(
52287
- systemPrompt,
52288
- providerMeta?.meshCoordinator?.systemPromptInjection,
52289
- { cliArgs, launchEnv, workspace, cliType }
52290
- );
52291
- autoImportContextFilePath = effect.contextFilePath;
52292
- }
52293
- if (cliType === "claude-cli") {
52294
- cliArgs.push("--mcp-config", coordinatorSetup.configPath);
52295
- }
52296
- const launchResult = await this.deps.cliManager.handleCliCommand("launch_cli", {
52297
- cliType,
52298
- dir: workspace,
52299
- cliArgs: cliArgs.length > 0 ? cliArgs : void 0,
52300
- env: Object.keys(launchEnv).length > 0 ? launchEnv : void 0,
52301
- settings: {
52302
- meshCoordinatorFor: meshId
52303
- }
52304
- });
52305
- if (launchResult?.success && autoImportContextFilePath) {
52306
- const stripPath = autoImportContextFilePath;
52307
- setTimeout(() => {
52308
- void Promise.resolve().then(() => (init_mesh_coordinator(), mesh_coordinator_exports)).then(({ stripCoordinatorWrapperFile: stripCoordinatorWrapperFile2 }) => {
52309
- stripCoordinatorWrapperFile2(stripPath);
52310
- LOG.info("MeshCoordinator", `Stripped wrapper from ${stripPath} after launch settle (auto_import)`);
52311
- }).catch(() => {
52312
- });
52313
- }, 5e3);
52314
- }
52315
- if (!launchResult?.success) {
52316
- return { success: false, error: launchResult?.error || "Failed to launch CLI session" };
52317
- }
52318
- LOG.info("MeshCoordinator", `Launched ${cliType} coordinator for mesh ${meshId} in ${workspace}`);
52319
- const launchSessionId = launchResult.sessionId || launchResult.id;
52320
- if (launchSessionId) {
52321
- const autoImportInjectionDecl = providerMeta?.meshCoordinator?.systemPromptInjection;
52322
- registerMeshCoordinator({
52323
- meshId,
52324
- sessionId: launchSessionId,
52325
- workspace,
52326
- startedAt: Date.now(),
52327
- cliType,
52328
- systemPrompt: systemPrompt || void 0,
52329
- extraSystemPrompt: extraSystemPrompt || void 0,
52330
- mcpConfigPath,
52331
- injection: autoImportInjectionDecl ? {
52332
- mode: autoImportInjectionDecl.mode,
52333
- target: "flag" in autoImportInjectionDecl ? autoImportInjectionDecl.flag : "name" in autoImportInjectionDecl ? autoImportInjectionDecl.name : "path" in autoImportInjectionDecl ? autoImportInjectionDecl.path : void 0
52334
- } : void 0
52335
- });
52336
- }
52337
- try {
52338
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
52339
- appendLedgerEntry2(meshId, {
52340
- kind: "coordinator_started",
52341
- sessionId: launchSessionId,
52342
- providerType: cliType,
52343
- payload: { workspace }
52344
- });
52345
- } catch {
52346
- }
52347
- return {
52348
- success: true,
52349
- meshId,
52350
- cliType,
52351
- workspace,
52352
- sessionId: launchSessionId,
52353
- mcpConfigWritten: true
52354
- };
52355
- } catch (e) {
52356
- LOG.error("MeshCoordinator", `Failed: ${e.message}`);
52357
- return { success: false, error: e.message };
52358
- }
52359
- }
52360
- case "mesh_status": {
52361
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
52362
- if (!meshId) return { success: false, error: "meshId required" };
52363
- try {
52364
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
52365
- const mesh = meshRecord?.mesh;
52366
- if (!mesh) return { success: false, error: "Mesh not found" };
52367
- const meshHost = resolveMeshHostStatus(mesh);
52368
- const refreshRequested = args?.refresh === true || args?.forceRefresh === true;
52369
- const verboseMissions = args?.verbose === true || args?.compact === false;
52370
- const peekScope = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : this.deps.statusInstanceId || void 0;
52371
- const pendingCoordinatorEventCount = getPendingMeshCoordinatorEvents(meshId, peekScope).length;
52372
- const hadAggregateCache = this.aggregateMeshStatusCache.has(meshId);
52373
- if (!refreshRequested && !verboseMissions && pendingCoordinatorEventCount === 0) {
52374
- const cachedStatus = this.getCachedAggregateMeshStatus(meshId, mesh, { requireDirectPeerTruth: args?.requireDirectPeerTruth === true });
52375
- if (cachedStatus) {
52376
- logRepoMeshStatusDebug("return_cached", {
52377
- meshId,
52378
- command: "mesh_status",
52379
- refreshRequested,
52380
- summary: summarizeRepoMeshStatusDebug(cachedStatus)
52381
- });
52382
- return cachedStatus;
52383
- }
52384
- }
52385
- const refreshReason = refreshRequested ? "explicit_refresh" : pendingCoordinatorEventCount > 0 ? "pending_coordinator_events" : hadAggregateCache ? "stale_pending_cache_refresh" : "cold_cache_miss";
52386
- const { getMeshQueueStats: getMeshQueueStats2, getQueue: getQueue2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
52387
- const queue = getQueue2(meshId);
52388
- const queueSummary = getMeshQueueStats2(meshId);
52389
- const { readLedgerEntries: readLedgerEntries2, getLedgerSummary: getLedgerSummary2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
52390
- const ledgerEntries = readLedgerEntries2(meshId, { tail: 20 });
52391
- const asyncRefineLedgerEntries = readLedgerEntries2(meshId, { tail: 100 });
52392
- const ledgerSummary = getLedgerSummary2(meshId);
52393
- const sessionHostRecords = this.deps.sessionHostControl?.listSessions ? await this.deps.sessionHostControl.listSessions().catch(() => []) : [];
52394
- const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
52395
- const localMachineId = loadConfig().machineId || "";
52396
- const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
52397
- const meshGitProbeCache = this.meshGitProbeCache;
52398
- const directTruth = requireDirectPeerTruth ? await hydrateInlineMeshDirectTruth({
52399
- mesh,
52400
- meshSource: meshRecord.source,
52401
- dispatchMeshCommand: this.deps.dispatchMeshCommand,
52402
- getMeshPeerConnectionStatus: this.deps.getMeshPeerConnectionStatus,
52403
- statusInstanceId: this.deps.statusInstanceId,
52404
- localMachineId,
52405
- // Standing-state model: only an explicit refresh fans
52406
- // out a blocking peer git probe. Default loads return
52407
- // held truth so one slow peer can't block the graph.
52408
- probeRemotePeers: refreshRequested,
52409
- probeCache: meshGitProbeCache
52410
- }) : {
52411
- directEvidenceCount: 0,
52412
- localConfirmedCount: 0,
52413
- peerAttemptedCount: 0,
52414
- peerConfirmedCount: 0,
52415
- standingEvidenceCount: 0,
52416
- unavailableNodeIds: [],
52417
- deadNodeIds: []
52418
- };
52419
- const passivePeerTruthNotAttempted = requireDirectPeerTruth && !refreshRequested && directTruth.directEvidenceCount > 0 && directTruth.peerAttemptedCount === 0;
52420
- const effectiveDirectTruth = passivePeerTruthNotAttempted ? { ...directTruth, unavailableNodeIds: [] } : directTruth;
52421
- const unavailableDirectTruthNodeIds = new Set(effectiveDirectTruth.unavailableNodeIds);
52422
- const unavailableNodesAreOnlyRemovedWorktrees = unavailableDirectTruthNodeIds.size > 0 && Array.isArray(mesh.nodes) && mesh.nodes.filter((node) => unavailableDirectTruthNodeIds.has(normalizeMeshNodeId(node) ?? "")).every((node) => node?.isLocalWorktree === true);
52423
- const directTruthSatisfied = !requireDirectPeerTruth || !refreshRequested || effectiveDirectTruth.directEvidenceCount > 0 && (effectiveDirectTruth.unavailableNodeIds.length === 0 || unavailableNodesAreOnlyRemovedWorktrees);
52424
- if (requireDirectPeerTruth && refreshRequested && !directTruthSatisfied) {
52425
- const failureResult = {
52426
- success: false,
52427
- code: "mesh_direct_peer_truth_unavailable",
52428
- error: "Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct mesh_status probes succeed.",
52429
- sourceOfTruth: {
52430
- membership: meshRecord.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
52431
- coordinatorOwnsLiveTruth: false,
52432
- currentStatus: "direct_peer_truth_unavailable",
52433
- directPeerTruth: {
52434
- required: true,
52435
- satisfied: false,
52436
- directEvidenceCount: directTruth.directEvidenceCount,
52437
- localConfirmedCount: directTruth.localConfirmedCount,
52438
- peerAttemptedCount: directTruth.peerAttemptedCount,
52439
- peerConfirmedCount: directTruth.peerConfirmedCount,
52440
- unavailableNodeIds: directTruth.unavailableNodeIds
52441
- }
52442
- }
52443
- };
52444
- logRepoMeshStatusDebug("direct_truth_unavailable", {
52445
- meshId,
52446
- command: "mesh_status",
52447
- refreshRequested,
52448
- meshSource: meshRecord.source,
52449
- directTruth
52450
- });
52451
- return failureResult;
52452
- }
52453
- const directTruthUnavailableNodeIds = new Set(effectiveDirectTruth.unavailableNodeIds);
52454
- const coordinatorHostname = osHostname();
52455
- const selectedCoordinatorNodeId = readStringValue(
52456
- mesh.coordinator?.preferredNodeId,
52457
- normalizeMeshNodeId(mesh.nodes?.[0])
52458
- );
52459
- const inlineCoordinatorNodeId = meshRecord?.inline && Array.isArray(mesh.nodes) ? selectedCoordinatorNodeId : void 0;
52460
- const refreshedAt = (/* @__PURE__ */ new Date()).toISOString();
52461
- const nodeStatuses = [];
52462
- for (const [nodeIndex, node] of (mesh.nodes || []).entries()) {
52463
- const nodeId = normalizeMeshNodeId(node) ?? "";
52464
- const daemonId = readStringValue(node.daemonId);
52465
- const nodeMachineId = readMeshNodeMachineId(node);
52466
- const nodeHostname = readMeshNodeHostname(node);
52467
- const providerPriority = readProviderPriorityFromPolicy(node.policy);
52468
- const configuredCoordinatorNode = Boolean(
52469
- nodeId && selectedCoordinatorNodeId && nodeId === selectedCoordinatorNodeId
52470
- );
52471
- const sparseConfiguredCoordinatorNode = configuredCoordinatorNode && !daemonId && !nodeMachineId && !nodeHostname;
52472
- const isSelfNode = Boolean(
52473
- nodeId && inlineCoordinatorNodeId && nodeId === inlineCoordinatorNodeId
52474
- ) || Boolean(
52475
- daemonId && (daemonIdsEquivalent(daemonId, localMachineId) || daemonIdsEquivalent(daemonId, this.deps.statusInstanceId))
52476
- ) || Boolean(meshRecord?.inline && nodeIndex === 0) || sparseConfiguredCoordinatorNode;
52477
- const machineIdentity = buildMeshNodeMachineIdentity(node, {
52478
- localMachineId,
52479
- localDaemonId: this.deps.statusInstanceId,
52480
- coordinatorHostname,
52481
- isSelfNode
52482
- });
52483
- const status = {
52484
- nodeId,
52485
- machineLabel: buildMeshNodeDisplayLabel(node, nodeId, providerPriority),
52486
- labelSource: readStringValue(node.machineLabel, node.machine_label, node.machineNickname, node.machine_nickname, node.alias) ? "explicit_metadata" : "workspace_host_provider_context",
52487
- workspace: node.workspace,
52488
- repoRoot: node.repoRoot,
52489
- isLocalWorktree: node.isLocalWorktree,
52490
- worktreeBranch: node.worktreeBranch,
52491
- role: normalizeMeshDaemonRole(node.role) || (meshHost.hostNodeId && nodeId === meshHost.hostNodeId ? "host" : void 0),
52492
- daemonId,
52493
- machineId: nodeMachineId || node.machineId,
52494
- machine: machineIdentity,
52495
- machineStatus: node.machineStatus,
52496
- health: "unknown",
52497
- providers: node.providers || [],
52498
- providerPriority,
52499
- activeSessions: [],
52500
- activeSessionDetails: [],
52501
- launchReady: false
52502
- };
52503
- if (isSelfNode) {
52504
- status.connection = {
52505
- perspective: "selected_coordinator",
52506
- source: "mesh_peer_status",
52507
- state: "self",
52508
- transport: "local",
52509
- reported: true,
52510
- reason: "Selected coordinator daemon",
52511
- lastStateChangeAt: refreshedAt
52512
- };
52513
- } else if (daemonId) {
52514
- const connection = this.deps.getMeshPeerConnectionStatus?.(daemonId);
52515
- status.connection = connection ?? {
52516
- perspective: "selected_coordinator",
52517
- source: "not_reported",
52518
- state: "unknown",
52519
- transport: "unknown",
52520
- reported: false,
52521
- reason: "No live mesh peer telemetry reported by the selected coordinator yet."
52522
- };
52523
- } else {
52524
- status.connection = {
52525
- perspective: "selected_coordinator",
52526
- source: "not_reported",
52527
- state: "unknown",
52528
- transport: "unknown",
52529
- reported: false,
52530
- reason: "Node has no daemon id, so mesh transport cannot be reported from the selected coordinator."
52531
- };
52532
- }
52533
- const matchedLiveSessionRecords = collectLiveMeshSessionRecords({
52534
- meshId,
52535
- node,
52536
- nodeId,
52537
- liveSessionRecords: liveMeshSessions,
52538
- allowCoordinatorSession: nodeId === selectedCoordinatorNodeId
52539
- });
52540
- const workspace = readLiveMeshNodeWorkspace({
52541
- meshId,
52542
- nodeId,
52543
- liveSessionRecords: matchedLiveSessionRecords,
52544
- allowCoordinatorSession: nodeId === selectedCoordinatorNodeId
52545
- }) || (typeof node.workspace === "string" ? node.workspace : "");
52546
- status.workspace = workspace || node.workspace;
52547
- if (matchedLiveSessionRecords.length > 0) {
52548
- const sessionIds = matchedLiveSessionRecords.map((record) => typeof record?.sessionId === "string" ? record.sessionId : "").filter(Boolean);
52549
- const providerTypes = matchedLiveSessionRecords.map((record) => readStringValue(record?.providerType)).filter(Boolean);
52550
- status.activeSessions = sessionIds;
52551
- status.activeSessionDetails = matchedLiveSessionRecords.map(summarizeMeshSessionRecord);
52552
- if (providerTypes.length > 0) {
52553
- status.providers = Array.from(/* @__PURE__ */ new Set([...Array.isArray(status.providers) ? status.providers : [], ...providerTypes]));
52554
- }
52555
- }
52556
- if (workspace) {
52557
- if (!fs27.existsSync(workspace)) {
52558
- const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
52559
- let remoteProbeApplied = false;
52560
- if (inlineTransitGit) {
52561
- status.git = inlineTransitGit;
52562
- status.health = inlineTransitGit.isGitRepo ? deriveMeshNodeHealthFromGit(inlineTransitGit) : "degraded";
52563
- const connection = readObjectRecord(status.connection);
52564
- const connectionState = readStringValue(connection.state);
52565
- const connectionReported = readBooleanValue(connection.reported) ?? false;
52566
- if (!connectionReported || connectionState === "unknown") {
52567
- status.connection = buildLivePeerGitConnection(connection, refreshedAt);
52568
- }
52569
- remoteProbeApplied = true;
52570
- } else if (refreshRequested && !isSelfNode && daemonId && this.deps.dispatchMeshCommand && !directTruthUnavailableNodeIds.has(nodeId)) {
52571
- const runNodeProbe = () => probeRemoteMeshGitStatusWithRetry({
52572
- dispatchMeshCommand: this.deps.dispatchMeshCommand,
52573
- daemonId,
52574
- workspace,
52575
- timeoutMs: MESH_DIRECT_PROBE_TIMEOUT_MS,
52576
- retryTimeoutMs: MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS,
52577
- getConnection: this.deps.getMeshPeerConnectionStatus,
52578
- onConnection: (connection) => {
52579
- status.connection = connection;
52580
- }
52581
- });
52582
- const remoteGit = await meshGitProbeCache.probe(daemonId, workspace, runNodeProbe);
52583
- if (remoteGit) {
52584
- status.git = remoteGit;
52585
- status.health = remoteGit.isGitRepo ? deriveMeshNodeHealthFromGit(remoteGit) : "degraded";
52586
- const connection = readObjectRecord(status.connection);
52587
- const connectionState = readStringValue(connection.state);
52588
- const connectionReported = readBooleanValue(connection.reported) ?? false;
52589
- if (!connectionReported || connectionState === "unknown") {
52590
- status.connection = buildLivePeerGitConnection(connection, refreshedAt);
52591
- }
52592
- const reporter = recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
52593
- persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
52594
- remoteProbeApplied = true;
52595
- }
52596
- }
52597
- if (!remoteProbeApplied) {
52598
- const connectionState = readStringValue(status.connection?.state);
52599
- const pendingPeerGitProbe = !inlineTransitGit && !isSelfNode && !!daemonId && (readStringValue(status.machineStatus) === "online" || readStringValue(status.health) === "online" || connectionState === "connecting" || connectionState === "connected" || connectionState === "unknown");
52600
- if (pendingPeerGitProbe) {
52601
- status.gitProbePending = true;
52602
- status.health = "unknown";
52603
- }
52604
- if (applyCachedInlineMeshNodeStatus(
52605
- status,
52606
- node,
52607
- pendingPeerGitProbe ? { skipGit: true, skipError: true, skipHealth: true } : void 0
52608
- )) {
52609
- applyInlineMeshBranchConvergence(mesh, node, status);
52610
- finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
52611
- nodeStatuses.push(status);
52612
- continue;
52613
- }
52614
- if (meshRecord?.source === "inline_cache" && !isSelfNode) {
52615
- applyInlineMeshBranchConvergence(mesh, node, status);
52616
- finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
52617
- nodeStatuses.push(status);
52618
- continue;
52619
- }
52620
- }
52621
- } else {
52622
- try {
52623
- const gitStatus = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
52624
- status.git = gitStatus;
52625
- const reporter = recordInlineMeshDirectGitTruth(node, gitStatus, "selected_coordinator_local_git");
52626
- persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
52627
- if (gitStatus.isGitRepo) {
52628
- status.health = deriveMeshNodeHealthFromGit(gitStatus);
52629
- } else {
52630
- status.health = "degraded";
52631
- if (gitStatus.error && !status.error) status.error = gitStatus.error;
52632
- }
52633
- } catch {
52634
- if (!applyCachedInlineMeshNodeStatus(status, node)) {
52635
- status.health = "degraded";
52636
- }
52637
- }
52638
- }
52639
- } else {
52640
- applyCachedInlineMeshNodeStatus(status, node);
52641
- }
52642
- applyInlineMeshBranchConvergence(mesh, node, status);
52643
- finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
52644
- nodeStatuses.push(status);
52645
- }
52646
- const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : this.deps.statusInstanceId || void 0;
52647
- const pendingCoordinatorEvents = getPendingMeshCoordinatorEvents(meshId, callerCoordinatorDaemonId);
52648
- const unroutableDeliveries = getRecentUnroutableDeliveries();
52649
- const previewFreshness = (() => {
52650
- const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs27.existsSync(candidate));
52651
- return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
52652
- })();
52653
- const asyncRefineJobs = buildMeshAsyncRefineJobs({
52654
- meshId,
52655
- ledgerEntries: asyncRefineLedgerEntries,
52656
- pendingEvents: [...pendingCoordinatorEvents]
52657
- });
52658
- const historicalSessions = buildHistoricalMeshSessions({
52659
- meshId,
52660
- nodes: mesh.nodes || [],
52661
- liveSessionRecords: liveMeshSessions
52662
- });
52663
- const { getMeshStatusMissionSummaries: getMeshStatusMissionSummaries2 } = await Promise.resolve().then(() => (init_mesh_missions(), mesh_missions_exports));
52664
- const missions = getMeshStatusMissionSummaries2(meshId, { verbose: verboseMissions, withStats: true });
52665
- const statusResult = {
52666
- success: true,
52667
- meshId: mesh.id,
52668
- meshName: mesh.name,
52669
- repoIdentity: mesh.repoIdentity,
52670
- defaultBranch: mesh.defaultBranch,
52671
- refreshedAt,
52672
- meshHost,
52673
- sourceOfTruth: {
52674
- membership: meshRecord?.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord?.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
52675
- coordinatorOwnsLiveTruth: directTruthSatisfied,
52676
- meshHost: {
52677
- owner: "mesh_host_daemon",
52678
- localRole: meshHost.role,
52679
- hostDaemonId: meshHost.hostDaemonId,
52680
- hostNodeId: meshHost.hostNodeId,
52681
- hostAddress: meshHost.hostAddress
52682
- },
52683
- ...requireDirectPeerTruth ? {
52684
- currentStatus: directTruthSatisfied ? "live_git_and_session_probes" : "direct_peer_truth_unavailable",
52685
- directPeerTruth: {
52686
- required: true,
52687
- satisfied: directTruthSatisfied,
52688
- directEvidenceCount: effectiveDirectTruth.directEvidenceCount,
52689
- localConfirmedCount: effectiveDirectTruth.localConfirmedCount,
52690
- peerAttemptedCount: effectiveDirectTruth.peerAttemptedCount,
52691
- peerConfirmedCount: effectiveDirectTruth.peerConfirmedCount,
52692
- unavailableNodeIds: effectiveDirectTruth.unavailableNodeIds,
52693
- partialNodeFailures: effectiveDirectTruth.unavailableNodeIds
52694
- }
52695
- } : {},
52696
- historicalEvidenceOnly: ["recoveryHints", "ledger.summary", "queue.summary", "historicalSessions"]
52697
- },
52698
- branchConvergenceSummary: summarizeInlineMeshBranchConvergence(nodeStatuses),
52699
- ...previewFreshness ? { previewFreshness, deployFreshness: previewFreshness } : {},
52700
- nodes: nodeStatuses,
52701
- queue: { tasks: queue, summary: queueSummary },
52702
- ledger: { entries: ledgerEntries, summary: ledgerSummary },
52703
- ...missions.length > 0 ? { missions } : {},
52704
- ...asyncRefineJobs.length > 0 ? { asyncRefineJobs } : {},
52705
- ...historicalSessions ? { historicalSessions } : {},
52706
- ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
52707
- ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {},
52708
- activeRefineJobs: Array.from(this.runningRefineJobs.values()).filter((job) => job.meshId === meshId).map((job) => ({
52709
- jobId: job.jobId,
52710
- nodeId: job.targetNodeId,
52711
- workspace: job.workspace,
52712
- startedAt: job.startedAt,
52713
- status: job.status,
52714
- targetCoordinatorDaemonId: job.targetCoordinatorDaemonId
52715
- }))
52716
- };
52717
- const { pendingCoordinatorEvents: _pendingCoordinatorEvents, unroutableDeliveries: _unroutableDeliveries, ...cacheableStatusResult } = statusResult;
52718
- const rememberedStatus = verboseMissions ? cacheableStatusResult : this.rememberAggregateMeshStatus(meshId, cacheableStatusResult, refreshReason);
52719
- const returnedStatus = {
52720
- ...rememberedStatus,
52721
- ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
52722
- ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {}
52723
- };
52724
- logRepoMeshStatusDebug("return_live", {
52725
- meshId,
52726
- command: "mesh_status",
52727
- refreshRequested,
52728
- refreshReason,
52729
- meshSource: meshRecord.source,
52730
- directTruth,
52731
- summary: summarizeRepoMeshStatusDebug(returnedStatus)
52732
- });
52733
- return returnedStatus;
52734
- } catch (e) {
52735
- return { success: false, error: e.message };
52736
- }
52737
- }
52738
- case "get_mesh_review_inbox": {
52739
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
52740
- if (!meshId) return { success: false, error: "meshId required" };
52741
- try {
52742
- const { deriveMeshReviewInboxItems: deriveMeshReviewInboxItems2 } = await Promise.resolve().then(() => (init_mesh_review_inbox(), mesh_review_inbox_exports));
52743
- const { readLedgerEntries: readLedgerEntries2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
52744
- const { getGitDiffSummary: getGitDiffSummary2 } = await Promise.resolve().then(() => (init_git_diff(), git_diff_exports));
52745
- const { existsSync: existsSync47 } = await import("fs");
52746
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
52747
- const mesh = meshRecord?.mesh;
52748
- if (!mesh) return { success: false, error: "Mesh not found" };
52749
- const inlineNodes = args?.inlineMesh && Array.isArray(args.inlineMesh?.nodes) ? args.inlineMesh.nodes : null;
52750
- let cachedStatus = !inlineNodes ? this.getCachedAggregateMeshStatus(meshId, mesh, {}) : null;
52751
- if (!cachedStatus && !inlineNodes) {
52752
- const freshStatus = await this.execute("mesh_status", {
52753
- meshId,
52754
- inlineMesh: args?.inlineMesh,
52755
- refresh: true
52756
- }, "get_mesh_review_inbox");
52757
- cachedStatus = freshStatus?.success !== false ? freshStatus : null;
52758
- }
52759
- const nodeStatuses = inlineNodes ? inlineNodes : Array.isArray(cachedStatus?.nodes) ? cachedStatus.nodes : Array.isArray(mesh.nodes) ? mesh.nodes : [];
52760
- const ledgerEntries = readLedgerEntries2(meshId, { tail: 300 });
52761
- const derivation = deriveMeshReviewInboxItems2({ nodes: nodeStatuses, ledgerEntries });
52762
- for (const item of derivation.items) {
52763
- const workspace = item.workspace;
52764
- if (!workspace || !existsSync47(workspace)) continue;
52765
- const baseRef = item.defaultBranch ? `origin/${item.defaultBranch}` : "origin/main";
52766
- try {
52767
- const diffResult = await getGitDiffSummary2(workspace, { baseRef, maxFiles: 100 });
52768
- if (diffResult.isGitRepo) {
52769
- item.diffSummary = {
52770
- baseRef,
52771
- files: diffResult.files.map((f) => ({
52772
- path: f.path,
52773
- status: f.status,
52774
- insertions: f.insertions,
52775
- deletions: f.deletions,
52776
- binary: f.binary,
52777
- oldPath: f.oldPath
52778
- })),
52779
- totalFiles: diffResult.files.length,
52780
- totalInsertions: diffResult.totalInsertions,
52781
- totalDeletions: diffResult.totalDeletions,
52782
- truncated: diffResult.truncated,
52783
- ...diffResult.error ? { error: diffResult.error } : {}
52784
- };
52785
- }
52786
- } catch {
52787
- item.diffSummary = null;
52788
- }
52789
- }
52790
- return {
52791
- success: true,
52792
- meshId,
52793
- inbox: derivation.items,
52794
- remoteNodesExcluded: derivation.remoteNodesExcluded,
52795
- excludedRemoteNodeIds: derivation.excludedRemoteNodeIds
52796
- };
52797
- } catch (e) {
52798
- return { success: false, error: e.message };
52799
- }
52800
- }
52801
- default:
52802
- break;
52982
+ const highFamilyHandler = highFamilyRegistry.get(cmd);
52983
+ if (highFamilyHandler) {
52984
+ return await highFamilyHandler(this.buildHighFamilyContext(), args);
52803
52985
  }
52804
52986
  return null;
52805
52987
  }
@@ -54525,7 +54707,7 @@ init_io_contracts();
54525
54707
  init_chat_message_normalization();
54526
54708
 
54527
54709
  // src/providers/version-archive.ts
54528
- import * as fs28 from "fs";
54710
+ import * as fs30 from "fs";
54529
54711
  import * as path37 from "path";
54530
54712
  import * as os28 from "os";
54531
54713
  import { platform as platform8 } from "os";
@@ -54539,8 +54721,8 @@ var VersionArchive = class {
54539
54721
  }
54540
54722
  load() {
54541
54723
  try {
54542
- if (fs28.existsSync(ARCHIVE_PATH)) {
54543
- this.history = JSON.parse(fs28.readFileSync(ARCHIVE_PATH, "utf-8"));
54724
+ if (fs30.existsSync(ARCHIVE_PATH)) {
54725
+ this.history = JSON.parse(fs30.readFileSync(ARCHIVE_PATH, "utf-8"));
54544
54726
  }
54545
54727
  } catch {
54546
54728
  this.history = {};
@@ -54577,8 +54759,8 @@ var VersionArchive = class {
54577
54759
  }
54578
54760
  save() {
54579
54761
  try {
54580
- fs28.mkdirSync(path37.dirname(ARCHIVE_PATH), { recursive: true });
54581
- fs28.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
54762
+ fs30.mkdirSync(path37.dirname(ARCHIVE_PATH), { recursive: true });
54763
+ fs30.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
54582
54764
  } catch {
54583
54765
  }
54584
54766
  }
@@ -54603,8 +54785,8 @@ function findBinary2(name) {
54603
54785
  for (const ext of exes) {
54604
54786
  const fullPath = path37.join(p, name + ext);
54605
54787
  try {
54606
- if (fs28.existsSync(fullPath)) {
54607
- const stat2 = fs28.statSync(fullPath);
54788
+ if (fs30.existsSync(fullPath)) {
54789
+ const stat2 = fs30.statSync(fullPath);
54608
54790
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
54609
54791
  return fullPath;
54610
54792
  }
@@ -54651,9 +54833,9 @@ function checkPathExists2(paths) {
54651
54833
  if (p.includes("*")) {
54652
54834
  const home = os28.homedir();
54653
54835
  const resolved = p.replace(/\*/g, home.split(path37.sep).pop() || "");
54654
- if (fs28.existsSync(resolved)) return resolved;
54836
+ if (fs30.existsSync(resolved)) return resolved;
54655
54837
  } else {
54656
- if (fs28.existsSync(p)) return p;
54838
+ if (fs30.existsSync(p)) return p;
54657
54839
  }
54658
54840
  }
54659
54841
  return null;
@@ -54661,7 +54843,7 @@ function checkPathExists2(paths) {
54661
54843
  async function getMacAppVersion(appPath) {
54662
54844
  if (platform8() !== "darwin" || !appPath.endsWith(".app")) return null;
54663
54845
  const plistPath = path37.join(appPath, "Contents", "Info.plist");
54664
- if (!fs28.existsSync(plistPath)) return null;
54846
+ if (!fs30.existsSync(plistPath)) return null;
54665
54847
  const raw = await runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
54666
54848
  return raw || null;
54667
54849
  }
@@ -54688,7 +54870,7 @@ async function detectAllVersions(loader, archive) {
54688
54870
  let resolvedBin = cliBin;
54689
54871
  if (!resolvedBin && appPath && currentOs === "darwin") {
54690
54872
  const bundled = path37.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
54691
- if (provider.cli && fs28.existsSync(bundled)) resolvedBin = bundled;
54873
+ if (provider.cli && fs30.existsSync(bundled)) resolvedBin = bundled;
54692
54874
  }
54693
54875
  info.installed = !!(appPath || resolvedBin);
54694
54876
  info.path = appPath || null;
@@ -54736,7 +54918,7 @@ async function detectAllVersions(loader, archive) {
54736
54918
 
54737
54919
  // src/daemon/dev-server.ts
54738
54920
  import * as http2 from "http";
54739
- import * as fs32 from "fs";
54921
+ import * as fs34 from "fs";
54740
54922
  import * as path41 from "path";
54741
54923
  init_config();
54742
54924
 
@@ -55089,7 +55271,7 @@ init_builders();
55089
55271
 
55090
55272
  // src/daemon/dev-cdp-handlers.ts
55091
55273
  init_logger();
55092
- import * as fs29 from "fs";
55274
+ import * as fs31 from "fs";
55093
55275
  import * as path38 from "path";
55094
55276
  async function handleCdpEvaluate(ctx, req, res) {
55095
55277
  const body = await ctx.readBody(req);
@@ -55269,17 +55451,17 @@ async function handleScriptHints(ctx, type, _req, res) {
55269
55451
  }
55270
55452
  let scriptsPath = "";
55271
55453
  const directScripts = path38.join(dir, "scripts.js");
55272
- if (fs29.existsSync(directScripts)) {
55454
+ if (fs31.existsSync(directScripts)) {
55273
55455
  scriptsPath = directScripts;
55274
55456
  } else {
55275
55457
  const scriptsDir = path38.join(dir, "scripts");
55276
- if (fs29.existsSync(scriptsDir)) {
55277
- const versions = fs29.readdirSync(scriptsDir).filter((d) => {
55278
- return fs29.statSync(path38.join(scriptsDir, d)).isDirectory();
55458
+ if (fs31.existsSync(scriptsDir)) {
55459
+ const versions = fs31.readdirSync(scriptsDir).filter((d) => {
55460
+ return fs31.statSync(path38.join(scriptsDir, d)).isDirectory();
55279
55461
  }).sort().reverse();
55280
55462
  for (const ver of versions) {
55281
55463
  const p = path38.join(scriptsDir, ver, "scripts.js");
55282
- if (fs29.existsSync(p)) {
55464
+ if (fs31.existsSync(p)) {
55283
55465
  scriptsPath = p;
55284
55466
  break;
55285
55467
  }
@@ -55291,7 +55473,7 @@ async function handleScriptHints(ctx, type, _req, res) {
55291
55473
  return;
55292
55474
  }
55293
55475
  try {
55294
- const source = fs29.readFileSync(scriptsPath, "utf-8");
55476
+ const source = fs31.readFileSync(scriptsPath, "utf-8");
55295
55477
  const hints = {};
55296
55478
  const funcRegex = /module\.exports\.(\w+)\s*=\s*function\s+\w+\s*\(params\)/g;
55297
55479
  let match;
@@ -56106,7 +56288,7 @@ async function handleDomContext(ctx, type, req, res) {
56106
56288
  }
56107
56289
 
56108
56290
  // src/daemon/dev-cli-debug.ts
56109
- import * as fs30 from "fs";
56291
+ import * as fs32 from "fs";
56110
56292
  import * as path39 from "path";
56111
56293
  function slugifyFixtureName(value) {
56112
56294
  const normalized = String(value || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
@@ -56122,10 +56304,10 @@ function getCliFixtureDir(ctx, type) {
56122
56304
  function readCliFixture(ctx, type, name) {
56123
56305
  const fixtureDir = getCliFixtureDir(ctx, type);
56124
56306
  const filePath = path39.join(fixtureDir, `${name}.json`);
56125
- if (!fs30.existsSync(filePath)) {
56307
+ if (!fs32.existsSync(filePath)) {
56126
56308
  throw new Error(`Fixture not found: ${filePath}`);
56127
56309
  }
56128
- return JSON.parse(fs30.readFileSync(filePath, "utf-8"));
56310
+ return JSON.parse(fs32.readFileSync(filePath, "utf-8"));
56129
56311
  }
56130
56312
  function getExerciseTranscriptText(result) {
56131
56313
  const parts = [];
@@ -56870,7 +57052,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
56870
57052
  return;
56871
57053
  }
56872
57054
  const fixtureDir = getCliFixtureDir(ctx, type);
56873
- fs30.mkdirSync(fixtureDir, { recursive: true });
57055
+ fs32.mkdirSync(fixtureDir, { recursive: true });
56874
57056
  const name = slugifyFixtureName(String(body?.name || `${type}-${Date.now()}`));
56875
57057
  const result = await runCliExerciseInternal(ctx, { ...request, type });
56876
57058
  const fixture = {
@@ -56898,7 +57080,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
56898
57080
  notes: typeof body?.notes === "string" ? body.notes : void 0
56899
57081
  };
56900
57082
  const filePath = path39.join(fixtureDir, `${name}.json`);
56901
- fs30.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
57083
+ fs32.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
56902
57084
  ctx.json(res, 200, {
56903
57085
  saved: true,
56904
57086
  name,
@@ -56916,14 +57098,14 @@ async function handleCliFixtureCapture(ctx, req, res) {
56916
57098
  async function handleCliFixtureList(ctx, type, _req, res) {
56917
57099
  try {
56918
57100
  const fixtureDir = getCliFixtureDir(ctx, type);
56919
- if (!fs30.existsSync(fixtureDir)) {
57101
+ if (!fs32.existsSync(fixtureDir)) {
56920
57102
  ctx.json(res, 200, { fixtures: [], count: 0 });
56921
57103
  return;
56922
57104
  }
56923
- const fixtures = fs30.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
57105
+ const fixtures = fs32.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
56924
57106
  const fullPath = path39.join(fixtureDir, file);
56925
57107
  try {
56926
- const raw = JSON.parse(fs30.readFileSync(fullPath, "utf-8"));
57108
+ const raw = JSON.parse(fs32.readFileSync(fullPath, "utf-8"));
56927
57109
  return {
56928
57110
  name: raw.name || file.replace(/\.json$/i, ""),
56929
57111
  path: fullPath,
@@ -57056,7 +57238,7 @@ async function handleCliRaw(ctx, req, res) {
57056
57238
  }
57057
57239
 
57058
57240
  // src/daemon/dev-auto-implement.ts
57059
- import * as fs31 from "fs";
57241
+ import * as fs33 from "fs";
57060
57242
  import * as path40 from "path";
57061
57243
  import * as os29 from "os";
57062
57244
  import { DEFAULT_SESSION_HOST_COLS as DEFAULT_SESSION_HOST_COLS7, DEFAULT_SESSION_HOST_ROWS as DEFAULT_SESSION_HOST_ROWS7 } from "@adhdev/session-host-core";
@@ -57105,10 +57287,10 @@ function resolveAutoImplReference(ctx, category, requestedReference, targetType)
57105
57287
  return fallback?.type || null;
57106
57288
  }
57107
57289
  function getLatestScriptVersionDir(scriptsDir) {
57108
- if (!fs31.existsSync(scriptsDir)) return null;
57109
- const versions = fs31.readdirSync(scriptsDir).filter((d) => {
57290
+ if (!fs33.existsSync(scriptsDir)) return null;
57291
+ const versions = fs33.readdirSync(scriptsDir).filter((d) => {
57110
57292
  try {
57111
- return fs31.statSync(path40.join(scriptsDir, d)).isDirectory();
57293
+ return fs33.statSync(path40.join(scriptsDir, d)).isDirectory();
57112
57294
  } catch {
57113
57295
  return false;
57114
57296
  }
@@ -57130,13 +57312,13 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
57130
57312
  if (!sourceDir) {
57131
57313
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
57132
57314
  }
57133
- if (!fs31.existsSync(desiredDir)) {
57134
- fs31.mkdirSync(path40.dirname(desiredDir), { recursive: true });
57135
- fs31.cpSync(sourceDir, desiredDir, { recursive: true });
57315
+ if (!fs33.existsSync(desiredDir)) {
57316
+ fs33.mkdirSync(path40.dirname(desiredDir), { recursive: true });
57317
+ fs33.cpSync(sourceDir, desiredDir, { recursive: true });
57136
57318
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
57137
57319
  }
57138
57320
  const providerJson = path40.join(desiredDir, "provider.json");
57139
- if (!fs31.existsSync(providerJson)) {
57321
+ if (!fs33.existsSync(providerJson)) {
57140
57322
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
57141
57323
  }
57142
57324
  return { dir: desiredDir };
@@ -57144,15 +57326,15 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
57144
57326
  function loadAutoImplReferenceScripts(ctx, referenceType) {
57145
57327
  if (!referenceType) return {};
57146
57328
  const refDir = ctx.findProviderDir(referenceType);
57147
- if (!refDir || !fs31.existsSync(refDir)) return {};
57329
+ if (!refDir || !fs33.existsSync(refDir)) return {};
57148
57330
  const referenceScripts = {};
57149
57331
  const scriptsDir = path40.join(refDir, "scripts");
57150
57332
  const latestDir = getLatestScriptVersionDir(scriptsDir);
57151
57333
  if (!latestDir) return referenceScripts;
57152
- for (const file of fs31.readdirSync(latestDir)) {
57334
+ for (const file of fs33.readdirSync(latestDir)) {
57153
57335
  if (!file.endsWith(".js")) continue;
57154
57336
  try {
57155
- referenceScripts[file] = fs31.readFileSync(path40.join(latestDir, file), "utf-8");
57337
+ referenceScripts[file] = fs33.readFileSync(path40.join(latestDir, file), "utf-8");
57156
57338
  } catch {
57157
57339
  }
57158
57340
  }
@@ -57261,15 +57443,15 @@ async function handleAutoImplement(ctx, type, req, res) {
57261
57443
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
57262
57444
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
57263
57445
  const tmpDir = path40.join(os29.tmpdir(), "adhdev-autoimpl");
57264
- if (!fs31.existsSync(tmpDir)) fs31.mkdirSync(tmpDir, { recursive: true });
57446
+ if (!fs33.existsSync(tmpDir)) fs33.mkdirSync(tmpDir, { recursive: true });
57265
57447
  const promptFile = path40.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
57266
- fs31.writeFileSync(promptFile, prompt, "utf-8");
57448
+ fs33.writeFileSync(promptFile, prompt, "utf-8");
57267
57449
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
57268
57450
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
57269
57451
  const spawn4 = agentProvider?.spawn;
57270
57452
  if (!spawn4?.command) {
57271
57453
  try {
57272
- fs31.unlinkSync(promptFile);
57454
+ fs33.unlinkSync(promptFile);
57273
57455
  } catch {
57274
57456
  }
57275
57457
  ctx.json(res, 400, { error: `Agent '${agent}' has no spawn config. Select a CLI provider with a spawn configuration.` });
@@ -57371,7 +57553,7 @@ async function handleAutoImplement(ctx, type, req, res) {
57371
57553
  } catch {
57372
57554
  }
57373
57555
  try {
57374
- fs31.unlinkSync(promptFile);
57556
+ fs33.unlinkSync(promptFile);
57375
57557
  } catch {
57376
57558
  }
57377
57559
  ctx.log(`Auto-implement (ACP) ${success ? "completed" : "failed"}: ${type} (exit: ${code})`);
@@ -57597,7 +57779,7 @@ async function handleAutoImplement(ctx, type, req, res) {
57597
57779
  }
57598
57780
  });
57599
57781
  try {
57600
- fs31.unlinkSync(promptFile);
57782
+ fs33.unlinkSync(promptFile);
57601
57783
  } catch {
57602
57784
  }
57603
57785
  ctx.log(`Auto-implement ${success ? "completed" : "failed"}: ${type} (exit: ${code})${verificationSummary ? ` verify=${verificationSummary.pass ? "pass" : "fail"}` : ""}`);
@@ -57702,10 +57884,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
57702
57884
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
57703
57885
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
57704
57886
  lines.push("");
57705
- for (const file of fs31.readdirSync(latestScriptsDir)) {
57887
+ for (const file of fs33.readdirSync(latestScriptsDir)) {
57706
57888
  if (file.endsWith(".js") && targetFileNames.has(file)) {
57707
57889
  try {
57708
- const content = fs31.readFileSync(path40.join(latestScriptsDir, file), "utf-8");
57890
+ const content = fs33.readFileSync(path40.join(latestScriptsDir, file), "utf-8");
57709
57891
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
57710
57892
  lines.push("```javascript");
57711
57893
  lines.push(content);
@@ -57715,14 +57897,14 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
57715
57897
  }
57716
57898
  }
57717
57899
  }
57718
- const refFiles = fs31.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
57900
+ const refFiles = fs33.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
57719
57901
  if (refFiles.length > 0) {
57720
57902
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
57721
57903
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
57722
57904
  lines.push("");
57723
57905
  for (const file of refFiles) {
57724
57906
  try {
57725
- const content = fs31.readFileSync(path40.join(latestScriptsDir, file), "utf-8");
57907
+ const content = fs33.readFileSync(path40.join(latestScriptsDir, file), "utf-8");
57726
57908
  lines.push(`### \`${file}\` \u{1F512}`);
57727
57909
  lines.push("```javascript");
57728
57910
  lines.push(content);
@@ -57767,7 +57949,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
57767
57949
  const loadGuide = (name) => {
57768
57950
  try {
57769
57951
  const p = path40.join(docsDir, name);
57770
- if (fs31.existsSync(p)) return fs31.readFileSync(p, "utf-8");
57952
+ if (fs33.existsSync(p)) return fs33.readFileSync(p, "utf-8");
57771
57953
  } catch {
57772
57954
  }
57773
57955
  return null;
@@ -58011,11 +58193,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
58011
58193
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
58012
58194
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
58013
58195
  lines.push("");
58014
- for (const file of fs31.readdirSync(latestScriptsDir)) {
58196
+ for (const file of fs33.readdirSync(latestScriptsDir)) {
58015
58197
  if (!file.endsWith(".js")) continue;
58016
58198
  if (!targetFileNames.has(file)) continue;
58017
58199
  try {
58018
- const content = fs31.readFileSync(path40.join(latestScriptsDir, file), "utf-8");
58200
+ const content = fs33.readFileSync(path40.join(latestScriptsDir, file), "utf-8");
58019
58201
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
58020
58202
  lines.push("```javascript");
58021
58203
  lines.push(content);
@@ -58024,14 +58206,14 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
58024
58206
  } catch {
58025
58207
  }
58026
58208
  }
58027
- const refFiles = fs31.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
58209
+ const refFiles = fs33.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
58028
58210
  if (refFiles.length > 0) {
58029
58211
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
58030
58212
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
58031
58213
  lines.push("");
58032
58214
  for (const file of refFiles) {
58033
58215
  try {
58034
- const content = fs31.readFileSync(path40.join(latestScriptsDir, file), "utf-8");
58216
+ const content = fs33.readFileSync(path40.join(latestScriptsDir, file), "utf-8");
58035
58217
  lines.push(`### \`${file}\` \u{1F512}`);
58036
58218
  lines.push("```javascript");
58037
58219
  lines.push(content);
@@ -58068,7 +58250,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
58068
58250
  const loadGuide = (name) => {
58069
58251
  try {
58070
58252
  const p = path40.join(docsDir, name);
58071
- if (fs31.existsSync(p)) return fs31.readFileSync(p, "utf-8");
58253
+ if (fs33.existsSync(p)) return fs33.readFileSync(p, "utf-8");
58072
58254
  } catch {
58073
58255
  }
58074
58256
  return null;
@@ -58808,7 +58990,7 @@ var DevServer = class _DevServer {
58808
58990
  path41.join(process.cwd(), "packages/web-devconsole/dist")
58809
58991
  ];
58810
58992
  for (const dir of candidates) {
58811
- if (fs32.existsSync(path41.join(dir, "index.html"))) return dir;
58993
+ if (fs34.existsSync(path41.join(dir, "index.html"))) return dir;
58812
58994
  }
58813
58995
  return null;
58814
58996
  }
@@ -58820,7 +59002,7 @@ var DevServer = class _DevServer {
58820
59002
  }
58821
59003
  const htmlPath = path41.join(distDir, "index.html");
58822
59004
  try {
58823
- const html = fs32.readFileSync(htmlPath, "utf-8");
59005
+ const html = fs34.readFileSync(htmlPath, "utf-8");
58824
59006
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
58825
59007
  res.end(html);
58826
59008
  } catch (e) {
@@ -58850,7 +59032,7 @@ var DevServer = class _DevServer {
58850
59032
  return;
58851
59033
  }
58852
59034
  try {
58853
- const content = fs32.readFileSync(filePath);
59035
+ const content = fs34.readFileSync(filePath);
58854
59036
  const ext = path41.extname(filePath);
58855
59037
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
58856
59038
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
@@ -58959,14 +59141,14 @@ var DevServer = class _DevServer {
58959
59141
  const files = [];
58960
59142
  const scan = (d, prefix) => {
58961
59143
  try {
58962
- for (const entry of fs32.readdirSync(d, { withFileTypes: true })) {
59144
+ for (const entry of fs34.readdirSync(d, { withFileTypes: true })) {
58963
59145
  if (entry.name.startsWith(".") || entry.name.endsWith(".bak")) continue;
58964
59146
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
58965
59147
  if (entry.isDirectory()) {
58966
59148
  files.push({ path: rel, size: 0, type: "dir" });
58967
59149
  scan(path41.join(d, entry.name), rel);
58968
59150
  } else {
58969
- const stat2 = fs32.statSync(path41.join(d, entry.name));
59151
+ const stat2 = fs34.statSync(path41.join(d, entry.name));
58970
59152
  files.push({ path: rel, size: stat2.size, type: "file" });
58971
59153
  }
58972
59154
  }
@@ -58994,11 +59176,11 @@ var DevServer = class _DevServer {
58994
59176
  this.json(res, 403, { error: "Forbidden" });
58995
59177
  return;
58996
59178
  }
58997
- if (!fs32.existsSync(fullPath) || fs32.statSync(fullPath).isDirectory()) {
59179
+ if (!fs34.existsSync(fullPath) || fs34.statSync(fullPath).isDirectory()) {
58998
59180
  this.json(res, 404, { error: `File not found: ${filePath}` });
58999
59181
  return;
59000
59182
  }
59001
- const content = fs32.readFileSync(fullPath, "utf-8");
59183
+ const content = fs34.readFileSync(fullPath, "utf-8");
59002
59184
  this.json(res, 200, { type, path: filePath, content, lines: content.split("\n").length });
59003
59185
  }
59004
59186
  /** POST /api/providers/:type/file — write a file { path, content } */
@@ -59020,9 +59202,9 @@ var DevServer = class _DevServer {
59020
59202
  return;
59021
59203
  }
59022
59204
  try {
59023
- if (fs32.existsSync(fullPath)) fs32.copyFileSync(fullPath, fullPath + ".bak");
59024
- fs32.mkdirSync(path41.dirname(fullPath), { recursive: true });
59025
- fs32.writeFileSync(fullPath, content, "utf-8");
59205
+ if (fs34.existsSync(fullPath)) fs34.copyFileSync(fullPath, fullPath + ".bak");
59206
+ fs34.mkdirSync(path41.dirname(fullPath), { recursive: true });
59207
+ fs34.writeFileSync(fullPath, content, "utf-8");
59026
59208
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
59027
59209
  this.providerLoader.reload();
59028
59210
  this.json(res, 200, { saved: true, path: filePath, chars: content.length });
@@ -59039,8 +59221,8 @@ var DevServer = class _DevServer {
59039
59221
  }
59040
59222
  for (const name of ["scripts.js", "provider.json"]) {
59041
59223
  const p = path41.join(dir, name);
59042
- if (fs32.existsSync(p)) {
59043
- const source = fs32.readFileSync(p, "utf-8");
59224
+ if (fs34.existsSync(p)) {
59225
+ const source = fs34.readFileSync(p, "utf-8");
59044
59226
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
59045
59227
  return;
59046
59228
  }
@@ -59059,11 +59241,11 @@ var DevServer = class _DevServer {
59059
59241
  this.json(res, 404, { error: `Provider not found: ${type}` });
59060
59242
  return;
59061
59243
  }
59062
- const target = fs32.existsSync(path41.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
59244
+ const target = fs34.existsSync(path41.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
59063
59245
  const targetPath = path41.join(dir, target);
59064
59246
  try {
59065
- if (fs32.existsSync(targetPath)) fs32.copyFileSync(targetPath, targetPath + ".bak");
59066
- fs32.writeFileSync(targetPath, source, "utf-8");
59247
+ if (fs34.existsSync(targetPath)) fs34.copyFileSync(targetPath, targetPath + ".bak");
59248
+ fs34.writeFileSync(targetPath, source, "utf-8");
59067
59249
  this.log(`Saved provider: ${targetPath} (${source.length} chars)`);
59068
59250
  this.providerLoader.reload();
59069
59251
  this.json(res, 200, { saved: true, path: targetPath, chars: source.length });
@@ -59208,20 +59390,20 @@ var DevServer = class _DevServer {
59208
59390
  let targetDir;
59209
59391
  targetDir = this.providerLoader.getUserProviderDir(category, type);
59210
59392
  const jsonPath = path41.join(targetDir, "provider.json");
59211
- if (fs32.existsSync(jsonPath)) {
59393
+ if (fs34.existsSync(jsonPath)) {
59212
59394
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
59213
59395
  return;
59214
59396
  }
59215
59397
  try {
59216
59398
  const result = generateFiles(type, name, category, { cdpPorts, cli, processName, installPath, binary, extensionId, version, osPaths, processNames });
59217
- fs32.mkdirSync(targetDir, { recursive: true });
59218
- fs32.writeFileSync(jsonPath, result["provider.json"], "utf-8");
59399
+ fs34.mkdirSync(targetDir, { recursive: true });
59400
+ fs34.writeFileSync(jsonPath, result["provider.json"], "utf-8");
59219
59401
  const createdFiles = ["provider.json"];
59220
59402
  if (result.files) {
59221
59403
  for (const [relPath, content] of Object.entries(result.files)) {
59222
59404
  const fullPath = path41.join(targetDir, relPath);
59223
- fs32.mkdirSync(path41.dirname(fullPath), { recursive: true });
59224
- fs32.writeFileSync(fullPath, content, "utf-8");
59405
+ fs34.mkdirSync(path41.dirname(fullPath), { recursive: true });
59406
+ fs34.writeFileSync(fullPath, content, "utf-8");
59225
59407
  createdFiles.push(relPath);
59226
59408
  }
59227
59409
  }
@@ -59270,10 +59452,10 @@ var DevServer = class _DevServer {
59270
59452
  }
59271
59453
  // ─── Phase 2: Auto-Implement Backend ───
59272
59454
  getLatestScriptVersionDir(scriptsDir) {
59273
- if (!fs32.existsSync(scriptsDir)) return null;
59274
- const versions = fs32.readdirSync(scriptsDir).filter((d) => {
59455
+ if (!fs34.existsSync(scriptsDir)) return null;
59456
+ const versions = fs34.readdirSync(scriptsDir).filter((d) => {
59275
59457
  try {
59276
- return fs32.statSync(path41.join(scriptsDir, d)).isDirectory();
59458
+ return fs34.statSync(path41.join(scriptsDir, d)).isDirectory();
59277
59459
  } catch {
59278
59460
  return false;
59279
59461
  }
@@ -59295,13 +59477,13 @@ var DevServer = class _DevServer {
59295
59477
  if (!sourceDir) {
59296
59478
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
59297
59479
  }
59298
- if (!fs32.existsSync(desiredDir)) {
59299
- fs32.mkdirSync(path41.dirname(desiredDir), { recursive: true });
59300
- fs32.cpSync(sourceDir, desiredDir, { recursive: true });
59480
+ if (!fs34.existsSync(desiredDir)) {
59481
+ fs34.mkdirSync(path41.dirname(desiredDir), { recursive: true });
59482
+ fs34.cpSync(sourceDir, desiredDir, { recursive: true });
59301
59483
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
59302
59484
  }
59303
59485
  const providerJson = path41.join(desiredDir, "provider.json");
59304
- if (!fs32.existsSync(providerJson)) {
59486
+ if (!fs34.existsSync(providerJson)) {
59305
59487
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
59306
59488
  }
59307
59489
  return { dir: desiredDir };
@@ -59344,10 +59526,10 @@ var DevServer = class _DevServer {
59344
59526
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
59345
59527
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
59346
59528
  lines.push("");
59347
- for (const file of fs32.readdirSync(latestScriptsDir)) {
59529
+ for (const file of fs34.readdirSync(latestScriptsDir)) {
59348
59530
  if (file.endsWith(".js") && targetFileNames.has(file)) {
59349
59531
  try {
59350
- const content = fs32.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59532
+ const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59351
59533
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
59352
59534
  lines.push("```javascript");
59353
59535
  lines.push(content);
@@ -59357,14 +59539,14 @@ var DevServer = class _DevServer {
59357
59539
  }
59358
59540
  }
59359
59541
  }
59360
- const refFiles = fs32.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
59542
+ const refFiles = fs34.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
59361
59543
  if (refFiles.length > 0) {
59362
59544
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
59363
59545
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
59364
59546
  lines.push("");
59365
59547
  for (const file of refFiles) {
59366
59548
  try {
59367
- const content = fs32.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59549
+ const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59368
59550
  lines.push(`### \`${file}\` \u{1F512}`);
59369
59551
  lines.push("```javascript");
59370
59552
  lines.push(content);
@@ -59409,7 +59591,7 @@ var DevServer = class _DevServer {
59409
59591
  const loadGuide = (name) => {
59410
59592
  try {
59411
59593
  const p = path41.join(docsDir, name);
59412
- if (fs32.existsSync(p)) return fs32.readFileSync(p, "utf-8");
59594
+ if (fs34.existsSync(p)) return fs34.readFileSync(p, "utf-8");
59413
59595
  } catch {
59414
59596
  }
59415
59597
  return null;
@@ -59590,11 +59772,11 @@ var DevServer = class _DevServer {
59590
59772
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
59591
59773
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
59592
59774
  lines.push("");
59593
- for (const file of fs32.readdirSync(latestScriptsDir)) {
59775
+ for (const file of fs34.readdirSync(latestScriptsDir)) {
59594
59776
  if (!file.endsWith(".js")) continue;
59595
59777
  if (!targetFileNames.has(file)) continue;
59596
59778
  try {
59597
- const content = fs32.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59779
+ const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59598
59780
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
59599
59781
  lines.push("```javascript");
59600
59782
  lines.push(content);
@@ -59603,14 +59785,14 @@ var DevServer = class _DevServer {
59603
59785
  } catch {
59604
59786
  }
59605
59787
  }
59606
- const refFiles = fs32.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
59788
+ const refFiles = fs34.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
59607
59789
  if (refFiles.length > 0) {
59608
59790
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
59609
59791
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
59610
59792
  lines.push("");
59611
59793
  for (const file of refFiles) {
59612
59794
  try {
59613
- const content = fs32.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59795
+ const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59614
59796
  lines.push(`### \`${file}\` \u{1F512}`);
59615
59797
  lines.push("```javascript");
59616
59798
  lines.push(content);
@@ -59647,7 +59829,7 @@ var DevServer = class _DevServer {
59647
59829
  const loadGuide = (name) => {
59648
59830
  try {
59649
59831
  const p = path41.join(docsDir, name);
59650
- if (fs32.existsSync(p)) return fs32.readFileSync(p, "utf-8");
59832
+ if (fs34.existsSync(p)) return fs34.readFileSync(p, "utf-8");
59651
59833
  } catch {
59652
59834
  }
59653
59835
  return null;
@@ -60755,8 +60937,8 @@ async function installExtension(ide, extension) {
60755
60937
  const res = await fetch(extension.vsixUrl);
60756
60938
  if (res.ok) {
60757
60939
  const buffer = Buffer.from(await res.arrayBuffer());
60758
- const fs33 = await import("fs");
60759
- fs33.writeFileSync(vsixPath, buffer);
60940
+ const fs35 = await import("fs");
60941
+ fs35.writeFileSync(vsixPath, buffer);
60760
60942
  return new Promise((resolve24) => {
60761
60943
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
60762
60944
  exec6(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
@@ -61333,11 +61515,11 @@ init_parse_session();
61333
61515
 
61334
61516
  // src/providers/sdk/v1/fixture-tooling/replay.ts
61335
61517
  init_provider_cli_shared();
61336
- import { readFileSync as readFileSync36 } from "fs";
61518
+ import { readFileSync as readFileSync37 } from "fs";
61337
61519
  import { dirname as dirname15, resolve as resolve22 } from "path";
61338
61520
 
61339
61521
  // src/providers/sdk/v1/validators/taint.ts
61340
- import { readFileSync as readFileSync37, existsSync as existsSync46 } from "fs";
61522
+ import { readFileSync as readFileSync38, existsSync as existsSync48 } from "fs";
61341
61523
  import { resolve as resolve23, dirname as dirname16, join as join47 } from "path";
61342
61524
 
61343
61525
  // src/providers/sdk/v1/validators/index.ts