@adhdev/daemon-core 0.9.82-rc.113 → 0.9.82-rc.115

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;
@@ -16490,7 +16826,16 @@ function readHistorySessionIdFromMessages(messages) {
16490
16826
  }
16491
16827
  return void 0;
16492
16828
  }
16493
- function normalizeNativeHistoryMessages(providerType, messages) {
16829
+ function shouldPreserveNativeIdentity(providerType, sessionId, message) {
16830
+ const providerUnitKey = typeof message.providerUnitKey === "string" ? message.providerUnitKey.trim() : "";
16831
+ const turnKey = typeof message._turnKey === "string" ? message._turnKey.trim() : "";
16832
+ if (!providerUnitKey || !turnKey) return false;
16833
+ if (providerType === "hermes-cli" && sessionId) {
16834
+ return providerUnitKey.startsWith(`${providerType}:native:${sessionId}:`) && turnKey.startsWith(`${providerType}:native-turn:${sessionId}:`);
16835
+ }
16836
+ return true;
16837
+ }
16838
+ function normalizeNativeHistoryMessages(providerType, messages, nativeSessionId) {
16494
16839
  let turnIndex = 0;
16495
16840
  return normalizeChatMessages(messages).map((message, index) => {
16496
16841
  const role = typeof message.role === "string" ? message.role.trim().toLowerCase() : "";
@@ -16505,7 +16850,11 @@ function normalizeNativeHistoryMessages(providerType, messages) {
16505
16850
  kind,
16506
16851
  flattenContent(message.content)
16507
16852
  ]).slice(0, 12);
16508
- const providerUnitKey = typeof message.providerUnitKey === "string" && message.providerUnitKey.trim() ? message.providerUnitKey.trim() : `${providerType}:native:${historySessionId || "workspace"}:${index}:${role || "message"}:${kind}:${contentHash}`;
16853
+ const nativeIdentitySessionId = historySessionId || (typeof nativeSessionId === "string" ? nativeSessionId.trim() : "");
16854
+ const preserveNativeIdentity = shouldPreserveNativeIdentity(providerType, nativeIdentitySessionId, message);
16855
+ const existingProviderUnitKey = typeof message.providerUnitKey === "string" ? message.providerUnitKey.trim() : "";
16856
+ const existingTurnKey = typeof message._turnKey === "string" ? message._turnKey.trim() : "";
16857
+ const providerUnitKey = preserveNativeIdentity ? existingProviderUnitKey : `${providerType}:native:${nativeIdentitySessionId || "workspace"}:${index}:${role || "message"}:${kind}:${contentHash}`;
16509
16858
  const meta = message.meta && typeof message.meta === "object" ? message.meta : void 0;
16510
16859
  const isSystemSessionStart = role === "system" || kind === "system" || kind === "session_start";
16511
16860
  const isActivity = role === "assistant" && (kind === "tool" || kind === "terminal" || kind === "thought");
@@ -16514,8 +16863,8 @@ function normalizeNativeHistoryMessages(providerType, messages) {
16514
16863
  role: role === "human" ? "user" : role || "assistant",
16515
16864
  kind: isSystemSessionStart ? "system" : kind,
16516
16865
  providerUnitKey,
16517
- bubbleId: typeof message.bubbleId === "string" && message.bubbleId.trim() ? message.bubbleId.trim() : `bubble:${providerUnitKey}`,
16518
- _turnKey: typeof message._turnKey === "string" && message._turnKey.trim() ? message._turnKey.trim() : `${providerType}:native-turn:${historySessionId || "workspace"}:${turnIndex}`,
16866
+ bubbleId: typeof message.bubbleId === "string" && message.bubbleId.trim() && preserveNativeIdentity ? message.bubbleId.trim() : `bubble:${providerUnitKey}`,
16867
+ _turnKey: preserveNativeIdentity ? existingTurnKey : `${providerType}:native-turn:${nativeIdentitySessionId || "workspace"}:${turnIndex}`,
16519
16868
  bubbleState: message.bubbleState || "final",
16520
16869
  ...isSystemSessionStart ? {
16521
16870
  visibility: message.visibility || "hidden",
@@ -17168,7 +17517,7 @@ function getCliVisibleTranscriptCount(adapter) {
17168
17517
  async function getStableExtensionBaseline(h) {
17169
17518
  const first = await readExtensionChatState(h);
17170
17519
  if (getStateMessageCount(first) > 0 || getStateLastSignature(first)) return first;
17171
- await new Promise((resolve16) => setTimeout(resolve16, 150));
17520
+ await new Promise((resolve17) => setTimeout(resolve17, 150));
17172
17521
  const second = await readExtensionChatState(h);
17173
17522
  return getStateMessageCount(second) >= getStateMessageCount(first) ? second : first;
17174
17523
  }
@@ -17176,7 +17525,7 @@ async function verifyExtensionSendObserved(h, before) {
17176
17525
  const beforeCount = getStateMessageCount(before);
17177
17526
  const beforeSignature = getStateLastSignature(before);
17178
17527
  for (let attempt = 0; attempt < 12; attempt += 1) {
17179
- await new Promise((resolve16) => setTimeout(resolve16, 250));
17528
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
17180
17529
  const state = await readExtensionChatState(h);
17181
17530
  if (state?.status === "waiting_approval") return true;
17182
17531
  const afterCount = getStateMessageCount(state);
@@ -17226,7 +17575,7 @@ async function handleChatHistory(h, args) {
17226
17575
  });
17227
17576
  if (supportsCliNativeTranscript(agentStr, provider) && isNativeSourceCanonicalHistory(provider?.canonicalHistory)) {
17228
17577
  const lookup = result.lookup === "workspace" ? "workspace" : "session";
17229
- const messages = Array.isArray(result.messages) ? normalizeNativeHistoryMessages(agentStr, result.messages) : [];
17578
+ const messages = Array.isArray(result.messages) ? normalizeNativeHistoryMessages(agentStr, result.messages, result?.providerSessionId) : [];
17230
17579
  const historyProviderSessionId = typeof result?.providerSessionId === "string" ? result.providerSessionId : readHistorySessionIdFromMessages(messages) || historySessionId;
17231
17580
  const safeMapping = hasSafeNativeHistoryMapping({
17232
17581
  historySessionId: lookup === "workspace" ? void 0 : historySessionId,
@@ -17334,7 +17683,7 @@ async function handleReadChat(h, args) {
17334
17683
  nativeHistory = null;
17335
17684
  }
17336
17685
  if (nativeHistory) {
17337
- const nativeMessages = Array.isArray(nativeHistory.messages) ? normalizeNativeHistoryMessages(agentStr, nativeHistory.messages) : [];
17686
+ const nativeMessages = Array.isArray(nativeHistory.messages) ? normalizeNativeHistoryMessages(agentStr, nativeHistory.messages, nativeHistory?.providerSessionId) : [];
17338
17687
  const historyProviderSessionId = typeof nativeHistory?.providerSessionId === "string" ? nativeHistory.providerSessionId : readHistorySessionIdFromMessages(nativeMessages) || nativeHistorySessionId || historySessionId;
17339
17688
  const nativeHistoryCoverage = typeof nativeHistory?.nativeHistoryCoverage === "string" ? nativeHistory.nativeHistoryCoverage : void 0;
17340
17689
  const partialReason = typeof nativeHistory?.partialReason === "string" ? nativeHistory.partialReason : void 0;
@@ -17462,7 +17811,7 @@ async function handleReadChat(h, args) {
17462
17811
  scripts: provider?.scripts
17463
17812
  });
17464
17813
  const lookup = history.lookup === "workspace" ? "workspace" : "session";
17465
- const historyMessages = Array.isArray(history?.messages) ? normalizeNativeHistoryMessages(agentStr, history.messages) : [];
17814
+ const historyMessages = Array.isArray(history?.messages) ? normalizeNativeHistoryMessages(agentStr, history.messages, history?.providerSessionId) : [];
17466
17815
  const historyProviderSessionId = typeof history?.providerSessionId === "string" ? history.providerSessionId : readHistorySessionIdFromMessages(historyMessages) || historySessionId;
17467
17816
  const nativeHistoryCoverage = typeof history?.nativeHistoryCoverage === "string" ? history.nativeHistoryCoverage : void 0;
17468
17817
  const partialReason = typeof history?.partialReason === "string" ? history.partialReason : void 0;
@@ -19065,7 +19414,7 @@ async function executeProviderScript(h, args, scriptName) {
19065
19414
  const enterCount = cliCommand.enterCount || 1;
19066
19415
  await adapter.writeRaw(cliCommand.text + "\r");
19067
19416
  for (let i = 1; i < enterCount; i += 1) {
19068
- await new Promise((resolve16) => setTimeout(resolve16, 50));
19417
+ await new Promise((resolve17) => setTimeout(resolve17, 50));
19069
19418
  await adapter.writeRaw("\r");
19070
19419
  }
19071
19420
  }
@@ -19754,7 +20103,7 @@ var DaemonCommandHandler = class {
19754
20103
  try {
19755
20104
  const http3 = await import("http");
19756
20105
  const postData = JSON.stringify(body);
19757
- const result = await new Promise((resolve16, reject) => {
20106
+ const result = await new Promise((resolve17, reject) => {
19758
20107
  const req = http3.request({
19759
20108
  hostname: "127.0.0.1",
19760
20109
  port: 19280,
@@ -19766,9 +20115,9 @@ var DaemonCommandHandler = class {
19766
20115
  res.on("data", (chunk) => data += chunk);
19767
20116
  res.on("end", () => {
19768
20117
  try {
19769
- resolve16(JSON.parse(data));
20118
+ resolve17(JSON.parse(data));
19770
20119
  } catch {
19771
- resolve16({ raw: data });
20120
+ resolve17({ raw: data });
19772
20121
  }
19773
20122
  });
19774
20123
  });
@@ -19786,15 +20135,15 @@ var DaemonCommandHandler = class {
19786
20135
  if (!providerType) return { success: false, error: "providerType required" };
19787
20136
  try {
19788
20137
  const http3 = await import("http");
19789
- const result = await new Promise((resolve16, reject) => {
20138
+ const result = await new Promise((resolve17, reject) => {
19790
20139
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
19791
20140
  let data = "";
19792
20141
  res.on("data", (chunk) => data += chunk);
19793
20142
  res.on("end", () => {
19794
20143
  try {
19795
- resolve16(JSON.parse(data));
20144
+ resolve17(JSON.parse(data));
19796
20145
  } catch {
19797
- resolve16({ raw: data });
20146
+ resolve17({ raw: data });
19798
20147
  }
19799
20148
  });
19800
20149
  }).on("error", reject);
@@ -19808,7 +20157,7 @@ var DaemonCommandHandler = class {
19808
20157
  try {
19809
20158
  const http3 = await import("http");
19810
20159
  const postData = JSON.stringify(args || {});
19811
- const result = await new Promise((resolve16, reject) => {
20160
+ const result = await new Promise((resolve17, reject) => {
19812
20161
  const req = http3.request({
19813
20162
  hostname: "127.0.0.1",
19814
20163
  port: 19280,
@@ -19820,9 +20169,9 @@ var DaemonCommandHandler = class {
19820
20169
  res.on("data", (chunk) => data += chunk);
19821
20170
  res.on("end", () => {
19822
20171
  try {
19823
- resolve16(JSON.parse(data));
20172
+ resolve17(JSON.parse(data));
19824
20173
  } catch {
19825
- resolve16({ raw: data });
20174
+ resolve17({ raw: data });
19826
20175
  }
19827
20176
  });
19828
20177
  });
@@ -19841,7 +20190,7 @@ var DaemonCommandHandler = class {
19841
20190
  var os13 = __toESM(require("os"));
19842
20191
  var path18 = __toESM(require("path"));
19843
20192
  var crypto4 = __toESM(require("crypto"));
19844
- var import_fs10 = require("fs");
20193
+ var import_fs11 = require("fs");
19845
20194
  var import_child_process5 = require("child_process");
19846
20195
  var import_chalk = __toESM(require("chalk"));
19847
20196
  init_provider_cli_adapter();
@@ -20066,7 +20415,7 @@ async function waitForCliAdapterReady(adapter, options) {
20066
20415
  if (status === "stopped") {
20067
20416
  throw new Error("CLI runtime stopped before it became ready");
20068
20417
  }
20069
- await new Promise((resolve16) => setTimeout(resolve16, pollMs));
20418
+ await new Promise((resolve17) => setTimeout(resolve17, pollMs));
20070
20419
  }
20071
20420
  throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
20072
20421
  }
@@ -20443,7 +20792,7 @@ var CliProviderInstance = class {
20443
20792
  const enterCount = cliCommand.enterCount || 1;
20444
20793
  await this.adapter.writeRaw(cliCommand.text + "\r");
20445
20794
  for (let i = 1; i < enterCount; i += 1) {
20446
- await new Promise((resolve16) => setTimeout(resolve16, 50));
20795
+ await new Promise((resolve17) => setTimeout(resolve17, 50));
20447
20796
  await this.adapter.writeRaw("\r");
20448
20797
  }
20449
20798
  }
@@ -21839,13 +22188,13 @@ var AcpProviderInstance = class {
21839
22188
  }
21840
22189
  this.currentStatus = "waiting_approval";
21841
22190
  this.detectStatusTransition();
21842
- const approved = await new Promise((resolve16) => {
21843
- this.permissionResolvers.push(resolve16);
22191
+ const approved = await new Promise((resolve17) => {
22192
+ this.permissionResolvers.push(resolve17);
21844
22193
  setTimeout(() => {
21845
- const idx = this.permissionResolvers.indexOf(resolve16);
22194
+ const idx = this.permissionResolvers.indexOf(resolve17);
21846
22195
  if (idx >= 0) {
21847
22196
  this.permissionResolvers.splice(idx, 1);
21848
- resolve16(false);
22197
+ resolve17(false);
21849
22198
  }
21850
22199
  }, 3e5);
21851
22200
  });
@@ -22456,7 +22805,7 @@ function commandExists(command) {
22456
22805
  const trimmed = command.trim();
22457
22806
  if (!trimmed) return false;
22458
22807
  if (isExplicitCommand(trimmed)) {
22459
- return (0, import_fs10.existsSync)(expandExecutable(trimmed));
22808
+ return (0, import_fs11.existsSync)(expandExecutable(trimmed));
22460
22809
  }
22461
22810
  try {
22462
22811
  (0, import_child_process5.execFileSync)(process.platform === "win32" ? "where" : "which", [trimmed], {
@@ -22554,7 +22903,7 @@ async function waitForZeroMessageStartingLaunch(adapter) {
22554
22903
  } catch {
22555
22904
  return false;
22556
22905
  }
22557
- await new Promise((resolve16) => setTimeout(resolve16, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
22906
+ await new Promise((resolve17) => setTimeout(resolve17, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
22558
22907
  try {
22559
22908
  return hasZeroMessageStartingLaunch(adapter);
22560
22909
  } catch {
@@ -22578,10 +22927,10 @@ function hasCliArg(args, flag) {
22578
22927
  }
22579
22928
  function ensureEmptyDelegatedMcpConfig(workspace) {
22580
22929
  const baseDir = path18.join(os13.tmpdir(), "adhdev-delegated-agent-empty-mcp");
22581
- (0, import_fs10.mkdirSync)(baseDir, { recursive: true });
22930
+ (0, import_fs11.mkdirSync)(baseDir, { recursive: true });
22582
22931
  const workspaceHash = crypto4.createHash("sha256").update(path18.resolve(workspace || os13.tmpdir())).digest("hex").slice(0, 16);
22583
22932
  const filePath = path18.join(baseDir, `${workspaceHash}.json`);
22584
- (0, import_fs10.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
22933
+ (0, import_fs11.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
22585
22934
  return filePath;
22586
22935
  }
22587
22936
  function buildCoordinatorDelegatedCliLaunchOptions(input) {
@@ -24627,8 +24976,8 @@ var ProviderLoader = class _ProviderLoader {
24627
24976
  }
24628
24977
  const https = require("https");
24629
24978
  const { exec: exec7 } = require("child_process");
24630
- const { promisify: promisify6 } = require("util");
24631
- const execAsync5 = promisify6(exec7);
24979
+ const { promisify: promisify7 } = require("util");
24980
+ const execAsync5 = promisify7(exec7);
24632
24981
  const metaPath = path19.join(this.upstreamDir, _ProviderLoader.META_FILE);
24633
24982
  let prevEtag = "";
24634
24983
  let prevTimestamp = 0;
@@ -24646,7 +24995,7 @@ var ProviderLoader = class _ProviderLoader {
24646
24995
  return { updated: false };
24647
24996
  }
24648
24997
  try {
24649
- const etag = await new Promise((resolve16, reject) => {
24998
+ const etag = await new Promise((resolve17, reject) => {
24650
24999
  const options = {
24651
25000
  method: "HEAD",
24652
25001
  hostname: "github.com",
@@ -24664,7 +25013,7 @@ var ProviderLoader = class _ProviderLoader {
24664
25013
  headers: { "User-Agent": "adhdev-launcher" },
24665
25014
  timeout: 1e4
24666
25015
  }, (res2) => {
24667
- resolve16(res2.headers.etag || res2.headers["last-modified"] || "");
25016
+ resolve17(res2.headers.etag || res2.headers["last-modified"] || "");
24668
25017
  });
24669
25018
  req2.on("error", reject);
24670
25019
  req2.on("timeout", () => {
@@ -24673,7 +25022,7 @@ var ProviderLoader = class _ProviderLoader {
24673
25022
  });
24674
25023
  req2.end();
24675
25024
  } else {
24676
- resolve16(res.headers.etag || res.headers["last-modified"] || "");
25025
+ resolve17(res.headers.etag || res.headers["last-modified"] || "");
24677
25026
  }
24678
25027
  });
24679
25028
  req.on("error", reject);
@@ -24737,7 +25086,7 @@ var ProviderLoader = class _ProviderLoader {
24737
25086
  downloadFile(url, destPath) {
24738
25087
  const https = require("https");
24739
25088
  const http3 = require("http");
24740
- return new Promise((resolve16, reject) => {
25089
+ return new Promise((resolve17, reject) => {
24741
25090
  const doRequest = (reqUrl, redirectCount = 0) => {
24742
25091
  if (redirectCount > 5) {
24743
25092
  reject(new Error("Too many redirects"));
@@ -24757,7 +25106,7 @@ var ProviderLoader = class _ProviderLoader {
24757
25106
  res.pipe(ws);
24758
25107
  ws.on("finish", () => {
24759
25108
  ws.close();
24760
- resolve16();
25109
+ resolve17();
24761
25110
  });
24762
25111
  ws.on("error", reject);
24763
25112
  });
@@ -25260,10 +25609,10 @@ function findMacAppProcessPids(psOutput, appPaths) {
25260
25609
 
25261
25610
  // src/launch.ts
25262
25611
  async function execQuiet(command, options = {}) {
25263
- return new Promise((resolve16) => {
25612
+ return new Promise((resolve17) => {
25264
25613
  (0, import_child_process6.exec)(command, options, (error, stdout) => {
25265
- if (error) return resolve16("");
25266
- resolve16(stdout.toString());
25614
+ if (error) return resolve17("");
25615
+ resolve17(stdout.toString());
25267
25616
  });
25268
25617
  });
25269
25618
  }
@@ -25344,17 +25693,17 @@ async function findFreePort(ports) {
25344
25693
  throw new Error("No free port found");
25345
25694
  }
25346
25695
  function checkPortFree(port) {
25347
- return new Promise((resolve16) => {
25696
+ return new Promise((resolve17) => {
25348
25697
  const server = net.createServer();
25349
25698
  server.unref();
25350
- server.on("error", () => resolve16(false));
25699
+ server.on("error", () => resolve17(false));
25351
25700
  server.listen(port, "127.0.0.1", () => {
25352
- server.close(() => resolve16(true));
25701
+ server.close(() => resolve17(true));
25353
25702
  });
25354
25703
  });
25355
25704
  }
25356
25705
  async function isCdpActive(port) {
25357
- return new Promise((resolve16) => {
25706
+ return new Promise((resolve17) => {
25358
25707
  const req = require("http").get(`http://127.0.0.1:${port}/json/version`, {
25359
25708
  timeout: 2e3
25360
25709
  }, (res) => {
@@ -25363,16 +25712,16 @@ async function isCdpActive(port) {
25363
25712
  res.on("end", () => {
25364
25713
  try {
25365
25714
  const info = JSON.parse(data);
25366
- resolve16(!!info["WebKit-Version"] || !!info["Browser"]);
25715
+ resolve17(!!info["WebKit-Version"] || !!info["Browser"]);
25367
25716
  } catch {
25368
- resolve16(false);
25717
+ resolve17(false);
25369
25718
  }
25370
25719
  });
25371
25720
  });
25372
- req.on("error", () => resolve16(false));
25721
+ req.on("error", () => resolve17(false));
25373
25722
  req.on("timeout", () => {
25374
25723
  req.destroy();
25375
- resolve16(false);
25724
+ resolve17(false);
25376
25725
  });
25377
25726
  });
25378
25727
  }
@@ -25846,7 +26195,7 @@ function getRecentCommands(count = 50) {
25846
26195
  cleanOldFiles();
25847
26196
 
25848
26197
  // src/commands/router.ts
25849
- var yaml2 = __toESM(require("js-yaml"));
26198
+ var yaml3 = __toESM(require("js-yaml"));
25850
26199
  init_logger();
25851
26200
 
25852
26201
  // src/commands/mesh-coordinator.ts
@@ -26034,6 +26383,88 @@ function resolveMcpPort(explicitPort) {
26034
26383
  init_mesh_events();
26035
26384
  init_mesh_host_ownership();
26036
26385
 
26386
+ // src/mesh/preview-freshness.ts
26387
+ var import_node_child_process4 = require("child_process");
26388
+ var import_node_fs3 = require("fs");
26389
+ var import_node_path2 = require("path");
26390
+ var PREVIEW_DEPLOY_RECORD = ".adhdev/preview-deploy.json";
26391
+ function runGit2(repoRoot, args) {
26392
+ try {
26393
+ return (0, import_node_child_process4.execFileSync)("git", args, {
26394
+ cwd: repoRoot,
26395
+ encoding: "utf8",
26396
+ stdio: ["ignore", "pipe", "ignore"],
26397
+ timeout: 5e3
26398
+ }).trim();
26399
+ } catch {
26400
+ return "";
26401
+ }
26402
+ }
26403
+ function readRecord3(repoRoot) {
26404
+ const path28 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
26405
+ if (!(0, import_node_fs3.existsSync)(path28)) return null;
26406
+ try {
26407
+ const parsed = JSON.parse((0, import_node_fs3.readFileSync)(path28, "utf8"));
26408
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
26409
+ } catch {
26410
+ return null;
26411
+ }
26412
+ }
26413
+ function normalizeCommit(value) {
26414
+ return typeof value === "string" && /^[0-9a-f]{7,40}$/i.test(value.trim()) ? value.trim() : null;
26415
+ }
26416
+ function readTargetFreshness(record, currentCommit) {
26417
+ const targets = record?.targets && typeof record.targets === "object" && !Array.isArray(record.targets) ? record.targets : {};
26418
+ const result = {};
26419
+ for (const targetName of ["npm", "server", "web"]) {
26420
+ const targetRecord = targets[targetName] && typeof targets[targetName] === "object" && !Array.isArray(targets[targetName]) ? targets[targetName] : {};
26421
+ const commit = normalizeCommit(targetRecord.commit);
26422
+ result[targetName] = {
26423
+ commit,
26424
+ deployedAt: typeof targetRecord.deployedAt === "string" ? targetRecord.deployedAt : void 0,
26425
+ status: commit && currentCommit ? commit === currentCommit ? "fresh" : "stale" : "unknown"
26426
+ };
26427
+ }
26428
+ return result;
26429
+ }
26430
+ function readCurrentMainCommit(repoRoot) {
26431
+ const originMain = runGit2(repoRoot, ["rev-parse", "--verify", "origin/main^{commit}"]);
26432
+ if (originMain) {
26433
+ return { currentMainCommit: originMain, currentMainCommitSource: "origin/main" };
26434
+ }
26435
+ const head = runGit2(repoRoot, ["rev-parse", "--verify", "HEAD"]);
26436
+ if (head) {
26437
+ return { currentMainCommit: head, currentMainCommitSource: "HEAD" };
26438
+ }
26439
+ return { currentMainCommit: null, currentMainCommitSource: "unknown" };
26440
+ }
26441
+ function buildPreviewFreshness(repoRoot) {
26442
+ const current = readCurrentMainCommit(repoRoot);
26443
+ const record = readRecord3(repoRoot);
26444
+ const lastPreviewCommit = normalizeCommit(record?.lastPreviewCommit);
26445
+ const targets = readTargetFreshness(record, current.currentMainCommit);
26446
+ let status = "unknown";
26447
+ let nextAction = "Run npm run deploy:preview from the current main commit, then smoke preview.";
26448
+ if (lastPreviewCommit && current.currentMainCommit) {
26449
+ status = lastPreviewCommit === current.currentMainCommit ? "fresh" : "stale";
26450
+ nextAction = status === "fresh" ? "No preview deploy action needed." : "Run npm run deploy:preview from origin/main, then smoke preview.";
26451
+ } else if (!current.currentMainCommit) {
26452
+ nextAction = "Resolve the current main commit before judging preview freshness.";
26453
+ }
26454
+ return {
26455
+ status,
26456
+ lastPreviewCommit,
26457
+ currentMainCommit: current.currentMainCommit,
26458
+ currentMainCommitSource: current.currentMainCommitSource,
26459
+ recordPath: PREVIEW_DEPLOY_RECORD,
26460
+ lastDeployedAt: typeof record?.updatedAt === "string" ? record.updatedAt : void 0,
26461
+ lastTarget: typeof record?.target === "string" ? record.target : void 0,
26462
+ previewVersion: typeof record?.previewVersion === "string" ? record.previewVersion : void 0,
26463
+ targets,
26464
+ nextAction
26465
+ };
26466
+ }
26467
+
26037
26468
  // src/status/snapshot.ts
26038
26469
  var os18 = __toESM(require("os"));
26039
26470
  init_config();
@@ -26540,7 +26971,7 @@ async function waitForPidExit(pid, timeoutMs) {
26540
26971
  while (Date.now() - start < timeoutMs) {
26541
26972
  try {
26542
26973
  process.kill(pid, 0);
26543
- await new Promise((resolve16) => setTimeout(resolve16, 250));
26974
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
26544
26975
  } catch {
26545
26976
  return;
26546
26977
  }
@@ -26651,7 +27082,7 @@ async function runDaemonUpgradeHelper(payload) {
26651
27082
  appendUpgradeLog(installOutput.trim());
26652
27083
  }
26653
27084
  if (process.platform === "win32") {
26654
- await new Promise((resolve16) => setTimeout(resolve16, 500));
27085
+ await new Promise((resolve17) => setTimeout(resolve17, 500));
26655
27086
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
26656
27087
  appendUpgradeLog("Post-install staging cleanup complete");
26657
27088
  }
@@ -26688,8 +27119,9 @@ async function maybeRunDaemonUpgradeHelperFromEnv() {
26688
27119
  // src/commands/router.ts
26689
27120
  init_mesh_work_queue();
26690
27121
  var import_os3 = require("os");
26691
- var import_path8 = require("path");
27122
+ var import_path9 = require("path");
26692
27123
  var fs11 = __toESM(require("fs"));
27124
+ var import_node_child_process5 = require("child_process");
26693
27125
  var CHANNEL_NPM_TAG = { stable: "latest", preview: "next" };
26694
27126
  var CHANNEL_SERVER_URL = {
26695
27127
  stable: "https://api.adhf.dev",
@@ -26835,7 +27267,7 @@ function buildMeshNodeDisplayLabel(node, nodeId, providerPriority) {
26835
27267
  const explicit = readStringValue(node.machineLabel, node.machine_label, node.machineNickname, node.machine_nickname, node.alias);
26836
27268
  if (explicit) return explicit;
26837
27269
  const workspace = readStringValue(node.workspace, node.repoRoot, node.repo_root);
26838
- const workspaceName = workspace ? (0, import_path8.basename)(workspace) : void 0;
27270
+ const workspaceName = workspace ? (0, import_path9.basename)(workspace) : void 0;
26839
27271
  const host = readStringValue(node.machineName, node.machine_name, node.hostname, node.host, node.daemonId, node.daemon_id, node.machineId, node.machine_id);
26840
27272
  const provider = providerPriority[0] || (Array.isArray(node.providers) ? readStringValue(...node.providers) : void 0);
26841
27273
  const parts = [workspaceName, host, provider].filter(Boolean);
@@ -27401,6 +27833,16 @@ function finalizeMeshNodeStatus(args) {
27401
27833
  if (machineStatus) status.machineStatus = machineStatus;
27402
27834
  }
27403
27835
  synthesizeMeshNodeFreshnessFromConnection(status);
27836
+ const bootstrap = readObjectRecord(node?.worktreeBootstrap);
27837
+ if (node?.isLocalWorktree && readStringValue(bootstrap.status)) {
27838
+ status.worktreeBootstrap = bootstrap;
27839
+ if (bootstrap.status === "failed" && bootstrap.required !== false) {
27840
+ status.launchReady = false;
27841
+ status.launchBlockedReason = "worktree_bootstrap_failed";
27842
+ status.launchBlockedMessage = readStringValue(bootstrap.error) || "Required worktree bootstrap failed; resolve it before launching an agent into this node.";
27843
+ return;
27844
+ }
27845
+ }
27404
27846
  const connectionState = readStringValue(readObjectRecord(status.connection).state);
27405
27847
  status.launchReady = !!daemonId && (readStringValue(status.machineStatus) === "online" || connectionState === "connected" || isSelfNode);
27406
27848
  }
@@ -27542,6 +27984,40 @@ function collectLiveMeshSessionRecords(args) {
27542
27984
  }
27543
27985
  return matches;
27544
27986
  }
27987
+ function buildHistoricalMeshSessions(args) {
27988
+ const liveNodeIds = /* @__PURE__ */ new Set();
27989
+ const liveWorkspaces = /* @__PURE__ */ new Set();
27990
+ for (const node of args.nodes || []) {
27991
+ const nodeId = readStringValue(node?.id, node?.nodeId);
27992
+ const workspace = readStringValue(node?.workspace);
27993
+ if (nodeId) liveNodeIds.add(nodeId);
27994
+ if (workspace) liveWorkspaces.add(workspace);
27995
+ }
27996
+ const sessions = [];
27997
+ for (const record of args.liveSessionRecords || []) {
27998
+ const meta = readObjectRecord(record?.meta);
27999
+ const recordMeshId = readStringValue(meta.meshNodeFor, meta.meshCoordinatorFor);
28000
+ if (recordMeshId !== args.meshId) continue;
28001
+ const recordNodeId = readStringValue(meta.meshNodeId);
28002
+ const workspace = readStringValue(record?.workspace);
28003
+ const removedNode = !!recordNodeId && !liveNodeIds.has(recordNodeId);
28004
+ const orphanedWorkspace = !!workspace && !liveWorkspaces.has(workspace) && meta.meshCoordinatorFor !== args.meshId;
28005
+ if (!removedNode && !orphanedWorkspace) continue;
28006
+ sessions.push({
28007
+ ...summarizeMeshSessionRecord(record),
28008
+ classification: removedNode ? "removedNode" : "orphanedSession",
28009
+ historical: true,
28010
+ meshNodeId: recordNodeId || null,
28011
+ 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."
28012
+ });
28013
+ }
28014
+ if (sessions.length === 0) return void 0;
28015
+ return {
28016
+ count: sessions.length,
28017
+ sessions: sessions.slice(0, 5),
28018
+ 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."
28019
+ };
28020
+ }
27545
28021
  function applyCachedInlineMeshNodeStatus(status, node, options) {
27546
28022
  const cachedStatus = readObjectRecord(node?.cachedStatus);
27547
28023
  const liveGit = buildInlineMeshTransitGitStatus(node);
@@ -27627,14 +28103,14 @@ function resolveRefineryAutoPublishSubmoduleMainCommits(mesh, workspace) {
27627
28103
  return { enabled: false };
27628
28104
  }
27629
28105
  async function computeGitPatchId(cwd, fromRef, toRef) {
27630
- const { execFileSync: execFileSync3 } = await import("child_process");
27631
- const diff = execFileSync3("git", ["diff", "--patch", "--full-index", fromRef, toRef], {
28106
+ const { execFileSync: execFileSync5 } = await import("child_process");
28107
+ const diff = execFileSync5("git", ["diff", "--patch", "--full-index", fromRef, toRef], {
27632
28108
  cwd,
27633
28109
  encoding: "utf8",
27634
28110
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
27635
28111
  });
27636
28112
  if (!diff.trim()) return "";
27637
- const patchId = execFileSync3("git", ["patch-id", "--stable"], {
28113
+ const patchId = execFileSync5("git", ["patch-id", "--stable"], {
27638
28114
  cwd,
27639
28115
  input: diff,
27640
28116
  encoding: "utf8",
@@ -27645,8 +28121,8 @@ async function computeGitPatchId(cwd, fromRef, toRef) {
27645
28121
  async function runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead) {
27646
28122
  const startedAt = Date.now();
27647
28123
  try {
27648
- const { execFileSync: execFileSync3 } = await import("child_process");
27649
- const git = (args) => execFileSync3("git", args, {
28124
+ const { execFileSync: execFileSync5 } = await import("child_process");
28125
+ const git = (args) => execFileSync5("git", args, {
27650
28126
  cwd: repoRoot,
27651
28127
  encoding: "utf8",
27652
28128
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -27690,6 +28166,135 @@ async function runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead)
27690
28166
  durationMs: Date.now() - startedAt,
27691
28167
  error: e?.message || String(e),
27692
28168
  stdout: truncateValidationOutput(e?.stdout),
28169
+ stderr: truncateValidationOutput(e?.stderr),
28170
+ actionableHint: buildPatchEquivalenceSubmoduleConflictHint(
28171
+ repoRoot,
28172
+ baseHead,
28173
+ branchHead,
28174
+ `${e?.message || ""}
28175
+ ${e?.stdout || ""}
28176
+ ${e?.stderr || ""}`
28177
+ )
28178
+ };
28179
+ }
28180
+ }
28181
+ function buildPatchEquivalenceSubmoduleConflictHint(repoRoot, baseHead, branchHead, output) {
28182
+ if (!/(submodule|160000)/i.test(output) || !/(conflict|failed to merge)/i.test(output)) return void 0;
28183
+ const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path28) => ({
28184
+ path: path28,
28185
+ baseCommit: readTreeObject(repoRoot, baseHead, path28),
28186
+ branchCommit: readTreeObject(repoRoot, branchHead, path28)
28187
+ }));
28188
+ if (conflicts.length === 0) return void 0;
28189
+ return {
28190
+ kind: "submodule_conflict",
28191
+ message: "Refinery could not synthesize a safe merge tree because the branch and base point the same submodule path at different commits.",
28192
+ conflicts,
28193
+ nextSteps: [
28194
+ "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.",
28195
+ "Resolve the submodule first by checking out or creating the intended submodule commit, then commit the chosen gitlink in the root branch.",
28196
+ "Ensure the chosen submodule commit is reachable from the configured submodule remote main branch, then rerun mesh_refine_node."
28197
+ ]
28198
+ };
28199
+ }
28200
+ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
28201
+ try {
28202
+ const output = (0, import_node_child_process5.execFileSync)("git", ["diff", "--raw", "--no-abbrev", fromRef, toRef], {
28203
+ cwd: repoRoot,
28204
+ encoding: "utf8",
28205
+ maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
28206
+ });
28207
+ const paths = /* @__PURE__ */ new Set();
28208
+ for (const line of output.split("\n")) {
28209
+ if (!line.trim()) continue;
28210
+ const metaAndPath = line.split(" ");
28211
+ const meta = metaAndPath[0] || "";
28212
+ const path28 = metaAndPath[metaAndPath.length - 1]?.trim();
28213
+ if (!path28) continue;
28214
+ const parts = meta.split(/\s+/);
28215
+ if (parts[0]?.includes("160000") || parts[1]?.includes("160000")) {
28216
+ paths.add(path28);
28217
+ }
28218
+ }
28219
+ return [...paths].sort();
28220
+ } catch {
28221
+ return [];
28222
+ }
28223
+ }
28224
+ function readTreeObject(repoRoot, ref, path28) {
28225
+ try {
28226
+ const output = (0, import_node_child_process5.execFileSync)("git", ["ls-tree", ref, "--", path28], {
28227
+ cwd: repoRoot,
28228
+ encoding: "utf8",
28229
+ maxBuffer: 1024 * 1024
28230
+ }).trim();
28231
+ const match = output.match(/\bcommit\s+([0-9a-f]{40})\b/i);
28232
+ return match?.[1];
28233
+ } catch {
28234
+ return void 0;
28235
+ }
28236
+ }
28237
+ async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, currentHead, options = {}) {
28238
+ const startedAt = Date.now();
28239
+ const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path28) => !(options.submoduleIgnorePaths || []).includes(path28));
28240
+ const preStatus = await getGitRepoStatus(repoRoot, {
28241
+ includeSubmodules: true,
28242
+ submoduleIgnorePaths: options.submoduleIgnorePaths,
28243
+ timeoutMs: 15e3
28244
+ });
28245
+ const outOfSyncPaths = (preStatus.submodules || []).filter((submodule) => submodule.dirty || submodule.outOfSync || !!submodule.error).map((submodule) => submodule.path);
28246
+ const updatePaths = [.../* @__PURE__ */ new Set([...changedGitlinkPaths, ...outOfSyncPaths])].sort();
28247
+ if (updatePaths.length === 0) {
28248
+ return {
28249
+ status: "skipped",
28250
+ changedGitlinkPaths,
28251
+ outOfSyncPaths,
28252
+ updatedPaths: [],
28253
+ verifiedPaths: [],
28254
+ durationMs: Date.now() - startedAt,
28255
+ reason: "no_changed_or_out_of_sync_submodules"
28256
+ };
28257
+ }
28258
+ const commandArgs = ["submodule", "update", "--init", "--recursive", "--", ...updatePaths];
28259
+ try {
28260
+ const { execFile: execFile4 } = await import("child_process");
28261
+ const { promisify: promisify7 } = await import("util");
28262
+ const execFileAsync3 = promisify7(execFile4);
28263
+ const result = await execFileAsync3("git", commandArgs, {
28264
+ cwd: repoRoot,
28265
+ encoding: "utf8",
28266
+ maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES,
28267
+ timeout: 6e4
28268
+ });
28269
+ const postStatus = await getGitRepoStatus(repoRoot, {
28270
+ includeSubmodules: true,
28271
+ submoduleIgnorePaths: options.submoduleIgnorePaths,
28272
+ timeoutMs: 15e3
28273
+ });
28274
+ const remaining = (postStatus.submodules || []).filter((submodule) => updatePaths.includes(submodule.path) && (submodule.dirty || submodule.outOfSync || !!submodule.error));
28275
+ return {
28276
+ status: remaining.length === 0 ? "passed" : "failed",
28277
+ changedGitlinkPaths,
28278
+ outOfSyncPaths,
28279
+ updatedPaths: updatePaths,
28280
+ verifiedPaths: updatePaths.filter((path28) => !remaining.some((submodule) => submodule.path === path28)),
28281
+ durationMs: Date.now() - startedAt,
28282
+ command: `git ${commandArgs.join(" ")}`,
28283
+ stdout: truncateValidationOutput(result.stdout),
28284
+ stderr: truncateValidationOutput(result.stderr),
28285
+ ...remaining.length > 0 ? { error: `Submodule checkout remained out of sync after update: ${remaining.map((entry) => entry.path).join(", ")}` } : {}
28286
+ };
28287
+ } catch (e) {
28288
+ return {
28289
+ status: "failed",
28290
+ changedGitlinkPaths,
28291
+ outOfSyncPaths,
28292
+ updatedPaths: updatePaths,
28293
+ verifiedPaths: [],
28294
+ durationMs: Date.now() - startedAt,
28295
+ command: `git ${commandArgs.join(" ")}`,
28296
+ error: e?.message || String(e),
28297
+ stdout: truncateValidationOutput(e?.stdout),
27693
28298
  stderr: truncateValidationOutput(e?.stderr)
27694
28299
  };
27695
28300
  }
@@ -27698,10 +28303,10 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27698
28303
  const startedAt = Date.now();
27699
28304
  const entries = [];
27700
28305
  try {
27701
- const { execFile: execFile3 } = await import("child_process");
27702
- const { promisify: promisify6 } = await import("util");
27703
- const execFileAsync3 = promisify6(execFile3);
27704
- const runGit2 = async (cwd, args) => {
28306
+ const { execFile: execFile4 } = await import("child_process");
28307
+ const { promisify: promisify7 } = await import("util");
28308
+ const execFileAsync3 = promisify7(execFile4);
28309
+ const runGit3 = async (cwd, args) => {
27705
28310
  const { stdout } = await execFileAsync3("git", args, {
27706
28311
  cwd,
27707
28312
  encoding: "utf8",
@@ -27712,8 +28317,8 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27712
28317
  return String(stdout || "");
27713
28318
  };
27714
28319
  const verifyRemoteMainContainsCommit = async (submodulePath, commit, branch = "main") => {
27715
- await runGit2(submodulePath, ["-c", "protocol.file.allow=always", "fetch", "origin", `refs/heads/${branch}:refs/remotes/origin/${branch}`]);
27716
- await runGit2(submodulePath, ["merge-base", "--is-ancestor", commit, `refs/remotes/origin/${branch}`]);
28320
+ await runGit3(submodulePath, ["-c", "protocol.file.allow=always", "fetch", "origin", `refs/heads/${branch}:refs/remotes/origin/${branch}`]);
28321
+ await runGit3(submodulePath, ["merge-base", "--is-ancestor", commit, `refs/remotes/origin/${branch}`]);
27717
28322
  };
27718
28323
  const publishCommitToRemoteMain = async (submodulePath, commit, branch = "main") => {
27719
28324
  const refspec = `${commit}:refs/heads/${branch}`;
@@ -27729,21 +28334,21 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27729
28334
  const importCommitFromWorktreeSubmodule = async (submodulePath, worktreeSubmodulePath, commit) => {
27730
28335
  if (!fs11.existsSync(worktreeSubmodulePath)) return false;
27731
28336
  try {
27732
- await runGit2(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
28337
+ await runGit3(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
27733
28338
  } catch {
27734
28339
  return false;
27735
28340
  }
27736
- await runGit2(submodulePath, ["-c", "protocol.file.allow=always", "fetch", worktreeSubmodulePath, commit]);
27737
- await runGit2(submodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
28341
+ await runGit3(submodulePath, ["-c", "protocol.file.allow=always", "fetch", worktreeSubmodulePath, commit]);
28342
+ await runGit3(submodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
27738
28343
  return true;
27739
28344
  };
27740
- const treeOutput = await runGit2(repoRoot, ["ls-tree", "-r", "-z", mergedTree]);
28345
+ const treeOutput = await runGit3(repoRoot, ["ls-tree", "-r", "-z", mergedTree]);
27741
28346
  const gitlinks = treeOutput.split("\0").filter(Boolean).map((record) => {
27742
28347
  const match = /^160000\s+commit\s+([0-9a-f]{40})\t(.+)$/.exec(record);
27743
28348
  return match ? { commit: match[1], path: match[2] } : null;
27744
28349
  }).filter((entry) => !!entry);
27745
28350
  for (const gitlink of gitlinks) {
27746
- const submodulePath = (0, import_path8.resolve)(repoRoot, gitlink.path);
28351
+ const submodulePath = (0, import_path9.resolve)(repoRoot, gitlink.path);
27747
28352
  const entry = {
27748
28353
  path: gitlink.path,
27749
28354
  commit: gitlink.commit,
@@ -27763,7 +28368,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27763
28368
  }
27764
28369
  entry.checkedLocal = true;
27765
28370
  try {
27766
- await runGit2(submodulePath, ["cat-file", "-e", `${gitlink.commit}^{commit}`]);
28371
+ await runGit3(submodulePath, ["cat-file", "-e", `${gitlink.commit}^{commit}`]);
27767
28372
  entry.localReachable = true;
27768
28373
  } catch {
27769
28374
  entry.localReachable = false;
@@ -27771,7 +28376,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27771
28376
  try {
27772
28377
  const imported = await importCommitFromWorktreeSubmodule(
27773
28378
  submodulePath,
27774
- (0, import_path8.resolve)(options.worktreeRoot, gitlink.path),
28379
+ (0, import_path9.resolve)(options.worktreeRoot, gitlink.path),
27775
28380
  gitlink.commit
27776
28381
  );
27777
28382
  if (imported) {
@@ -27787,7 +28392,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
27787
28392
  entry.remote = "origin";
27788
28393
  let remoteUrl = "";
27789
28394
  try {
27790
- remoteUrl = (await runGit2(submodulePath, ["remote", "get-url", "origin"])).trim();
28395
+ remoteUrl = (await runGit3(submodulePath, ["remote", "get-url", "origin"])).trim();
27791
28396
  if (!remoteUrl) throw new Error("origin remote has no URL");
27792
28397
  entry.remoteUrl = remoteUrl;
27793
28398
  } catch {
@@ -27902,9 +28507,9 @@ function buildMeshRefineValidationPlan(mesh, workspace) {
27902
28507
  };
27903
28508
  }
27904
28509
  async function runMeshRefineValidationGate(mesh, workspace) {
27905
- const { execFile: execFile3 } = await import("child_process");
27906
- const { promisify: promisify6 } = await import("util");
27907
- const execFileAsync3 = promisify6(execFile3);
28510
+ const { execFile: execFile4 } = await import("child_process");
28511
+ const { promisify: promisify7 } = await import("util");
28512
+ const execFileAsync3 = promisify7(execFile4);
27908
28513
  const selection = resolveMeshRefineValidationPlan(mesh, workspace);
27909
28514
  const summary = {
27910
28515
  status: "skipped",
@@ -27938,24 +28543,24 @@ async function runMeshRefineValidationGate(mesh, workspace) {
27938
28543
  ...extras
27939
28544
  });
27940
28545
  const isPackageManagerValidation = (candidate) => {
27941
- const command = (0, import_path8.basename)(candidate.command).replace(/\.(?:cmd|exe)$/i, "");
28546
+ const command = (0, import_path9.basename)(candidate.command).replace(/\.(?:cmd|exe)$/i, "");
27942
28547
  return ["npm", "pnpm", "yarn", "bun"].includes(command) && candidate.args.some((arg) => arg === "run" || arg === "test" || arg === "exec");
27943
28548
  };
27944
28549
  const dependenciesLikelyMissing = (cwd) => {
27945
- if (!fs11.existsSync((0, import_path8.join)(cwd, "package.json"))) return false;
27946
- if (fs11.existsSync((0, import_path8.join)(cwd, "node_modules"))) return false;
27947
- 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)));
28550
+ if (!fs11.existsSync((0, import_path9.join)(cwd, "package.json"))) return false;
28551
+ if (fs11.existsSync((0, import_path9.join)(cwd, "node_modules"))) return false;
28552
+ 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)));
27948
28553
  };
27949
28554
  for (const candidate of selection.bootstrapCommands) {
27950
28555
  const startedAt = Date.now();
27951
- const cwd = candidate.cwd ? (0, import_path8.resolve)(workspace, candidate.cwd) : workspace;
28556
+ const cwd = candidate.cwd ? (0, import_path9.resolve)(workspace, candidate.cwd) : workspace;
27952
28557
  const timeout = candidate.timeoutMs || REFINE_VALIDATION_TIMEOUT_MS;
27953
28558
  try {
27954
28559
  const result = await execFileAsync3(candidate.command, candidate.args, {
27955
28560
  cwd,
27956
28561
  encoding: "utf8",
27957
28562
  timeout,
27958
- maxBuffer: REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
28563
+ maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
27959
28564
  env: { ...process.env, CI: process.env.CI || "1", ...candidate.env || {} }
27960
28565
  });
27961
28566
  summary.bootstrapCommandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
@@ -27974,7 +28579,7 @@ async function runMeshRefineValidationGate(mesh, workspace) {
27974
28579
  }
27975
28580
  for (const candidate of selection.commands) {
27976
28581
  const startedAt = Date.now();
27977
- const cwd = candidate.cwd ? (0, import_path8.resolve)(workspace, candidate.cwd) : workspace;
28582
+ const cwd = candidate.cwd ? (0, import_path9.resolve)(workspace, candidate.cwd) : workspace;
27978
28583
  const timeout = candidate.timeoutMs || REFINE_VALIDATION_TIMEOUT_MS;
27979
28584
  if (selection.bootstrapCommands.length === 0 && isPackageManagerValidation(candidate) && dependenciesLikelyMissing(cwd)) {
27980
28585
  summary.commandsRun.push(commandRecord(candidate, cwd, startedAt, {
@@ -27994,7 +28599,7 @@ async function runMeshRefineValidationGate(mesh, workspace) {
27994
28599
  cwd,
27995
28600
  encoding: "utf8",
27996
28601
  timeout,
27997
- maxBuffer: REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
28602
+ maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
27998
28603
  env: { ...process.env, CI: process.env.CI || "1", ...candidate.env || {} }
27999
28604
  });
28000
28605
  summary.commandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
@@ -28019,7 +28624,7 @@ async function runMeshRefineValidationGate(mesh, workspace) {
28019
28624
  return summary;
28020
28625
  }
28021
28626
  function loadYamlModule() {
28022
- return yaml2;
28627
+ return yaml3;
28023
28628
  }
28024
28629
  function getMcpServersKey(format) {
28025
28630
  return format === "hermes_config_yaml" ? "mcp_servers" : "mcpServers";
@@ -28036,13 +28641,13 @@ function serializeMeshCoordinatorMcpConfig(config, format) {
28036
28641
  }
28037
28642
  function resolveHermesUserHome() {
28038
28643
  const explicitHome = process.env.HERMES_HOME?.trim();
28039
- return explicitHome || (0, import_path8.join)((0, import_os3.homedir)(), ".hermes");
28644
+ return explicitHome || (0, import_path9.join)((0, import_os3.homedir)(), ".hermes");
28040
28645
  }
28041
28646
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
28042
28647
  const sourceHome = resolveHermesUserHome();
28043
- const sourceConfigPath = (0, import_path8.join)(sourceHome, "config.yaml");
28648
+ const sourceConfigPath = (0, import_path9.join)(sourceHome, "config.yaml");
28044
28649
  if (!fs11.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
28045
- if ((0, import_path8.resolve)(sourceConfigPath) === (0, import_path8.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
28650
+ if ((0, import_path9.resolve)(sourceConfigPath) === (0, import_path9.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
28046
28651
  const parsed = parseMeshCoordinatorMcpConfig(fs11.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
28047
28652
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
28048
28653
  return { config: baseConfig, sourceHome, sourceConfigPath };
@@ -28076,10 +28681,10 @@ function stripHermesCoordinatorTempModelProviderOverrides(config) {
28076
28681
  return sanitized;
28077
28682
  }
28078
28683
  function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
28079
- if ((0, import_path8.resolve)(sourceHome) === (0, import_path8.resolve)(targetHome)) return;
28684
+ if ((0, import_path9.resolve)(sourceHome) === (0, import_path9.resolve)(targetHome)) return;
28080
28685
  for (const fileName of [".env", "auth.json"]) {
28081
- const sourcePath = (0, import_path8.join)(sourceHome, fileName);
28082
- const targetPath = (0, import_path8.join)(targetHome, fileName);
28686
+ const sourcePath = (0, import_path9.join)(sourceHome, fileName);
28687
+ const targetPath = (0, import_path9.join)(targetHome, fileName);
28083
28688
  if (!fs11.existsSync(sourcePath)) continue;
28084
28689
  try {
28085
28690
  fs11.copyFileSync(sourcePath, targetPath);
@@ -28461,7 +29066,7 @@ var DaemonCommandRouter = class {
28461
29066
  }
28462
29067
  const { resolveWorktreePath: resolveWorktreePath2, listWorktrees: listWorktrees2, removeWorktree: removeWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
28463
29068
  const normalizePath = (value) => {
28464
- const resolved = (0, import_path8.resolve)(value);
29069
+ const resolved = (0, import_path9.resolve)(value);
28465
29070
  try {
28466
29071
  return fs11.realpathSync(resolved);
28467
29072
  } catch {
@@ -28535,10 +29140,10 @@ var DaemonCommandRouter = class {
28535
29140
  if (metadataStatus === "merged_to_main" || metadataStatus === "cleanup_candidate") {
28536
29141
  return { allow: true, status: metadataStatus, source: "node_branch_convergence" };
28537
29142
  }
28538
- const { execFile: execFile3 } = await import("child_process");
28539
- const { promisify: promisify6 } = await import("util");
28540
- const execFileAsync3 = promisify6(execFile3);
28541
- const runGit2 = async (gitArgs, cwd) => {
29143
+ const { execFile: execFile4 } = await import("child_process");
29144
+ const { promisify: promisify7 } = await import("util");
29145
+ const execFileAsync3 = promisify7(execFile4);
29146
+ const runGit3 = async (gitArgs, cwd) => {
28542
29147
  const { stdout } = await execFileAsync3("git", gitArgs, {
28543
29148
  cwd,
28544
29149
  encoding: "utf8",
@@ -28550,14 +29155,14 @@ var DaemonCommandRouter = class {
28550
29155
  };
28551
29156
  let head = "";
28552
29157
  try {
28553
- head = await runGit2(["rev-parse", "HEAD"], args.workspace);
29158
+ head = await runGit3(["rev-parse", "HEAD"], args.workspace);
28554
29159
  } catch (e) {
28555
29160
  return { allow: false, error: `could not resolve worktree HEAD: ${e?.message || e}` };
28556
29161
  }
28557
29162
  if (!head) return { allow: false, error: "worktree HEAD is empty" };
28558
29163
  const candidateRefs = [];
28559
29164
  try {
28560
- const defaultBranch = await runGit2(["branch", "--show-current"], args.repoRoot);
29165
+ const defaultBranch = await runGit3(["branch", "--show-current"], args.repoRoot);
28561
29166
  if (defaultBranch) {
28562
29167
  candidateRefs.push(defaultBranch, `origin/${defaultBranch}`);
28563
29168
  }
@@ -28571,13 +29176,13 @@ var DaemonCommandRouter = class {
28571
29176
  seen.add(ref);
28572
29177
  let commit = "";
28573
29178
  try {
28574
- commit = await runGit2(["rev-parse", "--verify", `${ref}^{commit}`], args.repoRoot);
29179
+ commit = await runGit3(["rev-parse", "--verify", `${ref}^{commit}`], args.repoRoot);
28575
29180
  } catch {
28576
29181
  continue;
28577
29182
  }
28578
29183
  checkedRefs.push(ref);
28579
29184
  try {
28580
- await runGit2(["merge-base", "--is-ancestor", head, commit], args.repoRoot);
29185
+ await runGit3(["merge-base", "--is-ancestor", head, commit], args.repoRoot);
28581
29186
  return { allow: true, status: "merged_to_default_ref", source: "git_merge_base", ref };
28582
29187
  } catch {
28583
29188
  }
@@ -28969,9 +29574,9 @@ var DaemonCommandRouter = class {
28969
29574
  const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => n.id === node.clonedFromNodeId || n.nodeId === node.clonedFromNodeId) : mesh?.nodes.find((n) => !n.isLocalWorktree);
28970
29575
  const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
28971
29576
  if (!repoRoot) return { success: false, error: "Source node repoRoot not found", refineStages };
28972
- const { execFile: execFile3 } = await import("child_process");
28973
- const { promisify: promisify6 } = await import("util");
28974
- const execFileAsync3 = promisify6(execFile3);
29577
+ const { execFile: execFile4 } = await import("child_process");
29578
+ const { promisify: promisify7 } = await import("util");
29579
+ const execFileAsync3 = promisify7(execFile4);
28975
29580
  const resolveStarted = Date.now();
28976
29581
  const { stdout: branchStdout } = await execFileAsync3("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8" });
28977
29582
  const branch = branchStdout.trim();
@@ -29038,7 +29643,8 @@ var DaemonCommandRouter = class {
29038
29643
  equivalent: patchEquivalence.equivalent,
29039
29644
  expectedPatchId: patchEquivalence.expectedPatchId,
29040
29645
  actualPatchId: patchEquivalence.actualPatchId,
29041
- error: patchEquivalence.error
29646
+ error: patchEquivalence.error,
29647
+ actionableHint: patchEquivalence.actionableHint
29042
29648
  });
29043
29649
  if (!patchEquivalence.equivalent) {
29044
29650
  return {
@@ -29197,6 +29803,49 @@ var DaemonCommandRouter = class {
29197
29803
  }
29198
29804
  };
29199
29805
  }
29806
+ const submoduleAlignmentStarted = Date.now();
29807
+ const submoduleAlignment = await alignRefinerySubmodulesAfterMerge(repoRoot, baseHead, "HEAD", {
29808
+ submoduleIgnorePaths: Array.isArray(sourceNode?.policy?.submoduleIgnorePaths) ? sourceNode.policy.submoduleIgnorePaths.filter((value) => typeof value === "string") : void 0
29809
+ });
29810
+ if (submoduleAlignment.status !== "skipped") {
29811
+ recordMeshRefineStage(refineStages, "submodule_alignment", submoduleAlignment.status, submoduleAlignmentStarted, {
29812
+ changedGitlinkPaths: submoduleAlignment.changedGitlinkPaths,
29813
+ outOfSyncPaths: submoduleAlignment.outOfSyncPaths,
29814
+ updatedPaths: submoduleAlignment.updatedPaths,
29815
+ verifiedPaths: submoduleAlignment.verifiedPaths,
29816
+ command: submoduleAlignment.command,
29817
+ error: submoduleAlignment.error
29818
+ });
29819
+ }
29820
+ if (submoduleAlignment.status === "failed") {
29821
+ return {
29822
+ success: false,
29823
+ code: "post_merge_submodule_alignment_failed",
29824
+ error: "Refinery merge completed but post-merge submodule checkout alignment failed; run the reported git submodule update command and re-check base workspace status.",
29825
+ merged: true,
29826
+ branch,
29827
+ into: baseBranch,
29828
+ validationSummary,
29829
+ patchEquivalence,
29830
+ submoduleReachability,
29831
+ submoduleAlignment,
29832
+ mergeResult,
29833
+ refineStages,
29834
+ finalBranchConvergenceState: {
29835
+ branch: baseBranch,
29836
+ mergedBranch: branch,
29837
+ baseBranch,
29838
+ merged: true,
29839
+ removed: false,
29840
+ validation: "passed",
29841
+ patchEquivalence: "passed",
29842
+ submoduleReachability: "passed",
29843
+ submoduleAlignment: "failed",
29844
+ status: "post_merge_alignment_failed",
29845
+ nextStep: submoduleAlignment.command || "Run git submodule update --init --recursive for the reported path(s), then re-check base workspace status."
29846
+ }
29847
+ };
29848
+ }
29200
29849
  const cleanupStarted = Date.now();
29201
29850
  const removeResult = await this.execute("remove_mesh_node", {
29202
29851
  meshId,
@@ -29216,7 +29865,7 @@ var DaemonCommandRouter = class {
29216
29865
  appendLedgerEntry2(meshId, {
29217
29866
  kind: "node_removed",
29218
29867
  nodeId,
29219
- payload: { refined: true, mergedBranch: branch, into: baseBranch, validationSummary, patchEquivalence, submoduleReachability }
29868
+ payload: { refined: true, mergedBranch: branch, into: baseBranch, validationSummary, patchEquivalence, submoduleReachability, submoduleAlignment }
29220
29869
  });
29221
29870
  recordMeshRefineStage(refineStages, "ledger", "passed", ledgerStarted);
29222
29871
  } catch (e) {
@@ -29231,6 +29880,7 @@ var DaemonCommandRouter = class {
29231
29880
  removed: removeResult?.success !== false,
29232
29881
  validation: "passed",
29233
29882
  patchEquivalence: "passed",
29883
+ submoduleAlignment: submoduleAlignment.status,
29234
29884
  status: removeResult?.success === false ? "merged_cleanup_failed" : "merged"
29235
29885
  };
29236
29886
  if (removeResult?.success === false) {
@@ -29245,6 +29895,7 @@ var DaemonCommandRouter = class {
29245
29895
  validationSummary,
29246
29896
  patchEquivalence,
29247
29897
  submoduleReachability,
29898
+ submoduleAlignment,
29248
29899
  mergeResult,
29249
29900
  refineStages,
29250
29901
  ...ledgerError ? { ledgerError } : {},
@@ -29260,6 +29911,7 @@ var DaemonCommandRouter = class {
29260
29911
  validationSummary,
29261
29912
  patchEquivalence,
29262
29913
  submoduleReachability,
29914
+ submoduleAlignment,
29263
29915
  mergeResult,
29264
29916
  refineStages,
29265
29917
  ...ledgerError ? { ledgerError } : {},
@@ -30342,6 +30994,12 @@ var DaemonCommandRouter = class {
30342
30994
  success: true,
30343
30995
  schema: MESH_REFINE_CONFIG_SCHEMA,
30344
30996
  locations: MESH_REFINE_CONFIG_LOCATIONS,
30997
+ worktreeBootstrap: {
30998
+ schema: MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA,
30999
+ locations: MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS,
31000
+ sourceOfTruth: "repo worktree bootstrap config",
31001
+ runBehavior: "When present and enabled, clone_mesh_node runs commands after submodule initialization and records status on the worktree node."
31002
+ },
30345
31003
  sourceOfTruth: "repo mesh/refine config",
30346
31004
  heuristicRole: "suggestions_only_not_execution_path"
30347
31005
  };
@@ -30536,8 +31194,8 @@ var DaemonCommandRouter = class {
30536
31194
  const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
30537
31195
  if (initSubmodules) {
30538
31196
  try {
30539
- const { runGit: runGit2 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
30540
- await runGit2(
31197
+ const { runGit: runGit3 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
31198
+ await runGit3(
30541
31199
  { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
30542
31200
  ["submodule", "update", "--init", "--recursive"],
30543
31201
  { timeoutMs: 12e4 }
@@ -30546,12 +31204,35 @@ var DaemonCommandRouter = class {
30546
31204
  console.warn("[mesh] Submodule init failed for worktree:", subErr.message);
30547
31205
  }
30548
31206
  }
31207
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
31208
+ node.worktreeBootstrap = bootstrapState;
31209
+ if (!meshRecord.inline) {
31210
+ try {
31211
+ const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
31212
+ updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState });
31213
+ this.invalidateAggregateMeshStatus(meshId);
31214
+ } catch {
31215
+ }
31216
+ }
30549
31217
  try {
30550
31218
  const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
30551
31219
  appendLedgerEntry2(meshId, {
30552
31220
  kind: "node_cloned",
30553
31221
  nodeId: node.id,
30554
- payload: { sourceNodeId, branch: result.branch, worktreePath: result.worktreePath, submodulesInitialized: initSubmodules }
31222
+ payload: {
31223
+ sourceNodeId,
31224
+ branch: result.branch,
31225
+ worktreePath: result.worktreePath,
31226
+ submodulesInitialized: initSubmodules,
31227
+ worktreeBootstrap: {
31228
+ status: bootstrapState.status,
31229
+ required: bootstrapState.required,
31230
+ configSource: bootstrapState.configSource,
31231
+ configSourceType: bootstrapState.configSourceType,
31232
+ lastCommand: bootstrapState.lastCommand,
31233
+ exitCode: bootstrapState.exitCode
31234
+ }
31235
+ }
30555
31236
  });
30556
31237
  } catch {
30557
31238
  }
@@ -30559,7 +31240,8 @@ var DaemonCommandRouter = class {
30559
31240
  success: true,
30560
31241
  node,
30561
31242
  worktreePath: result.worktreePath,
30562
- branch: result.branch
31243
+ branch: result.branch,
31244
+ worktreeBootstrap: bootstrapState
30563
31245
  };
30564
31246
  } catch (e) {
30565
31247
  return { success: false, error: e.message };
@@ -30787,7 +31469,7 @@ ${block2}`);
30787
31469
  workspace
30788
31470
  };
30789
31471
  }
30790
- const { existsSync: existsSync26, readFileSync: readFileSync19, writeFileSync: writeFileSync14, copyFileSync: copyFileSync4, mkdirSync: mkdirSync18 } = await import("fs");
31472
+ const { existsSync: existsSync28, readFileSync: readFileSync21, writeFileSync: writeFileSync14, copyFileSync: copyFileSync4, mkdirSync: mkdirSync18 } = await import("fs");
30791
31473
  const { dirname: dirname9 } = await import("path");
30792
31474
  const mcpConfigPath = coordinatorSetup.configPath;
30793
31475
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -30830,14 +31512,14 @@ ${block2}`);
30830
31512
  if (hermesManualFallback) return returnManualFallback(message);
30831
31513
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
30832
31514
  }
30833
- const hadExistingMcpConfig = existsSync26(mcpConfigPath);
31515
+ const hadExistingMcpConfig = existsSync28(mcpConfigPath);
30834
31516
  let existingMcpConfig = hermesBaseConfig?.config || {};
30835
31517
  if (hermesBaseConfig) {
30836
31518
  copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname9(mcpConfigPath));
30837
31519
  }
30838
31520
  if (hadExistingMcpConfig) {
30839
31521
  try {
30840
- const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync19(mcpConfigPath, "utf-8"), configFormat);
31522
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync21(mcpConfigPath, "utf-8"), configFormat);
30841
31523
  const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
30842
31524
  existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
30843
31525
  copyFileSync4(mcpConfigPath, mcpConfigPath + ".backup");
@@ -30949,6 +31631,7 @@ ${block2}`);
30949
31631
  const queueSummary = getMeshQueueStats2(meshId);
30950
31632
  const { readLedgerEntries: readLedgerEntries2, getLedgerSummary: getLedgerSummary2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
30951
31633
  const ledgerEntries = readLedgerEntries2(meshId, { tail: 20 });
31634
+ const asyncRefineLedgerEntries = readLedgerEntries2(meshId, { tail: 100 });
30952
31635
  const ledgerSummary = getLedgerSummary2(meshId);
30953
31636
  const sessionHostRecords = this.deps.sessionHostControl?.listSessions ? await this.deps.sessionHostControl.listSessions().catch(() => []) : [];
30954
31637
  const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
@@ -31211,6 +31894,20 @@ ${block2}`);
31211
31894
  nodeStatuses.push(status);
31212
31895
  }
31213
31896
  const pendingCoordinatorEvents = drainPendingMeshCoordinatorEvents(meshId);
31897
+ const previewFreshness = (() => {
31898
+ const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs11.existsSync(candidate));
31899
+ return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
31900
+ })();
31901
+ const asyncRefineJobs = buildMeshAsyncRefineJobs({
31902
+ meshId,
31903
+ ledgerEntries: asyncRefineLedgerEntries,
31904
+ pendingEvents: pendingCoordinatorEvents
31905
+ });
31906
+ const historicalSessions = buildHistoricalMeshSessions({
31907
+ meshId,
31908
+ nodes: mesh.nodes || [],
31909
+ liveSessionRecords: liveMeshSessions
31910
+ });
31214
31911
  const statusResult = {
31215
31912
  success: true,
31216
31913
  meshId: mesh.id,
@@ -31242,12 +31939,15 @@ ${block2}`);
31242
31939
  partialNodeFailures: effectiveDirectTruth.unavailableNodeIds
31243
31940
  }
31244
31941
  } : {},
31245
- historicalEvidenceOnly: ["recoveryHints", "ledger.summary", "queue.summary"]
31942
+ historicalEvidenceOnly: ["recoveryHints", "ledger.summary", "queue.summary", "historicalSessions"]
31246
31943
  },
31247
31944
  branchConvergenceSummary: summarizeInlineMeshBranchConvergence(nodeStatuses),
31945
+ ...previewFreshness ? { previewFreshness, deployFreshness: previewFreshness } : {},
31248
31946
  nodes: nodeStatuses,
31249
31947
  queue: { tasks: queue, summary: queueSummary },
31250
31948
  ledger: { entries: ledgerEntries, summary: ledgerSummary },
31949
+ ...asyncRefineJobs.length > 0 ? { asyncRefineJobs } : {},
31950
+ ...historicalSessions ? { historicalSessions } : {},
31251
31951
  ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {}
31252
31952
  };
31253
31953
  const { pendingCoordinatorEvents: _pendingCoordinatorEvents, ...cacheableStatusResult } = statusResult;
@@ -31898,7 +32598,7 @@ var ProviderStreamAdapter = class {
31898
32598
  const beforeCount = this.messageCount(before);
31899
32599
  const beforeSignature = this.lastMessageSignature(before);
31900
32600
  for (let attempt = 0; attempt < 12; attempt += 1) {
31901
- await new Promise((resolve16) => setTimeout(resolve16, 250));
32601
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
31902
32602
  let state;
31903
32603
  try {
31904
32604
  state = await this.readChat(evaluate);
@@ -31920,7 +32620,7 @@ var ProviderStreamAdapter = class {
31920
32620
  if (this.messageCount(first) > 0 || this.lastMessageSignature(first)) {
31921
32621
  return first;
31922
32622
  }
31923
- await new Promise((resolve16) => setTimeout(resolve16, 150));
32623
+ await new Promise((resolve17) => setTimeout(resolve17, 150));
31924
32624
  const second = await this.readChat(evaluate);
31925
32625
  return this.messageCount(second) >= this.messageCount(first) ? second : first;
31926
32626
  }
@@ -32071,7 +32771,7 @@ var ProviderStreamAdapter = class {
32071
32771
  if (typeof data.error === "string" && data.error.trim()) return false;
32072
32772
  }
32073
32773
  for (let attempt = 0; attempt < 6; attempt += 1) {
32074
- await new Promise((resolve16) => setTimeout(resolve16, 250));
32774
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
32075
32775
  const state = await this.readChat(evaluate);
32076
32776
  const title = this.getStateTitle(state);
32077
32777
  if (this.titlesMatch(title, sessionId)) return true;
@@ -32999,13 +33699,13 @@ var VersionArchive = class {
32999
33699
  }
33000
33700
  };
33001
33701
  async function runCommand(cmd, timeout = 1e4) {
33002
- return new Promise((resolve16) => {
33702
+ return new Promise((resolve17) => {
33003
33703
  (0, import_child_process9.exec)(cmd, {
33004
33704
  encoding: "utf-8",
33005
33705
  timeout
33006
33706
  }, (error, stdout) => {
33007
- if (error) return resolve16(null);
33008
- resolve16(stdout.trim());
33707
+ if (error) return resolve17(null);
33708
+ resolve17(stdout.trim());
33009
33709
  });
33010
33710
  });
33011
33711
  }
@@ -34694,7 +35394,7 @@ function getCliTargetBundle(ctx, type, instanceId) {
34694
35394
  return { target, instance, adapter };
34695
35395
  }
34696
35396
  function sleep2(ms) {
34697
- return new Promise((resolve16) => setTimeout(resolve16, ms));
35397
+ return new Promise((resolve17) => setTimeout(resolve17, ms));
34698
35398
  }
34699
35399
  async function waitForCliReady(ctx, type, instanceId, timeoutMs) {
34700
35400
  const startedAt = Date.now();
@@ -36949,15 +37649,15 @@ var DevServer = class _DevServer {
36949
37649
  this.json(res, 500, { error: e.message });
36950
37650
  }
36951
37651
  });
36952
- return new Promise((resolve16, reject) => {
37652
+ return new Promise((resolve17, reject) => {
36953
37653
  this.server.listen(port, "127.0.0.1", () => {
36954
37654
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
36955
- resolve16();
37655
+ resolve17();
36956
37656
  });
36957
37657
  this.server.on("error", (e) => {
36958
37658
  if (e.code === "EADDRINUSE") {
36959
37659
  this.log(`Port ${port} in use, skipping dev server`);
36960
- resolve16();
37660
+ resolve17();
36961
37661
  } else {
36962
37662
  reject(e);
36963
37663
  }
@@ -37039,20 +37739,20 @@ var DevServer = class _DevServer {
37039
37739
  child.stderr?.on("data", (d) => {
37040
37740
  stderr += d.toString().slice(0, 2e3);
37041
37741
  });
37042
- await new Promise((resolve16) => {
37742
+ await new Promise((resolve17) => {
37043
37743
  const timer = setTimeout(() => {
37044
37744
  child.kill();
37045
- resolve16();
37745
+ resolve17();
37046
37746
  }, 3e3);
37047
37747
  child.on("exit", () => {
37048
37748
  clearTimeout(timer);
37049
- resolve16();
37749
+ resolve17();
37050
37750
  });
37051
37751
  child.stdout?.once("data", () => {
37052
37752
  setTimeout(() => {
37053
37753
  child.kill();
37054
37754
  clearTimeout(timer);
37055
- resolve16();
37755
+ resolve17();
37056
37756
  }, 500);
37057
37757
  });
37058
37758
  });
@@ -37555,14 +38255,14 @@ var DevServer = class _DevServer {
37555
38255
  child.stderr?.on("data", (d) => {
37556
38256
  stderr += d.toString();
37557
38257
  });
37558
- await new Promise((resolve16) => {
38258
+ await new Promise((resolve17) => {
37559
38259
  const timer = setTimeout(() => {
37560
38260
  child.kill();
37561
- resolve16();
38261
+ resolve17();
37562
38262
  }, timeout);
37563
38263
  child.on("exit", () => {
37564
38264
  clearTimeout(timer);
37565
- resolve16();
38265
+ resolve17();
37566
38266
  });
37567
38267
  });
37568
38268
  const elapsed = Date.now() - start;
@@ -38232,14 +38932,14 @@ data: ${JSON.stringify(msg.data)}
38232
38932
  res.end(JSON.stringify(data, null, 2));
38233
38933
  }
38234
38934
  async readBody(req) {
38235
- return new Promise((resolve16) => {
38935
+ return new Promise((resolve17) => {
38236
38936
  let body = "";
38237
38937
  req.on("data", (chunk) => body += chunk);
38238
38938
  req.on("end", () => {
38239
38939
  try {
38240
- resolve16(JSON.parse(body));
38940
+ resolve17(JSON.parse(body));
38241
38941
  } catch {
38242
- resolve16({});
38942
+ resolve17({});
38243
38943
  }
38244
38944
  });
38245
38945
  });
@@ -38777,7 +39477,7 @@ async function waitForReady(endpoint, timeoutMs = STARTUP_TIMEOUT_MS, requiredRe
38777
39477
  const deadline = Date.now() + timeoutMs;
38778
39478
  while (Date.now() < deadline) {
38779
39479
  if (await canConnect(endpoint, requiredRequestTypes)) return;
38780
- await new Promise((resolve16) => setTimeout(resolve16, STARTUP_POLL_MS));
39480
+ await new Promise((resolve17) => setTimeout(resolve17, STARTUP_POLL_MS));
38781
39481
  }
38782
39482
  throw new Error(`Session host did not become ready within ${timeoutMs}ms`);
38783
39483
  }
@@ -38957,10 +39657,10 @@ async function installExtension(ide, extension) {
38957
39657
  const buffer = Buffer.from(await res.arrayBuffer());
38958
39658
  const fs17 = await import("fs");
38959
39659
  fs17.writeFileSync(vsixPath, buffer);
38960
- return new Promise((resolve16) => {
39660
+ return new Promise((resolve17) => {
38961
39661
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
38962
39662
  (0, import_child_process10.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
38963
- resolve16({
39663
+ resolve17({
38964
39664
  extensionId: extension.id,
38965
39665
  marketplaceId: extension.marketplaceId,
38966
39666
  success: !error,
@@ -38973,11 +39673,11 @@ async function installExtension(ide, extension) {
38973
39673
  } catch (e) {
38974
39674
  }
38975
39675
  }
38976
- return new Promise((resolve16) => {
39676
+ return new Promise((resolve17) => {
38977
39677
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
38978
39678
  (0, import_child_process10.exec)(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
38979
39679
  if (error) {
38980
- resolve16({
39680
+ resolve17({
38981
39681
  extensionId: extension.id,
38982
39682
  marketplaceId: extension.marketplaceId,
38983
39683
  success: false,
@@ -38985,7 +39685,7 @@ async function installExtension(ide, extension) {
38985
39685
  error: stderr || error.message
38986
39686
  });
38987
39687
  } else {
38988
- resolve16({
39688
+ resolve17({
38989
39689
  extensionId: extension.id,
38990
39690
  marketplaceId: extension.marketplaceId,
38991
39691
  success: true,
@@ -39360,6 +40060,8 @@ async function shutdownDaemonComponents(components) {
39360
40060
  MAX_LEDGER_SLICE_LIMIT,
39361
40061
  MESH_REFINE_CONFIG_LOCATIONS,
39362
40062
  MESH_REFINE_CONFIG_SCHEMA,
40063
+ MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS,
40064
+ MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA,
39363
40065
  MIN_GIT_WORKSPACE_POLL_INTERVAL_MS,
39364
40066
  MIN_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS,
39365
40067
  MIN_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS,
@@ -39380,10 +40082,12 @@ async function shutdownDaemonComponents(components) {
39380
40082
  buildChatMessage,
39381
40083
  buildChatMessageSignature,
39382
40084
  buildChatTailDeliverySignature,
40085
+ buildCompactStaleDirectWorkSummary,
39383
40086
  buildCoordinatorSystemPrompt,
39384
40087
  buildMachineInfo,
39385
40088
  buildMeshActiveWork,
39386
40089
  buildMeshActiveWorkSummary,
40090
+ buildMeshAsyncRefineJobs,
39387
40091
  buildMeshHostRequiredFailure,
39388
40092
  buildMeshLedgerReconciliationEvidence,
39389
40093
  buildMeshLedgerReplicaEvidence,
@@ -39492,6 +40196,7 @@ async function shutdownDaemonComponents(components) {
39492
40196
  listWorktrees,
39493
40197
  loadConfig,
39494
40198
  loadMeshRefineConfig,
40199
+ loadMeshWorktreeBootstrapConfig,
39495
40200
  loadState,
39496
40201
  logCommand,
39497
40202
  markSetupComplete,
@@ -39543,6 +40248,7 @@ async function shutdownDaemonComponents(components) {
39543
40248
  resolveWorktreePath,
39544
40249
  runAsyncBatch,
39545
40250
  runGit,
40251
+ runMeshWorktreeBootstrap,
39546
40252
  saveConfig,
39547
40253
  saveState,
39548
40254
  setDebugRuntimeConfig,
@@ -39564,6 +40270,7 @@ async function shutdownDaemonComponents(components) {
39564
40270
  updateTaskStatus,
39565
40271
  upsertSavedProviderSession,
39566
40272
  validateMeshRefineConfig,
39567
- validateMeshTaskModeRequest
40273
+ validateMeshTaskModeRequest,
40274
+ validateMeshWorktreeBootstrapConfig
39568
40275
  });
39569
40276
  //# sourceMappingURL=index.js.map