adhdev 0.9.82-rc.4 → 0.9.82-rc.40

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
@@ -264,8 +264,14 @@ async function getGitRepoStatus(workspace, options = {}) {
264
264
  const includeSubmodules = options.includeSubmodules !== false;
265
265
  try {
266
266
  const repo = await resolveGitRepository(workspace, options);
267
- const statusOutput = await runGit(repo, ["status", "--porcelain=v2", "--branch"], options);
268
- const parsed = parsePorcelainV2Status(statusOutput.stdout);
267
+ let parsed = await readPorcelainStatus(repo, options);
268
+ let upstreamProbe = getInitialUpstreamProbe(parsed);
269
+ if (options.refreshUpstream) {
270
+ upstreamProbe = await refreshTrackedUpstream(repo, parsed, options);
271
+ if (upstreamProbe.upstreamStatus === "fresh") {
272
+ parsed = await readPorcelainStatus(repo, options);
273
+ }
274
+ }
269
275
  const head = await readHead(repo, options);
270
276
  const stashCount = await readStashCount(repo, options);
271
277
  let submodules;
@@ -280,6 +286,9 @@ async function getGitRepoStatus(workspace, options = {}) {
280
286
  headCommit: head.commit,
281
287
  headMessage: head.message,
282
288
  upstream: parsed.upstream,
289
+ upstreamStatus: parsed.upstream ? upstreamProbe.upstreamStatus : "no_upstream",
290
+ upstreamFetchedAt: upstreamProbe.upstreamFetchedAt,
291
+ upstreamFetchError: upstreamProbe.upstreamFetchError,
283
292
  ahead: parsed.ahead,
284
293
  behind: parsed.behind,
285
294
  staged: parsed.staged,
@@ -304,6 +313,60 @@ async function getGitRepoStatus(workspace, options = {}) {
304
313
  );
305
314
  }
306
315
  }
316
+ async function readPorcelainStatus(repo, options) {
317
+ const statusOutput = await runGit(repo, ["status", "--porcelain=v2", "--branch"], options);
318
+ return parsePorcelainV2Status(statusOutput.stdout);
319
+ }
320
+ function getInitialUpstreamProbe(parsed) {
321
+ return {
322
+ upstreamStatus: parsed.upstream ? "unchecked" : "no_upstream"
323
+ };
324
+ }
325
+ async function refreshTrackedUpstream(repo, parsed, options) {
326
+ if (!parsed.upstream || !parsed.branch) {
327
+ return { upstreamStatus: "no_upstream" };
328
+ }
329
+ const remoteName = await readBranchRemote(repo, parsed.branch, options) ?? inferRemoteName(parsed.upstream);
330
+ if (!remoteName) {
331
+ return {
332
+ upstreamStatus: "stale",
333
+ upstreamFetchError: `Unable to resolve remote for upstream '${parsed.upstream}'`
334
+ };
335
+ }
336
+ try {
337
+ await runGit(repo, ["fetch", "--quiet", "--prune", "--no-tags", remoteName], options);
338
+ return {
339
+ upstreamStatus: "fresh",
340
+ upstreamFetchedAt: Date.now()
341
+ };
342
+ } catch (error48) {
343
+ return {
344
+ upstreamStatus: "stale",
345
+ upstreamFetchError: formatGitError(error48)
346
+ };
347
+ }
348
+ }
349
+ async function readBranchRemote(repo, branch, options) {
350
+ try {
351
+ const result = await runGit(repo, ["config", "--get", `branch.${branch}.remote`], options);
352
+ return result.stdout.trim() || null;
353
+ } catch {
354
+ return null;
355
+ }
356
+ }
357
+ function inferRemoteName(upstream) {
358
+ const [remoteName] = upstream.split("/");
359
+ return remoteName?.trim() || null;
360
+ }
361
+ function formatGitError(error48) {
362
+ if (error48 instanceof GitCommandError) {
363
+ return error48.stderr || error48.message;
364
+ }
365
+ if (error48 instanceof Error) {
366
+ return error48.message;
367
+ }
368
+ return String(error48);
369
+ }
307
370
  function parsePorcelainV2Status(output) {
308
371
  const parsed = {
309
372
  branch: null,
@@ -398,6 +461,7 @@ function emptyStatus(workspace, lastCheckedAt, error48) {
398
461
  headCommit: null,
399
462
  headMessage: null,
400
463
  upstream: null,
464
+ upstreamStatus: "unavailable",
401
465
  ahead: 0,
402
466
  behind: 0,
403
467
  staged: 0,
@@ -690,6 +754,9 @@ function createGitCompactSummary(status, diffSummary) {
690
754
  isGitRepo: status.isGitRepo,
691
755
  repoRoot: status.repoRoot,
692
756
  branch: status.branch,
757
+ upstreamStatus: status.upstreamStatus,
758
+ upstreamFetchedAt: status.upstreamFetchedAt,
759
+ upstreamFetchError: status.upstreamFetchError,
693
760
  dirty: status.staged > 0 || status.modified > 0 || status.untracked > 0 || status.deleted > 0 || status.renamed > 0 || conflictCount > 0 || changedFiles > 0,
694
761
  changedFiles,
695
762
  ahead: status.ahead,
@@ -1017,7 +1084,7 @@ function serviceNotImplemented(command) {
1017
1084
  }
1018
1085
  function createDefaultGitCommandServices() {
1019
1086
  return {
1020
- getStatus: ({ workspace }) => getGitRepoStatus(workspace),
1087
+ getStatus: ({ workspace, refreshUpstream }) => getGitRepoStatus(workspace, { refreshUpstream }),
1021
1088
  getDiffSummary: ({ workspace }) => getGitDiffSummary(workspace),
1022
1089
  getDiffFile: ({ workspace, path: filePath }) => getGitFileDiff(workspace, filePath),
1023
1090
  createSnapshot: ({ workspace, reason, sessionId, turnId }) => defaultSnapshotStore.create({
@@ -1102,7 +1169,7 @@ async function handleGitCommand(command, args, services = defaultGitCommandServi
1102
1169
  switch (command) {
1103
1170
  case "git_status": {
1104
1171
  if (!services.getStatus) return serviceNotImplemented(command);
1105
- const status = await runService(() => services.getStatus({ workspace }));
1172
+ const status = await runService(() => services.getStatus({ workspace, refreshUpstream: optionalBoolean(args?.refreshUpstream) }));
1106
1173
  return "success" in status ? status : { success: true, status };
1107
1174
  }
1108
1175
  case "git_diff_summary": {
@@ -3223,6 +3290,36 @@ function getQueuePath(meshId) {
3223
3290
  const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
3224
3291
  return (0, import_path4.join)(getLedgerDir(), `${safe}.queue.json`);
3225
3292
  }
3293
+ function getLockPath(meshId) {
3294
+ const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
3295
+ return (0, import_path4.join)(getLedgerDir(), `${safe}.queue.lock`);
3296
+ }
3297
+ function withQueueLock(meshId, fn) {
3298
+ const lockPath = getLockPath(meshId);
3299
+ let fd = -1;
3300
+ for (let i = 0; i < 10; i++) {
3301
+ try {
3302
+ fd = (0, import_fs4.openSync)(lockPath, "wx");
3303
+ break;
3304
+ } catch {
3305
+ const deadline = Date.now() + 30;
3306
+ while (Date.now() < deadline) {
3307
+ }
3308
+ }
3309
+ }
3310
+ try {
3311
+ return fn();
3312
+ } finally {
3313
+ if (fd !== -1) try {
3314
+ (0, import_fs4.closeSync)(fd);
3315
+ } catch {
3316
+ }
3317
+ try {
3318
+ (0, import_fs4.unlinkSync)(lockPath);
3319
+ } catch {
3320
+ }
3321
+ }
3322
+ }
3226
3323
  function readQueue(meshId) {
3227
3324
  const path35 = getQueuePath(meshId);
3228
3325
  if (!(0, import_fs4.existsSync)(path35)) return [];
@@ -3238,20 +3335,22 @@ function writeQueue(meshId, queue) {
3238
3335
  (0, import_fs4.writeFileSync)(path35, JSON.stringify(queue, null, 2), "utf-8");
3239
3336
  }
3240
3337
  function enqueueTask(meshId, message, opts) {
3241
- const queue = readQueue(meshId);
3242
- const entry = {
3243
- id: (0, import_crypto5.randomUUID)(),
3244
- meshId,
3245
- message,
3246
- status: "pending",
3247
- targetNodeId: opts?.targetNodeId,
3248
- targetSessionId: opts?.targetSessionId,
3249
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3250
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3251
- };
3252
- queue.push(entry);
3253
- writeQueue(meshId, queue);
3254
- return entry;
3338
+ return withQueueLock(meshId, () => {
3339
+ const queue = readQueue(meshId);
3340
+ const entry = {
3341
+ id: (0, import_crypto5.randomUUID)(),
3342
+ meshId,
3343
+ message,
3344
+ status: "pending",
3345
+ targetNodeId: opts?.targetNodeId,
3346
+ targetSessionId: opts?.targetSessionId,
3347
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3348
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3349
+ };
3350
+ queue.push(entry);
3351
+ writeQueue(meshId, queue);
3352
+ return entry;
3353
+ });
3255
3354
  }
3256
3355
  function getQueue(meshId, opts) {
3257
3356
  let queue = readQueue(meshId);
@@ -3262,100 +3361,111 @@ function getQueue(meshId, opts) {
3262
3361
  return queue;
3263
3362
  }
3264
3363
  function claimNextTask(meshId, nodeId, sessionId) {
3265
- const queue = readQueue(meshId);
3266
- const hasActiveAssignment = queue.some((q) => q.status === "assigned" && (q.assignedSessionId === sessionId || q.assignedNodeId === nodeId));
3267
- if (hasActiveAssignment) return null;
3268
- let targetIdx = queue.findIndex((q) => q.status === "pending" && q.targetSessionId === sessionId);
3269
- if (targetIdx === -1) {
3270
- targetIdx = queue.findIndex((q) => q.status === "pending" && q.targetNodeId === nodeId && !q.targetSessionId);
3271
- }
3272
- if (targetIdx === -1) {
3273
- targetIdx = queue.findIndex((q) => q.status === "pending" && !q.targetNodeId && !q.targetSessionId);
3274
- }
3275
- if (targetIdx === -1) return null;
3276
- const entry = queue[targetIdx];
3277
- entry.status = "assigned";
3278
- entry.assignedNodeId = nodeId;
3279
- entry.assignedSessionId = sessionId;
3280
- entry.dispatchTimestamp = (/* @__PURE__ */ new Date()).toISOString();
3281
- entry.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3282
- writeQueue(meshId, queue);
3283
- return entry;
3364
+ return withQueueLock(meshId, () => {
3365
+ const queue = readQueue(meshId);
3366
+ const hasActiveAssignment = queue.some((q) => q.status === "assigned" && (q.assignedSessionId === sessionId || q.assignedNodeId === nodeId));
3367
+ if (hasActiveAssignment) return null;
3368
+ let targetIdx = queue.findIndex((q) => q.status === "pending" && q.targetSessionId === sessionId);
3369
+ if (targetIdx === -1) {
3370
+ targetIdx = queue.findIndex((q) => q.status === "pending" && q.targetNodeId === nodeId && !q.targetSessionId);
3371
+ }
3372
+ if (targetIdx === -1) {
3373
+ targetIdx = queue.findIndex((q) => q.status === "pending" && !q.targetNodeId && !q.targetSessionId);
3374
+ }
3375
+ if (targetIdx === -1) return null;
3376
+ const entry = queue[targetIdx];
3377
+ entry.status = "assigned";
3378
+ entry.assignedNodeId = nodeId;
3379
+ entry.assignedSessionId = sessionId;
3380
+ entry.dispatchTimestamp = (/* @__PURE__ */ new Date()).toISOString();
3381
+ entry.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3382
+ writeQueue(meshId, queue);
3383
+ return entry;
3384
+ });
3284
3385
  }
3285
3386
  function updateTaskStatus(meshId, taskId, status) {
3286
- const queue = readQueue(meshId);
3287
- const idx = queue.findIndex((q) => q.id === taskId);
3288
- if (idx === -1) return null;
3289
- queue[idx].status = status;
3290
- queue[idx].updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3291
- writeQueue(meshId, queue);
3292
- return queue[idx];
3387
+ return withQueueLock(meshId, () => {
3388
+ const queue = readQueue(meshId);
3389
+ const idx = queue.findIndex((q) => q.id === taskId);
3390
+ if (idx === -1) return null;
3391
+ queue[idx].status = status;
3392
+ queue[idx].updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3393
+ writeQueue(meshId, queue);
3394
+ return queue[idx];
3395
+ });
3293
3396
  }
3294
3397
  function recordTaskAutoLaunch(meshId, taskId, autoLaunch) {
3295
- const queue = readQueue(meshId);
3296
- const idx = queue.findIndex((q) => q.id === taskId);
3297
- if (idx === -1) return null;
3298
- const now = (/* @__PURE__ */ new Date()).toISOString();
3299
- queue[idx].autoLaunch = {
3300
- ...autoLaunch,
3301
- updatedAt: now
3302
- };
3303
- queue[idx].updatedAt = now;
3304
- writeQueue(meshId, queue);
3305
- return queue[idx];
3398
+ return withQueueLock(meshId, () => {
3399
+ const queue = readQueue(meshId);
3400
+ const idx = queue.findIndex((q) => q.id === taskId);
3401
+ if (idx === -1) return null;
3402
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3403
+ queue[idx].autoLaunch = { ...autoLaunch, updatedAt: now };
3404
+ queue[idx].updatedAt = now;
3405
+ writeQueue(meshId, queue);
3406
+ return queue[idx];
3407
+ });
3306
3408
  }
3307
3409
  function cancelTask(meshId, taskId, opts) {
3308
- const queue = readQueue(meshId);
3309
- const idx = queue.findIndex((q) => q.id === taskId);
3310
- if (idx === -1) return null;
3311
- const now = (/* @__PURE__ */ new Date()).toISOString();
3312
- queue[idx].status = "cancelled";
3313
- queue[idx].updatedAt = now;
3314
- queue[idx].cancelledAt = now;
3315
- if (opts?.reason) queue[idx].cancelReason = opts.reason;
3316
- writeQueue(meshId, queue);
3317
- return queue[idx];
3410
+ return withQueueLock(meshId, () => {
3411
+ const queue = readQueue(meshId);
3412
+ const idx = queue.findIndex((q) => q.id === taskId);
3413
+ if (idx === -1) return null;
3414
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3415
+ queue[idx].status = "cancelled";
3416
+ queue[idx].updatedAt = now;
3417
+ queue[idx].cancelledAt = now;
3418
+ if (opts?.reason) queue[idx].cancelReason = opts.reason;
3419
+ writeQueue(meshId, queue);
3420
+ return queue[idx];
3421
+ });
3318
3422
  }
3319
3423
  function requeueTask(meshId, taskId, opts) {
3320
- const queue = readQueue(meshId);
3321
- const idx = queue.findIndex((q) => q.id === taskId);
3322
- if (idx === -1) return null;
3323
- const entry = queue[idx];
3324
- const now = (/* @__PURE__ */ new Date()).toISOString();
3325
- entry.status = "pending";
3326
- delete entry.assignedNodeId;
3327
- delete entry.assignedSessionId;
3328
- delete entry.cancelledAt;
3329
- delete entry.cancelReason;
3330
- if (opts?.clearTargetNode) delete entry.targetNodeId;
3331
- if (typeof opts?.targetNodeId === "string") entry.targetNodeId = opts.targetNodeId;
3332
- if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
3333
- if (typeof opts?.targetSessionId === "string") entry.targetSessionId = opts.targetSessionId;
3334
- entry.updatedAt = now;
3335
- entry.requeuedAt = now;
3336
- entry.requeueCount = (entry.requeueCount || 0) + 1;
3337
- if (opts?.reason) entry.requeueReason = opts.reason;
3338
- writeQueue(meshId, queue);
3339
- return entry;
3340
- }
3341
- function updateSessionTaskStatus(meshId, sessionId, status) {
3342
- const queue = readQueue(meshId);
3343
- let bestIdx = -1;
3344
- let bestTime = 0;
3345
- for (let i = queue.length - 1; i >= 0; i--) {
3346
- if (queue[i].assignedSessionId === sessionId && queue[i].status === "assigned") {
3424
+ return withQueueLock(meshId, () => {
3425
+ const queue = readQueue(meshId);
3426
+ const idx = queue.findIndex((q) => q.id === taskId);
3427
+ if (idx === -1) return null;
3428
+ const entry = queue[idx];
3429
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3430
+ entry.status = "pending";
3431
+ delete entry.assignedNodeId;
3432
+ delete entry.assignedSessionId;
3433
+ delete entry.cancelledAt;
3434
+ delete entry.cancelReason;
3435
+ if (opts?.clearTargetNode) delete entry.targetNodeId;
3436
+ if (typeof opts?.targetNodeId === "string") entry.targetNodeId = opts.targetNodeId;
3437
+ if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
3438
+ if (typeof opts?.targetSessionId === "string") entry.targetSessionId = opts.targetSessionId;
3439
+ entry.updatedAt = now;
3440
+ entry.requeuedAt = now;
3441
+ entry.requeueCount = (entry.requeueCount || 0) + 1;
3442
+ if (opts?.reason) entry.requeueReason = opts.reason;
3443
+ writeQueue(meshId, queue);
3444
+ return entry;
3445
+ });
3446
+ }
3447
+ function updateSessionTaskStatus(meshId, sessionId, status, opts) {
3448
+ return withQueueLock(meshId, () => {
3449
+ const queue = readQueue(meshId);
3450
+ const occurredAtTime = opts?.occurredAt ? new Date(opts.occurredAt).getTime() : Number.NaN;
3451
+ const hasOccurredAt = Number.isFinite(occurredAtTime);
3452
+ let bestIdx = -1;
3453
+ let bestTime = 0;
3454
+ for (let i = queue.length - 1; i >= 0; i--) {
3455
+ if (queue[i].assignedSessionId !== sessionId || queue[i].status !== "assigned") continue;
3347
3456
  const time3 = new Date(queue[i].dispatchTimestamp || queue[i].updatedAt).getTime();
3457
+ if (hasOccurredAt && Number.isFinite(time3) && time3 > occurredAtTime) continue;
3348
3458
  if (time3 > bestTime) {
3349
3459
  bestTime = time3;
3350
3460
  bestIdx = i;
3351
3461
  }
3352
3462
  }
3353
- }
3354
- if (bestIdx === -1) return null;
3355
- queue[bestIdx].status = status;
3356
- queue[bestIdx].updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3357
- writeQueue(meshId, queue);
3358
- return queue[bestIdx];
3463
+ if (bestIdx === -1) return null;
3464
+ queue[bestIdx].status = status;
3465
+ queue[bestIdx].updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3466
+ writeQueue(meshId, queue);
3467
+ return queue[bestIdx];
3468
+ });
3359
3469
  }
3360
3470
  function getMeshQueueStats(meshId) {
3361
3471
  const queue = readQueue(meshId);
@@ -3759,18 +3869,75 @@ __export(mesh_events_exports, {
3759
3869
  drainPendingMeshCoordinatorEvents: () => drainPendingMeshCoordinatorEvents,
3760
3870
  getPendingMeshCoordinatorEvents: () => getPendingMeshCoordinatorEvents,
3761
3871
  handleMeshForwardEvent: () => handleMeshForwardEvent,
3872
+ queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
3762
3873
  setupMeshEventForwarding: () => setupMeshEventForwarding,
3763
3874
  triggerMeshQueue: () => triggerMeshQueue,
3764
3875
  tryAssignQueueTask: () => tryAssignQueueTask
3765
3876
  });
3766
- function drainPendingMeshCoordinatorEvents() {
3767
- return pendingMeshCoordinatorEvents.splice(0);
3877
+ function sweepExpiredRemoteIdleSessions() {
3878
+ const now = Date.now();
3879
+ for (const [key, session] of remoteIdleSessions) {
3880
+ if (session.expiresAt <= now) remoteIdleSessions.delete(key);
3881
+ }
3882
+ }
3883
+ function getPendingEventsPath(meshId) {
3884
+ const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
3885
+ return (0, import_path5.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
3886
+ }
3887
+ function queuePendingMeshCoordinatorEvent(event) {
3888
+ try {
3889
+ (0, import_fs6.appendFileSync)(getPendingEventsPath(event.meshId), JSON.stringify(event) + "\n", "utf-8");
3890
+ return true;
3891
+ } catch (e) {
3892
+ LOG.warn("MeshEvents", `Failed to persist pending coordinator event: ${e?.message || e}`);
3893
+ return false;
3894
+ }
3895
+ }
3896
+ function drainPendingMeshCoordinatorEvents(meshId) {
3897
+ if (!meshId) return [];
3898
+ const path35 = getPendingEventsPath(meshId);
3899
+ if (!(0, import_fs6.existsSync)(path35)) return [];
3900
+ try {
3901
+ const raw = (0, import_fs6.readFileSync)(path35, "utf-8");
3902
+ try {
3903
+ (0, import_fs6.unlinkSync)(path35);
3904
+ } catch {
3905
+ }
3906
+ return raw.split("\n").filter(Boolean).flatMap((line) => {
3907
+ try {
3908
+ return [JSON.parse(line)];
3909
+ } catch {
3910
+ return [];
3911
+ }
3912
+ });
3913
+ } catch {
3914
+ return [];
3915
+ }
3768
3916
  }
3769
- function getPendingMeshCoordinatorEvents() {
3770
- return pendingMeshCoordinatorEvents.slice();
3917
+ function getPendingMeshCoordinatorEvents(meshId) {
3918
+ if (!meshId) return [];
3919
+ const path35 = getPendingEventsPath(meshId);
3920
+ if (!(0, import_fs6.existsSync)(path35)) return [];
3921
+ try {
3922
+ const raw = (0, import_fs6.readFileSync)(path35, "utf-8");
3923
+ return raw.split("\n").filter(Boolean).flatMap((line) => {
3924
+ try {
3925
+ return [JSON.parse(line)];
3926
+ } catch {
3927
+ return [];
3928
+ }
3929
+ });
3930
+ } catch {
3931
+ return [];
3932
+ }
3771
3933
  }
3772
- function clearPendingMeshCoordinatorEvents() {
3773
- pendingMeshCoordinatorEvents.splice(0);
3934
+ function clearPendingMeshCoordinatorEvents(meshId) {
3935
+ if (!meshId) return;
3936
+ const path35 = getPendingEventsPath(meshId);
3937
+ if ((0, import_fs6.existsSync)(path35)) try {
3938
+ (0, import_fs6.unlinkSync)(path35);
3939
+ } catch {
3940
+ }
3774
3941
  }
3775
3942
  function readNonEmptyString(value) {
3776
3943
  return typeof value === "string" && value.trim() ? value.trim() : "";
@@ -3816,6 +3983,38 @@ function shouldSuppressIntentionalCleanupStop(args) {
3816
3983
  if (isIntentionalCleanupStopMetadata(args.metadataEvent)) return true;
3817
3984
  return hasRecentIntentionalCleanupStop(args.meshId, args.sessionId, args.nodeId);
3818
3985
  }
3986
+ function readEventTimestamp(value) {
3987
+ if (typeof value === "number" && Number.isFinite(value)) return value;
3988
+ if (typeof value === "string" && value.trim()) {
3989
+ const numeric = Number(value);
3990
+ if (Number.isFinite(numeric)) return numeric;
3991
+ const parsed = Date.parse(value);
3992
+ if (Number.isFinite(parsed)) return parsed;
3993
+ }
3994
+ return null;
3995
+ }
3996
+ function buildMeshCompletionFingerprint(args) {
3997
+ const timestampPart = Number.isFinite(args.timestamp) ? String(args.timestamp) : readNonEmptyString(args.finalSummary).slice(0, 200);
3998
+ return [
3999
+ args.meshId,
4000
+ args.event,
4001
+ args.sessionId,
4002
+ args.providerType || "",
4003
+ args.providerSessionId || "",
4004
+ timestampPart
4005
+ ].join("::");
4006
+ }
4007
+ function isDuplicateMeshCompletionEvent(args) {
4008
+ const fingerprint = buildMeshCompletionFingerprint(args);
4009
+ if (!fingerprint) return false;
4010
+ const now = Date.now();
4011
+ for (const [key, seenAt] of recentCompletionFingerprints.entries()) {
4012
+ if (now - seenAt > RECENT_COMPLETION_FINGERPRINT_TTL_MS) recentCompletionFingerprints.delete(key);
4013
+ }
4014
+ if (recentCompletionFingerprints.has(fingerprint)) return true;
4015
+ recentCompletionFingerprints.set(fingerprint, now);
4016
+ return false;
4017
+ }
3819
4018
  function tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType) {
3820
4019
  const task = claimNextTask(meshId, nodeId, sessionId);
3821
4020
  if (!task) {
@@ -3834,7 +4033,16 @@ function tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType)
3834
4033
  message: task.message
3835
4034
  }).catch((e) => {
3836
4035
  LOG.error("MeshQueue", `Failed to dispatch task via P2P to remote node ${nodeId}: ${e?.message}`);
3837
- updateTaskStatus(meshId, task.id, "failed");
4036
+ updateTaskStatus(meshId, task.id, "pending");
4037
+ try {
4038
+ appendLedgerEntry(meshId, {
4039
+ kind: "dispatch_failed",
4040
+ nodeId,
4041
+ sessionId,
4042
+ payload: { taskId: task.id, error: e?.message, retryable: true }
4043
+ });
4044
+ } catch {
4045
+ }
3838
4046
  });
3839
4047
  return true;
3840
4048
  }
@@ -4168,18 +4376,36 @@ function injectMeshSystemMessage(components, args) {
4168
4376
  LOG.info("MeshEvents", `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || "(unknown session)"}`);
4169
4377
  return { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true };
4170
4378
  }
4379
+ const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
4380
+ if (args.event === "agent:generating_completed" && eventSessionId) {
4381
+ const duplicateCompletion = isDuplicateMeshCompletionEvent({
4382
+ meshId: args.meshId,
4383
+ event: args.event,
4384
+ sessionId: eventSessionId,
4385
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || void 0,
4386
+ providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || void 0,
4387
+ timestamp: eventTimestamp,
4388
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || void 0
4389
+ });
4390
+ if (duplicateCompletion) {
4391
+ LOG.info("MeshEvents", `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
4392
+ return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true };
4393
+ }
4394
+ }
4171
4395
  let completedTaskForLedger = null;
4172
4396
  if (args.event === "agent:generating_completed") {
4173
4397
  const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
4174
4398
  const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
4175
4399
  const providerType = readNonEmptyString(args.metadataEvent.providerType);
4176
4400
  if (sessionId) {
4177
- const completedTask = updateSessionTaskStatus(args.meshId, sessionId, "completed");
4401
+ const completedTask = updateSessionTaskStatus(args.meshId, sessionId, "completed", {
4402
+ occurredAt: eventTimestamp !== null ? new Date(eventTimestamp).toISOString() : void 0
4403
+ });
4178
4404
  completedTaskForLedger = completedTask ? { id: completedTask.id } : null;
4179
4405
  if (nodeId && providerType) {
4180
- setTimeout(() => {
4406
+ setImmediate(() => {
4181
4407
  tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
4182
- }, 500);
4408
+ });
4183
4409
  }
4184
4410
  }
4185
4411
  } else if (args.event === "agent:ready") {
@@ -4217,13 +4443,17 @@ function injectMeshSystemMessage(components, args) {
4217
4443
  }
4218
4444
  }
4219
4445
  if (sessionId && nodeId && providerType) {
4220
- remoteIdleSessions.set(`${nodeId}:${sessionId}`, { nodeId, sessionId, providerType });
4221
- setTimeout(() => {
4446
+ sweepExpiredRemoteIdleSessions();
4447
+ remoteIdleSessions.set(`${nodeId}:${sessionId}`, {
4448
+ nodeId,
4449
+ sessionId,
4450
+ providerType,
4451
+ expiresAt: Date.now() + REMOTE_IDLE_SESSION_TTL_MS
4452
+ });
4453
+ setImmediate(() => {
4222
4454
  const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
4223
- if (assigned) {
4224
- remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
4225
- }
4226
- }, 500);
4455
+ if (assigned) remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
4456
+ });
4227
4457
  }
4228
4458
  } else if (args.event === "agent:generating_started") {
4229
4459
  const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
@@ -4334,17 +4564,18 @@ function injectMeshSystemMessage(components, args) {
4334
4564
  return true;
4335
4565
  });
4336
4566
  if (coordinatorInstances.length === 0) {
4337
- if (pendingMeshCoordinatorEvents.length < MAX_PENDING_EVENTS) {
4338
- pendingMeshCoordinatorEvents.push({
4339
- event: args.event,
4340
- meshId: args.meshId,
4341
- nodeLabel: args.nodeLabel,
4342
- metadataEvent: {
4343
- ...args.metadataEvent,
4344
- ...recoveryContext ? { recoveryContext } : {}
4345
- },
4346
- queuedAt: Date.now()
4347
- });
4567
+ if (queuePendingMeshCoordinatorEvent({
4568
+ event: args.event,
4569
+ meshId: args.meshId,
4570
+ nodeLabel: args.nodeLabel,
4571
+ nodeId: args.nodeId || void 0,
4572
+ workspace: readNonEmptyString(args.metadataEvent.workspace),
4573
+ metadataEvent: {
4574
+ ...args.metadataEvent,
4575
+ ...recoveryContext ? { recoveryContext } : {}
4576
+ },
4577
+ queuedAt: Date.now()
4578
+ })) {
4348
4579
  LOG.info("MeshEvents", `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
4349
4580
  }
4350
4581
  return { success: true, forwarded: 0 };
@@ -4383,6 +4614,7 @@ function handleMeshForwardEvent(components, payload) {
4383
4614
  providerType: readNonEmptyString(payload.providerType),
4384
4615
  providerSessionId: readNonEmptyString(payload.providerSessionId),
4385
4616
  finalSummary: readNonEmptyString(payload.finalSummary) || readNonEmptyString(payload.summary),
4617
+ ...payload.timestamp !== void 0 ? { timestamp: payload.timestamp } : {},
4386
4618
  intentional: payload.intentional === true,
4387
4619
  intentionalStop: payload.intentionalStop === true,
4388
4620
  operatorCleanup: payload.operatorCleanup === true,
@@ -4425,19 +4657,20 @@ function setupMeshEventForwarding(components) {
4425
4657
  });
4426
4658
  });
4427
4659
  }
4428
- var remoteIdleSessions, MAX_PENDING_EVENTS, pendingMeshCoordinatorEvents, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS, autoLaunchInProgress, autoLaunchCooldownUntil, AUTO_LAUNCH_COOLDOWN_MS;
4660
+ var import_fs6, import_path5, REMOTE_IDLE_SESSION_TTL_MS, remoteIdleSessions, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS, RECENT_COMPLETION_FINGERPRINT_TTL_MS, recentCompletionFingerprints, autoLaunchInProgress, autoLaunchCooldownUntil, AUTO_LAUNCH_COOLDOWN_MS;
4429
4661
  var init_mesh_events = __esm({
4430
4662
  "../../oss/packages/daemon-core/src/mesh/mesh-events.ts"() {
4431
4663
  "use strict";
4664
+ import_fs6 = require("fs");
4665
+ import_path5 = require("path");
4432
4666
  init_config();
4433
4667
  init_mesh_config();
4434
4668
  init_cli_detector();
4435
4669
  init_logger();
4436
4670
  init_mesh_ledger();
4437
4671
  init_mesh_work_queue();
4672
+ REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1e3;
4438
4673
  remoteIdleSessions = /* @__PURE__ */ new Map();
4439
- MAX_PENDING_EVENTS = 50;
4440
- pendingMeshCoordinatorEvents = [];
4441
4674
  MESH_COORDINATOR_EVENTS = /* @__PURE__ */ new Set([
4442
4675
  "agent:generating_started",
4443
4676
  "agent:generating_completed",
@@ -4453,6 +4686,8 @@ var init_mesh_events = __esm({
4453
4686
  "monitor:long_generating": "task_stalled"
4454
4687
  };
4455
4688
  INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS = 30 * 60 * 1e3;
4689
+ RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1e3;
4690
+ recentCompletionFingerprints = /* @__PURE__ */ new Map();
4456
4691
  autoLaunchInProgress = /* @__PURE__ */ new Set();
4457
4692
  autoLaunchCooldownUntil = /* @__PURE__ */ new Map();
4458
4693
  AUTO_LAUNCH_COOLDOWN_MS = 5e3;
@@ -4580,7 +4815,7 @@ function isPlainObject2(value) {
4580
4815
  return !!value && typeof value === "object" && !Array.isArray(value);
4581
4816
  }
4582
4817
  function getStatePath() {
4583
- return (0, import_path5.join)(getConfigDir(), "state.json");
4818
+ return (0, import_path6.join)(getConfigDir(), "state.json");
4584
4819
  }
4585
4820
  function normalizeState(raw) {
4586
4821
  const parsed = isPlainObject2(raw) ? raw : {};
@@ -4616,11 +4851,11 @@ function normalizeState(raw) {
4616
4851
  }
4617
4852
  function loadState() {
4618
4853
  const statePath = getStatePath();
4619
- if (!(0, import_fs6.existsSync)(statePath)) {
4854
+ if (!(0, import_fs7.existsSync)(statePath)) {
4620
4855
  return { ...DEFAULT_STATE };
4621
4856
  }
4622
4857
  try {
4623
- const raw = (0, import_fs6.readFileSync)(statePath, "utf-8");
4858
+ const raw = (0, import_fs7.readFileSync)(statePath, "utf-8");
4624
4859
  return normalizeState(JSON.parse(raw));
4625
4860
  } catch {
4626
4861
  return { ...DEFAULT_STATE };
@@ -4629,17 +4864,17 @@ function loadState() {
4629
4864
  function saveState(state) {
4630
4865
  const statePath = getStatePath();
4631
4866
  const normalized = normalizeState(state);
4632
- (0, import_fs6.writeFileSync)(statePath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
4867
+ (0, import_fs7.writeFileSync)(statePath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
4633
4868
  }
4634
4869
  function resetState() {
4635
4870
  saveState({ ...DEFAULT_STATE });
4636
4871
  }
4637
- var import_fs6, import_path5, DEFAULT_STATE;
4872
+ var import_fs7, import_path6, DEFAULT_STATE;
4638
4873
  var init_state_store = __esm({
4639
4874
  "../../oss/packages/daemon-core/src/config/state-store.ts"() {
4640
4875
  "use strict";
4641
- import_fs6 = require("fs");
4642
- import_path5 = require("path");
4876
+ import_fs7 = require("fs");
4877
+ import_path6 = require("path");
4643
4878
  init_config();
4644
4879
  DEFAULT_STATE = {
4645
4880
  recentActivity: [],
@@ -4672,7 +4907,7 @@ function findCliCommand(command) {
4672
4907
  if (path10.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~")) {
4673
4908
  const candidate = trimmed.startsWith("~") ? path10.join((0, import_os2.homedir)(), trimmed.slice(1)) : trimmed;
4674
4909
  const resolved = path10.isAbsolute(candidate) ? candidate : path10.resolve(candidate);
4675
- return (0, import_fs7.existsSync)(resolved) ? resolved : null;
4910
+ return (0, import_fs8.existsSync)(resolved) ? resolved : null;
4676
4911
  }
4677
4912
  try {
4678
4913
  const result = (0, import_child_process2.execSync)(
@@ -4703,9 +4938,9 @@ function checkPathExists(paths) {
4703
4938
  if (normalized.includes("*")) {
4704
4939
  const username = home.split(/[\\/]/).pop() || "";
4705
4940
  const resolved = normalized.replace("*", username);
4706
- if ((0, import_fs7.existsSync)(resolved)) return resolved;
4941
+ if ((0, import_fs8.existsSync)(resolved)) return resolved;
4707
4942
  } else {
4708
- if ((0, import_fs7.existsSync)(normalized)) return normalized;
4943
+ if ((0, import_fs8.existsSync)(normalized)) return normalized;
4709
4944
  }
4710
4945
  }
4711
4946
  return null;
@@ -4719,7 +4954,7 @@ async function detectIDEs(providerLoader) {
4719
4954
  let resolvedCli = cliPath;
4720
4955
  if (!resolvedCli && appPath && os30 === "darwin") {
4721
4956
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
4722
- if ((0, import_fs7.existsSync)(bundledCli)) resolvedCli = bundledCli;
4957
+ if ((0, import_fs8.existsSync)(bundledCli)) resolvedCli = bundledCli;
4723
4958
  }
4724
4959
  if (!resolvedCli && appPath && os30 === "win32") {
4725
4960
  const { dirname: dirname12 } = await import("path");
@@ -4732,7 +4967,7 @@ async function detectIDEs(providerLoader) {
4732
4967
  `${appDir}\\\\resources\\\\app\\\\bin\\\\${def.cli}.cmd`
4733
4968
  ];
4734
4969
  for (const c of candidates) {
4735
- if ((0, import_fs7.existsSync)(c)) {
4970
+ if ((0, import_fs8.existsSync)(c)) {
4736
4971
  resolvedCli = c;
4737
4972
  break;
4738
4973
  }
@@ -4753,12 +4988,12 @@ async function detectIDEs(providerLoader) {
4753
4988
  }
4754
4989
  return results;
4755
4990
  }
4756
- var import_child_process2, import_fs7, import_os2, path10, BUILTIN_IDE_DEFINITIONS, registeredIDEs;
4991
+ var import_child_process2, import_fs8, import_os2, path10, BUILTIN_IDE_DEFINITIONS, registeredIDEs;
4757
4992
  var init_ide_detector = __esm({
4758
4993
  "../../oss/packages/daemon-core/src/detection/ide-detector.ts"() {
4759
4994
  "use strict";
4760
4995
  import_child_process2 = require("child_process");
4761
- import_fs7 = require("fs");
4996
+ import_fs8 = require("fs");
4762
4997
  import_os2 = require("os");
4763
4998
  path10 = __toESM(require("path"));
4764
4999
  BUILTIN_IDE_DEFINITIONS = [];
@@ -6679,7 +6914,7 @@ var init_status_monitor = __esm({
6679
6914
  });
6680
6915
 
6681
6916
  // ../../oss/packages/daemon-core/src/providers/chat-message-normalization.ts
6682
- function extractFinalSummaryFromMessages(messages, maxChars = 500) {
6917
+ function extractFinalSummaryFromMessages(messages, maxChars = DEFAULT_FINAL_SUMMARY_MAX_CHARS) {
6683
6918
  if (!Array.isArray(messages) || messages.length === 0) return "";
6684
6919
  for (let i = messages.length - 1; i >= 0; i--) {
6685
6920
  const msg = messages[i];
@@ -6981,11 +7216,12 @@ function filterInternalChatMessages(messages) {
6981
7216
  function filterChatMessagesByVisibility(messages, surface) {
6982
7217
  return (Array.isArray(messages) ? messages : []).filter((message) => classifyChatMessageVisibility(message).surface === surface);
6983
7218
  }
6984
- var BUILTIN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_VISIBILITIES, CHAT_MESSAGE_TRANSCRIPT_VISIBILITIES, CHAT_MESSAGE_AUDIENCES, CHAT_MESSAGE_SOURCES, CHAT_MESSAGE_ACTIVITY_SOURCES, CHAT_MESSAGE_INTERNAL_SOURCES, KNOWN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_KIND_ALIASES, EXPLICIT_HIDDEN_VISIBILITIES, EXPLICIT_VISIBLE_VISIBILITIES, HIDDEN_AUDIENCES, ACTIVITY_SOURCE_SET, INTERNAL_SOURCE_SET;
7219
+ var DEFAULT_FINAL_SUMMARY_MAX_CHARS, BUILTIN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_VISIBILITIES, CHAT_MESSAGE_TRANSCRIPT_VISIBILITIES, CHAT_MESSAGE_AUDIENCES, CHAT_MESSAGE_SOURCES, CHAT_MESSAGE_ACTIVITY_SOURCES, CHAT_MESSAGE_INTERNAL_SOURCES, KNOWN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_KIND_ALIASES, EXPLICIT_HIDDEN_VISIBILITIES, EXPLICIT_VISIBLE_VISIBILITIES, HIDDEN_AUDIENCES, ACTIVITY_SOURCE_SET, INTERNAL_SOURCE_SET;
6985
7220
  var init_chat_message_normalization = __esm({
6986
7221
  "../../oss/packages/daemon-core/src/providers/chat-message-normalization.ts"() {
6987
7222
  "use strict";
6988
7223
  init_contracts();
7224
+ DEFAULT_FINAL_SUMMARY_MAX_CHARS = 4e3;
6989
7225
  BUILTIN_CHAT_MESSAGE_KINDS = ["standard", "thought", "tool", "terminal", "system"];
6990
7226
  CHAT_MESSAGE_VISIBILITIES = ["user", "debug", "internal", "hidden"];
6991
7227
  CHAT_MESSAGE_TRANSCRIPT_VISIBILITIES = ["visible", "chat", "user", "debug", "internal", "hidden"];
@@ -36737,7 +36973,7 @@ function commandExists(command) {
36737
36973
  const trimmed = command.trim();
36738
36974
  if (!trimmed) return false;
36739
36975
  if (isExplicitCommand(trimmed)) {
36740
- return (0, import_fs8.existsSync)(expandExecutable(trimmed));
36976
+ return (0, import_fs9.existsSync)(expandExecutable(trimmed));
36741
36977
  }
36742
36978
  try {
36743
36979
  (0, import_child_process6.execFileSync)(process.platform === "win32" ? "where" : "which", [trimmed], {
@@ -36758,10 +36994,10 @@ function hasCliArg(args, flag) {
36758
36994
  }
36759
36995
  function ensureEmptyDelegatedMcpConfig(workspace) {
36760
36996
  const baseDir = path18.join(os15.tmpdir(), "adhdev-delegated-agent-empty-mcp");
36761
- (0, import_fs8.mkdirSync)(baseDir, { recursive: true });
36997
+ (0, import_fs9.mkdirSync)(baseDir, { recursive: true });
36762
36998
  const workspaceHash = crypto4.createHash("sha256").update(path18.resolve(workspace || os15.tmpdir())).digest("hex").slice(0, 16);
36763
36999
  const filePath = path18.join(baseDir, `${workspaceHash}.json`);
36764
- (0, import_fs8.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
37000
+ (0, import_fs9.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
36765
37001
  return filePath;
36766
37002
  }
36767
37003
  function buildCoordinatorDelegatedCliLaunchOptions(input) {
@@ -36888,14 +37124,14 @@ function resolveCliSessionBinding(provider, normalizedType, cliArgs, requestedRe
36888
37124
  launchMode: "new"
36889
37125
  };
36890
37126
  }
36891
- var os15, path18, crypto4, import_fs8, import_child_process6, chalkModule, chalkApi, COORDINATOR_DELEGATED_ENV_UNSETS, DaemonCliManager;
37127
+ var os15, path18, crypto4, import_fs9, import_child_process6, chalkModule, chalkApi, COORDINATOR_DELEGATED_ENV_UNSETS, DaemonCliManager;
36892
37128
  var init_cli_manager = __esm({
36893
37129
  "../../oss/packages/daemon-core/src/commands/cli-manager.ts"() {
36894
37130
  "use strict";
36895
37131
  os15 = __toESM(require("os"));
36896
37132
  path18 = __toESM(require("path"));
36897
37133
  crypto4 = __toESM(require("crypto"));
36898
- import_fs8 = require("fs");
37134
+ import_fs9 = require("fs");
36899
37135
  import_child_process6 = require("child_process");
36900
37136
  init_source();
36901
37137
  init_provider_cli_adapter();
@@ -37809,7 +38045,7 @@ function createFsWatchInstance(path35, options, listener, errHandler, emitRaw) {
37809
38045
  }
37810
38046
  };
37811
38047
  try {
37812
- return (0, import_fs9.watch)(path35, {
38048
+ return (0, import_fs10.watch)(path35, {
37813
38049
  persistent: options.persistent
37814
38050
  }, handleEvent);
37815
38051
  } catch (error48) {
@@ -37817,11 +38053,11 @@ function createFsWatchInstance(path35, options, listener, errHandler, emitRaw) {
37817
38053
  return void 0;
37818
38054
  }
37819
38055
  }
37820
- var import_fs9, import_promises5, sysPath, import_os3, STR_DATA, STR_END, STR_CLOSE, EMPTY_FN, pl, isWindows, isMacos, isLinux, isFreeBSD, isIBMi, EVENTS, EV, THROTTLE_MODE_WATCH, statMethods, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, binaryExtensions, isBinaryPath, foreach, addAndConvert, clearItem, delFromSet, isEmptySet, FsWatchInstances, fsWatchBroadcast, setFsWatchListener, FsWatchFileInstances, setFsWatchFileListener, NodeFsHandler;
38056
+ var import_fs10, import_promises5, sysPath, import_os3, STR_DATA, STR_END, STR_CLOSE, EMPTY_FN, pl, isWindows, isMacos, isLinux, isFreeBSD, isIBMi, EVENTS, EV, THROTTLE_MODE_WATCH, statMethods, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, binaryExtensions, isBinaryPath, foreach, addAndConvert, clearItem, delFromSet, isEmptySet, FsWatchInstances, fsWatchBroadcast, setFsWatchListener, FsWatchFileInstances, setFsWatchFileListener, NodeFsHandler;
37821
38057
  var init_handler2 = __esm({
37822
38058
  "../../oss/node_modules/chokidar/esm/handler.js"() {
37823
38059
  "use strict";
37824
- import_fs9 = require("fs");
38060
+ import_fs10 = require("fs");
37825
38061
  import_promises5 = require("fs/promises");
37826
38062
  sysPath = __toESM(require("path"), 1);
37827
38063
  import_os3 = require("os");
@@ -38225,7 +38461,7 @@ var init_handler2 = __esm({
38225
38461
  let cont = FsWatchFileInstances.get(fullPath);
38226
38462
  const copts = cont && cont.options;
38227
38463
  if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
38228
- (0, import_fs9.unwatchFile)(fullPath);
38464
+ (0, import_fs10.unwatchFile)(fullPath);
38229
38465
  cont = void 0;
38230
38466
  }
38231
38467
  if (cont) {
@@ -38236,7 +38472,7 @@ var init_handler2 = __esm({
38236
38472
  listeners: listener,
38237
38473
  rawEmitters: rawEmitter,
38238
38474
  options,
38239
- watcher: (0, import_fs9.watchFile)(fullPath, options, (curr, prev) => {
38475
+ watcher: (0, import_fs10.watchFile)(fullPath, options, (curr, prev) => {
38240
38476
  foreach(cont.rawEmitters, (rawEmitter2) => {
38241
38477
  rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
38242
38478
  });
@@ -38253,7 +38489,7 @@ var init_handler2 = __esm({
38253
38489
  delFromSet(cont, KEY_RAW, rawEmitter);
38254
38490
  if (isEmptySet(cont.listeners)) {
38255
38491
  FsWatchFileInstances.delete(fullPath);
38256
- (0, import_fs9.unwatchFile)(fullPath);
38492
+ (0, import_fs10.unwatchFile)(fullPath);
38257
38493
  cont.options = cont.watcher = void 0;
38258
38494
  Object.freeze(cont);
38259
38495
  }
@@ -38631,11 +38867,11 @@ function watch(paths, options = {}) {
38631
38867
  watcher.add(paths);
38632
38868
  return watcher;
38633
38869
  }
38634
- var import_fs10, import_promises6, import_events2, sysPath2, SLASH, SLASH_SLASH, ONE_DOT, TWO_DOTS, STRING_TYPE, BACK_SLASH_RE, DOUBLE_SLASH_RE, DOT_RE, REPLACER_RE, isMatcherObject, unifyPaths, toUnix, normalizePathToUnix, normalizeIgnored, getAbsolutePath, EMPTY_SET, DirEntry, STAT_METHOD_F, STAT_METHOD_L, WatchHelper, FSWatcher;
38870
+ var import_fs11, import_promises6, import_events2, sysPath2, SLASH, SLASH_SLASH, ONE_DOT, TWO_DOTS, STRING_TYPE, BACK_SLASH_RE, DOUBLE_SLASH_RE, DOT_RE, REPLACER_RE, isMatcherObject, unifyPaths, toUnix, normalizePathToUnix, normalizeIgnored, getAbsolutePath, EMPTY_SET, DirEntry, STAT_METHOD_F, STAT_METHOD_L, WatchHelper, FSWatcher;
38635
38871
  var init_esm2 = __esm({
38636
38872
  "../../oss/node_modules/chokidar/esm/index.js"() {
38637
38873
  "use strict";
38638
- import_fs10 = require("fs");
38874
+ import_fs11 = require("fs");
38639
38875
  import_promises6 = require("fs/promises");
38640
38876
  import_events2 = require("events");
38641
38877
  sysPath2 = __toESM(require("path"), 1);
@@ -39113,7 +39349,7 @@ var init_esm2 = __esm({
39113
39349
  const now = /* @__PURE__ */ new Date();
39114
39350
  const writes = this._pendingWrites;
39115
39351
  function awaitWriteFinishFn(prevStat) {
39116
- (0, import_fs10.stat)(fullPath, (err, curStat) => {
39352
+ (0, import_fs11.stat)(fullPath, (err, curStat) => {
39117
39353
  if (err || !writes.has(path35)) {
39118
39354
  if (err && err.code !== "ENOENT")
39119
39355
  awfEmit(err);
@@ -45414,55 +45650,45 @@ function readBooleanValue(...values) {
45414
45650
  }
45415
45651
  return void 0;
45416
45652
  }
45417
- function buildCachedInlineMeshGitStatus(node) {
45418
- const cachedStatus = readObjectRecord(node?.cachedStatus);
45419
- const cachedGit = readObjectRecord(cachedStatus.git);
45420
- if (Object.keys(cachedGit).length) {
45421
- const conflictFiles2 = Array.isArray(cachedGit.conflictFiles) ? cachedGit.conflictFiles.filter((value) => typeof value === "string") : [];
45422
- const conflictCount2 = readNumberValue(cachedGit.conflicts) ?? conflictFiles2.length;
45423
- const hasConflicts2 = readBooleanValue(cachedGit.hasConflicts) ?? conflictCount2 > 0;
45424
- const isGitRepo2 = readBooleanValue(cachedGit.isGitRepo);
45425
- if (isGitRepo2 !== void 0) {
45426
- return {
45427
- workspace: readStringValue(cachedGit.workspace, node?.workspace) || "",
45428
- repoRoot: readStringValue(cachedGit.repoRoot, node?.repoRoot, node?.workspace) || null,
45429
- isGitRepo: isGitRepo2,
45430
- branch: readStringValue(cachedGit.branch) ?? null,
45431
- headCommit: readStringValue(cachedGit.headCommit) ?? null,
45432
- headMessage: readStringValue(cachedGit.headMessage) ?? null,
45433
- upstream: readStringValue(cachedGit.upstream) ?? null,
45434
- ahead: readNumberValue(cachedGit.ahead) ?? 0,
45435
- behind: readNumberValue(cachedGit.behind) ?? 0,
45436
- staged: readNumberValue(cachedGit.staged) ?? 0,
45437
- modified: readNumberValue(cachedGit.modified) ?? 0,
45438
- untracked: readNumberValue(cachedGit.untracked) ?? 0,
45439
- deleted: readNumberValue(cachedGit.deleted) ?? 0,
45440
- renamed: readNumberValue(cachedGit.renamed) ?? 0,
45441
- hasConflicts: hasConflicts2,
45442
- conflictFiles: conflictFiles2,
45443
- stashCount: readNumberValue(cachedGit.stashCount) ?? 0,
45444
- lastCheckedAt: readNumberValue(cachedGit.lastCheckedAt) ?? Date.now()
45445
- };
45446
- }
45447
- }
45448
- const rawGit = readObjectRecord(node?.lastGit ?? node?.last_git);
45449
- const gitResult = readObjectRecord(rawGit.result);
45450
- const directStatus = readObjectRecord(rawGit.status);
45451
- const nestedStatus = readObjectRecord(gitResult.status);
45452
- const rawProbe = readObjectRecord(node?.lastProbe ?? node?.last_probe);
45453
- const probeGit = readObjectRecord(rawProbe.git);
45454
- const probeGitResult = readObjectRecord(probeGit.result);
45455
- const probeDirectStatus = readObjectRecord(probeGit.status);
45456
- const probeNestedStatus = readObjectRecord(probeGitResult.status);
45457
- const status = Object.keys(directStatus).length ? directStatus : Object.keys(nestedStatus).length ? nestedStatus : Object.keys(probeDirectStatus).length ? probeDirectStatus : Object.keys(probeNestedStatus).length ? probeNestedStatus : {};
45653
+ function joinRepoPath(root, relativePath) {
45654
+ const normalizedRoot = typeof root === "string" ? root.trim().replace(/[\\/]+$/, "") : "";
45655
+ const normalizedPath = typeof relativePath === "string" ? relativePath.trim() : "";
45656
+ if (!normalizedPath) return void 0;
45657
+ if (/^(?:[A-Za-z]:[\\/]|\/)/.test(normalizedPath)) return normalizedPath;
45658
+ if (!normalizedRoot) return void 0;
45659
+ return `${normalizedRoot}/${normalizedPath.replace(/^[\\/]+/, "")}`;
45660
+ }
45661
+ function readGitSubmodules(value, parentRepoRoot) {
45662
+ if (!Array.isArray(value)) return void 0;
45663
+ const submodules = value.map((entry) => {
45664
+ const submodule = readObjectRecord(entry);
45665
+ const path35 = readStringValue(submodule.path);
45666
+ const commit = readStringValue(submodule.commit);
45667
+ const repoPath = readStringValue(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path35);
45668
+ if (!path35 || !commit || !repoPath) return null;
45669
+ return {
45670
+ path: path35,
45671
+ commit,
45672
+ repoPath,
45673
+ dirty: readBooleanValue(submodule.dirty) ?? false,
45674
+ outOfSync: readBooleanValue(submodule.outOfSync, submodule.out_of_sync) ?? false,
45675
+ lastCheckedAt: readNumberValue(submodule.lastCheckedAt, submodule.last_checked_at) ?? Date.now(),
45676
+ ...readStringValue(submodule.error) ? { error: readStringValue(submodule.error) } : {}
45677
+ };
45678
+ }).filter((entry) => entry !== null);
45679
+ return submodules.length > 0 ? submodules : void 0;
45680
+ }
45681
+ function normalizeInlineMeshGitStatus(status, node, options) {
45458
45682
  const isGitRepo = readBooleanValue(status.isGitRepo);
45459
45683
  if (!Object.keys(status).length || isGitRepo === void 0) return void 0;
45460
45684
  const conflictFiles = Array.isArray(status.conflictFiles) ? status.conflictFiles.filter((value) => typeof value === "string") : [];
45461
45685
  const conflictCount = readNumberValue(status.conflicts) ?? conflictFiles.length;
45462
45686
  const hasConflicts = readBooleanValue(status.hasConflicts) ?? conflictCount > 0;
45687
+ const repoRoot = readStringValue(status.repoRoot, status.repo_root, node?.repoRoot, node?.repo_root, status.workspace, node?.workspace) || void 0;
45688
+ const submodules = readGitSubmodules(status.submodules, repoRoot);
45463
45689
  return {
45464
45690
  workspace: readStringValue(status.workspace, node?.workspace) || "",
45465
- repoRoot: readStringValue(status.repoRoot, node?.repoRoot, node?.workspace) || null,
45691
+ repoRoot: repoRoot ?? null,
45466
45692
  isGitRepo,
45467
45693
  branch: readStringValue(status.branch) ?? null,
45468
45694
  headCommit: readStringValue(status.headCommit) ?? null,
@@ -45478,29 +45704,412 @@ function buildCachedInlineMeshGitStatus(node) {
45478
45704
  hasConflicts,
45479
45705
  conflictFiles,
45480
45706
  stashCount: readNumberValue(status.stashCount) ?? 0,
45481
- lastCheckedAt: Date.now()
45707
+ lastCheckedAt: options?.lastCheckedAt ?? readNumberValue(status.lastCheckedAt) ?? Date.now(),
45708
+ ...submodules ? { submodules } : {}
45709
+ };
45710
+ }
45711
+ function buildInlineMeshTransitGitStatus(node) {
45712
+ const rawGit = readObjectRecord(node?.lastGit ?? node?.last_git);
45713
+ const gitResult = readObjectRecord(rawGit.result);
45714
+ const directStatus = readObjectRecord(rawGit.status);
45715
+ const nestedStatus = readObjectRecord(gitResult.status);
45716
+ const rawProbe = readObjectRecord(node?.lastProbe ?? node?.last_probe);
45717
+ const probeGit = readObjectRecord(rawProbe.git);
45718
+ const probeGitResult = readObjectRecord(probeGit.result);
45719
+ const probeDirectStatus = readObjectRecord(probeGit.status);
45720
+ const probeNestedStatus = readObjectRecord(probeGitResult.status);
45721
+ const status = Object.keys(directStatus).length ? directStatus : Object.keys(nestedStatus).length ? nestedStatus : Object.keys(probeDirectStatus).length ? probeDirectStatus : Object.keys(probeNestedStatus).length ? probeNestedStatus : {};
45722
+ return normalizeInlineMeshGitStatus(status, node, { lastCheckedAt: Date.now() });
45723
+ }
45724
+ function recordInlineMeshDirectGitTruth(node, git, source) {
45725
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
45726
+ const checkedAt = readNumberValue(git.lastCheckedAt) ?? Date.now();
45727
+ const updatedAt = new Date(checkedAt).toISOString();
45728
+ const nextGit = {
45729
+ ...git,
45730
+ lastCheckedAt: checkedAt
45731
+ };
45732
+ node.lastGit = {
45733
+ source,
45734
+ checkedAt,
45735
+ status: nextGit
45736
+ };
45737
+ node.last_git = node.lastGit;
45738
+ node.machineStatus = "online";
45739
+ node.updatedAt = updatedAt;
45740
+ node.lastSeenAt = updatedAt;
45741
+ const repoRoot = readStringValue(nextGit.repoRoot);
45742
+ if (repoRoot && !readStringValue(node.repoRoot)) node.repoRoot = repoRoot;
45743
+ }
45744
+ function buildCachedInlineMeshGitStatus(node) {
45745
+ const liveGit = buildInlineMeshTransitGitStatus(node);
45746
+ if (liveGit) return liveGit;
45747
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
45748
+ const cachedGit = readObjectRecord(cachedStatus.git);
45749
+ if (!Object.keys(cachedGit).length) return void 0;
45750
+ return normalizeInlineMeshGitStatus(cachedGit, node);
45751
+ }
45752
+ function shouldDiscardCachedInlineMeshStatus(node) {
45753
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
45754
+ if (!Object.keys(cachedStatus).length) return false;
45755
+ const cachedGit = readObjectRecord(cachedStatus.git);
45756
+ const workspaceError = readStringValue(cachedStatus.error, node?.error);
45757
+ if (workspaceError && /workspace must be an existing directory/i.test(workspaceError)) return true;
45758
+ const isGitRepo = readBooleanValue(cachedGit.isGitRepo);
45759
+ const branch = readStringValue(cachedGit.branch);
45760
+ const headCommit = readStringValue(cachedGit.headCommit);
45761
+ return isGitRepo === false && !branch && !headCommit;
45762
+ }
45763
+ function stripInlineMeshTransientNodeState(node) {
45764
+ if (!node || typeof node !== "object" || Array.isArray(node)) return node;
45765
+ const {
45766
+ cachedStatus,
45767
+ lastGit: _lastGit,
45768
+ last_git: _lastGitLegacy,
45769
+ lastProbe: _lastProbe,
45770
+ last_probe: _lastProbeLegacy,
45771
+ error: _error,
45772
+ health: _health,
45773
+ machineStatus: _machineStatus,
45774
+ lastSeenAt: _lastSeenAt,
45775
+ last_seen_at: _lastSeenAtLegacy,
45776
+ updatedAt: _updatedAt,
45777
+ updated_at: _updatedAtLegacy,
45778
+ activeSession: _activeSession,
45779
+ active_session: _activeSessionLegacy,
45780
+ activeSessionId: _activeSessionId,
45781
+ active_session_id: _activeSessionIdLegacy,
45782
+ sessionId: _sessionId,
45783
+ session_id: _sessionIdLegacy,
45784
+ providerType: _providerType,
45785
+ provider_type: _providerTypeLegacy,
45786
+ ...rest
45787
+ } = node;
45788
+ if (cachedStatus && !shouldDiscardCachedInlineMeshStatus(node)) {
45789
+ return { ...rest, cachedStatus };
45790
+ }
45791
+ return rest;
45792
+ }
45793
+ function hasInlineMeshTransientNodeState(node) {
45794
+ if (!node || typeof node !== "object" || Array.isArray(node)) return false;
45795
+ return "cachedStatus" in node || "lastGit" in node || "last_git" in node || "lastProbe" in node || "last_probe" in node || "error" in node || "health" in node || "machineStatus" in node || "lastSeenAt" in node || "last_seen_at" in node || "updatedAt" in node || "updated_at" in node || "activeSession" in node || "active_session" in node || "activeSessionId" in node || "active_session_id" in node || "sessionId" in node || "session_id" in node || "providerType" in node || "provider_type" in node;
45796
+ }
45797
+ function inlineMeshCarriesTransientNodeTruth(inlineMesh) {
45798
+ if (!inlineMesh || typeof inlineMesh !== "object" || Array.isArray(inlineMesh)) return false;
45799
+ if (!Array.isArray(inlineMesh.nodes) || inlineMesh.nodes.length === 0) return false;
45800
+ return inlineMesh.nodes.some((node) => hasInlineMeshTransientNodeState(node));
45801
+ }
45802
+ function readInlineMeshNodeId(node) {
45803
+ return readStringValue(node?.id, node?.nodeId) || "";
45804
+ }
45805
+ function sanitizeInlineMesh(inlineMesh) {
45806
+ if (!inlineMesh || typeof inlineMesh !== "object" || Array.isArray(inlineMesh)) return inlineMesh;
45807
+ if (!Array.isArray(inlineMesh.nodes)) return inlineMesh;
45808
+ let changed = false;
45809
+ const nodes = inlineMesh.nodes.map((node) => {
45810
+ if (!hasInlineMeshTransientNodeState(node)) return node;
45811
+ changed = true;
45812
+ return stripInlineMeshTransientNodeState(node);
45813
+ });
45814
+ if (!changed) return inlineMesh;
45815
+ return {
45816
+ ...inlineMesh,
45817
+ nodes
45482
45818
  };
45483
45819
  }
45484
- function applyCachedInlineMeshNodeStatus(status, node) {
45820
+ function reconcileInlineMeshCache(cached2, incoming) {
45821
+ if (!cached2 || typeof cached2 !== "object" || Array.isArray(cached2)) return incoming;
45822
+ if (!incoming || typeof incoming !== "object" || Array.isArray(incoming)) return cached2;
45823
+ const cachedNodes = Array.isArray(cached2.nodes) ? cached2.nodes : [];
45824
+ const incomingNodes = Array.isArray(incoming.nodes) ? incoming.nodes : [];
45825
+ if (!cachedNodes.length || !incomingNodes.length) return { ...cached2, ...incoming };
45826
+ const incomingById = /* @__PURE__ */ new Map();
45827
+ for (const node of incomingNodes) {
45828
+ const nodeId = readInlineMeshNodeId(node);
45829
+ if (nodeId) incomingById.set(nodeId, node);
45830
+ }
45831
+ const nodes = cachedNodes.map((cachedNode) => {
45832
+ const nodeId = readInlineMeshNodeId(cachedNode);
45833
+ const incomingNode = nodeId ? incomingById.get(nodeId) : void 0;
45834
+ if (!incomingNode) return cachedNode;
45835
+ if (hasInlineMeshTransientNodeState(incomingNode)) {
45836
+ return { ...cachedNode, ...incomingNode };
45837
+ }
45838
+ return { ...stripInlineMeshTransientNodeState(cachedNode), ...incomingNode };
45839
+ });
45840
+ return {
45841
+ ...cached2,
45842
+ ...incoming,
45843
+ nodes
45844
+ };
45845
+ }
45846
+ function hasGitWorktreeChanges(git) {
45847
+ if (!git) return false;
45848
+ return Number(git.staged || 0) + Number(git.modified || 0) + Number(git.untracked || 0) + Number(git.deleted || 0) + Number(git.renamed || 0) > 0;
45849
+ }
45850
+ function getGitSubmoduleDriftState(git) {
45851
+ const submodules = Array.isArray(git?.submodules) ? git.submodules : [];
45852
+ let dirty = false;
45853
+ let outOfSync = false;
45854
+ for (const entry of submodules) {
45855
+ const submodule = readObjectRecord(entry);
45856
+ if (readBooleanValue(submodule.dirty) === true) dirty = true;
45857
+ if (readBooleanValue(submodule.outOfSync) === true || !!readStringValue(submodule.error)) outOfSync = true;
45858
+ }
45859
+ return { dirty, outOfSync };
45860
+ }
45861
+ function deriveMeshNodeHealthFromGit(git) {
45862
+ if (!git || readBooleanValue(git.isGitRepo) === false) return "degraded";
45863
+ const branch = readStringValue(git.branch);
45864
+ if (!branch) return "degraded";
45865
+ const submoduleDrift = getGitSubmoduleDriftState(git);
45866
+ if (submoduleDrift.outOfSync) return "degraded";
45867
+ if (submoduleDrift.dirty || hasGitWorktreeChanges(git)) return "dirty";
45868
+ return "online";
45869
+ }
45870
+ function readCachedInlineMeshActiveSessions(node) {
45871
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
45872
+ const activeSession = readObjectRecord(cachedStatus.activeSession);
45873
+ const fallbackSession = Object.keys(activeSession).length ? activeSession : readObjectRecord(node?.activeSession ?? node?.active_session);
45874
+ const sessionId = readStringValue(fallbackSession.id, fallbackSession.sessionId, fallbackSession.session_id, node?.activeSessionId, node?.active_session_id, node?.sessionId, node?.session_id);
45875
+ return sessionId ? [sessionId] : [];
45876
+ }
45877
+ function readCachedInlineMeshActiveSessionDetails(node) {
45485
45878
  const cachedStatus = readObjectRecord(node?.cachedStatus);
45486
- const git = buildCachedInlineMeshGitStatus(node);
45487
- const error48 = readStringValue(cachedStatus.error, node?.error);
45488
- const health = readStringValue(cachedStatus.health, node?.health);
45879
+ const activeSession = readObjectRecord(cachedStatus.activeSession);
45880
+ const fallbackSession = Object.keys(activeSession).length ? activeSession : readObjectRecord(node?.activeSession ?? node?.active_session);
45881
+ const sessionId = readStringValue(
45882
+ fallbackSession.id,
45883
+ fallbackSession.sessionId,
45884
+ fallbackSession.session_id,
45885
+ node?.activeSessionId,
45886
+ node?.active_session_id,
45887
+ node?.sessionId,
45888
+ node?.session_id
45889
+ );
45890
+ if (!sessionId) return [];
45891
+ return [{
45892
+ sessionId,
45893
+ providerType: readStringValue(
45894
+ fallbackSession.providerType,
45895
+ fallbackSession.provider_type,
45896
+ fallbackSession.cliType,
45897
+ fallbackSession.cli_type,
45898
+ fallbackSession.provider,
45899
+ node?.providerType,
45900
+ node?.provider_type
45901
+ ),
45902
+ state: readStringValue(fallbackSession.status, fallbackSession.state, fallbackSession.lifecycle),
45903
+ lifecycle: readStringValue(fallbackSession.lifecycle),
45904
+ title: readStringValue(fallbackSession.title, fallbackSession.displayName, fallbackSession.display_name) ?? null,
45905
+ workspace: readStringValue(fallbackSession.workspace, node?.workspace) ?? null,
45906
+ lastActivityAt: readStringValue(fallbackSession.lastActivityAt, fallbackSession.last_activity_at) ?? null,
45907
+ recoveryState: readStringValue(fallbackSession.recoveryState, fallbackSession.recovery_state) ?? null,
45908
+ isCached: true
45909
+ }];
45910
+ }
45911
+ function readLiveMeshSessionState(record2) {
45912
+ return readStringValue(
45913
+ record2?.meta?.sessionStatus,
45914
+ record2?.meta?.status,
45915
+ record2?.meta?.providerStatus,
45916
+ record2?.status,
45917
+ record2?.state,
45918
+ record2?.lifecycle
45919
+ );
45920
+ }
45921
+ function toIsoTimestamp(value) {
45922
+ if (typeof value === "number" && Number.isFinite(value)) return new Date(value).toISOString();
45923
+ const stringValue = readStringValue(value);
45924
+ return stringValue || null;
45925
+ }
45926
+ function synthesizeMeshNodeFreshnessFromConnection(status) {
45927
+ const connection = readObjectRecord(status.connection);
45928
+ const connectionFreshAt = toIsoTimestamp(connection.lastCommandAt ?? connection.lastConnectedAt ?? connection.lastStateChangeAt);
45929
+ const git = readObjectRecord(status.git);
45930
+ const gitCheckedAt = toIsoTimestamp(git.lastCheckedAt);
45931
+ if (!status.lastSeenAt && connectionFreshAt) status.lastSeenAt = connectionFreshAt;
45932
+ if (!status.updatedAt && (gitCheckedAt || connectionFreshAt)) {
45933
+ status.updatedAt = gitCheckedAt ?? connectionFreshAt;
45934
+ }
45935
+ }
45936
+ function finalizeMeshNodeStatus(args) {
45937
+ const { status, node, daemonId, isSelfNode } = args;
45938
+ if (!readStringValue(status.machineStatus)) {
45939
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
45940
+ const machineStatus = readStringValue(cachedStatus.machineStatus, cachedStatus.machine_status, node?.machineStatus);
45941
+ if (machineStatus) status.machineStatus = machineStatus;
45942
+ }
45943
+ synthesizeMeshNodeFreshnessFromConnection(status);
45944
+ const connectionState = readStringValue(readObjectRecord(status.connection).state);
45945
+ status.launchReady = !!daemonId && (readStringValue(status.machineStatus) === "online" || connectionState === "connected" || isSelfNode);
45946
+ }
45947
+ async function probeRemoteMeshGitStatus(args) {
45948
+ if (!args.dispatchMeshCommand) return null;
45949
+ const remoteResult = await Promise.race([
45950
+ args.dispatchMeshCommand(args.daemonId, "git_status", { workspace: args.workspace }),
45951
+ new Promise((_2, reject) => setTimeout(() => reject(new Error("timeout")), args.timeoutMs))
45952
+ ]);
45953
+ const remoteGit = remoteResult?.status ?? remoteResult?.git ?? remoteResult;
45954
+ return remoteGit && typeof remoteGit === "object" && typeof remoteGit.isGitRepo === "boolean" ? remoteGit : null;
45955
+ }
45956
+ async function hydrateInlineMeshDirectTruth(args) {
45957
+ const nodes = Array.isArray(args.mesh?.nodes) ? args.mesh.nodes : [];
45958
+ if (!nodes.length) {
45959
+ return {
45960
+ directEvidenceCount: 0,
45961
+ localConfirmedCount: 0,
45962
+ peerAttemptedCount: 0,
45963
+ peerConfirmedCount: 0,
45964
+ unavailableNodeIds: []
45965
+ };
45966
+ }
45967
+ const selectedCoordinatorNodeId = readStringValue(
45968
+ args.mesh?.coordinator?.preferredNodeId,
45969
+ nodes[0]?.id,
45970
+ nodes[0]?.nodeId
45971
+ );
45972
+ let localConfirmedCount = 0;
45973
+ let peerAttemptedCount = 0;
45974
+ let peerConfirmedCount = 0;
45975
+ const unavailableNodeIds = [];
45976
+ for (const [nodeIndex, node] of nodes.entries()) {
45977
+ const nodeId = readStringValue(node?.id, node?.nodeId) || `node_${nodeIndex}`;
45978
+ const workspace = readStringValue(node?.workspace);
45979
+ const daemonId = readStringValue(node?.daemonId);
45980
+ const isSelfNode = Boolean(
45981
+ nodeId && selectedCoordinatorNodeId && nodeId === selectedCoordinatorNodeId
45982
+ ) || Boolean(
45983
+ daemonId && (daemonId === args.localMachineId || daemonId === args.statusInstanceId)
45984
+ ) || Boolean(args.meshSource !== "local_config" && nodeIndex === 0);
45985
+ if (!workspace) {
45986
+ if (!isSelfNode && daemonId) unavailableNodeIds.push(nodeId);
45987
+ continue;
45988
+ }
45989
+ if (isSelfNode && fs10.existsSync(workspace)) {
45990
+ try {
45991
+ const localGit = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
45992
+ if (localGit?.isGitRepo) {
45993
+ recordInlineMeshDirectGitTruth(node, localGit, "selected_coordinator_local_git");
45994
+ localConfirmedCount += 1;
45995
+ continue;
45996
+ }
45997
+ } catch {
45998
+ }
45999
+ }
46000
+ if (!daemonId || !args.dispatchMeshCommand) {
46001
+ if (!isSelfNode) unavailableNodeIds.push(nodeId);
46002
+ continue;
46003
+ }
46004
+ peerAttemptedCount += 1;
46005
+ try {
46006
+ const remoteGit = await probeRemoteMeshGitStatus({
46007
+ dispatchMeshCommand: args.dispatchMeshCommand,
46008
+ daemonId,
46009
+ workspace,
46010
+ timeoutMs: 8e3
46011
+ });
46012
+ if (remoteGit) {
46013
+ recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
46014
+ peerConfirmedCount += 1;
46015
+ continue;
46016
+ }
46017
+ } catch {
46018
+ }
46019
+ unavailableNodeIds.push(nodeId);
46020
+ }
46021
+ return {
46022
+ directEvidenceCount: localConfirmedCount + peerConfirmedCount,
46023
+ localConfirmedCount,
46024
+ peerAttemptedCount,
46025
+ peerConfirmedCount,
46026
+ unavailableNodeIds
46027
+ };
46028
+ }
46029
+ function summarizeMeshSessionRecord(record2) {
46030
+ return {
46031
+ sessionId: readStringValue(record2?.sessionId) || "unknown",
46032
+ providerType: readStringValue(record2?.providerType),
46033
+ state: readLiveMeshSessionState(record2),
46034
+ lifecycle: readStringValue(record2?.lifecycle),
46035
+ surfaceKind: getSessionHostSurfaceKind(record2),
46036
+ recoveryState: readStringValue(record2?.meta?.runtimeRecoveryState) ?? null,
46037
+ workspace: readStringValue(record2?.workspace) ?? null,
46038
+ title: readStringValue(record2?.displayName, record2?.workspaceLabel) ?? null,
46039
+ lastActivityAt: toIsoTimestamp(record2?.updatedAt ?? record2?.lastActivityAt ?? record2?.last_activity_at),
46040
+ isCached: false
46041
+ };
46042
+ }
46043
+ function liveSessionRecordMatchesMeshNode(record2, meshId, nodeId) {
46044
+ const recordNodeId = readStringValue(record2?.meta?.meshNodeId);
46045
+ if (!recordNodeId || recordNodeId !== nodeId) return false;
46046
+ const recordMeshId = readStringValue(record2?.meta?.meshNodeFor);
46047
+ return !recordMeshId || recordMeshId === meshId;
46048
+ }
46049
+ function liveSessionRecordMatchesMeshWorkspace(record2, meshId, workspace) {
46050
+ const recordWorkspace = readStringValue(record2?.workspace);
46051
+ if (!recordWorkspace || !workspace || recordWorkspace !== workspace) return false;
46052
+ const recordMeshId = readStringValue(record2?.meta?.meshNodeFor);
46053
+ if (recordMeshId) return recordMeshId === meshId;
46054
+ return record2?.meta?.launchedByCoordinator === true || !!readStringValue(record2?.meta?.meshNodeId);
46055
+ }
46056
+ function readLiveMeshNodeWorkspace(args) {
46057
+ const directNodeWorkspace = args.liveSessionRecords.find((record2) => liveSessionRecordMatchesMeshNode(record2, args.meshId, args.nodeId) && readStringValue(record2?.workspace));
46058
+ if (directNodeWorkspace) {
46059
+ return readStringValue(directNodeWorkspace.workspace) || "";
46060
+ }
46061
+ if (args.allowCoordinatorSession) {
46062
+ const coordinatorWorkspace = args.liveSessionRecords.find((record2) => readStringValue(record2?.meta?.meshCoordinatorFor) === args.meshId && readStringValue(record2?.workspace));
46063
+ if (coordinatorWorkspace) {
46064
+ return readStringValue(coordinatorWorkspace.workspace) || "";
46065
+ }
46066
+ }
46067
+ return "";
46068
+ }
46069
+ function collectLiveMeshSessionRecords(args) {
46070
+ const matches = args.liveSessionRecords.filter((record2) => {
46071
+ const nodeWorkspace = readStringValue(args.node?.workspace);
46072
+ if (liveSessionRecordMatchesMeshNode(record2, args.meshId, args.nodeId)) return true;
46073
+ return !!nodeWorkspace && liveSessionRecordMatchesMeshWorkspace(record2, args.meshId, nodeWorkspace);
46074
+ });
46075
+ if (args.allowCoordinatorSession) {
46076
+ for (const record2 of args.liveSessionRecords) {
46077
+ if (readStringValue(record2?.meta?.meshCoordinatorFor) !== args.meshId) continue;
46078
+ const sessionId = readStringValue(record2?.sessionId);
46079
+ if (sessionId && matches.some((entry) => readStringValue(entry?.sessionId) === sessionId)) continue;
46080
+ matches.push(record2);
46081
+ }
46082
+ }
46083
+ return matches;
46084
+ }
46085
+ function applyCachedInlineMeshNodeStatus(status, node, options) {
46086
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
46087
+ const liveGit = buildInlineMeshTransitGitStatus(node);
46088
+ const git = options?.skipGit ? void 0 : liveGit ?? buildCachedInlineMeshGitStatus(node);
46089
+ const error48 = options?.skipError ? void 0 : liveGit ? void 0 : readStringValue(cachedStatus.error, node?.error);
46090
+ const health = options?.skipHealth ? void 0 : liveGit ? void 0 : readStringValue(cachedStatus.health, node?.health);
45489
46091
  const machineStatus = readStringValue(cachedStatus.machineStatus, node?.machineStatus);
45490
- if (!git && !error48 && !health) return false;
45491
- if (!machineStatus && !git && !error48) return false;
46092
+ const lastSeenAt = toIsoTimestamp(cachedStatus.lastSeenAt ?? cachedStatus.last_seen_at ?? node?.lastSeenAt ?? node?.last_seen_at);
46093
+ const updatedAt = toIsoTimestamp(cachedStatus.updatedAt ?? cachedStatus.updated_at ?? node?.updatedAt ?? node?.updated_at);
46094
+ const activeSessions = readCachedInlineMeshActiveSessions(node);
46095
+ const activeSessionDetails = readCachedInlineMeshActiveSessionDetails(node);
46096
+ if (!git && !error48 && !health && !machineStatus && !lastSeenAt && !updatedAt && activeSessions.length === 0) return false;
45492
46097
  if (git) status.git = git;
45493
46098
  if (error48) status.error = error48;
46099
+ if (machineStatus) status.machineStatus = machineStatus;
46100
+ if (lastSeenAt) status.lastSeenAt = lastSeenAt;
46101
+ if (updatedAt) status.updatedAt = updatedAt;
46102
+ if (activeSessions.length > 0) status.activeSessions = activeSessions;
46103
+ if (activeSessionDetails.length > 0) status.activeSessionDetails = activeSessionDetails;
45494
46104
  if (health) {
45495
46105
  status.health = health;
45496
46106
  return true;
45497
46107
  }
45498
46108
  if (git) {
45499
- const dirty = Number(git.staged || 0) + Number(git.modified || 0) + Number(git.untracked || 0) + Number(git.deleted || 0) + Number(git.renamed || 0) > 0;
45500
- status.health = git.isGitRepo === false ? "degraded" : dirty ? "dirty" : "online";
46109
+ status.health = deriveMeshNodeHealthFromGit(git);
45501
46110
  return true;
45502
46111
  }
45503
- return false;
46112
+ return activeSessions.length > 0 || !!machineStatus || !!lastSeenAt || !!updatedAt;
45504
46113
  }
45505
46114
  async function resolveProviderTypeFromPriority(args) {
45506
46115
  if (!args.providerPriority.length) {
@@ -45531,9 +46140,85 @@ function truncateValidationOutput(value) {
45531
46140
  return `${text.slice(0, REFINE_VALIDATION_SUMMARY_CHARS)}
45532
46141
  [truncated ${text.length - REFINE_VALIDATION_SUMMARY_CHARS} chars]`;
45533
46142
  }
46143
+ function recordMeshRefineStage(stages, stage, status, startedAt, details) {
46144
+ stages.push({
46145
+ stage,
46146
+ status,
46147
+ durationMs: Date.now() - startedAt,
46148
+ ...details || {}
46149
+ });
46150
+ }
46151
+ async function computeGitPatchId(cwd, fromRef, toRef) {
46152
+ const { execFileSync: execFileSync6 } = await import("child_process");
46153
+ const diff = execFileSync6("git", ["diff", "--patch", "--full-index", fromRef, toRef], {
46154
+ cwd,
46155
+ encoding: "utf8",
46156
+ maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
46157
+ });
46158
+ if (!diff.trim()) return "";
46159
+ const patchId = execFileSync6("git", ["patch-id", "--stable"], {
46160
+ cwd,
46161
+ input: diff,
46162
+ encoding: "utf8",
46163
+ maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
46164
+ }).trim();
46165
+ return patchId.split(/\s+/)[0] || "";
46166
+ }
46167
+ async function runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead) {
46168
+ const startedAt = Date.now();
46169
+ try {
46170
+ const { execFileSync: execFileSync6 } = await import("child_process");
46171
+ const git = (args) => execFileSync6("git", args, {
46172
+ cwd: repoRoot,
46173
+ encoding: "utf8",
46174
+ maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
46175
+ });
46176
+ const mergeBase = git(["merge-base", baseHead, branchHead]).trim();
46177
+ const mergeTreeStdout = git(["merge-tree", "--write-tree", baseHead, branchHead]);
46178
+ const mergedTree = mergeTreeStdout.trim().split(/\s+/)[0] || "";
46179
+ if (!mergeBase || !mergedTree) {
46180
+ return {
46181
+ status: "failed",
46182
+ equivalent: false,
46183
+ baseHead,
46184
+ branchHead,
46185
+ mergeBase: mergeBase || void 0,
46186
+ mergedTree: mergedTree || void 0,
46187
+ durationMs: Date.now() - startedAt,
46188
+ error: "patch equivalence preflight could not resolve merge-base or synthetic merge tree",
46189
+ stdout: truncateValidationOutput(mergeTreeStdout)
46190
+ };
46191
+ }
46192
+ const expectedPatchId = await computeGitPatchId(repoRoot, mergeBase, branchHead);
46193
+ const actualPatchId = await computeGitPatchId(repoRoot, baseHead, mergedTree);
46194
+ const equivalent = expectedPatchId === actualPatchId;
46195
+ return {
46196
+ status: equivalent ? "passed" : "failed",
46197
+ equivalent,
46198
+ baseHead,
46199
+ branchHead,
46200
+ mergeBase,
46201
+ mergedTree,
46202
+ expectedPatchId,
46203
+ actualPatchId,
46204
+ durationMs: Date.now() - startedAt
46205
+ };
46206
+ } catch (e) {
46207
+ return {
46208
+ status: "failed",
46209
+ equivalent: false,
46210
+ baseHead,
46211
+ branchHead,
46212
+ durationMs: Date.now() - startedAt,
46213
+ error: e?.message || String(e),
46214
+ stdout: truncateValidationOutput(e?.stdout),
46215
+ stderr: truncateValidationOutput(e?.stderr)
46216
+ };
46217
+ }
46218
+ }
45534
46219
  function readPackageScripts(workspace) {
45535
46220
  try {
45536
- const packageJsonPath = (0, import_path6.join)(workspace, "package.json");
46221
+ const packageJsonPath = (0, import_path7.join)(workspace, "package.json");
45537
46222
  const parsed = JSON.parse(fs10.readFileSync(packageJsonPath, "utf-8"));
45538
46223
  return parsed?.scripts && typeof parsed.scripts === "object" && !Array.isArray(parsed.scripts) ? parsed.scripts : {};
45539
46224
  } catch {
@@ -45741,13 +46426,13 @@ function serializeMeshCoordinatorMcpConfig(config2, format) {
45741
46426
  }
45742
46427
  function resolveHermesUserHome() {
45743
46428
  const explicitHome = process.env.HERMES_HOME?.trim();
45744
- return explicitHome || (0, import_path6.join)((0, import_os4.homedir)(), ".hermes");
46429
+ return explicitHome || (0, import_path7.join)((0, import_os4.homedir)(), ".hermes");
45745
46430
  }
45746
46431
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
45747
46432
  const sourceHome = resolveHermesUserHome();
45748
- const sourceConfigPath = (0, import_path6.join)(sourceHome, "config.yaml");
46433
+ const sourceConfigPath = (0, import_path7.join)(sourceHome, "config.yaml");
45749
46434
  if (!fs10.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
45750
- if ((0, import_path6.resolve)(sourceConfigPath) === (0, import_path6.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
46435
+ if ((0, import_path7.resolve)(sourceConfigPath) === (0, import_path7.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
45751
46436
  const parsed = parseMeshCoordinatorMcpConfig(fs10.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
45752
46437
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
45753
46438
  return { config: baseConfig, sourceHome, sourceConfigPath };
@@ -45781,10 +46466,10 @@ function stripHermesCoordinatorTempModelProviderOverrides(config2) {
45781
46466
  return sanitized;
45782
46467
  }
45783
46468
  function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
45784
- if ((0, import_path6.resolve)(sourceHome) === (0, import_path6.resolve)(targetHome)) return;
46469
+ if ((0, import_path7.resolve)(sourceHome) === (0, import_path7.resolve)(targetHome)) return;
45785
46470
  for (const fileName of [".env", "auth.json"]) {
45786
- const sourcePath = (0, import_path6.join)(sourceHome, fileName);
45787
- const targetPath = (0, import_path6.join)(targetHome, fileName);
46471
+ const sourcePath = (0, import_path7.join)(sourceHome, fileName);
46472
+ const targetPath = (0, import_path7.join)(targetHome, fileName);
45788
46473
  if (!fs10.existsSync(sourcePath)) continue;
45789
46474
  try {
45790
46475
  fs10.copyFileSync(sourcePath, targetPath);
@@ -45874,7 +46559,7 @@ function summarizeSessionHostPruneResult(result) {
45874
46559
  keptCount: Array.isArray(value.keptSessionIds) ? value.keptSessionIds.length : void 0
45875
46560
  };
45876
46561
  }
45877
- var import_os4, import_path6, fs10, CHANNEL_NPM_TAG, CHANNEL_SERVER_URL, REFINE_VALIDATION_CATEGORIES, REFINE_VALIDATION_TIMEOUT_MS, REFINE_VALIDATION_OUTPUT_LIMIT_BYTES, REFINE_VALIDATION_SUMMARY_CHARS, REFINE_VALIDATION_MAX_COMMANDS, CHAT_COMMANDS, READ_DEBUG_ENABLED2, DaemonCommandRouter;
46562
+ var import_os4, import_path7, fs10, CHANNEL_NPM_TAG, CHANNEL_SERVER_URL, REFINE_VALIDATION_CATEGORIES, REFINE_VALIDATION_TIMEOUT_MS, REFINE_VALIDATION_OUTPUT_LIMIT_BYTES, REFINE_VALIDATION_SUMMARY_CHARS, REFINE_VALIDATION_MAX_COMMANDS, REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES, CHAT_COMMANDS, READ_DEBUG_ENABLED2, DaemonCommandRouter;
45878
46563
  var init_router = __esm({
45879
46564
  "../../oss/packages/daemon-core/src/commands/router.ts"() {
45880
46565
  "use strict";
@@ -45890,6 +46575,7 @@ var init_router = __esm({
45890
46575
  init_chat_history();
45891
46576
  init_ide_detector();
45892
46577
  init_cli_detector();
46578
+ init_git_status();
45893
46579
  init_logger();
45894
46580
  init_command_log();
45895
46581
  init_js_yaml();
@@ -45903,7 +46589,7 @@ var init_router = __esm({
45903
46589
  init_snapshot();
45904
46590
  init_upgrade_helper();
45905
46591
  import_os4 = require("os");
45906
- import_path6 = require("path");
46592
+ import_path7 = require("path");
45907
46593
  fs10 = __toESM(require("fs"));
45908
46594
  CHANNEL_NPM_TAG = { stable: "latest", preview: "next" };
45909
46595
  CHANNEL_SERVER_URL = {
@@ -45915,6 +46601,7 @@ var init_router = __esm({
45915
46601
  REFINE_VALIDATION_OUTPUT_LIMIT_BYTES = 128 * 1024;
45916
46602
  REFINE_VALIDATION_SUMMARY_CHARS = 2e3;
45917
46603
  REFINE_VALIDATION_MAX_COMMANDS = 4;
46604
+ REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES = 4 * 1024 * 1024;
45918
46605
  CHAT_COMMANDS = [
45919
46606
  "send_chat",
45920
46607
  "new_chat",
@@ -45929,30 +46616,97 @@ var init_router = __esm({
45929
46616
  * Allows the MCP server to query mesh data via get_mesh even when
45930
46617
  * the mesh doesn't exist in the local meshes.json file. */
45931
46618
  inlineMeshCache = /* @__PURE__ */ new Map();
46619
+ /** Coordinator-owned whole-mesh aggregate status snapshots. Browser callers read this by default. */
46620
+ aggregateMeshStatusCache = /* @__PURE__ */ new Map();
45932
46621
  constructor(deps) {
45933
46622
  this.deps = deps;
45934
46623
  }
46624
+ cloneJsonValue(value) {
46625
+ if (typeof structuredClone === "function") return structuredClone(value);
46626
+ return JSON.parse(JSON.stringify(value));
46627
+ }
46628
+ getCachedAggregateMeshStatus(meshId) {
46629
+ const cached2 = this.aggregateMeshStatusCache.get(meshId);
46630
+ if (!cached2?.snapshot || cached2.snapshot.success !== true || !Array.isArray(cached2.snapshot.nodes)) return null;
46631
+ const snapshot = this.cloneJsonValue(cached2.snapshot);
46632
+ const ageMs = Math.max(0, Date.now() - cached2.builtAt);
46633
+ const sourceOfTruth = snapshot.sourceOfTruth && typeof snapshot.sourceOfTruth === "object" ? snapshot.sourceOfTruth : {};
46634
+ snapshot.sourceOfTruth = {
46635
+ ...sourceOfTruth,
46636
+ aggregateSnapshot: {
46637
+ ...sourceOfTruth.aggregateSnapshot && typeof sourceOfTruth.aggregateSnapshot === "object" ? sourceOfTruth.aggregateSnapshot : {},
46638
+ owner: "coordinator_daemon_memory",
46639
+ cached: true,
46640
+ source: "memory",
46641
+ refreshReason: "memory_cache_hit",
46642
+ ageMs,
46643
+ cachedAt: new Date(cached2.builtAt).toISOString(),
46644
+ returnedAt: (/* @__PURE__ */ new Date()).toISOString()
46645
+ }
46646
+ };
46647
+ return snapshot;
46648
+ }
46649
+ rememberAggregateMeshStatus(meshId, snapshot, refreshReason) {
46650
+ if (!snapshot || typeof snapshot !== "object" || snapshot.success !== true || !Array.isArray(snapshot.nodes)) return snapshot;
46651
+ const builtAt = Date.now();
46652
+ const next = this.cloneJsonValue(snapshot);
46653
+ const sourceOfTruth = next.sourceOfTruth && typeof next.sourceOfTruth === "object" ? next.sourceOfTruth : {};
46654
+ next.sourceOfTruth = {
46655
+ ...sourceOfTruth,
46656
+ aggregateSnapshot: {
46657
+ owner: "coordinator_daemon_memory",
46658
+ cached: false,
46659
+ source: "live_refresh",
46660
+ refreshReason,
46661
+ ageMs: 0,
46662
+ cachedAt: new Date(builtAt).toISOString(),
46663
+ returnedAt: new Date(builtAt).toISOString()
46664
+ }
46665
+ };
46666
+ this.aggregateMeshStatusCache.set(meshId, { builtAt, snapshot: this.cloneJsonValue(next) });
46667
+ return next;
46668
+ }
45935
46669
  getCachedInlineMesh(meshId, inlineMesh) {
45936
46670
  if (inlineMesh && typeof inlineMesh === "object") {
45937
- this.inlineMeshCache.set(meshId, inlineMesh);
45938
- return inlineMesh;
46671
+ return this.warmInlineMeshCache(meshId, inlineMesh);
45939
46672
  }
45940
46673
  return this.inlineMeshCache.get(meshId);
45941
46674
  }
46675
+ warmInlineMeshCache(meshId, inlineMesh) {
46676
+ if (!inlineMesh || typeof inlineMesh !== "object") return void 0;
46677
+ const sanitizedInlineMesh = sanitizeInlineMesh(inlineMesh);
46678
+ const cached2 = this.inlineMeshCache.get(meshId);
46679
+ if (cached2) {
46680
+ const merged = reconcileInlineMeshCache(cached2, sanitizedInlineMesh);
46681
+ this.inlineMeshCache.set(meshId, merged);
46682
+ return merged;
46683
+ }
46684
+ this.inlineMeshCache.set(meshId, sanitizedInlineMesh);
46685
+ return sanitizedInlineMesh;
46686
+ }
45942
46687
  async getMeshForCommand(meshId, inlineMesh, options) {
45943
46688
  const preferInline = options?.preferInline === true;
45944
46689
  if (preferInline) {
45945
- const cached3 = this.getCachedInlineMesh(meshId, inlineMesh);
45946
- if (cached3) return { mesh: cached3, inline: true };
46690
+ const cached3 = this.getCachedInlineMesh(meshId);
46691
+ if (cached3) return { mesh: cached3, inline: true, source: "inline_cache" };
46692
+ if (inlineMeshCarriesTransientNodeTruth(inlineMesh)) {
46693
+ this.warmInlineMeshCache(meshId, inlineMesh);
46694
+ return { mesh: inlineMesh, inline: true, source: "inline_bootstrap" };
46695
+ }
45947
46696
  }
45948
46697
  try {
45949
46698
  const { getMesh: getMesh3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
45950
46699
  const mesh = getMesh3(meshId);
45951
- if (mesh) return { mesh, inline: false };
46700
+ if (mesh) return { mesh, inline: false, source: "local_config" };
45952
46701
  } catch {
45953
46702
  }
45954
- const cached2 = this.getCachedInlineMesh(meshId, inlineMesh);
45955
- return cached2 ? { mesh: cached2, inline: true } : null;
46703
+ const cached2 = this.getCachedInlineMesh(meshId);
46704
+ if (cached2) return { mesh: cached2, inline: true, source: "inline_cache" };
46705
+ const warmedInline = this.warmInlineMeshCache(meshId, inlineMesh);
46706
+ return warmedInline ? { mesh: warmedInline, inline: true, source: "inline_bootstrap" } : null;
46707
+ }
46708
+ invalidateAggregateMeshStatus(meshId) {
46709
+ this.aggregateMeshStatusCache.delete(meshId);
45956
46710
  }
45957
46711
  updateInlineMeshNode(meshId, mesh, node) {
45958
46712
  if (!mesh || !Array.isArray(mesh.nodes) || !node?.id) return;
@@ -45961,6 +46715,7 @@ var init_router = __esm({
45961
46715
  else mesh.nodes.push(node);
45962
46716
  mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
45963
46717
  this.inlineMeshCache.set(meshId, mesh);
46718
+ this.invalidateAggregateMeshStatus(meshId);
45964
46719
  }
45965
46720
  removeInlineMeshNode(meshId, mesh, nodeId) {
45966
46721
  if (!mesh || !Array.isArray(mesh.nodes)) return false;
@@ -45969,6 +46724,7 @@ var init_router = __esm({
45969
46724
  mesh.nodes.splice(idx, 1);
45970
46725
  mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
45971
46726
  this.inlineMeshCache.set(meshId, mesh);
46727
+ this.invalidateAggregateMeshStatus(meshId);
45972
46728
  return true;
45973
46729
  }
45974
46730
  normalizeMeshSessionCleanupMode(value) {
@@ -46017,7 +46773,7 @@ var init_router = __esm({
46017
46773
  }
46018
46774
  const { resolveWorktreePath: resolveWorktreePath2, listWorktrees: listWorktrees2, removeWorktree: removeWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
46019
46775
  const normalizePath2 = (value) => {
46020
- const resolved = (0, import_path6.resolve)(value);
46776
+ const resolved = (0, import_path7.resolve)(value);
46021
46777
  try {
46022
46778
  return fs10.realpathSync(resolved);
46023
46779
  } catch {
@@ -46181,6 +46937,7 @@ var init_router = __esm({
46181
46937
  const deletedSessionIds = [];
46182
46938
  const skippedSessionIds = [];
46183
46939
  const skippedLiveSessionIds = [];
46940
+ const skippedCoordinatorSessionIds = [];
46184
46941
  const deleteUnsupportedSessionIds = [];
46185
46942
  const recordsRemainSessionIds = [];
46186
46943
  const errors = [];
@@ -46213,6 +46970,12 @@ var init_router = __esm({
46213
46970
  const completed = this.isCompletedHostedSession(record2);
46214
46971
  const surfaceKind = getSessionHostSurfaceKind(record2);
46215
46972
  const liveRuntime = surfaceKind === "live_runtime";
46973
+ const coordinatorSession = readStringValue(record2?.meta?.meshCoordinatorFor) === args.meshId;
46974
+ if (!hasExplicitSessionIds && coordinatorSession) {
46975
+ skippedSessionIds.push(sessionId);
46976
+ skippedCoordinatorSessionIds.push(sessionId);
46977
+ continue;
46978
+ }
46216
46979
  if (!hasExplicitSessionIds && liveRuntime) {
46217
46980
  skippedSessionIds.push(sessionId);
46218
46981
  skippedLiveSessionIds.push(sessionId);
@@ -46278,6 +47041,7 @@ var init_router = __esm({
46278
47041
  deletedSessionIds,
46279
47042
  skippedSessionIds,
46280
47043
  skippedLiveSessionIds,
47044
+ skippedCoordinatorSessionIds,
46281
47045
  ...deleteUnsupported ? {
46282
47046
  deleteUnsupported: true,
46283
47047
  effectiveCleanup: args.mode === "stop_and_delete" ? "stopped_only_records_remain" : "delete_unsupported_records_remain",
@@ -46410,7 +47174,8 @@ var init_router = __esm({
46410
47174
  return handleMeshForwardEvent({ instanceManager: this.deps.instanceManager }, args);
46411
47175
  }
46412
47176
  case "get_pending_mesh_events": {
46413
- const events = drainPendingMeshCoordinatorEvents();
47177
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47178
+ const events = drainPendingMeshCoordinatorEvents(meshId || void 0);
46414
47179
  return { success: true, events };
46415
47180
  }
46416
47181
  case "launch_cli":
@@ -46939,15 +47704,39 @@ var init_router = __esm({
46939
47704
  case "get_mesh": {
46940
47705
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46941
47706
  if (!meshId) return { success: false, error: "meshId required" };
46942
- try {
46943
- const { getMesh: getMesh3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46944
- const mesh = getMesh3(meshId);
46945
- if (mesh) return { success: true, mesh };
46946
- } catch {
47707
+ const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
47708
+ if (!meshRecord?.mesh) return { success: false, error: "Mesh not found" };
47709
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
47710
+ const directTruth = await hydrateInlineMeshDirectTruth({
47711
+ mesh: meshRecord.mesh,
47712
+ meshSource: meshRecord.source,
47713
+ dispatchMeshCommand: this.deps.dispatchMeshCommand,
47714
+ statusInstanceId: this.deps.statusInstanceId,
47715
+ localMachineId: loadConfig().machineId || ""
47716
+ });
47717
+ const directTruthSatisfied = meshRecord.source !== "inline_bootstrap" || directTruth.directEvidenceCount > 0;
47718
+ const sourceOfTruth = {
47719
+ membership: meshRecord.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
47720
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
47721
+ directPeerTruth: {
47722
+ required: requireDirectPeerTruth,
47723
+ satisfied: directTruthSatisfied,
47724
+ directEvidenceCount: directTruth.directEvidenceCount,
47725
+ localConfirmedCount: directTruth.localConfirmedCount,
47726
+ peerAttemptedCount: directTruth.peerAttemptedCount,
47727
+ peerConfirmedCount: directTruth.peerConfirmedCount,
47728
+ unavailableNodeIds: directTruth.unavailableNodeIds
47729
+ }
47730
+ };
47731
+ if (requireDirectPeerTruth && !directTruthSatisfied) {
47732
+ return {
47733
+ success: false,
47734
+ code: "mesh_direct_peer_truth_unavailable",
47735
+ error: "Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct get_mesh probes succeed.",
47736
+ sourceOfTruth
47737
+ };
46947
47738
  }
46948
- const cached2 = this.inlineMeshCache.get(meshId);
46949
- if (cached2) return { success: true, mesh: cached2 };
46950
- return { success: false, error: "Mesh not found" };
47739
+ return { success: true, mesh: meshRecord.mesh, sourceOfTruth };
46951
47740
  }
46952
47741
  case "create_mesh": {
46953
47742
  const name = typeof args?.name === "string" ? args.name.trim() : "";
@@ -46977,6 +47766,7 @@ var init_router = __esm({
46977
47766
  const mesh = updateMesh2(meshId, patch);
46978
47767
  if (!mesh) return { success: false, error: "Mesh not found" };
46979
47768
  this.inlineMeshCache.set(meshId, mesh);
47769
+ this.invalidateAggregateMeshStatus(meshId);
46980
47770
  return { success: true, mesh };
46981
47771
  } catch (e) {
46982
47772
  return { success: false, error: e.message };
@@ -47166,26 +47956,41 @@ var init_router = __esm({
47166
47956
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47167
47957
  const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
47168
47958
  if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
47959
+ const refineStages = [];
47169
47960
  try {
47170
47961
  const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh);
47171
47962
  const mesh = meshRecord?.mesh;
47172
47963
  const node = mesh?.nodes?.find((n) => n.id === nodeId || n.nodeId === nodeId);
47173
- if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
47964
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh`, refineStages };
47174
47965
  if (!node.isLocalWorktree || !node.workspace) {
47175
- return { success: false, error: `Refinery requires a local worktree node` };
47966
+ return { success: false, error: `Refinery requires a local worktree node`, refineStages };
47176
47967
  }
47177
47968
  const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => n.id === node.clonedFromNodeId || n.nodeId === node.clonedFromNodeId) : mesh?.nodes.find((n) => !n.isLocalWorktree);
47178
47969
  const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
47179
- if (!repoRoot) return { success: false, error: "Source node repoRoot not found" };
47970
+ if (!repoRoot) return { success: false, error: "Source node repoRoot not found", refineStages };
47180
47971
  const { execFile: execFile3 } = await import("child_process");
47181
47972
  const { promisify: promisify3 } = await import("util");
47182
47973
  const execFileAsync3 = promisify3(execFile3);
47974
+ const resolveStarted = Date.now();
47183
47975
  const { stdout: branchStdout } = await execFileAsync3("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8" });
47184
47976
  const branch = branchStdout.trim();
47185
- if (!branch) return { success: false, error: "Could not determine branch of the worktree node" };
47977
+ if (!branch) return { success: false, error: "Could not determine branch of the worktree node", refineStages };
47186
47978
  const { stdout: baseBranchStdout } = await execFileAsync3("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8" });
47187
47979
  const baseBranch = baseBranchStdout.trim();
47980
+ const { stdout: baseHeadStdout } = await execFileAsync3("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" });
47981
+ const { stdout: branchHeadStdout } = await execFileAsync3("git", ["rev-parse", branch], { cwd: node.workspace, encoding: "utf8" });
47982
+ const baseHead = baseHeadStdout.trim();
47983
+ const branchHead = branchHeadStdout.trim();
47984
+ recordMeshRefineStage(refineStages, "resolve_refs", "passed", resolveStarted, { branch, baseBranch, baseHead, branchHead });
47985
+ const validationStarted = Date.now();
47188
47986
  const validationSummary = await runMeshRefineValidationGate(mesh, node.workspace);
47987
+ recordMeshRefineStage(
47988
+ refineStages,
47989
+ "validation",
47990
+ validationSummary.status === "passed" ? "passed" : validationSummary.status === "failed" ? "failed" : "skipped",
47991
+ validationStarted,
47992
+ { validationStatus: validationSummary.status, commandsRun: validationSummary.commandsRun.length }
47993
+ );
47189
47994
  if (validationSummary.status === "failed") {
47190
47995
  return {
47191
47996
  success: false,
@@ -47195,6 +48000,7 @@ var init_router = __esm({
47195
48000
  branch,
47196
48001
  into: baseBranch,
47197
48002
  validationSummary,
48003
+ refineStages,
47198
48004
  finalBranchConvergenceState: {
47199
48005
  branch,
47200
48006
  baseBranch,
@@ -47214,6 +48020,7 @@ var init_router = __esm({
47214
48020
  branch,
47215
48021
  into: baseBranch,
47216
48022
  validationSummary,
48023
+ refineStages,
47217
48024
  finalBranchConvergenceState: {
47218
48025
  branch,
47219
48026
  baseBranch,
@@ -47224,37 +48031,121 @@ var init_router = __esm({
47224
48031
  }
47225
48032
  };
47226
48033
  }
48034
+ const patchEquivalenceStarted = Date.now();
48035
+ const patchEquivalence = await runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead);
48036
+ recordMeshRefineStage(refineStages, "patch_equivalence", patchEquivalence.status, patchEquivalenceStarted, {
48037
+ equivalent: patchEquivalence.equivalent,
48038
+ expectedPatchId: patchEquivalence.expectedPatchId,
48039
+ actualPatchId: patchEquivalence.actualPatchId,
48040
+ error: patchEquivalence.error
48041
+ });
48042
+ if (!patchEquivalence.equivalent) {
48043
+ return {
48044
+ success: false,
48045
+ code: "patch_equivalence_failed",
48046
+ convergenceStatus: "blocked_review",
48047
+ error: "Refinery patch-equivalence preflight failed; merge/refine was not attempted.",
48048
+ branch,
48049
+ into: baseBranch,
48050
+ validationSummary,
48051
+ patchEquivalence,
48052
+ refineStages,
48053
+ finalBranchConvergenceState: {
48054
+ branch,
48055
+ baseBranch,
48056
+ merged: false,
48057
+ removed: false,
48058
+ validation: "passed",
48059
+ patchEquivalence: "failed",
48060
+ status: "blocked_review"
48061
+ }
48062
+ };
48063
+ }
48064
+ let mergeResult;
48065
+ const mergeStarted = Date.now();
47227
48066
  try {
47228
- await execFileAsync3("git", ["merge", "--no-ff", branch, "-m", `Auto-merge branch '${branch}' via Refinery`], { cwd: repoRoot, encoding: "utf8" });
48067
+ const result = await execFileAsync3("git", ["merge", "--no-ff", branch, "-m", `Auto-merge branch '${branch}' via Refinery`], { cwd: repoRoot, encoding: "utf8" });
48068
+ mergeResult = {
48069
+ stdout: truncateValidationOutput(result.stdout),
48070
+ stderr: truncateValidationOutput(result.stderr),
48071
+ durationMs: Date.now() - mergeStarted
48072
+ };
48073
+ recordMeshRefineStage(refineStages, "merge", "passed", mergeStarted, mergeResult);
47229
48074
  } catch (e) {
48075
+ recordMeshRefineStage(refineStages, "merge", "failed", mergeStarted, {
48076
+ error: e?.message || String(e),
48077
+ stdout: truncateValidationOutput(e?.stdout),
48078
+ stderr: truncateValidationOutput(e?.stderr)
48079
+ });
47230
48080
  return {
47231
48081
  success: false,
47232
48082
  error: `Merge failed (conflicts?): ${e.message}`,
47233
48083
  validationSummary,
48084
+ patchEquivalence,
48085
+ refineStages,
47234
48086
  finalBranchConvergenceState: {
47235
48087
  branch,
47236
48088
  baseBranch,
47237
48089
  merged: false,
47238
48090
  removed: false,
47239
48091
  validation: "passed",
48092
+ patchEquivalence: "passed",
47240
48093
  status: "not_mergeable"
47241
48094
  }
47242
48095
  };
47243
48096
  }
48097
+ const cleanupStarted = Date.now();
47244
48098
  const removeResult = await this.execute("remove_mesh_node", {
47245
48099
  meshId,
47246
48100
  nodeId,
47247
- sessionCleanupMode: "kill",
48101
+ sessionCleanupMode: "preserve",
47248
48102
  inlineMesh: args?.inlineMesh
47249
48103
  });
48104
+ recordMeshRefineStage(refineStages, "cleanup", removeResult?.success === false ? "failed" : "passed", cleanupStarted, {
48105
+ removed: removeResult?.removed,
48106
+ code: removeResult?.code,
48107
+ error: removeResult?.error
48108
+ });
48109
+ let ledgerError;
48110
+ const ledgerStarted = Date.now();
47250
48111
  try {
47251
48112
  const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
47252
48113
  appendLedgerEntry2(meshId, {
47253
48114
  kind: "node_removed",
47254
48115
  nodeId,
47255
- payload: { refined: true, mergedBranch: branch, into: baseBranch, validationSummary }
48116
+ payload: { refined: true, mergedBranch: branch, into: baseBranch, validationSummary, patchEquivalence }
47256
48117
  });
47257
- } catch {
48118
+ recordMeshRefineStage(refineStages, "ledger", "passed", ledgerStarted);
48119
+ } catch (e) {
48120
+ ledgerError = e?.message || String(e);
48121
+ recordMeshRefineStage(refineStages, "ledger", "failed", ledgerStarted, { error: ledgerError });
48122
+ }
48123
+ const finalBranchConvergenceState = {
48124
+ branch: baseBranch,
48125
+ mergedBranch: branch,
48126
+ baseBranch,
48127
+ merged: true,
48128
+ removed: removeResult?.success !== false,
48129
+ validation: "passed",
48130
+ patchEquivalence: "passed",
48131
+ status: removeResult?.success === false ? "merged_cleanup_failed" : "merged"
48132
+ };
48133
+ if (removeResult?.success === false) {
48134
+ return {
48135
+ success: false,
48136
+ code: "cleanup_failed",
48137
+ error: "Refinery merge completed but worktree cleanup failed; manual cleanup/retry is required.",
48138
+ merged: true,
48139
+ branch,
48140
+ into: baseBranch,
48141
+ removeResult,
48142
+ validationSummary,
48143
+ patchEquivalence,
48144
+ mergeResult,
48145
+ refineStages,
48146
+ ...ledgerError ? { ledgerError } : {},
48147
+ finalBranchConvergenceState
48148
+ };
47258
48149
  }
47259
48150
  return {
47260
48151
  success: true,
@@ -47263,18 +48154,14 @@ var init_router = __esm({
47263
48154
  into: baseBranch,
47264
48155
  removeResult,
47265
48156
  validationSummary,
47266
- finalBranchConvergenceState: {
47267
- branch: baseBranch,
47268
- mergedBranch: branch,
47269
- baseBranch,
47270
- merged: true,
47271
- removed: removeResult?.success !== false,
47272
- validation: "passed",
47273
- status: removeResult?.success === false ? "merged_cleanup_failed" : "merged"
47274
- }
48157
+ patchEquivalence,
48158
+ mergeResult,
48159
+ refineStages,
48160
+ ...ledgerError ? { ledgerError } : {},
48161
+ finalBranchConvergenceState
47275
48162
  };
47276
48163
  } catch (e) {
47277
- return { success: false, error: e.message };
48164
+ return { success: false, error: e.message, refineStages };
47278
48165
  }
47279
48166
  }
47280
48167
  case "remove_mesh_node": {
@@ -47315,6 +48202,7 @@ var init_router = __esm({
47315
48202
  } else {
47316
48203
  const { removeNode: removeNode3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
47317
48204
  removed = removeNode3(meshId, nodeId);
48205
+ if (removed) this.invalidateAggregateMeshStatus(meshId);
47318
48206
  }
47319
48207
  if (removed) {
47320
48208
  try {
@@ -47393,6 +48281,7 @@ var init_router = __esm({
47393
48281
  policy: { ...sourceNode.policy || {} }
47394
48282
  });
47395
48283
  if (!node) return { success: false, error: "Failed to register worktree node" };
48284
+ this.invalidateAggregateMeshStatus(meshId);
47396
48285
  }
47397
48286
  const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
47398
48287
  if (initSubmodules) {
@@ -47468,7 +48357,14 @@ var init_router = __esm({
47468
48357
  cliType
47469
48358
  };
47470
48359
  }
47471
- const workspace = typeof coordinatorNode.workspace === "string" ? coordinatorNode.workspace.trim() : "";
48360
+ const sessionHostRecords = this.deps.sessionHostControl?.listSessions ? await this.deps.sessionHostControl.listSessions().catch(() => []) : [];
48361
+ const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
48362
+ const workspace = readLiveMeshNodeWorkspace({
48363
+ meshId,
48364
+ nodeId: String(coordinatorNode.id || coordinatorNode.nodeId || preferredCoordinatorNodeId || ""),
48365
+ liveSessionRecords: liveMeshSessions,
48366
+ allowCoordinatorSession: true
48367
+ }) || (typeof coordinatorNode.workspace === "string" ? coordinatorNode.workspace.trim() : "");
47472
48368
  if (!workspace) return { success: false, error: "Coordinator node workspace required", meshId, cliType };
47473
48369
  if (!cliType) {
47474
48370
  const resolved = await resolveProviderTypeFromPriority({
@@ -47630,7 +48526,7 @@ ${block}`);
47630
48526
  workspace
47631
48527
  };
47632
48528
  }
47633
- const { existsSync: existsSync29, readFileSync: readFileSync22, writeFileSync: writeFileSync17, copyFileSync: copyFileSync5, mkdirSync: mkdirSync21 } = await import("fs");
48529
+ const { existsSync: existsSync30, readFileSync: readFileSync23, writeFileSync: writeFileSync17, copyFileSync: copyFileSync5, mkdirSync: mkdirSync21 } = await import("fs");
47634
48530
  const { dirname: dirname12 } = await import("path");
47635
48531
  const mcpConfigPath = coordinatorSetup.configPath;
47636
48532
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -47673,14 +48569,14 @@ ${block}`);
47673
48569
  if (hermesManualFallback) return returnManualFallback(message);
47674
48570
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
47675
48571
  }
47676
- const hadExistingMcpConfig = existsSync29(mcpConfigPath);
48572
+ const hadExistingMcpConfig = existsSync30(mcpConfigPath);
47677
48573
  let existingMcpConfig = hermesBaseConfig?.config || {};
47678
48574
  if (hermesBaseConfig) {
47679
48575
  copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname12(mcpConfigPath));
47680
48576
  }
47681
48577
  if (hadExistingMcpConfig) {
47682
48578
  try {
47683
- const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync22(mcpConfigPath, "utf-8"), configFormat);
48579
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync23(mcpConfigPath, "utf-8"), configFormat);
47684
48580
  const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
47685
48581
  existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
47686
48582
  copyFileSync5(mcpConfigPath, mcpConfigPath + ".backup");
@@ -47770,110 +48666,264 @@ ${block}`);
47770
48666
  const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
47771
48667
  const mesh = meshRecord?.mesh;
47772
48668
  if (!mesh) return { success: false, error: "Mesh not found" };
48669
+ const refreshRequested = args?.refresh === true || args?.forceRefresh === true;
48670
+ if (!refreshRequested) {
48671
+ const cachedStatus = this.getCachedAggregateMeshStatus(meshId);
48672
+ if (cachedStatus) return cachedStatus;
48673
+ }
48674
+ const refreshReason = refreshRequested ? "explicit_refresh" : "cold_cache_miss";
47773
48675
  const { getMeshQueueStats: getMeshQueueStats2, getQueue: getQueue2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
47774
48676
  const queue = getQueue2(meshId);
47775
48677
  const queueSummary = getMeshQueueStats2(meshId);
47776
48678
  const { readLedgerEntries: readLedgerEntries2, getLedgerSummary: getLedgerSummary2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
47777
48679
  const ledgerEntries = readLedgerEntries2(meshId, { tail: 20 });
47778
48680
  const ledgerSummary = getLedgerSummary2(meshId);
48681
+ const sessionHostRecords = this.deps.sessionHostControl?.listSessions ? await this.deps.sessionHostControl.listSessions().catch(() => []) : [];
48682
+ const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
48683
+ const localMachineId = loadConfig().machineId || "";
48684
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
48685
+ const directTruth = requireDirectPeerTruth ? await hydrateInlineMeshDirectTruth({
48686
+ mesh,
48687
+ meshSource: meshRecord.source,
48688
+ dispatchMeshCommand: this.deps.dispatchMeshCommand,
48689
+ statusInstanceId: this.deps.statusInstanceId,
48690
+ localMachineId
48691
+ }) : {
48692
+ directEvidenceCount: 0,
48693
+ localConfirmedCount: 0,
48694
+ peerAttemptedCount: 0,
48695
+ peerConfirmedCount: 0,
48696
+ unavailableNodeIds: []
48697
+ };
48698
+ const directTruthSatisfied = meshRecord.source !== "inline_bootstrap" || directTruth.directEvidenceCount > 0;
48699
+ if (requireDirectPeerTruth && !directTruthSatisfied) {
48700
+ return {
48701
+ success: false,
48702
+ code: "mesh_direct_peer_truth_unavailable",
48703
+ error: "Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct mesh_status probes succeed.",
48704
+ sourceOfTruth: {
48705
+ membership: meshRecord.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
48706
+ coordinatorOwnsLiveTruth: false,
48707
+ currentStatus: "direct_peer_truth_unavailable",
48708
+ directPeerTruth: {
48709
+ required: true,
48710
+ satisfied: false,
48711
+ directEvidenceCount: directTruth.directEvidenceCount,
48712
+ localConfirmedCount: directTruth.localConfirmedCount,
48713
+ peerAttemptedCount: directTruth.peerAttemptedCount,
48714
+ peerConfirmedCount: directTruth.peerConfirmedCount,
48715
+ unavailableNodeIds: directTruth.unavailableNodeIds
48716
+ }
48717
+ }
48718
+ };
48719
+ }
48720
+ const directTruthUnavailableNodeIds = new Set(directTruth.unavailableNodeIds);
48721
+ const selectedCoordinatorNodeId = readStringValue(
48722
+ mesh.coordinator?.preferredNodeId,
48723
+ mesh.nodes?.[0]?.id,
48724
+ mesh.nodes?.[0]?.nodeId
48725
+ );
48726
+ const inlineCoordinatorNodeId = meshRecord?.inline && Array.isArray(mesh.nodes) ? selectedCoordinatorNodeId : void 0;
48727
+ const refreshedAt = (/* @__PURE__ */ new Date()).toISOString();
47779
48728
  const nodeStatuses = [];
47780
- for (const node of mesh.nodes || []) {
48729
+ for (const [nodeIndex, node] of (mesh.nodes || []).entries()) {
48730
+ const nodeId = String(node.id || node.nodeId || "");
48731
+ const daemonId = readStringValue(node.daemonId);
48732
+ const providerPriority = readProviderPriorityFromPolicy(node.policy);
48733
+ const isSelfNode = Boolean(
48734
+ nodeId && inlineCoordinatorNodeId && nodeId === inlineCoordinatorNodeId
48735
+ ) || Boolean(
48736
+ daemonId && (daemonId === localMachineId || daemonId === this.deps.statusInstanceId)
48737
+ ) || Boolean(meshRecord?.inline && nodeIndex === 0);
47781
48738
  const status = {
47782
- nodeId: node.id || node.nodeId,
48739
+ nodeId,
47783
48740
  machineLabel: node.machineLabel || node.id || node.nodeId,
47784
48741
  workspace: node.workspace,
47785
48742
  repoRoot: node.repoRoot,
47786
48743
  isLocalWorktree: node.isLocalWorktree,
47787
48744
  worktreeBranch: node.worktreeBranch,
47788
- daemonId: node.daemonId,
48745
+ daemonId,
47789
48746
  machineId: node.machineId,
48747
+ machineStatus: node.machineStatus,
47790
48748
  health: "unknown",
47791
48749
  providers: node.providers || [],
47792
- activeSessions: []
48750
+ providerPriority,
48751
+ activeSessions: [],
48752
+ activeSessionDetails: [],
48753
+ launchReady: false
47793
48754
  };
47794
- if (node.workspace && typeof node.workspace === "string") {
47795
- if (!fs10.existsSync(node.workspace) && applyCachedInlineMeshNodeStatus(status, node)) {
47796
- nodeStatuses.push(status);
47797
- continue;
48755
+ if (isSelfNode) {
48756
+ status.connection = {
48757
+ perspective: "selected_coordinator",
48758
+ source: "mesh_peer_status",
48759
+ state: "self",
48760
+ transport: "local",
48761
+ reported: true,
48762
+ reason: "Selected coordinator daemon",
48763
+ lastStateChangeAt: refreshedAt
48764
+ };
48765
+ } else if (daemonId) {
48766
+ const connection = this.deps.getMeshPeerConnectionStatus?.(daemonId);
48767
+ status.connection = connection ?? {
48768
+ perspective: "selected_coordinator",
48769
+ source: "not_reported",
48770
+ state: "unknown",
48771
+ transport: "unknown",
48772
+ reported: false,
48773
+ reason: "No live mesh peer telemetry reported by the selected coordinator yet."
48774
+ };
48775
+ } else {
48776
+ status.connection = {
48777
+ perspective: "selected_coordinator",
48778
+ source: "not_reported",
48779
+ state: "unknown",
48780
+ transport: "unknown",
48781
+ reported: false,
48782
+ reason: "Node has no daemon id, so mesh transport cannot be reported from the selected coordinator."
48783
+ };
48784
+ }
48785
+ const matchedLiveSessionRecords = collectLiveMeshSessionRecords({
48786
+ meshId,
48787
+ node,
48788
+ nodeId,
48789
+ liveSessionRecords: liveMeshSessions,
48790
+ allowCoordinatorSession: nodeId === selectedCoordinatorNodeId
48791
+ });
48792
+ const workspace = readLiveMeshNodeWorkspace({
48793
+ meshId,
48794
+ nodeId,
48795
+ liveSessionRecords: matchedLiveSessionRecords,
48796
+ allowCoordinatorSession: nodeId === selectedCoordinatorNodeId
48797
+ }) || (typeof node.workspace === "string" ? node.workspace : "");
48798
+ status.workspace = workspace || node.workspace;
48799
+ if (matchedLiveSessionRecords.length > 0) {
48800
+ const sessionIds = matchedLiveSessionRecords.map((record2) => typeof record2?.sessionId === "string" ? record2.sessionId : "").filter(Boolean);
48801
+ const providerTypes = matchedLiveSessionRecords.map((record2) => readStringValue(record2?.providerType)).filter(Boolean);
48802
+ status.activeSessions = sessionIds;
48803
+ status.activeSessionDetails = matchedLiveSessionRecords.map(summarizeMeshSessionRecord);
48804
+ if (providerTypes.length > 0) {
48805
+ status.providers = Array.from(/* @__PURE__ */ new Set([...Array.isArray(status.providers) ? status.providers : [], ...providerTypes]));
47798
48806
  }
47799
- try {
47800
- const { execFile: execFile3 } = await import("child_process");
47801
- const { promisify: promisify3 } = await import("util");
47802
- const execFileAsync3 = promisify3(execFile3);
47803
- const runGit2 = async (args2) => {
47804
- const result = await execFileAsync3("git", ["-C", node.workspace, ...args2], {
47805
- encoding: "utf8",
47806
- timeout: 1e4
47807
- });
47808
- return result.stdout.trim();
47809
- };
47810
- const branch = await runGit2(["branch", "--show-current"]).catch(() => "");
47811
- const porc = await runGit2(["status", "--porcelain"]).catch(() => "");
47812
- const headCommit = await runGit2(["rev-parse", "--short", "HEAD"]).catch(() => null);
47813
- const headMessage = await runGit2(["log", "-1", "--format=%s"]).catch(() => null);
47814
- const upstream = await runGit2(["rev-parse", "--abbrev-ref", "@{upstream}"]).catch(() => null);
47815
- const aheadBehind = await runGit2(["rev-list", "--left-right", "--count", "@{upstream}...HEAD"]).catch(() => "");
47816
- const stashCount = await runGit2(["stash", "list"]).catch(() => "");
47817
- let ahead = 0, behind = 0;
47818
- if (aheadBehind) {
47819
- const parts = aheadBehind.split(/\s+/);
47820
- if (parts.length >= 2) {
47821
- behind = parseInt(parts[0], 10) || 0;
47822
- ahead = parseInt(parts[1], 10) || 0;
48807
+ }
48808
+ if (workspace) {
48809
+ if (!fs10.existsSync(workspace)) {
48810
+ const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
48811
+ let remoteProbeApplied = false;
48812
+ if (inlineTransitGit) {
48813
+ status.git = inlineTransitGit;
48814
+ status.health = inlineTransitGit.isGitRepo ? deriveMeshNodeHealthFromGit(inlineTransitGit) : "degraded";
48815
+ remoteProbeApplied = true;
48816
+ } else if (!isSelfNode && daemonId && this.deps.dispatchMeshCommand && !directTruthUnavailableNodeIds.has(nodeId)) {
48817
+ try {
48818
+ const remoteGit = await probeRemoteMeshGitStatus({
48819
+ dispatchMeshCommand: this.deps.dispatchMeshCommand,
48820
+ daemonId,
48821
+ workspace,
48822
+ timeoutMs: 8e3
48823
+ });
48824
+ if (remoteGit) {
48825
+ status.git = remoteGit;
48826
+ status.health = remoteGit.isGitRepo ? deriveMeshNodeHealthFromGit(remoteGit) : "degraded";
48827
+ recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
48828
+ remoteProbeApplied = true;
48829
+ }
48830
+ } catch {
48831
+ const refreshedConnection = this.deps.getMeshPeerConnectionStatus?.(daemonId);
48832
+ const refreshedConnectionState = readStringValue(refreshedConnection?.state);
48833
+ if (refreshedConnection && refreshedConnectionState === "connected") {
48834
+ status.connection = refreshedConnection;
48835
+ try {
48836
+ const remoteGit = await probeRemoteMeshGitStatus({
48837
+ dispatchMeshCommand: this.deps.dispatchMeshCommand,
48838
+ daemonId,
48839
+ workspace,
48840
+ timeoutMs: 12e3
48841
+ });
48842
+ if (remoteGit) {
48843
+ status.git = remoteGit;
48844
+ status.health = remoteGit.isGitRepo ? deriveMeshNodeHealthFromGit(remoteGit) : "degraded";
48845
+ recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
48846
+ remoteProbeApplied = true;
48847
+ }
48848
+ } catch {
48849
+ }
48850
+ }
47823
48851
  }
47824
48852
  }
47825
- const dirty = porc.length > 0;
47826
- const lines = porc ? porc.split("\n").filter(Boolean) : [];
47827
- let staged = 0, modified = 0, untracked = 0, deleted = 0, renamed2 = 0;
47828
- for (const line of lines) {
47829
- const xy = line.slice(0, 2);
47830
- if (xy[0] !== " " && xy[0] !== "?") staged++;
47831
- if (xy[1] === "M") modified++;
47832
- if (xy[1] === "D") deleted++;
47833
- if (xy[0] === "R" || xy[1] === "R") renamed2++;
47834
- if (xy === "??") untracked++;
48853
+ if (!remoteProbeApplied) {
48854
+ const connectionState = readStringValue(status.connection?.state);
48855
+ const pendingPeerGitProbe = !inlineTransitGit && !isSelfNode && !!daemonId && (readStringValue(status.machineStatus) === "online" || readStringValue(status.health) === "online" || connectionState === "connecting" || connectionState === "connected" || connectionState === "unknown");
48856
+ if (pendingPeerGitProbe) {
48857
+ status.gitProbePending = true;
48858
+ status.health = "unknown";
48859
+ }
48860
+ if (applyCachedInlineMeshNodeStatus(
48861
+ status,
48862
+ node,
48863
+ pendingPeerGitProbe ? { skipGit: true, skipError: true, skipHealth: true } : void 0
48864
+ )) {
48865
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
48866
+ nodeStatuses.push(status);
48867
+ continue;
48868
+ }
48869
+ if (meshRecord?.source === "inline_cache" && !isSelfNode) {
48870
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
48871
+ nodeStatuses.push(status);
48872
+ continue;
48873
+ }
47835
48874
  }
47836
- status.git = {
47837
- workspace: node.workspace,
47838
- repoRoot: node.workspace,
47839
- isGitRepo: true,
47840
- branch: branch || null,
47841
- headCommit,
47842
- headMessage,
47843
- upstream,
47844
- ahead,
47845
- behind,
47846
- staged,
47847
- modified,
47848
- untracked,
47849
- deleted,
47850
- renamed: renamed2,
47851
- hasConflicts: false,
47852
- conflictFiles: [],
47853
- stashCount: stashCount ? stashCount.split("\n").filter(Boolean).length : 0,
47854
- lastCheckedAt: Date.now()
47855
- };
47856
- status.health = branch ? dirty ? "dirty" : "online" : "degraded";
47857
- } catch {
47858
- if (!applyCachedInlineMeshNodeStatus(status, node)) {
47859
- status.health = "degraded";
48875
+ } else {
48876
+ try {
48877
+ const gitStatus = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
48878
+ status.git = gitStatus;
48879
+ recordInlineMeshDirectGitTruth(node, gitStatus, "selected_coordinator_local_git");
48880
+ if (gitStatus.isGitRepo) {
48881
+ status.health = deriveMeshNodeHealthFromGit(gitStatus);
48882
+ } else {
48883
+ status.health = "degraded";
48884
+ if (gitStatus.error && !status.error) status.error = gitStatus.error;
48885
+ }
48886
+ } catch {
48887
+ if (!applyCachedInlineMeshNodeStatus(status, node)) {
48888
+ status.health = "degraded";
48889
+ }
47860
48890
  }
47861
48891
  }
47862
48892
  } else {
47863
48893
  applyCachedInlineMeshNodeStatus(status, node);
47864
48894
  }
48895
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
47865
48896
  nodeStatuses.push(status);
47866
48897
  }
47867
- return {
48898
+ const statusResult = {
47868
48899
  success: true,
47869
48900
  meshId: mesh.id,
47870
48901
  meshName: mesh.name,
47871
48902
  repoIdentity: mesh.repoIdentity,
47872
48903
  defaultBranch: mesh.defaultBranch,
48904
+ refreshedAt,
48905
+ sourceOfTruth: {
48906
+ membership: meshRecord?.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord?.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
48907
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
48908
+ ...requireDirectPeerTruth ? {
48909
+ currentStatus: directTruthSatisfied ? "live_git_and_session_probes" : "direct_peer_truth_unavailable",
48910
+ directPeerTruth: {
48911
+ required: true,
48912
+ satisfied: directTruthSatisfied,
48913
+ directEvidenceCount: directTruth.directEvidenceCount,
48914
+ localConfirmedCount: directTruth.localConfirmedCount,
48915
+ peerAttemptedCount: directTruth.peerAttemptedCount,
48916
+ peerConfirmedCount: directTruth.peerConfirmedCount,
48917
+ unavailableNodeIds: directTruth.unavailableNodeIds
48918
+ }
48919
+ } : {},
48920
+ historicalEvidenceOnly: ["recoveryHints", "ledger.summary", "queue.summary"]
48921
+ },
47873
48922
  nodes: nodeStatuses,
47874
48923
  queue: { tasks: queue, summary: queueSummary },
47875
48924
  ledger: { entries: ledgerEntries, summary: ledgerSummary }
47876
48925
  };
48926
+ return this.rememberAggregateMeshStatus(meshId, statusResult, refreshReason);
47877
48927
  } catch (e) {
47878
48928
  return { success: false, error: e.message };
47879
48929
  }
@@ -55948,6 +56998,7 @@ async function initDaemonComponents(config2) {
55948
56998
  sessionHostControl: config2.sessionHostControl,
55949
56999
  statusInstanceId: config2.statusInstanceId,
55950
57000
  statusVersion: config2.statusVersion,
57001
+ getMeshPeerConnectionStatus: config2.getMeshPeerConnectionStatus,
55951
57002
  getCdpLogFn: config2.getCdpLogFn || ((ideType) => LOG.forComponent(`CDP:${ideType}`).asLogFn())
55952
57003
  });
55953
57004
  poller = new AgentStreamPoller({
@@ -56249,6 +57300,7 @@ __export(src_exports, {
56249
57300
  prepareSessionChatTailUpdate: () => prepareSessionChatTailUpdate,
56250
57301
  prepareSessionModalUpdate: () => prepareSessionModalUpdate,
56251
57302
  probeCdpPort: () => probeCdpPort,
57303
+ queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
56252
57304
  readChatHistory: () => readChatHistory,
56253
57305
  readLedgerEntries: () => readLedgerEntries,
56254
57306
  readLedgerSlice: () => readLedgerSlice,
@@ -56477,7 +57529,9 @@ var init_server_connection = __esm({
56477
57529
  const requestId = `mesh_${crypto.randomUUID()}`;
56478
57530
  const timer = setTimeout(() => {
56479
57531
  this.off("daemon_mesh_result", handler);
56480
- reject(new Error(`Mesh command timed out after ${timeoutMs}ms`));
57532
+ reject(new Error(
57533
+ `Mesh command '${command}' to ${targetDaemonId.slice(0, 12)} timed out after ${timeoutMs}ms (requestId=${requestId})`
57534
+ ));
56481
57535
  }, timeoutMs);
56482
57536
  const handler = (msg) => {
56483
57537
  const body = msg.payload && typeof msg.payload === "object" ? { ...msg, ...msg.payload } : msg;
@@ -58292,7 +59346,7 @@ var require_filesystem = __commonJS({
58292
59346
  var LDD_PATH = "/usr/bin/ldd";
58293
59347
  var SELF_PATH = "/proc/self/exe";
58294
59348
  var MAX_LENGTH = 2048;
58295
- var readFileSync22 = (path35) => {
59349
+ var readFileSync23 = (path35) => {
58296
59350
  const fd = fs20.openSync(path35, "r");
58297
59351
  const buffer = Buffer.alloc(MAX_LENGTH);
58298
59352
  const bytesRead = fs20.readSync(fd, buffer, 0, MAX_LENGTH, 0);
@@ -58317,7 +59371,7 @@ var require_filesystem = __commonJS({
58317
59371
  module2.exports = {
58318
59372
  LDD_PATH,
58319
59373
  SELF_PATH,
58320
- readFileSync: readFileSync22,
59374
+ readFileSync: readFileSync23,
58321
59375
  readFile: readFile2
58322
59376
  };
58323
59377
  }
@@ -58366,7 +59420,7 @@ var require_detect_libc = __commonJS({
58366
59420
  "use strict";
58367
59421
  var childProcess = require("child_process");
58368
59422
  var { isLinux: isLinux2, getReport } = require_process();
58369
- var { LDD_PATH, SELF_PATH, readFile: readFile2, readFileSync: readFileSync22 } = require_filesystem();
59423
+ var { LDD_PATH, SELF_PATH, readFile: readFile2, readFileSync: readFileSync23 } = require_filesystem();
58370
59424
  var { interpreterPath } = require_elf();
58371
59425
  var cachedFamilyInterpreter;
58372
59426
  var cachedFamilyFilesystem;
@@ -58458,7 +59512,7 @@ var require_detect_libc = __commonJS({
58458
59512
  }
58459
59513
  cachedFamilyFilesystem = null;
58460
59514
  try {
58461
- const lddContent = readFileSync22(LDD_PATH);
59515
+ const lddContent = readFileSync23(LDD_PATH);
58462
59516
  cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);
58463
59517
  } catch (e) {
58464
59518
  }
@@ -58483,7 +59537,7 @@ var require_detect_libc = __commonJS({
58483
59537
  }
58484
59538
  cachedFamilyInterpreter = null;
58485
59539
  try {
58486
- const selfContent = readFileSync22(SELF_PATH);
59540
+ const selfContent = readFileSync23(SELF_PATH);
58487
59541
  const path35 = interpreterPath(selfContent);
58488
59542
  cachedFamilyInterpreter = familyFromInterpreterPath(path35);
58489
59543
  } catch (e) {
@@ -58547,7 +59601,7 @@ var require_detect_libc = __commonJS({
58547
59601
  }
58548
59602
  cachedVersionFilesystem = null;
58549
59603
  try {
58550
- const lddContent = readFileSync22(LDD_PATH);
59604
+ const lddContent = readFileSync23(LDD_PATH);
58551
59605
  const versionMatch = lddContent.match(RE_GLIBC_VERSION);
58552
59606
  if (versionMatch) {
58553
59607
  cachedVersionFilesystem = versionMatch[1];
@@ -65989,25 +67043,25 @@ function resolvePackageVersion(options) {
65989
67043
  const injectedVersion = options?.injectedVersion || "unknown";
65990
67044
  const dir = options?.dirname || __dirname;
65991
67045
  const possiblePaths = [
65992
- (0, import_path7.join)(dir, "..", "..", "package.json"),
65993
- (0, import_path7.join)(dir, "..", "package.json"),
65994
- (0, import_path7.join)(dir, "package.json")
67046
+ (0, import_path8.join)(dir, "..", "..", "package.json"),
67047
+ (0, import_path8.join)(dir, "..", "package.json"),
67048
+ (0, import_path8.join)(dir, "package.json")
65995
67049
  ];
65996
67050
  for (const p of possiblePaths) {
65997
67051
  try {
65998
- const data = JSON.parse((0, import_fs11.readFileSync)(p, "utf-8"));
67052
+ const data = JSON.parse((0, import_fs12.readFileSync)(p, "utf-8"));
65999
67053
  if (data.version) return data.version;
66000
67054
  } catch {
66001
67055
  }
66002
67056
  }
66003
67057
  return injectedVersion;
66004
67058
  }
66005
- var import_fs11, import_path7;
67059
+ var import_fs12, import_path8;
66006
67060
  var init_version = __esm({
66007
67061
  "src/version.ts"() {
66008
67062
  "use strict";
66009
- import_fs11 = require("fs");
66010
- import_path7 = require("path");
67063
+ import_fs12 = require("fs");
67064
+ import_path8 = require("path");
66011
67065
  }
66012
67066
  });
66013
67067
 
@@ -66040,11 +67094,37 @@ var init_daemon_mesh_manager = __esm({
66040
67094
  nodeDatachannel = null;
66041
67095
  peers = /* @__PURE__ */ new Map();
66042
67096
  // Map<targetDaemonId, PeerEntry>
67097
+ peerSnapshots = /* @__PURE__ */ new Map();
66043
67098
  pendingRequests = /* @__PURE__ */ new Map();
66044
67099
  commandCallback;
66045
67100
  p2pFailure(message, command, targetDaemonId) {
66046
67101
  return new P2pRelayFailureError(message, { command, targetDaemonId });
66047
67102
  }
67103
+ logMeshCommandEvent(event, fields) {
67104
+ try {
67105
+ LOG.info("Mesh", `[MeshCommand] ${JSON.stringify({ event, ...fields })}`);
67106
+ } catch {
67107
+ LOG.info("Mesh", `[MeshCommand] ${event}`);
67108
+ }
67109
+ }
67110
+ updatePeerSnapshot(targetDaemonId, state, patch = {}) {
67111
+ const previous = this.peerSnapshots.get(targetDaemonId);
67112
+ const now = (/* @__PURE__ */ new Date()).toISOString();
67113
+ this.peerSnapshots.set(targetDaemonId, {
67114
+ perspective: "selected_coordinator",
67115
+ source: "mesh_peer_status",
67116
+ reported: true,
67117
+ state,
67118
+ transport: patch.transport ?? previous?.transport ?? "unknown",
67119
+ reason: patch.reason ?? previous?.reason,
67120
+ lastStateChangeAt: now,
67121
+ lastConnectedAt: patch.lastConnectedAt ?? previous?.lastConnectedAt,
67122
+ lastCommandAt: patch.lastCommandAt ?? previous?.lastCommandAt
67123
+ });
67124
+ }
67125
+ getPeerConnectionStatus(targetDaemonId) {
67126
+ return this.peerSnapshots.get(targetDaemonId) ?? null;
67127
+ }
66048
67128
  invalidatePeer(targetDaemonId, reason, options = {}) {
66049
67129
  const peer = this.peers.get(targetDaemonId);
66050
67130
  if (peer?.commandQueue) {
@@ -66059,6 +67139,11 @@ var init_daemon_mesh_manager = __esm({
66059
67139
  pending.reject(this.p2pFailure(reason, pending.command, targetDaemonId));
66060
67140
  }
66061
67141
  }
67142
+ const snapshotState = peer?.state === "closed" ? "closed" : peer?.state === "disconnected" ? "disconnected" : "failed";
67143
+ this.updatePeerSnapshot(targetDaemonId, snapshotState, {
67144
+ reason,
67145
+ transport: peer?.isRelay === true ? "relay" : peer?.isRelay === false ? "direct" : "unknown"
67146
+ });
66062
67147
  if (options.closeResources !== false && peer) {
66063
67148
  try {
66064
67149
  peer.dataChannel?.close?.();
@@ -66091,6 +67176,7 @@ var init_daemon_mesh_manager = __esm({
66091
67176
  "send_chat",
66092
67177
  "read_chat",
66093
67178
  "get_chat_debug_bundle",
67179
+ "get_pending_mesh_events",
66094
67180
  "git_status",
66095
67181
  "git_diff_summary",
66096
67182
  "launch_cli",
@@ -66151,6 +67237,13 @@ var init_daemon_mesh_manager = __esm({
66151
67237
  const peer = this.peers.get(targetDaemonId);
66152
67238
  if (!peer || peer.state !== "connected" || !peer.dataChannel?.isOpen()) {
66153
67239
  LOG.warn("Mesh", `[Mesh] Cannot send result for ${requestId}, P2P not open with ${targetDaemonId.slice(0, 12)}`);
67240
+ this.logMeshCommandEvent("response_send_failed", {
67241
+ requestId,
67242
+ targetDaemonId,
67243
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
67244
+ peerState: peer?.state ?? "missing",
67245
+ error: "P2P not open"
67246
+ });
66154
67247
  return;
66155
67248
  }
66156
67249
  try {
@@ -66161,8 +67254,22 @@ var init_daemon_mesh_manager = __esm({
66161
67254
  result,
66162
67255
  error: error48
66163
67256
  }));
67257
+ this.logMeshCommandEvent("response_sent", {
67258
+ requestId,
67259
+ targetDaemonId,
67260
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
67261
+ peerState: peer.state,
67262
+ success: !error48
67263
+ });
66164
67264
  } catch (err) {
66165
67265
  LOG.warn("Mesh", `[Mesh] Failed to send command result: ${err.message}`);
67266
+ this.logMeshCommandEvent("response_send_failed", {
67267
+ requestId,
67268
+ targetDaemonId,
67269
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
67270
+ peerState: peer.state,
67271
+ error: err?.message || "Failed to send command result"
67272
+ });
66166
67273
  }
66167
67274
  }
66168
67275
  /** Convenience: send a one-off mesh command without a rule. */
@@ -66178,11 +67285,37 @@ var init_daemon_mesh_manager = __esm({
66178
67285
  if (!peer) {
66179
67286
  throw this.p2pFailure("Failed to initiate P2P connection entry", command, targetDaemonId);
66180
67287
  }
67288
+ const lastCommandAt = (/* @__PURE__ */ new Date()).toISOString();
67289
+ if (peer.state === "connected") {
67290
+ this.updatePeerSnapshot(targetDaemonId, "connected", {
67291
+ transport: peer.isRelay === true ? "relay" : peer.isRelay === false ? "direct" : "unknown",
67292
+ lastConnectedAt: this.peerSnapshots.get(targetDaemonId)?.lastConnectedAt,
67293
+ lastCommandAt
67294
+ });
67295
+ } else {
67296
+ this.updatePeerSnapshot(targetDaemonId, "connecting", {
67297
+ transport: peer.isRelay === true ? "relay" : peer.isRelay === false ? "direct" : "unknown",
67298
+ reason: "Waiting for mesh DataChannel to open.",
67299
+ lastCommandAt
67300
+ });
67301
+ }
66181
67302
  return new Promise((resolve20, reject) => {
66182
67303
  const requestId = `req_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
67304
+ const queuedAt = (/* @__PURE__ */ new Date()).toISOString();
66183
67305
  const timer = setTimeout(() => {
67306
+ const pending = this.pendingRequests.get(requestId);
66184
67307
  this.pendingRequests.delete(requestId);
67308
+ const timedOutAt = (/* @__PURE__ */ new Date()).toISOString();
66185
67309
  const message = `P2P DataChannel command '${command}' to ${targetDaemonId.slice(0, 12)} timed out after 30s`;
67310
+ this.logMeshCommandEvent("timeout", {
67311
+ requestId,
67312
+ command,
67313
+ targetDaemonId,
67314
+ queuedAt: pending?.queuedAt ?? queuedAt,
67315
+ sentAt: pending?.sentAt,
67316
+ timedOutAt,
67317
+ peerState: peer?.state
67318
+ });
66186
67319
  this.invalidatePeer(targetDaemonId, message, { rejectPending: true, excludeRequestId: requestId });
66187
67320
  reject(this.p2pFailure(message, command, targetDaemonId));
66188
67321
  }, 3e4);
@@ -66199,7 +67332,8 @@ var init_daemon_mesh_manager = __esm({
66199
67332
  },
66200
67333
  timer,
66201
67334
  targetDaemonId,
66202
- command
67335
+ command,
67336
+ queuedAt
66203
67337
  });
66204
67338
  const payload = {
66205
67339
  type: "mesh_command",
@@ -66208,18 +67342,47 @@ var init_daemon_mesh_manager = __esm({
66208
67342
  args
66209
67343
  };
66210
67344
  if (peer.state === "connected" && peer.dataChannel?.isOpen()) {
67345
+ const sentAt = (/* @__PURE__ */ new Date()).toISOString();
67346
+ const pending = this.pendingRequests.get(requestId);
67347
+ if (pending) pending.sentAt = sentAt;
66211
67348
  LOG.info("Mesh", `[Mesh] Sending '${command}' via P2P DataChannel to ${targetDaemonId.slice(0, 12)}`);
67349
+ this.logMeshCommandEvent("sent", {
67350
+ requestId,
67351
+ command,
67352
+ targetDaemonId,
67353
+ queuedAt,
67354
+ sentAt,
67355
+ peerState: peer.state,
67356
+ transport: peer.isRelay === true ? "relay" : peer.isRelay === false ? "direct" : "unknown"
67357
+ });
66212
67358
  try {
66213
67359
  peer.dataChannel.sendMessage(JSON.stringify(payload));
66214
67360
  } catch (err) {
66215
67361
  const req = this.pendingRequests.get(requestId);
66216
67362
  const message = err?.message || "P2P DataChannel send failed";
67363
+ this.logMeshCommandEvent("send_failed", {
67364
+ requestId,
67365
+ command,
67366
+ targetDaemonId,
67367
+ queuedAt,
67368
+ sentAt,
67369
+ failedAt: (/* @__PURE__ */ new Date()).toISOString(),
67370
+ error: message
67371
+ });
66217
67372
  this.invalidatePeer(targetDaemonId, message, { rejectPending: true, excludeRequestId: requestId });
66218
67373
  if (req) req.reject(this.p2pFailure(message, command, targetDaemonId));
66219
67374
  }
66220
67375
  return;
66221
67376
  }
66222
67377
  LOG.info("Mesh", `[Mesh] Queuing '${command}' for ${targetDaemonId.slice(0, 12)} (state: ${peer.state})`);
67378
+ this.logMeshCommandEvent("queued", {
67379
+ requestId,
67380
+ command,
67381
+ targetDaemonId,
67382
+ queuedAt,
67383
+ peerState: peer.state,
67384
+ transport: peer.isRelay === true ? "relay" : peer.isRelay === false ? "direct" : "unknown"
67385
+ });
66223
67386
  if (!peer.commandQueue) {
66224
67387
  peer.commandQueue = [];
66225
67388
  }
@@ -66227,6 +67390,7 @@ var init_daemon_mesh_manager = __esm({
66227
67390
  command,
66228
67391
  args,
66229
67392
  requestId,
67393
+ queuedAt,
66230
67394
  reject: (err) => {
66231
67395
  const req = this.pendingRequests.get(requestId);
66232
67396
  if (req) req.reject(err);
@@ -66265,7 +67429,18 @@ var init_daemon_mesh_manager = __esm({
66265
67429
  peer.pendingCandidates = [];
66266
67430
  }
66267
67431
  } catch (err) {
66268
- LOG.warn("Mesh", `[Mesh] Failed to set remote desc: ${err.message}`);
67432
+ const errorMessage = err?.message || "Failed to set remote description";
67433
+ const isDuplicateStableAnswer = type2 === "mesh_p2p_answer" && /Unexpected remote answer description in signaling state stable/i.test(errorMessage);
67434
+ this.logMeshCommandEvent(isDuplicateStableAnswer ? "remote_desc_duplicate_ignored" : "remote_desc_failed", {
67435
+ targetDaemonId,
67436
+ signalType: type2,
67437
+ receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
67438
+ peerState: peer.state,
67439
+ error: errorMessage
67440
+ });
67441
+ if (isDuplicateStableAnswer) return;
67442
+ LOG.warn("Mesh", `[Mesh] Failed to set remote desc for ${type2} from ${targetDaemonId.slice(0, 12)}: ${errorMessage}`);
67443
+ this.invalidatePeer(targetDaemonId, `P2P remote description failed: ${errorMessage}`, { rejectPending: true, closeResources: true });
66269
67444
  }
66270
67445
  } else if (type2 === "mesh_p2p_ice") {
66271
67446
  try {
@@ -66321,6 +67496,9 @@ var init_daemon_mesh_manager = __esm({
66321
67496
  remoteDescriptionSet: false
66322
67497
  };
66323
67498
  this.peers.set(targetDaemonId, entry);
67499
+ this.updatePeerSnapshot(targetDaemonId, "connecting", {
67500
+ reason: isInitiator ? "P2P mesh connection initiated by the selected coordinator." : "Waiting for the remote daemon to finish the mesh DataChannel handshake."
67501
+ });
66324
67502
  pc.onLocalDescription((sdp, type2) => {
66325
67503
  this.serverConn.sendMeshCommand(targetDaemonId, type2 === "offer" ? "mesh_p2p_offer" : "mesh_p2p_answer", { sdp, type: type2 });
66326
67504
  });
@@ -66331,7 +67509,26 @@ var init_daemon_mesh_manager = __esm({
66331
67509
  LOG.info("Mesh", `[Mesh] P2P state with ${targetDaemonId.slice(0, 12)}: ${state}`);
66332
67510
  if (state === "connected") {
66333
67511
  entry.state = "connected";
67512
+ let transport = "unknown";
67513
+ try {
67514
+ const pair = pc.getSelectedCandidatePair?.();
67515
+ if (pair) {
67516
+ const localType = pair.local?.type || "unknown";
67517
+ const remoteType = pair.remote?.type || "unknown";
67518
+ entry.isRelay = localType === "relay" || remoteType === "relay";
67519
+ transport = entry.isRelay ? "relay" : "direct";
67520
+ LOG.info("Mesh", `[Mesh] Candidate pair with ${targetDaemonId.slice(0, 12)}: local=${localType} remote=${remoteType} \u2192 ${transport}`);
67521
+ }
67522
+ } catch {
67523
+ transport = entry.isRelay === true ? "relay" : entry.isRelay === false ? "direct" : "unknown";
67524
+ }
67525
+ this.updatePeerSnapshot(targetDaemonId, "connected", {
67526
+ transport,
67527
+ reason: transport === "relay" ? "Connected over TURN relay." : transport === "direct" ? "Connected directly peer-to-peer." : "Connected, but selected candidate pair details are unavailable.",
67528
+ lastConnectedAt: (/* @__PURE__ */ new Date()).toISOString()
67529
+ });
66334
67530
  } else if (state === "failed" || state === "closed" || state === "disconnected") {
67531
+ entry.state = state;
66335
67532
  this.invalidatePeer(targetDaemonId, `P2P state changed to ${state}`, { rejectPending: true, closeResources: false });
66336
67533
  }
66337
67534
  });
@@ -66349,12 +67546,30 @@ var init_daemon_mesh_manager = __esm({
66349
67546
  dc.onOpen(() => {
66350
67547
  LOG.info("Mesh", `[Mesh] DataChannel OPEN with ${targetDaemonId.slice(0, 12)}`);
66351
67548
  entry.state = "connected";
67549
+ this.updatePeerSnapshot(targetDaemonId, "connected", {
67550
+ transport: entry.isRelay === true ? "relay" : entry.isRelay === false ? "direct" : "unknown",
67551
+ reason: entry.isRelay === true ? "Connected over TURN relay." : entry.isRelay === false ? "Connected directly peer-to-peer." : "DataChannel open; transport details not reported yet.",
67552
+ lastConnectedAt: (/* @__PURE__ */ new Date()).toISOString()
67553
+ });
66352
67554
  if (entry.commandQueue) {
66353
67555
  const queue = entry.commandQueue;
66354
67556
  entry.commandQueue = [];
66355
67557
  for (const item of queue) {
66356
67558
  try {
67559
+ const sentAt = (/* @__PURE__ */ new Date()).toISOString();
67560
+ const pending = this.pendingRequests.get(item.requestId);
67561
+ if (pending) pending.sentAt = sentAt;
66357
67562
  LOG.info("Mesh", `[Mesh] Flushing queued '${item.command}' to ${targetDaemonId.slice(0, 12)}`);
67563
+ this.logMeshCommandEvent("sent", {
67564
+ requestId: item.requestId,
67565
+ command: item.command,
67566
+ targetDaemonId,
67567
+ queuedAt: item.queuedAt,
67568
+ sentAt,
67569
+ peerState: entry.state,
67570
+ transport: entry.isRelay === true ? "relay" : entry.isRelay === false ? "direct" : "unknown",
67571
+ flushed: true
67572
+ });
66358
67573
  dc.sendMessage(JSON.stringify({
66359
67574
  type: "mesh_command",
66360
67575
  requestId: item.requestId,
@@ -66362,6 +67577,14 @@ var init_daemon_mesh_manager = __esm({
66362
67577
  args: item.args
66363
67578
  }));
66364
67579
  } catch (err) {
67580
+ this.logMeshCommandEvent("send_failed", {
67581
+ requestId: item.requestId,
67582
+ command: item.command,
67583
+ targetDaemonId,
67584
+ queuedAt: item.queuedAt,
67585
+ failedAt: (/* @__PURE__ */ new Date()).toISOString(),
67586
+ error: err?.message || "P2P DataChannel send failed while flushing command queue"
67587
+ });
66365
67588
  item.reject(this.p2pFailure(err?.message || "P2P DataChannel send failed while flushing command queue", item.command, targetDaemonId));
66366
67589
  }
66367
67590
  }
@@ -66376,6 +67599,12 @@ var init_daemon_mesh_manager = __esm({
66376
67599
  const str2 = typeof msg === "string" ? msg : msg.toString("utf8");
66377
67600
  const data = JSON.parse(str2);
66378
67601
  if (data.type === "mesh_command" && data.command) {
67602
+ this.logMeshCommandEvent("incoming", {
67603
+ requestId: data.requestId,
67604
+ command: data.command,
67605
+ senderDaemonId: targetDaemonId,
67606
+ receivedAt: (/* @__PURE__ */ new Date()).toISOString()
67607
+ });
66379
67608
  if (this.commandCallback) {
66380
67609
  this.commandCallback(targetDaemonId, data.command, data.args, data.requestId).catch((e) => {
66381
67610
  LOG.warn("Mesh", `[Mesh] Error handling incoming P2P command: ${e.message}`);
@@ -66384,11 +67613,27 @@ var init_daemon_mesh_manager = __esm({
66384
67613
  } else if (data.type === "mesh_command_result" && data.requestId) {
66385
67614
  const pending = this.pendingRequests.get(data.requestId);
66386
67615
  if (pending) {
67616
+ this.logMeshCommandEvent("response_received", {
67617
+ requestId: data.requestId,
67618
+ command: pending.command,
67619
+ targetDaemonId: pending.targetDaemonId,
67620
+ queuedAt: pending.queuedAt,
67621
+ sentAt: pending.sentAt,
67622
+ receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
67623
+ success: data.success === true
67624
+ });
66387
67625
  if (data.success) {
66388
67626
  pending.resolve(data.result);
66389
67627
  } else {
66390
67628
  pending.reject(new Error(data.error || "P2P Command failed"));
66391
67629
  }
67630
+ } else {
67631
+ this.logMeshCommandEvent("response_orphan", {
67632
+ requestId: data.requestId,
67633
+ targetDaemonId,
67634
+ receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
67635
+ success: data.success === true
67636
+ });
66392
67637
  }
66393
67638
  }
66394
67639
  } catch (e) {
@@ -66628,6 +67873,7 @@ var init_adhdev_daemon = __esm({
66628
67873
  "use strict";
66629
67874
  init_server_connection();
66630
67875
  init_src();
67876
+ init_mesh_events();
66631
67877
  init_daemon_p2p2();
66632
67878
  init_screenshot_controller();
66633
67879
  init_session_host();
@@ -66644,7 +67890,7 @@ var init_adhdev_daemon = __esm({
66644
67890
  init_version();
66645
67891
  init_src();
66646
67892
  init_runtime_defaults();
66647
- pkgVersion = resolvePackageVersion({ injectedVersion: "0.9.82-rc.4" });
67893
+ pkgVersion = resolvePackageVersion({ injectedVersion: "0.9.82-rc.40" });
66648
67894
  AdhdevDaemon = class _AdhdevDaemon {
66649
67895
  localHttpServer = null;
66650
67896
  localWss = null;
@@ -67168,6 +68414,7 @@ ${err?.stack || ""}`);
67168
68414
  if (!this.meshManager) throw new Error("Mesh manager not initialized");
67169
68415
  return this.meshManager.sendCommand(daemonId, command, args);
67170
68416
  },
68417
+ getMeshPeerConnectionStatus: (daemonId) => this.meshManager?.getPeerConnectionStatus(daemonId) ?? null,
67171
68418
  onStatusChange: () => {
67172
68419
  this.invalidateHotChatSnapshotCache();
67173
68420
  this.statusReporter?.onStatusChange();
@@ -67537,6 +68784,7 @@ ${err?.stack || ""}`);
67537
68784
  const meshId = this.readMeshString(settings.meshNodeFor);
67538
68785
  const coordinatorDaemonId = this.readMeshString(settings.meshCoordinatorDaemonId);
67539
68786
  if (!meshId || !coordinatorDaemonId) return;
68787
+ const relayTimestamp = typeof event.timestamp === "number" && Number.isFinite(event.timestamp) ? event.timestamp : this.readMeshString(event.timestamp) || void 0;
67540
68788
  const payload = {
67541
68789
  event: this.readMeshString(event.event),
67542
68790
  meshId,
@@ -67545,7 +68793,8 @@ ${err?.stack || ""}`);
67545
68793
  targetSessionId: this.readMeshString(event.targetSessionId) || instanceId,
67546
68794
  providerType: this.readMeshString(event.providerType),
67547
68795
  providerSessionId: this.readMeshString(event.providerSessionId),
67548
- finalSummary: this.readMeshString(event.finalSummary) || this.readMeshString(event.summary)
68796
+ finalSummary: this.readMeshString(event.finalSummary) || this.readMeshString(event.summary),
68797
+ ...relayTimestamp !== void 0 ? { timestamp: relayTimestamp } : {}
67549
68798
  };
67550
68799
  if (coordinatorDaemonId === localDaemonId) {
67551
68800
  try {
@@ -67560,6 +68809,22 @@ ${err?.stack || ""}`);
67560
68809
  await this.meshManager.sendCommand(coordinatorDaemonId, "mesh_forward_event", payload);
67561
68810
  LOG.info("MeshEvents", `Relayed ${payload.event} for mesh ${meshId} to coordinator daemon ${coordinatorDaemonId.slice(0, 12)}\u2026`);
67562
68811
  } catch (error48) {
68812
+ queuePendingMeshCoordinatorEvent({
68813
+ event: payload.event,
68814
+ meshId,
68815
+ nodeLabel: payload.nodeId ? `Node '${payload.nodeId}'` : payload.workspace ? `Agent at ${payload.workspace}` : "Remote agent",
68816
+ nodeId: payload.nodeId || void 0,
68817
+ workspace: payload.workspace || void 0,
68818
+ metadataEvent: {
68819
+ targetSessionId: payload.targetSessionId,
68820
+ providerType: payload.providerType,
68821
+ providerSessionId: payload.providerSessionId,
68822
+ finalSummary: payload.finalSummary,
68823
+ workspace: payload.workspace,
68824
+ ...payload.timestamp !== void 0 ? { timestamp: payload.timestamp } : {}
68825
+ },
68826
+ queuedAt: Date.now()
68827
+ });
67563
68828
  LOG.warn("MeshEvents", `Failed to relay ${payload.event} for mesh ${meshId}: ${error48?.message || error48}`);
67564
68829
  }
67565
68830
  }
@@ -82608,7 +83873,7 @@ var require_buffer_list = __commonJS({
82608
83873
  }
82609
83874
  }, {
82610
83875
  key: "join",
82611
- value: function join36(s) {
83876
+ value: function join37(s) {
82612
83877
  if (this.length === 0) return "";
82613
83878
  var p = this.head;
82614
83879
  var ret = "" + p.data;
@@ -96667,13 +97932,13 @@ function splitStringBySpace(str2) {
96667
97932
  }
96668
97933
  return pieces;
96669
97934
  }
96670
- var import_chardet, import_child_process14, import_fs12, import_node_path3, import_node_os3, import_node_crypto3, import_iconv_lite, ExternalEditor;
97935
+ var import_chardet, import_child_process14, import_fs13, import_node_path3, import_node_os3, import_node_crypto3, import_iconv_lite, ExternalEditor;
96671
97936
  var init_esm4 = __esm({
96672
97937
  "../../node_modules/@inquirer/external-editor/dist/esm/index.js"() {
96673
97938
  "use strict";
96674
97939
  import_chardet = __toESM(require_lib2(), 1);
96675
97940
  import_child_process14 = require("child_process");
96676
- import_fs12 = require("fs");
97941
+ import_fs13 = require("fs");
96677
97942
  import_node_path3 = __toESM(require("path"), 1);
96678
97943
  import_node_os3 = __toESM(require("os"), 1);
96679
97944
  import_node_crypto3 = require("crypto");
@@ -96749,14 +98014,14 @@ var init_esm4 = __esm({
96749
98014
  if (Object.prototype.hasOwnProperty.call(this.fileOptions, "mode")) {
96750
98015
  opt.mode = this.fileOptions.mode;
96751
98016
  }
96752
- (0, import_fs12.writeFileSync)(this.tempFile, this.text, opt);
98017
+ (0, import_fs13.writeFileSync)(this.tempFile, this.text, opt);
96753
98018
  } catch (createFileError) {
96754
98019
  throw new CreateFileError(createFileError);
96755
98020
  }
96756
98021
  }
96757
98022
  readTemporaryFile() {
96758
98023
  try {
96759
- const tempFileBuffer = (0, import_fs12.readFileSync)(this.tempFile);
98024
+ const tempFileBuffer = (0, import_fs13.readFileSync)(this.tempFile);
96760
98025
  if (tempFileBuffer.length === 0) {
96761
98026
  this.text = "";
96762
98027
  } else {
@@ -96772,7 +98037,7 @@ var init_esm4 = __esm({
96772
98037
  }
96773
98038
  removeTemporaryFile() {
96774
98039
  try {
96775
- (0, import_fs12.unlinkSync)(this.tempFile);
98040
+ (0, import_fs13.unlinkSync)(this.tempFile);
96776
98041
  } catch (removeFileError) {
96777
98042
  throw new RemoveFileError(removeFileError);
96778
98043
  }