@adhdev/daemon-core 0.9.82-rc.114 → 0.9.82-rc.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1055,6 +1055,7 @@ function addNode(meshId, opts) {
1055
1055
  isLocalWorktree: opts.isLocalWorktree,
1056
1056
  worktreeBranch: opts.worktreeBranch,
1057
1057
  clonedFromNodeId: opts.clonedFromNodeId,
1058
+ worktreeBootstrap: opts.worktreeBootstrap,
1058
1059
  role: opts.role
1059
1060
  };
1060
1061
  mesh.nodes.push(node);
@@ -1081,6 +1082,7 @@ function updateNode(meshId, nodeId, opts) {
1081
1082
  if (!node) return void 0;
1082
1083
  if (opts.userOverrides) node.userOverrides = { ...node.userOverrides, ...opts.userOverrides };
1083
1084
  if (opts.policy) node.policy = { ...node.policy, ...opts.policy };
1085
+ if (opts.worktreeBootstrap) node.worktreeBootstrap = opts.worktreeBootstrap;
1084
1086
  mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1085
1087
  saveMeshConfig(config);
1086
1088
  return node;
@@ -1302,19 +1304,19 @@ function isIntentionalCleanupStopEntry(entry) {
1302
1304
  return payload.intentional === true && (payload.reason === "operator_cleanup" || payload.intentionalStopReason === "operator_cleanup" || payload.source === "mesh_cleanup_sessions" || payload.source === "mesh_remove_node");
1303
1305
  }
1304
1306
  function getLedgerDir() {
1305
- const dir = (0, import_path4.join)(getConfigDir(), LEDGER_DIR_NAME);
1306
- if (!(0, import_fs4.existsSync)(dir)) {
1307
- (0, import_fs4.mkdirSync)(dir, { recursive: true, mode: 448 });
1307
+ const dir = (0, import_path5.join)(getConfigDir(), LEDGER_DIR_NAME);
1308
+ if (!(0, import_fs5.existsSync)(dir)) {
1309
+ (0, import_fs5.mkdirSync)(dir, { recursive: true, mode: 448 });
1308
1310
  }
1309
1311
  return dir;
1310
1312
  }
1311
1313
  function getLedgerPath(meshId) {
1312
1314
  const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
1313
- return (0, import_path4.join)(getLedgerDir(), `${safe}.jsonl`);
1315
+ return (0, import_path5.join)(getLedgerDir(), `${safe}.jsonl`);
1314
1316
  }
1315
1317
  function getRotatedPath(meshId, index) {
1316
1318
  const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
1317
- return (0, import_path4.join)(getLedgerDir(), `${safe}.${index}.jsonl`);
1319
+ return (0, import_path5.join)(getLedgerDir(), `${safe}.${index}.jsonl`);
1318
1320
  }
1319
1321
  function readNonEmptyString(value) {
1320
1322
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
@@ -1436,9 +1438,9 @@ function appendLedgerEntry(meshId, partial) {
1436
1438
  ...partial
1437
1439
  };
1438
1440
  const filePath = getLedgerPath(meshId);
1439
- if ((0, import_fs4.existsSync)(filePath)) {
1441
+ if ((0, import_fs5.existsSync)(filePath)) {
1440
1442
  try {
1441
- const stat2 = (0, import_fs4.statSync)(filePath);
1443
+ const stat2 = (0, import_fs5.statSync)(filePath);
1442
1444
  if (stat2.size >= MAX_FILE_SIZE_BYTES) {
1443
1445
  rotateLedgerFile(meshId, filePath);
1444
1446
  }
@@ -1447,7 +1449,7 @@ function appendLedgerEntry(meshId, partial) {
1447
1449
  }
1448
1450
  try {
1449
1451
  const line = JSON.stringify(entry) + "\n";
1450
- (0, import_fs4.appendFileSync)(filePath, line, { encoding: "utf-8", mode: 384 });
1452
+ (0, import_fs5.appendFileSync)(filePath, line, { encoding: "utf-8", mode: 384 });
1451
1453
  meshLedgerEvents.emit("append", meshId, entry);
1452
1454
  return entry;
1453
1455
  } catch (e) {
@@ -1492,7 +1494,7 @@ function appendRemoteLedgerEntries(meshId, entries) {
1492
1494
  }
1493
1495
  try {
1494
1496
  const lines = validEntries.map((e) => JSON.stringify(e)).join("\n") + "\n";
1495
- (0, import_fs4.appendFileSync)(ledgerPath, lines, { encoding: "utf-8", mode: 384 });
1497
+ (0, import_fs5.appendFileSync)(ledgerPath, lines, { encoding: "utf-8", mode: 384 });
1496
1498
  for (const entry of validEntries) {
1497
1499
  meshLedgerEvents.emit("append", meshId, entry);
1498
1500
  }
@@ -1503,10 +1505,10 @@ function appendRemoteLedgerEntries(meshId, entries) {
1503
1505
  }
1504
1506
  function readLedgerEntries(meshId, opts) {
1505
1507
  const filePath = getLedgerPath(meshId);
1506
- if (!(0, import_fs4.existsSync)(filePath)) return [];
1508
+ if (!(0, import_fs5.existsSync)(filePath)) return [];
1507
1509
  let content;
1508
1510
  try {
1509
- content = (0, import_fs4.readFileSync)(filePath, "utf-8");
1511
+ content = (0, import_fs5.readFileSync)(filePath, "utf-8");
1510
1512
  } catch {
1511
1513
  return [];
1512
1514
  }
@@ -1678,22 +1680,22 @@ function getSessionRecoveryContext(meshId, opts) {
1678
1680
  }
1679
1681
  function rotateLedgerFile(meshId, currentPath) {
1680
1682
  let index = 1;
1681
- while ((0, import_fs4.existsSync)(getRotatedPath(meshId, index))) {
1683
+ while ((0, import_fs5.existsSync)(getRotatedPath(meshId, index))) {
1682
1684
  index++;
1683
1685
  if (index > 10) break;
1684
1686
  }
1685
1687
  if (index > 10) index = 10;
1686
1688
  try {
1687
- (0, import_fs4.renameSync)(currentPath, getRotatedPath(meshId, index));
1689
+ (0, import_fs5.renameSync)(currentPath, getRotatedPath(meshId, index));
1688
1690
  } catch {
1689
1691
  }
1690
1692
  }
1691
- var import_fs4, import_path4, import_crypto4, import_events, LEDGER_DIR_NAME, MAX_FILE_SIZE_BYTES, RECENT_FAILURE_WINDOW_MS, DEFAULT_LEDGER_SLICE_LIMIT, MAX_LEDGER_SLICE_LIMIT, meshLedgerEvents;
1693
+ var import_fs5, import_path5, import_crypto4, import_events, LEDGER_DIR_NAME, MAX_FILE_SIZE_BYTES, RECENT_FAILURE_WINDOW_MS, DEFAULT_LEDGER_SLICE_LIMIT, MAX_LEDGER_SLICE_LIMIT, meshLedgerEvents;
1692
1694
  var init_mesh_ledger = __esm({
1693
1695
  "src/mesh/mesh-ledger.ts"() {
1694
1696
  "use strict";
1695
- import_fs4 = require("fs");
1696
- import_path4 = require("path");
1697
+ import_fs5 = require("fs");
1698
+ import_path5 = require("path");
1697
1699
  import_crypto4 = require("crypto");
1698
1700
  init_config();
1699
1701
  import_events = require("events");
@@ -1717,14 +1719,14 @@ function safeMeshId(meshId) {
1717
1719
  return meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
1718
1720
  }
1719
1721
  function legacyQueuePath(meshId) {
1720
- return (0, import_path5.join)(getLedgerDir(), `${safeMeshId(meshId)}.queue.json`);
1722
+ return (0, import_path6.join)(getLedgerDir(), `${safeMeshId(meshId)}.queue.json`);
1721
1723
  }
1722
- var import_fs5, import_path5, import_module, import_meta, DatabaseCtor, BeadsDB;
1724
+ var import_fs6, import_path6, import_module, import_meta, DatabaseCtor, BeadsDB;
1723
1725
  var init_beads_db = __esm({
1724
1726
  "src/mesh/beads-db.ts"() {
1725
1727
  "use strict";
1726
- import_fs5 = require("fs");
1727
- import_path5 = require("path");
1728
+ import_fs6 = require("fs");
1729
+ import_path6 = require("path");
1728
1730
  import_module = require("module");
1729
1731
  init_mesh_ledger();
1730
1732
  import_meta = {};
@@ -1733,8 +1735,8 @@ var init_beads_db = __esm({
1733
1735
  db;
1734
1736
  migratedMeshIds = /* @__PURE__ */ new Set();
1735
1737
  constructor(dbPath) {
1736
- const dir = (0, import_path5.dirname)(dbPath);
1737
- if (!(0, import_fs5.existsSync)(dir)) (0, import_fs5.mkdirSync)(dir, { recursive: true });
1738
+ const dir = (0, import_path6.dirname)(dbPath);
1739
+ if (!(0, import_fs6.existsSync)(dir)) (0, import_fs6.mkdirSync)(dir, { recursive: true });
1738
1740
  this.db = new (loadDatabaseCtor())(dbPath);
1739
1741
  this.db.pragma("journal_mode = WAL");
1740
1742
  this.db.pragma("synchronous = NORMAL");
@@ -1744,7 +1746,7 @@ var init_beads_db = __esm({
1744
1746
  }
1745
1747
  static getInstance() {
1746
1748
  if (!this.instance) {
1747
- this.instance = new _BeadsDB((0, import_path5.join)(getLedgerDir(), "beads.db"));
1749
+ this.instance = new _BeadsDB((0, import_path6.join)(getLedgerDir(), "beads.db"));
1748
1750
  }
1749
1751
  return this.instance;
1750
1752
  }
@@ -1785,9 +1787,9 @@ var init_beads_db = __esm({
1785
1787
  const count = this.db.prepare("SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?").get(meshId);
1786
1788
  if (count.count > 0) return;
1787
1789
  const path28 = legacyQueuePath(meshId);
1788
- if (!(0, import_fs5.existsSync)(path28)) return;
1790
+ if (!(0, import_fs6.existsSync)(path28)) return;
1789
1791
  try {
1790
- const entries = JSON.parse((0, import_fs5.readFileSync)(path28, "utf-8"));
1792
+ const entries = JSON.parse((0, import_fs6.readFileSync)(path28, "utf-8"));
1791
1793
  if (!Array.isArray(entries)) return;
1792
1794
  const insert = this.db.prepare(`
1793
1795
  INSERT OR REPLACE INTO mesh_queue (
@@ -2146,24 +2148,24 @@ function resolveCommandPath(command) {
2146
2148
  if (isExplicitCommandPath(trimmed)) {
2147
2149
  const expanded = expandHome(trimmed);
2148
2150
  const candidate = path8.isAbsolute(expanded) ? expanded : path8.resolve(expanded);
2149
- return (0, import_fs6.existsSync)(candidate) ? candidate : null;
2151
+ return (0, import_fs7.existsSync)(candidate) ? candidate : null;
2150
2152
  }
2151
2153
  return null;
2152
2154
  }
2153
2155
  function execAsync(cmd, timeoutMs = 5e3) {
2154
- return new Promise((resolve16) => {
2156
+ return new Promise((resolve17) => {
2155
2157
  const child = (0, import_child_process.exec)(cmd, {
2156
2158
  encoding: "utf-8",
2157
2159
  timeout: timeoutMs,
2158
2160
  ...process.platform === "win32" ? { windowsHide: true } : {}
2159
2161
  }, (err, stdout) => {
2160
2162
  if (err || !stdout?.trim()) {
2161
- resolve16(null);
2163
+ resolve17(null);
2162
2164
  } else {
2163
- resolve16(stdout.trim());
2165
+ resolve17(stdout.trim());
2164
2166
  }
2165
2167
  });
2166
- child.on("error", () => resolve16(null));
2168
+ child.on("error", () => resolve17(null));
2167
2169
  });
2168
2170
  }
2169
2171
  async function detectCLIs(providerLoader, options) {
@@ -2246,14 +2248,14 @@ async function detectCLI(cliId, providerLoader, options) {
2246
2248
  const all = await detectCLIs(providerLoader, options);
2247
2249
  return all.find((c) => c.id === resolvedId && c.installed) || null;
2248
2250
  }
2249
- var import_child_process, os2, path8, import_fs6;
2251
+ var import_child_process, os2, path8, import_fs7;
2250
2252
  var init_cli_detector = __esm({
2251
2253
  "src/detection/cli-detector.ts"() {
2252
2254
  "use strict";
2253
2255
  import_child_process = require("child_process");
2254
2256
  os2 = __toESM(require("os"));
2255
2257
  path8 = __toESM(require("path"));
2256
- import_fs6 = require("fs");
2258
+ import_fs7 = require("fs");
2257
2259
  }
2258
2260
  });
2259
2261
 
@@ -2539,7 +2541,7 @@ __export(mesh_events_exports, {
2539
2541
  tryAssignQueueTask: () => tryAssignQueueTask
2540
2542
  });
2541
2543
  function readWorkerResultMetadata(event) {
2542
- return readRecord(event.workerResult) || readRecord(event.meshWorkerResult) || readRecord(event.structuredResult);
2544
+ return readRecord2(event.workerResult) || readRecord2(event.meshWorkerResult) || readRecord2(event.structuredResult);
2543
2545
  }
2544
2546
  function sweepExpiredRemoteIdleSessions() {
2545
2547
  const now = Date.now();
@@ -2548,9 +2550,9 @@ function sweepExpiredRemoteIdleSessions() {
2548
2550
  }
2549
2551
  }
2550
2552
  function readRefineJobId(event) {
2551
- const metadata = readRecord(event.metadataEvent) || event;
2552
- const result = readRecord(metadata.result);
2553
- const refineJob = readRecord(result?.refineJob);
2553
+ const metadata = readRecord2(event.metadataEvent) || event;
2554
+ const result = readRecord2(metadata.result);
2555
+ const refineJob = readRecord2(result?.refineJob);
2554
2556
  return readNonEmptyString2(metadata.jobId) || readNonEmptyString2(refineJob?.jobId);
2555
2557
  }
2556
2558
  function buildRefineTerminalEventFingerprint(meshId, eventName, metadataEvent) {
@@ -2566,10 +2568,10 @@ function hasPendingRefineTerminalEventDuplicate(event) {
2566
2568
  );
2567
2569
  }
2568
2570
  function buildPendingEventFingerprint(event) {
2569
- const metadata = readRecord(event.metadataEvent) || {};
2571
+ const metadata = readRecord2(event.metadataEvent) || {};
2570
2572
  const sessionId = resolveEventSessionId(metadata);
2571
2573
  const providerSessionId = readNonEmptyString2(metadata.providerSessionId);
2572
- const taskId = readNonEmptyString2(metadata.taskId) || readNonEmptyString2(readRecord(metadata.payload)?.taskId);
2574
+ const taskId = readNonEmptyString2(metadata.taskId) || readNonEmptyString2(readRecord2(metadata.payload)?.taskId);
2573
2575
  const jobId = readRefineJobId(event);
2574
2576
  const timestamp = metadata.timestamp !== void 0 && metadata.timestamp !== null ? String(metadata.timestamp) : "";
2575
2577
  return [
@@ -2590,7 +2592,7 @@ function hasPendingCoordinatorEventDuplicate(event) {
2590
2592
  }
2591
2593
  function getPendingEventsPath(meshId) {
2592
2594
  const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
2593
- return (0, import_path6.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
2595
+ return (0, import_path7.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
2594
2596
  }
2595
2597
  function queuePendingMeshCoordinatorEvent(event) {
2596
2598
  try {
@@ -2602,7 +2604,7 @@ function queuePendingMeshCoordinatorEvent(event) {
2602
2604
  LOG.info("MeshEvents", `Suppressed duplicate pending ${event.event} for mesh ${event.meshId}`);
2603
2605
  return true;
2604
2606
  }
2605
- (0, import_fs7.appendFileSync)(getPendingEventsPath(event.meshId), JSON.stringify(event) + "\n", "utf-8");
2607
+ (0, import_fs8.appendFileSync)(getPendingEventsPath(event.meshId), JSON.stringify(event) + "\n", "utf-8");
2606
2608
  return true;
2607
2609
  } catch (e) {
2608
2610
  LOG.warn("MeshEvents", `Failed to persist pending coordinator event: ${e?.message || e}`);
@@ -2612,11 +2614,11 @@ function queuePendingMeshCoordinatorEvent(event) {
2612
2614
  function drainPendingMeshCoordinatorEvents(meshId) {
2613
2615
  if (!meshId) return [];
2614
2616
  const path28 = getPendingEventsPath(meshId);
2615
- if (!(0, import_fs7.existsSync)(path28)) return [];
2617
+ if (!(0, import_fs8.existsSync)(path28)) return [];
2616
2618
  try {
2617
- const raw = (0, import_fs7.readFileSync)(path28, "utf-8");
2619
+ const raw = (0, import_fs8.readFileSync)(path28, "utf-8");
2618
2620
  try {
2619
- (0, import_fs7.unlinkSync)(path28);
2621
+ (0, import_fs8.unlinkSync)(path28);
2620
2622
  } catch {
2621
2623
  }
2622
2624
  return raw.split("\n").filter(Boolean).flatMap((line) => {
@@ -2633,9 +2635,9 @@ function drainPendingMeshCoordinatorEvents(meshId) {
2633
2635
  function getPendingMeshCoordinatorEvents(meshId) {
2634
2636
  if (!meshId) return [];
2635
2637
  const path28 = getPendingEventsPath(meshId);
2636
- if (!(0, import_fs7.existsSync)(path28)) return [];
2638
+ if (!(0, import_fs8.existsSync)(path28)) return [];
2637
2639
  try {
2638
- const raw = (0, import_fs7.readFileSync)(path28, "utf-8");
2640
+ const raw = (0, import_fs8.readFileSync)(path28, "utf-8");
2639
2641
  return raw.split("\n").filter(Boolean).flatMap((line) => {
2640
2642
  try {
2641
2643
  return [JSON.parse(line)];
@@ -2650,15 +2652,15 @@ function getPendingMeshCoordinatorEvents(meshId) {
2650
2652
  function clearPendingMeshCoordinatorEvents(meshId) {
2651
2653
  if (!meshId) return;
2652
2654
  const path28 = getPendingEventsPath(meshId);
2653
- if ((0, import_fs7.existsSync)(path28)) try {
2654
- (0, import_fs7.unlinkSync)(path28);
2655
+ if ((0, import_fs8.existsSync)(path28)) try {
2656
+ (0, import_fs8.unlinkSync)(path28);
2655
2657
  } catch {
2656
2658
  }
2657
2659
  }
2658
2660
  function readNonEmptyString2(value) {
2659
2661
  return typeof value === "string" && value.trim() ? value.trim() : "";
2660
2662
  }
2661
- function readRecord(value) {
2663
+ function readRecord2(value) {
2662
2664
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2663
2665
  }
2664
2666
  function resolveEventSessionId(event, fallback) {
@@ -3098,10 +3100,10 @@ Do NOT retry on this node. Consider reassigning to a different node or asking th
3098
3100
  }
3099
3101
  if (args.event === "refine:completed") {
3100
3102
  const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
3101
- const result = readRecord(args.metadataEvent.result);
3102
- const validationSummary = readRecord(result?.validationSummary);
3103
- const patchEquivalence = readRecord(result?.patchEquivalence);
3104
- const finalConvergence = readRecord(result?.finalBranchConvergenceState);
3103
+ const result = readRecord2(args.metadataEvent.result);
3104
+ const validationSummary = readRecord2(result?.validationSummary);
3105
+ const patchEquivalence = readRecord2(result?.patchEquivalence);
3106
+ const finalConvergence = readRecord2(result?.finalBranchConvergenceState);
3105
3107
  const validationStatus = readNonEmptyString2(validationSummary?.status);
3106
3108
  const patchStatus = readNonEmptyString2(patchEquivalence?.status) || (patchEquivalence?.equivalent === true ? "passed" : "");
3107
3109
  const into = readNonEmptyString2(result?.into);
@@ -3122,10 +3124,10 @@ Next step: ${nextStep}`;
3122
3124
  }
3123
3125
  if (args.event === "refine:failed") {
3124
3126
  const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
3125
- const result = readRecord(args.metadataEvent.result);
3126
- const validationSummary = readRecord(result?.validationSummary);
3127
- const patchEquivalence = readRecord(result?.patchEquivalence);
3128
- const finalConvergence = readRecord(result?.finalBranchConvergenceState);
3127
+ const result = readRecord2(args.metadataEvent.result);
3128
+ const validationSummary = readRecord2(result?.validationSummary);
3129
+ const patchEquivalence = readRecord2(result?.patchEquivalence);
3130
+ const finalConvergence = readRecord2(result?.finalBranchConvergenceState);
3129
3131
  const code = readNonEmptyString2(result?.code);
3130
3132
  const error = readNonEmptyString2(result?.error);
3131
3133
  const validationStatus = readNonEmptyString2(validationSummary?.status);
@@ -3493,12 +3495,12 @@ function setupMeshEventForwarding(components) {
3493
3495
  });
3494
3496
  });
3495
3497
  }
3496
- var import_fs7, import_path6, REMOTE_IDLE_SESSION_TTL_MS, remoteIdleSessions, REFINE_TERMINAL_EVENTS, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS, RECENT_COMPLETION_FINGERPRINT_TTL_MS, recentCompletionFingerprints, autoLaunchInProgress, autoLaunchCooldownUntil, AUTO_LAUNCH_COOLDOWN_MS;
3498
+ var import_fs8, import_path7, REMOTE_IDLE_SESSION_TTL_MS, remoteIdleSessions, REFINE_TERMINAL_EVENTS, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS, RECENT_COMPLETION_FINGERPRINT_TTL_MS, recentCompletionFingerprints, autoLaunchInProgress, autoLaunchCooldownUntil, AUTO_LAUNCH_COOLDOWN_MS;
3497
3499
  var init_mesh_events = __esm({
3498
3500
  "src/mesh/mesh-events.ts"() {
3499
3501
  "use strict";
3500
- import_fs7 = require("fs");
3501
- import_path6 = require("path");
3502
+ import_fs8 = require("fs");
3503
+ import_path7 = require("path");
3502
3504
  init_config();
3503
3505
  init_mesh_config();
3504
3506
  init_cli_detector();
@@ -5214,7 +5216,7 @@ ${lastSnapshot}`;
5214
5216
  `[${this.cliType}] Waiting for interactive prompt: status=${status} stableMs=${stableMs} recentOutputMs=${recentlyOutput} screen=${JSON.stringify(summarizeCliTraceText(screenText, 220)).slice(0, 260)}`
5215
5217
  );
5216
5218
  }
5217
- await new Promise((resolve16) => setTimeout(resolve16, 50));
5219
+ await new Promise((resolve17) => setTimeout(resolve17, 50));
5218
5220
  }
5219
5221
  const finalScreenText = this.terminalScreen.getText() || "";
5220
5222
  LOG.warn(
@@ -6441,7 +6443,7 @@ ${lastSnapshot}`;
6441
6443
  const deadline = Date.now() + 1e4;
6442
6444
  while (this.startupParseGate && Date.now() < deadline) {
6443
6445
  this.resolveStartupState("send_wait");
6444
- await new Promise((resolve16) => setTimeout(resolve16, 50));
6446
+ await new Promise((resolve17) => setTimeout(resolve17, 50));
6445
6447
  }
6446
6448
  }
6447
6449
  const parsedStatusBeforeSend = !allowInputDuringGeneration ? (() => {
@@ -6538,13 +6540,13 @@ ${lastSnapshot}`;
6538
6540
  }
6539
6541
  this.responseEpoch += 1;
6540
6542
  this.responseSettleIgnoreUntil = Date.now() + submitDelayMs + this.timeouts.outputSettle + 250;
6541
- await new Promise((resolve16, reject) => {
6543
+ await new Promise((resolve17, reject) => {
6542
6544
  let resolved = false;
6543
6545
  const completion = {
6544
6546
  resolveOnce: () => {
6545
6547
  if (resolved) return;
6546
6548
  resolved = true;
6547
- resolve16();
6549
+ resolve17();
6548
6550
  },
6549
6551
  rejectOnce: (error) => {
6550
6552
  if (resolved) return;
@@ -6702,17 +6704,17 @@ ${lastSnapshot}`;
6702
6704
  }
6703
6705
  }
6704
6706
  waitForStopped(timeoutMs) {
6705
- return new Promise((resolve16) => {
6707
+ return new Promise((resolve17) => {
6706
6708
  const startedAt = Date.now();
6707
6709
  const timer = setInterval(() => {
6708
6710
  if (!this.ptyProcess || this.currentStatus === "stopped") {
6709
6711
  clearInterval(timer);
6710
- resolve16(true);
6712
+ resolve17(true);
6711
6713
  return;
6712
6714
  }
6713
6715
  if (Date.now() - startedAt >= timeoutMs) {
6714
6716
  clearInterval(timer);
6715
- resolve16(false);
6717
+ resolve17(false);
6716
6718
  }
6717
6719
  }, 100);
6718
6720
  });
@@ -7042,6 +7044,8 @@ __export(index_exports, {
7042
7044
  MAX_LEDGER_SLICE_LIMIT: () => MAX_LEDGER_SLICE_LIMIT,
7043
7045
  MESH_REFINE_CONFIG_LOCATIONS: () => MESH_REFINE_CONFIG_LOCATIONS,
7044
7046
  MESH_REFINE_CONFIG_SCHEMA: () => MESH_REFINE_CONFIG_SCHEMA,
7047
+ MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS: () => MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS,
7048
+ MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA: () => MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA,
7045
7049
  MIN_GIT_WORKSPACE_POLL_INTERVAL_MS: () => MIN_GIT_WORKSPACE_POLL_INTERVAL_MS,
7046
7050
  MIN_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS: () => MIN_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS,
7047
7051
  MIN_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS: () => MIN_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS,
@@ -7062,10 +7066,12 @@ __export(index_exports, {
7062
7066
  buildChatMessage: () => buildChatMessage,
7063
7067
  buildChatMessageSignature: () => buildChatMessageSignature,
7064
7068
  buildChatTailDeliverySignature: () => buildChatTailDeliverySignature,
7069
+ buildCompactStaleDirectWorkSummary: () => buildCompactStaleDirectWorkSummary,
7065
7070
  buildCoordinatorSystemPrompt: () => buildCoordinatorSystemPrompt,
7066
7071
  buildMachineInfo: () => buildMachineInfo,
7067
7072
  buildMeshActiveWork: () => buildMeshActiveWork,
7068
7073
  buildMeshActiveWorkSummary: () => buildMeshActiveWorkSummary,
7074
+ buildMeshAsyncRefineJobs: () => buildMeshAsyncRefineJobs,
7069
7075
  buildMeshHostRequiredFailure: () => buildMeshHostRequiredFailure,
7070
7076
  buildMeshLedgerReconciliationEvidence: () => buildMeshLedgerReconciliationEvidence,
7071
7077
  buildMeshLedgerReplicaEvidence: () => buildMeshLedgerReplicaEvidence,
@@ -7174,6 +7180,7 @@ __export(index_exports, {
7174
7180
  listWorktrees: () => listWorktrees,
7175
7181
  loadConfig: () => loadConfig,
7176
7182
  loadMeshRefineConfig: () => loadMeshRefineConfig,
7183
+ loadMeshWorktreeBootstrapConfig: () => loadMeshWorktreeBootstrapConfig,
7177
7184
  loadState: () => loadState,
7178
7185
  logCommand: () => logCommand,
7179
7186
  markSetupComplete: () => markSetupComplete,
@@ -7225,6 +7232,7 @@ __export(index_exports, {
7225
7232
  resolveWorktreePath: () => resolveWorktreePath,
7226
7233
  runAsyncBatch: () => runAsyncBatch,
7227
7234
  runGit: () => runGit,
7235
+ runMeshWorktreeBootstrap: () => runMeshWorktreeBootstrap,
7228
7236
  saveConfig: () => saveConfig,
7229
7237
  saveState: () => saveState,
7230
7238
  setDebugRuntimeConfig: () => setDebugRuntimeConfig,
@@ -7246,7 +7254,8 @@ __export(index_exports, {
7246
7254
  updateTaskStatus: () => updateTaskStatus,
7247
7255
  upsertSavedProviderSession: () => upsertSavedProviderSession,
7248
7256
  validateMeshRefineConfig: () => validateMeshRefineConfig,
7249
- validateMeshTaskModeRequest: () => validateMeshTaskModeRequest
7257
+ validateMeshTaskModeRequest: () => validateMeshTaskModeRequest,
7258
+ validateMeshWorktreeBootstrapConfig: () => validateMeshWorktreeBootstrapConfig
7250
7259
  });
7251
7260
  module.exports = __toCommonJS(index_exports);
7252
7261
  init_repo_mesh_types();
@@ -8316,10 +8325,17 @@ async function gitCheckpoint(workspace, message, includeUntracked) {
8316
8325
  } catch (err) {
8317
8326
  const output = (err?.stdout || "") + (err?.stderr || "");
8318
8327
  if (/nothing to commit/i.test(output)) {
8319
- throw new GitCommandError("nothing_to_commit", "Nothing to commit \u2014 working tree is clean.", {
8320
- stdout: err?.stdout,
8321
- stderr: err?.stderr
8322
- });
8328
+ return {
8329
+ workspace: repo.workspace,
8330
+ repoRoot,
8331
+ isGitRepo: true,
8332
+ message: fullMsg,
8333
+ status: "skipped",
8334
+ skipped: true,
8335
+ noop: true,
8336
+ reason: "nothing_to_commit",
8337
+ lastCheckedAt: Date.now()
8338
+ };
8323
8339
  }
8324
8340
  throw err;
8325
8341
  }
@@ -8329,6 +8345,7 @@ async function gitCheckpoint(workspace, message, includeUntracked) {
8329
8345
  isGitRepo: true,
8330
8346
  commit: commitSha,
8331
8347
  message: fullMsg,
8348
+ status: "created",
8332
8349
  lastCheckedAt: Date.now()
8333
8350
  };
8334
8351
  }
@@ -9032,6 +9049,7 @@ var MESH_REFINE_CONFIG_SCHEMA = {
9032
9049
  category: { enum: [...MESH_REFINE_VALIDATION_CATEGORIES, "custom"] },
9033
9050
  cwd: { type: "string" },
9034
9051
  timeoutMs: { type: "number", minimum: 1e3, maximum: 6e5 },
9052
+ outputLimitBytes: { type: "number", minimum: 1024, maximum: 1048576 },
9035
9053
  env: { type: "object", additionalProperties: { type: "string" } }
9036
9054
  }
9037
9055
  }
@@ -9049,6 +9067,7 @@ var MESH_REFINE_CONFIG_SCHEMA = {
9049
9067
  category: { enum: [...MESH_REFINE_VALIDATION_CATEGORIES, "custom"] },
9050
9068
  cwd: { type: "string" },
9051
9069
  timeoutMs: { type: "number", minimum: 1e3, maximum: 6e5 },
9070
+ outputLimitBytes: { type: "number", minimum: 1024, maximum: 1048576 },
9052
9071
  env: { type: "object", additionalProperties: { type: "string" } }
9053
9072
  }
9054
9073
  }
@@ -9057,7 +9076,7 @@ var MESH_REFINE_CONFIG_SCHEMA = {
9057
9076
  }
9058
9077
  }
9059
9078
  };
9060
- function isRecord(value) {
9079
+ function isMeshConfigRecord(value) {
9061
9080
  return !!value && typeof value === "object" && !Array.isArray(value);
9062
9081
  }
9063
9082
  function tokenizeCommandString(command) {
@@ -9072,8 +9091,8 @@ function tokenizeCommandString(command) {
9072
9091
  function validateCategory(value) {
9073
9092
  return typeof value === "string" && [...MESH_REFINE_VALIDATION_CATEGORIES, "custom"].includes(value) ? value : "custom";
9074
9093
  }
9075
- function normalizeCommandConfig(entry, source) {
9076
- if (!isRecord(entry) || typeof entry.command !== "string") {
9094
+ function normalizeMeshCommandConfig(entry, source) {
9095
+ if (!isMeshConfigRecord(entry) || typeof entry.command !== "string") {
9077
9096
  return { rejected: { source, reason: "validation command must be an object with a command string" } };
9078
9097
  }
9079
9098
  const commandText = entry.command.trim();
@@ -9100,7 +9119,10 @@ function normalizeCommandConfig(entry, source) {
9100
9119
  if (entry.timeoutMs !== void 0 && (typeof entry.timeoutMs !== "number" || !Number.isFinite(entry.timeoutMs) || entry.timeoutMs < 1e3 || entry.timeoutMs > 6e5)) {
9101
9120
  return { rejected: { source, command: commandText, reason: "timeoutMs must be between 1000 and 600000" } };
9102
9121
  }
9103
- if (entry.env !== void 0 && (!isRecord(entry.env) || !Object.values(entry.env).every((value) => typeof value === "string"))) {
9122
+ if (entry.outputLimitBytes !== void 0 && (typeof entry.outputLimitBytes !== "number" || !Number.isFinite(entry.outputLimitBytes) || entry.outputLimitBytes < 1024 || entry.outputLimitBytes > 1048576)) {
9123
+ return { rejected: { source, command: commandText, reason: "outputLimitBytes must be between 1024 and 1048576" } };
9124
+ }
9125
+ if (entry.env !== void 0 && (!isMeshConfigRecord(entry.env) || !Object.values(entry.env).every((value) => typeof value === "string"))) {
9104
9126
  return { rejected: { source, command: commandText, reason: "env must be an object of string values" } };
9105
9127
  }
9106
9128
  return {
@@ -9112,10 +9134,12 @@ function normalizeCommandConfig(entry, source) {
9112
9134
  source,
9113
9135
  ...typeof entry.cwd === "string" && entry.cwd.trim() ? { cwd: entry.cwd.trim() } : {},
9114
9136
  ...typeof entry.timeoutMs === "number" ? { timeoutMs: entry.timeoutMs } : {},
9115
- ...isRecord(entry.env) ? { env: entry.env } : {}
9137
+ ...typeof entry.outputLimitBytes === "number" ? { outputLimitBytes: entry.outputLimitBytes } : {},
9138
+ ...isMeshConfigRecord(entry.env) ? { env: entry.env } : {}
9116
9139
  }
9117
9140
  };
9118
9141
  }
9142
+ var isRecord = isMeshConfigRecord;
9119
9143
  function validateMeshRefineConfig(config, source = "inline") {
9120
9144
  const errors = [];
9121
9145
  const bootstrapCommands = [];
@@ -9134,14 +9158,14 @@ function validateMeshRefineConfig(config, source = "inline") {
9134
9158
  if (rawBootstrapCommands !== void 0 && !Array.isArray(rawBootstrapCommands)) errors.push("validation.bootstrapCommands must be an array");
9135
9159
  if (Array.isArray(rawBootstrapCommands)) {
9136
9160
  rawBootstrapCommands.forEach((entry, index) => {
9137
- const normalized = normalizeCommandConfig(entry, `${source}:validation.bootstrapCommands[${index}]`);
9161
+ const normalized = normalizeMeshCommandConfig(entry, `${source}:validation.bootstrapCommands[${index}]`);
9138
9162
  if (normalized.command) bootstrapCommands.push(normalized.command);
9139
9163
  if (normalized.rejected) rejectedCommands.push(normalized.rejected);
9140
9164
  });
9141
9165
  }
9142
9166
  if (Array.isArray(rawCommands)) {
9143
9167
  rawCommands.forEach((entry, index) => {
9144
- const normalized = normalizeCommandConfig(entry, `${source}:validation.commands[${index}]`);
9168
+ const normalized = normalizeMeshCommandConfig(entry, `${source}:validation.commands[${index}]`);
9145
9169
  if (normalized.command) commands.push(normalized.command);
9146
9170
  if (normalized.rejected) rejectedCommands.push(normalized.rejected);
9147
9171
  });
@@ -9253,6 +9277,190 @@ function resolveMeshRefineValidationPlan(mesh, workspace) {
9253
9277
  };
9254
9278
  }
9255
9279
 
9280
+ // src/mesh/worktree-bootstrap-config.ts
9281
+ var import_fs4 = require("fs");
9282
+ var import_path4 = require("path");
9283
+ var import_node_child_process3 = require("child_process");
9284
+ var import_node_util3 = require("util");
9285
+ var yaml2 = __toESM(require("js-yaml"));
9286
+ var MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS = [
9287
+ ".adhdev/worktree_bootstrap.json",
9288
+ ".adhdev/worktree_bootstrap.yaml",
9289
+ ".adhdev/worktree_bootstrap.yml",
9290
+ ".adhdev/worktree-bootstrap.json",
9291
+ ".adhdev/worktree-bootstrap.yaml",
9292
+ ".adhdev/worktree-bootstrap.yml"
9293
+ ];
9294
+ var MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA = {
9295
+ $schema: "https://json-schema.org/draft/2020-12/schema",
9296
+ title: "ADHDev Repo Mesh Worktree Bootstrap Config",
9297
+ type: "object",
9298
+ additionalProperties: false,
9299
+ required: ["version"],
9300
+ properties: {
9301
+ version: { const: 1 },
9302
+ enabled: { type: "boolean", default: true },
9303
+ runOnClone: { type: "boolean", default: true },
9304
+ required: { type: "boolean", default: true },
9305
+ staleInputs: { type: "array", maxItems: 16, items: { type: "string", minLength: 1 } },
9306
+ commands: {
9307
+ type: "array",
9308
+ minItems: 1,
9309
+ maxItems: 4,
9310
+ items: {
9311
+ type: "object",
9312
+ additionalProperties: false,
9313
+ required: ["command"],
9314
+ properties: {
9315
+ command: { type: "string", minLength: 1 },
9316
+ args: { type: "array", items: { type: "string" } },
9317
+ category: { enum: ["typecheck", "test", "lint", "build", "custom"] },
9318
+ cwd: { type: "string" },
9319
+ timeoutMs: { type: "number", minimum: 1e3, maximum: 6e5 },
9320
+ outputLimitBytes: { type: "number", minimum: 1024, maximum: 1048576 },
9321
+ env: { type: "object", additionalProperties: { type: "string" } }
9322
+ }
9323
+ }
9324
+ }
9325
+ }
9326
+ };
9327
+ var DEFAULT_TIMEOUT_MS2 = 12e4;
9328
+ var DEFAULT_OUTPUT_LIMIT_BYTES = 128 * 1024;
9329
+ var OUTPUT_SUMMARY_CHARS = 2e3;
9330
+ function parseConfigText2(path28, text) {
9331
+ if (/\.json$/i.test(path28)) return JSON.parse(text);
9332
+ return yaml2.load(text);
9333
+ }
9334
+ function truncateOutput(value) {
9335
+ const text = typeof value === "string" ? value : value == null ? "" : String(value);
9336
+ if (text.length <= OUTPUT_SUMMARY_CHARS) return text;
9337
+ return `${text.slice(0, OUTPUT_SUMMARY_CHARS)}
9338
+ [truncated ${text.length - OUTPUT_SUMMARY_CHARS} chars]`;
9339
+ }
9340
+ function validateMeshWorktreeBootstrapConfig(config, source = "inline") {
9341
+ const errors = [];
9342
+ const commands = [];
9343
+ const rejectedCommands = [];
9344
+ if (!isMeshConfigRecord(config)) return { valid: false, errors: ["config must be an object"], commands, rejectedCommands };
9345
+ if (config.version !== 1) errors.push("version must be 1");
9346
+ if (config.enabled !== void 0 && typeof config.enabled !== "boolean") errors.push("enabled must be a boolean when provided");
9347
+ if (config.runOnClone !== void 0 && typeof config.runOnClone !== "boolean") errors.push("runOnClone must be a boolean when provided");
9348
+ if (config.required !== void 0 && typeof config.required !== "boolean") errors.push("required must be a boolean when provided");
9349
+ if (config.staleInputs !== void 0 && (!Array.isArray(config.staleInputs) || !config.staleInputs.every((input) => typeof input === "string" && input.trim()))) {
9350
+ errors.push("staleInputs must be an array of non-empty strings when provided");
9351
+ }
9352
+ if (config.commands !== void 0 && !Array.isArray(config.commands)) errors.push("commands must be an array");
9353
+ if (Array.isArray(config.commands)) {
9354
+ config.commands.forEach((entry, index) => {
9355
+ const normalized = normalizeMeshCommandConfig(entry, `${source}:commands[${index}]`);
9356
+ if (normalized.command) commands.push(normalized.command);
9357
+ if (normalized.rejected) rejectedCommands.push(normalized.rejected);
9358
+ });
9359
+ }
9360
+ if (config.enabled !== false && config.runOnClone !== false && commands.length === 0) errors.push("commands must contain at least one command when bootstrap is enabled");
9361
+ if (rejectedCommands.length) errors.push("one or more bootstrap commands are invalid");
9362
+ return { valid: errors.length === 0, errors, commands, rejectedCommands };
9363
+ }
9364
+ function loadMeshWorktreeBootstrapConfig(mesh, workspace) {
9365
+ const inline = mesh?.worktreeBootstrapConfig || mesh?.policy?.worktreeBootstrapConfig || mesh?.policy?.worktreeBootstrap;
9366
+ if (inline !== void 0) {
9367
+ const validation = validateMeshWorktreeBootstrapConfig(inline, "mesh.policy.worktreeBootstrapConfig");
9368
+ if (!validation.valid) return { source: "mesh.policy.worktreeBootstrapConfig", sourceType: "invalid", error: String(validation.rejectedCommands[0]?.reason || validation.errors.join("; ")) };
9369
+ return { config: inline, source: "mesh.policy.worktreeBootstrapConfig", sourceType: "mesh_policy" };
9370
+ }
9371
+ for (const relative3 of MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS) {
9372
+ const configPath = (0, import_path4.join)(workspace, relative3);
9373
+ if (!(0, import_fs4.existsSync)(configPath)) continue;
9374
+ try {
9375
+ const parsed = parseConfigText2(configPath, (0, import_fs4.readFileSync)(configPath, "utf-8"));
9376
+ const validation = validateMeshWorktreeBootstrapConfig(parsed, relative3);
9377
+ if (!validation.valid) return { source: relative3, sourceType: "invalid", path: configPath, error: String(validation.rejectedCommands[0]?.reason || validation.errors.join("; ")) };
9378
+ return { config: parsed, source: relative3, sourceType: "repo_file", path: configPath };
9379
+ } catch (error) {
9380
+ return { source: relative3, sourceType: "invalid", path: configPath, error: error?.message || String(error) };
9381
+ }
9382
+ }
9383
+ return { source: "unavailable", sourceType: "unavailable", error: `No worktree bootstrap config found. Checked: ${MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS.join(", ")}` };
9384
+ }
9385
+ async function runMeshWorktreeBootstrap(mesh, workspace) {
9386
+ const loaded = loadMeshWorktreeBootstrapConfig(mesh, workspace);
9387
+ if (!loaded.config) {
9388
+ return { status: "not_configured", required: false, configSource: loaded.source, configSourceType: loaded.sourceType, error: loaded.error };
9389
+ }
9390
+ const required = loaded.config.required !== false;
9391
+ if (loaded.config.enabled === false || loaded.config.runOnClone === false) {
9392
+ return { status: "disabled", required, configSource: loaded.path || loaded.source, configSourceType: loaded.sourceType };
9393
+ }
9394
+ const validation = validateMeshWorktreeBootstrapConfig(loaded.config, loaded.source);
9395
+ if (!validation.valid) {
9396
+ return { status: "failed", required, configSource: loaded.path || loaded.source, configSourceType: "invalid", error: String(validation.rejectedCommands[0]?.reason || validation.errors.join("; ")), commandsRun: [] };
9397
+ }
9398
+ const execFileAsync3 = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
9399
+ const state = {
9400
+ status: "running",
9401
+ required,
9402
+ configSource: loaded.path || loaded.source,
9403
+ configSourceType: loaded.sourceType,
9404
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
9405
+ commandsRun: [],
9406
+ staleInputs: loaded.config.staleInputs
9407
+ };
9408
+ for (const command of validation.commands) {
9409
+ const cwd = command.cwd ? (0, import_path4.resolve)(workspace, command.cwd) : workspace;
9410
+ const startedAt = Date.now();
9411
+ state.lastCommand = command.displayCommand;
9412
+ try {
9413
+ const result = await execFileAsync3(command.command, command.args, {
9414
+ cwd,
9415
+ encoding: "utf8",
9416
+ timeout: command.timeoutMs || DEFAULT_TIMEOUT_MS2,
9417
+ maxBuffer: command.outputLimitBytes || DEFAULT_OUTPUT_LIMIT_BYTES,
9418
+ env: { ...process.env, CI: process.env.CI || "1", ...command.env || {} },
9419
+ windowsHide: true
9420
+ });
9421
+ state.commandsRun?.push({
9422
+ command: command.command,
9423
+ args: command.args,
9424
+ displayCommand: command.displayCommand,
9425
+ category: command.category,
9426
+ source: command.source,
9427
+ cwd,
9428
+ passed: true,
9429
+ durationMs: Date.now() - startedAt,
9430
+ exitCode: 0,
9431
+ stdout: truncateOutput(result.stdout),
9432
+ stderr: truncateOutput(result.stderr)
9433
+ });
9434
+ } catch (error) {
9435
+ const exitCode = typeof error?.code === "number" ? error.code : null;
9436
+ state.status = "failed";
9437
+ state.exitCode = exitCode;
9438
+ state.error = error?.message || String(error);
9439
+ state.completedAt = (/* @__PURE__ */ new Date()).toISOString();
9440
+ state.commandsRun?.push({
9441
+ command: command.command,
9442
+ args: command.args,
9443
+ displayCommand: command.displayCommand,
9444
+ category: command.category,
9445
+ source: command.source,
9446
+ cwd,
9447
+ passed: false,
9448
+ durationMs: Date.now() - startedAt,
9449
+ exitCode,
9450
+ signal: typeof error?.signal === "string" ? error.signal : null,
9451
+ timedOut: error?.killed === true || /timed out/i.test(String(error?.message || "")),
9452
+ stdout: truncateOutput(error?.stdout),
9453
+ stderr: truncateOutput(error?.stderr || error?.message)
9454
+ });
9455
+ return state;
9456
+ }
9457
+ }
9458
+ state.status = "ready";
9459
+ state.exitCode = 0;
9460
+ state.completedAt = (/* @__PURE__ */ new Date()).toISOString();
9461
+ return state;
9462
+ }
9463
+
9256
9464
  // src/mesh/mesh-sync.ts
9257
9465
  init_mesh_config();
9258
9466
  async function syncMeshes(transport) {
@@ -9904,6 +10112,134 @@ function buildMeshActiveWork(opts) {
9904
10112
  }
9905
10113
  return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
9906
10114
  }
10115
+ function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
10116
+ const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
10117
+ const reasonCounts = {};
10118
+ for (const entry of staleDirectWork) {
10119
+ const reason = entry.staleReason || "unknown";
10120
+ reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
10121
+ }
10122
+ return {
10123
+ count: staleDirectWork.length,
10124
+ sampleLimit,
10125
+ sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
10126
+ taskId: entry.taskId,
10127
+ status: entry.status,
10128
+ nodeId: entry.nodeId,
10129
+ sessionId: entry.sessionId,
10130
+ taskTitle: entry.taskTitle,
10131
+ createdAt: entry.createdAt,
10132
+ staleReason: entry.staleReason
10133
+ })),
10134
+ reasonCounts,
10135
+ detailHint: opts.detailHint || "Stale direct records are historical recovery evidence only. Use mesh_task_history for full ledger details, or request includeStaleDirectWorkDetails when supported by the caller.",
10136
+ ...opts.note ? { note: opts.note } : {}
10137
+ };
10138
+ }
10139
+
10140
+ // src/mesh/mesh-refine-status.ts
10141
+ function readString3(value) {
10142
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
10143
+ }
10144
+ function readRecord(value) {
10145
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
10146
+ }
10147
+ function eventStatus(event, fallback) {
10148
+ if (event === "refine:accepted") return "accepted";
10149
+ if (event === "refine:completed") return "completed";
10150
+ if (event === "refine:failed") return "failed";
10151
+ if (fallback === "completed" || fallback === "failed" || fallback === "accepted") return fallback;
10152
+ return void 0;
10153
+ }
10154
+ function ledgerStatus(kind, fallback) {
10155
+ if (kind === "task_completed") return "completed";
10156
+ if (kind === "task_failed") return "failed";
10157
+ if (fallback === "accepted") return "accepted";
10158
+ return "running";
10159
+ }
10160
+ function instructionForStatus(status) {
10161
+ if (status === "accepted") return "Refine job is accepted; wait for asyncRefineJobs or pendingCoordinatorEvents to report running/completed/failed.";
10162
+ if (status === "running") return "Refine job is running; do not poll the ledger repeatedly. Watch asyncRefineJobs or pendingCoordinatorEvents for the terminal result.";
10163
+ if (status === "completed") return "Refine job completed; inspect branch convergence and cleanup evidence before reporting final merge state.";
10164
+ return "Refine job failed; inspect result/finalBranchConvergenceState in mesh_task_history, fix the blocker, then rerun mesh_refine_node when ready.";
10165
+ }
10166
+ function mergeJob(jobs, patch) {
10167
+ const jobId = readString3(patch.jobId);
10168
+ if (!jobId) return;
10169
+ const previous = jobs.get(jobId);
10170
+ const status = patch.status || previous?.status || "running";
10171
+ const definedPatch = Object.fromEntries(
10172
+ Object.entries(patch).filter(([, value]) => value !== void 0)
10173
+ );
10174
+ jobs.set(jobId, {
10175
+ ...previous,
10176
+ ...definedPatch,
10177
+ jobId,
10178
+ status,
10179
+ instruction: instructionForStatus(status)
10180
+ });
10181
+ }
10182
+ function buildMeshAsyncRefineJobs(args) {
10183
+ const jobs = /* @__PURE__ */ new Map();
10184
+ for (const entry of args.ledgerEntries || []) {
10185
+ const payload = readRecord(entry.payload);
10186
+ if (payload?.source !== "refine_mesh_node_async_job") continue;
10187
+ const refineJob = readRecord(payload.refineJob);
10188
+ const result = readRecord(payload.result);
10189
+ const finalState = readRecord(payload.finalBranchConvergenceState) || readRecord(result?.finalBranchConvergenceState);
10190
+ const jobId = readString3(refineJob?.jobId);
10191
+ if (!jobId) continue;
10192
+ const status = ledgerStatus(entry.kind, readString3(refineJob?.status));
10193
+ mergeJob(jobs, {
10194
+ jobId,
10195
+ interactionId: readString3(refineJob?.interactionId),
10196
+ status,
10197
+ meshId: readString3(refineJob?.meshId) || args.meshId,
10198
+ nodeId: readString3(refineJob?.nodeId) || entry.nodeId,
10199
+ targetNodeId: readString3(refineJob?.nodeId) || entry.nodeId,
10200
+ targetDaemonId: readString3(refineJob?.targetDaemonId),
10201
+ workspace: readString3(refineJob?.workspace),
10202
+ branch: readString3(result?.branch) || readString3(finalState?.branch),
10203
+ into: readString3(result?.into) || readString3(finalState?.baseBranch),
10204
+ startedAt: readString3(refineJob?.startedAt),
10205
+ completedAt: readString3(refineJob?.completedAt),
10206
+ retryOfJobId: readString3(refineJob?.retryOfJobId) || readString3(payload.retryOfJobId),
10207
+ lastLedgerKind: entry.kind,
10208
+ lastUpdatedAt: entry.timestamp
10209
+ });
10210
+ }
10211
+ for (const event of args.pendingEvents || []) {
10212
+ const metadata = readRecord(event.metadataEvent);
10213
+ if (metadata?.source !== "refine_mesh_node_async_job") continue;
10214
+ const result = readRecord(metadata.result);
10215
+ const finalState = readRecord(result?.finalBranchConvergenceState);
10216
+ const jobId = readString3(metadata.jobId);
10217
+ if (!jobId) continue;
10218
+ const status = eventStatus(event.event, readString3(metadata.status));
10219
+ mergeJob(jobs, {
10220
+ jobId,
10221
+ interactionId: readString3(metadata.interactionId),
10222
+ ...status ? { status } : {},
10223
+ meshId: readString3(metadata.meshId) || event.meshId || args.meshId,
10224
+ nodeId: readString3(metadata.nodeId) || event.nodeId,
10225
+ targetNodeId: readString3(metadata.nodeId) || event.nodeId,
10226
+ targetDaemonId: readString3(metadata.targetDaemonId),
10227
+ workspace: readString3(metadata.workspace) || event.workspace,
10228
+ branch: readString3(result?.branch) || readString3(finalState?.branch),
10229
+ into: readString3(result?.into) || readString3(finalState?.baseBranch),
10230
+ startedAt: readString3(metadata.startedAt),
10231
+ completedAt: readString3(metadata.completedAt),
10232
+ retryOfJobId: readString3(metadata.retryOfJobId),
10233
+ lastEvent: event.event,
10234
+ lastUpdatedAt: new Date(event.queuedAt).toISOString()
10235
+ });
10236
+ }
10237
+ return Array.from(jobs.values()).sort((a, b) => {
10238
+ const aTime = new Date(a.lastUpdatedAt || a.startedAt || "").getTime();
10239
+ const bTime = new Date(b.lastUpdatedAt || b.startedAt || "").getTime();
10240
+ return (Number.isFinite(bTime) ? bTime : 0) - (Number.isFinite(aTime) ? aTime : 0);
10241
+ });
10242
+ }
9907
10243
 
9908
10244
  // src/index.ts
9909
10245
  init_mesh_host_ownership();
@@ -10020,8 +10356,8 @@ var P2pRelayFailureError = class extends Error {
10020
10356
  };
10021
10357
 
10022
10358
  // src/config/state-store.ts
10023
- var import_fs8 = require("fs");
10024
- var import_path7 = require("path");
10359
+ var import_fs9 = require("fs");
10360
+ var import_path8 = require("path");
10025
10361
  init_config();
10026
10362
  var DEFAULT_STATE = {
10027
10363
  recentActivity: [],
@@ -10035,7 +10371,7 @@ function isPlainObject2(value) {
10035
10371
  return !!value && typeof value === "object" && !Array.isArray(value);
10036
10372
  }
10037
10373
  function getStatePath() {
10038
- return (0, import_path7.join)(getConfigDir(), "state.json");
10374
+ return (0, import_path8.join)(getConfigDir(), "state.json");
10039
10375
  }
10040
10376
  function normalizeState(raw) {
10041
10377
  const parsed = isPlainObject2(raw) ? raw : {};
@@ -10071,11 +10407,11 @@ function normalizeState(raw) {
10071
10407
  }
10072
10408
  function loadState() {
10073
10409
  const statePath = getStatePath();
10074
- if (!(0, import_fs8.existsSync)(statePath)) {
10410
+ if (!(0, import_fs9.existsSync)(statePath)) {
10075
10411
  return { ...DEFAULT_STATE };
10076
10412
  }
10077
10413
  try {
10078
- const raw = (0, import_fs8.readFileSync)(statePath, "utf-8");
10414
+ const raw = (0, import_fs9.readFileSync)(statePath, "utf-8");
10079
10415
  return normalizeState(JSON.parse(raw));
10080
10416
  } catch {
10081
10417
  return { ...DEFAULT_STATE };
@@ -10084,7 +10420,7 @@ function loadState() {
10084
10420
  function saveState(state) {
10085
10421
  const statePath = getStatePath();
10086
10422
  const normalized = normalizeState(state);
10087
- (0, import_fs8.writeFileSync)(statePath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
10423
+ (0, import_fs9.writeFileSync)(statePath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
10088
10424
  }
10089
10425
  function resetState() {
10090
10426
  saveState({ ...DEFAULT_STATE });
@@ -10093,7 +10429,7 @@ function resetState() {
10093
10429
  // src/detection/ide-detector.ts
10094
10430
  var import_child_process2 = require("child_process");
10095
10431
  var import_util = require("util");
10096
- var import_fs9 = require("fs");
10432
+ var import_fs10 = require("fs");
10097
10433
  var import_os2 = require("os");
10098
10434
  var path10 = __toESM(require("path"));
10099
10435
  var execAsync2 = (0, import_util.promisify)(import_child_process2.exec);
@@ -10118,7 +10454,7 @@ function findCliCommand(command) {
10118
10454
  if (path10.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~")) {
10119
10455
  const candidate = trimmed.startsWith("~") ? path10.join((0, import_os2.homedir)(), trimmed.slice(1)) : trimmed;
10120
10456
  const resolved = path10.isAbsolute(candidate) ? candidate : path10.resolve(candidate);
10121
- return (0, import_fs9.existsSync)(resolved) ? resolved : null;
10457
+ return (0, import_fs10.existsSync)(resolved) ? resolved : null;
10122
10458
  }
10123
10459
  const isWin = (0, import_os2.platform)() === "win32";
10124
10460
  const paths = (process.env.PATH || "").split(isWin ? ";" : ":");
@@ -10128,8 +10464,8 @@ function findCliCommand(command) {
10128
10464
  for (const ext of exes) {
10129
10465
  const fullPath = path10.join(p, trimmed + ext);
10130
10466
  try {
10131
- if ((0, import_fs9.existsSync)(fullPath)) {
10132
- const stat2 = (0, import_fs9.statSync)(fullPath);
10467
+ if ((0, import_fs10.existsSync)(fullPath)) {
10468
+ const stat2 = (0, import_fs10.statSync)(fullPath);
10133
10469
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
10134
10470
  return fullPath;
10135
10471
  }
@@ -10158,9 +10494,9 @@ function checkPathExists(paths) {
10158
10494
  if (normalized.includes("*")) {
10159
10495
  const username = home.split(/[\\/]/).pop() || "";
10160
10496
  const resolved = normalized.replace("*", username);
10161
- if ((0, import_fs9.existsSync)(resolved)) return resolved;
10497
+ if ((0, import_fs10.existsSync)(resolved)) return resolved;
10162
10498
  } else {
10163
- if ((0, import_fs9.existsSync)(normalized)) return normalized;
10499
+ if ((0, import_fs10.existsSync)(normalized)) return normalized;
10164
10500
  }
10165
10501
  }
10166
10502
  return null;
@@ -10174,7 +10510,7 @@ async function detectIDEs(providerLoader) {
10174
10510
  let resolvedCli = cliPath;
10175
10511
  if (!resolvedCli && appPath && os22 === "darwin") {
10176
10512
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
10177
- if ((0, import_fs9.existsSync)(bundledCli)) resolvedCli = bundledCli;
10513
+ if ((0, import_fs10.existsSync)(bundledCli)) resolvedCli = bundledCli;
10178
10514
  }
10179
10515
  if (!resolvedCli && appPath && os22 === "win32") {
10180
10516
  const { dirname: dirname9 } = await import("path");
@@ -10187,7 +10523,7 @@ async function detectIDEs(providerLoader) {
10187
10523
  `${appDir}\\\\resources\\\\app\\\\bin\\\\${def.cli}.cmd`
10188
10524
  ];
10189
10525
  for (const c of candidates) {
10190
- if ((0, import_fs9.existsSync)(c)) {
10526
+ if ((0, import_fs10.existsSync)(c)) {
10191
10527
  resolvedCli = c;
10192
10528
  break;
10193
10529
  }
@@ -10503,7 +10839,7 @@ var DaemonCdpManager = class {
10503
10839
  * Returns multiple entries if multiple IDE windows are open on same port
10504
10840
  */
10505
10841
  static listAllTargets(port) {
10506
- return new Promise((resolve16) => {
10842
+ return new Promise((resolve17) => {
10507
10843
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
10508
10844
  let data = "";
10509
10845
  res.on("data", (chunk) => data += chunk.toString());
@@ -10519,16 +10855,16 @@ var DaemonCdpManager = class {
10519
10855
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
10520
10856
  );
10521
10857
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
10522
- resolve16(mainPages.length > 0 ? mainPages : fallbackPages);
10858
+ resolve17(mainPages.length > 0 ? mainPages : fallbackPages);
10523
10859
  } catch {
10524
- resolve16([]);
10860
+ resolve17([]);
10525
10861
  }
10526
10862
  });
10527
10863
  });
10528
- req.on("error", () => resolve16([]));
10864
+ req.on("error", () => resolve17([]));
10529
10865
  req.setTimeout(2e3, () => {
10530
10866
  req.destroy();
10531
- resolve16([]);
10867
+ resolve17([]);
10532
10868
  });
10533
10869
  });
10534
10870
  }
@@ -10568,7 +10904,7 @@ var DaemonCdpManager = class {
10568
10904
  }
10569
10905
  }
10570
10906
  findTargetOnPort(port) {
10571
- return new Promise((resolve16) => {
10907
+ return new Promise((resolve17) => {
10572
10908
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
10573
10909
  let data = "";
10574
10910
  res.on("data", (chunk) => data += chunk.toString());
@@ -10579,7 +10915,7 @@ var DaemonCdpManager = class {
10579
10915
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
10580
10916
  );
10581
10917
  if (pages.length === 0) {
10582
- resolve16(targets.find((t) => t.webSocketDebuggerUrl) || null);
10918
+ resolve17(targets.find((t) => t.webSocketDebuggerUrl) || null);
10583
10919
  return;
10584
10920
  }
10585
10921
  const titleFilteredPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -10598,25 +10934,25 @@ var DaemonCdpManager = class {
10598
10934
  this._targetId = selected.target.id;
10599
10935
  }
10600
10936
  this._pageTitle = selected.target.title || "";
10601
- resolve16(selected.target);
10937
+ resolve17(selected.target);
10602
10938
  return;
10603
10939
  }
10604
10940
  if (previousTargetId) {
10605
10941
  this.log(`[CDP] Target ${previousTargetId} not found in page list`);
10606
- resolve16(null);
10942
+ resolve17(null);
10607
10943
  return;
10608
10944
  }
10609
10945
  this._pageTitle = list[0]?.title || "";
10610
- resolve16(list[0]);
10946
+ resolve17(list[0]);
10611
10947
  } catch {
10612
- resolve16(null);
10948
+ resolve17(null);
10613
10949
  }
10614
10950
  });
10615
10951
  });
10616
- req.on("error", () => resolve16(null));
10952
+ req.on("error", () => resolve17(null));
10617
10953
  req.setTimeout(2e3, () => {
10618
10954
  req.destroy();
10619
- resolve16(null);
10955
+ resolve17(null);
10620
10956
  });
10621
10957
  });
10622
10958
  }
@@ -10627,7 +10963,7 @@ var DaemonCdpManager = class {
10627
10963
  this.extensionProviders = providers;
10628
10964
  }
10629
10965
  connectToTarget(wsUrl) {
10630
- return new Promise((resolve16) => {
10966
+ return new Promise((resolve17) => {
10631
10967
  this.ws = new import_ws.default(wsUrl);
10632
10968
  this.ws.on("open", async () => {
10633
10969
  this._connected = true;
@@ -10637,17 +10973,17 @@ var DaemonCdpManager = class {
10637
10973
  }
10638
10974
  this.connectBrowserWs().catch(() => {
10639
10975
  });
10640
- resolve16(true);
10976
+ resolve17(true);
10641
10977
  });
10642
10978
  this.ws.on("message", (data) => {
10643
10979
  try {
10644
10980
  const msg = JSON.parse(data.toString());
10645
10981
  if (msg.id && this.pending.has(msg.id)) {
10646
- const { resolve: resolve17, reject } = this.pending.get(msg.id);
10982
+ const { resolve: resolve18, reject } = this.pending.get(msg.id);
10647
10983
  this.pending.delete(msg.id);
10648
10984
  this.failureCount = 0;
10649
10985
  if (msg.error) reject(new Error(msg.error.message));
10650
- else resolve17(msg.result);
10986
+ else resolve18(msg.result);
10651
10987
  } else if (msg.method === "Runtime.executionContextCreated") {
10652
10988
  this.contexts.add(msg.params.context.id);
10653
10989
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -10670,7 +11006,7 @@ var DaemonCdpManager = class {
10670
11006
  this.ws.on("error", (err) => {
10671
11007
  this.log(`[CDP] WebSocket error: ${err.message}`);
10672
11008
  this._connected = false;
10673
- resolve16(false);
11009
+ resolve17(false);
10674
11010
  });
10675
11011
  });
10676
11012
  }
@@ -10684,7 +11020,7 @@ var DaemonCdpManager = class {
10684
11020
  return;
10685
11021
  }
10686
11022
  this.log(`[CDP] Connecting browser WS for target discovery...`);
10687
- await new Promise((resolve16, reject) => {
11023
+ await new Promise((resolve17, reject) => {
10688
11024
  this.browserWs = new import_ws.default(browserWsUrl);
10689
11025
  this.browserWs.on("open", async () => {
10690
11026
  this._browserConnected = true;
@@ -10694,16 +11030,16 @@ var DaemonCdpManager = class {
10694
11030
  } catch (e) {
10695
11031
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
10696
11032
  }
10697
- resolve16();
11033
+ resolve17();
10698
11034
  });
10699
11035
  this.browserWs.on("message", (data) => {
10700
11036
  try {
10701
11037
  const msg = JSON.parse(data.toString());
10702
11038
  if (msg.id && this.browserPending.has(msg.id)) {
10703
- const { resolve: resolve17, reject: reject2 } = this.browserPending.get(msg.id);
11039
+ const { resolve: resolve18, reject: reject2 } = this.browserPending.get(msg.id);
10704
11040
  this.browserPending.delete(msg.id);
10705
11041
  if (msg.error) reject2(new Error(msg.error.message));
10706
- else resolve17(msg.result);
11042
+ else resolve18(msg.result);
10707
11043
  }
10708
11044
  } catch {
10709
11045
  }
@@ -10723,31 +11059,31 @@ var DaemonCdpManager = class {
10723
11059
  }
10724
11060
  }
10725
11061
  getBrowserWsUrl() {
10726
- return new Promise((resolve16) => {
11062
+ return new Promise((resolve17) => {
10727
11063
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
10728
11064
  let data = "";
10729
11065
  res.on("data", (chunk) => data += chunk.toString());
10730
11066
  res.on("end", () => {
10731
11067
  try {
10732
11068
  const info = JSON.parse(data);
10733
- resolve16(info.webSocketDebuggerUrl || null);
11069
+ resolve17(info.webSocketDebuggerUrl || null);
10734
11070
  } catch {
10735
- resolve16(null);
11071
+ resolve17(null);
10736
11072
  }
10737
11073
  });
10738
11074
  });
10739
- req.on("error", () => resolve16(null));
11075
+ req.on("error", () => resolve17(null));
10740
11076
  req.setTimeout(3e3, () => {
10741
11077
  req.destroy();
10742
- resolve16(null);
11078
+ resolve17(null);
10743
11079
  });
10744
11080
  });
10745
11081
  }
10746
11082
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
10747
- return new Promise((resolve16, reject) => {
11083
+ return new Promise((resolve17, reject) => {
10748
11084
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
10749
11085
  const id = this.browserMsgId++;
10750
- this.browserPending.set(id, { resolve: resolve16, reject });
11086
+ this.browserPending.set(id, { resolve: resolve17, reject });
10751
11087
  this.browserWs.send(JSON.stringify({ id, method, params }));
10752
11088
  setTimeout(() => {
10753
11089
  if (this.browserPending.has(id)) {
@@ -10787,11 +11123,11 @@ var DaemonCdpManager = class {
10787
11123
  }
10788
11124
  // ─── CDP Protocol ────────────────────────────────────────
10789
11125
  sendInternal(method, params = {}, timeoutMs = 15e3) {
10790
- return new Promise((resolve16, reject) => {
11126
+ return new Promise((resolve17, reject) => {
10791
11127
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
10792
11128
  if (this.ws.readyState !== import_ws.default.OPEN) return reject(new Error("WebSocket not open"));
10793
11129
  const id = this.msgId++;
10794
- this.pending.set(id, { resolve: resolve16, reject });
11130
+ this.pending.set(id, { resolve: resolve17, reject });
10795
11131
  this.ws.send(JSON.stringify({ id, method, params }));
10796
11132
  setTimeout(() => {
10797
11133
  if (this.pending.has(id)) {
@@ -11040,7 +11376,7 @@ var DaemonCdpManager = class {
11040
11376
  const browserWs = this.browserWs;
11041
11377
  let msgId = this.browserMsgId;
11042
11378
  const sendWs = (method, params = {}, sessionId) => {
11043
- return new Promise((resolve16, reject) => {
11379
+ return new Promise((resolve17, reject) => {
11044
11380
  const mid = msgId++;
11045
11381
  this.browserMsgId = msgId;
11046
11382
  const handler = (raw) => {
@@ -11049,7 +11385,7 @@ var DaemonCdpManager = class {
11049
11385
  if (msg.id === mid) {
11050
11386
  browserWs.removeListener("message", handler);
11051
11387
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
11052
- else resolve16(msg.result);
11388
+ else resolve17(msg.result);
11053
11389
  }
11054
11390
  } catch {
11055
11391
  }
@@ -11250,14 +11586,14 @@ var DaemonCdpManager = class {
11250
11586
  if (!ws || ws.readyState !== import_ws.default.OPEN) {
11251
11587
  throw new Error("CDP not connected");
11252
11588
  }
11253
- return new Promise((resolve16, reject) => {
11589
+ return new Promise((resolve17, reject) => {
11254
11590
  const id = getNextId();
11255
11591
  pendingMap.set(id, {
11256
11592
  resolve: (result) => {
11257
11593
  if (result?.result?.subtype === "error") {
11258
11594
  reject(new Error(result.result.description));
11259
11595
  } else {
11260
- resolve16(result?.result?.value);
11596
+ resolve17(result?.result?.value);
11261
11597
  }
11262
11598
  },
11263
11599
  reject
@@ -11289,10 +11625,10 @@ var DaemonCdpManager = class {
11289
11625
  throw new Error("CDP not connected");
11290
11626
  }
11291
11627
  const sendViaSession = (method, params = {}) => {
11292
- return new Promise((resolve16, reject) => {
11628
+ return new Promise((resolve17, reject) => {
11293
11629
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
11294
11630
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
11295
- pendingMap.set(id, { resolve: resolve16, reject });
11631
+ pendingMap.set(id, { resolve: resolve17, reject });
11296
11632
  ws.send(JSON.stringify({ id, sessionId, method, params }));
11297
11633
  setTimeout(() => {
11298
11634
  if (pendingMap.has(id)) {
@@ -16394,7 +16730,7 @@ function getSendChatInputEnvelope(args) {
16394
16730
  return normalizeInputEnvelope(args?.input ? { input: args.input } : args);
16395
16731
  }
16396
16732
  function sleep(ms) {
16397
- return new Promise((resolve16) => setTimeout(resolve16, ms));
16733
+ return new Promise((resolve17) => setTimeout(resolve17, ms));
16398
16734
  }
16399
16735
  async function waitOnceForFreshHermesCliStart(adapter, log) {
16400
16736
  if (adapter.cliType !== "hermes-cli") return;
@@ -16617,16 +16953,39 @@ function hasOverlappingVisibleConversationText(nativeMessages, ptyMessages) {
16617
16953
  return false;
16618
16954
  }
16619
16955
  function hasSafeNativeHistoryMapping(args) {
16956
+ const isCoordinatorTranscript = args.nativeMessages.some((m) => {
16957
+ const text = typeof m?.content === "string" ? m.content : JSON.stringify(m?.content || "");
16958
+ return text.includes("mesh_send_task") || text.includes("mesh_status") || text.includes("mesh_read_chat") || text.includes("mesh_launch_session");
16959
+ });
16620
16960
  const explicitSessionId = String(args.historySessionId || args.providerSessionId || "").trim();
16621
16961
  if (explicitSessionId) {
16622
16962
  const messageSessionIds = args.nativeMessages.map((message) => typeof message?.historySessionId === "string" ? message.historySessionId.trim() : "").filter(Boolean);
16623
- if (messageSessionIds.length === 0) return true;
16624
- return messageSessionIds.some((id) => id === explicitSessionId);
16963
+ if (messageSessionIds.length > 0) {
16964
+ return messageSessionIds.some((id) => id === explicitSessionId);
16965
+ }
16966
+ if (isCoordinatorTranscript && args.ptyMessages && args.ptyMessages.length > 0) {
16967
+ const ptyHasCoordinator = args.ptyMessages.some((m) => {
16968
+ const text = typeof m?.content === "string" ? m.content : JSON.stringify(m?.content || "");
16969
+ return text.includes("mesh_send_task") || text.includes("mesh_status") || text.includes("mesh_read_chat");
16970
+ });
16971
+ if (!ptyHasCoordinator) {
16972
+ return false;
16973
+ }
16974
+ }
16625
16975
  }
16626
16976
  const workspace = String(args.workspace || "").trim();
16627
16977
  if (!workspace) return false;
16628
16978
  const workspaceMatches = args.nativeMessages.some((message) => String(message?.workspace || "").trim() === workspace);
16629
16979
  if (!workspaceMatches) return false;
16980
+ if (isCoordinatorTranscript && args.ptyMessages && args.ptyMessages.length > 0) {
16981
+ const ptyHasCoordinator = args.ptyMessages.some((m) => {
16982
+ const text = typeof m?.content === "string" ? m.content : JSON.stringify(m?.content || "");
16983
+ return text.includes("mesh_send_task") || text.includes("mesh_status") || text.includes("mesh_read_chat");
16984
+ });
16985
+ if (!ptyHasCoordinator) {
16986
+ return false;
16987
+ }
16988
+ }
16630
16989
  if (!args.requireWorkspaceContentOverlap) return true;
16631
16990
  return hasOverlappingVisibleConversationText(args.nativeMessages, args.ptyMessages || []);
16632
16991
  }
@@ -17181,7 +17540,7 @@ function getCliVisibleTranscriptCount(adapter) {
17181
17540
  async function getStableExtensionBaseline(h) {
17182
17541
  const first = await readExtensionChatState(h);
17183
17542
  if (getStateMessageCount(first) > 0 || getStateLastSignature(first)) return first;
17184
- await new Promise((resolve16) => setTimeout(resolve16, 150));
17543
+ await new Promise((resolve17) => setTimeout(resolve17, 150));
17185
17544
  const second = await readExtensionChatState(h);
17186
17545
  return getStateMessageCount(second) >= getStateMessageCount(first) ? second : first;
17187
17546
  }
@@ -17189,7 +17548,7 @@ async function verifyExtensionSendObserved(h, before) {
17189
17548
  const beforeCount = getStateMessageCount(before);
17190
17549
  const beforeSignature = getStateLastSignature(before);
17191
17550
  for (let attempt = 0; attempt < 12; attempt += 1) {
17192
- await new Promise((resolve16) => setTimeout(resolve16, 250));
17551
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
17193
17552
  const state = await readExtensionChatState(h);
17194
17553
  if (state?.status === "waiting_approval") return true;
17195
17554
  const afterCount = getStateMessageCount(state);
@@ -19078,7 +19437,7 @@ async function executeProviderScript(h, args, scriptName) {
19078
19437
  const enterCount = cliCommand.enterCount || 1;
19079
19438
  await adapter.writeRaw(cliCommand.text + "\r");
19080
19439
  for (let i = 1; i < enterCount; i += 1) {
19081
- await new Promise((resolve16) => setTimeout(resolve16, 50));
19440
+ await new Promise((resolve17) => setTimeout(resolve17, 50));
19082
19441
  await adapter.writeRaw("\r");
19083
19442
  }
19084
19443
  }
@@ -19767,7 +20126,7 @@ var DaemonCommandHandler = class {
19767
20126
  try {
19768
20127
  const http3 = await import("http");
19769
20128
  const postData = JSON.stringify(body);
19770
- const result = await new Promise((resolve16, reject) => {
20129
+ const result = await new Promise((resolve17, reject) => {
19771
20130
  const req = http3.request({
19772
20131
  hostname: "127.0.0.1",
19773
20132
  port: 19280,
@@ -19779,9 +20138,9 @@ var DaemonCommandHandler = class {
19779
20138
  res.on("data", (chunk) => data += chunk);
19780
20139
  res.on("end", () => {
19781
20140
  try {
19782
- resolve16(JSON.parse(data));
20141
+ resolve17(JSON.parse(data));
19783
20142
  } catch {
19784
- resolve16({ raw: data });
20143
+ resolve17({ raw: data });
19785
20144
  }
19786
20145
  });
19787
20146
  });
@@ -19799,15 +20158,15 @@ var DaemonCommandHandler = class {
19799
20158
  if (!providerType) return { success: false, error: "providerType required" };
19800
20159
  try {
19801
20160
  const http3 = await import("http");
19802
- const result = await new Promise((resolve16, reject) => {
20161
+ const result = await new Promise((resolve17, reject) => {
19803
20162
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
19804
20163
  let data = "";
19805
20164
  res.on("data", (chunk) => data += chunk);
19806
20165
  res.on("end", () => {
19807
20166
  try {
19808
- resolve16(JSON.parse(data));
20167
+ resolve17(JSON.parse(data));
19809
20168
  } catch {
19810
- resolve16({ raw: data });
20169
+ resolve17({ raw: data });
19811
20170
  }
19812
20171
  });
19813
20172
  }).on("error", reject);
@@ -19821,7 +20180,7 @@ var DaemonCommandHandler = class {
19821
20180
  try {
19822
20181
  const http3 = await import("http");
19823
20182
  const postData = JSON.stringify(args || {});
19824
- const result = await new Promise((resolve16, reject) => {
20183
+ const result = await new Promise((resolve17, reject) => {
19825
20184
  const req = http3.request({
19826
20185
  hostname: "127.0.0.1",
19827
20186
  port: 19280,
@@ -19833,9 +20192,9 @@ var DaemonCommandHandler = class {
19833
20192
  res.on("data", (chunk) => data += chunk);
19834
20193
  res.on("end", () => {
19835
20194
  try {
19836
- resolve16(JSON.parse(data));
20195
+ resolve17(JSON.parse(data));
19837
20196
  } catch {
19838
- resolve16({ raw: data });
20197
+ resolve17({ raw: data });
19839
20198
  }
19840
20199
  });
19841
20200
  });
@@ -19854,7 +20213,7 @@ var DaemonCommandHandler = class {
19854
20213
  var os13 = __toESM(require("os"));
19855
20214
  var path18 = __toESM(require("path"));
19856
20215
  var crypto4 = __toESM(require("crypto"));
19857
- var import_fs10 = require("fs");
20216
+ var import_fs11 = require("fs");
19858
20217
  var import_child_process5 = require("child_process");
19859
20218
  var import_chalk = __toESM(require("chalk"));
19860
20219
  init_provider_cli_adapter();
@@ -20079,7 +20438,7 @@ async function waitForCliAdapterReady(adapter, options) {
20079
20438
  if (status === "stopped") {
20080
20439
  throw new Error("CLI runtime stopped before it became ready");
20081
20440
  }
20082
- await new Promise((resolve16) => setTimeout(resolve16, pollMs));
20441
+ await new Promise((resolve17) => setTimeout(resolve17, pollMs));
20083
20442
  }
20084
20443
  throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
20085
20444
  }
@@ -20456,7 +20815,7 @@ var CliProviderInstance = class {
20456
20815
  const enterCount = cliCommand.enterCount || 1;
20457
20816
  await this.adapter.writeRaw(cliCommand.text + "\r");
20458
20817
  for (let i = 1; i < enterCount; i += 1) {
20459
- await new Promise((resolve16) => setTimeout(resolve16, 50));
20818
+ await new Promise((resolve17) => setTimeout(resolve17, 50));
20460
20819
  await this.adapter.writeRaw("\r");
20461
20820
  }
20462
20821
  }
@@ -21852,13 +22211,13 @@ var AcpProviderInstance = class {
21852
22211
  }
21853
22212
  this.currentStatus = "waiting_approval";
21854
22213
  this.detectStatusTransition();
21855
- const approved = await new Promise((resolve16) => {
21856
- this.permissionResolvers.push(resolve16);
22214
+ const approved = await new Promise((resolve17) => {
22215
+ this.permissionResolvers.push(resolve17);
21857
22216
  setTimeout(() => {
21858
- const idx = this.permissionResolvers.indexOf(resolve16);
22217
+ const idx = this.permissionResolvers.indexOf(resolve17);
21859
22218
  if (idx >= 0) {
21860
22219
  this.permissionResolvers.splice(idx, 1);
21861
- resolve16(false);
22220
+ resolve17(false);
21862
22221
  }
21863
22222
  }, 3e5);
21864
22223
  });
@@ -22469,7 +22828,7 @@ function commandExists(command) {
22469
22828
  const trimmed = command.trim();
22470
22829
  if (!trimmed) return false;
22471
22830
  if (isExplicitCommand(trimmed)) {
22472
- return (0, import_fs10.existsSync)(expandExecutable(trimmed));
22831
+ return (0, import_fs11.existsSync)(expandExecutable(trimmed));
22473
22832
  }
22474
22833
  try {
22475
22834
  (0, import_child_process5.execFileSync)(process.platform === "win32" ? "where" : "which", [trimmed], {
@@ -22567,7 +22926,7 @@ async function waitForZeroMessageStartingLaunch(adapter) {
22567
22926
  } catch {
22568
22927
  return false;
22569
22928
  }
22570
- await new Promise((resolve16) => setTimeout(resolve16, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
22929
+ await new Promise((resolve17) => setTimeout(resolve17, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
22571
22930
  try {
22572
22931
  return hasZeroMessageStartingLaunch(adapter);
22573
22932
  } catch {
@@ -22591,10 +22950,10 @@ function hasCliArg(args, flag) {
22591
22950
  }
22592
22951
  function ensureEmptyDelegatedMcpConfig(workspace) {
22593
22952
  const baseDir = path18.join(os13.tmpdir(), "adhdev-delegated-agent-empty-mcp");
22594
- (0, import_fs10.mkdirSync)(baseDir, { recursive: true });
22953
+ (0, import_fs11.mkdirSync)(baseDir, { recursive: true });
22595
22954
  const workspaceHash = crypto4.createHash("sha256").update(path18.resolve(workspace || os13.tmpdir())).digest("hex").slice(0, 16);
22596
22955
  const filePath = path18.join(baseDir, `${workspaceHash}.json`);
22597
- (0, import_fs10.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
22956
+ (0, import_fs11.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
22598
22957
  return filePath;
22599
22958
  }
22600
22959
  function buildCoordinatorDelegatedCliLaunchOptions(input) {
@@ -24640,8 +24999,8 @@ var ProviderLoader = class _ProviderLoader {
24640
24999
  }
24641
25000
  const https = require("https");
24642
25001
  const { exec: exec7 } = require("child_process");
24643
- const { promisify: promisify6 } = require("util");
24644
- const execAsync5 = promisify6(exec7);
25002
+ const { promisify: promisify7 } = require("util");
25003
+ const execAsync5 = promisify7(exec7);
24645
25004
  const metaPath = path19.join(this.upstreamDir, _ProviderLoader.META_FILE);
24646
25005
  let prevEtag = "";
24647
25006
  let prevTimestamp = 0;
@@ -24659,7 +25018,7 @@ var ProviderLoader = class _ProviderLoader {
24659
25018
  return { updated: false };
24660
25019
  }
24661
25020
  try {
24662
- const etag = await new Promise((resolve16, reject) => {
25021
+ const etag = await new Promise((resolve17, reject) => {
24663
25022
  const options = {
24664
25023
  method: "HEAD",
24665
25024
  hostname: "github.com",
@@ -24677,7 +25036,7 @@ var ProviderLoader = class _ProviderLoader {
24677
25036
  headers: { "User-Agent": "adhdev-launcher" },
24678
25037
  timeout: 1e4
24679
25038
  }, (res2) => {
24680
- resolve16(res2.headers.etag || res2.headers["last-modified"] || "");
25039
+ resolve17(res2.headers.etag || res2.headers["last-modified"] || "");
24681
25040
  });
24682
25041
  req2.on("error", reject);
24683
25042
  req2.on("timeout", () => {
@@ -24686,7 +25045,7 @@ var ProviderLoader = class _ProviderLoader {
24686
25045
  });
24687
25046
  req2.end();
24688
25047
  } else {
24689
- resolve16(res.headers.etag || res.headers["last-modified"] || "");
25048
+ resolve17(res.headers.etag || res.headers["last-modified"] || "");
24690
25049
  }
24691
25050
  });
24692
25051
  req.on("error", reject);
@@ -24750,7 +25109,7 @@ var ProviderLoader = class _ProviderLoader {
24750
25109
  downloadFile(url, destPath) {
24751
25110
  const https = require("https");
24752
25111
  const http3 = require("http");
24753
- return new Promise((resolve16, reject) => {
25112
+ return new Promise((resolve17, reject) => {
24754
25113
  const doRequest = (reqUrl, redirectCount = 0) => {
24755
25114
  if (redirectCount > 5) {
24756
25115
  reject(new Error("Too many redirects"));
@@ -24770,7 +25129,7 @@ var ProviderLoader = class _ProviderLoader {
24770
25129
  res.pipe(ws);
24771
25130
  ws.on("finish", () => {
24772
25131
  ws.close();
24773
- resolve16();
25132
+ resolve17();
24774
25133
  });
24775
25134
  ws.on("error", reject);
24776
25135
  });
@@ -25273,10 +25632,10 @@ function findMacAppProcessPids(psOutput, appPaths) {
25273
25632
 
25274
25633
  // src/launch.ts
25275
25634
  async function execQuiet(command, options = {}) {
25276
- return new Promise((resolve16) => {
25635
+ return new Promise((resolve17) => {
25277
25636
  (0, import_child_process6.exec)(command, options, (error, stdout) => {
25278
- if (error) return resolve16("");
25279
- resolve16(stdout.toString());
25637
+ if (error) return resolve17("");
25638
+ resolve17(stdout.toString());
25280
25639
  });
25281
25640
  });
25282
25641
  }
@@ -25357,17 +25716,17 @@ async function findFreePort(ports) {
25357
25716
  throw new Error("No free port found");
25358
25717
  }
25359
25718
  function checkPortFree(port) {
25360
- return new Promise((resolve16) => {
25719
+ return new Promise((resolve17) => {
25361
25720
  const server = net.createServer();
25362
25721
  server.unref();
25363
- server.on("error", () => resolve16(false));
25722
+ server.on("error", () => resolve17(false));
25364
25723
  server.listen(port, "127.0.0.1", () => {
25365
- server.close(() => resolve16(true));
25724
+ server.close(() => resolve17(true));
25366
25725
  });
25367
25726
  });
25368
25727
  }
25369
25728
  async function isCdpActive(port) {
25370
- return new Promise((resolve16) => {
25729
+ return new Promise((resolve17) => {
25371
25730
  const req = require("http").get(`http://127.0.0.1:${port}/json/version`, {
25372
25731
  timeout: 2e3
25373
25732
  }, (res) => {
@@ -25376,16 +25735,16 @@ async function isCdpActive(port) {
25376
25735
  res.on("end", () => {
25377
25736
  try {
25378
25737
  const info = JSON.parse(data);
25379
- resolve16(!!info["WebKit-Version"] || !!info["Browser"]);
25738
+ resolve17(!!info["WebKit-Version"] || !!info["Browser"]);
25380
25739
  } catch {
25381
- resolve16(false);
25740
+ resolve17(false);
25382
25741
  }
25383
25742
  });
25384
25743
  });
25385
- req.on("error", () => resolve16(false));
25744
+ req.on("error", () => resolve17(false));
25386
25745
  req.on("timeout", () => {
25387
25746
  req.destroy();
25388
- resolve16(false);
25747
+ resolve17(false);
25389
25748
  });
25390
25749
  });
25391
25750
  }
@@ -25859,7 +26218,7 @@ function getRecentCommands(count = 50) {
25859
26218
  cleanOldFiles();
25860
26219
 
25861
26220
  // src/commands/router.ts
25862
- var yaml2 = __toESM(require("js-yaml"));
26221
+ var yaml3 = __toESM(require("js-yaml"));
25863
26222
  init_logger();
25864
26223
 
25865
26224
  // src/commands/mesh-coordinator.ts
@@ -26047,6 +26406,88 @@ function resolveMcpPort(explicitPort) {
26047
26406
  init_mesh_events();
26048
26407
  init_mesh_host_ownership();
26049
26408
 
26409
+ // src/mesh/preview-freshness.ts
26410
+ var import_node_child_process4 = require("child_process");
26411
+ var import_node_fs3 = require("fs");
26412
+ var import_node_path2 = require("path");
26413
+ var PREVIEW_DEPLOY_RECORD = ".adhdev/preview-deploy.json";
26414
+ function runGit2(repoRoot, args) {
26415
+ try {
26416
+ return (0, import_node_child_process4.execFileSync)("git", args, {
26417
+ cwd: repoRoot,
26418
+ encoding: "utf8",
26419
+ stdio: ["ignore", "pipe", "ignore"],
26420
+ timeout: 5e3
26421
+ }).trim();
26422
+ } catch {
26423
+ return "";
26424
+ }
26425
+ }
26426
+ function readRecord3(repoRoot) {
26427
+ const path28 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
26428
+ if (!(0, import_node_fs3.existsSync)(path28)) return null;
26429
+ try {
26430
+ const parsed = JSON.parse((0, import_node_fs3.readFileSync)(path28, "utf8"));
26431
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
26432
+ } catch {
26433
+ return null;
26434
+ }
26435
+ }
26436
+ function normalizeCommit(value) {
26437
+ return typeof value === "string" && /^[0-9a-f]{7,40}$/i.test(value.trim()) ? value.trim() : null;
26438
+ }
26439
+ function readTargetFreshness(record, currentCommit) {
26440
+ const targets = record?.targets && typeof record.targets === "object" && !Array.isArray(record.targets) ? record.targets : {};
26441
+ const result = {};
26442
+ for (const targetName of ["npm", "server", "web"]) {
26443
+ const targetRecord = targets[targetName] && typeof targets[targetName] === "object" && !Array.isArray(targets[targetName]) ? targets[targetName] : {};
26444
+ const commit = normalizeCommit(targetRecord.commit);
26445
+ result[targetName] = {
26446
+ commit,
26447
+ deployedAt: typeof targetRecord.deployedAt === "string" ? targetRecord.deployedAt : void 0,
26448
+ status: commit && currentCommit ? commit === currentCommit ? "fresh" : "stale" : "unknown"
26449
+ };
26450
+ }
26451
+ return result;
26452
+ }
26453
+ function readCurrentMainCommit(repoRoot) {
26454
+ const originMain = runGit2(repoRoot, ["rev-parse", "--verify", "origin/main^{commit}"]);
26455
+ if (originMain) {
26456
+ return { currentMainCommit: originMain, currentMainCommitSource: "origin/main" };
26457
+ }
26458
+ const head = runGit2(repoRoot, ["rev-parse", "--verify", "HEAD"]);
26459
+ if (head) {
26460
+ return { currentMainCommit: head, currentMainCommitSource: "HEAD" };
26461
+ }
26462
+ return { currentMainCommit: null, currentMainCommitSource: "unknown" };
26463
+ }
26464
+ function buildPreviewFreshness(repoRoot) {
26465
+ const current = readCurrentMainCommit(repoRoot);
26466
+ const record = readRecord3(repoRoot);
26467
+ const lastPreviewCommit = normalizeCommit(record?.lastPreviewCommit);
26468
+ const targets = readTargetFreshness(record, current.currentMainCommit);
26469
+ let status = "unknown";
26470
+ let nextAction = "Run npm run deploy:preview from the current main commit, then smoke preview.";
26471
+ if (lastPreviewCommit && current.currentMainCommit) {
26472
+ status = lastPreviewCommit === current.currentMainCommit ? "fresh" : "stale";
26473
+ nextAction = status === "fresh" ? "No preview deploy action needed." : "Run npm run deploy:preview from origin/main, then smoke preview.";
26474
+ } else if (!current.currentMainCommit) {
26475
+ nextAction = "Resolve the current main commit before judging preview freshness.";
26476
+ }
26477
+ return {
26478
+ status,
26479
+ lastPreviewCommit,
26480
+ currentMainCommit: current.currentMainCommit,
26481
+ currentMainCommitSource: current.currentMainCommitSource,
26482
+ recordPath: PREVIEW_DEPLOY_RECORD,
26483
+ lastDeployedAt: typeof record?.updatedAt === "string" ? record.updatedAt : void 0,
26484
+ lastTarget: typeof record?.target === "string" ? record.target : void 0,
26485
+ previewVersion: typeof record?.previewVersion === "string" ? record.previewVersion : void 0,
26486
+ targets,
26487
+ nextAction
26488
+ };
26489
+ }
26490
+
26050
26491
  // src/status/snapshot.ts
26051
26492
  var os18 = __toESM(require("os"));
26052
26493
  init_config();
@@ -26553,7 +26994,7 @@ async function waitForPidExit(pid, timeoutMs) {
26553
26994
  while (Date.now() - start < timeoutMs) {
26554
26995
  try {
26555
26996
  process.kill(pid, 0);
26556
- await new Promise((resolve16) => setTimeout(resolve16, 250));
26997
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
26557
26998
  } catch {
26558
26999
  return;
26559
27000
  }
@@ -26664,7 +27105,7 @@ async function runDaemonUpgradeHelper(payload) {
26664
27105
  appendUpgradeLog(installOutput.trim());
26665
27106
  }
26666
27107
  if (process.platform === "win32") {
26667
- await new Promise((resolve16) => setTimeout(resolve16, 500));
27108
+ await new Promise((resolve17) => setTimeout(resolve17, 500));
26668
27109
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
26669
27110
  appendUpgradeLog("Post-install staging cleanup complete");
26670
27111
  }
@@ -26701,8 +27142,9 @@ async function maybeRunDaemonUpgradeHelperFromEnv() {
26701
27142
  // src/commands/router.ts
26702
27143
  init_mesh_work_queue();
26703
27144
  var import_os3 = require("os");
26704
- var import_path8 = require("path");
27145
+ var import_path9 = require("path");
26705
27146
  var fs11 = __toESM(require("fs"));
27147
+ var import_node_child_process5 = require("child_process");
26706
27148
  var CHANNEL_NPM_TAG = { stable: "latest", preview: "next" };
26707
27149
  var CHANNEL_SERVER_URL = {
26708
27150
  stable: "https://api.adhf.dev",
@@ -26848,7 +27290,7 @@ function buildMeshNodeDisplayLabel(node, nodeId, providerPriority) {
26848
27290
  const explicit = readStringValue(node.machineLabel, node.machine_label, node.machineNickname, node.machine_nickname, node.alias);
26849
27291
  if (explicit) return explicit;
26850
27292
  const workspace = readStringValue(node.workspace, node.repoRoot, node.repo_root);
26851
- const workspaceName = workspace ? (0, import_path8.basename)(workspace) : void 0;
27293
+ const workspaceName = workspace ? (0, import_path9.basename)(workspace) : void 0;
26852
27294
  const host = readStringValue(node.machineName, node.machine_name, node.hostname, node.host, node.daemonId, node.daemon_id, node.machineId, node.machine_id);
26853
27295
  const provider = providerPriority[0] || (Array.isArray(node.providers) ? readStringValue(...node.providers) : void 0);
26854
27296
  const parts = [workspaceName, host, provider].filter(Boolean);
@@ -27414,6 +27856,16 @@ function finalizeMeshNodeStatus(args) {
27414
27856
  if (machineStatus) status.machineStatus = machineStatus;
27415
27857
  }
27416
27858
  synthesizeMeshNodeFreshnessFromConnection(status);
27859
+ const bootstrap = readObjectRecord(node?.worktreeBootstrap);
27860
+ if (node?.isLocalWorktree && readStringValue(bootstrap.status)) {
27861
+ status.worktreeBootstrap = bootstrap;
27862
+ if (bootstrap.status === "failed" && bootstrap.required !== false) {
27863
+ status.launchReady = false;
27864
+ status.launchBlockedReason = "worktree_bootstrap_failed";
27865
+ status.launchBlockedMessage = readStringValue(bootstrap.error) || "Required worktree bootstrap failed; resolve it before launching an agent into this node.";
27866
+ return;
27867
+ }
27868
+ }
27417
27869
  const connectionState = readStringValue(readObjectRecord(status.connection).state);
27418
27870
  status.launchReady = !!daemonId && (readStringValue(status.machineStatus) === "online" || connectionState === "connected" || isSelfNode);
27419
27871
  }
@@ -27555,6 +28007,40 @@ function collectLiveMeshSessionRecords(args) {
27555
28007
  }
27556
28008
  return matches;
27557
28009
  }
28010
+ function buildHistoricalMeshSessions(args) {
28011
+ const liveNodeIds = /* @__PURE__ */ new Set();
28012
+ const liveWorkspaces = /* @__PURE__ */ new Set();
28013
+ for (const node of args.nodes || []) {
28014
+ const nodeId = readStringValue(node?.id, node?.nodeId);
28015
+ const workspace = readStringValue(node?.workspace);
28016
+ if (nodeId) liveNodeIds.add(nodeId);
28017
+ if (workspace) liveWorkspaces.add(workspace);
28018
+ }
28019
+ const sessions = [];
28020
+ for (const record of args.liveSessionRecords || []) {
28021
+ const meta = readObjectRecord(record?.meta);
28022
+ const recordMeshId = readStringValue(meta.meshNodeFor, meta.meshCoordinatorFor);
28023
+ if (recordMeshId !== args.meshId) continue;
28024
+ const recordNodeId = readStringValue(meta.meshNodeId);
28025
+ const workspace = readStringValue(record?.workspace);
28026
+ const removedNode = !!recordNodeId && !liveNodeIds.has(recordNodeId);
28027
+ const orphanedWorkspace = !!workspace && !liveWorkspaces.has(workspace) && meta.meshCoordinatorFor !== args.meshId;
28028
+ if (!removedNode && !orphanedWorkspace) continue;
28029
+ sessions.push({
28030
+ ...summarizeMeshSessionRecord(record),
28031
+ classification: removedNode ? "removedNode" : "orphanedSession",
28032
+ historical: true,
28033
+ meshNodeId: recordNodeId || null,
28034
+ reason: removedNode ? "Session is tagged to a mesh node that is no longer in live membership." : "Session workspace is no longer attached to a live mesh node."
28035
+ });
28036
+ }
28037
+ if (sessions.length === 0) return void 0;
28038
+ return {
28039
+ count: sessions.length,
28040
+ sessions: sessions.slice(0, 5),
28041
+ instruction: "These sessions are separated from normal node activeSessions because their mesh node/workspace is no longer live. Use mesh_cleanup_sessions only if cleanup is intended."
28042
+ };
28043
+ }
27558
28044
  function applyCachedInlineMeshNodeStatus(status, node, options) {
27559
28045
  const cachedStatus = readObjectRecord(node?.cachedStatus);
27560
28046
  const liveGit = buildInlineMeshTransitGitStatus(node);
@@ -27640,14 +28126,14 @@ function resolveRefineryAutoPublishSubmoduleMainCommits(mesh, workspace) {
27640
28126
  return { enabled: false };
27641
28127
  }
27642
28128
  async function computeGitPatchId(cwd, fromRef, toRef) {
27643
- const { execFileSync: execFileSync3 } = await import("child_process");
27644
- const diff = execFileSync3("git", ["diff", "--patch", "--full-index", fromRef, toRef], {
28129
+ const { execFileSync: execFileSync5 } = await import("child_process");
28130
+ const diff = execFileSync5("git", ["diff", "--patch", "--full-index", fromRef, toRef], {
27645
28131
  cwd,
27646
28132
  encoding: "utf8",
27647
28133
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
27648
28134
  });
27649
28135
  if (!diff.trim()) return "";
27650
- const patchId = execFileSync3("git", ["patch-id", "--stable"], {
28136
+ const patchId = execFileSync5("git", ["patch-id", "--stable"], {
27651
28137
  cwd,
27652
28138
  input: diff,
27653
28139
  encoding: "utf8",
@@ -27658,8 +28144,8 @@ async function computeGitPatchId(cwd, fromRef, toRef) {
27658
28144
  async function runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead) {
27659
28145
  const startedAt = Date.now();
27660
28146
  try {
27661
- const { execFileSync: execFileSync3 } = await import("child_process");
27662
- const git = (args) => execFileSync3("git", args, {
28147
+ const { execFileSync: execFileSync5 } = await import("child_process");
28148
+ const git = (args) => execFileSync5("git", args, {
27663
28149
  cwd: repoRoot,
27664
28150
  encoding: "utf8",
27665
28151
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -27703,6 +28189,135 @@ async function runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead)
27703
28189
  durationMs: Date.now() - startedAt,
27704
28190
  error: e?.message || String(e),
27705
28191
  stdout: truncateValidationOutput(e?.stdout),
28192
+ stderr: truncateValidationOutput(e?.stderr),
28193
+ actionableHint: buildPatchEquivalenceSubmoduleConflictHint(
28194
+ repoRoot,
28195
+ baseHead,
28196
+ branchHead,
28197
+ `${e?.message || ""}
28198
+ ${e?.stdout || ""}
28199
+ ${e?.stderr || ""}`
28200
+ )
28201
+ };
28202
+ }
28203
+ }
28204
+ function buildPatchEquivalenceSubmoduleConflictHint(repoRoot, baseHead, branchHead, output) {
28205
+ if (!/(submodule|160000)/i.test(output) || !/(conflict|failed to merge)/i.test(output)) return void 0;
28206
+ const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path28) => ({
28207
+ path: path28,
28208
+ baseCommit: readTreeObject(repoRoot, baseHead, path28),
28209
+ branchCommit: readTreeObject(repoRoot, branchHead, path28)
28210
+ }));
28211
+ if (conflicts.length === 0) return void 0;
28212
+ return {
28213
+ kind: "submodule_conflict",
28214
+ message: "Refinery could not synthesize a safe merge tree because the branch and base point the same submodule path at different commits.",
28215
+ conflicts,
28216
+ nextSteps: [
28217
+ "Inspect the listed submodule path in both base and branch: baseCommit is the commit currently recorded by the base workspace, branchCommit is the commit recorded by the worktree branch.",
28218
+ "Resolve the submodule first by checking out or creating the intended submodule commit, then commit the chosen gitlink in the root branch.",
28219
+ "Ensure the chosen submodule commit is reachable from the configured submodule remote main branch, then rerun mesh_refine_node."
28220
+ ]
28221
+ };
28222
+ }
28223
+ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
28224
+ try {
28225
+ const output = (0, import_node_child_process5.execFileSync)("git", ["diff", "--raw", "--no-abbrev", fromRef, toRef], {
28226
+ cwd: repoRoot,
28227
+ encoding: "utf8",
28228
+ maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
28229
+ });
28230
+ const paths = /* @__PURE__ */ new Set();
28231
+ for (const line of output.split("\n")) {
28232
+ if (!line.trim()) continue;
28233
+ const metaAndPath = line.split(" ");
28234
+ const meta = metaAndPath[0] || "";
28235
+ const path28 = metaAndPath[metaAndPath.length - 1]?.trim();
28236
+ if (!path28) continue;
28237
+ const parts = meta.split(/\s+/);
28238
+ if (parts[0]?.includes("160000") || parts[1]?.includes("160000")) {
28239
+ paths.add(path28);
28240
+ }
28241
+ }
28242
+ return [...paths].sort();
28243
+ } catch {
28244
+ return [];
28245
+ }
28246
+ }
28247
+ function readTreeObject(repoRoot, ref, path28) {
28248
+ try {
28249
+ const output = (0, import_node_child_process5.execFileSync)("git", ["ls-tree", ref, "--", path28], {
28250
+ cwd: repoRoot,
28251
+ encoding: "utf8",
28252
+ maxBuffer: 1024 * 1024
28253
+ }).trim();
28254
+ const match = output.match(/\bcommit\s+([0-9a-f]{40})\b/i);
28255
+ return match?.[1];
28256
+ } catch {
28257
+ return void 0;
28258
+ }
28259
+ }
28260
+ async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, currentHead, options = {}) {
28261
+ const startedAt = Date.now();
28262
+ const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path28) => !(options.submoduleIgnorePaths || []).includes(path28));
28263
+ const preStatus = await getGitRepoStatus(repoRoot, {
28264
+ includeSubmodules: true,
28265
+ submoduleIgnorePaths: options.submoduleIgnorePaths,
28266
+ timeoutMs: 15e3
28267
+ });
28268
+ const outOfSyncPaths = (preStatus.submodules || []).filter((submodule) => submodule.dirty || submodule.outOfSync || !!submodule.error).map((submodule) => submodule.path);
28269
+ const updatePaths = [.../* @__PURE__ */ new Set([...changedGitlinkPaths, ...outOfSyncPaths])].sort();
28270
+ if (updatePaths.length === 0) {
28271
+ return {
28272
+ status: "skipped",
28273
+ changedGitlinkPaths,
28274
+ outOfSyncPaths,
28275
+ updatedPaths: [],
28276
+ verifiedPaths: [],
28277
+ durationMs: Date.now() - startedAt,
28278
+ reason: "no_changed_or_out_of_sync_submodules"
28279
+ };
28280
+ }
28281
+ const commandArgs = ["submodule", "update", "--init", "--recursive", "--", ...updatePaths];
28282
+ try {
28283
+ const { execFile: execFile4 } = await import("child_process");
28284
+ const { promisify: promisify7 } = await import("util");
28285
+ const execFileAsync3 = promisify7(execFile4);
28286
+ const result = await execFileAsync3("git", commandArgs, {
28287
+ cwd: repoRoot,
28288
+ encoding: "utf8",
28289
+ maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES,
28290
+ timeout: 6e4
28291
+ });
28292
+ const postStatus = await getGitRepoStatus(repoRoot, {
28293
+ includeSubmodules: true,
28294
+ submoduleIgnorePaths: options.submoduleIgnorePaths,
28295
+ timeoutMs: 15e3
28296
+ });
28297
+ const remaining = (postStatus.submodules || []).filter((submodule) => updatePaths.includes(submodule.path) && (submodule.dirty || submodule.outOfSync || !!submodule.error));
28298
+ return {
28299
+ status: remaining.length === 0 ? "passed" : "failed",
28300
+ changedGitlinkPaths,
28301
+ outOfSyncPaths,
28302
+ updatedPaths: updatePaths,
28303
+ verifiedPaths: updatePaths.filter((path28) => !remaining.some((submodule) => submodule.path === path28)),
28304
+ durationMs: Date.now() - startedAt,
28305
+ command: `git ${commandArgs.join(" ")}`,
28306
+ stdout: truncateValidationOutput(result.stdout),
28307
+ stderr: truncateValidationOutput(result.stderr),
28308
+ ...remaining.length > 0 ? { error: `Submodule checkout remained out of sync after update: ${remaining.map((entry) => entry.path).join(", ")}` } : {}
28309
+ };
28310
+ } catch (e) {
28311
+ return {
28312
+ status: "failed",
28313
+ changedGitlinkPaths,
28314
+ outOfSyncPaths,
28315
+ updatedPaths: updatePaths,
28316
+ verifiedPaths: [],
28317
+ durationMs: Date.now() - startedAt,
28318
+ command: `git ${commandArgs.join(" ")}`,
28319
+ error: e?.message || String(e),
28320
+ stdout: truncateValidationOutput(e?.stdout),
27706
28321
  stderr: truncateValidationOutput(e?.stderr)
27707
28322
  };
27708
28323
  }
@@ -27711,10 +28326,10 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27711
28326
  const startedAt = Date.now();
27712
28327
  const entries = [];
27713
28328
  try {
27714
- const { execFile: execFile3 } = await import("child_process");
27715
- const { promisify: promisify6 } = await import("util");
27716
- const execFileAsync3 = promisify6(execFile3);
27717
- const runGit2 = async (cwd, args) => {
28329
+ const { execFile: execFile4 } = await import("child_process");
28330
+ const { promisify: promisify7 } = await import("util");
28331
+ const execFileAsync3 = promisify7(execFile4);
28332
+ const runGit3 = async (cwd, args) => {
27718
28333
  const { stdout } = await execFileAsync3("git", args, {
27719
28334
  cwd,
27720
28335
  encoding: "utf8",
@@ -27725,8 +28340,8 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27725
28340
  return String(stdout || "");
27726
28341
  };
27727
28342
  const verifyRemoteMainContainsCommit = async (submodulePath, commit, branch = "main") => {
27728
- await runGit2(submodulePath, ["-c", "protocol.file.allow=always", "fetch", "origin", `refs/heads/${branch}:refs/remotes/origin/${branch}`]);
27729
- await runGit2(submodulePath, ["merge-base", "--is-ancestor", commit, `refs/remotes/origin/${branch}`]);
28343
+ await runGit3(submodulePath, ["-c", "protocol.file.allow=always", "fetch", "origin", `refs/heads/${branch}:refs/remotes/origin/${branch}`]);
28344
+ await runGit3(submodulePath, ["merge-base", "--is-ancestor", commit, `refs/remotes/origin/${branch}`]);
27730
28345
  };
27731
28346
  const publishCommitToRemoteMain = async (submodulePath, commit, branch = "main") => {
27732
28347
  const refspec = `${commit}:refs/heads/${branch}`;
@@ -27742,21 +28357,21 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27742
28357
  const importCommitFromWorktreeSubmodule = async (submodulePath, worktreeSubmodulePath, commit) => {
27743
28358
  if (!fs11.existsSync(worktreeSubmodulePath)) return false;
27744
28359
  try {
27745
- await runGit2(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
28360
+ await runGit3(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
27746
28361
  } catch {
27747
28362
  return false;
27748
28363
  }
27749
- await runGit2(submodulePath, ["-c", "protocol.file.allow=always", "fetch", worktreeSubmodulePath, commit]);
27750
- await runGit2(submodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
28364
+ await runGit3(submodulePath, ["-c", "protocol.file.allow=always", "fetch", worktreeSubmodulePath, commit]);
28365
+ await runGit3(submodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
27751
28366
  return true;
27752
28367
  };
27753
- const treeOutput = await runGit2(repoRoot, ["ls-tree", "-r", "-z", mergedTree]);
28368
+ const treeOutput = await runGit3(repoRoot, ["ls-tree", "-r", "-z", mergedTree]);
27754
28369
  const gitlinks = treeOutput.split("\0").filter(Boolean).map((record) => {
27755
28370
  const match = /^160000\s+commit\s+([0-9a-f]{40})\t(.+)$/.exec(record);
27756
28371
  return match ? { commit: match[1], path: match[2] } : null;
27757
28372
  }).filter((entry) => !!entry);
27758
28373
  for (const gitlink of gitlinks) {
27759
- const submodulePath = (0, import_path8.resolve)(repoRoot, gitlink.path);
28374
+ const submodulePath = (0, import_path9.resolve)(repoRoot, gitlink.path);
27760
28375
  const entry = {
27761
28376
  path: gitlink.path,
27762
28377
  commit: gitlink.commit,
@@ -27776,7 +28391,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27776
28391
  }
27777
28392
  entry.checkedLocal = true;
27778
28393
  try {
27779
- await runGit2(submodulePath, ["cat-file", "-e", `${gitlink.commit}^{commit}`]);
28394
+ await runGit3(submodulePath, ["cat-file", "-e", `${gitlink.commit}^{commit}`]);
27780
28395
  entry.localReachable = true;
27781
28396
  } catch {
27782
28397
  entry.localReachable = false;
@@ -27784,7 +28399,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27784
28399
  try {
27785
28400
  const imported = await importCommitFromWorktreeSubmodule(
27786
28401
  submodulePath,
27787
- (0, import_path8.resolve)(options.worktreeRoot, gitlink.path),
28402
+ (0, import_path9.resolve)(options.worktreeRoot, gitlink.path),
27788
28403
  gitlink.commit
27789
28404
  );
27790
28405
  if (imported) {
@@ -27800,7 +28415,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27800
28415
  entry.remote = "origin";
27801
28416
  let remoteUrl = "";
27802
28417
  try {
27803
- remoteUrl = (await runGit2(submodulePath, ["remote", "get-url", "origin"])).trim();
28418
+ remoteUrl = (await runGit3(submodulePath, ["remote", "get-url", "origin"])).trim();
27804
28419
  if (!remoteUrl) throw new Error("origin remote has no URL");
27805
28420
  entry.remoteUrl = remoteUrl;
27806
28421
  } catch {
@@ -27915,9 +28530,9 @@ function buildMeshRefineValidationPlan(mesh, workspace) {
27915
28530
  };
27916
28531
  }
27917
28532
  async function runMeshRefineValidationGate(mesh, workspace) {
27918
- const { execFile: execFile3 } = await import("child_process");
27919
- const { promisify: promisify6 } = await import("util");
27920
- const execFileAsync3 = promisify6(execFile3);
28533
+ const { execFile: execFile4 } = await import("child_process");
28534
+ const { promisify: promisify7 } = await import("util");
28535
+ const execFileAsync3 = promisify7(execFile4);
27921
28536
  const selection = resolveMeshRefineValidationPlan(mesh, workspace);
27922
28537
  const summary = {
27923
28538
  status: "skipped",
@@ -27951,24 +28566,24 @@ async function runMeshRefineValidationGate(mesh, workspace) {
27951
28566
  ...extras
27952
28567
  });
27953
28568
  const isPackageManagerValidation = (candidate) => {
27954
- const command = (0, import_path8.basename)(candidate.command).replace(/\.(?:cmd|exe)$/i, "");
28569
+ const command = (0, import_path9.basename)(candidate.command).replace(/\.(?:cmd|exe)$/i, "");
27955
28570
  return ["npm", "pnpm", "yarn", "bun"].includes(command) && candidate.args.some((arg) => arg === "run" || arg === "test" || arg === "exec");
27956
28571
  };
27957
28572
  const dependenciesLikelyMissing = (cwd) => {
27958
- if (!fs11.existsSync((0, import_path8.join)(cwd, "package.json"))) return false;
27959
- if (fs11.existsSync((0, import_path8.join)(cwd, "node_modules"))) return false;
27960
- return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs11.existsSync((0, import_path8.join)(cwd, lock)));
28573
+ if (!fs11.existsSync((0, import_path9.join)(cwd, "package.json"))) return false;
28574
+ if (fs11.existsSync((0, import_path9.join)(cwd, "node_modules"))) return false;
28575
+ return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs11.existsSync((0, import_path9.join)(cwd, lock)));
27961
28576
  };
27962
28577
  for (const candidate of selection.bootstrapCommands) {
27963
28578
  const startedAt = Date.now();
27964
- const cwd = candidate.cwd ? (0, import_path8.resolve)(workspace, candidate.cwd) : workspace;
28579
+ const cwd = candidate.cwd ? (0, import_path9.resolve)(workspace, candidate.cwd) : workspace;
27965
28580
  const timeout = candidate.timeoutMs || REFINE_VALIDATION_TIMEOUT_MS;
27966
28581
  try {
27967
28582
  const result = await execFileAsync3(candidate.command, candidate.args, {
27968
28583
  cwd,
27969
28584
  encoding: "utf8",
27970
28585
  timeout,
27971
- maxBuffer: REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
28586
+ maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
27972
28587
  env: { ...process.env, CI: process.env.CI || "1", ...candidate.env || {} }
27973
28588
  });
27974
28589
  summary.bootstrapCommandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
@@ -27987,7 +28602,7 @@ async function runMeshRefineValidationGate(mesh, workspace) {
27987
28602
  }
27988
28603
  for (const candidate of selection.commands) {
27989
28604
  const startedAt = Date.now();
27990
- const cwd = candidate.cwd ? (0, import_path8.resolve)(workspace, candidate.cwd) : workspace;
28605
+ const cwd = candidate.cwd ? (0, import_path9.resolve)(workspace, candidate.cwd) : workspace;
27991
28606
  const timeout = candidate.timeoutMs || REFINE_VALIDATION_TIMEOUT_MS;
27992
28607
  if (selection.bootstrapCommands.length === 0 && isPackageManagerValidation(candidate) && dependenciesLikelyMissing(cwd)) {
27993
28608
  summary.commandsRun.push(commandRecord(candidate, cwd, startedAt, {
@@ -28007,7 +28622,7 @@ async function runMeshRefineValidationGate(mesh, workspace) {
28007
28622
  cwd,
28008
28623
  encoding: "utf8",
28009
28624
  timeout,
28010
- maxBuffer: REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
28625
+ maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
28011
28626
  env: { ...process.env, CI: process.env.CI || "1", ...candidate.env || {} }
28012
28627
  });
28013
28628
  summary.commandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
@@ -28032,7 +28647,7 @@ async function runMeshRefineValidationGate(mesh, workspace) {
28032
28647
  return summary;
28033
28648
  }
28034
28649
  function loadYamlModule() {
28035
- return yaml2;
28650
+ return yaml3;
28036
28651
  }
28037
28652
  function getMcpServersKey(format) {
28038
28653
  return format === "hermes_config_yaml" ? "mcp_servers" : "mcpServers";
@@ -28049,13 +28664,13 @@ function serializeMeshCoordinatorMcpConfig(config, format) {
28049
28664
  }
28050
28665
  function resolveHermesUserHome() {
28051
28666
  const explicitHome = process.env.HERMES_HOME?.trim();
28052
- return explicitHome || (0, import_path8.join)((0, import_os3.homedir)(), ".hermes");
28667
+ return explicitHome || (0, import_path9.join)((0, import_os3.homedir)(), ".hermes");
28053
28668
  }
28054
28669
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
28055
28670
  const sourceHome = resolveHermesUserHome();
28056
- const sourceConfigPath = (0, import_path8.join)(sourceHome, "config.yaml");
28671
+ const sourceConfigPath = (0, import_path9.join)(sourceHome, "config.yaml");
28057
28672
  if (!fs11.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
28058
- if ((0, import_path8.resolve)(sourceConfigPath) === (0, import_path8.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
28673
+ if ((0, import_path9.resolve)(sourceConfigPath) === (0, import_path9.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
28059
28674
  const parsed = parseMeshCoordinatorMcpConfig(fs11.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
28060
28675
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
28061
28676
  return { config: baseConfig, sourceHome, sourceConfigPath };
@@ -28089,10 +28704,10 @@ function stripHermesCoordinatorTempModelProviderOverrides(config) {
28089
28704
  return sanitized;
28090
28705
  }
28091
28706
  function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
28092
- if ((0, import_path8.resolve)(sourceHome) === (0, import_path8.resolve)(targetHome)) return;
28707
+ if ((0, import_path9.resolve)(sourceHome) === (0, import_path9.resolve)(targetHome)) return;
28093
28708
  for (const fileName of [".env", "auth.json"]) {
28094
- const sourcePath = (0, import_path8.join)(sourceHome, fileName);
28095
- const targetPath = (0, import_path8.join)(targetHome, fileName);
28709
+ const sourcePath = (0, import_path9.join)(sourceHome, fileName);
28710
+ const targetPath = (0, import_path9.join)(targetHome, fileName);
28096
28711
  if (!fs11.existsSync(sourcePath)) continue;
28097
28712
  try {
28098
28713
  fs11.copyFileSync(sourcePath, targetPath);
@@ -28474,7 +29089,7 @@ var DaemonCommandRouter = class {
28474
29089
  }
28475
29090
  const { resolveWorktreePath: resolveWorktreePath2, listWorktrees: listWorktrees2, removeWorktree: removeWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
28476
29091
  const normalizePath = (value) => {
28477
- const resolved = (0, import_path8.resolve)(value);
29092
+ const resolved = (0, import_path9.resolve)(value);
28478
29093
  try {
28479
29094
  return fs11.realpathSync(resolved);
28480
29095
  } catch {
@@ -28548,10 +29163,10 @@ var DaemonCommandRouter = class {
28548
29163
  if (metadataStatus === "merged_to_main" || metadataStatus === "cleanup_candidate") {
28549
29164
  return { allow: true, status: metadataStatus, source: "node_branch_convergence" };
28550
29165
  }
28551
- const { execFile: execFile3 } = await import("child_process");
28552
- const { promisify: promisify6 } = await import("util");
28553
- const execFileAsync3 = promisify6(execFile3);
28554
- const runGit2 = async (gitArgs, cwd) => {
29166
+ const { execFile: execFile4 } = await import("child_process");
29167
+ const { promisify: promisify7 } = await import("util");
29168
+ const execFileAsync3 = promisify7(execFile4);
29169
+ const runGit3 = async (gitArgs, cwd) => {
28555
29170
  const { stdout } = await execFileAsync3("git", gitArgs, {
28556
29171
  cwd,
28557
29172
  encoding: "utf8",
@@ -28563,14 +29178,14 @@ var DaemonCommandRouter = class {
28563
29178
  };
28564
29179
  let head = "";
28565
29180
  try {
28566
- head = await runGit2(["rev-parse", "HEAD"], args.workspace);
29181
+ head = await runGit3(["rev-parse", "HEAD"], args.workspace);
28567
29182
  } catch (e) {
28568
29183
  return { allow: false, error: `could not resolve worktree HEAD: ${e?.message || e}` };
28569
29184
  }
28570
29185
  if (!head) return { allow: false, error: "worktree HEAD is empty" };
28571
29186
  const candidateRefs = [];
28572
29187
  try {
28573
- const defaultBranch = await runGit2(["branch", "--show-current"], args.repoRoot);
29188
+ const defaultBranch = await runGit3(["branch", "--show-current"], args.repoRoot);
28574
29189
  if (defaultBranch) {
28575
29190
  candidateRefs.push(defaultBranch, `origin/${defaultBranch}`);
28576
29191
  }
@@ -28584,13 +29199,13 @@ var DaemonCommandRouter = class {
28584
29199
  seen.add(ref);
28585
29200
  let commit = "";
28586
29201
  try {
28587
- commit = await runGit2(["rev-parse", "--verify", `${ref}^{commit}`], args.repoRoot);
29202
+ commit = await runGit3(["rev-parse", "--verify", `${ref}^{commit}`], args.repoRoot);
28588
29203
  } catch {
28589
29204
  continue;
28590
29205
  }
28591
29206
  checkedRefs.push(ref);
28592
29207
  try {
28593
- await runGit2(["merge-base", "--is-ancestor", head, commit], args.repoRoot);
29208
+ await runGit3(["merge-base", "--is-ancestor", head, commit], args.repoRoot);
28594
29209
  return { allow: true, status: "merged_to_default_ref", source: "git_merge_base", ref };
28595
29210
  } catch {
28596
29211
  }
@@ -28982,9 +29597,9 @@ var DaemonCommandRouter = class {
28982
29597
  const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => n.id === node.clonedFromNodeId || n.nodeId === node.clonedFromNodeId) : mesh?.nodes.find((n) => !n.isLocalWorktree);
28983
29598
  const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
28984
29599
  if (!repoRoot) return { success: false, error: "Source node repoRoot not found", refineStages };
28985
- const { execFile: execFile3 } = await import("child_process");
28986
- const { promisify: promisify6 } = await import("util");
28987
- const execFileAsync3 = promisify6(execFile3);
29600
+ const { execFile: execFile4 } = await import("child_process");
29601
+ const { promisify: promisify7 } = await import("util");
29602
+ const execFileAsync3 = promisify7(execFile4);
28988
29603
  const resolveStarted = Date.now();
28989
29604
  const { stdout: branchStdout } = await execFileAsync3("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8" });
28990
29605
  const branch = branchStdout.trim();
@@ -29051,7 +29666,8 @@ var DaemonCommandRouter = class {
29051
29666
  equivalent: patchEquivalence.equivalent,
29052
29667
  expectedPatchId: patchEquivalence.expectedPatchId,
29053
29668
  actualPatchId: patchEquivalence.actualPatchId,
29054
- error: patchEquivalence.error
29669
+ error: patchEquivalence.error,
29670
+ actionableHint: patchEquivalence.actionableHint
29055
29671
  });
29056
29672
  if (!patchEquivalence.equivalent) {
29057
29673
  return {
@@ -29210,6 +29826,49 @@ var DaemonCommandRouter = class {
29210
29826
  }
29211
29827
  };
29212
29828
  }
29829
+ const submoduleAlignmentStarted = Date.now();
29830
+ const submoduleAlignment = await alignRefinerySubmodulesAfterMerge(repoRoot, baseHead, "HEAD", {
29831
+ submoduleIgnorePaths: Array.isArray(sourceNode?.policy?.submoduleIgnorePaths) ? sourceNode.policy.submoduleIgnorePaths.filter((value) => typeof value === "string") : void 0
29832
+ });
29833
+ if (submoduleAlignment.status !== "skipped") {
29834
+ recordMeshRefineStage(refineStages, "submodule_alignment", submoduleAlignment.status, submoduleAlignmentStarted, {
29835
+ changedGitlinkPaths: submoduleAlignment.changedGitlinkPaths,
29836
+ outOfSyncPaths: submoduleAlignment.outOfSyncPaths,
29837
+ updatedPaths: submoduleAlignment.updatedPaths,
29838
+ verifiedPaths: submoduleAlignment.verifiedPaths,
29839
+ command: submoduleAlignment.command,
29840
+ error: submoduleAlignment.error
29841
+ });
29842
+ }
29843
+ if (submoduleAlignment.status === "failed") {
29844
+ return {
29845
+ success: false,
29846
+ code: "post_merge_submodule_alignment_failed",
29847
+ error: "Refinery merge completed but post-merge submodule checkout alignment failed; run the reported git submodule update command and re-check base workspace status.",
29848
+ merged: true,
29849
+ branch,
29850
+ into: baseBranch,
29851
+ validationSummary,
29852
+ patchEquivalence,
29853
+ submoduleReachability,
29854
+ submoduleAlignment,
29855
+ mergeResult,
29856
+ refineStages,
29857
+ finalBranchConvergenceState: {
29858
+ branch: baseBranch,
29859
+ mergedBranch: branch,
29860
+ baseBranch,
29861
+ merged: true,
29862
+ removed: false,
29863
+ validation: "passed",
29864
+ patchEquivalence: "passed",
29865
+ submoduleReachability: "passed",
29866
+ submoduleAlignment: "failed",
29867
+ status: "post_merge_alignment_failed",
29868
+ nextStep: submoduleAlignment.command || "Run git submodule update --init --recursive for the reported path(s), then re-check base workspace status."
29869
+ }
29870
+ };
29871
+ }
29213
29872
  const cleanupStarted = Date.now();
29214
29873
  const removeResult = await this.execute("remove_mesh_node", {
29215
29874
  meshId,
@@ -29229,7 +29888,7 @@ var DaemonCommandRouter = class {
29229
29888
  appendLedgerEntry2(meshId, {
29230
29889
  kind: "node_removed",
29231
29890
  nodeId,
29232
- payload: { refined: true, mergedBranch: branch, into: baseBranch, validationSummary, patchEquivalence, submoduleReachability }
29891
+ payload: { refined: true, mergedBranch: branch, into: baseBranch, validationSummary, patchEquivalence, submoduleReachability, submoduleAlignment }
29233
29892
  });
29234
29893
  recordMeshRefineStage(refineStages, "ledger", "passed", ledgerStarted);
29235
29894
  } catch (e) {
@@ -29244,6 +29903,7 @@ var DaemonCommandRouter = class {
29244
29903
  removed: removeResult?.success !== false,
29245
29904
  validation: "passed",
29246
29905
  patchEquivalence: "passed",
29906
+ submoduleAlignment: submoduleAlignment.status,
29247
29907
  status: removeResult?.success === false ? "merged_cleanup_failed" : "merged"
29248
29908
  };
29249
29909
  if (removeResult?.success === false) {
@@ -29258,6 +29918,7 @@ var DaemonCommandRouter = class {
29258
29918
  validationSummary,
29259
29919
  patchEquivalence,
29260
29920
  submoduleReachability,
29921
+ submoduleAlignment,
29261
29922
  mergeResult,
29262
29923
  refineStages,
29263
29924
  ...ledgerError ? { ledgerError } : {},
@@ -29273,6 +29934,7 @@ var DaemonCommandRouter = class {
29273
29934
  validationSummary,
29274
29935
  patchEquivalence,
29275
29936
  submoduleReachability,
29937
+ submoduleAlignment,
29276
29938
  mergeResult,
29277
29939
  refineStages,
29278
29940
  ...ledgerError ? { ledgerError } : {},
@@ -30355,6 +31017,12 @@ var DaemonCommandRouter = class {
30355
31017
  success: true,
30356
31018
  schema: MESH_REFINE_CONFIG_SCHEMA,
30357
31019
  locations: MESH_REFINE_CONFIG_LOCATIONS,
31020
+ worktreeBootstrap: {
31021
+ schema: MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA,
31022
+ locations: MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS,
31023
+ sourceOfTruth: "repo worktree bootstrap config",
31024
+ runBehavior: "When present and enabled, clone_mesh_node runs commands after submodule initialization and records status on the worktree node."
31025
+ },
30358
31026
  sourceOfTruth: "repo mesh/refine config",
30359
31027
  heuristicRole: "suggestions_only_not_execution_path"
30360
31028
  };
@@ -30549,8 +31217,8 @@ var DaemonCommandRouter = class {
30549
31217
  const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
30550
31218
  if (initSubmodules) {
30551
31219
  try {
30552
- const { runGit: runGit2 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
30553
- await runGit2(
31220
+ const { runGit: runGit3 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
31221
+ await runGit3(
30554
31222
  { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
30555
31223
  ["submodule", "update", "--init", "--recursive"],
30556
31224
  { timeoutMs: 12e4 }
@@ -30559,12 +31227,35 @@ var DaemonCommandRouter = class {
30559
31227
  console.warn("[mesh] Submodule init failed for worktree:", subErr.message);
30560
31228
  }
30561
31229
  }
31230
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
31231
+ node.worktreeBootstrap = bootstrapState;
31232
+ if (!meshRecord.inline) {
31233
+ try {
31234
+ const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
31235
+ updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState });
31236
+ this.invalidateAggregateMeshStatus(meshId);
31237
+ } catch {
31238
+ }
31239
+ }
30562
31240
  try {
30563
31241
  const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
30564
31242
  appendLedgerEntry2(meshId, {
30565
31243
  kind: "node_cloned",
30566
31244
  nodeId: node.id,
30567
- payload: { sourceNodeId, branch: result.branch, worktreePath: result.worktreePath, submodulesInitialized: initSubmodules }
31245
+ payload: {
31246
+ sourceNodeId,
31247
+ branch: result.branch,
31248
+ worktreePath: result.worktreePath,
31249
+ submodulesInitialized: initSubmodules,
31250
+ worktreeBootstrap: {
31251
+ status: bootstrapState.status,
31252
+ required: bootstrapState.required,
31253
+ configSource: bootstrapState.configSource,
31254
+ configSourceType: bootstrapState.configSourceType,
31255
+ lastCommand: bootstrapState.lastCommand,
31256
+ exitCode: bootstrapState.exitCode
31257
+ }
31258
+ }
30568
31259
  });
30569
31260
  } catch {
30570
31261
  }
@@ -30572,7 +31263,8 @@ var DaemonCommandRouter = class {
30572
31263
  success: true,
30573
31264
  node,
30574
31265
  worktreePath: result.worktreePath,
30575
- branch: result.branch
31266
+ branch: result.branch,
31267
+ worktreeBootstrap: bootstrapState
30576
31268
  };
30577
31269
  } catch (e) {
30578
31270
  return { success: false, error: e.message };
@@ -30800,7 +31492,7 @@ ${block2}`);
30800
31492
  workspace
30801
31493
  };
30802
31494
  }
30803
- const { existsSync: existsSync26, readFileSync: readFileSync19, writeFileSync: writeFileSync14, copyFileSync: copyFileSync4, mkdirSync: mkdirSync18 } = await import("fs");
31495
+ const { existsSync: existsSync28, readFileSync: readFileSync21, writeFileSync: writeFileSync14, copyFileSync: copyFileSync4, mkdirSync: mkdirSync18 } = await import("fs");
30804
31496
  const { dirname: dirname9 } = await import("path");
30805
31497
  const mcpConfigPath = coordinatorSetup.configPath;
30806
31498
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -30843,14 +31535,14 @@ ${block2}`);
30843
31535
  if (hermesManualFallback) return returnManualFallback(message);
30844
31536
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
30845
31537
  }
30846
- const hadExistingMcpConfig = existsSync26(mcpConfigPath);
31538
+ const hadExistingMcpConfig = existsSync28(mcpConfigPath);
30847
31539
  let existingMcpConfig = hermesBaseConfig?.config || {};
30848
31540
  if (hermesBaseConfig) {
30849
31541
  copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname9(mcpConfigPath));
30850
31542
  }
30851
31543
  if (hadExistingMcpConfig) {
30852
31544
  try {
30853
- const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync19(mcpConfigPath, "utf-8"), configFormat);
31545
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync21(mcpConfigPath, "utf-8"), configFormat);
30854
31546
  const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
30855
31547
  existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
30856
31548
  copyFileSync4(mcpConfigPath, mcpConfigPath + ".backup");
@@ -30962,6 +31654,7 @@ ${block2}`);
30962
31654
  const queueSummary = getMeshQueueStats2(meshId);
30963
31655
  const { readLedgerEntries: readLedgerEntries2, getLedgerSummary: getLedgerSummary2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
30964
31656
  const ledgerEntries = readLedgerEntries2(meshId, { tail: 20 });
31657
+ const asyncRefineLedgerEntries = readLedgerEntries2(meshId, { tail: 100 });
30965
31658
  const ledgerSummary = getLedgerSummary2(meshId);
30966
31659
  const sessionHostRecords = this.deps.sessionHostControl?.listSessions ? await this.deps.sessionHostControl.listSessions().catch(() => []) : [];
30967
31660
  const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
@@ -31224,6 +31917,20 @@ ${block2}`);
31224
31917
  nodeStatuses.push(status);
31225
31918
  }
31226
31919
  const pendingCoordinatorEvents = drainPendingMeshCoordinatorEvents(meshId);
31920
+ const previewFreshness = (() => {
31921
+ const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs11.existsSync(candidate));
31922
+ return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
31923
+ })();
31924
+ const asyncRefineJobs = buildMeshAsyncRefineJobs({
31925
+ meshId,
31926
+ ledgerEntries: asyncRefineLedgerEntries,
31927
+ pendingEvents: pendingCoordinatorEvents
31928
+ });
31929
+ const historicalSessions = buildHistoricalMeshSessions({
31930
+ meshId,
31931
+ nodes: mesh.nodes || [],
31932
+ liveSessionRecords: liveMeshSessions
31933
+ });
31227
31934
  const statusResult = {
31228
31935
  success: true,
31229
31936
  meshId: mesh.id,
@@ -31255,12 +31962,15 @@ ${block2}`);
31255
31962
  partialNodeFailures: effectiveDirectTruth.unavailableNodeIds
31256
31963
  }
31257
31964
  } : {},
31258
- historicalEvidenceOnly: ["recoveryHints", "ledger.summary", "queue.summary"]
31965
+ historicalEvidenceOnly: ["recoveryHints", "ledger.summary", "queue.summary", "historicalSessions"]
31259
31966
  },
31260
31967
  branchConvergenceSummary: summarizeInlineMeshBranchConvergence(nodeStatuses),
31968
+ ...previewFreshness ? { previewFreshness, deployFreshness: previewFreshness } : {},
31261
31969
  nodes: nodeStatuses,
31262
31970
  queue: { tasks: queue, summary: queueSummary },
31263
31971
  ledger: { entries: ledgerEntries, summary: ledgerSummary },
31972
+ ...asyncRefineJobs.length > 0 ? { asyncRefineJobs } : {},
31973
+ ...historicalSessions ? { historicalSessions } : {},
31264
31974
  ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {}
31265
31975
  };
31266
31976
  const { pendingCoordinatorEvents: _pendingCoordinatorEvents, ...cacheableStatusResult } = statusResult;
@@ -31911,7 +32621,7 @@ var ProviderStreamAdapter = class {
31911
32621
  const beforeCount = this.messageCount(before);
31912
32622
  const beforeSignature = this.lastMessageSignature(before);
31913
32623
  for (let attempt = 0; attempt < 12; attempt += 1) {
31914
- await new Promise((resolve16) => setTimeout(resolve16, 250));
32624
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
31915
32625
  let state;
31916
32626
  try {
31917
32627
  state = await this.readChat(evaluate);
@@ -31933,7 +32643,7 @@ var ProviderStreamAdapter = class {
31933
32643
  if (this.messageCount(first) > 0 || this.lastMessageSignature(first)) {
31934
32644
  return first;
31935
32645
  }
31936
- await new Promise((resolve16) => setTimeout(resolve16, 150));
32646
+ await new Promise((resolve17) => setTimeout(resolve17, 150));
31937
32647
  const second = await this.readChat(evaluate);
31938
32648
  return this.messageCount(second) >= this.messageCount(first) ? second : first;
31939
32649
  }
@@ -32084,7 +32794,7 @@ var ProviderStreamAdapter = class {
32084
32794
  if (typeof data.error === "string" && data.error.trim()) return false;
32085
32795
  }
32086
32796
  for (let attempt = 0; attempt < 6; attempt += 1) {
32087
- await new Promise((resolve16) => setTimeout(resolve16, 250));
32797
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
32088
32798
  const state = await this.readChat(evaluate);
32089
32799
  const title = this.getStateTitle(state);
32090
32800
  if (this.titlesMatch(title, sessionId)) return true;
@@ -33012,13 +33722,13 @@ var VersionArchive = class {
33012
33722
  }
33013
33723
  };
33014
33724
  async function runCommand(cmd, timeout = 1e4) {
33015
- return new Promise((resolve16) => {
33725
+ return new Promise((resolve17) => {
33016
33726
  (0, import_child_process9.exec)(cmd, {
33017
33727
  encoding: "utf-8",
33018
33728
  timeout
33019
33729
  }, (error, stdout) => {
33020
- if (error) return resolve16(null);
33021
- resolve16(stdout.trim());
33730
+ if (error) return resolve17(null);
33731
+ resolve17(stdout.trim());
33022
33732
  });
33023
33733
  });
33024
33734
  }
@@ -34707,7 +35417,7 @@ function getCliTargetBundle(ctx, type, instanceId) {
34707
35417
  return { target, instance, adapter };
34708
35418
  }
34709
35419
  function sleep2(ms) {
34710
- return new Promise((resolve16) => setTimeout(resolve16, ms));
35420
+ return new Promise((resolve17) => setTimeout(resolve17, ms));
34711
35421
  }
34712
35422
  async function waitForCliReady(ctx, type, instanceId, timeoutMs) {
34713
35423
  const startedAt = Date.now();
@@ -36962,15 +37672,15 @@ var DevServer = class _DevServer {
36962
37672
  this.json(res, 500, { error: e.message });
36963
37673
  }
36964
37674
  });
36965
- return new Promise((resolve16, reject) => {
37675
+ return new Promise((resolve17, reject) => {
36966
37676
  this.server.listen(port, "127.0.0.1", () => {
36967
37677
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
36968
- resolve16();
37678
+ resolve17();
36969
37679
  });
36970
37680
  this.server.on("error", (e) => {
36971
37681
  if (e.code === "EADDRINUSE") {
36972
37682
  this.log(`Port ${port} in use, skipping dev server`);
36973
- resolve16();
37683
+ resolve17();
36974
37684
  } else {
36975
37685
  reject(e);
36976
37686
  }
@@ -37052,20 +37762,20 @@ var DevServer = class _DevServer {
37052
37762
  child.stderr?.on("data", (d) => {
37053
37763
  stderr += d.toString().slice(0, 2e3);
37054
37764
  });
37055
- await new Promise((resolve16) => {
37765
+ await new Promise((resolve17) => {
37056
37766
  const timer = setTimeout(() => {
37057
37767
  child.kill();
37058
- resolve16();
37768
+ resolve17();
37059
37769
  }, 3e3);
37060
37770
  child.on("exit", () => {
37061
37771
  clearTimeout(timer);
37062
- resolve16();
37772
+ resolve17();
37063
37773
  });
37064
37774
  child.stdout?.once("data", () => {
37065
37775
  setTimeout(() => {
37066
37776
  child.kill();
37067
37777
  clearTimeout(timer);
37068
- resolve16();
37778
+ resolve17();
37069
37779
  }, 500);
37070
37780
  });
37071
37781
  });
@@ -37568,14 +38278,14 @@ var DevServer = class _DevServer {
37568
38278
  child.stderr?.on("data", (d) => {
37569
38279
  stderr += d.toString();
37570
38280
  });
37571
- await new Promise((resolve16) => {
38281
+ await new Promise((resolve17) => {
37572
38282
  const timer = setTimeout(() => {
37573
38283
  child.kill();
37574
- resolve16();
38284
+ resolve17();
37575
38285
  }, timeout);
37576
38286
  child.on("exit", () => {
37577
38287
  clearTimeout(timer);
37578
- resolve16();
38288
+ resolve17();
37579
38289
  });
37580
38290
  });
37581
38291
  const elapsed = Date.now() - start;
@@ -38245,14 +38955,14 @@ data: ${JSON.stringify(msg.data)}
38245
38955
  res.end(JSON.stringify(data, null, 2));
38246
38956
  }
38247
38957
  async readBody(req) {
38248
- return new Promise((resolve16) => {
38958
+ return new Promise((resolve17) => {
38249
38959
  let body = "";
38250
38960
  req.on("data", (chunk) => body += chunk);
38251
38961
  req.on("end", () => {
38252
38962
  try {
38253
- resolve16(JSON.parse(body));
38963
+ resolve17(JSON.parse(body));
38254
38964
  } catch {
38255
- resolve16({});
38965
+ resolve17({});
38256
38966
  }
38257
38967
  });
38258
38968
  });
@@ -38790,7 +39500,7 @@ async function waitForReady(endpoint, timeoutMs = STARTUP_TIMEOUT_MS, requiredRe
38790
39500
  const deadline = Date.now() + timeoutMs;
38791
39501
  while (Date.now() < deadline) {
38792
39502
  if (await canConnect(endpoint, requiredRequestTypes)) return;
38793
- await new Promise((resolve16) => setTimeout(resolve16, STARTUP_POLL_MS));
39503
+ await new Promise((resolve17) => setTimeout(resolve17, STARTUP_POLL_MS));
38794
39504
  }
38795
39505
  throw new Error(`Session host did not become ready within ${timeoutMs}ms`);
38796
39506
  }
@@ -38970,10 +39680,10 @@ async function installExtension(ide, extension) {
38970
39680
  const buffer = Buffer.from(await res.arrayBuffer());
38971
39681
  const fs17 = await import("fs");
38972
39682
  fs17.writeFileSync(vsixPath, buffer);
38973
- return new Promise((resolve16) => {
39683
+ return new Promise((resolve17) => {
38974
39684
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
38975
39685
  (0, import_child_process10.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
38976
- resolve16({
39686
+ resolve17({
38977
39687
  extensionId: extension.id,
38978
39688
  marketplaceId: extension.marketplaceId,
38979
39689
  success: !error,
@@ -38986,11 +39696,11 @@ async function installExtension(ide, extension) {
38986
39696
  } catch (e) {
38987
39697
  }
38988
39698
  }
38989
- return new Promise((resolve16) => {
39699
+ return new Promise((resolve17) => {
38990
39700
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
38991
39701
  (0, import_child_process10.exec)(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
38992
39702
  if (error) {
38993
- resolve16({
39703
+ resolve17({
38994
39704
  extensionId: extension.id,
38995
39705
  marketplaceId: extension.marketplaceId,
38996
39706
  success: false,
@@ -38998,7 +39708,7 @@ async function installExtension(ide, extension) {
38998
39708
  error: stderr || error.message
38999
39709
  });
39000
39710
  } else {
39001
- resolve16({
39711
+ resolve17({
39002
39712
  extensionId: extension.id,
39003
39713
  marketplaceId: extension.marketplaceId,
39004
39714
  success: true,
@@ -39373,6 +40083,8 @@ async function shutdownDaemonComponents(components) {
39373
40083
  MAX_LEDGER_SLICE_LIMIT,
39374
40084
  MESH_REFINE_CONFIG_LOCATIONS,
39375
40085
  MESH_REFINE_CONFIG_SCHEMA,
40086
+ MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS,
40087
+ MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA,
39376
40088
  MIN_GIT_WORKSPACE_POLL_INTERVAL_MS,
39377
40089
  MIN_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS,
39378
40090
  MIN_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS,
@@ -39393,10 +40105,12 @@ async function shutdownDaemonComponents(components) {
39393
40105
  buildChatMessage,
39394
40106
  buildChatMessageSignature,
39395
40107
  buildChatTailDeliverySignature,
40108
+ buildCompactStaleDirectWorkSummary,
39396
40109
  buildCoordinatorSystemPrompt,
39397
40110
  buildMachineInfo,
39398
40111
  buildMeshActiveWork,
39399
40112
  buildMeshActiveWorkSummary,
40113
+ buildMeshAsyncRefineJobs,
39400
40114
  buildMeshHostRequiredFailure,
39401
40115
  buildMeshLedgerReconciliationEvidence,
39402
40116
  buildMeshLedgerReplicaEvidence,
@@ -39505,6 +40219,7 @@ async function shutdownDaemonComponents(components) {
39505
40219
  listWorktrees,
39506
40220
  loadConfig,
39507
40221
  loadMeshRefineConfig,
40222
+ loadMeshWorktreeBootstrapConfig,
39508
40223
  loadState,
39509
40224
  logCommand,
39510
40225
  markSetupComplete,
@@ -39556,6 +40271,7 @@ async function shutdownDaemonComponents(components) {
39556
40271
  resolveWorktreePath,
39557
40272
  runAsyncBatch,
39558
40273
  runGit,
40274
+ runMeshWorktreeBootstrap,
39559
40275
  saveConfig,
39560
40276
  saveState,
39561
40277
  setDebugRuntimeConfig,
@@ -39577,6 +40293,7 @@ async function shutdownDaemonComponents(components) {
39577
40293
  updateTaskStatus,
39578
40294
  upsertSavedProviderSession,
39579
40295
  validateMeshRefineConfig,
39580
- validateMeshTaskModeRequest
40296
+ validateMeshTaskModeRequest,
40297
+ validateMeshWorktreeBootstrapConfig
39581
40298
  });
39582
40299
  //# sourceMappingURL=index.js.map