@adhdev/daemon-standalone 1.0.44-rc.1 → 1.0.44-rc.2

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
@@ -36556,10 +36556,10 @@ var require_dist3 = __commonJS({
36556
36556
  }
36557
36557
  function getDaemonBuildInfo() {
36558
36558
  if (cached2) return cached2;
36559
- const commit = readInjected(true ? "c44c9ecb04316113166fd0c06a0a3584f072be76" : void 0) ?? "unknown";
36560
- const commitShort = readInjected(true ? "c44c9ecb" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36561
- const version2 = readInjected(true ? "1.0.44-rc.1" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36562
- const builtAt = readInjected(true ? "2026-08-11T06:22:26.388Z" : void 0);
36559
+ const commit = readInjected(true ? "648305378fc7e0a1970cfe964a80ce7a68172964" : void 0) ?? "unknown";
36560
+ const commitShort = readInjected(true ? "64830537" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36561
+ const version2 = readInjected(true ? "1.0.44-rc.2" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36562
+ const builtAt = readInjected(true ? "2026-08-11T08:23:49.936Z" : void 0);
36563
36563
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
36564
36564
  return cached2;
36565
36565
  }
@@ -45717,14 +45717,60 @@ Next step: ${nextStep}`;
45717
45717
  const reconciled = terminalJobIds.size === 0 ? events : events.filter((event) => !(event.event === "refine:accepted" && terminalJobIds.has(readRefineJobId2(event))));
45718
45718
  return backfilled.length === 0 ? reconciled : [...reconciled, ...backfilled];
45719
45719
  }
45720
+ function getPendingRetentionCounters() {
45721
+ return { ...pendingRetentionCounters };
45722
+ }
45723
+ function ledgerRecordExpiredUndrainedEvent(row) {
45724
+ try {
45725
+ const restored = row.payload && typeof row.payload === "object" ? row.payload : void 0;
45726
+ const finalSummary = restored?.metadataEvent ? readMeshCompletionSummary(restored.metadataEvent) : void 0;
45727
+ appendLedgerEntry(row.meshId, {
45728
+ kind: "event_held",
45729
+ ...restored?.nodeId ? { nodeId: restored.nodeId } : {},
45730
+ payload: {
45731
+ event: row.event,
45732
+ reason: PENDING_RETENTION_EXPIRED_HOLD_REASON,
45733
+ recoverable: true,
45734
+ nodeLabel: restored?.nodeLabel ?? "",
45735
+ ...restored?.workspace ? { workspace: restored.workspace } : {},
45736
+ targetCoordinatorDaemonId: restored?.targetCoordinatorDaemonId ?? null,
45737
+ ...readNonEmptyString(restored?.eventId) ? { eventId: restored.eventId } : {},
45738
+ queuedAt: restored?.queuedAt ?? null,
45739
+ ...finalSummary ? { finalSummary } : {},
45740
+ // Full original event so mesh_requeue_held_events can restore it
45741
+ // losslessly (event_held→pending), same as every other event_held feeder.
45742
+ ...restored ? { heldEvent: restored } : {}
45743
+ }
45744
+ });
45745
+ } catch (e) {
45746
+ pendingRetentionCounters.undrainedExpiredMirrorFailed++;
45747
+ LOG2.warn("MeshEvents", `Failed to ledger-record retention-expired pending event ${row.event} (row ${row.id}, mesh ${row.meshId}) \u2014 it is being deleted UNRECOVERABLY: ${e?.message || e}`);
45748
+ }
45749
+ }
45720
45750
  function prunePendingMeshCoordinatorEventsRetention() {
45721
45751
  try {
45722
- const removed = MeshRuntimeStore.getInstance().prunePendingEvents({
45752
+ const { drainedExpired, undrainedExpired, undrainedRows } = MeshRuntimeStore.getInstance().prunePendingEvents({
45723
45753
  drainedOlderThanMs: PENDING_EVENTS_DRAINED_RETENTION_MS,
45724
45754
  undrainedOlderThanMs: PENDING_EVENTS_UNDRAINED_RETENTION_MS
45725
45755
  });
45756
+ pendingRetentionCounters.drainedExpired += drainedExpired;
45757
+ pendingRetentionCounters.undrainedExpired += undrainedExpired;
45758
+ if (undrainedRows.length > 0) {
45759
+ for (const row of undrainedRows) {
45760
+ ledgerRecordExpiredUndrainedEvent(row);
45761
+ }
45762
+ const meshIds = [...new Set(undrainedRows.map((r) => r.meshId))];
45763
+ const droppedAt = (/* @__PURE__ */ new Date()).toISOString();
45764
+ LOG2.warn(
45765
+ "MeshEvents",
45766
+ `Pending-event retention DROPPED ${undrainedRows.length} never-delivered event(s) at ${droppedAt} (queued >30d, still undrained) across mesh(es) ${meshIds.join(", ")} \u2014 mirrored to the ledger as event_held (reason: ${PENDING_RETENTION_EXPIRED_HOLD_REASON}); recover with mesh_requeue_held_events.`
45767
+ );
45768
+ }
45769
+ const removed = drainedExpired + undrainedExpired;
45726
45770
  if (removed > 0) {
45727
45771
  LOG2.info("MeshEvents", `Pruned ${removed} stale pending-event row(s) (drained >7d / undrained >30d)`);
45772
+ } else {
45773
+ pendingRetentionCounters.sweepsNoop++;
45728
45774
  }
45729
45775
  return removed;
45730
45776
  } catch (e) {
@@ -46053,6 +46099,8 @@ Next step: ${nextStep}`;
46053
46099
  var TERMINAL_COMPLETION_EVENTS;
46054
46100
  var PENDING_EVENTS_DRAINED_RETENTION_MS;
46055
46101
  var PENDING_EVENTS_UNDRAINED_RETENTION_MS;
46102
+ var PENDING_RETENTION_EXPIRED_HOLD_REASON;
46103
+ var pendingRetentionCounters;
46056
46104
  var init_mesh_events_pending = __esm2({
46057
46105
  "src/mesh/mesh-events-pending.ts"() {
46058
46106
  "use strict";
@@ -46101,6 +46149,22 @@ Next step: ${nextStep}`;
46101
46149
  TERMINAL_COMPLETION_EVENTS = /* @__PURE__ */ new Set(["agent:generating_completed", "agent:stopped"]);
46102
46150
  PENDING_EVENTS_DRAINED_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
46103
46151
  PENDING_EVENTS_UNDRAINED_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
46152
+ PENDING_RETENTION_EXPIRED_HOLD_REASON = "pending_retention_expired";
46153
+ pendingRetentionCounters = {
46154
+ /** Already-drained rows deleted past the 7-day dedup-useful window. Not a drop. */
46155
+ drainedExpired: 0,
46156
+ /** Never-delivered rows deleted past the 30-day undrained window. A genuine
46157
+ * silent-drop risk — mirrored to event_held before deletion (see below). */
46158
+ undrainedExpired: 0,
46159
+ /** undrainedExpired rows that failed to mirror to the ledger (ledger write threw).
46160
+ * Non-zero here means those specific rows are NOT recoverable via
46161
+ * mesh_requeue_held_events — the delete still proceeds (retention must not wedge
46162
+ * on a ledger fault), but this count is the operator's signal of true loss. */
46163
+ undrainedExpiredMirrorFailed: 0,
46164
+ /** How many times the sweep has run and found nothing to prune (0 in both
46165
+ * windows). Purely diagnostic — confirms the sweep is actually firing. */
46166
+ sweepsNoop: 0
46167
+ };
46104
46168
  }
46105
46169
  });
46106
46170
  var mesh_missions_exports = {};
@@ -49838,21 +49902,43 @@ Next step: ${nextStep}`;
49838
49902
  * receives its backlog; only genuinely unrecoverable orphans are swept.
49839
49903
  *
49840
49904
  * Both windows key off `queued_at` (always present) — `drained_at` can be NULL on
49841
- * legacy rows. Returns the number of rows deleted. Best-effort / idempotent:
49842
- * running it repeatedly with nothing to prune is a cheap no-op.
49905
+ * legacy rows. Returns the number of rows deleted, split by which window matched:
49906
+ * `drainedExpired` (already-delivered rows past the dedup-useful window not a
49907
+ * drop, the coordinator already got these) and `undrainedExpired` (rows that were
49908
+ * NEVER delivered — a genuine silent drop, same shape as the retired JSONL trim's
49909
+ * `pending_trim_dropped`). `undrainedRows` carries the id/meshId/event/payload of
49910
+ * every undrained-expired row BEFORE deletion so the caller can mirror it to the
49911
+ * mesh ledger as `event_held` (recoverable via mesh_requeue_held_events) instead of
49912
+ * losing it silently — this is the observability gap the retired trim used to cover
49913
+ * and the SQLite-only cutover left open. Best-effort / idempotent: running it
49914
+ * repeatedly with nothing to prune is a cheap no-op.
49843
49915
  */
49844
49916
  prunePendingEvents(opts) {
49845
49917
  const now = Date.now();
49846
49918
  const drainedCutoff = now - Math.max(0, opts.drainedOlderThanMs);
49847
49919
  const undrainedCutoff = now - Math.max(0, opts.undrainedOlderThanMs);
49848
- let removed = 0;
49849
- removed += this.db.prepare(
49920
+ const undrainedSelectRows = this.db.prepare(
49921
+ "SELECT id, mesh_id, event, payload FROM mesh_pending_events WHERE drained = 0 AND queued_at < ?"
49922
+ ).all(undrainedCutoff);
49923
+ const undrainedRows = undrainedSelectRows.map((r) => ({
49924
+ id: r.id,
49925
+ meshId: r.mesh_id,
49926
+ event: r.event,
49927
+ payload: (() => {
49928
+ try {
49929
+ return JSON.parse(r.payload);
49930
+ } catch {
49931
+ return {};
49932
+ }
49933
+ })()
49934
+ }));
49935
+ const drainedExpired = this.db.prepare(
49850
49936
  "DELETE FROM mesh_pending_events WHERE drained = 1 AND queued_at < ?"
49851
49937
  ).run(drainedCutoff).changes;
49852
- removed += this.db.prepare(
49938
+ const undrainedExpired = this.db.prepare(
49853
49939
  "DELETE FROM mesh_pending_events WHERE drained = 0 AND queued_at < ?"
49854
49940
  ).run(undrainedCutoff).changes;
49855
- return removed;
49941
+ return { drainedExpired, undrainedExpired, undrainedRows };
49856
49942
  }
49857
49943
  // ── TURN-LEDGER (Stage 5): authoritative turn attempts ───────────────────
49858
49944
  /**
@@ -60371,7 +60457,17 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
60371
60457
  LOG2.warn("MeshQueue", `Failed to retract stale dispatch-blocked event for task ${taskId} (mesh ${meshId}): ${e?.message || e}`);
60372
60458
  }
60373
60459
  }
60374
- function actionableSkipGuidance(reason) {
60460
+ function resolveTaskDeliveryEvidence(meshId, taskId) {
60461
+ try {
60462
+ const store = MeshRuntimeStore.getInstance();
60463
+ if (store.taskDeliveryConsumed(meshId, taskId)) return "consumed";
60464
+ if (store.taskHasConfirmedDelivery(meshId, taskId)) return "delivered";
60465
+ } catch {
60466
+ return "delivered";
60467
+ }
60468
+ return "never_dispatched";
60469
+ }
60470
+ function actionableSkipGuidance(reason, evidence) {
60375
60471
  if (reason === "target_node_id_unmatched") return {
60376
60472
  summary: "it is pinned to a target node id that matches no node in the mesh (the node may have been removed, or its id form does not resolve)",
60377
60473
  nextAction: "Verify the target node still exists with mesh_status, then re-enqueue without the node pin or with a valid node id (or re-clone the node)."
@@ -60396,10 +60492,20 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
60396
60492
  summary: "the node's workspace is dirty, so auto-launch is blocked to avoid clobbering uncommitted changes",
60397
60493
  nextAction: "Clean or commit the node's working tree (or fast-forward it); the task will then auto-assign."
60398
60494
  };
60399
- if (reason === "target_session_pin_expired") return {
60400
- summary: "it was pinned to a specific session (a follow-up/delta for work already in flight) that never claimed it within the pin TTL, so the pin was cleared and the message will NOT reach the session it was addressed to",
60401
- nextAction: "Assume the addressed session never received this delta and is still acting on its previous instructions. Re-send it to that session once it is idle (or re-target it), and re-check the work it produced in the meantime."
60402
- };
60495
+ if (reason === "target_session_pin_expired") {
60496
+ if (evidence === "consumed") return {
60497
+ summary: "it was pinned to a specific session and the pin TTL expired before the queue row was claimed \u2014 but the delivery record shows this session DID receive and start acting on the message (a turn was started for it), so the queue row lagging is a bookkeeping gap, not a lost delta",
60498
+ nextAction: "Do NOT re-send it \u2014 the session already has this message and re-sending would run the same instruction twice. Check its current output (mesh_read_chat / mesh_read_terminal) to confirm the work is under way."
60499
+ };
60500
+ if (evidence === "delivered") return {
60501
+ summary: "it was pinned to a specific session and the pin TTL expired before the queue row was claimed; the message WAS handed to that session's transport, but the session never echoed a turn start, so whether it acted on it is unconfirmed",
60502
+ nextAction: "Verify before re-sending: check the session with mesh_read_chat / mesh_read_terminal. Re-send only if its output shows no sign of this message \u2014 it may already be acting on it, and re-sending would duplicate the instruction."
60503
+ };
60504
+ return {
60505
+ summary: "it was pinned to a specific session (a follow-up/delta for work already in flight) that never claimed it within the pin TTL, so the pin was cleared; no delivery to that session was ever recorded, so the message did not reach it",
60506
+ nextAction: "The addressed session never received this delta and is still acting on its previous instructions. Re-send it to that session once it is idle (or re-target it), and re-check the work it produced in the meantime."
60507
+ };
60508
+ }
60403
60509
  if (reason === SLOT_MODEL_ABSENT_SKIP_REASON) return {
60404
60510
  summary: "no capability slot on the node declares the model this task resolved to (its difficulty\u2192brain preset picked a model the node was never configured to run)",
60405
60511
  nextAction: "Re-enqueue with a difficulty/model the node's slots declare, target a node that declares this model, or add a slot for it. The task is NOT run on a substitute model \u2014 an undeclared model is never launched."
@@ -60427,8 +60533,10 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
60427
60533
  const targetCoordinatorDaemonId = readNonEmptyString(loadConfig2().machineId);
60428
60534
  const targetCoordinatorSessionId = readNonEmptyString(task?.sourceCoordinatorSessionId);
60429
60535
  const nodeLabel = readNonEmptyString(nodeId) || readNonEmptyString(task?.targetNodeId);
60430
- const { summary, nextAction } = actionableSkipGuidance(reason);
60431
- const coordinatorMessage = `[System] A queued mesh task${nodeLabel ? ` for node ${nodeLabel}` : ""} is not being dispatched because ${summary}. ${nextAction} This is an actionable blocker \u2014 it will NOT clear on its own; the task stays pending until you resolve it.`;
60536
+ const evidence = reason === "target_session_pin_expired" ? resolveTaskDeliveryEvidence(meshId, taskId) : void 0;
60537
+ const { summary, nextAction } = actionableSkipGuidance(reason, evidence);
60538
+ const closing = reason === "target_session_pin_expired" ? "The stale pin has already been cleared, so the task is now claimable by any compatible session \u2014 the action above is about the session it was originally addressed to." : "This is an actionable blocker \u2014 it will NOT clear on its own; the task stays pending until you resolve it.";
60539
+ const coordinatorMessage = `[System] A queued mesh task${nodeLabel ? ` for node ${nodeLabel}` : ""} is not being dispatched because ${summary}. ${nextAction} ${closing}`;
60432
60540
  try {
60433
60541
  queuePendingMeshCoordinatorEvent({
60434
60542
  event: "mesh:dispatch_blocked",
@@ -60461,6 +60569,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
60461
60569
  "use strict";
60462
60570
  init_logger();
60463
60571
  init_mesh_work_queue();
60572
+ init_mesh_runtime_store();
60464
60573
  init_dist();
60465
60574
  init_mesh_events_utils();
60466
60575
  init_mesh_events_pending();
@@ -60879,14 +60988,15 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
60879
60988
  if (timer) clearTimeout(timer);
60880
60989
  const isQueued = res && typeof res === "object" && res.status === "queued";
60881
60990
  updateSessionDeliveryStatus(delivery.id, isQueued ? "queued" : "delivered");
60882
- if (!isQueued && ctx.task.attemptId) {
60991
+ if (ctx.task.attemptId) {
60883
60992
  try {
60884
60993
  recordTurnAck({
60885
60994
  meshId: ctx.meshId,
60886
60995
  taskId: ctx.task.id,
60887
- kind: "delivered",
60996
+ kind: isQueued ? "accepted" : "delivered",
60888
60997
  attemptId: ctx.task.attemptId,
60889
- sessionId: ctx.sessionId
60998
+ sessionId: ctx.sessionId,
60999
+ ...isQueued ? { evidence: { source: "transport_queued_in_adapter" } } : {}
60890
61000
  });
60891
61001
  } catch {
60892
61002
  }
@@ -60927,22 +61037,52 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
60927
61037
  LOG2.error("MeshQueue", `Failed to dispatch task via ${ctx.transport} to node ${ctx.nodeId}: ${e?.message}`);
60928
61038
  updateSessionDeliveryStatus(delivery.id, "failed", { lastError: e?.message, incrementAttempt: true });
60929
61039
  endTaskDispatchInFlight(ctx.meshId, ctx.task.id);
60930
- updateTaskStatus(ctx.meshId, ctx.task.id, "pending");
60931
61040
  try {
60932
61041
  closeAttemptForReassignment({ meshId: ctx.meshId, taskId: ctx.task.id, reason: "dispatch_failed" });
60933
61042
  } catch {
60934
61043
  }
61044
+ const retryable = isRetryableDispatchFailure(e);
61045
+ if (!retryable) {
61046
+ failTaskAsUndeliverable(ctx, `dispatch_unrecoverable: ${e?.message || "transport reported the failure as non-recoverable"}`);
61047
+ } else {
61048
+ const requeued = requeueTask(ctx.meshId, ctx.task.id, {
61049
+ reason: "dispatch_failed",
61050
+ clearTargetSession: false
61051
+ });
61052
+ if (requeued?.status === "failed") {
61053
+ LOG2.error("MeshQueue", `Task ${ctx.task.id} (mesh ${ctx.meshId}) failed after repeated undeliverable dispatches to node ${ctx.nodeId}: ${requeued.cancelReason || "max_retries_exceeded"}. Dependents were unblocked.`);
61054
+ }
61055
+ }
60935
61056
  try {
60936
61057
  appendLedgerEntry(ctx.meshId, {
60937
61058
  kind: "dispatch_failed",
60938
61059
  nodeId: ctx.nodeId,
60939
61060
  sessionId: ctx.sessionId,
60940
- payload: { taskId: ctx.task.id, deliveryId: delivery.id, error: e?.message, retryable: isRetryableDispatchFailure(e), transport: ctx.transport }
61061
+ payload: { taskId: ctx.task.id, deliveryId: delivery.id, error: e?.message, retryable, transport: ctx.transport }
60941
61062
  });
60942
61063
  } catch {
60943
61064
  }
60944
61065
  });
60945
61066
  }
61067
+ function failTaskAsUndeliverable(ctx, reason) {
61068
+ try {
61069
+ const failed = requeueTask(ctx.meshId, ctx.task.id, { maxRetries: 0, reason, clearTargetSession: false });
61070
+ if (!failed) return;
61071
+ } catch (err) {
61072
+ LOG2.warn("MeshQueue", `Failed to mark undeliverable task ${ctx.task.id} (mesh ${ctx.meshId}) terminal: ${err?.message || err}`);
61073
+ return;
61074
+ }
61075
+ LOG2.error("MeshQueue", `Task ${ctx.task.id} (mesh ${ctx.meshId}) is undeliverable to node ${ctx.nodeId} (session ${ctx.sessionId ?? "?"}) and will NOT be retried: ${reason}`);
61076
+ try {
61077
+ appendLedgerEntry(ctx.meshId, {
61078
+ kind: "task_failed",
61079
+ nodeId: ctx.nodeId,
61080
+ sessionId: ctx.sessionId,
61081
+ payload: { taskId: ctx.task.id, reason, undeliverable: true }
61082
+ });
61083
+ } catch {
61084
+ }
61085
+ }
60946
61086
  function isRetryableDispatchFailure(e) {
60947
61087
  if (e && typeof e === "object") {
60948
61088
  if (e.retryRecommended === false) return false;
@@ -69010,6 +69150,7 @@ ${cleanBody}`;
69010
69150
  });
69011
69151
  var mesh_events_exports = {};
69012
69152
  __export2(mesh_events_exports, {
69153
+ PENDING_RETENTION_EXPIRED_HOLD_REASON: () => PENDING_RETENTION_EXPIRED_HOLD_REASON,
69013
69154
  __resetIdleAutoFastForwardForTests: () => __resetIdleAutoFastForwardForTests,
69014
69155
  __resetMeshWorkspaceCacheForTests: () => __resetMeshWorkspaceCacheForTests,
69015
69156
  clearPendingMeshCoordinatorEvents: () => clearPendingMeshCoordinatorEvents,
@@ -69017,6 +69158,7 @@ ${cleanBody}`;
69017
69158
  getMeshV2BackstopCounters: () => getMeshV2BackstopCounters,
69018
69159
  getMeshV2DrainCounters: () => getMeshV2DrainCounters,
69019
69160
  getPendingMeshCoordinatorEvents: () => getPendingMeshCoordinatorEvents,
69161
+ getPendingRetentionCounters: () => getPendingRetentionCounters,
69020
69162
  handleMeshForwardEvent: () => handleMeshForwardEvent,
69021
69163
  isMeshCoordinatorEvent: () => isMeshCoordinatorEvent,
69022
69164
  isMeshProtocolV2EnforceEnabled: () => isMeshProtocolV2EnforceEnabled,
@@ -110848,7 +110990,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
110848
110990
  drain: { ...getMeshV2DrainCounters() },
110849
110991
  backstop: { ...getMeshV2BackstopCounters() }
110850
110992
  };
110851
- return { success: true, events, hasLiveCliCoordinator, meshProtocolV2Counters, ...selfCoordinatorInboxRead ? { surfacedForSelfCoordinator: true } : {} };
110993
+ const pendingRetentionCounters2 = { ...getPendingRetentionCounters() };
110994
+ return { success: true, events, hasLiveCliCoordinator, meshProtocolV2Counters, pendingRetentionCounters: pendingRetentionCounters2, ...selfCoordinatorInboxRead ? { surfacedForSelfCoordinator: true } : {} };
110852
110995
  },
110853
110996
  interactive_prompt_response: async (ctx, args) => {
110854
110997
  const sessionId = typeof args?.targetSessionId === "string" && args.targetSessionId.trim() ? args.targetSessionId.trim() : typeof args?.sessionId === "string" && args.sessionId.trim() ? args.sessionId.trim() : "";
@@ -112005,6 +112148,7 @@ ${ptyResult.output.slice(-2e3)}`);
112005
112148
  drain: { ...getMeshV2DrainCounters() },
112006
112149
  backstop: { ...getMeshV2BackstopCounters() }
112007
112150
  };
112151
+ const pendingRetentionCounters2 = { ...getPendingRetentionCounters() };
112008
112152
  const turnPresentationCounters = getTurnPresentationMetrics();
112009
112153
  const previewFreshness = (() => {
112010
112154
  const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs43.existsSync(candidate));
@@ -112096,6 +112240,7 @@ ${ptyResult.output.slice(-2e3)}`);
112096
112240
  ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
112097
112241
  ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {},
112098
112242
  meshProtocolV2Counters,
112243
+ pendingRetentionCounters: pendingRetentionCounters2,
112099
112244
  turnPresentationCounters,
112100
112245
  activeRefineJobs: Array.from(ctx.runningRefineJobs.values()).filter((job) => job.meshId === meshId).map((job) => ({
112101
112246
  jobId: job.jobId,
@@ -112106,13 +112251,14 @@ ${ptyResult.output.slice(-2e3)}`);
112106
112251
  targetCoordinatorDaemonId: job.targetCoordinatorDaemonId
112107
112252
  }))
112108
112253
  };
112109
- const { pendingCoordinatorEvents: _pendingCoordinatorEvents, unroutableDeliveries: _unroutableDeliveries, meshProtocolV2Counters: _meshProtocolV2Counters, turnPresentationCounters: _turnPresentationCounters, ...cacheableStatusResult } = statusResult;
112254
+ const { pendingCoordinatorEvents: _pendingCoordinatorEvents, unroutableDeliveries: _unroutableDeliveries, meshProtocolV2Counters: _meshProtocolV2Counters, pendingRetentionCounters: _pendingRetentionCounters, turnPresentationCounters: _turnPresentationCounters, ...cacheableStatusResult } = statusResult;
112110
112255
  const rememberedStatus = verboseMissions ? cacheableStatusResult : ctx.rememberAggregateMeshStatus(meshId, cacheableStatusResult, refreshReason);
112111
112256
  const returnedStatus = {
112112
112257
  ...rememberedStatus,
112113
112258
  ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
112114
112259
  ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {},
112115
112260
  meshProtocolV2Counters,
112261
+ pendingRetentionCounters: pendingRetentionCounters2,
112116
112262
  turnPresentationCounters
112117
112263
  };
112118
112264
  logRepoMeshStatusDebug("return_live", {
@@ -115977,17 +116123,27 @@ ${e?.stderr || ""}`;
115977
116123
  }
115978
116124
  async function startMeshRefineJob(self, meshId, nodeId, args) {
115979
116125
  const key2 = buildRefineJobKey(self, meshId, nodeId);
115980
- const running = self.runningRefineJobs.get(key2);
115981
- if (running) return { ...running, duplicate: true };
115982
116126
  const terminal = self.terminalRefineJobs.get(key2);
116127
+ const alreadyRunning = self.runningRefineJobs.get(key2);
116128
+ if (alreadyRunning) return { ...alreadyRunning, duplicate: true };
116129
+ const jobId = `refine_${createInteractionId()}`;
116130
+ const interactionId = createInteractionId();
116131
+ const placeholder = buildRefineJobHandle(self, { meshId, nodeId, jobId, interactionId, retryOfJobId: terminal?.jobId });
116132
+ self.runningRefineJobs.set(key2, placeholder);
115983
116133
  const meshRecord = await self.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
115984
116134
  const mesh = meshRecord?.mesh;
115985
116135
  const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
115986
- if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
115987
- if (!node.isLocalWorktree || !node.workspace) return { success: false, error: `Refinery requires a local worktree node` };
116136
+ if (!node) {
116137
+ self.runningRefineJobs.delete(key2);
116138
+ return { success: false, error: `Node '${nodeId}' not found in mesh` };
116139
+ }
116140
+ if (!node.isLocalWorktree || !node.workspace) {
116141
+ self.runningRefineJobs.delete(key2);
116142
+ return { success: false, error: `Refinery requires a local worktree node` };
116143
+ }
115988
116144
  const coordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : self.deps.statusInstanceId || void 0;
115989
116145
  const coordinatorSessionId = typeof args?.coordinatorSessionId === "string" && args.coordinatorSessionId.trim() ? args.coordinatorSessionId.trim() : void 0;
115990
- const handle = buildRefineJobHandle(self, { meshId, nodeId, node, retryOfJobId: terminal?.jobId, coordinatorDaemonId, coordinatorSessionId });
116146
+ const handle = buildRefineJobHandle(self, { meshId, nodeId, node, jobId, interactionId, retryOfJobId: terminal?.jobId, coordinatorDaemonId, coordinatorSessionId });
115991
116147
  self.runningRefineJobs.set(key2, handle);
115992
116148
  await appendRefineJobLedger(self, "task_dispatched", handle);
115993
116149
  queueRefineJobEvent(self, "refine:accepted", handle);