@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
@@ -1,2993 +1,30 @@
1
- import { existsSync } from 'fs';
2
- import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
3
- import { loadConfig } from '../config/config.js';
4
- import { getMesh, getMeshByRepo, listMeshes } from '../config/mesh-config.js';
5
- import { detectCLI } from '../detection/cli-detector.js';
6
- import { LOG } from '../logging/logger.js';
7
- import { appendLedgerEntry, buildTaskCompletionEvidence, getSessionRecoveryContext, isIntentionalCleanupStopEntry, readLedgerEntries } from './mesh-ledger.js';
8
- import type { MeshLedgerKind, SessionRecoveryContext } from './mesh-ledger.js';
9
- import { buildMeshNodeCapabilityTags, nodeSatisfiesRequiredTags, claimNextTask, updateSessionTaskStatus, enqueueTask, updateTaskStatus, getQueue, recordTaskAutoLaunch, updateDirectDispatchStatus, cleanupTerminalDirectDispatches, getActiveDirectDispatches, hasPendingDependents } 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, markSessionDeliveriesTerminal, updateSessionDeliveryStatus, recordCompletionConflict } from './mesh-delivery-policy.js';
13
- import { MeshRuntimeStore } from './mesh-runtime-store.js';
14
- import { queuePendingMeshCoordinatorEvent, drainPendingMeshCoordinatorEvents } from './mesh-events-pending.js';
15
- import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
16
- import { resolveWorkerDelegateRouting, recordUnroutableDelegateEvent, isUnroutableDelegateRejection } from './mesh-routing.js';
17
- import { enqueueUnresolvedDelegateForward, peekUnresolvedDelegateForwards, ackUnresolvedDelegateForward } from './mesh-unresolved-forward-outbox.js';
18
- import { traceMeshEventStage, traceMeshEventDrop } from './mesh-event-trace.js';
19
- import { awaitWithWarmupDeadline, resolveWarmupDeadlineOpts } from './mesh-warmup-deadline.js';
20
- import { getLastDisplayMessage } from '../status/snapshot.js';
21
- import { resolveDelegatedWorkerAutoApprove, resolveProviderMaxParallel, resolveNodeSchedulingPriority, normalizeMeshSchedulingStrategy } from '../repo-mesh-types.js';
22
- import type { RepoMeshSchedulingStrategy } from '../repo-mesh-types.js';
23
- import { normalizeMeshNodeId, meshNodeIdMatches, daemonIdsEquivalent, expandDaemonIdForms, normalizeMeshWorkspaceForCompare, meshWorkspacesEquivalent, type MeshNodeIdentified } from '@adhdev/mesh-shared';
24
- import {
25
- findRecentTerminalLedgerEvidence,
26
- findTerminalLedgerEvidenceForTask,
27
- hasDispatchAfterTerminal,
28
- hasUnterminalDirectDispatchLedgerEntry,
29
- buildNoProgressCompletionReconciliation,
30
- } from './mesh-events-stale.js';
31
- import {
32
- buildMeshSystemMessage,
33
- readNonEmptyString,
34
- readRecord,
35
- resolveEventSessionId,
36
- readRefineJobId,
37
- readWorkerResultMetadata,
38
- resolveMeshSurfacedSessionPreview,
39
- } from './mesh-events-utils.js';
40
-
41
- // The set of coordinator-daemon ids this daemon answers to when draining the
42
- // pending-events queue. Mirrors resolveCoordinatorDaemonIds in mesh-reconcile-loop:
43
- // a unicast event may be stamped with the status id, the bare machineId, OR the
44
- // config-form node daemonId (`daemon_<machineId>`) depending on which dispatch path
45
- // created the worker. We expand to EVERY equivalent form so a `daemon_<machineId>`
46
- // completion matches a coordinator that knows itself as bare `<machineId>` (the
47
- // base-node completion-surface bug) and vice versa.
48
- function resolveCoordinatorDrainDaemonIds(components: DaemonComponents): string[] {
49
- const statusInstanceId = readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId);
50
- const machineId = readNonEmptyString(loadConfig().machineId);
51
- return expandDaemonIdForms([statusInstanceId, machineId]);
52
- }
53
-
54
- // ---------------------------------------------------------------------------
55
- // Remote Node Idle Session Tracking
56
- // ---------------------------------------------------------------------------
57
- const REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1000; // 5 minutes
58
-
59
- // ---------------------------------------------------------------------------
60
- // Workspace-to-mesh lookup cache
61
- // ---------------------------------------------------------------------------
62
- const meshByWorkspaceCache = new Map<string, { mesh: any; cachedAt: number }>();
63
- const MESH_WORKSPACE_CACHE_TTL_MS = 5_000;
64
- const IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1000;
65
- const idleAutoFastForwardLastAttempt = new Map<string, number>();
66
-
67
- function getCachedMeshByWorkspace(workspace: string): any {
68
- const now = Date.now();
69
- const cached = meshByWorkspaceCache.get(workspace);
70
- if (cached && now - cached.cachedAt < MESH_WORKSPACE_CACHE_TTL_MS) return cached.mesh;
71
- const mesh = getMeshByRepo(workspace);
72
- meshByWorkspaceCache.set(workspace, { mesh, cachedAt: now });
73
- return mesh;
74
- }
75
-
76
- // Deterministic meshId recovery for a forwarded worker event that carries no meshId.
77
- // An unresolved-mesh worker (forwardUnresolvedDelegateEvent) cannot resolve its own
78
- // meshId locally, so it pushes the event with nodeId + workspace only and relies on
79
- // the coordinator — which hosts the mesh — to recover the id. Workspace recovery
80
- // (getCachedMeshByWorkspace → getMeshByRepo) is the fast path but can miss (a worktree
81
- // clone whose repoIdentity differs, or a transient cache state), which left the retry
82
- // permanently rejected with "meshId required". The node-id IS a stable, coordinator-side
83
- // fact: scan the hosted meshes for the one whose node matches the forwarded nodeId
84
- // (3-form normalizer). This is timing-independent and never depends on repo lookup.
85
- function recoverMeshIdByNodeId(nodeId: string): string {
86
- if (!nodeId) return '';
87
- for (const mesh of listMeshes()) {
88
- if (Array.isArray(mesh.nodes) && mesh.nodes.some((n: any) => meshNodeIdMatches(n, nodeId))) {
89
- return readNonEmptyString(mesh.id);
90
- }
91
- }
92
- return '';
93
- }
94
-
95
- // RECONCILE-MESHID-DROP: WORKER-side meshId resolution for an unresolved-delegate
96
- // forward payload. forwardUnresolvedDelegateEvent omits meshId by design (the worker
97
- // "can't resolve it") and relies on the COORDINATOR recovering it from workspace/nodeId.
98
- // That recovery fails when the no_node_binding session's payload has an empty nodeId AND
99
- // the coordinator's workspace→mesh lookup misses (a worktree clone whose repoIdentity
100
- // differs / a cache miss) — leaving the reconcile retry rejected with "meshId required"
101
- // every 4s forever. The worker actually has MORE context than the stripped payload gives
102
- // the coordinator: it hosts the node as a member and holds the LIVE session, whose
103
- // settings.meshNodeFor / meshNodeId are authoritative even when they were not stamped
104
- // onto the original event. Resolve here (worker side) and stamp meshId onto the payload so
105
- // the coordinator accepts it. Mirrors the receiver's recovery order, then adds the live-
106
- // session fallback. Returns '' when even the worker cannot resolve it (truly unresolvable —
107
- // the retry cap then drops it instead of looping). No side effects; safe to call per retry.
108
- export function resolveForwardEventMeshId(
109
- components: DaemonComponents,
110
- payload: Record<string, unknown>,
111
- ): string {
112
- const direct = readNonEmptyString(payload.meshId);
113
- if (direct) return direct;
114
- const workspace = readNonEmptyString(payload.workspace);
115
- const byWorkspace = workspace ? readNonEmptyString(getCachedMeshByWorkspace(workspace)?.id) : '';
116
- if (byWorkspace) return byWorkspace;
117
- const byNode = recoverMeshIdByNodeId(readNonEmptyString(payload.nodeId));
118
- if (byNode) return byNode;
119
- // Live-session fallback: the worker session may carry meshNodeFor / meshNodeId now even
120
- // though the original event didn't (a late stamp, or an event that fired before binding).
121
- const sessionId = readNonEmptyString(payload.targetSessionId)
122
- || readNonEmptyString(payload.sessionId)
123
- || readNonEmptyString(payload.instanceId);
124
- if (sessionId) {
125
- try {
126
- const state = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
127
- const settings = (state?.settings as Record<string, unknown>) || {};
128
- const meshNodeFor = readNonEmptyString(settings.meshNodeFor);
129
- if (meshNodeFor) return meshNodeFor;
130
- const byStamp = recoverMeshIdByNodeId(readNonEmptyString(settings.meshNodeId));
131
- if (byStamp) return byStamp;
132
- const sessionWorkspace = readNonEmptyString(state?.workspace);
133
- const bySessionWorkspace = sessionWorkspace ? readNonEmptyString(getCachedMeshByWorkspace(sessionWorkspace)?.id) : '';
134
- if (bySessionWorkspace) return bySessionWorkspace;
135
- } catch { /* best-effort — fall through to unresolved */ }
136
- }
137
- return '';
138
- }
139
-
140
- export function __resetIdleAutoFastForwardForTests(): void {
141
- idleAutoFastForwardLastAttempt.clear();
142
- }
143
-
144
- export function __resetMeshWorkspaceCacheForTests(): void {
145
- meshByWorkspaceCache.clear();
146
- }
147
-
148
- function sweepExpiredRemoteIdleSessions(): void {
149
- try {
150
- MeshRuntimeStore.getInstance().pruneExpiredRemoteIdleSessions();
151
- } catch { /* best-effort */ }
152
- }
153
-
154
- function getMeshWithCache(components: DaemonComponents, meshId: string): any | undefined {
155
- const localMesh = getMesh(meshId);
156
- const cachedMesh = components.router?.getCachedInlineMesh(meshId);
157
- if (!localMesh) return cachedMesh;
158
- if (!cachedMesh) return localMesh;
159
- return mergeInlineCacheOnlyNodes(localMesh, cachedMesh);
160
- }
161
-
162
- /**
163
- * Claim-time membership view unification (CLAIMSTALL fix).
164
- *
165
- * The coordinator's claim path — triggerMeshQueue → autoLaunch candidate filter
166
- * and the local/remote idle-session drain — reads mesh membership through
167
- * getMeshWithCache, which historically returned the local-config mesh verbatim
168
- * whenever one existed. A freshly cloned worktree node is registered ONLY into the
169
- * router's inline mesh cache: clone_mesh_node's `meshRecord.inline` branch calls
170
- * updateInlineMeshNode, NOT addNode, so the worktree node never reaches local
171
- * config (meshes.json). The config-first view therefore omits the worktree node,
172
- * while send_task — which resolves membership through getMeshForCommand(preferInline)
173
- * over the same inline cache — sees it. That view asymmetry is the stall: a queue
174
- * task pinned to the worktree node reports `target_node_id_unmatched` (autoLaunch
175
- * candidate filter / targetPinUnmatched check) and the node's idle session is
176
- * dropped from the drain pool (mesh.nodes.find miss), so claim never fires and the
177
- * task is stranded pending — even though nodeId matching itself is correct.
178
- *
179
- * Fix: union the local-config nodes with any inline-cache-ONLY nodes, so the claim
180
- * view matches the command (send_task) view. Base (non-worktree) nodes present in
181
- * local config stay config-authoritative — their entry is taken verbatim from
182
- * localMesh, so base node claim/matching is byte-for-byte unchanged. Only nodes
183
- * that exist solely in the inline cache (the cloned worktree nodes) are appended.
184
- * Identity comparison uses the shared 3-form normalizer (id / nodeId / node_id),
185
- * identical to every other claim-path consumer — the matching logic is untouched,
186
- * only which nodes are visible.
187
- */
188
- function mergeInlineCacheOnlyNodes(localMesh: any, cachedMesh: any): any {
189
- const localNodes = Array.isArray(localMesh?.nodes) ? localMesh.nodes : [];
190
- const cachedNodes = Array.isArray(cachedMesh?.nodes) ? cachedMesh.nodes : [];
191
- if (!cachedNodes.length) return localMesh;
192
- const cacheOnly = cachedNodes.filter((cachedNode: any) => {
193
- const cachedId = readMeshNodeId(cachedNode);
194
- // Unidentifiable cache entries can never be a claim/route target — skip them
195
- // rather than appending junk that no consumer can address.
196
- if (!cachedId) return false;
197
- return !localNodes.some((localNode: any) => meshNodeIdMatches(localNode, cachedId));
198
- });
199
- if (!cacheOnly.length) return localMesh;
200
- return { ...localMesh, nodes: [...localNodes, ...cacheOnly] };
201
- }
202
-
203
- const INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS = 30 * 60 * 1000;
204
-
205
- function isIntentionalCleanupStopMetadata(event: Record<string, unknown>): boolean {
206
- return event.intentional === true
207
- || event.intentionalStop === true
208
- || event.operatorCleanup === true
209
- || event.reason === 'operator_cleanup'
210
- || event.stopReason === 'operator_cleanup'
211
- || event.cleanupReason === 'operator_cleanup'
212
- || event.source === 'mesh_cleanup_sessions'
213
- || event.source === 'mesh_remove_node';
214
- }
215
-
216
- function hasRecentIntentionalCleanupStop(meshId: string, sessionId?: string, nodeId?: string): boolean {
217
- if (!sessionId && !nodeId) return false;
218
- const cutoff = Date.now() - INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS;
219
- const entries = readLedgerEntries(meshId, { tail: 200 });
220
- for (let i = entries.length - 1; i >= 0; i--) {
221
- const entry = entries[i];
222
- const timestamp = new Date(entry.timestamp).getTime();
223
- if (!Number.isNaN(timestamp) && timestamp < cutoff) break;
224
- if (!isIntentionalCleanupStopEntry(entry)) continue;
225
- if (sessionId && entry.sessionId === sessionId) return true;
226
- // Normalized node-id match (P4): the cleanup-stop entry's node id may be stored as
227
- // `nodeId` or `node_id` and the `nodeId` arg can be in either form — a raw `===`
228
- // would miss a genuine intentional-cleanup entry and fail to suppress the stop event.
229
- if (!sessionId && nodeId && meshNodeIdMatches(entry as unknown as MeshNodeIdentified, nodeId)) return true;
230
- }
231
- return false;
232
- }
233
-
234
- function shouldSuppressIntentionalCleanupStop(args: {
235
- event: string;
236
- meshId: string;
237
- metadataEvent: Record<string, unknown>;
238
- sessionId?: string;
239
- nodeId?: string;
240
- }): boolean {
241
- if (args.event !== 'agent:stopped' && args.event !== 'monitor:no_progress') return false;
242
- if (isIntentionalCleanupStopMetadata(args.metadataEvent)) return true;
243
- return hasRecentIntentionalCleanupStop(args.meshId, args.sessionId, args.nodeId);
244
- }
245
-
246
- const RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1000;
247
-
248
- function hasFingerprintSeen(fingerprint: string): boolean {
249
- try {
250
- return MeshRuntimeStore.getInstance().hasCompletionFingerprint(fingerprint);
251
- } catch {
252
- return false;
253
- }
254
- }
255
-
256
- function recordFingerprintSeen(fingerprint: string): void {
257
- try {
258
- const db = MeshRuntimeStore.getInstance();
259
- db.recordCompletionFingerprint(fingerprint, RECENT_COMPLETION_FINGERPRINT_TTL_MS);
260
- db.sweepExpiredFingerprints();
261
- } catch { /* best-effort; duplicate events are preferable to a crash */ }
262
- }
263
-
264
- function readEventTimestamp(value: unknown): number | null {
265
- if (typeof value === 'number' && Number.isFinite(value)) return value;
266
- if (typeof value === 'string' && value.trim()) {
267
- const numeric = Number(value);
268
- if (Number.isFinite(numeric)) return numeric;
269
- const parsed = Date.parse(value);
270
- if (Number.isFinite(parsed)) return parsed;
271
- }
272
- return null;
273
- }
274
-
275
- function buildMeshCompletionFingerprint(args: {
276
- meshId: string;
277
- event: string;
278
- sessionId: string;
279
- providerType?: string;
280
- providerSessionId?: string;
281
- timestamp?: number | null;
282
- finalSummary?: string;
283
- coordinatorDaemonId?: string;
284
- }): string {
285
- const timestampPart = Number.isFinite(args.timestamp)
286
- ? String(args.timestamp)
287
- : readNonEmptyString(args.finalSummary).slice(0, 200);
288
- return [
289
- args.meshId,
290
- args.event,
291
- args.sessionId,
292
- args.providerType || '',
293
- args.providerSessionId || '',
294
- timestampPart,
295
- args.coordinatorDaemonId || '',
296
- ].join('::');
297
- }
298
-
299
- function isDuplicateMeshCompletionEvent(args: {
300
- meshId: string;
301
- event: string;
302
- sessionId: string;
303
- providerType?: string;
304
- providerSessionId?: string;
305
- timestamp?: number | null;
306
- finalSummary?: string;
307
- coordinatorDaemonId?: string;
308
- taskId?: string;
309
- nodeId?: string;
310
- }): boolean {
311
- const fingerprint = buildMeshCompletionFingerprint(args);
312
- if (!fingerprint) return false;
313
- if (hasFingerprintSeen(fingerprint)) {
314
- if (args.taskId) {
315
- recordCompletionConflict({
316
- meshId: args.meshId,
317
- fingerprint,
318
- conflictingTaskId: args.taskId,
319
- conflictingSessionId: args.sessionId,
320
- event: args.event,
321
- });
322
- }
323
- return true;
324
- }
325
- recordFingerprintSeen(fingerprint);
326
- return false;
327
- }
328
-
329
- function isDuplicateMeshApprovalEvent(args: {
330
- meshId: string;
331
- sessionId: string;
332
- providerType?: string;
333
- timestamp?: number | null;
334
- modalMessage?: string;
335
- modalButtons?: unknown;
336
- }): boolean {
337
- const modalButtons = Array.isArray(args.modalButtons)
338
- ? args.modalButtons.map(button => String(button).trim()).filter(Boolean)
339
- : [];
340
- const approvalIdentity = Number.isFinite(args.timestamp)
341
- ? String(args.timestamp)
342
- : JSON.stringify({ message: args.modalMessage || '', buttons: modalButtons });
343
- if (!approvalIdentity || approvalIdentity === '{"message":"","buttons":[]}') return false;
344
- const fingerprint = [
345
- args.meshId,
346
- 'agent:waiting_approval',
347
- args.sessionId,
348
- args.providerType || '',
349
- approvalIdentity,
350
- ].join('::');
351
- if (hasFingerprintSeen(fingerprint)) return true;
352
- recordFingerprintSeen(fingerprint);
353
- return false;
354
- }
355
-
356
- function isDuplicateRefineTerminalEvent(meshId: string, eventName: string, metadataEvent: Record<string, unknown>): boolean {
357
- const jobId = readRefineJobId({ metadataEvent });
358
- const fingerprint = jobId && new Set(['refine:completed', 'refine:failed']).has(eventName) ? `${meshId}::${eventName}::${jobId}` : '';
359
- if (!fingerprint) return false;
360
- if (hasFingerprintSeen(fingerprint)) return true;
361
- recordFingerprintSeen(fingerprint);
362
- return false;
363
- }
364
-
365
- // A worker/coordinator "false idle": the provider dropped to idle WITHOUT a confirmed
366
- // final assistant message for the turn (a finalization timeout, or a "scheduled fallback"
367
- // idle). This is the signal cli-provider-instance emits as
368
- // completionDiagnostic.blockReason='missing_final_assistant' / finalAssistantPresent=false.
369
- // Such a completion is NOT trustworthy terminal evidence: it must neither permanently
370
- // terminate a direct-dispatch task nor suppress the genuine completion a later turn
371
- // (commonly driven by a coordinator nudge / re-dispatch) produces.
372
- function isFalseIdleCompletion(metadataEvent: Record<string, unknown>): boolean {
373
- const diag = readRecord(metadataEvent.completionDiagnostic);
374
- if (!diag) return false;
375
- return diag.finalAssistantPresent === false || diag.blockReason === 'missing_final_assistant';
376
- }
377
-
378
- // The genuine-completion counterpart: a real final summary / worker result is present and
379
- // the completion is not flagged as a missing-final-assistant false idle. Used to decide
380
- // whether a new completion may supersede a prior WEAK (false-idle) terminal.
381
- function isGenuineCompletionEvidence(metadataEvent: Record<string, unknown>): boolean {
382
- if (isFalseIdleCompletion(metadataEvent)) return false;
383
- return !!readWorkerResultMetadata(metadataEvent) || !!readNonEmptyString(metadataEvent.finalSummary);
384
- }
385
-
386
- // True when a terminal ledger payload was recorded from WEAK completion evidence (a false
387
- // idle): insufficient evidence level, review-recommended, or a missing-final-assistant
388
- // completion diagnostic. A weak terminal is non-authoritative — a later genuine completion
389
- // (live path) or a transcript reconcile (fallback path) may supersede it.
390
- function isWeakTerminalLedgerPayload(payload: Record<string, unknown> | undefined): boolean {
391
- if (!payload) return false;
392
- if (payload.evidenceLevel === 'insufficient' || payload.reviewRecommended === true) return true;
393
- const diag = readRecord(payload.completionDiagnostic);
394
- return diag?.finalAssistantPresent === false || diag?.blockReason === 'missing_final_assistant';
395
- }
396
-
397
- // (FALSEIDLE-BGCHILD-b) A later genuine completion of the SAME task that carries a
398
- // substantively different — and fuller — final summary than the recorded terminal is the REAL
399
- // final that an earlier (false-idle) completion pre-empted, not a duplicate. The background-child
400
- // false idle is the nasty case the plain isWeakTerminalLedgerPayload supersession misses: the
401
- // early completion's screen parser DID see a prior/intermediate standard assistant, so it is
402
- // recorded as a STRONG terminal with a non-empty (but truncated) finalSummary. Without this the
403
- // providerSessionId/finalSummary dedup below swallows the genuine final and the coordinator is
404
- // stuck with the truncated mid-turn text forever (the one-shot-consumption symptom). Same-task,
405
- // new event is genuine, prior terminal summary is a strict prefix of (or otherwise shorter than)
406
- // the new one → treat as the corrected final and let it through. Conservative: requires the new
407
- // summary to be genuine evidence AND meaningfully longer, so an identical re-arrival or a SHORTER
408
- // later summary is still deduped.
409
- function supersedesTruncatedTerminalSummary(args: {
410
- terminalPayload: Record<string, unknown>;
411
- metadataEvent: Record<string, unknown>;
412
- terminalTaskId: string;
413
- eventTaskId: string;
414
- }): boolean {
415
- // Only applies when both name the SAME task (a distinct task is handled by distinctTaskCompletion).
416
- if (!args.terminalTaskId || !args.eventTaskId || args.terminalTaskId !== args.eventTaskId) return false;
417
- if (!isGenuineCompletionEvidence(args.metadataEvent)) return false;
418
- const terminalSummary = readNonEmptyString(args.terminalPayload.finalSummary);
419
- const eventSummary = readNonEmptyString(args.metadataEvent.finalSummary);
420
- if (!eventSummary) return false;
421
- // Identical text → genuine duplicate, keep deduping.
422
- if (terminalSummary === eventSummary) return false;
423
- // The recorded terminal was a known-weak (false-idle) one → already handled by the weak
424
- // supersession path; nothing extra to do here.
425
- if (isWeakTerminalLedgerPayload(args.terminalPayload)) return false;
426
- // No prior summary at all, or the new summary strictly extends / is meaningfully longer than
427
- // the recorded one → the recorded terminal was the truncated pre-emption; supersede it.
428
- if (!terminalSummary) return true;
429
- if (eventSummary.startsWith(terminalSummary)) return true;
430
- return eventSummary.length > terminalSummary.length + 32;
431
- }
432
-
433
- // The latest still-active direct-dispatch taskId for a session, resolved BEFORE the
434
- // completion flips the dispatch row terminal. Direct dispatches (mesh_send_task) have no
435
- // work-queue row, so this is the only taskId available to attribute the terminal ledger
436
- // entry (and thus mesh task-stats) to — without it the terminal carries no taskId and the
437
- // task surfaces as status='unknown' / terminalKind=null in computeMeshTaskStats.
438
- function resolveActiveDirectDispatchTaskId(meshId: string, sessionId: string): string | undefined {
439
- try {
440
- const matches = getActiveDirectDispatches(meshId).filter(d => d.sessionId === sessionId);
441
- if (!matches.length) return undefined;
442
- // getActiveDirectDispatches returns rows ordered by dispatched_at ASC; the last is
443
- // the most recent dispatch (the re-dispatch / nudge whose completion this is).
444
- return readNonEmptyString(matches[matches.length - 1].taskId) || undefined;
445
- } catch {
446
- return undefined;
447
- }
448
- }
449
-
450
- // ---------------------------------------------------------------------------
451
- // Queue assignment
452
- // ---------------------------------------------------------------------------
453
-
454
- // Per-dispatch confirmation timeout (Bug B). A dispatch promise that never settles —
455
- // a saturated remote P2P relay that hangs, or a transport that resolves only after
456
- // the worker acks — would otherwise leave the just-claimed queue row 'assigned' with
457
- // its delivery stuck 'delivering' forever: the .catch that requeues never fires, and
458
- // PHASE 3 reconcile skips the row (it counts 0 pending). Racing the dispatch against
459
- // this timeout guarantees a hung dispatch deterministically returns the task to
460
- // 'pending' for re-dispatch. Generous so a merely-slow-but-live dispatch (a cold
461
- // remote relay) is never reclaimed early; the reconcile assigned-stranded watchdog is
462
- // the durable cross-restart backstop for a timer lost to a daemon restart.
463
- const DISPATCH_CONFIRM_TIMEOUT_MS = 120_000;
464
-
465
- // Cold-open connect budget for the warmup-aware REMOTE task dispatch deadline. A
466
- // remote `agent_command` to a peer whose mesh DataChannel is not open yet first has
467
- // to drive the cross-machine (often TURN-relayed) handshake; charging that warmup
468
- // against the response budget is the same cold-open false-timeout the git_status
469
- // probe path already guards against. This budget bounds ONLY the "channel not open
470
- // yet" phase; once the channel is warm the DISPATCH_CONFIRM_TIMEOUT_MS response
471
- // budget governs (identical to the legacy flat guard for an already-open peer, so
472
- // no latency is added to a normal dispatch). Matches the daemon-cloud
473
- // DaemonMeshManager CONNECT_TIMEOUT_MS (45s) so the caller-side deadline tracks the
474
- // transport's own cold-open window rather than guessing.
475
- const DISPATCH_CONNECT_TIMEOUT_MS = 45_000;
476
-
477
- // Fail-loud (throttled) trace for a remote dispatch that ran with NO live mesh
478
- // connection getter wired — the same degraded-warmup misconfiguration the git probe
479
- // path warns about. Warn once per peer; resolveWarmupDeadlineOpts then falls back to
480
- // the conservative combined budget instead of silently assuming "always warm".
481
- const dispatchWarmupGetterMissingWarned = new Set<string>();
482
- function warnDispatchWarmupGetterMissingOnce(daemonId: string): void {
483
- if (dispatchWarmupGetterMissingWarned.has(daemonId)) return;
484
- dispatchWarmupGetterMissingWarned.add(daemonId);
485
- 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.`);
486
- }
487
-
488
- interface DeliverTaskContext {
489
- meshId: string;
490
- nodeId: string;
491
- sessionId: string;
492
- providerType: string;
493
- task: MeshWorkQueueEntry;
494
- transport: 'remote' | 'local';
495
- sourceCoordinatorSessionId?: string;
496
- sourceCoordinatorDaemonId?: string;
497
- }
498
-
499
- // CONS scope 3: the SINGLE source of truth for dispatching a claimed task to its
500
- // session. The remote (P2P dispatchMeshCommand) and local (cliManager.handleCliCommand)
501
- // branches differ ONLY in the transport call — the delivery record, the delivered/failed
502
- // transitions, the pending-requeue-on-failure, the dispatch_failed ledger entry, AND the
503
- // Bug B hang timeout are identical and live here once so a future change to the dispatch
504
- // lifecycle cannot drift between the two paths. The caller passes a `dispatchThunk` that
505
- // performs only the transport-specific send and returns its promise.
506
- //
507
- // Cold-open warmup (remote only): the REMOTE transport speaks over a P2P
508
- // DataChannel that may still be opening when the first task is dispatched to a peer.
509
- // When `warmup` is supplied the dispatch is awaited under the warmup-aware deadline
510
- // (mesh-warmup-deadline) — the cold-open handshake is charged to the connect budget
511
- // and only the warm round trip to the DISPATCH_CONFIRM_TIMEOUT_MS response budget —
512
- // so the very first dispatch to a not-yet-open peer is no longer false-timed at the
513
- // combined window. An already-open peer behaves identically to the legacy flat guard
514
- // (response budget governs from t0), so a normal dispatch sees no added latency. The
515
- // LOCAL transport (in-process cliManager) has no channel to warm up and keeps the
516
- // flat Bug B hang guard.
517
- function deliverTaskToSession(
518
- dispatchThunk: () => Promise<unknown>,
519
- ctx: DeliverTaskContext,
520
- warmup?: { daemonId: string; getConnection?: (daemonId: string) => Record<string, unknown> | null },
521
- ): void {
522
- const delivery = createSessionDelivery({
523
- meshId: ctx.meshId,
524
- nodeId: ctx.nodeId,
525
- sessionId: ctx.sessionId,
526
- providerType: ctx.providerType,
527
- taskId: ctx.task.id,
528
- kind: 'task',
529
- message: ctx.task.message,
530
- status: 'delivering',
531
- ...(ctx.sourceCoordinatorSessionId ? { sourceCoordinatorSessionId: ctx.sourceCoordinatorSessionId } : {}),
532
- ...(ctx.sourceCoordinatorDaemonId ? { sourceCoordinatorDaemonId: ctx.sourceCoordinatorDaemonId } : {}),
533
- });
534
-
535
- // Invoke the transport synchronously (preserves the prior fire-and-forget timing,
536
- // and lets a synchronous throw fall into the same failure path as a rejection).
537
- let dispatchPromise: Promise<unknown>;
538
- try {
539
- dispatchPromise = Promise.resolve(dispatchThunk());
540
- } catch (e) {
541
- dispatchPromise = Promise.reject(e);
542
- }
543
-
544
- let timer: ReturnType<typeof setTimeout> | undefined;
545
- let guarded: Promise<unknown>;
546
- if (warmup) {
547
- // Remote P2P: cold-open-aware deadline. awaitWithWarmupDeadline owns its own
548
- // timers (so `timer` stays undefined and the clearTimeout below is a no-op),
549
- // and rejects with Error('timeout') when either budget lapses — the same
550
- // retryable failure shape the catch below already handles (requeue + ledger).
551
- guarded = awaitWithWarmupDeadline(dispatchPromise, resolveWarmupDeadlineOpts({
552
- getConnection: warmup.getConnection,
553
- daemonId: warmup.daemonId,
554
- connectTimeoutMs: DISPATCH_CONNECT_TIMEOUT_MS,
555
- responseTimeoutMs: DISPATCH_CONFIRM_TIMEOUT_MS,
556
- onMissingGetter: warnDispatchWarmupGetterMissingOnce,
557
- }));
558
- } else {
559
- guarded = Promise.race([
560
- dispatchPromise,
561
- new Promise<never>((_, reject) => {
562
- timer = setTimeout(
563
- () => reject(new Error(`dispatch_confirm_timeout after ${DISPATCH_CONFIRM_TIMEOUT_MS}ms`)),
564
- DISPATCH_CONFIRM_TIMEOUT_MS,
565
- );
566
- // Never keep the process alive solely for this confirm-timeout timer.
567
- if (typeof (timer as { unref?: () => void })?.unref === 'function') (timer as { unref: () => void }).unref();
568
- }),
569
- ]);
570
- }
571
-
572
- guarded.then(() => {
573
- if (timer) clearTimeout(timer);
574
- updateSessionDeliveryStatus(delivery.id, 'delivered');
575
- }).catch((e: any) => {
576
- if (timer) clearTimeout(timer);
577
- // A dispatch failure (transport reject OR hang timeout) is most often transient —
578
- // a busy/refusing adapter, or a relay that never acked — not a permanent task
579
- // failure. Marking the task terminal here would permanently kill tasks a later
580
- // tick delivers fine. Return it to 'pending' and record a retryable dispatch_failed
581
- // ledger entry so the reconcile loop re-dispatches it. Identical for both transports.
582
- LOG.error('MeshQueue', `Failed to dispatch task via ${ctx.transport} to node ${ctx.nodeId}: ${e?.message}`);
583
- updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
584
- updateTaskStatus(ctx.meshId, ctx.task.id, 'pending');
585
- try {
586
- appendLedgerEntry(ctx.meshId, {
587
- kind: 'dispatch_failed' as any,
588
- nodeId: ctx.nodeId,
589
- sessionId: ctx.sessionId,
590
- payload: { taskId: ctx.task.id, deliveryId: delivery.id, error: e?.message, retryable: true, transport: ctx.transport },
591
- });
592
- } catch { /* ledger write is best-effort */ }
593
- });
594
- }
595
-
596
- // WTCLAIM: workspace normalization for base-vs-worktree comparison now lives in
597
- // @adhdev/mesh-shared (normalizeMeshWorkspaceForCompare) so the enqueue→claim path,
598
- // the mesh_status per-node session filter, and the read_chat node scope guard all
599
- // share one comparison rule instead of drifting module-private copies.
600
-
601
- export function tryAssignQueueTask(
602
- components: DaemonComponents,
603
- meshId: string,
604
- nodeId: string,
605
- sessionId: string,
606
- providerType: string
607
- ): boolean {
608
- const mesh = getMeshWithCache(components, meshId);
609
- const node = mesh?.nodes.find((n: any) => readMeshNodeId(n) === nodeId);
610
-
611
- // WTCLAIM (fix-B extended to the enqueue→claim path): a base-targeted task must never be
612
- // claimed by — and dispatched into — a co-located worktree-clone session, nor vice versa.
613
- // The drain candidate's nodeId is derived from settings.meshNodeId || settings.nodeId
614
- // (triggerMeshQueue), so a worktree session whose meshNodeId is empty/stale falls back to
615
- // settings.nodeId = the BASE node id and impersonates the base node here. fix-B's worker-side
616
- // workspace scope only ran for sessionless dispatch (meshScopeNodeId && !targetSessionId); the
617
- // claim path ALWAYS carries a targetSessionId, so it never engaged. Apply the same scope here:
618
- // for a LOCAL claiming session (adapter resolvable on this daemon), require its actual
619
- // workingDir to match the target node's declared workspace. On a confirmed mismatch, refuse the
620
- // claim so the task returns to pending for the correctly-scoped session/node to pull. Scoped to
621
- // local sessions where the workspace is verifiable — a remote session lives on another daemon
622
- // whose paths we cannot compare here (and remote candidates are already nodeId-matched from
623
- // getRemoteIdleSessions). Conservative by design: when either workspace is unknown we do NOT
624
- // skip, so a node with no declared workspace keeps its prior behavior and no legitimate claim
625
- // is starved.
626
- // WTDISPATCH (residual of WTCLAIM): the cross-node claim guard must reach EVERY claiming
627
- // session this daemon can observe — not only those whose adapter happens to be in
628
- // cliManager.adapters. An auto-launched worker session can carry its node binding on the
629
- // CLI-instance settings while its session-host record shows no_node_binding, and the
630
- // event-driven / remote-idle drain (agent:ready → setRemoteIdleSession → tryAssignQueueTask)
631
- // can pass a nodeId that does NOT belong to the claiming session — a sibling worktree node
632
- // on the SAME daemon. The adapter-only WTCLAIM check (rc.361/4c5b30b1) never engaged for a
633
- // session observed solely via instanceManager, so session A could pull node B's task and
634
- // node A's task was left with no session to claim it (no task_dispatched — it never dispatches).
635
- //
636
- // Resolve the claiming session's REAL identity from the adapter workingDir, then fall back to
637
- // the live CLI instance's workspace + its stamped meshNodeId, and refuse a claim that
638
- // contradicts EITHER (fail-closed). Reuses the shared meshWorkspacesEquivalent / meshNodeIdMatches
639
- // comparators — no new comparison logic. Conservative: when neither the workspace NOR the stamp
640
- // is resolvable we do NOT refuse, so a node with no declared workspace keeps prior behavior and
641
- // a genuinely remote (cross-daemon) candidate stays nodeId-matched from getRemoteIdleSessions.
642
- const localClaimAdapter = components.cliManager?.adapters?.get(sessionId) as { workingDir?: string } | undefined;
643
- let claimInstanceWorkspace = '';
644
- let claimStampedNodeId = '';
645
- try {
646
- const claimState = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
647
- claimInstanceWorkspace = readNonEmptyString(claimState?.workspace);
648
- const claimSettings = (claimState?.settings as Record<string, unknown>) || {};
649
- claimStampedNodeId = readNonEmptyString(claimSettings.meshNodeId);
650
- } catch { /* best-effort — fall through to the conservative (no refuse) path */ }
651
-
652
- const nodeWorkspaceRaw = readNonEmptyString(node?.workspace);
653
- const sessionWorkspaceRaw = readNonEmptyString(localClaimAdapter?.workingDir) || claimInstanceWorkspace;
654
-
655
- if (claimStampedNodeId && nodeId) {
656
- // The session carries its OWN meshNodeId stamp — its authoritative node identity, set when
657
- // the coordinator launched/dispatched it (mesh-routing trusts this stamp FIRST). When it
658
- // matches the claim target the session genuinely belongs to this node, so the stamp settles
659
- // it and the workspace heuristic is skipped (a base/worktree pair can legitimately share a
660
- // workspace). When it does NOT match, the claim is a cross-node leak — refuse, fail-closed.
661
- if (!meshNodeIdMatches({ id: claimStampedNodeId } as MeshNodeIdentified, nodeId)) {
662
- LOG.info('MeshQueue', `WTDISPATCH: refusing claim for node ${nodeId} (${sessionId}) — session is bound to node "${claimStampedNodeId}" (cross-node claim blocked)`);
663
- return false;
664
- }
665
- } else if (sessionWorkspaceRaw && nodeWorkspaceRaw && !meshWorkspacesEquivalent(sessionWorkspaceRaw, nodeWorkspaceRaw)) {
666
- // No stamp (the no_node_binding worker) — fall back to the workspace to tell two co-located
667
- // sibling worktree sessions apart. WTCLAIM, now reaching instanceManager-observable sessions
668
- // too. Conservative: unknown workspace on either side → do NOT refuse (no legitimate claim
669
- // starved; a genuinely remote cross-daemon candidate stays nodeId-matched as before).
670
- LOG.info('MeshQueue', `WTCLAIM: refusing claim for node ${nodeId} (${sessionId}) — session workspace "${normalizeMeshWorkspaceForCompare(sessionWorkspaceRaw)}" ≠ node workspace "${normalizeMeshWorkspaceForCompare(nodeWorkspaceRaw)}" (cross-workspace dispatch blocked)`);
671
- return false;
672
- }
673
-
674
- const capabilityTags = buildMeshNodeCapabilityTags(node, providerType);
675
- // Per-(node, provider) maxParallel cap (RepoMeshNodePolicy.providerRoles) layers
676
- // on top of the global/taskMode caps — stricter wins. Resolved here where the
677
- // claiming session's providerType + node policy are both known, then enforced
678
- // inside the atomic claim transaction so concurrent claims can't overshoot it.
679
- const providerMaxParallel = resolveProviderMaxParallel(node?.policy, providerType);
680
- // WTDISPATCH-FANOUT: tell the atomic claim whether the claiming node is a worktree
681
- // clone so a `convergence` task (base-only: merge → push → cleanup) is refused for
682
- // worktree sessions. Without it, every sibling worktree session on this daemon could
683
- // claim the same convergence intent and race push/production-deploy (the 4-way fan-out).
684
- const nodeIsWorktree = node?.isLocalWorktree === true;
685
- const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags, {
686
- providerType,
687
- ...(providerMaxParallel !== undefined ? { providerMaxParallel } : {}),
688
- nodeIsWorktree,
689
- });
690
- if (!task) {
691
- return false;
692
- }
693
-
694
- const terminal = findTerminalLedgerEvidenceForTask({
695
- meshId,
696
- taskId: task.id,
697
- });
698
- if (terminal) {
699
- const status = terminal.kind === 'task_completed' ? 'completed' : 'failed';
700
- updateTaskStatus(meshId, task.id, status);
701
- LOG.info('MeshQueue', `Skipped dispatch for terminal task ${task.id} on mesh ${meshId}; ${terminal.kind} ledger evidence already exists`);
702
- traceMeshEventDrop('dispatch_terminal_ledger', {
703
- taskId: task.id,
704
- sessionId,
705
- nodeId,
706
- meshId,
707
- event: 'agent_command',
708
- }, terminal.kind);
709
- return false;
710
- }
711
-
712
- LOG.info('MeshQueue', `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
713
-
714
- if (node?.daemonId && components.dispatchMeshCommand) {
715
- const isLocalNode = components.cliManager.adapters.has(sessionId);
716
- if (!isLocalNode) {
717
- const localDaemonIdForDispatch = readNonEmptyString(loadConfig().machineId) || undefined;
718
- // (3) Originating coordinator session that enqueued this task — route its
719
- // completion back to that exact session (multi-coordinator). Carried over P2P
720
- // to the remote worker, which echoes it on its completion event.
721
- const sourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId) || undefined;
722
- const dispatchMeshCommand = components.dispatchMeshCommand;
723
- const remoteDaemonId = node.daemonId;
724
- // CONS3: only the transport call differs — everything else (delivery record,
725
- // status transitions, requeue-on-failure, ledger, Bug B hang timeout) is in
726
- // the shared deliverTaskToSession helper.
727
- deliverTaskToSession(
728
- () => dispatchMeshCommand(remoteDaemonId, 'agent_command', {
729
- targetSessionId: sessionId,
730
- cliType: providerType,
731
- action: 'send_chat',
732
- message: task.message,
733
- meshContext: {
734
- meshId,
735
- nodeId,
736
- taskId: task.id,
737
- ...(localDaemonIdForDispatch ? { coordinatorDaemonId: localDaemonIdForDispatch } : {}),
738
- ...(sourceCoordinatorSessionId ? { coordinatorSessionId: sourceCoordinatorSessionId } : {}),
739
- },
740
- }),
741
- {
742
- meshId,
743
- nodeId,
744
- sessionId,
745
- providerType,
746
- task,
747
- transport: 'remote',
748
- ...(sourceCoordinatorSessionId ? { sourceCoordinatorSessionId } : {}),
749
- ...(localDaemonIdForDispatch ? { sourceCoordinatorDaemonId: localDaemonIdForDispatch } : {}),
750
- },
751
- // Warmup-aware deadline: this dispatch can be the FIRST command to a
752
- // peer whose mesh DataChannel is still opening — charge the cold-open
753
- // handshake to the connect budget, not the response budget.
754
- { daemonId: remoteDaemonId, getConnection: components.getMeshPeerConnectionStatus },
755
- );
756
- return true;
757
- }
758
- }
759
-
760
- // Stamp mesh context onto the session so completion events route correctly
761
- // via setupMeshEventForwarding. Without this, manually-opened idle sessions
762
- // (mesh_launch_session without auto-launch) lack meshNodeFor/meshNodeId and
763
- // agent:generating_completed is silently dropped as isMeshDelegate=false.
764
- try {
765
- const inst = components.instanceManager.getInstance(sessionId);
766
- if (inst && typeof inst.updateSettings === 'function') {
767
- // Adopting a (possibly manually-opened) local session as a worker: apply the
768
- // delegated-worker auto-approve policy here too, so a session that was launched
769
- // without autoApprove still auto-approves once the coordinator dispatches a task
770
- // to it (the "approval notification fires only for certain delegated sessions"
771
- // case). updateSettings preserves runtime mesh keys; passing autoApprove keeps it.
772
- //
773
- // This local-dispatch branch also runs on the coordinator daemon for a co-located
774
- // session, so the coordinator daemon id IS this daemon's id. Stamp it alongside
775
- // the node identity so the session is fully relay-safe (meshCoordinatorDaemonId is
776
- // the anchor the forwarder keys on), matching what mesh_launch_session stamps.
777
- const localDaemonId = readNonEmptyString(loadConfig().machineId);
778
- const localSourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId);
779
- inst.updateSettings({
780
- meshNodeFor: meshId,
781
- meshNodeId: nodeId,
782
- launchedByCoordinator: true,
783
- autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
784
- ...(localDaemonId ? { meshCoordinatorDaemonId: localDaemonId } : {}),
785
- // (3) Stamp the originating coordinator session for session-anchored routing
786
- // of this co-located worker's completion. Absent → daemon-level fallback.
787
- ...(localSourceCoordinatorSessionId ? { meshCoordinatorSessionId: localSourceCoordinatorSessionId } : {}),
788
- });
789
- }
790
- } catch { /* best-effort — dispatch still proceeds */ }
791
-
792
- // CONS3: same shared dispatch lifecycle as the remote branch — only the transport
793
- // (cliManager.handleCliCommand) differs.
794
- deliverTaskToSession(
795
- () => components.cliManager.handleCliCommand('agent_command', {
796
- targetSessionId: sessionId,
797
- cliType: providerType,
798
- action: 'send_chat',
799
- message: task.message,
800
- }),
801
- {
802
- meshId,
803
- nodeId,
804
- sessionId,
805
- providerType,
806
- task,
807
- transport: 'local',
808
- ...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { sourceCoordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
809
- ...(readNonEmptyString(loadConfig().machineId) ? { sourceCoordinatorDaemonId: readNonEmptyString(loadConfig().machineId) } : {}),
810
- },
811
- );
812
-
813
- return true;
814
- }
815
-
816
- const autoLaunchInProgress = new Set<string>();
817
- const autoLaunchCooldownUntil = new Map<string, number>();
818
- const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
819
- // A remote auto-launch (launch_cli forward) is fire-and-async: the worker session
820
- // spawns, reaches idle, emits agent:ready, that ready is queued on the worker, pulled
821
- // by this coordinator (reconcile PHASE 1), and only THEN claims the task. That round
822
- // trip routinely exceeds the 5s per-(mesh,node) cooldown, so cooldown alone lets the
823
- // reconcile loop fire a SECOND launch for the same still-pending task before the first
824
- // session's claim lands — every tick spawns yet another orphan session (observed live:
825
- // 26 sessions for one task). This is a per-TASK await-claim window: once a task has a
826
- // successfully-launched session whose claim we are still waiting on, do not launch it
827
- // again until the window lapses. It is generous (a slow remote spawn can take tens of
828
- // seconds) but bounded so a launch that silently never reaches idle is eventually retried.
829
- const AUTO_LAUNCH_AWAIT_CLAIM_MS = 90_000;
830
-
831
- // De-dup for repeated `skipped` ledger noise: the reconcile loop re-runs the queue
832
- // trigger every 4s, so a task that can't be claimed (e.g. a remote node with no
833
- // transport, or a node under cooldown) would otherwise append an identical
834
- // session_auto_launch{phase:'skipped'} entry on every tick — flooding the ledger.
835
- // We suppress a `skipped` ledger append when the immediately-prior recorded event
836
- // for that task was the SAME (phase, reason). Any non-skip phase (started/failed/
837
- // completed) or a changed reason resets the de-dup so real transitions still record.
838
- const lastAutoLaunchLedgerKey = new Map<string, string>();
839
- const AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2000;
840
-
841
- function sweepExpiredCooldowns(): void {
842
- const now = Date.now();
843
- for (const [key, until] of autoLaunchCooldownUntil) {
844
- if (now >= until) autoLaunchCooldownUntil.delete(key);
845
- }
846
- }
847
-
848
- function normalizeProviderPriority(policy: unknown): string[] {
849
- const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
850
- ? (policy as Record<string, unknown>).providerPriority
851
- : undefined;
852
- if (!Array.isArray(raw)) return [];
853
- const seen = new Set<string>();
854
- return raw
855
- .map(type => typeof type === 'string' ? type.trim() : '')
856
- .filter(Boolean)
857
- .filter(type => {
858
- if (seen.has(type)) return false;
859
- seen.add(type);
860
- return true;
861
- });
862
- }
863
-
864
- function isTerminalSessionStatus(status: string): boolean {
865
- return ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(status);
866
- }
867
-
868
- function isIdleSessionState(state: any): boolean {
869
- const status = readNonEmptyString(state?.status).toLowerCase();
870
- if (isTerminalSessionStatus(status)) return false;
871
- return status === 'idle' || state?.activeChat?.status === 'waiting_input';
872
- }
873
-
874
- function isDirtyNode(node: any): boolean {
875
- return node?.health === 'dirty' || node?.git?.dirty === true;
876
- }
877
-
878
- function resolveAutoFastForwardPolicy(mesh: any): { enabled: boolean; maxBehind?: number; requireCleanSubmodules: boolean } {
879
- const record = mesh?.policy?.autoFastForward && typeof mesh.policy.autoFastForward === 'object' && !Array.isArray(mesh.policy.autoFastForward)
880
- ? mesh.policy.autoFastForward as Record<string, unknown>
881
- : {};
882
- const maxBehind = Number(record.maxBehind);
883
- return {
884
- enabled: record.enabled !== false,
885
- ...(Number.isFinite(maxBehind) && maxBehind >= 0 ? { maxBehind: Math.floor(maxBehind) } : {}),
886
- requireCleanSubmodules: record.requireCleanSubmodules !== false,
887
- };
888
- }
889
-
890
- function sessionStateLooksActive(state: any): boolean {
891
- const status = readNonEmptyString(state?.status).toLowerCase();
892
- const chatStatus = readNonEmptyString(state?.activeChat?.status).toLowerCase();
893
- // 'long_generating' is retained as a legacy alias for the renamed 'no_progress' busy status.
894
- const active = new Set(['generating', 'streaming', 'no_progress', 'long_generating', 'working', 'starting', 'waiting_approval']);
895
- return active.has(status) || active.has(chatStatus);
896
- }
897
-
898
- function nodeHasActiveMeshWork(components: DaemonComponents, meshId: string, nodeId: string, currentSessionId?: string): boolean {
899
- if (nodeHasActiveAssignment(meshId, nodeId)) return true;
900
- return components.instanceManager.getByCategory('cli').some((inst: any) => {
901
- const state = inst.getState();
902
- const settings = state.settings as Record<string, unknown> || {};
903
- if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
904
- const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
905
- if (instNodeId !== nodeId) return false;
906
- const sessionId = readNonEmptyString(state.instanceId);
907
- if (currentSessionId && sessionId === currentSessionId && isIdleSessionState(state)) return false;
908
- return sessionStateLooksActive(state);
909
- });
910
- }
911
-
912
- function isLaunchableNode(node: any): boolean {
913
- if (!node || node.status === 'disabled' || node.status === 'removed') return false;
914
- const health = readNonEmptyString(node.health).toLowerCase();
915
- if (!health) return true;
916
- return health === 'online' || health === 'unknown';
917
- }
918
-
919
- /** Whether a mesh node's daemon/machine identity resolves to THIS coordinator daemon
920
- * (i.e. the queue session can be spawned by a direct local `launch_cli`). */
921
- function isLocalAutoLaunchNode(node: any): boolean {
922
- const daemonId = readNonEmptyString(node?.daemonId);
923
- const machineId = readNonEmptyString(node?.machineId);
924
- const appConfig = loadConfig();
925
- const localMachineId = readNonEmptyString(appConfig.machineId) || readNonEmptyString(appConfig.registeredMachineId);
926
-
927
- // Route through the canonical daemon-id equivalence helper so a node carrying the
928
- // bare `mach_<hex>` form (not just the reassembled `daemon_`/`standalone_` prefixed
929
- // forms) resolves to THIS coordinator instead of being misjudged as remote.
930
- const daemonMatchesLocal = !daemonId || daemonIdsEquivalent(daemonId, localMachineId);
931
- const machineMatchesLocal = !machineId || (!!localMachineId && machineId === localMachineId);
932
-
933
- if (node?.isLocalWorktree === true) {
934
- return daemonMatchesLocal && machineMatchesLocal;
935
- }
936
- if (daemonId || machineId) {
937
- return daemonMatchesLocal && machineMatchesLocal;
938
- }
939
- return true;
940
- }
941
-
942
- /**
943
- * Resolve how a pending queue task should be auto-launched onto a node.
944
- *
945
- * - `local`: spawn directly on this daemon via cliManager.handleCliCommand('launch_cli').
946
- * - `remote`: forward `launch_cli` to the node's daemon via dispatchMeshCommand
947
- * (mirrors what mesh_launch_session does). Requires dispatchMeshCommand AND a
948
- * resolvable coordinator daemonId for relay-safe completion routing.
949
- * - `skip`: not launchable from here — carries the reason (e.g. a remote node with
950
- * no dispatch transport, or no coordinator daemonId to stamp).
951
- */
952
- function resolveAutoLaunchTarget(components: DaemonComponents, node: any): {
953
- mode: 'local' | 'remote' | 'skip';
954
- reason?: string;
955
- daemonId?: string;
956
- coordinatorDaemonId?: string;
957
- } {
958
- if (isLocalAutoLaunchNode(node)) return { mode: 'local' };
959
-
960
- // Remote node. Forwarding the launch is possible only with a dispatch transport
961
- // (cloud mode) plus a coordinator daemonId to stamp into the worker so completion
962
- // events route back here. Without either, fall back to a graceful skip.
963
- const daemonId = readNonEmptyString(node?.daemonId);
964
- if (!daemonId) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
965
- if (!components.dispatchMeshCommand) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
966
- const coordinatorDaemonId = readNonEmptyString(loadConfig().machineId);
967
- if (!coordinatorDaemonId) return { mode: 'skip', reason: 'remote_auto_launch_no_coordinator_daemon_id' };
968
- return { mode: 'remote', daemonId, coordinatorDaemonId };
969
- }
970
-
971
- function activeAssignedCount(meshId: string): number {
972
- return getQueue(meshId, { status: ['assigned'] as any }).length;
973
- }
974
-
975
- /** Active assignments that hold the one-active-per-node / global-parallel invariant
976
- * (everything except read-only diagnoses, which run unbounded by the write cap). */
977
- export function activeWriteAssignedCount(meshId: string): number {
978
- return getQueue(meshId, { status: ['assigned'] as any })
979
- .filter(task => task.taskMode !== 'live_debug_readonly').length;
980
- }
981
-
982
- /** Active read-only (live_debug_readonly) assignments, for the read-only safety cap. */
983
- export function activeReadonlyAssignedCount(meshId: string): number {
984
- return getQueue(meshId, { status: ['assigned'] as any })
985
- .filter(task => task.taskMode === 'live_debug_readonly').length;
986
- }
987
-
988
- function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
989
- return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedNodeId === nodeId);
990
- }
991
-
992
- /** Active (status='assigned') task count for a node — the load metric for
993
- * least-loaded / round-robin ranking. Lower = preferred. */
994
- function nodeActiveLoad(meshId: string, nodeId: string): number {
995
- return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
996
- }
997
-
998
- /**
999
- * The mesh-wide scheduling strategy. Defaults to 'first_eligible' (strict
1000
- * no-change) for any mesh that does not set it. Only governs the final tie-break;
1001
- * eligibility, capacity, and priority gates apply identically to every strategy.
1002
- */
1003
- function resolveSchedulingStrategy(mesh: any): RepoMeshSchedulingStrategy {
1004
- return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
1005
- }
1006
-
1007
- /**
1008
- * Order eligible nodes for assignment per the mesh scheduling pipeline:
1009
- * PRIORITY (schedulingPriority desc) → TIE-BREAK (strategy).
1010
- *
1011
- * The caller has already applied the TAG hard-filter and is responsible for the
1012
- * MAX-ALLOC capacity gate (the per-node launch/claim checks). This function only
1013
- * decides the *preference order* among nodes that are otherwise eligible.
1014
- *
1015
- * - 'first_eligible' (default): returns the input order verbatim and does NOT touch
1016
- * the round-robin cursor — byte-for-byte the pre-feature behavior.
1017
- * - 'priority_only': schedulingPriority desc, then input order (load ignored).
1018
- * - 'least_loaded': schedulingPriority desc, then active load asc, then input order.
1019
- * - 'round_robin': same as least_loaded, but among nodes tied at (priority, load)
1020
- * the input order is rotated by a per-mesh cursor that advances once per pass.
1021
- *
1022
- * `nodes` carries the original config/array index so the tie-break can fall back to
1023
- * deterministic input order. `bumpCursor` advances the round-robin cursor exactly
1024
- * once per scheduling pass (only consulted for 'round_robin').
1025
- */
1026
- interface RankableNode { nodeId: string; node: any; index: number }
1027
-
1028
- /** Test-only: the pure node-ordering stage (PRIORITY → TIE-BREAK). Exposed so the
1029
- * scheduling pipeline can be unit-tested without standing up live CLI sessions. */
1030
- export function __orderEligibleNodesForTests(
1031
- meshId: string,
1032
- strategy: RepoMeshSchedulingStrategy,
1033
- nodes: RankableNode[],
1034
- opts?: { bumpCursor?: boolean },
1035
- ): RankableNode[] {
1036
- return orderEligibleNodes(meshId, strategy, nodes, opts);
1037
- }
1038
-
1039
- function orderEligibleNodes(
1040
- meshId: string,
1041
- strategy: RepoMeshSchedulingStrategy,
1042
- nodes: RankableNode[],
1043
- opts?: { bumpCursor?: boolean },
1044
- ): RankableNode[] {
1045
- if (strategy === 'first_eligible' || nodes.length <= 1) {
1046
- return nodes;
1047
- }
1048
-
1049
- const priorityOf = (n: { node: any }) => resolveNodeSchedulingPriority(n.node?.policy);
1050
-
1051
- // Round-robin rotation offset: rotate the deterministic input order by a
1052
- // per-mesh cursor so the tie-break winner among equal (priority, load) nodes
1053
- // cycles across passes. The cursor advances once per scheduling pass.
1054
- let rotation = 0;
1055
- if (strategy === 'round_robin') {
1056
- const cursor = opts?.bumpCursor
1057
- ? MeshRuntimeStore.getInstance().bumpSchedulerCursor(meshId)
1058
- : MeshRuntimeStore.getInstance().getSchedulerCursor(meshId);
1059
- rotation = ((cursor % nodes.length) + nodes.length) % nodes.length;
1060
- }
1061
-
1062
- // Rotation rank: position of each node after rotating input order by `rotation`.
1063
- // For non-round-robin strategies rotation is 0, so this is just the input index.
1064
- const rotationRank = (index: number) => (index - rotation + nodes.length) % nodes.length;
1065
-
1066
- return [...nodes].sort((a, b) => {
1067
- const prioDelta = priorityOf(b) - priorityOf(a); // higher priority first
1068
- if (prioDelta !== 0) return prioDelta;
1069
- if (strategy === 'least_loaded' || strategy === 'round_robin') {
1070
- const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
1071
- if (loadDelta !== 0) return loadDelta;
1072
- }
1073
- return rotationRank(a.index) - rotationRank(b.index);
1074
- });
1075
- }
1076
-
1077
- /** Active assignments on a (node, provider) — pre-launch guard for the per-(node,
1078
- * provider) maxParallel cap. The authoritative enforcement is in the claim
1079
- * transaction; this only avoids spawning a session that would fail the claim. */
1080
- function activeProviderAssignedCount(meshId: string, nodeId: string, providerType: string): number {
1081
- return getQueue(meshId, { status: ['assigned'] as any })
1082
- .filter(task => task.assignedNodeId === nodeId && task.assignedProviderType === providerType).length;
1083
- }
1084
-
1085
- function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
1086
- if (getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedSessionId === sessionId)) {
1087
- return true;
1088
- }
1089
- // Direct dispatches (mesh_send_task) are tracked in mesh_direct_dispatches, not the
1090
- // work queue. A session completing a still-active direct dispatch IS an active
1091
- // assignment — without this, findRecentTerminalLedgerEvidence dedup wrongly suppresses
1092
- // the canonical agent:generating_completed for direct-dispatch tasks (validation/general),
1093
- // so the coordinator polling get_pending_mesh_events never observes task_completed and the
1094
- // session goes silently idle. This check runs before markSessionTerminal marks the
1095
- // dispatch terminal, so the in-flight dispatch is still observable here.
1096
- try {
1097
- if (getActiveDirectDispatches(meshId).some(d => d.sessionId === sessionId)) return true;
1098
- if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
1099
- } catch { /* best-effort — fall through to false */ }
1100
- return false;
1101
- }
1102
-
1103
- function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
1104
- return components.instanceManager.getByCategory('cli').filter((inst: any) => {
1105
- const state = inst.getState();
1106
- const settings = state.settings as Record<string, unknown> || {};
1107
- if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
1108
- const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
1109
- if (instNodeId !== nodeId) return false;
1110
- const status = readNonEmptyString(state.status).toLowerCase();
1111
- return !isTerminalSessionStatus(status);
1112
- }).length;
1113
- }
1114
-
1115
- function recordAutoLaunchEvent(meshId: string, args: {
1116
- phase: 'skipped' | 'started' | 'failed' | 'completed';
1117
- taskId: string;
1118
- nodeId?: string;
1119
- providerType?: string;
1120
- sessionId?: string;
1121
- reason?: string;
1122
- error?: string;
1123
- }) {
1124
- // Suppress consecutive identical `skipped` entries for the same task (4s reconcile
1125
- // re-trigger noise). Non-skip phases and changed reasons always record and reset
1126
- // the de-dup so genuine state transitions remain visible in the ledger.
1127
- const dedupKey = `${meshId}:${args.taskId}`;
1128
- const currentSig = `${args.phase}|${args.reason || ''}`;
1129
- if (args.phase === 'skipped' && lastAutoLaunchLedgerKey.get(dedupKey) === currentSig) {
1130
- return;
1131
- }
1132
- lastAutoLaunchLedgerKey.set(dedupKey, currentSig);
1133
- if (lastAutoLaunchLedgerKey.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
1134
- // Bound memory: drop the oldest insertion (Map preserves insertion order).
1135
- const oldest = lastAutoLaunchLedgerKey.keys().next().value;
1136
- if (oldest !== undefined) lastAutoLaunchLedgerKey.delete(oldest);
1137
- }
1138
- try {
1139
- appendLedgerEntry(meshId, {
1140
- kind: 'session_auto_launch',
1141
- nodeId: args.nodeId,
1142
- sessionId: args.sessionId,
1143
- providerType: args.providerType,
1144
- payload: {
1145
- phase: args.phase,
1146
- taskId: args.taskId,
1147
- reason: args.reason,
1148
- error: args.error,
1149
- },
1150
- });
1151
- } catch (e: any) {
1152
- LOG.warn('MeshQueue', `Failed to record auto-launch ledger event: ${e?.message || e}`);
1153
- }
1154
- }
1155
-
1156
- function markAutoLaunch(meshId: string, taskId: string, args: {
1157
- status: 'skipped' | 'started' | 'failed' | 'completed';
1158
- reason?: string;
1159
- nodeId?: string;
1160
- providerType?: string;
1161
- sessionId?: string;
1162
- error?: string;
1163
- }) {
1164
- recordTaskAutoLaunch(meshId, taskId, {
1165
- status: args.status,
1166
- reason: args.reason || args.error,
1167
- nodeId: args.nodeId,
1168
- providerType: args.providerType,
1169
- sessionId: args.sessionId,
1170
- });
1171
- recordAutoLaunchEvent(meshId, {
1172
- phase: args.status,
1173
- taskId,
1174
- nodeId: args.nodeId,
1175
- providerType: args.providerType,
1176
- sessionId: args.sessionId,
1177
- reason: args.reason,
1178
- error: args.error,
1179
- });
1180
- }
1181
-
1182
- async function resolveUsableProvider(
1183
- components: DaemonComponents,
1184
- nodeId: string,
1185
- node: any,
1186
- requiredTags?: string[],
1187
- ): Promise<{ providerType?: string; reason?: string }> {
1188
- const providerPriority = normalizeProviderPriority(node?.policy);
1189
- if (!providerPriority.length) return { reason: 'missing_provider_priority' };
1190
- const providerLoader = components.providerLoader;
1191
- if (!providerLoader) return { reason: 'provider_loader_unavailable' };
1192
-
1193
- const failed: string[] = [];
1194
- for (const requestedType of providerPriority) {
1195
- const normalizedType = typeof providerLoader.resolveAlias === 'function'
1196
- ? providerLoader.resolveAlias(requestedType)
1197
- : requestedType;
1198
- // Skip providers that can't satisfy the task's requiredTags (e.g. provider=hermes-cli
1199
- // means only hermes-cli qualifies, not any other type in providerPriority).
1200
- if (requiredTags?.length && !nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, normalizedType))) {
1201
- failed.push(`${requestedType}: required_tags_mismatch`);
1202
- continue;
1203
- }
1204
- if (typeof providerLoader.isMachineProviderEnabled === 'function' && !providerLoader.isMachineProviderEnabled(normalizedType)) {
1205
- failed.push(`${requestedType}: disabled`);
1206
- continue;
1207
- }
1208
- let detected: any;
1209
- try {
1210
- detected = await detectCLI(normalizedType, providerLoader, { includeVersion: false });
1211
- } catch (e: any) {
1212
- failed.push(`${requestedType}: detect failed: ${e?.message || e}`);
1213
- continue;
1214
- }
1215
- if (typeof providerLoader.setCliDetectionResults === 'function') {
1216
- providerLoader.setCliDetectionResults([{
1217
- id: normalizedType,
1218
- installed: !!detected,
1219
- path: detected?.path,
1220
- }], false);
1221
- }
1222
- (components as any).onStatusChange?.();
1223
- if (detected) return { providerType: normalizedType };
1224
- failed.push(`${requestedType}: not detected`);
1225
- }
1226
- return { reason: `provider_priority_unusable: ${failed.join('; ') || nodeId}` };
1227
- }
1228
-
1229
- // Canonical mesh node-id normalization. A node may arrive from the local config
1230
- // form (`id`) or the inline-cache form (`nodeId`/`node_id`) — see
1231
- // readInlineMeshNodeId in commands/router.ts. Comparing only `node.id` against a
1232
- // task.targetNodeId silently drops inline-cached worktree nodes, leaving a
1233
- // target-routed task permanently pending with a misleading
1234
- // `no_node_satisfies_required_tags` skip.
1235
- function readMeshNodeId(node: any): string {
1236
- // Delegate to the shared 3-way (id / nodeId / node_id) normalizer so this
1237
- // and every other mesh node-id read agree on identity. Coalesce to '' to
1238
- // preserve the existing string return contract for callers that do
1239
- // `=== task.targetNodeId` / `if (!nodeId)`.
1240
- return normalizeMeshNodeId(node) ?? '';
1241
- }
1242
-
1243
- async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, meshId: string, mesh: any): Promise<boolean> {
1244
- const queue = getQueue(meshId);
1245
- const pending = queue.filter(task => task.status === 'pending');
1246
- if (!pending.length) return false;
1247
-
1248
- const maxParallelTasks = Math.max(1, Math.floor(Number(mesh?.policy?.maxParallelTasks) || 2));
1249
- // Read-only diagnoses carry no isolation/merge cost, so they are exempt from the
1250
- // write-task parallel cap. To prevent runaway auto-launch they get their own,
1251
- // higher safety cap (2x the write cap).
1252
- const maxReadonlyParallelTasks = Math.max(2, maxParallelTasks * 2);
1253
- for (const task of pending) {
1254
- const isReadonly = task.taskMode === 'live_debug_readonly';
1255
- if (isReadonly) {
1256
- if (activeReadonlyAssignedCount(meshId) >= maxReadonlyParallelTasks) {
1257
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_readonly_parallel_tasks_reached' });
1258
- continue;
1259
- }
1260
- } else if (activeWriteAssignedCount(meshId) >= maxParallelTasks) {
1261
- // Write tasks are capped; skip this one but keep scanning so a later
1262
- // read-only task in the queue can still launch under its own cap.
1263
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
1264
- continue;
1265
- }
1266
- if (task.targetSessionId) {
1267
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
1268
- continue;
1269
- }
1270
-
1271
- // Per-task await-claim guard. A prior auto-launch already spawned a session for
1272
- // this task and we are waiting for that session's idle→claim to land (remote
1273
- // claims arrive via the worker→coordinator agent:ready pull, which can lag well
1274
- // past the per-node cooldown). Re-launching now would spawn a duplicate orphan
1275
- // session that never gets work. The task leaves `pending` the instant the claim
1276
- // succeeds, so this guard only suppresses the in-flight window; if the launched
1277
- // session never reaches idle within the window, a later tick retries.
1278
- if (task.autoLaunch?.status === 'completed' && task.autoLaunch.sessionId) {
1279
- const launchedAtMs = Date.parse(task.autoLaunch.updatedAt);
1280
- if (Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS) {
1281
- // Record the skip in the ledger ONLY (dedup'd). Do NOT call markAutoLaunch
1282
- // here: recordTaskAutoLaunch overwrites task.autoLaunch wholesale, which would
1283
- // erase the very `completed` record (status + sessionId + updatedAt) this guard
1284
- // reads on the next tick, reopening the duplicate-launch hole it closes.
1285
- recordAutoLaunchEvent(meshId, { phase: 'skipped', taskId: task.id, reason: 'awaiting_launched_session_claim', nodeId: task.autoLaunch.nodeId, sessionId: task.autoLaunch.sessionId });
1286
- continue;
1287
- }
1288
- }
1289
-
1290
- const candidateNodes = Array.isArray(mesh?.nodes)
1291
- ? mesh.nodes.filter((node: any) => {
1292
- // Bug A: match the target pin with the shared 3-form (id / nodeId / node_id)
1293
- // normalizer, mirroring the remote-idle drain (meshNodeIdMatches at the
1294
- // getRemoteIdleSessions filter). A strict `readMeshNodeId(node) !== targetNodeId`
1295
- // dropped a target node whose identity arrived under a different form (a freshly
1296
- // mesh_clone_node'd worktree), emptying candidateNodes and mislabelling the skip.
1297
- if (task.targetNodeId && !meshNodeIdMatches(node, task.targetNodeId)) return false;
1298
- // WTDISPATCH-FANOUT: a convergence task is base-only (it merges/pushes onto
1299
- // base). Never auto-launch a worktree-clone session for it — that is the very
1300
- // fan-out the claim guard refuses, so spinning the session up would only waste
1301
- // a launch that can never claim. Mirrors claimNextQueueTask's convergence gate.
1302
- if (task.taskMode === 'convergence' && node?.isLocalWorktree === true) return false;
1303
- // Skip nodes that can never satisfy requiredTags regardless of which provider
1304
- // from providerPriority is selected. A node satisfies tags if at least one
1305
- // provider in its priority list would produce matching capability tags.
1306
- if (task.requiredTags?.length) {
1307
- const priorities = normalizeProviderPriority(node?.policy);
1308
- const providerCandidates = priorities.length ? priorities : [undefined as unknown as string];
1309
- return providerCandidates.some(p =>
1310
- nodeSatisfiesRequiredTags(task.requiredTags, buildMeshNodeCapabilityTags(node, p))
1311
- );
1312
- }
1313
- return true;
1314
- })
1315
- : [];
1316
- if (!candidateNodes.length) {
1317
- // Bug A: distinguish the two ways the candidate set empties. A task pinned to a
1318
- // targetNodeId whose node is absent from the mesh (or whose id arrived under a
1319
- // different form) is a ROUTING miss — report it as `target_node_id_unmatched`, not
1320
- // the hard-coded `no_node_satisfies_required_tags`, which mislabelled a 3-form
1321
- // node-id mismatch as a capability failure and sent diagnosis down the wrong path.
1322
- // Only fall back to the tag reason when no target pin is in play, or the pin DID
1323
- // match a node but its tags excluded it (a genuine capability miss).
1324
- const targetPinUnmatched = !!task.targetNodeId
1325
- && !(Array.isArray(mesh?.nodes) && mesh.nodes.some((n: any) => meshNodeIdMatches(n, task.targetNodeId)));
1326
- markAutoLaunch(meshId, task.id, {
1327
- status: 'skipped',
1328
- reason: targetPinUnmatched ? 'target_node_id_unmatched' : 'no_node_satisfies_required_tags',
1329
- nodeId: task.targetNodeId,
1330
- });
1331
- continue;
1332
- }
1333
-
1334
- // PRIORITY → TIE-BREAK: order the eligible (TAG-filtered) candidate nodes by
1335
- // the mesh scheduling strategy. 'first_eligible' (default) returns them in
1336
- // config/array order unchanged, so distribution is strictly opt-in. The
1337
- // per-node MAX-ALLOC capacity gate (nodeHasActiveAssignment, provider cap,
1338
- // maxConcurrentSessions) is still applied inside the loop below; this only
1339
- // chooses which eligible node is *tried first*.
1340
- const strategy = resolveSchedulingStrategy(mesh);
1341
- const orderedCandidateNodes = strategy === 'first_eligible'
1342
- ? candidateNodes
1343
- : orderEligibleNodes(
1344
- meshId,
1345
- strategy,
1346
- candidateNodes
1347
- .map((node: any, index: number) => ({ nodeId: readMeshNodeId(node), node, index }))
1348
- .filter((c: RankableNode) => c.nodeId),
1349
- { bumpCursor: true },
1350
- ).map((c: RankableNode) => c.node);
1351
-
1352
- for (const node of orderedCandidateNodes) {
1353
- const nodeId = readMeshNodeId(node);
1354
- if (!nodeId) continue;
1355
- const launchKey = `${meshId}:${nodeId}`;
1356
- const now = Date.now();
1357
- const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
1358
- if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
1359
- if (autoLaunchInProgress.has(launchKey)) {
1360
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
1361
- continue;
1362
- }
1363
- if (now < cooldownUntil) {
1364
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
1365
- continue;
1366
- }
1367
- if (isDirtyNode(node)) {
1368
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dirty_workspace', nodeId });
1369
- continue;
1370
- }
1371
- if (!isLaunchableNode(node)) {
1372
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_not_launch_ready', nodeId });
1373
- continue;
1374
- }
1375
- const launchTarget = resolveAutoLaunchTarget(components, node);
1376
- if (launchTarget.mode === 'skip') {
1377
- // Remote node we can't reach (no transport / no coordinator daemonId).
1378
- // Set a cooldown so the 4s reconcile loop doesn't re-attempt this node
1379
- // every tick; the de-dup'd skip ledger keeps it diagnosable without flood.
1380
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: launchTarget.reason || 'auto_launch_unavailable', nodeId });
1381
- autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1382
- continue;
1383
- }
1384
- // Write tasks keep the one-active-per-node invariant (worktree isolation);
1385
- // read-only (live_debug_readonly) diagnoses may auto-launch onto a node
1386
- // that already has an active assignment.
1387
- if (task.taskMode !== 'live_debug_readonly' && nodeHasActiveAssignment(meshId, nodeId)) {
1388
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
1389
- continue;
1390
- }
1391
- const maxConcurrentSessions = Number(node?.policy?.maxConcurrentSessions);
1392
- if (Number.isFinite(maxConcurrentSessions) && maxConcurrentSessions >= 0 && liveSessionCountForNode(components, meshId, nodeId) >= maxConcurrentSessions) {
1393
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_concurrent_sessions_reached', nodeId });
1394
- continue;
1395
- }
1396
-
1397
- autoLaunchInProgress.add(launchKey);
1398
- try {
1399
- const resolved = await resolveUsableProvider(components, nodeId, node, task.requiredTags);
1400
- if (!resolved.providerType) {
1401
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: resolved.reason || 'provider_unusable', nodeId });
1402
- continue;
1403
- }
1404
-
1405
- // Don't spawn a session for a (node, provider) already at its declared
1406
- // maxParallel cap — it would launch only to fail the claim. The claim
1407
- // transaction enforces the cap regardless; this just avoids a doomed launch.
1408
- const providerCap = resolveProviderMaxParallel(node?.policy, resolved.providerType);
1409
- if (
1410
- providerCap !== undefined
1411
- && activeProviderAssignedCount(meshId, nodeId, resolved.providerType) >= providerCap
1412
- ) {
1413
- markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_provider_parallel_reached', nodeId, providerType: resolved.providerType });
1414
- continue;
1415
- }
1416
-
1417
- // Shared worker-launch envelope. For a local node it spawns directly on this
1418
- // daemon; for a remote node the identical command is forwarded to the node's
1419
- // daemon (mirrors mesh_launch_session), with the coordinator daemonId stamped
1420
- // so the worker's completion events route back to this coordinator.
1421
- const launchSettings: Record<string, unknown> = {
1422
- // Worker launch envelope: role + mesh context so worker can route completion events.
1423
- role: 'worker',
1424
- meshNodeFor: meshId,
1425
- meshNodeId: nodeId,
1426
- spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
1427
- // Coordinator-dispatched worker: auto-approve unless mesh/node policy
1428
- // opts out (default true). Lands in settingsOverride and beats the
1429
- // global per-provider-type autoApprove config (see shouldAutoApprove).
1430
- autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
1431
- launchedByCoordinator: true,
1432
- autoLaunchedForQueueTaskId: task.id,
1433
- };
1434
-
1435
- if (launchTarget.mode === 'remote') {
1436
- // Relay-safe completion routing: stamp the coordinator anchor the same way
1437
- // mesh_launch_session does so the worker forwards events back to this daemon.
1438
- const remoteSettings: Record<string, unknown> = {
1439
- ...launchSettings,
1440
- meshCoordinatorDaemonId: launchTarget.coordinatorDaemonId,
1441
- meshCoordinatorNodeId: nodeId,
1442
- };
1443
- markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1444
- let launchResult: any;
1445
- try {
1446
- launchResult = await components.dispatchMeshCommand!(launchTarget.daemonId!, 'launch_cli', {
1447
- cliType: resolved.providerType,
1448
- dir: node.workspace,
1449
- settings: remoteSettings,
1450
- });
1451
- } catch (e: any) {
1452
- markAutoLaunch(meshId, task.id, { status: 'failed', reason: `remote_launch_dispatch_failed: ${e?.message || String(e)}`, nodeId, providerType: resolved.providerType });
1453
- autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1454
- return false;
1455
- }
1456
- const payload = (launchResult && typeof launchResult === 'object' && 'payload' in launchResult && launchResult.payload && typeof launchResult.payload === 'object')
1457
- ? launchResult.payload
1458
- : launchResult;
1459
- if (!payload?.success) {
1460
- const reason = readNonEmptyString(payload?.error) || 'remote_launch_cli_failed';
1461
- markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1462
- autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1463
- return false;
1464
- }
1465
- // Remote launch is async: the worker session will register and emit agent:ready,
1466
- // which (forwarded back here) drives the claim via the normal event path / PHASE 1
1467
- // reconcile. Set a cooldown so the 4s loop doesn't re-launch before that lands.
1468
- const remoteSessionId = readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.id) || readNonEmptyString(payload.runtimeSessionId);
1469
- markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId: remoteSessionId || undefined });
1470
- autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1471
- return true;
1472
- }
1473
-
1474
- markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1475
- const launchResult: any = await components.cliManager.handleCliCommand('launch_cli', {
1476
- cliType: resolved.providerType,
1477
- dir: node.workspace,
1478
- settings: launchSettings,
1479
- });
1480
- if (!launchResult?.success) {
1481
- const reason = launchResult?.error || 'launch_cli_failed';
1482
- markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1483
- autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1484
- return false;
1485
- }
1486
- const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
1487
- if (!sessionId) {
1488
- markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
1489
- autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1490
- return false;
1491
- }
1492
- markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
1493
- tryAssignQueueTask(components, meshId, nodeId, sessionId, resolved.providerType);
1494
- return true;
1495
- } catch (e: any) {
1496
- markAutoLaunch(meshId, task.id, { status: 'failed', error: e?.message || String(e), nodeId });
1497
- autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
1498
- return false;
1499
- } finally {
1500
- autoLaunchInProgress.delete(launchKey);
1501
- }
1502
- }
1503
- }
1504
- return false;
1505
- }
1506
-
1507
- export interface MeshQueueTriggerResult {
1508
- success: true;
1509
- meshId: string;
1510
- pendingBefore: number;
1511
- assignedBefore: number;
1512
- pendingAfter: number;
1513
- assignedAfter: number;
1514
- claimed: boolean;
1515
- newlyAssignedTasks: Array<{
1516
- id: string;
1517
- nodeId?: string;
1518
- sessionId?: string;
1519
- }>;
1520
- localIdleSessionsChecked: number;
1521
- remoteIdleSessionsChecked: number;
1522
- skippedSessions: Array<{
1523
- nodeId?: string;
1524
- sessionId?: string;
1525
- reason: string;
1526
- status?: string;
1527
- }>;
1528
- autoLaunchStarted: boolean;
1529
- /**
1530
- * True when a worker session is already on its way to claim a still-pending task —
1531
- * either launched this tick (autoLaunchStarted) or launched on a prior tick and still
1532
- * booting/awaiting-claim. Callers MUST treat this as "wait, do not launch another
1533
- * session": a second launch double-edits the worktree. Mutually informative with
1534
- * `noIdleMeshSessionAvailable`, which is suppressed whenever this is true.
1535
- */
1536
- autoLaunchPending?: boolean;
1537
- noIdleMeshSessionAvailable?: boolean;
1538
- }
1539
-
1540
- function countQueueStatus(meshId: string, status: 'pending' | 'assigned'): number {
1541
- return getQueue(meshId, { status: [status] as any }).length;
1542
- }
1543
-
1544
- function getQueueStatusById(meshId: string): Map<string, string> {
1545
- return new Map(getQueue(meshId).map(task => [task.id, task.status]));
1546
- }
1547
-
1548
- export async function triggerMeshQueue(components: DaemonComponents, meshId: string): Promise<MeshQueueTriggerResult> {
1549
- const mesh = getMeshWithCache(components, meshId);
1550
- const pendingBefore = countQueueStatus(meshId, 'pending');
1551
- const assignedBefore = countQueueStatus(meshId, 'assigned');
1552
- const beforeStatus = getQueueStatusById(meshId);
1553
- const skippedSessions: MeshQueueTriggerResult['skippedSessions'] = [];
1554
- let localIdleSessionsChecked = 0;
1555
- let remoteIdleSessionsChecked = 0;
1556
- let autoLaunchStarted = false;
1557
- if (!mesh) {
1558
- return {
1559
- success: true,
1560
- meshId,
1561
- pendingBefore,
1562
- assignedBefore,
1563
- pendingAfter: pendingBefore,
1564
- assignedAfter: assignedBefore,
1565
- claimed: false,
1566
- newlyAssignedTasks: [],
1567
- localIdleSessionsChecked,
1568
- remoteIdleSessionsChecked,
1569
- skippedSessions: [{ reason: 'mesh_not_found' }],
1570
- autoLaunchStarted,
1571
- noIdleMeshSessionAvailable: true,
1572
- };
1573
- }
1574
-
1575
- // Collect every idle mesh session (local CLI instances + remote idle records)
1576
- // as drain candidates. The drain ORDER depends on the scheduling strategy:
1577
- // - 'first_eligible' (default): local-first, then remote, exactly as before.
1578
- // - otherwise: local + remote merged into one pool and drained in scheduling
1579
- // order (priority → load → tie-break). This local-first debias is required
1580
- // because without it the coordinator's own local node is always visited
1581
- // first and greedily absorbs all untargeted work before any remote idle
1582
- // session is even considered — the comparator alone can't spread work if
1583
- // local is always tried first.
1584
- type IdleCandidate = { nodeId: string; sessionId: string; providerType: string; origin: 'local' | 'remote'; node: any };
1585
- const strategy = resolveSchedulingStrategy(mesh);
1586
- const localCandidates: IdleCandidate[] = [];
1587
-
1588
- const cliInstances = components.instanceManager.getByCategory('cli');
1589
- for (const inst of cliInstances) {
1590
- const state = inst.getState();
1591
- const settings = state.settings as Record<string, unknown> || {};
1592
-
1593
- const instMeshId = readNonEmptyString(settings.meshNodeFor);
1594
- if (instMeshId !== meshId) continue;
1595
-
1596
- const nodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
1597
- if (!nodeId) continue;
1598
-
1599
- if (!isIdleSessionState(state)) {
1600
- const status = readNonEmptyString(state.status).toLowerCase();
1601
- skippedSessions.push({
1602
- nodeId,
1603
- sessionId: readNonEmptyString(state.instanceId),
1604
- reason: isTerminalSessionStatus(status) ? 'terminal_session' : 'session_not_idle',
1605
- status: status || undefined,
1606
- });
1607
- continue;
1608
- }
1609
-
1610
- const sessionId = state.instanceId;
1611
- const providerType = state.type || readNonEmptyString(settings.providerType);
1612
-
1613
- if (providerType) {
1614
- localIdleSessionsChecked += 1;
1615
- localCandidates.push({ nodeId, sessionId, providerType, origin: 'local', node: mesh.nodes.find((n: any) => readMeshNodeId(n) === nodeId) });
1616
- } else {
1617
- skippedSessions.push({
1618
- nodeId,
1619
- sessionId,
1620
- reason: 'provider_type_missing',
1621
- });
1622
- }
1623
- }
1624
-
1625
- let remoteSessions: Array<{ nodeId: string; sessionId: string; providerType: string }> = [];
1626
- try {
1627
- remoteSessions = MeshRuntimeStore.getInstance().getRemoteIdleSessions();
1628
- } catch { /* best-effort */ }
1629
-
1630
- const remoteCandidates: IdleCandidate[] = [];
1631
- for (const idle of remoteSessions) {
1632
- // Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
1633
- // `n.id`, so an inline-cached worktree node whose identity arrived under a
1634
- // different form is not silently dropped — leaving a remote idle session
1635
- // unable to claim its pending queue task.
1636
- const node = mesh.nodes.find((n: any) => meshNodeIdMatches(n, idle.nodeId));
1637
- if (node) {
1638
- remoteIdleSessionsChecked += 1;
1639
- remoteCandidates.push({ nodeId: idle.nodeId, sessionId: idle.sessionId, providerType: idle.providerType, origin: 'remote', node });
1640
- }
1641
- }
1642
-
1643
- const assignIdleCandidate = (candidate: IdleCandidate): void => {
1644
- const assigned = tryAssignQueueTask(components, meshId, candidate.nodeId, candidate.sessionId, candidate.providerType);
1645
- if (assigned && candidate.origin === 'remote') {
1646
- try {
1647
- MeshRuntimeStore.getInstance().deleteRemoteIdleSession(candidate.nodeId, candidate.sessionId);
1648
- } catch { /* best-effort */ }
1649
- }
1650
- };
1651
-
1652
- if (strategy === 'first_eligible') {
1653
- // Strict no-change: drain local idle sessions first (original order), then
1654
- // remote idle sessions. tryAssignQueueTask is a no-op when nothing matches.
1655
- for (const candidate of localCandidates) assignIdleCandidate(candidate);
1656
- for (const candidate of remoteCandidates) assignIdleCandidate(candidate);
1657
- } else {
1658
- // Merge local + remote into one pool and drain in scheduling order. Each
1659
- // assignment mutates a node's active load, and the next pick re-reads it,
1660
- // so re-ranking after every assignment keeps the spread fair as load shifts.
1661
- const pool = [...localCandidates, ...remoteCandidates];
1662
- const baseIndex = new Map<string, number>();
1663
- pool.forEach((c, i) => { if (!baseIndex.has(c.nodeId)) baseIndex.set(c.nodeId, i); });
1664
- // Bump the round-robin cursor once for this whole drain pass.
1665
- const uniqueNodes = [...new Set(pool.map(c => c.nodeId))]
1666
- .map((nodeId, index) => ({ nodeId, node: pool.find(c => c.nodeId === nodeId)?.node, index }));
1667
- const ranked = orderEligibleNodes(meshId, strategy, uniqueNodes, { bumpCursor: true });
1668
- const rankIndex = new Map<string, number>(ranked.map((r, i) => [r.nodeId, i]));
1669
- const remaining = [...pool];
1670
- while (remaining.length > 0) {
1671
- // Re-rank each pass so a node that just took work defers its next session.
1672
- remaining.sort((a, b) => {
1673
- const aPrio = resolveNodeSchedulingPriority(a.node?.policy);
1674
- const bPrio = resolveNodeSchedulingPriority(b.node?.policy);
1675
- if (aPrio !== bPrio) return bPrio - aPrio;
1676
- if (strategy === 'least_loaded' || strategy === 'round_robin') {
1677
- const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
1678
- if (loadDelta !== 0) return loadDelta;
1679
- }
1680
- return (rankIndex.get(a.nodeId) ?? 0) - (rankIndex.get(b.nodeId) ?? 0);
1681
- });
1682
- assignIdleCandidate(remaining.shift()!);
1683
- }
1684
- }
1685
-
1686
- autoLaunchStarted = await maybeAutoLaunchOneQueueSession(components, meshId, mesh);
1687
- const afterQueue = getQueue(meshId);
1688
- const pendingAfter = afterQueue.filter(task => task.status === 'pending').length;
1689
- const assignedAfter = afterQueue.filter(task => task.status === 'assigned').length;
1690
- const newlyAssignedTasks = afterQueue
1691
- .filter(task => task.status === 'assigned' && beforeStatus.get(task.id) !== 'assigned')
1692
- .map(task => ({
1693
- id: task.id,
1694
- nodeId: task.assignedNodeId,
1695
- sessionId: task.assignedSessionId,
1696
- }));
1697
-
1698
- // An auto-launch is "pending" when the coordinator has already spun a session up
1699
- // for a still-pending task and is waiting on that session's idle→claim. This covers
1700
- // two ticks:
1701
- // - THIS tick fired the launch (autoLaunchStarted), or
1702
- // - a PRIOR tick launched a session that is still booting/awaiting-claim — the
1703
- // per-task await-claim guard (maybeAutoLaunchOneQueueSession) deliberately
1704
- // declines to launch again, so autoLaunchStarted is false even though a session
1705
- // is on its way to claim this task.
1706
- // Without this signal, the second tick reports `noIdleMeshSessionAvailable` and the
1707
- // MCP guidance tells the coordinator to launch ANOTHER worker — producing a duplicate
1708
- // session that double-edits the worktree. The claim itself is fine; only the wording
1709
- // was wrong, so we surface `autoLaunchPending` to suppress the bad "launch one more"
1710
- // advice while the just-launched session converges.
1711
- const autoLaunchPending = autoLaunchStarted || afterQueue.some(task => {
1712
- if (task.status !== 'pending') return false;
1713
- const al = task.autoLaunch;
1714
- if (!al || (al.status !== 'started' && al.status !== 'completed')) return false;
1715
- const launchedAtMs = Date.parse(al.updatedAt);
1716
- return Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS;
1717
- });
1718
-
1719
- return {
1720
- success: true,
1721
- meshId,
1722
- pendingBefore,
1723
- assignedBefore,
1724
- pendingAfter,
1725
- assignedAfter,
1726
- claimed: newlyAssignedTasks.length > 0,
1727
- newlyAssignedTasks,
1728
- localIdleSessionsChecked,
1729
- remoteIdleSessionsChecked,
1730
- skippedSessions,
1731
- autoLaunchStarted,
1732
- ...(autoLaunchPending ? { autoLaunchPending: true } : {}),
1733
- // Only report "no idle session, go launch one" when nothing is already on its way.
1734
- // A pending auto-launch (this tick or a prior still-converging one) means a session
1735
- // WILL claim shortly, so it is not a no-session-available situation.
1736
- ...(pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchPending
1737
- ? { noIdleMeshSessionAvailable: true }
1738
- : {}),
1739
- };
1740
- }
1741
-
1742
- async function maybeAutoFastForwardIdleNode(components: DaemonComponents, args: {
1743
- meshId: string;
1744
- nodeId: string;
1745
- sessionId?: string;
1746
- providerType?: string;
1747
- }): Promise<void> {
1748
- const mesh = getMeshWithCache(components, args.meshId);
1749
- const node = mesh?.nodes?.find((candidate: any) => meshNodeIdMatches(candidate, args.nodeId));
1750
- const workspace = readNonEmptyString(node?.workspace);
1751
- if (!workspace) return;
1752
- if (!existsSync(workspace)) return;
1753
-
1754
- const policy = resolveAutoFastForwardPolicy(mesh);
1755
- if (!policy.enabled) return;
1756
- if (nodeHasActiveMeshWork(components, args.meshId, args.nodeId, args.sessionId)) return;
1757
-
1758
- const throttleKey = `${args.meshId}:${args.nodeId}`;
1759
- const now = Date.now();
1760
- const lastAttempt = idleAutoFastForwardLastAttempt.get(throttleKey) || 0;
1761
- if (now - lastAttempt < IDLE_AUTO_FAST_FORWARD_THROTTLE_MS) return;
1762
- idleAutoFastForwardLastAttempt.set(throttleKey, now);
1763
-
1764
- const submoduleIgnorePaths = Array.isArray(node?.policy?.submoduleIgnorePaths)
1765
- ? node.policy.submoduleIgnorePaths.filter((value: unknown): value is string => typeof value === 'string')
1766
- : undefined;
1767
- try {
1768
- const dryRun = await fastForwardMeshNode({
1769
- meshId: args.meshId,
1770
- nodeId: args.nodeId,
1771
- workspace,
1772
- execute: false,
1773
- dryRun: true,
1774
- updateSubmodules: false,
1775
- submoduleIgnorePaths,
1776
- trigger: 'idle_auto',
1777
- });
1778
- if (!dryRun || dryRun.code !== 'fast_forward_available' || dryRun.allowed !== true) return;
1779
- const behind = Number(dryRun.current?.behind);
1780
- if (policy.maxBehind !== undefined && Number.isFinite(behind) && behind > policy.maxBehind) return;
1781
- if (policy.requireCleanSubmodules) {
1782
- const submodules = Array.isArray(dryRun.current?.submodules) ? dryRun.current.submodules : [];
1783
- if (submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return;
1784
- }
1785
- await fastForwardMeshNode({
1786
- meshId: args.meshId,
1787
- nodeId: args.nodeId,
1788
- workspace,
1789
- execute: true,
1790
- dryRun: false,
1791
- updateSubmodules: false,
1792
- submoduleIgnorePaths,
1793
- trigger: 'idle_auto',
1794
- });
1795
- } catch (e: any) {
1796
- LOG.warn('MeshFastForward', `Idle auto fast-forward check failed for ${args.nodeId}: ${e?.message || e}`);
1797
- }
1798
- }
1799
-
1800
- function runIdleMaintenanceThenAssignQueue(components: DaemonComponents, args: {
1801
- meshId: string;
1802
- nodeId: string;
1803
- sessionId: string;
1804
- providerType: string;
1805
- }): void {
1806
- setImmediate(() => {
1807
- maybeAutoFastForwardIdleNode(components, args)
1808
- .finally(() => {
1809
- try {
1810
- tryAssignQueueTask(components, args.meshId, args.nodeId, args.sessionId, args.providerType);
1811
- } catch (e: any) {
1812
- LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${args.nodeId}: ${e?.message || e}`);
1813
- }
1814
- });
1815
- });
1816
- }
1817
-
1818
- // ---------------------------------------------------------------------------
1819
- // Core event injection
1820
- // ---------------------------------------------------------------------------
1821
-
1822
- const MESH_COORDINATOR_EVENTS = new Set([
1823
- 'agent:generating_started',
1824
- 'agent:generating_completed',
1825
- 'agent:waiting_approval',
1826
- 'agent:stopped',
1827
- 'agent:ready',
1828
- 'monitor:no_progress',
1829
- 'refine:accepted',
1830
- 'refine:completed',
1831
- 'refine:failed',
1832
- 'worktree_bootstrap_complete',
1833
- 'worktree_bootstrap_failed',
1834
- ]);
1835
-
1836
- const EVENT_TO_LEDGER_KIND: Record<string, MeshLedgerKind> = {
1837
- 'agent:generating_completed': 'task_completed',
1838
- 'agent:waiting_approval': 'task_approval_needed',
1839
- 'agent:stopped': 'task_failed',
1840
- 'monitor:no_progress': 'task_stalled',
1841
- };
1842
-
1843
- export function isMeshCoordinatorEvent(eventName: unknown): eventName is string {
1844
- return typeof eventName === 'string' && MESH_COORDINATOR_EVENTS.has(eventName);
1845
- }
1846
-
1847
- // Terminal events that the coordinator is actively blocked waiting on. When the
1848
- // coordinator CLI session dispatches a task (e.g. mesh_send_task) it stays in
1849
- // `generating` until the result arrives — but a generating coordinator queues
1850
- // incoming send_message calls into its adapter's pendingOutboundQueue, which is
1851
- // only flushed on the coordinator's OWN idle transition. That transition can't
1852
- // happen until it receives this very event → deadlock. We force-inject these so
1853
- // they bypass the busy send-guard and land in the PTY while generating.
1854
- export const MESH_FORCE_INJECT_EVENTS: ReadonlySet<string> = new Set([
1855
- 'agent:generating_completed',
1856
- 'agent:stopped',
1857
- 'agent:waiting_approval',
1858
- 'refine:completed',
1859
- 'refine:failed',
1860
- 'worktree_bootstrap_complete',
1861
- 'worktree_bootstrap_failed',
1862
- ]);
1863
-
1864
- export function shouldForceInjectMeshEvent(eventName: unknown): boolean {
1865
- return typeof eventName === 'string' && MESH_FORCE_INJECT_EVENTS.has(eventName);
1866
- }
1867
-
1868
- // Coordinator-side suppression/reconcile gate for an incoming mesh event. Each clause is a
1869
- // closed dedup/suppression concern that only inspects the event + already-resolved context and
1870
- // either (a) returns a `suppress` result the caller forwards verbatim, (b) returns a `reconcile`
1871
- // signal carrying the rewritten metadataEvent for the caller to re-inject as
1872
- // agent:generating_completed, or (c) returns null to let the event fall through to the
1873
- // terminal/ledger machinery. Extracted verbatim from injectMeshSystemMessage — no behavior
1874
- // change; the only side effects (best-effort remote-idle cleanup, LOG, trace) fire on the same
1875
- // paths as before.
1876
- function evaluateMeshEventSuppression(
1877
- args: {
1878
- meshId: string;
1879
- sourceInstanceId?: string;
1880
- nodeId?: string;
1881
- nodeLabel: string;
1882
- event: string;
1883
- metadataEvent: Record<string, unknown>;
1884
- },
1885
- ctx: {
1886
- traceCtx: Parameters<typeof traceMeshEventDrop>[1];
1887
- eventSessionId: string;
1888
- eventNodeId: string;
1889
- eventTimestamp: number | null;
1890
- workerCoordinatorDaemonId: string | undefined;
1891
- },
1892
- ):
1893
- | { kind: 'suppress'; result: { success: true; forwarded: 0; suppressed: true; [extra: string]: unknown } }
1894
- | { kind: 'reconcile'; metadataEvent: Record<string, unknown> }
1895
- | null {
1896
- const { traceCtx, eventSessionId, eventNodeId, eventTimestamp, workerCoordinatorDaemonId } = ctx;
1897
-
1898
- const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
1899
- event: args.event,
1900
- meshId: args.meshId,
1901
- metadataEvent: args.metadataEvent,
1902
- sessionId: eventSessionId || undefined,
1903
- nodeId: eventNodeId || undefined,
1904
- });
1905
- if (intentionalCleanupStop) {
1906
- if (eventSessionId && eventNodeId) {
1907
- try {
1908
- MeshRuntimeStore.getInstance().deleteRemoteIdleSession(eventNodeId, eventSessionId);
1909
- } catch { /* best-effort */ }
1910
- }
1911
- LOG.info('MeshEvents', `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || '(unknown session)'}`);
1912
- traceMeshEventDrop('intentional_cleanup_stop', traceCtx);
1913
- return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true } };
1914
- }
1915
-
1916
- if (args.event === 'monitor:no_progress') {
1917
- const reconciledCompletion = buildNoProgressCompletionReconciliation({
1918
- meshId: args.meshId,
1919
- nodeId: args.nodeId,
1920
- nodeLabel: args.nodeLabel,
1921
- metadataEvent: args.metadataEvent,
1922
- sourceInstanceId: args.sourceInstanceId,
1923
- });
1924
- if (reconciledCompletion?.source === 'no_progress_reconciliation') {
1925
- LOG.info('MeshEvents', `Reconciled no-progress monitor to completion for session ${eventSessionId || '(unknown session)'}`);
1926
- return { kind: 'reconcile', metadataEvent: reconciledCompletion };
1927
- }
1928
- if (reconciledCompletion?.source === 'no_progress_terminal_ledger_suppression') {
1929
- LOG.info('MeshEvents', `Suppressed no-progress monitor because terminal ledger evidence already exists for session ${eventSessionId || '(unknown session)'}`);
1930
- traceMeshEventDrop('no_progress_terminal_ledger_suppression', traceCtx, `terminalKind=${reconciledCompletion.terminalLedgerKind}`);
1931
- return {
1932
- kind: 'suppress',
1933
- result: {
1934
- success: true,
1935
- forwarded: 0,
1936
- suppressed: true,
1937
- terminalLedgerEvidence: true,
1938
- terminalLedgerKind: reconciledCompletion.terminalLedgerKind,
1939
- },
1940
- };
1941
- }
1942
- }
1943
-
1944
- if (isDuplicateRefineTerminalEvent(args.meshId, args.event, args.metadataEvent)) {
1945
- LOG.info('MeshEvents', `Suppressed duplicate ${args.event} for refine job ${readRefineJobId({ metadataEvent: args.metadataEvent })}`);
1946
- traceMeshEventDrop('duplicate_refine_terminal', traceCtx);
1947
- return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true } };
1948
- }
1949
-
1950
- if (args.event === 'agent:waiting_approval' && eventSessionId) {
1951
- const duplicateApproval = isDuplicateMeshApprovalEvent({
1952
- meshId: args.meshId,
1953
- sessionId: eventSessionId,
1954
- providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
1955
- timestamp: eventTimestamp,
1956
- modalMessage: readNonEmptyString(args.metadataEvent.modalMessage) || undefined,
1957
- modalButtons: args.metadataEvent.modalButtons,
1958
- });
1959
- if (duplicateApproval) {
1960
- LOG.info('MeshEvents', `Suppressed duplicate approval event for mesh ${args.meshId} session ${eventSessionId}`);
1961
- traceMeshEventDrop('duplicate_approval', traceCtx);
1962
- return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateApproval: true } };
1963
- }
1964
- }
1965
- if (args.event === 'agent:generating_completed' && eventSessionId) {
1966
- const terminal = findRecentTerminalLedgerEvidence({
1967
- meshId: args.meshId,
1968
- sessionId: eventSessionId,
1969
- nodeId: eventNodeId || undefined,
1970
- });
1971
- if (terminal?.kind === 'task_completed' && !sessionHasActiveAssignment(args.meshId, eventSessionId)) {
1972
- const newDispatchAfterTerminal = hasDispatchAfterTerminal(args.meshId, eventSessionId, terminal.id);
1973
- // Fix B (re-dispatch 2nd-completion routing): a prior terminal recorded from a FALSE
1974
- // idle (weak evidence / no confirmed final assistant) must NOT permanently suppress a
1975
- // later GENUINE completion of the same session. providerSessionId is stable across a
1976
- // session's turns, so the providerSessionId/finalSummary dedup below would otherwise
1977
- // swallow the real 2nd-turn completion that a coordinator nudge (direct re-dispatch)
1978
- // drove — exactly the missed-event bug. When the prior terminal was weak and the new
1979
- // event carries genuine completion evidence, let it through so it is recorded and
1980
- // re-attributed to the latest task (the normal task_completed path below).
1981
- const supersedesWeakTerminal = isWeakTerminalLedgerPayload(terminal.payload)
1982
- && isGenuineCompletionEvidence(args.metadataEvent);
1983
- // CANON-B (direct-dispatch completion race): a FAST direct dispatch (mesh_send_task)
1984
- // to an already-idle, previously-used session can have its genuine completion reach
1985
- // this coordinator handler BEFORE the dispatching side records the new task's dispatch
1986
- // row / task_dispatched ledger entry — insertDirectDispatch + appendLedgerEntry both run
1987
- // AFTER the agent_command await resolves, while the worker may already be done. In that
1988
- // window sessionHasActiveAssignment is false (no active dispatch row, no unterminal
1989
- // ledger entry yet), so this prior-terminal dedup engages; and because providerSessionId
1990
- // is STABLE across a reused session's turns, the providerSessionId/finalSummary match
1991
- // below would suppress the NEW task's completion as a duplicate of the PRIOR task —
1992
- // silently losing it (the observed intermittent miss; fresh enqueue/autoLaunch is immune
1993
- // because a fresh session has no prior same-providerSessionId terminal and the queue row
1994
- // is claimed atomically before dispatch). The echoed taskId is the authoritative
1995
- // discriminator: when the completion names a DIFFERENT task than the recorded terminal,
1996
- // it is a genuinely new task's completion, never a duplicate — let it through so it is
1997
- // attributed to its own taskId. A same-task re-arrival (taskId equal) or a taskId-less
1998
- // legacy event still falls through to the providerSessionId/finalSummary dedup.
1999
- const terminalTaskId = readNonEmptyString(terminal.payload.taskId);
2000
- const eventTaskId = readNonEmptyString(args.metadataEvent.taskId);
2001
- const distinctTaskCompletion = !!eventTaskId && !!terminalTaskId && eventTaskId !== terminalTaskId;
2002
- // (FALSEIDLE-BGCHILD-b) Same-task genuine completion carrying a fuller summary than the
2003
- // recorded (truncated, false-idle-pre-empted) terminal supersedes it — see helper.
2004
- const supersedesTruncatedTerminal = supersedesTruncatedTerminalSummary({
2005
- terminalPayload: terminal.payload,
2006
- metadataEvent: args.metadataEvent,
2007
- terminalTaskId,
2008
- eventTaskId,
2009
- });
2010
- if (!newDispatchAfterTerminal && !supersedesWeakTerminal && !distinctTaskCompletion && !supersedesTruncatedTerminal) {
2011
- const terminalProviderSessionId = readNonEmptyString(terminal.payload.providerSessionId);
2012
- const terminalFinalSummary = readNonEmptyString(terminal.payload.finalSummary);
2013
- const eventProviderSessionId = readNonEmptyString(args.metadataEvent.providerSessionId);
2014
- const eventFinalSummary = readNonEmptyString(args.metadataEvent.finalSummary);
2015
- if (
2016
- (terminalProviderSessionId && terminalProviderSessionId === eventProviderSessionId)
2017
- || (terminalFinalSummary && terminalFinalSummary === eventFinalSummary)
2018
- || args.metadataEvent.source === 'no_progress_reconciliation'
2019
- ) {
2020
- LOG.info('MeshEvents', `Suppressed duplicate completion with existing terminal ledger evidence for mesh ${args.meshId} session ${eventSessionId}`);
2021
- traceMeshEventDrop('duplicate_completion_terminal_ledger', traceCtx);
2022
- return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true } };
2023
- }
2024
- }
2025
- }
2026
- const duplicateCompletion = isDuplicateMeshCompletionEvent({
2027
- meshId: args.meshId,
2028
- event: args.event,
2029
- sessionId: eventSessionId,
2030
- providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
2031
- providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
2032
- timestamp: eventTimestamp,
2033
- finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
2034
- coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
2035
- taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
2036
- nodeId: eventNodeId || undefined,
2037
- });
2038
- if (duplicateCompletion) {
2039
- LOG.info('MeshEvents', `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
2040
- traceMeshEventDrop('duplicate_completion', traceCtx);
2041
- return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true } };
2042
- }
2043
- }
2044
- if (args.event === 'agent:stopped' && eventSessionId) {
2045
- const duplicateStopped = isDuplicateMeshCompletionEvent({
2046
- meshId: args.meshId,
2047
- event: args.event,
2048
- sessionId: eventSessionId,
2049
- providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
2050
- providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
2051
- timestamp: eventTimestamp,
2052
- finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
2053
- coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
2054
- taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
2055
- nodeId: eventNodeId || undefined,
2056
- });
2057
- if (duplicateStopped) {
2058
- LOG.info('MeshEvents', `Suppressed duplicate stopped event for mesh ${args.meshId} session ${eventSessionId}`);
2059
- traceMeshEventDrop('duplicate_stopped', traceCtx);
2060
- return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateStopped: true } };
2061
- }
2062
- }
2063
-
2064
- return null;
2065
- }
2066
-
2067
- function injectMeshSystemMessage(components: DaemonComponents, args: {
2068
- meshId: string;
2069
- sourceInstanceId?: string;
2070
- nodeId?: string;
2071
- nodeLabel: string;
2072
- event: string;
2073
- metadataEvent: Record<string, unknown>;
2074
- }) {
2075
- const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
2076
- const eventNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
2077
-
2078
- // EVTTRACE correlation context for this event's coordinator-side lifecycle (queue /
2079
- // dedup / suppress). Observation only — never read by any decision below.
2080
- const traceCtx = {
2081
- taskId: args.metadataEvent.taskId,
2082
- sessionId: eventSessionId,
2083
- nodeId: eventNodeId,
2084
- meshId: args.meshId,
2085
- event: args.event,
2086
- };
2087
-
2088
- const sourceSession = args.sourceInstanceId
2089
- ? components.instanceManager.getInstance(args.sourceInstanceId)
2090
- : undefined;
2091
- const workerCoordinatorDaemonId = readNonEmptyString(
2092
- (sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorDaemonId,
2093
- );
2094
- // Session-level routing anchor (multi-coordinator). Prefer the LIVE worker session's
2095
- // stamp; fall back to a relayed value carried in metadataEvent.meshCoordinatorSessionId
2096
- // (a remote worker's completion arrives via handleMeshForwardEvent with no local
2097
- // sourceSession, so the stamp can only ride in the relayed metadata). Empty on legacy /
2098
- // version-skewed dispatches → the event stays daemon-broadcast (no regression).
2099
- const workerCoordinatorSessionId = readNonEmptyString(
2100
- (sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorSessionId,
2101
- ) || readNonEmptyString(args.metadataEvent.meshCoordinatorSessionId);
2102
-
2103
- // T2: a summary-less completion (and any non-completion status-sync event) carries no
2104
- // assistant text on the event, so resolveMeshSurfacedSessionPreview had nothing to surface
2105
- // and the coordinator's inbox mirror stayed stuck on the first dispatched user task. When
2106
- // THIS daemon hosts the live worker instance (sourceSession present), derive the worker's
2107
- // latest display message straight from its transcript and attach it to the event as
2108
- // lastMessagePreview/lastMessageRole/lastMessageAt. resolveMeshSurfacedSessionPreview reads
2109
- // these as an assistant-only fallback; they also ride the pending-queue + P2P relay
2110
- // (handleMeshForwardEvent whitelist) so a remote coordinator can surface them. A remote
2111
- // coordinator has no local instance and keeps relying on the relayed fields — unchanged.
2112
- const enrichedMetadataEvent = ((): Record<string, unknown> => {
2113
- const last = sourceSession ? getLastDisplayMessage(sourceSession.getState()) : null;
2114
- if (!last || !last.preview) return args.metadataEvent;
2115
- return {
2116
- ...args.metadataEvent,
2117
- lastMessagePreview: last.preview,
2118
- lastMessageRole: last.role,
2119
- ...(last.receivedAt > 0 ? { lastMessageAt: last.receivedAt } : {}),
2120
- };
2121
- })();
2122
-
2123
- // R2: cloud P2P dashboard metadata sync. The cloud daemon used to do this from its own
2124
- // relay listener; now the single core forwarder invokes the injected hook (no-op on
2125
- // standalone) so the event path stays single-listener and the local code path is identical
2126
- // across standalone and cloud.
2127
- if (components.onMeshCoordinatorEventForwarded) {
2128
- try {
2129
- // T: the coordinator surfaces a remote worker's session but holds no local
2130
- // instance for it, so the status snapshot can't derive a preview and the
2131
- // mirror would stay stuck on the first dispatched user task. Resolve the
2132
- // worker's latest assistant reply (carried on the completion event's
2133
- // finalSummary / workerResult) into a preview the mirror can stamp, so the
2134
- // mobile inbox reflects the assistant response. Completion events carry assistant
2135
- // text as finalSummary; a summary-less completion / status sync falls back to the
2136
- // worker's latest assistant display message (enrichedMetadataEvent.lastMessage*).
2137
- // For a mid-turn user-only event this is undefined and the prior surfaced preview
2138
- // is preserved downstream (no clobber).
2139
- const surfacedPreview = resolveMeshSurfacedSessionPreview(enrichedMetadataEvent);
2140
- components.onMeshCoordinatorEventForwarded({
2141
- event: args.event,
2142
- meshId: args.meshId,
2143
- nodeId: eventNodeId || undefined,
2144
- ...enrichedMetadataEvent,
2145
- // Ensure a `workspace` field reaches updateMeshOwnedSession even when the
2146
- // worker provider event only carried `workspaceName`. The merge spread of
2147
- // metadataEvent above wins when it already has a non-empty `workspace`.
2148
- workspace: readNonEmptyString(args.metadataEvent.workspace)
2149
- || readNonEmptyString(args.metadataEvent.workspaceName)
2150
- || undefined,
2151
- ...(surfacedPreview ? {
2152
- meshSessionLastMessagePreview: surfacedPreview.preview,
2153
- meshSessionLastMessageRole: surfacedPreview.role,
2154
- meshSessionLastMessageAt: surfacedPreview.receivedAt || undefined,
2155
- } : {}),
2156
- });
2157
- } catch { /* dashboard metadata sync is best-effort */ }
2158
- }
2159
-
2160
- const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
2161
- // Coordinator-side dedup/suppression gate (extracted, behavior-preserving). A non-null
2162
- // outcome either short-circuits with a forwarded result or signals a no-progress→completion
2163
- // reconciliation that we re-inject; null lets the event fall through to the ledger machinery.
2164
- const suppression = evaluateMeshEventSuppression(args, {
2165
- traceCtx,
2166
- eventSessionId,
2167
- eventNodeId,
2168
- eventTimestamp,
2169
- workerCoordinatorDaemonId,
2170
- });
2171
- if (suppression) {
2172
- if (suppression.kind === 'reconcile') {
2173
- return injectMeshSystemMessage(components, {
2174
- ...args,
2175
- event: 'agent:generating_completed',
2176
- metadataEvent: suppression.metadataEvent,
2177
- });
2178
- }
2179
- return suppression.result;
2180
- }
2181
-
2182
- function markSessionTerminal(sessionId: string, outcome: 'completed' | 'failed', occurredAtMs?: number | null, opts?: { tentativeIfDirect?: boolean }): { id?: string } | null {
2183
- // C2: prefer an exact taskId match when the completion event carries one —
2184
- // it's immune to coordinator↔worker clock skew that can hide the assigned row.
2185
- const eventTaskId = readNonEmptyString(args.metadataEvent.taskId) || undefined;
2186
- const task = updateSessionTaskStatus(args.meshId, sessionId, outcome, {
2187
- occurredAt: occurredAtMs != null ? new Date(occurredAtMs).toISOString() : undefined,
2188
- taskId: eventTaskId,
2189
- });
2190
- // Fix A (early-terminal prevention): a false-idle completion (no confirmed final
2191
- // assistant) for a DIRECT dispatch — i.e. no work-queue row matched — must not flip the
2192
- // dispatch row terminal. Leaving it active lets the reconcile loop (PHASE 4) re-read the
2193
- // transcript and record the genuine completion once the worker truly finishes (commonly
2194
- // after a coordinator nudge / re-dispatch). A matched queue task, or a completion with
2195
- // genuine evidence, is marked terminal as before.
2196
- // WARMUPGAP: a no-taskId completion from a session that holds no active assignment is a
2197
- // pre-assignment warmup / ghost event (a worker spawns, idles, and emits idle→generating→
2198
- // completed before any task is dispatched, with meshActiveTaskId unset so the event carries
2199
- // no taskId). Letting it through would hit the session_id fallback in updateDirectDispatchStatus
2200
- // and flip a sibling/stale dispatch row this event does not own — the real task later lands on
2201
- // a corrupted row and never reaches completed. Skip the dispatch update for that case. A
2202
- // taskId-carrying completion (real task), or any completion whose session currently holds an
2203
- // active assignment (legacy/relayed worker), still flips as before.
2204
- const leaveDirectDispatchActive = (!task && opts?.tentativeIfDirect === true)
2205
- || (!eventTaskId && !sessionHasActiveAssignment(args.meshId, sessionId));
2206
- if (!leaveDirectDispatchActive) {
2207
- // CANON-B: flip the exact dispatch row the completion echoed its taskId for; the
2208
- // session_id fallback (no echoed taskId) still covers legacy/relayed workers.
2209
- updateDirectDispatchStatus(args.meshId, sessionId, outcome, eventTaskId);
2210
- }
2211
- markSessionDeliveriesTerminal(args.meshId, sessionId, outcome);
2212
- setImmediate(() => cleanupTerminalDirectDispatches());
2213
- return task ? { id: task.id } : null;
2214
- }
2215
-
2216
- let completedTaskForLedger: { id?: string } | null = null;
2217
- // Fix B: direct-dispatch taskId used to attribute the terminal ledger entry when no
2218
- // work-queue row matches (resolved BEFORE markSessionTerminal flips the dispatch terminal).
2219
- let directDispatchTaskIdForLedger: string | undefined;
2220
- if (args.event === 'agent:generating_completed') {
2221
- const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
2222
- const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
2223
- const providerType = readNonEmptyString(args.metadataEvent.providerType);
2224
-
2225
- if (sessionId) {
2226
- // CANON-B: trust the taskId the completion echoed; only fall back to the
2227
- // most-recent-by-session heuristic when the worker carried none.
2228
- directDispatchTaskIdForLedger = readNonEmptyString(args.metadataEvent.taskId)
2229
- || resolveActiveDirectDispatchTaskId(args.meshId, sessionId);
2230
- // A false-idle completion of a direct dispatch is recorded but kept tentative (the
2231
- // dispatch row stays active for the reconcile fallback); a genuine completion is terminal.
2232
- const isFalseIdle = isFalseIdleCompletion(args.metadataEvent);
2233
- completedTaskForLedger = markSessionTerminal(sessionId, 'completed', eventTimestamp, { tentativeIfDirect: isFalseIdle });
2234
- if (nodeId && providerType) {
2235
- runIdleMaintenanceThenAssignQueue(components, { meshId: args.meshId, nodeId, sessionId, providerType });
2236
- }
2237
- // M1-3: wake dependents of the completed task. The maintenance path above
2238
- // only assigns to the completing session; dependents may be claimable by
2239
- // other idle sessions, so run a full queue trigger when any are waiting.
2240
- const completedTaskId = completedTaskForLedger?.id;
2241
- if (completedTaskId && hasPendingDependents(args.meshId, completedTaskId)) {
2242
- setImmediate(() => {
2243
- triggerMeshQueue(components, args.meshId).catch((e: any) => {
2244
- LOG.warn('MeshQueue', `Dependent wake after task ${completedTaskId} failed: ${e?.message || e}`);
2245
- });
2246
- });
2247
- }
2248
- }
2249
- } else if (args.event === 'agent:ready') {
2250
- const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
2251
- const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
2252
- const providerType = readNonEmptyString(args.metadataEvent.providerType);
2253
- const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
2254
- const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
2255
- const workerResult = readWorkerResultMetadata(args.metadataEvent);
2256
- const hasCompletionEvidence = !!finalSummary || !!workerResult;
2257
- if (sessionId && hasCompletionEvidence) {
2258
- completedTaskForLedger = markSessionTerminal(sessionId, 'completed');
2259
- if (completedTaskForLedger) {
2260
- try {
2261
- appendLedgerEntry(args.meshId, {
2262
- kind: 'task_completed',
2263
- nodeId: nodeId || undefined,
2264
- sessionId,
2265
- providerType: providerType || undefined,
2266
- payload: {
2267
- event: args.event,
2268
- nodeLabel: args.nodeLabel,
2269
- taskId: completedTaskForLedger.id,
2270
- completedViaReady: true,
2271
- providerSessionId,
2272
- finalSummary,
2273
- workerResult,
2274
- evidence: buildTaskCompletionEvidence({
2275
- event: 'agent:ready',
2276
- nodeId,
2277
- sessionId,
2278
- providerType: providerType || undefined,
2279
- providerSessionId,
2280
- finalSummary,
2281
- workerResult,
2282
- }),
2283
- },
2284
- });
2285
- } catch (e: any) {
2286
- LOG.warn('MeshLedger', `Failed to record task_completed from ready: ${e?.message || e}`);
2287
- }
2288
- }
2289
- }
2290
-
2291
- if (sessionId && nodeId && providerType) {
2292
- sweepExpiredRemoteIdleSessions();
2293
- try {
2294
- MeshRuntimeStore.getInstance().setRemoteIdleSession(nodeId, sessionId, providerType, Date.now() + REMOTE_IDLE_SESSION_TTL_MS);
2295
- } catch { /* best-effort */ }
2296
- setImmediate(() => {
2297
- maybeAutoFastForwardIdleNode(components, { meshId: args.meshId, nodeId, sessionId, providerType })
2298
- .finally(() => {
2299
- try {
2300
- const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
2301
- if (assigned) MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
2302
- } catch (e: any) {
2303
- LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${nodeId}: ${e?.message || e}`);
2304
- }
2305
- });
2306
- });
2307
- }
2308
- } else if (args.event === 'agent:generating_started') {
2309
- const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
2310
- const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
2311
- if (sessionId && nodeId) {
2312
- try {
2313
- MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
2314
- } catch { /* best-effort */ }
2315
- }
2316
- if (sessionId) {
2317
- // CANON-B: a generating_started that echoes its taskId acks exactly the dispatch
2318
- // and the delivery for THAT task — not every in-flight dispatch/delivery on the
2319
- // session. A session that already holds a freshly-dispatched (still 'dispatched')
2320
- // sibling must keep that row 'dispatched' so its own confirm can match it; acking
2321
- // by session would mark it 'acked' prematurely and hide a genuine non-delivery.
2322
- const startedTaskId = readNonEmptyString(args.metadataEvent.taskId) || undefined;
2323
- // WARMUPGAP: only ack a dispatch row when the event names its task, or the session
2324
- // currently holds an active assignment. A no-taskId generating_started from an
2325
- // unassigned session is a pre-assignment warmup — the session_id fallback would ack a
2326
- // sibling/stale dispatch row this event does not own, marking it 'acked' prematurely and
2327
- // hiding a genuine non-delivery. Skip the dispatch ack for that ghost case (the delivery
2328
- // acks below are bound to actual deliveries and stay a no-op for a warmup session).
2329
- if (startedTaskId || sessionHasActiveAssignment(args.meshId, sessionId)) {
2330
- updateDirectDispatchStatus(args.meshId, sessionId, 'acked', startedTaskId);
2331
- }
2332
- const activeDeliveries = ((): { id: string; taskId: string | null }[] => {
2333
- try { return MeshRuntimeStore.getInstance().getActiveSessionDeliveries(args.meshId, sessionId); }
2334
- catch { return []; }
2335
- })();
2336
- const deliveriesToAck = startedTaskId
2337
- ? activeDeliveries.filter(d => d.taskId === startedTaskId)
2338
- : activeDeliveries;
2339
- for (const d of deliveriesToAck) {
2340
- updateSessionDeliveryStatus(d.id, 'acked');
2341
- }
2342
- }
2343
- } else if (args.event === 'agent:stopped') {
2344
- const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
2345
- const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
2346
- if (sessionId && nodeId) {
2347
- try {
2348
- MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
2349
- } catch { /* best-effort */ }
2350
- }
2351
- if (sessionId) {
2352
- // CANON-B: prefer the echoed taskId; session heuristic is the fallback.
2353
- directDispatchTaskIdForLedger = readNonEmptyString(args.metadataEvent.taskId)
2354
- || resolveActiveDirectDispatchTaskId(args.meshId, sessionId);
2355
- completedTaskForLedger = markSessionTerminal(sessionId, 'failed');
2356
- }
2357
- }
2358
-
2359
- const ledgerKind = EVENT_TO_LEDGER_KIND[args.event];
2360
- if (ledgerKind) {
2361
- try {
2362
- const ledgerNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined;
2363
- const ledgerSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined;
2364
- const ledgerProviderType = readNonEmptyString(args.metadataEvent.providerType) || undefined;
2365
- const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
2366
- const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
2367
- const workerResult = readWorkerResultMetadata(args.metadataEvent);
2368
- const completionEvidence = ledgerKind === 'task_completed' && ledgerNodeId && ledgerSessionId
2369
- ? buildTaskCompletionEvidence({
2370
- event: 'agent:generating_completed',
2371
- nodeId: ledgerNodeId,
2372
- sessionId: ledgerSessionId,
2373
- providerType: ledgerProviderType,
2374
- providerSessionId,
2375
- finalSummary,
2376
- workerResult,
2377
- })
2378
- : undefined;
2379
- appendLedgerEntry(args.meshId, {
2380
- kind: ledgerKind,
2381
- nodeId: ledgerNodeId,
2382
- sessionId: ledgerSessionId,
2383
- providerType: ledgerProviderType,
2384
- payload: {
2385
- event: args.event,
2386
- nodeLabel: args.nodeLabel,
2387
- // Fix B: fall back to the direct-dispatch taskId when no work-queue row
2388
- // matched, so the terminal entry is attributable in mesh task-stats
2389
- // (otherwise the direct task shows status='unknown' / terminalKind=null).
2390
- taskId: completedTaskForLedger?.id || directDispatchTaskIdForLedger || undefined,
2391
- providerSessionId,
2392
- finalSummary,
2393
- workerResult,
2394
- completionDiagnostic: args.metadataEvent.completionDiagnostic && typeof args.metadataEvent.completionDiagnostic === 'object'
2395
- ? args.metadataEvent.completionDiagnostic
2396
- : undefined,
2397
- evidence: completionEvidence,
2398
- // B2: evidenceLevel lets coordinator know when completion evidence is insufficient.
2399
- ...(completionEvidence
2400
- ? completionEvidence.workerResult.source === 'default'
2401
- ? { evidenceLevel: 'insufficient', reviewRecommended: true }
2402
- : { evidenceLevel: 'sufficient' }
2403
- : {}),
2404
- },
2405
- });
2406
- } catch (e: any) {
2407
- LOG.warn('MeshLedger', `Failed to record ${ledgerKind}: ${e?.message || e}`);
2408
- }
2409
- }
2410
-
2411
- let recoveryContext: SessionRecoveryContext | null = null;
2412
- if (args.event === 'agent:stopped') {
2413
- try {
2414
- const mesh = getMesh(args.meshId);
2415
- const maxRetries = mesh?.policy?.maxTaskRetries ?? 1;
2416
-
2417
- recoveryContext = getSessionRecoveryContext(args.meshId, {
2418
- sessionId: resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined,
2419
- nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined,
2420
- maxRetries,
2421
- });
2422
- recoveryContext.failedProviderType = readNonEmptyString(args.metadataEvent.providerType) || null;
2423
-
2424
- if (recoveryContext.retryRecommended && recoveryContext.consecutiveNodeFailures > 0) {
2425
- appendLedgerEntry(args.meshId, {
2426
- kind: 'recovery_attempted',
2427
- nodeId: recoveryContext.failedNodeId || undefined,
2428
- sessionId: recoveryContext.failedSessionId || undefined,
2429
- providerType: recoveryContext.failedProviderType || undefined,
2430
- payload: {
2431
- consecutiveFailures: recoveryContext.consecutiveNodeFailures,
2432
- taskAttemptCount: recoveryContext.taskAttemptCount,
2433
- retryRecommended: recoveryContext.retryRecommended,
2434
- advice: recoveryContext.advice,
2435
- },
2436
- });
2437
-
2438
- if (recoveryContext.lastTaskMessage && recoveryContext.failedNodeId && recoveryContext.failedProviderType) {
2439
- const autoNodeId = recoveryContext.failedNodeId;
2440
- try {
2441
- const task = enqueueTask(args.meshId, recoveryContext.lastTaskMessage, {
2442
- targetNodeId: autoNodeId
2443
- });
2444
- LOG.info('MeshRecovery', `Auto-requeued failed task: ${task.id} for node ${autoNodeId}`);
2445
-
2446
- const node = mesh?.nodes.find((n: any) => meshNodeIdMatches(n, autoNodeId));
2447
- if (node) {
2448
- components.cliManager.handleCliCommand('launch_cli', {
2449
- cliType: recoveryContext.failedProviderType,
2450
- dir: node.workspace,
2451
- settings: {
2452
- role: 'worker',
2453
- meshNodeFor: args.meshId,
2454
- meshNodeId: node.id,
2455
- spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
2456
- // Coordinator-dispatched recovery relaunch: same auto-approve
2457
- // policy as the primary worker launch path.
2458
- autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
2459
- launchedByCoordinator: true,
2460
- }
2461
- }).catch((e: any) => LOG.error('MeshRecovery', `Failed to auto-relaunch session for ${node.id}: ${e?.message}`));
2462
- }
2463
- } catch (e: any) {
2464
- LOG.warn('MeshRecovery', `Failed to execute auto-recovery: ${e?.message}`);
2465
- }
2466
- }
2467
- }
2468
-
2469
- LOG.info('MeshRecovery', `Recovery context for ${args.nodeLabel}: ${recoveryContext.advice}`);
2470
- } catch (e: any) {
2471
- LOG.warn('MeshRecovery', `Failed to build recovery context: ${e?.message || e}`);
2472
- }
2473
- }
2474
-
2475
- const messageText = buildMeshSystemMessage({
2476
- event: args.event,
2477
- nodeLabel: args.nodeLabel,
2478
- metadataEvent: args.metadataEvent,
2479
- recoveryContext,
2480
- });
2481
- if (!messageText) {
2482
- // Lifecycle events that carry no coordinator-facing message (agent:ready /
2483
- // agent:generating_started) still drive the remote-claim state machine: the
2484
- // coordinator's agent:ready branch above runs setRemoteIdleSession +
2485
- // tryAssignQueueTask, and agent:generating_started clears the remote-idle entry.
2486
- // For a LOCAL worker whose coordinator is a REMOTE daemon those side effects ran
2487
- // on the wrong daemon (this worker's empty queue / store), so the coordinator never
2488
- // learns the auto-launched session went idle and re-auto-launches it forever
2489
- // (queue task stuck pending). Queue the silent event so the coordinator pulls it
2490
- // (PHASE 1 pullRemoteNodeQueues → handleMeshForwardEvent) and re-runs the claim on
2491
- // the daemon that actually owns the queue. Gate strictly on a present, REMOTE
2492
- // coordinator daemon id: a co-located worker already ran the claim on the right
2493
- // daemon, and a coordinator processing a *pulled* event has no sourceSession so
2494
- // workerCoordinatorDaemonId is empty — neither re-queues, so there is no loop.
2495
- const isSilentClaimRelevantEvent = args.event === 'agent:ready' || args.event === 'agent:generating_started';
2496
- const coordinatorIsRemote = !!workerCoordinatorDaemonId
2497
- && !resolveCoordinatorDrainDaemonIds(components).includes(workerCoordinatorDaemonId);
2498
- if (!(isSilentClaimRelevantEvent && coordinatorIsRemote)) {
2499
- return { success: false, error: 'unsupported mesh event' };
2500
- }
2501
- }
2502
-
2503
- // ── Queue-only delivery (single-model: queue + periodic poll) ──────────────
2504
- // Every mesh coordinator event — terminal or not, local-coordinator or
2505
- // remote — is persisted to the pending-events queue (SQLite + JSONL) and
2506
- // NOTHING is pushed here. The old spontaneous-forward paths were removed:
2507
- // - F1 remote P2P `mesh_forward_event` dispatch (network/stamp-dependent,
2508
- // silently dropped on P2P failure or missing meshCoordinatorDaemonId)
2509
- // - F3 live-CLI PTY `send_message` fire-and-forget inject (silently
2510
- // dropped when the coordinator was generating)
2511
- // Delivery to a live CLI coordinator now happens via setupMeshReconcileLoop,
2512
- // which drains this queue on a fixed interval and injects into the coordinator
2513
- // only when it is idle. A pure stdio MCP (LLM) coordinator — which has no live
2514
- // CLI session to inject into — drains the queue itself when it calls a mesh
2515
- // tool (mesh_status / mesh_read_chat). Either way the queue is the single
2516
- // source of truth and the only thing this function writes to.
2517
- //
2518
- // targetCoordinatorDaemonId scopes the event to a specific coordinator daemon
2519
- // (unicast) when the worker carries one, so the reconcile loop on the right
2520
- // daemon drains it and other daemons skip it. Absent → broadcast/backfill.
2521
- const pendingEvent = {
2522
- event: args.event,
2523
- meshId: args.meshId,
2524
- nodeLabel: args.nodeLabel,
2525
- nodeId: args.nodeId || undefined,
2526
- workspace: readNonEmptyString(args.metadataEvent.workspace)
2527
- || readNonEmptyString(args.metadataEvent.workspaceName),
2528
- metadataEvent: {
2529
- ...enrichedMetadataEvent,
2530
- ...(recoveryContext ? { recoveryContext } : {}),
2531
- // Stash the coordinator session id INSIDE metadataEvent too, so it survives the
2532
- // P2P relay serialization (buildForwardPayloadFromPending spreads metadata; the
2533
- // handleMeshForwardEvent whitelist reads it back) — a top-level field alone would
2534
- // be dropped when the event crosses a machine boundary.
2535
- ...(workerCoordinatorSessionId ? { meshCoordinatorSessionId: workerCoordinatorSessionId } : {}),
2536
- },
2537
- // Silent lifecycle events (agent:ready / agent:generating_started) carry no
2538
- // coordinator message; they are queued only so the coordinator re-runs the
2539
- // remote-claim state machine on pull. injectPendingIntoCoordinator skips
2540
- // entries without a coordinatorMessage, so a live CLI coordinator is not spammed.
2541
- ...(messageText ? { coordinatorMessage: messageText } : {}),
2542
- queuedAt: Date.now(),
2543
- ...(workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}),
2544
- // Top-level session anchor for the local PHASE 2 strict-match on the coordinator
2545
- // daemon. Absent → daemon-level broadcast (legacy / single-coordinator path).
2546
- ...(workerCoordinatorSessionId ? { targetCoordinatorSessionId: workerCoordinatorSessionId } : {}),
2547
- };
2548
- if (queuePendingMeshCoordinatorEvent(pendingEvent)) {
2549
- LOG.info('MeshEvents', `Queued ${args.event} for coordinator (mesh ${args.meshId}${workerCoordinatorDaemonId ? `, coordinator daemon ${workerCoordinatorDaemonId}` : ''}${workerCoordinatorSessionId ? `, coordinator session ${workerCoordinatorSessionId}` : ''})`);
2550
- // EVTTRACE: event persisted to the coordinator pending queue (awaiting reconcile drain).
2551
- traceMeshEventStage('queued', traceCtx, workerCoordinatorDaemonId ? `coordinatorDaemon=${workerCoordinatorDaemonId}` : 'broadcast');
2552
- } else {
2553
- // EVTTRACE: queue rejected the event (dedup at queue time / persistence guard).
2554
- traceMeshEventDrop('queue_dedup', traceCtx);
2555
- }
2556
- return { success: true, forwarded: 0 };
2557
- }
2558
-
2559
- // Reconstruct the metadataEvent that injectMeshSystemMessage consumes from a forwarded
2560
- // (cross-machine) mesh event. The remote relay hop arrives as a flat payload, NOT the
2561
- // original provider event object, so this whitelists the fields the coordinator-side
2562
- // pipeline reads and re-projects them. Kept pure + exported so the relay-path field
2563
- // preservation (esp. taskId) is unit-testable without driving injectMeshSystemMessage.
2564
- //
2565
- // IMPORTANT asymmetry: the LOCAL in-process forward path (onMeshCoordinatorEventForwarded)
2566
- // passes the whole event through as metadataEvent, so every field on the event survives
2567
- // there for free. This remote-only path must explicitly mirror each field it needs.
2568
- export function buildRelayMetadataEvent(payload: Record<string, unknown>): Record<string, unknown> {
2569
- const relayModalMessage = readNonEmptyString(payload.modalMessage);
2570
- const relayModalButtons = Array.isArray(payload.modalButtons)
2571
- ? (payload.modalButtons as unknown[]).filter((b): b is string => typeof b === 'string' && b.trim().length > 0)
2572
- : null;
2573
- return {
2574
- // Preserve the dispatch task id across the machine boundary. The `received` trace
2575
- // stage reads payload.taskId; without mirroring it here the rebuilt metadataEvent
2576
- // loses it, so injectMeshSystemMessage's traceCtx.taskId and the
2577
- // updateDirectDispatchStatus(eventTaskId) call go undefined — the EvtTrace
2578
- // queued/surfaced stages show task=- and the direct-dispatch ledger falls back to a
2579
- // session_id match (which can flip a sibling row). The local in-process forward path
2580
- // keeps event.taskId/meshActiveTaskId for free; this mirrors it for the remote relay.
2581
- // Same taskId/meshActiveTaskId ordering the local unroutable trace uses.
2582
- taskId: readNonEmptyString(payload.taskId) || readNonEmptyString(payload.meshActiveTaskId),
2583
- targetSessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.instanceId),
2584
- providerType: readNonEmptyString(payload.providerType),
2585
- providerSessionId: readNonEmptyString(payload.providerSessionId),
2586
- // Preserve the originating coordinator SESSION id across the machine boundary so
2587
- // the completion routes back to the exact coordinator session (multi-coordinator).
2588
- // buildForwardPayloadFromPending spreads the worker event's metadata, so the id
2589
- // arrives as payload.meshCoordinatorSessionId; the top-level targetCoordinatorSessionId
2590
- // is also accepted as a fallback. injectMeshSystemMessage re-derives the routing
2591
- // anchors from this. Absent → daemon-level fallback (version-skew safe).
2592
- meshCoordinatorSessionId: readNonEmptyString(payload.meshCoordinatorSessionId) || readNonEmptyString(payload.targetCoordinatorSessionId),
2593
- // Carry the session identity fields the worker provider event emits so the
2594
- // coordinator's mirror (updateMeshOwnedSession) gets a real workspace/title/
2595
- // settings. Without these the remote-relay hop reconstructs metadataEvent with
2596
- // an empty workspace, and the dashboard flaps to the generic
2597
- // "Terminal (Mesh Node)" title (and degrades the provider label) between live
2598
- // events and the periodic get_status_metadata snapshot. The local in-process
2599
- // forward path (onMeshCoordinatorEventForwarded) already preserves these; this
2600
- // mirrors them for the remote-only relay path.
2601
- workspace: readNonEmptyString(payload.workspace) || readNonEmptyString(payload.workspaceName),
2602
- workspaceName: readNonEmptyString(payload.workspaceName) || readNonEmptyString(payload.workspace),
2603
- sessionTitle: readNonEmptyString(payload.sessionTitle),
2604
- sessionStatus: readNonEmptyString(payload.sessionStatus),
2605
- sessionChatStatus: readNonEmptyString(payload.sessionChatStatus),
2606
- providerName: readNonEmptyString(payload.providerName),
2607
- ...(payload.sessionSettings && typeof payload.sessionSettings === 'object' && !Array.isArray(payload.sessionSettings) ? { sessionSettings: payload.sessionSettings } : {}),
2608
- finalSummary: readNonEmptyString(payload.finalSummary) || readNonEmptyString(payload.summary),
2609
- // T2: carry the worker's status-snapshot last-message preview across the machine
2610
- // boundary so a summary-less completion still surfaces the assistant reply in the
2611
- // coordinator's inbox mirror. resolveMeshSurfacedSessionPreview reads these
2612
- // (assistant-role only) when finalSummary is absent.
2613
- lastMessagePreview: readNonEmptyString(payload.lastMessagePreview),
2614
- lastMessageRole: readNonEmptyString(payload.lastMessageRole),
2615
- ...(payload.lastMessageAt !== undefined ? { lastMessageAt: payload.lastMessageAt } : {}),
2616
- jobId: readNonEmptyString(payload.jobId),
2617
- interactionId: readNonEmptyString(payload.interactionId),
2618
- status: readNonEmptyString(payload.status),
2619
- targetDaemonId: readNonEmptyString(payload.targetDaemonId),
2620
- startedAt: readNonEmptyString(payload.startedAt),
2621
- completedAt: readNonEmptyString(payload.completedAt),
2622
- retryOfJobId: readNonEmptyString(payload.retryOfJobId),
2623
- ...(relayModalMessage ? { modalMessage: relayModalMessage } : {}),
2624
- ...(relayModalButtons && relayModalButtons.length > 0 ? { modalButtons: relayModalButtons } : {}),
2625
- ...(payload.result && typeof payload.result === 'object' && !Array.isArray(payload.result) ? { result: payload.result } : {}),
2626
- ...(payload.completionDiagnostic && typeof payload.completionDiagnostic === 'object' && !Array.isArray(payload.completionDiagnostic) ? { completionDiagnostic: payload.completionDiagnostic } : {}),
2627
- ...(payload.workerResult && typeof payload.workerResult === 'object' && !Array.isArray(payload.workerResult) ? { workerResult: payload.workerResult } : {}),
2628
- ...(payload.meshWorkerResult && typeof payload.meshWorkerResult === 'object' && !Array.isArray(payload.meshWorkerResult) ? { meshWorkerResult: payload.meshWorkerResult } : {}),
2629
- ...(payload.structuredResult && typeof payload.structuredResult === 'object' && !Array.isArray(payload.structuredResult) ? { structuredResult: payload.structuredResult } : {}),
2630
- ...(payload.timestamp !== undefined ? { timestamp: payload.timestamp } : {}),
2631
- intentional: payload.intentional === true,
2632
- intentionalStop: payload.intentionalStop === true,
2633
- operatorCleanup: payload.operatorCleanup === true,
2634
- reason: readNonEmptyString(payload.reason),
2635
- stopReason: readNonEmptyString(payload.stopReason),
2636
- cleanupReason: readNonEmptyString(payload.cleanupReason),
2637
- source: readNonEmptyString(payload.source),
2638
- };
2639
- }
2640
-
2641
- export function handleMeshForwardEvent(components: DaemonComponents, payload: Record<string, unknown>) {
2642
- const eventName = readNonEmptyString(payload.event);
2643
- if (!isMeshCoordinatorEvent(eventName)) {
2644
- return { success: false, error: 'unsupported mesh event' };
2645
- }
2646
- const nodeId = readNonEmptyString(payload.nodeId);
2647
- const workspace = readNonEmptyString(payload.workspace);
2648
-
2649
- // The fallback worker-forward path (forwardUnresolvedDelegateEvent) cannot resolve a
2650
- // mesh id locally on the remote worker, so it forwards the event with nodeId +
2651
- // workspace only. The coordinator hosting the mesh CAN resolve it. Two recovery
2652
- // paths, in order:
2653
- // 1) workspace → mesh (fast path; cached repoIdentity lookup), then
2654
- // 2) nodeId → mesh (deterministic backstop; scans hosted meshes for the node).
2655
- // Workspace recovery alone was unreliable — a worktree clone whose repoIdentity
2656
- // differs, or a transient cache miss, left the reconcile retry permanently rejected
2657
- // ("meshId required") so the worker's completion never surfaced to the coordinator.
2658
- // The nodeId is a stable coordinator-side fact and resolves timing-independently.
2659
- const meshId = readNonEmptyString(payload.meshId)
2660
- || (workspace ? readNonEmptyString(getCachedMeshByWorkspace(workspace)?.id) : '')
2661
- || recoverMeshIdByNodeId(nodeId);
2662
- if (!meshId) {
2663
- // EVTTRACE: forwarded event rejected at receive — no meshId could be resolved
2664
- // (no payload.meshId, no workspace→mesh, no nodeId→mesh). Observation only.
2665
- traceMeshEventDrop('meshId_required', {
2666
- taskId: payload.taskId,
2667
- sessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId),
2668
- nodeId,
2669
- event: eventName,
2670
- }, workspace ? `workspace=${workspace} unresolved` : 'no workspace/nodeId');
2671
- return { success: false, error: 'meshId required' };
2672
- }
2673
- // EVTTRACE: forwarded event accepted at receive (meshId resolved).
2674
- traceMeshEventStage('received', {
2675
- taskId: payload.taskId,
2676
- sessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId),
2677
- nodeId,
2678
- meshId,
2679
- event: eventName,
2680
- });
2681
- const nodeLabel = nodeId ? `Node '${nodeId}'` : workspace ? `Agent at ${workspace}` : 'Remote agent';
2682
-
2683
- return injectMeshSystemMessage(components, {
2684
- meshId,
2685
- nodeId,
2686
- nodeLabel,
2687
- event: eventName,
2688
- metadataEvent: buildRelayMetadataEvent(payload),
2689
- });
2690
- }
2691
-
2692
- // ---------------------------------------------------------------------------
2693
- // Per-coordinator forward serialization (P2P send-backpressure relief).
2694
- //
2695
- // When several workers finish at once, each completion runs forwardUnresolvedDelegate
2696
- // Event and fires its own `mesh_forward_event` push. Firing the whole burst
2697
- // concurrently dumps it into the single per-peer P2P DataChannel buffer in one tick,
2698
- // which starves the rpc_ack/rpc_res replies the same channel must carry — a
2699
- // coordinator's inbound `git_status` then times out even though the worker's own
2700
- // forward acks return in ~1s. To cap the concurrent burst we serialize the immediate
2701
- // pushes per coordinator: at most one push is in flight to a given coordinator at a
2702
- // time, the rest run in arrival order behind it. A lone event (idle lane) still
2703
- // dispatches immediately — only a genuine burst is paced. Durability is unchanged:
2704
- // every event is already persisted to the outbox before the push runs, so serializing
2705
- // only delays the best-effort fast path; PHASE 0 retry still covers any gap. This pairs
2706
- // with the DataChannel send-buffer gate in daemon-cloud's mesh manager (writeRequest),
2707
- // which is the hard guarantee; this throttle keeps the burst from piling up there.
2708
- interface CoordinatorForwardLane { tail: Promise<unknown>; depth: number; }
2709
- const coordinatorForwardLanes = new Map<string, CoordinatorForwardLane>();
2710
- function enqueueCoordinatorForwardPush(coordinatorDaemonId: string, run: () => Promise<unknown>): void {
2711
- let lane = coordinatorForwardLanes.get(coordinatorDaemonId);
2712
- if (!lane) { lane = { tail: Promise.resolve(), depth: 0 }; coordinatorForwardLanes.set(coordinatorDaemonId, lane); }
2713
- const wasIdle = lane.depth === 0;
2714
- lane.depth += 1;
2715
- const dec = (): void => { lane!.depth -= 1; };
2716
- if (wasIdle) {
2717
- // Idle lane → dispatch synchronously, so a lone completion (the common case) has
2718
- // ZERO added latency and the push call happens in-line. Only a genuine burst —
2719
- // events arriving while a push is still in flight — is paced (else branch).
2720
- lane.tail = Promise.resolve(run()).catch(() => {}).then(dec, dec);
2721
- } else {
2722
- // Burst: queue behind the in-flight push(es) in arrival order so the whole burst
2723
- // is not dumped into the shared DataChannel buffer at once. The tail is guarded
2724
- // so one rejecting push never wedges the lane for the next.
2725
- lane.tail = lane.tail.then(() => run()).catch(() => {}).then(dec, dec);
2726
- }
2727
- }
2728
-
2729
- // ---------------------------------------------------------------------------
2730
- // Worker-side fallback forward for unresolved-mesh delegates.
2731
- //
2732
- // A REMOTE worker daemon that is being P2P-remote-controlled by a coordinator is
2733
- // NOT a member of the coordinator's mesh — it has no local mesh record. So when its
2734
- // completion event reaches the forwarder, resolveWorkerDelegateRouting() resolves the
2735
- // coordinator anchor (meshCoordinatorDaemonId) from the worker envelope but cannot
2736
- // resolve the mesh id (neither meshNodeFor nor a workspace→mesh lookup yields one) and
2737
- // returns isDelegate=false / mesh_unresolved. Before this fallback the event was dropped
2738
- // (delivery_unroutable) and only recovered later when the coordinator happened to pull
2739
- // the worker's queue — which it can't, because the worker never queued an unroutable
2740
- // event. Live symptom: `WARN [MeshEvents] delivery_unroutable: ... mesh unresolved`.
2741
- //
2742
- // The fix: the routing object still carries coordinatorDaemonId. Forward the raw event
2743
- // straight to that coordinator daemon over P2P (mesh_forward_event). The coordinator
2744
- // hosts the mesh, so it recovers the mesh id by workspace in handleMeshForwardEvent and
2745
- // injects/queues it normally. meshId is intentionally omitted from the payload (the
2746
- // worker has none); workspace is the routing anchor the coordinator resolves from.
2747
- //
2748
- // No loop / no double-delivery:
2749
- // - This only fires on the WORKER (the coordinator-own session is rejected by the
2750
- // resolver before reaching here), and the coordinator merely injects — it does not
2751
- // re-enter this forwarder for the relayed event.
2752
- // - It fires only when the normal queue path did NOT run (isDelegate=false), so the
2753
- // event is never both queued locally and forwarded.
2754
- //
2755
- // Returns true when the event was durably accepted for delivery to the coordinator
2756
- // daemon (so the caller skips the delivery_unroutable diagnostic); false when no
2757
- // fallback was possible (no coordinator anchor / no dispatch transport).
2758
- //
2759
- // Durability: the directed push to the coordinator is the ONLY delivery route for an
2760
- // unresolved-mesh worker (it is in no mesh.node the coordinator can pull). So instead
2761
- // of a fire-and-forget push that drops on one transient P2P failure, the event is
2762
- // persisted to the worker-side outbox FIRST and only acked after a successful push.
2763
- // A best-effort immediate push keeps latency low on the happy path; a failed or
2764
- // un-acked push leaves the durable row for setupMeshReconcileLoop's PHASE 0 to retry.
2765
- function forwardUnresolvedDelegateEvent(
2766
- components: DaemonComponents,
2767
- routing: ReturnType<typeof resolveWorkerDelegateRouting>,
2768
- event: Record<string, unknown>,
2769
- ): boolean {
2770
- const coordinatorDaemonId = readNonEmptyString(routing.coordinatorDaemonId);
2771
- if (!coordinatorDaemonId) return false;
2772
- if (!components.dispatchMeshCommand) return false;
2773
-
2774
- const eventName = readNonEmptyString(event.event);
2775
- if (!eventName) return false;
2776
-
2777
- // Flat payload mirroring buildForwardPayloadFromPending / what handleMeshForwardEvent
2778
- // reads. nodeId/workspace come from the worker envelope so the coordinator can name and
2779
- // locate the node.
2780
- const payload: Record<string, unknown> = {
2781
- ...event,
2782
- event: eventName,
2783
- nodeId: readNonEmptyString(routing.nodeId) || readNonEmptyString(event.meshNodeId) || undefined,
2784
- workspace: readNonEmptyString(routing.workspace) || readNonEmptyString(event.workspace) || undefined,
2785
- };
2786
- // RECONCILE-MESHID-DROP: stamp meshId when the WORKER can resolve it (member node /
2787
- // live-session meshNodeFor). Historically omitted "because the worker can't resolve
2788
- // it", but for a member-hosted node a no_node_binding session's coordinator-side
2789
- // recovery (empty payload nodeId + workspace cache miss) fails and the retry is
2790
- // rejected "meshId required" forever. Resolving here makes the forward self-sufficient;
2791
- // when unresolvable even here it stays absent and the coordinator's own workspace/nodeId
2792
- // recovery still runs (unchanged), with the retry cap as the loop backstop.
2793
- const resolvedMeshId = resolveForwardEventMeshId(components, payload);
2794
- if (resolvedMeshId) payload.meshId = resolvedMeshId;
2795
-
2796
- // Self-addressed fallback: the resolved coordinator IS this daemon (a self-
2797
- // coordinating / single-node mesh, or a delegate whose coordinator anchor resolved
2798
- // to our own id). A cross-daemon mesh_forward_event to our own id is REFUSED by the
2799
- // dispatch self-dial guard ("route via the local router instead"), so persisting it
2800
- // to the outbox would only loop forever in PHASE 0's retry, never acked. Honour the
2801
- // guard's advice: route the event straight through the local receiver — the exact
2802
- // path the coordinator runs on receiving a remote push — and skip the outbox entirely.
2803
- const selfDaemonIds = resolveCoordinatorDrainDaemonIds(components);
2804
- if (selfDaemonIds.some(self => daemonIdsEquivalent(self, coordinatorDaemonId))) {
2805
- try {
2806
- handleMeshForwardEvent(components, payload);
2807
- LOG.info('MeshEvents', `Self-addressed unresolved-delegate ${eventName} routed via local router (coordinator ${coordinatorDaemonId} is self) — outbox skipped`);
2808
- } catch (e: any) {
2809
- LOG.warn('MeshEvents', `Local route of self-addressed unresolved-delegate ${eventName} failed: ${e?.message || e}`);
2810
- }
2811
- return true;
2812
- }
2813
-
2814
- // 1) Persist durably FIRST. Idempotent on fingerprint, so a re-fired completion
2815
- // does not duplicate the outbox row. If persistence fails we still attempt the
2816
- // push below (degrades to the old at-most-once behaviour rather than dropping
2817
- // the chance entirely).
2818
- const persisted = enqueueUnresolvedDelegateForward(coordinatorDaemonId, eventName, payload);
2819
- // EVTTRACE: unresolved-mesh worker persisted its completion to the outbox (no meshId
2820
- // available locally; coordinator will recover it on receive).
2821
- const fwdTraceCtx = {
2822
- taskId: (payload as Record<string, unknown>).taskId,
2823
- sessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId),
2824
- nodeId: readNonEmptyString(routing.nodeId) || readNonEmptyString(event.meshNodeId),
2825
- event: eventName,
2826
- };
2827
- traceMeshEventStage('outbox_enqueue', fwdTraceCtx, `coordinatorDaemon=${coordinatorDaemonId} meshId=absent`);
2828
-
2829
- // 2) Best-effort immediate push for low latency. On success, ack the outbox row so
2830
- // the retry loop won't re-send it. On failure, leave it queued — PHASE 0 retries.
2831
- traceMeshEventStage('forward_send', fwdTraceCtx, 'immediate push');
2832
- // Serialize per coordinator so a multi-worker completion burst is paced rather than
2833
- // dumped concurrently into the shared P2P DataChannel buffer (see coordinator
2834
- // ForwardLanes). dispatchMeshCommand was null-checked above; capture it for the
2835
- // deferred closure.
2836
- const dispatchMeshCommand = components.dispatchMeshCommand;
2837
- enqueueCoordinatorForwardPush(coordinatorDaemonId, () =>
2838
- Promise.resolve(dispatchMeshCommand(coordinatorDaemonId, 'mesh_forward_event', payload))
2839
- .then((result: any) => {
2840
- if (result && result.success === false) {
2841
- LOG.warn('MeshEvents', `Immediate forward of ${eventName} to coordinator ${coordinatorDaemonId} rejected (${readNonEmptyString(result.error) || 'no reason'}) — left queued for retry`);
2842
- traceMeshEventDrop('immediate_forward_rejected', fwdTraceCtx, readNonEmptyString(result.error) || 'no reason');
2843
- return;
2844
- }
2845
- // Acked. Mark the durable copy delivered so the retry loop skips it.
2846
- if (persisted) ackUnresolvedDelegateForwardByFingerprint(coordinatorDaemonId, eventName, payload);
2847
- })
2848
- .catch((e: any) => {
2849
- // Coordinator momentarily unreachable; the durable row stays queued and the
2850
- // reconcile loop retries it. Trace so the relay attempt is visible.
2851
- LOG.warn('MeshEvents', `Immediate forward of ${eventName} to coordinator ${coordinatorDaemonId} failed: ${e?.message || e} — left queued for retry`);
2852
- }));
2853
- LOG.info('MeshEvents', `Durably forwarded ${eventName} for unresolved-mesh worker at ${routing.workspace || '(no workspace)'} to coordinator daemon ${coordinatorDaemonId}`);
2854
- return true;
2855
- }
2856
-
2857
- // Ack a just-pushed outbox entry by re-deriving its row from the same coordinator +
2858
- // event + payload. We don't thread the row id back from enqueue (the immediate push is
2859
- // fire-then-ack), so locate it among the undrained entries by matching coordinator and
2860
- // the flat payload's forward identity. A miss is harmless — the retry loop's own
2861
- // receiver-side dedup suppresses a duplicate delivery.
2862
- function ackUnresolvedDelegateForwardByFingerprint(
2863
- coordinatorDaemonId: string,
2864
- eventName: string,
2865
- payload: Record<string, unknown>,
2866
- ): void {
2867
- const match = peekUnresolvedDelegateForwards().find(entry =>
2868
- daemonIdsEquivalent(entry.coordinatorDaemonId, coordinatorDaemonId)
2869
- && readNonEmptyString(entry.payload.event) === eventName
2870
- && readNonEmptyString(entry.payload.targetSessionId || entry.payload.sessionId || entry.payload.instanceId)
2871
- === readNonEmptyString(payload.targetSessionId || payload.sessionId || payload.instanceId)
2872
- && readNonEmptyString(entry.payload.workspace) === readNonEmptyString(payload.workspace),
2873
- );
2874
- if (match) ackUnresolvedDelegateForward(match.id);
2875
- }
2876
-
2877
- export function setupMeshEventForwarding(components: DaemonComponents) {
2878
- components.instanceManager.onEvent((event) => {
2879
- // --- Coordinator idle auto-flush (fast path) ---
2880
- // When a coordinator session becomes idle, immediately flush any pending
2881
- // coordinator events that accumulated while it was generating, rather than
2882
- // waiting up to one reconcile interval for setupMeshReconcileLoop to do it.
2883
- // Both paths drain the SAME queue via drainPendingMeshCoordinatorEvents,
2884
- // whose SQLite drained=1 marking is atomic — whichever fires first consumes
2885
- // the events and the other gets nothing, so there is no double-delivery.
2886
- // This runs before the delegate routing below so that coordinator-own idle
2887
- // transitions are handled first.
2888
- // Exception: a coordinator that is itself a direct-dispatch target still needs
2889
- // to go through delegate routing so that the dispatching coordinator receives a
2890
- // pendingCoordinatorEvents entry for the completion.
2891
- if (event.event === 'agent:ready' || event.event === 'agent:generating_completed') {
2892
- const flushInstanceId = readNonEmptyString(event.instanceId);
2893
- if (flushInstanceId) {
2894
- const flushSource = components.instanceManager.getInstance(flushInstanceId);
2895
- if (flushSource && flushSource.category === 'cli') {
2896
- const flushState = flushSource.getState();
2897
- const flushSettings = flushState.settings && typeof flushState.settings === 'object' ? flushState.settings as Record<string, unknown> : {};
2898
- const coordinatorMeshId = readNonEmptyString(flushSettings.meshCoordinatorFor);
2899
- if (coordinatorMeshId) {
2900
- const status = readNonEmptyString(flushState.status).toLowerCase();
2901
- if (status === 'idle') {
2902
- try {
2903
- // Drain with the daemon's full coordinator-id set (status id + machineId).
2904
- // The MCP layer stamps the prefixed status id (`standalone_<machineId>` /
2905
- // `daemon_<machineId>`) as the worker's meshCoordinatorDaemonId; draining
2906
- // with bare machineId alone would miss those unicast events. Mirrors
2907
- // resolveCoordinatorDaemonIds in mesh-reconcile-loop.
2908
- const drainDaemonIds = resolveCoordinatorDrainDaemonIds(components);
2909
- const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
2910
- if (pendingEvents.length > 0) {
2911
- LOG.info('MeshEvents', `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId} on coordinator idle`);
2912
- for (const pending of pendingEvents) {
2913
- if (!pending.coordinatorMessage) continue;
2914
- const forcePending = shouldForceInjectMeshEvent(pending.event);
2915
- flushSource.onEvent('send_message', {
2916
- input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
2917
- ...(forcePending ? { force: true } : {}),
2918
- });
2919
- }
2920
- }
2921
- } catch (e: any) {
2922
- LOG.warn('MeshEvents', `Failed to auto-flush pending coordinator events: ${e?.message || e}`);
2923
- }
2924
- }
2925
- // Skip delegate routing unless this coordinator session is itself
2926
- // a direct-dispatch target — in that case fall through so the
2927
- // dispatching coordinator gets a pendingCoordinatorEvents entry.
2928
- let hasDirectDispatch = false;
2929
- try {
2930
- hasDirectDispatch =
2931
- getActiveDirectDispatches(coordinatorMeshId).some(d => d.sessionId === flushInstanceId)
2932
- || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, flushInstanceId);
2933
- } catch { /* best-effort */ }
2934
- if (!hasDirectDispatch) return;
2935
- }
2936
- }
2937
- }
2938
- }
2939
-
2940
- // --- Delegate event routing ---
2941
- if (!isMeshCoordinatorEvent(event.event)) return;
2942
-
2943
- const instanceId = readNonEmptyString(event.instanceId);
2944
- if (!instanceId) return;
2945
-
2946
- // R1: all session→node→mesh→coordinator interpretation is folded into the single
2947
- // resolveWorkerDelegateRouting() resolver. No stamp (meshNodeFor / meshNodeId /
2948
- // meshCoordinatorDaemonId / meshCoordinatorNodeId / launchedByCoordinator) is read
2949
- // here to make a routing decision — the resolver is the one authority, and the
2950
- // forwarder consumes its typed result only.
2951
- const routing = resolveWorkerDelegateRouting(components, instanceId, {
2952
- getMeshById: (meshId) => getMeshWithCache(components, meshId),
2953
- getMeshByWorkspace: (workspace) => getCachedMeshByWorkspace(workspace),
2954
- });
2955
- if (!routing.isDelegate) {
2956
- // Fallback: a REMOTE worker that isn't a member of the coordinator's mesh can't
2957
- // resolve a mesh id locally (mesh_unresolved), but it still carries the coordinator
2958
- // daemon anchor. Forward the event straight to that coordinator over P2P instead of
2959
- // dropping it — the coordinator hosts the mesh and recovers the id by workspace.
2960
- if (isUnroutableDelegateRejection(routing)
2961
- && forwardUnresolvedDelegateEvent(components, routing, event)) {
2962
- return;
2963
- }
2964
- // R4: a worker that presented a valid envelope but resolved to no mesh (and could
2965
- // not be fallback-forwarded — e.g. no coordinator anchor) used to be dropped
2966
- // silently. Leave a fail-loud diagnostic so the missing completion is traceable.
2967
- // Benign non-delegate rejections (not_cli / no_workspace / etc.) are no-ops inside
2968
- // recordUnroutableDelegateEvent.
2969
- // EVTTRACE: a delegate event that could not be routed AND could not be
2970
- // fallback-forwarded (no coordinator anchor). Only mesh_unresolved is a real
2971
- // drop; the benign non-delegate rejections are ordinary non-mesh traffic.
2972
- if (isUnroutableDelegateRejection(routing)) {
2973
- traceMeshEventDrop('unroutable', {
2974
- taskId: (event as Record<string, unknown>).meshActiveTaskId ?? (event as Record<string, unknown>).taskId,
2975
- sessionId: routing.sessionId,
2976
- nodeId: routing.nodeId,
2977
- event: event.event,
2978
- }, 'no coordinator anchor / mesh_unresolved');
2979
- }
2980
- recordUnroutableDelegateEvent(routing, event.event);
2981
- return;
2982
- }
2983
-
2984
- injectMeshSystemMessage(components, {
2985
- meshId: routing.meshId,
2986
- sourceInstanceId: instanceId,
2987
- nodeId: routing.nodeId,
2988
- nodeLabel: routing.nodeLabel,
2989
- event: event.event,
2990
- metadataEvent: event,
2991
- });
2992
- });
2993
- }
1
+ // Re-export barrel (A-4 split). This module was split into three domain files —
2
+ // classification predicates (mesh-event-classify), queue task assignment / dispatch /
3
+ // auto-launch (mesh-queue-assignment), and forward-event handling / relay metadata /
4
+ // dedup (mesh-event-forwarding). The barrel preserves the exact original public export
5
+ // surface so every existing importer is unchanged. The acyclic layering is:
6
+ // mesh-event-classify (leaf) mesh-queue-assignment mesh-event-forwarding
7
+
8
+ export {
9
+ isMeshCoordinatorEvent,
10
+ MESH_FORCE_INJECT_EVENTS,
11
+ shouldForceInjectMeshEvent,
12
+ } from './mesh-event-classify.js';
13
+
14
+ export {
15
+ __orderEligibleNodesForTests,
16
+ __resetIdleAutoFastForwardForTests,
17
+ activeReadonlyAssignedCount,
18
+ activeWriteAssignedCount,
19
+ triggerMeshQueue,
20
+ tryAssignQueueTask,
21
+ } from './mesh-queue-assignment.js';
22
+ export type { MeshQueueTriggerResult } from './mesh-queue-assignment.js';
23
+
24
+ export {
25
+ __resetMeshWorkspaceCacheForTests,
26
+ buildRelayMetadataEvent,
27
+ handleMeshForwardEvent,
28
+ resolveForwardEventMeshId,
29
+ setupMeshEventForwarding,
30
+ } from './mesh-event-forwarding.js';