@adhdev/daemon-core 0.9.82-rc.365 → 0.9.82-rc.367

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.
@@ -0,0 +1,639 @@
1
+ /**
2
+ * RF-ROUTER HIGH family — mesh aggregate status + review inbox.
3
+ *
4
+ * mesh_status: the coordinator's aggregate mesh render — resolves membership,
5
+ * gates the memory cache against pending coordinator events / explicit refresh,
6
+ * optionally fans out a direct peer-truth probe, then renders per-node health
7
+ * (live session records, local/remote/inline git truth, branch convergence) and
8
+ * folds in queue/ledger/missions/async-refine/historical-session/active-refine
9
+ * state. get_mesh_review_inbox: derives review-inbox items from node statuses +
10
+ * ledger and annotates each with a worktree git-diff summary. Extracted verbatim
11
+ * from executeDaemonCommand — only `this.*` router members became `ctx.*` and the
12
+ * relative dynamic-import paths were re-based one directory deeper.
13
+ */
14
+ import * as fs from 'fs';
15
+ import { hostname as osHostname } from 'os';
16
+ import { loadConfig } from '../../config/config.js';
17
+ import { getGitRepoStatus } from '../../git/git-status.js';
18
+ import {
19
+ normalizeMeshNodeId,
20
+ daemonIdsEquivalent,
21
+ } from '@adhdev/mesh-shared';
22
+ import { getPendingMeshCoordinatorEvents } from '../../mesh/mesh-events.js';
23
+ import { getRecentUnroutableDeliveries } from '../../mesh/mesh-routing.js';
24
+ import { normalizeMeshDaemonRole, resolveMeshHostStatus } from '../../mesh/mesh-host-ownership.js';
25
+ import { buildPreviewFreshness } from '../../mesh/preview-freshness.js';
26
+ import { buildMeshAsyncRefineJobs } from '../../mesh/mesh-refine-status.js';
27
+ import { partitionSessionHostRecords } from '../../session-host/runtime-surface.js';
28
+ import {
29
+ readStringValue,
30
+ readObjectRecord,
31
+ readBooleanValue,
32
+ readMeshNodeMachineId,
33
+ readMeshNodeHostname,
34
+ readProviderPriorityFromPolicy,
35
+ buildMeshNodeMachineIdentity,
36
+ buildMeshNodeDisplayLabel,
37
+ collectLiveMeshSessionRecords,
38
+ readLiveMeshNodeWorkspace,
39
+ summarizeMeshSessionRecord,
40
+ buildInlineMeshTransitGitStatus,
41
+ deriveMeshNodeHealthFromGit,
42
+ buildLivePeerGitConnection,
43
+ probeRemoteMeshGitStatusWithRetry,
44
+ recordInlineMeshDirectGitTruth,
45
+ persistNodeReporterPlatform,
46
+ applyCachedInlineMeshNodeStatus,
47
+ applyInlineMeshBranchConvergence,
48
+ finalizeMeshNodeStatus,
49
+ summarizeInlineMeshBranchConvergence,
50
+ buildHistoricalMeshSessions,
51
+ hydrateInlineMeshDirectTruth,
52
+ logRepoMeshStatusDebug,
53
+ summarizeRepoMeshStatusDebug,
54
+ MESH_DIRECT_PROBE_TIMEOUT_MS,
55
+ MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS,
56
+ } from '../router.js';
57
+ import type { HighFamilyContext, HighFamilyHandler } from './types.js';
58
+
59
+ export const meshStatusHandlers: Record<string, HighFamilyHandler> = {
60
+ mesh_status: async (ctx: HighFamilyContext, args: any) => {
61
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
62
+ if (!meshId) return { success: false, error: 'meshId required' };
63
+ try {
64
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
65
+ const mesh = meshRecord?.mesh;
66
+ if (!mesh) return { success: false, error: 'Mesh not found' };
67
+ const meshHost = resolveMeshHostStatus(mesh);
68
+
69
+ const refreshRequested = args?.refresh === true || args?.forceRefresh === true;
70
+ // Compact (default) elides each mission's full goal text from the
71
+ // payload — coordinators polling node health don't need every
72
+ // mission's multi-hundred-char goal repeated. verbose=true (or the
73
+ // explicit compact=false) restores full goals. Verbose bypasses the
74
+ // shared (compact) aggregate cache so a verbose call never poisons
75
+ // the compact cache and vice versa.
76
+ const verboseMissions = args?.verbose === true || args?.compact === false;
77
+ // See (B3) below: scope the peek to this daemon when the
78
+ // caller doesn't tell us, otherwise scoped events look
79
+ // missing and we falsely return a stale cache.
80
+ const peekScope = typeof args?.coordinatorDaemonId === 'string' && args.coordinatorDaemonId.trim()
81
+ ? args.coordinatorDaemonId.trim()
82
+ : (ctx.deps.statusInstanceId || undefined);
83
+ const pendingCoordinatorEventCount = getPendingMeshCoordinatorEvents(meshId, peekScope).length;
84
+ const hadAggregateCache = ctx.aggregateMeshStatusCache.has(meshId);
85
+ if (!refreshRequested && !verboseMissions && pendingCoordinatorEventCount === 0) {
86
+ const cachedStatus = ctx.getCachedAggregateMeshStatus(meshId, mesh, { requireDirectPeerTruth: args?.requireDirectPeerTruth === true });
87
+ if (cachedStatus) {
88
+ logRepoMeshStatusDebug('return_cached', {
89
+ meshId,
90
+ command: 'mesh_status',
91
+ refreshRequested,
92
+ summary: summarizeRepoMeshStatusDebug(cachedStatus),
93
+ });
94
+ return cachedStatus;
95
+ }
96
+ }
97
+ const refreshReason = refreshRequested
98
+ ? 'explicit_refresh'
99
+ : pendingCoordinatorEventCount > 0
100
+ ? 'pending_coordinator_events'
101
+ : hadAggregateCache
102
+ ? 'stale_pending_cache_refresh'
103
+ : 'cold_cache_miss';
104
+
105
+ const { getMeshQueueStats, getQueue } = await import('../../mesh/mesh-work-queue.js');
106
+ const queue = getQueue(meshId);
107
+ const queueSummary = getMeshQueueStats(meshId);
108
+
109
+ const { readLedgerEntries, getLedgerSummary } = await import('../../mesh/mesh-ledger.js');
110
+ const ledgerEntries = readLedgerEntries(meshId, { tail: 20 });
111
+ const asyncRefineLedgerEntries = readLedgerEntries(meshId, { tail: 100 });
112
+ const ledgerSummary = getLedgerSummary(meshId);
113
+ const sessionHostRecords = ctx.deps.sessionHostControl?.listSessions
114
+ ? await ctx.deps.sessionHostControl.listSessions().catch(() => [])
115
+ : [];
116
+ const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
117
+
118
+ const localMachineId = loadConfig().machineId || '';
119
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
120
+ // Shared probe gate for this mesh_status call: the bootstrap
121
+ // hydrate below and the per-node render loop further down both
122
+ // probe the same peers — route both through this cache so they
123
+ // dedup within the call and reuse recent results across calls.
124
+ const meshGitProbeCache = ctx.meshGitProbeCache;
125
+ const directTruth = requireDirectPeerTruth
126
+ ? await hydrateInlineMeshDirectTruth({
127
+ mesh,
128
+ meshSource: meshRecord.source,
129
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
130
+ getMeshPeerConnectionStatus: ctx.deps.getMeshPeerConnectionStatus,
131
+ statusInstanceId: ctx.deps.statusInstanceId,
132
+ localMachineId,
133
+ // Standing-state model: only an explicit refresh fans
134
+ // out a blocking peer git probe. Default loads return
135
+ // held truth so one slow peer can't block the graph.
136
+ probeRemotePeers: refreshRequested,
137
+ probeCache: meshGitProbeCache,
138
+ })
139
+ : {
140
+ directEvidenceCount: 0,
141
+ localConfirmedCount: 0,
142
+ peerAttemptedCount: 0,
143
+ peerConfirmedCount: 0,
144
+ standingEvidenceCount: 0,
145
+ unavailableNodeIds: [] as string[],
146
+ deadNodeIds: [] as string[],
147
+ };
148
+ // Default/cached loads may not attempt a remote peer probe yet; do not surface that as
149
+ // a direct mesh truth failure until an explicit probe attempt actually fails.
150
+ const passivePeerTruthNotAttempted = requireDirectPeerTruth
151
+ && !refreshRequested
152
+ && directTruth.directEvidenceCount > 0
153
+ && directTruth.peerAttemptedCount === 0;
154
+ const effectiveDirectTruth = passivePeerTruthNotAttempted
155
+ ? { ...directTruth, unavailableNodeIds: [] as string[] }
156
+ : directTruth;
157
+ const unavailableDirectTruthNodeIds = new Set(effectiveDirectTruth.unavailableNodeIds);
158
+ const unavailableNodesAreOnlyRemovedWorktrees = unavailableDirectTruthNodeIds.size > 0
159
+ && Array.isArray(mesh.nodes)
160
+ && mesh.nodes
161
+ .filter((node: any) => unavailableDirectTruthNodeIds.has(normalizeMeshNodeId(node) ?? ''))
162
+ .every((node: any) => node?.isLocalWorktree === true);
163
+ // Default (non-refresh) loads never hard-fail: held
164
+ // standing-state truth is returned and the graph renders
165
+ // immediately. The hard mesh_direct_peer_truth_unavailable
166
+ // failure is reserved for an explicit refresh that actually
167
+ // attempted a peer probe and could not confirm any evidence.
168
+ const directTruthSatisfied = !requireDirectPeerTruth
169
+ || !refreshRequested
170
+ || (effectiveDirectTruth.directEvidenceCount > 0 && (effectiveDirectTruth.unavailableNodeIds.length === 0 || unavailableNodesAreOnlyRemovedWorktrees));
171
+ if (requireDirectPeerTruth && refreshRequested && !directTruthSatisfied) {
172
+ const failureResult = {
173
+ success: false,
174
+ code: 'mesh_direct_peer_truth_unavailable',
175
+ error: 'Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct mesh_status probes succeed.',
176
+ sourceOfTruth: {
177
+ membership: meshRecord.source === 'inline_cache'
178
+ ? 'coordinator_inline_mesh_cache'
179
+ : meshRecord.source === 'local_config'
180
+ ? 'local_mesh_config'
181
+ : 'inline_bootstrap_snapshot',
182
+ coordinatorOwnsLiveTruth: false,
183
+ currentStatus: 'direct_peer_truth_unavailable',
184
+ directPeerTruth: {
185
+ required: true,
186
+ satisfied: false,
187
+ directEvidenceCount: directTruth.directEvidenceCount,
188
+ localConfirmedCount: directTruth.localConfirmedCount,
189
+ peerAttemptedCount: directTruth.peerAttemptedCount,
190
+ peerConfirmedCount: directTruth.peerConfirmedCount,
191
+ unavailableNodeIds: directTruth.unavailableNodeIds,
192
+ },
193
+ },
194
+ };
195
+ logRepoMeshStatusDebug('direct_truth_unavailable', {
196
+ meshId,
197
+ command: 'mesh_status',
198
+ refreshRequested,
199
+ meshSource: meshRecord.source,
200
+ directTruth,
201
+ });
202
+ return failureResult;
203
+ }
204
+ const directTruthUnavailableNodeIds = new Set(effectiveDirectTruth.unavailableNodeIds);
205
+ const coordinatorHostname = osHostname();
206
+ const selectedCoordinatorNodeId = readStringValue(
207
+ mesh.coordinator?.preferredNodeId,
208
+ normalizeMeshNodeId(mesh.nodes?.[0] as any),
209
+ );
210
+ const inlineCoordinatorNodeId = meshRecord?.inline && Array.isArray(mesh.nodes)
211
+ ? selectedCoordinatorNodeId
212
+ : undefined;
213
+ const refreshedAt = new Date().toISOString();
214
+ const nodeStatuses = [];
215
+ for (const [nodeIndex, node] of (mesh.nodes || []).entries()) {
216
+ const nodeId = normalizeMeshNodeId(node) ?? '';
217
+ const daemonId = readStringValue(node.daemonId);
218
+ const nodeMachineId = readMeshNodeMachineId(node as Record<string, unknown>);
219
+ const nodeHostname = readMeshNodeHostname(node as Record<string, unknown>);
220
+ const providerPriority = readProviderPriorityFromPolicy(node.policy);
221
+ const configuredCoordinatorNode = Boolean(
222
+ nodeId && selectedCoordinatorNodeId && nodeId === selectedCoordinatorNodeId,
223
+ );
224
+ const sparseConfiguredCoordinatorNode = configuredCoordinatorNode
225
+ && !daemonId
226
+ && !nodeMachineId
227
+ && !nodeHostname;
228
+ const isSelfNode = Boolean(
229
+ nodeId && inlineCoordinatorNodeId && nodeId === inlineCoordinatorNodeId,
230
+ ) || Boolean(
231
+ daemonId && (daemonIdsEquivalent(daemonId, localMachineId) || daemonIdsEquivalent(daemonId, ctx.deps.statusInstanceId)),
232
+ ) || Boolean(meshRecord?.inline && nodeIndex === 0)
233
+ || sparseConfiguredCoordinatorNode;
234
+ const machineIdentity = buildMeshNodeMachineIdentity(node as Record<string, unknown>, {
235
+ localMachineId,
236
+ localDaemonId: ctx.deps.statusInstanceId,
237
+ coordinatorHostname,
238
+ isSelfNode,
239
+ });
240
+ const status: Record<string, unknown> = {
241
+ nodeId,
242
+ machineLabel: buildMeshNodeDisplayLabel(node as Record<string, unknown>, nodeId, providerPriority),
243
+ labelSource: readStringValue(node.machineLabel, node.machine_label, node.machineNickname, node.machine_nickname, node.alias)
244
+ ? 'explicit_metadata'
245
+ : 'workspace_host_provider_context',
246
+ workspace: node.workspace,
247
+ repoRoot: node.repoRoot,
248
+ isLocalWorktree: node.isLocalWorktree,
249
+ worktreeBranch: node.worktreeBranch,
250
+ role: normalizeMeshDaemonRole(node.role) || (meshHost.hostNodeId && nodeId === meshHost.hostNodeId ? 'host' : undefined),
251
+ daemonId,
252
+ machineId: nodeMachineId || node.machineId,
253
+ machine: machineIdentity,
254
+ machineStatus: node.machineStatus,
255
+ health: 'unknown',
256
+ providers: node.providers || [],
257
+ providerPriority,
258
+ activeSessions: [],
259
+ activeSessionDetails: [],
260
+ launchReady: false,
261
+ };
262
+ if (isSelfNode) {
263
+ status.connection = {
264
+ perspective: 'selected_coordinator',
265
+ source: 'mesh_peer_status',
266
+ state: 'self',
267
+ transport: 'local',
268
+ reported: true,
269
+ reason: 'Selected coordinator daemon',
270
+ lastStateChangeAt: refreshedAt,
271
+ };
272
+ } else if (daemonId) {
273
+ const connection = ctx.deps.getMeshPeerConnectionStatus?.(daemonId);
274
+ status.connection = connection ?? {
275
+ perspective: 'selected_coordinator',
276
+ source: 'not_reported',
277
+ state: 'unknown',
278
+ transport: 'unknown',
279
+ reported: false,
280
+ reason: 'No live mesh peer telemetry reported by the selected coordinator yet.',
281
+ };
282
+ } else {
283
+ status.connection = {
284
+ perspective: 'selected_coordinator',
285
+ source: 'not_reported',
286
+ state: 'unknown',
287
+ transport: 'unknown',
288
+ reported: false,
289
+ reason: 'Node has no daemon id, so mesh transport cannot be reported from the selected coordinator.',
290
+ };
291
+ }
292
+ const matchedLiveSessionRecords = collectLiveMeshSessionRecords({
293
+ meshId,
294
+ node,
295
+ nodeId,
296
+ liveSessionRecords: liveMeshSessions,
297
+ allowCoordinatorSession: nodeId === selectedCoordinatorNodeId,
298
+ });
299
+ const workspace = readLiveMeshNodeWorkspace({
300
+ meshId,
301
+ nodeId,
302
+ liveSessionRecords: matchedLiveSessionRecords,
303
+ allowCoordinatorSession: nodeId === selectedCoordinatorNodeId,
304
+ }) || (typeof node.workspace === 'string' ? node.workspace : '');
305
+ status.workspace = workspace || node.workspace;
306
+ if (matchedLiveSessionRecords.length > 0) {
307
+ const sessionIds = matchedLiveSessionRecords
308
+ .map((record: any) => typeof record?.sessionId === 'string' ? record.sessionId : '')
309
+ .filter(Boolean);
310
+ const providerTypes = matchedLiveSessionRecords
311
+ .map((record: any) => readStringValue(record?.providerType))
312
+ .filter(Boolean) as string[];
313
+ status.activeSessions = sessionIds;
314
+ status.activeSessionDetails = matchedLiveSessionRecords.map(summarizeMeshSessionRecord);
315
+ if (providerTypes.length > 0) {
316
+ status.providers = Array.from(new Set([...(Array.isArray(status.providers) ? status.providers as string[] : []), ...providerTypes]));
317
+ }
318
+ }
319
+ if (workspace) {
320
+ if (!fs.existsSync(workspace)) {
321
+ // Workspace not local — prefer direct live inline truth, then attempt a P2P git probe.
322
+ const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
323
+ let remoteProbeApplied = false;
324
+ if (inlineTransitGit) {
325
+ status.git = inlineTransitGit;
326
+ status.health = inlineTransitGit.isGitRepo
327
+ ? deriveMeshNodeHealthFromGit(inlineTransitGit as unknown as Record<string, unknown>)
328
+ : 'degraded';
329
+ const connection = readObjectRecord(status.connection);
330
+ const connectionState = readStringValue(connection.state);
331
+ const connectionReported = readBooleanValue(connection.reported) ?? false;
332
+ if (!connectionReported || connectionState === 'unknown') {
333
+ status.connection = buildLivePeerGitConnection(connection, refreshedAt);
334
+ }
335
+ remoteProbeApplied = true;
336
+ } else if (refreshRequested && !isSelfNode && daemonId && ctx.deps.dispatchMeshCommand && !directTruthUnavailableNodeIds.has(nodeId)) {
337
+ // Only an explicit refresh fans out a blocking
338
+ // per-node git probe. On the default load a peer
339
+ // with no held truth falls through to
340
+ // gitProbePending below — the graph still renders.
341
+ // Bounded retry (shared with the bootstrap hydrate
342
+ // path), gated on the peer staying connected, so a
343
+ // slow TURN-relayed peer is recovered rather than
344
+ // dropped after a single timeout.
345
+ const runNodeProbe = () => probeRemoteMeshGitStatusWithRetry({
346
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
347
+ daemonId,
348
+ workspace,
349
+ timeoutMs: MESH_DIRECT_PROBE_TIMEOUT_MS,
350
+ retryTimeoutMs: MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS,
351
+ getConnection: ctx.deps.getMeshPeerConnectionStatus,
352
+ onConnection: connection => { status.connection = connection; },
353
+ });
354
+ // Same shared cache as the bootstrap hydrate path: within one
355
+ // mesh_status call this dedups the bootstrap probe against this
356
+ // per-node probe for the same peer, and across calls it reuses a
357
+ // recent result so the dashboard auto-retry loop can't restart a
358
+ // fresh refreshUpstream probe seconds apart.
359
+ const remoteGit = await meshGitProbeCache.probe(daemonId, workspace, runNodeProbe);
360
+ if (remoteGit) {
361
+ status.git = remoteGit;
362
+ status.health = remoteGit.isGitRepo
363
+ ? deriveMeshNodeHealthFromGit(remoteGit as unknown as Record<string, unknown>)
364
+ : 'degraded';
365
+ const connection = readObjectRecord(status.connection);
366
+ const connectionState = readStringValue(connection.state);
367
+ const connectionReported = readBooleanValue(connection.reported) ?? false;
368
+ if (!connectionReported || connectionState === 'unknown') {
369
+ status.connection = buildLivePeerGitConnection(connection, refreshedAt);
370
+ }
371
+ const reporter = recordInlineMeshDirectGitTruth(node, remoteGit, 'selected_coordinator_mesh_p2p_git');
372
+ persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
373
+ remoteProbeApplied = true;
374
+ }
375
+ }
376
+ if (!remoteProbeApplied) {
377
+ const connectionState = readStringValue((status.connection as any)?.state);
378
+ const pendingPeerGitProbe = !inlineTransitGit
379
+ && !isSelfNode
380
+ && !!daemonId
381
+ && (
382
+ readStringValue(status.machineStatus) === 'online'
383
+ || readStringValue(status.health) === 'online'
384
+ || connectionState === 'connecting'
385
+ || connectionState === 'connected'
386
+ || connectionState === 'unknown'
387
+ );
388
+ if (pendingPeerGitProbe) {
389
+ status.gitProbePending = true;
390
+ status.health = 'unknown';
391
+ }
392
+ if (applyCachedInlineMeshNodeStatus(
393
+ status,
394
+ node,
395
+ pendingPeerGitProbe ? { skipGit: true, skipError: true, skipHealth: true } : undefined,
396
+ )) {
397
+ applyInlineMeshBranchConvergence(mesh, node, status);
398
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
399
+ nodeStatuses.push(status);
400
+ continue;
401
+ }
402
+ if (meshRecord?.source === 'inline_cache' && !isSelfNode) {
403
+ applyInlineMeshBranchConvergence(mesh, node, status);
404
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
405
+ nodeStatuses.push(status);
406
+ continue;
407
+ }
408
+ }
409
+ } else {
410
+ try {
411
+ const gitStatus = await getGitRepoStatus(workspace, { timeoutMs: 10_000, refreshUpstream: true });
412
+ status.git = gitStatus;
413
+ const reporter = recordInlineMeshDirectGitTruth(node, gitStatus as unknown as Record<string, unknown>, 'selected_coordinator_local_git');
414
+ persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
415
+ if (gitStatus.isGitRepo) {
416
+ status.health = deriveMeshNodeHealthFromGit(gitStatus as unknown as Record<string, unknown>);
417
+ } else {
418
+ status.health = 'degraded';
419
+ if (gitStatus.error && !status.error) status.error = gitStatus.error;
420
+ }
421
+ } catch {
422
+ if (!applyCachedInlineMeshNodeStatus(status, node)) {
423
+ status.health = 'degraded';
424
+ }
425
+ }
426
+ }
427
+ } else {
428
+ applyCachedInlineMeshNodeStatus(status, node);
429
+ }
430
+ applyInlineMeshBranchConvergence(mesh, node, status);
431
+ finalizeMeshNodeStatus({ status, node, daemonId, isSelfNode });
432
+ nodeStatuses.push(status);
433
+ }
434
+
435
+ // (B3) Resolve the coordinator daemon scope for the peek.
436
+ // mesh_status is a read-only status query — it must not consume
437
+ // (drain) pending events as a side effect. Coordinators that see
438
+ // pendingCoordinatorEvents in the response are expected to call
439
+ // get_pending_mesh_events to explicitly drain them after processing.
440
+ const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === 'string' && args.coordinatorDaemonId.trim()
441
+ ? args.coordinatorDaemonId.trim()
442
+ : (ctx.deps.statusInstanceId || undefined);
443
+ const pendingCoordinatorEvents = getPendingMeshCoordinatorEvents(meshId, callerCoordinatorDaemonId);
444
+ // R4: surface recent fail-loud routing drops so a coordinator/operator can see
445
+ // that a worker completion was lost (envelope present, mesh unresolved) instead
446
+ // of it vanishing silently. Diagnostic-only — never cached (see omit below).
447
+ const unroutableDeliveries = getRecentUnroutableDeliveries();
448
+ const previewFreshness = (() => {
449
+ const localRepoRoot = nodeStatuses
450
+ .map((node: any) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace))
451
+ .find((candidate: string | undefined) => !!candidate && fs.existsSync(candidate));
452
+ return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : undefined;
453
+ })();
454
+ const asyncRefineJobs = buildMeshAsyncRefineJobs({
455
+ meshId,
456
+ ledgerEntries: asyncRefineLedgerEntries,
457
+ pendingEvents: [...pendingCoordinatorEvents],
458
+ });
459
+ const historicalSessions = buildHistoricalMeshSessions({
460
+ meshId,
461
+ nodes: mesh.nodes || [],
462
+ liveSessionRecords: liveMeshSessions,
463
+ });
464
+ const { getMeshStatusMissionSummaries } = await import('../../mesh/mesh-missions.js');
465
+ // withStats opts in to per-mission operational rollups (durations /
466
+ // retries) for the dashboard mission detail. The rollup scans a
467
+ // bounded ledger tail per mission, but only over the bounded set
468
+ // returned here (live + capped history), so the cost stays linear
469
+ // in visible missions rather than the whole mesh history.
470
+ const missions = getMeshStatusMissionSummaries(meshId, { verbose: verboseMissions, withStats: true });
471
+ const statusResult = {
472
+ success: true,
473
+ meshId: mesh.id,
474
+ meshName: mesh.name,
475
+ repoIdentity: mesh.repoIdentity,
476
+ defaultBranch: mesh.defaultBranch,
477
+ refreshedAt,
478
+ meshHost,
479
+ sourceOfTruth: {
480
+ membership: meshRecord?.source === 'inline_cache'
481
+ ? 'coordinator_inline_mesh_cache'
482
+ : meshRecord?.source === 'local_config'
483
+ ? 'local_mesh_config'
484
+ : 'inline_bootstrap_snapshot',
485
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
486
+ meshHost: {
487
+ owner: 'mesh_host_daemon',
488
+ localRole: meshHost.role,
489
+ hostDaemonId: meshHost.hostDaemonId,
490
+ hostNodeId: meshHost.hostNodeId,
491
+ hostAddress: meshHost.hostAddress,
492
+ },
493
+ ...(requireDirectPeerTruth ? {
494
+ currentStatus: directTruthSatisfied ? 'live_git_and_session_probes' : 'direct_peer_truth_unavailable',
495
+ directPeerTruth: {
496
+ required: true,
497
+ satisfied: directTruthSatisfied,
498
+ directEvidenceCount: effectiveDirectTruth.directEvidenceCount,
499
+ localConfirmedCount: effectiveDirectTruth.localConfirmedCount,
500
+ peerAttemptedCount: effectiveDirectTruth.peerAttemptedCount,
501
+ peerConfirmedCount: effectiveDirectTruth.peerConfirmedCount,
502
+ unavailableNodeIds: effectiveDirectTruth.unavailableNodeIds,
503
+ partialNodeFailures: effectiveDirectTruth.unavailableNodeIds,
504
+ },
505
+ } : {}),
506
+ historicalEvidenceOnly: ['recoveryHints', 'ledger.summary', 'queue.summary', 'historicalSessions'],
507
+ },
508
+ branchConvergenceSummary: summarizeInlineMeshBranchConvergence(nodeStatuses),
509
+ ...(previewFreshness ? { previewFreshness, deployFreshness: previewFreshness } : {}),
510
+ nodes: nodeStatuses,
511
+ queue: { tasks: queue, summary: queueSummary },
512
+ ledger: { entries: ledgerEntries, summary: ledgerSummary },
513
+ ...(missions.length > 0 ? { missions } : {}),
514
+ ...(asyncRefineJobs.length > 0 ? { asyncRefineJobs } : {}),
515
+ ...(historicalSessions ? { historicalSessions } : {}),
516
+ ...(pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {}),
517
+ ...(unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {}),
518
+ activeRefineJobs: Array.from(ctx.runningRefineJobs.values())
519
+ .filter(job => job.meshId === meshId)
520
+ .map(job => ({
521
+ jobId: job.jobId,
522
+ nodeId: job.targetNodeId,
523
+ workspace: job.workspace,
524
+ startedAt: job.startedAt,
525
+ status: job.status,
526
+ targetCoordinatorDaemonId: job.targetCoordinatorDaemonId,
527
+ })),
528
+ };
529
+ const { pendingCoordinatorEvents: _pendingCoordinatorEvents, unroutableDeliveries: _unroutableDeliveries, ...cacheableStatusResult } = statusResult as any;
530
+ // Verbose carries full mission goals; never store it in the shared
531
+ // (compact) aggregate cache or a later compact poll would return the
532
+ // heavy goals from cache. Return it without caching.
533
+ const rememberedStatus = verboseMissions
534
+ ? cacheableStatusResult
535
+ : ctx.rememberAggregateMeshStatus(meshId, cacheableStatusResult, refreshReason);
536
+ const returnedStatus = {
537
+ ...rememberedStatus,
538
+ ...(pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {}),
539
+ ...(unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {}),
540
+ };
541
+ logRepoMeshStatusDebug('return_live', {
542
+ meshId,
543
+ command: 'mesh_status',
544
+ refreshRequested,
545
+ refreshReason,
546
+ meshSource: meshRecord.source,
547
+ directTruth,
548
+ summary: summarizeRepoMeshStatusDebug(returnedStatus),
549
+ });
550
+ return returnedStatus;
551
+ } catch (e: any) {
552
+ return { success: false, error: e.message };
553
+ }
554
+ },
555
+
556
+ get_mesh_review_inbox: async (ctx: HighFamilyContext, args: any) => {
557
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
558
+ if (!meshId) return { success: false, error: 'meshId required' };
559
+ try {
560
+ const { deriveMeshReviewInboxItems } = await import('../../mesh/mesh-review-inbox.js');
561
+ const { readLedgerEntries } = await import('../../mesh/mesh-ledger.js');
562
+ const { getGitDiffSummary } = await import('../../git/git-diff.js');
563
+ const { existsSync } = await import('node:fs');
564
+
565
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
566
+ const mesh = meshRecord?.mesh;
567
+ if (!mesh) return { success: false, error: 'Mesh not found' };
568
+
569
+ // Ensure we have a fresh aggregate status so nodeStatuses carry
570
+ // computed fields (connection.state, branchConvergence, isLocalWorktree)
571
+ // that the raw mesh.nodes config objects don't have.
572
+ // When the caller provides an inlineMesh, prefer its nodes directly
573
+ // (they already carry the computed fields from the coordinator).
574
+ const inlineNodes = args?.inlineMesh && Array.isArray((args.inlineMesh as any)?.nodes)
575
+ ? (args.inlineMesh as any).nodes as Record<string, unknown>[]
576
+ : null;
577
+ let cachedStatus = !inlineNodes ? ctx.getCachedAggregateMeshStatus(meshId, mesh, {}) : null;
578
+ if (!cachedStatus && !inlineNodes) {
579
+ const freshStatus = await ctx.execute('mesh_status', {
580
+ meshId,
581
+ inlineMesh: args?.inlineMesh,
582
+ refresh: true,
583
+ }, 'get_mesh_review_inbox');
584
+ cachedStatus = (freshStatus?.success !== false) ? freshStatus : null;
585
+ }
586
+ const nodeStatuses: Record<string, unknown>[] = inlineNodes
587
+ ? inlineNodes
588
+ : Array.isArray(cachedStatus?.nodes)
589
+ ? cachedStatus.nodes as Record<string, unknown>[]
590
+ : Array.isArray(mesh.nodes)
591
+ ? mesh.nodes as Record<string, unknown>[]
592
+ : [];
593
+
594
+ const ledgerEntries = readLedgerEntries(meshId, { tail: 300 });
595
+ const derivation = deriveMeshReviewInboxItems({ nodes: nodeStatuses, ledgerEntries });
596
+
597
+ for (const item of derivation.items) {
598
+ const workspace = item.workspace;
599
+ if (!workspace || !existsSync(workspace)) continue;
600
+ const baseRef = item.defaultBranch
601
+ ? `origin/${item.defaultBranch}`
602
+ : 'origin/main';
603
+ try {
604
+ const diffResult = await getGitDiffSummary(workspace, { baseRef, maxFiles: 100 });
605
+ if (diffResult.isGitRepo) {
606
+ item.diffSummary = {
607
+ baseRef,
608
+ files: diffResult.files.map(f => ({
609
+ path: f.path,
610
+ status: f.status,
611
+ insertions: f.insertions,
612
+ deletions: f.deletions,
613
+ binary: f.binary,
614
+ oldPath: f.oldPath,
615
+ })),
616
+ totalFiles: diffResult.files.length,
617
+ totalInsertions: diffResult.totalInsertions,
618
+ totalDeletions: diffResult.totalDeletions,
619
+ truncated: diffResult.truncated,
620
+ ...(diffResult.error ? { error: diffResult.error } : {}),
621
+ };
622
+ }
623
+ } catch {
624
+ item.diffSummary = null;
625
+ }
626
+ }
627
+
628
+ return {
629
+ success: true,
630
+ meshId,
631
+ inbox: derivation.items,
632
+ remoteNodesExcluded: derivation.remoteNodesExcluded,
633
+ excludedRemoteNodeIds: derivation.excludedRemoteNodeIds,
634
+ };
635
+ } catch (e: any) {
636
+ return { success: false, error: e.message };
637
+ }
638
+ },
639
+ };