@adhdev/daemon-core 0.9.82-rc.376 → 0.9.82-rc.378

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.
Files changed (48) hide show
  1. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  2. package/dist/commands/chat-commands-read.d.ts +7 -0
  3. package/dist/commands/chat-commands-scope.d.ts +39 -0
  4. package/dist/commands/chat-commands-shared.d.ts +33 -0
  5. package/dist/commands/chat-commands-write.d.ts +14 -0
  6. package/dist/commands/chat-commands.d.ts +9 -49
  7. package/dist/commands/router.d.ts +3 -470
  8. package/dist/index.js +3166 -3115
  9. package/dist/index.js.map +1 -1
  10. package/dist/index.mjs +3561 -3510
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  13. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  14. package/dist/mesh/mesh-event-forwarding.d.ts +18 -0
  15. package/dist/mesh/mesh-events-coordinator.d.ts +4 -92
  16. package/dist/mesh/mesh-events-utils.d.ts +3 -0
  17. package/dist/mesh/mesh-ledger-reconciliation.d.ts +0 -1
  18. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  19. package/dist/mesh/mesh-queue-assignment.d.ts +86 -0
  20. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  21. package/dist/mesh/mesh-runtime-store.d.ts +0 -3
  22. package/dist/providers/native-history/constants.d.ts +12 -0
  23. package/dist/runtime-defaults.d.ts +2 -0
  24. package/package.json +2 -2
  25. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  26. package/src/commands/chat-commands-read.ts +2327 -0
  27. package/src/commands/chat-commands-scope.ts +54 -0
  28. package/src/commands/chat-commands-shared.ts +114 -0
  29. package/src/commands/chat-commands-write.ts +880 -0
  30. package/src/commands/chat-commands.ts +20 -3697
  31. package/src/commands/router.ts +59 -3631
  32. package/src/mesh/mesh-coordinator-config.ts +97 -0
  33. package/src/mesh/mesh-event-classify.ts +51 -0
  34. package/src/mesh/mesh-event-forwarding.ts +1502 -0
  35. package/src/mesh/mesh-events-coordinator.ts +30 -2993
  36. package/src/mesh/mesh-events-pending.ts +1 -10
  37. package/src/mesh/mesh-events-stale.ts +3 -14
  38. package/src/mesh/mesh-events-utils.ts +52 -14
  39. package/src/mesh/mesh-ledger-reconciliation.ts +0 -2
  40. package/src/mesh/mesh-node-identity.ts +1887 -0
  41. package/src/mesh/mesh-queue-assignment.ts +1457 -0
  42. package/src/mesh/mesh-refine-gates.ts +1652 -0
  43. package/src/mesh/mesh-runtime-store.ts +0 -37
  44. package/src/providers/cli-provider-instance.ts +40 -1
  45. package/src/providers/native-history/constants.ts +19 -0
  46. package/src/providers/native-history/dispatcher.ts +2 -3
  47. package/src/providers/spec/native-history-executor.ts +1 -9
  48. package/src/runtime-defaults.ts +39 -0
@@ -0,0 +1,1457 @@
1
+ import { existsSync } from 'fs';
2
+ import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
3
+ import { MESH_CONNECT_TIMEOUT_MS } from '../runtime-defaults.js';
4
+ import { loadConfig } from '../config/config.js';
5
+ import { getMesh } from '../config/mesh-config.js';
6
+ import { detectCLI } from '../detection/cli-detector.js';
7
+ import { LOG } from '../logging/logger.js';
8
+ import { appendLedgerEntry } from './mesh-ledger.js';
9
+ import { buildMeshNodeCapabilityTags, nodeSatisfiesRequiredTags, claimNextTask, updateTaskStatus, getQueue, recordTaskAutoLaunch, getActiveDirectDispatches } from './mesh-work-queue.js';
10
+ import type { MeshWorkQueueEntry } from './mesh-work-queue.js';
11
+ import { fastForwardMeshNode } from './mesh-fast-forward.js';
12
+ import { createSessionDelivery, updateSessionDeliveryStatus } from './mesh-delivery-policy.js';
13
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
14
+ import { traceMeshEventDrop } from './mesh-event-trace.js';
15
+ import { awaitWithWarmupDeadline, resolveWarmupDeadlineOpts } from './mesh-warmup-deadline.js';
16
+ import { resolveDelegatedWorkerAutoApprove, resolveProviderMaxParallel, resolveNodeSchedulingPriority, normalizeMeshSchedulingStrategy } from '../repo-mesh-types.js';
17
+ import type { RepoMeshSchedulingStrategy } from '../repo-mesh-types.js';
18
+ import { normalizeMeshNodeId, meshNodeIdMatches, daemonIdsEquivalent, normalizeMeshWorkspaceForCompare, meshWorkspacesEquivalent, type MeshNodeIdentified } from '@adhdev/mesh-shared';
19
+ import { findTerminalLedgerEvidenceForTask, hasUnterminalDirectDispatchLedgerEntry } from './mesh-events-stale.js';
20
+ import { readNonEmptyString } from './mesh-events-utils.js';
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Idle auto fast-forward throttle state
24
+ // ---------------------------------------------------------------------------
25
+ const IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1000;
26
+ const idleAutoFastForwardLastAttempt = new Map<string, number>();
27
+
28
+ export function __resetIdleAutoFastForwardForTests(): void {
29
+ idleAutoFastForwardLastAttempt.clear();
30
+ }
31
+
32
+ export function getMeshWithCache(components: DaemonComponents, meshId: string): any | undefined {
33
+ const localMesh = getMesh(meshId);
34
+ const cachedMesh = components.router?.getCachedInlineMesh(meshId);
35
+ if (!localMesh) return cachedMesh;
36
+ if (!cachedMesh) return localMesh;
37
+ return mergeInlineCacheOnlyNodes(localMesh, cachedMesh);
38
+ }
39
+
40
+ /**
41
+ * Claim-time membership view unification (CLAIMSTALL fix).
42
+ *
43
+ * The coordinator's claim path — triggerMeshQueue → autoLaunch candidate filter
44
+ * and the local/remote idle-session drain — reads mesh membership through
45
+ * getMeshWithCache, which historically returned the local-config mesh verbatim
46
+ * whenever one existed. A freshly cloned worktree node is registered ONLY into the
47
+ * router's inline mesh cache: clone_mesh_node's `meshRecord.inline` branch calls
48
+ * updateInlineMeshNode, NOT addNode, so the worktree node never reaches local
49
+ * config (meshes.json). The config-first view therefore omits the worktree node,
50
+ * while send_task — which resolves membership through getMeshForCommand(preferInline)
51
+ * over the same inline cache — sees it. That view asymmetry is the stall: a queue
52
+ * task pinned to the worktree node reports `target_node_id_unmatched` (autoLaunch
53
+ * candidate filter / targetPinUnmatched check) and the node's idle session is
54
+ * dropped from the drain pool (mesh.nodes.find miss), so claim never fires and the
55
+ * task is stranded pending — even though nodeId matching itself is correct.
56
+ *
57
+ * Fix: union the local-config nodes with any inline-cache-ONLY nodes, so the claim
58
+ * view matches the command (send_task) view. Base (non-worktree) nodes present in
59
+ * local config stay config-authoritative — their entry is taken verbatim from
60
+ * localMesh, so base node claim/matching is byte-for-byte unchanged. Only nodes
61
+ * that exist solely in the inline cache (the cloned worktree nodes) are appended.
62
+ * Identity comparison uses the shared 3-form normalizer (id / nodeId / node_id),
63
+ * identical to every other claim-path consumer — the matching logic is untouched,
64
+ * only which nodes are visible.
65
+ */
66
+ function mergeInlineCacheOnlyNodes(localMesh: any, cachedMesh: any): any {
67
+ const localNodes = Array.isArray(localMesh?.nodes) ? localMesh.nodes : [];
68
+ const cachedNodes = Array.isArray(cachedMesh?.nodes) ? cachedMesh.nodes : [];
69
+ if (!cachedNodes.length) return localMesh;
70
+ const cacheOnly = cachedNodes.filter((cachedNode: any) => {
71
+ const cachedId = readMeshNodeId(cachedNode);
72
+ // Unidentifiable cache entries can never be a claim/route target — skip them
73
+ // rather than appending junk that no consumer can address.
74
+ if (!cachedId) return false;
75
+ return !localNodes.some((localNode: any) => meshNodeIdMatches(localNode, cachedId));
76
+ });
77
+ if (!cacheOnly.length) return localMesh;
78
+ return { ...localMesh, nodes: [...localNodes, ...cacheOnly] };
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Queue assignment
83
+ // ---------------------------------------------------------------------------
84
+
85
+ // Per-dispatch confirmation timeout (Bug B). A dispatch promise that never settles —
86
+ // a saturated remote P2P relay that hangs, or a transport that resolves only after
87
+ // the worker acks — would otherwise leave the just-claimed queue row 'assigned' with
88
+ // its delivery stuck 'delivering' forever: the .catch that requeues never fires, and
89
+ // PHASE 3 reconcile skips the row (it counts 0 pending). Racing the dispatch against
90
+ // this timeout guarantees a hung dispatch deterministically returns the task to
91
+ // 'pending' for re-dispatch. Generous so a merely-slow-but-live dispatch (a cold
92
+ // remote relay) is never reclaimed early; the reconcile assigned-stranded watchdog is
93
+ // the durable cross-restart backstop for a timer lost to a daemon restart.
94
+ const DISPATCH_CONFIRM_TIMEOUT_MS = 120_000;
95
+
96
+ // Cold-open connect budget for the warmup-aware REMOTE task dispatch deadline. A
97
+ // remote `agent_command` to a peer whose mesh DataChannel is not open yet first has
98
+ // to drive the cross-machine (often TURN-relayed) handshake; charging that warmup
99
+ // against the response budget is the same cold-open false-timeout the git_status
100
+ // probe path already guards against. This budget bounds ONLY the "channel not open
101
+ // yet" phase; once the channel is warm the DISPATCH_CONFIRM_TIMEOUT_MS response
102
+ // budget governs (identical to the legacy flat guard for an already-open peer, so
103
+ // no latency is added to a normal dispatch). Matches the daemon-cloud
104
+ // DaemonMeshManager CONNECT_TIMEOUT_MS (45s) so the caller-side deadline tracks the
105
+ // transport's own cold-open window rather than guessing.
106
+ //
107
+ // Sourced from the unified, env-overridable MESH_CONNECT_TIMEOUT_MS (runtime-defaults)
108
+ // — the SAME budget the router's direct-peer git_status probe uses. Previously this
109
+ // was a hard-coded 45_000 while the probe path was env-overridable, so setting the
110
+ // env tuned the probe but silently left this dispatch path at 45s (a silent
111
+ // asymmetry). They now move together.
112
+ const DISPATCH_CONNECT_TIMEOUT_MS = MESH_CONNECT_TIMEOUT_MS;
113
+
114
+ // Fail-loud (throttled) trace for a remote dispatch that ran with NO live mesh
115
+ // connection getter wired — the same degraded-warmup misconfiguration the git probe
116
+ // path warns about. Warn once per peer; resolveWarmupDeadlineOpts then falls back to
117
+ // the conservative combined budget instead of silently assuming "always warm".
118
+ const dispatchWarmupGetterMissingWarned = new Set<string>();
119
+ function warnDispatchWarmupGetterMissingOnce(daemonId: string): void {
120
+ if (dispatchWarmupGetterMissingWarned.has(daemonId)) return;
121
+ dispatchWarmupGetterMissingWarned.add(daemonId);
122
+ LOG.warn('MeshQueue', `Mesh peer connection getter unavailable for ${String(daemonId).slice(0, 12)}; remote task-dispatch warmup deadline degraded to the combined connect+response window. Avoids a cold-open false-timeout but loses warm/cold precision — wire getMeshPeerConnectionStatus on this daemon.`);
123
+ }
124
+
125
+ interface DeliverTaskContext {
126
+ meshId: string;
127
+ nodeId: string;
128
+ sessionId: string;
129
+ providerType: string;
130
+ task: MeshWorkQueueEntry;
131
+ transport: 'remote' | 'local';
132
+ sourceCoordinatorSessionId?: string;
133
+ sourceCoordinatorDaemonId?: string;
134
+ }
135
+
136
+ // CONS scope 3: the SINGLE source of truth for dispatching a claimed task to its
137
+ // session. The remote (P2P dispatchMeshCommand) and local (cliManager.handleCliCommand)
138
+ // branches differ ONLY in the transport call — the delivery record, the delivered/failed
139
+ // transitions, the pending-requeue-on-failure, the dispatch_failed ledger entry, AND the
140
+ // Bug B hang timeout are identical and live here once so a future change to the dispatch
141
+ // lifecycle cannot drift between the two paths. The caller passes a `dispatchThunk` that
142
+ // performs only the transport-specific send and returns its promise.
143
+ //
144
+ // Cold-open warmup (remote only): the REMOTE transport speaks over a P2P
145
+ // DataChannel that may still be opening when the first task is dispatched to a peer.
146
+ // When `warmup` is supplied the dispatch is awaited under the warmup-aware deadline
147
+ // (mesh-warmup-deadline) — the cold-open handshake is charged to the connect budget
148
+ // and only the warm round trip to the DISPATCH_CONFIRM_TIMEOUT_MS response budget —
149
+ // so the very first dispatch to a not-yet-open peer is no longer false-timed at the
150
+ // combined window. An already-open peer behaves identically to the legacy flat guard
151
+ // (response budget governs from t0), so a normal dispatch sees no added latency. The
152
+ // LOCAL transport (in-process cliManager) has no channel to warm up and keeps the
153
+ // flat Bug B hang guard.
154
+ function deliverTaskToSession(
155
+ dispatchThunk: () => Promise<unknown>,
156
+ ctx: DeliverTaskContext,
157
+ warmup?: { daemonId: string; getConnection?: (daemonId: string) => Record<string, unknown> | null },
158
+ ): void {
159
+ const delivery = createSessionDelivery({
160
+ meshId: ctx.meshId,
161
+ nodeId: ctx.nodeId,
162
+ sessionId: ctx.sessionId,
163
+ providerType: ctx.providerType,
164
+ taskId: ctx.task.id,
165
+ kind: 'task',
166
+ message: ctx.task.message,
167
+ status: 'delivering',
168
+ ...(ctx.sourceCoordinatorSessionId ? { sourceCoordinatorSessionId: ctx.sourceCoordinatorSessionId } : {}),
169
+ ...(ctx.sourceCoordinatorDaemonId ? { sourceCoordinatorDaemonId: ctx.sourceCoordinatorDaemonId } : {}),
170
+ });
171
+
172
+ // Invoke the transport synchronously (preserves the prior fire-and-forget timing,
173
+ // and lets a synchronous throw fall into the same failure path as a rejection).
174
+ let dispatchPromise: Promise<unknown>;
175
+ try {
176
+ dispatchPromise = Promise.resolve(dispatchThunk());
177
+ } catch (e) {
178
+ dispatchPromise = Promise.reject(e);
179
+ }
180
+
181
+ let timer: ReturnType<typeof setTimeout> | undefined;
182
+ let guarded: Promise<unknown>;
183
+ if (warmup) {
184
+ // Remote P2P: cold-open-aware deadline. awaitWithWarmupDeadline owns its own
185
+ // timers (so `timer` stays undefined and the clearTimeout below is a no-op),
186
+ // and rejects with Error('timeout') when either budget lapses — the same
187
+ // retryable failure shape the catch below already handles (requeue + ledger).
188
+ guarded = awaitWithWarmupDeadline(dispatchPromise, resolveWarmupDeadlineOpts({
189
+ getConnection: warmup.getConnection,
190
+ daemonId: warmup.daemonId,
191
+ connectTimeoutMs: DISPATCH_CONNECT_TIMEOUT_MS,
192
+ responseTimeoutMs: DISPATCH_CONFIRM_TIMEOUT_MS,
193
+ onMissingGetter: warnDispatchWarmupGetterMissingOnce,
194
+ }));
195
+ } else {
196
+ guarded = Promise.race([
197
+ dispatchPromise,
198
+ new Promise<never>((_, reject) => {
199
+ timer = setTimeout(
200
+ () => reject(new Error(`dispatch_confirm_timeout after ${DISPATCH_CONFIRM_TIMEOUT_MS}ms`)),
201
+ DISPATCH_CONFIRM_TIMEOUT_MS,
202
+ );
203
+ // Never keep the process alive solely for this confirm-timeout timer.
204
+ if (typeof (timer as { unref?: () => void })?.unref === 'function') (timer as { unref: () => void }).unref();
205
+ }),
206
+ ]);
207
+ }
208
+
209
+ guarded.then(() => {
210
+ if (timer) clearTimeout(timer);
211
+ updateSessionDeliveryStatus(delivery.id, 'delivered');
212
+ }).catch((e: any) => {
213
+ if (timer) clearTimeout(timer);
214
+ // A dispatch failure (transport reject OR hang timeout) is most often transient —
215
+ // a busy/refusing adapter, or a relay that never acked — not a permanent task
216
+ // failure. Marking the task terminal here would permanently kill tasks a later
217
+ // tick delivers fine. Return it to 'pending' and record a retryable dispatch_failed
218
+ // ledger entry so the reconcile loop re-dispatches it. Identical for both transports.
219
+ LOG.error('MeshQueue', `Failed to dispatch task via ${ctx.transport} to node ${ctx.nodeId}: ${e?.message}`);
220
+ updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
221
+ updateTaskStatus(ctx.meshId, ctx.task.id, 'pending');
222
+ try {
223
+ appendLedgerEntry(ctx.meshId, {
224
+ kind: 'dispatch_failed' as any,
225
+ nodeId: ctx.nodeId,
226
+ sessionId: ctx.sessionId,
227
+ payload: { taskId: ctx.task.id, deliveryId: delivery.id, error: e?.message, retryable: true, transport: ctx.transport },
228
+ });
229
+ } catch { /* ledger write is best-effort */ }
230
+ });
231
+ }
232
+
233
+ // WTCLAIM: workspace normalization for base-vs-worktree comparison now lives in
234
+ // @adhdev/mesh-shared (normalizeMeshWorkspaceForCompare) so the enqueue→claim path,
235
+ // the mesh_status per-node session filter, and the read_chat node scope guard all
236
+ // share one comparison rule instead of drifting module-private copies.
237
+
238
+ export function tryAssignQueueTask(
239
+ components: DaemonComponents,
240
+ meshId: string,
241
+ nodeId: string,
242
+ sessionId: string,
243
+ providerType: string
244
+ ): boolean {
245
+ const mesh = getMeshWithCache(components, meshId);
246
+ const node = mesh?.nodes.find((n: any) => readMeshNodeId(n) === nodeId);
247
+
248
+ // WTCLAIM (fix-B extended to the enqueue→claim path): a base-targeted task must never be
249
+ // claimed by — and dispatched into — a co-located worktree-clone session, nor vice versa.
250
+ // The drain candidate's nodeId is derived from settings.meshNodeId || settings.nodeId
251
+ // (triggerMeshQueue), so a worktree session whose meshNodeId is empty/stale falls back to
252
+ // settings.nodeId = the BASE node id and impersonates the base node here. fix-B's worker-side
253
+ // workspace scope only ran for sessionless dispatch (meshScopeNodeId && !targetSessionId); the
254
+ // claim path ALWAYS carries a targetSessionId, so it never engaged. Apply the same scope here:
255
+ // for a LOCAL claiming session (adapter resolvable on this daemon), require its actual
256
+ // workingDir to match the target node's declared workspace. On a confirmed mismatch, refuse the
257
+ // claim so the task returns to pending for the correctly-scoped session/node to pull. Scoped to
258
+ // local sessions where the workspace is verifiable — a remote session lives on another daemon
259
+ // whose paths we cannot compare here (and remote candidates are already nodeId-matched from
260
+ // getRemoteIdleSessions). Conservative by design: when either workspace is unknown we do NOT
261
+ // skip, so a node with no declared workspace keeps its prior behavior and no legitimate claim
262
+ // is starved.
263
+ // WTDISPATCH (residual of WTCLAIM): the cross-node claim guard must reach EVERY claiming
264
+ // session this daemon can observe — not only those whose adapter happens to be in
265
+ // cliManager.adapters. An auto-launched worker session can carry its node binding on the
266
+ // CLI-instance settings while its session-host record shows no_node_binding, and the
267
+ // event-driven / remote-idle drain (agent:ready → setRemoteIdleSession → tryAssignQueueTask)
268
+ // can pass a nodeId that does NOT belong to the claiming session — a sibling worktree node
269
+ // on the SAME daemon. The adapter-only WTCLAIM check (rc.361/4c5b30b1) never engaged for a
270
+ // session observed solely via instanceManager, so session A could pull node B's task and
271
+ // node A's task was left with no session to claim it (no task_dispatched — it never dispatches).
272
+ //
273
+ // Resolve the claiming session's REAL identity from the adapter workingDir, then fall back to
274
+ // the live CLI instance's workspace + its stamped meshNodeId, and refuse a claim that
275
+ // contradicts EITHER (fail-closed). Reuses the shared meshWorkspacesEquivalent / meshNodeIdMatches
276
+ // comparators — no new comparison logic. Conservative: when neither the workspace NOR the stamp
277
+ // is resolvable we do NOT refuse, so a node with no declared workspace keeps prior behavior and
278
+ // a genuinely remote (cross-daemon) candidate stays nodeId-matched from getRemoteIdleSessions.
279
+ const localClaimAdapter = components.cliManager?.adapters?.get(sessionId) as { workingDir?: string } | undefined;
280
+ let claimInstanceWorkspace = '';
281
+ let claimStampedNodeId = '';
282
+ try {
283
+ const claimState = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
284
+ claimInstanceWorkspace = readNonEmptyString(claimState?.workspace);
285
+ const claimSettings = (claimState?.settings as Record<string, unknown>) || {};
286
+ claimStampedNodeId = readNonEmptyString(claimSettings.meshNodeId);
287
+ } catch { /* best-effort — fall through to the conservative (no refuse) path */ }
288
+
289
+ const nodeWorkspaceRaw = readNonEmptyString(node?.workspace);
290
+ const sessionWorkspaceRaw = readNonEmptyString(localClaimAdapter?.workingDir) || claimInstanceWorkspace;
291
+
292
+ if (claimStampedNodeId && nodeId) {
293
+ // The session carries its OWN meshNodeId stamp — its authoritative node identity, set when
294
+ // the coordinator launched/dispatched it (mesh-routing trusts this stamp FIRST). When it
295
+ // matches the claim target the session genuinely belongs to this node, so the stamp settles
296
+ // it and the workspace heuristic is skipped (a base/worktree pair can legitimately share a
297
+ // workspace). When it does NOT match, the claim is a cross-node leak — refuse, fail-closed.
298
+ if (!meshNodeIdMatches({ id: claimStampedNodeId } as MeshNodeIdentified, nodeId)) {
299
+ LOG.info('MeshQueue', `WTDISPATCH: refusing claim for node ${nodeId} (${sessionId}) — session is bound to node "${claimStampedNodeId}" (cross-node claim blocked)`);
300
+ return false;
301
+ }
302
+ } else if (sessionWorkspaceRaw && nodeWorkspaceRaw && !meshWorkspacesEquivalent(sessionWorkspaceRaw, nodeWorkspaceRaw)) {
303
+ // No stamp (the no_node_binding worker) — fall back to the workspace to tell two co-located
304
+ // sibling worktree sessions apart. WTCLAIM, now reaching instanceManager-observable sessions
305
+ // too. Conservative: unknown workspace on either side → do NOT refuse (no legitimate claim
306
+ // starved; a genuinely remote cross-daemon candidate stays nodeId-matched as before).
307
+ LOG.info('MeshQueue', `WTCLAIM: refusing claim for node ${nodeId} (${sessionId}) — session workspace "${normalizeMeshWorkspaceForCompare(sessionWorkspaceRaw)}" ≠ node workspace "${normalizeMeshWorkspaceForCompare(nodeWorkspaceRaw)}" (cross-workspace dispatch blocked)`);
308
+ return false;
309
+ }
310
+
311
+ const capabilityTags = buildMeshNodeCapabilityTags(node, providerType);
312
+ // Per-(node, provider) maxParallel cap (RepoMeshNodePolicy.providerRoles) layers
313
+ // on top of the global/taskMode caps — stricter wins. Resolved here where the
314
+ // claiming session's providerType + node policy are both known, then enforced
315
+ // inside the atomic claim transaction so concurrent claims can't overshoot it.
316
+ const providerMaxParallel = resolveProviderMaxParallel(node?.policy, providerType);
317
+ // WTDISPATCH-FANOUT: tell the atomic claim whether the claiming node is a worktree
318
+ // clone so a `convergence` task (base-only: merge → push → cleanup) is refused for
319
+ // worktree sessions. Without it, every sibling worktree session on this daemon could
320
+ // claim the same convergence intent and race push/production-deploy (the 4-way fan-out).
321
+ const nodeIsWorktree = node?.isLocalWorktree === true;
322
+ const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags, {
323
+ providerType,
324
+ ...(providerMaxParallel !== undefined ? { providerMaxParallel } : {}),
325
+ nodeIsWorktree,
326
+ });
327
+ if (!task) {
328
+ return false;
329
+ }
330
+
331
+ const terminal = findTerminalLedgerEvidenceForTask({
332
+ meshId,
333
+ taskId: task.id,
334
+ });
335
+ if (terminal) {
336
+ const status = terminal.kind === 'task_completed' ? 'completed' : 'failed';
337
+ updateTaskStatus(meshId, task.id, status);
338
+ LOG.info('MeshQueue', `Skipped dispatch for terminal task ${task.id} on mesh ${meshId}; ${terminal.kind} ledger evidence already exists`);
339
+ traceMeshEventDrop('dispatch_terminal_ledger', {
340
+ taskId: task.id,
341
+ sessionId,
342
+ nodeId,
343
+ meshId,
344
+ event: 'agent_command',
345
+ }, terminal.kind);
346
+ return false;
347
+ }
348
+
349
+ LOG.info('MeshQueue', `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
350
+
351
+ if (node?.daemonId && components.dispatchMeshCommand) {
352
+ const isLocalNode = components.cliManager.adapters.has(sessionId);
353
+ if (!isLocalNode) {
354
+ const localDaemonIdForDispatch = readNonEmptyString(loadConfig().machineId) || undefined;
355
+ // (3) Originating coordinator session that enqueued this task — route its
356
+ // completion back to that exact session (multi-coordinator). Carried over P2P
357
+ // to the remote worker, which echoes it on its completion event.
358
+ const sourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId) || undefined;
359
+ const dispatchMeshCommand = components.dispatchMeshCommand;
360
+ const remoteDaemonId = node.daemonId;
361
+ // CONS3: only the transport call differs — everything else (delivery record,
362
+ // status transitions, requeue-on-failure, ledger, Bug B hang timeout) is in
363
+ // the shared deliverTaskToSession helper.
364
+ deliverTaskToSession(
365
+ () => dispatchMeshCommand(remoteDaemonId, 'agent_command', {
366
+ targetSessionId: sessionId,
367
+ cliType: providerType,
368
+ action: 'send_chat',
369
+ message: task.message,
370
+ meshContext: {
371
+ meshId,
372
+ nodeId,
373
+ taskId: task.id,
374
+ ...(localDaemonIdForDispatch ? { coordinatorDaemonId: localDaemonIdForDispatch } : {}),
375
+ ...(sourceCoordinatorSessionId ? { coordinatorSessionId: sourceCoordinatorSessionId } : {}),
376
+ },
377
+ }),
378
+ {
379
+ meshId,
380
+ nodeId,
381
+ sessionId,
382
+ providerType,
383
+ task,
384
+ transport: 'remote',
385
+ ...(sourceCoordinatorSessionId ? { sourceCoordinatorSessionId } : {}),
386
+ ...(localDaemonIdForDispatch ? { sourceCoordinatorDaemonId: localDaemonIdForDispatch } : {}),
387
+ },
388
+ // Warmup-aware deadline: this dispatch can be the FIRST command to a
389
+ // peer whose mesh DataChannel is still opening — charge the cold-open
390
+ // handshake to the connect budget, not the response budget.
391
+ { daemonId: remoteDaemonId, getConnection: components.getMeshPeerConnectionStatus },
392
+ );
393
+ return true;
394
+ }
395
+ }
396
+
397
+ // Stamp mesh context onto the session so completion events route correctly
398
+ // via setupMeshEventForwarding. Without this, manually-opened idle sessions
399
+ // (mesh_launch_session without auto-launch) lack meshNodeFor/meshNodeId and
400
+ // agent:generating_completed is silently dropped as isMeshDelegate=false.
401
+ try {
402
+ const inst = components.instanceManager.getInstance(sessionId);
403
+ if (inst && typeof inst.updateSettings === 'function') {
404
+ // Adopting a (possibly manually-opened) local session as a worker: apply the
405
+ // delegated-worker auto-approve policy here too, so a session that was launched
406
+ // without autoApprove still auto-approves once the coordinator dispatches a task
407
+ // to it (the "approval notification fires only for certain delegated sessions"
408
+ // case). updateSettings preserves runtime mesh keys; passing autoApprove keeps it.
409
+ //
410
+ // This local-dispatch branch also runs on the coordinator daemon for a co-located
411
+ // session, so the coordinator daemon id IS this daemon's id. Stamp it alongside
412
+ // the node identity so the session is fully relay-safe (meshCoordinatorDaemonId is
413
+ // the anchor the forwarder keys on), matching what mesh_launch_session stamps.
414
+ const localDaemonId = readNonEmptyString(loadConfig().machineId);
415
+ const localSourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId);
416
+ inst.updateSettings({
417
+ meshNodeFor: meshId,
418
+ meshNodeId: nodeId,
419
+ launchedByCoordinator: true,
420
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
421
+ ...(localDaemonId ? { meshCoordinatorDaemonId: localDaemonId } : {}),
422
+ // (3) Stamp the originating coordinator session for session-anchored routing
423
+ // of this co-located worker's completion. Absent → daemon-level fallback.
424
+ ...(localSourceCoordinatorSessionId ? { meshCoordinatorSessionId: localSourceCoordinatorSessionId } : {}),
425
+ });
426
+ }
427
+ } catch { /* best-effort — dispatch still proceeds */ }
428
+
429
+ // CONS3: same shared dispatch lifecycle as the remote branch — only the transport
430
+ // (cliManager.handleCliCommand) differs.
431
+ deliverTaskToSession(
432
+ () => components.cliManager.handleCliCommand('agent_command', {
433
+ targetSessionId: sessionId,
434
+ cliType: providerType,
435
+ action: 'send_chat',
436
+ message: task.message,
437
+ }),
438
+ {
439
+ meshId,
440
+ nodeId,
441
+ sessionId,
442
+ providerType,
443
+ task,
444
+ transport: 'local',
445
+ ...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { sourceCoordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
446
+ ...(readNonEmptyString(loadConfig().machineId) ? { sourceCoordinatorDaemonId: readNonEmptyString(loadConfig().machineId) } : {}),
447
+ },
448
+ );
449
+
450
+ return true;
451
+ }
452
+
453
+ const autoLaunchInProgress = new Set<string>();
454
+ const autoLaunchCooldownUntil = new Map<string, number>();
455
+ const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
456
+ // A remote auto-launch (launch_cli forward) is fire-and-async: the worker session
457
+ // spawns, reaches idle, emits agent:ready, that ready is queued on the worker, pulled
458
+ // by this coordinator (reconcile PHASE 1), and only THEN claims the task. That round
459
+ // trip routinely exceeds the 5s per-(mesh,node) cooldown, so cooldown alone lets the
460
+ // reconcile loop fire a SECOND launch for the same still-pending task before the first
461
+ // session's claim lands — every tick spawns yet another orphan session (observed live:
462
+ // 26 sessions for one task). This is a per-TASK await-claim window: once a task has a
463
+ // successfully-launched session whose claim we are still waiting on, do not launch it
464
+ // again until the window lapses. It is generous (a slow remote spawn can take tens of
465
+ // seconds) but bounded so a launch that silently never reaches idle is eventually retried.
466
+ const AUTO_LAUNCH_AWAIT_CLAIM_MS = 90_000;
467
+
468
+ // De-dup for repeated `skipped` ledger noise: the reconcile loop re-runs the queue
469
+ // trigger every 4s, so a task that can't be claimed (e.g. a remote node with no
470
+ // transport, or a node under cooldown) would otherwise append an identical
471
+ // session_auto_launch{phase:'skipped'} entry on every tick — flooding the ledger.
472
+ // We suppress a `skipped` ledger append when the immediately-prior recorded event
473
+ // for that task was the SAME (phase, reason). Any non-skip phase (started/failed/
474
+ // completed) or a changed reason resets the de-dup so real transitions still record.
475
+ const lastAutoLaunchLedgerKey = new Map<string, string>();
476
+ const AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2000;
477
+
478
+ function sweepExpiredCooldowns(): void {
479
+ const now = Date.now();
480
+ for (const [key, until] of autoLaunchCooldownUntil) {
481
+ if (now >= until) autoLaunchCooldownUntil.delete(key);
482
+ }
483
+ }
484
+
485
+ function normalizeProviderPriority(policy: unknown): string[] {
486
+ const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
487
+ ? (policy as Record<string, unknown>).providerPriority
488
+ : undefined;
489
+ if (!Array.isArray(raw)) return [];
490
+ const seen = new Set<string>();
491
+ return raw
492
+ .map(type => typeof type === 'string' ? type.trim() : '')
493
+ .filter(Boolean)
494
+ .filter(type => {
495
+ if (seen.has(type)) return false;
496
+ seen.add(type);
497
+ return true;
498
+ });
499
+ }
500
+
501
+ function isTerminalSessionStatus(status: string): boolean {
502
+ return ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(status);
503
+ }
504
+
505
+ function isIdleSessionState(state: any): boolean {
506
+ const status = readNonEmptyString(state?.status).toLowerCase();
507
+ if (isTerminalSessionStatus(status)) return false;
508
+ return status === 'idle' || state?.activeChat?.status === 'waiting_input';
509
+ }
510
+
511
+ function isDirtyNode(node: any): boolean {
512
+ return node?.health === 'dirty' || node?.git?.dirty === true;
513
+ }
514
+
515
+ function resolveAutoFastForwardPolicy(mesh: any): { enabled: boolean; maxBehind?: number; requireCleanSubmodules: boolean } {
516
+ const record = mesh?.policy?.autoFastForward && typeof mesh.policy.autoFastForward === 'object' && !Array.isArray(mesh.policy.autoFastForward)
517
+ ? mesh.policy.autoFastForward as Record<string, unknown>
518
+ : {};
519
+ const maxBehind = Number(record.maxBehind);
520
+ return {
521
+ enabled: record.enabled !== false,
522
+ ...(Number.isFinite(maxBehind) && maxBehind >= 0 ? { maxBehind: Math.floor(maxBehind) } : {}),
523
+ requireCleanSubmodules: record.requireCleanSubmodules !== false,
524
+ };
525
+ }
526
+
527
+ function sessionStateLooksActive(state: any): boolean {
528
+ const status = readNonEmptyString(state?.status).toLowerCase();
529
+ const chatStatus = readNonEmptyString(state?.activeChat?.status).toLowerCase();
530
+ // 'long_generating' is retained as a legacy alias for the renamed 'no_progress' busy status.
531
+ const active = new Set(['generating', 'streaming', 'no_progress', 'long_generating', 'working', 'starting', 'waiting_approval']);
532
+ return active.has(status) || active.has(chatStatus);
533
+ }
534
+
535
+ function nodeHasActiveMeshWork(components: DaemonComponents, meshId: string, nodeId: string, currentSessionId?: string): boolean {
536
+ if (nodeHasActiveAssignment(meshId, nodeId)) return true;
537
+ return components.instanceManager.getByCategory('cli').some((inst: any) => {
538
+ const state = inst.getState();
539
+ const settings = state.settings as Record<string, unknown> || {};
540
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
541
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
542
+ if (instNodeId !== nodeId) return false;
543
+ const sessionId = readNonEmptyString(state.instanceId);
544
+ if (currentSessionId && sessionId === currentSessionId && isIdleSessionState(state)) return false;
545
+ return sessionStateLooksActive(state);
546
+ });
547
+ }
548
+
549
+ function isLaunchableNode(node: any): boolean {
550
+ if (!node || node.status === 'disabled' || node.status === 'removed') return false;
551
+ const health = readNonEmptyString(node.health).toLowerCase();
552
+ if (!health) return true;
553
+ return health === 'online' || health === 'unknown';
554
+ }
555
+
556
+ /** Whether a mesh node's daemon/machine identity resolves to THIS coordinator daemon
557
+ * (i.e. the queue session can be spawned by a direct local `launch_cli`). */
558
+ function isLocalAutoLaunchNode(node: any): boolean {
559
+ const daemonId = readNonEmptyString(node?.daemonId);
560
+ const machineId = readNonEmptyString(node?.machineId);
561
+ const appConfig = loadConfig();
562
+ const localMachineId = readNonEmptyString(appConfig.machineId) || readNonEmptyString(appConfig.registeredMachineId);
563
+
564
+ // Route BOTH the daemonId and the machineId through the canonical machine-core
565
+ // equivalence helper so a node carrying any interchangeable id form (bare `mach_<hex>`
566
+ // or a `daemon_`/`standalone_` prefixed form) resolves to THIS coordinator instead of
567
+ // being misjudged as remote. machineId used to use a raw `===`, which — AND-combined
568
+ // with the daemonId match — would misjudge a local node as remote whenever a
569
+ // form-mismatched machineId arrived, dispatching a local task to a remote node (B-2).
570
+ const daemonMatchesLocal = !daemonId || daemonIdsEquivalent(daemonId, localMachineId);
571
+ const machineMatchesLocal = !machineId || daemonIdsEquivalent(machineId, localMachineId);
572
+
573
+ if (node?.isLocalWorktree === true) {
574
+ return daemonMatchesLocal && machineMatchesLocal;
575
+ }
576
+ if (daemonId || machineId) {
577
+ return daemonMatchesLocal && machineMatchesLocal;
578
+ }
579
+ return true;
580
+ }
581
+
582
+ /**
583
+ * Resolve how a pending queue task should be auto-launched onto a node.
584
+ *
585
+ * - `local`: spawn directly on this daemon via cliManager.handleCliCommand('launch_cli').
586
+ * - `remote`: forward `launch_cli` to the node's daemon via dispatchMeshCommand
587
+ * (mirrors what mesh_launch_session does). Requires dispatchMeshCommand AND a
588
+ * resolvable coordinator daemonId for relay-safe completion routing.
589
+ * - `skip`: not launchable from here — carries the reason (e.g. a remote node with
590
+ * no dispatch transport, or no coordinator daemonId to stamp).
591
+ */
592
+ function resolveAutoLaunchTarget(components: DaemonComponents, node: any): {
593
+ mode: 'local' | 'remote' | 'skip';
594
+ reason?: string;
595
+ daemonId?: string;
596
+ coordinatorDaemonId?: string;
597
+ } {
598
+ if (isLocalAutoLaunchNode(node)) return { mode: 'local' };
599
+
600
+ // Remote node. Forwarding the launch is possible only with a dispatch transport
601
+ // (cloud mode) plus a coordinator daemonId to stamp into the worker so completion
602
+ // events route back here. Without either, fall back to a graceful skip.
603
+ const daemonId = readNonEmptyString(node?.daemonId);
604
+ if (!daemonId) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
605
+ if (!components.dispatchMeshCommand) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
606
+ const coordinatorDaemonId = readNonEmptyString(loadConfig().machineId);
607
+ if (!coordinatorDaemonId) return { mode: 'skip', reason: 'remote_auto_launch_no_coordinator_daemon_id' };
608
+ return { mode: 'remote', daemonId, coordinatorDaemonId };
609
+ }
610
+
611
+ function activeAssignedCount(meshId: string): number {
612
+ return getQueue(meshId, { status: ['assigned'] as any }).length;
613
+ }
614
+
615
+ /** Active assignments that hold the one-active-per-node / global-parallel invariant
616
+ * (everything except read-only diagnoses, which run unbounded by the write cap). */
617
+ export function activeWriteAssignedCount(meshId: string): number {
618
+ return getQueue(meshId, { status: ['assigned'] as any })
619
+ .filter(task => task.taskMode !== 'live_debug_readonly').length;
620
+ }
621
+
622
+ /** Active read-only (live_debug_readonly) assignments, for the read-only safety cap. */
623
+ export function activeReadonlyAssignedCount(meshId: string): number {
624
+ return getQueue(meshId, { status: ['assigned'] as any })
625
+ .filter(task => task.taskMode === 'live_debug_readonly').length;
626
+ }
627
+
628
+ function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
629
+ return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedNodeId === nodeId);
630
+ }
631
+
632
+ /** Active (status='assigned') task count for a node — the load metric for
633
+ * least-loaded / round-robin ranking. Lower = preferred. */
634
+ function nodeActiveLoad(meshId: string, nodeId: string): number {
635
+ return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
636
+ }
637
+
638
+ /**
639
+ * The mesh-wide scheduling strategy. Defaults to 'first_eligible' (strict
640
+ * no-change) for any mesh that does not set it. Only governs the final tie-break;
641
+ * eligibility, capacity, and priority gates apply identically to every strategy.
642
+ */
643
+ function resolveSchedulingStrategy(mesh: any): RepoMeshSchedulingStrategy {
644
+ return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
645
+ }
646
+
647
+ /**
648
+ * Order eligible nodes for assignment per the mesh scheduling pipeline:
649
+ * PRIORITY (schedulingPriority desc) → TIE-BREAK (strategy).
650
+ *
651
+ * The caller has already applied the TAG hard-filter and is responsible for the
652
+ * MAX-ALLOC capacity gate (the per-node launch/claim checks). This function only
653
+ * decides the *preference order* among nodes that are otherwise eligible.
654
+ *
655
+ * - 'first_eligible' (default): returns the input order verbatim and does NOT touch
656
+ * the round-robin cursor — byte-for-byte the pre-feature behavior.
657
+ * - 'priority_only': schedulingPriority desc, then input order (load ignored).
658
+ * - 'least_loaded': schedulingPriority desc, then active load asc, then input order.
659
+ * - 'round_robin': same as least_loaded, but among nodes tied at (priority, load)
660
+ * the input order is rotated by a per-mesh cursor that advances once per pass.
661
+ *
662
+ * `nodes` carries the original config/array index so the tie-break can fall back to
663
+ * deterministic input order. `bumpCursor` advances the round-robin cursor exactly
664
+ * once per scheduling pass (only consulted for 'round_robin').
665
+ */
666
+ interface RankableNode { nodeId: string; node: any; index: number }
667
+
668
+ /** Test-only: the pure node-ordering stage (PRIORITY → TIE-BREAK). Exposed so the
669
+ * scheduling pipeline can be unit-tested without standing up live CLI sessions. */
670
+ export function __orderEligibleNodesForTests(
671
+ meshId: string,
672
+ strategy: RepoMeshSchedulingStrategy,
673
+ nodes: RankableNode[],
674
+ opts?: { bumpCursor?: boolean },
675
+ ): RankableNode[] {
676
+ return orderEligibleNodes(meshId, strategy, nodes, opts);
677
+ }
678
+
679
+ function orderEligibleNodes(
680
+ meshId: string,
681
+ strategy: RepoMeshSchedulingStrategy,
682
+ nodes: RankableNode[],
683
+ opts?: { bumpCursor?: boolean },
684
+ ): RankableNode[] {
685
+ if (strategy === 'first_eligible' || nodes.length <= 1) {
686
+ return nodes;
687
+ }
688
+
689
+ const priorityOf = (n: { node: any }) => resolveNodeSchedulingPriority(n.node?.policy);
690
+
691
+ // Round-robin rotation offset: rotate the deterministic input order by a
692
+ // per-mesh cursor so the tie-break winner among equal (priority, load) nodes
693
+ // cycles across passes. The cursor advances once per scheduling pass.
694
+ let rotation = 0;
695
+ if (strategy === 'round_robin') {
696
+ const cursor = opts?.bumpCursor
697
+ ? MeshRuntimeStore.getInstance().bumpSchedulerCursor(meshId)
698
+ : MeshRuntimeStore.getInstance().getSchedulerCursor(meshId);
699
+ rotation = ((cursor % nodes.length) + nodes.length) % nodes.length;
700
+ }
701
+
702
+ // Rotation rank: position of each node after rotating input order by `rotation`.
703
+ // For non-round-robin strategies rotation is 0, so this is just the input index.
704
+ const rotationRank = (index: number) => (index - rotation + nodes.length) % nodes.length;
705
+
706
+ return [...nodes].sort((a, b) => {
707
+ const prioDelta = priorityOf(b) - priorityOf(a); // higher priority first
708
+ if (prioDelta !== 0) return prioDelta;
709
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
710
+ const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
711
+ if (loadDelta !== 0) return loadDelta;
712
+ }
713
+ return rotationRank(a.index) - rotationRank(b.index);
714
+ });
715
+ }
716
+
717
+ /** Active assignments on a (node, provider) — pre-launch guard for the per-(node,
718
+ * provider) maxParallel cap. The authoritative enforcement is in the claim
719
+ * transaction; this only avoids spawning a session that would fail the claim. */
720
+ function activeProviderAssignedCount(meshId: string, nodeId: string, providerType: string): number {
721
+ return getQueue(meshId, { status: ['assigned'] as any })
722
+ .filter(task => task.assignedNodeId === nodeId && task.assignedProviderType === providerType).length;
723
+ }
724
+
725
+ export function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
726
+ if (getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedSessionId === sessionId)) {
727
+ return true;
728
+ }
729
+ // Direct dispatches (mesh_send_task) are tracked in mesh_direct_dispatches, not the
730
+ // work queue. A session completing a still-active direct dispatch IS an active
731
+ // assignment — without this, findRecentTerminalLedgerEvidence dedup wrongly suppresses
732
+ // the canonical agent:generating_completed for direct-dispatch tasks (validation/general),
733
+ // so the coordinator polling get_pending_mesh_events never observes task_completed and the
734
+ // session goes silently idle. This check runs before markSessionTerminal marks the
735
+ // dispatch terminal, so the in-flight dispatch is still observable here.
736
+ try {
737
+ if (getActiveDirectDispatches(meshId).some(d => d.sessionId === sessionId)) return true;
738
+ if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
739
+ } catch { /* best-effort — fall through to false */ }
740
+ return false;
741
+ }
742
+
743
+ function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
744
+ return components.instanceManager.getByCategory('cli').filter((inst: any) => {
745
+ const state = inst.getState();
746
+ const settings = state.settings as Record<string, unknown> || {};
747
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
748
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
749
+ if (instNodeId !== nodeId) return false;
750
+ const status = readNonEmptyString(state.status).toLowerCase();
751
+ return !isTerminalSessionStatus(status);
752
+ }).length;
753
+ }
754
+
755
+ function recordAutoLaunchEvent(meshId: string, args: {
756
+ phase: 'skipped' | 'started' | 'failed' | 'completed';
757
+ taskId: string;
758
+ nodeId?: string;
759
+ providerType?: string;
760
+ sessionId?: string;
761
+ reason?: string;
762
+ error?: string;
763
+ }) {
764
+ // Suppress consecutive identical `skipped` entries for the same task (4s reconcile
765
+ // re-trigger noise). Non-skip phases and changed reasons always record and reset
766
+ // the de-dup so genuine state transitions remain visible in the ledger.
767
+ const dedupKey = `${meshId}:${args.taskId}`;
768
+ const currentSig = `${args.phase}|${args.reason || ''}`;
769
+ if (args.phase === 'skipped' && lastAutoLaunchLedgerKey.get(dedupKey) === currentSig) {
770
+ return;
771
+ }
772
+ lastAutoLaunchLedgerKey.set(dedupKey, currentSig);
773
+ if (lastAutoLaunchLedgerKey.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
774
+ // Bound memory: drop the oldest insertion (Map preserves insertion order).
775
+ const oldest = lastAutoLaunchLedgerKey.keys().next().value;
776
+ if (oldest !== undefined) lastAutoLaunchLedgerKey.delete(oldest);
777
+ }
778
+ try {
779
+ appendLedgerEntry(meshId, {
780
+ kind: 'session_auto_launch',
781
+ nodeId: args.nodeId,
782
+ sessionId: args.sessionId,
783
+ providerType: args.providerType,
784
+ payload: {
785
+ phase: args.phase,
786
+ taskId: args.taskId,
787
+ reason: args.reason,
788
+ error: args.error,
789
+ },
790
+ });
791
+ } catch (e: any) {
792
+ LOG.warn('MeshQueue', `Failed to record auto-launch ledger event: ${e?.message || e}`);
793
+ }
794
+ }
795
+
796
+ function markAutoLaunch(meshId: string, taskId: string, args: {
797
+ status: 'skipped' | 'started' | 'failed' | 'completed';
798
+ reason?: string;
799
+ nodeId?: string;
800
+ providerType?: string;
801
+ sessionId?: string;
802
+ error?: string;
803
+ }) {
804
+ recordTaskAutoLaunch(meshId, taskId, {
805
+ status: args.status,
806
+ reason: args.reason || args.error,
807
+ nodeId: args.nodeId,
808
+ providerType: args.providerType,
809
+ sessionId: args.sessionId,
810
+ });
811
+ recordAutoLaunchEvent(meshId, {
812
+ phase: args.status,
813
+ taskId,
814
+ nodeId: args.nodeId,
815
+ providerType: args.providerType,
816
+ sessionId: args.sessionId,
817
+ reason: args.reason,
818
+ error: args.error,
819
+ });
820
+ }
821
+
822
+ async function resolveUsableProvider(
823
+ components: DaemonComponents,
824
+ nodeId: string,
825
+ node: any,
826
+ requiredTags?: string[],
827
+ ): Promise<{ providerType?: string; reason?: string }> {
828
+ const providerPriority = normalizeProviderPriority(node?.policy);
829
+ if (!providerPriority.length) return { reason: 'missing_provider_priority' };
830
+ const providerLoader = components.providerLoader;
831
+ if (!providerLoader) return { reason: 'provider_loader_unavailable' };
832
+
833
+ const failed: string[] = [];
834
+ for (const requestedType of providerPriority) {
835
+ const normalizedType = typeof providerLoader.resolveAlias === 'function'
836
+ ? providerLoader.resolveAlias(requestedType)
837
+ : requestedType;
838
+ // Skip providers that can't satisfy the task's requiredTags (e.g. provider=hermes-cli
839
+ // means only hermes-cli qualifies, not any other type in providerPriority).
840
+ if (requiredTags?.length && !nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, normalizedType))) {
841
+ failed.push(`${requestedType}: required_tags_mismatch`);
842
+ continue;
843
+ }
844
+ if (typeof providerLoader.isMachineProviderEnabled === 'function' && !providerLoader.isMachineProviderEnabled(normalizedType)) {
845
+ failed.push(`${requestedType}: disabled`);
846
+ continue;
847
+ }
848
+ let detected: any;
849
+ try {
850
+ detected = await detectCLI(normalizedType, providerLoader, { includeVersion: false });
851
+ } catch (e: any) {
852
+ failed.push(`${requestedType}: detect failed: ${e?.message || e}`);
853
+ continue;
854
+ }
855
+ if (typeof providerLoader.setCliDetectionResults === 'function') {
856
+ providerLoader.setCliDetectionResults([{
857
+ id: normalizedType,
858
+ installed: !!detected,
859
+ path: detected?.path,
860
+ }], false);
861
+ }
862
+ (components as any).onStatusChange?.();
863
+ if (detected) return { providerType: normalizedType };
864
+ failed.push(`${requestedType}: not detected`);
865
+ }
866
+ return { reason: `provider_priority_unusable: ${failed.join('; ') || nodeId}` };
867
+ }
868
+
869
+ // Canonical mesh node-id normalization. A node may arrive from the local config
870
+ // form (`id`) or the inline-cache form (`nodeId`/`node_id`) — see
871
+ // readInlineMeshNodeId in commands/router.ts. Comparing only `node.id` against a
872
+ // task.targetNodeId silently drops inline-cached worktree nodes, leaving a
873
+ // target-routed task permanently pending with a misleading
874
+ // `no_node_satisfies_required_tags` skip.
875
+ function readMeshNodeId(node: any): string {
876
+ // Delegate to the shared 3-way (id / nodeId / node_id) normalizer so this
877
+ // and every other mesh node-id read agree on identity. Coalesce to '' to
878
+ // preserve the existing string return contract for callers that do
879
+ // `=== task.targetNodeId` / `if (!nodeId)`.
880
+ return normalizeMeshNodeId(node) ?? '';
881
+ }
882
+
883
+ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, meshId: string, mesh: any): Promise<boolean> {
884
+ const queue = getQueue(meshId);
885
+ const pending = queue.filter(task => task.status === 'pending');
886
+ if (!pending.length) return false;
887
+
888
+ const maxParallelTasks = Math.max(1, Math.floor(Number(mesh?.policy?.maxParallelTasks) || 2));
889
+ // Read-only diagnoses carry no isolation/merge cost, so they are exempt from the
890
+ // write-task parallel cap. To prevent runaway auto-launch they get their own,
891
+ // higher safety cap (2x the write cap).
892
+ const maxReadonlyParallelTasks = Math.max(2, maxParallelTasks * 2);
893
+ for (const task of pending) {
894
+ const isReadonly = task.taskMode === 'live_debug_readonly';
895
+ if (isReadonly) {
896
+ if (activeReadonlyAssignedCount(meshId) >= maxReadonlyParallelTasks) {
897
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_readonly_parallel_tasks_reached' });
898
+ continue;
899
+ }
900
+ } else if (activeWriteAssignedCount(meshId) >= maxParallelTasks) {
901
+ // Write tasks are capped; skip this one but keep scanning so a later
902
+ // read-only task in the queue can still launch under its own cap.
903
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
904
+ continue;
905
+ }
906
+ if (task.targetSessionId) {
907
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
908
+ continue;
909
+ }
910
+
911
+ // Per-task await-claim guard. A prior auto-launch already spawned a session for
912
+ // this task and we are waiting for that session's idle→claim to land (remote
913
+ // claims arrive via the worker→coordinator agent:ready pull, which can lag well
914
+ // past the per-node cooldown). Re-launching now would spawn a duplicate orphan
915
+ // session that never gets work. The task leaves `pending` the instant the claim
916
+ // succeeds, so this guard only suppresses the in-flight window; if the launched
917
+ // session never reaches idle within the window, a later tick retries.
918
+ if (task.autoLaunch?.status === 'completed' && task.autoLaunch.sessionId) {
919
+ const launchedAtMs = Date.parse(task.autoLaunch.updatedAt);
920
+ if (Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS) {
921
+ // Record the skip in the ledger ONLY (dedup'd). Do NOT call markAutoLaunch
922
+ // here: recordTaskAutoLaunch overwrites task.autoLaunch wholesale, which would
923
+ // erase the very `completed` record (status + sessionId + updatedAt) this guard
924
+ // reads on the next tick, reopening the duplicate-launch hole it closes.
925
+ recordAutoLaunchEvent(meshId, { phase: 'skipped', taskId: task.id, reason: 'awaiting_launched_session_claim', nodeId: task.autoLaunch.nodeId, sessionId: task.autoLaunch.sessionId });
926
+ continue;
927
+ }
928
+ }
929
+
930
+ const candidateNodes = Array.isArray(mesh?.nodes)
931
+ ? mesh.nodes.filter((node: any) => {
932
+ // Bug A: match the target pin with the shared 3-form (id / nodeId / node_id)
933
+ // normalizer, mirroring the remote-idle drain (meshNodeIdMatches at the
934
+ // getRemoteIdleSessions filter). A strict `readMeshNodeId(node) !== targetNodeId`
935
+ // dropped a target node whose identity arrived under a different form (a freshly
936
+ // mesh_clone_node'd worktree), emptying candidateNodes and mislabelling the skip.
937
+ if (task.targetNodeId && !meshNodeIdMatches(node, task.targetNodeId)) return false;
938
+ // WTDISPATCH-FANOUT: a convergence task is base-only (it merges/pushes onto
939
+ // base). Never auto-launch a worktree-clone session for it — that is the very
940
+ // fan-out the claim guard refuses, so spinning the session up would only waste
941
+ // a launch that can never claim. Mirrors claimNextQueueTask's convergence gate.
942
+ if (task.taskMode === 'convergence' && node?.isLocalWorktree === true) return false;
943
+ // Skip nodes that can never satisfy requiredTags regardless of which provider
944
+ // from providerPriority is selected. A node satisfies tags if at least one
945
+ // provider in its priority list would produce matching capability tags.
946
+ if (task.requiredTags?.length) {
947
+ const priorities = normalizeProviderPriority(node?.policy);
948
+ const providerCandidates = priorities.length ? priorities : [undefined as unknown as string];
949
+ return providerCandidates.some(p =>
950
+ nodeSatisfiesRequiredTags(task.requiredTags, buildMeshNodeCapabilityTags(node, p))
951
+ );
952
+ }
953
+ return true;
954
+ })
955
+ : [];
956
+ if (!candidateNodes.length) {
957
+ // Bug A: distinguish the two ways the candidate set empties. A task pinned to a
958
+ // targetNodeId whose node is absent from the mesh (or whose id arrived under a
959
+ // different form) is a ROUTING miss — report it as `target_node_id_unmatched`, not
960
+ // the hard-coded `no_node_satisfies_required_tags`, which mislabelled a 3-form
961
+ // node-id mismatch as a capability failure and sent diagnosis down the wrong path.
962
+ // Only fall back to the tag reason when no target pin is in play, or the pin DID
963
+ // match a node but its tags excluded it (a genuine capability miss).
964
+ const targetPinUnmatched = !!task.targetNodeId
965
+ && !(Array.isArray(mesh?.nodes) && mesh.nodes.some((n: any) => meshNodeIdMatches(n, task.targetNodeId)));
966
+ markAutoLaunch(meshId, task.id, {
967
+ status: 'skipped',
968
+ reason: targetPinUnmatched ? 'target_node_id_unmatched' : 'no_node_satisfies_required_tags',
969
+ nodeId: task.targetNodeId,
970
+ });
971
+ continue;
972
+ }
973
+
974
+ // PRIORITY → TIE-BREAK: order the eligible (TAG-filtered) candidate nodes by
975
+ // the mesh scheduling strategy. 'first_eligible' (default) returns them in
976
+ // config/array order unchanged, so distribution is strictly opt-in. The
977
+ // per-node MAX-ALLOC capacity gate (nodeHasActiveAssignment, provider cap,
978
+ // maxConcurrentSessions) is still applied inside the loop below; this only
979
+ // chooses which eligible node is *tried first*.
980
+ const strategy = resolveSchedulingStrategy(mesh);
981
+ const orderedCandidateNodes = strategy === 'first_eligible'
982
+ ? candidateNodes
983
+ : orderEligibleNodes(
984
+ meshId,
985
+ strategy,
986
+ candidateNodes
987
+ .map((node: any, index: number) => ({ nodeId: readMeshNodeId(node), node, index }))
988
+ .filter((c: RankableNode) => c.nodeId),
989
+ { bumpCursor: true },
990
+ ).map((c: RankableNode) => c.node);
991
+
992
+ for (const node of orderedCandidateNodes) {
993
+ const nodeId = readMeshNodeId(node);
994
+ if (!nodeId) continue;
995
+ const launchKey = `${meshId}:${nodeId}`;
996
+ const now = Date.now();
997
+ const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
998
+ if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
999
+ if (autoLaunchInProgress.has(launchKey)) {
1000
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
1001
+ continue;
1002
+ }
1003
+ if (now < cooldownUntil) {
1004
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
1005
+ continue;
1006
+ }
1007
+ if (isDirtyNode(node)) {
1008
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dirty_workspace', nodeId });
1009
+ continue;
1010
+ }
1011
+ if (!isLaunchableNode(node)) {
1012
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_not_launch_ready', nodeId });
1013
+ continue;
1014
+ }
1015
+ const launchTarget = resolveAutoLaunchTarget(components, node);
1016
+ if (launchTarget.mode === 'skip') {
1017
+ // Remote node we can't reach (no transport / no coordinator daemonId).
1018
+ // Set a cooldown so the 4s reconcile loop doesn't re-attempt this node
1019
+ // every tick; the de-dup'd skip ledger keeps it diagnosable without flood.
1020
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: launchTarget.reason || 'auto_launch_unavailable', nodeId });
1021
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1022
+ continue;
1023
+ }
1024
+ // Write tasks keep the one-active-per-node invariant (worktree isolation);
1025
+ // read-only (live_debug_readonly) diagnoses may auto-launch onto a node
1026
+ // that already has an active assignment.
1027
+ if (task.taskMode !== 'live_debug_readonly' && nodeHasActiveAssignment(meshId, nodeId)) {
1028
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
1029
+ continue;
1030
+ }
1031
+ const maxConcurrentSessions = Number(node?.policy?.maxConcurrentSessions);
1032
+ if (Number.isFinite(maxConcurrentSessions) && maxConcurrentSessions >= 0 && liveSessionCountForNode(components, meshId, nodeId) >= maxConcurrentSessions) {
1033
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_concurrent_sessions_reached', nodeId });
1034
+ continue;
1035
+ }
1036
+
1037
+ autoLaunchInProgress.add(launchKey);
1038
+ try {
1039
+ const resolved = await resolveUsableProvider(components, nodeId, node, task.requiredTags);
1040
+ if (!resolved.providerType) {
1041
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: resolved.reason || 'provider_unusable', nodeId });
1042
+ continue;
1043
+ }
1044
+
1045
+ // Don't spawn a session for a (node, provider) already at its declared
1046
+ // maxParallel cap — it would launch only to fail the claim. The claim
1047
+ // transaction enforces the cap regardless; this just avoids a doomed launch.
1048
+ const providerCap = resolveProviderMaxParallel(node?.policy, resolved.providerType);
1049
+ if (
1050
+ providerCap !== undefined
1051
+ && activeProviderAssignedCount(meshId, nodeId, resolved.providerType) >= providerCap
1052
+ ) {
1053
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_provider_parallel_reached', nodeId, providerType: resolved.providerType });
1054
+ continue;
1055
+ }
1056
+
1057
+ // Shared worker-launch envelope. For a local node it spawns directly on this
1058
+ // daemon; for a remote node the identical command is forwarded to the node's
1059
+ // daemon (mirrors mesh_launch_session), with the coordinator daemonId stamped
1060
+ // so the worker's completion events route back to this coordinator.
1061
+ const launchSettings: Record<string, unknown> = {
1062
+ // Worker launch envelope: role + mesh context so worker can route completion events.
1063
+ role: 'worker',
1064
+ meshNodeFor: meshId,
1065
+ meshNodeId: nodeId,
1066
+ spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
1067
+ // Coordinator-dispatched worker: auto-approve unless mesh/node policy
1068
+ // opts out (default true). Lands in settingsOverride and beats the
1069
+ // global per-provider-type autoApprove config (see shouldAutoApprove).
1070
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
1071
+ launchedByCoordinator: true,
1072
+ autoLaunchedForQueueTaskId: task.id,
1073
+ };
1074
+
1075
+ if (launchTarget.mode === 'remote') {
1076
+ // Relay-safe completion routing: stamp the coordinator anchor the same way
1077
+ // mesh_launch_session does so the worker forwards events back to this daemon.
1078
+ const remoteSettings: Record<string, unknown> = {
1079
+ ...launchSettings,
1080
+ meshCoordinatorDaemonId: launchTarget.coordinatorDaemonId,
1081
+ meshCoordinatorNodeId: nodeId,
1082
+ };
1083
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1084
+ let launchResult: any;
1085
+ try {
1086
+ launchResult = await components.dispatchMeshCommand!(launchTarget.daemonId!, 'launch_cli', {
1087
+ cliType: resolved.providerType,
1088
+ dir: node.workspace,
1089
+ settings: remoteSettings,
1090
+ });
1091
+ } catch (e: any) {
1092
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: `remote_launch_dispatch_failed: ${e?.message || String(e)}`, nodeId, providerType: resolved.providerType });
1093
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1094
+ return false;
1095
+ }
1096
+ const payload = (launchResult && typeof launchResult === 'object' && 'payload' in launchResult && launchResult.payload && typeof launchResult.payload === 'object')
1097
+ ? launchResult.payload
1098
+ : launchResult;
1099
+ if (!payload?.success) {
1100
+ const reason = readNonEmptyString(payload?.error) || 'remote_launch_cli_failed';
1101
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1102
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1103
+ return false;
1104
+ }
1105
+ // Remote launch is async: the worker session will register and emit agent:ready,
1106
+ // which (forwarded back here) drives the claim via the normal event path / PHASE 1
1107
+ // reconcile. Set a cooldown so the 4s loop doesn't re-launch before that lands.
1108
+ const remoteSessionId = readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.id) || readNonEmptyString(payload.runtimeSessionId);
1109
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId: remoteSessionId || undefined });
1110
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1111
+ return true;
1112
+ }
1113
+
1114
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1115
+ const launchResult: any = await components.cliManager.handleCliCommand('launch_cli', {
1116
+ cliType: resolved.providerType,
1117
+ dir: node.workspace,
1118
+ settings: launchSettings,
1119
+ });
1120
+ if (!launchResult?.success) {
1121
+ const reason = launchResult?.error || 'launch_cli_failed';
1122
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1123
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1124
+ return false;
1125
+ }
1126
+ const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
1127
+ if (!sessionId) {
1128
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
1129
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1130
+ return false;
1131
+ }
1132
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
1133
+ tryAssignQueueTask(components, meshId, nodeId, sessionId, resolved.providerType);
1134
+ return true;
1135
+ } catch (e: any) {
1136
+ markAutoLaunch(meshId, task.id, { status: 'failed', error: e?.message || String(e), nodeId });
1137
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
1138
+ return false;
1139
+ } finally {
1140
+ autoLaunchInProgress.delete(launchKey);
1141
+ }
1142
+ }
1143
+ }
1144
+ return false;
1145
+ }
1146
+
1147
+ export interface MeshQueueTriggerResult {
1148
+ success: true;
1149
+ meshId: string;
1150
+ pendingBefore: number;
1151
+ assignedBefore: number;
1152
+ pendingAfter: number;
1153
+ assignedAfter: number;
1154
+ claimed: boolean;
1155
+ newlyAssignedTasks: Array<{
1156
+ id: string;
1157
+ nodeId?: string;
1158
+ sessionId?: string;
1159
+ }>;
1160
+ localIdleSessionsChecked: number;
1161
+ remoteIdleSessionsChecked: number;
1162
+ skippedSessions: Array<{
1163
+ nodeId?: string;
1164
+ sessionId?: string;
1165
+ reason: string;
1166
+ status?: string;
1167
+ }>;
1168
+ autoLaunchStarted: boolean;
1169
+ /**
1170
+ * True when a worker session is already on its way to claim a still-pending task —
1171
+ * either launched this tick (autoLaunchStarted) or launched on a prior tick and still
1172
+ * booting/awaiting-claim. Callers MUST treat this as "wait, do not launch another
1173
+ * session": a second launch double-edits the worktree. Mutually informative with
1174
+ * `noIdleMeshSessionAvailable`, which is suppressed whenever this is true.
1175
+ */
1176
+ autoLaunchPending?: boolean;
1177
+ noIdleMeshSessionAvailable?: boolean;
1178
+ }
1179
+
1180
+ function countQueueStatus(meshId: string, status: 'pending' | 'assigned'): number {
1181
+ return getQueue(meshId, { status: [status] as any }).length;
1182
+ }
1183
+
1184
+ function getQueueStatusById(meshId: string): Map<string, string> {
1185
+ return new Map(getQueue(meshId).map(task => [task.id, task.status]));
1186
+ }
1187
+
1188
+ export async function triggerMeshQueue(components: DaemonComponents, meshId: string): Promise<MeshQueueTriggerResult> {
1189
+ const mesh = getMeshWithCache(components, meshId);
1190
+ const pendingBefore = countQueueStatus(meshId, 'pending');
1191
+ const assignedBefore = countQueueStatus(meshId, 'assigned');
1192
+ const beforeStatus = getQueueStatusById(meshId);
1193
+ const skippedSessions: MeshQueueTriggerResult['skippedSessions'] = [];
1194
+ let localIdleSessionsChecked = 0;
1195
+ let remoteIdleSessionsChecked = 0;
1196
+ let autoLaunchStarted = false;
1197
+ if (!mesh) {
1198
+ return {
1199
+ success: true,
1200
+ meshId,
1201
+ pendingBefore,
1202
+ assignedBefore,
1203
+ pendingAfter: pendingBefore,
1204
+ assignedAfter: assignedBefore,
1205
+ claimed: false,
1206
+ newlyAssignedTasks: [],
1207
+ localIdleSessionsChecked,
1208
+ remoteIdleSessionsChecked,
1209
+ skippedSessions: [{ reason: 'mesh_not_found' }],
1210
+ autoLaunchStarted,
1211
+ noIdleMeshSessionAvailable: true,
1212
+ };
1213
+ }
1214
+
1215
+ // Collect every idle mesh session (local CLI instances + remote idle records)
1216
+ // as drain candidates. The drain ORDER depends on the scheduling strategy:
1217
+ // - 'first_eligible' (default): local-first, then remote, exactly as before.
1218
+ // - otherwise: local + remote merged into one pool and drained in scheduling
1219
+ // order (priority → load → tie-break). This local-first debias is required
1220
+ // because without it the coordinator's own local node is always visited
1221
+ // first and greedily absorbs all untargeted work before any remote idle
1222
+ // session is even considered — the comparator alone can't spread work if
1223
+ // local is always tried first.
1224
+ type IdleCandidate = { nodeId: string; sessionId: string; providerType: string; origin: 'local' | 'remote'; node: any };
1225
+ const strategy = resolveSchedulingStrategy(mesh);
1226
+ const localCandidates: IdleCandidate[] = [];
1227
+
1228
+ const cliInstances = components.instanceManager.getByCategory('cli');
1229
+ for (const inst of cliInstances) {
1230
+ const state = inst.getState();
1231
+ const settings = state.settings as Record<string, unknown> || {};
1232
+
1233
+ const instMeshId = readNonEmptyString(settings.meshNodeFor);
1234
+ if (instMeshId !== meshId) continue;
1235
+
1236
+ const nodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
1237
+ if (!nodeId) continue;
1238
+
1239
+ if (!isIdleSessionState(state)) {
1240
+ const status = readNonEmptyString(state.status).toLowerCase();
1241
+ skippedSessions.push({
1242
+ nodeId,
1243
+ sessionId: readNonEmptyString(state.instanceId),
1244
+ reason: isTerminalSessionStatus(status) ? 'terminal_session' : 'session_not_idle',
1245
+ status: status || undefined,
1246
+ });
1247
+ continue;
1248
+ }
1249
+
1250
+ const sessionId = state.instanceId;
1251
+ const providerType = state.type || readNonEmptyString(settings.providerType);
1252
+
1253
+ if (providerType) {
1254
+ localIdleSessionsChecked += 1;
1255
+ localCandidates.push({ nodeId, sessionId, providerType, origin: 'local', node: mesh.nodes.find((n: any) => readMeshNodeId(n) === nodeId) });
1256
+ } else {
1257
+ skippedSessions.push({
1258
+ nodeId,
1259
+ sessionId,
1260
+ reason: 'provider_type_missing',
1261
+ });
1262
+ }
1263
+ }
1264
+
1265
+ let remoteSessions: Array<{ nodeId: string; sessionId: string; providerType: string }> = [];
1266
+ try {
1267
+ remoteSessions = MeshRuntimeStore.getInstance().getRemoteIdleSessions();
1268
+ } catch { /* best-effort */ }
1269
+
1270
+ const remoteCandidates: IdleCandidate[] = [];
1271
+ for (const idle of remoteSessions) {
1272
+ // Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
1273
+ // `n.id`, so an inline-cached worktree node whose identity arrived under a
1274
+ // different form is not silently dropped — leaving a remote idle session
1275
+ // unable to claim its pending queue task.
1276
+ const node = mesh.nodes.find((n: any) => meshNodeIdMatches(n, idle.nodeId));
1277
+ if (node) {
1278
+ remoteIdleSessionsChecked += 1;
1279
+ remoteCandidates.push({ nodeId: idle.nodeId, sessionId: idle.sessionId, providerType: idle.providerType, origin: 'remote', node });
1280
+ }
1281
+ }
1282
+
1283
+ const assignIdleCandidate = (candidate: IdleCandidate): void => {
1284
+ const assigned = tryAssignQueueTask(components, meshId, candidate.nodeId, candidate.sessionId, candidate.providerType);
1285
+ if (assigned && candidate.origin === 'remote') {
1286
+ try {
1287
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(candidate.nodeId, candidate.sessionId);
1288
+ } catch { /* best-effort */ }
1289
+ }
1290
+ };
1291
+
1292
+ if (strategy === 'first_eligible') {
1293
+ // Strict no-change: drain local idle sessions first (original order), then
1294
+ // remote idle sessions. tryAssignQueueTask is a no-op when nothing matches.
1295
+ for (const candidate of localCandidates) assignIdleCandidate(candidate);
1296
+ for (const candidate of remoteCandidates) assignIdleCandidate(candidate);
1297
+ } else {
1298
+ // Merge local + remote into one pool and drain in scheduling order. Each
1299
+ // assignment mutates a node's active load, and the next pick re-reads it,
1300
+ // so re-ranking after every assignment keeps the spread fair as load shifts.
1301
+ const pool = [...localCandidates, ...remoteCandidates];
1302
+ const baseIndex = new Map<string, number>();
1303
+ pool.forEach((c, i) => { if (!baseIndex.has(c.nodeId)) baseIndex.set(c.nodeId, i); });
1304
+ // Bump the round-robin cursor once for this whole drain pass.
1305
+ const uniqueNodes = [...new Set(pool.map(c => c.nodeId))]
1306
+ .map((nodeId, index) => ({ nodeId, node: pool.find(c => c.nodeId === nodeId)?.node, index }));
1307
+ const ranked = orderEligibleNodes(meshId, strategy, uniqueNodes, { bumpCursor: true });
1308
+ const rankIndex = new Map<string, number>(ranked.map((r, i) => [r.nodeId, i]));
1309
+ const remaining = [...pool];
1310
+ while (remaining.length > 0) {
1311
+ // Re-rank each pass so a node that just took work defers its next session.
1312
+ remaining.sort((a, b) => {
1313
+ const aPrio = resolveNodeSchedulingPriority(a.node?.policy);
1314
+ const bPrio = resolveNodeSchedulingPriority(b.node?.policy);
1315
+ if (aPrio !== bPrio) return bPrio - aPrio;
1316
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
1317
+ const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
1318
+ if (loadDelta !== 0) return loadDelta;
1319
+ }
1320
+ return (rankIndex.get(a.nodeId) ?? 0) - (rankIndex.get(b.nodeId) ?? 0);
1321
+ });
1322
+ assignIdleCandidate(remaining.shift()!);
1323
+ }
1324
+ }
1325
+
1326
+ autoLaunchStarted = await maybeAutoLaunchOneQueueSession(components, meshId, mesh);
1327
+ const afterQueue = getQueue(meshId);
1328
+ const pendingAfter = afterQueue.filter(task => task.status === 'pending').length;
1329
+ const assignedAfter = afterQueue.filter(task => task.status === 'assigned').length;
1330
+ const newlyAssignedTasks = afterQueue
1331
+ .filter(task => task.status === 'assigned' && beforeStatus.get(task.id) !== 'assigned')
1332
+ .map(task => ({
1333
+ id: task.id,
1334
+ nodeId: task.assignedNodeId,
1335
+ sessionId: task.assignedSessionId,
1336
+ }));
1337
+
1338
+ // An auto-launch is "pending" when the coordinator has already spun a session up
1339
+ // for a still-pending task and is waiting on that session's idle→claim. This covers
1340
+ // two ticks:
1341
+ // - THIS tick fired the launch (autoLaunchStarted), or
1342
+ // - a PRIOR tick launched a session that is still booting/awaiting-claim — the
1343
+ // per-task await-claim guard (maybeAutoLaunchOneQueueSession) deliberately
1344
+ // declines to launch again, so autoLaunchStarted is false even though a session
1345
+ // is on its way to claim this task.
1346
+ // Without this signal, the second tick reports `noIdleMeshSessionAvailable` and the
1347
+ // MCP guidance tells the coordinator to launch ANOTHER worker — producing a duplicate
1348
+ // session that double-edits the worktree. The claim itself is fine; only the wording
1349
+ // was wrong, so we surface `autoLaunchPending` to suppress the bad "launch one more"
1350
+ // advice while the just-launched session converges.
1351
+ const autoLaunchPending = autoLaunchStarted || afterQueue.some(task => {
1352
+ if (task.status !== 'pending') return false;
1353
+ const al = task.autoLaunch;
1354
+ if (!al || (al.status !== 'started' && al.status !== 'completed')) return false;
1355
+ const launchedAtMs = Date.parse(al.updatedAt);
1356
+ return Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS;
1357
+ });
1358
+
1359
+ return {
1360
+ success: true,
1361
+ meshId,
1362
+ pendingBefore,
1363
+ assignedBefore,
1364
+ pendingAfter,
1365
+ assignedAfter,
1366
+ claimed: newlyAssignedTasks.length > 0,
1367
+ newlyAssignedTasks,
1368
+ localIdleSessionsChecked,
1369
+ remoteIdleSessionsChecked,
1370
+ skippedSessions,
1371
+ autoLaunchStarted,
1372
+ ...(autoLaunchPending ? { autoLaunchPending: true } : {}),
1373
+ // Only report "no idle session, go launch one" when nothing is already on its way.
1374
+ // A pending auto-launch (this tick or a prior still-converging one) means a session
1375
+ // WILL claim shortly, so it is not a no-session-available situation.
1376
+ ...(pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchPending
1377
+ ? { noIdleMeshSessionAvailable: true }
1378
+ : {}),
1379
+ };
1380
+ }
1381
+
1382
+ export async function maybeAutoFastForwardIdleNode(components: DaemonComponents, args: {
1383
+ meshId: string;
1384
+ nodeId: string;
1385
+ sessionId?: string;
1386
+ providerType?: string;
1387
+ }): Promise<void> {
1388
+ const mesh = getMeshWithCache(components, args.meshId);
1389
+ const node = mesh?.nodes?.find((candidate: any) => meshNodeIdMatches(candidate, args.nodeId));
1390
+ const workspace = readNonEmptyString(node?.workspace);
1391
+ if (!workspace) return;
1392
+ if (!existsSync(workspace)) return;
1393
+
1394
+ const policy = resolveAutoFastForwardPolicy(mesh);
1395
+ if (!policy.enabled) return;
1396
+ if (nodeHasActiveMeshWork(components, args.meshId, args.nodeId, args.sessionId)) return;
1397
+
1398
+ const throttleKey = `${args.meshId}:${args.nodeId}`;
1399
+ const now = Date.now();
1400
+ const lastAttempt = idleAutoFastForwardLastAttempt.get(throttleKey) || 0;
1401
+ if (now - lastAttempt < IDLE_AUTO_FAST_FORWARD_THROTTLE_MS) return;
1402
+ idleAutoFastForwardLastAttempt.set(throttleKey, now);
1403
+
1404
+ const submoduleIgnorePaths = Array.isArray(node?.policy?.submoduleIgnorePaths)
1405
+ ? node.policy.submoduleIgnorePaths.filter((value: unknown): value is string => typeof value === 'string')
1406
+ : undefined;
1407
+ try {
1408
+ const dryRun = await fastForwardMeshNode({
1409
+ meshId: args.meshId,
1410
+ nodeId: args.nodeId,
1411
+ workspace,
1412
+ execute: false,
1413
+ dryRun: true,
1414
+ updateSubmodules: false,
1415
+ submoduleIgnorePaths,
1416
+ trigger: 'idle_auto',
1417
+ });
1418
+ if (!dryRun || dryRun.code !== 'fast_forward_available' || dryRun.allowed !== true) return;
1419
+ const behind = Number(dryRun.current?.behind);
1420
+ if (policy.maxBehind !== undefined && Number.isFinite(behind) && behind > policy.maxBehind) return;
1421
+ if (policy.requireCleanSubmodules) {
1422
+ const submodules = Array.isArray(dryRun.current?.submodules) ? dryRun.current.submodules : [];
1423
+ if (submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return;
1424
+ }
1425
+ await fastForwardMeshNode({
1426
+ meshId: args.meshId,
1427
+ nodeId: args.nodeId,
1428
+ workspace,
1429
+ execute: true,
1430
+ dryRun: false,
1431
+ updateSubmodules: false,
1432
+ submoduleIgnorePaths,
1433
+ trigger: 'idle_auto',
1434
+ });
1435
+ } catch (e: any) {
1436
+ LOG.warn('MeshFastForward', `Idle auto fast-forward check failed for ${args.nodeId}: ${e?.message || e}`);
1437
+ }
1438
+ }
1439
+
1440
+ export function runIdleMaintenanceThenAssignQueue(components: DaemonComponents, args: {
1441
+ meshId: string;
1442
+ nodeId: string;
1443
+ sessionId: string;
1444
+ providerType: string;
1445
+ }): void {
1446
+ setImmediate(() => {
1447
+ maybeAutoFastForwardIdleNode(components, args)
1448
+ .finally(() => {
1449
+ try {
1450
+ tryAssignQueueTask(components, args.meshId, args.nodeId, args.sessionId, args.providerType);
1451
+ } catch (e: any) {
1452
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${args.nodeId}: ${e?.message || e}`);
1453
+ }
1454
+ });
1455
+ });
1456
+ }
1457
+