@adhdev/daemon-standalone 0.9.82-rc.99 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +86588 -43350
- package/dist/index.js.map +1 -1
- package/package.json +7 -5
- package/public/assets/index-DuHZKmcF.js +121 -0
- package/public/assets/index-p-ehiI_L.css +1 -0
- package/public/assets/{terminal-D46M5EWH.js → terminal-CqjiB824.js} +21 -21
- package/public/assets/vendor-B6OqYKvq.js +2776 -0
- package/public/index.html +3 -3
- package/public/snake.html +229 -0
- package/vendor/mcp-server/index.js +6539 -2572
- package/vendor/mcp-server/index.js.map +1 -1
- package/vendor/mcp-server/package.json +3 -2
- package/vendor/session-host-daemon/index.d.mts +0 -10
- package/vendor/session-host-daemon/index.d.ts +0 -10
- package/vendor/session-host-daemon/index.js +305 -196
- package/vendor/session-host-daemon/index.js.map +1 -1
- package/vendor/session-host-daemon/index.mjs +299 -188
- package/vendor/session-host-daemon/index.mjs.map +1 -1
- package/public/assets/index-Bso1b8Lh.css +0 -1
- package/public/assets/index-DaIkPFUd.js +0 -99
- package/public/assets/vendor-CgiI0UIA.js +0 -2745
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/tools/mesh-tools.ts","../src/transports/ipc.ts","../src/transports/mode.ts","../src/tools/chat-compact.ts","../src/tools/read-chat-polling-advisory.ts","../src/help.ts","../src/server.ts","../src/transports/local.ts","../src/transports/cloud.ts","../src/tools/list-sessions.ts","../src/tools/list-daemons.ts","../src/tools/read-chat.ts","../src/tools/read-chat-debug.ts","../src/tools/send-chat.ts","../src/tools/approve.ts","../src/tools/screenshot.ts","../src/tools/git-status.ts","../src/tools/git-log.ts","../src/tools/git-diff.ts","../src/tools/git-checkpoint.ts","../src/tools/git-push.ts","../src/tools/launch-session.ts","../src/tools/stop-session.ts","../src/tools/check-pending.ts"],"sourcesContent":["/**\n * @adhdev/mcp-server — CLI entry point\n *\n * Usage:\n * npx @adhdev/mcp-server # local mode (localhost:3847)\n * npx @adhdev/mcp-server --port 4000 # custom port\n * npx @adhdev/mcp-server --api-key adk_xxx # cloud mode\n * npx @adhdev/mcp-server --mode ipc --repo-mesh mesh_xxx # cloud daemon IPC mode\n */\n\nimport { buildMcpHelpText } from './help.js';\nimport { startMcpServer } from './server.js';\n\nexport function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): {\n mode: 'local' | 'cloud' | 'ipc';\n port?: number;\n password?: string;\n apiKey?: string;\n baseUrl?: string;\n meshId?: string;\n} {\n const args = argv.slice(2);\n let apiKey: string | undefined;\n let baseUrl: string | undefined;\n let port: number | undefined;\n let password: string | undefined;\n let meshId: string | undefined;\n let explicitMode: 'local' | 'cloud' | 'ipc' | undefined;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if ((arg === '--api-key' || arg === '-k') && args[i + 1]) {\n apiKey = args[++i];\n } else if (arg?.startsWith('--api-key=')) {\n apiKey = arg.slice('--api-key='.length);\n } else if (arg === '--base-url' && args[i + 1]) {\n baseUrl = args[++i];\n } else if (arg === '--mode' && args[i + 1]) {\n const value = String(args[++i]).trim();\n if (value === 'local' || value === 'cloud' || value === 'ipc') explicitMode = value;\n } else if (arg?.startsWith('--mode=')) {\n const value = arg.slice('--mode='.length).trim();\n if (value === 'local' || value === 'cloud' || value === 'ipc') explicitMode = value;\n } else if (arg === '--port' && args[i + 1]) {\n port = Number(args[++i]);\n } else if (arg?.startsWith('--port=')) {\n port = Number(arg.slice('--port='.length));\n } else if (arg === '--password' && args[i + 1]) {\n password = args[++i];\n } else if ((arg === '--repo-mesh' || arg === '--mesh') && args[i + 1]) {\n meshId = args[++i];\n } else if (arg?.startsWith('--repo-mesh=')) {\n meshId = arg.slice('--repo-mesh='.length);\n } else if (arg === '--help' || arg === '-h') {\n printHelp();\n process.exit(0);\n }\n }\n\n // Also accept env vars\n if (!apiKey && env.ADHDEV_API_KEY) apiKey = env.ADHDEV_API_KEY;\n if (!password && env.ADHDEV_PASSWORD) password = env.ADHDEV_PASSWORD;\n if (!meshId && env.ADHDEV_MESH_ID) meshId = env.ADHDEV_MESH_ID;\n if (!explicitMode && env.ADHDEV_MCP_TRANSPORT) {\n const value = env.ADHDEV_MCP_TRANSPORT.trim();\n if (value === 'local' || value === 'cloud' || value === 'ipc') explicitMode = value;\n }\n\n const mode = explicitMode || (apiKey ? 'cloud' : (meshId && env.ADHDEV_INLINE_MESH ? 'ipc' : 'local'));\n return { mode, port, password, apiKey, baseUrl, meshId };\n}\n\nfunction printHelp(): void {\n console.error(buildMcpHelpText());\n}\n\nstartMcpServer(parseArgs(process.argv)).catch((err) => {\n process.stderr.write(`[adhdev-mcp] Fatal: ${err?.message ?? err}\\n`);\n process.exit(1);\n});\n","/**\n * Mesh Tools — Mesh-scoped coordinator tools for Repo Mesh orchestration\n *\n * These tools wrap existing MCP transport operations but restrict targets\n * to mesh member nodes only. The coordinator uses these to delegate work\n * to agents across the mesh via natural conversation.\n *\n * 24 tools: mesh_status, mesh_list_nodes, mesh_enqueue_task, mesh_view_queue,\n * mesh_queue_cancel, mesh_queue_requeue, mesh_send_task, mesh_read_chat,\n * mesh_read_debug, mesh_launch_session, mesh_git_status,\n * mesh_fast_forward_node, mesh_checkpoint, mesh_approve,\n * mesh_clone_node, mesh_remove_node, mesh_refine_node,\n * mesh_refine_config_schema, mesh_validate_refine_config,\n * mesh_suggest_refine_config, mesh_refine_plan,\n * mesh_cleanup_sessions, mesh_task_history, mesh_reconcile_ledger\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { CloudTransport } from '../transports/cloud.js';\nimport { IpcTransport } from '../transports/ipc.js';\nimport { isLocalTransport } from '../transports/mode.js';\nimport type { McpTransport } from '../transports/mode.js';\nimport { compactChatPayload } from './chat-compact.js';\nimport { annotateRapidReadChatAdvisory } from './read-chat-polling-advisory.js';\nimport type { LocalMeshEntry, LocalMeshNodeEntry, MeshActiveWorkSummary, RepoMeshPolicy, RepoMeshRelatedRepo } from '@adhdev/daemon-core';\nimport {\n appendLedgerEntry,\n appendRemoteLedgerEntries,\n buildMeshActiveWork,\n buildMeshLedgerReconciliationEvidence,\n buildMeshLedgerReplicaEvidence,\n buildP2pRelayFailurePayload,\n cancelTask,\n classifyP2pRelayFailure,\n drainPendingMeshCoordinatorEvents,\n enqueueTask,\n getQueue,\n getLedgerSummary,\n getSessionRecoveryContext,\n isP2pRelayTransportFailure,\n readLedgerEntries,\n readLedgerSlice,\n requeueTask,\n validateMeshTaskModeRequest,\n} from '@adhdev/daemon-core';\n\nexport interface MeshContext {\n mesh: LocalMeshEntry;\n transport: McpTransport;\n /** Daemon ID for this local machine (local mode) */\n localDaemonId?: string;\n /** Machine Registry ID for this local machine */\n localMachineId?: string;\n /** Hostname of the daemon/MCP coordinator machine. */\n coordinatorHostname?: string;\n}\n\ntype MeshSessionProviderMetadata = {\n providerType: string;\n providerSessionId?: string;\n};\n\nconst meshSessionProviderMetadata = new Map<string, MeshSessionProviderMetadata>();\n\nconst ACTIVE_WORK_POLLING_BACKOFF_MS = 60_000;\n\ninterface MeshPollingGuidance {\n activeGeneratingWork: true;\n generatingCount: number;\n doNotPollBefore: string;\n eventSurface: 'pendingCoordinatorEvents';\n nextRecommendedAction: string;\n message: string;\n}\n\nfunction buildActiveWorkPollingGuidance(summary: MeshActiveWorkSummary, now = Date.now()): MeshPollingGuidance | undefined {\n if (!summary || summary.generatingCount <= 0) return undefined;\n return {\n activeGeneratingWork: true,\n generatingCount: summary.generatingCount,\n doNotPollBefore: new Date(now + ACTIVE_WORK_POLLING_BACKOFF_MS).toISOString(),\n eventSurface: 'pendingCoordinatorEvents',\n nextRecommendedAction: 'Wait for pendingCoordinatorEvents/completion events or an explicit user status request. After a terminal signal, call mesh_read_chat once with compact=true, then verify git state if repository changes were expected.',\n message: 'Do not repeatedly poll mesh_status/mesh_view_queue/mesh_read_chat while delegated work is generating; these snapshots rarely change until the worker emits a completion/status event.',\n };\n}\n\n// ─── Helpers ────────────────────────────────────\n\nfunction readString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\nfunction summarizeTaskMessage(message: string): { taskTitle: string; taskSummary: string } {\n const taskSummary = message.replace(/\\s+/g, ' ').trim();\n const taskTitle = taskSummary.length > 96 ? `${taskSummary.slice(0, 93)}...` : taskSummary;\n return { taskTitle: taskTitle || '(untitled task)', taskSummary };\n}\n\nfunction buildDirectTaskPayload(\n message: string,\n via: 'p2p_direct' | 'local_direct' | 'mesh_send_task',\n opts: {\n taskId: string;\n taskMode?: string;\n providerType?: string;\n targetSessionId?: string;\n },\n): Record<string, unknown> {\n const descriptor = summarizeTaskMessage(message);\n return {\n source: 'direct',\n via,\n taskId: opts.taskId,\n message,\n taskTitle: descriptor.taskTitle,\n taskSummary: descriptor.taskSummary,\n ...(opts.taskMode ? { taskMode: opts.taskMode } : {}),\n ...(opts.providerType ? { providerType: opts.providerType } : {}),\n ...(opts.targetSessionId ? { targetSessionId: opts.targetSessionId } : {}),\n };\n}\n\nfunction findNode(mesh: LocalMeshEntry, nodeId: string): LocalMeshNodeEntry {\n const node = mesh.nodes.find(n => n.id === nodeId);\n if (!node) throw new Error(`Node '${nodeId}' is not a member of mesh '${mesh.name}'`);\n return node;\n}\n\nconst DUPLICATE_DISPATCH_WINDOW_MS = 60_000;\nconst STALE_ASSIGNED_QUEUE_MS = 30 * 60_000;\nconst OLD_HISTORICAL_QUEUE_RECORD_MS = 7 * 24 * 60 * 60_000;\nconst ACTIVE_QUEUE_STATUSES = new Set(['pending', 'assigned']);\nconst HISTORICAL_QUEUE_STATUSES = new Set(['completed', 'failed', 'cancelled']);\ntype QueueViewMode = 'all' | 'active' | 'historical';\n\n/**\n * Refresh the MCP process's mesh snapshot from the daemon inline mesh cache.\n * This is required for status/list tools when a previous MCP process already\n * created or removed worktree nodes through clone_mesh_node/remove_mesh_node.\n */\nasync function refreshMeshFromDaemon(ctx: MeshContext): Promise<void> {\n if (!(ctx.transport instanceof IpcTransport)) return;\n try {\n const result = await (ctx.transport as IpcTransport).command('get_mesh', { meshId: ctx.mesh.id }) as any;\n if (!result?.success || !Array.isArray(result.mesh?.nodes)) return;\n const refreshedNodes = result.mesh.nodes\n .filter((n: any) => n?.id)\n .map((n: any) => n as LocalMeshNodeEntry);\n (ctx.mesh.nodes as LocalMeshNodeEntry[]).splice(0, ctx.mesh.nodes.length, ...refreshedNodes);\n ctx.mesh.updatedAt = result.mesh.updatedAt ?? ctx.mesh.updatedAt;\n } catch { /* refresh is best-effort; callers still report their original status/errors */ }\n}\n\nasync function syncCoordinatorDaemonMeshCache(ctx: MeshContext): Promise<void> {\n if (!(ctx.transport instanceof IpcTransport)) return;\n try {\n await (ctx.transport as IpcTransport).command('get_mesh', {\n meshId: ctx.mesh.id,\n inlineMesh: ctx.mesh,\n });\n } catch {\n /* cache sync is best-effort; the MCP process still keeps its local ctx.mesh copy */\n }\n}\n\nasync function findNodeWithRefresh(ctx: MeshContext, nodeId: string): Promise<LocalMeshNodeEntry> {\n const hit = ctx.mesh.nodes.find(n => n.id === nodeId);\n if (hit && !hit.isLocalWorktree) return hit;\n\n await refreshMeshFromDaemon(ctx);\n\n const refreshed = ctx.mesh.nodes.find(n => n.id === nodeId);\n if (!refreshed) throw new Error(`Node '${nodeId}' is not a member of mesh '${ctx.mesh.name}'`);\n return refreshed;\n}\n\nasync function findOptionalNodeWithRefresh(ctx: MeshContext, nodeId: string): Promise<LocalMeshNodeEntry | null> {\n const hit = ctx.mesh.nodes.find(n => n.id === nodeId);\n if (hit && !hit.isLocalWorktree) return hit;\n\n await refreshMeshFromDaemon(ctx);\n\n return ctx.mesh.nodes.find(n => n.id === nodeId) ?? null;\n}\n\nfunction hasRecentDuplicateDispatch(ctx: MeshContext, args: { node_id: string; session_id?: string; message: string }): { duplicate: boolean; entry?: any; source?: 'ledger' | 'queue' } {\n const now = Date.now();\n const normalizedMessage = args.message.trim();\n\n for (const task of getQueue(ctx.mesh.id)) {\n const timestamp = new Date(task.updatedAt || task.createdAt).getTime();\n if (!Number.isFinite(timestamp) || now - timestamp > DUPLICATE_DISPATCH_WINDOW_MS) continue;\n if (task.targetNodeId && task.targetNodeId !== args.node_id) continue;\n if (task.assignedNodeId && task.assignedNodeId !== args.node_id) continue;\n if (args.session_id && task.targetSessionId !== args.session_id && task.assignedSessionId !== args.session_id) continue;\n if (task.message?.trim() === normalizedMessage) {\n return { duplicate: true, entry: task, source: 'queue' };\n }\n }\n\n const entries = readLedgerEntries(ctx.mesh.id, { tail: 200 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i];\n const timestamp = new Date(entry.timestamp).getTime();\n if (Number.isFinite(timestamp) && now - timestamp > DUPLICATE_DISPATCH_WINDOW_MS) break;\n if (entry.kind !== 'task_dispatched') continue;\n if (entry.nodeId !== args.node_id) continue;\n if (args.session_id && entry.sessionId !== args.session_id) continue;\n if (typeof entry.payload?.message !== 'string') continue;\n if (entry.payload.message.trim() === normalizedMessage) {\n return { duplicate: true, entry, source: 'ledger' };\n }\n }\n return { duplicate: false };\n}\n\nfunction buildMissingNodeReadChatRecovery(ctx: MeshContext, args: { node_id: string; session_id: string; provider_session_id?: string; tail?: number; compact?: boolean }): Record<string, unknown> {\n const entries = readLedgerEntries(ctx.mesh.id, { tail: 300 });\n const relatedEntries = entries.filter(entry => entry.nodeId === args.node_id || entry.sessionId === args.session_id);\n const completedEntries = relatedEntries.filter(entry => entry.kind === 'task_completed');\n const lastDispatch = [...relatedEntries].reverse().find(entry => entry.kind === 'task_dispatched');\n const lastTerminal = [...relatedEntries].reverse().find(entry => entry.kind === 'task_completed' || entry.kind === 'task_failed' || entry.kind === 'task_stalled');\n const lastRemoved = [...relatedEntries].reverse().find(entry => entry.kind === 'node_removed');\n const lastLaunch = [...relatedEntries].reverse().find(entry => entry.kind === 'session_launched');\n const providerSessionId = args.provider_session_id\n || readString(lastTerminal?.payload?.providerSessionId)\n || readString(lastLaunch?.payload?.providerSessionId)\n || readString(lastDispatch?.payload?.providerSessionId);\n const finalSummary = readString(lastTerminal?.payload?.finalSummary)\n || readString(lastTerminal?.payload?.compactSummary)\n || readString(lastTerminal?.payload?.summary);\n const ledger = {\n taskCompletedFound: completedEntries.length > 0,\n nodeRemovedFound: !!lastRemoved,\n providerType: lastTerminal?.providerType || lastLaunch?.providerType || lastDispatch?.providerType,\n providerSessionId,\n nodeRemovedAt: lastRemoved?.timestamp,\n sessionCleanupMode: readString(lastRemoved?.payload?.sessionCleanupMode),\n readDebugLocator: readString(lastTerminal?.payload?.readDebugLocator) || readString(lastTerminal?.payload?.debugBundlePath),\n };\n\n if (finalSummary) {\n if (args.compact === true) {\n return {\n ...compactChatPayload({\n success: true,\n status: 'idle',\n providerSessionId,\n summary: finalSummary,\n messages: [{ role: 'assistant', content: finalSummary, isHistorical: true }],\n }, {\n nodeId: args.node_id,\n sessionId: args.session_id,\n limit: args.tail ?? 10,\n }),\n recoveredFromLedger: true,\n ledger,\n };\n }\n return {\n success: true,\n compact: false,\n recoveredFromLedger: true,\n nodeId: args.node_id,\n sessionId: args.session_id,\n summary: finalSummary,\n ledger,\n messages: [{ role: 'assistant', content: finalSummary, isHistorical: true }],\n };\n }\n\n return {\n success: false,\n recoverable: true,\n code: 'mesh_removed_node_transcript_unavailable',\n error: `Node '${args.node_id}' is not a current member of mesh '${ctx.mesh.name}'.`,\n nodeId: args.node_id,\n sessionId: args.session_id,\n providerSessionId,\n reason: 'node_not_in_current_mesh_snapshot',\n ledger,\n completedSessionSeenInLedger: ledger.taskCompletedFound,\n lastDispatch: lastDispatch ? {\n timestamp: lastDispatch.timestamp,\n sessionId: lastDispatch.sessionId,\n providerType: lastDispatch.providerType,\n taskId: typeof lastDispatch.payload?.taskId === 'string' ? lastDispatch.payload.taskId : undefined,\n messagePreview: typeof lastDispatch.payload?.message === 'string' ? lastDispatch.payload.message.slice(0, 500) : undefined,\n } : null,\n lastTerminalEvent: lastTerminal ? {\n kind: lastTerminal.kind,\n timestamp: lastTerminal.timestamp,\n sessionId: lastTerminal.sessionId,\n providerType: lastTerminal.providerType,\n taskId: typeof lastTerminal.payload?.taskId === 'string' ? lastTerminal.payload.taskId : undefined,\n payload: lastTerminal.payload,\n } : null,\n nextSteps: [\n providerSessionId\n ? `Retry mesh_read_chat with provider_session_id='${providerSessionId}' on a current live node for the same daemon if one exists.`\n : 'If the node UI shows a provider transcript id, retry mesh_read_chat/mesh_read_debug with provider_session_id.',\n 'Use mesh_read_debug with the provider_session_id or daemon-side debug bundle locator if available.',\n 'Check mesh_task_history for task_completed and node_removed entries before redispatching; do not resend solely because transcript recovery failed.',\n 'If this node was removed with stop_and_delete, the runtime transcript may be gone; rely on the ledger summary/locator or ask the operator for the saved UI output.',\n ],\n recoveryHints: [\n 'The worktree/node may have been removed or the mesh snapshot may be stale after task completion.',\n 'If you have a provider_session_id, retry mesh_read_chat with that value while targeting a live node for the same daemon if available.',\n 'Use mesh_read_debug with provider_session_id, or inspect the daemon/session-host history locator if the transcript has already been archived.',\n 'Avoid redispatching the same task solely because read_chat could not recover the transcript; check task_history and git status first.',\n ],\n };\n}\n\ntype QueueLivenessIndex = {\n nodeIds: Set<string>;\n nodeSessionIds: Map<string, Set<string>>;\n};\n\nfunction readSessionRecordId(session: any): string | undefined {\n return readString(session?.id)\n || readString(session?.sessionId)\n || readString(session?.session_id)\n || readString(session?.runtimeSessionId)\n || readString(session?.runtime_session_id)\n || readString(session?.instanceId)\n || readString(session?.instance_id);\n}\n\nfunction extractStatusMetadataSessions(value: any): any[] {\n const payload = unwrapCommandPayload(value);\n const status = payload?.status && typeof payload.status === 'object'\n ? payload.status\n : payload;\n return Array.isArray(status?.sessions) ? status.sessions : [];\n}\n\nfunction resolveSessionProviderType(session: any): string {\n return readString(session?.providerType)\n || readString(session?.cliType)\n || readString(session?.agentType)\n || '';\n}\n\nfunction addSessionRecord(target: Set<string>, session: any): void {\n if (!session || typeof session !== 'object' || isTerminalSessionRecord(session)) return;\n const sessionId = readSessionRecordId(session);\n if (sessionId) target.add(sessionId);\n}\n\nfunction collectNodeSessionIds(node: any): Set<string> {\n const sessions = new Set<string>();\n const sessionArrays = [\n node?.sessions,\n node?.activeSessions,\n node?.active_sessions,\n node?.lastProbe?.sessions,\n node?.last_probe?.sessions,\n node?.lastProbe?.status?.sessions,\n node?.last_probe?.status?.sessions,\n ];\n for (const value of sessionArrays) {\n if (Array.isArray(value)) value.forEach(session => addSessionRecord(sessions, session));\n }\n\n const sessionRecords = [\n node?.activeSession,\n node?.active_session,\n node?.currentSession,\n node?.current_session,\n node?.runtimeSession,\n node?.runtime_session,\n node?.session,\n node?.lastProbe?.activeSession,\n node?.last_probe?.active_session,\n node?.lastProbe?.currentSession,\n node?.last_probe?.current_session,\n node?.lastProbe?.session,\n node?.last_probe?.session,\n ];\n sessionRecords.forEach(session => addSessionRecord(sessions, session));\n return sessions;\n}\n\nfunction buildQueueLivenessIndex(mesh?: LocalMeshEntry): QueueLivenessIndex {\n const nodeIds = new Set<string>();\n const nodeSessionIds = new Map<string, Set<string>>();\n for (const node of Array.isArray(mesh?.nodes) ? mesh.nodes : []) {\n const nodeId = readString((node as any).id) || readString((node as any).nodeId) || readString((node as any).node_id);\n if (!nodeId) continue;\n nodeIds.add(nodeId);\n const sessions = collectNodeSessionIds(node);\n if (sessions.size > 0) nodeSessionIds.set(nodeId, sessions);\n }\n return { nodeIds, nodeSessionIds };\n}\n\nfunction queueAssignmentStaleReason(task: any, liveness: QueueLivenessIndex): string | undefined {\n if (task?.status !== 'assigned') return undefined;\n const nodeId = readString(task.assignedNodeId) || readString(task.nodeId) || readString(task.node_id) || readString(task.targetNodeId);\n const sessionId = readString(task.assignedSessionId) || readString(task.sessionId) || readString(task.session_id) || readString(task.targetSessionId);\n\n if (nodeId && liveness.nodeIds.size > 0 && !liveness.nodeIds.has(nodeId)) {\n return 'assigned node is not present in the current mesh snapshot';\n }\n if (nodeId && sessionId && liveness.nodeSessionIds.has(nodeId) && !liveness.nodeSessionIds.get(nodeId)!.has(sessionId)) {\n return 'assigned session is not live on the assigned node';\n }\n\n const updatedAt = new Date(task.updatedAt).getTime();\n const ageMs = Number.isFinite(updatedAt) ? Date.now() - updatedAt : null;\n if (!nodeId && ageMs !== null && ageMs >= STALE_ASSIGNED_QUEUE_MS) {\n return 'assigned task has no assigned node metadata';\n }\n return undefined;\n}\n\nfunction buildQueueStatusSummary(queue: any[]): Record<string, unknown> {\n const counts = { pending: 0, assigned: 0, completed: 0, failed: 0, cancelled: 0 };\n let staleAssigned = 0;\n for (const task of queue) {\n const status = typeof task?.status === 'string' ? task.status : undefined;\n if (status && Object.prototype.hasOwnProperty.call(counts, status)) {\n counts[status as keyof typeof counts] += 1;\n }\n if (status === 'assigned' && task?.staleAssigned === true) staleAssigned += 1;\n }\n const liveAssigned = Math.max(0, counts.assigned - staleAssigned);\n return {\n totalCount: queue.length,\n activeCount: counts.pending + liveAssigned,\n historicalCount: counts.completed + counts.failed + counts.cancelled,\n counts,\n activeCounts: {\n pending: counts.pending,\n assigned: liveAssigned,\n },\n staleAssignedCount: staleAssigned,\n rawActiveCounts: {\n pending: counts.pending,\n assigned: counts.assigned,\n },\n historicalCounts: {\n completed: counts.completed,\n failed: counts.failed,\n cancelled: counts.cancelled,\n },\n };\n}\n\nfunction normalizeQueueViewMode(value: unknown): QueueViewMode {\n return value === 'active' || value === 'historical' || value === 'all' ? value : 'all';\n}\n\nfunction sanitizeQueueStatusFilter(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const statuses = value\n .map(item => typeof item === 'string' ? item.trim() : '')\n .filter(status => ACTIVE_QUEUE_STATUSES.has(status) || HISTORICAL_QUEUE_STATUSES.has(status));\n return statuses.length ? Array.from(new Set(statuses)) : undefined;\n}\n\nfunction filterQueueForView(queue: any[], view: QueueViewMode, statuses?: string[]): any[] {\n if (statuses?.length) {\n const allowed = new Set(statuses);\n return queue.filter(task => allowed.has(String(task?.status || '')));\n }\n if (view === 'active') return queue.filter(task => ACTIVE_QUEUE_STATUSES.has(String(task?.status || '')));\n if (view === 'historical') return queue.filter(task => HISTORICAL_QUEUE_STATUSES.has(String(task?.status || '')));\n return queue;\n}\n\nfunction prioritizeActiveQueueRows(queue: any[]): any[] {\n const active: any[] = [];\n const historical: any[] = [];\n const other: any[] = [];\n for (const task of queue) {\n const status = String(task?.status || '');\n if (ACTIVE_QUEUE_STATUSES.has(status)) active.push(task);\n else if (HISTORICAL_QUEUE_STATUSES.has(status)) historical.push(task);\n else other.push(task);\n }\n return [...active, ...other, ...historical];\n}\n\nfunction slimQueueTask(task: any): Record<string, unknown> {\n return {\n id: task?.id,\n status: task?.status,\n assignedNodeId: task?.assignedNodeId,\n assignedSessionId: task?.assignedSessionId,\n targetNodeId: task?.targetNodeId,\n targetSessionId: task?.targetSessionId,\n updatedAt: task?.updatedAt,\n staleAssigned: task?.staleAssigned === true,\n staleReason: task?.staleReason,\n };\n}\n\nfunction buildQueueMaintenanceReport(queue: any[]): Record<string, unknown> {\n const now = Date.now();\n const staleAssignedTasks = queue\n .filter(task => task?.status === 'assigned' && task?.staleAssigned === true)\n .map(slimQueueTask);\n const historicalTasks = queue.filter(task => HISTORICAL_QUEUE_STATUSES.has(String(task?.status || '')));\n const oldHistoricalTasks = historicalTasks\n .filter(task => {\n const updatedAt = new Date(task?.updatedAt).getTime();\n return Number.isFinite(updatedAt) && now - updatedAt >= OLD_HISTORICAL_QUEUE_RECORD_MS;\n })\n .map(task => ({\n ...slimQueueTask(task),\n cleanupClass: 'old_historical_record',\n reason: 'terminal queue record is older than the read-only maintenance threshold',\n }));\n const cleanupCandidates = [\n ...staleAssignedTasks.map(task => ({\n ...task,\n cleanupClass: 'stale_assigned',\n reason: typeof task.staleReason === 'string' ? task.staleReason : 'active assigned task does not match current live mesh node/session state',\n suggestedOperation: 'operator_review_then_requeue_or_cancel',\n })),\n ...oldHistoricalTasks.map(task => ({\n ...task,\n suggestedOperation: 'operator_review_then_archive_or_keep',\n })),\n ];\n return {\n readOnly: true,\n mutationPerformed: false,\n sourceOfTruth: 'mesh_work_queue_file',\n staleAssignedDefinition: 'Only active assigned queue rows are stale candidates, and only when the assigned node/session is absent from the current live mesh snapshot.',\n historicalDefinition: 'completed/failed/cancelled rows are historical ledger records and never active assignments.',\n staleAssignedTasks,\n staleAssignedCount: staleAssignedTasks.length,\n historicalRecordCount: historicalTasks.length,\n oldHistoricalRecordCount: oldHistoricalTasks.length,\n cleanupCandidates,\n cleanupCandidateCount: cleanupCandidates.length,\n };\n}\n\nfunction annotateQueueStaleness(queue: any[], mesh?: LocalMeshEntry): any[] {\n const liveness = buildQueueLivenessIndex(mesh);\n const now = Date.now();\n return queue.map(task => {\n const taskStatus = typeof task?.status === 'string' ? task.status : undefined;\n const annotated = {\n ...task,\n taskStatus,\n isActive: taskStatus ? ACTIVE_QUEUE_STATUSES.has(taskStatus) : false,\n isHistorical: taskStatus ? HISTORICAL_QUEUE_STATUSES.has(taskStatus) : false,\n dispatchedAt: task?.createdAt,\n ...(taskStatus === 'assigned' ? { activeTaskId: task.id } : {}),\n ...(taskStatus === 'completed' || taskStatus === 'failed' ? {\n completedAt: task.updatedAt,\n } : {}),\n };\n if (taskStatus !== 'assigned') return annotated;\n const updatedAt = new Date(task.updatedAt).getTime();\n const ageMs = Number.isFinite(updatedAt) ? now - updatedAt : null;\n const staleReason = queueAssignmentStaleReason(task, liveness);\n if (!staleReason) return annotated;\n return {\n ...annotated,\n stale: true,\n staleAssigned: true,\n staleReason,\n ...(ageMs !== null ? { assignedAgeMs: ageMs } : {}),\n };\n });\n}\n\nfunction unwrapCommandPayload(value: any): any {\n let current = value;\n const seen = new Set<any>();\n for (let depth = 0; depth < 8; depth += 1) {\n if (!current || typeof current !== 'object' || seen.has(current)) break;\n seen.add(current);\n\n const nested = current.result ?? current.payload;\n if (!nested || typeof nested !== 'object') break;\n current = nested;\n }\n return current;\n}\n\nfunction isTerminalSessionRecord(session: any): boolean {\n const status = typeof session?.status === 'string' ? session.status.toLowerCase() : '';\n const lifecycle = typeof session?.lifecycle === 'string' ? session.lifecycle.toLowerCase() : '';\n const state = typeof session?.state === 'string' ? session.state.toLowerCase() : '';\n return [status, lifecycle, state].some(value => ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(value));\n}\n\nfunction isIdleSessionRecord(session: any): boolean {\n if (isTerminalSessionRecord(session)) return false;\n const status = typeof session?.status === 'string' ? session.status.toLowerCase() : '';\n const chatStatus = typeof session?.activeChat?.status === 'string' ? session.activeChat.status.toLowerCase() : '';\n return status === 'idle' || chatStatus === 'waiting_input';\n}\n\nfunction isMeshOwnedDelegateSession(session: any, meshId: string, nodeId: string): boolean {\n const settings = session?.settings;\n const sessionMeshId = typeof settings?.meshNodeFor === 'string' ? settings.meshNodeFor.trim() : '';\n const coordinatorDaemonId = typeof settings?.meshCoordinatorDaemonId === 'string' ? settings.meshCoordinatorDaemonId.trim() : '';\n const sessionNodeId = typeof settings?.meshNodeId === 'string' ? settings.meshNodeId.trim() : '';\n if (sessionMeshId !== meshId || !coordinatorDaemonId) return false;\n return !sessionNodeId || sessionNodeId === nodeId;\n}\n\nfunction chooseDispatchableSession(sessions: any[], providerType: string, meshId: string, nodeId: string): any | undefined {\n const live = sessions.filter(session => !isTerminalSessionRecord(session));\n const matchingProvider = (session: any) => !providerType || session?.providerType === providerType || session?.cliType === providerType;\n const meshSessions = live.filter((session: any) =>\n isMeshOwnedDelegateSession(session, meshId, nodeId)\n );\n return meshSessions.find(session => isIdleSessionRecord(session) && matchingProvider(session))\n || meshSessions.find(matchingProvider)\n || undefined;\n}\n\nfunction buildRelayUnsafeRemoteSessionFailure(ctx: MeshContext, node: LocalMeshNodeEntry, sessionId: string, providerType?: string): ({ success: false; error: string } & Record<string, unknown>) {\n return {\n success: false,\n recoverable: true,\n code: 'mesh_delegate_session_missing_relay_metadata',\n reason: 'mesh_delegate_session_missing_relay_metadata',\n transport: 'mesh_transport',\n retryRecommended: true,\n meshId: ctx.mesh.id,\n nodeId: node.id,\n daemonId: node.daemonId,\n workspace: node.workspace,\n sessionId,\n ...(providerType ? { resolvedProviderType: providerType } : {}),\n error: `Remote session '${sessionId}' is not relay-safe for mesh '${ctx.mesh.id}': missing meshNodeFor/meshCoordinatorDaemonId metadata, so completion events would not reach the coordinator ledger.`,\n nextAction: `Launch a fresh relay-safe session with mesh_launch_session(node_id: '${node.id}'${providerType ? `, type: '${providerType}'` : ''}) or dispatch without session_id so Repo Mesh can choose a valid delegate session.`,\n noFallbackReason: 'Blindly reusing a remote session without mesh relay metadata would silently drop task_completed / generating_completed events.',\n };\n}\n\nfunction buildMissingCoordinatorDaemonIdFailure(ctx: MeshContext, node: LocalMeshNodeEntry, providerType?: string): ({ success: false; error: string } & Record<string, unknown>) {\n return {\n success: false,\n recoverable: true,\n code: 'mesh_coordinator_daemon_unknown',\n reason: 'mesh_coordinator_daemon_unknown',\n transport: 'mesh_transport',\n retryRecommended: true,\n meshId: ctx.mesh.id,\n nodeId: node.id,\n daemonId: node.daemonId,\n workspace: node.workspace,\n ...(providerType ? { resolvedProviderType: providerType } : {}),\n error: `Cannot launch a remote mesh delegate for node '${node.id}': coordinator daemon identity is unavailable, so the worker would be unable to relay completion events back to the coordinator.`,\n nextAction: 'Retry after the coordinator daemon identity is available (for example from an attached daemon-backed MCP session) so meshCoordinatorDaemonId can be stamped on the worker session.',\n noFallbackReason: 'Launching without meshCoordinatorDaemonId would create a worker session that can finish work but cannot emit task_completed / generating_completed back to the coordinator.',\n };\n}\n\nfunction findNestedPayload(value: any, predicate: (payload: any) => boolean): any {\n const seen = new Set<any>();\n const stack: Array<{ payload: any; depth: number }> = [{ payload: value, depth: 0 }];\n\n while (stack.length) {\n const { payload, depth } = stack.pop()!;\n if (predicate(payload)) return payload;\n if (!payload || typeof payload !== 'object' || seen.has(payload) || depth >= 8) continue;\n seen.add(payload);\n\n // Cloud/daemon relay layers have used both `result` and `payload` for\n // command_result bodies. Follow only those envelope keys so clone node\n // discovery stays tied to returned command payloads, not arbitrary data.\n for (const key of ['payload', 'result']) {\n if (key in payload) stack.push({ payload: payload[key], depth: depth + 1 });\n }\n }\n\n return value;\n}\n\nfunction extractCloneNodePayload(value: any): any {\n return findNestedPayload(value, payload => Boolean(payload?.node?.id));\n}\n\nfunction extractGitStatus(value: any): any {\n const payload = unwrapCommandPayload(value);\n return payload?.status ?? value?.status ?? payload;\n}\n\nfunction extractGitDiff(value: any): any {\n const payload = unwrapCommandPayload(value);\n return payload?.diffSummary ?? payload?.diff ?? value?.diffSummary ?? value?.diff ?? payload;\n}\n\nfunction extractSubmodules(value: any, ignorePaths: string[]): any[] | undefined {\n const payload = unwrapCommandPayload(value);\n const subs = payload?.status?.submodules\n ?? payload?.submodules\n ?? value?.status?.submodules\n ?? value?.submodules;\n if (!Array.isArray(subs)) return undefined;\n if (ignorePaths.length === 0) return subs;\n const ignoreSet = new Set(ignorePaths);\n return subs.filter((s: any) => s?.path && !ignoreSet.has(s.path));\n}\n\nfunction assignFullGitSnapshot(entry: Record<string, unknown>, status: any): void {\n if (!status || typeof status !== 'object' || Array.isArray(status)) return;\n entry.git = status;\n}\n\nfunction extractLaunchPayload(value: any): any {\n return findNestedPayload(value, payload => Boolean(payload?.sessionId || payload?.id || payload?.runtimeSessionId));\n}\n\ntype MeshLaunchFailureClassification = {\n code: string;\n reason: string;\n transport: string;\n recoverable: boolean;\n retryRecommended: boolean;\n nextAction: string;\n noFallbackReason?: string;\n};\n\nfunction classifyMeshLaunchFailure(error: unknown): MeshLaunchFailureClassification {\n const message = error instanceof Error ? error.message : String(error || 'launch failed');\n const lower = message.toLowerCase();\n const p2pClassification = classifyP2pRelayFailure(error, { command: 'launch_cli' });\n if (p2pClassification.recoverable) {\n return p2pClassification;\n }\n if (lower.includes('cannot connect to daemon ipc') || lower.includes('daemon ipc command')) {\n return {\n code: 'local_ipc_unavailable',\n reason: 'local_daemon_ipc_unavailable',\n transport: 'local_ipc',\n recoverable: true,\n retryRecommended: true,\n nextAction: 'Check the local daemon IPC connection, then retry mesh_launch_session once after the daemon is reachable.',\n };\n }\n if (lower.includes('timed out') || lower.includes('timeout')) {\n return {\n code: 'mesh_transport_timeout',\n reason: 'mesh_transport_timeout',\n transport: 'mesh_transport',\n recoverable: true,\n retryRecommended: true,\n nextAction: 'Check mesh transport health, then do one bounded retry before requeueing or relaunching the task.',\n };\n }\n return {\n code: 'mesh_launch_failed',\n reason: 'provider_launch_failed',\n transport: 'mesh_transport',\n recoverable: false,\n retryRecommended: false,\n nextAction: 'Inspect the provider launch error and fix the underlying provider/configuration issue before retrying.',\n };\n}\n\nfunction buildWorktreeCleanupHint(node: LocalMeshNodeEntry): Record<string, unknown> | undefined {\n if (!node.isLocalWorktree) return undefined;\n return {\n tool: 'mesh_remove_node',\n args: { node_id: node.id, session_cleanup_mode: 'preserve' },\n hint: `If the worktree is no longer needed, remove the orphan worktree node with mesh_remove_node(node_id: \"${node.id}\").`,\n };\n}\n\nfunction buildRecoverableLaunchFailure(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n providerType: string | undefined,\n error: unknown,\n): Record<string, unknown> {\n const message = error instanceof Error ? error.message : String(error || 'launch failed');\n const classified = classifyMeshLaunchFailure(error);\n const cleanup = buildWorktreeCleanupHint(node);\n return {\n success: false,\n recoverable: classified.recoverable,\n code: classified.code,\n reason: classified.reason,\n transport: classified.transport,\n retryRecommended: classified.retryRecommended,\n nextAction: classified.nextAction,\n ...(classified.noFallbackReason ? { noFallbackReason: classified.noFallbackReason } : {}),\n error: message,\n meshId: ctx.mesh.id,\n nodeId: node.id,\n daemonId: node.daemonId,\n workspace: node.workspace,\n isLocalWorktree: node.isLocalWorktree === true,\n worktreeBranch: node.worktreeBranch,\n clonedFromNodeId: node.clonedFromNodeId,\n ...(providerType ? { resolvedProviderType: providerType } : {}),\n retryHint: `Retry mesh_launch_session(node_id: \"${node.id}\"${providerType ? `, type: \"${providerType}\"` : ''}) after daemon mesh transport/P2P is healthy.`,\n ...(cleanup ? { cleanup } : {}),\n nextStepHints: [\n `Retry mesh_launch_session(node_id: \"${node.id}\"${providerType ? `, type: \"${providerType}\"` : ''}) after checking daemon/P2P health.`,\n ...(cleanup ? [`Cleanup orphan worktree node with mesh_remove_node(node_id: \"${node.id}\") if retry is not desired.`] : []),\n 'Run mesh_status to see the degraded reason and recovery hints before redispatching work.',\n ],\n };\n}\n\nfunction recordRecoverableLaunchFailure(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n providerType: string | undefined,\n error: unknown,\n): Record<string, unknown> {\n const failure = buildRecoverableLaunchFailure(ctx, node, providerType, error);\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'recovery_attempted',\n nodeId: node.id,\n providerType,\n payload: {\n event: 'session_launch_failed',\n ...failure,\n },\n });\n } catch { /* ledger append is best-effort */ }\n return failure;\n}\n\nfunction getLatestActiveLaunchFailure(meshId: string, nodeId: string): Record<string, unknown> | null {\n const entries = readLedgerEntries(meshId, { tail: 200 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i];\n if (entry.nodeId !== nodeId) continue;\n if (entry.kind === 'session_launched' || entry.kind === 'node_removed') return null;\n if (entry.kind === 'recovery_attempted' && entry.payload?.event === 'session_launch_failed') {\n return { timestamp: entry.timestamp, ...entry.payload };\n }\n }\n return null;\n}\n\ntype RemoteAgentDispatchResult =\n | { success: true; dispatched: true; sessionId: string; providerType?: string }\n | ({ success: false; error: string } & Record<string, unknown>);\n\nfunction buildCoordinatorP2pRelayFailure(\n error: unknown,\n context: { command: string; targetDaemonId?: string; nodeId?: string; sessionId?: string },\n): { success: false; error: string } & Record<string, unknown> {\n const payload = buildP2pRelayFailurePayload(error, {\n command: context.command,\n targetDaemonId: context.targetDaemonId,\n });\n return {\n ...payload,\n ...(context.nodeId ? { nodeId: context.nodeId } : {}),\n ...(context.sessionId ? { sessionId: context.sessionId } : {}),\n retryHint: payload.retryRecommended ? payload.nextAction : 'Do not retry as a P2P transport recovery; inspect the command/provider error first.',\n };\n}\n\n/**\n * For IpcTransport + remote node: resolve an active session on the node and\n * dispatch an agent_command directly via P2P relay (mesh_relay_command).\n *\n * This bypasses the local queue (which remote daemons cannot read) and sends\n * the message directly to the session running on the remote daemon.\n *\n * Returns { success, sessionId } or throws.\n */\nasync function ipcDispatchToRemoteAgent(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n args: { session_id?: string; message: string; providerType?: string },\n): Promise<RemoteAgentDispatchResult> {\n const transport = ctx.transport as IpcTransport;\n const daemonId = node.daemonId!;\n\n let sessionId = args.session_id?.trim() || '';\n // Resolve provider type: caller arg > node policy providerPriority > empty (fuzzy fallback)\n const providerPriorityList: string[] = Array.isArray((node.policy as any)?.providerPriority)\n ? (node.policy as any).providerPriority\n : [];\n let resolvedProviderType = args.providerType?.trim() || providerPriorityList[0] || '';\n\n // Ask the remote daemon for live session truth when we need to auto-pick a\n // delegate session, or when an explicit session_id must be verified as a\n // relay-safe mesh-owned worker before we dispatch into it.\n if (!sessionId || args.session_id) {\n try {\n const relayResult = await transport.meshCommand(daemonId, 'get_status_metadata', {});\n const sessions = extractStatusMetadataSessions(relayResult);\n\n if (sessionId) {\n const explicitSession = sessions.find(session => readSessionRecordId(session) === sessionId);\n if (!explicitSession) {\n return {\n success: false,\n recoverable: true,\n code: 'mesh_target_session_not_found',\n reason: 'mesh_target_session_not_found',\n transport: 'mesh_transport',\n retryRecommended: true,\n meshId: ctx.mesh.id,\n nodeId: node.id,\n daemonId,\n workspace: node.workspace,\n sessionId,\n ...(resolvedProviderType ? { resolvedProviderType } : {}),\n error: `Remote session '${sessionId}' is not present in the live status for node '${node.id}'.`,\n nextAction: `Launch a fresh session with mesh_launch_session(node_id: '${node.id}'${resolvedProviderType ? `, type: '${resolvedProviderType}'` : ''}) or retry without session_id so Repo Mesh can target a live delegate session.`,\n };\n }\n if (!isMeshOwnedDelegateSession(explicitSession, ctx.mesh.id, node.id)) {\n return buildRelayUnsafeRemoteSessionFailure(\n ctx,\n node,\n sessionId,\n resolvedProviderType || resolveSessionProviderType(explicitSession) || undefined,\n );\n }\n if (!resolvedProviderType) {\n resolvedProviderType = resolveSessionProviderType(explicitSession);\n }\n } else {\n // Prefer live idle sessions launched for this mesh node. Never route\n // a new task into restored/stopped session records; that produces the\n // coordinator-visible \"pending only, chat never received it\" failure.\n const targetSession = chooseDispatchableSession(sessions, resolvedProviderType, ctx.mesh.id, node.id);\n\n if (targetSession?.id || targetSession?.sessionId) {\n sessionId = targetSession.id || targetSession.sessionId;\n if (!resolvedProviderType) {\n resolvedProviderType = resolveSessionProviderType(targetSession);\n }\n }\n }\n } catch (e: any) {\n if (sessionId) {\n return {\n ...buildCoordinatorP2pRelayFailure(e, {\n command: 'get_status_metadata',\n targetDaemonId: daemonId,\n nodeId: node.id,\n sessionId,\n }),\n success: false,\n error: `Cannot verify remote session '${sessionId}' before dispatch: ${e?.message || String(e)}`,\n };\n }\n // fall through — will attempt dispatch with just providerType (fuzzy)\n }\n }\n\n // agent_command requires agentType — fail if we cannot determine provider type\n if (!resolvedProviderType) {\n return { success: false, error: `Cannot dispatch to remote node '${node.id}': providerType unknown. Set providerPriority on the node policy or call mesh_launch_session first.` };\n }\n\n try {\n const dispatchResult = await transport.meshCommand(daemonId, 'agent_command', {\n ...(sessionId ? { targetSessionId: sessionId } : {}),\n agentType: resolvedProviderType,\n cliType: resolvedProviderType,\n action: 'send_chat',\n message: args.message,\n });\n const dispatchPayload = unwrapCommandPayload(dispatchResult);\n if (dispatchPayload?.success === false || dispatchResult?.success === false) {\n const source = dispatchPayload?.success === false ? dispatchPayload : dispatchResult;\n const errorMessage = dispatchPayload?.error || dispatchResult?.error || 'agent_command rejected the task';\n return {\n ...buildCoordinatorP2pRelayFailure(source?.error || errorMessage, {\n command: 'agent_command',\n targetDaemonId: daemonId,\n nodeId: node.id,\n sessionId,\n }),\n ...(source && typeof source === 'object' ? source : {}),\n success: false,\n error: `P2P dispatch failed: ${errorMessage}`,\n };\n }\n return { success: true, dispatched: true, sessionId: sessionId || resolvedProviderType, providerType: resolvedProviderType };\n } catch (e: any) {\n const errorMessage = e?.message || String(e);\n return {\n ...buildCoordinatorP2pRelayFailure(e, {\n command: 'agent_command',\n targetDaemonId: daemonId,\n nodeId: node.id,\n sessionId,\n }),\n error: `P2P dispatch failed: ${errorMessage}`,\n };\n }\n}\n\nfunction resolveCoordinatorNode(ctx: MeshContext): LocalMeshNodeEntry | undefined {\n const preferredNodeId = typeof ctx.mesh.coordinator?.preferredNodeId === 'string'\n ? ctx.mesh.coordinator.preferredNodeId.trim()\n : '';\n if (preferredNodeId) {\n const preferred = ctx.mesh.nodes.find(n => n.id === preferredNodeId && typeof n.daemonId === 'string' && n.daemonId.trim());\n if (preferred) return preferred;\n }\n if (ctx.localMachineId) {\n const byMachine = ctx.mesh.nodes.find(n => readNodeMachineId(n) === ctx.localMachineId);\n if (byMachine) return byMachine;\n }\n if (ctx.localDaemonId) {\n return ctx.mesh.nodes.find(n => readNodeDaemonId(n) === ctx.localDaemonId);\n }\n return undefined;\n}\n\nfunction readNodeMachineId(node: LocalMeshNodeEntry): string | undefined {\n return readString((node as any).machineId)\n || readString((node as any).machine_id)\n || readString((node as any).machine?.id)\n || readString((node as any).machine?.machineId)\n || readString((node as any).lastProbe?.machineId)\n || readString((node as any).last_probe?.machine_id)\n || readString((node as any).lastProbe?.machine?.id)\n || readString((node as any).lastProbe?.machine?.machineId)\n || readString((node as any).last_probe?.machine?.id)\n || readString((node as any).last_probe?.machine?.machine_id);\n}\n\nfunction readNodeDaemonId(node: LocalMeshNodeEntry): string | undefined {\n return readString(node.daemonId)\n || readString((node as any).daemon_id)\n || readString((node as any).machine?.daemonId)\n || readString((node as any).machine?.daemon_id)\n || readString((node as any).lastProbe?.daemonId)\n || readString((node as any).last_probe?.daemon_id)\n || readString((node as any).lastProbe?.machine?.daemonId)\n || readString((node as any).lastProbe?.machine?.daemon_id)\n || readString((node as any).last_probe?.machine?.daemonId)\n || readString((node as any).last_probe?.machine?.daemon_id);\n}\n\nfunction normalizeHostname(value: unknown): string | undefined {\n const hostname = readString(value);\n if (!hostname) return undefined;\n return hostname.toLowerCase().replace(/\\.$/, '');\n}\n\nfunction readNodeHostname(node: LocalMeshNodeEntry): string | undefined {\n return readString((node as any).hostname)\n || readString((node as any).host)\n || readString((node as any).machineHostname)\n || readString((node as any).machine_hostname)\n || readString((node as any).machine?.hostname)\n || readString((node as any).machine?.host)\n || readString((node as any).lastProbe?.hostname)\n || readString((node as any).last_probe?.hostname)\n || readString((node as any).lastProbe?.machine?.hostname)\n || readString((node as any).last_probe?.machine?.hostname);\n}\n\nfunction readNodeDisplayMachineName(node: LocalMeshNodeEntry): string | undefined {\n return readString((node as any).machineName)\n || readString((node as any).machine_name)\n || readString((node as any).machineLabel)\n || readString((node as any).machine_label)\n || readString((node as any).machineNickname)\n || readString((node as any).machine_nickname)\n || readString((node as any).alias)\n || readString((node as any).machine?.name)\n || readString((node as any).machine?.displayName)\n || readString((node as any).machine?.display_name)\n || readString((node as any).lastProbe?.machineName)\n || readString((node as any).last_probe?.machine_name)\n || readString((node as any).lastProbe?.machine?.name)\n || readString((node as any).last_probe?.machine?.name)\n || readNodeHostname(node);\n}\n\nfunction compactIdentityEvidence(value: string | undefined): string | undefined {\n if (!value) return undefined;\n return value.length > 24 ? `${value.slice(0, 12)}…${value.slice(-8)}` : value;\n}\n\nfunction pushIdentityEvidence(evidence: string[], label: string, value: string | undefined): void {\n const compact = compactIdentityEvidence(value);\n if (compact) evidence.push(`${label}:${compact}`);\n}\n\nfunction buildNodeMachineIdentity(ctx: MeshContext, node: LocalMeshNodeEntry): Record<string, unknown> {\n const machineId = readNodeMachineId(node);\n const daemonId = readNodeDaemonId(node);\n const hostname = readNodeHostname(node);\n const machineName = readNodeDisplayMachineName(node);\n const coordinatorHostname = readString(ctx.coordinatorHostname);\n const directLocal = isLocalControlPlaneNode(ctx, node);\n const hostnameMatches = Boolean(\n normalizeHostname(hostname)\n && normalizeHostname(coordinatorHostname)\n && normalizeHostname(hostname) === normalizeHostname(coordinatorHostname),\n );\n const sameMachine = directLocal || hostnameMatches;\n const evidence: string[] = [];\n pushIdentityEvidence(evidence, 'machineName', machineName);\n pushIdentityEvidence(evidence, 'hostname', hostname);\n pushIdentityEvidence(evidence, 'machineId', machineId);\n pushIdentityEvidence(evidence, 'daemonId', daemonId);\n const locality = sameMachine ? 'same_machine' : (evidence.length > 0 ? 'remote_known' : 'remote_or_unknown');\n const localityReason = sameMachine\n ? (directLocal ? 'matched coordinator daemon or machine id' : 'matched coordinator hostname')\n : evidence.length > 0\n ? `known remote/other machine identity; no local coordinator match (${evidence.join(', ')})`\n : 'no useful machine identity evidence available';\n return {\n daemonId,\n machineId,\n hostname,\n machineName,\n displayName: machineName || hostname || daemonId || machineId,\n coordinatorHostname,\n sameMachine,\n locality,\n localityReason,\n identityEvidence: evidence,\n };\n}\n\nfunction isDirectLocalNode(ctx: MeshContext, node: LocalMeshNodeEntry): boolean {\n const machineId = readNodeMachineId(node);\n const daemonId = readNodeDaemonId(node);\n return Boolean(\n (ctx.localMachineId && machineId === ctx.localMachineId)\n || (ctx.localDaemonId && daemonId === ctx.localDaemonId),\n );\n}\n\nfunction findClonedFromNode(ctx: MeshContext, node: LocalMeshNodeEntry): LocalMeshNodeEntry | undefined {\n const clonedFromNodeId = readString(node.clonedFromNodeId) || readString((node as any).cloned_from_node_id);\n if (!clonedFromNodeId) return undefined;\n return ctx.mesh.nodes.find(n => n.id === clonedFromNodeId || (n as any).nodeId === clonedFromNodeId || (n as any).node_id === clonedFromNodeId);\n}\n\nfunction isLocalControlPlaneNode(ctx: MeshContext, node: LocalMeshNodeEntry): boolean {\n if (isDirectLocalNode(ctx, node)) return true;\n\n // Worktree nodes created by the local daemon may be persisted without their\n // own machineId. In that case, preserve locality from the cloned source node\n // rather than incorrectly routing local workspace commands through P2P.\n if (node.isLocalWorktree === true) {\n const sourceNode = findClonedFromNode(ctx, node);\n if (sourceNode && isDirectLocalNode(ctx, sourceNode)) return true;\n }\n\n return false;\n}\n\nfunction meshSessionCacheKey(nodeId: string, runtimeSessionId: string): string {\n return `${nodeId}:${runtimeSessionId}`;\n}\n\nfunction rememberMeshSessionProviderMetadata(\n nodeId: string | undefined,\n runtimeSessionId: string | undefined,\n metadata: MeshSessionProviderMetadata,\n): void {\n const keyNodeId = readString(nodeId);\n const keySessionId = readString(runtimeSessionId);\n if (!keyNodeId || !keySessionId) return;\n const providerType = readString(metadata.providerType);\n const providerSessionId = readString(metadata.providerSessionId);\n if (!providerType && !providerSessionId) return;\n const existing = meshSessionProviderMetadata.get(meshSessionCacheKey(keyNodeId, keySessionId)) || { providerType: '' };\n meshSessionProviderMetadata.set(meshSessionCacheKey(keyNodeId, keySessionId), {\n providerType: providerType || existing.providerType,\n providerSessionId: providerSessionId || existing.providerSessionId,\n });\n}\n\nfunction rememberMeshSessionProviderMetadataFromEvent(event: any): void {\n const metadataEvent = event?.metadataEvent && typeof event.metadataEvent === 'object'\n ? event.metadataEvent as Record<string, unknown>\n : event && typeof event === 'object'\n ? event as Record<string, unknown>\n : {};\n const nodeId = readString(event?.nodeId) || readString(metadataEvent.nodeId) || readString(metadataEvent.meshNodeId);\n const sessionId = readString(metadataEvent.targetSessionId)\n || readString(metadataEvent.sessionId)\n || readString(metadataEvent.instanceId)\n || readString(event?.sessionId);\n rememberMeshSessionProviderMetadata(nodeId, sessionId, {\n providerType: readString(metadataEvent.providerType) || readString(event?.providerType) || '',\n providerSessionId: readString(metadataEvent.providerSessionId) || readString(event?.providerSessionId),\n });\n}\n\nfunction resolveMeshSessionProviderMetadataFromLedger(\n ctx: MeshContext,\n nodeId: string,\n runtimeSessionId: string,\n): MeshSessionProviderMetadata | undefined {\n const entries = readLedgerEntries(ctx.mesh.id, { tail: 500 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i];\n const payload = entry.payload && typeof entry.payload === 'object' && !Array.isArray(entry.payload)\n ? entry.payload as Record<string, unknown>\n : {};\n const entryNodeId = readString(entry.nodeId) || readString(payload.nodeId) || readString(payload.meshNodeId);\n if (entryNodeId && entryNodeId !== nodeId) continue;\n const entrySessionId = readString(entry.sessionId)\n || readString(payload.targetSessionId)\n || readString(payload.sessionId)\n || readString(payload.instanceId);\n if (entrySessionId !== runtimeSessionId) continue;\n const providerType = readString(entry.providerType) || readString(payload.providerType);\n const completionDiagnostic = payload.completionDiagnostic && typeof payload.completionDiagnostic === 'object' && !Array.isArray(payload.completionDiagnostic)\n ? payload.completionDiagnostic as Record<string, unknown>\n : {};\n const metadataEvent = payload.metadataEvent && typeof payload.metadataEvent === 'object' && !Array.isArray(payload.metadataEvent)\n ? payload.metadataEvent as Record<string, unknown>\n : {};\n const providerSessionId = readString(payload.providerSessionId)\n || readString(completionDiagnostic.providerSessionId)\n || readString(metadataEvent.providerSessionId);\n if (providerType || providerSessionId) {\n return { providerType: providerType || '', providerSessionId };\n }\n }\n return undefined;\n}\n\nfunction resolveMeshSessionProviderMetadata(\n ctx: MeshContext,\n nodeId: string,\n runtimeSessionId: string,\n): MeshSessionProviderMetadata | undefined {\n const cached = meshSessionProviderMetadata.get(meshSessionCacheKey(nodeId, runtimeSessionId));\n if (cached?.providerType || cached?.providerSessionId) return cached;\n const fromLedger = resolveMeshSessionProviderMetadataFromLedger(ctx, nodeId, runtimeSessionId);\n if (fromLedger) rememberMeshSessionProviderMetadata(nodeId, runtimeSessionId, fromLedger);\n return fromLedger;\n}\n\nfunction countUncommittedChanges(status: any): number {\n if (typeof status?.uncommittedChanges === 'number') return status.uncommittedChanges;\n const keys = ['staged', 'modified', 'untracked', 'deleted', 'renamed'];\n const counted = keys.reduce((sum, key) => sum + (Number.isFinite(Number(status?.[key])) ? Number(status[key]) : 0), 0);\n const conflicts = Array.isArray(status?.conflictFiles) ? status.conflictFiles.length : (status?.hasConflicts ? 1 : 0);\n return counted + conflicts;\n}\n\nfunction isGitStatusDirty(status: any): boolean {\n if (typeof status?.isDirty === 'boolean') return status.isDirty;\n if (typeof status?.dirty === 'boolean') return status.dirty;\n return countUncommittedChanges(status) > 0;\n}\n\nfunction readRelatedRepos(node: LocalMeshNodeEntry): RepoMeshRelatedRepo[] {\n const raw = Array.isArray((node as any).relatedRepos)\n ? (node as any).relatedRepos\n : Array.isArray((node.policy as any)?.relatedRepos)\n ? (node.policy as any).relatedRepos\n : [];\n\n return raw\n .map((entry: any) => ({\n label: typeof entry?.label === 'string' ? entry.label.trim() : '',\n workspace: typeof entry?.workspace === 'string' ? entry.workspace.trim() : '',\n }))\n .filter((entry: RepoMeshRelatedRepo) => Boolean(entry.label && entry.workspace));\n}\n\nfunction summarizeRelatedRepoStatus(repo: RepoMeshRelatedRepo, status: any): Record<string, unknown> {\n const dirty = isGitStatusDirty(status);\n return {\n label: repo.label,\n workspace: repo.workspace,\n isGitRepo: status?.isGitRepo === true,\n branch: status?.branch ?? null,\n upstream: status?.upstream ?? null,\n upstreamStatus: typeof status?.upstreamStatus === 'string' ? status.upstreamStatus : (status?.upstream ? 'unchecked' : 'no_upstream'),\n upstreamFetchedAt: Number.isFinite(Number(status?.upstreamFetchedAt)) ? Number(status.upstreamFetchedAt) : null,\n upstreamFetchError: typeof status?.upstreamFetchError === 'string' ? status.upstreamFetchError : null,\n ahead: Number.isFinite(Number(status?.ahead)) ? Number(status.ahead) : 0,\n behind: Number.isFinite(Number(status?.behind)) ? Number(status.behind) : 0,\n dirty,\n uncommittedChanges: countUncommittedChanges(status),\n head: status?.headCommit ?? null,\n lastCommitSummary: status?.headMessage ?? null,\n ...(status?.reason ? { reason: status.reason } : {}),\n ...(status?.error ? { error: status.error } : {}),\n };\n}\n\nasync function collectRelatedRepoStatuses(ctx: MeshContext, node: LocalMeshNodeEntry): Promise<Array<Record<string, unknown>>> {\n const relatedRepos = readRelatedRepos(node);\n if (!relatedRepos.length) return [];\n\n const results: Array<Record<string, unknown>> = [];\n for (const repo of relatedRepos) {\n try {\n const statusResult = !isLocalTransport(ctx.transport) && node.daemonId\n ? await (ctx.transport as CloudTransport).gitStatus(node.daemonId, repo.workspace, false, true)\n : await commandForNode(ctx, node, 'git_status', { workspace: repo.workspace, refreshUpstream: true });\n const status = extractGitStatus(statusResult);\n results.push(summarizeRelatedRepoStatus(repo, status));\n } catch (e: any) {\n results.push({\n label: repo.label,\n workspace: repo.workspace,\n error: e?.message || 'related repo status failed',\n });\n }\n }\n return results;\n}\n\nfunction findNodeByWorkspace(mesh: LocalMeshEntry, workspace: string): LocalMeshNodeEntry {\n const node = mesh.nodes.find(n => n.workspace === workspace);\n if (!node) throw new Error(`Workspace '${workspace}' is not a member of mesh '${mesh.name}'`);\n return node;\n}\n\nfunction readProviderPriority(policy: unknown): string[] {\n const raw = (policy as any)?.providerPriority;\n return Array.isArray(raw)\n ? raw.map((type: unknown) => typeof type === 'string' ? type.trim() : '').filter(Boolean)\n : [];\n}\n\nfunction readSpawnedSessionVisibility(policy: unknown): 'visible' | 'hidden' {\n return (policy as any)?.spawnedSessionVisibility === 'hidden' ? 'hidden' : 'visible';\n}\n\nfunction missingProviderPriorityMessage(nodeId: string): string {\n return `Node '${nodeId}' has no providerPriority policy; pass type explicitly or configure node.policy.providerPriority`;\n}\n\nfunction getNodeLaunchReadiness(node: LocalMeshNodeEntry): Record<string, unknown> {\n const providerPriority = readProviderPriority(node.policy);\n if (providerPriority.length) {\n return {\n providerPriority,\n launchReady: true,\n };\n }\n\n return {\n providerPriority,\n launchReady: false,\n launchBlockedReason: 'missing_provider_priority',\n launchBlockedMessage: missingProviderPriorityMessage(node.id),\n };\n}\n\nasync function collectLiveStatusSessions(ctx: MeshContext, node: LocalMeshNodeEntry): Promise<any[]> {\n try {\n const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {});\n return extractStatusMetadataSessions(statusResult);\n } catch {\n return [];\n }\n}\n\nfunction readNumeric(value: unknown, fallback = 0): number {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : fallback;\n}\n\nfunction buildBranchConvergence(\n mesh: LocalMeshEntry,\n node: LocalMeshNodeEntry,\n status: any,\n dirty: boolean,\n uncommittedChanges: number,\n): Record<string, unknown> {\n const defaultBranch = readString(mesh.defaultBranch) ?? 'main';\n const branch = readString(status?.branch) ?? readString(node.worktreeBranch) ?? null;\n const ahead = readNumeric(status?.ahead);\n const behind = readNumeric(status?.behind);\n const upstream = readString(status?.upstream) ?? null;\n const upstreamStatus = readString(status?.upstreamStatus) ?? (upstream ? 'unchecked' : 'no_upstream');\n const hasConflicts = status?.hasConflicts === true || (Array.isArray(status?.conflictFiles) && status.conflictFiles.length > 0);\n const base = {\n defaultBranch,\n branch,\n upstream,\n upstreamStatus,\n ahead,\n behind,\n isWorktree: node.isLocalWorktree === true,\n isDefaultBranch: branch === defaultBranch,\n };\n\n if (status?.isGitRepo !== true) {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'git_status_unavailable',\n nextStep: `Resolve git status for node '${node.id}' before marking the task complete.`,\n };\n }\n\n if (!branch) {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'branch_unknown',\n nextStep: `Inspect node '${node.id}' git branch before deciding whether it is merged to ${defaultBranch}.`,\n };\n }\n\n if (hasConflicts || dirty || uncommittedChanges > 0) {\n return {\n ...base,\n status: 'not_mergeable',\n needsConvergence: true,\n reason: hasConflicts ? 'conflicts_present' : 'dirty_workspace',\n nextStep: `Commit, checkpoint, or resolve node '${node.id}' before any main convergence step.`,\n };\n }\n\n if (branch === defaultBranch) {\n if (upstream && upstreamStatus !== 'fresh') {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'default_branch_upstream_unverified',\n nextStep: `Refresh ${defaultBranch}'s upstream refs or resolve the fetch failure before declaring convergence complete for node '${node.id}'.`,\n };\n }\n if (ahead > 0 || behind > 0) {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'default_branch_not_even_with_upstream',\n nextStep: `Bring ${defaultBranch} even with its upstream before declaring convergence complete.`,\n };\n }\n return {\n ...base,\n status: 'merged_to_main',\n needsConvergence: false,\n reason: 'clean_default_branch',\n nextStep: null,\n };\n }\n\n if (node.isLocalWorktree) {\n return {\n ...base,\n status: 'cleanup_candidate',\n needsConvergence: true,\n reason: 'clean_non_default_worktree_branch',\n nextStep: `Run mesh_refine_node(node_id: \"${node.id}\") or explicitly classify this worktree as blocked_review/not_mergeable before ending the task.`,\n };\n }\n\n if (upstream && upstreamStatus !== 'fresh') {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'feature_branch_upstream_unverified',\n nextStep: `Refresh branch '${branch}' upstream refs or resolve the fetch failure before deciding whether it is ready to merge into ${defaultBranch}.`,\n };\n }\n\n if (!upstream || ahead > 0 || behind > 0) {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: !upstream ? 'feature_branch_missing_upstream' : 'feature_branch_not_even_with_upstream',\n nextStep: `Push or reconcile branch '${branch}', then merge it into ${defaultBranch} or mark it not_mergeable with a reason.`,\n };\n }\n\n return {\n ...base,\n status: 'pushed_feature_branch_needs_merge',\n needsConvergence: true,\n reason: 'clean_non_default_branch',\n nextStep: `Review and merge branch '${branch}' into ${defaultBranch}; do not report the task as fully complete while it remains off main.`,\n };\n}\n\nfunction summarizeBranchConvergence(nodes: any[]): Record<string, unknown> {\n const followUps = nodes\n .filter(node => node?.branchConvergence?.needsConvergence === true)\n .map(node => ({\n nodeId: node.nodeId,\n workspace: node.workspace,\n branch: node.branchConvergence.branch,\n status: node.branchConvergence.status,\n reason: node.branchConvergence.reason,\n nextStep: node.branchConvergence.nextStep,\n }));\n\n return {\n needsFollowUp: followUps.length > 0,\n unresolvedCount: followUps.length,\n requiredFinalStates: ['merged_to_main', 'pushed_feature_branch_needs_merge', 'blocked_review', 'cleanup_candidate', 'not_mergeable'],\n followUps,\n };\n}\n\nasync function commandForNode(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n command: string,\n args: Record<string, unknown> = {},\n): Promise<any> {\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n\n if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {\n return ctx.transport.meshCommand(node.daemonId, command, args);\n }\n if (isLocalTransport(ctx.transport)) {\n return ctx.transport.command(command, args);\n }\n const identity = buildNodeMachineIdentity(ctx, node);\n throw new Error(`Command '${command}' requires daemon IPC/local transport for node '${node.id}' (hostname=${identity.hostname || 'unknown'}, coordinatorHostname=${identity.coordinatorHostname || 'unknown'}, sameMachine=${identity.sameMachine})`);\n}\n\nfunction normalizePendingMeshCoordinatorEvents(value: any): any[] {\n const payload = unwrapCommandPayload(value);\n const events = Array.isArray(payload?.events)\n ? payload.events\n : Array.isArray(value?.events)\n ? value.events\n : [];\n return events.filter((event: unknown) => event && typeof event === 'object');\n}\n\nfunction buildMeshForwardPayloadFromPendingEvent(event: any): Record<string, unknown> {\n const metadataEvent = event?.metadataEvent && typeof event.metadataEvent === 'object'\n ? event.metadataEvent as Record<string, unknown>\n : {};\n return {\n event: readString(event?.event),\n meshId: readString(event?.meshId),\n nodeId: readString(event?.nodeId) || readString(metadataEvent.meshNodeId),\n workspace: readString(event?.workspace) || readString(metadataEvent.workspace),\n targetSessionId: readString(metadataEvent.targetSessionId) || readString(metadataEvent.sessionId) || readString(metadataEvent.instanceId),\n providerType: readString(metadataEvent.providerType),\n providerSessionId: readString(metadataEvent.providerSessionId),\n finalSummary: readString(metadataEvent.finalSummary) || readString(metadataEvent.summary),\n jobId: readString(metadataEvent.jobId),\n interactionId: readString(metadataEvent.interactionId),\n status: readString(metadataEvent.status),\n targetDaemonId: readString(metadataEvent.targetDaemonId),\n startedAt: readString(metadataEvent.startedAt),\n completedAt: readString(metadataEvent.completedAt),\n retryOfJobId: readString(metadataEvent.retryOfJobId),\n ...(metadataEvent.result && typeof metadataEvent.result === 'object' && !Array.isArray(metadataEvent.result) ? { result: metadataEvent.result } : {}),\n ...(metadataEvent.intentional === true ? { intentional: true } : {}),\n ...(metadataEvent.intentionalStop === true ? { intentionalStop: true } : {}),\n ...(metadataEvent.operatorCleanup === true ? { operatorCleanup: true } : {}),\n ...(readString(metadataEvent.reason) ? { reason: readString(metadataEvent.reason) } : {}),\n ...(readString(metadataEvent.stopReason) ? { stopReason: readString(metadataEvent.stopReason) } : {}),\n ...(readString(metadataEvent.cleanupReason) ? { cleanupReason: readString(metadataEvent.cleanupReason) } : {}),\n ...(readString(metadataEvent.source) ? { source: readString(metadataEvent.source) } : {}),\n };\n}\n\nasync function drainCoordinatorPendingEvents(\n ctx: MeshContext,\n opts?: { nodeIds?: string[] },\n): Promise<any[]> {\n const requestedNodeIds = opts?.nodeIds?.length ? new Set(opts.nodeIds) : null;\n const matchesCurrentMesh = (event: any) => readString(event?.meshId) === ctx.mesh.id;\n\n if (ctx.transport instanceof IpcTransport) {\n const surfacedEvents: any[] = [];\n\n try {\n surfacedEvents.push(\n ...normalizePendingMeshCoordinatorEvents(await ctx.transport.command('get_pending_mesh_events', { meshId: ctx.mesh.id }) as any)\n .filter(matchesCurrentMesh),\n );\n surfacedEvents.forEach(rememberMeshSessionProviderMetadataFromEvent);\n } catch {\n // Non-fatal: pending events are best-effort.\n }\n\n for (const node of ctx.mesh.nodes) {\n if (!node.daemonId || isLocalControlPlaneNode(ctx, node)) continue;\n if (requestedNodeIds && !requestedNodeIds.has(node.id)) continue;\n\n try {\n const remoteEvents = normalizePendingMeshCoordinatorEvents(\n await ctx.transport.meshCommand(node.daemonId, 'get_pending_mesh_events', { meshId: ctx.mesh.id }),\n ).filter(matchesCurrentMesh);\n if (remoteEvents.length === 0) continue;\n\n for (const event of remoteEvents) {\n const payload = buildMeshForwardPayloadFromPendingEvent(event);\n if (!payload.event || !payload.meshId) continue;\n await ctx.transport.command('mesh_forward_event', payload);\n rememberMeshSessionProviderMetadataFromEvent({ ...event, metadataEvent: payload });\n }\n } catch {\n // Non-fatal: remote pending-event recovery is best-effort.\n }\n }\n\n try {\n surfacedEvents.push(\n ...normalizePendingMeshCoordinatorEvents(await ctx.transport.command('get_pending_mesh_events', { meshId: ctx.mesh.id }) as any)\n .filter(matchesCurrentMesh),\n );\n surfacedEvents.forEach(rememberMeshSessionProviderMetadataFromEvent);\n } catch {\n // Non-fatal: pending events are best-effort.\n }\n\n return surfacedEvents;\n }\n\n if (isLocalTransport(ctx.transport)) {\n const events = (drainPendingMeshCoordinatorEvents(ctx.mesh.id) as any[]).filter(matchesCurrentMesh);\n events.forEach(rememberMeshSessionProviderMetadataFromEvent);\n return events;\n }\n\n return [];\n}\n\nfunction isP2pTransportUnavailableError(error: unknown): boolean {\n return isP2pRelayTransportFailure(error);\n}\n\nfunction buildRemoveNodeArgs(ctx: MeshContext, nodeId: string, sessionCleanupMode?: string): Record<string, unknown> {\n return {\n meshId: ctx.mesh.id,\n nodeId,\n ...(sessionCleanupMode ? { sessionCleanupMode } : {}),\n inlineMesh: ctx.mesh,\n };\n}\n\n// ─── Tool Definitions ───────────────────────────\n\nexport const MESH_STATUS_TOOL = {\n name: 'mesh_status',\n description: 'Get the current status of all nodes in the repo mesh — health, git state, active sessions, recovery hints, and recommended next steps. Use this to decide which node to send work to or how to recover from failures. Do not repeatedly call this to wait for generating delegated work; wait for pendingCoordinatorEvents/completion events or an explicit user status request.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n _gemini_compat: { type: 'string', description: 'Dummy property for Gemini compatibility. Ignore this.' },\n },\n },\n};\n\nexport const MESH_LIST_NODES_TOOL = {\n name: 'mesh_list_nodes',\n description: 'List all nodes in the mesh with their capabilities, platform, and workspace paths.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n _gemini_compat: { type: 'string', description: 'Dummy property for Gemini compatibility. Ignore this.' },\n },\n },\n};\n\nexport const MESH_ENQUEUE_TASK_TOOL = {\n name: 'mesh_enqueue_task',\n description: 'Add a new task to the mesh work queue. Idle nodes will automatically pull and execute tasks from this queue. Use this instead of mesh_send_task when you do not need to target a specific node.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n message: { type: 'string', description: 'The task instruction for the agent.' },\n task_mode: { type: 'string', enum: ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'], description: 'Optional task-mode contract. live_debug_readonly rejects obvious write/commit/push/deploy/destructive instructions before dispatch.' },\n taskMode: { type: 'string', enum: ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'], description: 'CamelCase alias for task_mode.' },\n },\n required: ['message'],\n },\n};\n\nexport const MESH_VIEW_QUEUE_TOOL = {\n name: 'mesh_view_queue',\n description: 'View the mesh work queue with source-of-truth active counts separated from historical completed/failed/cancelled records. Do not repeatedly call this to wait for generating assigned work; wait for pendingCoordinatorEvents/completion events or an explicit user status request.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n status: {\n type: 'array',\n items: { type: 'string' },\n description: 'Explicit row filter by task status: pending, assigned, completed, failed, cancelled. Source-of-truth counts remain unfiltered; visible* counts describe returned rows.',\n },\n view: {\n type: 'string',\n enum: ['all', 'active', 'historical'],\n description: 'Optional row view. active returns pending/assigned rows, historical returns completed/failed/cancelled rows, all returns every persisted queue row. Defaults to all for compatibility.',\n },\n },\n },\n};\n\nexport const MESH_QUEUE_CANCEL_TOOL = {\n name: 'mesh_queue_cancel',\n description: 'Cancel a pending/assigned/completed/failed mesh queue task without deleting audit history. Use this to retire stale queue items that target dead sessions.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n task_id: { type: 'string', description: 'Queue task ID to cancel.' },\n reason: { type: 'string', description: 'Optional operator-visible reason for cancellation.' },\n },\n required: ['task_id'],\n },\n};\n\nexport const MESH_QUEUE_REQUEUE_TOOL = {\n name: 'mesh_queue_requeue',\n description: 'Return a mesh queue task to pending for retry. By default clears stale assigned owner and target session so another live session can claim it.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n task_id: { type: 'string', description: 'Queue task ID to requeue.' },\n reason: { type: 'string', description: 'Optional operator-visible reason for requeueing.' },\n target_node_id: { type: 'string', description: 'Optional replacement target node ID.' },\n target_session_id: { type: 'string', description: 'Optional replacement target runtime session ID.' },\n clear_target_node: { type: 'boolean', description: 'When true, remove any existing target node constraint.' },\n keep_target_session: { type: 'boolean', description: 'When true, preserve an existing target session if target_session_id is not provided. Defaults false to avoid stale session targets.' },\n },\n required: ['task_id'],\n },\n};\n\nexport const MESH_SEND_TASK_TOOL = {\n name: 'mesh_send_task',\n description: 'Legacy push-based task assignment. Enqueues a task specifically targeted at a given node. The node will pull it immediately if idle.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID (from mesh_list_nodes).' },\n session_id: { type: 'string', description: 'Agent session ID on the target node.' },\n message: { type: 'string', description: 'Natural-language task to send to the agent.' },\n task_mode: { type: 'string', enum: ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'], description: 'Optional task-mode contract. live_debug_readonly rejects obvious write/commit/push/deploy/destructive instructions before local or remote direct dispatch.' },\n taskMode: { type: 'string', enum: ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'], description: 'CamelCase alias for task_mode.' },\n },\n required: ['node_id', 'session_id', 'message'],\n },\n};\n\nexport const MESH_READ_CHAT_TOOL = {\n name: 'mesh_read_chat',\n description: 'Read recent chat messages from a delegated agent session on a mesh node. Use compact=true for coordinator context-efficient review: it filters tool/internal/debug chatter and returns the final user-visible summary plus recent key messages. If the runtime session has completed, provider_session_id can explicitly target provider transcript history.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n session_id: { type: 'string', description: 'Agent session ID to read from.' },\n provider_session_id: { type: 'string', description: 'Optional provider transcript/session ID for completed sessions.' },\n tail: { type: 'number', description: 'Number of recent messages to return (default: 10).' },\n compact: { type: 'boolean', description: 'When true, return a compact coordinator summary instead of the full transcript: tool/internal/control/debug messages are excluded and only recent user-visible key messages plus the final assistant summary are included.' },\n },\n required: ['node_id', 'session_id'],\n },\n};\n\nexport const MESH_READ_DEBUG_TOOL = {\n name: 'mesh_read_debug',\n description: 'Collect a daemon-side chat/parser debug bundle for a delegated agent session on a mesh node without opening the browser UI. Defaults to daemon_file delivery and returns a saved bundle locator.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n session_id: { type: 'string', description: 'Agent session ID to debug.' },\n provider_session_id: { type: 'string', description: 'Optional provider transcript/session ID for completed session history.' },\n tail: { type: 'number', description: 'Number of recent read_chat messages to embed (default: 40).' },\n delivery: { type: 'string', enum: ['daemon_file', 'inline'], description: 'daemon_file saves the full sanitized bundle on the daemon; inline returns it directly. Default: daemon_file.' },\n },\n required: ['node_id', 'session_id'],\n },\n};\n\nexport const MESH_LAUNCH_SESSION_TOOL = {\n name: 'mesh_launch_session',\n description: 'Launch a new agent session on a mesh node. Returns the session ID for subsequent send_task/read_chat calls. If the user names a provider, preserve it exactly: Hermes = hermes-cli, Claude Code/Claude = claude-cli, Codex = codex-cli, Gemini = gemini-cli. If type is omitted, resolve strictly from the node policy providerPriority and provider detection; fail closed when no configured provider is usable. Do not default to claude-cli.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n type: { type: 'string', description: 'Optional provider type to launch. Use hermes-cli for Hermes, claude-cli for Claude Code, codex-cli for Codex, gemini-cli for Gemini. When omitted, node.policy.providerPriority is probed in order.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_GIT_STATUS_TOOL = {\n name: 'mesh_git_status',\n description: 'Get git status for a mesh node workspace — branch, dirty state, changed files.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_FAST_FORWARD_NODE_TOOL = {\n name: 'mesh_fast_forward_node',\n description: 'Safely dry-run or execute an obvious direct fast-forward for a mesh node without launching an agent session. Defaults to dry-run; execution requires execute=true. Never pushes, rebases, resets, cleans, or checks out arbitrary revisions.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n branch: { type: 'string', description: 'Optional guard: require the node\\'s current branch to match this branch before planning/executing.' },\n execute: { type: 'boolean', description: 'When true, apply the fast-forward if all safety gates pass. Defaults false/dry-run.' },\n dry_run: { type: 'boolean', description: 'Preview only. Defaults true unless execute=true; dry_run=true overrides execute.' },\n update_submodules: { type: 'boolean', description: 'When true, if the root fast-forward changes gitlinks, run only git submodule update --init --recursive and verify submodules clean.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_CHECKPOINT_TOOL = {\n name: 'mesh_checkpoint',\n description: 'Create a git checkpoint (commit) on a mesh node workspace.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n message: { type: 'string', description: 'Checkpoint commit message.' },\n },\n required: ['node_id', 'message'],\n },\n};\n\nexport const MESH_APPROVE_TOOL = {\n name: 'mesh_approve',\n description: 'Approve or reject a pending action on a delegated agent session.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n session_id: { type: 'string', description: 'Agent session ID with pending approval.' },\n action: { type: 'string', enum: ['approve', 'reject'], description: 'Action to take.' },\n },\n required: ['node_id', 'session_id', 'action'],\n },\n};\n\nexport const MESH_CLONE_NODE_TOOL = {\n name: 'mesh_clone_node',\n description: 'Create a new worktree-based node from an existing node for isolated parallel work. '\n + 'Creates a git worktree on a new branch so multiple tasks can run on separate branches simultaneously.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n source_node_id: { type: 'string', description: 'Node ID to clone from (from mesh_list_nodes).' },\n branch: { type: 'string', description: 'Branch name for the new worktree (e.g. \"feat/auth-refactor\").' },\n base_branch: { type: 'string', description: 'Starting point for the branch (default: current HEAD).' },\n },\n required: ['source_node_id', 'branch'],\n },\n};\n\nexport const MESH_REMOVE_NODE_TOOL = {\n name: 'mesh_remove_node',\n description: 'Remove a node from the mesh. If the node is a worktree, also cleans up the git worktree and directory. Session cleanup is controlled by mesh policy sessionCleanupOnNodeRemove unless session_cleanup_mode overrides it for this call.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Node ID to remove.' },\n session_cleanup_mode: {\n type: 'string',\n enum: ['preserve', 'stop', 'delete_stopped', 'stop_and_delete'],\n description: 'Optional override for cleanup of delegated sessions attached to this node. preserve keeps history/processes; stop stops live runtimes only; delete_stopped removes completed transcripts only; stop_and_delete stops live runtimes and deletes records.',\n },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_CLEANUP_SESSIONS_TOOL = {\n name: 'mesh_cleanup_sessions',\n description: 'Manually clean up delegated session records for a mesh node without removing the node. Defaults should preserve reviewable history unless the caller chooses a mode explicitly.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Node ID whose delegated sessions should be considered for cleanup.' },\n mode: {\n type: 'string',\n enum: ['preserve', 'stop', 'delete_stopped', 'stop_and_delete'],\n description: 'preserve = no-op; stop = release process occupancy by stopping live runtimes; delete_stopped = remove completed/stopped records while leaving live runtimes alone; stop_and_delete = stop live runtimes and delete records.',\n },\n session_ids: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional explicit session IDs to limit cleanup to. When omitted, sessions are matched by node/workspace metadata.',\n },\n dry_run: { type: 'boolean', description: 'Preview matched/stopped/deleted/skipped session IDs without mutating session-host state.' },\n },\n required: ['node_id', 'mode'],\n },\n};\n\nexport const MESH_TASK_HISTORY_TOOL = {\n name: 'mesh_task_history',\n description: 'Read the task ledger for this mesh — dispatched tasks, completions, failures, checkpoints, and node lifecycle events. Use to understand what has been done before deciding next steps, to detect repeated failures, and to inform recovery decisions.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n tail: { type: 'number', description: 'Number of recent entries to return (default: 20).' },\n kind: { type: 'string', description: 'Filter by entry kind: task_dispatched, task_completed, task_failed, task_stalled, session_launched, checkpoint_created, node_cloned, node_removed, direct_fast_forward.' },\n },\n },\n};\n\nexport const MESH_RECONCILE_LEDGER_TOOL = {\n name: 'mesh_reconcile_ledger',\n description: 'Reconcile daemon-local mesh ledgers by querying bounded ledger slices over P2P/DataChannel and importing missing entries into the coordinator local JSONL ledger. Cloud/D1 is not used as a ledger source of truth.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_ids: { type: 'array', items: { type: 'string' }, description: 'Optional node IDs to query. Defaults to all mesh nodes.' },\n limit: { type: 'number', description: 'Bounded slice size per node. Defaults to 100 and is clamped by daemon-core.' },\n after_id: { type: 'string', description: 'Optional cursor entry ID; remote slices return entries strictly after this ID when present.' },\n since: { type: 'string', description: 'Optional ISO timestamp lower bound for queried entries.' },\n import_entries: { type: 'boolean', description: 'When false, query and report evidence without importing remote entries. Defaults true.' },\n },\n },\n};\n\nexport const MESH_REFINE_NODE_TOOL = {\n name: 'mesh_refine_node',\n description: 'The Refinery: Accept an async validation/merge/cleanup job for a completed worktree node. The immediate response includes async:true, status:\\'accepted\\', jobId, interactionId, target node, and startedAt; completion/failure evidence is delivered through pending mesh events and the mesh task ledger.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Node ID of the completed worktree node to refine and merge.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_REFINE_CONFIG_SCHEMA_TOOL = {\n name: 'mesh_refine_config_schema',\n description: 'Return the Repo Mesh Refinery config JSON schema and supported repo-local config locations. This is the validation source of truth; heuristic command detection is suggestions-only.',\n inputSchema: { type: 'object' as const, properties: {} },\n};\n\nexport const MESH_VALIDATE_REFINE_CONFIG_TOOL = {\n name: 'mesh_validate_refine_config',\n description: 'Validate the repo mesh/refine config for a node/workspace without running validation commands or merging.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Optional node/workspace whose refine config should be loaded. Defaults to the first mesh node.' },\n config: { type: 'object', description: 'Optional inline config object to validate instead of loading from the repo.' },\n },\n },\n};\n\nexport const MESH_SUGGEST_REFINE_CONFIG_TOOL = {\n name: 'mesh_suggest_refine_config',\n description: 'Suggest a repo mesh/refine config scaffold from project context/package scripts. Suggestions are never executed until saved as explicit refine config.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Optional node/workspace used for suggestions. Defaults to the first mesh node.' },\n },\n },\n};\n\nexport const MESH_REFINE_PLAN_TOOL = {\n name: 'mesh_refine_plan',\n description: 'Dry-run Refinery plan for a worktree node: reports config source, validation commands, suggestions/unavailable reason, and merge/cleanup intent without executing validation or git merge.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Node ID of the worktree node to plan.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const ALL_MESH_TOOLS = [\n MESH_STATUS_TOOL,\n MESH_LIST_NODES_TOOL,\n MESH_ENQUEUE_TASK_TOOL,\n MESH_VIEW_QUEUE_TOOL,\n MESH_QUEUE_CANCEL_TOOL,\n MESH_QUEUE_REQUEUE_TOOL,\n MESH_SEND_TASK_TOOL,\n MESH_READ_CHAT_TOOL,\n MESH_READ_DEBUG_TOOL,\n MESH_LAUNCH_SESSION_TOOL,\n MESH_GIT_STATUS_TOOL,\n MESH_FAST_FORWARD_NODE_TOOL,\n MESH_CHECKPOINT_TOOL,\n MESH_APPROVE_TOOL,\n MESH_CLONE_NODE_TOOL,\n MESH_REMOVE_NODE_TOOL,\n MESH_REFINE_NODE_TOOL,\n MESH_REFINE_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_REFINE_CONFIG_TOOL,\n MESH_SUGGEST_REFINE_CONFIG_TOOL,\n MESH_REFINE_PLAN_TOOL,\n MESH_CLEANUP_SESSIONS_TOOL,\n MESH_TASK_HISTORY_TOOL,\n MESH_RECONCILE_LEDGER_TOOL,\n];\n\n// ─── Tool Implementations ───────────────────────\n\nexport async function meshStatus(ctx: MeshContext): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const { mesh, transport } = ctx;\n const results: any[] = [];\n\n const ledgerSummary = getLedgerSummary(mesh.id);\n\n for (const node of mesh.nodes) {\n const entry: any = {\n nodeId: node.id,\n workspace: node.workspace,\n machine: buildNodeMachineIdentity(ctx, node),\n daemonId: readNodeDaemonId(node),\n machineId: readNodeMachineId(node),\n ...getNodeLaunchReadiness(node),\n };\n\n try {\n if (!isLocalTransport(transport) && node.daemonId) {\n const result = await (transport as CloudTransport).gitStatus(node.daemonId, node.workspace, false, true);\n const status = extractGitStatus(result);\n const uncommittedChanges = countUncommittedChanges(status);\n const dirty = isGitStatusDirty(status);\n entry.health = status?.isGitRepo ? (dirty ? 'dirty' : 'online') : 'degraded';\n assignFullGitSnapshot(entry, status);\n entry.branch = status?.branch;\n entry.isDirty = dirty;\n entry.uncommittedChanges = uncommittedChanges;\n entry.branchConvergence = buildBranchConvergence(mesh, node, status, dirty, uncommittedChanges);\n // Submodule out-of-sync warning\n const submodules = extractSubmodules(result, (node.policy as any)?.submoduleIgnorePaths || []);\n if (submodules && submodules.some((s: any) => s?.outOfSync)) {\n entry.submoduleWarning = 'One or more submodules are out of sync with the parent repo. Run `git submodule update` or check deployment readiness.';\n entry.outOfSyncSubmodules = submodules.filter((s: any) => s?.outOfSync).map((s: any) => s.path);\n }\n } else if (isLocalTransport(transport)) {\n const autoDiscover = (node.policy as any)?.autoDiscoverSubmodules !== false;\n const statusResult = await commandForNode(ctx, node, 'git_status', {\n workspace: node.workspace,\n refreshUpstream: true,\n includeSubmodules: autoDiscover,\n submoduleIgnorePaths: (node.policy as any)?.submoduleIgnorePaths || undefined,\n });\n const status = extractGitStatus(statusResult);\n const uncommittedChanges = countUncommittedChanges(status);\n const dirty = isGitStatusDirty(status);\n entry.health = status?.isGitRepo ? (dirty ? 'dirty' : 'online') : 'degraded';\n assignFullGitSnapshot(entry, status);\n entry.branch = status?.branch;\n entry.isDirty = dirty;\n entry.uncommittedChanges = uncommittedChanges;\n entry.branchConvergence = buildBranchConvergence(mesh, node, status, dirty, uncommittedChanges);\n // Submodule out-of-sync warning\n const submodules = extractSubmodules(statusResult, (node.policy as any)?.submoduleIgnorePaths || []);\n if (submodules && submodules.some((s: any) => s?.outOfSync)) {\n entry.submoduleWarning = 'One or more submodules are out of sync with the parent repo. Run `git submodule update` or check deployment readiness.';\n entry.outOfSyncSubmodules = submodules.filter((s: any) => s?.outOfSync).map((s: any) => s.path);\n }\n } else {\n entry.health = 'unknown';\n entry.note = 'No daemonId available for cloud status probe';\n }\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'git_status',\n targetDaemonId: node.daemonId,\n nodeId: node.id,\n });\n entry.health = 'degraded';\n entry.error = failure.error;\n entry.degradedReason = failure.recoverable ? 'p2p_relay_failure' : 'git_status_unavailable';\n Object.assign(entry, {\n code: failure.code,\n transport: failure.transport,\n recoverable: failure.recoverable,\n retryRecommended: failure.retryRecommended,\n nextAction: failure.nextAction,\n noFallbackReason: failure.noFallbackReason,\n });\n }\n\n // Recovery Hints & Next-step reporting\n const recoveryContext = getSessionRecoveryContext(mesh.id, { nodeId: node.id });\n if (recoveryContext.consecutiveNodeFailures > 0) {\n entry.recoveryHints = {\n consecutiveFailures: recoveryContext.consecutiveNodeFailures,\n lastTaskMessage: recoveryContext.lastTaskMessage,\n advice: recoveryContext.advice,\n retryRecommended: recoveryContext.retryRecommended,\n };\n }\n\n const activeLaunchFailure = getLatestActiveLaunchFailure(mesh.id, node.id);\n if (activeLaunchFailure && node.isLocalWorktree) {\n entry.health = 'degraded';\n entry.degradedReason = 'worktree_launch_failed';\n entry.launchReady = false;\n entry.launchBlockedReason = activeLaunchFailure.code || 'mesh_launch_failed';\n entry.launchBlockedMessage = activeLaunchFailure.error || 'Previous worktree session launch failed';\n entry.lastLaunchFailure = activeLaunchFailure;\n }\n\n const nextStepHints: string[] = [];\n if (entry.degradedReason === 'worktree_launch_failed') {\n nextStepHints.push(`Retry mesh_launch_session(node_id: \"${node.id}\") after daemon mesh transport/P2P is healthy.`);\n nextStepHints.push(`If retry is not desired, cleanup the orphan worktree node with mesh_remove_node(node_id: \"${node.id}\").`);\n } else if (entry.health === 'online' && node.isLocalWorktree) {\n nextStepHints.push(`Merge worktree to base via mesh_refine_node(node_id: \"${node.id}\")`);\n } else if (entry.health === 'dirty') {\n nextStepHints.push(`Commit changes via mesh_checkpoint(node_id: \"${node.id}\", message: \"...\")`);\n } else if (entry.health === 'degraded' && entry.error?.includes('git')) {\n nextStepHints.push('Initialize git repository or check workspace path.');\n }\n\n if (entry.branchConvergence?.needsConvergence === true && entry.branchConvergence.nextStep) {\n nextStepHints.push(String(entry.branchConvergence.nextStep));\n }\n\n if (recoveryContext.consecutiveNodeFailures > 0) {\n if (recoveryContext.retryRecommended) {\n nextStepHints.push(`Retry task on this node or launch a fresh session.`);\n } else {\n nextStepHints.push(`Consider reassigning work to a different node.`);\n }\n }\n\n if (nextStepHints.length > 0) {\n entry.nextStepHints = nextStepHints;\n }\n\n const relatedRepos = await collectRelatedRepoStatuses(ctx, node);\n if (relatedRepos.length) entry.relatedRepos = relatedRepos;\n\n const liveSessions = await collectLiveStatusSessions(ctx, node);\n if (liveSessions.length > 0) {\n entry.sessions = liveSessions;\n }\n\n results.push(entry);\n }\n\n const activeWorkEvidence = buildMeshActiveWork({\n meshId: mesh.id,\n queue: getQueue(mesh.id),\n ledgerEntries: readLedgerEntries(mesh.id, { tail: 500 }),\n nodes: results,\n });\n\n const pollingGuidance = buildActiveWorkPollingGuidance(activeWorkEvidence.summary);\n const response: Record<string, unknown> = {\n meshId: mesh.id,\n meshName: mesh.name,\n repoIdentity: mesh.repoIdentity,\n policy: mesh.policy,\n refreshedAt: new Date().toISOString(),\n sourceOfTruth: {\n membership: 'coordinator_daemon_live_mesh',\n currentStatus: 'live_git_and_session_probes',\n activeWork: 'mesh_queue_file_and_local_ledger',\n historicalEvidenceOnly: ['recoveryHints', 'ledgerSummary'],\n },\n nodes: results,\n activeWork: activeWorkEvidence.activeWork,\n staleDirectWork: activeWorkEvidence.staleDirectWork,\n terminalDirectWork: activeWorkEvidence.terminalDirectWork,\n activeWorkSummary: activeWorkEvidence.summary,\n ...(pollingGuidance ? { pollingGuidance } : {}),\n branchConvergenceSummary: summarizeBranchConvergence(results),\n };\n\n // Include task ledger summary for coordinator context\n try {\n response.ledgerSummary = ledgerSummary;\n } catch { /* ledger read is best-effort */ }\n\n try {\n const pendingEvents = await drainCoordinatorPendingEvents(ctx);\n if (pendingEvents.length > 0) {\n response.pendingCoordinatorEvents = pendingEvents;\n }\n } catch {\n // Non-fatal: pending events are best-effort.\n }\n\n return JSON.stringify(response, null, 2);\n}\n\nexport async function meshTaskHistory(\n ctx: MeshContext,\n args: { tail?: number; kind?: string },\n): Promise<string> {\n const { mesh } = ctx;\n const pendingEvents = await drainCoordinatorPendingEvents(ctx);\n const tail = typeof args.tail === 'number' && args.tail > 0 ? args.tail : 20;\n const kind = typeof args.kind === 'string' && args.kind.trim() ? [args.kind.trim() as any] : undefined;\n const entries = readLedgerEntries(mesh.id, { tail, kind });\n const summary = getLedgerSummary(mesh.id);\n return JSON.stringify({\n meshId: mesh.id,\n entries,\n summary,\n ...(pendingEvents.length > 0 ? { pendingCoordinatorEvents: pendingEvents } : {}),\n }, null, 2);\n}\n\nexport async function meshReconcileLedger(\n ctx: MeshContext,\n args: { node_ids?: string[]; limit?: number; after_id?: string; since?: string; import_entries?: boolean },\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const requestedNodeIds = Array.isArray(args.node_ids)\n ? new Set(args.node_ids.map(id => typeof id === 'string' ? id.trim() : '').filter(Boolean))\n : null;\n const nodes = ctx.mesh.nodes.filter(node => !requestedNodeIds || requestedNodeIds.has(node.id));\n const replicas: any[] = [];\n const shouldImport = args.import_entries !== false;\n const queryArgs = {\n meshId: ctx.mesh.id,\n ...(typeof args.limit === 'number' ? { limit: args.limit } : {}),\n ...(typeof args.after_id === 'string' && args.after_id.trim() ? { afterId: args.after_id.trim() } : {}),\n ...(typeof args.since === 'string' && args.since.trim() ? { since: args.since.trim() } : {}),\n };\n\n for (const node of nodes) {\n try {\n if (isLocalControlPlaneNode(ctx, node) || !node.daemonId) {\n const slice = readLedgerSlice(ctx.mesh.id, queryArgs);\n replicas.push(buildMeshLedgerReplicaEvidence({\n nodeId: node.id,\n daemonId: node.daemonId,\n transport: 'local',\n slice,\n status: 'local',\n }));\n continue;\n }\n\n const result = await commandForNode(ctx, node, 'get_mesh_ledger_slice', queryArgs);\n const payload = unwrapCommandPayload(result);\n if (payload?.success === false) {\n throw new Error(payload.error || 'remote get_mesh_ledger_slice failed');\n }\n const slice = payload?.slice ?? payload;\n if (slice?.protocol !== 'adhdev.mesh.ledger.slice.v1' || !Array.isArray(slice.entries)) {\n throw new Error('remote daemon returned an invalid ledger slice payload');\n }\n const importResult = shouldImport\n ? appendRemoteLedgerEntries(ctx.mesh.id, slice.entries)\n : { accepted: 0, skippedDuplicate: 0, rejectedInvalid: 0, entries: [] };\n replicas.push(buildMeshLedgerReplicaEvidence({\n nodeId: node.id,\n daemonId: node.daemonId,\n transport: 'p2p_datachannel',\n slice,\n importResult,\n }));\n if (shouldImport && importResult.accepted > 0) {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'ledger_replicated',\n nodeId: node.id,\n payload: {\n protocol: 'adhdev.mesh.ledger.slice.v1',\n imported: importResult.accepted,\n skippedDuplicate: importResult.skippedDuplicate,\n rejectedInvalid: importResult.rejectedInvalid,\n nextAfterId: slice.cursor?.nextAfterId ?? null,\n via: 'p2p_datachannel',\n },\n });\n }\n } catch (e: any) {\n replicas.push(buildMeshLedgerReplicaEvidence({\n nodeId: node.id,\n daemonId: node.daemonId,\n transport: node.daemonId ? 'p2p_datachannel' : 'local',\n status: 'failed',\n error: e?.message ?? String(e),\n }));\n }\n }\n\n const evidence = buildMeshLedgerReconciliationEvidence(ctx.mesh.id, replicas);\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'ledger_reconciled',\n payload: {\n protocol: evidence.protocol,\n sourceOfTruth: evidence.sourceOfTruth,\n totals: evidence.totals,\n convergence: evidence.convergence,\n },\n });\n return JSON.stringify({ success: true, evidence }, null, 2);\n}\n\nexport async function meshListNodes(ctx: MeshContext): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const { mesh } = ctx;\n return JSON.stringify({\n meshId: mesh.id,\n meshName: mesh.name,\n nodes: mesh.nodes.map(n => ({\n nodeId: n.id,\n workspace: n.workspace,\n repoRoot: n.repoRoot,\n daemonId: readNodeDaemonId(n),\n machineId: readNodeMachineId(n),\n machine: buildNodeMachineIdentity(ctx, n),\n isLocalWorktree: n.isLocalWorktree,\n policy: n.policy,\n relatedRepos: readRelatedRepos(n),\n ...getNodeLaunchReadiness(n),\n userOverrides: n.userOverrides,\n })),\n }, null, 2);\n}\n\nexport async function meshEnqueueTask(\n ctx: MeshContext,\n args: { message: string; task_mode?: string; taskMode?: string },\n): Promise<string> {\n const taskMode = readString(args.task_mode) || readString(args.taskMode);\n try {\n const task = enqueueTask(ctx.mesh.id, args.message, { taskMode });\n\n // ── LocalTransport: queue-based pull (standalone daemon, all local) ─────\n if (isLocalTransport(ctx.transport) && !(ctx.transport instanceof IpcTransport)) {\n ctx.transport.command('trigger_mesh_queue', { meshId: ctx.mesh.id }).catch(() => {});\n return JSON.stringify({ success: true, source: 'queue', taskId: task.id, status: task.status, taskMode: task.taskMode });\n }\n\n // ── IpcTransport (Cloud Mesh): the queue file lives on THIS machine only.\n // Remote daemons on other machines cannot read the local queue file.\n // Strategy: trigger local queue for local nodes, and for remote nodes\n // directly P2P-dispatch to the first idle session found (enqueue-and-push).\n if (ctx.transport instanceof IpcTransport) {\n // 1. Trigger local queue for local node pick-up\n ctx.transport.command('trigger_mesh_queue', { meshId: ctx.mesh.id }).catch(() => {});\n\n // 2. For each remote node, directly dispatch to an idle session via P2P\n const dispatchPromises: Promise<void>[] = [];\n for (const node of ctx.mesh.nodes) {\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n if (isLocalNode || !node.daemonId) continue;\n\n dispatchPromises.push(\n ipcDispatchToRemoteAgent(ctx, node, { message: args.message })\n .then(result => {\n if (result.success) {\n try {\n const providerType = result.providerType;\n const descriptor = summarizeTaskMessage(args.message);\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'task_dispatched',\n nodeId: node.id,\n sessionId: result.sessionId,\n providerType,\n payload: {\n source: 'queue',\n via: 'p2p_direct',\n taskId: task.id,\n message: args.message,\n taskTitle: descriptor.taskTitle,\n taskSummary: descriptor.taskSummary,\n ...(task.taskMode ? { taskMode: task.taskMode } : {}),\n ...(providerType ? { providerType } : {}),\n targetSessionId: result.sessionId,\n },\n });\n } catch { /* best-effort */ }\n }\n })\n .catch(() => { /* non-fatal: no idle session or P2P failure */ }),\n );\n }\n // Fire-and-forget — don't block the coordinator response\n Promise.all(dispatchPromises).catch(() => {});\n\n return JSON.stringify({ success: true, source: 'queue', taskId: task.id, status: task.status, taskMode: task.taskMode });\n }\n\n // ── CloudTransport fallback ───────────────────────────────────────────────\n return JSON.stringify({ success: true, source: 'queue', taskId: task.id, status: task.status, taskMode: task.taskMode });\n } catch (e: any) {\n const message = e?.message || String(e);\n if (message.includes('live_debug_readonly_guardrail_violation')) {\n return JSON.stringify({ success: false, code: 'live_debug_readonly_guardrail_violation', taskMode, error: message });\n }\n return JSON.stringify({ success: false, error: message });\n }\n}\n\nexport async function meshViewQueue(\n ctx: MeshContext,\n args: { status?: string[]; view?: QueueViewMode },\n): Promise<string> {\n try {\n await refreshMeshFromDaemon(ctx);\n const statusFilter = sanitizeQueueStatusFilter(args.status);\n const view = normalizeQueueViewMode(args.view);\n const fullQueue = prioritizeActiveQueueRows(annotateQueueStaleness(getQueue(ctx.mesh.id), ctx.mesh));\n const queue = filterQueueForView(fullQueue, view, statusFilter);\n const summary = buildQueueStatusSummary(fullQueue);\n const visibleSummary = buildQueueStatusSummary(queue);\n const maintenance = buildQueueMaintenanceReport(fullQueue);\n const activeWorkEvidence = buildMeshActiveWork({\n meshId: ctx.mesh.id,\n queue: fullQueue,\n ledgerEntries: readLedgerEntries(ctx.mesh.id, { tail: 500 }),\n nodes: ctx.mesh.nodes,\n });\n const staleAssignedTasks = (maintenance as any).staleAssignedTasks || [];\n const requestedHistoricalRows = queue.some((task: any) => HISTORICAL_QUEUE_STATUSES.has(String(task?.status || '')));\n const pollingGuidance = buildActiveWorkPollingGuidance(activeWorkEvidence.summary);\n return JSON.stringify({\n success: true,\n sourceOfTruth: {\n kind: 'mesh_work_queue_file',\n activeStatuses: ['pending', 'assigned'],\n historicalStatuses: ['completed', 'failed', 'cancelled'],\n notes: 'pending/assigned are active work; completed/failed/cancelled are historical ledger records and never stale assignments.',\n },\n filter: {\n view,\n statuses: statusFilter,\n filtered: Boolean(statusFilter?.length) || view !== 'all',\n },\n queue,\n visibleQueue: queue,\n activeWork: activeWorkEvidence.activeWork,\n staleDirectWork: activeWorkEvidence.staleDirectWork,\n activeWorkSummary: activeWorkEvidence.summary,\n ...(pollingGuidance ? { pollingGuidance } : {}),\n visibleSummary,\n summary,\n activeCounts: (summary as any).activeCounts,\n historicalCounts: (summary as any).historicalCounts,\n activeCount: (summary as any).activeCount,\n historicalCount: (summary as any).historicalCount,\n visibleActiveCounts: (visibleSummary as any).activeCounts,\n visibleHistoricalCounts: (visibleSummary as any).historicalCounts,\n visibleActiveCount: (visibleSummary as any).activeCount,\n visibleHistoricalCount: (visibleSummary as any).historicalCount,\n staleAssignedTasks,\n staleAssignedCount: (maintenance as any).staleAssignedCount,\n queueMaintenance: maintenance,\n cleanupDryRun: maintenance,\n ...(view === 'active' || statusFilter?.some(status => ACTIVE_QUEUE_STATUSES.has(status)) ? {\n activeQueue: queue.filter((task: any) => ACTIVE_QUEUE_STATUSES.has(String(task?.status || ''))),\n } : {}),\n ...(view === 'historical' || requestedHistoricalRows ? {\n historicalQueue: queue.filter((task: any) => HISTORICAL_QUEUE_STATUSES.has(String(task?.status || ''))),\n } : {}),\n // Back-compat alias for callers already reading the first hardening payload.\n staleAssignments: staleAssignedTasks,\n }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n}\n\nexport async function meshQueueCancel(\n ctx: MeshContext,\n args: { task_id?: string; taskId?: string; reason?: string },\n): Promise<string> {\n try {\n const taskId = (args.task_id || args.taskId || '').trim();\n if (!taskId) return JSON.stringify({ success: false, error: 'task_id required' });\n const task = cancelTask(ctx.mesh.id, taskId, { reason: args.reason });\n if (!task) return JSON.stringify({ success: false, error: `Queue task '${taskId}' not found` });\n if (isLocalTransport(ctx.transport)) {\n ctx.transport.command('trigger_mesh_queue', { meshId: ctx.mesh.id }).catch(() => {});\n }\n return JSON.stringify({ success: true, task }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n}\n\nexport async function meshQueueRequeue(\n ctx: MeshContext,\n args: {\n task_id?: string;\n taskId?: string;\n reason?: string;\n target_node_id?: string;\n targetNodeId?: string;\n target_session_id?: string;\n targetSessionId?: string;\n clear_target_node?: boolean;\n clearTargetNode?: boolean;\n keep_target_session?: boolean;\n keepTargetSession?: boolean;\n },\n): Promise<string> {\n try {\n const taskId = (args.task_id || args.taskId || '').trim();\n if (!taskId) return JSON.stringify({ success: false, error: 'task_id required' });\n const targetNodeId = (args.target_node_id || args.targetNodeId || '').trim() || undefined;\n const targetSessionId = (args.target_session_id || args.targetSessionId || '').trim() || undefined;\n const keepTargetSession = args.keep_target_session === true || args.keepTargetSession === true;\n const task = requeueTask(ctx.mesh.id, taskId, {\n reason: args.reason,\n targetNodeId,\n targetSessionId,\n clearTargetNode: args.clear_target_node === true || args.clearTargetNode === true,\n clearTargetSession: targetSessionId ? false : !keepTargetSession,\n });\n if (!task) return JSON.stringify({ success: false, error: `Queue task '${taskId}' not found` });\n if (isLocalTransport(ctx.transport)) {\n ctx.transport.command('trigger_mesh_queue', { meshId: ctx.mesh.id }).catch(() => {});\n }\n return JSON.stringify({ success: true, task }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n}\n\nexport async function meshSendTask(\n ctx: MeshContext,\n args: { node_id: string; session_id?: string; message: string; task_mode?: string; taskMode?: string },\n): Promise<string> {\n const requestedTaskMode = readString(args.task_mode) || readString(args.taskMode);\n const modeValidation = validateMeshTaskModeRequest(requestedTaskMode, args.message);\n if (!modeValidation.valid) {\n return JSON.stringify({\n success: false,\n code: 'live_debug_readonly_guardrail_violation',\n taskMode: modeValidation.taskMode || requestedTaskMode,\n violations: modeValidation.violations,\n allowedOperations: modeValidation.allowedOperations,\n error: `live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`,\n });\n }\n const taskMode = modeValidation.taskMode;\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n // Policy check: read-only node cannot receive tasks\n if (node.policy?.readOnly) {\n return JSON.stringify({ error: `Node '${args.node_id}' is read-only` });\n }\n\n // Avoid duplicate side effects when an MCP/tool call is interrupted after\n // the daemon already accepted the send and the coordinator retries the\n // exact same node/session/message immediately.\n const duplicate = hasRecentDuplicateDispatch(ctx, args);\n if (duplicate.duplicate) {\n return JSON.stringify({\n success: true,\n duplicate: true,\n dispatched: false,\n warning: 'Duplicate mesh_send_task suppressed: the same node/session/message was dispatched recently.',\n nodeId: args.node_id,\n sessionId: args.session_id,\n source: duplicate.source,\n previousDispatch: duplicate.entry ? {\n id: duplicate.entry.id,\n timestamp: duplicate.entry.timestamp || duplicate.entry.updatedAt || duplicate.entry.createdAt,\n nodeId: duplicate.entry.nodeId || duplicate.entry.targetNodeId || duplicate.entry.assignedNodeId,\n sessionId: duplicate.entry.sessionId || duplicate.entry.targetSessionId || duplicate.entry.assignedSessionId,\n } : undefined,\n });\n }\n\n try {\n // ── CloudTransport: delegate to Cloud API ──────────────────────────────\n if (!isLocalTransport(ctx.transport) && node.daemonId) {\n const res = await (ctx.transport as CloudTransport).meshEnqueueTask(node.daemonId, {\n meshId: ctx.mesh.id,\n message: args.message,\n targetNodeId: args.node_id,\n ...(taskMode ? { taskMode } : {}),\n });\n return JSON.stringify(res);\n }\n\n // ── IpcTransport + remote node: direct P2P agent_command dispatch ──────\n //\n // The local queue file (mesh-ledger/*.queue.json) is stored on THIS\n // machine and is inaccessible to the remote daemon. Sending\n // trigger_mesh_queue to the remote daemon would always be a no-op\n // because it cannot read the queue. Instead we relay agent_command\n // directly over P2P so the remote daemon forwards it to its agent.\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {\n const cached = meshSessionProviderMetadata.get(meshSessionCacheKey(args.node_id, args.session_id || ''));\n const taskId = randomUUID();\n const result = await ipcDispatchToRemoteAgent(ctx, node, {\n session_id: args.session_id,\n message: args.message,\n providerType: cached?.providerType,\n });\n if (result.success) {\n // Record dispatch in ledger so task_history is accurate\n const dispatchedSessionId = args.session_id || result.sessionId;\n try {\n const providerType = result.providerType || cached?.providerType;\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'task_dispatched',\n nodeId: args.node_id,\n sessionId: dispatchedSessionId,\n providerType,\n payload: buildDirectTaskPayload(args.message, 'p2p_direct', {\n taskId,\n taskMode,\n providerType,\n targetSessionId: dispatchedSessionId,\n }),\n });\n } catch { /* best-effort */ }\n }\n return JSON.stringify({\n ...result,\n nodeId: args.node_id,\n sessionId: result.success ? (args.session_id || result.sessionId) : args.session_id,\n ...(result.success ? { source: 'direct', taskId } : {}),\n taskMode,\n ...(result.success && result.providerType ? { providerType: result.providerType } : {}),\n dispatched: result.success === true,\n });\n }\n\n // ── LocalTransport or local IpcTransport node ────────────────────────\n // If the coordinator explicitly targets a runtime session, push directly\n // and surface route failures immediately instead of creating a queue item\n // that can remain pending forever when the session was already stopped.\n if (args.session_id && isLocalTransport(ctx.transport)) {\n const cached = meshSessionProviderMetadata.get(meshSessionCacheKey(args.node_id, args.session_id));\n let resolvedProviderType = cached?.providerType || '';\n if (!resolvedProviderType) {\n const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {});\n const sessions = extractStatusMetadataSessions(statusResult);\n const explicitSession = sessions.find(session => readSessionRecordId(session) === args.session_id);\n if (!explicitSession) {\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_target_session_not_found',\n reason: 'mesh_target_session_not_found',\n transport: 'local_ipc',\n retryRecommended: true,\n nodeId: args.node_id,\n sessionId: args.session_id,\n error: `Local session '${args.session_id}' is not present in live status for node '${args.node_id}'.`,\n nextAction: `Launch a fresh session with mesh_launch_session(node_id: '${args.node_id}') or retry without session_id so Repo Mesh can target a live delegate session.`,\n });\n }\n resolvedProviderType = resolveSessionProviderType(explicitSession);\n if (resolvedProviderType) {\n meshSessionProviderMetadata.set(meshSessionCacheKey(args.node_id, args.session_id), {\n providerType: resolvedProviderType,\n providerSessionId: readString(explicitSession?.providerSessionId) || undefined,\n });\n }\n }\n if (!resolvedProviderType) {\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_target_session_provider_unknown',\n reason: 'mesh_target_session_provider_unknown',\n transport: 'local_ipc',\n retryRecommended: false,\n nodeId: args.node_id,\n sessionId: args.session_id,\n error: `Local session '${args.session_id}' is live but does not expose providerType/cliType, so agent_command cannot be routed safely.`,\n nextAction: `Relaunch the target session on node '${args.node_id}' or retry without session_id so Repo Mesh can pick a session with provider metadata.`,\n });\n }\n const dispatchResult = await commandForNode(ctx, node, 'agent_command', {\n targetSessionId: args.session_id,\n agentType: resolvedProviderType,\n cliType: resolvedProviderType,\n providerType: resolvedProviderType,\n action: 'send_chat',\n message: args.message,\n });\n const dispatchPayload = unwrapCommandPayload(dispatchResult);\n if (dispatchPayload?.success === false || dispatchResult?.success === false) {\n const source = dispatchPayload?.success === false ? dispatchPayload : dispatchResult;\n return JSON.stringify({\n ...(source && typeof source === 'object' ? source : {}),\n success: false,\n nodeId: args.node_id,\n sessionId: args.session_id,\n error: dispatchPayload?.error || dispatchResult?.error || 'agent_command rejected the task',\n });\n }\n const taskId = randomUUID();\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'task_dispatched',\n nodeId: args.node_id,\n sessionId: args.session_id,\n providerType: resolvedProviderType,\n payload: buildDirectTaskPayload(args.message, 'local_direct', {\n taskId,\n taskMode,\n providerType: resolvedProviderType,\n targetSessionId: args.session_id,\n }),\n });\n } catch { /* best-effort */ }\n return JSON.stringify({ success: true, dispatched: true, source: 'direct', taskId, taskMode, providerType: resolvedProviderType, nodeId: args.node_id, sessionId: args.session_id });\n }\n\n // ── Untargeted local task: use queue pull ─────────────────────────────\n const task = enqueueTask(ctx.mesh.id, args.message, {\n targetNodeId: args.node_id,\n targetSessionId: args.session_id,\n taskMode,\n });\n\n if (isLocalTransport(ctx.transport) || ctx.transport instanceof IpcTransport) {\n ctx.transport.command('trigger_mesh_queue', { meshId: ctx.mesh.id }).catch(() => {});\n }\n\n // Also drain any pending coordinator events so the caller sees them inline\n const pendingEvents = isLocalTransport(ctx.transport)\n ? drainPendingMeshCoordinatorEvents(ctx.mesh.id)\n : [];\n\n const result: Record<string, unknown> = { success: true, source: 'queue', nodeId: args.node_id, taskId: task.id, status: task.status, taskMode: task.taskMode };\n if (pendingEvents.length > 0) {\n result.pendingCoordinatorEvents = pendingEvents;\n }\n return JSON.stringify(result);\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'mesh_send_task',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n sessionId: args.session_id,\n });\n return JSON.stringify(failure);\n }\n}\n\nexport async function meshReadChat(\n ctx: MeshContext,\n args: { node_id: string; session_id: string; provider_session_id?: string; tail?: number; compact?: boolean },\n): Promise<string> {\n const node = await findOptionalNodeWithRefresh(ctx, args.node_id);\n if (!node) {\n return JSON.stringify(buildMissingNodeReadChatRecovery(ctx, args), null, 2);\n }\n\n if (ctx.transport instanceof IpcTransport || isLocalTransport(ctx.transport)) {\n await drainCoordinatorPendingEvents(ctx, { nodeIds: [args.node_id] });\n }\n\n if (isLocalTransport(ctx.transport)) {\n const cached = resolveMeshSessionProviderMetadata(ctx, args.node_id, args.session_id);\n const providerSessionId = typeof args.provider_session_id === 'string' && args.provider_session_id.trim()\n ? args.provider_session_id.trim()\n : cached?.providerSessionId;\n const result = await commandForNode(ctx, node, 'read_chat', {\n sessionId: args.session_id,\n targetSessionId: args.session_id,\n workspace: node.workspace,\n ...(cached?.providerType ? { agentType: cached.providerType, providerType: cached.providerType } : {}),\n ...(providerSessionId ? { providerSessionId } : {}),\n tailLimit: args.tail ?? 10,\n });\n const payload = annotateRapidReadChatAdvisory(unwrapCommandPayload(result) as Record<string, any>, {\n key: `mesh:${args.node_id}:${args.session_id}`,\n toolName: 'mesh_read_chat',\n completionCallbackExpected: true,\n });\n if (args.compact) {\n const compactPayload = compactChatPayload(payload, {\n nodeId: args.node_id,\n sessionId: args.session_id,\n limit: args.tail ?? 10,\n });\n return JSON.stringify(\n payload.pollingAdvisory ? { ...compactPayload, pollingAdvisory: payload.pollingAdvisory } : compactPayload,\n null,\n 2,\n );\n }\n return JSON.stringify(payload, null, 2);\n } else if (!isLocalTransport(ctx.transport) && node.daemonId) {\n try {\n const targetId = `${node.daemonId}:session:${args.session_id}`;\n const res = await (ctx.transport as CloudTransport).readChat(targetId, {\n limit: args.tail ?? 10,\n sessionId: args.session_id,\n });\n return JSON.stringify(res, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n } else {\n return JSON.stringify({ error: 'Cloud mesh read_chat requires node daemonId' });\n }\n}\n\nexport async function meshReadDebug(\n ctx: MeshContext,\n args: { node_id: string; session_id: string; provider_session_id?: string; tail?: number; delivery?: 'daemon_file' | 'inline' },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n if (isLocalTransport(ctx.transport)) {\n const cached = resolveMeshSessionProviderMetadata(ctx, args.node_id, args.session_id);\n const providerSessionId = typeof args.provider_session_id === 'string' && args.provider_session_id.trim()\n ? args.provider_session_id.trim()\n : cached?.providerSessionId;\n const delivery = args.delivery === 'inline' ? undefined : 'daemon_file';\n const result = await commandForNode(ctx, node, 'get_chat_debug_bundle', {\n sessionId: args.session_id,\n targetSessionId: args.session_id,\n workspace: node.workspace,\n ...(cached?.providerType ? { agentType: cached.providerType, providerType: cached.providerType } : {}),\n ...(providerSessionId ? { providerSessionId } : {}),\n tailLimit: args.tail ?? 40,\n ...(delivery ? { delivery } : {}),\n });\n const payload = unwrapCommandPayload(result);\n return JSON.stringify(payload, null, 2);\n } else if (!isLocalTransport(ctx.transport) && node.daemonId) {\n try {\n const targetId = `${node.daemonId}:session:${args.session_id}`;\n const res = await (ctx.transport as CloudTransport).getChatDebugBundle(targetId, {\n sessionId: args.session_id,\n tailLimit: args.tail ?? 40,\n delivery: args.delivery,\n });\n return JSON.stringify(res, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n }\n\n return JSON.stringify({ error: 'Cloud mesh read_debug requires node daemonId' });\n}\n\nexport async function meshLaunchSession(\n ctx: MeshContext,\n args: { node_id: string; type?: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n if (isLocalTransport(ctx.transport)) {\n let resolvedProviderType = typeof args.type === 'string' && args.type.trim() ? args.type : '';\n if (!resolvedProviderType) {\n const providerPriority = readProviderPriority(node.policy);\n if (!providerPriority.length) {\n return JSON.stringify({ success: false, error: missingProviderPriorityMessage(args.node_id) });\n }\n\n const failed: string[] = [];\n for (const providerType of providerPriority) {\n const detectedResult = await commandForNode(ctx, node, 'detect_provider', { providerType });\n const detectedPayload = unwrapCommandPayload(detectedResult);\n if (detectedPayload?.success && detectedPayload?.detected) {\n resolvedProviderType = providerType;\n break;\n }\n failed.push(`${providerType}: ${detectedPayload?.error || 'not detected'}`);\n }\n if (!resolvedProviderType) {\n return JSON.stringify({ success: false, error: `No usable provider detected for node '${args.node_id}' from providerPriority: ${failed.join('; ')}` });\n }\n }\n\n const coordinatorNode = resolveCoordinatorNode(ctx);\n const coordinatorDaemonId = coordinatorNode?.daemonId || ctx.localDaemonId;\n const spawnedSessionVisibility = readSpawnedSessionVisibility(ctx.mesh.policy);\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n if (node.daemonId && !isLocalNode && !coordinatorDaemonId) {\n return JSON.stringify(buildMissingCoordinatorDaemonIdFailure(ctx, node, resolvedProviderType), null, 2);\n }\n let result: any;\n try {\n result = await commandForNode(ctx, node, 'launch_cli', {\n cliType: resolvedProviderType,\n dir: node.workspace,\n settings: {\n meshNodeFor: ctx.mesh.id,\n meshNodeId: args.node_id,\n spawnedSessionVisibility,\n ...(coordinatorDaemonId ? { meshCoordinatorDaemonId: coordinatorDaemonId } : {}),\n ...(coordinatorNode?.id ? { meshCoordinatorNodeId: coordinatorNode.id } : {}),\n launchedByCoordinator: true\n }\n });\n } catch (e: any) {\n return JSON.stringify(recordRecoverableLaunchFailure(ctx, node, resolvedProviderType, e), null, 2);\n }\n const launchPayload = extractLaunchPayload(result);\n if (launchPayload?.success === false || result?.success === false) {\n const launchError = new Error(launchPayload?.error || result?.error || 'launch_cli rejected the session launch');\n return JSON.stringify(recordRecoverableLaunchFailure(ctx, node, resolvedProviderType, launchError), null, 2);\n }\n const runtimeSessionId = typeof launchPayload?.sessionId === 'string'\n ? launchPayload.sessionId\n : typeof launchPayload?.id === 'string'\n ? launchPayload.id\n : typeof launchPayload?.runtimeSessionId === 'string'\n ? launchPayload.runtimeSessionId\n : '';\n const providerSessionId = typeof launchPayload?.providerSessionId === 'string' && launchPayload.providerSessionId.trim()\n ? launchPayload.providerSessionId.trim()\n : undefined;\n if (runtimeSessionId) {\n meshSessionProviderMetadata.set(meshSessionCacheKey(args.node_id, runtimeSessionId), {\n providerType: resolvedProviderType,\n ...(providerSessionId ? { providerSessionId } : {}),\n });\n }\n // Record session launch in ledger\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'session_launched',\n nodeId: args.node_id,\n sessionId: runtimeSessionId || undefined,\n providerType: resolvedProviderType,\n payload: { providerSessionId },\n });\n } catch { /* ledger append is best-effort */ }\n\n // Tell daemon to trigger queue processing so the new session immediately picks up pending tasks\n if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {\n ctx.transport.meshCommand(node.daemonId, 'trigger_mesh_queue', { meshId: ctx.mesh.id }).catch(() => {});\n } else if (isLocalTransport(ctx.transport)) {\n ctx.transport.command('trigger_mesh_queue', { meshId: ctx.mesh.id }).catch(() => {});\n }\n\n return JSON.stringify({\n ...launchPayload,\n resolvedProviderType,\n ...(providerSessionId ? { providerSessionId } : {}),\n }, null, 2);\n } else if (!isLocalTransport(ctx.transport) && node.daemonId) {\n let resolvedProviderType = typeof args.type === 'string' && args.type.trim() ? args.type : '';\n if (!resolvedProviderType) {\n const providerPriority = readProviderPriority(node.policy);\n if (!providerPriority.length) {\n return JSON.stringify({ success: false, error: missingProviderPriorityMessage(args.node_id) });\n }\n resolvedProviderType = providerPriority[0]; // Best effort for cloud, skip detection\n }\n\n const coordinatorNode = resolveCoordinatorNode(ctx);\n const coordinatorDaemonId = coordinatorNode?.daemonId || ctx.localDaemonId;\n const spawnedSessionVisibility = readSpawnedSessionVisibility(ctx.mesh.policy);\n if (!coordinatorDaemonId) {\n return JSON.stringify(buildMissingCoordinatorDaemonIdFailure(ctx, node, resolvedProviderType), null, 2);\n }\n\n try {\n const res = await (ctx.transport as CloudTransport).launch(node.daemonId, {\n type: resolvedProviderType,\n dir: node.workspace,\n settings: {\n meshNodeFor: ctx.mesh.id,\n meshNodeId: args.node_id,\n spawnedSessionVisibility,\n ...(coordinatorDaemonId ? { meshCoordinatorDaemonId: coordinatorDaemonId } : {}),\n ...(coordinatorNode?.id ? { meshCoordinatorNodeId: coordinatorNode.id } : {}),\n launchedByCoordinator: true\n }\n });\n\n const runtimeSessionId = typeof res?.sessionId === 'string' ? res.sessionId : typeof res?.id === 'string' ? res.id : '';\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'session_launched',\n nodeId: args.node_id,\n sessionId: runtimeSessionId || undefined,\n providerType: resolvedProviderType,\n payload: {},\n });\n } catch { /* best-effort */ }\n\n return JSON.stringify({ ...res, resolvedProviderType }, null, 2);\n } catch (e: any) {\n return JSON.stringify(recordRecoverableLaunchFailure(ctx, node, resolvedProviderType, e), null, 2);\n }\n } else {\n return JSON.stringify({ error: 'Cloud mesh launch_session requires node daemonId' });\n }\n}\n\nexport async function meshGitStatus(\n ctx: MeshContext,\n args: { node_id: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n // Determine submodule options from node policy\n const autoDiscoverSubmodules = (node.policy as any)?.autoDiscoverSubmodules !== false;\n const submoduleIgnorePaths = (node.policy as any)?.submoduleIgnorePaths || [];\n\n try {\n if (!isLocalTransport(ctx.transport) && node.daemonId) {\n const result = await (ctx.transport as CloudTransport).gitStatus(node.daemonId, node.workspace, true, true);\n return JSON.stringify({\n nodeId: args.node_id,\n workspace: node.workspace,\n status: extractGitStatus(result),\n diff: extractGitDiff(result),\n submodules: autoDiscoverSubmodules ? extractSubmodules(result, submoduleIgnorePaths) : undefined,\n relatedRepos: await collectRelatedRepoStatuses(ctx, node),\n }, null, 2);\n } else if (isLocalTransport(ctx.transport)) {\n const statusResult = await commandForNode(ctx, node, 'git_status', {\n workspace: node.workspace,\n refreshUpstream: true,\n includeSubmodules: autoDiscoverSubmodules,\n submoduleIgnorePaths: submoduleIgnorePaths.length > 0 ? submoduleIgnorePaths : undefined,\n });\n const diffResult = await commandForNode(ctx, node, 'git_diff_summary', {\n workspace: node.workspace,\n });\n return JSON.stringify({\n nodeId: args.node_id,\n workspace: node.workspace,\n status: extractGitStatus(statusResult),\n diff: extractGitDiff(diffResult),\n submodules: autoDiscoverSubmodules ? extractSubmodules(statusResult, submoduleIgnorePaths) : undefined,\n relatedRepos: await collectRelatedRepoStatuses(ctx, node),\n }, null, 2);\n } else {\n return JSON.stringify({ error: 'No daemonId available for cloud git_status probe' });\n }\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'git_status',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n });\n return JSON.stringify({\n ...failure,\n workspace: node.workspace,\n }, null, 2);\n }\n}\n\nexport async function meshFastForwardNode(\n ctx: MeshContext,\n args: { node_id: string; branch?: string; execute?: boolean; dry_run?: boolean; update_submodules?: boolean },\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const node = await findNodeWithRefresh(ctx, args.node_id);\n const submoduleIgnorePaths = (node.policy as any)?.submoduleIgnorePaths || [];\n\n if (node.policy?.readOnly) {\n return JSON.stringify({\n success: false,\n code: 'node_read_only',\n nodeId: args.node_id,\n workspace: node.workspace,\n allowed: false,\n willRun: false,\n executed: false,\n blockingReasons: ['node_read_only'],\n }, null, 2);\n }\n\n try {\n const dryRun = args.dry_run === true || args.execute !== true;\n const result = await commandForNode(ctx, node, 'fast_forward_mesh_node', {\n meshId: ctx.mesh.id,\n nodeId: node.id,\n workspace: node.workspace,\n branch: typeof args.branch === 'string' ? args.branch : undefined,\n execute: args.execute === true && args.dry_run !== true,\n dryRun,\n updateSubmodules: args.update_submodules === true,\n submoduleIgnorePaths: submoduleIgnorePaths.length > 0 ? submoduleIgnorePaths : undefined,\n });\n return JSON.stringify(unwrapCommandPayload(result), null, 2);\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'fast_forward_mesh_node',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n });\n return JSON.stringify({\n ...failure,\n workspace: node.workspace,\n allowed: false,\n willRun: false,\n executed: false,\n blockingReasons: [failure.code || 'mesh_fast_forward_unavailable'],\n }, null, 2);\n }\n}\n\nexport async function meshCheckpoint(\n ctx: MeshContext,\n args: { node_id: string; message: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n // Policy checks\n if (node.policy?.readOnly) {\n return JSON.stringify({ error: `Node '${args.node_id}' is read-only — cannot checkpoint` });\n }\n\n if (isLocalTransport(ctx.transport)) {\n const result = await commandForNode(ctx, node, 'git_checkpoint', {\n workspace: node.workspace,\n message: args.message,\n includeUntracked: true,\n });\n\n // Record checkpoint in ledger\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'checkpoint_created',\n nodeId: args.node_id,\n payload: { message: args.message, commit: (result as any)?.checkpoint?.commit },\n });\n } catch { /* ledger append is best-effort */ }\n\n return JSON.stringify(result, null, 2);\n } else if (!isLocalTransport(ctx.transport) && node.daemonId) {\n try {\n const res = await (ctx.transport as CloudTransport).gitCheckpoint(node.daemonId, {\n workspace: node.workspace,\n message: args.message,\n includeUntracked: true,\n });\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'checkpoint_created',\n nodeId: args.node_id,\n payload: { message: args.message, commit: (res as any)?.checkpoint?.commit },\n });\n } catch { /* best-effort */ }\n return JSON.stringify(res, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n } else {\n return JSON.stringify({ error: 'Cloud mesh checkpoint requires node daemonId' });\n }\n}\n\nexport async function meshApprove(\n ctx: MeshContext,\n args: { node_id: string; session_id: string; action: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id); // membership check\n\n if (isLocalTransport(ctx.transport)) {\n const cached = meshSessionProviderMetadata.get(meshSessionCacheKey(args.node_id, args.session_id));\n const providerSessionId = cached?.providerSessionId;\n const result = await commandForNode(ctx, node, 'resolve_action', {\n sessionId: args.session_id,\n targetSessionId: args.session_id,\n workspace: node.workspace,\n ...(cached?.providerType ? { agentType: cached.providerType, providerType: cached.providerType } : {}),\n ...(providerSessionId ? { providerSessionId } : {}),\n action: args.action === 'reject' ? 'reject' : 'approve',\n });\n return JSON.stringify(result, null, 2);\n } else if (!isLocalTransport(ctx.transport) && node.daemonId) {\n try {\n const targetId = `${node.daemonId}:session:${args.session_id}`;\n const res = await (ctx.transport as CloudTransport).approve(targetId, args.action === 'reject' ? 'reject' : 'approve');\n return JSON.stringify(res, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n } else {\n return JSON.stringify({ error: 'Cloud mesh approve requires node daemonId' });\n }\n}\n\nexport async function meshCloneNode(\n ctx: MeshContext,\n args: { source_node_id: string; branch: string; base_branch?: string },\n): Promise<string> {\n const sourceNode = await findNodeWithRefresh(ctx, args.source_node_id);\n\n if (isLocalTransport(ctx.transport)) {\n const result = await commandForNode(ctx, sourceNode, 'clone_mesh_node', {\n meshId: ctx.mesh.id,\n sourceNodeId: args.source_node_id,\n branch: args.branch,\n baseBranch: args.base_branch,\n inlineMesh: ctx.mesh,\n });\n const clonePayload = extractCloneNodePayload(result);\n if (clonePayload?.success && clonePayload.node?.id) {\n const existingIndex = ctx.mesh.nodes.findIndex(n => n.id === clonePayload.node.id);\n if (existingIndex >= 0) ctx.mesh.nodes[existingIndex] = clonePayload.node;\n else ctx.mesh.nodes.push(clonePayload.node);\n ctx.mesh.updatedAt = new Date().toISOString();\n await syncCoordinatorDaemonMeshCache(ctx);\n }\n return JSON.stringify(result, null, 2);\n } else if (!isLocalTransport(ctx.transport) && sourceNode.daemonId) {\n try {\n const res = await (ctx.transport as CloudTransport).meshCloneNode(sourceNode.daemonId, {\n meshId: ctx.mesh.id,\n sourceNodeId: args.source_node_id,\n branch: args.branch,\n baseBranch: args.base_branch,\n inlineMesh: ctx.mesh,\n });\n const clonePayload = extractCloneNodePayload(res);\n if (clonePayload?.success && clonePayload.node?.id) {\n const existingIndex = ctx.mesh.nodes.findIndex(n => n.id === clonePayload.node.id);\n if (existingIndex >= 0) ctx.mesh.nodes[existingIndex] = clonePayload.node;\n else ctx.mesh.nodes.push(clonePayload.node);\n ctx.mesh.updatedAt = new Date().toISOString();\n await syncCoordinatorDaemonMeshCache(ctx);\n }\n return JSON.stringify(res, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n } else {\n return JSON.stringify({ error: 'Cloud mesh clone_node requires source node daemonId' });\n }\n}\n\nexport async function meshCleanupSessions(\n ctx: MeshContext,\n args: { node_id: string; mode: string; session_ids?: string[]; dry_run?: boolean },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n if (isLocalTransport(ctx.transport)) {\n const result = await commandForNode(ctx, node, 'cleanup_mesh_sessions', {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n mode: args.mode,\n sessionIds: args.session_ids,\n dryRun: args.dry_run === true,\n inlineMesh: ctx.mesh,\n });\n return JSON.stringify(result, null, 2);\n } else if (!isLocalTransport(ctx.transport) && node.daemonId) {\n try {\n const res = await (ctx.transport as CloudTransport).meshCleanupSessions(node.daemonId, {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n mode: args.mode,\n sessionIds: args.session_ids,\n dryRun: args.dry_run === true,\n inlineMesh: ctx.mesh,\n });\n return JSON.stringify(res, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n } else {\n return JSON.stringify({ error: 'Cloud mesh cleanup_sessions requires node daemonId' });\n }\n}\n\nexport async function meshRemoveNode(\n ctx: MeshContext,\n args: { node_id: string; session_cleanup_mode?: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n if (isLocalTransport(ctx.transport)) {\n const removeArgs = buildRemoveNodeArgs(ctx, args.node_id, args.session_cleanup_mode);\n let result: any;\n let transportFallback: Record<string, unknown> | undefined;\n try {\n result = await commandForNode(ctx, node, 'remove_mesh_node', removeArgs);\n } catch (e: any) {\n if (ctx.transport instanceof IpcTransport && (node as any).isLocalWorktree && isP2pTransportUnavailableError(e)) {\n result = await ctx.transport.command('remove_mesh_node', removeArgs);\n transportFallback = {\n from: 'p2p_mesh_relay',\n to: 'local_control_plane',\n reason: e?.message || String(e),\n };\n } else {\n return JSON.stringify({\n success: false,\n code: isP2pTransportUnavailableError(e) ? 'p2p_unavailable' : 'mesh_remove_node_failed',\n error: e?.message || String(e),\n recoveryHint: isP2pTransportUnavailableError(e)\n ? 'If this is an ADHDev-managed local worktree, retry from a coordinator connected to the daemon that owns the worktree; dashboard command/data-plane traffic still requires P2P.'\n : 'Inspect mesh_status and retry after resolving the reported failure.',\n }, null, 2);\n }\n }\n if (result?.success && result.removed !== false) {\n const idx = ctx.mesh.nodes.findIndex(n => n.id === args.node_id);\n if (idx >= 0) {\n ctx.mesh.nodes.splice(idx, 1);\n ctx.mesh.updatedAt = new Date().toISOString();\n }\n }\n return JSON.stringify({ ...(result || {}), ...(transportFallback ? { transportFallback } : {}) }, null, 2);\n } else if (!isLocalTransport(ctx.transport) && node.daemonId) {\n try {\n const res = await (ctx.transport as CloudTransport).meshRemoveNode(node.daemonId, {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n ...(args.session_cleanup_mode ? { sessionCleanupMode: args.session_cleanup_mode } : {}),\n inlineMesh: ctx.mesh,\n });\n if (res?.success && res.removed !== false) {\n const idx = ctx.mesh.nodes.findIndex(n => n.id === args.node_id);\n if (idx >= 0) {\n ctx.mesh.nodes.splice(idx, 1);\n ctx.mesh.updatedAt = new Date().toISOString();\n }\n }\n return JSON.stringify(res, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n } else {\n return JSON.stringify({ error: 'Cloud mesh remove_node requires node daemonId' });\n }\n}\n\nfunction resolveRefineConfigNode(ctx: MeshContext, nodeId?: string): LocalMeshNodeEntry {\n if (nodeId) return findNode(ctx.mesh, nodeId);\n const node = ctx.mesh.nodes.find((entry: LocalMeshNodeEntry) => !!entry.workspace);\n if (!node) throw new Error('No mesh node with a workspace is available');\n return node;\n}\n\nexport async function meshRefineConfigSchema(ctx: MeshContext): Promise<string> {\n const node = resolveRefineConfigNode(ctx);\n const result = await commandForNode(ctx, node, 'get_mesh_refine_config_schema', {});\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshValidateRefineConfig(\n ctx: MeshContext,\n args: { node_id?: string; config?: Record<string, unknown> },\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'validate_mesh_refine_config', {\n workspace: node.workspace,\n inlineMesh: ctx.mesh,\n ...(args.config ? { config: args.config } : {}),\n });\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshSuggestRefineConfig(\n ctx: MeshContext,\n args: { node_id?: string },\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'suggest_mesh_refine_config', {\n workspace: node.workspace,\n inlineMesh: ctx.mesh,\n });\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshRefinePlan(\n ctx: MeshContext,\n args: { node_id: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'plan_mesh_refine_node', {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n inlineMesh: ctx.mesh,\n });\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshRefineNode(\n ctx: MeshContext,\n args: { node_id: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n if (isLocalTransport(ctx.transport)) {\n const result = await commandForNode(ctx, node, 'refine_mesh_node', {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n inlineMesh: ctx.mesh,\n });\n if (result?.success && result.async !== true && result.removeResult?.removed !== false) {\n const idx = ctx.mesh.nodes.findIndex(n => n.id === args.node_id);\n if (idx >= 0) {\n ctx.mesh.nodes.splice(idx, 1);\n ctx.mesh.updatedAt = new Date().toISOString();\n }\n }\n return JSON.stringify(result, null, 2);\n } else if (!isLocalTransport(ctx.transport) && node.daemonId) {\n try {\n const res = await (ctx.transport as CloudTransport).meshRefineNode(node.daemonId, {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n inlineMesh: ctx.mesh,\n });\n if (res?.success && res.async !== true && res.removeResult?.removed !== false) {\n const idx = ctx.mesh.nodes.findIndex(n => n.id === args.node_id);\n if (idx >= 0) {\n ctx.mesh.nodes.splice(idx, 1);\n ctx.mesh.updatedAt = new Date().toISOString();\n }\n }\n return JSON.stringify(res, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n } else {\n return JSON.stringify({ error: 'Cloud mesh refine_node requires node daemonId' });\n }\n}\n","/**\n * IpcTransport — WebSocket client for the cloud daemon's local IPC server.\n *\n * This is used by Repo Mesh coordinators launched by `adhdev daemon` (cloud\n * daemon). They run on the same machine as the daemon, but not against the\n * standalone HTTP server at localhost:3847.\n */\n\nconst DEFAULT_IPC_PORT = 19222;\nconst DEFAULT_IPC_PATH = '/ipc';\nconst DEFAULT_IPC_COMMAND_TIMEOUT_MS = 15_000;\nconst IPC_COMMAND_TIMEOUTS_MS: Record<string, number> = {\n mesh_relay_command: 120_000,\n agent_command: 30_000,\n git_status: 45_000,\n git_diff_summary: 45_000,\n fast_forward_mesh_node: 120_000,\n mesh_status: 120_000,\n};\n\nexport interface IpcTransportOptions {\n port?: number;\n path?: string;\n}\n\nexport class IpcTransport {\n private port: number;\n private path: string;\n\n constructor(opts: IpcTransportOptions = {}) {\n this.port = opts.port ?? DEFAULT_IPC_PORT;\n this.path = opts.path || DEFAULT_IPC_PATH;\n }\n\n async ping(): Promise<boolean> {\n try {\n const res = await fetch(`http://127.0.0.1:${this.port}/health`);\n return res.ok;\n } catch {\n return false;\n }\n }\n\n async getStatus(): Promise<any> {\n return this.command('get_status_metadata');\n }\n\n async command(type: string, args: Record<string, unknown> = {}): Promise<any> {\n return this.sendIpcCommand(type, args);\n }\n\n async meshCommand(\n targetDaemonId: string,\n command: string,\n args: Record<string, unknown> = {},\n ): Promise<any> {\n return this.sendIpcCommand('mesh_relay_command', {\n targetDaemonId,\n command,\n args,\n });\n }\n\n private async sendIpcCommand(type: string, args: Record<string, unknown>): Promise<any> {\n const WebSocketCtor = globalThis.WebSocket;\n if (!WebSocketCtor) {\n throw new Error('WebSocket is not available in this Node runtime; Node 20+ is required for daemon IPC mode');\n }\n\n return new Promise((resolve, reject) => {\n const requestId = `mcp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n const ws = new WebSocketCtor(`ws://127.0.0.1:${this.port}${this.path}`);\n let settled = false;\n\n const finish = (fn: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n try { ws.close(); } catch { /* noop */ }\n fn();\n };\n\n const nestedCommand = typeof args?.command === 'string' ? args.command : '';\n const targetDaemonId = typeof args?.targetDaemonId === 'string' ? args.targetDaemonId : '';\n const effectiveType = type === 'mesh_relay_command' && nestedCommand ? nestedCommand : type;\n const timeoutMs = Math.max(\n IPC_COMMAND_TIMEOUTS_MS[type] ?? DEFAULT_IPC_COMMAND_TIMEOUT_MS,\n IPC_COMMAND_TIMEOUTS_MS[effectiveType] ?? DEFAULT_IPC_COMMAND_TIMEOUT_MS,\n );\n const diagnosticParts = [\n `command='${type}'`,\n ...(nestedCommand ? [`relayedCommand='${nestedCommand}'`] : []),\n ...(targetDaemonId ? [`targetDaemonId='${targetDaemonId.slice(0, 12)}'`] : []),\n ...(typeof args?.nodeId === 'string' ? [`nodeId='${args.nodeId}'`] : []),\n ...(typeof args?.workspace === 'string' ? [`workspace='${args.workspace}'`] : []),\n ];\n const timeout = setTimeout(() => {\n finish(() => reject(new Error(`Daemon IPC ${diagnosticParts.join(' ')} timed out after ${Math.round(timeoutMs / 1000)}s (requestId=${requestId})`)));\n }, timeoutMs);\n\n let commandSent = false;\n const send = () => {\n if (commandSent) return;\n commandSent = true;\n ws.send(JSON.stringify({\n type: 'ext:command',\n payload: { command: type, args, requestId },\n }));\n };\n\n ws.addEventListener('open', () => {\n ws.send(JSON.stringify({\n type: 'ext:register',\n payload: {\n ideType: 'mcp-server',\n ideVersion: '1.0.0',\n extensionVersion: '1.0.0',\n instanceId: `mcp-server-${process.pid}`,\n machineId: 'mcp-server',\n workspaceFolders: [],\n },\n }));\n });\n\n ws.addEventListener('message', (event) => {\n try {\n const raw = typeof event.data === 'string' ? event.data : String(event.data);\n const msg = JSON.parse(raw);\n if (msg?.type === 'daemon:welcome') {\n send();\n return;\n }\n if (msg?.type !== 'ext:command_result') return;\n if (msg?.payload?.requestId !== requestId) return;\n const payload = msg.payload;\n if (payload?.success === false) {\n finish(() => reject(new Error(payload.error || `Daemon IPC command '${type}' failed`)));\n return;\n }\n finish(() => resolve(payload?.result ?? payload));\n } catch {\n // Ignore non-JSON or unrelated daemon messages.\n }\n });\n\n ws.addEventListener('error', () => {\n finish(() => reject(new Error(`Cannot connect to daemon IPC at ws://127.0.0.1:${this.port}${this.path}`)));\n });\n });\n }\n}\n","import type { LocalTransport } from './local.js';\nimport type { CloudTransport } from './cloud.js';\nimport type { IpcTransport } from './ipc.js';\n\nexport type CommandTransport = LocalTransport | IpcTransport;\nexport type McpTransport = CommandTransport | CloudTransport;\n\n/**\n * Local/IPC and cloud transports are intentionally detected by an operation that\n * is unique to command-routed daemon modes. CloudTransport also exposes methods\n * like getStatus(targetId), so checking for getStatus incorrectly routes cloud\n * tools through command mode.\n */\nexport function isLocalTransport(\n transport: McpTransport,\n): transport is CommandTransport {\n return typeof (transport as { command?: unknown }).command === 'function';\n}\n","export type CompactChatMessage = Record<string, any>;\n\nfunction isAssistantLike(message: any): boolean {\n const role = String(message?.role ?? '').toLowerCase();\n return role === 'assistant' || role === 'agent';\n}\n\nexport function messageContent(message: any): string {\n const content = message?.content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content.map((part: any) => (typeof part === 'string' ? part : part?.text ?? '')).join('');\n }\n return '';\n}\n\nexport function isCoordinatorVisibleMessage(message: any): boolean {\n if (!message || typeof message !== 'object') return false;\n const role = String(message.role ?? '').toLowerCase();\n if (role === 'tool' || role === 'system' || role === 'debug') return false;\n const kind = String(message.kind ?? message.type ?? message.messageKind ?? '').toLowerCase();\n if (['tool', 'tool_call', 'tool_result', 'terminal', 'internal', 'control', 'debug', 'status'].includes(kind)) return false;\n const meta = message.meta ?? message.metadata;\n if (meta?.internal === true || meta?.debug === true || meta?.control === true || meta?.userVisible === false || meta?.user_visible === false) return false;\n return role === 'user' || role === 'assistant' || role === 'agent';\n}\n\nexport function buildCompactMessageTail(\n visibleMessages: CompactChatMessage[],\n opts: { summary?: string; finalAssistant?: CompactChatMessage | undefined; limit: number },\n): CompactChatMessage[] {\n const summary = typeof opts.summary === 'string' ? opts.summary.trim() : '';\n const shouldOmitSummaryMessage = !!summary\n && !!opts.finalAssistant\n && isAssistantLike(opts.finalAssistant)\n && messageContent(opts.finalAssistant).trim() === summary;\n const sourceMessages = shouldOmitSummaryMessage\n ? visibleMessages.filter((message) => message !== opts.finalAssistant)\n : visibleMessages;\n return sourceMessages.slice(-opts.limit);\n}\n\nexport function compactChatPayload(\n payload: any,\n opts: { sessionId?: string | null; nodeId?: string; limit?: number } = {},\n): any {\n const rawMessages = Array.isArray(payload?.messages) ? payload.messages : [];\n const visible = rawMessages.filter(isCoordinatorVisibleMessage);\n const limit = Math.max(1, Math.min(opts.limit ?? 10, 10));\n const finalAssistant = [...visible].reverse().find((message: any) => {\n const role = String(message?.role ?? '').toLowerCase();\n return (role === 'assistant' || role === 'agent') && messageContent(message).trim();\n });\n const summary = typeof payload?.summary === 'string' && payload.summary.trim()\n ? payload.summary.trim()\n : messageContent(finalAssistant).trim();\n const messages = buildCompactMessageTail(visible, { summary, finalAssistant, limit });\n\n return {\n success: payload?.success !== false,\n compact: true,\n ...(opts.nodeId ? { nodeId: opts.nodeId } : {}),\n ...(opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {}),\n status: payload?.status ?? null,\n providerSessionId: payload?.providerSessionId ?? null,\n totalMessages: rawMessages.length,\n visibleMessages: visible.length,\n filteredMessages: visible.length,\n omittedMessages: Math.max(0, rawMessages.length - visible.length),\n summary,\n ...(payload?.changedFiles !== undefined ? { changedFiles: payload.changedFiles } : {}),\n ...(payload?.testsRun !== undefined ? { testsRun: payload.testsRun } : {}),\n messages,\n };\n}\n","export const RAPID_READ_CHAT_ADVISORY_WINDOW_MS = 5_000;\n\nconst ACTIVE_READ_STATUSES = new Set([\n 'generating',\n 'running',\n 'streaming',\n 'starting',\n 'busy',\n]);\n\ntype RecentRead = {\n at: number;\n status?: string;\n};\n\nexport type RapidReadChatAdvisory = {\n type: 'rapid_read_chat_polling';\n toolName: string;\n windowMs: number;\n elapsedMs: number;\n nextSuggestedReadAt: number;\n completionCallbackExpected: boolean;\n message: string;\n};\n\nconst recentReads = new Map<string, RecentRead>();\n\nexport function clearRapidReadChatAdvisoryStateForTests(): void {\n recentReads.clear();\n}\n\nexport function isActiveReadChatStatus(status: unknown): boolean {\n return typeof status === 'string' && ACTIVE_READ_STATUSES.has(status.toLowerCase());\n}\n\nexport function annotateRapidReadChatAdvisory<T extends Record<string, any>>(\n payload: T,\n options: {\n key: string;\n now?: number;\n status?: unknown;\n toolName: 'read_chat' | 'mesh_read_chat' | string;\n completionCallbackExpected?: boolean;\n },\n): T & { pollingAdvisory?: RapidReadChatAdvisory } {\n const now = options.now ?? Date.now();\n const status = options.status ?? payload?.status ?? payload?.data?.status ?? payload?.result?.status;\n const active = isActiveReadChatStatus(status);\n const previous = recentReads.get(options.key);\n\n if (!active) {\n recentReads.set(options.key, { at: now, status: typeof status === 'string' ? status : undefined });\n return payload;\n }\n\n recentReads.set(options.key, { at: now, status: typeof status === 'string' ? status : undefined });\n\n if (!previous || !isActiveReadChatStatus(previous.status)) return payload;\n const elapsedMs = now - previous.at;\n if (elapsedMs < 0 || elapsedMs >= RAPID_READ_CHAT_ADVISORY_WINDOW_MS) return payload;\n\n return {\n ...payload,\n pollingAdvisory: {\n type: 'rapid_read_chat_polling',\n toolName: options.toolName,\n windowMs: RAPID_READ_CHAT_ADVISORY_WINDOW_MS,\n elapsedMs,\n nextSuggestedReadAt: previous.at + RAPID_READ_CHAT_ADVISORY_WINDOW_MS,\n completionCallbackExpected: Boolean(options.completionCallbackExpected),\n message: `This session is still ${String(status)}. Avoid repeated ${options.toolName} polling for the same generating session; wait for the completion callback/status event or retry after the suggested time if you are debugging a real stall.`,\n },\n };\n}\n","import { ALL_MESH_TOOLS } from './tools/mesh-tools.js';\n\nconst STANDARD_TOOLS = [\n 'list_daemons',\n 'list_sessions',\n 'launch_session',\n 'stop_session',\n 'check_pending',\n 'read_chat',\n 'read_chat_debug',\n 'send_chat',\n 'approve',\n 'git_status',\n 'git_log',\n 'git_diff',\n 'git_checkpoint',\n 'git_push',\n 'screenshot',\n];\n\nexport function buildMcpHelpText(): string {\n const meshTools = ALL_MESH_TOOLS.map(tool => tool.name);\n return `\nADHDev MCP Server\n\nUsage:\n adhdev mcp Local mode (requires standalone daemon)\n adhdev mcp --api-key <key> Cloud mode (ADHDev cloud API)\n adhdev mcp --mode ipc --repo-mesh <mesh_id> Cloud daemon IPC mesh mode\n adhdev-mcp --help Compatibility bin (same server, legacy package entrypoint)\n\nOptions:\n --mode <mode> Transport: local, cloud, or ipc\n --port <n> Standalone or IPC daemon port (defaults: local 3847, ipc 19222)\n --password <pass> Standalone daemon password (if set)\n --api-key <key> ADHDev cloud API key (switches to cloud mode)\n --base-url <url> Override cloud API base URL\n --repo-mesh <mesh_id> Enable mesh mode — exposes only mesh-scoped coordinator tools\n --help Show this help\n\nEnvironment variables:\n ADHDEV_API_KEY API key (cloud mode)\n ADHDEV_PASSWORD Daemon password (local mode)\n ADHDEV_MESH_ID Mesh ID (mesh mode)\n ADHDEV_MCP_TRANSPORT Transport: local, cloud, or ipc\n\nStandard tools: ${STANDARD_TOOLS.join(', ')}\nMesh tools: ${meshTools.join(', ')}\n`.trim();\n}\n","/**\n * ADHDev MCP Server\n *\n * Exposes IDE agent sessions as MCP tools via stdio transport.\n * Three modes:\n * local — talks to standalone daemon at localhost:3847\n * cloud — talks to ADHDev cloud API with an API key\n * ipc — talks to cloud daemon local IPC at localhost:19222\n */\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport os from 'node:os';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { LocalTransport } from './transports/local.js';\nimport { CloudTransport } from './transports/cloud.js';\nimport { IpcTransport } from './transports/ipc.js';\nimport type { McpTransport } from './transports/mode.js';\n\nimport { LIST_SESSIONS_TOOL, listSessions } from './tools/list-sessions.js';\nimport { LIST_DAEMONS_TOOL, listDaemons } from './tools/list-daemons.js';\nimport { READ_CHAT_TOOL, readChat } from './tools/read-chat.js';\nimport { READ_CHAT_DEBUG_TOOL, readChatDebug } from './tools/read-chat-debug.js';\nimport { SEND_CHAT_TOOL, sendChat } from './tools/send-chat.js';\nimport { APPROVE_TOOL, approve } from './tools/approve.js';\nimport { SCREENSHOT_TOOL, screenshot } from './tools/screenshot.js';\nimport { GIT_STATUS_TOOL, gitStatus } from './tools/git-status.js';\nimport { GIT_LOG_TOOL, gitLog } from './tools/git-log.js';\nimport { GIT_DIFF_TOOL, gitDiff } from './tools/git-diff.js';\nimport { GIT_CHECKPOINT_TOOL, gitCheckpoint } from './tools/git-checkpoint.js';\nimport { GIT_PUSH_TOOL, gitPush } from './tools/git-push.js';\nimport { LAUNCH_SESSION_TOOL, launchSession } from './tools/launch-session.js';\nimport { STOP_SESSION_TOOL, stopSession } from './tools/stop-session.js';\nimport { CHECK_PENDING_TOOL, checkPending } from './tools/check-pending.js';\nimport {\n ALL_MESH_TOOLS, meshStatus, meshListNodes, meshSendTask, meshReadChat,\n meshEnqueueTask, meshViewQueue, meshQueueCancel, meshQueueRequeue,\n meshReadDebug,\n meshLaunchSession, meshGitStatus, meshFastForwardNode, meshCheckpoint, meshApprove,\n meshCloneNode, meshRemoveNode, meshRefineNode,\n meshRefineConfigSchema, meshValidateRefineConfig, meshSuggestRefineConfig, meshRefinePlan,\n meshCleanupSessions, meshTaskHistory, meshReconcileLedger\n} from './tools/mesh-tools.js';\nimport type { MeshContext } from './tools/mesh-tools.js';\n\nexport interface AdhdevMcpServerOptions {\n mode: 'local' | 'cloud' | 'ipc';\n // local options\n port?: number;\n password?: string;\n // cloud options\n apiKey?: string;\n baseUrl?: string;\n // mesh mode (optional — restricts tools to mesh-scoped set)\n meshId?: string;\n}\n\nexport async function buildMeshModeCoordinatorPrompt(mesh: any): Promise<string> {\n try {\n const { buildCoordinatorSystemPrompt } = await import('@adhdev/daemon-core');\n return buildCoordinatorSystemPrompt({ mesh });\n } catch (e: any) {\n throw new Error(`Failed to build Repo Mesh coordinator prompt: ${e?.message ?? String(e)}`);\n }\n}\n\nexport async function startMcpServer(opts: AdhdevMcpServerOptions): Promise<void> {\n const transport: McpTransport =\n opts.mode === 'cloud'\n ? new CloudTransport({ apiKey: opts.apiKey!, baseUrl: opts.baseUrl })\n : opts.mode === 'ipc'\n ? new IpcTransport({ port: opts.port })\n : new LocalTransport({ port: opts.port, password: opts.password });\n\n // Verify connectivity before registering tools\n const alive = await transport.ping();\n if (!alive) {\n const hint =\n opts.mode === 'local'\n ? `Make sure the standalone daemon is running (adhdev standalone or npx @adhdev/daemon-standalone).`\n : opts.mode === 'ipc'\n ? `Make sure the cloud daemon is running with local IPC enabled (adhdev daemon).`\n : `Check your API key and network connectivity.`;\n process.stderr.write(`[adhdev-mcp] Cannot reach ${opts.mode} daemon. ${hint}\\n`);\n process.exit(1);\n }\n\n const isLocal = opts.mode === 'local';\n\n // ── Mesh Mode ─────────────────────────────────\n if (opts.meshId) {\n let mesh: any;\n\n // Priority 1: ADHDEV_INLINE_MESH env var (set by daemon in .mcp.json for cloud meshes)\n if (!mesh && process.env.ADHDEV_INLINE_MESH) {\n try {\n mesh = JSON.parse(process.env.ADHDEV_INLINE_MESH);\n process.stderr.write(`[adhdev-mcp] Loaded mesh config from ADHDEV_INLINE_MESH env\\n`);\n } catch (e: any) {\n process.stderr.write(`[adhdev-mcp] Failed to parse ADHDEV_INLINE_MESH: ${e.message}\\n`);\n }\n }\n\n // Priority 2: Cloud API (when running with --api-key)\n if (!mesh && opts.mode === 'cloud' && opts.apiKey) {\n try {\n const base = opts.baseUrl || 'https://api.adhf.dev';\n const res = await fetch(`${base}/api/v1/repo-meshes/${opts.meshId}`, {\n headers: { 'Authorization': `Bearer ${opts.apiKey}`, 'Content-Type': 'application/json' },\n });\n if (res.ok) {\n const data = await res.json() as any;\n const rm = data.mesh;\n const nodes = data.nodes || [];\n // Convert cloud D1 record → LocalMeshEntry shape for mesh tools\n let policy: any = {};\n try { policy = JSON.parse(rm.policy_json || rm.policy || '{}'); } catch { /* */ }\n let coordinator: any = {};\n try { coordinator = JSON.parse(rm.coordinator_json || rm.coordinator_config || '{}'); } catch { /* */ }\n mesh = {\n id: rm.id,\n name: rm.name,\n repoIdentity: rm.repo_identity,\n repoRemoteUrl: rm.repo_remote_url,\n defaultBranch: rm.default_branch,\n policy: {\n requirePreTaskCheckpoint: false,\n requirePostTaskCheckpoint: true,\n requireApprovalForPush: true,\n allowAutoPublishSubmoduleMainCommits: false,\n requireApprovalForDestructiveGit: true,\n dirtyWorkspaceBehavior: 'warn',\n maxParallelTasks: 2,\n spawnedSessionVisibility: 'visible',\n ...policy,\n },\n coordinator,\n nodes: nodes.map((n: any) => ({\n id: n.id,\n workspace: n.workspace,\n repoRoot: n.repo_root,\n daemonId: n.daemon_id,\n userOverrides: {},\n policy: {},\n isLocalWorktree: false,\n })),\n createdAt: rm.created_at,\n updatedAt: rm.updated_at,\n };\n process.stderr.write(`[adhdev-mcp] Loaded mesh config from cloud API\\n`);\n }\n } catch (e: any) {\n process.stderr.write(`[adhdev-mcp] Cloud mesh fetch failed, falling back to local: ${e.message}\\n`);\n }\n }\n\n // Priority 3: Local ~/.adhdev/meshes.json\n if (!mesh) {\n try {\n const { getMesh } = await import('@adhdev/daemon-core');\n mesh = getMesh(opts.meshId);\n } catch (e: any) {\n process.stderr.write(`[adhdev-mcp] Local meshes.json lookup failed: ${e.message}\\n`);\n }\n }\n\n // Fallback: query the running daemon (supports cloud-originating meshes\n // launched via inlineMesh that don't exist in local meshes.json)\n if (!mesh && (transport instanceof LocalTransport || transport instanceof IpcTransport)) {\n try {\n const result = await transport.command('get_mesh', { meshId: opts.meshId });\n if (result?.success && result.mesh) {\n mesh = result.mesh;\n process.stderr.write(`[adhdev-mcp] Loaded mesh config from daemon\\n`);\n }\n } catch (e: any) {\n process.stderr.write(`[adhdev-mcp] Daemon mesh query failed: ${e.message}\\n`);\n }\n }\n\n if (!mesh) {\n process.stderr.write(`[adhdev-mcp] Mesh '${opts.meshId}' not found in ${opts.mode === 'cloud' ? 'cloud or local' : 'local'} config. Use 'adhdev mesh list' to see available meshes.\\n`);\n process.exit(1);\n }\n\n let localDaemonId: string | undefined;\n let localMachineId: string | undefined;\n let coordinatorHostname: string | undefined = os.hostname();\n\n if (transport instanceof LocalTransport || transport instanceof IpcTransport) {\n try {\n const { loadConfig } = await import('@adhdev/daemon-core');\n const cfg = loadConfig();\n if (cfg.registeredMachineId) localMachineId = cfg.registeredMachineId;\n } catch { /* best-effort */ }\n }\n\n if (transport instanceof IpcTransport) {\n try {\n const statusResult = await transport.getStatus();\n const instanceId = typeof statusResult?.status?.instanceId === 'string' ? statusResult.status.instanceId.trim() : '';\n const hostname = typeof statusResult?.status?.hostname === 'string'\n ? statusResult.status.hostname.trim()\n : typeof statusResult?.status?.machine?.hostname === 'string'\n ? statusResult.status.machine.hostname.trim()\n : '';\n if (instanceId) localDaemonId = instanceId;\n if (hostname) coordinatorHostname = hostname;\n } catch { /* best-effort metadata for remote completion forwarding */ }\n }\n\n const meshCtx: MeshContext = { mesh, transport, ...(localDaemonId ? { localDaemonId } : {}), ...(localMachineId ? { localMachineId } : {}), ...(coordinatorHostname ? { coordinatorHostname } : {}) };\n\n const coordinatorPrompt = await buildMeshModeCoordinatorPrompt(mesh);\n\n const server = new Server(\n { name: 'adhdev-mcp-server', version: '0.9.81' },\n { capabilities: { tools: {}, resources: {} } },\n );\n\n // Expose coordinator prompt as MCP resource\n const { ListResourcesRequestSchema, ReadResourceRequestSchema } = await import('@modelcontextprotocol/sdk/types.js');\n server.setRequestHandler(ListResourcesRequestSchema, async () => ({\n resources: [{\n uri: 'coordinator://system-prompt',\n name: 'Coordinator System Prompt',\n description: `System prompt for mesh \"${mesh.name}\" coordinator`,\n mimeType: 'text/plain',\n }],\n }));\n server.setRequestHandler(ReadResourceRequestSchema, async (req) => {\n if (req.params.uri === 'coordinator://system-prompt') {\n return { contents: [{ uri: req.params.uri, mimeType: 'text/plain', text: coordinatorPrompt }] };\n }\n throw new Error(`Unknown resource: ${req.params.uri}`);\n });\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: ALL_MESH_TOOLS }));\n\n server.setRequestHandler(CallToolRequestSchema, async (req) => {\n const { name, arguments: args } = req.params;\n const a = (args ?? {}) as Record<string, any>;\n try {\n let text: string;\n switch (name) {\n case 'mesh_status': text = await meshStatus(meshCtx); break;\n case 'mesh_list_nodes': text = await meshListNodes(meshCtx); break;\n case 'mesh_enqueue_task': text = await meshEnqueueTask(meshCtx, a as any); break;\n case 'mesh_view_queue': text = await meshViewQueue(meshCtx, a as any); break;\n case 'mesh_queue_cancel': text = await meshQueueCancel(meshCtx, a as any); break;\n case 'mesh_queue_requeue': text = await meshQueueRequeue(meshCtx, a as any); break;\n case 'mesh_send_task': text = await meshSendTask(meshCtx, a as any); break;\n case 'mesh_read_chat': text = await meshReadChat(meshCtx, a as any); break;\n case 'mesh_read_debug': text = await meshReadDebug(meshCtx, a as any); break;\n case 'mesh_launch_session': text = await meshLaunchSession(meshCtx, a as any); break;\n case 'mesh_git_status': text = await meshGitStatus(meshCtx, a as any); break;\n case 'mesh_fast_forward_node': text = await meshFastForwardNode(meshCtx, a as any); break;\n case 'mesh_checkpoint': text = await meshCheckpoint(meshCtx, a as any); break;\n case 'mesh_approve': text = await meshApprove(meshCtx, a as any); break;\n case 'mesh_clone_node': text = await meshCloneNode(meshCtx, a as any); break;\n case 'mesh_remove_node': text = await meshRemoveNode(meshCtx, a as any); break;\n case 'mesh_refine_node': text = await meshRefineNode(meshCtx, a as any); break;\n case 'mesh_refine_config_schema': text = await meshRefineConfigSchema(meshCtx); break;\n case 'mesh_validate_refine_config': text = await meshValidateRefineConfig(meshCtx, a as any); break;\n case 'mesh_suggest_refine_config': text = await meshSuggestRefineConfig(meshCtx, a as any); break;\n case 'mesh_refine_plan': text = await meshRefinePlan(meshCtx, a as any); break;\n case 'mesh_cleanup_sessions': text = await meshCleanupSessions(meshCtx, a as any); break;\n case 'mesh_task_history': text = await meshTaskHistory(meshCtx, a as any); break;\n case 'mesh_reconcile_ledger': text = await meshReconcileLedger(meshCtx, a as any); break;\n default: return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n return { content: [{ type: 'text', text }] };\n } catch (err: any) {\n return { content: [{ type: 'text', text: `Error: ${err?.message ?? String(err)}` }], isError: true };\n }\n });\n\n const stdioTransport = new StdioServerTransport();\n await server.connect(stdioTransport);\n process.stderr.write(`[adhdev-mcp] Server running in ${opts.mode} mesh mode — mesh: ${mesh.name} (${mesh.repoIdentity})\\n`);\n return;\n }\n\n // ── Standard Mode ──────────────────────────────\n\n // Tool availability by mode:\n // both: list_sessions, launch_session, read_chat, send_chat, approve, git_status\n // local: + screenshot (requires P2P / local daemon access)\n const allTools = [\n LIST_DAEMONS_TOOL,\n LIST_SESSIONS_TOOL,\n LAUNCH_SESSION_TOOL,\n STOP_SESSION_TOOL,\n CHECK_PENDING_TOOL,\n READ_CHAT_TOOL,\n READ_CHAT_DEBUG_TOOL,\n SEND_CHAT_TOOL,\n APPROVE_TOOL,\n GIT_STATUS_TOOL,\n GIT_LOG_TOOL,\n GIT_DIFF_TOOL,\n GIT_CHECKPOINT_TOOL,\n GIT_PUSH_TOOL,\n ...(isLocal ? [SCREENSHOT_TOOL] : []),\n ];\n\n const server = new Server(\n { name: 'adhdev-mcp-server', version: '0.9.66' },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: allTools }));\n\n server.setRequestHandler(CallToolRequestSchema, async (req) => {\n const { name, arguments: args } = req.params;\n const a = (args ?? {}) as Record<string, any>;\n\n try {\n switch (name) {\n case 'list_daemons': {\n const text = await listDaemons(transport, { format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'list_sessions': {\n const text = await listSessions(transport, { format: a.format, daemon_id: a.daemon_id });\n return { content: [{ type: 'text', text }] };\n }\n case 'read_chat': {\n const text = await readChat(transport, a);\n return { content: [{ type: 'text', text }] };\n }\n case 'read_chat_debug': {\n const text = await readChatDebug(transport, a as any);\n return { content: [{ type: 'text', text }] };\n }\n case 'send_chat': {\n const text = await sendChat(transport, { message: a.message, session_id: a.session_id, daemon_id: a.daemon_id });\n return { content: [{ type: 'text', text }] };\n }\n case 'approve': {\n const action = a.action === 'reject' ? 'reject' : 'approve';\n const text = await approve(transport, { action, session_id: a.session_id, daemon_id: a.daemon_id });\n return { content: [{ type: 'text', text }] };\n }\n case 'screenshot': {\n const result = await screenshot(transport, { session_id: a.session_id });\n if (result.type === 'image') {\n return {\n content: [{ type: 'image', data: result.data, mimeType: result.mimeType }],\n };\n }\n return { content: [{ type: 'text', text: result.text }] };\n }\n case 'git_status': {\n const text = await gitStatus(transport, { workspace: a.workspace, include_diff: a.include_diff, daemon_id: a.daemon_id, format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'git_log': {\n const text = await gitLog(transport, { workspace: a.workspace, limit: a.limit, file: a.file, since: a.since, until: a.until, daemon_id: a.daemon_id, format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'git_diff': {\n const text = await gitDiff(transport, { workspace: a.workspace, file: a.file, max_lines: a.max_lines, staged: a.staged, daemon_id: a.daemon_id, format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'git_checkpoint': {\n const text = await gitCheckpoint(transport, { workspace: a.workspace, message: a.message, include_untracked: a.include_untracked, daemon_id: a.daemon_id });\n return { content: [{ type: 'text', text }] };\n }\n case 'git_push': {\n const text = await gitPush(transport, { workspace: a.workspace, remote: a.remote, branch: a.branch, daemon_id: a.daemon_id });\n return { content: [{ type: 'text', text }] };\n }\n case 'launch_session': {\n const text = await launchSession(transport, {\n type: a.type,\n workspace: a.workspace,\n model: a.model,\n daemon_id: a.daemon_id,\n });\n return { content: [{ type: 'text', text }] };\n }\n case 'stop_session': {\n const text = await stopSession(transport, {\n session_id: a.session_id,\n daemon_id: a.daemon_id,\n type: a.type,\n });\n return { content: [{ type: 'text', text }] };\n }\n case 'check_pending': {\n const text = await checkPending(transport, { daemon_id: a.daemon_id, format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n default:\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n } catch (err: any) {\n return {\n content: [{ type: 'text', text: `Error: ${err?.message ?? String(err)}` }],\n isError: true,\n };\n }\n });\n\n const stdioTransport = new StdioServerTransport();\n await server.connect(stdioTransport);\n process.stderr.write(`[adhdev-mcp] Server running in ${opts.mode} mode.\\n`);\n}\n","/**\n * LocalTransport — HTTP client for standalone daemon at localhost:3847\n */\n\nconst DEFAULT_PORT = 3847;\n\nexport interface LocalTransportOptions {\n port?: number;\n password?: string;\n}\n\nexport class LocalTransport {\n private baseUrl: string;\n private authHeader: string | null;\n\n constructor(opts: LocalTransportOptions = {}) {\n this.baseUrl = `http://localhost:${opts.port ?? DEFAULT_PORT}`;\n this.authHeader = opts.password ? `Bearer ${opts.password}` : null;\n }\n\n private headers(): Record<string, string> {\n const h: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.authHeader) h['Authorization'] = this.authHeader;\n return h;\n }\n\n async getStatus(): Promise<any> {\n const res = await fetch(`${this.baseUrl}/api/v1/status`, { headers: this.headers() });\n if (!res.ok) throw new Error(`Status fetch failed: ${res.status}`);\n return res.json();\n }\n\n async command(type: string, args: Record<string, unknown> = {}): Promise<any> {\n const res = await fetch(`${this.baseUrl}/api/v1/command`, {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify({ type, ...args }),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText);\n throw new Error(`Command ${type} failed: ${res.status} ${text}`);\n }\n return res.json();\n }\n\n async ping(): Promise<boolean> {\n try {\n await this.getStatus();\n return true;\n } catch {\n return false;\n }\n }\n}\n","/**\n * CloudTransport — HTTP client for ADHDev cloud API (api.adhf.dev)\n *\n * Uses shortcuts API: /api/v1/shortcuts/:targetId/*\n * Requires an API key (adk_*) with appropriate scopes.\n */\n\nconst DEFAULT_BASE_URL = 'https://api.adhf.dev';\n\nexport interface CloudTransportOptions {\n apiKey: string;\n baseUrl?: string;\n}\n\nexport class CloudTransport {\n private baseUrl: string;\n private apiKey: string;\n\n constructor(opts: CloudTransportOptions) {\n this.apiKey = opts.apiKey;\n this.baseUrl = opts.baseUrl ?? DEFAULT_BASE_URL;\n }\n\n private headers(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n };\n }\n\n async listRemoteMeshes(): Promise<{ meshes: any[] }> {\n const res = await fetch(`${this.baseUrl}/api/v1/repo-meshes`, { headers: this.headers() });\n if (!res.ok) throw new Error(`List remote meshes failed: ${res.status}`);\n return res.json() as any;\n }\n\n async createRemoteMesh(data: {\n name: string;\n repo_identity: string;\n repo_remote_url?: string;\n default_branch?: string;\n policy?: string;\n }): Promise<{ mesh: any }> {\n const res = await fetch(`${this.baseUrl}/api/v1/repo-meshes`, {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(data),\n });\n if (!res.ok) throw new Error(`Create remote mesh failed: ${res.status}`);\n return res.json() as any;\n }\n\n async deleteRemoteMesh(meshId: string): Promise<void> {\n const res = await fetch(`${this.baseUrl}/api/v1/repo-meshes/${encodeURIComponent(meshId)}`, {\n method: 'DELETE',\n headers: this.headers(),\n });\n if (!res.ok) throw new Error(`Delete remote mesh failed: ${res.status}`);\n }\n\n async listDaemons(): Promise<any> {\n const res = await fetch(`${this.baseUrl}/api/v1/daemons`, { headers: this.headers() });\n if (!res.ok) throw new Error(`List daemons failed: ${res.status}`);\n return res.json() as any;\n }\n\n async getStatus(targetId: string): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(targetId)}/status`,\n { headers: this.headers() },\n );\n if (!res.ok) throw new Error(`Status failed: ${res.status}`);\n return res.json() as any;\n }\n\n /** Get all sessions for a daemon (returns CompactSessionEntry[]). */\n async getDaemonStatus(daemonId: string): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/daemons/${encodeURIComponent(daemonId)}/status`,\n { headers: this.headers() },\n );\n if (!res.ok) throw new Error(`Daemon status failed: ${res.status}`);\n return res.json() as any;\n }\n\n async readChat(targetId: string, opts: { limit?: number; sessionId?: string } = {}): Promise<any> {\n const params = new URLSearchParams();\n if (opts.limit) params.set('limit', String(opts.limit));\n if (opts.sessionId) params.set('sessionId', opts.sessionId);\n const qs = params.toString() ? `?${params}` : '';\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(targetId)}/chat${qs}`,\n { headers: this.headers() },\n );\n if (!res.ok) throw new Error(`Read chat failed: ${res.status}`);\n return res.json() as any;\n }\n\n async getChatDebugBundle(\n targetId: string,\n opts: { sessionId?: string; agentType?: string; tailLimit?: number; delivery?: 'daemon_file' | 'inline' } = {},\n ): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(targetId)}/chat/debug`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify({\n ...(opts.agentType ? { agentType: opts.agentType } : {}),\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n ...(opts.tailLimit ? { tailLimit: opts.tailLimit } : {}),\n ...(opts.delivery ? { delivery: opts.delivery } : {}),\n }),\n },\n );\n if (!res.ok) throw new Error(`Chat debug bundle failed: ${res.status}`);\n return res.json() as any;\n }\n\n async sendChat(targetId: string, message: string, opts: { sessionId?: string; ideType?: string } = {}): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(targetId)}/chat`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify({ message, ...opts }),\n },\n );\n if (!res.ok) throw new Error(`Send chat failed: ${res.status}`);\n return res.json() as any;\n }\n\n async approve(targetId: string, action: 'approve' | 'reject', agentType?: string): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(targetId)}/approve`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify({ action, ...(agentType ? { agentType } : {}) }),\n },\n );\n if (!res.ok) throw new Error(`Approve failed: ${res.status}`);\n return res.json() as any;\n }\n\n async gitStatus(daemonId: string, workspace: string, includeDiff = true, refreshUpstream = false): Promise<any> {\n const params = new URLSearchParams({ workspace, includeDiff: String(includeDiff), refreshUpstream: String(refreshUpstream) });\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/git-status?${params}`,\n { headers: this.headers() },\n );\n if (!res.ok) throw new Error(`Git status failed: ${res.status}`);\n return res.json() as any;\n }\n\n async stop(daemonId: string, opts: { id?: string; type?: string; dir?: string }): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/stop`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(opts),\n },\n );\n if (!res.ok) throw new Error(`Stop failed: ${res.status}`);\n return res.json() as any;\n }\n\n async launch(daemonId: string, opts: { type: string; dir?: string; model?: string; settings?: Record<string, any> }): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/launch`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(opts),\n },\n );\n if (!res.ok) throw new Error(`Launch failed: ${res.status}`);\n return res.json() as any;\n }\n\n async gitLog(daemonId: string, workspace: string, opts: { limit?: number; file?: string; since?: string; until?: string } = {}): Promise<any> {\n const params = new URLSearchParams({ workspace });\n if (opts.limit) params.set('limit', String(opts.limit));\n if (opts.file) params.set('file', opts.file);\n if (opts.since) params.set('since', opts.since);\n if (opts.until) params.set('until', opts.until);\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/git-log?${params}`,\n { headers: this.headers() },\n );\n if (!res.ok) throw new Error(`Git log failed: ${res.status}`);\n return res.json() as any;\n }\n\n async gitDiff(daemonId: string, workspace: string, opts: { file?: string; maxLines?: number; staged?: boolean } = {}): Promise<any> {\n const params = new URLSearchParams({ workspace });\n if (opts.file) params.set('file', opts.file);\n if (opts.maxLines) params.set('maxLines', String(opts.maxLines));\n if (opts.staged) params.set('staged', 'true');\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/git-diff?${params}`,\n { headers: this.headers() },\n );\n if (!res.ok) throw new Error(`Git diff failed: ${res.status}`);\n return res.json() as any;\n }\n\n async gitPush(daemonId: string, opts: { workspace: string; remote?: string; branch?: string }): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/git-push`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(opts),\n },\n );\n if (!res.ok) throw new Error(`Git push failed: ${res.status}`);\n return res.json() as any;\n }\n\n async gitCheckpoint(daemonId: string, opts: { workspace: string; message: string; includeUntracked?: boolean }): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/git-checkpoint`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(opts),\n },\n );\n if (!res.ok) throw new Error(`Git checkpoint failed: ${res.status}`);\n return res.json() as any;\n }\n\n async meshCloneNode(daemonId: string, payload: any): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/mesh/clone-node`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(payload),\n },\n );\n if (!res.ok) throw new Error(`Mesh clone node failed: ${res.status}`);\n return res.json() as any;\n }\n\n async meshRemoveNode(daemonId: string, payload: any): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/mesh/remove-node`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(payload),\n },\n );\n if (!res.ok) throw new Error(`Mesh remove node failed: ${res.status}`);\n return res.json() as any;\n }\n\n async meshCleanupSessions(daemonId: string, payload: any): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/mesh/cleanup-sessions`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(payload),\n },\n );\n if (!res.ok) throw new Error(`Mesh cleanup sessions failed: ${res.status}`);\n return res.json() as any;\n }\n\n async meshEnqueueTask(daemonId: string, payload: any): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/mesh/enqueue`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(payload),\n },\n );\n if (!res.ok) throw new Error(`Mesh enqueue task failed: ${res.status}`);\n return res.json() as any;\n }\n\n async meshRefineNode(daemonId: string, payload: any): Promise<any> {\n const res = await fetch(\n `${this.baseUrl}/api/v1/shortcuts/${encodeURIComponent(daemonId)}/mesh/refine-node`,\n {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify(payload),\n },\n );\n if (!res.ok) throw new Error(`Mesh refine node failed: ${res.status}`);\n return res.json() as any;\n }\n\n async ping(): Promise<boolean> {\n try {\n await this.listDaemons();\n return true;\n } catch {\n return false;\n }\n }\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport type { CloudTransport } from '../transports/cloud.js';\nimport { isLocalTransport } from '../transports/mode.js';\n\nexport const FORMAT_PROP = {\n format: {\n type: 'string' as const,\n enum: ['text', 'json'],\n description: \"Output format: 'text' (default, human-readable) or 'json' (structured, for programmatic use).\",\n },\n};\n\nexport const LIST_SESSIONS_TOOL = {\n name: 'list_sessions',\n description:\n 'List all connected agent sessions. In cloud mode, fetches session state from each daemon ' +\n '(data is sourced from daemon WS status reports, up to 30s stale). ' +\n 'Pass daemon_id to scope to a single daemon.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only). Omit to list sessions across all daemons.',\n },\n ...FORMAT_PROP,\n },\n required: [],\n },\n};\n\nexport async function listSessions(\n transport: McpTransport,\n args: { daemon_id?: string; format?: 'text' | 'json' } = {},\n): Promise<string> {\n const asJson = args.format === 'json';\n\n if (isLocalTransport(transport)) {\n // Local: single daemon, status endpoint has full SessionEntry[]\n const status = await transport.getStatus();\n const sessions: any[] = status?.sessions ?? [];\n\n if (asJson) {\n return JSON.stringify({\n sessions: sessions.map((s: any) => ({\n id: s.id,\n type: s.providerType ?? s.type ?? 'unknown',\n label: s.label ?? null,\n status: s.status ?? s.agentStatus ?? null,\n workspace: s.workspace ?? null,\n })),\n }, null, 2);\n }\n\n if (sessions.length === 0) return 'No active sessions.';\n const lines = sessions.map((s: any) => {\n const parts = [`id: ${s.id}`, `type: ${s.providerType ?? s.type ?? 'unknown'}`];\n if (s.label) parts.push(`label: ${s.label}`);\n if (s.status ?? s.agentStatus) parts.push(`status: ${s.status ?? s.agentStatus}`);\n if (s.workspace) parts.push(`workspace: ${s.workspace}`);\n return parts.join(', ');\n });\n return `Sessions (${sessions.length}):\\n${lines.join('\\n')}`;\n }\n\n // Cloud: UserSessionDO /list-daemons intentionally strips sessions[] (P2P architecture —\n // session data flows to dashboard via P2P DataChannel, not server WS).\n // MCP must fetch sessions directly from each DaemonConnectionDO's WS status cache.\n return listSessionsCloud(transport, args.daemon_id, asJson);\n}\n\nasync function listSessionsCloud(\n transport: CloudTransport,\n daemonId: string | undefined,\n asJson: boolean,\n): Promise<string> {\n const collected: Array<{ daemonId: string; session: any }> = [];\n\n if (daemonId) {\n const daemonStatus = await transport.getDaemonStatus(daemonId);\n for (const s of daemonStatus?.sessions ?? []) {\n collected.push({ daemonId, session: s });\n }\n } else {\n const data = await transport.listDaemons();\n const daemons: any[] = data?.daemons ?? [];\n\n // Batch 5 at a time to avoid flooding the API\n for (let i = 0; i < daemons.length; i += 5) {\n await Promise.allSettled(\n daemons.slice(i, i + 5).map(async (d) => {\n try {\n const daemonStatus = await transport.getDaemonStatus(d.id);\n for (const s of daemonStatus?.sessions ?? []) {\n collected.push({ daemonId: d.id, session: s });\n }\n } catch {\n // skip unreachable daemons\n }\n }),\n );\n }\n }\n\n if (asJson) {\n return JSON.stringify({\n sessions: collected.map(({ daemonId: dId, session: s }) => ({\n daemon_id: dId,\n id: s.id,\n type: s.providerType ?? 'unknown',\n status: s.status ?? null,\n workspace: s.workspace ?? null,\n })),\n }, null, 2);\n }\n\n if (collected.length === 0) return 'No active sessions.';\n const lines = collected.map(({ daemonId: dId, session: s }) => {\n const parts = [\n `daemon: ${dId}`,\n `session: ${s.id}`,\n `type: ${s.providerType ?? 'unknown'}`,\n ];\n if (s.status) parts.push(`status: ${s.status}`);\n if (s.workspace) parts.push(`workspace: ${s.workspace}`);\n return parts.join(', ');\n });\n return `Sessions (${collected.length}):\\n${lines.join('\\n')}`;\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport { isLocalTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const LIST_DAEMONS_TOOL = {\n name: 'list_daemons',\n description:\n 'List all connected daemons (machines running the ADHDev agent). ' +\n 'Use this to discover daemon IDs before calling launch_session, git_status, or other tools that require daemon_id. ' +\n 'In local mode returns the single standalone daemon info.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n ...FORMAT_PROP,\n },\n required: [],\n },\n};\n\nexport async function listDaemons(\n transport: McpTransport,\n args: { format?: 'text' | 'json' } = {},\n): Promise<string> {\n const asJson = args.format === 'json';\n\n if (isLocalTransport(transport)) {\n // Local: single standalone daemon — extract identity from status\n const status = await transport.getStatus();\n const daemon = {\n id: status?.id ?? status?.instanceId ?? 'standalone',\n hostname: status?.hostname ?? status?.machine?.hostname ?? 'localhost',\n platform: status?.platform ?? status?.machine?.platform ?? 'unknown',\n version: status?.version ?? null,\n sessions: (status?.sessions ?? []).length,\n };\n if (asJson) return JSON.stringify({ daemons: [daemon] }, null, 2);\n return `Daemons (1):\\n id: ${daemon.id}, hostname: ${daemon.hostname}, platform: ${daemon.platform}${daemon.version ? `, version: ${daemon.version}` : ''}, sessions: ${daemon.sessions}`;\n }\n\n // Cloud: full daemon list from UserSessionDO\n const data = await transport.listDaemons();\n const daemons: any[] = data?.daemons ?? [];\n\n if (asJson) {\n return JSON.stringify({\n daemons: daemons.map((d) => ({\n id: d.id,\n hostname: d.hostname ?? null,\n platform: d.platform ?? null,\n nickname: d.nickname ?? null,\n version: d.version ?? null,\n p2p_available: d.p2p?.available ?? null,\n cdp_connected: d.cdpConnected ?? null,\n })),\n }, null, 2);\n }\n\n if (daemons.length === 0) return 'No connected daemons.';\n const lines = daemons.map((d) => {\n const parts = [`id: ${d.id}`];\n if (d.nickname) parts.push(`nickname: ${d.nickname}`);\n if (d.hostname) parts.push(`hostname: ${d.hostname}`);\n if (d.platform) parts.push(`platform: ${d.platform}`);\n if (d.version) parts.push(`version: ${d.version}`);\n if (d.p2p?.available != null) parts.push(`p2p: ${d.p2p.available ? 'yes' : 'no'}`);\n return parts.join(', ');\n });\n return `Daemons (${daemons.length}):\\n${lines.join('\\n')}`;\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport { isLocalTransport } from '../transports/mode.js';\nimport { compactChatPayload, messageContent } from './chat-compact.js';\nimport { annotateRapidReadChatAdvisory, type RapidReadChatAdvisory } from './read-chat-polling-advisory.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const READ_CHAT_TOOL = {\n name: 'read_chat',\n description: 'Read the current chat conversation from an IDE agent session. Returns recent messages.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Target session ID (from list_sessions). Pass explicitly in local mode when more than one session exists; omitting requires an active target and may fail.',\n },\n limit: {\n type: 'number',\n description: 'Max messages to return (default: 50).',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only). Omit for local mode.',\n },\n compact: {\n type: 'boolean',\n description: 'Opt-in compact mode: filters tool/terminal/system/internal/control/debug/status chatter and returns user-visible messages plus lightweight summary metadata.',\n },\n ...FORMAT_PROP,\n },\n required: [],\n },\n};\n\nexport async function readChat(\n transport: McpTransport,\n args: { session_id?: string; limit?: number; daemon_id?: string; format?: 'text' | 'json'; compact?: boolean },\n): Promise<string> {\n const limit = args.limit ?? 50;\n\n if (isLocalTransport(transport)) {\n const result = await transport.command('read_chat', {\n ...(args.session_id ? { targetSessionId: args.session_id } : {}),\n tailLimit: limit,\n });\n const annotated = annotateRapidReadChatAdvisory(result as Record<string, any>, {\n key: `local:${args.session_id ?? '__active__'}`,\n toolName: 'read_chat',\n completionCallbackExpected: false,\n });\n return formatChatResult(annotated, args.session_id, args.format, limit, args.compact);\n }\n\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const targetId = args.session_id ? `${args.daemon_id}:session:${args.session_id}` : args.daemon_id;\n const result = await transport.readChat(targetId, { limit, sessionId: args.session_id });\n const annotated = annotateRapidReadChatAdvisory(result as Record<string, any>, {\n key: `cloud:${args.daemon_id}:${args.session_id ?? '__active__'}`,\n toolName: 'read_chat',\n completionCallbackExpected: false,\n });\n return formatChatResult(annotated, args.session_id, args.format, limit, args.compact);\n}\n\nfunction formatChatResult(result: any, sessionId?: string, format?: 'text' | 'json', limit = 50, compact = false): string {\n if (!result?.success && result?.error) {\n if (format === 'json') return JSON.stringify({ error: result.error, messages: [] }, null, 2);\n return `Error: ${result.error}`;\n }\n\n const messages: any[] = result?.messages ?? result?.data?.messages ?? [];\n const source = { ...result, messages };\n const compactPayload = compact ? compactChatPayload(source, { sessionId: sessionId ?? null, limit }) : null;\n const outputMessages = compact ? compactPayload.messages : messages;\n\n if (format === 'json') {\n if (compact && compactPayload) {\n return JSON.stringify({\n session_id: sessionId ?? null,\n ...compactPayload,\n ...(result?.pollingAdvisory ? { pollingAdvisory: result.pollingAdvisory as RapidReadChatAdvisory } : {}),\n messages: compactPayload.messages.map((m: any) => ({\n role: m.role,\n kind: m.kind ?? null,\n content: messageContent(m),\n timestamp: m.timestamp ?? null,\n })),\n }, null, 2);\n }\n return JSON.stringify({\n session_id: sessionId ?? null,\n ...(result?.pollingAdvisory ? { pollingAdvisory: result.pollingAdvisory as RapidReadChatAdvisory } : {}),\n messages: outputMessages.slice(-limit).map((m: any) => ({\n role: m.role,\n kind: m.kind ?? null,\n content: messageContent(m),\n timestamp: m.timestamp ?? null,\n })),\n }, null, 2);\n }\n\n if ((format === 'text' || format === undefined) && compact && compactPayload) {\n const lines = outputMessages.slice(-limit).map((m: any) => {\n const role = m.role === 'user' ? 'User' : m.role === 'assistant' ? 'Agent' : m.role;\n const content = messageContent(m);\n const truncated = content.length > 500 ? `${content.slice(0, 500)}…` : content;\n return `[${role}] ${truncated}`;\n });\n if (compactPayload.summary) {\n const truncatedSummary = compactPayload.summary.length > 500\n ? `${compactPayload.summary.slice(0, 500)}…`\n : compactPayload.summary;\n lines.push(`[Summary] ${truncatedSummary}`);\n }\n if (result?.pollingAdvisory) {\n lines.push(`Advisory: ${(result.pollingAdvisory as RapidReadChatAdvisory).message}`);\n }\n return lines.length > 0 ? lines.join('\\n\\n') : 'No messages in chat.';\n }\n\n if (outputMessages.length === 0) {\n return result?.pollingAdvisory\n ? `No messages in chat.\\n\\nAdvisory: ${(result.pollingAdvisory as RapidReadChatAdvisory).message}`\n : 'No messages in chat.';\n }\n const lines = outputMessages.slice(-limit).map((m: any) => {\n const role = m.role === 'user' ? 'User' : m.role === 'assistant' ? 'Agent' : m.role;\n const content = messageContent(m);\n const truncated = content.length > 500 ? `${content.slice(0, 500)}…` : content;\n return `[${role}] ${truncated}`;\n });\n if (result?.pollingAdvisory) {\n lines.push(`Advisory: ${(result.pollingAdvisory as RapidReadChatAdvisory).message}`);\n }\n return lines.join('\\n\\n');\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport { isLocalTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const READ_CHAT_DEBUG_TOOL = {\n name: 'read_chat_debug',\n description: 'Collect a daemon-side chat/parser debug bundle for an agent session without opening the browser UI. Prefer this when terminal/chat diverge or long CLI transcripts parse incorrectly. Defaults to daemon_file delivery and returns a saved bundle locator.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Target session ID (from list_sessions). Required for reliable routing.',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only). Omit for local mode.',\n },\n agent_type: {\n type: 'string',\n description: 'Optional provider/agent type hint, e.g. hermes-cli, claude-cli, codex-cli.',\n },\n limit: {\n type: 'number',\n description: 'Max read_chat tail messages embedded in the bundle (default: 40).',\n },\n delivery: {\n type: 'string',\n enum: ['daemon_file', 'inline'],\n description: 'daemon_file saves the full sanitized bundle on the daemon and returns a locator; inline returns the sanitized bundle in the MCP response. Default: daemon_file.',\n },\n ...FORMAT_PROP,\n },\n required: ['session_id'],\n },\n};\n\nexport async function readChatDebug(\n transport: McpTransport,\n args: {\n session_id?: string;\n daemon_id?: string;\n agent_type?: string;\n limit?: number;\n delivery?: 'daemon_file' | 'inline';\n format?: 'text' | 'json';\n },\n): Promise<string> {\n const sessionId = typeof args.session_id === 'string' ? args.session_id.trim() : '';\n if (!sessionId) throw new Error('session_id is required');\n\n const tailLimit = args.limit ?? 40;\n const delivery = args.delivery === 'inline' ? 'inline' : 'daemon_file';\n const commandArgs = {\n targetSessionId: sessionId,\n tailLimit,\n ...(args.agent_type ? { agentType: args.agent_type, providerType: args.agent_type } : {}),\n ...(delivery === 'daemon_file' ? { delivery: 'daemon_file' } : {}),\n };\n\n let result: any;\n if (isLocalTransport(transport)) {\n result = await transport.command('get_chat_debug_bundle', commandArgs);\n } else {\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const targetId = `${args.daemon_id}:session:${sessionId}`;\n result = await transport.getChatDebugBundle(targetId, {\n sessionId,\n agentType: args.agent_type,\n tailLimit,\n delivery,\n });\n }\n\n return formatChatDebugResult(result, { sessionId, delivery, format: args.format });\n}\n\nexport function formatChatDebugResult(\n result: any,\n options: { sessionId: string; delivery: 'daemon_file' | 'inline'; format?: 'text' | 'json' },\n): string {\n if (!result?.success && result?.error) {\n if (options.format === 'json') return JSON.stringify({ success: false, error: result.error }, null, 2);\n return `Error: ${result.error}`;\n }\n\n if (options.format === 'json') {\n return JSON.stringify(result, null, 2);\n }\n\n if (result?.delivery === 'daemon_file') {\n const summary = result.summary && typeof result.summary === 'object' ? result.summary : {};\n return [\n 'ADHDev chat debug bundle saved on daemon.',\n `session_id: ${options.sessionId}`,\n `bundle_id: ${String(result.bundleId || '')}`,\n `saved_path: ${String(result.savedPath || '')}`,\n `size_bytes: ${String(result.sizeBytes || '')}`,\n `created_at: ${String(result.createdAt || '')}`,\n `read_chat_status: ${String((summary as any).readChatStatus || '')}`,\n `read_chat_total_messages: ${String((summary as any).readChatTotalMessages ?? '')}`,\n `cli_status: ${String((summary as any).cliStatus || '')}`,\n `cli_message_count: ${String((summary as any).cliMessageCount ?? '')}`,\n ].join('\\n');\n }\n\n if (typeof result?.text === 'string') return result.text;\n if (result?.bundle) return JSON.stringify(result.bundle, null, 2);\n return JSON.stringify(result, null, 2);\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport type { CloudTransport } from '../transports/cloud.js';\nimport { isLocalTransport } from '../transports/mode.js';\n\nexport const SEND_CHAT_TOOL = {\n name: 'send_chat',\n description: 'Send a message to an IDE agent session.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n message: {\n type: 'string',\n description: 'The message to send to the agent.',\n },\n session_id: {\n type: 'string',\n description: 'Target session ID (from list_sessions). Omit to use the active session.',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only). Omit for local mode.',\n },\n },\n required: ['message'],\n },\n};\n\nexport async function sendChat(\n transport: McpTransport,\n args: { message: string; session_id?: string; daemon_id?: string },\n): Promise<string> {\n if (!args.message?.trim()) throw new Error('message is required');\n\n if (isLocalTransport(transport)) {\n // LocalTransport\n const result = await transport.command('send_chat', {\n message: args.message,\n ...(args.session_id ? { targetSessionId: args.session_id } : {}),\n });\n if (result?.success === false) return `Error: ${result.error ?? 'send_chat failed'}`;\n return 'Message sent.';\n }\n\n // CloudTransport\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const targetId = args.session_id ? `${args.daemon_id}:session:${args.session_id}` : args.daemon_id;\n const result = await transport.sendChat(targetId, args.message, {\n ...(args.session_id ? { sessionId: args.session_id } : {}),\n });\n if (result?.success === false) return `Error: ${result.error ?? 'send_chat failed'}`;\n return 'Message sent.';\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport type { CloudTransport } from '../transports/cloud.js';\nimport { isLocalTransport } from '../transports/mode.js';\n\nexport const APPROVE_TOOL = {\n name: 'approve',\n description: 'Approve or reject a pending agent action (e.g. file write, command execution).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n action: {\n type: 'string',\n enum: ['approve', 'reject'],\n description: 'Whether to approve or reject the pending action.',\n },\n session_id: {\n type: 'string',\n description: 'Target session ID. Omit to use the active session.',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only).',\n },\n },\n required: ['action'],\n },\n};\n\nexport async function approve(\n transport: McpTransport,\n args: { action: 'approve' | 'reject'; session_id?: string; daemon_id?: string },\n): Promise<string> {\n const action = args.action === 'reject' ? 'reject' : 'approve';\n\n if (isLocalTransport(transport)) {\n // LocalTransport\n const result = await transport.command('resolve_action', {\n action,\n ...(args.session_id ? { targetSessionId: args.session_id } : {}),\n });\n if (result?.success === false) return `Error: ${result.error ?? 'resolve_action failed'}`;\n return `Action ${action}d.`;\n }\n\n // CloudTransport\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const targetId = args.session_id ? `${args.daemon_id}:session:${args.session_id}` : args.daemon_id;\n const result = await transport.approve(targetId, action);\n if (result?.success === false) return `Error: ${result.error ?? 'approve failed'}`;\n return `Action ${action}d.`;\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport type { CloudTransport } from '../transports/cloud.js';\nimport { isLocalTransport } from '../transports/mode.js';\n\nexport const SCREENSHOT_TOOL = {\n name: 'screenshot',\n description:\n 'Capture a screenshot of the current IDE window. Returns the image. ' +\n 'Local mode only — screenshots require direct P2P access to the daemon and are not available in cloud mode.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Target session ID. Omit to use the active session.',\n },\n },\n required: [],\n },\n};\n\nexport async function screenshot(\n transport: McpTransport,\n args: { session_id?: string },\n): Promise<{ type: 'image'; data: string; mimeType: string } | { type: 'text'; text: string }> {\n let result: any;\n\n if (isLocalTransport(transport)) {\n result = await transport.command('screenshot', {\n ...(args.session_id ? { targetSessionId: args.session_id } : {}),\n });\n } else {\n // CloudTransport: use shortcuts status endpoint — screenshot not on shortcuts, fall back to error\n return { type: 'text', text: 'Screenshots are not available in cloud mode. Run adhdev mcp in local mode (requires standalone daemon).' };\n }\n\n if (result?.success === false) {\n return { type: 'text', text: `Error: ${result.error ?? 'screenshot failed'}` };\n }\n\n const b64: string | undefined = result?.base64 ?? result?.screenshot ?? result?.result;\n if (!b64) {\n return { type: 'text', text: 'Screenshot captured but no image data returned.' };\n }\n\n const mimeType = result?.format === 'png' ? 'image/png' : 'image/webp';\n return { type: 'image', data: b64, mimeType };\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport { isLocalTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const GIT_STATUS_TOOL = {\n name: 'git_status',\n description: 'Get git repository status for a workspace on the daemon machine.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n include_diff: {\n type: 'boolean',\n description: 'Include changed file list (default: true).',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only).',\n },\n ...FORMAT_PROP,\n },\n required: ['workspace'],\n },\n};\n\nexport async function gitStatus(\n transport: McpTransport,\n args: { workspace: string; include_diff?: boolean; daemon_id?: string; format?: 'text' | 'json' },\n): Promise<string> {\n let status: any;\n let diffSummary: any;\n\n if (isLocalTransport(transport)) {\n const statusResult = await transport.command('git_status', {\n workspace: args.workspace,\n });\n status = statusResult?.status ?? statusResult;\n\n if (args.include_diff !== false) {\n const diffResult = await transport.command('git_diff_summary', {\n workspace: args.workspace,\n });\n diffSummary = diffResult?.diffSummary ?? diffResult;\n }\n } else {\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const result = await transport.gitStatus(\n args.daemon_id,\n args.workspace,\n args.include_diff !== false,\n );\n if (result?.error) {\n if (args.format === 'json') return JSON.stringify({ error: result.error }, null, 2);\n return `Error: ${result.error}`;\n }\n status = result?.status;\n diffSummary = result?.diff;\n }\n\n if (status?.success === false || status?.reason) {\n const msg = status?.error ?? status?.reason ?? 'unknown';\n if (args.format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return `Git error: ${msg}`;\n }\n if (!status?.isGitRepo) {\n if (args.format === 'json') return JSON.stringify({ error: `Not a git repository: ${args.workspace}` }, null, 2);\n return `Not a git repository: ${args.workspace}`;\n }\n\n if (args.format === 'json') {\n const files = diffSummary?.files?.map((f: any) => ({\n path: f.path,\n old_path: f.oldPath ?? null,\n status: f.status ?? 'M',\n insertions: f.insertions ?? 0,\n deletions: f.deletions ?? 0,\n })) ?? [];\n return JSON.stringify({\n branch: status.branch ?? null,\n head_commit: status.headCommit ?? null,\n head_message: status.headMessage ?? null,\n ahead: status.ahead ?? 0,\n behind: status.behind ?? 0,\n staged: status.staged ?? 0,\n modified: status.modified ?? 0,\n untracked: status.untracked ?? 0,\n deleted: status.deleted ?? 0,\n stash_count: status.stashCount ?? 0,\n has_conflicts: status.hasConflicts ?? false,\n dirty: status.dirty ?? false,\n changed_files: files,\n total_insertions: diffSummary?.totalInsertions ?? 0,\n total_deletions: diffSummary?.totalDeletions ?? 0,\n }, null, 2);\n }\n\n const lines: string[] = [];\n if (status.branch) lines.push(`Branch: ${status.branch}`);\n if (status.headCommit) {\n lines.push(`HEAD: ${status.headCommit.slice(0, 7)}${status.headMessage ? ` — ${status.headMessage.slice(0, 80)}` : ''}`);\n }\n if (status.ahead > 0) lines.push(`Ahead: ${status.ahead}`);\n if (status.behind > 0) lines.push(`Behind: ${status.behind}`);\n if (status.staged > 0) lines.push(`Staged: ${status.staged}`);\n if (status.modified > 0) lines.push(`Modified: ${status.modified}`);\n if (status.untracked > 0) lines.push(`Untracked: ${status.untracked}`);\n if (status.deleted > 0) lines.push(`Deleted: ${status.deleted}`);\n if (status.stashCount > 0) lines.push(`Stashes: ${status.stashCount}`);\n if (status.hasConflicts) lines.push('Conflicts: YES');\n if (!status.dirty) lines.push('Working tree: clean');\n\n if (diffSummary?.files?.length > 0) {\n lines.push('');\n lines.push(`Changed files (${diffSummary.files.length}):`);\n for (const f of diffSummary.files.slice(0, 20)) {\n lines.push(` ${f.status ?? 'M'} ${f.path}${f.oldPath ? ` (was ${f.oldPath})` : ''}${f.insertions || f.deletions ? ` +${f.insertions ?? 0}/-${f.deletions ?? 0}` : ''}`);\n }\n if (diffSummary.files.length > 20) lines.push(` … and ${diffSummary.files.length - 20} more`);\n if (diffSummary.totalInsertions || diffSummary.totalDeletions) {\n lines.push(`Total: +${diffSummary.totalInsertions ?? 0}/-${diffSummary.totalDeletions ?? 0}`);\n }\n }\n\n return lines.join('\\n');\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport { isLocalTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const GIT_LOG_TOOL = {\n name: 'git_log',\n description:\n 'Get commit history for a workspace. Shows hash, message, author, and date for recent commits. ' +\n 'Use this to track what changes an agent has made, verify checkpoint commits, or understand project history.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n limit: {\n type: 'number',\n description: 'Max commits to return (default: 20, max: 100).',\n },\n file: {\n type: 'string',\n description: 'Filter history to commits that touched this repo-relative file path (optional).',\n },\n since: {\n type: 'string',\n description: 'Only commits after this date (ISO 8601 or git date string, optional).',\n },\n until: {\n type: 'string',\n description: 'Only commits before this date (ISO 8601 or git date string, optional).',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only, required).',\n },\n ...FORMAT_PROP,\n },\n required: ['workspace'],\n },\n};\n\nexport async function gitLog(\n transport: McpTransport,\n args: {\n workspace: string;\n limit?: number;\n file?: string;\n since?: string;\n until?: string;\n daemon_id?: string;\n format?: 'text' | 'json';\n },\n): Promise<string> {\n const limit = Math.max(1, Math.min(100, args.limit ?? 20));\n\n let raw: any;\n if (isLocalTransport(transport)) {\n raw = await transport.command('git_log', {\n workspace: args.workspace,\n limit,\n ...(args.file ? { path: args.file } : {}),\n ...(args.since ? { since: args.since } : {}),\n ...(args.until ? { until: args.until } : {}),\n });\n raw = raw?.log ?? raw;\n } else {\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const result = await transport.gitLog(args.daemon_id, args.workspace, {\n limit,\n file: args.file,\n since: args.since,\n until: args.until,\n });\n raw = result?.log ?? result;\n }\n\n if (raw?.success === false || raw?.reason) {\n const msg = raw?.error ?? raw?.reason ?? 'unknown';\n if (args.format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return `Git log error: ${msg}`;\n }\n\n if (!raw?.isGitRepo) {\n const msg = `Not a git repository: ${args.workspace}`;\n if (args.format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return msg;\n }\n\n const entries: any[] = raw?.entries ?? [];\n\n if (args.format === 'json') {\n return JSON.stringify({\n workspace: raw.workspace,\n branch: raw.branch ?? null,\n entries: entries.map((e) => ({\n commit: e.commit,\n short: e.commit?.slice(0, 7),\n message: e.message,\n author: e.authorName ?? null,\n author_email: e.authorEmail ?? null,\n authored_at: e.authoredAt ? new Date(e.authoredAt).toISOString() : null,\n })),\n total: entries.length,\n truncated: raw.truncated ?? false,\n }, null, 2);\n }\n\n if (entries.length === 0) return 'No commits found.';\n\n const lines = entries.map((e) => {\n const hash = e.commit?.slice(0, 7) ?? '???????';\n const date = e.authoredAt ? new Date(e.authoredAt).toISOString().slice(0, 10) : '';\n const author = e.authorName ? ` (${e.authorName})` : '';\n return `${hash} ${date}${author} ${e.message}`;\n });\n\n const header = `Commits (${entries.length}${raw.truncated ? ', truncated' : ''}):`;\n return `${header}\\n${lines.join('\\n')}`;\n}\n","import type { CommandTransport, McpTransport } from '../transports/mode.js';\nimport { isLocalTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const GIT_DIFF_TOOL = {\n name: 'git_diff',\n description:\n 'Get the actual diff content for changed files in a workspace. ' +\n 'Without a specific file, returns diffs for up to 5 changed files. ' +\n 'Use this to review what an agent actually changed — file names alone (from git_status) are not enough for code review.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n file: {\n type: 'string',\n description: 'Specific repo-relative file path to diff (optional — if omitted, returns top 5 changed files).',\n },\n max_lines: {\n type: 'number',\n description: 'Max diff lines per file before truncating (default: 300).',\n },\n staged: {\n type: 'boolean',\n description: 'Show staged changes instead of unstaged (default: false).',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only, required).',\n },\n ...FORMAT_PROP,\n },\n required: ['workspace'],\n },\n};\n\ninterface FileDiffResult {\n path: string;\n old_path?: string | null;\n status?: string;\n diff: string;\n truncated: boolean;\n binary: boolean;\n error?: string;\n}\n\nexport async function gitDiff(\n transport: McpTransport,\n args: {\n workspace: string;\n file?: string;\n max_lines?: number;\n staged?: boolean;\n daemon_id?: string;\n format?: 'text' | 'json';\n },\n): Promise<string> {\n const maxLines = Math.max(10, Math.min(2000, args.max_lines ?? 300));\n const staged = args.staged ?? false;\n\n if (isLocalTransport(transport)) {\n return localGitDiff(transport, args.workspace, args.file, maxLines, staged, args.format);\n }\n\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const result = await transport.gitDiff(args.daemon_id, args.workspace, {\n file: args.file,\n maxLines,\n staged,\n });\n\n if (result?.error) {\n if (args.format === 'json') return JSON.stringify({ error: result.error }, null, 2);\n return `Git diff error: ${result.error}`;\n }\n\n return formatDiffResult(result, args.format);\n}\n\nasync function localGitDiff(\n transport: CommandTransport,\n workspace: string,\n file: string | undefined,\n maxLines: number,\n staged: boolean,\n format: 'text' | 'json' | undefined,\n): Promise<string> {\n if (file) {\n const raw = await transport.command('git_diff_file', { workspace, path: file, staged });\n const d = raw?.diff ?? raw;\n\n if (d?.success === false || d?.reason) {\n const msg = d?.error ?? d?.reason ?? 'unknown';\n if (format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return `Git diff error: ${msg}`;\n }\n\n const lines = (d?.diff ?? '').split('\\n');\n const truncated = lines.length > maxLines;\n const result = {\n files: [{\n path: file,\n diff: truncated ? lines.slice(0, maxLines).join('\\n') + '\\n... (truncated)' : (d?.diff ?? ''),\n truncated,\n binary: d?.binary ?? false,\n }],\n total_files: 1,\n shown_files: 1,\n truncated,\n };\n return formatDiffResult(result, format);\n }\n\n // No specific file: get summary then fetch top 5\n const summaryRaw = await transport.command('git_diff_summary', { workspace, staged });\n const summary = summaryRaw?.diffSummary ?? summaryRaw;\n\n if (summary?.success === false || summary?.reason) {\n const msg = summary?.error ?? summary?.reason ?? 'unknown';\n if (format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return `Git diff error: ${msg}`;\n }\n\n if (!summary?.isGitRepo) {\n const msg = `Not a git repository: ${workspace}`;\n if (format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return msg;\n }\n\n const files: any[] = summary?.files ?? [];\n if (files.length === 0) {\n if (format === 'json') return JSON.stringify({ files: [], total_files: 0, shown_files: 0, truncated: false }, null, 2);\n return 'No changed files.';\n }\n\n const topFiles = files.slice(0, 5);\n const fileDiffs: FileDiffResult[] = await Promise.all(\n topFiles.map(async (f: any): Promise<FileDiffResult> => {\n try {\n const raw = await transport.command('git_diff_file', { workspace, path: f.path, staged });\n const d = raw?.diff ?? raw;\n const lines = (d?.diff ?? '').split('\\n');\n const trunc = lines.length > maxLines;\n return {\n path: f.path,\n old_path: f.oldPath ?? null,\n status: f.status ?? 'M',\n diff: trunc ? lines.slice(0, maxLines).join('\\n') + '\\n... (truncated)' : (d?.diff ?? ''),\n truncated: trunc,\n binary: d?.binary ?? false,\n };\n } catch {\n return { path: f.path, diff: '', truncated: false, binary: false, error: 'fetch failed' };\n }\n }),\n );\n\n return formatDiffResult({\n files: fileDiffs,\n total_files: files.length,\n shown_files: topFiles.length,\n truncated: files.length > 5,\n }, format);\n}\n\nfunction formatDiffResult(result: any, format: 'text' | 'json' | undefined): string {\n if (format === 'json') return JSON.stringify(result, null, 2);\n\n const files: FileDiffResult[] = result?.files ?? [];\n if (files.length === 0) return 'No changed files.';\n\n const parts: string[] = [];\n const totalShown = result?.shown_files ?? files.length;\n const totalAll = result?.total_files ?? files.length;\n if (totalAll > totalShown) {\n parts.push(`Showing ${totalShown} of ${totalAll} changed files:\\n`);\n }\n\n for (const f of files) {\n const header = `--- ${f.path}${f.old_path ? ` (was ${f.old_path})` : ''} ---`;\n if (f.error) {\n parts.push(`${header}\\n(error: ${f.error})\\n`);\n } else if (f.binary) {\n parts.push(`${header}\\n(binary file)\\n`);\n } else if (!f.diff) {\n parts.push(`${header}\\n(no diff)\\n`);\n } else {\n parts.push(`${header}\\n${f.diff}${f.truncated ? '' : '\\n'}`);\n }\n }\n\n return parts.join('\\n');\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport { isLocalTransport } from '../transports/mode.js';\n\nexport const GIT_CHECKPOINT_TOOL = {\n name: 'git_checkpoint',\n description:\n 'Create a checkpoint commit in a workspace. ' +\n 'Stages all tracked changes (or all files including untracked) and commits with a prefixed message. ' +\n 'Use this to save progress before a risky operation, or to create a restore point the orchestrator can reference.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n message: {\n type: 'string',\n description: 'Checkpoint message (max 200 chars). Will be prefixed with \"adhdev: checkpoint \".',\n },\n include_untracked: {\n type: 'boolean',\n description: 'Also stage and commit untracked files (default: false).',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only, required).',\n },\n },\n required: ['workspace', 'message'],\n },\n};\n\nexport async function gitCheckpoint(\n transport: McpTransport,\n args: {\n workspace: string;\n message: string;\n include_untracked?: boolean;\n daemon_id?: string;\n },\n): Promise<string> {\n const message = args.message?.trim();\n if (!message) return 'Error: message is required';\n if (message.length > 200) return 'Error: message must be 200 characters or fewer';\n\n let raw: any;\n if (isLocalTransport(transport)) {\n raw = await transport.command('git_checkpoint', {\n workspace: args.workspace,\n message,\n includeUntracked: args.include_untracked ?? false,\n });\n raw = raw?.checkpoint ?? raw;\n } else {\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const result = await transport.gitCheckpoint(args.daemon_id, {\n workspace: args.workspace,\n message,\n includeUntracked: args.include_untracked ?? false,\n });\n raw = result?.checkpoint ?? result;\n }\n\n if (raw?.success === false || raw?.reason) {\n const msg = raw?.error ?? raw?.reason ?? 'unknown';\n if (msg.includes('Nothing to commit') || msg.includes('nothing to commit')) {\n return 'Nothing to commit — working tree is clean.';\n }\n return `Git checkpoint error: ${msg}`;\n }\n\n const commit = raw?.commit?.slice(0, 7) ?? '???????';\n const fullMsg = raw?.message ?? `adhdev: checkpoint ${message}`;\n return `Checkpoint created: ${commit} — ${fullMsg}`;\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport { isLocalTransport } from '../transports/mode.js';\n\nexport const GIT_PUSH_TOOL = {\n name: 'git_push',\n description:\n 'Push a branch to a remote repository on the daemon machine. ' +\n 'If the branch has no upstream configured, sets it automatically. ' +\n 'Key for parallel multi-machine workflows: after git_checkpoint, push each machine\\'s ' +\n 'branch to origin so changes are available for PR/review.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n remote: {\n type: 'string',\n description: 'Remote name (default: \"origin\").',\n },\n branch: {\n type: 'string',\n description: 'Branch to push (default: current branch).',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only, required).',\n },\n },\n required: ['workspace'],\n },\n};\n\nexport async function gitPush(\n transport: McpTransport,\n args: {\n workspace: string;\n remote?: string;\n branch?: string;\n daemon_id?: string;\n },\n): Promise<string> {\n let raw: any;\n\n if (isLocalTransport(transport)) {\n raw = await transport.command('git_push', {\n workspace: args.workspace,\n remote: args.remote ?? 'origin',\n ...(args.branch ? { branch: args.branch } : {}),\n });\n raw = raw?.push ?? raw;\n } else {\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const result = await transport.gitPush(args.daemon_id, {\n workspace: args.workspace,\n remote: args.remote,\n branch: args.branch,\n });\n raw = result?.push ?? result;\n }\n\n if (raw?.success === false || raw?.reason) {\n const msg = raw?.error ?? raw?.reason ?? 'unknown';\n return `Git push error: ${msg}`;\n }\n\n const branch = raw?.branch ?? args.branch ?? '(current)';\n const remote = raw?.remote ?? args.remote ?? 'origin';\n const newBranch = raw?.newBranch ? ' [new branch]' : '';\n const output = raw?.output ? `\\n${raw.output}` : '';\n\n return `Pushed ${branch} → ${remote}${newBranch}${output}`;\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport type { CloudTransport } from '../transports/cloud.js';\nimport { isLocalTransport } from '../transports/mode.js';\n\nexport const LAUNCH_SESSION_TOOL = {\n name: 'launch_session',\n description:\n 'Launch a new agent session on the daemon. Supports CLI agents (e.g. hermes-cli, claude-cli, gemini-cli), ACP agents (e.g. claude-acp), and IDEs (e.g. cursor, vscode).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n type: {\n type: 'string',\n description:\n 'Provider type to launch. CLI examples: hermes-cli, claude-cli, gemini-cli. ACP examples: claude-acp. IDE examples: cursor, vscode.',\n },\n workspace: {\n type: 'string',\n description: 'Working directory for the session. Defaults to the daemon default workspace.',\n },\n model: {\n type: 'string',\n description: 'Model override for ACP agents (e.g. claude-opus-4-7).',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only). Required in cloud mode.',\n },\n },\n required: ['type'],\n },\n};\n\nexport async function launchSession(\n transport: McpTransport,\n args: { type: string; workspace?: string; model?: string; daemon_id?: string },\n): Promise<string> {\n if (isLocalTransport(transport)) {\n // LocalTransport\n const isCliOrAcp =\n args.type.includes('-cli') || args.type.includes('-acp') || args.type === 'codex';\n const commandType = isCliOrAcp ? 'launch_cli' : 'launch_ide';\n const payload: Record<string, unknown> = isCliOrAcp\n ? { cliType: args.type, dir: args.workspace ?? '~', ...(args.model ? { model: args.model } : {}) }\n : { ideType: args.type, enableCdp: true };\n const result = await transport.command(commandType, payload);\n if (result?.success === false) return `Error: ${result.error ?? 'launch failed'}`;\n const id = result?.id ?? result?.sessionId;\n return id ? `Session launched. id: ${id}, type: ${args.type}` : `Launched: ${JSON.stringify(result)}`;\n }\n\n // CloudTransport\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const result = await transport.launch(args.daemon_id, {\n type: args.type,\n dir: args.workspace,\n model: args.model,\n });\n if (result?.success === false || result?.error) return `Error: ${result.error ?? 'launch failed'}`;\n const id = result?.id ?? result?.sessionId;\n return id ? `Session launched. id: ${id}, type: ${args.type}` : `Launched: ${JSON.stringify(result)}`;\n}\n","import type { McpTransport } from '../transports/mode.js';\nimport type { CloudTransport } from '../transports/cloud.js';\nimport { isLocalTransport } from '../transports/mode.js';\n\nexport const STOP_SESSION_TOOL = {\n name: 'stop_session',\n description:\n 'Stop a running agent session. For CLI agents (hermes-cli, claude-cli, etc.) this sends a graceful stop signal. ' +\n 'Use list_sessions to find the session_id.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Session ID to stop (from list_sessions).',\n },\n daemon_id: {\n type: 'string',\n description: 'Daemon ID (cloud mode only, required).',\n },\n type: {\n type: 'string',\n description:\n 'Provider type (e.g. hermes-cli, claude-cli). Local mode auto-resolves from session_id if omitted; cloud mode forwards the session_id and omits type unless explicitly provided.',\n },\n },\n required: ['session_id'],\n },\n};\n\nexport async function stopSession(\n transport: McpTransport,\n args: { session_id: string; daemon_id?: string; type?: string },\n): Promise<string> {\n if (isLocalTransport(transport)) {\n const local = transport;\n let resolvedType = args.type;\n\n // Auto-resolve type from session status if not provided\n if (!resolvedType) {\n const status = await local.getStatus();\n const session = (status?.sessions ?? []).find((s: any) => s.id === args.session_id);\n resolvedType = session?.providerType ?? session?.type;\n }\n\n if (!resolvedType) {\n return `Error: could not resolve session type for ${args.session_id}. Pass type= explicitly.`;\n }\n\n const result = await local.command('stop_cli', {\n targetSessionId: args.session_id,\n cliType: resolvedType,\n });\n if (result?.success === false) return `Error: ${result.error ?? 'stop failed'}`;\n return `Session ${args.session_id} stopped.`;\n }\n\n // CloudTransport\n if (!args.daemon_id) throw new Error('daemon_id is required in cloud mode');\n const result = await transport.stop(args.daemon_id, {\n id: args.session_id,\n ...(args.type ? { type: args.type } : {}),\n });\n if (result?.success === false || result?.error) return `Error: ${result.error ?? 'stop failed'}`;\n return `Session ${args.session_id} stopped.`;\n}\n","import type { CommandTransport, McpTransport } from '../transports/mode.js';\nimport type { CloudTransport } from '../transports/cloud.js';\nimport { isLocalTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const CHECK_PENDING_TOOL = {\n name: 'check_pending',\n description:\n 'List all agent sessions currently waiting for user approval (tool-use confirmation). ' +\n 'Returns session ID, daemon ID, workspace, and the approval prompt message when available. ' +\n 'Use approve() with the session_id to approve or reject.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n daemon_id: {\n type: 'string',\n description: 'Daemon ID to check (cloud mode). Omit to check all daemons.',\n },\n ...FORMAT_PROP,\n },\n required: [],\n },\n};\n\nexport async function checkPending(\n transport: McpTransport,\n args: { daemon_id?: string; format?: 'text' | 'json' },\n): Promise<string> {\n if (isLocalTransport(transport)) {\n return checkPendingLocal(transport, args.format);\n }\n return checkPendingCloud(transport, args.daemon_id, args.format);\n}\n\nasync function checkPendingLocal(\n transport: CommandTransport,\n format?: 'text' | 'json',\n): Promise<string> {\n const status = await transport.getStatus();\n const sessions: any[] = status?.sessions ?? [];\n\n const pending = sessions.filter(\n (s) => s.status === 'waiting_approval' || s.agentStatus === 'waiting_approval',\n );\n\n if (format === 'json') {\n return JSON.stringify({\n pending: pending.map((s) => ({\n session_id: s.id,\n workspace: s.workspace ?? null,\n type: s.providerType ?? null,\n modal_message: s.activeChat?.activeModal?.message ?? null,\n buttons: s.activeChat?.activeModal?.buttons ?? [],\n })),\n }, null, 2);\n }\n\n if (pending.length === 0) return 'No sessions waiting for approval.';\n const lines = pending.map((s) => {\n const modal = s.activeChat?.activeModal;\n const parts = [`session_id: ${s.id}`];\n if (s.workspace) parts.push(`workspace: ${s.workspace}`);\n if (s.providerType) parts.push(`type: ${s.providerType}`);\n if (modal?.message) parts.push(`prompt: ${modal.message}`);\n if (modal?.buttons?.length) parts.push(`buttons: ${modal.buttons.join(', ')}`);\n return parts.join('\\n ');\n });\n return `Pending approvals (${pending.length}):\\n\\n${lines.join('\\n\\n')}`;\n}\n\nasync function checkPendingCloud(\n transport: CloudTransport,\n daemonId?: string,\n format?: 'text' | 'json',\n): Promise<string> {\n const pending: Array<{ daemonId: string; session: any }> = [];\n\n if (daemonId) {\n const daemonStatus = await transport.getDaemonStatus(daemonId);\n const sessions: any[] = daemonStatus?.sessions ?? [];\n for (const s of sessions) {\n if (s.status === 'waiting_approval') pending.push({ daemonId, session: s });\n }\n } else {\n const data = await transport.listDaemons();\n const daemons: any[] = data?.daemons ?? [];\n\n // Process in batches of 5 to avoid flooding the API with concurrent requests\n for (let i = 0; i < daemons.length; i += 5) {\n await Promise.allSettled(\n daemons.slice(i, i + 5).map(async (d) => {\n try {\n const daemonStatus = await transport.getDaemonStatus(d.id);\n const sessions: any[] = daemonStatus?.sessions ?? [];\n for (const s of sessions) {\n if (s.status === 'waiting_approval') pending.push({ daemonId: d.id, session: s });\n }\n } catch {\n // skip unreachable daemons\n }\n }),\n );\n }\n }\n\n if (format === 'json') {\n return JSON.stringify({\n pending: pending.map(({ daemonId: dId, session: s }) => ({\n daemon_id: dId,\n session_id: s.id,\n workspace: s.workspace ?? null,\n type: s.providerType ?? null,\n modal_message: null,\n buttons: [],\n })),\n }, null, 2);\n }\n\n if (pending.length === 0) return 'No sessions waiting for approval.';\n const lines = pending.map(({ daemonId: dId, session: s }) => {\n const parts = [`daemon_id: ${dId}`, `session_id: ${s.id}`];\n if (s.workspace) parts.push(`workspace: ${s.workspace}`);\n if (s.providerType) parts.push(`type: ${s.providerType}`);\n parts.push('(use read_chat to see the approval prompt)');\n return parts.join('\\n ');\n });\n return `Pending approvals (${pending.length}):\\n\\n${lines.join('\\n\\n')}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,yBAA2B;;;ACT3B,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AACzB,IAAM,iCAAiC;AACvC,IAAM,0BAAkD;AAAA,EACtD,oBAAoB;AAAA,EACpB,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,wBAAwB;AAAA,EACxB,aAAa;AACf;AAOO,IAAM,eAAN,MAAmB;AAAA,EAChB;AAAA,EACA;AAAA,EAER,YAAY,OAA4B,CAAC,GAAG;AAC1C,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,OAAO,KAAK,QAAQ;AAAA,EAC3B;AAAA,EAEA,MAAM,OAAyB;AAC7B,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,oBAAoB,KAAK,IAAI,SAAS;AAC9D,aAAO,IAAI;AAAA,IACb,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAM,YAA0B;AAC9B,WAAO,KAAK,QAAQ,qBAAqB;AAAA,EAC3C;AAAA,EAEA,MAAM,QAAQ,MAAc,OAAgC,CAAC,GAAiB;AAC5E,WAAO,KAAK,eAAe,MAAM,IAAI;AAAA,EACvC;AAAA,EAEA,MAAM,YACJ,gBACA,SACA,OAAgC,CAAC,GACnB;AACd,WAAO,KAAK,eAAe,sBAAsB;AAAA,MAC/C;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,MAAc,eAAe,MAAc,MAA6C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AAiB,YAAW,IAAI;AACrD,MAAI,CAAC,UAAU,IAAI,eAAgB,UAAS,IAAI;AAChD,MAAI,CAAC,gBAAgB,IAAI,sBAAsB;AAC7C,UAAM,QAAQ,IAAI,qBAAqB,KAAK;AAC5C,QAAI,UAAU,WAAW,UAAU,WAAW,UAAU,MAAO,gBAAe;AAAA,EAChF;AAEA,QAAM,OAAO,iBAAiB,SAAS,UAAW,UAAU,IAAI,qBAAqB,QAAQ;AAC7F,SAAO,EAAE,MAAM,MAAM,UAAU,QAAQ,SAAS,OAAO;AACzD;AAEA,SAAS,YAAkB;AACzB,UAAQ,MAAM,iBAAiB,CAAC;AAClC;AAEA,eAAe,UAAU,QAAQ,IAAI,CAAC,EAAE,MAAM,CAAC,QAAQ;AACrD,UAAQ,OAAO,MAAM,uBAAuB,KAAK,WAAW,GAAG;AAAA,CAAI;AACnE,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["slice","result","result","annotated","lines","result","result","result","id","result","os","server","stdioTransport"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/transports/ipc.ts","../src/tools/chat-compact.ts","../../mesh-shared/src/json.ts","../../mesh-shared/src/git-normalize.ts","../../mesh-shared/src/session-normalize.ts","../../mesh-shared/src/node-normalize.ts","../../mesh-shared/src/workspace-normalize.ts","../../mesh-shared/src/daemon-normalize.ts","../../mesh-shared/src/git-summarize.ts","../../mesh-shared/src/magi.ts","../../mesh-shared/src/brain-routing.ts","../../mesh-shared/src/interpolation.ts","../../mesh-shared/src/mesh-tool-names.ts","../../mesh-shared/src/mesh-status-probe.ts","../src/tools/mesh-tools-internal.ts","../src/tools/mesh-tool-shared.ts","../src/tools/mesh-session-helpers.ts","../src/tools/mesh-node-identity.ts","../src/tools/mesh-tool-schemas.ts","../src/tools/mesh-compact.ts","../src/tools/mesh-queue-helpers.ts","../src/tools/read-chat-polling-advisory.ts","../src/tools/mesh-tools-status.ts","../src/tools/mesh-tools-queue.ts","../src/tools/mesh-tools-mission.ts","../src/tools/mesh-tools-magi.ts","../src/tools/mesh-tools-slots.ts","../src/tools/mesh-tools-session.ts","../src/tools/mesh-tools-git.ts","../src/tools/mesh-tools-refine.ts","../src/help.ts","../src/server.ts","../src/transports/local.ts","../src/tools/list-sessions.ts","../src/tools/list-daemons.ts","../src/tools/read-chat.ts","../src/tools/read-chat-debug.ts","../src/tools/spec-debug.ts","../src/tools/send-chat.ts","../src/tools/approve.ts","../src/tools/screenshot.ts","../src/tools/git-status.ts","../src/tools/git-log.ts","../src/tools/git-diff.ts","../src/tools/git-checkpoint.ts","../src/tools/git-push.ts","../src/tools/launch-session.ts","../src/tools/stop-session.ts","../src/tools/check-pending.ts"],"sourcesContent":["/**\n * @adhdev/mcp-server — CLI entry point\n *\n * Usage:\n * npx @adhdev/mcp-server # local mode (localhost:3847)\n * npx @adhdev/mcp-server --port 4000 # custom port\n * npx @adhdev/mcp-server --mode ipc --repo-mesh mesh_xxx # cloud daemon IPC mode\n */\n\nimport { buildMcpHelpText } from './help.js';\nimport { startMcpServer } from './server.js';\n\nexport function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): {\n mode: 'local' | 'ipc';\n port?: number;\n password?: string;\n meshId?: string;\n} {\n const args = argv.slice(2);\n let port: number | undefined;\n let password: string | undefined;\n let meshId: string | undefined;\n let explicitMode: 'local' | 'ipc' | undefined;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--mode' && args[i + 1]) {\n const value = String(args[++i]).trim();\n if (value === 'local' || value === 'ipc') explicitMode = value;\n } else if (arg?.startsWith('--mode=')) {\n const value = arg.slice('--mode='.length).trim();\n if (value === 'local' || value === 'ipc') explicitMode = value;\n } else if (arg === '--port' && args[i + 1]) {\n port = Number(args[++i]);\n } else if (arg?.startsWith('--port=')) {\n port = Number(arg.slice('--port='.length));\n } else if (arg === '--password' && args[i + 1]) {\n password = args[++i];\n } else if ((arg === '--repo-mesh' || arg === '--mesh') && args[i + 1]) {\n meshId = args[++i];\n } else if (arg?.startsWith('--repo-mesh=')) {\n meshId = arg.slice('--repo-mesh='.length);\n } else if (arg === '--help' || arg === '-h') {\n printHelp();\n process.exit(0);\n }\n }\n\n // Also accept env vars\n if (!password && env.ADHDEV_PASSWORD) password = env.ADHDEV_PASSWORD;\n if (!meshId && env.ADHDEV_MESH_ID) meshId = env.ADHDEV_MESH_ID;\n if (!explicitMode && env.ADHDEV_MCP_TRANSPORT) {\n const value = env.ADHDEV_MCP_TRANSPORT.trim();\n if (value === 'local' || value === 'ipc') explicitMode = value;\n }\n\n const mode = explicitMode || (meshId && env.ADHDEV_INLINE_MESH ? 'ipc' : 'local');\n return { mode, port, password, meshId };\n}\n\nfunction printHelp(): void {\n console.error(buildMcpHelpText());\n}\n\nstartMcpServer(parseArgs(process.argv)).catch((err) => {\n process.stderr.write(`[adhdev-mcp] Fatal: ${err?.message ?? err}\\n`);\n process.exit(1);\n});\n","/**\n * IpcTransport — WebSocket client for the cloud daemon's local IPC server.\n *\n * This is used by Repo Mesh coordinators launched by `adhdev daemon` (cloud\n * daemon). They run on the same machine as the daemon, but not against the\n * standalone HTTP server at localhost:3847.\n *\n * Uses a persistent connection pool (one WS per port+path) so concurrent\n * mesh tool calls share a single connection instead of opening a new socket\n * per request.\n */\n\nconst DEFAULT_IPC_PORT = 19222;\nconst DEFAULT_IPC_PATH = '/ipc';\nconst DEFAULT_IPC_COMMAND_TIMEOUT_MS = 15_000;\n// IPC (layer-1) is the OUTERMOST deadline. For a REMOTE node the coordinator wraps\n// the verb in `mesh_relay_command` (120s here), so getTimeoutMs() already covers the\n// relay/responder budget. But for a LOCAL node commandForNode() sends the BARE verb\n// (transport.command), so the only deadline is this table — and any heavy verb missing\n// an entry fell back to the 15s default and false-timed-out while the responder was\n// still working (e.g. a local `clone_mesh_node` worktree create). Entries below keep\n// IPC ≥ the relay budget (daemon-cloud resultTimeoutForCommand) ≥ the responder budget.\nconst IPC_COMMAND_TIMEOUTS_MS: Record<string, number> = {\n mesh_relay_command: 120_000,\n agent_command: 30_000,\n git_status: 45_000,\n git_diff_summary: 45_000,\n fast_forward_mesh_node: 120_000,\n mesh_status: 120_000,\n // Heavy repo-mutating worktree ops (relay budgets: clone 90s, remove 60s). A local\n // clone synchronously creates a worktree (~30s) plus a bounded setup-wait (~14s);\n // 120s leaves headroom and matches the relay-wrapped remote path.\n clone_mesh_node: 120_000,\n remove_mesh_node: 60_000,\n // A5: plan_mesh_refine_node is the SYNCHRONOUS refine dry-run — it runs several git\n // probes (status/merge-tree/submodule) inline before replying, which can approach the\n // 15s default on a slow (Windows) host. 45s defensively, matching git_status/diff.\n plan_mesh_refine_node: 45_000,\n // A2: refine_mesh_node / batch_refine_mesh_nodes are async-job-ack (the responder\n // returns { async:true, status:'accepted' } immediately and works in the background),\n // so 15s already suffices. 30s is a defensive floor guarding a future sync-dry-run\n // regression; it is intentionally BELOW the relay 90s budget because the synchronous\n // ack reply is sub-second and never bounded by the relay deadline.\n refine_mesh_node: 30_000,\n batch_refine_mesh_nodes: 30_000,\n};\n\n// WS readyState constants (same as browser)\nconst WS_CONNECTING = 0;\nconst WS_OPEN = 1;\n\ninterface PendingRequest {\n resolve: (value: any) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\nconst POOL_IDLE_EVICT_MS = 5 * 60_000; // evict connections idle for >5 min\nconst POOL_MAX_AGE_MS = 10 * 60_000; // force-refresh connections older than 10 min\n\ninterface PooledConnection {\n ws: WebSocket;\n ready: boolean;\n commandQueue: Array<{ type: string; args: Record<string, unknown>; requestId: string }>;\n pending: Map<string, PendingRequest>;\n lastUsedAt: number;\n createdAt: number;\n}\n\nconst connectionPool = new Map<string, PooledConnection>();\n\nfunction buildRequestId(): string {\n return `mcp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\nexport function getTimeoutMs(type: string, nestedCommand: string): number {\n return Math.max(\n IPC_COMMAND_TIMEOUTS_MS[type] ?? DEFAULT_IPC_COMMAND_TIMEOUT_MS,\n IPC_COMMAND_TIMEOUTS_MS[nestedCommand] ?? DEFAULT_IPC_COMMAND_TIMEOUT_MS,\n );\n}\n\nfunction getOrCreateConnection(\n WebSocketCtor: typeof WebSocket,\n url: string,\n): PooledConnection {\n const existing = connectionPool.get(url);\n if (existing) {\n const { readyState } = existing.ws;\n const now = Date.now();\n const isAlive = readyState === WS_CONNECTING || readyState === WS_OPEN;\n const isIdle = now - existing.lastUsedAt > POOL_IDLE_EVICT_MS && existing.pending.size === 0;\n const isTooOld = now - existing.createdAt > POOL_MAX_AGE_MS && existing.pending.size === 0;\n if (isAlive && !isIdle && !isTooOld) {\n return existing;\n }\n if (isAlive && (isIdle || isTooOld)) {\n try { existing.ws.close(); } catch { /* noop */ }\n connectionPool.delete(url);\n }\n // Stale — remove and recreate\n connectionPool.delete(url);\n }\n\n const now = Date.now();\n const conn: PooledConnection = {\n ws: new WebSocketCtor(url),\n ready: false,\n commandQueue: [],\n pending: new Map(),\n lastUsedAt: now,\n createdAt: now,\n };\n connectionPool.set(url, conn);\n\n const drainQueue = () => {\n conn.ready = true;\n for (const { type, args, requestId } of conn.commandQueue) {\n conn.ws.send(JSON.stringify({ type: 'ext:command', payload: { command: type, args, requestId } }));\n }\n conn.commandQueue = [];\n };\n\n let tornDown = false;\n const teardown = (error: Error) => {\n if (tornDown) return;\n tornDown = true;\n connectionPool.delete(url);\n conn.ready = false;\n for (const [, req] of conn.pending) {\n clearTimeout(req.timer);\n req.reject(error);\n }\n conn.pending.clear();\n conn.commandQueue = [];\n };\n\n conn.ws.addEventListener('open', () => {\n conn.ws.send(JSON.stringify({\n type: 'ext:register',\n payload: {\n ideType: 'mcp-server',\n ideVersion: '1.0.0',\n extensionVersion: '1.0.0',\n instanceId: `mcp-server-${process.pid}`,\n machineId: 'mcp-server',\n workspaceFolders: [],\n },\n }));\n });\n\n conn.ws.addEventListener('message', (event: MessageEvent) => {\n try {\n const raw = typeof event.data === 'string' ? event.data : String(event.data);\n const msg = JSON.parse(raw);\n if (msg?.type === 'daemon:welcome') {\n drainQueue();\n return;\n }\n if (msg?.type !== 'ext:command_result') return;\n const req = conn.pending.get(msg?.payload?.requestId);\n if (!req) return;\n conn.pending.delete(msg.payload.requestId);\n clearTimeout(req.timer);\n const payload = msg.payload;\n // A structured `result` means the responder actually processed the command\n // and produced a semantic outcome — including a legitimate FAILURE such as a\n // `blocked` fast-forward carrying `blockingReasons` (success:false, no top-level\n // `error`). That is NOT a transport failure; rejecting here would discard the\n // result and surface an opaque \"Daemon IPC command failed\" to the coordinator.\n // Only reject when the reply carries no structured result to preserve (i.e. a\n // genuine transport/handler failure with just an error string).\n const hasStructuredResult = payload != null && payload.result != null;\n if (payload?.success === false && !hasStructuredResult) {\n req.reject(new Error(payload.error || 'Daemon IPC command failed'));\n } else {\n req.resolve(payload?.result ?? payload);\n }\n } catch {\n // Ignore non-JSON or unrelated daemon messages.\n }\n });\n\n conn.ws.addEventListener('error', () => {\n teardown(new Error(`Cannot connect to daemon IPC at ${url}`));\n });\n\n conn.ws.addEventListener('close', () => {\n teardown(new Error(`Daemon IPC connection closed: ${url}`));\n });\n\n return conn;\n}\n\nexport interface IpcTransportOptions {\n port?: number;\n path?: string;\n}\n\nexport class IpcTransport {\n private port: number;\n private path: string;\n\n constructor(opts: IpcTransportOptions = {}) {\n this.port = opts.port ?? DEFAULT_IPC_PORT;\n this.path = opts.path || DEFAULT_IPC_PATH;\n }\n\n async ping(): Promise<boolean> {\n try {\n const res = await fetch(`http://127.0.0.1:${this.port}/health`);\n return res.ok;\n } catch {\n return false;\n }\n }\n\n async getStatus(): Promise<any> {\n return this.command('get_status_metadata');\n }\n\n async command(type: string, args: Record<string, unknown> = {}): Promise<any> {\n return this.sendIpcCommand(type, args);\n }\n\n async meshCommand(\n targetDaemonId: string,\n command: string,\n args: Record<string, unknown> = {},\n ): Promise<any> {\n return this.sendIpcCommand('mesh_relay_command', {\n targetDaemonId,\n command,\n args,\n });\n }\n\n private sendIpcCommand(type: string, args: Record<string, unknown>): Promise<any> {\n const WebSocketCtor = globalThis.WebSocket;\n if (!WebSocketCtor) {\n return Promise.reject(new Error('WebSocket is not available in this Node runtime; Node 20+ is required for daemon IPC mode'));\n }\n\n const requestId = buildRequestId();\n const nestedCommand = typeof args?.command === 'string' ? args.command : '';\n const timeoutMs = getTimeoutMs(type, nestedCommand);\n const targetDaemonId = typeof args?.targetDaemonId === 'string' ? args.targetDaemonId : '';\n\n const diagnosticParts = [\n `command='${type}'`,\n ...(nestedCommand ? [`relayedCommand='${nestedCommand}'`] : []),\n ...(targetDaemonId ? [`targetDaemonId='${targetDaemonId.slice(0, 12)}'`] : []),\n ...(typeof args?.nodeId === 'string' ? [`nodeId='${args.nodeId}'`] : []),\n ...(typeof args?.workspace === 'string' ? [`workspace='${args.workspace}'`] : []),\n ];\n\n const url = `ws://127.0.0.1:${this.port}${this.path}`;\n\n return new Promise((resolve, reject) => {\n let conn: PooledConnection;\n try {\n conn = getOrCreateConnection(WebSocketCtor as typeof WebSocket, url);\n } catch (e: any) {\n return reject(new Error(`Failed to create IPC connection: ${e?.message || e}`));\n }\n\n const timer = setTimeout(() => {\n conn.pending.delete(requestId);\n reject(new Error(`Daemon IPC ${diagnosticParts.join(' ')} timed out after ${Math.round(timeoutMs / 1000)}s (requestId=${requestId})`));\n }, timeoutMs);\n\n conn.pending.set(requestId, { resolve, reject, timer });\n conn.lastUsedAt = Date.now();\n\n if (conn.ready) {\n conn.ws.send(JSON.stringify({ type: 'ext:command', payload: { command: type, args, requestId } }));\n } else {\n conn.commandQueue.push({ type, args, requestId });\n }\n });\n }\n}\n","export type CompactChatMessage = Record<string, any>;\n\nexport function messageContent(message: any): string {\n const content = message?.content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content.map((part: any) => (typeof part === 'string' ? part : part?.text ?? '')).join('');\n }\n return '';\n}\n\nexport function isCoordinatorVisibleMessage(message: any): boolean {\n if (!message || typeof message !== 'object') return false;\n const role = String(message.role ?? '').toLowerCase();\n if (role === 'tool' || role === 'system' || role === 'debug') return false;\n const kind = String(message.kind ?? message.type ?? message.messageKind ?? '').toLowerCase();\n if (['tool', 'tool_call', 'tool_result', 'terminal', 'internal', 'control', 'debug', 'status'].includes(kind)) return false;\n const meta = message.meta ?? message.metadata;\n if (meta?.internal === true || meta?.debug === true || meta?.control === true || meta?.userVisible === false || meta?.user_visible === false) return false;\n return role === 'user' || role === 'assistant' || role === 'agent';\n}\n\n/**\n * Build a one-line summary string for a tool/bash message that was filtered out.\n * Returns null when no useful summary can be extracted.\n */\nexport function summarizeToolMessage(message: any): string | null {\n if (!message || typeof message !== 'object') return null;\n const kind = String(message.kind ?? message.type ?? message.messageKind ?? '').toLowerCase();\n const role = String(message.role ?? '').toLowerCase();\n\n // Bash / terminal execution\n if (kind === 'terminal' || kind === 'bash') {\n const cmd = message.command ?? message.cmd ?? message.input ?? messageContent(message);\n const exit = message.exitCode ?? message.exit_code ?? message.code;\n const cmdShort = typeof cmd === 'string' ? cmd.split('\\n')[0].slice(0, 120) : null;\n if (!cmdShort) return null;\n return exit !== undefined && exit !== null ? `[Bash] ${cmdShort} → exit ${exit}` : `[Bash] ${cmdShort}`;\n }\n\n // Tool call (Claude-style function call)\n if (kind === 'tool_call' || kind === 'tool' || role === 'tool') {\n const name = message.name ?? message.toolName ?? message.tool_name ?? message.function?.name;\n if (typeof name === 'string' && name.trim()) return `[Tool] ${name.trim()}`;\n return null;\n }\n\n // Tool result with explicit exit code\n if (kind === 'tool_result') {\n const exit = message.exitCode ?? message.exit_code ?? message.code;\n const name = message.name ?? message.toolName ?? message.tool_name;\n const label = typeof name === 'string' && name.trim() ? name.trim() : 'tool';\n return exit !== undefined && exit !== null ? `[Tool result: ${label}] exit ${exit}` : null;\n }\n\n return null;\n}\n\nexport function buildCompactMessageTail(\n visibleMessages: CompactChatMessage[],\n opts: { summary?: string; finalAssistant?: CompactChatMessage | undefined; limit: number },\n): CompactChatMessage[] {\n const tail = visibleMessages.slice(-opts.limit);\n // Always include the final assistant message even if it falls outside the tail window.\n if (opts.finalAssistant && !tail.includes(opts.finalAssistant)) {\n return [opts.finalAssistant, ...tail];\n }\n return tail;\n}\n\n/**\n * Normalize message text for an equality check between the compact `summary`\n * field and a message bubble's content. Trims and collapses interior whitespace\n * so trivially-different copies of the same report compare equal.\n */\nfunction normalizeForSummaryEquality(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * When compact mode lifts the final assistant bubble into the `summary` field,\n * the same report text would otherwise be serialized a SECOND time inside the\n * returned `messages[]` tail — exactly doubling the payload for long reports.\n * This rewrites any tail bubble whose content is substantively identical to the\n * summary into a content-free stub carrying `_sameAsSummary: true`, so the body\n * lives exactly once (in `summary`). Bubble position/role/timestamp are preserved\n * for callers that walk the tail; the body is recoverable from `summary`.\n */\nexport function dedupeSummaryFromTail(\n messages: CompactChatMessage[],\n summary: string | undefined,\n): CompactChatMessage[] {\n const normalizedSummary = summary ? normalizeForSummaryEquality(summary) : '';\n if (!normalizedSummary) return messages;\n return messages.map((message) => {\n const role = String(message?.role ?? '').toLowerCase();\n if (role !== 'assistant' && role !== 'agent') return message;\n const content = messageContent(message);\n if (!content.trim()) return message;\n if (normalizeForSummaryEquality(content) !== normalizedSummary) return message;\n const { content: _omitted, ...rest } = message;\n return { ...rest, content: '', _sameAsSummary: true };\n });\n}\n\nexport function compactChatPayload(\n payload: any,\n opts: { sessionId?: string | null; nodeId?: string; limit?: number } = {},\n): any {\n const rawMessages = Array.isArray(payload?.messages) ? payload.messages : [];\n const visible = rawMessages.filter(isCoordinatorVisibleMessage);\n const limit = Math.max(1, Math.min(opts.limit ?? 10, 10));\n const finalAssistant = [...visible].reverse().find((message: any) => {\n const role = String(message?.role ?? '').toLowerCase();\n return (role === 'assistant' || role === 'agent') && messageContent(message).trim();\n });\n const summary = typeof payload?.summary === 'string' && payload.summary.trim()\n ? payload.summary.trim()\n : messageContent(finalAssistant).trim();\n // The final assistant bubble is now lifted into `summary`; strip its duplicate\n // body from the tail so a long report isn't serialized twice (leak #1).\n const messages = dedupeSummaryFromTail(\n buildCompactMessageTail(visible, { summary, finalAssistant, limit }),\n summary,\n );\n\n // Collect one-line summaries for filtered-out tool/bash messages so the coordinator\n // can see what actions were taken without reading the full transcript.\n const toolSummaries = rawMessages\n .filter((m: any) => !isCoordinatorVisibleMessage(m))\n .map(summarizeToolMessage)\n .filter((s: string | null): s is string => s !== null);\n\n // omittedMessages = total messages not included in the returned `messages` tail.\n // This includes both filtered (tool/system) messages AND visible messages cut off by the tail limit.\n const omittedMessages = Math.max(0, rawMessages.length - messages.length);\n // filteredMessages = only the non-user-visible messages (for backward compat).\n const filteredMessages = Math.max(0, rawMessages.length - visible.length);\n\n return {\n success: payload?.success !== false,\n compact: true,\n ...(opts.nodeId ? { nodeId: opts.nodeId } : {}),\n ...(opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {}),\n status: payload?.status ?? null,\n providerSessionId: payload?.providerSessionId ?? null,\n totalMessages: rawMessages.length,\n visibleMessages: visible.length,\n filteredMessages,\n omittedMessages,\n ...(toolSummaries.length > 0 ? { toolSummaries } : {}),\n summary,\n ...(payload?.changedFiles !== undefined ? { changedFiles: payload.changedFiles } : {}),\n ...(payload?.testsRun !== undefined ? { testsRun: payload.testsRun } : {}),\n messages,\n };\n}\n","/**\n * Pure JSON-record reading primitives shared by the cloud (web-core / P2P transit)\n * and standalone (daemon-core / local IPC) mesh normalizers.\n *\n * These operate only on plain JS values — no Node/DOM APIs, no transport, no git\n * exec — so both cores can import them without violating the core↔core dependency\n * ban. They are the single source of truth for the field-coercion rules that the\n * two transports previously hand-synced (and drifted on).\n */\n\nexport type JsonRecord = Record<string, unknown>\n\nexport function readRecord(value: unknown): JsonRecord {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonRecord : {}\n}\n\nexport function readString(...values: unknown[]): string | undefined {\n for (const value of values) {\n if (typeof value !== 'string') continue\n const trimmed = value.trim()\n if (trimmed) return trimmed\n }\n return undefined\n}\n\nexport function readNumber(...values: unknown[]): number | undefined {\n for (const value of values) {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\nexport function readBoolean(...values: unknown[]): boolean | undefined {\n for (const value of values) {\n if (typeof value === 'boolean') return value\n }\n return undefined\n}\n\nexport function readStringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0)\n : []\n}\n\n/**\n * Coerce a value that is either an already-parsed plain object or a JSON string\n * into a plain object record. Arrays, primitives, parse failures and empty\n * strings all collapse to {} — callers treat the result as a best-effort record.\n *\n * This is the single source of truth for the `parseJsonRecord`/`parseJsonObject`\n * coercion that cloud mesh normalizers previously hand-redefined per file.\n */\nexport function parseJsonRecord(value: unknown): JsonRecord {\n if (!value) return {}\n if (typeof value === 'object') return readRecord(value)\n if (typeof value !== 'string') return {}\n const trimmed = value.trim()\n if (!trimmed) return {}\n try {\n return readRecord(JSON.parse(trimmed))\n } catch {\n return {}\n }\n}\n\n/**\n * Join a (possibly absent) repo root with a relative submodule path. Returns the\n * path unchanged when it is already absolute, and undefined when nothing usable\n * can be derived — callers must treat the result as optional.\n */\nexport function joinRepoPath(root: string | undefined, relativePath: string | undefined): string | undefined {\n const normalizedRoot = typeof root === 'string' ? root.trim().replace(/[\\\\/]+$/, '') : ''\n const normalizedPath = typeof relativePath === 'string' ? relativePath.trim() : ''\n if (!normalizedPath) return undefined\n if (/^(?:[A-Za-z]:[\\\\/]|\\/)/.test(normalizedPath)) return normalizedPath\n if (!normalizedRoot) return undefined\n return `${normalizedRoot}/${normalizedPath.replace(/^[\\\\/]+/, '')}`\n}\n","/**\n * Canonical git-status normalizers shared by the cloud (web-core) and standalone\n * (daemon-core router) mesh paths. Previously each transport hand-maintained its\n * own copy and they drifted (e.g. submodule drop rules, evidence checks); this is\n * the one implementation both import.\n */\n\nimport { joinRepoPath, readBoolean, readNumber, readRecord, readString, type JsonRecord } from './json'\nimport type { GitRepoStatus, GitSubmoduleStatus, GitUpstreamFreshness } from './types'\n\nexport function scoreGitUpstreamFreshness(status: GitUpstreamFreshness | undefined): number {\n switch (status) {\n case 'fresh':\n return 30\n case 'no_upstream':\n return 4\n case 'unchecked':\n case undefined:\n return 0\n case 'stale':\n return -10\n case 'unavailable':\n return -15\n default:\n return 0\n }\n}\n\nexport function readGitSubmodules(value: unknown, parentRepoRoot?: string): GitSubmoduleStatus[] | undefined {\n if (!Array.isArray(value)) return undefined\n const submodules = value\n .map(entry => {\n const submodule = readRecord(entry)\n const path = readString(submodule.path)\n const commit = readString(submodule.commit)\n const repoPath = readString(submodule.repoPath, submodule.repo_root)\n ?? joinRepoPath(parentRepoRoot, path)\n // repoPath is only used for the submodule node's display workspace, which is\n // allowed to be empty. The cloud P2P transit path can deliver submodule entries\n // without repoPath (and a per-node git object without a derivable repoRoot), so\n // dropping on missing repoPath would silently strip every submodule graph node.\n // Keep any submodule that carries both path and commit.\n if (!path || !commit) return null\n const result: GitSubmoduleStatus = {\n path,\n commit,\n dirty: readBoolean(submodule.dirty) ?? false,\n outOfSync: readBoolean(submodule.outOfSync, submodule.out_of_sync) ?? false,\n lastCheckedAt: readNumber(submodule.lastCheckedAt, submodule.last_checked_at) ?? Date.now(),\n }\n if (repoPath) result.repoPath = repoPath\n const error = readString(submodule.error)\n if (error) result.error = error\n return result\n })\n .filter((entry): entry is GitSubmoduleStatus => entry !== null)\n return submodules.length > 0 ? submodules : undefined\n}\n\nexport function hasGitStatusEvidence(status: JsonRecord): boolean {\n // BUG FIX: a transit-reshaped git status that carries only a repoRoot/workspace\n // (e.g. cloud P2P stripped the branch/upstream/counters but kept the path) must\n // NOT be dropped — otherwise the node loses its git object and any submodules\n // hanging off it. Treat a present repoRoot/repo_root/workspace as evidence too.\n return readBoolean(status.isGitRepo) !== undefined\n || Boolean(readString(status.branch, status.upstream, status.upstreamStatus, status.upstream_status, status.headCommit))\n || Boolean(readString(status.repoRoot, status.repo_root, status.workspace))\n || readNumber(\n status.ahead,\n status.behind,\n status.staged,\n status.modified,\n status.untracked,\n status.deleted,\n status.renamed,\n status.lastCheckedAt,\n status.last_checked_at,\n ) !== undefined\n || (Array.isArray(status.submodules) && status.submodules.length > 0)\n}\n\nexport function normalizeGitStatus(\n status: JsonRecord,\n node: JsonRecord,\n options?: { lastCheckedAt?: number },\n): GitRepoStatus | undefined {\n const explicitIsGitRepo = readBoolean(status.isGitRepo)\n if (!Object.keys(status).length || !hasGitStatusEvidence(status)) return undefined\n const isGitRepo = explicitIsGitRepo ?? true\n const conflictFiles = Array.isArray(status.conflictFiles)\n ? status.conflictFiles.filter((entry): entry is string => typeof entry === 'string')\n : []\n const conflictCount = readNumber(status.conflicts) ?? conflictFiles.length\n const hasConflicts = readBoolean(status.hasConflicts) ?? conflictCount > 0\n // node.workspace is in the fallback chain so a transit node carrying its path only\n // on the node (not the inner git object) still yields a parentRepoRoot for submodules.\n const repoRoot = readString(status.repoRoot, status.repo_root, node.repoRoot, node.repo_root, status.workspace, node.workspace) || undefined\n const submodules = readGitSubmodules(status.submodules, repoRoot)\n const upstreamStatus = readString(status.upstreamStatus, status.upstream_status)\n const upstreamFetchedAt = readNumber(status.upstreamFetchedAt, status.upstream_fetched_at)\n const upstreamFetchError = readString(status.upstreamFetchError, status.upstream_fetch_error)\n const error = readString(status.error)\n const staged = readNumber(status.staged) ?? 0\n const modified = readNumber(status.modified) ?? 0\n const untracked = readNumber(status.untracked) ?? 0\n const deleted = readNumber(status.deleted) ?? 0\n const renamed = readNumber(status.renamed) ?? 0\n return {\n workspace: readString(status.workspace, node.workspace) || '',\n repoRoot: repoRoot ?? null,\n isGitRepo,\n branch: readString(status.branch) ?? null,\n headCommit: readString(status.headCommit) ?? null,\n headMessage: readString(status.headMessage) ?? null,\n upstream: readString(status.upstream) ?? null,\n upstreamStatus: (upstreamStatus as GitUpstreamFreshness) ?? 'unchecked',\n ...(upstreamFetchedAt !== undefined ? { upstreamFetchedAt } : {}),\n ...(upstreamFetchError ? { upstreamFetchError } : {}),\n ahead: readNumber(status.ahead) ?? 0,\n behind: readNumber(status.behind) ?? 0,\n staged,\n modified,\n untracked,\n deleted,\n renamed,\n dirty: readBoolean(status.dirty, status.isDirty, status.is_dirty) ?? (staged + modified + untracked + deleted + renamed > 0 || hasConflicts),\n hasConflicts,\n conflictFiles,\n stashCount: readNumber(status.stashCount, status.stash_count) ?? 0,\n lastCheckedAt: options?.lastCheckedAt ?? readNumber(status.lastCheckedAt, status.last_checked_at) ?? Date.now(),\n ...(submodules ? { submodules } : {}),\n ...(error ? { error } : {}),\n }\n}\n\nexport function scoreGitStatusCandidate(git: GitRepoStatus | undefined): number {\n if (!git) return Number.NEGATIVE_INFINITY\n let score = 0\n if (git.isGitRepo === true) score += 50\n if (git.isGitRepo === false) score -= 10\n if (git.branch) score += 20\n if (git.headCommit) score += 20\n if (git.upstream) score += 10\n score += scoreGitUpstreamFreshness(git.upstreamStatus)\n if (typeof git.ahead === 'number') score += 2\n if (typeof git.behind === 'number') score += 2\n if (Array.isArray(git.submodules) && git.submodules.length > 0) score += 4 + git.submodules.length\n if (git.error) score -= 20\n return score\n}\n\n/**\n * Pick the best git status out of the four transit envelope slots a mesh node can\n * carry: lastGit.status, lastGit.result.status, lastProbe.git.status,\n * lastProbe.git.result.status. Returns undefined when none carry git evidence.\n */\nexport function pickBestTransitGitStatus(node: JsonRecord, options?: { lastCheckedAt?: number }): GitRepoStatus | undefined {\n const rawGit = readRecord(node.lastGit ?? node.last_git)\n const gitResult = readRecord(rawGit.result)\n const directStatus = readRecord(rawGit.status)\n const nestedStatus = readRecord(gitResult.status)\n const rawProbe = readRecord(node.lastProbe ?? node.last_probe)\n const probeGit = readRecord(rawProbe.git)\n const probeGitResult = readRecord(probeGit.result)\n const probeDirectStatus = readRecord(probeGit.status)\n const probeNestedStatus = readRecord(probeGitResult.status)\n const lastCheckedAt = options?.lastCheckedAt\n let best: { git: GitRepoStatus; score: number } | null = null\n for (const status of [directStatus, nestedStatus, probeDirectStatus, probeNestedStatus]) {\n const normalized = normalizeGitStatus(status, node, { lastCheckedAt: lastCheckedAt ?? Date.now() })\n if (!normalized) continue\n const score = scoreGitStatusCandidate(normalized)\n if (!best || score > best.score) best = { git: normalized, score }\n }\n return best?.git\n}\n","/**\n * Canonical mesh-session record normalizer shared by the cloud (web-core) mesh\n * paths. Parses an already-transit-shaped session record into a typed\n * RepoMeshSessionStatus.\n */\n\nimport { readBoolean, readRecord, readString } from './json'\nimport type { RepoMeshSessionStatus } from './types'\n\n/**\n * Build a deterministic synthetic session id from a record that has no explicit\n * id. Two transit refreshes of the same logical session produce the same id so\n * downstream dedupe stays stable across refreshes (a random id would create a new\n * node every poll). Derived from the stable identifying fields available on the\n * record; prefixed \"synthetic:\" so callers can tell it apart from a real id.\n */\nfunction deriveSyntheticSessionId(record: ReturnType<typeof readRecord>): string | undefined {\n const parts = [\n readString(record.workspace),\n readString(record.providerType, record.provider),\n readString(record.role),\n readString(record.state, record.status),\n readString(record.title),\n readString(record.createdAt, record.created_at),\n readString(record.startedAt, record.started_at),\n ].filter((part): part is string => Boolean(part))\n if (parts.length === 0) return undefined\n return `synthetic:${parts.join('|')}`\n}\n\n/**\n * Session-id equivalence — the sessionId counterpart of daemonIdsEquivalent /\n * meshNodeIdMatches. A session id is SINGLE-FORM: one canonical UUID minted once\n * via crypto.randomUUID() in the provider instance and carried verbatim across\n * daemons, with no node/daemon-id style serialization variants. Equivalence is\n * therefore an exact match after trimming, never matching an absent/empty id\n * against another absent/empty id. Routing every mesh comparison site through\n * this one predicate keeps that single-form policy in one place (and gives any\n * future session-id aliasing a single seam) instead of scattering raw `===`.\n */\nexport function sessionIdsEquivalent(a: string | null | undefined, b: string | null | undefined): boolean {\n const idA = readString(a)\n const idB = readString(b)\n if (!idA || !idB) return false\n return idA === idB\n}\n\nexport function normalizeMeshSessionRecord(entry: unknown): RepoMeshSessionStatus | null {\n const record = readRecord(entry)\n // BUG FIX: cloud transit can reshape/strip the explicit id field. Fall back\n // through sessionId → session_id → id, then to a DETERMINISTIC synthetic id\n // derived from record content so the session survives the round trip instead\n // of being dropped (and so dedupe stays stable across refreshes). Return null\n // ONLY when the record carries no identifying fields at all.\n const sessionId = readString(record.sessionId, record.session_id, record.id)\n ?? deriveSyntheticSessionId(record)\n if (!sessionId) return null\n return {\n sessionId,\n ...(readString(record.providerType, record.provider) ? { providerType: readString(record.providerType, record.provider) } : {}),\n ...(readString(record.state, record.status) ? { state: readString(record.state, record.status) } : {}),\n ...(readString(record.chatStatus, record.chat_status) ? { chatStatus: readString(record.chatStatus, record.chat_status) } : {}),\n ...(readString(record.lifecycle) ? { lifecycle: readString(record.lifecycle) as RepoMeshSessionStatus['lifecycle'] } : {}),\n ...(readString(record.surfaceKind, record.surface_kind) ? { surfaceKind: readString(record.surfaceKind, record.surface_kind) as RepoMeshSessionStatus['surfaceKind'] } : {}),\n ...(readString(record.recoveryState, record.recovery_state) ? { recoveryState: readString(record.recoveryState, record.recovery_state) } : {}),\n ...(readString(record.workspace) ? { workspace: readString(record.workspace) } : {}),\n ...(readString(record.title) ? { title: readString(record.title) } : {}),\n ...(readString(record.role) ? { role: readString(record.role) } : {}),\n ...(readBoolean(record.isSelfCoordinator, record.is_self_coordinator) !== undefined ? { isSelfCoordinator: readBoolean(record.isSelfCoordinator, record.is_self_coordinator) } : {}),\n ...(readString(record.statusNote, record.status_note) ? { statusNote: readString(record.statusNote, record.status_note) } : {}),\n ...(readString(record.createdAt, record.created_at) ? { createdAt: readString(record.createdAt, record.created_at) } : {}),\n ...(readString(record.startedAt, record.started_at) ? { startedAt: readString(record.startedAt, record.started_at) } : {}),\n ...(readString(record.lastActivityAt, record.last_activity_at) ? { lastActivityAt: readString(record.lastActivityAt, record.last_activity_at) } : {}),\n ...(readBoolean(record.isCached, record.is_cached) !== undefined ? { isCached: readBoolean(record.isCached, record.is_cached) } : {}),\n }\n}\n","/**\n * Canonical mesh-node identity normalizer shared by daemon-core (standalone /\n * local IPC) and web-core (cloud / P2P transit) — the node-id counterpart of\n * session-normalize.ts.\n *\n * A mesh node record can carry its stable identifier under THREE different field\n * names depending on the serialization path it travelled, all with the same\n * value:\n * - `id` — config canonical form (mesh registry / persisted config)\n * - `nodeId` — runtime/wire camelCase form (inline-cache de-serialization,\n * mesh_status output via readStringValue(node.nodeId, node.id))\n * - `node_id` — SQLite DB column form leaked onto the object\n *\n * Comparing only `node.id` (or a 2-way `id ?? nodeId` that omits `node_id`)\n * against a target id silently drops nodes that arrived in another form — e.g. an\n * inline-cached worktree node, leaving a target-routed task permanently pending\n * with a misleading `no_node_satisfies_required_tags` skip. This module is the\n * single 3-way source of truth so every comparison site absorbs all three forms.\n */\n\nimport { readString } from './json'\nimport type { MeshNodeIdentified } from './types'\n\n/**\n * Read a mesh node's stable identifier, absorbing any of the three\n * serialization forms (`id` / `nodeId` / `node_id`). Returns undefined when the\n * record carries no usable id in any form.\n */\nexport function normalizeMeshNodeId(node: MeshNodeIdentified | null | undefined): string | undefined {\n const record = (node && typeof node === 'object' ? node : {}) as MeshNodeIdentified\n return readString(record.id, record.nodeId, record.node_id)\n}\n\n/**\n * Whether a mesh node record matches the given candidate id, comparing the\n * node's normalized id (any form) against the candidate. False when either side\n * is empty — never matches an absent id against an absent candidate.\n */\nexport function meshNodeIdMatches(\n node: MeshNodeIdentified | null | undefined,\n candidateId: string | null | undefined,\n): boolean {\n if (!candidateId) return false\n const trimmed = candidateId.trim()\n if (!trimmed) return false\n return normalizeMeshNodeId(node) === trimmed\n}\n","/**\n * Canonical workspace-path normalizer for mesh node/session scope comparison,\n * shared by daemon-core (standalone / local IPC) and any other core that has to\n * tell a base node apart from a co-located worktree clone whose ONLY structural\n * difference is its distinct workspace root.\n *\n * One physical daemon can host a base node plus several worktree nodes. Session\n * records, queue claims, and read_chat requests are scoped to a node by matching\n * the session's actual workspace against the node's declared workspace. Those two\n * paths can arrive in different but equivalent spellings (back/forward slashes,\n * trailing separators, Windows case-insensitivity), so a raw string compare would\n * either falsely separate equal paths or fail to engage at all.\n *\n * This folds separator style, trailing slashes, and case into a single comparable\n * form. It was previously a module-private copy in daemon-core's\n * mesh-events-coordinator.ts (WTCLAIM fix-B); promoting it here keeps the one\n * comparison rule identical across the enqueue→claim path, the mesh_status\n * per-node session filter, and the read_chat node scope guard. Pure string ops —\n * no Node/DOM APIs — so it stays a valid mesh-shared leaf.\n */\nexport function normalizeMeshWorkspaceForCompare(dir?: string | null): string {\n if (typeof dir !== 'string') return ''\n return dir.trim().replace(/[\\\\/]+/g, '/').replace(/\\/+$/, '').toLowerCase()\n}\n\n/**\n * Whether two workspace paths refer to the same workspace root after\n * normalization. Returns false when either side is empty — an unknown workspace\n * never \"matches\" another, so callers must decide separately whether an unknown\n * workspace should be treated permissively (the WTCLAIM convention: unknown →\n * do not block).\n */\nexport function meshWorkspacesEquivalent(a?: string | null, b?: string | null): boolean {\n const left = normalizeMeshWorkspaceForCompare(a)\n const right = normalizeMeshWorkspaceForCompare(b)\n if (!left || !right) return false\n return left === right\n}\n","/**\n * Canonical coordinator/daemon-id form normalizer shared by daemon-core (the mesh\n * reconcile loop, pending-event queue, and MCP surface) — the daemon-id counterpart\n * of node-normalize.ts.\n *\n * A daemon answers to the SAME machine under three interchangeable id forms, all\n * derived from one `mach_<hex>` machine id:\n * - bare — `mach_<hex>` (loadConfig().machineId; stamped by the local\n * queue-assignment dispatch path)\n * - cloud — `daemon_mach_<hex>` (the coordinator mesh node's config-form\n * daemonId, which the MCP layer's resolveCoordinatorDaemonId\n * prefers and stamps onto a worker's meshCoordinatorDaemonId)\n * - standalone — `standalone_mach_<hex>` (a standalone daemon's status instanceId)\n *\n * A worker's completion event is scoped (`coordinator_daemon_id`) with whichever\n * form the dispatch path happened to stamp, but the coordinator that later drains /\n * surfaces that event resolves its OWN id through a different path and frequently\n * holds a DIFFERENT form. Because the scope filter is an exact-string match\n * (`coordinator_daemon_id IS NULL OR IN (...)` in SQL, `.includes()` in JS), a\n * completion stamped `daemon_mach_X` is silently skipped by a coordinator whose\n * self-id set only contains bare `mach_X` (or standalone form) — the event never\n * surfaces and the coordinator is never auto-notified, while NULL-scoped events\n * (e.g. worktree bootstrap) always pass via the `IS NULL` branch.\n *\n * This module is the single source of truth that collapses the three forms to one\n * machine core and EXPANDS a self-id set to every equivalent form, so a scope match\n * succeeds regardless of which form stamped the event. Expansion stays WITHIN a\n * single machine core (`daemon_mach_X` only ever expands to other `mach_X` forms),\n * so an event scoped to a DIFFERENT coordinator is never falsely claimed.\n */\n\nimport { readString } from './json'\n\nconst DAEMON_ID_PREFIXES = ['daemon_', 'standalone_'] as const\n\n/**\n * Reduce any daemon-id form to its machine core: strips a leading `daemon_` /\n * `standalone_` prefix, leaving the bare `mach_<hex>` (or returning a non-prefixed\n * id unchanged). Returns undefined for an empty/absent id.\n */\nexport function machineCoreFromDaemonId(id: string | null | undefined): string | undefined {\n const trimmed = readString(id)\n if (!trimmed) return undefined\n for (const prefix of DAEMON_ID_PREFIXES) {\n if (trimmed.startsWith(prefix)) {\n const core = trimmed.slice(prefix.length).trim()\n return core || undefined\n }\n }\n return trimmed\n}\n\n/**\n * Canonicalize any daemon-id form to the single CANON producer form\n * `daemon_mach_<core>` (the cloud `daemon_` form).\n *\n * CANON-IDENTITY double-dispatch root cause: the coordinator daemon id is stamped\n * onto a worker dispatch by TWO independent producers — the MCP-side\n * resolveCoordinatorDaemonId (which prefers the coordinator mesh node's config-form\n * `daemon_mach_X` daemonId) and the daemon-core queue dispatch (which stamps the\n * bare `loadConfig().machineId` = `mach_X`). When the SAME coordinator dispatches\n * the same task down both paths, the two worker sessions are stamped with two\n * DIFFERENT coordinator-id forms; a raw-string dedup that should recognise \"this\n * task is already dispatched by me\" fails, and the task runs twice.\n *\n * The durable fix is comparator-side (daemonIdsEquivalent / expandDaemonIdForms),\n * but unifying every PRODUCER on one canonical form shrinks the surface so even a\n * raw `===` agrees. The canon is the cloud `daemon_` form because that is what the\n * coordinator mesh node's config-form daemonId already carries and what the cloud\n * P2P signaling layer registers a daemon under — so canonicalizing the bare/standalone\n * fallback forms makes them consistent with the already-working primary path.\n *\n * Only a `mach_<…>` core is rewritten; an arbitrary/non-machine id (e.g. a custom\n * node id) is returned unchanged so it is never ballooned into a spurious `daemon_`\n * form. Idempotent. Returns undefined for an empty/absent id.\n */\nexport function canonicalDaemonId(id: string | null | undefined): string | undefined {\n const core = machineCoreFromDaemonId(id)\n if (!core) return undefined\n if (!core.startsWith('mach_')) return core\n return `daemon_${core}`\n}\n\n/** True when both ids resolve to the same machine core — i.e. they are the same\n * daemon under different id forms. False when either side is empty. */\nexport function daemonIdsEquivalent(a: string | null | undefined, b: string | null | undefined): boolean {\n const coreA = machineCoreFromDaemonId(a)\n const coreB = machineCoreFromDaemonId(b)\n if (!coreA || !coreB) return false\n return coreA === coreB\n}\n\n/**\n * Expand a set of coordinator/daemon ids to every equivalent form, so an\n * exact-string scope filter (SQL `IN (...)` or JS `.includes()`) matches a\n * completion stamped in any form of the same machine. The original ids are kept in\n * their input order and FIRST (callers that treat `[0]` as the primary — e.g.\n * per-daemon JSONL file naming — keep their original primary); the derived\n * `mach_<hex>` / `daemon_mach_<hex>` / `standalone_mach_<hex>` forms are appended.\n *\n * Derived prefixed forms are emitted ONLY for a core that looks like a real machine\n * id (`mach_<…>`), so arbitrary/test ids (e.g. `node-daemon-id`) are passed through\n * untouched and never balloon into spurious forms. Result is de-duplicated.\n */\nexport function expandDaemonIdForms(\n ids: string | null | undefined | ReadonlyArray<string | null | undefined>,\n): string[] {\n const list = Array.isArray(ids) ? ids : ids != null ? [ids] : []\n const out: string[] = []\n const seen = new Set<string>()\n const add = (value: string | undefined): void => {\n if (!value || seen.has(value)) return\n seen.add(value)\n out.push(value)\n }\n // Pass 1: originals first, in input order (preserve caller's primary at [0]).\n for (const raw of list) add(readString(raw))\n // Pass 2: derived machine-core forms for any id that resolves to a `mach_` core.\n for (const raw of list) {\n const core = machineCoreFromDaemonId(readString(raw))\n if (!core || !core.startsWith('mach_')) continue\n add(core)\n for (const prefix of DAEMON_ID_PREFIXES) add(`${prefix}${core}`)\n }\n return out\n}\n","/**\n * Canonical compact git-shape summarizer used by debug/log surfaces on both the\n * cloud (daemon-cloud mesh command summarizer) and standalone (daemon-core router\n * RepoMeshStatusDebug) paths. Produces a small, log-safe projection of a git\n * status record — commit SHAs are truncated to 12 chars.\n *\n * Transport-specific envelope unwrapping (result / result.status / top-level)\n * stays in the caller; this takes an already-unwrapped status record.\n */\n\nimport { readBoolean, readNumber, readRecord, readString } from './json'\n\nexport function summarizeGitShape(status: unknown): Record<string, unknown> | null {\n const record = readRecord(status)\n if (!Object.keys(record).length) return null\n const submodules = Array.isArray(record.submodules)\n ? record.submodules.map((entry: unknown) => {\n const sub = readRecord(entry)\n return {\n path: readString(sub.path) ?? null,\n commit: readString(sub.commit)?.slice(0, 12) ?? null,\n dirty: readBoolean(sub.dirty) ?? false,\n outOfSync: readBoolean(sub.outOfSync, sub.out_of_sync) ?? false,\n }\n })\n : []\n return {\n isGitRepo: readBoolean(record.isGitRepo),\n workspace: readString(record.workspace) ?? null,\n repoRoot: readString(record.repoRoot, record.repo_root) ?? null,\n branch: readString(record.branch) ?? null,\n upstream: readString(record.upstream) ?? null,\n upstreamStatus: readString(record.upstreamStatus, record.upstream_status) ?? null,\n headCommit: readString(record.headCommit, record.head_commit)?.slice(0, 12) ?? null,\n ahead: readNumber(record.ahead) ?? null,\n behind: readNumber(record.behind) ?? null,\n dirtyCounts: {\n staged: readNumber(record.staged) ?? 0,\n modified: readNumber(record.modified) ?? 0,\n untracked: readNumber(record.untracked) ?? 0,\n deleted: readNumber(record.deleted) ?? 0,\n renamed: readNumber(record.renamed) ?? 0,\n },\n lastCheckedAt: readNumber(record.lastCheckedAt, record.last_checked_at) ?? null,\n submoduleCount: submodules.length,\n submodules,\n }\n}\n","/**\n * MAGI — Multi-Agent Ground-truth Insight.\n *\n * Pure shared types for the mesh cross-verification quorum: the per-task_kind\n * panel binding (machine-local config, stored in ~/.adhdev/meshes.json\n * `magiKindPanels`), the agent-agnostic common output schema every dispatched\n * replica answers with, and the synthesis result shapes. These cross the\n * daemon-core (storage / accessors) ↔ mcp-server (fan-out / synthesis) boundary,\n * so they live in the dependency-free mesh-shared leaf — no runtime, no Node/DOM APIs.\n *\n * Design: docs/design/2026-06-28-mesh-magi-review.md. Core stance: no personas,\n * no named lenses — a panel slot is just one `(node × provider)` target that\n * answers the SAME question. The value is the friction (contested / singleton /\n * source-coupled findings), NOT a majority vote.\n *\n * NOTE: the former named-panel model (MagiPanel / MagiPanelMember / MagiPanelMap\n * and inline `members`) was REMOVED. A MAGI review resolves its fan-out slots\n * EXCLUSIVELY from the `magiKindPanels` binding for the review's `task_kind`; an\n * unconfigured kind is a hard error, never a synthesized or named-panel fallback.\n */\n\n// ─── Kind → panel binding (machine-local config) ─────────\n//\n// MAGI-KIND-PANEL: an explicit, per-task_kind panel binding. `mesh_magi_review`\n// invoked with a bare `task_kind` (no panel name / inline members) resolves the\n// panel from THIS map — the user must have configured ≥1 slot for that kind in mesh\n// settings. There is NO hardcoded preset auto-synthesis fallback: an unconfigured\n// kind is a hard error (magi_kind_not_configured), never a silent synthetic panel.\n\n/**\n * One kind-panel slot: a `(node × provider [× model])` target. `provider` required;\n * `nodeId` pins a concrete mesh node; `model` optionally selects the agent model at\n * launch; `capabilityTags` route by tag when no nodeId is given; `n` is an optional\n * per-slot replica count. This is the SOLE panel-member shape — the fan-out planner\n * (buildMagiFanoutPlan) resolves a `MagiSlot[]` directly.\n */\nexport interface MagiSlot {\n /** Optional — pin to a specific mesh node id. Absent → route by capabilityTags + provider. */\n nodeId?: string\n /** REQUIRED — provider type, e.g. 'claude-cli' | 'codex-cli' | 'gemini-cli'. */\n provider: string\n /**\n * Optional model override applied at replica launch (e.g. 'opus' | 'sonnet' for\n * claude-cli). Threaded through enqueueTask → the auto-launched session's\n * `launch_cli` payload as `initialModel`. For ACP providers it drives\n * setConfigOption('model', …); for CLI providers it is expanded via the provider\n * manifest's `modelLaunchArgs` template into launch args (a provider with no\n * template silently ignores it — model is best-effort, never fatal).\n */\n model?: string\n /** Optional routing tags, ANDed with the provider tag when nodeId is absent. */\n capabilityTags?: string[]\n /** Optional per-slot replica count; defaults to the kind-panel defaultN / global n / 1. */\n n?: number\n}\n\n/**\n * Per-task_kind panel binding, stored machine-local in `~/.adhdev/meshes.json`\n * under the top-level `magiKindPanels` map. A kind absent from the map has NO\n * configured panel → `mesh_magi_review({task_kind})` errors with\n * `magi_kind_not_configured` rather than synthesizing one. `freeform` MAY be bound\n * like any other kind (a direct kind→slots binding).\n */\nexport type MagiKindPanelMap = Partial<Record<MagiTaskKind, MagiSlot[]>>\n\n/**\n * The output-schema selector a MAGI fan-out injects into every replica prompt and\n * the strict parser used at collection. Code-orthogonal to the panel's slot set\n * (the fan-out planner never reads it) — it ONLY shapes the per-replica prompt /\n * parse contract. SSOT lives here (mesh-shared leaf) so both daemon-core (slot\n * normalization) and mcp-server (resolution / prompt assembly) consume one union.\n *\n * - claim_audit (default, backward-compatible), rca, design → require evidence[].\n * - freeform → no schema, no evidence; contributes NO structured claims to\n * synthesis. It MAY still be bound as a kind-panel key (a direct kind→slots\n * binding), unlike the removed named-panel `defaultKind`.\n */\nexport type MagiTaskKind = 'claim_audit' | 'rca' | 'design' | 'freeform'\n\n/**\n * Synthesis emphasis hint. Affects weighting / labels only — NEVER the agent\n * count or the common schema. (Per-mode weighting tuning is a deferred refinement;\n * the field is accepted now so callers and panels are forward-stable.)\n */\nexport type MagiMode = 'rca' | 'investigation' | 'claim_audit' | 'design_review' | 'code_audit'\n\n// ─── Common output schema (agent-agnostic) ──────\n\nexport type MagiClaimStance = 'support' | 'oppose' | 'uncertain'\n\n/**\n * One claim from one agent. `evidence` carries `file:line` or external-source\n * strings; `confidence` is 0..1. Identical regardless of which provider/machine\n * produced it — this is the forced structured-output contract injected into each\n * dispatched task prompt.\n */\nexport interface MagiClaim {\n claim: string\n stance: MagiClaimStance\n evidence: string[]\n confidence: number\n}\n\n/** The agent-agnostic response every dispatched replica returns. */\nexport interface MagiAgentResponse {\n claims: MagiClaim[]\n top_findings: string[]\n open_questions: string[]\n}\n\n// ─── Synthesis result shapes ────────────────────\n\n/**\n * Where one response came from — the `(node × provider)` identity that backs a\n * claim's independence. `ok=false` marks a replica that died / produced no\n * parseable common-schema output (excluded from clusters, counted as missing).\n */\nexport interface MagiResponseSource {\n /** Mesh task id of the dispatched replica. */\n taskId: string\n nodeId?: string\n provider?: string\n /** False when the replica failed or its output could not be parsed. */\n ok: boolean\n /** Reason when ok=false (timeout / failed / unparseable / stale). */\n error?: string\n /**\n * True when the replica was detected STALE during collection — assigned to a\n * node/session no longer present in the live mesh (so it will never reach a\n * terminal state). Distinguishes a dead-assignment replica from one that is\n * merely still generating. Always implies ok=false.\n */\n stale?: boolean\n /**\n * Git ref of the node this replica ran on, captured at collection time from the\n * live mesh node's compact git summary. Lets synthesis (and a dashboard) detect\n * GIT SKEW across the panel — if the answering replicas span different branches\n * or diverge (ahead/behind), their file:line evidence is comparing different code\n * and \"agreement\" is less meaningful. Best-effort; absent when the node carried\n * no git summary.\n */\n git?: MagiReplicaGitRef\n /**\n * The replica's raw end-user answer text as read from its session transcript at\n * collection time, truncated to MAGI_RAW_ANSWER_CAP chars (with `rawAnswerTruncated`\n * set when it was longer). This is the human-readable original a replica produced —\n * useful when the structured claim parse dropped nuance, or for a cluster member that\n * needs the source prose. GATED: stripped from the persisted `magi_synthesis` ledger\n * entry (to bound ledger payload growth) and from the default mesh_magi_collect\n * response; surfaced ONLY in mesh_magi_collect verbose. Best-effort; absent for a\n * replica that produced no readable transcript (failed / stale / unparseable).\n */\n rawAnswer?: string\n /** True when `rawAnswer` was truncated at MAGI_RAW_ANSWER_CAP. */\n rawAnswerTruncated?: boolean\n}\n\n/** Max chars of a replica's raw answer retained on MagiResponseSource.rawAnswer. */\nexport const MAGI_RAW_ANSWER_CAP = 4000\n\n/** Compact git ref of the node a replica ran on (subset of GitRepoStatus). */\nexport interface MagiReplicaGitRef {\n branch?: string | null\n /** HEAD commit sha of the node's workspace — the exact code the replica saw. */\n headCommit?: string | null\n ahead?: number\n behind?: number\n dirty?: boolean\n}\n\n/**\n * Cross-replica git divergence assessment. `skewed` is true when the answering\n * replicas span more than one branch OR any replica diverges from its upstream\n * (ahead/behind > 0) — both mean the panel is not all looking at the same code, so\n * file:line evidence and agreement are git-skewed. Always present on a synthesis\n * (skewed=false / distinctBranches≤1 when there is nothing to flag).\n */\nexport interface MagiGitSkew {\n skewed: boolean\n /** Number of distinct branches across the answering replicas with a known branch. */\n distinctBranches: number\n /** The distinct branch names (sorted), for display. */\n branches: string[]\n /** Replicas whose branch/divergence differs from the panel baseline. */\n divergentReplicas: number\n note?: string\n}\n\n/** A parsed replica response paired with its source identity. */\nexport interface MagiSynthesizedResponse {\n source: MagiResponseSource\n response: MagiAgentResponse\n}\n\n/**\n * Synthesis category for a claim cluster. `needs_verification` is the PRIMARY\n * OUTPUT = contested ∪ singleton ∪ source_coupled ∪ (high-impact claims lacking\n * independent evidence). `agreed` is the only \"safe to trust, low priority\" bucket.\n */\nexport type MagiClusterCategory =\n | 'agreed'\n | 'contested'\n | 'dissent'\n | 'singleton'\n | 'source_coupled'\n\n/** One member observation inside a claim cluster. */\nexport interface MagiClusterMember {\n taskId: string\n nodeId?: string\n provider?: string\n claim: string\n stance: MagiClaimStance\n evidence: string[]\n confidence: number\n}\n\n/**\n * A cluster of semantically-equivalent claims across responses, with its\n * stance tally and diversity-weighted independence assessment.\n */\nexport interface MagiClaimCluster {\n /** Representative (first / longest) claim text for the cluster. */\n claim: string\n category: MagiClusterCategory\n members: MagiClusterMember[]\n stance: { support: number; oppose: number; uncertain: number }\n /** Distinct providers / nodes / evidence sources backing the cluster. */\n distinctProviders: number\n distinctNodes: number\n distinctEvidence: number\n /** Diversity-weighted independence score (NOT the raw agent count). */\n independenceScore: number\n /** True when this cluster is routed to needs_verification. */\n needsVerification: boolean\n /** Why it needs verification (contested / singleton / source_coupled / no_independent_evidence). */\n reasons: string[]\n}\n\n/** The full synthesis result — N-agnostic, diversity-weighted, not a vote. */\nexport interface MagiSynthesis {\n /** How many replicas were expected vs. produced parseable output. */\n replicasExpected: number\n replicasAnswered: number\n replicasMissing: number\n /** Distinct providers / nodes across the answering replicas. */\n distinctProviders: number\n distinctNodes: number\n /**\n * Set when the resolved panel collapsed to a single provider or single\n * machine — agreements are then flagged source-coupled. Null when independence\n * was achieved.\n */\n independenceBanner: string | null\n clusters: MagiClaimCluster[]\n /** PRIMARY OUTPUT — clusters routed to needs_verification, highest priority first. */\n needsVerification: MagiClaimCluster[]\n /** High-independence agreements — safe to trust, lowest review priority. */\n agreed: MagiClaimCluster[]\n /** Union of every response's open_questions (deduped). */\n openQuestions: string[]\n /**\n * Per-replica source identity (taskId / nodeId / provider / ok / stale / git) for\n * every replica in the fan-out. Lets a consumer (the dashboard's extractMagiActivity)\n * read which node × provider answered and the git ref each ran at — the inputs behind\n * the gitSkew assessment.\n */\n replicas: MagiResponseSource[]\n /**\n * Cross-replica git divergence. When skewed, the answering replicas were not all\n * on the same code (different branches / ahead-behind), so evidence and agreement\n * should be read with that caveat. Always present.\n */\n gitSkew: MagiGitSkew\n}\n","/**\n * Brain-routing (task difficulty → provider/model/thinking) types.\n *\n * The coordinator classifies each task it enqueues by execution difficulty, and a\n * per-difficulty \"brain\" preset resolves that into a concrete provider / model /\n * thinking-level for the launched session. The goal is token economy: an `easy`\n * task runs on a cheaper model at low reasoning effort; a `difficult` task gets a\n * stronger model at high effort. This is a separate axis from MAGI's review kinds\n * (rca/design/…) — MAGI fans out review replicas; this picks the single brain that\n * *executes* a task — but it reuses the same slot shape (provider/model) and the\n * same machine-local storage (`~/.adhdev/meshes.json`).\n */\n\n/** The fixed difficulty axis the coordinator classifies a task into. */\nexport type MeshTaskDifficulty = 'easy' | 'medium' | 'difficult' | 'freeform'\n\nexport const MESH_TASK_DIFFICULTIES: MeshTaskDifficulty[] = ['easy', 'medium', 'difficult', 'freeform']\n\n/**\n * A per-difficulty brain preset: which provider / model / thinking level a task of\n * that difficulty should run on. Every field is optional — a preset may set only a\n * model (keep the routed provider) or only a thinking level. Applied at enqueue:\n * an explicit model/thinkingLevel on the task always wins over the preset.\n */\nexport interface BrainSlot {\n /** Optional provider type, e.g. 'claude-cli' | 'codex-cli'. Absent → keep the tag/priority-routed provider. */\n provider?: string\n /** Optional model, e.g. 'opus' | 'sonnet' | 'haiku'. Best-effort at launch (initialModel). */\n model?: string\n /** Optional standard thinking level, 'low' | 'medium' | 'high'. Best-effort (initialThinkingLevel). */\n thinkingLevel?: 'low' | 'medium' | 'high'\n}\n\n/**\n * Per-difficulty brain bindings, stored machine-local in `~/.adhdev/meshes.json`\n * under the top-level `difficultyBrains` map (sibling of `magiKindPanels`). A\n * difficulty absent from the map has no preset — the task runs with no\n * difficulty-derived model/thinking (ordinary routing).\n */\nexport type DifficultyBrainMap = Partial<Record<MeshTaskDifficulty, BrainSlot>>\n\n/** True for a recognized difficulty value. */\nexport function isMeshTaskDifficulty(value: unknown): value is MeshTaskDifficulty {\n return typeof value === 'string' && (MESH_TASK_DIFFICULTIES as string[]).includes(value)\n}\n\n/**\n * Sensible default presets, seeded when a mesh has no `difficultyBrains` configured\n * yet. Model names are provider-agnostic strings (opus/sonnet/haiku); a provider\n * that cannot honor a given model or thinking level ignores it (best-effort). The\n * operator can edit these. `freeform` has no preset by default (untouched routing).\n */\nexport const DEFAULT_DIFFICULTY_BRAINS: DifficultyBrainMap = {\n easy: { model: 'haiku', thinkingLevel: 'low' },\n medium: { model: 'sonnet', thinkingLevel: 'medium' },\n difficult: { model: 'opus', thinkingLevel: 'high' },\n}\n\n/** Normalize a raw thinking level to the standard union, or undefined. */\nexport function normalizeThinkingLevel(value: unknown): 'low' | 'medium' | 'high' | undefined {\n const v = typeof value === 'string' ? value.trim().toLowerCase() : ''\n return v === 'low' || v === 'medium' || v === 'high' ? v : undefined\n}\n\n/** Normalize a raw BrainSlot (trim strings, drop empties, clamp thinkingLevel). */\nexport function normalizeBrainSlot(raw: unknown): BrainSlot {\n const r = (raw && typeof raw === 'object') ? raw as Record<string, unknown> : {}\n const provider = typeof r.provider === 'string' ? r.provider.trim() : ''\n const model = typeof r.model === 'string' ? r.model.trim() : ''\n const thinkingLevel = normalizeThinkingLevel(r.thinkingLevel)\n return {\n ...(provider ? { provider } : {}),\n ...(model ? { model } : {}),\n ...(thinkingLevel ? { thinkingLevel } : {}),\n }\n}\n\n/** Normalize a raw DifficultyBrainMap, dropping unknown keys and empty slots. */\nexport function normalizeDifficultyBrainMap(raw: unknown): DifficultyBrainMap {\n const out: DifficultyBrainMap = {}\n if (!raw || typeof raw !== 'object') return out\n for (const key of MESH_TASK_DIFFICULTIES) {\n const slot = normalizeBrainSlot((raw as Record<string, unknown>)[key])\n if (slot.provider || slot.model || slot.thinkingLevel) out[key] = slot\n }\n return out\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Node capability slots (ORCHESTRATION_NODE_SLOTS.md)\n//\n// A node's \"Preferred AI tools\" list is redefined as an ordered array of\n// capability slots. Each slot bundles what used to be scattered across\n// providerPriority (order), a per-provider maxParallel cap, and the\n// machine-global difficultyBrains (difficulty → model/thinking). Slot order =\n// preference. This single profile is the source of truth for task routing, MAGI\n// fan-out, and orchestrator-proposed edits.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * One capability slot on a mesh node. Extends the BrainSlot shape\n * (provider/model/thinkingLevel) with the difficulty range it handles, capability\n * tags, and a per-slot parallelism cap.\n */\nexport interface NodeCapabilitySlot {\n /** Provider type this slot uses, e.g. 'claude-cli' | 'codex-cli'. Required (a slot is defined by its provider). */\n provider: string\n /** Optional model, e.g. 'opus' | 'sonnet' | 'haiku'. Best-effort at launch. */\n model?: string\n /**\n * Optional thinking level. The provider's own vocabulary (e.g. low/medium/high,\n * or codex's low/medium/high/max) passed through verbatim — best-effort at\n * launch. A string, not the standard union, so provider-declared levels like\n * 'max' are not dropped.\n */\n thinkingLevel?: string\n /**\n * Difficulty range this slot handles. Empty/absent = handles all difficulties\n * (a general-purpose slot). A task's difficulty is matched against this range;\n * no exact match falls back to the nearest/general slot (never blocks).\n */\n difficulty?: MeshTaskDifficulty[]\n /** Capability tags this slot satisfies (matched against a task's requiredTags). */\n capability?: string[]\n /** Per-node·per-slot max concurrent tasks. Omit = no per-slot cap. */\n maxParallel?: number\n}\n\n/** Normalize a raw NodeCapabilitySlot; returns null when it has no usable provider. */\nexport function normalizeNodeCapabilitySlot(raw: unknown): NodeCapabilitySlot | null {\n const r = (raw && typeof raw === 'object') ? raw as Record<string, unknown> : {}\n const provider = typeof r.provider === 'string' ? r.provider.trim() : ''\n if (!provider) return null\n const model = typeof r.model === 'string' ? r.model.trim() : ''\n // Pass the provider's own thinking-level vocabulary through verbatim (don't\n // clamp to low/medium/high — a provider may declare 'max' etc.).\n const thinkingLevel = typeof r.thinkingLevel === 'string' ? r.thinkingLevel.trim() : ''\n const difficulty = Array.isArray(r.difficulty)\n ? (r.difficulty.filter(isMeshTaskDifficulty) as MeshTaskDifficulty[])\n : []\n const capability = Array.isArray(r.capability)\n ? r.capability.filter((t): t is string => typeof t === 'string' && !!t.trim()).map(t => t.trim())\n : []\n const maxParallelNum = Number(r.maxParallel)\n const maxParallel = Number.isFinite(maxParallelNum) && maxParallelNum > 0 ? Math.floor(maxParallelNum) : undefined\n return {\n provider,\n ...(model ? { model } : {}),\n ...(thinkingLevel ? { thinkingLevel } : {}),\n ...(difficulty.length ? { difficulty } : {}),\n ...(capability.length ? { capability } : {}),\n ...(maxParallel !== undefined ? { maxParallel } : {}),\n }\n}\n\n/** Normalize a raw slot array, dropping provider-less entries. */\nexport function normalizeNodeCapabilitySlots(raw: unknown): NodeCapabilitySlot[] {\n if (!Array.isArray(raw)) return []\n const out: NodeCapabilitySlot[] = []\n for (const entry of raw) {\n const slot = normalizeNodeCapabilitySlot(entry)\n if (slot) out.push(slot)\n }\n return out\n}\n\n/**\n * Back-compat migration: derive capability slots from the legacy fields when a\n * node has no explicit `slots`. Order follows providerPriority; difficulty/model/\n * thinking are folded in from the machine-global difficultyBrains (each difficulty\n * attaches to the slot whose provider the brain preset names, or — when the brain\n * has no provider — to every slot as a shared model/thinking default for that\n * difficulty).\n *\n * (Legacy nodes' per-provider `maxParallel` cap has been migrated onto\n * `slots[].maxParallel` at config-load time, so it is no longer folded in here.)\n *\n * Returns [] when there's nothing to derive (caller then keeps legacy behavior:\n * first available provider).\n */\nexport function deriveSlotsFromLegacy(input: {\n providerPriority?: string[]\n difficultyBrains?: DifficultyBrainMap\n}): NodeCapabilitySlot[] {\n const priority = Array.isArray(input.providerPriority)\n ? input.providerPriority.filter((p): p is string => typeof p === 'string' && !!p.trim()).map(p => p.trim())\n : []\n if (priority.length === 0) return []\n\n // Brain presets keyed by the provider they name (provider-specific), plus a\n // provider-agnostic list applied to every slot as a shared default.\n const brains = input.difficultyBrains || {}\n const byProvider = new Map<string, Array<{ difficulty: MeshTaskDifficulty; model?: string; thinkingLevel?: 'low' | 'medium' | 'high' }>>()\n const shared: Array<{ difficulty: MeshTaskDifficulty; model?: string; thinkingLevel?: 'low' | 'medium' | 'high' }> = []\n for (const diff of MESH_TASK_DIFFICULTIES) {\n const b = brains[diff]\n if (!b) continue\n const entry = { difficulty: diff, model: b.model, thinkingLevel: b.thinkingLevel }\n if (b.provider) {\n const list = byProvider.get(b.provider) ?? []\n list.push(entry)\n byProvider.set(b.provider, list)\n } else {\n shared.push(entry)\n }\n }\n\n return priority.map((provider): NodeCapabilitySlot => {\n // Provider-specific brain first, else the shared default, else nothing.\n const specific = byProvider.get(provider) || []\n const applied = specific.length ? specific : shared\n const difficulty = applied.map(a => a.difficulty)\n // Fold model/thinking from the applied presets: take the first that sets each.\n const model = applied.find(a => a.model)?.model\n const thinkingLevel = applied.find(a => a.thinkingLevel)?.thinkingLevel\n return {\n provider,\n ...(model ? { model } : {}),\n ...(thinkingLevel ? { thinkingLevel } : {}),\n ...(difficulty.length ? { difficulty } : {}),\n }\n })\n}\n","/**\n * Pure {{key}} template interpolation shared by the mesh command paths.\n *\n * Hoisted from packages/daemon-cloud/src/mesh/mesh-interpolation.ts — the\n * substitution is transport-agnostic (plain string/object work), so it belongs\n * in the dependency-free mesh-shared leaf where standalone can reuse it too.\n * The substitution semantics are byte-for-byte identical to the prior cloud copy.\n */\nexport function interpolateArgs(\n args: Record<string, unknown>,\n context: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(args)) {\n result[k] = typeof v === 'string' ? interpolateString(v, context) : v;\n }\n return result;\n}\n\nexport function interpolateString(template: string, ctx: Record<string, unknown>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key) => {\n const val = ctx[key];\n return val !== undefined ? String(val) : `{{${key}}}`;\n });\n}\n","/**\n * Canonical Repo Mesh coordinator tool-name registry — the single source of truth\n * the three surfaces must agree on:\n *\n * 1. mcp-server `ALL_MESH_TOOLS` (the published MCP tool schemas),\n * 2. daemon-core `coordinator-prompt.ts` `TOOLS_SECTION` (what the coordinator LLM\n * is told it can call), and\n * 3. the `NN tools` doc comments in the mesh-tools barrels.\n *\n * mcp-server does not depend on daemon-core's internal prompt, and daemon-core cannot\n * import mcp-server (dependency direction: daemon-core ← mcp-server). This dependency-\n * free leaf is the only place both can reference, so the 6-6 consistency test\n * (daemon-core coordinator-prompt.test.ts) and mcp-server both assert against THIS\n * list. Adding a new mesh tool means adding its name here first; the tests then force\n * the schema + prompt + barrel comment to catch up, which is exactly the regression\n * gate that let coordinator-prompt drift 14 tools behind the schema before.\n *\n * Order mirrors mcp-server `ALL_MESH_TOOLS` for easy visual diffing, but the consistency\n * checks are set-based (order-insensitive).\n */\nexport const CANONICAL_MESH_TOOL_NAMES = [\n 'mesh_status',\n 'mesh_list_nodes',\n 'mesh_enqueue_task',\n 'mesh_view_queue',\n 'mesh_queue_cancel',\n 'mesh_queue_requeue',\n 'mesh_send_task',\n 'mesh_read_chat',\n 'mesh_read_debug',\n 'mesh_read_terminal',\n 'mesh_send_keys',\n 'mesh_launch_session',\n 'mesh_git_status',\n 'mesh_read_node_logs',\n 'mesh_fast_forward_node',\n 'mesh_restart_daemon',\n 'mesh_checkpoint',\n 'mesh_approve',\n 'mesh_list_pending_approvals',\n 'mesh_clone_node',\n 'mesh_remove_node',\n 'mesh_refine_node',\n 'mesh_refine_batch',\n 'mesh_refine_config',\n 'mesh_change_impact_config',\n 'mesh_init',\n 'mesh_reinit',\n 'mesh_write_mesh_json_config',\n 'mesh_refine_plan',\n 'mesh_cleanup_sessions',\n 'mesh_prune_stale_direct',\n 'mesh_task_history',\n 'mesh_ledger_query',\n 'mesh_record_note',\n 'mesh_forget_note',\n 'mesh_reconcile_ledger',\n 'mesh_requeue_held_events',\n 'mesh_mission_upsert',\n 'mesh_mission_list',\n 'mesh_review_inbox',\n 'mesh_magi_review',\n 'mesh_magi_collect',\n 'mesh_magi_kind_panel_set',\n 'mesh_magi_kind_panel_list',\n 'mesh_node_slots_set',\n 'mesh_node_slots_list',\n] as const;\n\nexport type CanonicalMeshToolName = typeof CANONICAL_MESH_TOOL_NAMES[number];\n\n/** The count the `NN tools` barrel doc comments and consistency test assert against. */\nexport const CANONICAL_MESH_TOOL_COUNT = CANONICAL_MESH_TOOL_NAMES.length;\n","/**\n * OFFLINE-NODE-STATUS-REFRESH — the status-origin probe marker.\n *\n * A remote `git_status` (or any relayed/dispatched mesh command) that originates from\n * an explicit_refresh / mesh_status aggregate carries this marker inside its ARGS. The\n * daemon-cloud dispatch wrapper and MCP relay handler read it to grant the SHORT\n * connect-wait budget so a single offline (powered-off) peer no longer blocks the whole\n * status assembly for ~90s.\n *\n * It is deliberately an args marker rather than adding `git_status` to the global\n * probe-class command set: a user-driven / targeted `git_status` (no marker) must keep\n * waiting out the full connect deadline for a slow relay to open (rc.503 intent). Only a\n * status-origin probe opts into the short budget.\n *\n * The key is `_`-prefixed so it travels alongside the real args (workspace,\n * refreshUpstream, includeSubmodules, …) and is ignored by the git_status handler; the\n * dispatch/relay sites strip it defensively before the command executes so it never\n * reaches a handler that echoes unknown args.\n *\n * This dependency-free leaf is the single source of truth shared by daemon-core (the\n * aggregate probe producer), mcp-server (the MCP relay producer), and daemon-cloud (the\n * dispatch/relay consumer) so the key cannot drift between producer and consumer.\n */\nexport const STATUS_PROBE_ARG_KEY = '_statusProbe' as const;\n\n/** Stamp the status-origin probe marker onto a command's args (non-mutating). */\nexport function withStatusProbeMarker(\n args: Record<string, unknown> = {},\n): Record<string, unknown> {\n return { ...args, [STATUS_PROBE_ARG_KEY]: true };\n}\n\n/** True when the args carry the status-origin probe marker. */\nexport function argsCarryStatusProbeMarker(args: unknown): boolean {\n return (\n !!args &&\n typeof args === 'object' &&\n (args as Record<string, unknown>)[STATUS_PROBE_ARG_KEY] === true\n );\n}\n\n/**\n * Return a shallow copy of args with the internal marker removed so it never leaks to\n * the executing command handler. Returns the original reference when no marker is\n * present (avoids an allocation on the common path).\n */\nexport function stripStatusProbeMarker(\n args: Record<string, unknown>,\n): Record<string, unknown> {\n if (!argsCarryStatusProbeMarker(args)) return args;\n const { [STATUS_PROBE_ARG_KEY]: _drop, ...rest } = args;\n return rest;\n}\n","/**\n * Mesh Tools — Mesh-scoped coordinator tools for Repo Mesh orchestration\n *\n * These tools wrap existing MCP transport operations but restrict targets\n * to mesh member nodes only. The coordinator uses these to delegate work\n * to agents across the mesh via natural conversation.\n *\n * 44 tools (== ALL_MESH_TOOLS, kept in sync with the coordinator-prompt TOOLS table\n * by the 6-6 consistency test in daemon-core coordinator-prompt.test.ts):\n * mesh_status, mesh_list_nodes, mesh_enqueue_task, mesh_view_queue,\n * mesh_queue_cancel, mesh_queue_requeue, mesh_send_task, mesh_read_chat,\n * mesh_read_debug, mesh_read_terminal, mesh_send_keys, mesh_launch_session, mesh_git_status, mesh_read_node_logs,\n * mesh_fast_forward_node, mesh_restart_daemon, mesh_checkpoint, mesh_approve,\n * mesh_list_pending_approvals,\n * mesh_clone_node, mesh_remove_node, mesh_refine_node, mesh_refine_batch,\n * mesh_refine_config, mesh_change_impact_config, mesh_init, mesh_reinit,\n * mesh_write_mesh_json_config, mesh_refine_plan, mesh_cleanup_sessions,\n * mesh_prune_stale_direct, mesh_task_history, mesh_ledger_query,\n * mesh_record_note, mesh_forget_note, mesh_reconcile_ledger,\n * mesh_requeue_held_events,\n * mesh_mission_upsert, mesh_mission_list, mesh_review_inbox, mesh_magi_review,\n * mesh_magi_collect,\n * mesh_magi_kind_panel_set, mesh_magi_kind_panel_list\n */\n\n// ─── Internal module ───────────────────────────\n// Shared helpers, types, module-level state, and dependency re-exports for the mesh tool\n// domain files (mesh-tools-{status,queue,mission,session,git,refine}.ts). Split out of\n// mesh-tools.ts as a pure move — no behavior change. mesh-tools.ts is now a re-export barrel.\n\nimport { randomUUID } from 'node:crypto';\nimport { IpcTransport } from '../transports/ipc.js';\nimport type { CommandTransport } from '../transports/mode.js';\nimport { compactChatPayload, isCoordinatorVisibleMessage, messageContent } from './chat-compact.js';\nimport { annotateRapidReadChatAdvisory } from './read-chat-polling-advisory.js';\nimport { withStatusProbeMarker, normalizeNodeCapabilitySlots } from '@adhdev/mesh-shared';\nimport type { LocalMeshEntry, LocalMeshNodeEntry, MeshActiveWorkSummary, RepoMeshPolicy, RepoMeshRelatedRepo } from '@adhdev/daemon-core';\nimport {\n daemonIdsEquivalent,\n meshNodeIdMatches,\n appendLedgerEntry,\n appendRemoteLedgerEntries,\n buildCompactStaleDirectWorkSummary,\n buildMeshActiveWork,\n collectPendingApprovals,\n buildMeshAsyncRefineJobs,\n summarizeMeshAsyncRefineJobs,\n buildMeshMagiActivity,\n summarizeMeshMagiActivity,\n getMeshMagiActivityByGroup,\n MAGI_RAW_ANSWER_CAP,\n buildMeshLedgerReconciliationEvidence,\n buildMeshLedgerReplicaEvidence,\n buildMeshNodeCapabilityTags,\n buildMeshNodeProbeFreshness,\n buildMeshSchedulingRuntime,\n buildP2pRelayFailurePayload,\n cancelTask,\n classifyP2pRelayFailure,\n pruneStaleDirectDispatches,\n describeTaskDependencyState,\n taskDependenciesSatisfied,\n drainPendingMeshCoordinatorEvents,\n serializeV2EnvelopeToWire,\n enqueueTask,\n computeMeshMissionStats,\n computeMeshTaskStats,\n getActiveMeshMissionSummaries,\n getMeshStatusMissionSummaries,\n getMeshStatusMissionsCompact,\n listMeshMissionSummaries,\n listMeshMissionsForTool,\n MESH_MISSION_STATUSES,\n upsertMeshMission,\n getActiveDirectDispatches,\n getQueue,\n getLedgerSummary,\n getSessionRecoveryContext,\n insertDirectDispatch,\n recordDirectDispatchTask,\n isP2pRelayTransportFailure,\n markStaleDirectDispatches,\n nodeSatisfiesRequiredTags,\n normalizeMeshCapabilityTags,\n isMeshNodeHealthLaunchable,\n resolveEffectiveMeshNodeHealth,\n readLedgerEntries,\n coordinatorIdentityFromEmitFields,\n readLedgerSlice,\n readLedgerSliceFromStore,\n reconcileDirectDispatchCompletionFromTranscript,\n recordMeshToolCall,\n requeueTask,\n requeueHeldMeshCoordinatorEvents,\n resolveMeshSurfacedSessionPreview,\n resolveDelegatedWorkerAutoApprove,\n resolveAllowSendKeysDestructive,\n validateMeshTaskModeRequest,\n} from '@adhdev/daemon-core';\nimport { readString, readNumeric, LARGE_LEDGER_FIELD_KEYS, summarizeLargeLedgerField, elideLargeNestedValue } from './mesh-tool-shared.js';\nimport {\n readSessionRecordId,\n extractStatusMetadataSessions,\n resolveSessionProviderType,\n isMeshCoordinatorSessionRecord,\n isUnmanagedSessionRecord,\n isWorkerTaskMode,\n collectNodeSessionIds,\n unwrapCommandPayload,\n isTerminalSessionRecord,\n isIdleSessionRecord,\n} from './mesh-session-helpers.js';\nimport {\n ACTIVE_QUEUE_STATUSES,\n HISTORICAL_QUEUE_STATUSES,\n COMPACT_MAX_ACTIVE_QUEUE_ROWS,\n COMPACT_MAX_ACTIVE_WORK_ROWS,\n buildQueueStatusSummary,\n normalizeQueueViewMode,\n sanitizeQueueStatusFilter,\n filterQueueForView,\n prioritizeActiveQueueRows,\n buildQueueMaintenanceReport,\n buildCompactQueueMaintenanceReport,\n compactQueueRow,\n compactQueueRows,\n compactActiveWorkRecords,\n annotateQueueStaleness,\n} from './mesh-queue-helpers.js';\nimport type { QueueViewMode } from './mesh-queue-helpers.js';\nimport {\n compactMeshStatusNode,\n compactNodeSeverity,\n isNoteworthyCompactNode,\n minimalCompactNode,\n summarizeNodeSessions,\n} from './mesh-compact.js';\n\n// Node identity / locality helpers were physically moved to ./mesh-node-identity.ts\n// (pure move, no behavior change). Imported back for internal use here.\nimport {\n resolveCoordinatorNode,\n resolveCoordinatorDaemonId,\n readNodeMachineId,\n readNodeDaemonId,\n buildNodeMachineIdentity,\n resolvePreferredWorktreeNodeId,\n isLocalControlPlaneNode,\n} from './mesh-node-identity.js';\n\n// Re-exported so the public `./tools/mesh-tools.js` path still exposes it.\nexport { resolveCoordinatorDaemonId } from './mesh-node-identity.js';\n\n\n// ─── Tool Definitions ───────────────────────────\n\n// Tool schema definitions live in ./mesh-tool-schemas.ts. Re-exported here so the\n// public `./tools/mesh-tools.js` import path (server.ts, help.ts) is unchanged.\nexport {\n MESH_STATUS_TOOL,\n MESH_LIST_NODES_TOOL,\n MESH_ENQUEUE_TASK_TOOL,\n MESH_VIEW_QUEUE_TOOL,\n MESH_QUEUE_CANCEL_TOOL,\n MESH_QUEUE_REQUEUE_TOOL,\n MESH_SEND_TASK_TOOL,\n MESH_READ_CHAT_TOOL,\n MESH_READ_DEBUG_TOOL,\n MESH_LAUNCH_SESSION_TOOL,\n MESH_GIT_STATUS_TOOL,\n MESH_READ_NODE_LOGS_TOOL,\n MESH_FAST_FORWARD_NODE_TOOL,\n MESH_RESTART_DAEMON_TOOL,\n MESH_CHECKPOINT_TOOL,\n MESH_MISSION_UPSERT_TOOL,\n MESH_MISSION_LIST_TOOL,\n MESH_APPROVE_TOOL,\n MESH_LIST_PENDING_APPROVALS_TOOL,\n MESH_CLONE_NODE_TOOL,\n MESH_REMOVE_NODE_TOOL,\n MESH_CLEANUP_SESSIONS_TOOL,\n MESH_TASK_HISTORY_TOOL,\n MESH_RECORD_NOTE_TOOL,\n MESH_FORGET_NOTE_TOOL,\n MESH_RECONCILE_LEDGER_TOOL,\n MESH_REQUEUE_HELD_EVENTS_TOOL,\n MESH_PRUNE_STALE_DIRECT_TOOL,\n MESH_REFINE_NODE_TOOL,\n MESH_REFINE_BATCH_TOOL,\n MESH_REFINE_CONFIG_TOOL,\n MESH_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_INIT_TOOL,\n MESH_REINIT_TOOL,\n MESH_WRITE_MESH_JSON_CONFIG_TOOL,\n MESH_MAGI_KIND_PANEL_SET_TOOL,\n MESH_MAGI_KIND_PANEL_LIST_TOOL,\n MESH_REFINE_PLAN_TOOL,\n MESH_REVIEW_INBOX_TOOL,\n ALL_MESH_TOOLS,\n} from './mesh-tool-schemas.js';\n\n// Re-export imported dependencies so the domain tool files import everything from this module.\nexport {\n IpcTransport,\n} from '../transports/ipc.js';\nexport type {\n CommandTransport,\n} from '../transports/mode.js';\nexport {\n compactChatPayload,\n isCoordinatorVisibleMessage,\n messageContent,\n} from './chat-compact.js';\nexport {\n compactMeshStatusNode,\n compactNodeSeverity,\n isNoteworthyCompactNode,\n minimalCompactNode,\n summarizeNodeSessions,\n} from './mesh-compact.js';\nexport {\n buildNodeMachineIdentity,\n isLocalControlPlaneNode,\n readNodeDaemonId,\n readNodeMachineId,\n resolveCoordinatorNode,\n resolvePreferredWorktreeNodeId,\n} from './mesh-node-identity.js';\nexport {\n ACTIVE_QUEUE_STATUSES,\n COMPACT_MAX_ACTIVE_QUEUE_ROWS,\n COMPACT_MAX_ACTIVE_WORK_ROWS,\n HISTORICAL_QUEUE_STATUSES,\n annotateQueueStaleness,\n buildCompactQueueMaintenanceReport,\n buildQueueMaintenanceReport,\n buildQueueStatusSummary,\n compactActiveWorkRecords,\n compactQueueRow,\n compactQueueRows,\n filterQueueForView,\n normalizeQueueViewMode,\n prioritizeActiveQueueRows,\n sanitizeQueueStatusFilter,\n} from './mesh-queue-helpers.js';\nexport type {\n QueueViewMode,\n} from './mesh-queue-helpers.js';\nexport {\n collectNodeSessionIds,\n extractStatusMetadataSessions,\n isIdleSessionRecord,\n isMeshCoordinatorSessionRecord,\n isTerminalSessionRecord,\n isUnmanagedSessionRecord,\n isWorkerTaskMode,\n readSessionRecordId,\n resolveSessionProviderType,\n unwrapCommandPayload,\n} from './mesh-session-helpers.js';\nexport {\n LARGE_LEDGER_FIELD_KEYS,\n elideLargeNestedValue,\n readNumeric,\n readString,\n summarizeLargeLedgerField,\n} from './mesh-tool-shared.js';\nexport {\n annotateRapidReadChatAdvisory,\n} from './read-chat-polling-advisory.js';\nexport {\n MESH_MISSION_STATUSES,\n appendLedgerEntry,\n appendRemoteLedgerEntries,\n buildCompactStaleDirectWorkSummary,\n buildMeshActiveWork,\n collectPendingApprovals,\n buildMeshAsyncRefineJobs,\n buildMeshMagiActivity,\n summarizeMeshMagiActivity,\n getMeshMagiActivityByGroup,\n MAGI_RAW_ANSWER_CAP,\n buildMeshLedgerReconciliationEvidence,\n buildMeshLedgerReplicaEvidence,\n buildMeshNodeCapabilityTags,\n buildMeshNodeProbeFreshness,\n buildMeshSchedulingRuntime,\n buildP2pRelayFailurePayload,\n cancelTask,\n classifyP2pRelayFailure,\n computeMeshMissionStats,\n computeMeshTaskStats,\n daemonIdsEquivalent,\n deleteDirectDispatchesByTaskId,\n describeTaskDependencyState,\n taskDependenciesSatisfied,\n drainPendingMeshCoordinatorEvents,\n enqueueTask,\n getActiveDirectDispatches,\n getActiveMeshMissionSummaries,\n getLedgerSummary,\n getMagiKindPanel,\n listMagiKindPanels,\n setMagiKindPanel,\n removeMagiKindPanel,\n normalizeMagiSlots,\n getMeshMission,\n getMeshStatusMissionSummaries,\n getMeshStatusMissionsCompact,\n getQueue,\n getSessionRecoveryContext,\n insertDirectDispatch,\n isP2pRelayTransportFailure,\n isWeakCompletionEvidence,\n listMeshMissionSummaries,\n listMeshMissionsForTool,\n markStaleDirectDispatches,\n meshNodeIdMatches,\n nodeSatisfiesRequiredTags,\n normalizeMeshCapabilityTags,\n isMeshNodeHealthLaunchable,\n resolveEffectiveMeshNodeHealth,\n normalizeMeshTaskPriority,\n resolveNotBefore,\n meshTaskPriorityRank,\n pruneStaleDirectDispatches,\n readLedgerEntries,\n readLedgerSlice,\n readLedgerSliceFromStore,\n reconcileDirectDispatchCompletionFromTranscript,\n recordDirectDispatchTask,\n recordMeshToolCall,\n requeueTask,\n requeueHeldMeshCoordinatorEvents,\n resolveDelegatedWorkerAutoApprove,\n resolveAllowSendKeysDestructive,\n resolveMeshSurfacedSessionPreview,\n summarizeMeshAsyncRefineJobs,\n tombstoneOperatingNote,\n upsertMeshMission,\n validateMeshTaskModeRequest,\n} from '@adhdev/daemon-core';\nexport type {\n LocalMeshEntry,\n LocalMeshNodeEntry,\n MagiAgentResponse,\n MagiClaim,\n MagiClaimCluster,\n MagiClusterMember,\n MagiGitSkew,\n MagiMode,\n MagiTaskKind,\n MagiReplicaGitRef,\n MagiResponseSource,\n MagiSlot,\n MagiKindPanelMap,\n MagiSynthesis,\n MagiSynthesizedResponse,\n MeshActiveWorkSummary,\n MeshPendingApproval,\n MeshSchedulingRuntime,\n MeshNodeSchedulingRuntime,\n RepoMeshPolicy,\n RepoMeshRelatedRepo,\n} from '@adhdev/daemon-core';\nexport {\n randomUUID,\n} from 'node:crypto';\n\nexport interface MeshContext {\n mesh: LocalMeshEntry;\n transport: CommandTransport;\n /** Daemon ID for this local machine (local mode) */\n localDaemonId?: string;\n /** Machine Registry ID for this local machine */\n localMachineId?: string;\n /** Hostname of the daemon/MCP coordinator machine. */\n coordinatorHostname?: string;\n /**\n * Runtime session id of THIS coordinator's CLI session, injected by the daemon at\n * coordinator launch via ADHDEV_COORDINATOR_SESSION_ID. Stamped onto dispatched\n * workers (meshContext.coordinatorSessionId) so a worker's completion event routes\n * back to the exact originating coordinator session — even when several coordinator\n * sessions share one daemon. Absent for non-coordinator / legacy launches → routing\n * falls back to the daemon-level anchor.\n */\n coordinatorSessionId?: string;\n /**\n * T6 (B3c): the mesh-protocol-v2 enforce/backstop counters snapshot ridden on the\n * most recent local get_pending_mesh_events drain response (set by\n * drainCoordinatorPendingEvents). Lets a pure stdio MCP coordinator surface the\n * enforce state + quarantine / last-resort-backstop tallies in mesh_status without\n * a second daemon round-trip. Absent on version-skewed daemons that don't ride it.\n */\n lastMeshProtocolV2Counters?: MeshProtocolV2CountersSnapshot;\n}\n\n/** T6 (B3c) live v2 enforce/observability counters snapshot (mirrors the daemon-core\n * RepoMeshStatus.meshProtocolV2Counters shape). Structural type — no daemon-core import. */\nexport interface MeshProtocolV2CountersSnapshot {\n enforce: boolean;\n drain: Record<string, number>;\n backstop: Record<string, number>;\n}\n\nexport type MeshSessionProviderMetadata = {\n providerType: string;\n providerSessionId?: string;\n};\n\nexport const SESSION_PROVIDER_METADATA_TTL_MS = 30 * 60_000;\n\nexport type TimestampedSessionMetadata = MeshSessionProviderMetadata & { expiresAt: number };\n\nexport const meshSessionProviderMetadata = new Map<string, TimestampedSessionMetadata>();\n\nexport function getSessionMetadata(key: string): MeshSessionProviderMetadata | undefined {\n const entry = meshSessionProviderMetadata.get(key);\n if (!entry) return undefined;\n if (entry.expiresAt <= Date.now()) {\n meshSessionProviderMetadata.delete(key);\n return undefined;\n }\n return entry;\n}\n\nexport const ACTIVE_WORK_POLLING_BACKOFF_MS = 60_000;\n\nexport interface MeshPollingGuidance {\n activeGeneratingWork: true;\n generatingCount: number;\n doNotPollBefore: string;\n eventSurface: 'pendingCoordinatorEvents';\n nextRecommendedAction: string;\n message: string;\n}\n\nexport function buildActiveWorkPollingGuidance(summary: MeshActiveWorkSummary, now = Date.now()): MeshPollingGuidance | undefined {\n if (!summary || summary.generatingCount <= 0) return undefined;\n return {\n activeGeneratingWork: true,\n generatingCount: summary.generatingCount,\n doNotPollBefore: new Date(now + ACTIVE_WORK_POLLING_BACKOFF_MS).toISOString(),\n eventSurface: 'pendingCoordinatorEvents',\n nextRecommendedAction: 'Wait for pendingCoordinatorEvents/completion events or an explicit user status request. If no terminal evidence appears and the user asks for status, make one bounded status check, then wait again.',\n message: 'Do not repeatedly poll mesh_status/mesh_view_queue/mesh_read_chat while delegated work is generating; terminal ledger or completion evidence will be surfaced through pendingCoordinatorEvents when available.',\n };\n}\n\n\n// ─── Helpers ────────────────────────────────────\n\nexport function summarizeTaskMessage(message: string): { taskTitle: string; taskSummary: string } {\n const taskSummary = message.replace(/\\s+/g, ' ').trim();\n const taskTitle = taskSummary.length > 96 ? `${taskSummary.slice(0, 93)}...` : taskSummary;\n return { taskTitle: taskTitle || '(untitled task)', taskSummary };\n}\n\nexport function buildDirectTaskPayload(\n message: string,\n via: 'p2p_direct' | 'local_direct' | 'mesh_send_task',\n opts: {\n taskId: string;\n taskMode?: string;\n providerType?: string;\n targetSessionId?: string;\n /** When true, the target session was idle at time of dispatch. This flag helps\n * mesh-active-work stale detection identify unacknowledged direct dispatches. */\n dispatchedToIdleSession?: boolean;\n /** NOTIF-DROP-SYNTH-NO-MESSAGE: the originating coordinator SESSION that dispatched this\n * task. Persisted in the task_dispatched ledger so a later transcript-reconcile synth of\n * the completion can STRICT-route the [System] notification back to the exact coordinator\n * session (not just the daemon). Mirrors the `coordinatorSessionId` already stamped into\n * the worker's meshContext. */\n coordinatorSessionId?: string;\n /** COORD-EVENT-MISROUTE (anchor preservation): the originating coordinator DAEMON that\n * dispatched this task. Persisted in the task_dispatched ledger so a later transcript-\n * reconcile synth recovers the DISPATCHING coordinator's daemon anchor from the ledger\n * instead of stamping the WORKER's own self-daemon (mesh-completion-synthesis selfIds) —\n * the anchor corruption that downgraded a cross-machine completion to a broadcast\n * deliverable to any coordinator. Mirrors the `coordinatorDaemonId` already stamped into\n * the worker's meshContext. Absent on legacy rows → daemon-level fallback (unchanged). */\n coordinatorDaemonId?: string;\n },\n): Record<string, unknown> {\n const descriptor = summarizeTaskMessage(message);\n return {\n source: 'direct',\n via,\n taskId: opts.taskId,\n message,\n taskTitle: descriptor.taskTitle,\n taskSummary: descriptor.taskSummary,\n ...(opts.taskMode ? { taskMode: opts.taskMode } : {}),\n ...(opts.providerType ? { providerType: opts.providerType } : {}),\n ...(opts.targetSessionId ? { targetSessionId: opts.targetSessionId } : {}),\n ...(opts.dispatchedToIdleSession !== undefined ? { dispatchedToIdleSession: opts.dispatchedToIdleSession } : {}),\n ...(opts.coordinatorSessionId ? { coordinatorSessionId: opts.coordinatorSessionId } : {}),\n ...(opts.coordinatorDaemonId ? { coordinatorDaemonId: opts.coordinatorDaemonId } : {}),\n };\n}\n\nexport function findNode(mesh: LocalMeshEntry, nodeId: string): LocalMeshNodeEntry {\n const node = mesh.nodes.find(n => meshNodeIdMatches(n as any, nodeId));\n if (!node) throw new Error(`Node '${nodeId}' is not a member of mesh '${mesh.name}'`);\n return node;\n}\n\nexport const DUPLICATE_DISPATCH_WINDOW_MS = 60_000;\n\n// (queue constants/types moved to ./mesh-queue-helpers.ts)\n\n/**\n * Refresh the MCP process's mesh snapshot from the daemon inline mesh cache.\n * This is required for status/list tools when a previous MCP process already\n * created or removed worktree nodes through clone_mesh_node/remove_mesh_node.\n */\nexport async function refreshMeshFromDaemon(ctx: MeshContext): Promise<void> {\n try {\n const result = await ctx.transport.command('get_mesh', { meshId: ctx.mesh.id }) as any;\n if (!result?.success || !Array.isArray(result.mesh?.nodes)) return;\n const refreshedNodes = result.mesh.nodes\n .filter((n: any) => n?.id)\n .map((n: any) => n as LocalMeshNodeEntry);\n (ctx.mesh.nodes as LocalMeshNodeEntry[]).splice(0, ctx.mesh.nodes.length, ...refreshedNodes);\n ctx.mesh.updatedAt = result.mesh.updatedAt ?? ctx.mesh.updatedAt;\n } catch { /* refresh is best-effort; callers still report their original status/errors */ }\n}\n\nexport async function syncCoordinatorDaemonMeshCache(ctx: MeshContext): Promise<void> {\n if (!(ctx.transport instanceof IpcTransport)) return;\n try {\n await (ctx.transport as IpcTransport).command('get_mesh', {\n meshId: ctx.mesh.id,\n inlineMesh: ctx.mesh,\n });\n } catch {\n /* cache sync is best-effort; the MCP process still keeps its local ctx.mesh copy */\n }\n}\n\nexport async function findNodeWithRefresh(ctx: MeshContext, nodeId: string): Promise<LocalMeshNodeEntry> {\n const hit = ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, nodeId));\n if (hit && !hit.isLocalWorktree) return hit;\n\n await refreshMeshFromDaemon(ctx);\n\n const refreshed = ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, nodeId));\n if (!refreshed) throw new Error(`Node '${nodeId}' is not a member of mesh '${ctx.mesh.name}'`);\n return refreshed;\n}\n\nexport async function findOptionalNodeWithRefresh(ctx: MeshContext, nodeId: string): Promise<LocalMeshNodeEntry | null> {\n const hit = ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, nodeId));\n if (hit && !hit.isLocalWorktree) return hit;\n\n await refreshMeshFromDaemon(ctx);\n\n return ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, nodeId)) ?? null;\n}\n\nexport function hasRecentDuplicateDispatch(ctx: MeshContext, args: { node_id: string; session_id?: string; message: string }): { duplicate: boolean; entry?: any; source?: 'ledger' | 'queue' } {\n const now = Date.now();\n const normalizedMessage = args.message.trim();\n\n for (const task of getQueue(ctx.mesh.id)) {\n const timestamp = new Date(task.updatedAt || task.createdAt).getTime();\n if (!Number.isFinite(timestamp) || now - timestamp > DUPLICATE_DISPATCH_WINDOW_MS) continue;\n if (task.targetNodeId && task.targetNodeId !== args.node_id) continue;\n if (task.assignedNodeId && task.assignedNodeId !== args.node_id) continue;\n if (args.session_id && task.targetSessionId !== args.session_id && task.assignedSessionId !== args.session_id) continue;\n if (task.message?.trim() === normalizedMessage) {\n return { duplicate: true, entry: task, source: 'queue' };\n }\n }\n\n const entries = readLedgerEntries(ctx.mesh.id, { tail: 200 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i];\n const timestamp = new Date(entry.timestamp).getTime();\n if (Number.isFinite(timestamp) && now - timestamp > DUPLICATE_DISPATCH_WINDOW_MS) break;\n if (entry.kind !== 'task_dispatched') continue;\n if (entry.nodeId !== args.node_id) continue;\n if (args.session_id && entry.sessionId !== args.session_id) continue;\n if (typeof entry.payload?.message !== 'string') continue;\n if (entry.payload.message.trim() === normalizedMessage) {\n return { duplicate: true, entry, source: 'ledger' };\n }\n }\n return { duplicate: false };\n}\n\nexport function buildMissingNodeReadChatRecovery(ctx: MeshContext, args: { node_id: string; session_id: string; provider_session_id?: string; tail?: number; compact?: boolean }): Record<string, unknown> {\n const entries = readLedgerEntries(ctx.mesh.id, { tail: 300 });\n const relatedEntries = entries.filter(entry => entry.nodeId === args.node_id || entry.sessionId === args.session_id);\n const completedEntries = relatedEntries.filter(entry => entry.kind === 'task_completed');\n const lastDispatch = [...relatedEntries].reverse().find(entry => entry.kind === 'task_dispatched');\n const lastTerminal = [...relatedEntries].reverse().find(entry => entry.kind === 'task_completed' || entry.kind === 'task_failed' || entry.kind === 'task_stalled');\n const lastRemoved = [...relatedEntries].reverse().find(entry => entry.kind === 'node_removed');\n const lastLaunch = [...relatedEntries].reverse().find(entry => entry.kind === 'session_launched');\n const providerSessionId = args.provider_session_id\n || readString(lastTerminal?.payload?.providerSessionId)\n || readString(lastLaunch?.payload?.providerSessionId)\n || readString(lastDispatch?.payload?.providerSessionId);\n const finalSummary = readString(lastTerminal?.payload?.finalSummary)\n || readString(lastTerminal?.payload?.compactSummary)\n || readString(lastTerminal?.payload?.summary);\n const ledger = {\n taskCompletedFound: completedEntries.length > 0,\n nodeRemovedFound: !!lastRemoved,\n providerType: lastTerminal?.providerType || lastLaunch?.providerType || lastDispatch?.providerType,\n providerSessionId,\n nodeRemovedAt: lastRemoved?.timestamp,\n sessionCleanupMode: readString(lastRemoved?.payload?.sessionCleanupMode),\n readDebugLocator: readString(lastTerminal?.payload?.readDebugLocator) || readString(lastTerminal?.payload?.debugBundlePath),\n };\n\n if (finalSummary) {\n if (args.compact === true) {\n return {\n ...compactChatPayload({\n success: true,\n status: 'idle',\n providerSessionId,\n summary: finalSummary,\n messages: [{ role: 'assistant', content: finalSummary, isHistorical: true }],\n }, {\n nodeId: args.node_id,\n sessionId: args.session_id,\n limit: args.tail ?? 10,\n }),\n recoveredFromLedger: true,\n ledger,\n };\n }\n return {\n success: true,\n compact: false,\n recoveredFromLedger: true,\n nodeId: args.node_id,\n sessionId: args.session_id,\n summary: finalSummary,\n ledger,\n messages: [{ role: 'assistant', content: finalSummary, isHistorical: true }],\n };\n }\n\n return {\n success: false,\n recoverable: true,\n code: 'mesh_removed_node_transcript_unavailable',\n error: `Node '${args.node_id}' is not a current member of mesh '${ctx.mesh.name}'.`,\n nodeId: args.node_id,\n sessionId: args.session_id,\n providerSessionId,\n reason: 'node_not_in_current_mesh_snapshot',\n ledger,\n completedSessionSeenInLedger: ledger.taskCompletedFound,\n lastDispatch: lastDispatch ? {\n timestamp: lastDispatch.timestamp,\n sessionId: lastDispatch.sessionId,\n providerType: lastDispatch.providerType,\n taskId: typeof lastDispatch.payload?.taskId === 'string' ? lastDispatch.payload.taskId : undefined,\n messagePreview: typeof lastDispatch.payload?.message === 'string' ? lastDispatch.payload.message.slice(0, 500) : undefined,\n } : null,\n lastTerminalEvent: lastTerminal ? {\n kind: lastTerminal.kind,\n timestamp: lastTerminal.timestamp,\n sessionId: lastTerminal.sessionId,\n providerType: lastTerminal.providerType,\n taskId: typeof lastTerminal.payload?.taskId === 'string' ? lastTerminal.payload.taskId : undefined,\n payload: lastTerminal.payload,\n } : null,\n nextSteps: [\n providerSessionId\n ? `Retry mesh_read_chat with provider_session_id='${providerSessionId}' on a current live node for the same daemon if one exists.`\n : 'If the node UI shows a provider transcript id, retry mesh_read_chat/mesh_read_debug with provider_session_id.',\n 'Use mesh_read_debug with the provider_session_id or daemon-side debug bundle locator if available.',\n 'Check mesh_task_history for task_completed and node_removed entries before redispatching; do not resend solely because transcript recovery failed.',\n 'If this node was removed with stop_and_delete, the runtime transcript may be gone; rely on the ledger summary/locator or ask the operator for the saved UI output.',\n ],\n recoveryHints: [\n 'The worktree/node may have been removed or the mesh snapshot may be stale after task completion.',\n 'If you have a provider_session_id, retry mesh_read_chat with that value while targeting a live node for the same daemon if available.',\n 'Use mesh_read_debug with provider_session_id, or inspect the daemon/session-host history locator if the transcript has already been archived.',\n 'Avoid redispatching the same task solely because read_chat could not recover the transcript; check task_history and git status first.',\n ],\n };\n}\n\n\n// (queue helpers moved to ./mesh-queue-helpers.ts)\n\n// (moved to ./mesh-session-helpers.ts — session/payload record helpers)\n\nexport function isDirectDispatchLedgerEntry(entry: any): boolean {\n if (entry?.kind !== 'task_dispatched') return false;\n const payload = entry.payload || {};\n const via = readString(payload.via);\n return payload.source === 'direct' || via === 'p2p_direct' || via === 'local_direct' || via === 'mesh_send_task';\n}\n\nexport function readMessageTimestampIso(message: any): string | undefined {\n for (const value of [message?.timestamp, message?.createdAt, message?.created_at, message?.updatedAt, message?.time]) {\n if (typeof value === 'number' && Number.isFinite(value)) {\n const ms = value > 10_000_000_000 ? value : value * 1000;\n return new Date(ms).toISOString();\n }\n if (typeof value === 'string' && value.trim()) {\n const ms = new Date(value.trim()).getTime();\n if (Number.isFinite(ms)) return new Date(ms).toISOString();\n }\n }\n return undefined;\n}\n\n// EARLYNOTIFY-GATEBYPASS (a)/(b): mirror daemon-core's selectFinalAssistantTurnEndMessage\n// turn-finality rule so the MCP mesh_status transcript reconcile applies the SAME \"which bubble is\n// the turn's final answer\" judgement as the daemon path it delegates to. A genuine turn end is a\n// NON-EMPTY LATEST coordinator-visible assistant/agent bubble: scanning from the end, the first\n// coordinator-visible message must itself be a non-empty assistant reply. An empty (streaming /\n// mid-turn) latest assistant bubble, or a trailing user message, means the turn is not proven done\n// — we do NOT walk back past it to promote an earlier narration to \"final\" (the Defect-B walk-back)\n// and we do NOT fall back to a bare payload.summary in that case. This structural check plus the\n// daemon-side grace gate (reconcileDirectDispatchCompletionFromTranscript) keep a coordinator poll\n// from synthesizing a completion mid-turn.\nexport function readFinalAssistantTranscriptEvidence(payload: any): { finalSummary?: string; transcriptMessageAt?: string } {\n const rawMessages = Array.isArray(payload?.messages) ? payload.messages : [];\n let turnEnd: any | undefined;\n for (let i = rawMessages.length - 1; i >= 0; i--) {\n const message = rawMessages[i];\n if (!isCoordinatorVisibleMessage(message)) continue; // skip tool/thought/status activity\n const role = String(message?.role ?? '').toLowerCase();\n // First coordinator-visible message from the end = who had the last word.\n turnEnd = (role === 'assistant' || role === 'agent') && messageContent(message).trim()\n ? message\n : undefined;\n break;\n }\n if (!turnEnd) return { finalSummary: undefined, transcriptMessageAt: undefined };\n return {\n finalSummary: messageContent(turnEnd).trim(),\n transcriptMessageAt: readMessageTimestampIso(turnEnd),\n };\n}\n\nexport function findNodeSession(nodes: any[], nodeId?: string | null, sessionId?: string | null): { node?: any; session?: any } {\n if (!nodeId || !sessionId) return {};\n const node = nodes.find((candidate: any) => meshNodeIdMatches(candidate, nodeId));\n if (!node) return {};\n const sessions = Array.isArray(node.sessions) ? node.sessions : [];\n const session = sessions.find((candidate: any) => readSessionRecordId(candidate) === sessionId);\n return { node, session };\n}\n\nexport function buildDirectDispatchReconciliationCandidates(directDispatches: any[], ledgerEntries: any[]): any[] {\n const candidates: any[] = [];\n const seenTaskIds = new Set<string>();\n for (const dispatch of directDispatches || []) {\n const taskId = readString(dispatch?.taskId);\n if (!taskId || seenTaskIds.has(taskId)) continue;\n seenTaskIds.add(taskId);\n candidates.push(dispatch);\n }\n for (const entry of ledgerEntries || []) {\n if (!isDirectDispatchLedgerEntry(entry)) continue;\n const taskId = readString(entry.payload?.taskId);\n if (!taskId || seenTaskIds.has(taskId)) continue;\n seenTaskIds.add(taskId);\n candidates.push({\n taskId,\n nodeId: entry.nodeId,\n sessionId: entry.sessionId,\n providerType: entry.providerType || readString(entry.payload?.providerType),\n message: readString(entry.payload?.message),\n dispatchedAt: entry.timestamp,\n via: readString(entry.payload?.via),\n });\n }\n return candidates;\n}\n\nexport async function reconcileDirectDispatchesFromTranscriptEvidence(\n ctx: MeshContext,\n liveNodes: any[],\n directDispatches: any[],\n ledgerEntries: any[],\n): Promise<{ attempted: number; reconciled: number; skipped: number }> {\n let attempted = 0;\n let reconciled = 0;\n let skipped = 0;\n const candidates = buildDirectDispatchReconciliationCandidates(directDispatches, ledgerEntries);\n for (const dispatch of candidates) {\n const taskId = readString(dispatch?.taskId);\n const nodeId = readString(dispatch?.nodeId);\n const sessionId = readString(dispatch?.sessionId);\n if (!taskId || !nodeId || !sessionId) {\n skipped += 1;\n continue;\n }\n const { session } = findNodeSession(liveNodes, nodeId, sessionId);\n // EARLYNOTIFY-GATEBYPASS (e): a single snapshot-idle sample is NOT sufficient to synthesize\n // a completion — a mid-turn poll routinely reads idle for an instant. This idle check only\n // makes the session ELIGIBLE for a transcript read; the actual turn-finality gate is\n // enforced downstream: readFinalAssistantTranscriptEvidence requires a genuine non-empty\n // latest-assistant turn end, and reconcileDirectDispatchCompletionFromTranscript (the\n // guarded daemon path this delegates to) applies the dispatch grace window + stale-summary\n // guard before it will write a terminal. So a coordinator poll cannot force a mid-turn synth.\n if (!session || !isIdleSessionRecord(session)) {\n skipped += 1;\n continue;\n }\n const node = await findOptionalNodeWithRefresh(ctx, nodeId).catch(() => null);\n if (!node) {\n skipped += 1;\n continue;\n }\n const providerType = readString(dispatch?.providerType) || resolveSessionProviderType(session);\n const providerSessionId = readString(session?.providerSessionId)\n || readString(session?.activeChat?.providerSessionId)\n || readString(session?.settings?.providerSessionId)\n || resolveMeshSessionProviderMetadata(ctx, nodeId, sessionId)?.providerSessionId;\n attempted += 1;\n try {\n const readResult = await commandForNode(ctx, node, 'read_chat', {\n sessionId,\n targetSessionId: sessionId,\n workspace: node.workspace,\n ...(providerType ? { agentType: providerType, providerType } : {}),\n ...(providerSessionId ? { providerSessionId } : {}),\n tailLimit: 10,\n });\n const payload = unwrapCommandPayload(readResult);\n if (payload?.success === false) continue;\n const evidence = readFinalAssistantTranscriptEvidence(payload);\n if (!evidence.finalSummary) continue;\n const result = reconcileDirectDispatchCompletionFromTranscript({\n meshId: ctx.mesh.id,\n nodeId,\n sessionId,\n providerType,\n providerSessionId: readString(payload?.providerSessionId) || providerSessionId,\n taskId,\n finalSummary: evidence.finalSummary,\n transcriptMessageAt: evidence.transcriptMessageAt,\n targetCoordinatorDaemonId: ctx.localDaemonId,\n source: 'mcp_mesh_status_transcript_reconciliation',\n });\n if (result.reconciled) reconciled += 1;\n } catch {\n skipped += 1;\n }\n }\n return { attempted, reconciled, skipped };\n}\n\nexport async function triggerMeshQueueAndReport(\n ctx: MeshContext,\n): Promise<Record<string, unknown> | undefined> {\n try {\n // trigger_mesh_queue is a coordinator-only operation: triggerMeshQueue\n // reads the mesh object, the coordinator's local CLI instances, and the\n // queue ledger (stored on THIS machine), then dispatches assignments to\n // remote idle sessions over P2P itself. Relaying trigger_mesh_queue to a\n // remote worker daemon would hit requireMeshHostMutationOwner →\n // getMeshForCommand → null ('Mesh not found'), because only the\n // coordinator daemon hosts the mesh. Always run it on the coordinator's\n // local IPC, regardless of which node prompted the trigger.\n const raw = await ctx.transport.command('trigger_mesh_queue', { meshId: ctx.mesh.id });\n const payload = unwrapCommandPayload(raw);\n const trigger = payload?.trigger && typeof payload.trigger === 'object' ? payload.trigger : payload;\n return trigger && typeof trigger === 'object' ? trigger : { success: true };\n } catch (e: any) {\n return {\n success: false,\n error: e?.message || String(e),\n };\n }\n}\n\nexport function buildQueueTriggerGuidance(queueTrigger: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!queueTrigger || queueTrigger.claimed === true) return undefined;\n if (queueTrigger.success === false) {\n return {\n queueClaimed: false,\n queueDispatchState: 'trigger_failed',\n nextAction: 'Do not assume the queued task is running. Check mesh_view_queue and daemon connectivity before redispatching.',\n };\n }\n if (queueTrigger.autoLaunchPending === true) {\n // The coordinator already spun up (or is spinning up) a worker session for this\n // task — it is booting and will claim within a few seconds. Telling the caller to\n // launch ANOTHER session here would double-edit the worktree. Do NOT advise a new\n // launch; just wait for the in-flight session to claim.\n return {\n queueClaimed: false,\n queueDispatchState: 'pending_waiting_for_autolaunch',\n nextAction: 'A worker session was just auto-launched for this task and is booting; it will claim the task shortly. Wait for it to claim — do NOT launch another session. Use mesh_view_queue to confirm the assignment lands.',\n };\n }\n if (queueTrigger.noIdleMeshSessionAvailable === true) {\n return {\n queueClaimed: false,\n queueDispatchState: 'pending_no_idle_mesh_session',\n nextAction: 'The task is queued but not running. Launch a managed worker with mesh_launch_session, or wait for a delegated session to become ready and trigger the queue again.',\n };\n }\n return {\n queueClaimed: false,\n queueDispatchState: 'pending_or_waiting_for_ready',\n nextAction: 'The task is queued but this trigger did not claim it. Use mesh_view_queue for the current active-work source of truth before retrying.',\n };\n}\n\n\n// (moved to ./mesh-session-helpers.ts — session/payload record helpers)\n\nexport function isMeshOwnedDelegateSession(session: any, meshId: string, nodeId: string): boolean {\n const settings = session?.settings;\n const sessionMeshId = typeof settings?.meshNodeFor === 'string' ? settings.meshNodeFor.trim() : '';\n const sessionNodeId = typeof settings?.meshNodeId === 'string' ? settings.meshNodeId.trim() : '';\n // meshNodeFor is the primary ownership signal. Relay safety is checked separately\n // for remote dispatch because older local delegates may not carry coordinator\n // daemon metadata.\n if (sessionMeshId) {\n if (sessionMeshId !== meshId) return false;\n return !sessionNodeId || sessionNodeId === nodeId;\n }\n // Post-detach: detachMeshAssignment intentionally clears meshNodeFor / meshNodeId /\n // meshActiveTaskId after a relay-safe completion, but preserves the coordinator\n // markers (launchedByCoordinator / meshCoordinatorDaemonId). Without recognizing\n // those, a follow-up dispatch to the SAME session would be misclassified as an\n // unrelated alias and rejected — even though the router self-heals meshNodeFor /\n // meshNodeId at dispatch time (buildMeshWorkerRelayStamp). Treat the preserved\n // coordinator markers as ownership evidence so the dispatch-time restamp can run.\n const coordinatorOwned = settings?.launchedByCoordinator === true || Boolean(readString(settings?.meshCoordinatorDaemonId));\n if (!coordinatorOwned) return false;\n // WTCLAIM (A): a detached coordinator session is reusable, but ONLY for the node\n // it last served. detachMeshAssignment preserves meshLastNodeId (the sticky bind\n // marker). On a daemon hosting BOTH a base node and a cloned worktree node (same\n // daemonId), without this gate a detached BASE session would be auto-picked for a\n // worktree-targeted sessionless dispatch — running worktree work on the base node.\n // When the sticky marker is present it must equal the requested node; legitimate\n // same-node reuse still passes. When absent (never bound, or a pre-fix session),\n // fall back to the prior permissive behavior — fix (B)'s worker-side nodeId/\n // workspace scoping is the defense-in-depth backstop for that residual case.\n const lastNodeId = readString(settings?.meshLastNodeId);\n if (lastNodeId) return lastNodeId === nodeId;\n return true;\n}\n\nexport function hasRemoteRelayMetadata(session: any): boolean {\n return Boolean(\n readString(session?.settings?.meshCoordinatorDaemonId)\n || readString(session?.meta?.meshCoordinatorDaemonId)\n || readString(session?.metadata?.meshCoordinatorDaemonId)\n || readString(session?.meshCoordinatorDaemonId),\n );\n}\n\nexport function isRelaySafeRemoteDelegateSession(session: any, meshId: string, nodeId: string): boolean {\n return isMeshOwnedDelegateSession(session, meshId, nodeId) && hasRemoteRelayMetadata(session);\n}\n\n\n/**\n * Pre-dispatch relay-safety classification for an explicit remote delegate\n * session. The local direct-dispatch path (commandForNode → agent_command) has\n * no such gate: it always dispatches with meshContext.coordinatorDaemonId, and\n * the remote router self-heals the session's meshCoordinatorDaemonId at dispatch\n * time (router.ts buildMeshWorkerRelayStamp). The remote path used to hard-block\n * any session lacking meshCoordinatorDaemonId, which prevented that dispatch-time\n * stamp from ever running — leaving launch-stamp-less but otherwise mesh-owned\n * sessions permanently relay-unsafe.\n *\n * Mirror the local path: a session that is mesh-owned for THIS mesh self-heals\n * as long as we can hand the remote router a coordinator anchor to stamp.\n *\n * - 'safe' — already carries meshCoordinatorDaemonId; dispatch as-is.\n * - 'self_heal' — mesh-owned for this mesh, missing the anchor, but a\n * coordinatorDaemonId is resolvable → dispatch and let the\n * remote router stamp the anchor (parity with local path).\n * - 'missing_anchor' — mesh-owned for this mesh, missing the anchor, AND no\n * coordinatorDaemonId resolvable → cannot delegate the stamp,\n * so completion events would still be undeliverable → block.\n * - 'unsafe_alias' — not mesh-owned for this mesh (different mesh / unrelated\n * session). Dispatching risks aliasing an unrelated transcript\n * and orphaning completion events → block.\n */\nexport function classifyRemoteDelegateRelaySafety(\n session: any,\n meshId: string,\n nodeId: string,\n coordinatorDaemonId: string,\n): 'safe' | 'self_heal' | 'missing_anchor' | 'unsafe_alias' {\n if (!isMeshOwnedDelegateSession(session, meshId, nodeId)) return 'unsafe_alias';\n if (hasRemoteRelayMetadata(session)) return 'safe';\n return coordinatorDaemonId ? 'self_heal' : 'missing_anchor';\n}\n\nexport function chooseDispatchableSession(sessions: any[], providerType: string, meshId: string, nodeId: string, coordinatorDaemonId: string): any | undefined {\n const live = sessions.filter(session => !isTerminalSessionRecord(session));\n const matchingProvider = (session: any) => !providerType || session?.providerType === providerType || session?.cliType === providerType;\n // Accept mesh-owned sessions whose relay anchor is either already present or\n // self-healable at dispatch time (coordinatorDaemonId resolvable). Mirrors the\n // explicit-session relay-safety classification so auto-pick and explicit\n // dispatch converge on the same set of safe delegates.\n const meshSessions = live.filter((session: any) => {\n const safety = classifyRemoteDelegateRelaySafety(session, meshId, nodeId, coordinatorDaemonId);\n return safety === 'safe' || safety === 'self_heal';\n });\n // Only auto-pick an IDLE matching session. The previous\n // `|| meshSessions.find(matchingProvider)` fallback accepted a generating/busy\n // session, injecting a new task into a session mid-generation — the exact case\n // the explicit-session path guards against via resolveDeliveryDecision (queue or\n // reject when !idle). When no idle session exists, return undefined so the caller\n // dispatches sessionless and lets the worker pick/create a session (or the task\n // queues), instead of clobbering an in-flight one.\n return meshSessions.find(session => isIdleSessionRecord(session) && matchingProvider(session))\n || undefined;\n}\n\nexport function buildRelayUnsafeRemoteSessionFailure(ctx: MeshContext, node: LocalMeshNodeEntry, sessionId: string, providerType?: string): ({ success: false; error: string } & Record<string, unknown>) {\n return {\n success: false,\n recoverable: true,\n code: 'mesh_delegate_session_missing_relay_metadata',\n reason: 'mesh_delegate_session_missing_relay_metadata',\n transport: 'mesh_transport',\n retryRecommended: true,\n meshId: ctx.mesh.id,\n nodeId: node.id,\n daemonId: node.daemonId,\n workspace: node.workspace,\n sessionId,\n unsafeTranscriptAlias: true,\n ...(providerType ? { resolvedProviderType: providerType } : {}),\n error: `Remote session '${sessionId}' is not relay-safe for mesh '${ctx.mesh.id}': missing meshNodeFor/meshCoordinatorDaemonId metadata, so completion events would not reach the coordinator ledger. This session may be the coordinator itself or an unrelated session (unsafe_transcript_alias risk).`,\n nextAction: `Launch a fresh relay-safe session with mesh_launch_session(node_id: '${node.id}'${providerType ? `, type: '${providerType}'` : ''}) or dispatch without session_id so Repo Mesh can choose a valid delegate session.`,\n noFallbackReason: 'Blindly reusing a remote session without mesh relay metadata would silently drop task_completed / generating_completed events.',\n };\n}\n\nexport function buildMissingCoordinatorDaemonIdFailure(ctx: MeshContext, node: LocalMeshNodeEntry, providerType?: string): ({ success: false; error: string } & Record<string, unknown>) {\n return {\n success: false,\n recoverable: true,\n code: 'mesh_coordinator_daemon_unknown',\n reason: 'mesh_coordinator_daemon_unknown',\n transport: 'mesh_transport',\n retryRecommended: true,\n meshId: ctx.mesh.id,\n nodeId: node.id,\n daemonId: node.daemonId,\n workspace: node.workspace,\n ...(providerType ? { resolvedProviderType: providerType } : {}),\n error: `Cannot launch a remote mesh delegate for node '${node.id}': coordinator daemon identity is unavailable, so the worker would be unable to relay completion events back to the coordinator.`,\n nextAction: 'Retry after the coordinator daemon identity is available (for example from an attached daemon-backed MCP session) so meshCoordinatorDaemonId can be stamped on the worker session.',\n noFallbackReason: 'Launching without meshCoordinatorDaemonId would create a worker session that can finish work but cannot emit task_completed / generating_completed back to the coordinator.',\n };\n}\n\nexport function findNestedPayload(value: any, predicate: (payload: any) => boolean): any {\n const seen = new Set<any>();\n const stack: Array<{ payload: any; depth: number }> = [{ payload: value, depth: 0 }];\n\n while (stack.length) {\n const { payload, depth } = stack.pop()!;\n if (predicate(payload)) return payload;\n if (!payload || typeof payload !== 'object' || seen.has(payload) || depth >= 8) continue;\n seen.add(payload);\n\n // Cloud/daemon relay layers have used both `result` and `payload` for\n // command_result bodies. Follow only those envelope keys so clone node\n // discovery stays tied to returned command payloads, not arbitrary data.\n for (const key of ['payload', 'result']) {\n if (key in payload) stack.push({ payload: payload[key], depth: depth + 1 });\n }\n }\n\n return value;\n}\n\nexport function extractCloneNodePayload(value: any): any {\n return findNestedPayload(value, payload => Boolean(payload?.node?.id));\n}\n\nexport function extractGitStatus(value: any): any {\n const payload = unwrapCommandPayload(value);\n return payload?.status ?? value?.status ?? payload;\n}\n\nexport function extractGitDiff(value: any): any {\n const payload = unwrapCommandPayload(value);\n return payload?.diffSummary ?? payload?.diff ?? value?.diffSummary ?? value?.diff ?? payload;\n}\n\nexport function extractSubmodules(value: any, ignorePaths: string[]): any[] | undefined {\n const payload = unwrapCommandPayload(value);\n const subs = payload?.status?.submodules\n ?? payload?.submodules\n ?? value?.status?.submodules\n ?? value?.submodules;\n if (!Array.isArray(subs)) return undefined;\n if (ignorePaths.length === 0) return subs;\n const ignoreSet = new Set(ignorePaths);\n return subs.filter((s: any) => s?.path && !ignoreSet.has(s.path));\n}\n\nexport function assignFullGitSnapshot(entry: Record<string, unknown>, status: any): void {\n if (!status || typeof status !== 'object' || Array.isArray(status)) return;\n entry.git = status;\n}\n\n\n// (compact git-snapshot helpers moved to ./mesh-compact.ts)\n\n// (compactMeshStatusNode moved to ./mesh-compact.ts)\n\n// Compact mode bounds the node array so the payload stays under the MCP token cap\n// regardless of how many worktree nodes a mesh has. EVERY node stays present and\n// individually addressable (coordinators look nodes up by id), but \"quiet\" nodes —\n// healthy/clean, no sessions, nothing to converge — are reduced to a minimal stub\n// (id/workspace/health/branch/launchReady + branchConvergence decision scalars)\n// while \"noteworthy\" nodes (anything actionable) keep the full compact detail. On\n// top of that the detailed set is held to a serialized byte budget (highest\n// severity first); when the budget is exceeded the lowest-priority detailed nodes\n// degrade to the same minimal stub so even a mesh of all-noteworthy nodes can't\n// blow the cap. No node is ever dropped — only its detail level is reduced.\nexport const COMPACT_DETAILED_NODES_BYTE_BUDGET = 9000;\n\n// Total byte budget for the whole compact node array (detail + minimal stubs).\n// Nodes that don't fit even as a stub are folded into a counts+id-list summary so\n// the array stays bounded on pathologically large meshes; every node id is still\n// listed in foldedNodes.nodeIds, so nothing becomes undiscoverable.\n//\n// This must leave headroom for the compact payload's FIXED top-level overhead\n// (branchConvergenceSummary, staleDaemonBuild* aggregates, activeWork*/ledger/\n// scheduling summaries, sourceOfTruth/hints — ~12KB with a large stale mesh) so the\n// whole compact string stays under the MCP token cap even for an all-noteworthy mesh\n// (the contract asserted by mesh-compact-payload-budget.test.ts). That top-level\n// overhead grew as compact aggregates were added, so 13000 here let a 12-node stale\n// mesh tip the whole payload to ~25.2KB — over the 25KB budget. 11500 restores the\n// margin (nodes + overhead ≈ 24KB) while still keeping the highest-severity nodes in\n// detail and every node id discoverable (array stub or foldedNodes.nodeIds).\nexport const COMPACT_NODES_TOTAL_BYTE_BUDGET = 11500;\n\n\n// Byte budget for the whole compact `missions` array (live active/paused missions).\n// Completed/abandoned history is already folded to a counts+id summary upstream;\n// this bounds the LIVE-mission detail so the section can't grow unbounded with the\n// number of active/paused missions. Newest-active first; overflow is folded into\n// `foldedMissions` (id list) so every live mission id stays addressable.\nexport const COMPACT_MISSIONS_BYTE_BUDGET = 6000;\n\n\n// (compact node-fold helpers moved to ./mesh-compact.ts)\n\nexport function extractLaunchPayload(value: any): any {\n return findNestedPayload(value, payload => Boolean(payload?.sessionId || payload?.id || payload?.runtimeSessionId));\n}\n\nexport type MeshLaunchFailureClassification = {\n code: string;\n reason: string;\n transport: string;\n recoverable: boolean;\n retryRecommended: boolean;\n nextAction: string;\n noFallbackReason?: string;\n};\n\nexport function classifyMeshLaunchFailure(error: unknown): MeshLaunchFailureClassification {\n const message = error instanceof Error ? error.message : String(error || 'launch failed');\n const lower = message.toLowerCase();\n const p2pClassification = classifyP2pRelayFailure(error, { command: 'launch_cli' });\n if (p2pClassification.recoverable) {\n return p2pClassification;\n }\n if (lower.includes('cannot connect to daemon ipc') || lower.includes('daemon ipc command')) {\n return {\n code: 'local_ipc_unavailable',\n reason: 'local_daemon_ipc_unavailable',\n transport: 'local_ipc',\n recoverable: true,\n retryRecommended: true,\n nextAction: 'Check the local daemon IPC connection, then retry mesh_launch_session once after the daemon is reachable.',\n };\n }\n if (lower.includes('timed out') || lower.includes('timeout')) {\n return {\n code: 'mesh_transport_timeout',\n reason: 'mesh_transport_timeout',\n transport: 'mesh_transport',\n recoverable: true,\n retryRecommended: true,\n nextAction: 'Check mesh transport health, then do one bounded retry before requeueing or relaunching the task.',\n };\n }\n return {\n code: 'mesh_launch_failed',\n reason: 'provider_launch_failed',\n transport: 'mesh_transport',\n recoverable: false,\n retryRecommended: false,\n nextAction: 'Inspect the provider launch error and fix the underlying provider/configuration issue before retrying.',\n };\n}\n\nexport function buildWorktreeCleanupHint(node: LocalMeshNodeEntry): Record<string, unknown> | undefined {\n if (!node.isLocalWorktree) return undefined;\n return {\n tool: 'mesh_remove_node',\n args: { node_id: node.id, session_cleanup_mode: 'preserve' },\n hint: `If the worktree is no longer needed, remove the orphan worktree node with mesh_remove_node(node_id: \"${node.id}\").`,\n };\n}\n\nexport function buildRecoverableLaunchFailure(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n providerType: string | undefined,\n error: unknown,\n): Record<string, unknown> {\n const message = error instanceof Error ? error.message : String(error || 'launch failed');\n const classified = classifyMeshLaunchFailure(error);\n const cleanup = buildWorktreeCleanupHint(node);\n return {\n success: false,\n recoverable: classified.recoverable,\n code: classified.code,\n reason: classified.reason,\n transport: classified.transport,\n retryRecommended: classified.retryRecommended,\n nextAction: classified.nextAction,\n ...(classified.noFallbackReason ? { noFallbackReason: classified.noFallbackReason } : {}),\n error: message,\n meshId: ctx.mesh.id,\n nodeId: node.id,\n daemonId: node.daemonId,\n workspace: node.workspace,\n isLocalWorktree: node.isLocalWorktree === true,\n worktreeBranch: node.worktreeBranch,\n clonedFromNodeId: node.clonedFromNodeId,\n ...(providerType ? { resolvedProviderType: providerType } : {}),\n retryHint: `Retry mesh_launch_session(node_id: \"${node.id}\"${providerType ? `, type: \"${providerType}\"` : ''}) after daemon mesh transport/P2P is healthy.`,\n ...(cleanup ? { cleanup } : {}),\n nextStepHints: [\n `Retry mesh_launch_session(node_id: \"${node.id}\"${providerType ? `, type: \"${providerType}\"` : ''}) after checking daemon/P2P health.`,\n ...(cleanup ? [`Cleanup orphan worktree node with mesh_remove_node(node_id: \"${node.id}\") if retry is not desired.`] : []),\n 'Run mesh_status to see the degraded reason and recovery hints before redispatching work.',\n ],\n };\n}\n\nexport function recordRecoverableLaunchFailure(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n providerType: string | undefined,\n error: unknown,\n): Record<string, unknown> {\n const failure = buildRecoverableLaunchFailure(ctx, node, providerType, error);\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'recovery_attempted',\n nodeId: node.id,\n providerType,\n payload: {\n event: 'session_launch_failed',\n ...failure,\n },\n });\n } catch { /* ledger append is best-effort */ }\n return failure;\n}\n\nexport function getLatestActiveLaunchFailure(meshId: string, nodeId: string): Record<string, unknown> | null {\n const entries = readLedgerEntries(meshId, { tail: 200 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i];\n if (entry.nodeId !== nodeId) continue;\n if (entry.kind === 'session_launched' || entry.kind === 'node_removed') return null;\n if (entry.kind === 'recovery_attempted' && entry.payload?.event === 'session_launch_failed') {\n return { timestamp: entry.timestamp, ...entry.payload };\n }\n }\n return null;\n}\n\nexport type RemoteAgentDispatchResult =\n | { success: true; dispatched: true; sessionId: string; providerType?: string }\n | ({ success: false; error: string } & Record<string, unknown>);\n\nexport function buildCoordinatorP2pRelayFailure(\n error: unknown,\n context: { command: string; targetDaemonId?: string; nodeId?: string; sessionId?: string },\n): { success: false; error: string } & Record<string, unknown> {\n const payload = buildP2pRelayFailurePayload(error, {\n command: context.command,\n targetDaemonId: context.targetDaemonId,\n });\n return {\n ...payload,\n ...(context.nodeId ? { nodeId: context.nodeId } : {}),\n ...(context.sessionId ? { sessionId: context.sessionId } : {}),\n retryHint: payload.retryRecommended ? payload.nextAction : 'Do not retry as a P2P transport recovery; inspect the command/provider error first.',\n };\n}\n\n\n/**\n * For IpcTransport + remote node: resolve an active session on the node and\n * dispatch an agent_command directly via P2P relay (mesh_relay_command).\n *\n * This bypasses the local queue (which remote daemons cannot read) and sends\n * the message directly to the session running on the remote daemon.\n *\n * Returns { success, sessionId } or throws.\n */\nexport async function ipcDispatchToRemoteAgent(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n args: { session_id?: string; message: string; providerType?: string; verifiedSession?: any; meshContext?: { meshId: string; nodeId?: string; taskId?: string; coordinatorDaemonId?: string } },\n): Promise<RemoteAgentDispatchResult> {\n const transport = ctx.transport as IpcTransport;\n const daemonId = node.daemonId!;\n\n // The coordinator anchor the remote router will stamp onto the worker session\n // at dispatch time (router.ts buildMeshWorkerRelayStamp). When present, a\n // mesh-owned session that was never launch-stamped can still self-heal to\n // relay-safe — exactly like the local direct-dispatch path.\n const dispatchCoordinatorDaemonId = readString(args.meshContext?.coordinatorDaemonId) || '';\n\n let sessionId = args.session_id?.trim() || '';\n // Resolve provider type: caller arg > node policy providerPriority > empty (fuzzy fallback)\n const providerPriorityList: string[] = Array.isArray((node.policy as any)?.providerPriority)\n ? (node.policy as any).providerPriority\n : [];\n let resolvedProviderType = args.providerType?.trim() || providerPriorityList[0] || '';\n\n // Ask the remote daemon for live session truth when we need to auto-pick a\n // delegate session, or when an explicit session_id must be verified as a\n // relay-safe mesh-owned worker before we dispatch into it.\n if (sessionId && args.verifiedSession) {\n const explicitSession = args.verifiedSession;\n const relaySafety = classifyRemoteDelegateRelaySafety(explicitSession, ctx.mesh.id, node.id, dispatchCoordinatorDaemonId);\n if (relaySafety === 'unsafe_alias') {\n return buildRelayUnsafeRemoteSessionFailure(\n ctx,\n node,\n sessionId,\n resolvedProviderType || resolveSessionProviderType(explicitSession) || undefined,\n );\n }\n if (relaySafety === 'missing_anchor') {\n return buildMissingCoordinatorDaemonIdFailure(\n ctx,\n node,\n resolvedProviderType || resolveSessionProviderType(explicitSession) || undefined,\n );\n }\n // 'safe' or 'self_heal' → dispatch; the remote router stamps the relay\n // anchor from meshContext.coordinatorDaemonId when self-healing.\n if (!resolvedProviderType) {\n resolvedProviderType = resolveSessionProviderType(explicitSession);\n }\n } else if (!sessionId || args.session_id) {\n try {\n const relayResult = await transport.meshCommand(daemonId, 'get_status_metadata', {});\n const sessions = extractStatusMetadataSessions(relayResult);\n\n if (sessionId) {\n const explicitSession = sessions.find(session => readSessionRecordId(session) === sessionId);\n if (!explicitSession) {\n return {\n success: false,\n recoverable: true,\n code: 'mesh_target_session_not_found',\n reason: 'mesh_target_session_not_found',\n transport: 'mesh_transport',\n retryRecommended: true,\n meshId: ctx.mesh.id,\n nodeId: node.id,\n daemonId,\n workspace: node.workspace,\n sessionId,\n ...(resolvedProviderType ? { resolvedProviderType } : {}),\n error: `Remote session '${sessionId}' is not present in the live status for node '${node.id}'.`,\n nextAction: `Launch a fresh session with mesh_launch_session(node_id: '${node.id}'${resolvedProviderType ? `, type: '${resolvedProviderType}'` : ''}) or retry without session_id so Repo Mesh can target a live delegate session.`,\n };\n }\n const relaySafety = classifyRemoteDelegateRelaySafety(explicitSession, ctx.mesh.id, node.id, dispatchCoordinatorDaemonId);\n if (relaySafety === 'unsafe_alias') {\n return buildRelayUnsafeRemoteSessionFailure(\n ctx,\n node,\n sessionId,\n resolvedProviderType || resolveSessionProviderType(explicitSession) || undefined,\n );\n }\n if (relaySafety === 'missing_anchor') {\n return buildMissingCoordinatorDaemonIdFailure(\n ctx,\n node,\n resolvedProviderType || resolveSessionProviderType(explicitSession) || undefined,\n );\n }\n // 'safe' or 'self_heal' → dispatch; the remote router stamps the\n // relay anchor from meshContext.coordinatorDaemonId when self-healing.\n if (!resolvedProviderType) {\n resolvedProviderType = resolveSessionProviderType(explicitSession);\n }\n } else {\n // Prefer live idle sessions launched for this mesh node. Never route\n // a new task into restored/stopped session records; that produces the\n // coordinator-visible \"pending only, chat never received it\" failure.\n const targetSession = chooseDispatchableSession(sessions, resolvedProviderType, ctx.mesh.id, node.id, dispatchCoordinatorDaemonId);\n\n if (targetSession?.id || targetSession?.sessionId) {\n sessionId = targetSession.id || targetSession.sessionId;\n if (!resolvedProviderType) {\n resolvedProviderType = resolveSessionProviderType(targetSession);\n }\n }\n }\n } catch (e: any) {\n if (sessionId) {\n return {\n ...buildCoordinatorP2pRelayFailure(e, {\n command: 'get_status_metadata',\n targetDaemonId: daemonId,\n nodeId: node.id,\n sessionId,\n }),\n success: false,\n error: `Cannot verify remote session '${sessionId}' before dispatch: ${e?.message || String(e)}`,\n };\n }\n // fall through — will attempt dispatch with just providerType (fuzzy)\n }\n }\n\n // agent_command requires agentType — fail if we cannot determine provider type\n if (!resolvedProviderType) {\n return { success: false, error: `Cannot dispatch to remote node '${node.id}': providerType unknown. Set providerPriority on the node policy or call mesh_launch_session first.` };\n }\n\n try {\n const dispatchResult = await transport.meshCommand(daemonId, 'agent_command', {\n ...(sessionId ? { targetSessionId: sessionId } : {}),\n agentType: resolvedProviderType,\n cliType: resolvedProviderType,\n action: 'send_chat',\n message: args.message,\n // WTCLAIM (B): carry the node workspace so a sessionless dispatch can be\n // scoped to THIS node's session on the worker (findAdapter dir match /\n // findMeshNodeAdapter). Without it, a worker hosting both a base node and a\n // cloned worktree node (same daemonId) would fall through to a provider-only\n // fuzzy match and could land worktree work on the base session.\n ...(node.workspace ? { dir: node.workspace } : {}),\n ...(args.meshContext ? { meshContext: args.meshContext } : {}),\n });\n const dispatchPayload = unwrapCommandPayload(dispatchResult);\n if (dispatchPayload?.success === false || dispatchResult?.success === false) {\n const source = dispatchPayload?.success === false ? dispatchPayload : dispatchResult;\n const errorMessage = dispatchPayload?.error || dispatchResult?.error || 'agent_command rejected the task';\n return {\n ...buildCoordinatorP2pRelayFailure(source?.error || errorMessage, {\n command: 'agent_command',\n targetDaemonId: daemonId,\n nodeId: node.id,\n sessionId,\n }),\n ...(source && typeof source === 'object' ? source : {}),\n success: false,\n error: `P2P dispatch failed: ${errorMessage}`,\n };\n }\n // Do NOT fall back to resolvedProviderType for sessionId: a sessionless\n // dispatch (no targetSessionId above) lets the worker pick/create the real\n // session, so the provider type ('claude-cli', …) is NOT a session id.\n // Returning it here used to poison assigned_session_id downstream, breaking\n // findAssignedBySession (provider type vs real session id) and orphaning the\n // task_completed match. Leave it empty so completion matching falls back to\n // taskId via the meshContext.taskId carried in the dispatch.\n return { success: true, dispatched: true, sessionId: sessionId || '', providerType: resolvedProviderType };\n } catch (e: any) {\n const errorMessage = e?.message || String(e);\n return {\n ...buildCoordinatorP2pRelayFailure(e, {\n command: 'agent_command',\n targetDaemonId: daemonId,\n nodeId: node.id,\n sessionId,\n }),\n error: `P2P dispatch failed: ${errorMessage}`,\n };\n }\n}\n\nexport function meshSessionCacheKey(nodeId: string, runtimeSessionId: string): string {\n return `${nodeId}:${runtimeSessionId}`;\n}\n\nexport function rememberMeshSessionProviderMetadata(\n nodeId: string | undefined,\n runtimeSessionId: string | undefined,\n metadata: MeshSessionProviderMetadata,\n): void {\n const keyNodeId = readString(nodeId);\n const keySessionId = readString(runtimeSessionId);\n if (!keyNodeId || !keySessionId) return;\n const providerType = readString(metadata.providerType);\n const providerSessionId = readString(metadata.providerSessionId);\n if (!providerType && !providerSessionId) return;\n const existing = getSessionMetadata(meshSessionCacheKey(keyNodeId, keySessionId)) || { providerType: '' };\n meshSessionProviderMetadata.set(meshSessionCacheKey(keyNodeId, keySessionId), {\n providerType: providerType || existing.providerType,\n providerSessionId: providerSessionId || existing.providerSessionId,\n expiresAt: Date.now() + SESSION_PROVIDER_METADATA_TTL_MS,\n });\n}\n\nexport function rememberMeshSessionProviderMetadataFromEvent(event: any): void {\n const metadataEvent = event?.metadataEvent && typeof event.metadataEvent === 'object'\n ? event.metadataEvent as Record<string, unknown>\n : event && typeof event === 'object'\n ? event as Record<string, unknown>\n : {};\n const nodeId = readString(event?.nodeId) || readString(metadataEvent.nodeId) || readString(metadataEvent.meshNodeId);\n const sessionId = readString(metadataEvent.targetSessionId)\n || readString(metadataEvent.sessionId)\n || readString(metadataEvent.instanceId)\n || readString(event?.sessionId);\n rememberMeshSessionProviderMetadata(nodeId, sessionId, {\n providerType: readString(metadataEvent.providerType) || readString(event?.providerType) || '',\n providerSessionId: readString(metadataEvent.providerSessionId) || readString(event?.providerSessionId),\n });\n}\n\nexport function resolveMeshSessionProviderMetadataFromLedger(\n ctx: MeshContext,\n nodeId: string,\n runtimeSessionId: string,\n): MeshSessionProviderMetadata | undefined {\n const entries = readLedgerEntries(ctx.mesh.id, { tail: 50 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i];\n const payload = entry.payload && typeof entry.payload === 'object' && !Array.isArray(entry.payload)\n ? entry.payload as Record<string, unknown>\n : {};\n const entryNodeId = readString(entry.nodeId) || readString(payload.nodeId) || readString(payload.meshNodeId);\n if (entryNodeId && entryNodeId !== nodeId) continue;\n const entrySessionId = readString(entry.sessionId)\n || readString(payload.targetSessionId)\n || readString(payload.sessionId)\n || readString(payload.instanceId);\n if (entrySessionId !== runtimeSessionId) continue;\n const providerType = readString(entry.providerType) || readString(payload.providerType);\n const completionDiagnostic = payload.completionDiagnostic && typeof payload.completionDiagnostic === 'object' && !Array.isArray(payload.completionDiagnostic)\n ? payload.completionDiagnostic as Record<string, unknown>\n : {};\n const metadataEvent = payload.metadataEvent && typeof payload.metadataEvent === 'object' && !Array.isArray(payload.metadataEvent)\n ? payload.metadataEvent as Record<string, unknown>\n : {};\n const providerSessionId = readString(payload.providerSessionId)\n || readString(completionDiagnostic.providerSessionId)\n || readString(metadataEvent.providerSessionId);\n if (providerType || providerSessionId) {\n return { providerType: providerType || '', providerSessionId };\n }\n }\n return undefined;\n}\n\nexport function resolveMeshSessionProviderMetadata(\n ctx: MeshContext,\n nodeId: string,\n runtimeSessionId: string,\n): MeshSessionProviderMetadata | undefined {\n const cached = getSessionMetadata(meshSessionCacheKey(nodeId, runtimeSessionId));\n if (cached?.providerType || cached?.providerSessionId) return cached;\n const fromLedger = resolveMeshSessionProviderMetadataFromLedger(ctx, nodeId, runtimeSessionId);\n if (fromLedger) rememberMeshSessionProviderMetadata(nodeId, runtimeSessionId, fromLedger);\n return fromLedger;\n}\n\nexport function countUncommittedChanges(status: any): number {\n if (typeof status?.uncommittedChanges === 'number') return status.uncommittedChanges;\n const keys = ['staged', 'modified', 'untracked', 'deleted', 'renamed'];\n const counted = keys.reduce((sum, key) => sum + (Number.isFinite(Number(status?.[key])) ? Number(status[key]) : 0), 0);\n const conflicts = Array.isArray(status?.conflictFiles) ? status.conflictFiles.length : (status?.hasConflicts ? 1 : 0);\n return counted + conflicts;\n}\n\nexport function isGitStatusDirty(status: any): boolean {\n if (typeof status?.isDirty === 'boolean') return status.isDirty;\n if (typeof status?.dirty === 'boolean') return status.dirty;\n if (Array.isArray(status?.submodules) && status.submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return true;\n return countUncommittedChanges(status) > 0;\n}\n\n\n// Large structured fields that bloat refine/batch ledger entries (each can carry a\n// full per-node validation plan + suggested config). In compact mode these are\n// summarized rather than dropped — full detail stays available via verbose=true /\n// mesh_reconcile_ledger.\n// (large-value compaction utils moved to ./mesh-tool-shared.ts)\n\nexport function slimLedgerPayload(payload: Record<string, unknown>): Record<string, unknown> {\n const slim: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(payload)) {\n if (k === 'message' || k === 'taskSummary') {\n slim[k] = typeof v === 'string' && v.length > 200 ? v.slice(0, 200) + '…' : v;\n } else if (k === 'evidence' || k === 'workerResult' || k === 'gitStatus' || k === 'validationResults') {\n // Skip large nested evidence objects — accessible via mesh_reconcile_ledger if needed.\n } else if (k === 'finalSummary') {\n slim[k] = typeof v === 'string' && v.length > 300 ? v.slice(0, 300) + '…' : v;\n } else if (LARGE_LEDGER_FIELD_KEYS.has(k)) {\n // plan / validationPlan / suggestedConfig / nested payload — these are the\n // refine_batch task_dispatched offenders that blow past the token limit.\n slim[k] = summarizeLargeLedgerField(k, v);\n } else {\n // Primary, key-agnostic defense: elide any oversized nested evidence blob\n // (validationSummary, result, patchEquivalence, submoduleReachability, and\n // any future large key) by serialized byte size. Small scalars/short fields\n // are returned as-is.\n slim[k] = elideLargeNestedValue(k, v);\n }\n }\n return slim;\n}\n\nexport function readRelatedRepos(node: LocalMeshNodeEntry): RepoMeshRelatedRepo[] {\n const raw = Array.isArray((node as any).relatedRepos)\n ? (node as any).relatedRepos\n : Array.isArray((node.policy as any)?.relatedRepos)\n ? (node.policy as any).relatedRepos\n : [];\n\n return raw\n .map((entry: any) => ({\n label: typeof entry?.label === 'string' ? entry.label.trim() : '',\n workspace: typeof entry?.workspace === 'string' ? entry.workspace.trim() : '',\n }))\n .filter((entry: RepoMeshRelatedRepo) => Boolean(entry.label && entry.workspace));\n}\n\nexport function summarizeRelatedRepoStatus(repo: RepoMeshRelatedRepo, status: any): Record<string, unknown> {\n const dirty = isGitStatusDirty(status);\n return {\n label: repo.label,\n workspace: repo.workspace,\n isGitRepo: status?.isGitRepo === true,\n branch: status?.branch ?? null,\n upstream: status?.upstream ?? null,\n upstreamStatus: typeof status?.upstreamStatus === 'string' ? status.upstreamStatus : (status?.upstream ? 'unchecked' : 'no_upstream'),\n upstreamFetchedAt: Number.isFinite(Number(status?.upstreamFetchedAt)) ? Number(status.upstreamFetchedAt) : null,\n upstreamFetchError: typeof status?.upstreamFetchError === 'string' ? status.upstreamFetchError : null,\n ahead: Number.isFinite(Number(status?.ahead)) ? Number(status.ahead) : 0,\n behind: Number.isFinite(Number(status?.behind)) ? Number(status.behind) : 0,\n dirty,\n uncommittedChanges: countUncommittedChanges(status),\n head: status?.headCommit ?? null,\n lastCommitSummary: status?.headMessage ?? null,\n ...(status?.reason ? { reason: status.reason } : {}),\n ...(status?.error ? { error: status.error } : {}),\n };\n}\n\nexport async function collectRelatedRepoStatuses(ctx: MeshContext, node: LocalMeshNodeEntry): Promise<Array<Record<string, unknown>>> {\n const relatedRepos = readRelatedRepos(node);\n if (!relatedRepos.length) return [];\n\n const results: Array<Record<string, unknown>> = [];\n for (const repo of relatedRepos) {\n try {\n // OFFLINE-NODE-STATUS-REFRESH: related-repo status is part of the mesh_status\n // per-node assembly — mark it status-origin for the SHORT connect-wait budget.\n const statusResult = await commandForNode(ctx, node, 'git_status', { workspace: repo.workspace, refreshUpstream: true }, { statusProbe: true });\n const status = extractGitStatus(statusResult);\n results.push(summarizeRelatedRepoStatus(repo, status));\n } catch (e: any) {\n results.push({\n label: repo.label,\n workspace: repo.workspace,\n error: e?.message || 'related repo status failed',\n });\n }\n }\n return results;\n}\n\nexport function findNodeByWorkspace(mesh: LocalMeshEntry, workspace: string): LocalMeshNodeEntry {\n const node = mesh.nodes.find(n => n.workspace === workspace);\n if (!node) throw new Error(`Workspace '${workspace}' is not a member of mesh '${mesh.name}'`);\n return node;\n}\n\nexport function readProviderPriority(policy: unknown): string[] {\n const raw = (policy as any)?.providerPriority;\n return Array.isArray(raw)\n ? raw.map((type: unknown) => typeof type === 'string' ? type.trim() : '').filter(Boolean)\n : [];\n}\n\n/**\n * Ordered, de-duplicated provider types a node can launch — every provider it could\n * be asked to run. Reads `policy.slots` (the SSOT — ORCHESTRATION_NODE_SLOTS.md),\n * unioned with the legacy `policy.providerPriority`. Used to ENUMERATE per-provider\n * capability-tag sets for observability (buildNodeCapabilityExposure). Note: the\n * mesh_launch_session fail-closed GATE deliberately checks slots ALONE (not this\n * union) — providerPriority is a preference hint, not a capability whitelist.\n */\nexport function readNodeSupportedProviders(policy: unknown): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n const push = (type: unknown) => {\n const trimmed = typeof type === 'string' ? type.trim() : '';\n if (!trimmed || seen.has(trimmed)) return;\n seen.add(trimmed);\n out.push(trimmed);\n };\n for (const slot of normalizeNodeCapabilitySlots((policy as any)?.slots)) push(slot.provider);\n for (const type of readProviderPriority(policy)) push(type);\n return out;\n}\n\n\n/**\n * Surface the capability tags a node can match against required_tags routing,\n * plus its operator-defined capability labels. Computed via the same\n * buildMeshNodeCapabilityTags the queue/dispatch matcher uses, so what the\n * coordinator sees is exactly what routing will match.\n *\n * - capabilityTags: the representative tag set (os=/arch=/converge= plus the\n * first declared provider's provider= tag and any worktree= tag). This is\n * what nodeSatisfiesRequiredTags compares against when no provider is pinned.\n * - capabilityTagsByProvider: per-provider tag sets, one per entry in the\n * node's providerPriority — the provider= tag differs by provider, so a tag\n * like provider=codex-cli only matches when that provider is launchable here.\n * - capabilities: the operator-defined capability labels persisted on the node\n * (already folded into capabilityTags; surfaced raw so operators can see\n * which tags they configured vs. which are auto-advertised).\n *\n * Note: os=/arch= reflect the TARGET node's own machine — for remote member\n * nodes these come from the platform/arch the member daemon stamped into its\n * node record at join time (node.userOverrides.platform/arch), falling back to\n * the local process platform/arch only for the coordinator's own / local\n * worktree nodes. This matches the matcher's behavior, so the exposed set is a\n * faithful preview of routing, not an independent re-derivation.\n */\nexport function buildNodeCapabilityExposure(node: LocalMeshNodeEntry): {\n capabilityTags: string[];\n capabilityTagsByProvider?: Record<string, string[]>;\n capabilities?: string[];\n} {\n // Enumerate EVERY provider the node can launch (policy.slots is the single source\n // of truth, else legacy providerPriority) — not just providerPriority — so the\n // per-provider tag sets cover a provider that lives in slots but is not the first\n // priority entry (e.g. cursor-cli). The representative capabilityTags already\n // advertises a provider= tag for each of these (buildMeshNodeCapabilityTags).\n const providers = readNodeSupportedProviders(node.policy);\n const capabilityTags = buildMeshNodeCapabilityTags(node);\n const exposure: {\n capabilityTags: string[];\n capabilityTagsByProvider?: Record<string, string[]>;\n capabilities?: string[];\n } = { capabilityTags };\n if (providers.length) {\n const byProvider: Record<string, string[]> = {};\n for (const provider of providers) {\n byProvider[provider] = buildMeshNodeCapabilityTags(node, provider);\n }\n exposure.capabilityTagsByProvider = byProvider;\n }\n const capabilities = Array.isArray(node.capabilities)\n ? node.capabilities.filter((tag): tag is string => typeof tag === 'string' && !!tag.trim())\n : [];\n if (capabilities.length) exposure.capabilities = capabilities;\n return exposure;\n}\n\nexport function readSpawnedSessionVisibility(policy: unknown): 'visible' | 'hidden' {\n return (policy as any)?.spawnedSessionVisibility === 'hidden' ? 'hidden' : 'visible';\n}\n\nexport function missingProviderPriorityMessage(nodeId: string): string {\n return `Node '${nodeId}' has no providerPriority policy; pass type explicitly or configure node.policy.providerPriority`;\n}\n\nexport function getNodeLaunchReadiness(node: LocalMeshNodeEntry): Record<string, unknown> {\n const bootstrap = (node as any).worktreeBootstrap;\n if ((node as any).isLocalWorktree && bootstrap?.status === 'failed' && bootstrap?.required !== false) {\n return {\n providerPriority: readProviderPriority(node.policy),\n launchReady: false,\n launchBlockedReason: 'worktree_bootstrap_failed',\n launchBlockedMessage: typeof bootstrap.error === 'string' && bootstrap.error.trim()\n ? bootstrap.error.trim()\n : 'Required worktree bootstrap failed; resolve it before launching an agent into this node.',\n worktreeBootstrap: bootstrap,\n };\n }\n\n const providerPriority = readProviderPriority(node.policy);\n if (providerPriority.length) {\n return {\n providerPriority,\n launchReady: true,\n };\n }\n\n return {\n providerPriority,\n launchReady: false,\n launchBlockedReason: 'missing_provider_priority',\n launchBlockedMessage: missingProviderPriorityMessage(node.id),\n };\n}\n\nexport function getWorktreeBootstrapLaunchBlock(node: LocalMeshNodeEntry, meshPolicy?: unknown): Record<string, unknown> | undefined {\n if (!(node as any).isLocalWorktree) return undefined;\n const bootstrap = (node as any).worktreeBootstrap;\n\n // M2-4 (opt-in): with policy.requireBootstrapBeforeLaunch, any non-ready\n // bootstrap state blocks the launch fail-closed - not just failures.\n const requireReady = !!(meshPolicy && typeof meshPolicy === 'object'\n && (meshPolicy as Record<string, unknown>).requireBootstrapBeforeLaunch === true);\n if (requireReady && bootstrap?.status !== 'ready') {\n return {\n success: false,\n code: 'bootstrap_not_ready',\n error: `Node '${node.id}' bootstrap state is '${bootstrap?.status ?? 'unknown'}' and mesh policy requireBootstrapBeforeLaunch is enabled.`,\n nodeId: node.id,\n worktreeBootstrap: bootstrap ?? null,\n recoveryHint: 'Run the worktree bootstrap (clone runOnClone or a refine with bootstrap inherit) until the node reports ready, or disable requireBootstrapBeforeLaunch.',\n };\n }\n\n if (bootstrap?.status !== 'failed' || bootstrap?.required === false) return undefined;\n return {\n success: false,\n code: 'worktree_bootstrap_failed',\n error: typeof bootstrap.error === 'string' && bootstrap.error.trim()\n ? bootstrap.error.trim()\n : `Node '${node.id}' has a failed required worktree bootstrap.`,\n nodeId: node.id,\n worktreeBootstrap: bootstrap,\n recoveryHint: 'Fix the configured worktree bootstrap command or remove/recreate the worktree node before launching an agent.',\n };\n}\n\nexport async function collectLiveStatusSessions(ctx: MeshContext, node: LocalMeshNodeEntry): Promise<any[]> {\n try {\n const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {});\n return extractStatusMetadataSessions(statusResult);\n } catch {\n return [];\n }\n}\n\n\n/**\n * One get_status_metadata probe → both the live session list and the daemon's\n * build stamp. Used by mesh_status so a single daemon-wide probe yields the\n * sessions AND the `daemonBuild` field (commit/version of the running daemon).\n */\nexport async function collectLiveStatusProbe(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n): Promise<{ sessions: any[]; daemonBuild?: { commit: string; commitShort: string; version: string; builtAt?: string } }> {\n try {\n // OFFLINE-NODE-STATUS-REFRESH: part of the mesh_status per-node assembly — mark it\n // status-origin so the relay to an offline peer uses the SHORT connect-wait budget.\n const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {}, { statusProbe: true });\n return {\n sessions: extractStatusMetadataSessions(statusResult),\n daemonBuild: extractDaemonBuildInfo(statusResult),\n };\n } catch {\n return { sessions: [] };\n }\n}\n\nexport function extractDaemonBuildInfo(value: any): { commit: string; commitShort: string; version: string; builtAt?: string } | undefined {\n const payload = unwrapCommandPayload(value);\n const build = payload?.daemonBuild && typeof payload.daemonBuild === 'object'\n ? payload.daemonBuild\n : (value?.daemonBuild && typeof value.daemonBuild === 'object' ? value.daemonBuild : undefined);\n if (!build) return undefined;\n const commit = readString(build.commit);\n if (!commit) return undefined;\n return {\n commit,\n commitShort: readString(build.commitShort) || commit.slice(0, 7),\n version: readString(build.version) || 'unknown',\n ...(readString(build.builtAt) ? { builtAt: readString(build.builtAt) } : {}),\n };\n}\n\nexport async function collectMeshViewQueueNodesWithLiveSessions(ctx: MeshContext): Promise<any[]> {\n const nodes = await Promise.all(ctx.mesh.nodes.map(async (node) => {\n const liveSessions = await collectLiveStatusSessions(ctx, node);\n return liveSessions.length > 0\n ? { ...node, sessions: liveSessions }\n : node;\n }));\n return nodes;\n}\n\nexport function buildBranchConvergence(\n mesh: LocalMeshEntry,\n node: LocalMeshNodeEntry,\n status: any,\n dirty: boolean,\n uncommittedChanges: number,\n): Record<string, unknown> {\n const defaultBranch = readString(mesh.defaultBranch) ?? 'main';\n const branch = readString(status?.branch) ?? readString(node.worktreeBranch) ?? null;\n const ahead = readNumeric(status?.ahead);\n const behind = readNumeric(status?.behind);\n const upstream = readString(status?.upstream) ?? null;\n const upstreamStatus = readString(status?.upstreamStatus) ?? (upstream ? 'unchecked' : 'no_upstream');\n const hasConflicts = status?.hasConflicts === true || (Array.isArray(status?.conflictFiles) && status.conflictFiles.length > 0);\n const base = {\n defaultBranch,\n branch,\n upstream,\n upstreamStatus,\n ahead,\n behind,\n isWorktree: node.isLocalWorktree === true,\n isDefaultBranch: branch === defaultBranch,\n };\n\n if (status?.isGitRepo !== true) {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'git_status_unavailable',\n nextStep: `Resolve git status for node '${node.id}' before marking the task complete.`,\n };\n }\n\n if (!branch) {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'branch_unknown',\n nextStep: `Inspect node '${node.id}' git branch before deciding whether it is merged to ${defaultBranch}.`,\n };\n }\n\n if (hasConflicts || dirty || uncommittedChanges > 0) {\n return {\n ...base,\n status: 'not_mergeable',\n needsConvergence: true,\n reason: hasConflicts ? 'conflicts_present' : 'dirty_workspace',\n nextStep: `Commit, checkpoint, or resolve node '${node.id}' before any main convergence step.`,\n };\n }\n\n if (branch === defaultBranch) {\n if (upstream && upstreamStatus !== 'fresh') {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'default_branch_upstream_unverified',\n nextStep: `Refresh ${defaultBranch}'s upstream refs or resolve the fetch failure before declaring convergence complete for node '${node.id}'.`,\n };\n }\n if (ahead > 0 || behind > 0) {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'default_branch_not_even_with_upstream',\n nextStep: `Bring ${defaultBranch} even with its upstream before declaring convergence complete.`,\n };\n }\n return {\n ...base,\n status: 'merged_to_main',\n needsConvergence: false,\n reason: 'clean_default_branch',\n nextStep: null,\n };\n }\n\n if (node.isLocalWorktree) {\n return {\n ...base,\n status: 'cleanup_candidate',\n needsConvergence: true,\n reason: 'clean_non_default_worktree_branch',\n nextStep: `Run mesh_refine_node(node_id: \"${node.id}\") or explicitly classify this worktree as blocked_review/not_mergeable before ending the task.`,\n };\n }\n\n if (upstream && upstreamStatus !== 'fresh') {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: 'feature_branch_upstream_unverified',\n nextStep: `Refresh branch '${branch}' upstream refs or resolve the fetch failure before deciding whether it is ready to merge into ${defaultBranch}.`,\n };\n }\n\n if (!upstream || ahead > 0 || behind > 0) {\n return {\n ...base,\n status: 'blocked_review',\n needsConvergence: true,\n reason: !upstream ? 'feature_branch_missing_upstream' : 'feature_branch_not_even_with_upstream',\n nextStep: `Push or reconcile branch '${branch}', then merge it into ${defaultBranch} or mark it not_mergeable with a reason.`,\n };\n }\n\n return {\n ...base,\n status: 'pushed_feature_branch_needs_merge',\n needsConvergence: true,\n reason: 'clean_non_default_branch',\n nextStep: `Review and merge branch '${branch}' into ${defaultBranch}; do not report the task as fully complete while it remains off main.`,\n };\n}\n\n\n// In compact mode the per-node followUp rows are capped so this summary can't grow\n// unbounded with node count; the dropped rows are folded into a by-status count and\n// the full list stays available via verbose.\nexport const COMPACT_MAX_CONVERGENCE_FOLLOWUPS = 12;\n\nexport function summarizeBranchConvergence(nodes: any[], compact = false): Record<string, unknown> {\n const allFollowUps = nodes\n .filter(node => node?.branchConvergence?.needsConvergence === true)\n .map(node => ({\n nodeId: node.nodeId,\n // workspace is a long absolute path redundant with nodeId — drop it in\n // compact mode to keep this summary bounded.\n ...(compact ? {} : { workspace: node.workspace }),\n branch: node.branchConvergence.branch,\n status: node.branchConvergence.status,\n reason: node.branchConvergence.reason,\n // The per-node nextStep is long prose that repeats node ids/branch names.\n // In compact mode drop it (the status+reason carry the actionable signal;\n // verbose still surfaces the full nextStep) so this summary stays bounded\n // as node count grows.\n ...(compact ? {} : { nextStep: node.branchConvergence.nextStep }),\n }));\n\n const byStatus: Record<string, number> = {};\n for (const f of allFollowUps) {\n const s = typeof f.status === 'string' ? f.status : 'unknown';\n byStatus[s] = (byStatus[s] ?? 0) + 1;\n }\n\n const followUps = compact ? allFollowUps.slice(0, COMPACT_MAX_CONVERGENCE_FOLLOWUPS) : allFollowUps;\n const omitted = allFollowUps.length - followUps.length;\n\n return {\n needsFollowUp: allFollowUps.length > 0,\n unresolvedCount: allFollowUps.length,\n byStatus,\n requiredFinalStates: ['merged_to_main', 'pushed_feature_branch_needs_merge', 'blocked_review', 'cleanup_candidate', 'not_mergeable'],\n followUps,\n ...(omitted > 0 ? { followUpsOmitted: omitted, followUpsHint: 'Per-node followUp rows are capped in compact mode; counts above are complete. Use verbose=true for the full list.' } : {}),\n };\n}\n\nexport async function commandForNode(\n ctx: MeshContext,\n node: LocalMeshNodeEntry,\n command: string,\n args: Record<string, unknown> = {},\n opts?: { statusProbe?: boolean },\n): Promise<any> {\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n\n if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {\n // OFFLINE-NODE-STATUS-REFRESH: a status-origin probe (explicit_refresh /\n // mesh_status) stamps the marker into the relayed args so the daemon-cloud\n // relay handler grants the SHORT connect-wait budget — an offline peer is\n // rejected in ~seconds instead of blocking the relay for the full 90s connect\n // deadline. A local-transport call needs no marker (no relay / no connect wait).\n const relayedArgs = opts?.statusProbe ? withStatusProbeMarker(args) : args;\n return ctx.transport.meshCommand(node.daemonId, command, relayedArgs);\n }\n return ctx.transport.command(command, args);\n}\n\nexport function normalizePendingMeshCoordinatorEvents(value: any): any[] {\n const payload = unwrapCommandPayload(value);\n const events = Array.isArray(payload?.events)\n ? payload.events\n : Array.isArray(value?.events)\n ? value.events\n : [];\n return events.filter((event: unknown) => event && typeof event === 'object');\n}\n\nexport function buildMeshForwardPayloadFromPendingEvent(event: any): Record<string, unknown> {\n const metadataEvent = event?.metadataEvent && typeof event.metadataEvent === 'object'\n ? event.metadataEvent as Record<string, unknown>\n : {};\n return {\n event: readString(event?.event),\n meshId: readString(event?.meshId),\n nodeId: readString(event?.nodeId) || readString(metadataEvent.meshNodeId),\n workspace: readString(event?.workspace) || readString(metadataEvent.workspace),\n targetSessionId: readString(metadataEvent.targetSessionId) || readString(metadataEvent.sessionId) || readString(metadataEvent.instanceId),\n providerType: readString(metadataEvent.providerType),\n providerSessionId: readString(metadataEvent.providerSessionId),\n finalSummary: readString(metadataEvent.finalSummary) || readString(metadataEvent.summary),\n jobId: readString(metadataEvent.jobId),\n interactionId: readString(metadataEvent.interactionId),\n status: readString(metadataEvent.status),\n targetDaemonId: readString(metadataEvent.targetDaemonId),\n startedAt: readString(metadataEvent.startedAt),\n completedAt: readString(metadataEvent.completedAt),\n retryOfJobId: readString(metadataEvent.retryOfJobId),\n ...(metadataEvent.result && typeof metadataEvent.result === 'object' && !Array.isArray(metadataEvent.result) ? { result: metadataEvent.result } : {}),\n ...(metadataEvent.intentional === true ? { intentional: true } : {}),\n ...(metadataEvent.intentionalStop === true ? { intentionalStop: true } : {}),\n ...(metadataEvent.operatorCleanup === true ? { operatorCleanup: true } : {}),\n ...(readString(metadataEvent.reason) ? { reason: readString(metadataEvent.reason) } : {}),\n ...(readString(metadataEvent.stopReason) ? { stopReason: readString(metadataEvent.stopReason) } : {}),\n ...(readString(metadataEvent.cleanupReason) ? { cleanupReason: readString(metadataEvent.cleanupReason) } : {}),\n ...(readString(metadataEvent.source) ? { source: readString(metadataEvent.source) } : {}),\n // T4 (B3b): carry the v2 envelope across the P2P relay so a remote worker's\n // completion pulled by an MCP/LLM coordinator re-forwards with its ORIGINAL\n // eventId (idempotency) and unicast routing intact, matching the reconcile-loop\n // relay path (buildForwardPayloadFromPending). Spread LAST so the authoritative\n // envelope always wins. Empty for a v1 event (version-skew safe).\n ...serializeV2EnvelopeToWire(event as any),\n };\n}\n\nexport async function drainCoordinatorPendingEvents(\n ctx: MeshContext,\n opts?: { nodeIds?: string[] },\n): Promise<any[]> {\n const requestedNodeIds = opts?.nodeIds?.length ? new Set(opts.nodeIds) : null;\n const matchesCurrentMesh = (event: any) => readString(event?.meshId) === ctx.mesh.id;\n\n if (ctx.transport instanceof IpcTransport) {\n const transport = ctx.transport;\n const surfacedEvents: any[] = [];\n const coordinatorDaemonId = readString(ctx.localDaemonId);\n const pendingEventArgs = {\n meshId: ctx.mesh.id,\n ...(coordinatorDaemonId ? { coordinatorDaemonId } : {}),\n };\n // SELF-COORDINATOR INBOX LEVEL-DRAIN (Defect 2): this LOCAL drain is the coordinator\n // reading its OWN inbox — the drained events return in this tool call's RESULT and are\n // surfaced to the LLM directly (a lossless data-queue surface), so the daemon must NOT\n // hold it while the local CLI coordinator is busy. Scoped to the local drain only; the\n // remote-node pulls below keep the default (reconcile-owned) delivery.\n const localPendingEventArgs = { ...pendingEventArgs, selfCoordinatorInboxRead: true };\n\n // Drain THIS daemon's local pending queue and route each event to its delivery surface.\n //\n // NOTIF-DROP (drain-without-inject) fix: when this daemon has NO live CLI coordinator\n // for the mesh (a pure stdio MCP/LLM coordinator), the MCP tool result is the ONLY\n // surface. Re-forwarding the event via mesh_forward_event then just RE-QUEUES it\n // (injectMeshSystemMessage has no live CLI session to inject into), so the completion\n // loops in the queue at drained=0 and never reaches the LLM — the exact single-event\n // loss observed for a daemon_reconcile_transcript_completion consumed while the\n // coordinator was busy. In that case we surface the drained events to the LLM directly\n // (the event's coordinator-side state — task_completed ledger etc. — was already applied\n // when it was first queued, so skipping the redundant re-forward loses nothing).\n //\n // When a live CLI coordinator DOES exist, the reconcile loop owns PTY delivery, so keep\n // the existing forward path (and only surface as a fallback when the forward itself\n // throws). hasLiveCliCoordinator rides the get_pending_mesh_events response for exactly\n // this decision. The remote-node pull below is unchanged — its forward re-homes a remote\n // worker's event into the local queue, which the second local drain then surfaces.\n const drainLocalToSurface = async (): Promise<void> => {\n const raw = await transport.command('get_pending_mesh_events', localPendingEventArgs) as any;\n const payloadRaw = unwrapCommandPayload(raw);\n // T6 (B3c): capture the enforce/backstop counters the daemon rode on this\n // local drain so mesh_status can surface them (see MeshContext).\n const counters = payloadRaw?.meshProtocolV2Counters ?? raw?.meshProtocolV2Counters;\n if (counters && typeof counters === 'object') {\n ctx.lastMeshProtocolV2Counters = counters as MeshProtocolV2CountersSnapshot;\n }\n const hasLiveCliCoordinator = payloadRaw?.hasLiveCliCoordinator === true\n || raw?.hasLiveCliCoordinator === true;\n // SELF-COORDINATOR INBOX LEVEL-DRAIN (Defect 2): the daemon relaxed the busy-coordinator\n // hold because this is the self-coordinator's own inbox read, and it flagged the events\n // as surfaced through THIS tool result. Surface them directly to the LLM — do NOT\n // re-forward into the (busy) live PTY (the lossy drain-without-inject path). Without the\n // flag, delivery is unchanged: forward when a live CLI coordinator owns PTY delivery.\n const surfacedForSelfCoordinator = payloadRaw?.surfacedForSelfCoordinator === true\n || raw?.surfacedForSelfCoordinator === true;\n const localEvents = normalizePendingMeshCoordinatorEvents(raw).filter(matchesCurrentMesh);\n for (const event of localEvents) {\n const payload = buildMeshForwardPayloadFromPendingEvent(event);\n if (!payload.event || !payload.meshId) continue;\n if (!hasLiveCliCoordinator || surfacedForSelfCoordinator) {\n // Pure-MCP coordinator, OR the self-coordinator's own busy inbox read: the LLM\n // tool result is the surface. Do NOT re-forward (that re-queues with no free PTY\n // → the drain-without-inject loop / the ~59s self-coordinator strand).\n rememberMeshSessionProviderMetadataFromEvent({ ...event, metadataEvent: payload });\n surfacedEvents.push(event);\n continue;\n }\n let injected = false;\n try {\n await transport.command('mesh_forward_event', payload);\n injected = true;\n } catch { /* best-effort */ }\n rememberMeshSessionProviderMetadataFromEvent({ ...event, metadataEvent: payload });\n if (!injected) surfacedEvents.push(event);\n }\n };\n\n try {\n await drainLocalToSurface();\n } catch {\n // Non-fatal: pending events are best-effort.\n }\n\n for (const node of ctx.mesh.nodes) {\n if (!node.daemonId || isLocalControlPlaneNode(ctx, node)) continue;\n if (requestedNodeIds && !requestedNodeIds.has(node.id)) continue;\n\n try {\n const remoteEvents = normalizePendingMeshCoordinatorEvents(\n await transport.meshCommand(node.daemonId, 'get_pending_mesh_events', pendingEventArgs),\n ).filter(matchesCurrentMesh);\n if (remoteEvents.length === 0) continue;\n\n for (const event of remoteEvents) {\n const payload = buildMeshForwardPayloadFromPendingEvent(event);\n if (!payload.event || !payload.meshId) continue;\n await transport.command('mesh_forward_event', payload);\n rememberMeshSessionProviderMetadataFromEvent({ ...event, metadataEvent: payload });\n }\n } catch {\n // Non-fatal: remote pending-event recovery is best-effort.\n }\n }\n\n try {\n await drainLocalToSurface();\n } catch {\n // Non-fatal: pending events are best-effort.\n }\n\n return surfacedEvents;\n }\n\n // (B3) Pass localDaemonId so unicast events targeted at other\n // coordinators are skipped (and requeued) instead of being silently\n // consumed by this MCP. drainPendingMeshCoordinatorEvents already\n // accepts the second arg in the base; we were the missing wiring.\n //\n // COORD-EVENT-MISROUTE (defense-in-depth, session filter): thread THIS coordinator's own\n // sessionId into the drainer identity so identityDeliversTo can exclude a SIBLING coordinator\n // session's unicast completion on the same daemon (contracts.ts identityDeliversTo compares\n // sessions only when BOTH the event's intendedFor AND the drainer name one). Without a session\n // in the drainer identity the filter is inert and a daemon-level drain sweeps every local\n // coordinator's events. Regression-0: when coordinatorSessionId is empty (single-coordinator /\n // legacy) the drainer stays session-less → daemon-level delivery is unchanged; and a broadcast\n // event is delivered regardless (shouldDeliverPendingEventToCoordinator → true for broadcast),\n // so this only narrows genuine per-session unicast, never suppresses a broadcast.\n const drainerIdentity = coordinatorIdentityFromEmitFields({\n daemonId: ctx.localDaemonId,\n sessionId: ctx.coordinatorSessionId,\n });\n const events = (drainPendingMeshCoordinatorEvents(\n ctx.mesh.id,\n ctx.localDaemonId,\n drainerIdentity ? { drainerIdentity } : undefined,\n ) as any[]).filter(matchesCurrentMesh);\n events.forEach(rememberMeshSessionProviderMetadataFromEvent);\n return events;\n}\n\nexport function isP2pTransportUnavailableError(error: unknown): boolean {\n return isP2pRelayTransportFailure(error);\n}\n\nexport function buildRemoveNodeArgs(ctx: MeshContext, nodeId: string, sessionCleanupMode?: string, force?: boolean): Record<string, unknown> {\n return {\n meshId: ctx.mesh.id,\n nodeId,\n ...(sessionCleanupMode ? { sessionCleanupMode } : {}),\n ...(force === true ? { force: true } : {}),\n inlineMesh: ctx.mesh,\n };\n}\n\n\n/**\n * Distinguish a P2P read_chat transport failure between \"the peer is reachable but\n * saturated/slow\" (REQUEST_TIMEOUT — acked, result deadline elapsed) and \"the peer was\n * never connected / the request never reached a working handler\" (CONNECT_TIMEOUT,\n * ACK_TIMEOUT delivery failure, NO_PEER, datachannel closed, …). Both still warrant the\n * cached-summary fallback, but the advisory wording differs so the coordinator knows\n * whether a quick retry is plausible (saturated) or the daemon is simply offline.\n *\n * The transport-layer code (meshCode) is lost crossing IPC — only the error message\n * string survives — so classification is by message text.\n */\nexport function classifyReadChatTransportCause(error: unknown): 'not_connected' | 'saturated' {\n const message = (error instanceof Error ? error.message : String(error ?? '')).toLowerCase();\n if (/not acknowledged|delivery failure|channel never opened|connect timed out|not connected|datachannel|disconnected|\\bclosed\\b|offline|no route|failed to initiate p2p|p2p mesh is not available|connect queue full/.test(message)) {\n return 'not_connected';\n }\n // Acked but the result deadline elapsed (REQUEST_TIMEOUT) — peer reachable but\n // saturated / still working and could not return the transcript in time.\n return 'saturated';\n}\n\n\n/**\n * The coordinator already holds the worker's latest assistant text from the completion /\n * status events it surfaced into the ledger (finalSummary / workerResult.summary — the\n * same fields resolveMeshSurfacedSessionPreview reads off a live event, and the same\n * data the mobile inbox is fed). When the live P2P read_chat path is unavailable this\n * resolves that cached preview so mesh_read_chat can degrade to a stale-but-present\n * summary instead of a hard 30s timeout. Scans the most recent matching ledger entry for\n * the node+session.\n */\nexport function resolveCachedMeshSessionPreviewFromLedger(\n ctx: MeshContext,\n nodeId: string,\n sessionId: string,\n): { preview: string; role: 'assistant'; receivedAt: number; ledgerKind: string; timestamp: string } | undefined {\n const entries = readLedgerEntries(ctx.mesh.id, { tail: 200 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i];\n const payload = entry.payload && typeof entry.payload === 'object' && !Array.isArray(entry.payload)\n ? entry.payload as Record<string, unknown>\n : {};\n const entryNodeId = readString(entry.nodeId) || readString(payload.nodeId) || readString(payload.meshNodeId);\n if (entryNodeId && entryNodeId !== nodeId) continue;\n const entrySessionId = readString(entry.sessionId)\n || readString(payload.targetSessionId)\n || readString(payload.sessionId)\n || readString(payload.instanceId);\n if (entrySessionId !== sessionId) continue;\n // Prefer a nested metadataEvent when present, else read the entry payload itself\n // (task_completed / task_failed entries carry finalSummary + workerResult inline).\n const metadataEvent = payload.metadataEvent && typeof payload.metadataEvent === 'object' && !Array.isArray(payload.metadataEvent)\n ? payload.metadataEvent as Record<string, unknown>\n : payload;\n const preview = resolveMeshSurfacedSessionPreview(metadataEvent);\n if (preview) {\n return { ...preview, ledgerKind: entry.kind, timestamp: entry.timestamp };\n }\n }\n return undefined;\n}\n\n\n/**\n * mesh_read_chat fallback for a REMOTE P2P read that failed at the transport layer.\n *\n * Mirrors mesh_status's collectLiveStatusProbe graceful-degrade pattern: rather than\n * hard-failing on a 30s P2P timeout to a saturated/unreachable worker, surface the\n * cached coordinator-side summary (the same finalSummary/lastMessagePreview the mobile\n * dashboard renders). This is a READ/meta-plane degrade — status & preview already flow\n * over the WS/event plane — NOT a data-plane command WS fallback (which stays P2P-only\n * by policy). The full transcript still requires a live P2P read_chat; the fallback is\n * explicitly a stale point-in-time summary only.\n */\nexport function buildMeshReadChatCacheFallback(\n ctx: MeshContext,\n args: { node_id: string; session_id: string },\n node: LocalMeshNodeEntry,\n error: unknown,\n): string {\n const classification = classifyP2pRelayFailure(error, { command: 'read_chat', targetDaemonId: node.daemonId });\n const cause = classifyReadChatTransportCause(error);\n const errorMessage = error instanceof Error ? error.message : String(error ?? '');\n const causeNote = cause === 'not_connected'\n ? 'the worker daemon is not currently connected over P2P (no live channel)'\n : 'the worker daemon is connected but saturated — it acknowledged the request but did not return the transcript within the deadline';\n\n const cached = resolveCachedMeshSessionPreviewFromLedger(ctx, args.node_id, args.session_id);\n if (cached) {\n return JSON.stringify({\n success: true,\n source: 'coordinator_cache_fallback',\n fallback: true,\n nodeId: args.node_id,\n sessionId: args.session_id,\n transport: 'p2p',\n transportFailure: {\n code: classification.code,\n reason: classification.reason,\n cause,\n error: errorMessage,\n },\n advisory: `Live transcript unavailable (${causeNote}). Showing the cached coordinator-side summary surfaced from the worker's last completion/status event — a stale point-in-time summary, NOT the live transcript. The full transcript requires a live P2P read_chat once the peer is reachable.`,\n fullTranscriptRequiresP2p: true,\n summary: cached.preview,\n messages: [{\n role: cached.role,\n content: cached.preview,\n cached: true,\n ...(cached.receivedAt ? { receivedAt: cached.receivedAt } : {}),\n }],\n cachedPreview: {\n role: cached.role,\n ledgerKind: cached.ledgerKind,\n ledgerTimestamp: cached.timestamp,\n ...(cached.receivedAt ? { receivedAt: cached.receivedAt } : {}),\n },\n }, null, 2);\n }\n\n // No cached summary either — return the structured relay failure with a clear reason,\n // and make explicit that even a fallback summary is unavailable.\n const failure = buildCoordinatorP2pRelayFailure(error, {\n command: 'read_chat',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n sessionId: args.session_id,\n });\n return JSON.stringify({\n ...failure,\n cause,\n cachedSummaryAvailable: false,\n fullTranscriptRequiresP2p: true,\n advisory: `Live transcript unavailable (${causeNote}) and no cached coordinator-side summary exists for this session yet (no completion/status event has been surfaced). The full transcript requires a live P2P read_chat once the peer is reachable.`,\n }, null, 2);\n}\n\nexport function resolveRefineConfigNode(ctx: MeshContext, nodeId?: string): LocalMeshNodeEntry {\n if (nodeId) return findNode(ctx.mesh, nodeId);\n const node = ctx.mesh.nodes.find((entry: LocalMeshNodeEntry) => !!entry.workspace);\n if (!node) throw new Error('No mesh node with a workspace is available');\n return node;\n}\n","/**\n * Shared low-level helpers and constants for the mesh_* tool family.\n *\n * Leaf module: depends only on daemon-core/mesh-shared (never on mesh-tools.ts or\n * any of the split-out cluster files), so the cluster files (mesh-compact.ts,\n * mesh-queue-helpers.ts, mesh-node-identity.ts) and mesh-tools.ts can all import\n * from here without a runtime import cycle. Physically split out of mesh-tools.ts\n * (RF-SURVEY candidate C1) with no behavior change — same function bodies, same\n * constant values.\n */\n\nexport function readString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\nexport function readNumeric(value: unknown, fallback = 0): number {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : fallback;\n}\n\n// ─── Large-value / ledger-field compaction (shared by queue + compact + ledger) ───\n\nexport const LARGE_LEDGER_FIELD_KEYS = new Set(['plan', 'validationPlan', 'suggestedConfig', 'payload']);\nconst LARGE_LEDGER_OBJECT_THRESHOLD = 800;\n// Any nested object/array in a compact payload whose serialized size exceeds this\n// is replaced with an elided placeholder. This is the PRIMARY defense: it covers\n// arbitrary evidence keys (validationSummary, result, patchEquivalence,\n// submoduleReachability, plus any future key) without a hardcoded allowlist. The\n// specific per-key rules below are just tuning on top of this general guard.\nconst LARGE_LEDGER_NESTED_BYTES_THRESHOLD = 2000;\n\nexport function summarizeLargeLedgerField(key: string, value: unknown): unknown {\n if (typeof value === 'string') {\n return value.length > 500 ? value.slice(0, 500) + '…' : value;\n }\n if (Array.isArray(value)) {\n const serialized = JSON.stringify(value);\n if (serialized && serialized.length > LARGE_LEDGER_OBJECT_THRESHOLD) {\n return `[${key} summarized: ${value.length} items — use verbose=true or mesh_reconcile_ledger]`;\n }\n return value;\n }\n if (value && typeof value === 'object') {\n const serialized = JSON.stringify(value);\n if (serialized && serialized.length > LARGE_LEDGER_OBJECT_THRESHOLD) {\n return `[${key} summarized: ${Object.keys(value as Record<string, unknown>).length} keys — use verbose=true or mesh_reconcile_ledger]`;\n }\n return value;\n }\n return value;\n}\n\n// Generic nested-value guard. Replaces any object/array (or oversized string) whose\n// serialized size exceeds LARGE_LEDGER_NESTED_BYTES_THRESHOLD with a compact\n// placeholder that records the original key, byte size, and a recovery hint. Small\n// scalars and short fields (source, success, async, into, mergedBranch, …) pass\n// through untouched.\nexport function elideLargeNestedValue(key: string, value: unknown): unknown {\n if (value === null || value === undefined) return value;\n if (typeof value === 'string') {\n // Long bare strings (not one of the explicitly-capped fields) get a hard cap\n // so a single multi-KB string blob can't blow the payload either.\n return value.length > 1000 ? value.slice(0, 1000) + '…' : value;\n }\n if (typeof value !== 'object') return value; // number / boolean\n const serialized = JSON.stringify(value);\n const bytes = serialized ? serialized.length : 0;\n if (bytes <= LARGE_LEDGER_NESTED_BYTES_THRESHOLD) return value;\n return {\n _elided: true,\n _kind: key,\n _bytes: bytes,\n _hint: 'full evidence via mesh_reconcile_ledger',\n };\n}\n","/**\n * Session / command-payload record helpers for the mesh_* tools.\n *\n * Leaf module: depends on mesh-tool-shared (readString) and daemon-core's pure\n * isTaskReadonly predicate (for isWorkerTaskMode classification). Holds the shared\n * session-record readers/classifiers (id/provider/coordinator/unmanaged/terminal/\n * idle), the node session-id collector, and the command-payload unwrapper.\n * Physically split out of mesh-tools.ts (RF-SURVEY candidate C1) with no behavior\n * change — same function bodies. mesh-tools.ts and the queue/compact cluster files\n * import these back, so there is no runtime import cycle.\n */\nimport { readString } from './mesh-tool-shared.js';\nimport { isTaskReadonly } from '@adhdev/daemon-core';\n\nexport function readSessionRecordId(session: any): string | undefined {\n return readString(session?.id)\n || readString(session?.sessionId)\n || readString(session?.session_id)\n || readString(session?.runtimeSessionId)\n || readString(session?.runtime_session_id)\n || readString(session?.instanceId)\n || readString(session?.instance_id);\n}\n\nexport function extractStatusMetadataSessions(value: any): any[] {\n const payload = unwrapCommandPayload(value);\n const status = payload?.status && typeof payload.status === 'object'\n ? payload.status\n : payload;\n return Array.isArray(status?.sessions) ? status.sessions : [];\n}\n\nexport function resolveSessionProviderType(session: any): string {\n return readString(session?.providerType)\n || readString(session?.cliType)\n || readString(session?.agentType)\n || '';\n}\n\nexport function isMeshCoordinatorSessionRecord(session: any): boolean {\n return Boolean(\n readString(session?.settings?.meshCoordinatorFor)\n || readString(session?.meta?.meshCoordinatorFor)\n || readString(session?.metadata?.meshCoordinatorFor)\n || readString(session?.meshCoordinatorFor),\n );\n}\n\n/**\n * Returns true when a session has no mesh delegation metadata at all — neither\n * meshNodeFor (worker) nor meshCoordinatorFor (coordinator). Dispatching a\n * worker task to such a session is unsafe: the session may be the coordinator's\n * own CLI session (self-send risk), an unrelated session, or a stale record\n * whose providerSessionId now aliases the coordinator's transcript.\n *\n * The check intentionally fails closed: an explicit delegate session launched\n * via mesh_launch_session always carries meshNodeFor, so any safe target passes.\n */\nexport function isUnmanagedSessionRecord(session: any): boolean {\n const hasMeshNodeFor = Boolean(\n readString(session?.settings?.meshNodeFor)\n || readString(session?.meta?.meshNodeFor)\n || readString(session?.metadata?.meshNodeFor)\n || readString(session?.meshNodeFor),\n );\n if (hasMeshNodeFor) return false;\n if (isMeshCoordinatorSessionRecord(session)) return false;\n // launchedByCoordinator is set by the daemon when it auto-launches a worker\n // session in response to a queue task; treat it as a managed delegate.\n const launchedByCoordinator = Boolean(\n session?.settings?.launchedByCoordinator === true\n || session?.meta?.launchedByCoordinator === true\n || session?.launchedByCoordinator === true,\n );\n return !launchedByCoordinator;\n}\n\n/**\n * QUEUE-NODE-SERIALIZATION: a \"worker task mode\" is any task that is NOT read-only —\n * i.e. one that needs a visible worker session and the one-active-per-node isolation.\n * Delegates to daemon-core's single {@link isTaskReadonly} predicate so this boundary\n * stays in lock-step with the scheduler's classification (no duplicate inline copy).\n * `readonly` is the explicit boolean axis; live_debug_readonly remains an OR-fallback\n * inside the predicate.\n */\nexport function isWorkerTaskMode(taskMode: string | undefined, readonly?: boolean): boolean {\n return !isTaskReadonly({ readonly, taskMode });\n}\n\nfunction addSessionRecord(target: Set<string>, session: any): void {\n if (!session || typeof session !== 'object' || isTerminalSessionRecord(session)) return;\n const sessionId = readSessionRecordId(session);\n if (sessionId) target.add(sessionId);\n}\n\nexport function collectNodeSessionIds(node: any): Set<string> {\n const sessions = new Set<string>();\n const sessionArrays = [\n node?.sessions,\n node?.activeSessions,\n node?.active_sessions,\n node?.lastProbe?.sessions,\n node?.last_probe?.sessions,\n node?.lastProbe?.status?.sessions,\n node?.last_probe?.status?.sessions,\n ];\n for (const value of sessionArrays) {\n if (Array.isArray(value)) value.forEach(session => addSessionRecord(sessions, session));\n }\n\n const sessionRecords = [\n node?.activeSession,\n node?.active_session,\n node?.currentSession,\n node?.current_session,\n node?.runtimeSession,\n node?.runtime_session,\n node?.session,\n node?.lastProbe?.activeSession,\n node?.last_probe?.active_session,\n node?.lastProbe?.currentSession,\n node?.last_probe?.current_session,\n node?.lastProbe?.session,\n node?.last_probe?.session,\n ];\n sessionRecords.forEach(session => addSessionRecord(sessions, session));\n return sessions;\n}\n\nexport function unwrapCommandPayload(value: any): any {\n let current = value;\n const seen = new Set<any>();\n for (let depth = 0; depth < 8; depth += 1) {\n if (!current || typeof current !== 'object' || seen.has(current)) break;\n seen.add(current);\n\n const nested = current.result ?? current.payload;\n if (!nested || typeof nested !== 'object') break;\n current = nested;\n }\n return current;\n}\n\nexport function isTerminalSessionRecord(session: any): boolean {\n const status = typeof session?.status === 'string' ? session.status.toLowerCase() : '';\n const lifecycle = typeof session?.lifecycle === 'string' ? session.lifecycle.toLowerCase() : '';\n const state = typeof session?.state === 'string' ? session.state.toLowerCase() : '';\n return [status, lifecycle, state].some(value => ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(value));\n}\n\nexport function isIdleSessionRecord(session: any): boolean {\n if (isTerminalSessionRecord(session)) return false;\n const status = typeof session?.status === 'string' ? session.status.toLowerCase() : '';\n const chatStatus = typeof session?.activeChat?.status === 'string' ? session.activeChat.status.toLowerCase() : '';\n return status === 'idle' || chatStatus === 'waiting_input';\n}\n","/**\n * Node identity / locality resolution helpers for the mesh_* tools.\n *\n * Physically split out of mesh-tools.ts (RF-SURVEY candidate C1) with no behavior\n * change. Resolves machine/daemon/hostname identity for a mesh node and decides\n * whether a node is the local control-plane / coordinator node. Imports only leaf\n * deps (mesh-tool-shared, daemon-core) plus the MeshContext type (type-only, so no\n * runtime import cycle); mesh-tools.ts imports the exported helpers back.\n */\nimport { daemonIdsEquivalent, meshNodeIdMatches, canonicalDaemonId } from '@adhdev/daemon-core';\nimport type { LocalMeshNodeEntry } from '@adhdev/daemon-core';\nimport { readString } from './mesh-tool-shared.js';\nimport type { MeshContext } from './mesh-tools.js';\n\nexport function resolveCoordinatorNode(ctx: MeshContext): LocalMeshNodeEntry | undefined {\n const preferredNodeId = typeof ctx.mesh.coordinator?.preferredNodeId === 'string'\n ? ctx.mesh.coordinator.preferredNodeId.trim()\n : '';\n if (preferredNodeId) {\n const preferred = ctx.mesh.nodes.find(n => n.id === preferredNodeId && typeof n.daemonId === 'string' && n.daemonId.trim());\n if (preferred) return preferred;\n }\n if (ctx.localMachineId) {\n const byMachine = ctx.mesh.nodes.find(n => readNodeMachineId(n) === ctx.localMachineId);\n if (byMachine) return byMachine;\n }\n if (ctx.localDaemonId) {\n // Compare under canonical machine-core form (daemonIdsEquivalent), NOT a raw\n // `===`: the node's daemonId and ctx.localDaemonId may carry interchangeable\n // forms (bare `mach_X` / `daemon_mach_X` / `standalone_mach_X`). A raw `===`\n // misses the coordinator's own node on a form skew and forces the resolver to\n // fall through to a different anchor form than the queue path stamps — the\n // CANON-IDENTITY double-dispatch (two coordinator-id forms for one task).\n return ctx.mesh.nodes.find(n => daemonIdsEquivalent(readNodeDaemonId(n), ctx.localDaemonId));\n }\n return undefined;\n}\n\n/**\n * Resolve the coordinator anchor id stamped into a worker dispatch's meshContext\n * (`coordinatorDaemonId`), which the remote router turns into the worker\n * session's `meshCoordinatorDaemonId` relay anchor (router.ts buildMeshWorkerRelayStamp).\n * Without a non-empty value the forwarder gate treats the worker as relay-unsafe\n * and the completion event sits in the pending queue until a later read_chat\n * forces a reconcile.\n *\n * Order: the coordinator mesh node's daemonId → the IPC daemon instanceId\n * (ctx.localDaemonId) → the local machine registry id (ctx.localMachineId). The\n * final fallback mirrors the queue-assignment dispatch path, which stamps\n * `loadConfig().machineId` (== ctx.localMachineId; see server.ts) — so the\n * direct-dispatch path now resolves an anchor whenever the queue path would.\n */\nexport function resolveCoordinatorDaemonId(ctx: MeshContext): string | undefined {\n const resolved = readString(resolveCoordinatorNode(ctx)?.daemonId)\n || readString(ctx.localDaemonId)\n || readString(ctx.localMachineId);\n // CANON: emit the single canonical `daemon_mach_<core>` producer form for ALL\n // three tiers. Tier 1 (the coordinator node's config-form daemonId) is already\n // `daemon_mach_` and is the proven P2P-routable form; the localDaemonId /\n // localMachineId fallbacks resolve to bare `mach_` or `standalone_mach_` forms.\n // Without this, the fallback tiers stamp a DIFFERENT coordinator-id form than the\n // primary path and the queue dispatch — the form skew that lets one task be\n // dedup-missed and dispatched into a second session. canonicalDaemonId leaves a\n // non-machine id unchanged and returns undefined for an empty resolve.\n return canonicalDaemonId(resolved) ?? readString(resolved);\n}\n\nexport function readNodeMachineId(node: LocalMeshNodeEntry): string | undefined {\n return readString((node as any).machineId)\n || readString((node as any).machine_id)\n || readString((node as any).machine?.id)\n || readString((node as any).machine?.machineId)\n || readString((node as any).lastProbe?.machineId)\n || readString((node as any).last_probe?.machine_id)\n || readString((node as any).lastProbe?.machine?.id)\n || readString((node as any).lastProbe?.machine?.machineId)\n || readString((node as any).last_probe?.machine?.id)\n || readString((node as any).last_probe?.machine?.machine_id);\n}\n\nexport function readNodeDaemonId(node: LocalMeshNodeEntry): string | undefined {\n return readString(node.daemonId)\n || readString((node as any).daemon_id)\n || readString((node as any).machine?.daemonId)\n || readString((node as any).machine?.daemon_id)\n || readString((node as any).lastProbe?.daemonId)\n || readString((node as any).last_probe?.daemon_id)\n || readString((node as any).lastProbe?.machine?.daemonId)\n || readString((node as any).lastProbe?.machine?.daemon_id)\n || readString((node as any).last_probe?.machine?.daemonId)\n || readString((node as any).last_probe?.machine?.daemon_id);\n}\n\nfunction normalizeHostname(value: unknown): string | undefined {\n const hostname = readString(value);\n if (!hostname) return undefined;\n return hostname.toLowerCase().replace(/\\.$/, '');\n}\n\nfunction readNodeHostname(node: LocalMeshNodeEntry): string | undefined {\n return readString((node as any).hostname)\n || readString((node as any).host)\n || readString((node as any).machineHostname)\n || readString((node as any).machine_hostname)\n || readString((node as any).machine?.hostname)\n || readString((node as any).machine?.host)\n || readString((node as any).lastProbe?.hostname)\n || readString((node as any).last_probe?.hostname)\n || readString((node as any).lastProbe?.machine?.hostname)\n || readString((node as any).last_probe?.machine?.hostname);\n}\n\nfunction readNodeDisplayMachineName(node: LocalMeshNodeEntry): string | undefined {\n return readString((node as any).machineName)\n || readString((node as any).machine_name)\n || readString((node as any).machineLabel)\n || readString((node as any).machine_label)\n || readString((node as any).machineNickname)\n || readString((node as any).machine_nickname)\n || readString((node as any).alias)\n || readString((node as any).machine?.name)\n || readString((node as any).machine?.displayName)\n || readString((node as any).machine?.display_name)\n || readString((node as any).lastProbe?.machineName)\n || readString((node as any).last_probe?.machine_name)\n || readString((node as any).lastProbe?.machine?.name)\n || readString((node as any).last_probe?.machine?.name)\n || readNodeHostname(node);\n}\n\nfunction compactIdentityEvidence(value: string | undefined): string | undefined {\n if (!value) return undefined;\n return value.length > 24 ? `${value.slice(0, 12)}…${value.slice(-8)}` : value;\n}\n\nfunction pushIdentityEvidence(evidence: string[], label: string, value: string | undefined): void {\n const compact = compactIdentityEvidence(value);\n if (compact) evidence.push(`${label}:${compact}`);\n}\n\nexport function buildNodeMachineIdentity(ctx: MeshContext, node: LocalMeshNodeEntry): Record<string, unknown> {\n const machineId = readNodeMachineId(node);\n const daemonId = readNodeDaemonId(node);\n const hostname = readNodeHostname(node);\n const machineName = readNodeDisplayMachineName(node);\n const coordinatorHostname = readString(ctx.coordinatorHostname);\n const localControlPlaneReason = getLocalControlPlaneMatchReason(ctx, node);\n const directLocal = !!localControlPlaneReason;\n const hostnameMatches = Boolean(\n normalizeHostname(hostname)\n && normalizeHostname(coordinatorHostname)\n && normalizeHostname(hostname) === normalizeHostname(coordinatorHostname),\n );\n const sameMachine = directLocal || hostnameMatches;\n const evidence: string[] = [];\n pushIdentityEvidence(evidence, 'machineName', machineName);\n pushIdentityEvidence(evidence, 'hostname', hostname);\n pushIdentityEvidence(evidence, 'machineId', machineId);\n pushIdentityEvidence(evidence, 'daemonId', daemonId);\n if (localControlPlaneReason) {\n pushIdentityEvidence(evidence, 'localMatch', localControlPlaneReason);\n pushIdentityEvidence(evidence, 'localMachineId', ctx.localMachineId);\n pushIdentityEvidence(evidence, 'localDaemonId', ctx.localDaemonId);\n }\n const locality = sameMachine ? 'same_machine' : (evidence.length > 0 ? 'remote_known' : 'remote_or_unknown');\n const localityReason = sameMachine\n ? (localControlPlaneReason || 'matched coordinator hostname')\n : evidence.length > 0\n ? `known remote/other machine identity; no local coordinator match (${evidence.join(', ')})`\n : 'no useful machine identity evidence available';\n return {\n daemonId,\n machineId,\n hostname,\n machineName,\n displayName: machineName || hostname || daemonId || machineId,\n coordinatorHostname,\n sameMachine,\n locality,\n localityReason,\n identityEvidence: evidence,\n };\n}\n\nfunction nodeHasLocalDaemonEvidence(ctx: MeshContext, node: any): boolean {\n const isLocal = (session: any) => {\n if (!session || typeof session !== 'object') return false;\n // meshCoordinatorDaemonId identifies where a worker should relay completion events.\n // Remote workers also point this at the local coordinator, so it is not locality evidence.\n // Likewise launchedByCoordinator only proves the coordinator created the session, not\n // that the session is running on this daemon.\n // runtime.owner / daemonClient.daemonId and ctx.localDaemonId may carry\n // interchangeable id forms (bare mach_ / daemon_mach_ / standalone_mach_), so\n // compare under canonical machine-core form rather than a raw ===; a form\n // mismatch would otherwise drop valid local-daemon evidence.\n if (ctx.localDaemonId && daemonIdsEquivalent(session.runtime?.owner, ctx.localDaemonId)) return true;\n if (ctx.localDaemonId && daemonIdsEquivalent(session.daemonClient?.daemonId, ctx.localDaemonId)) return true;\n return false;\n };\n\n const sessionArrays = [\n node?.sessions,\n node?.activeSessions,\n node?.active_sessions,\n node?.lastProbe?.sessions,\n node?.last_probe?.sessions,\n node?.lastProbe?.status?.sessions,\n node?.last_probe?.status?.sessions,\n ];\n for (const arr of sessionArrays) {\n if (Array.isArray(arr) && arr.some(isLocal)) return true;\n }\n\n const sessionRecords = [\n node?.activeSession,\n node?.active_session,\n node?.currentSession,\n node?.current_session,\n node?.runtimeSession,\n node?.runtime_session,\n node?.session,\n node?.lastProbe?.activeSession,\n node?.last_probe?.active_session,\n node?.lastProbe?.currentSession,\n node?.last_probe?.current_session,\n node?.lastProbe?.session,\n node?.last_probe?.session,\n ];\n for (const session of sessionRecords) {\n if (isLocal(session)) return true;\n }\n \n return false;\n}\n\nfunction isDirectLocalNode(ctx: MeshContext, node: LocalMeshNodeEntry): boolean {\n const machineId = readNodeMachineId(node);\n const daemonId = readNodeDaemonId(node);\n // id-form robust: a node's daemon/machine id may be stored in a DIFFERENT form\n // (bare `mach_X` vs `daemon_mach_X` vs `standalone_mach_X`) than the coordinator's\n // resolved ctx ids. A strict `===` misclassified the coordinator's own node as\n // REMOTE, so the enqueue fan-out dispatched the task body to this very daemon — where\n // it fuzzy-injected into the coordinator's own CLI session (TASKECHO). daemonIdsEquivalent\n // canonicalizes both sides to the machine core before comparing.\n return Boolean(\n (ctx.localMachineId && daemonIdsEquivalent(machineId, ctx.localMachineId))\n || (ctx.localDaemonId && daemonIdsEquivalent(daemonId, ctx.localDaemonId))\n || nodeHasLocalDaemonEvidence(ctx, node)\n );\n}\n\nfunction isConfiguredCoordinatorNode(ctx: MeshContext, node: LocalMeshNodeEntry): boolean {\n if (!ctx.localMachineId && !ctx.localDaemonId) return false;\n const nodeId = readString(node.id) || readString((node as any).nodeId) || readString((node as any).node_id);\n if (!nodeId) return false;\n // If the node carries explicit daemon/machine identity that doesn't match the\n // coordinator, it is definitively a remote node — skip the positional fallback.\n // Compare under canonical id form (daemonIdsEquivalent), NOT a raw `!==`: a local\n // coordinator node stored in a different daemon-id form (bare vs `daemon_`/`standalone_`)\n // would otherwise be wrongly excluded here and treated as remote.\n const nodeDaemonId = readNodeDaemonId(node);\n const nodeMachineId = readNodeMachineId(node);\n if (nodeDaemonId && ctx.localDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.localDaemonId)) return false;\n if (nodeMachineId && ctx.localMachineId && !daemonIdsEquivalent(nodeMachineId, ctx.localMachineId)) return false;\n const preferredNodeId = readString(ctx.mesh.coordinator?.preferredNodeId)\n || readString((ctx.mesh.coordinator as any)?.preferred_node_id);\n if (preferredNodeId) return nodeId === preferredNodeId;\n const first = ctx.mesh.nodes?.[0] as any;\n const firstNodeId = readString(first?.id) || readString(first?.nodeId) || readString(first?.node_id);\n return !!firstNodeId && nodeId === firstNodeId;\n}\n\nfunction getLocalControlPlaneMatchReason(ctx: MeshContext, node: LocalMeshNodeEntry): string | undefined {\n if (isDirectLocalNode(ctx, node)) return 'matched coordinator daemon or machine id';\n if (isConfiguredCoordinatorNode(ctx, node)) return 'matched configured coordinator node';\n if (node.isLocalWorktree === true) {\n const sourceNode = findClonedFromNode(ctx, node);\n if (sourceNode && isDirectLocalNode(ctx, sourceNode)) return 'matched local cloned-from node';\n if (sourceNode && isConfiguredCoordinatorNode(ctx, sourceNode)) return 'matched configured coordinator source node';\n }\n return undefined;\n}\n\nfunction findClonedFromNode(ctx: MeshContext, node: LocalMeshNodeEntry): LocalMeshNodeEntry | undefined {\n const clonedFromNodeId = readString(node.clonedFromNodeId) || readString((node as any).cloned_from_node_id);\n if (!clonedFromNodeId) return undefined;\n return ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, clonedFromNodeId));\n}\n\n/**\n * Resolve the node id a `prefer_worktree` enqueue should target.\n *\n * Worktree clones (mesh_clone_node) are appended to `ctx.mesh.nodes`, so the\n * LAST worktree node in array order is the most recently created one — the one\n * the coordinator most likely just spun up for isolated work. Without an\n * explicit target, an unconstrained queue task is claimed by whichever node\n * polls first (typically the base/main workspace), defeating the isolation\n * intent. Returning a concrete node id lets enqueueTask stamp targetNodeId so\n * the existing node-targeted claim tier routes the task to the worktree.\n *\n * Returns undefined when no worktree node exists (the caller treats this as a\n * no-op and falls back to normal unconstrained queueing).\n */\nexport function resolvePreferredWorktreeNodeId(ctx: MeshContext): string | undefined {\n const worktreeNodes = (ctx.mesh.nodes || []).filter(n => (n as any).isLocalWorktree === true);\n if (worktreeNodes.length === 0) return undefined;\n const chosen = worktreeNodes[worktreeNodes.length - 1] as any;\n return readString(chosen?.id) || readString(chosen?.nodeId) || readString(chosen?.node_id);\n}\n\nexport function isLocalControlPlaneNode(ctx: MeshContext, node: LocalMeshNodeEntry): boolean {\n return !!getLocalControlPlaneMatchReason(ctx, node);\n}\n","/**\n * MCP tool schema definitions for the mesh_* tool family.\n *\n * Pure data: per-tool input schemas plus the ALL_MESH_TOOLS registry. Physically\n * split out of mesh-tools.ts (which keeps the handler implementations) — see\n * RF-SURVEY candidate C1. No behavior change: mesh-tools.ts re-exports every symbol\n * below so existing `./tools/mesh-tools.js` import paths stay intact.\n */\n\nexport const MESH_STATUS_TOOL = {\n name: 'mesh_status',\n description: 'Get the current status of all nodes in the repo mesh — health, git state, active sessions, recovery hints, and recommended next steps. Use this to decide which node to send work to or how to recover from failures. Also reports the running daemon build per daemonId under top-level daemonBuilds ({commit, commitShort, version}); when a live daemon was built from a commit BEHIND its workspace HEAD it adds staleDaemonBuilds[] + staleDaemonBuildWarning — meaning a just-merged refinery/mesh-tool fix is NOT yet live on that daemon (awaiting deploy/restart; a local dist rebuild does not update a cloud daemon). Do not repeatedly call this to wait for generating delegated work; wait for pendingCoordinatorEvents/completion events or an explicit user status request.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n _gemini_compat: { type: 'string', description: 'Dummy property for Gemini compatibility. Ignore this.' },\n includeStaleDirectWorkDetails: { type: 'boolean', description: 'Opt in to the full staleDirectWork array. Defaults false; normal status returns compact staleDirectWorkSummary only.' },\n includeSessions: { type: 'boolean', description: 'Opt in to per-node live session arrays. Default false: compact mode returns a per-node sessionSummary (counts) and de-duplicated full session lists under top-level daemonSessions keyed by daemonId (sessions are not repeated for every node that shares a daemon). Set true to also include the full session array on each node.' },\n compact: { type: 'boolean', description: 'Slim payload for LLM callers. Default true. Folds per-node session arrays to sessionSummary and de-duplicates daemon-shared sessions into daemonSessions. Set false (or verbose=true) for the full dashboard-grade payload.' },\n verbose: { type: 'boolean', description: 'Force the full payload; overrides compact.' },\n },\n },\n};\n\nexport const MESH_LIST_NODES_TOOL = {\n name: 'mesh_list_nodes',\n description: 'List all nodes in the mesh with their capabilities, platform, and workspace paths.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n _gemini_compat: { type: 'string', description: 'Dummy property for Gemini compatibility. Ignore this.' },\n },\n },\n};\n\nexport const MESH_ENQUEUE_TASK_TOOL = {\n name: 'mesh_enqueue_task',\n description: 'Add a new task to the mesh work queue. Idle nodes will automatically pull and execute tasks from this queue. Use this instead of mesh_send_task when you do not need to target a specific node. '\n + 'Supports task-level priority (high tasks are pulled ahead of older normal/low tasks), not_before delayed execution (hold a task pending until a time), maxRetries (auto-fail after N requeues), and duplicate detection '\n + '(by default warns in the response when an in-flight task with the same message+target already exists; pass block_duplicate=true to refuse instead, or allow_duplicate=true to silence the warning).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n message: { type: 'string', description: 'The task instruction for the agent.' },\n task_mode: { type: 'string', enum: ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'], description: 'Optional task-mode contract. live_debug_readonly rejects obvious write/commit/push/deploy/destructive instructions before dispatch.' },\n taskMode: { type: 'string', enum: ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'], description: 'CamelCase alias for task_mode.' },\n readonly: { type: 'boolean', description: 'Optional read-only axis (orthogonal to task_mode). When true the task runs without the one-active-per-node write isolation (N read-only tasks may run in parallel on one node), is counted under the read-only safety cap, and rejects write/commit/push/deploy/destructive instructions like live_debug_readonly. Equivalent to task_mode=live_debug_readonly but composable with any task_mode.' },\n read_only: { type: 'boolean', description: 'Snake-case alias for readonly.' },\n requiredTags: { type: 'array', items: { type: 'string' }, description: 'Optional capability tags that every eligible node must have, e.g. os=darwin, provider=codex-cli, gpu.' },\n required_tags: { type: 'array', items: { type: 'string' }, description: 'Snake_case alias for requiredTags.' },\n target_node_id: { type: 'string', description: 'Optional HARD constraint: ONLY this node may claim the task. No other node (especially a different machine) will ever claim it — if the target node has no idle session the task stays pending until it does. Use to route a queued task to a specific (e.g. freshly cloned) worktree node instead of letting the first idle base node claim it. Takes priority over prefer_worktree. An unresolvable target id is rejected at enqueue (no silent unpin).' },\n targetNodeId: { type: 'string', description: 'CamelCase alias for target_node_id.' },\n target_node: { type: 'string', description: 'Alias for target_node_id.' },\n targetNode: { type: 'string', description: 'CamelCase alias for target_node_id.' },\n prefer_worktree: { type: 'boolean', description: 'Optional: when true, route this task to the most recently cloned idle worktree node (avoids the main/base workspace preemptively claiming an isolated task). No-op if no worktree node exists; resolves to a target_node_id when one does.' },\n preferWorktree: { type: 'boolean', description: 'CamelCase alias for prefer_worktree.' },\n depends_on: { type: 'array', items: { type: 'string' }, description: 'Task ids that must complete before this task becomes claimable. Cycles are rejected at enqueue.' },\n dependsOn: { type: 'array', items: { type: 'string' }, description: 'CamelCase alias for depends_on.' },\n mission_id: { type: 'string', description: 'Mission this task belongs to (mesh_mission record id).' },\n missionId: { type: 'string', description: 'CamelCase alias for mission_id.' },\n priority: { type: 'string', enum: ['low', 'normal', 'high'], description: 'G6 (task-level scheduling priority). Within the claim tier a high task is pulled ahead of an older normal/low task (created_at is the tie-break); low is pulled last. Defaults to normal. This is the TASK priority (which task a node pulls first) — distinct from a node\\'s schedulingPriority (which node work goes to). Use high to jump an urgent fix ahead of a backlog without cancelling the queue.' },\n model: { type: 'string', description: 'Optional model override for the agent that runs this task, e.g. opus, sonnet, haiku. Best-effort: applied at launch for providers that support a model flag (claude-cli --model, ACP setConfigOption); ignored by providers that cannot honor it. Use a cheaper model for simple tasks to save tokens, a stronger one for hard work. Blank = the provider default.' },\n thinkingLevel: { type: 'string', enum: ['low', 'medium', 'high'], description: 'Optional reasoning-effort level for this task. Best-effort: applied at launch for providers that support it (claude-cli --effort, codex-cli reasoning effort, ACP thought_level); ignored otherwise. Use low for simple tasks (fewer tokens), high for hard reasoning.' },\n difficulty: { type: 'string', enum: ['easy', 'medium', 'difficult', 'freeform'], description: 'Optional task execution difficulty. When set, the mesh per-difficulty brain preset fills in the model + thinkingLevel you did not pass explicitly (easy → cheap model / low effort to save tokens; difficult → strong model / high effort). Classify each task you enqueue so simple work runs cheaply. An explicit model/thinkingLevel above always wins over the preset.' },\n notBefore: { type: 'number', description: 'CamelCase alias for not_before. Also accepts an ISO-8601 timestamp string.' },\n max_retries: { type: 'number', description: 'P3 (retry cap). Max automatic requeue attempts before the task auto-fails instead of returning to pending. When requeueCount reaches this, mesh_queue_requeue auto-fails the task unless force=true. Omit to use the mesh policy default (maxTaskRetries, typically 1).' },\n maxRetries: { type: 'number', description: 'CamelCase alias for max_retries.' },\n block_duplicate: { type: 'boolean', description: 'G4 (duplicate detection, block mode). Default false = warn-only: if an in-flight (pending/assigned) task with the same message (+ target node when pinned) already exists, the task is still enqueued but the response carries duplicateSuspect. Set true to REFUSE the enqueue with code duplicate_suspect instead (structural TASKBUBBLE-DUP defense — use when re-sending a task that a slow prior turn may have already enqueued).' },\n blockDuplicate: { type: 'boolean', description: 'CamelCase alias for block_duplicate.' },\n allow_duplicate: { type: 'boolean', description: 'G4. Set true to skip duplicate detection entirely (no warning, no block) for an intentional re-enqueue of the same instruction.' },\n allowDuplicate: { type: 'boolean', description: 'CamelCase alias for allow_duplicate.' },\n },\n required: ['message'],\n },\n};\n\nexport const MESH_VIEW_QUEUE_TOOL = {\n name: 'mesh_view_queue',\n description: 'View the mesh work queue with source-of-truth active counts separated from historical completed/failed/cancelled records. Do not repeatedly call this to wait for generating assigned work; wait for pendingCoordinatorEvents/completion events or an explicit user status request.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n status: {\n type: 'array',\n items: { type: 'string' },\n description: 'Explicit row filter by task status: pending, assigned, completed, failed, cancelled. Source-of-truth counts remain unfiltered; visible* counts describe returned rows.',\n },\n view: {\n type: 'string',\n enum: ['all', 'active', 'historical'],\n description: 'Optional row view. active returns pending/assigned rows, historical returns completed/failed/cancelled rows, all returns every persisted queue row. Defaults to all for compatibility.',\n },\n compact: { type: 'boolean', description: 'Slim payload for LLM callers. Default true. Drops large historical (completed/failed/cancelled) queue row arrays, the full staleDirectWork orphan array (kept as staleDirectWorkSummary counts), and per-row maintenance cleanupCandidates in favor of counts; pending/assigned active rows are retained. Set false (or verbose=true) for the full dashboard-grade payload.' },\n verbose: { type: 'boolean', description: 'Force the full payload; overrides compact.' },\n },\n },\n};\n\nexport const MESH_QUEUE_CANCEL_TOOL = {\n name: 'mesh_queue_cancel',\n description: 'Cancel a pending/assigned/completed/failed mesh queue task without deleting audit history. Use this to retire stale queue items that target dead sessions.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n task_id: { type: 'string', description: 'Queue task ID to cancel.' },\n reason: { type: 'string', description: 'Optional operator-visible reason for cancellation.' },\n },\n required: ['task_id'],\n },\n};\n\nexport const MESH_QUEUE_REQUEUE_TOOL = {\n name: 'mesh_queue_requeue',\n description: 'Return a mesh queue task to pending for retry. By default clears stale assigned owner and target session so another live session can claim it. When the task has exceeded its retry cap it is auto-failed instead; use force=true to override.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n task_id: { type: 'string', description: 'Queue task ID to requeue.' },\n reason: { type: 'string', description: 'Optional operator-visible reason for requeueing.' },\n target_node_id: { type: 'string', description: 'Optional replacement target node ID.' },\n target_session_id: { type: 'string', description: 'Optional replacement target runtime session ID.' },\n clear_target_node: { type: 'boolean', description: 'When true, remove any existing target node constraint.' },\n keep_target_session: { type: 'boolean', description: 'When true, preserve an existing target session if target_session_id is not provided. Defaults false to avoid stale session targets.' },\n force: { type: 'boolean', description: 'When true, bypass the retry cap and requeue even if maxRetries has been exceeded. Use only for explicit operator recovery.' },\n },\n required: ['task_id'],\n },\n};\n\nexport const MESH_SEND_TASK_TOOL = {\n name: 'mesh_send_task',\n description: 'Legacy push-based task assignment. Enqueues a task specifically targeted at a given node. The node will pull it immediately if idle.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID (from mesh_list_nodes).' },\n session_id: { type: 'string', description: 'Agent session ID on the target node.' },\n message: { type: 'string', description: 'Natural-language task to send to the agent.' },\n task_mode: { type: 'string', enum: ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'], description: 'Optional task-mode contract. live_debug_readonly rejects obvious write/commit/push/deploy/destructive instructions before local or remote direct dispatch.' },\n taskMode: { type: 'string', enum: ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'], description: 'CamelCase alias for task_mode.' },\n readonly: { type: 'boolean', description: 'Optional read-only axis (orthogonal to task_mode). When true the task runs without write isolation, is counted under the read-only cap, and rejects write/commit/push/deploy/destructive instructions like live_debug_readonly. Composable with any task_mode.' },\n read_only: { type: 'boolean', description: 'Snake-case alias for readonly.' },\n mission_id: { type: 'string', description: 'Mission this task belongs to (mesh_mission record id). When set, the directly dispatched task is attributed to the mission task aggregates exactly like mesh_enqueue_task, including terminal completion. Omit for an unattributed direct dispatch.' },\n missionId: { type: 'string', description: 'CamelCase alias for mission_id.' },\n },\n required: ['node_id', 'session_id', 'message'],\n },\n};\n\nexport const MESH_READ_CHAT_TOOL = {\n name: 'mesh_read_chat',\n description: 'Read recent chat messages from a delegated agent session on a mesh node. Use compact=true for coordinator context-efficient review: it filters tool/internal/debug chatter and returns the final user-visible summary plus recent key messages. If the runtime session has completed, provider_session_id can explicitly target provider transcript history.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n session_id: { type: 'string', description: 'Agent session ID to read from.' },\n provider_session_id: { type: 'string', description: 'Optional provider transcript/session ID for completed sessions.' },\n tail: { type: 'number', description: 'Number of recent messages to return (default: 10).' },\n compact: { type: 'boolean', description: 'When true, return a compact coordinator summary instead of the full transcript: tool/internal/control/debug messages are excluded and only recent user-visible key messages plus the final assistant summary are included.' },\n },\n required: ['node_id', 'session_id'],\n },\n};\n\nexport const MESH_READ_DEBUG_TOOL = {\n name: 'mesh_read_debug',\n description: 'Collect a daemon-side chat/parser debug bundle for a delegated agent session on a mesh node without opening the browser UI. Defaults to daemon_file delivery and returns a saved bundle locator.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n session_id: { type: 'string', description: 'Agent session ID to debug.' },\n provider_session_id: { type: 'string', description: 'Optional provider transcript/session ID for completed session history.' },\n tail: { type: 'number', description: 'Number of recent read_chat messages to embed (default: 40).' },\n delivery: { type: 'string', enum: ['daemon_file', 'inline'], description: 'daemon_file saves the full sanitized bundle on the daemon; inline returns it directly. Default: daemon_file.' },\n },\n required: ['node_id', 'session_id'],\n },\n};\n\nexport const MESH_READ_TERMINAL_TOOL = {\n name: 'mesh_read_terminal',\n description: 'Read the CURRENT raw terminal screen (the rendered PTY viewport — what a human would see on screen right now) of a delegated agent session on a mesh node. '\n + 'This is the LIVE screen, not the parsed chat transcript: use it to see exactly what the worker is showing — a prompt it is parked on, a modal, a spinner, or unparsed output that mesh_read_chat does not surface. For the conversation transcript use mesh_read_chat instead. '\n + 'The reply is byte-bounded (default 32KiB, max 64KiB; the BOTTOM of the screen — prompt/modal/recent output — is kept when truncated) and returns truncated/original_bytes/returned_bytes plus the cursor position and viewport size. '\n + 'Scoped to coordinator-spawned mesh worker sessions only. NOTE: the raw screen can contain tokens / command args / env values, so treat the returned text as sensitive.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n session_id: { type: 'string', description: 'Agent session ID whose live terminal viewport to read.' },\n max_bytes: { type: 'number', description: 'Optional UTF-8 byte cap for the returned screen text (default 32768, clamped to [1024, 65536]). When the screen exceeds it, the bottom (most recent) lines are kept.' },\n },\n required: ['node_id', 'session_id'],\n },\n};\n\nexport const MESH_SEND_KEYS_TOOL = {\n name: 'mesh_send_keys',\n description: 'Inject a STRUCTURED key sequence into a delegated worker session\\'s live PTY (keystrokes a human would type). '\n + 'Use for interactions mesh_send_task cannot express: dismiss/answer a non-approval prompt, navigate a picker (arrows/TAB), submit an already-typed line (ENTER), correct input (BACKSPACE), or interrupt a runaway command (CTRL_C). For sending a task/message, use mesh_send_task; for an APPROVAL modal, use mesh_approve (send_keys is refused on an actionable approval modal by design). '\n + 'Each sequence item is either {\"text\":\"literal\"} or {\"key\":NAME} where NAME ∈ ENTER|ESC|CTRL_C|UP|DOWN|LEFT|RIGHT|TAB|BACKSPACE. text+ENTER is submitted atomically. '\n + 'DESTRUCTIVE keys (CTRL_C, ESC) can kill/derail the worker and require BOTH confirm_destructive=true AND mesh policy allowSendKeysDestructive — otherwise refused. '\n + 'The injection is refused if the session has a pending submit/echo race, or (for non-destructive keys) an actionable approval modal. Scoped to coordinator-spawned mesh worker sessions. Each injection is audited (key enums + result; the literal text body is NOT recorded).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n session_id: { type: 'string', description: 'Agent session ID whose PTY to inject into.' },\n sequence: {\n type: 'array',\n description: 'Ordered key sequence. Each item is {\"text\":\"literal UTF-8\"} OR {\"key\":\"ENTER|ESC|CTRL_C|UP|DOWN|LEFT|RIGHT|TAB|BACKSPACE\"}. Max 64 items, 4096 total text bytes.',\n items: {\n type: 'object',\n properties: {\n text: { type: 'string', description: 'Literal UTF-8 text to type.' },\n key: { type: 'string', enum: ['ENTER', 'ESC', 'CTRL_C', 'UP', 'DOWN', 'LEFT', 'RIGHT', 'TAB', 'BACKSPACE'], description: 'Named key.' },\n },\n },\n },\n confirm_destructive: { type: 'boolean', description: 'Required true when the sequence contains a destructive key (CTRL_C/ESC). Also requires mesh policy allowSendKeysDestructive.' },\n allow_modal_override: { type: 'boolean', description: 'Override the actionable-approval-modal fail-closed refusal for NON-destructive keys. Use only when you deliberately need to inject into a modal-parked session that is NOT an approval you should route through mesh_approve.' },\n },\n required: ['node_id', 'session_id', 'sequence'],\n },\n};\n\nexport const MESH_LAUNCH_SESSION_TOOL = {\n name: 'mesh_launch_session',\n description: 'Launch a new agent session on a mesh node. Returns the session ID for subsequent send_task/read_chat calls. If the user names a provider, preserve it exactly: Hermes = hermes-cli, Claude Code/Claude = claude-cli, Codex = codex-cli, Gemini = gemini-cli. If type is omitted, resolve strictly from the node policy providerPriority and provider detection; fail closed when no configured provider is usable. Do not default to claude-cli.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n type: { type: 'string', description: 'Optional provider type to launch. Use hermes-cli for Hermes, claude-cli for Claude Code, codex-cli for Codex, gemini-cli for Gemini. When omitted, node.policy.providerPriority is probed in order.' },\n force: { type: 'boolean', description: 'Set true to launch an ADDITIONAL session even when this node already has a live mesh-owned worker session. Default false: if a live worker session for this mesh+node already exists (e.g. an enqueue auto-launch just spawned one), the existing session is returned idempotently instead of creating an empty duplicate. Only pass force when you intentionally want a second concurrent provider/session on the node.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_GIT_STATUS_TOOL = {\n name: 'mesh_git_status',\n description: 'Get git status for a mesh node workspace — branch, dirty state, changed files.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_READ_NODE_LOGS_TOOL = {\n name: 'mesh_read_node_logs',\n description: 'Fetch a recent daemon LOG tail directly from a (possibly remote) mesh node over P2P — no session launch, no PowerShell/shell grep on the remote machine. '\n + 'Use this to debug a node\\'s daemon: read its error/warn lines, grep for a pattern, or read since a timestamp. '\n + 'The reply is byte-bounded (≤128KB, default 64KB; truncated:true when the file was larger, newest lines kept) and secrets (API keys, machine secrets, bearer tokens, JWTs, TURN credentials) are redacted before transmission. '\n + 'This reads the DAEMON log, not an agent session transcript — for a session transcript use mesh_read_chat / mesh_read_debug.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID (the daemon owning it serves its own log).' },\n grep: { type: 'string', description: 'Optional regex (case-insensitive) — only matching log lines are returned. Invalid regex falls back to a literal substring match.' },\n since_ms: { type: 'number', description: 'Optional epoch-ms floor — only log lines at/after this time are returned (lines without a parseable timestamp are kept).' },\n tail_bytes: { type: 'number', description: 'Max bytes of log tail to read (default 65536, capped at 131072). Larger files are truncated to the newest tail_bytes.' },\n date: { type: 'string', description: 'Optional YYYY-MM-DD log date (defaults to today). Falls back to the size-rotation backup when the active file is absent.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_FAST_FORWARD_NODE_TOOL = {\n name: 'mesh_fast_forward_node',\n description: 'Safely dry-run or execute an obvious direct fast-forward for a mesh node without launching an agent session. '\n + 'mode=\"merge\" (default) absorbs upstream commits into the local branch via git merge --ff-only (ahead=0, behind>0). '\n + 'mode=\"push\" publishes local commits to origin via a strict ff-only push (HEAD must be a descendant of origin/<branch>). '\n + 'Defaults to dry-run; execution requires execute=true. Never force-pushes, rebases, resets, cleans, or checks out arbitrary revisions. '\n + 'When the merge path finds the branch ahead with nothing to merge, it returns code \"ahead_needs_push\" pointing at mode=\"push\".',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n mode: { type: 'string', enum: ['merge', 'push'], description: 'merge (default): git merge --ff-only to absorb upstream. push: strict ff-only push of local commits to origin/<branch>; refuses any non-fast-forward.' },\n branch: { type: 'string', description: 'Optional guard: require the node\\'s current branch to match this branch before planning/executing.' },\n execute: { type: 'boolean', description: 'When true, apply the fast-forward/push if all safety gates pass. Defaults false/dry-run.' },\n dry_run: { type: 'boolean', description: 'Preview only. Defaults true unless execute=true; dry_run=true overrides execute.' },\n update_submodules: { type: 'boolean', description: 'mode=\"merge\" only: when true, if the root fast-forward changes gitlinks, run only git submodule update --init --recursive and verify submodules clean.' },\n push_submodules: { type: 'boolean', description: 'mode=\"push\" only: also ff-only push submodule HEADs to their origin main. Gated by mesh policy allowAutoPublishSubmoduleMainCommits — skipped unless that policy is enabled. Defaults false (root push only).' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_RESTART_DAEMON_TOOL = {\n name: 'mesh_restart_daemon',\n description: 'Update a mesh node\\'s daemon to the latest published version on its release channel and restart it — the same path as the dashboard \"preview update\" button, exposed as a mesh command so a coordinator can roll a worker daemon onto a freshly deployed version without a manual restart round-trip. No agent session is launched. '\n + 'Idle-gated: a node whose daemon has an active session (generating / waiting_approval / starting) is refused with code \"blocking_sessions\" so an in-flight turn is never interrupted. '\n + 'If the node is already on the latest version it is a no-op (no restart), matching the dashboard button (returns alreadyLatest:true). '\n + 'Targets a single node — call other (idle) nodes first; restarting the coordinator\\'s OWN daemon is naturally refused while its calling turn is active. '\n + 'Passing channel switches the daemon\\'s release channel (and server URL) before restarting; omit it to keep the daemon on its configured channel.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID — the daemon that owns this node is updated and restarted.' },\n channel: { type: 'string', enum: ['stable', 'preview'], description: 'Optional release channel to update from. Defaults to the daemon\\'s configured updateChannel. Setting it also repoints the daemon\\'s server URL to that channel.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_CHECKPOINT_TOOL = {\n name: 'mesh_checkpoint',\n description: 'Create a git checkpoint (commit) on a mesh node workspace.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n message: { type: 'string', description: 'Checkpoint commit message.' },\n },\n required: ['node_id', 'message'],\n },\n};\n\nexport const MESH_MISSION_UPSERT_TOOL = {\n name: 'mesh_mission_upsert',\n description: 'Create or update a persistent mission record so the plan survives coordinator restarts. '\n + 'Create a mission before enqueueing a multi-task batch, attach tasks via mesh_enqueue_task mission_id, and update status to completed/abandoned when the outcome is decided. Progress is derived from task statuses — there is no separate progress field. '\n + 'Single mission: pass title (and optionally mission_id to update an existing one). '\n + 'Bulk status transition (e.g. one-time stale cleanup): pass mission_ids (array) + status to apply that status to many missions at once; title/goal are ignored and a per-mission result array is returned. mission_ids takes precedence over mission_id when both are given.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n mission_id: { type: 'string', description: 'Mission id to update. Omit to create a new mission. Ignored when mission_ids is provided.' },\n mission_ids: {\n type: 'array',\n items: { type: 'string' },\n description: 'Bulk mode: apply `status` to every listed mission id in one call (stale cleanup). Requires `status`. Returns a per-mission { id, ok, status?, error? } result array. Overrides mission_id/title/goal.',\n },\n title: { type: 'string', description: 'Short mission title. Required to create/update a single mission; ignored in bulk (mission_ids) mode.' },\n goal: { type: 'string', description: 'Free-text mission goal/definition of done. Ignored in bulk (mission_ids) mode.' },\n status: { type: 'string', enum: ['active', 'paused', 'completed', 'abandoned'], description: 'Mission lifecycle status. Defaults to active on create. Required in bulk (mission_ids) mode.' },\n },\n // No hard-required field: the single path requires `title` and the bulk path\n // requires `mission_ids` + `status`; the handler enforces the mode-specific rule\n // and returns a clear error, rather than the schema forcing `title` on bulk calls.\n required: [],\n },\n};\n\nexport const MESH_MISSION_LIST_TOOL = {\n name: 'mesh_mission_list',\n description: 'List missions with their goal, status, and live task progress (total/pending/assigned/completed/failed). '\n + 'Default (no `status`): non-terminal missions (active/paused) return in detail, while completed/abandoned missions are '\n + 'folded into a `historyFold` summary (counts by status + newest-first `missionIds`) rather than listed one-by-one — this '\n + 'keeps the payload bounded as a mesh accumulates hundreds of finished missions. To read finished missions in full, pass '\n + '`status` explicitly (e.g. [\"completed\"]); those are returned in detail but still capped by `limit` (default 50), with '\n + 'overflow reported as truncated=true + overflowIds. '\n + 'Completed MAGI cross-verification missions (one auto-created per mesh_magi_review) are hidden by default to keep the list '\n + 'coordinator-focused — in-progress MAGI missions still show; pass include_magi=true to list completed ones too. '\n + 'Per-mission stats (ledger-scanned durations/attempts) are OMITTED by default — the `tasks` aggregate carries progress; '\n + 'pass include_stats=true (or verbose=true) to attach them. '\n + 'Compact (default) elides the full goal to a capped preview; pass verbose=true for full goal text. Read-only.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n status: {\n type: 'array',\n items: { type: 'string', enum: ['active', 'paused', 'completed', 'abandoned'] },\n description: 'Optional status filter. Omit for the default folded view (active/paused in detail, completed/abandoned summarized). '\n + 'Provide it (e.g. [\"completed\"]) to list those missions in detail — bounded by `limit`.',\n },\n limit: {\n type: 'number',\n description: 'Max missions returned in detail (default 50). Overflow beyond the cap is reported as truncated=true + overflowIds.',\n },\n verbose: { type: 'boolean', description: 'Return full goal text instead of a capped preview (also attaches stats). Defaults to false (compact).' },\n include_stats: { type: 'boolean', description: 'Attach per-mission ledger stats (durations/attempts). Off by default; tasks aggregate is usually enough.' },\n include_magi: { type: 'boolean', description: 'Include completed MAGI cross-verification missions (hidden by default). Defaults to false.' },\n },\n },\n};\n\nexport const MESH_APPROVE_TOOL = {\n name: 'mesh_approve',\n description: 'Approve or reject a pending action on a delegated agent session.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Target node ID.' },\n session_id: { type: 'string', description: 'Agent session ID with pending approval.' },\n action: { type: 'string', enum: ['approve', 'reject'], description: 'Action to take.' },\n },\n required: ['node_id', 'session_id', 'action'],\n },\n};\n\nexport const MESH_LIST_PENDING_APPROVALS_TOOL = {\n name: 'mesh_list_pending_approvals',\n description: 'List every session across the mesh that is currently awaiting an approval decision (status awaiting_approval) — the mesh-wide approval inbox. '\n + 'mesh_approve resolves ONE (node_id, session_id) at a time; this read-only tool enumerates the full pending set so you can see all blocked sessions at once and drive a mesh_approve for each. '\n + 'Each row carries nodeId, sessionId, providerType, taskTitle, and how long it has been waiting (waitingSince/waitingMs), longest-waiting first. Does not mutate anything.',\n inputSchema: {\n type: 'object' as const,\n properties: {},\n },\n};\n\nexport const MESH_CLONE_NODE_TOOL = {\n name: 'mesh_clone_node',\n description: 'Create a new worktree-based node from an existing node for isolated parallel work. '\n + 'Creates a git worktree on a new branch so multiple tasks can run on separate branches simultaneously.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n source_node_id: { type: 'string', description: 'Node ID to clone from (from mesh_list_nodes).' },\n branch: { type: 'string', description: 'Branch name for the new worktree (e.g. \"feat/auth-refactor\").' },\n base_branch: { type: 'string', description: 'Starting point for the branch (default: current HEAD).' },\n },\n required: ['source_node_id', 'branch'],\n },\n};\n\nexport const MESH_REMOVE_NODE_TOOL = {\n name: 'mesh_remove_node',\n description: 'Remove a node from the mesh. If the node is a worktree, also cleans up the git worktree and directory. Session cleanup is controlled by mesh policy sessionCleanupOnNodeRemove unless session_cleanup_mode overrides it for this call. The coordinator\\'s own local base node (same machine, NOT a worktree) is protected — removing it breaks live mesh membership and is rejected unless force:true is passed.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Node ID to remove.' },\n session_cleanup_mode: {\n type: 'string',\n enum: ['preserve', 'stop', 'delete_stopped', 'stop_and_delete'],\n description: 'Optional override for cleanup of delegated sessions attached to this node. preserve keeps history/processes; stop stops live runtimes only; delete_stopped removes completed transcripts only; stop_and_delete stops live runtimes and deletes records.',\n },\n force: { type: 'boolean', description: 'Override the coordinator-base-node guard. Only set true to intentionally tear down this mesh; the coordinator must then be re-registered/restarted. Worktree nodes never need force.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_CLEANUP_SESSIONS_TOOL = {\n name: 'mesh_cleanup_sessions',\n description: 'Manually clean up delegated session records for a mesh node without removing the node. Defaults should preserve reviewable history unless the caller chooses a mode explicitly.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Node ID whose delegated sessions should be considered for cleanup.' },\n mode: {\n type: 'string',\n enum: ['preserve', 'stop', 'delete_stopped', 'stop_and_delete'],\n description: 'preserve = no-op; stop = release process occupancy by stopping live runtimes; delete_stopped = remove completed/stopped records while leaving live runtimes alone; stop_and_delete = stop live runtimes and delete records.',\n },\n session_ids: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional explicit session IDs to limit cleanup to. When omitted, sessions are matched by node/workspace metadata.',\n },\n dry_run: { type: 'boolean', description: 'Preview matched/stopped/deleted/skipped session IDs without mutating session-host state.' },\n },\n required: ['node_id', 'mode'],\n },\n};\n\nexport const MESH_TASK_HISTORY_TOOL = {\n name: 'mesh_task_history',\n description: 'Read the task ledger for this mesh — dispatched tasks, completions, failures, checkpoints, node lifecycle events, and mission lifecycle (mission_created / mission_status_changed / mission_goal_updated). Use to understand what has been done before deciding next steps, to detect repeated failures, to audit mission goal/status changes, and to inform recovery decisions.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n tail: { type: 'number', description: 'Number of recent entries to return (default: 20; clamped to 40 in compact mode, 200 in verbose).' },\n kind: { type: 'string', description: 'Filter by entry kind: task_dispatched, task_completed, task_failed, task_stalled, session_launched, checkpoint_created, node_cloned, node_removed, direct_fast_forward, mission_created, mission_status_changed, mission_goal_updated.' },\n compact: { type: 'boolean', description: 'Slim payload for LLM callers. Default true. Truncates long payload strings (message/taskSummary ≤200, finalSummary ≤300) and elides any large nested evidence blob (>2KB serialized — e.g. validationSummary/result/patchEquivalence/submoduleReachability) to a {_elided,_kind,_bytes,_hint} placeholder; full evidence stays accessible via mesh_reconcile_ledger. Set false (or verbose=true) for full untruncated payloads.' },\n verbose: { type: 'boolean', description: 'Force the full untruncated payload; overrides compact.' },\n },\n },\n};\n\nexport const MESH_LEDGER_QUERY_TOOL = {\n name: 'mesh_ledger_query',\n description: 'Read-only ledger query along the kind / time / node axes — the complement to mesh_task_history (which is task-axis-centric). Use this to answer \"what happened on node X\", \"what failed since <time>\", or \"show every checkpoint_created\" without scanning transcripts. Filters compose (AND): kind narrows to one or more entry kinds, since bounds the time window, node restricts to one node (identity-form-agnostic), tail caps the returned count to the most recent N. Returns the filtered ledger entries (oldest→newest) plus a small summary. Does not mutate anything.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n kind: { type: 'string', description: 'Filter by entry kind. Accepts one kind, or a comma-separated list (e.g. \"task_failed,task_stalled\"). Valid kinds include: task_dispatched, task_completed, task_failed, task_stalled, task_approval_needed, session_launched, session_stopped, checkpoint_created, node_cloned, node_joined, node_removed, direct_fast_forward, ledger_reconciled, event_held, mission_created, mission_status_changed, mission_goal_updated, magi_dispatched, magi_synthesis.' },\n since: { type: 'string', description: 'Only return entries at/after this time. ISO-8601 string (e.g. \"2026-07-05T00:00:00Z\") or epoch-milliseconds. Omit for no lower bound.' },\n node: { type: 'string', description: 'Only return entries originating from this node (nodeId). Matched by daemon-id equivalence, so any identifier form (mach_X / daemon_mach_X) resolves.' },\n tail: { type: 'number', description: 'Return only the most recent N matching entries (default 50; clamped to 500).' },\n },\n },\n};\n\nexport const MESH_RECORD_NOTE_TOOL = {\n name: 'mesh_record_note',\n description: 'Record a durable operating note for this mesh — a runtime-accumulated lesson that future coordinators inherit. '\n + 'Unlike Claude-only memory/CLAUDE.md, this is provider-neutral: it persists in the mesh ledger and is injected into every coordinator\\'s system prompt at launch (codex, hermes, antigravity, claude alike). '\n + 'Use it when you learn something durable: a provider quirk, a pattern to avoid, or a recovery lesson. Keep each note to one concrete, reusable fact. Not for transient task status — use missions/checkpoints for that.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n text: { type: 'string', description: 'The note — one concrete, reusable operating fact/lesson. Phrase it so a future coordinator can act on it without this conversation\\'s context.' },\n category: {\n type: 'string',\n enum: ['provider_quirk', 'pattern_to_avoid', 'recovery_lesson'],\n description: 'Optional classification: provider_quirk (a provider/runtime behaves unexpectedly), pattern_to_avoid (an approach that caused problems), recovery_lesson (how a failure was recovered).',\n },\n },\n required: ['text'],\n },\n};\n\nexport const MESH_FORGET_NOTE_TOOL = {\n name: 'mesh_forget_note',\n description: 'Retract a stale or wrong operating note recorded via mesh_record_note. '\n + 'Appends a tombstone to the mesh ledger so the targeted note(s) stop riding into future coordinators\\' system prompts and drop out of the operating-notes list. '\n + 'History is preserved (append-only) — this suppresses, it does not rewrite. '\n + 'Target by note_id (from mesh_record_note / mesh_task_history) for an exact match, or by text to retract every note with that exact wording. Provide at least one.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n note_id: { type: 'string', description: 'The ledger note id to retract (exact). Returned by mesh_record_note as noteId, or visible in mesh_task_history entries.' },\n text: { type: 'string', description: 'Retract every operating note whose trimmed text exactly matches this string. Use when you do not have the note id.' },\n reason: { type: 'string', description: 'Optional short reason for the retraction, recorded on the tombstone for audit.' },\n },\n },\n};\n\nexport const MESH_RECONCILE_LEDGER_TOOL = {\n name: 'mesh_reconcile_ledger',\n description: 'Reconcile daemon-local mesh ledgers by querying bounded ledger slices over P2P/DataChannel and importing missing entries into the coordinator local JSONL ledger. Cloud/D1 is not used as a ledger source of truth.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_ids: { type: 'array', items: { type: 'string' }, description: 'Optional node IDs to query. Defaults to all mesh nodes.' },\n limit: { type: 'number', description: 'Bounded slice size per node. Defaults to 100 and is clamped by daemon-core.' },\n after_id: { type: 'string', description: 'Optional cursor entry ID; remote slices return entries strictly after this ID when present.' },\n since: { type: 'string', description: 'Optional ISO timestamp lower bound for queried entries.' },\n import_entries: { type: 'boolean', description: 'When false, query and report evidence without importing remote entries. Defaults true.' },\n },\n },\n};\n\nexport const MESH_REQUEUE_HELD_EVENTS_TOOL = {\n name: 'mesh_requeue_held_events',\n description: 'Restore recoverable held coordinator events back to the pending queue. T6 quarantine (v2 enforce) and the pending-events trim mirror a destructively-drained-but-undelivered event into the ledger as a recoverable `event_held` entry — this is the operator path that actually requeues them (event_held→pending), so a coordinator drains them on its next poll. Lossless: the full original event is restored, the pending-queue dedup suppresses any still-live duplicate, and each held entry is marked once so a second call does not requeue it again. Read-only by default? No — it mutates the pending queue; scope it with `filter` when you only want a subset.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n filter: {\n type: 'object',\n description: 'Optional narrowing filter within this mesh. Omit to requeue every not-yet-recovered held event.',\n properties: {\n task_id: { type: 'string', description: 'Only requeue held events for this worker task id.' },\n node_id: { type: 'string', description: 'Only requeue held events originating from this node.' },\n event: { type: 'string', description: 'Only requeue held events of this event name (e.g. session:completed).' },\n reason: { type: 'string', description: 'Only requeue held entries with this hold reason (e.g. pending_trim_dropped, v2_enforce_validation_failed_quarantined).' },\n since: { type: 'string', description: 'Only requeue held entries recorded at/after this ISO timestamp.' },\n },\n },\n },\n },\n};\n\nexport const MESH_PRUNE_STALE_DIRECT_TOOL = {\n name: 'mesh_prune_stale_direct',\n description: 'Prune orphaned staleDirect dispatch records — direct task dispatches whose original node/session is no longer present in the live mesh. dry_run (default) reports exactly which records would be pruned without mutating anything; pass execute=true to delete them. Active/pending/assigned/generating work and fresh unacknowledged dispatch failures (node/session still live) are always preserved. The append-only mesh ledger audit history is left intact.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n execute: { type: 'boolean', description: 'When true, actually delete the orphaned records. Defaults false (dry run). Ignored when dry_run=true.' },\n dry_run: { type: 'boolean', description: 'Force a preview without mutation even if execute=true. Defaults to dry-run behavior when execute is not set.' },\n include_terminal: { type: 'boolean', description: 'Also prune terminal (completed/failed) direct dispatch store rows in addition to orphans. Defaults false.' },\n },\n },\n};\n\nexport const MESH_REFINE_NODE_TOOL = {\n name: 'mesh_refine_node',\n description: 'The Refinery: validate → merge → push → clean up a completed worktree node onto the base branch. '\n + 'Defaults to dry-run (plan only): returns the validation plan with mergeWillRun:false/cleanupWillRun:false and performs NO merge/push/cleanup. '\n + 'Pass execute=true to actually converge the node. execute=true is async: the immediate response includes async:true, status:\\'accepted\\', jobId, interactionId, target node, and startedAt; completion/failure evidence is delivered through pending mesh events and the mesh task ledger. '\n + 'dry_run=true overrides execute. Matches the mesh_refine_batch / mesh_fast_forward_node dry_run/execute contract.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Node ID of the completed worktree node to refine and merge.' },\n execute: { type: 'boolean', description: 'When true, run validation/merge/push/cleanup for this node. Defaults false/dry-run.' },\n dry_run: { type: 'boolean', description: 'Preview the validation plan without merging. Defaults true unless execute=true; dry_run=true overrides execute.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_REFINE_BATCH_TOOL = {\n name: 'mesh_refine_batch',\n description: 'Batch Refinery: converge multiple sibling worktree nodes onto the base branch in one conflict-aware sequential pipeline. '\n + 'Orders nodes by change-area (non-submodule nodes first, submodule-touching nodes serialized last) so each merged sibling advances the base and the next node auto-rebases + re-checks patch-equivalence before its own merge. '\n + 'Each node runs the same validation/patch-equivalence/submodule-reachability/merge/cleanup gates as mesh_refine_node. '\n + 'Conflicting or blocked nodes are isolated as blocked_review while the rest of the batch proceeds. Defaults to dry-run (plan only); set execute=true to converge. Never force-pushes or resets. '\n + 'execute=true is async: the immediate response is async:true / status:\\'accepted\\' with the batch jobId and ordered target node list; per-node convergence runs in the background and the aggregate completion/failure (with per-node merged / blocked_review / not_mergeable results) is delivered as a terminal refine event via pending mesh events and the ledger — do not re-invoke while a batch is in flight. dry_run returns the plan synchronously.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_ids: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional explicit node IDs to converge, in any order (the tool computes the safe merge order). When omitted, all local worktree nodes that need convergence are auto-collected.',\n },\n execute: { type: 'boolean', description: 'When true, run validation/rebase/merge for each node in order. Defaults false/dry-run.' },\n dry_run: { type: 'boolean', description: 'Preview the ordering + per-node validation plan without executing. Defaults true unless execute=true; dry_run=true overrides execute.' },\n },\n required: [],\n },\n};\n\n// Unified read-only Refinery config helper. Consolidates the former\n// mesh_refine_config_schema / mesh_validate_refine_config / mesh_suggest_refine_config\n// tools into a single `mode`-dispatched tool (MESH-COMPLEXITY-AUDIT Part 8-4). The old\n// three names remain dispatchable as 1-release hidden aliases (see server.ts), but only\n// this unified tool is published in ALL_MESH_TOOLS. These are read-only helpers — they\n// never run validation commands or git merges (that is mesh_refine_node / mesh_refine_plan).\nexport const MESH_REFINE_CONFIG_TOOL = {\n name: 'mesh_refine_config',\n description: 'Repo Mesh Refinery config helper — unified read-only entry for the three refine-config operations. Select the operation with `mode` (REQUIRED). '\n + 'mode=\\'schema\\': return the Refinery config JSON schema and supported repo-local config locations (the validation source of truth; heuristic command detection is suggestions-only) — takes no other parameters. '\n + 'mode=\\'validate\\': validate the repo mesh/refine config for a node/workspace without running validation commands or merging — accepts optional `node_id` (defaults to the first mesh node) and an optional inline `config` object (validated instead of loading from the repo). '\n + 'mode=\\'suggest\\': suggest a refine config scaffold from project context/package scripts (never executed until saved) — accepts optional `node_id`. '\n + 'Does NOT run validation commands or git merges — use mesh_refine_node / mesh_refine_plan for execution.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n mode: {\n type: 'string',\n enum: ['schema', 'validate', 'suggest'],\n description: 'Which config operation to run (required). schema: return the config JSON schema (no other params). validate: validate a node/workspace refine config (optional node_id, optional inline config). suggest: scaffold a config from project context (optional node_id).',\n },\n node_id: { type: 'string', description: 'Optional node/workspace. Used by mode=validate (config to load) and mode=suggest (context source); defaults to the first mesh node. Ignored by mode=schema.' },\n config: { type: 'object', description: 'Optional inline config object to validate instead of loading from the repo. Only used by mode=validate.' },\n },\n required: ['mode'],\n },\n};\n\n// Unified read-only Change Impact config helper. Consolidates the former\n// mesh_change_impact_config_schema / mesh_validate_change_impact_config /\n// mesh_suggest_change_impact_config tools into a single `mode`-dispatched tool\n// (MESH-COMPLEXITY-AUDIT, symmetric to the Part 8-4 refine-config consolidation). The old\n// three names remain dispatchable as 1-release hidden aliases (see server.ts), but only this\n// unified tool is published in ALL_MESH_TOOLS. These are read-only helpers — Change Impact\n// config is declarative and parsed, never executed.\nexport const MESH_CHANGE_IMPACT_CONFIG_TOOL = {\n name: 'mesh_change_impact_config',\n description: 'Repo Mesh Change Impact config helper — unified read-only entry for the three change-impact config operations. '\n + 'Change Impact config declaratively classifies which package/file changes between the live daemon build and workspace HEAD require a daemon rebuild/restart vs. a web-only redeploy vs. nothing (parsed, never executed). Select the operation with `mode` (REQUIRED). '\n + 'mode=\\'schema\\': return the Change Impact config JSON schema and supported repo-local config locations — takes no other parameters. '\n + 'mode=\\'validate\\': validate a Change Impact config for a node/workspace and report valid/errors — loads .adhdev/change-impact.{json,yaml,yml} (or repo-mesh-change-impact.* alias) unless an inline `config` object is provided; accepts optional `node_id` (defaults to the first mesh node). '\n + 'mode=\\'suggest\\': suggest a Change Impact config scaffold from the repo package layout (web-* → web-only, others → daemon-runtime, plus docs/license markers as non-runtime) — the draft must be reviewed and saved before it takes effect; accepts optional `node_id`. '\n + 'Declarative only — nothing is executed.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n mode: {\n type: 'string',\n enum: ['schema', 'validate', 'suggest'],\n description: 'Which config operation to run (required). schema: return the config JSON schema (no other params). validate: validate a node/workspace change-impact config (optional node_id, optional inline config). suggest: scaffold a config from the repo package layout (optional node_id).',\n },\n node_id: { type: 'string', description: 'Optional node/workspace. Used by mode=validate (config to load) and mode=suggest (context source); defaults to the first mesh node. Ignored by mode=schema.' },\n config: { type: 'object', description: 'Optional inline config object to validate instead of loading from the repo. Only used by mode=validate.' },\n },\n required: ['mode'],\n },\n};\n\nexport const MESH_INIT_TOOL = {\n name: 'mesh_init',\n description: 'One-click mesh onboarding for an existing git project. Detects installed CLI providers, suggests all three repo `.adhdev/*` config families — Refinery (.adhdev/refine.json), worktree bootstrap (.adhdev/worktree_bootstrap.json) AND change-impact (.adhdev/change-impact.json) — optionally writes them to disk, and recommends a node providerPriority from the detected providers. Also returns `currentConfig`: the currently-saved config per domain (repo files + machine-local magiKindPanels) so you can present a current-vs-suggested diff before overwriting. Suggestions are scaffold only and never execute until saved; providerPriority is a recommendation to apply to node policy, not auto-applied. Defaults to dry-run (no files written) and never overwrites an existing config unless overwrite=true. For an already-onboarded repo that needs refreshing, use mesh_reinit (overwrite semantics + enforced diff).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Optional node/workspace to onboard. Defaults to the first mesh node with a workspace.' },\n write: { type: 'boolean', description: 'When true, persist the suggested configs to disk. Defaults false (dry-run preview only).' },\n overwrite: { type: 'boolean', description: 'When true, overwrite an existing config file. Defaults false (never clobber an existing refine/bootstrap config).' },\n },\n },\n};\n\nexport const MESH_REINIT_TOOL = {\n name: 'mesh_reinit',\n description: 'Re-onboard an ALREADY-initialized repo: re-suggest the repo `.adhdev/*` configs (refine / worktree_bootstrap / change-impact) with OVERWRITE semantics and return a current-vs-suggested diff so you can replace stale config. This is NOT a new write engine — it reuses mesh_init\\'s suggest→validate→gated-write with overwrite=true (default) plus the current-config echo (`currentConfig`). CONTRACT: overwrite is a WHOLESALE replacement, so it must NOT silently drop operator hand-edits — the first call (write=false, the default) is a DRY-RUN preview that surfaces the per-section diff; you MUST present that current-vs-suggested diff and get EXPLICIT per-section user approval, then re-invoke with write=true. Use mesh_init (not reinit) for a fresh, never-onboarded repo.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Optional node/workspace to re-onboard. Defaults to the first mesh node with a workspace.' },\n write: { type: 'boolean', description: 'When true, persist the overwritten configs. Defaults false (dry-run preview surfacing the current-vs-suggested diff — approve per-section first).' },\n overwrite: { type: 'boolean', description: 'Defaults true (reinit replaces existing config). Pass false to fall back to existing-wins (equivalent to mesh_init).' },\n },\n },\n};\n\nexport const MESH_REFINE_PLAN_TOOL = {\n name: 'mesh_refine_plan',\n description: 'Dry-run Refinery plan for a worktree node: reports config source, validation commands, suggestions/unavailable reason, and merge/cleanup intent without executing validation or git merge.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Node ID of the worktree node to plan.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_REVIEW_INBOX_TOOL = {\n name: 'mesh_review_inbox',\n description: 'List local worktree nodes that need human review: merge candidates (pushed feature branches ready to merge) and Refinery-blocked review results. Returns evidence summaries, diff stats vs. the default branch, and suggested actions (Refine / Requeue / Dismiss). Remote nodes are excluded in M4.0.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n mesh_id: { type: 'string', description: 'Mesh ID (optional — inferred from active mesh if omitted).' },\n },\n required: [],\n },\n};\n\n// ─── MAGI — Multi-Agent Ground-truth Insight ──\n\nexport const MESH_MAGI_REVIEW_TOOL = {\n name: 'mesh_magi_review',\n description: 'Cross-verify a read-only investigation across a standing panel of independent mesh agents (different machines/providers), instead of sending a SINGLE read-only worker. Drop-in for any read-only investigation — bug RCA, defect/regression measurement, \"why does this code do X?\", or doc/design/API review. Fans the SAME question out to N independent (node × provider) replicas, then synthesizes consensus/disagreement/unique evidence into a needs_verification list — NOT a majority vote (high agreement among coupled agents ≠ correct). Read-only is FORCED (no execute/write flag exists). COST: multiplies token spend by the total replica count (the call is the opt-in). PANEL RESOLUTION: the panel is resolved SOLELY from the USER-CONFIGURED kind-panel binding for the given `task_kind` (mesh settings → magiKindPanels: task_kind → (node × provider × model) slots). `task_kind` is REQUIRED — there is NO named-panel, inline-members, or automatic-preset path. A task_kind with no configured kind-panel errors `magi_kind_not_configured` (configure slots in mesh settings first). The binding must resolve to ≥2 (node, provider) targets; never silently degrades to N=1 (errors magi_insufficient_targets if the live mesh cannot supply the configured slots).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n question: { type: 'string', description: 'The single investigation question every agent answers — e.g. \"What is the root cause of this defect?\", \"Refute this RCA.\", \"Why does this code do X?\". Not only \"review this\".' },\n target: { type: 'string', description: 'What to investigate — file path(s), a bug symptom / error / stack trace, a code area / symbol, or omitted when the question is self-contained.' },\n artifacts: { type: 'array', items: { type: 'string' }, description: 'Inline content when not file-backed: a doc/diff, a log/error dump, or a prior single-worker RCA to refute.' },\n n: { type: 'number', description: 'Global replica override per slot (clamped by the total-replica guard cap, default 12).' },\n task_kind: { type: 'string', enum: ['claim_audit', 'rca', 'design', 'freeform'], description: 'REQUIRED. Selects (1) the SINGLE output schema injected into each replica prompt and the strict parser used at collection (no schema-on-schema conflict), AND (2) the user-configured kind-panel binding that supplies the fan-out slots (mesh settings → magiKindPanels; errors magi_kind_not_configured if that kind has no configured slots — no named-panel/inline/preset fallback). claim_audit: {claims[],top_findings[],open_questions[]}. rca: {rootCause,failsAt,mechanism,evidence[],fixDirection,confidence}. design: {recommendation,rationale,alternatives[],tradeoffs[],risks[],evidence[],confidence}. freeform: no schema — natural-language answer, parsing/evidence checks waived, cross-verification is weak. Every kind except freeform requires non-empty evidence[]; an empty-evidence or schema-invalid answer triggers ONE delta re-request before being dropped as unparseable. Do NOT also embed an output-format schema in the question — it collides with this contract (a warning is surfaced if detected).' },\n mode: { type: 'string', enum: ['rca', 'investigation', 'claim_audit', 'design_review', 'code_audit'], description: 'Synthesis emphasis hint — affects labels only, never the agent count or schema. Distinct from task_kind (which selects the output schema).' },\n use_judge: { type: 'boolean', description: 'Default false (clustering synthesis). STUB: judge synthesis is not yet implemented — passing true currently falls back to clustering with a warning. Reserved interface only.' },\n require_independent_evidence: { type: 'boolean', description: 'Default true — high-impact claims with no file:line/source evidence are routed to needs_verification.' },\n include_stale: { type: 'boolean', description: 'Default false. By default, panel slots whose node HEAD commit differs from the coordinator reference commit are EXCLUDED (they would investigate different code). Set true to fan out to them anyway — results will be git-skewed and a warning is surfaced. If exclusion drops the panel below 2 independent targets the call errors rather than degrading to N=1; include_stale=true is one way to recover.' },\n wait: { type: 'boolean', description: 'Default true — collect replica outputs and return the synthesis. Set false to dispatch async and return a consensusGroupId handle; collect later with mesh_magi_collect.' },\n wait_timeout_ms: { type: 'number', description: 'Max time to wait for replica completion before returning a partial \"missing K of N\" synthesis. Default ~4 min.' },\n auto_cleanup: { type: 'boolean', description: 'Default = mesh policy magiSessionCleanup (ON / stop_and_delete unless overridden). Once all replicas are terminal, stop+delete ONLY the worker sessions THIS fan-out auto-launched (marker-verified) so repeated reviews don\\'t accumulate idle worker sessions. Reused/coordinator/other sessions are never touched. Set false to preserve auto-launched worker sessions for inspection. No effect on a partial (non-terminal) collection.' },\n },\n required: ['question', 'task_kind'],\n },\n};\n\nexport const MESH_MAGI_COLLECT_TOOL = {\n name: 'mesh_magi_collect',\n description: 'Collect + synthesize a previously dispatched MAGI fan-out by its consensus group id — the async companion to mesh_magi_review({ wait:false }). Rediscovers the replica tasks from the queue and runs the SAME diversity-weighted synthesis (consensus/disagreement/unique-evidence → needs_verification list). Defaults to a SNAPSHOT (wait=false): returns whatever replicas are terminal right now, with a pending note if some are still generating; pass wait=true to block for the rest. Read-only. Drive off mission completion / pendingCoordinatorEvents rather than polling this in a tight loop.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n consensus_group_id: { type: 'string', description: 'The consensusGroupId returned by a wait=false mesh_magi_review.' },\n task_kind: { type: 'string', enum: ['claim_audit', 'rca', 'design', 'freeform'], description: 'Optional override of the task_kind used to parse replica answers. Normally recovered automatically from the original dispatch — only set this if the dispatched ledger entry was pruned and auto-recovery falls back to claim_audit incorrectly.' },\n require_independent_evidence: { type: 'boolean', description: 'Default true — high-impact claims with no file:line/source evidence are routed to needs_verification.' },\n wait: { type: 'boolean', description: 'Default false (snapshot). Set true to block for outstanding replicas up to wait_timeout_ms before synthesizing.' },\n wait_timeout_ms: { type: 'number', description: 'When wait=true, max time to wait for remaining replica completion. Default ~4 min.' },\n auto_cleanup: { type: 'boolean', description: 'Default = mesh policy magiSessionCleanup (ON / stop_and_delete). When the collection is terminal, stop+delete ONLY the worker sessions THIS fan-out auto-launched (marker-verified). Reused/coordinator/other sessions are never touched. Set false to preserve them. No effect on a partial (non-terminal) snapshot.' },\n verbose: { type: 'boolean', description: 'Default false. When true, each synthesis.replicas[] entry also carries rawAnswer — the replica\\'s raw end-user answer text (capped). Omitted by default to keep the payload small; the structured clusters already carry the parsed claims.' },\n },\n required: ['consensus_group_id'],\n },\n};\n\nexport const MESH_MAGI_KIND_PANEL_SET_TOOL = {\n name: 'mesh_magi_kind_panel_set',\n description: 'Bind a task_kind to its MAGI kind-panel slot list (machine-local ~/.adhdev/meshes.json `magiKindPanels`). This binding is what a `mesh_magi_review({ task_kind })` resolves to — it is the SOLE panel-resolution path (there is no named-panel or inline-members alternative). IMPORTANT — WHOLESALE REPLACEMENT: a task_kind has exactly one binding, so the `slots` you pass become the COMPLETE new slot set and any prior slots for that kind are dropped (not merged). Because it silently replaces the current binding, get EXPLICIT user approval before writing and present the current-vs-new slot lists (the dry-run returns `currentSlots`). Defaults to dry-run (write=false). Machine-local scope (NOT a repo-committed file).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n task_kind: { type: 'string', description: 'The task_kind key to bind, e.g. claim_audit / rca / design / freeform.' },\n slots: {\n type: 'array',\n description: 'The COMPLETE desired slot list for this kind (wholesale replacement). Each slot: { provider (REQUIRED), nodeId?, model?, capabilityTags?, n? }.',\n items: {\n type: 'object',\n properties: {\n provider: { type: 'string', description: 'REQUIRED — provider type, e.g. claude-cli / codex-cli / gemini-cli / hermes-cli.' },\n nodeId: { type: 'string', description: 'Optional — pin to a specific mesh node id.' },\n model: { type: 'string', description: 'Optional — pin a specific model for this slot.' },\n capabilityTags: { type: 'array', items: { type: 'string' }, description: 'Optional routing tags (ANDed with the provider tag) when nodeId is absent.' },\n n: { type: 'number', description: 'Optional per-slot replica count (default 1).' },\n },\n required: ['provider'],\n },\n },\n write: { type: 'boolean', description: 'When true, persist the slot list (wholesale replacement) to meshes.json. Defaults false (dry-run preview of the normalized slots + currentSlots).' },\n },\n required: ['task_kind', 'slots'],\n },\n};\n\nexport const MESH_MAGI_KIND_PANEL_LIST_TOOL = {\n name: 'mesh_magi_kind_panel_list',\n description: 'List the configured MAGI kind→panel slot bindings (machine-local). Read-only. Use to confirm what a `task_kind` resolves to before mesh_magi_review, and to diff current-vs-new before an overwrite via mesh_magi_kind_panel_set.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n task_kind: { type: 'string', description: 'Optional — show only this task_kind\\'s binding. Omit to list all configured kind bindings.' },\n },\n },\n};\n\nexport const MESH_NODE_SLOTS_SET_TOOL = {\n name: 'mesh_node_slots_set',\n description: 'PROPOSE (dry-run) or APPLY a mesh node\\'s capability-slot list (policy.slots) — the orchestrator\\'s surface for autonomously adjusting a node\\'s AI-tool profile mid-run (ORCHESTRATION_NODE_SLOTS.md §5). A node\\'s slots drive task→node fitness routing and MAGI fan-out, so changing them changes how work is distributed. IMPORTANT — WHOLESALE REPLACEMENT: the `slots` you pass become the node\\'s COMPLETE new slot list; any prior slot not in the list is dropped (not merged). Because it silently replaces the profile, get EXPLICIT user approval before writing: the default dry-run (write=false) returns `currentSlots` vs `proposedSlots` for you to present as a diff — re-run with write=true ONLY after the user approves. Apply goes through update_mesh_node (machine-local node policy).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'REQUIRED — the mesh node id whose capability slots to set.' },\n slots: {\n type: 'array',\n description: 'The COMPLETE desired capability-slot list for this node (wholesale replacement). Each slot: { provider (REQUIRED), model?, thinkingLevel?, difficulty?, capability?, maxParallel? }.',\n items: {\n type: 'object',\n properties: {\n provider: { type: 'string', description: 'REQUIRED — provider type, e.g. claude-cli / codex-cli / gemini-cli / hermes-cli.' },\n model: { type: 'string', description: 'Optional — model for this slot (best-effort at launch, e.g. opus / gpt-5-codex).' },\n thinkingLevel: { type: 'string', description: 'Optional — provider-specific thinking level verbatim (e.g. low/medium/high/max, or codex minimal/xhigh).' },\n difficulty: { type: 'array', items: { type: 'string' }, description: 'Optional — task difficulties this slot handles (easy/medium/difficult/freeform). Empty = all (general-purpose).' },\n capability: { type: 'array', items: { type: 'string' }, description: 'Optional — capability tags this slot satisfies (matched against a task\\'s requiredTags).' },\n maxParallel: { type: 'number', description: 'Optional — per-node·per-slot max concurrent tasks. Omit = no per-slot cap.' },\n },\n required: ['provider'],\n },\n },\n reason: { type: 'string', description: 'Optional — a short rationale for the proposal, echoed in the dry-run so the user sees WHY the change is suggested.' },\n write: { type: 'boolean', description: 'When true, apply the slot list (wholesale replacement) to the node. Defaults false (dry-run preview of proposedSlots + currentSlots).' },\n },\n required: ['node_id', 'slots'],\n },\n};\n\nexport const MESH_NODE_SLOTS_LIST_TOOL = {\n name: 'mesh_node_slots_list',\n description: 'List a mesh node\\'s capability slots (policy.slots). Read-only. Use to confirm the current AI-tool profile of a node and to diff current-vs-proposed before a mesh_node_slots_set overwrite.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'REQUIRED — the mesh node id whose capability slots to list.' },\n },\n required: ['node_id'],\n },\n};\n\nexport const MESH_WRITE_MESH_JSON_CONFIG_TOOL = {\n name: 'mesh_write_mesh_json_config',\n description: 'Write `.adhdev/mesh.json` (the repo-committed coordinator prompt override/append + declarative config) from the machine-local mesh entry. Gated WRITE sibling of the draft-only export_mesh_json_config. Follows the mesh_init write/overwrite/dry-run precedent: defaults to dry-run (write=false), never clobbers an existing repo mesh.json unless overwrite=true, and validates before writing. Overwrite silently replaces the file, so present a current-vs-suggested diff and get explicit approval first. REPO-COMMITTED scope (commit target) — distinct from the machine-local MAGI kind-panel writes.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n write: { type: 'boolean', description: 'When true, persist .adhdev/mesh.json to the repo (commit target). Defaults false (dry-run preview).' },\n overwrite: { type: 'boolean', description: 'When true, replace an existing .adhdev/mesh.json. Defaults false (never clobber an existing repo mesh.json).' },\n workspace: { type: 'string', description: 'Optional workspace path whose .adhdev/mesh.json is written. Defaults to the coordinator node workspace.' },\n },\n },\n};\n\nexport const ALL_MESH_TOOLS = [\n MESH_STATUS_TOOL,\n MESH_LIST_NODES_TOOL,\n MESH_ENQUEUE_TASK_TOOL,\n MESH_VIEW_QUEUE_TOOL,\n MESH_QUEUE_CANCEL_TOOL,\n MESH_QUEUE_REQUEUE_TOOL,\n MESH_SEND_TASK_TOOL,\n MESH_READ_CHAT_TOOL,\n MESH_READ_DEBUG_TOOL,\n MESH_READ_TERMINAL_TOOL,\n MESH_SEND_KEYS_TOOL,\n MESH_LAUNCH_SESSION_TOOL,\n MESH_GIT_STATUS_TOOL,\n MESH_READ_NODE_LOGS_TOOL,\n MESH_FAST_FORWARD_NODE_TOOL,\n MESH_RESTART_DAEMON_TOOL,\n MESH_CHECKPOINT_TOOL,\n MESH_APPROVE_TOOL,\n MESH_LIST_PENDING_APPROVALS_TOOL,\n MESH_CLONE_NODE_TOOL,\n MESH_REMOVE_NODE_TOOL,\n MESH_REFINE_NODE_TOOL,\n MESH_REFINE_BATCH_TOOL,\n MESH_REFINE_CONFIG_TOOL,\n MESH_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_INIT_TOOL,\n MESH_REINIT_TOOL,\n MESH_WRITE_MESH_JSON_CONFIG_TOOL,\n MESH_REFINE_PLAN_TOOL,\n MESH_CLEANUP_SESSIONS_TOOL,\n MESH_PRUNE_STALE_DIRECT_TOOL,\n MESH_TASK_HISTORY_TOOL,\n MESH_LEDGER_QUERY_TOOL,\n MESH_RECORD_NOTE_TOOL,\n MESH_FORGET_NOTE_TOOL,\n MESH_RECONCILE_LEDGER_TOOL,\n MESH_REQUEUE_HELD_EVENTS_TOOL,\n MESH_MISSION_UPSERT_TOOL,\n MESH_MISSION_LIST_TOOL,\n MESH_REVIEW_INBOX_TOOL,\n MESH_MAGI_REVIEW_TOOL,\n MESH_MAGI_COLLECT_TOOL,\n MESH_MAGI_KIND_PANEL_SET_TOOL,\n MESH_MAGI_KIND_PANEL_LIST_TOOL,\n MESH_NODE_SLOTS_SET_TOOL,\n MESH_NODE_SLOTS_LIST_TOOL,\n];\n","/**\n * mesh_status compact-mode per-node fold helpers.\n *\n * Physically split out of mesh-tools.ts (RF-SURVEY candidate C1) with no behavior\n * change. Slims the LLM-facing node copy: compact git snapshot, the canonical\n * preserved-marker list, the full per-node compaction (compactMeshStatusNode), the\n * quiet-node minimal stub (minimalCompactNode), node severity / noteworthiness\n * ranking, and the per-node session summary. Imports only the shared large-value\n * elider; the mesh_status node-array byte-budget bounding stays in mesh-tools.ts and\n * imports these back, so there is no runtime import cycle.\n */\nimport { elideLargeNestedValue } from './mesh-tool-shared.js';\n\n// Compact-mode git snapshot for LLM callers: keep the coordinator-relevant scalar\n// signals (branch/upstream/ahead/behind/dirty/headCommit) and the submodules array\n// (its out-of-sync state drives convergence decisions) while dropping the large\n// duplicated blobs (full changed-file lists, diffs, raw porcelain) that the full\n// dashboard payload carries. The full status object remains available via verbose.\nfunction buildCompactGitSnapshot(status: any): Record<string, unknown> | undefined {\n if (!status || typeof status !== 'object' || Array.isArray(status)) return undefined;\n const slim: Record<string, unknown> = {};\n const carry = [\n 'isGitRepo',\n 'branch',\n 'headCommit',\n 'upstream',\n 'upstreamStatus',\n 'ahead',\n 'behind',\n 'dirty',\n 'detached',\n 'submodules',\n ];\n for (const key of carry) {\n if (status[key] !== undefined) slim[key] = status[key];\n }\n return slim;\n}\n\n// Compact-mode submodules fold: the full submodules array (path/commit/status/\n// branch per submodule) is repeated on every node that shares a superproject, so\n// it grows O(nodes × submodules). In compact mode we keep the actionable signal\n// (count + the out-of-sync paths, which drive convergence decisions) and drop the\n// per-submodule commit/status blobs. The full array stays in verbose. Out-of-sync\n// paths are also surfaced separately on the node as `outOfSyncSubmodules`.\nfunction summarizeCompactSubmodules(submodules: any): Record<string, unknown> | undefined {\n if (!Array.isArray(submodules) || submodules.length === 0) return undefined;\n const outOfSync = submodules.filter((s: any) => s?.outOfSync).map((s: any) => s?.path).filter(Boolean);\n return {\n count: submodules.length,\n ...(outOfSync.length > 0 ? { outOfSyncPaths: outOfSync } : {}),\n };\n}\n\n// Canonical set of small per-node MARKER fields that MUST survive compact folding\n// intact on every node — quiet stub or detailed. Both fold paths reference this one\n// list: (a) the generic elide backstop skips these so they aren't truncated, and\n// (b) the minimal-stub reconstruction (minimalCompactNode) re-attaches them. Keeping\n// it single-sourced is the fix for the class of bug the rc.371 dataFreshness\n// regression exposed — a canonical node marker that survived the elide skip-list but\n// was silently dropped by the allowlist-based minimal stub, so it read null on\n// exactly the quiet nodes a coordinator most needs the marker for. Add a new marker\n// field HERE once and both fold paths preserve it; never hand-list it in two places.\nconst MESH_COMPACT_PRESERVED_MARKER_FIELDS = ['dataFreshness'] as const;\n\n// Compact-mode per-node fold for mesh_status. The dashboard/verbose payload\n// (`results`) is untouched; this only slims the LLM-facing node copy. It folds\n// the repetitive heavy fields that scale O(nodes):\n// - git: slim scalar snapshot + summarized submodules (no full file lists/blobs)\n// - machine: drop the verbose identityEvidence[] array and the long\n// localityReason string (which interpolates every evidence token) — keep the\n// resolved scalars (displayName/daemonId/machineId/hostname/sameMachine/locality)\n// - staleDaemonBuild: the full ~300-char warning + duplicated build fields are\n// already aggregated ONCE at the top level under staleDaemonBuilds[] +\n// staleDaemonBuildWarning. On the node, collapse to a short boolean-ish flag so\n// the per-node copy isn't N× the same warning text.\n// - branchConvergence: keep the decision fields (status/needsConvergence/reason/\n// branch/ahead/behind); drop the long per-node nextStep prose (it is echoed in\n// nextStepHints and branchConvergenceSummary).\n// Any remaining oversized nested blob is elided by the generic byte guard.\nexport function compactMeshStatusNode(entry: any): any {\n if (!entry || typeof entry !== 'object') return entry;\n const next: any = { ...entry };\n\n if (next.git !== undefined) {\n const slimGit = buildCompactGitSnapshot(next.git);\n if (slimGit) {\n if (slimGit.submodules !== undefined) {\n const subSummary = summarizeCompactSubmodules(slimGit.submodules);\n if (subSummary) slimGit.submodules = subSummary;\n else delete slimGit.submodules;\n }\n next.git = slimGit;\n }\n }\n\n if (next.machine && typeof next.machine === 'object') {\n const m = next.machine as Record<string, unknown>;\n next.machine = {\n daemonId: m.daemonId,\n machineId: m.machineId,\n hostname: m.hostname,\n displayName: m.displayName,\n sameMachine: m.sameMachine,\n locality: m.locality,\n };\n }\n\n // submoduleWarning is a fixed ~120-char prose string repeated on every node\n // with an out-of-sync submodule. The actionable signal (which submodules) is\n // already on `outOfSyncSubmodules`; collapse the prose to a boolean flag in\n // compact mode.\n if (typeof next.submoduleWarning === 'string') {\n next.submodulesOutOfSync = true;\n delete next.submoduleWarning;\n }\n\n if (next.staleDaemonBuild && typeof next.staleDaemonBuild === 'object') {\n const b = next.staleDaemonBuild as Record<string, unknown>;\n // Replace the full per-node object (warning prose + build fields, all of\n // which are aggregated top-level) with a terse flag. The daemonId lets the\n // coordinator cross-reference the top-level staleDaemonBuilds[] entry.\n next.staleDaemonBuild = {\n scope: b.scope,\n isDaemonAffecting: b.isDaemonAffecting !== false,\n seeStaleDaemonBuilds: true,\n };\n }\n\n // branchConvergence is kept intact for detailed compact nodes (it carries the\n // actionable per-node nextStep). It is small per-node and bounded by the\n // detail byte-budget; the larger repetition lives in branchConvergenceSummary,\n // which is capped separately. Quiet nodes drop nextStep via minimalCompactNode.\n\n // capabilityTagsByProvider repeats the os=/arch=/converge= base set once per\n // provider — heavy and O(nodes × providers). The representative capabilityTags\n // (kept) already conveys what a node can match; the per-provider breakdown is a\n // verbose/dashboard concern. Drop it from the compact LLM-facing copy.\n delete next.capabilityTagsByProvider;\n\n // Generic backstop: elide any other oversized nested blob on the node. The\n // structural blobs slimmed above plus the canonical preserved markers are skipped\n // so the byte guard never truncates them.\n const elideSkip = new Set<string>(['git', 'machine', 'branchConvergence', 'staleDaemonBuild', 'sessions', ...MESH_COMPACT_PRESERVED_MARKER_FIELDS]);\n for (const k of Object.keys(next)) {\n if (elideSkip.has(k)) continue;\n next[k] = elideLargeNestedValue(k, next[k]);\n }\n\n return next;\n}\n\n// Rough severity ranking so that when the byte budget forces a downgrade, the most\n// urgent nodes (errors/degraded/blocked launches) are the ones kept in detail.\nexport function compactNodeSeverity(entry: any): number {\n if (!entry || typeof entry !== 'object') return 0;\n if (entry.error || (entry.health && entry.health !== 'online' && entry.health !== 'dirty')) return 5;\n if (entry.launchReady === false) return 4;\n if (entry.isDirty === true || entry.health === 'dirty') return 3;\n if (entry.branchConvergence?.needsConvergence === true) return 2;\n if (entry.staleDaemonBuild || entry.submodulesOutOfSync || entry.recoveryHints) return 1;\n return 0;\n}\n\nexport function isNoteworthyCompactNode(entry: any): boolean {\n if (!entry || typeof entry !== 'object') return true;\n if (entry.health && entry.health !== 'online') return true;\n if (entry.isDirty === true) return true;\n if (entry.error) return true;\n if (entry.launchReady === false) return true;\n if (entry.staleDaemonBuild) return true;\n if (entry.submoduleWarning || entry.submodulesOutOfSync) return true;\n if (entry.recoveryHints) return true;\n if (Array.isArray(entry.nextStepHints) && entry.nextStepHints.length > 0) return true;\n if (entry.branchConvergence?.needsConvergence === true) return true;\n const sessionCount = Array.isArray(entry.sessions)\n ? entry.sessions.length\n : (entry.sessionSummary?.total ?? 0);\n if (sessionCount > 0) return true;\n return false;\n}\n\n// Minimal per-node stub for quiet nodes / byte-budget overflow. Keeps the fields a\n// coordinator needs to find and reason about a node (id/workspace/health/branch/\n// launchReady) plus the branchConvergence decision scalars, marked `folded` so\n// callers know the full compact detail is available via verbose.\nexport function minimalCompactNode(entry: any): any {\n if (!entry || typeof entry !== 'object') return entry;\n const bc = entry.branchConvergence && typeof entry.branchConvergence === 'object'\n ? {\n status: entry.branchConvergence.status,\n needsConvergence: entry.branchConvergence.needsConvergence,\n reason: entry.branchConvergence.reason,\n branch: entry.branchConvergence.branch,\n }\n : undefined;\n // Canonical per-node marker fields (e.g. dataFreshness) are exactly the signal a\n // coordinator needs on a QUIET node — is this idle peer live, cached, or\n // unreachable? — and they are tiny, so re-attach them from the single canonical\n // list rather than hand-listing each one (the path the dataFreshness regression\n // slipped through when only one field was added by hand).\n const preservedMarkers: Record<string, unknown> = {};\n for (const field of MESH_COMPACT_PRESERVED_MARKER_FIELDS) {\n if (entry[field] !== undefined) preservedMarkers[field] = entry[field];\n }\n return {\n nodeId: entry.nodeId,\n workspace: entry.workspace,\n daemonId: entry.daemonId,\n health: entry.health,\n branch: entry.branch,\n launchReady: entry.launchReady,\n ...(entry.providerPriority !== undefined ? { providerPriority: entry.providerPriority } : {}),\n // Keep the routable tag set on quiet/folded nodes — a coordinator planning\n // required_tags routing needs it even for nodes with nothing to converge.\n ...(entry.capabilityTags !== undefined ? { capabilityTags: entry.capabilityTags } : {}),\n ...(entry.launchBlockedReason !== undefined ? { launchBlockedReason: entry.launchBlockedReason } : {}),\n ...(bc ? { branchConvergence: bc } : {}),\n ...(entry.sessionSummary ? { sessionSummary: entry.sessionSummary } : {}),\n ...preservedMarkers,\n folded: true,\n };\n}\n\n// Fold a node's slim session list into status/provider counts. Compact mode\n// returns this instead of the full per-session array so the payload does not\n// grow O(nodes × sessions). The self-coordinator marker is preserved as a\n// dedicated count + id list so the coordinator never mis-reads its own\n// generating CLI session as a foreign delegated task.\nexport function summarizeNodeSessions(sessions: any[]): Record<string, unknown> {\n const list = Array.isArray(sessions) ? sessions : [];\n const byStatus: Record<string, number> = {};\n const providerCounts: Record<string, number> = {};\n const selfCoordinatorSessionIds: string[] = [];\n for (const s of list) {\n const status = typeof s?.status === 'string' && s.status ? s.status : 'unknown';\n byStatus[status] = (byStatus[status] ?? 0) + 1;\n const provider = typeof s?.providerType === 'string' && s.providerType ? s.providerType : 'unknown';\n providerCounts[provider] = (providerCounts[provider] ?? 0) + 1;\n if (s?.isSelfCoordinator === true && s.id) selfCoordinatorSessionIds.push(String(s.id));\n }\n const summary: Record<string, unknown> = {\n total: list.length,\n byStatus,\n providerCounts,\n };\n if (selfCoordinatorSessionIds.length > 0) {\n summary.selfCoordinatorSessionIds = selfCoordinatorSessionIds;\n }\n return summary;\n}\n","/**\n * Work-queue view / maintenance / compaction helpers for the mesh_* tools.\n *\n * Physically split out of mesh-tools.ts (RF-SURVEY candidate C1) with no behavior\n * change. Holds queue status/view normalization, the liveness index + stale-\n * assignment detection, maintenance reporting, and the compact row/active-work\n * folders. Imports only leaf deps (mesh-tool-shared, mesh-session-helpers) plus the\n * LocalMeshEntry type; mesh-tools.ts imports the exported helpers/constants back, so\n * there is no runtime import cycle.\n */\nimport type { LocalMeshEntry } from '@adhdev/daemon-core';\nimport { readString, elideLargeNestedValue } from './mesh-tool-shared.js';\nimport { collectNodeSessionIds } from './mesh-session-helpers.js';\n\nconst STALE_ASSIGNED_QUEUE_MS = 30 * 60_000;\nconst OLD_HISTORICAL_QUEUE_RECORD_MS = 7 * 24 * 60 * 60_000;\nexport const ACTIVE_QUEUE_STATUSES = new Set(['pending', 'assigned']);\nexport const HISTORICAL_QUEUE_STATUSES = new Set(['completed', 'failed', 'cancelled']);\nexport type QueueViewMode = 'all' | 'active' | 'historical';\n\ntype QueueLivenessIndex = {\n nodeIds: Set<string>;\n nodeSessionIds: Map<string, Set<string>>;\n};\n\nfunction buildQueueLivenessIndex(mesh?: LocalMeshEntry): QueueLivenessIndex {\n const nodeIds = new Set<string>();\n const nodeSessionIds = new Map<string, Set<string>>();\n for (const node of Array.isArray(mesh?.nodes) ? mesh.nodes : []) {\n const nodeId = readString((node as any).id) || readString((node as any).nodeId) || readString((node as any).node_id);\n if (!nodeId) continue;\n nodeIds.add(nodeId);\n const sessions = collectNodeSessionIds(node);\n if (sessions.size > 0) nodeSessionIds.set(nodeId, sessions);\n }\n return { nodeIds, nodeSessionIds };\n}\n\nfunction queueAssignmentStaleReason(task: any, liveness: QueueLivenessIndex): string | undefined {\n if (task?.status !== 'assigned') return undefined;\n const nodeId = readString(task.assignedNodeId) || readString(task.nodeId) || readString(task.node_id) || readString(task.targetNodeId);\n const sessionId = readString(task.assignedSessionId) || readString(task.sessionId) || readString(task.session_id) || readString(task.targetSessionId);\n\n if (nodeId && liveness.nodeIds.size > 0 && !liveness.nodeIds.has(nodeId)) {\n return 'assigned node is not present in the current mesh snapshot';\n }\n if (nodeId && sessionId && liveness.nodeSessionIds.has(nodeId) && !liveness.nodeSessionIds.get(nodeId)!.has(sessionId)) {\n return 'assigned session is not live on the assigned node';\n }\n\n const updatedAt = new Date(task.updatedAt).getTime();\n const ageMs = Number.isFinite(updatedAt) ? Date.now() - updatedAt : null;\n if (!nodeId && ageMs !== null && ageMs >= STALE_ASSIGNED_QUEUE_MS) {\n return 'assigned task has no assigned node metadata';\n }\n return undefined;\n}\n\nexport function buildQueueStatusSummary(queue: any[]): Record<string, unknown> {\n const counts = { pending: 0, assigned: 0, completed: 0, failed: 0, cancelled: 0 };\n let staleAssigned = 0;\n for (const task of queue) {\n const status = typeof task?.status === 'string' ? task.status : undefined;\n if (status && Object.prototype.hasOwnProperty.call(counts, status)) {\n counts[status as keyof typeof counts] += 1;\n }\n if (status === 'assigned' && task?.staleAssigned === true) staleAssigned += 1;\n }\n const liveAssigned = Math.max(0, counts.assigned - staleAssigned);\n return {\n totalCount: queue.length,\n activeCount: counts.pending + liveAssigned,\n historicalCount: counts.completed + counts.failed + counts.cancelled,\n counts,\n activeCounts: {\n pending: counts.pending,\n assigned: liveAssigned,\n },\n staleAssignedCount: staleAssigned,\n rawActiveCounts: {\n pending: counts.pending,\n assigned: counts.assigned,\n },\n historicalCounts: {\n completed: counts.completed,\n failed: counts.failed,\n cancelled: counts.cancelled,\n },\n };\n}\n\nexport function normalizeQueueViewMode(value: unknown): QueueViewMode {\n return value === 'active' || value === 'historical' || value === 'all' ? value : 'all';\n}\n\nexport function sanitizeQueueStatusFilter(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const statuses = value\n .map(item => typeof item === 'string' ? item.trim() : '')\n .filter(status => ACTIVE_QUEUE_STATUSES.has(status) || HISTORICAL_QUEUE_STATUSES.has(status));\n return statuses.length ? Array.from(new Set(statuses)) : undefined;\n}\n\nexport function filterQueueForView(queue: any[], view: QueueViewMode, statuses?: string[]): any[] {\n if (statuses?.length) {\n const allowed = new Set(statuses);\n return queue.filter(task => allowed.has(String(task?.status || '')));\n }\n if (view === 'active') return queue.filter(task => ACTIVE_QUEUE_STATUSES.has(String(task?.status || '')));\n if (view === 'historical') return queue.filter(task => HISTORICAL_QUEUE_STATUSES.has(String(task?.status || '')));\n return queue;\n}\n\nexport function prioritizeActiveQueueRows(queue: any[]): any[] {\n const active: any[] = [];\n const historical: any[] = [];\n const other: any[] = [];\n for (const task of queue) {\n const status = String(task?.status || '');\n if (ACTIVE_QUEUE_STATUSES.has(status)) active.push(task);\n else if (HISTORICAL_QUEUE_STATUSES.has(status)) historical.push(task);\n else other.push(task);\n }\n return [...active, ...other, ...historical];\n}\n\nfunction slimQueueTask(task: any): Record<string, unknown> {\n return {\n id: task?.id,\n status: task?.status,\n assignedNodeId: task?.assignedNodeId,\n assignedSessionId: task?.assignedSessionId,\n targetNodeId: task?.targetNodeId,\n targetSessionId: task?.targetSessionId,\n updatedAt: task?.updatedAt,\n staleAssigned: task?.staleAssigned === true,\n staleReason: task?.staleReason,\n };\n}\n\nexport function buildQueueMaintenanceReport(queue: any[]): Record<string, unknown> {\n const now = Date.now();\n const staleAssignedTasks = queue\n .filter(task => task?.status === 'assigned' && task?.staleAssigned === true)\n .map(slimQueueTask);\n const historicalTasks = queue.filter(task => HISTORICAL_QUEUE_STATUSES.has(String(task?.status || '')));\n const oldHistoricalTasks = historicalTasks\n .filter(task => {\n const updatedAt = new Date(task?.updatedAt).getTime();\n return Number.isFinite(updatedAt) && now - updatedAt >= OLD_HISTORICAL_QUEUE_RECORD_MS;\n })\n .map(task => ({\n ...slimQueueTask(task),\n cleanupClass: 'old_historical_record',\n reason: 'terminal queue record is older than the read-only maintenance threshold',\n }));\n const cleanupCandidates = [\n ...staleAssignedTasks.map(task => ({\n ...task,\n cleanupClass: 'stale_assigned',\n reason: typeof task.staleReason === 'string' ? task.staleReason : 'active assigned task does not match current live mesh node/session state',\n suggestedOperation: 'operator_review_then_requeue_or_cancel',\n })),\n ...oldHistoricalTasks.map(task => ({\n ...task,\n suggestedOperation: 'operator_review_then_archive_or_keep',\n })),\n ];\n return {\n readOnly: true,\n mutationPerformed: false,\n sourceOfTruth: 'mesh_work_queue_file',\n staleAssignedDefinition: 'Only active assigned queue rows are stale candidates, and only when the assigned node/session is absent from the current live mesh snapshot.',\n historicalDefinition: 'completed/failed/cancelled rows are historical ledger records and never active assignments.',\n staleAssignedTasks,\n staleAssignedCount: staleAssignedTasks.length,\n historicalRecordCount: historicalTasks.length,\n oldHistoricalRecordCount: oldHistoricalTasks.length,\n cleanupCandidates,\n cleanupCandidateCount: cleanupCandidates.length,\n };\n}\n\n// Compact maintenance report: drop the per-row arrays (staleAssignedTasks,\n// cleanupCandidates) that scale with old historical record count and instead\n// surface the counts. staleAssignedTasks rows are still active work, so keep a\n// small sample for coordinator visibility; cleanupCandidates are dominated by\n// old historical rows and are dropped entirely in favor of the count + a hint.\nexport function buildCompactQueueMaintenanceReport(maintenance: Record<string, unknown>): Record<string, unknown> {\n const staleAssignedTasks = Array.isArray((maintenance as any).staleAssignedTasks)\n ? (maintenance as any).staleAssignedTasks\n : [];\n const cleanupCandidateCount = (maintenance as any).cleanupCandidateCount ?? 0;\n return {\n readOnly: true,\n mutationPerformed: false,\n sourceOfTruth: 'mesh_work_queue_file',\n payloadMode: 'compact',\n staleAssignedDefinition: (maintenance as any).staleAssignedDefinition,\n historicalDefinition: (maintenance as any).historicalDefinition,\n // staleAssignedTasks are active assigned rows (not historical) — retain a\n // bounded sample so coordinators can still see drift without the full array.\n staleAssignedTasks: staleAssignedTasks.slice(0, 5),\n staleAssignedSampleLimit: 5,\n staleAssignedCount: (maintenance as any).staleAssignedCount ?? staleAssignedTasks.length,\n historicalRecordCount: (maintenance as any).historicalRecordCount ?? 0,\n oldHistoricalRecordCount: (maintenance as any).oldHistoricalRecordCount ?? 0,\n cleanupCandidateCount,\n cleanupCandidatesOmitted: true,\n cleanupCandidatesHint: 'Per-row cleanup candidates are omitted in compact mode; call mesh_view_queue with verbose=true for the full maintenance/cleanupDryRun rows.',\n };\n}\n\n// Compact-mode bounds for mesh_view_queue active rows. Active (pending/assigned)\n// rows are kept — they drive dispatch decisions — but a busy mesh can have dozens\n// of them, each carrying the full task `message` (often multi-KB). Truncate the\n// message and cap the row count so the active queue can't blow the token cap.\nexport const COMPACT_MAX_ACTIVE_QUEUE_ROWS = 15;\nconst COMPACT_QUEUE_MESSAGE_CAP = 140;\nexport const COMPACT_MAX_ACTIVE_WORK_ROWS = 12;\n// In compact mode an activeWork row keeps a single short title only; the original\n// delegation prompt is NOT echoed (leak #2). 80 chars is enough to recognize the task.\nconst COMPACT_ACTIVE_WORK_TITLE_CAP = 80;\n\nfunction truncateForCompact(value: unknown, cap: number): unknown {\n if (typeof value !== 'string') return value;\n return value.length > cap ? value.slice(0, cap) + '…' : value;\n}\n\n// Slim an active queue row for compact mode: truncate the long free-text message\n// and elide any oversized nested field. Status/ids/deps/tags (the dispatch-relevant\n// scalars) are preserved.\nexport function compactQueueRow(task: any): any {\n if (!task || typeof task !== 'object') return task;\n const slim: any = {};\n for (const [k, v] of Object.entries(task)) {\n if (k === 'message') slim[k] = truncateForCompact(v, COMPACT_QUEUE_MESSAGE_CAP);\n else slim[k] = elideLargeNestedValue(k, v);\n }\n return slim;\n}\n\nexport function compactQueueRows(rows: any[]): { rows: any[]; omitted: number } {\n const capped = rows.slice(0, COMPACT_MAX_ACTIVE_QUEUE_ROWS).map(compactQueueRow);\n return { rows: capped, omitted: Math.max(0, rows.length - capped.length) };\n}\n\n// Slim an activeWork record for compact mode. Leak #2: the original delegation\n// prompt was echoed THREE times per row — `taskTitle` (truncated) + `taskSummary`\n// (mid-length) + `message` (full). In compact we keep only a single short\n// `taskTitle`; `taskSummary` and `message` are dropped entirely (the full text is\n// available via mesh_task_history or with verbose=true). All dispatch-relevant\n// scalars (taskId/status/nodeId/sessionId/timestamps/terminal+stale flags) are\n// preserved so the row stays actionable.\nfunction compactActiveWorkRecord(record: any): any {\n if (!record || typeof record !== 'object') return record;\n const slim: any = {};\n for (const [k, v] of Object.entries(record)) {\n if (k === 'message' || k === 'taskSummary') continue; // redundant full-text echoes\n else if (k === 'taskTitle') slim[k] = truncateForCompact(v, COMPACT_ACTIVE_WORK_TITLE_CAP);\n else slim[k] = elideLargeNestedValue(k, v);\n }\n return slim;\n}\n\nexport function compactActiveWorkRecords(records: any[]): { records: any[]; omitted: number } {\n if (!Array.isArray(records)) return { records, omitted: 0 };\n const capped = records.slice(0, COMPACT_MAX_ACTIVE_WORK_ROWS).map(compactActiveWorkRecord);\n return { records: capped, omitted: Math.max(0, records.length - capped.length) };\n}\n\nexport function annotateQueueStaleness(queue: any[], mesh?: LocalMeshEntry): any[] {\n const liveness = buildQueueLivenessIndex(mesh);\n const now = Date.now();\n return queue.map(task => {\n const taskStatus = typeof task?.status === 'string' ? task.status : undefined;\n const annotated = {\n ...task,\n taskStatus,\n isActive: taskStatus ? ACTIVE_QUEUE_STATUSES.has(taskStatus) : false,\n isHistorical: taskStatus ? HISTORICAL_QUEUE_STATUSES.has(taskStatus) : false,\n dispatchedAt: task?.createdAt,\n ...(taskStatus === 'assigned' ? { activeTaskId: task.id } : {}),\n ...(taskStatus === 'completed' || taskStatus === 'failed' ? {\n completedAt: task.updatedAt,\n } : {}),\n };\n if (taskStatus !== 'assigned') return annotated;\n const updatedAt = new Date(task.updatedAt).getTime();\n const ageMs = Number.isFinite(updatedAt) ? now - updatedAt : null;\n const staleReason = queueAssignmentStaleReason(task, liveness);\n if (!staleReason) return annotated;\n return {\n ...annotated,\n stale: true,\n staleAssigned: true,\n staleReason,\n ...(ageMs !== null ? { assignedAgeMs: ageMs } : {}),\n };\n });\n}\n","export const RAPID_READ_CHAT_ADVISORY_WINDOW_MS = 5_000;\n\nconst ACTIVE_READ_STATUSES = new Set([\n 'generating',\n 'running',\n 'streaming',\n 'starting',\n 'busy',\n]);\n\ntype RecentRead = {\n at: number;\n status?: string;\n};\n\nexport type RapidReadChatAdvisory = {\n type: 'rapid_read_chat_polling';\n toolName: string;\n windowMs: number;\n elapsedMs: number;\n nextSuggestedReadAt: number;\n completionCallbackExpected: boolean;\n message: string;\n};\n\nconst recentReads = new Map<string, RecentRead>();\n\nexport function clearRapidReadChatAdvisoryStateForTests(): void {\n recentReads.clear();\n}\n\nexport function isActiveReadChatStatus(status: unknown): boolean {\n return typeof status === 'string' && ACTIVE_READ_STATUSES.has(status.toLowerCase());\n}\n\nexport function annotateRapidReadChatAdvisory<T extends Record<string, any>>(\n payload: T,\n options: {\n key: string;\n now?: number;\n status?: unknown;\n toolName: 'read_chat' | 'mesh_read_chat' | string;\n completionCallbackExpected?: boolean;\n },\n): T & { pollingAdvisory?: RapidReadChatAdvisory } {\n const now = options.now ?? Date.now();\n const status = options.status ?? payload?.status ?? payload?.data?.status ?? payload?.result?.status;\n const active = isActiveReadChatStatus(status);\n const previous = recentReads.get(options.key);\n\n if (!active) {\n recentReads.set(options.key, { at: now, status: typeof status === 'string' ? status : undefined });\n return payload;\n }\n\n recentReads.set(options.key, { at: now, status: typeof status === 'string' ? status : undefined });\n\n if (!previous || !isActiveReadChatStatus(previous.status)) return payload;\n const elapsedMs = now - previous.at;\n if (elapsedMs < 0 || elapsedMs >= RAPID_READ_CHAT_ADVISORY_WINDOW_MS) return payload;\n\n return {\n ...payload,\n pollingAdvisory: {\n type: 'rapid_read_chat_polling',\n toolName: options.toolName,\n windowMs: RAPID_READ_CHAT_ADVISORY_WINDOW_MS,\n elapsedMs,\n nextSuggestedReadAt: previous.at + RAPID_READ_CHAT_ADVISORY_WINDOW_MS,\n completionCallbackExpected: Boolean(options.completionCallbackExpected),\n message: `This session is still ${String(status)}. Avoid repeated ${options.toolName} polling for the same generating session; wait for the completion callback/status event or retry after the suggested time if you are debugging a real stall.`,\n },\n };\n}\n","// Mesh tool implementations — status domain.\n// Pure move out of mesh-tools.ts (no behavior change). Shared helpers, types, module\n// state and dependency re-exports live in ./mesh-tools-internal.ts; mesh-tools.ts is a barrel.\n\nimport {\n COMPACT_DETAILED_NODES_BYTE_BUDGET,\n COMPACT_MAX_ACTIVE_WORK_ROWS,\n COMPACT_MISSIONS_BYTE_BUDGET,\n COMPACT_NODES_TOTAL_BYTE_BUDGET,\n assignFullGitSnapshot,\n buildActiveWorkPollingGuidance,\n buildBranchConvergence,\n buildCompactStaleDirectWorkSummary,\n buildCoordinatorP2pRelayFailure,\n buildMeshActiveWork,\n buildMeshAsyncRefineJobs,\n buildMeshMagiActivity,\n summarizeMeshMagiActivity,\n buildMeshNodeProbeFreshness,\n buildMeshSchedulingRuntime,\n buildNodeCapabilityExposure,\n buildNodeMachineIdentity,\n collectLiveStatusProbe,\n collectRelatedRepoStatuses,\n commandForNode,\n compactActiveWorkRecords,\n compactMeshStatusNode,\n compactNodeSeverity,\n computeMeshMissionStats,\n countUncommittedChanges,\n drainCoordinatorPendingEvents,\n extractGitStatus,\n extractSubmodules,\n getActiveDirectDispatches,\n getLatestActiveLaunchFailure,\n getLedgerSummary,\n getMeshStatusMissionSummaries,\n getMeshStatusMissionsCompact,\n getNodeLaunchReadiness,\n getQueue,\n getSessionRecoveryContext,\n isGitStatusDirty,\n isNoteworthyCompactNode,\n minimalCompactNode,\n readLedgerEntries,\n readNodeDaemonId,\n readNodeMachineId,\n readRelatedRepos,\n reconcileDirectDispatchesFromTranscriptEvidence,\n recordMeshToolCall,\n refreshMeshFromDaemon,\n summarizeBranchConvergence,\n summarizeMeshAsyncRefineJobs,\n summarizeNodeSessions,\n} from './mesh-tools-internal.js';\nimport type {\n MeshContext,\n} from './mesh-tools-internal.js';\n\n// The v2 protocol version literal (mirrors MESH_PROTOCOL_VERSION_V2 in\n// daemon-core mesh/contracts.ts). Kept as a local literal so this MCP-side\n// summarizer stays dependency-free of daemon-core internals — the wire value is\n// a stable contract, not an implementation detail.\nconst MESH_PROTOCOL_VERSION_V2_WIRE = '2.0';\n\n/**\n * T7 (B4): summarize mesh-protocol-v2 adoption over the batch of pending events\n * surfaced in one mesh_status drain. Returns the count carrying a v2 envelope\n * (protocolVersion '2.0'), the count still on v1 (unstamped), the v2 adoption\n * ratio, and — for v2 events — a scope breakdown (unicast/broadcast/system).\n * Returns null when there is nothing to report (empty batch) so the caller can\n * omit the field. Read-only over the drained array — no store or counter mutation.\n */\nexport function summarizePendingEventProtocolMetrics(\n pendingEvents: any[],\n): { total: number; v2: number; v1: number; v2Ratio: number; scopes: Record<string, number> } | null {\n if (!Array.isArray(pendingEvents) || pendingEvents.length === 0) return null;\n let v2 = 0;\n const scopes: Record<string, number> = {};\n for (const event of pendingEvents) {\n const protocolVersion = typeof event?.protocolVersion === 'string' ? event.protocolVersion : '';\n if (protocolVersion === MESH_PROTOCOL_VERSION_V2_WIRE) {\n v2 += 1;\n const scope = typeof event?.scope === 'string' && event.scope ? event.scope : 'unspecified';\n scopes[scope] = (scopes[scope] ?? 0) + 1;\n }\n }\n const total = pendingEvents.length;\n return {\n total,\n v2,\n v1: total - v2,\n v2Ratio: total > 0 ? Math.round((v2 / total) * 100) / 100 : 0,\n scopes,\n };\n}\n\n\n\n// ─── Tool Implementations ───────────────────────\n\nexport async function meshStatus(ctx: MeshContext, args: { includeStaleDirectWorkDetails?: boolean; includeTerminalDirectWork?: boolean; includeSessions?: boolean; compact?: boolean; verbose?: boolean } = {}): Promise<string> {\n const rateResult = recordMeshToolCall({ meshId: ctx.mesh.id, tool: 'mesh_status' });\n // Default to the slim payload for LLM callers; verbose forces the full payload.\n const compact = args.verbose === true ? false : (args.compact ?? true);\n\n await refreshMeshFromDaemon(ctx);\n const { mesh, transport } = ctx;\n\n let ledgerSummary = getLedgerSummary(mesh.id);\n\n // Scheduling-runtime projection (load-balancer's live view): tie-break strategy,\n // global parallel caps + consumption, and per-node load / priority / provider caps\n // with structured \"why this node can't take more write work\" reasons. Derived from\n // the mesh config + a queue snapshot (read-only) — never drives a scheduling\n // decision, only exposes the picture the claim path acts on. Computed once so each\n // node entry below can attach its slice and the response can carry the mesh rollup.\n const schedulingRuntime = buildMeshSchedulingRuntime(mesh, getQueue(mesh.id));\n const schedulingByNode = new Map(schedulingRuntime.nodes.map(n => [n.nodeId, n]));\n\n // Probe all nodes in parallel — git_status + session collection per node are independent.\n //\n // Dual-surface note (mesh-status-dual-surface): this coordinator-side node object\n // is assembled here independently of the daemon-core finalize path\n // (commands/high-family/mesh-status.ts, which stamps its own node via\n // buildMeshNodeMachineIdentity). The two surfaces are INTENTIONALLY distinct:\n // • machine identity — buildNodeMachineIdentity (mesh-node-identity.ts) emits\n // the SAME output shape as daemon-core's buildMeshNodeMachineIdentity\n // (daemonId/machineId/hostname/machineName/displayName/coordinatorHostname/\n // sameMachine/locality/localityReason/identityEvidence), so a field added to\n // one must be added to the other. It cannot be collapsed into the daemon-core\n // builder because the coordinator surface derives sameMachine/locality from\n // richer control-plane evidence (isDirectLocalNode / isConfiguredCoordinatorNode /\n // cloned-from tracing / local session evidence) that needs the full MeshContext,\n // which the daemon-core `opts`-scalar signature does not carry.\n // • capability exposure — buildNodeCapabilityExposure already delegates its tag\n // computation to daemon-core's buildMeshNodeCapabilityTags (the SAME function\n // the queue/dispatch matcher uses), so the exposed tags cannot drift from\n // routing; only the exposure wrapper (byProvider map + raw capabilities) is local.\n // When adding a node field on either surface, update the peer surface too.\n const results = await Promise.all(mesh.nodes.map(async (node) => {\n const entry: any = {\n nodeId: node.id,\n workspace: node.workspace,\n machine: buildNodeMachineIdentity(ctx, node),\n daemonId: readNodeDaemonId(node),\n machineId: readNodeMachineId(node),\n ...getNodeLaunchReadiness(node),\n ...buildNodeCapabilityExposure(node),\n };\n\n // Per-node scheduling runtime (load, priority, provider caps, claim-block reasons).\n // Full detail is a dashboard/verbose concern; in compact mode it repeats per node\n // and would inflate the LLM payload past its byte budget, so compact keeps only the\n // two scalars a coordinator needs to reason about load (current load + cap-reached).\n // The mesh-level scheduling rollup (strategy/global caps) is always present below.\n const nodeScheduling = schedulingByNode.get(node.id);\n if (nodeScheduling) {\n // Drop the redundant nodeId — the entry already carries it.\n const { nodeId: _omit, ...rest } = nodeScheduling;\n entry.scheduling = compact\n ? { load: rest.load, capReached: rest.capReached }\n : rest;\n }\n\n // Tracks whether THIS call obtained live truth from a fresh git_status probe.\n // The coordinator-facing mesh_status always probes each node fresh, so a probe\n // that returns is live truth and a probe that throws is an unreachable peer —\n // consumed below to stamp the additive `dataFreshness` marker.\n let liveTruthProbed = false;\n try {\n const autoDiscover = (node.policy as any)?.autoDiscoverSubmodules !== false;\n // OFFLINE-NODE-STATUS-REFRESH: this is the mesh_status per-node git_status probe\n // (first awaited in the sequence, so it blocks earliest). Mark it status-origin so\n // an offline peer's relay gives up on the SHORT connect-wait budget instead of\n // sinking the whole explicit_refresh into the 90s connect deadline.\n const statusResult = await commandForNode(ctx, node, 'git_status', {\n workspace: node.workspace,\n refreshUpstream: true,\n includeSubmodules: autoDiscover,\n submoduleIgnorePaths: (node.policy as any)?.submoduleIgnorePaths || undefined,\n }, { statusProbe: true });\n liveTruthProbed = true;\n const status = extractGitStatus(statusResult);\n const uncommittedChanges = countUncommittedChanges(status);\n const dirty = isGitStatusDirty(status);\n entry.health = status?.isGitRepo ? (dirty ? 'dirty' : 'online') : 'degraded';\n assignFullGitSnapshot(entry, status);\n entry.branch = status?.branch;\n entry.isDirty = dirty;\n entry.uncommittedChanges = uncommittedChanges;\n entry.branchConvergence = buildBranchConvergence(mesh, node, status, dirty, uncommittedChanges);\n // Stale-daemon-build warning: the live daemon's build commit is a\n // strict ancestor of this workspace HEAD (or its oss submodule),\n // meaning merged code is not yet live (awaiting deploy/restart).\n // Computed git-correctly on the daemon side (git_status →\n // daemonBuildBehind); surfaced here as a top-level node field.\n if (status?.daemonBuildBehind && typeof status.daemonBuildBehind === 'object') {\n entry.staleDaemonBuild = status.daemonBuildBehind;\n }\n // Submodule out-of-sync warning\n const submodules = extractSubmodules(statusResult, (node.policy as any)?.submoduleIgnorePaths || []);\n if (submodules && submodules.some((s: any) => s?.outOfSync)) {\n entry.submoduleWarning = 'One or more submodules are out of sync with the parent repo. Run `git submodule update` or check deployment readiness.';\n entry.outOfSyncSubmodules = submodules.filter((s: any) => s?.outOfSync).map((s: any) => s.path);\n }\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'git_status',\n targetDaemonId: node.daemonId,\n nodeId: node.id,\n });\n entry.health = 'degraded';\n entry.error = failure.error;\n entry.degradedReason = failure.recoverable ? 'p2p_relay_failure' : 'git_status_unavailable';\n Object.assign(entry, {\n code: failure.code,\n transport: failure.transport,\n recoverable: failure.recoverable,\n retryRecommended: failure.retryRecommended,\n nextAction: failure.nextAction,\n noFallbackReason: failure.noFallbackReason,\n });\n }\n\n // Additive freshness/reachability marker. Without this, the coordinator's\n // mesh_status could not tell a node whose live probe just succeeded from one\n // it could not reach — both rendered as `health` + git scalars only. Derived\n // through the SINGLE canonical daemon-core live-probe adapter\n // (buildMeshNodeProbeFreshness) rather than rebuilding the freshness input\n // here, so the dataSource/staleness wiring cannot drift between this\n // coordinator surface and the daemon aggregate (the rc.371 regression where\n // dataFreshness was wired on the daemon surface but null on every coordinator\n // node because this site re-derived its own input).\n entry.dataFreshness = buildMeshNodeProbeFreshness({\n git: entry.git,\n liveTruthProbed,\n isSelfNode: (entry.machine as any)?.sameMachine === true,\n daemonId: readNodeDaemonId(node),\n node,\n });\n\n // Recovery Hints & Next-step reporting\n const recoveryContext = getSessionRecoveryContext(mesh.id, { nodeId: node.id });\n if (recoveryContext.consecutiveNodeFailures > 0) {\n entry.recoveryHints = {\n consecutiveFailures: recoveryContext.consecutiveNodeFailures,\n lastTaskMessage: typeof recoveryContext.lastTaskMessage === 'string'\n ? recoveryContext.lastTaskMessage.slice(0, 100) + (recoveryContext.lastTaskMessage.length > 100 ? '…' : '')\n : recoveryContext.lastTaskMessage,\n advice: recoveryContext.advice,\n retryRecommended: recoveryContext.retryRecommended,\n };\n }\n\n const activeLaunchFailure = getLatestActiveLaunchFailure(mesh.id, node.id);\n if (activeLaunchFailure && node.isLocalWorktree) {\n entry.health = 'degraded';\n entry.degradedReason = 'worktree_launch_failed';\n entry.launchReady = false;\n entry.launchBlockedReason = activeLaunchFailure.code || 'mesh_launch_failed';\n entry.launchBlockedMessage = activeLaunchFailure.error || 'Previous worktree session launch failed';\n entry.lastLaunchFailure = activeLaunchFailure;\n }\n\n const nextStepHints: string[] = [];\n if (entry.degradedReason === 'worktree_launch_failed') {\n nextStepHints.push(`Retry mesh_launch_session(node_id: \"${node.id}\") after daemon mesh transport/P2P is healthy.`);\n nextStepHints.push(`If retry is not desired, cleanup the orphan worktree node with mesh_remove_node(node_id: \"${node.id}\").`);\n } else if (entry.health === 'online' && node.isLocalWorktree) {\n nextStepHints.push(`Merge worktree to base via mesh_refine_node(node_id: \"${node.id}\")`);\n } else if (entry.health === 'dirty') {\n nextStepHints.push(`Commit changes via mesh_checkpoint(node_id: \"${node.id}\", message: \"...\")`);\n } else if (entry.health === 'degraded' && entry.error?.includes('git')) {\n nextStepHints.push('Initialize git repository or check workspace path.');\n }\n\n if (entry.branchConvergence?.needsConvergence === true && entry.branchConvergence.nextStep) {\n nextStepHints.push(String(entry.branchConvergence.nextStep));\n }\n\n if (recoveryContext.consecutiveNodeFailures > 0) {\n if (recoveryContext.retryRecommended) {\n nextStepHints.push(`Retry task on this node or launch a fresh session.`);\n } else {\n nextStepHints.push(`Consider reassigning work to a different node.`);\n }\n }\n\n if (nextStepHints.length > 0) {\n entry.nextStepHints = nextStepHints;\n }\n\n const relatedRepos = await collectRelatedRepoStatuses(ctx, node);\n if (relatedRepos.length) entry.relatedRepos = relatedRepos;\n\n const statusProbe = await collectLiveStatusProbe(ctx, node);\n const liveSessions = statusProbe.sessions;\n // Per-node daemon build stamp (commit/version of the running daemon).\n // Compact mode folds these per-daemonId at the response level, but the\n // raw field is kept on the node so verbose callers and self-coordinator\n // shape stay intact.\n if (statusProbe.daemonBuild) entry.daemonBuild = statusProbe.daemonBuild;\n if (liveSessions.length > 0) {\n // Slim to essential fields only — full session objects are expensive in coordinator context.\n entry.sessions = liveSessions\n .map((s: any) => {\n // A session is marked as a coordinator for THIS mesh when the daemon's\n // coordinator registry / session settings report its meshId matches ours.\n // From the caller's perspective (which is itself a coordinator for this\n // mesh), any such session is \"self\" — i.e. it is the calling coordinator\n // session, not a foreign delegated worker. This prevents the coordinator\n // from mis-reporting its own generating CLI session as someone else's\n // delegated task.\n const coordinatorMeshId =\n typeof s.coordinator?.meshId === 'string' ? s.coordinator.meshId : undefined;\n const isSelfCoordinator = coordinatorMeshId === mesh.id;\n return {\n id: s.instanceId ?? s.id ?? s.sessionId,\n status: s.status ?? s.lifecycle ?? s.state,\n providerType: s.providerType ?? s.cliType ?? s.type,\n ...(s.activeChat?.status ? { chatStatus: s.activeChat.status } : {}),\n ...(isSelfCoordinator ? { isSelfCoordinator: true, role: 'coordinator' as const } : {}),\n // [T2] Carry the worker-computed last-message preview through the slim so\n // the coordinator's inbox can show the worker's latest ASSISTANT reply\n // without re-deriving it from a live in-process instance it doesn't host.\n // The worker's get_status_metadata snapshot already computes these\n // (status/snapshot.ts) from its real transcript; dropping them here forced\n // the coordinator down a derive path that fails for genuinely remote\n // workers, leaving the mobile inbox stuck on the dispatched user task.\n ...(typeof s.lastMessagePreview === 'string' && s.lastMessagePreview\n ? { lastMessagePreview: s.lastMessagePreview } : {}),\n ...(typeof s.lastMessageRole === 'string' && s.lastMessageRole\n ? { lastMessageRole: s.lastMessageRole } : {}),\n ...(typeof s.lastMessageAt === 'number' && Number.isFinite(s.lastMessageAt)\n ? { lastMessageAt: s.lastMessageAt } : {}),\n // RESTORE-STICK: carry the worker's AUTHORITATIVE dashboard hide/mute\n // state (already resolved by the worker's status/builders honoring any\n // per-session user override) plus the raw userHidden/userMuted overrides.\n // The coordinator's cloud snapshot append (daemon-cloud\n // appendMeshOwnedSessionsToSnapshot) otherwise re-derives hide/mute purely\n // from mesh policy and clobbers a user's manual restore/un-mute every\n // snapshot — the un-hide flickered visible then re-hid. Dropping these\n // here is exactly what starved the coordinator of the worker's real state.\n ...(typeof s.surfaceHidden === 'boolean' ? { surfaceHidden: s.surfaceHidden } : {}),\n ...(typeof s.muted === 'boolean' ? { muted: s.muted } : {}),\n ...(typeof s.settings?.userHidden === 'boolean' ? { userHidden: s.settings.userHidden } : {}),\n ...(typeof s.settings?.userMuted === 'boolean' ? { userMuted: s.settings.userMuted } : {}),\n };\n })\n // Exclude sessions with no resolvable id (malformed or custom provider response).\n .filter((s: any) => s.id);\n }\n\n return entry;\n }));\n\n let ledgerEntries = readLedgerEntries(mesh.id, { tail: 200 });\n let directDispatches = getActiveDirectDispatches(mesh.id);\n const directReconciliation = await reconcileDirectDispatchesFromTranscriptEvidence(ctx, results, directDispatches, ledgerEntries);\n if (directReconciliation.reconciled > 0) {\n ledgerEntries = readLedgerEntries(mesh.id, { tail: 200 });\n directDispatches = getActiveDirectDispatches(mesh.id);\n ledgerSummary = getLedgerSummary(mesh.id);\n }\n const activeWorkEvidence = buildMeshActiveWork({\n meshId: mesh.id,\n queue: getQueue(mesh.id),\n ledgerEntries,\n directDispatches,\n nodes: results,\n });\n\n const pollingGuidance = buildActiveWorkPollingGuidance(activeWorkEvidence.summary);\n const staleDirectWorkSummary = buildCompactStaleDirectWorkSummary(activeWorkEvidence.staleDirectWork, {\n note: activeWorkEvidence.staleDirectWorkNote,\n detailHint: 'Full stale direct entries are omitted from mesh_status by default. Call mesh_status with includeStaleDirectWorkDetails=true or inspect mesh_task_history for ledger detail.',\n });\n // Leak #2: in compact mode each activeWork row drops the duplicated\n // taskSummary/message echoes (keeps a short taskTitle + dispatch scalars).\n // Verbose keeps the full per-record text for debugging.\n const activeWorkForResponse = compact\n ? compactActiveWorkRecords(activeWorkEvidence.activeWork)\n : { records: activeWorkEvidence.activeWork, omitted: 0 };\n\n // Surface coordinator session identity at the top level so the caller (which\n // is itself a coordinator for this mesh) can immediately recognize which\n // sessions in the response are its own — see the per-session\n // `isSelfCoordinator` marker derived above.\n const coordinatorSessions: Array<Record<string, unknown>> = [];\n for (const nodeEntry of results) {\n const sessions = Array.isArray((nodeEntry as any).sessions) ? (nodeEntry as any).sessions : [];\n for (const s of sessions) {\n if (s?.isSelfCoordinator === true && s.id) {\n coordinatorSessions.push({\n nodeId: (nodeEntry as any).nodeId,\n sessionId: s.id,\n providerType: s.providerType,\n status: s.status,\n });\n }\n }\n }\n\n // Compact mode: slim each node's large duplicated `git` blob down to the\n // coordinator-relevant scalars + submodules. branch/health/headCommit/ahead/\n // behind/dirty/upstreamStatus/branchConvergence live as top-level node\n // fields (or inside the slim git snapshot) and are always preserved.\n //\n // Session N×M de-duplication: the per-node session list comes from a\n // daemon-wide `get_status_metadata` probe, so every node that shares a\n // daemonId reports the SAME sessions. Emitting the full array on every node\n // makes the payload grow O(nodes × sessions). In compact mode we therefore\n // (a) fold each node's `sessions` array to a `sessionSummary` (counts only),\n // and (b) emit the full slim session arrays exactly once per daemon under\n // top-level `daemonSessions`. The self-coordinator marker survives in both\n // the per-node summary (`selfCoordinatorSessionIds`) and the top-level\n // `coordinatorSessions`/`selfIdentification`. Individual per-node session\n // detail can be opted back in with `includeSessions=true`.\n const includeSessions = args.includeSessions === true;\n // Top-level per-daemon session map (compact). Sessions are recorded ONCE per\n // daemonId regardless of how many mesh nodes share that daemon, eliminating\n // the N×M duplication. With includeSessions=true the full slim session arrays\n // are emitted; otherwise each daemon is folded to a counts summary.\n const daemonSessions: Record<string, unknown> = {};\n if (compact) {\n const seenDaemons = new Set<string>();\n for (const entry of results as any[]) {\n const daemonId = typeof entry?.daemonId === 'string' && entry.daemonId ? entry.daemonId : '';\n const sessions = Array.isArray(entry?.sessions) ? entry.sessions : [];\n if (daemonId && sessions.length > 0 && !seenDaemons.has(daemonId)) {\n seenDaemons.add(daemonId);\n daemonSessions[daemonId] = includeSessions ? sessions : summarizeNodeSessions(sessions);\n }\n }\n }\n // Per-daemon build fold: the daemon build stamp is identical for every node\n // sharing a daemonId (it's a daemon-wide probe), so record it ONCE per\n // daemonId at the top level. Small field — emitted in both compact and\n // verbose modes so the coordinator can compare the live daemon's commit with\n // a just-merged fix without paging through nodes.\n const daemonBuilds: Record<string, unknown> = {};\n for (const entry of results as any[]) {\n const daemonId = typeof entry?.daemonId === 'string' && entry.daemonId ? entry.daemonId : '';\n if (daemonId && entry?.daemonBuild && !(daemonId in daemonBuilds)) {\n daemonBuilds[daemonId] = entry.daemonBuild;\n }\n }\n // Stale-build aggregate: any node whose live daemon build is behind its\n // workspace HEAD. Deduplicated per daemonId+scope so N worktrees on one\n // stale daemon don't spam N identical warnings.\n const staleDaemonBuilds: Array<Record<string, unknown>> = [];\n const seenStale = new Set<string>();\n for (const entry of results as any[]) {\n const behind = entry?.staleDaemonBuild;\n if (!behind || typeof behind !== 'object') continue;\n const daemonId = typeof entry?.daemonId === 'string' ? entry.daemonId : '';\n const key = `${daemonId}::${behind.scope ?? ''}::${behind.buildCommit ?? ''}::${behind.head ?? ''}`;\n if (seenStale.has(key)) continue;\n seenStale.add(key);\n // web-only stale builds are informational, not \"fix not live\". Only daemon-\n // affecting stale builds (or ones where the classification is unknown →\n // defaulted true) mean a merged daemon/refinery fix is not yet live.\n const isDaemonAffecting = behind.isDaemonAffecting !== false;\n staleDaemonBuilds.push({\n daemonId,\n nodeId: entry.nodeId,\n scope: behind.scope,\n liveBuildCommit: behind.buildCommit,\n liveBuildCommitShort: behind.buildCommitShort,\n head: behind.head,\n isDaemonAffecting,\n ...(Array.isArray(behind.affectedPackages) && behind.affectedPackages.length > 0\n ? { affectedPackages: behind.affectedPackages }\n : {}),\n // The full ~300-char warning prose is identical for every entry and is\n // already emitted ONCE at the top level as `staleDaemonBuildWarning`.\n // Keep it per-entry only in verbose to avoid N× duplication in compact.\n ...(compact ? {} : { warning: behind.warning }),\n });\n }\n const daemonAffectingStaleBuilds = staleDaemonBuilds.filter((b) => b.isDaemonAffecting !== false);\n const webOnlyStaleBuilds = staleDaemonBuilds.filter((b) => b.isDaemonAffecting === false);\n\n // T7 (visibility 7-2b): provider-version skew across nodes. Mirrors the\n // daemonBuilds/staleDaemonBuild aggregate pattern — fold each node's\n // self-reported providerVersions into a per-provider view, then flag any\n // provider whose version differs across the nodes that reported it. Purely\n // observational (never fail-closed): a coordinator uses this to notice that\n // node A is on claude-cli 1.2.3 while node B is on 1.1.0 before it delegates\n // work that assumes a uniform toolchain — the exact gap daemonBuilds could not\n // show (build-commit alone doesn't capture the installed CLI versions).\n const providerVersionsByProvider: Record<string, Record<string, string[]>> = {};\n for (const entry of results as any[]) {\n const versions = entry?.providerVersions;\n if (!versions || typeof versions !== 'object') continue;\n const nodeId = typeof entry?.nodeId === 'string' ? entry.nodeId : '';\n for (const [providerId, rawVersion] of Object.entries(versions as Record<string, unknown>)) {\n const version = typeof rawVersion === 'string' ? rawVersion.trim() : '';\n if (!providerId || !version) continue;\n const byVersion = (providerVersionsByProvider[providerId] ??= {});\n (byVersion[version] ??= []).push(nodeId);\n }\n }\n const providerVersionSkew: Array<Record<string, unknown>> = [];\n for (const [providerId, byVersion] of Object.entries(providerVersionsByProvider)) {\n const distinctVersions = Object.keys(byVersion);\n if (distinctVersions.length <= 1) continue; // uniform → no skew\n providerVersionSkew.push({\n provider: providerId,\n versions: distinctVersions.map((version) => ({\n version,\n nodeIds: byVersion[version].filter(Boolean),\n })),\n });\n }\n\n let stubbedNodeCount = 0;\n let foldedNodesSummary: Record<string, unknown> | undefined;\n const nodesForResponse = compact\n ? (() => {\n const compacted = results.map((entry: any) => {\n const next = compactMeshStatusNode(entry);\n if (!next || typeof next !== 'object') return next;\n if (Array.isArray(next.sessions)) {\n next.sessionSummary = summarizeNodeSessions(next.sessions);\n // Drop the full per-node array unless explicitly opted in. The\n // de-duplicated full lists are available under top-level\n // `daemonSessions` keyed by daemonId.\n if (!includeSessions) delete next.sessions;\n }\n // Build stamp is folded per-daemon under top-level `daemonBuilds`;\n // drop the repetitive per-node copy in compact mode.\n if (next.daemonBuild !== undefined) delete next.daemonBuild;\n return next;\n });\n\n // Two-tier bounding, highest-severity first:\n // 1. detail byte-budget — noteworthy nodes get full compact detail until\n // COMPACT_DETAILED_NODES_BYTE_BUDGET is spent; the rest degrade to a stub.\n // 2. total node-array byte-budget — quiet/overflow nodes are emitted as\n // minimal stubs until COMPACT_NODES_TOTAL_BYTE_BUDGET is spent; any node\n // beyond that is fully folded into the foldedNodes id-list summary.\n // Nodes that survive in the array keep their ORIGINAL order. Every node id is\n // either in the array (detail or stub) or listed in foldedNodes.nodeIds.\n const noteworthy = compacted.filter((n: any) => n && typeof n === 'object' && isNoteworthyCompactNode(n));\n const ranked = [...noteworthy].sort((a, b) => compactNodeSeverity(b) - compactNodeSeverity(a));\n const detailedIds = new Set<string>();\n let detailSpent = 0;\n for (const n of ranked) {\n const cost = JSON.stringify(n).length + 1;\n if (detailedIds.size === 0 || detailSpent + cost <= COMPACT_DETAILED_NODES_BYTE_BUDGET) {\n detailedIds.add(String(n.nodeId));\n detailSpent += cost;\n }\n }\n\n // severity order for awarding the remaining total budget to stubs\n const stubOrder = [...compacted]\n .filter((n: any) => n && typeof n === 'object')\n .sort((a, b) => compactNodeSeverity(b) - compactNodeSeverity(a));\n const keptIds = new Set<string>(detailedIds);\n let totalSpent = detailSpent;\n for (const n of stubOrder) {\n const id = String(n.nodeId);\n if (keptIds.has(id)) continue;\n const stubCost = JSON.stringify(minimalCompactNode(n)).length + 1;\n if (totalSpent + stubCost <= COMPACT_NODES_TOTAL_BYTE_BUDGET) {\n keptIds.add(id);\n totalSpent += stubCost;\n }\n }\n\n const fullyFolded: any[] = [];\n const out = compacted\n .map((n: any) => {\n if (!n || typeof n !== 'object') return n;\n const id = String(n.nodeId);\n if (detailedIds.has(id)) return n;\n if (keptIds.has(id)) {\n stubbedNodeCount += 1;\n return minimalCompactNode(n);\n }\n fullyFolded.push(n);\n return null;\n })\n .filter((n: any) => n !== null);\n\n if (fullyFolded.length > 0) {\n const byBranchConvergence: Record<string, number> = {};\n const byHealth: Record<string, number> = {};\n const nodeIds: string[] = [];\n for (const n of fullyFolded) {\n const bc = typeof n?.branchConvergence?.status === 'string' ? n.branchConvergence.status : 'unknown';\n byBranchConvergence[bc] = (byBranchConvergence[bc] ?? 0) + 1;\n const h = typeof n?.health === 'string' ? n.health : 'unknown';\n byHealth[h] = (byHealth[h] ?? 0) + 1;\n if (n?.nodeId) nodeIds.push(String(n.nodeId));\n }\n foldedNodesSummary = {\n count: fullyFolded.length,\n note: 'Node-array byte budget reached: these nodes are listed by id only. Query a specific node_id or use verbose=true for their detail.',\n byHealth,\n byBranchConvergence,\n nodeIds,\n };\n }\n return out;\n })()\n : results;\n\n const response: Record<string, unknown> = {\n meshId: mesh.id,\n meshName: mesh.name,\n repoIdentity: mesh.repoIdentity,\n policy: mesh.policy,\n // Mesh-level scheduling rollup (strategy + global cap consumption). Per-node\n // detail (load/priority/provider caps/claim-block reasons) lives on each\n // nodes[].scheduling; the node array is dropped here to avoid duplicating it.\n scheduling: {\n strategy: schedulingRuntime.strategy,\n maxParallelTasks: schedulingRuntime.maxParallelTasks,\n maxReadonlyParallelTasks: schedulingRuntime.maxReadonlyParallelTasks,\n activeWriteAssigned: schedulingRuntime.activeWriteAssigned,\n activeReadonlyAssigned: schedulingRuntime.activeReadonlyAssigned,\n globalWriteCapReached: schedulingRuntime.globalWriteCapReached,\n globalReadonlyCapReached: schedulingRuntime.globalReadonlyCapReached,\n },\n payloadMode: compact ? 'compact' : 'full',\n refreshedAt: new Date().toISOString(),\n sourceOfTruth: {\n membership: 'coordinator_daemon_live_mesh',\n currentStatus: 'live_git_and_session_probes',\n activeWork: 'mesh_queue_file_and_local_ledger',\n historicalEvidenceOnly: ['recoveryHints', 'ledgerSummary'],\n },\n nodes: nodesForResponse,\n ...(compact && stubbedNodeCount > 0\n ? {\n stubbedNodesNote: `${stubbedNodeCount} node(s) in the array above are reduced to a minimal stub (marked folded:true) in compact mode — healthy/clean nodes plus any beyond the detail byte-budget. They remain addressable by node_id; use verbose=true for their full detail.`,\n }\n : {}),\n ...(compact && foldedNodesSummary ? { foldedNodes: foldedNodesSummary } : {}),\n ...(compact && Object.keys(daemonSessions).length > 0 ? { daemonSessions } : {}),\n ...(Object.keys(daemonBuilds).length > 0 ? { daemonBuilds } : {}),\n ...(staleDaemonBuilds.length > 0 ? { staleDaemonBuilds } : {}),\n ...(daemonAffectingStaleBuilds.length > 0\n ? {\n staleDaemonBuildWarning: 'One or more live daemons were built from a commit behind the workspace HEAD with daemon-runtime package changes. Merged refinery/mesh-tool fixes are NOT live on those daemons until they are rebuilt/redeployed and restarted — a local daemon-core dist rebuild does not update a cloud daemon. Do not assume a just-merged fix is active.',\n }\n : {}),\n ...(webOnlyStaleBuilds.length > 0\n ? {\n webOnlyStaleBuildNote: 'One or more live daemons are behind workspace HEAD, but only web packages changed in that range. The daemon does NOT need a rebuild/restart — redeploy the web app to reflect those changes. This is informational, not a \"fix not live\" condition.',\n }\n : {}),\n // T7: provider CLI/ACP version skew across nodes (observational only).\n ...(providerVersionSkew.length > 0\n ? {\n providerVersionSkew,\n providerVersionSkewWarning: 'One or more provider CLIs/ACP agents are running different versions across mesh nodes (see providerVersionSkew). This is informational, not a dispatch blocker — but a task that assumes a uniform toolchain (e.g. a version-specific flag or output format) may behave differently per node. Consider aligning versions or pinning the task to a node with the expected version.',\n }\n : {}),\n activeWork: activeWorkForResponse.records,\n ...(compact && activeWorkForResponse.omitted > 0\n ? { activeWorkRowsOmitted: activeWorkForResponse.omitted }\n : {}),\n ...(compact\n ? { activeWorkHint: `Compact activeWork rows carry a short taskTitle + dispatch scalars only; full task prompt/summary text is omitted — use mesh_task_history or mesh_status verbose=true. First ${COMPACT_MAX_ACTIVE_WORK_ROWS} rows serialized.` }\n : {}),\n staleDirectWorkSummary,\n ...(args.includeStaleDirectWorkDetails === true ? { staleDirectWork: activeWorkEvidence.staleDirectWork } : {}),\n // terminalDirectWork is historical (completed/failed direct dispatches) — opt-in only.\n ...(args.includeTerminalDirectWork === true ? { terminalDirectWork: activeWorkEvidence.terminalDirectWork } : {}),\n activeWorkSummary: activeWorkEvidence.summary,\n ...(pollingGuidance ? { pollingGuidance } : {}),\n ...(rateResult.rateLimitExceeded ? { pollingRateAdvisory: { type: 'rate_limit_exceeded', tool: 'mesh_status', callsInWindow: rateResult.callsInWindow, message: rateResult.advisory } } : {}),\n branchConvergenceSummary: summarizeBranchConvergence(results, compact),\n ...(coordinatorSessions.length > 0\n ? {\n coordinatorSessions,\n selfIdentification: {\n meshId: mesh.id,\n coordinatorSessions,\n note: 'Sessions listed here are coordinator sessions for this mesh. The calling coordinator IS one of these sessions — do not treat its own generating CLI session as a foreign delegated task. Per-session marker: sessions[].isSelfCoordinator === true.',\n },\n }\n : {}),\n };\n\n // Include task ledger summary for coordinator context\n try {\n response.ledgerSummary = ledgerSummary;\n } catch { /* ledger read is best-effort */ }\n\n // M3-2: mission summaries — goal + live task aggregates (derived, not stored).\n // M7: each mission also carries time/attempt stats derived from the ledger.\n //\n // The missions section previously dominated the compact payload: every live\n // mission AND up to 10 history missions were emitted in full (goalPreview +\n // tasks + a per-mission stats rollup) on every poll, so a mesh with many\n // missions pushed mesh_status past the MCP token cap. Compact mode now folds\n // missions like it folds nodes/sessions:\n // • live (active/paused) missions keep detail, goal-elided to a tight preview\n // and WITHOUT the stats rollup (the tasks aggregate already carries\n // progress; stats is a verbose/dashboard concern);\n // • completed/abandoned history is folded to a counts + id summary\n // (missionsHistory) instead of full per-mission detail;\n // • a byte budget bounds the live array — overflow folds into foldedMissions\n // (id list), so even a mesh of many active missions can't blow the cap.\n // verbose=true restores the full dashboard-grade missions (full goal text, the\n // stats rollup, and full-detail history) — the backward-compatible escape hatch.\n try {\n if (compact) {\n const { live, historyFold } = getMeshStatusMissionsCompact(mesh.id);\n // Bound the live-mission detail by byte budget, newest-active first.\n // Overflow folds into foldedMissions so every live id stays addressable.\n const ranked = [...live].sort((a, b) =>\n String((b as any).tasks?.lastActivityAt ?? '').localeCompare(String((a as any).tasks?.lastActivityAt ?? '')));\n const kept: any[] = [];\n const overflow: any[] = [];\n let spent = 0;\n for (const m of ranked) {\n const cost = JSON.stringify(m).length + 1;\n if (kept.length === 0 || spent + cost <= COMPACT_MISSIONS_BYTE_BUDGET) {\n kept.push(m);\n spent += cost;\n } else {\n overflow.push(m);\n }\n }\n if (kept.length > 0) response.missions = kept;\n if (overflow.length > 0) {\n const byStatus: Record<string, number> = {};\n for (const m of overflow) byStatus[String(m.status)] = (byStatus[String(m.status)] ?? 0) + 1;\n response.foldedMissions = {\n count: overflow.length,\n note: 'Live-mission byte budget reached: these active/paused missions are listed by id only. Use mesh_mission_list or mesh_status verbose=true for their detail.',\n byStatus,\n missionIds: overflow.map(m => String(m.id)),\n };\n }\n if (historyFold) response.missionsHistory = historyFold;\n } else {\n const missions = getMeshStatusMissionSummaries(mesh.id, { verbose: true });\n if (missions.length > 0) {\n response.missions = missions.map(mission => {\n try {\n return { ...mission, stats: computeMeshMissionStats(mesh.id, mission.id) };\n } catch {\n return mission;\n }\n });\n }\n }\n } catch { /* mission read is best-effort */ }\n\n try {\n const pendingEvents = await drainCoordinatorPendingEvents(ctx);\n const asyncRefineJobs = buildMeshAsyncRefineJobs({\n meshId: mesh.id,\n ledgerEntries,\n pendingEvents,\n });\n if (asyncRefineJobs.length > 0) {\n if (compact) {\n // Drop terminal (completed/failed) refine jobs — they are historical and\n // dominate the payload. Keep active (non-terminal) job objects so the\n // coordinator can still track in-flight refines, and replace the rest with\n // a status-count summary.\n //\n // Stale terminal jobs (resolved refinery rejections/successes from earlier\n // in the ledger window — often multi-day-old) are folded out of the counts\n // so byStatus.failed reflects *current* breakage, not historical residue.\n // The folded count is surfaced as `staleTerminal` for transparency.\n const summary = summarizeMeshAsyncRefineJobs(asyncRefineJobs);\n if (summary.activeJobs.length > 0) response.asyncRefineJobs = summary.activeJobs;\n response.asyncRefineJobsSummary = {\n total: summary.total,\n byStatus: summary.byStatus,\n ...(summary.staleTerminal > 0 ? { staleTerminal: summary.staleTerminal } : {}),\n };\n } else {\n response.asyncRefineJobs = asyncRefineJobs;\n }\n }\n\n // deltaE: fold persisted MAGI cross-verification activity into mesh_status so a\n // coordinator (and the dashboard's extractMagiActivity) can read the synthesis\n // fields — needs_verification counts, independence banner, and git skew —\n // without re-running collection. Bounded like asyncRefineJobs: running groups\n // always shown, synthesized groups only when recent (stale ones folded to a count).\n const magiActivity = buildMeshMagiActivity({ meshId: mesh.id, ledgerEntries });\n if (magiActivity.length > 0) {\n const fold = summarizeMeshMagiActivity(magiActivity);\n if (compact) {\n if (fold.groups.length > 0) response.magiActivity = fold.groups;\n response.magiActivitySummary = {\n total: fold.total,\n byStatus: fold.byStatus,\n ...(fold.staleSynthesized > 0 ? { staleSynthesized: fold.staleSynthesized } : {}),\n };\n } else {\n response.magiActivity = magiActivity;\n }\n }\n\n if (pendingEvents.length > 0) {\n response.pendingCoordinatorEvents = pendingEvents;\n }\n\n // T7 (B4 visibility): mesh protocol v2 adoption metrics, derived from the\n // events surfaced in THIS drain. T1 stamps every newly-emitted pending event\n // with a v2 envelope (protocolVersion '2.0' + scope), so the share of drained\n // events carrying protocolVersion is the observable adoption signal — a\n // rollout gate that does NOT depend on daemonBuilds alone. This is a snapshot\n // of the drained batch (not a durable counter): quarantine/violation counts\n // and the PHASE-4 synthesis backstop counter are NOT aggregated here — those\n // counters land with the enforce path (T6, in mesh-reconcile-loop.ts, which\n // T7 does not touch). Omitted when nothing was drained.\n const protocolMetrics = summarizePendingEventProtocolMetrics(pendingEvents);\n if (protocolMetrics) {\n response.meshProtocolMetrics = protocolMetrics;\n }\n\n // T6 (B3c): the live enforce/backstop counters the daemon rode on the drain\n // above (drainCoordinatorPendingEvents stashed them on ctx). Unlike\n // meshProtocolMetrics (a per-batch adoption snapshot), these are process-lifetime\n // enforce-health totals: quarantine tallies + the last-resort backstop fire\n // counts (target 0 under a healthy v2 contract). Omitted on version-skewed\n // daemons that don't ride the field.\n if (ctx.lastMeshProtocolV2Counters) {\n response.meshProtocolV2Counters = ctx.lastMeshProtocolV2Counters;\n }\n } catch {\n // Non-fatal: pending events are best-effort.\n }\n\n return JSON.stringify(response, null, 2);\n}\n\nexport async function meshListNodes(ctx: MeshContext): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const { mesh } = ctx;\n return JSON.stringify({\n meshId: mesh.id,\n meshName: mesh.name,\n nodes: mesh.nodes.map(n => ({\n nodeId: n.id,\n workspace: n.workspace,\n repoRoot: n.repoRoot,\n daemonId: readNodeDaemonId(n),\n machineId: readNodeMachineId(n),\n machine: buildNodeMachineIdentity(ctx, n),\n isLocalWorktree: n.isLocalWorktree,\n policy: n.policy,\n relatedRepos: readRelatedRepos(n),\n ...getNodeLaunchReadiness(n),\n ...buildNodeCapabilityExposure(n),\n userOverrides: n.userOverrides,\n })),\n }, null, 2);\n}\n","// Mesh tool implementations — queue domain.\n// Pure move out of mesh-tools.ts (no behavior change). Shared helpers, types, module\n// state and dependency re-exports live in ./mesh-tools-internal.ts; mesh-tools.ts is a barrel.\n\nimport {\n ACTIVE_QUEUE_STATUSES,\n COMPACT_MAX_ACTIVE_QUEUE_ROWS,\n COMPACT_MAX_ACTIVE_WORK_ROWS,\n HISTORICAL_QUEUE_STATUSES,\n IpcTransport,\n annotateQueueStaleness,\n appendLedgerEntry,\n buildActiveWorkPollingGuidance,\n buildCompactQueueMaintenanceReport,\n buildCompactStaleDirectWorkSummary,\n buildMeshActiveWork,\n buildMeshNodeCapabilityTags,\n buildQueueMaintenanceReport,\n buildQueueStatusSummary,\n buildQueueTriggerGuidance,\n cancelTask,\n collectMeshViewQueueNodesWithLiveSessions,\n compactActiveWorkRecords,\n compactQueueRow,\n compactQueueRows,\n describeTaskDependencyState,\n enqueueTask,\n normalizeMeshTaskPriority,\n resolveNotBefore,\n filterQueueForView,\n getActiveDirectDispatches,\n getQueue,\n ipcDispatchToRemoteAgent,\n isLocalControlPlaneNode,\n markStaleDirectDispatches,\n meshNodeIdMatches,\n nodeSatisfiesRequiredTags,\n normalizeMeshCapabilityTags,\n normalizeQueueViewMode,\n prioritizeActiveQueueRows,\n readLedgerEntries,\n readString,\n reconcileDirectDispatchesFromTranscriptEvidence,\n recordMeshToolCall,\n refreshMeshFromDaemon,\n requeueTask,\n resolveCoordinatorDaemonId,\n resolvePreferredWorktreeNodeId,\n sanitizeQueueStatusFilter,\n summarizeTaskMessage,\n taskDependenciesSatisfied,\n triggerMeshQueueAndReport,\n unwrapCommandPayload,\n} from './mesh-tools-internal.js';\nimport type {\n MeshContext,\n QueueViewMode,\n} from './mesh-tools-internal.js';\n\n/**\n * G4: normalize a task message for duplicate fingerprinting. Collapses whitespace and\n * lowercases so trivial reformatting of the same instruction still matches. Intentionally\n * coarse — a false positive is a warning (warn-only default), never a silent drop.\n */\nfunction normalizeDedupMessage(message: string): string {\n return (message || '').trim().replace(/\\s+/g, ' ').toLowerCase();\n}\n\n/**\n * G4: find an in-flight (pending/assigned) queue task whose (normalized message + resolved\n * target node) matches the task about to be enqueued. Terminal rows (completed/failed/\n * cancelled) are historical and never a live duplicate. When no target node is pinned on the\n * new task, matching is on message alone (an unpinned re-enqueue of the same instruction is the\n * TASKBUBBLE-DUP case); when a target IS pinned, both message AND target must match so the same\n * instruction sent to two DIFFERENT nodes is not flagged. Returns the first match or null.\n */\nfunction findInFlightDuplicate(\n ctx: MeshContext,\n message: string,\n targetNodeId: string | undefined,\n): { id: string; status: string; assignedNodeId?: string; targetNodeId?: string } | null {\n const fingerprint = normalizeDedupMessage(message);\n if (!fingerprint) return null;\n for (const task of getQueue(ctx.mesh.id)) {\n if (task.status !== 'pending' && task.status !== 'assigned') continue;\n if (normalizeDedupMessage(task.message) !== fingerprint) continue;\n // Target-scoped match: only compare targets when the NEW task pins one. An unpinned\n // new task matches any in-flight task with the same message (broadest dup guard).\n if (targetNodeId) {\n const existingTarget = task.targetNodeId || task.assignedNodeId;\n if (!existingTarget || !meshNodeIdMatches({ id: existingTarget } as any, targetNodeId)) continue;\n }\n return { id: task.id, status: task.status, assignedNodeId: task.assignedNodeId, targetNodeId: task.targetNodeId };\n }\n return null;\n}\n\nexport async function meshEnqueueTask(\n ctx: MeshContext,\n args: {\n message: string; task_mode?: string; taskMode?: string;\n readonly?: boolean; read_only?: boolean;\n requiredTags?: string[]; required_tags?: string[];\n targetNodeId?: string; target_node_id?: string;\n targetNode?: string; target_node?: string;\n preferWorktree?: boolean; prefer_worktree?: boolean;\n dependsOn?: string[]; depends_on?: string[];\n missionId?: string; mission_id?: string;\n priority?: string;\n model?: string;\n thinkingLevel?: string;\n difficulty?: string;\n notBefore?: string | number; not_before?: string | number;\n maxRetries?: number; max_retries?: number;\n allowDuplicate?: boolean; allow_duplicate?: boolean;\n blockDuplicate?: boolean; block_duplicate?: boolean;\n },\n): Promise<string> {\n // DELIVERY-MSG-GUARD: make the schema's nominal `required: ['message']` real. The\n // tool dispatcher forwards raw args without runtime schema validation, so a caller\n // that omits message (or passes a non-string) would otherwise hand undefined to\n // enqueueTask → a message-less queue payload that crashes insertSessionDelivery's\n // NOT NULL at claim/dispatch. Reject at the tool boundary with a clear error.\n const message = readString(args.message);\n if (!message) {\n return JSON.stringify({\n success: false,\n code: 'invalid_message',\n error: 'mesh_enqueue_task requires a non-empty string `message`.',\n });\n }\n const taskMode = readString(args.task_mode) || readString(args.taskMode);\n const readonly = args.readonly === true || args.read_only === true;\n const requiredTags = normalizeMeshCapabilityTags(Array.isArray(args.requiredTags) ? args.requiredTags : args.required_tags);\n const dependsOn = Array.isArray(args.dependsOn) ? args.dependsOn : Array.isArray(args.depends_on) ? args.depends_on : undefined;\n const missionId = readString(args.missionId) || readString(args.mission_id) || undefined;\n // G6: task-level priority ('low' | 'normal' | 'high'). Invalid input → undefined (defaults to normal).\n const priority = normalizeMeshTaskPriority(readString(args.priority)) || undefined;\n // Optional model override — best-effort, applied at launch by providers that\n // support a model flag. Trimmed; blank → undefined (provider default).\n const model = readString(args.model) || undefined;\n // Brain-routing thinking axis + difficulty preset. thinkingLevel is best-effort\n // at launch; difficulty resolves the mesh preset in daemon-core enqueueTask\n // (fills model/thinkingLevel left blank). Both trimmed; blank → undefined.\n const thinkingLevel = readString(args.thinkingLevel) || undefined;\n const difficulty = readString(args.difficulty) || undefined;\n // G7: delayed execution. Accept a camelCase or snake_case not_before; resolveNotBefore\n // (in daemon-core, at enqueue) does the ISO/epoch-ms/relative-ms normalization — echoing it\n // here only for the response and dedup fingerprint.\n const notBeforeRaw = args.notBefore !== undefined ? args.notBefore : args.not_before;\n const notBefore = resolveNotBefore(notBeforeRaw);\n // P3: max automatic requeue attempts before the task auto-fails. Absent → policy default.\n const maxRetriesRaw = typeof args.maxRetries === 'number' ? args.maxRetries\n : typeof args.max_retries === 'number' ? args.max_retries : undefined;\n const maxRetries = typeof maxRetriesRaw === 'number' && Number.isFinite(maxRetriesRaw) && maxRetriesRaw >= 0\n ? Math.floor(maxRetriesRaw) : undefined;\n // G4: duplicate detection. Default is warn-only; block is opt-in (block_duplicate=true).\n // allow_duplicate=true silences the warning entirely (explicit intentional re-enqueue).\n const allowDuplicate = args.allowDuplicate === true || args.allow_duplicate === true;\n const blockDuplicate = args.blockDuplicate === true || args.block_duplicate === true;\n // Routing hint: explicit target id wins; otherwise prefer_worktree resolves to the\n // most recently cloned worktree node so isolated work is not preemptively claimed by\n // the first idle base node. Either becomes a targetNodeId, which the node-targeted\n // claim tier honors as a HARD constraint (only that node may claim).\n //\n // MESH-DISPATCH-MISROUTE: accept target_node / targetNode in addition to\n // target_node_id / targetNodeId. A coordinator that passed target_node (the natural\n // name) previously had it silently dropped — the task enqueued UNPINNED and any idle\n // node, including a different machine's base, could claim it (the live cross-machine\n // misroute). Resolving every spelling closes that gap.\n const explicitTargetRaw = readString(args.targetNodeId) || readString(args.target_node_id)\n || readString(args.targetNode) || readString(args.target_node) || undefined;\n const preferWorktree = args.preferWorktree === true || args.prefer_worktree === true;\n\n // MESH-DISPATCH-MISROUTE: a target pin is a hard constraint, so an unresolvable target\n // id must FAIL LOUDLY rather than silently fall through to an unpinned (any-node) task.\n // Canonicalize the supplied id to the live mesh node's own id via the shared identity\n // normalizer (handles id / nodeId / node_id and daemon-id forms) so the downstream raw\n // `node.id === targetNodeId` compares and the claim-tier SQL both match exactly.\n let targetNodeId: string | undefined;\n if (explicitTargetRaw) {\n const matched = ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, explicitTargetRaw));\n if (!matched) {\n return JSON.stringify({\n success: false,\n code: 'target_node_not_found',\n error: `target node '${explicitTargetRaw}' is not a member of this mesh — refusing to enqueue an unpinned task (it could be claimed by any node, including a different machine). Use mesh_list_nodes to get a valid node id.`,\n targetNodeId: explicitTargetRaw,\n availableNodeIds: ctx.mesh.nodes.map(n => (n as any).id).filter(Boolean),\n });\n }\n targetNodeId = readString((matched as any).id) || explicitTargetRaw;\n } else if (preferWorktree) {\n targetNodeId = resolvePreferredWorktreeNodeId(ctx) || undefined;\n }\n\n // ── G4: enqueue duplicate detection ──────────────────────────────────────\n // TASKBUBBLE-DUP is the recurring class where the SAME task is enqueued twice\n // (e.g. a coordinator re-sends after a slow turn) and both dispatch, doubling the\n // work. Fingerprint the new task by (normalized message + resolved targetNode) and\n // scan the IN-FLIGHT queue (pending/assigned only — terminal rows are historical and\n // never a live duplicate). Default is warn-only: the task still enqueues but the\n // response carries duplicateSuspect so the coordinator can notice and cancel one.\n // Blocking is opt-in (block_duplicate=true); allow_duplicate=true suppresses even the\n // warning for an intentional re-enqueue.\n const duplicateSuspect = allowDuplicate ? null : findInFlightDuplicate(ctx, message, targetNodeId);\n if (duplicateSuspect && blockDuplicate) {\n return JSON.stringify({\n success: false,\n code: 'duplicate_suspect',\n error: `an in-flight task with the same message${targetNodeId ? ' and target node' : ''} already exists (task '${duplicateSuspect.id}', status '${duplicateSuspect.status}'). Refusing because block_duplicate=true. Cancel it, wait for it, or re-enqueue with allow_duplicate=true.`,\n duplicateOf: { taskId: duplicateSuspect.id, status: duplicateSuspect.status, assignedNodeId: duplicateSuspect.assignedNodeId, targetNodeId: duplicateSuspect.targetNodeId },\n });\n }\n\n try {\n const task = enqueueTask(ctx.mesh.id, message, {\n taskMode, ...(readonly ? { readonly: true } : {}), requiredTags, dependsOn, missionId, targetNodeId,\n ...(priority ? { priority } : {}),\n ...(model ? { model } : {}),\n ...(thinkingLevel ? { thinkingLevel } : {}),\n ...(difficulty ? { difficulty } : {}),\n ...(notBefore ? { notBefore } : {}),\n ...(maxRetries !== undefined ? { maxRetries } : {}),\n ...(ctx.coordinatorSessionId ? { sourceCoordinatorSessionId: ctx.coordinatorSessionId } : {}),\n });\n const duplicateWarning = duplicateSuspect\n ? { duplicateSuspect: { taskId: duplicateSuspect.id, status: duplicateSuspect.status, assignedNodeId: duplicateSuspect.assignedNodeId, targetNodeId: duplicateSuspect.targetNodeId }, duplicateSuspectHint: 'An in-flight task with the same message+target already exists. This new task was enqueued anyway (warn-only). Cancel one via mesh_queue_cancel if it is an accidental re-enqueue, or pass allow_duplicate=true to silence this, or block_duplicate=true to refuse next time.' }\n : {};\n const enqueueEcho = {\n ...(task.priority ? { priority: task.priority } : {}),\n ...(task.notBefore ? { notBefore: task.notBefore } : {}),\n ...(task.maxRetries !== undefined ? { maxRetries: task.maxRetries } : {}),\n };\n\n // ── LocalTransport: queue-based pull (standalone daemon, all local) ─────\n if (!(ctx.transport instanceof IpcTransport)) {\n const queueTrigger = await triggerMeshQueueAndReport(ctx);\n return JSON.stringify({\n success: true,\n source: 'queue',\n taskId: task.id,\n status: task.status,\n taskMode: task.taskMode,\n requiredTags: task.requiredTags,\n ...enqueueEcho,\n ...(targetNodeId ? { targetNodeId } : {}),\n ...(preferWorktree && !explicitTargetRaw && !targetNodeId ? { preferWorktreeNoOp: true } : {}),\n ...duplicateWarning,\n queueTrigger,\n ...buildQueueTriggerGuidance(queueTrigger),\n });\n }\n\n // ── IpcTransport (Cloud Mesh): the queue file lives on THIS machine only.\n // Remote daemons on other machines cannot read the local queue file.\n // Strategy: trigger local queue for local nodes, and for remote nodes\n // directly P2P-dispatch to the first idle session found (enqueue-and-push).\n {\n // 1. Trigger local queue for local node pick-up\n const queueTrigger = await triggerMeshQueueAndReport(ctx);\n\n // 2. For each remote node, directly dispatch to an idle session via P2P\n //\n // DEPENDSON-GATE-SYMMETRY: gate the eager push with the SAME predicate the\n // queue-claim (claimNextQueueTask) and auto-launch paths use. If the task we\n // just enqueued still has unmet dependencies (or a system block), pushing it\n // straight to a remote idle session would bypass the gate the pull path\n // enforces and run the task BEFORE its prerequisites. Defer it entirely to the\n // queue drain (claim path), which re-evaluates the same predicate once the\n // dependency completes. Tasks with no dependsOn are unaffected (predicate is\n // true), preserving the prior eager-push behavior. The status index spans the\n // FULL queue (incl. completed) so terminal dependency states are visible.\n const dependencyStatusById = new Map(\n getQueue(ctx.mesh.id).map(t => [t.id, t.status] as const),\n );\n const eagerPushDeferred = !taskDependenciesSatisfied(task, dependencyStatusById);\n const coordinatorDaemonId = resolveCoordinatorDaemonId(ctx);\n const dispatchPromises: Promise<void>[] = [];\n const eagerPushTargets = eagerPushDeferred ? [] : ctx.mesh.nodes;\n for (const node of eagerPushTargets) {\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n if (isLocalNode || !node.daemonId) continue;\n // When the task targets a specific node, only that node's daemon\n // should receive the P2P push; others would steal the work.\n if (targetNodeId && node.id !== targetNodeId) continue;\n if (!nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node))) continue;\n\n // MISROUTE-INJECT-SPLIT: stamp meshContext (nodeId) onto the eager P2P push so the\n // worker's agent_command handler scopes it to THIS node's session via the\n // fail-closed findMeshNodeAdapter, instead of the provider-only fuzzy fallback that\n // can land a freshly-launched worktree node's task on a co-located idle BASE session\n // (the base-leak). Without nodeId the receiver's meshScopeNodeId is empty and it falls\n // through to findAdapter's first-same-cliType match. The queue-claim path already\n // carries this context; the enqueue-and-push path was the only dispatch missing it.\n dispatchPromises.push(\n ipcDispatchToRemoteAgent(ctx, node, {\n message,\n meshContext: {\n meshId: ctx.mesh.id,\n nodeId: node.id,\n taskId: task.id,\n ...(coordinatorDaemonId ? { coordinatorDaemonId } : {}),\n },\n })\n .then(result => {\n if (result.success) {\n try {\n const providerType = result.providerType;\n const descriptor = summarizeTaskMessage(message);\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'task_dispatched',\n nodeId: node.id,\n sessionId: result.sessionId,\n providerType,\n payload: {\n source: 'queue',\n via: 'p2p_direct',\n taskId: task.id,\n message,\n taskTitle: descriptor.taskTitle,\n taskSummary: descriptor.taskSummary,\n ...(task.taskMode ? { taskMode: task.taskMode } : {}),\n ...(providerType ? { providerType } : {}),\n targetSessionId: result.sessionId,\n },\n });\n } catch { /* best-effort */ }\n }\n })\n .catch((err: any) => {\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'p2p_dispatch_failed',\n nodeId: node.id,\n payload: {\n source: 'queue',\n via: 'p2p_direct',\n taskId: task.id,\n error: err?.message || String(err),\n dispatchFailedAt: new Date().toISOString(),\n },\n });\n } catch { /* best-effort */ }\n }),\n );\n }\n // Fire-and-forget — don't block the coordinator response\n Promise.all(dispatchPromises).catch(() => {});\n\n return JSON.stringify({\n success: true,\n source: 'queue',\n taskId: task.id,\n status: task.status,\n taskMode: task.taskMode,\n requiredTags: task.requiredTags,\n ...enqueueEcho,\n ...(targetNodeId ? { targetNodeId } : {}),\n ...(preferWorktree && !explicitTargetRaw && !targetNodeId ? { preferWorktreeNoOp: true } : {}),\n ...(eagerPushDeferred ? { eagerPushDeferred: true, eagerPushDeferredReason: 'dependencies_unsatisfied' } : {}),\n ...duplicateWarning,\n queueTrigger,\n ...buildQueueTriggerGuidance(queueTrigger),\n });\n }\n } catch (e: any) {\n const message = e?.message || String(e);\n if (message.includes('live_debug_readonly_guardrail_violation')) {\n return JSON.stringify({ success: false, code: 'live_debug_readonly_guardrail_violation', taskMode, error: message });\n }\n if (message.includes('dependency_cycle_detected')) {\n return JSON.stringify({ success: false, code: 'dependency_cycle_detected', dependsOn, error: message });\n }\n return JSON.stringify({ success: false, error: message });\n }\n}\n\nexport async function meshViewQueue(\n ctx: MeshContext,\n args: { status?: string[]; view?: QueueViewMode; compact?: boolean; verbose?: boolean },\n): Promise<string> {\n const rateResult = recordMeshToolCall({ meshId: ctx.mesh.id, tool: 'mesh_view_queue' });\n // Default to the slim payload for LLM callers; verbose forces the full payload.\n const compact = args.verbose === true ? false : (args.compact ?? true);\n try {\n await refreshMeshFromDaemon(ctx);\n const statusFilter = sanitizeQueueStatusFilter(args.status);\n const view = normalizeQueueViewMode(args.view);\n const rawQueue = getQueue(ctx.mesh.id);\n // M1: annotate dependency state (waitingOn, dependenciesSatisfied) at view time.\n const statusById = new Map(rawQueue.map(task => [task.id, task.status]));\n const withDependencies = rawQueue.map(task => {\n if (!Array.isArray(task.dependsOn) || task.dependsOn.length === 0) return task;\n const depState = describeTaskDependencyState(task, statusById);\n return { ...task, ...depState };\n });\n const fullQueue = prioritizeActiveQueueRows(annotateQueueStaleness(withDependencies, ctx.mesh));\n const queue = filterQueueForView(fullQueue, view, statusFilter);\n const summary = buildQueueStatusSummary(fullQueue);\n const visibleSummary = buildQueueStatusSummary(queue);\n const maintenance = buildQueueMaintenanceReport(fullQueue);\n const liveNodes = await collectMeshViewQueueNodesWithLiveSessions(ctx);\n let ledgerEntries = readLedgerEntries(ctx.mesh.id, { tail: 200 });\n let directDispatches = getActiveDirectDispatches(ctx.mesh.id);\n const directReconciliation = await reconcileDirectDispatchesFromTranscriptEvidence(ctx, liveNodes, directDispatches, ledgerEntries);\n if (directReconciliation.reconciled > 0) {\n ledgerEntries = readLedgerEntries(ctx.mesh.id, { tail: 200 });\n directDispatches = getActiveDirectDispatches(ctx.mesh.id);\n }\n // Mark dispatched entries with no session activity after 30 min as stale.\n markStaleDirectDispatches(ctx.mesh.id);\n directDispatches = getActiveDirectDispatches(ctx.mesh.id);\n const activeWorkEvidence = buildMeshActiveWork({\n meshId: ctx.mesh.id,\n queue: fullQueue,\n ledgerEntries,\n // Always pass MeshRuntimeStore records (may be empty). buildMeshActiveWork uses them for local\n // dispatches and falls through to ledger scan for remote P2P dispatches not in MeshRuntimeStore.\n directDispatches,\n nodes: liveNodes,\n });\n const recentDispatchFailures = ledgerEntries\n .filter(e => e.kind === 'p2p_dispatch_failed')\n .slice(-20)\n .map(e => ({\n nodeId: e.nodeId,\n taskId: e.payload?.taskId,\n error: e.payload?.error,\n via: e.payload?.via,\n failedAt: e.payload?.dispatchFailedAt || e.timestamp,\n }));\n const staleAssignedTasks = (maintenance as any).staleAssignedTasks || [];\n const requestedHistoricalRows = queue.some((task: any) => HISTORICAL_QUEUE_STATUSES.has(String(task?.status || '')));\n const pollingGuidance = buildActiveWorkPollingGuidance(activeWorkEvidence.summary);\n\n // Compact mode: completed/failed/cancelled historical row arrays are the main\n // payload bloat (mesh_view_queue has overflowed 250k chars on busy meshes).\n // Drop them in favor of the status counts that summary/visibleSummary already\n // carry, but keep pending/assigned active rows — those drive coordinator\n // dispatch decisions. verbose=true returns every row as before.\n const activeOnlyQueue = queue.filter((task: any) => !HISTORICAL_QUEUE_STATUSES.has(String(task?.status || '')));\n // Compact mode: cap active rows and truncate per-row messages (a busy mesh\n // can carry dozens of multi-KB task messages → 70KB+ in the active array).\n const compactQueueResult = compact ? compactQueueRows(activeOnlyQueue) : { rows: activeOnlyQueue, omitted: 0 };\n const visibleQueue = compact ? compactQueueResult.rows : queue;\n const wantActiveQueueArray = view === 'active' || statusFilter?.some(status => ACTIVE_QUEUE_STATUSES.has(status));\n const wantHistoricalQueueArray = !compact && (view === 'historical' || requestedHistoricalRows);\n // activeWork carries the full task message/summary per record — the single\n // largest payload source on a busy mesh. Slim + cap it in compact mode.\n const activeWorkResult = compact\n ? compactActiveWorkRecords(activeWorkEvidence.activeWork)\n : { records: activeWorkEvidence.activeWork, omitted: 0 };\n\n // staleDirectWork is a full MeshActiveWorkRecord[] of orphaned/historical\n // direct dispatches — it is the second major payload-bloat source (the first\n // being historical queue rows). In compact mode, collapse it to the same\n // bounded summary mesh_status uses and only emit the full array in verbose mode.\n const staleDirectWorkSummary = buildCompactStaleDirectWorkSummary(activeWorkEvidence.staleDirectWork, {\n note: activeWorkEvidence.staleDirectWorkNote,\n detailHint: 'Full stale direct entries are omitted from mesh_view_queue in compact mode. Call mesh_view_queue with verbose=true, or inspect mesh_task_history for ledger detail.',\n });\n // queueMaintenance/cleanupDryRun serialize the same maintenance object whose\n // cleanupCandidates array scales with old historical record count. In compact\n // mode drop the per-row arrays in favor of counts.\n const maintenanceForResponse = compact ? buildCompactQueueMaintenanceReport(maintenance) : maintenance;\n\n return JSON.stringify({\n success: true,\n payloadMode: compact ? 'compact' : 'full',\n sourceOfTruth: {\n kind: 'mesh_work_queue_file',\n activeStatuses: ['pending', 'assigned'],\n historicalStatuses: ['completed', 'failed', 'cancelled'],\n notes: 'pending/assigned are active work; completed/failed/cancelled are historical ledger records and never stale assignments.',\n },\n filter: {\n view,\n statuses: statusFilter,\n filtered: Boolean(statusFilter?.length) || view !== 'all',\n },\n queue: visibleQueue,\n ...(compact ? { historicalRowsOmitted: true, historicalRowsHint: 'Completed/failed/cancelled rows are omitted in compact mode; see historicalCounts. Call mesh_view_queue with verbose=true (or view=historical, compact=false) for full rows.' } : {}),\n ...(compact && compactQueueResult.omitted > 0 ? {\n activeRowsOmitted: compactQueueResult.omitted,\n activeRowsHint: `Showing the first ${COMPACT_MAX_ACTIVE_QUEUE_ROWS} active rows (per-row messages truncated). ${compactQueueResult.omitted} more active row(s) omitted — see activeCount/activeCounts for the complete total or use verbose=true.`,\n } : {}),\n activeWork: activeWorkResult.records,\n ...(compact && activeWorkResult.omitted > 0 ? {\n activeWorkOmitted: activeWorkResult.omitted,\n activeWorkHint: `Showing the first ${COMPACT_MAX_ACTIVE_WORK_ROWS} active-work records (messages truncated). ${activeWorkResult.omitted} more omitted — see activeWorkSummary for complete counts or use verbose=true.`,\n } : {}),\n staleDirectWorkSummary,\n ...(compact ? {} : { staleDirectWork: activeWorkEvidence.staleDirectWork }),\n activeWorkSummary: activeWorkEvidence.summary,\n ...(pollingGuidance ? { pollingGuidance } : {}),\n ...(rateResult.rateLimitExceeded ? { pollingRateAdvisory: { type: 'rate_limit_exceeded', tool: 'mesh_view_queue', callsInWindow: rateResult.callsInWindow, message: rateResult.advisory } } : {}),\n summary,\n visibleSummary,\n activeCounts: summary.activeCounts,\n historicalCounts: summary.historicalCounts,\n visibleActiveCounts: visibleSummary.activeCounts,\n visibleHistoricalCounts: visibleSummary.historicalCounts,\n activeCount: summary.activeCount,\n historicalCount: summary.historicalCount,\n visibleActiveCount: visibleSummary.activeCount,\n visibleHistoricalCount: visibleSummary.historicalCount,\n staleAssignedTasks: compact ? staleAssignedTasks.slice(0, 10).map(compactQueueRow) : staleAssignedTasks,\n staleAssignedCount: (maintenance as any).staleAssignedCount,\n queueMaintenance: maintenanceForResponse,\n cleanupDryRun: maintenanceForResponse,\n ...(recentDispatchFailures.length > 0 ? {\n recentDispatchFailures,\n dispatchFailureCount: recentDispatchFailures.length,\n dispatchFailureNote: 'Remote P2P dispatch attempts that failed. Affected tasks remain pending and may require mesh_queue_requeue if no idle session picks them up.',\n } : {}),\n ...(wantActiveQueueArray && !compact ? {\n activeQueue: queue.filter((task: any) => ACTIVE_QUEUE_STATUSES.has(String(task?.status || ''))),\n } : {}),\n // In compact mode the `queue` field already holds exactly the slimmed+\n // capped active rows, so the separate activeQueue array would be a verbatim\n // duplicate (it doubled the payload). Point callers at `queue` instead.\n ...(wantActiveQueueArray && compact ? { activeQueueHint: 'In compact mode the active rows are in `queue` (already filtered to pending/assigned). Use verbose=true for the separate full activeQueue array.' } : {}),\n ...(wantHistoricalQueueArray ? {\n historicalQueue: queue.filter((task: any) => HISTORICAL_QUEUE_STATUSES.has(String(task?.status || ''))),\n } : {}),\n // Back-compat alias for callers already reading the first hardening payload.\n staleAssignments: compact ? staleAssignedTasks.slice(0, 10).map(compactQueueRow) : staleAssignedTasks,\n }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n}\n\nexport async function meshQueueCancel(\n ctx: MeshContext,\n args: { task_id?: string; taskId?: string; reason?: string },\n): Promise<string> {\n try {\n const taskId = (args.task_id || args.taskId || '').trim();\n if (!taskId) return JSON.stringify({ success: false, error: 'task_id required' });\n\n // MESH-DISPATCH-MISROUTE: read the PRE-cancel entry so we know whether the task was\n // already dispatched to a live worker. cancelTask overwrites status to 'cancelled'\n // but preserves assignedSessionId/Node/Provider, so the assignment fields survive —\n // only the status must be captured before the mutation.\n const preCancel = getQueue(ctx.mesh.id).find((t: any) => t?.id === taskId) as {\n status?: string; assignedSessionId?: string; assignedNodeId?: string; assignedProviderType?: string;\n } | undefined;\n const wasAssigned = preCancel?.status === 'assigned';\n const assignedSessionId = readString(preCancel?.assignedSessionId) || undefined;\n const assignedNodeId = readString(preCancel?.assignedNodeId) || undefined;\n const assignedProviderType = readString(preCancel?.assignedProviderType) || undefined;\n\n const task = cancelTask(ctx.mesh.id, taskId, { reason: args.reason });\n if (!task) return JSON.stringify({ success: false, error: `Queue task '${taskId}' not found` });\n ctx.transport.command('trigger_mesh_queue', { meshId: ctx.mesh.id }).catch(() => {});\n\n // MESH-DISPATCH-MISROUTE (fix 2): cancelling the queue row alone does NOT stop a worker\n // that already claimed the task and is generating — it ran to completion and committed\n // to the (often base) checkout. When the task was dispatched to a live session, propagate\n // a stop so the worker halts its in-flight generation. Guards:\n // - only for an 'assigned' task with a resolvable assignedSessionId (a pending/terminal\n // task has no live worker to stop — sending one would be a no-op at best);\n // - NEVER stop the coordinator's own session (ctx.coordinatorSessionId) — that is the\n // session issuing the cancel, not the worker. Stopping it would kill the coordinator.\n // The stop rides agent_command(action:'stop'), which is already in the router's\n // MESH_FORWARDABLE_SESSION_COMMANDS set: a session hosted on a REMOTE worker daemon is\n // auto-forwarded to that daemon (cross-machine workers are reached), and meshContext.nodeId\n // keeps the fail-closed cross-node scoping AND now seeds the router's deterministic\n // owner-resolution fallback (assignedNodeId → owner daemon) so a worktree-clone worker\n // whose session id missed the coordinator's cached active-sessions snapshot is still reached.\n // CANCEL-STOP false-positive fix: AWAIT the stop and report its REAL outcome\n // (stopped / no response from remote worker daemon / \"CLI agent not running\") instead of\n // pre-stamping attempted:true on a fire-and-forget call. Best-effort: any stop failure is\n // caught and surfaced in workerStop.reason — it must NEVER fail the cancel itself, which\n // already committed the queue 'cancelled' transition above.\n let workerStop: { attempted: boolean; stopped?: boolean; sessionId?: string; nodeId?: string; reason?: string } = { attempted: false };\n if (wasAssigned && assignedSessionId && assignedSessionId !== ctx.coordinatorSessionId && assignedProviderType) {\n workerStop = { attempted: true, sessionId: assignedSessionId, nodeId: assignedNodeId };\n try {\n const stopResult = await ctx.transport.command('agent_command', {\n targetSessionId: assignedSessionId,\n cliType: assignedProviderType,\n agentType: assignedProviderType,\n action: 'stop',\n ...(assignedNodeId ? { meshContext: { meshId: ctx.mesh.id, nodeId: assignedNodeId, taskId } } : {}),\n });\n const stopped = stopResult?.stopped === true || stopResult?.success === true;\n workerStop.stopped = stopped;\n if (!stopped) {\n workerStop.reason = readString(stopResult?.error) || 'worker stop not confirmed';\n }\n } catch (e: any) {\n workerStop.stopped = false;\n workerStop.reason = e?.message || String(e);\n }\n } else if (wasAssigned && assignedSessionId === ctx.coordinatorSessionId) {\n workerStop = { attempted: false, reason: 'assigned_session_is_coordinator_self — stop suppressed' };\n }\n\n return JSON.stringify({ success: true, task, workerStop }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n}\n\nexport async function meshQueueRequeue(\n ctx: MeshContext,\n args: {\n task_id?: string;\n taskId?: string;\n reason?: string;\n target_node_id?: string;\n targetNodeId?: string;\n target_session_id?: string;\n targetSessionId?: string;\n clear_target_node?: boolean;\n clearTargetNode?: boolean;\n keep_target_session?: boolean;\n keepTargetSession?: boolean;\n force?: boolean;\n },\n): Promise<string> {\n try {\n const taskId = (args.task_id || args.taskId || '').trim();\n if (!taskId) return JSON.stringify({ success: false, error: 'task_id required' });\n const targetNodeId = (args.target_node_id || args.targetNodeId || '').trim() || undefined;\n const targetSessionId = (args.target_session_id || args.targetSessionId || '').trim() || undefined;\n const keepTargetSession = args.keep_target_session === true || args.keepTargetSession === true;\n const clearTargetNode = args.clear_target_node === true || args.clearTargetNode === true;\n // clearTargetSession contract: an explicit target session pins the row (never cleared);\n // otherwise clear the stale target session unless the caller asked to keep it.\n const clearTargetSession = targetSessionId ? false : !keepTargetSession;\n const force = args.force === true;\n\n // CANON-IDENTITY cross-process single-flight: the in-flight guard set\n // (daemon-core mesh-task-inflight) is process-LOCAL. In IpcTransport (cloud /\n // multi-coordinator) mode this tool runs in the COORDINATOR process, but the\n // dispatch that marks a task in-flight (tryAssignQueueTask → beginTaskDispatchInFlight)\n // runs in the mesh-host DAEMON process. An in-process requeueTask here would consult a\n // DIFFERENT (empty) Set, so isTaskDispatchInFlight is always false, the guard is a\n // no-op, and a requeue-while-generating flips the row to pending → a SECOND session\n // claims the SAME task (the double-dispatch). Delegate the requeue to the daemon so\n // begin (dispatch) and check (requeue guard) are co-located in ONE process. The daemon\n // handler (requeue_mesh_queue_task) implements the same guard + the refused signal,\n // which we surface to the caller verbatim. LocalTransport (standalone) runs daemon and\n // coordinator in the same process, so its in-process path already sees the right Set.\n if (ctx.transport instanceof IpcTransport) {\n const raw = await ctx.transport.command('requeue_mesh_queue_task', {\n meshId: ctx.mesh.id,\n taskId,\n reason: args.reason,\n ...(targetNodeId ? { targetNodeId } : {}),\n ...(targetSessionId ? { targetSessionId } : {}),\n clearTargetNode,\n clearTargetSession,\n force,\n });\n const result = unwrapCommandPayload(raw) || {};\n // Refused (in-flight / live-generating guard) or daemon error → surface verbatim\n // so the coordinator learns the requeue did NOT open a second dispatch.\n if (result.success === false) {\n return JSON.stringify(result, null, 2);\n }\n const task = result.task;\n if (!task) return JSON.stringify({ success: false, error: `Queue task '${taskId}' not found` });\n if (task.status === 'failed' && task.cancelReason?.startsWith('max_retries_exceeded')) {\n return JSON.stringify({\n success: false,\n code: 'max_retries_exceeded',\n error: task.cancelReason,\n task,\n hint: 'Use force=true to bypass the retry cap for explicit operator recovery.',\n }, null, 2);\n }\n const triggerPreferredNodeId = targetNodeId || task.targetNodeId || undefined;\n ctx.transport.command('trigger_mesh_queue', {\n meshId: ctx.mesh.id,\n ...(triggerPreferredNodeId ? { preferredNodeId: triggerPreferredNodeId } : {}),\n }).catch(() => {});\n return JSON.stringify({ success: true, task }, null, 2);\n }\n\n const task = requeueTask(ctx.mesh.id, taskId, {\n reason: args.reason,\n targetNodeId,\n targetSessionId,\n clearTargetNode,\n clearTargetSession,\n force,\n });\n if (!task) return JSON.stringify({ success: false, error: `Queue task '${taskId}' not found` });\n if (task.status === 'failed' && task.cancelReason?.startsWith('max_retries_exceeded')) {\n return JSON.stringify({\n success: false,\n code: 'max_retries_exceeded',\n error: task.cancelReason,\n task,\n hint: 'Use force=true to bypass the retry cap for explicit operator recovery.',\n }, null, 2);\n }\n // Pass the task's target node as preferredNodeId so the trigger claims the\n // requeued task on the intended node's idle session FIRST (router.ts\n // preferred-node tier) before the general round-robin picks a different node.\n // Honours an explicit requeue target_node_id over the persisted one.\n const triggerPreferredNodeId = targetNodeId || task.targetNodeId || undefined;\n ctx.transport.command('trigger_mesh_queue', {\n meshId: ctx.mesh.id,\n ...(triggerPreferredNodeId ? { preferredNodeId: triggerPreferredNodeId } : {}),\n }).catch(() => {});\n return JSON.stringify({ success: true, task }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e.message });\n }\n}\n","// Mesh tool implementations — mission domain.\n// Pure move out of mesh-tools.ts (no behavior change). Shared helpers, types, module\n// state and dependency re-exports live in ./mesh-tools-internal.ts; mesh-tools.ts is a barrel.\n\nimport {\n MESH_MISSION_STATUSES,\n appendLedgerEntry,\n appendRemoteLedgerEntries,\n buildMeshLedgerReconciliationEvidence,\n buildMeshLedgerReplicaEvidence,\n commandForNode,\n computeMeshTaskStats,\n drainCoordinatorPendingEvents,\n getLedgerSummary,\n isLocalControlPlaneNode,\n listMeshMissionsForTool,\n readLedgerEntries,\n readLedgerSlice,\n getMeshMission,\n readLedgerSliceFromStore,\n readString,\n refreshMeshFromDaemon,\n requeueHeldMeshCoordinatorEvents,\n slimLedgerPayload,\n tombstoneOperatingNote,\n unwrapCommandPayload,\n upsertMeshMission,\n} from './mesh-tools-internal.js';\nimport type {\n MeshContext,\n} from './mesh-tools-internal.js';\n\nexport async function meshTaskHistory(\n ctx: MeshContext,\n args: { tail?: number; kind?: string; compact?: boolean; verbose?: boolean },\n): Promise<string> {\n const { mesh } = ctx;\n // Default to the slim payload for LLM callers; verbose forces full payloads.\n const compact = args.verbose === true ? false : (args.compact ?? true);\n const pendingEvents = await drainCoordinatorPendingEvents(ctx);\n // Clamp tail so a large default/explicit value can't blow up the payload in\n // compact mode. Full (verbose) callers may request a deeper window.\n const requestedTail = typeof args.tail === 'number' && args.tail > 0 ? Math.floor(args.tail) : 20;\n // Compact: cap conservatively so even large refine-batch entries can't blow the\n // token limit. slimLedgerPayload is the primary defense (it summarizes large\n // plan/validationPlan/suggestedConfig fields); this clamp is the backstop. A deep\n // explicit request (tail > 50) is clamped harder (20) than a modest one (30).\n const compactCap = requestedTail > 50 ? 20 : 30;\n const tail = compact ? Math.min(requestedTail, compactCap) : Math.min(requestedTail, 200);\n const kind = typeof args.kind === 'string' && args.kind.trim() ? [args.kind.trim() as any] : undefined;\n const rawEntries = readLedgerEntries(mesh.id, { tail, kind });\n // Slim large payload fields so coordinator context stays lean. Verbose\n // returns the raw payloads untouched for full audit detail.\n const entries = compact\n ? rawEntries.map(e => ({\n ...e,\n payload: e.payload ? slimLedgerPayload(e.payload) : e.payload,\n }))\n : rawEntries;\n const summary = getLedgerSummary(mesh.id);\n // M7: per-task time/attempt stats for tasks visible in the returned window.\n // Derived from ledger truth at query time; incomplete evidence is flagged,\n // never estimated.\n let taskStats: unknown[] | undefined;\n try {\n const taskIds = [...new Set(rawEntries\n .map(e => (typeof e.payload?.taskId === 'string' ? e.payload.taskId : ''))\n .filter(Boolean))] as string[];\n if (taskIds.length > 0) {\n const stats = computeMeshTaskStats(mesh.id, { taskIds });\n if (stats.length > 0) taskStats = stats;\n }\n } catch { /* stats are best-effort */ }\n return JSON.stringify({\n meshId: mesh.id,\n payloadMode: compact ? 'compact' : 'full',\n entries,\n summary,\n ...(taskStats ? { taskStats } : {}),\n ...(pendingEvents.length > 0 ? { pendingCoordinatorEvents: pendingEvents } : {}),\n }, null, 2);\n}\n\nexport async function meshLedgerQuery(\n ctx: MeshContext,\n args: { kind?: string; since?: string; node?: string; tail?: number },\n): Promise<string> {\n const { mesh } = ctx;\n const pendingEvents = await drainCoordinatorPendingEvents(ctx);\n // kind accepts one kind or a comma-separated list; normalize to the array the\n // ledger reader expects. Empty tokens are dropped.\n const kind = typeof args.kind === 'string' && args.kind.trim()\n ? (args.kind.split(',').map(k => k.trim()).filter(Boolean) as any[])\n : undefined;\n // since accepts ISO-8601 or epoch-ms; readLedgerEntries parses via new Date(),\n // which handles both an ISO string and a numeric ms value (as string or number).\n const since = typeof args.since === 'string' && args.since.trim()\n ? args.since.trim()\n : (typeof args.since === 'number' ? String(args.since) : undefined);\n const node = typeof args.node === 'string' && args.node.trim() ? args.node.trim() : undefined;\n // tail default 50, clamped to 500 (read-only query axis — deeper than the\n // compact task_history window since it isn't payload-heavy by default).\n const requestedTail = typeof args.tail === 'number' && args.tail > 0 ? Math.floor(args.tail) : 50;\n const tail = Math.min(requestedTail, 500);\n const entries = readLedgerEntries(mesh.id, { tail, kind, since, node });\n const summary = getLedgerSummary(mesh.id);\n return JSON.stringify({\n meshId: mesh.id,\n query: {\n ...(kind ? { kind } : {}),\n ...(since ? { since } : {}),\n ...(node ? { node } : {}),\n tail,\n },\n count: entries.length,\n entries,\n summary,\n ...(pendingEvents.length > 0 ? { pendingCoordinatorEvents: pendingEvents } : {}),\n }, null, 2);\n}\n\nexport async function meshRecordNote(\n ctx: MeshContext,\n args: { text?: string; category?: string },\n): Promise<string> {\n const { mesh } = ctx;\n const text = typeof args.text === 'string' ? args.text.trim() : '';\n if (!text) {\n return JSON.stringify({ success: false, error: 'text required' }, null, 2);\n }\n const category = args.category === 'provider_quirk' || args.category === 'pattern_to_avoid' || args.category === 'recovery_lesson'\n ? args.category\n : undefined;\n const createdAt = new Date().toISOString();\n // sourceCoordinator: best-effort identity of the recording coordinator so a\n // future coordinator can attribute the note. Session id is the most precise;\n // fall back to the daemon/hostname.\n const sourceCoordinator = ctx.coordinatorSessionId || ctx.localDaemonId || ctx.coordinatorHostname || undefined;\n const entry = appendLedgerEntry(mesh.id, {\n kind: 'coordinator_operating_note',\n ...(sourceCoordinator ? { sessionId: sourceCoordinator } : {}),\n payload: {\n text,\n ...(category ? { category } : {}),\n createdAt,\n ...(sourceCoordinator ? { sourceCoordinator } : {}),\n },\n });\n return JSON.stringify({\n success: true,\n meshId: mesh.id,\n noteId: entry.id,\n recorded: { text, category: category ?? null, createdAt },\n note: 'Recorded to the mesh ledger. Future coordinators on this mesh will see it under \"## Operating Notes\" at launch.',\n }, null, 2);\n}\n\nexport async function meshForgetNote(\n ctx: MeshContext,\n args: { note_id?: string; noteId?: string; text?: string; reason?: string },\n): Promise<string> {\n const { mesh } = ctx;\n const noteId = readString(args.note_id) || readString(args.noteId) || undefined;\n const text = typeof args.text === 'string' ? args.text.trim() : '';\n if (!noteId && !text) {\n return JSON.stringify({ success: false, error: 'note_id or text required' }, null, 2);\n }\n try {\n const { tombstone, matched } = tombstoneOperatingNote(mesh.id, {\n ...(noteId ? { noteId } : {}),\n ...(text ? { text } : {}),\n ...(typeof args.reason === 'string' && args.reason.trim() ? { reason: args.reason.trim() } : {}),\n });\n return JSON.stringify({\n success: true,\n meshId: mesh.id,\n tombstoneId: tombstone.id,\n forgot: { noteId: noteId ?? null, text: text || null, matched },\n note: matched > 0\n ? `Retracted ${matched} operating note(s). Future coordinators on this mesh will no longer see them at launch. History is preserved (append-only tombstone).`\n : 'No live operating note matched — recorded a tombstone anyway so any matching note appended later is also suppressed.',\n }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e?.message || String(e) }, null, 2);\n }\n}\n\nexport async function meshReconcileLedger(\n ctx: MeshContext,\n args: { node_ids?: string[]; limit?: number; after_id?: string; since?: string; import_entries?: boolean },\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const requestedNodeIds = Array.isArray(args.node_ids)\n ? new Set(args.node_ids.map(id => typeof id === 'string' ? id.trim() : '').filter(Boolean))\n : null;\n const nodes = ctx.mesh.nodes.filter(node => !requestedNodeIds || requestedNodeIds.has(node.id));\n const replicas: any[] = [];\n const shouldImport = args.import_entries !== false;\n const queryArgs = {\n meshId: ctx.mesh.id,\n ...(typeof args.limit === 'number' ? { limit: args.limit } : {}),\n ...(typeof args.after_id === 'string' && args.after_id.trim() ? { afterId: args.after_id.trim() } : {}),\n ...(typeof args.since === 'string' && args.since.trim() ? { since: args.since.trim() } : {}),\n };\n\n // OFFLINE-NODE-BLOCKING: the ledger fan-out issues one `get_mesh_ledger_slice` per\n // node. Run them concurrently with per-node error isolation (Promise.allSettled) so a\n // single dead node no longer serializes the rest, AND stamp the read-only slice probe\n // with the status-origin marker ({ statusProbe: true }) so the daemon-cloud relay grants\n // the SHORT connect-wait budget — an offline (powered-off) node is rejected in ~2s with\n // PEER_NOT_CONNECTED instead of sinking into the 90s connect deadline. Order-preserving:\n // results are collected back in `nodes` order so the aggregated evidence is unchanged.\n const reconcileNode = async (node: (typeof nodes)[number]): Promise<any> => {\n try {\n if (isLocalControlPlaneNode(ctx, node) || !node.daemonId) {\n // G4: Use SQLite mesh_event_ledger (bounded slice) as the local P2P reconcile read path.\n // readLedgerSlice (JSONL) is retained for per-daemon P2P export; coordinator local reads use SQLite.\n const slice = readLedgerSliceFromStore(ctx.mesh.id, queryArgs);\n return buildMeshLedgerReplicaEvidence({\n nodeId: node.id,\n daemonId: node.daemonId,\n transport: 'local',\n slice,\n status: 'local',\n });\n }\n\n const result = await commandForNode(ctx, node, 'get_mesh_ledger_slice', queryArgs, { statusProbe: true });\n const payload = unwrapCommandPayload(result);\n if (payload?.success === false) {\n throw new Error(payload.error || 'remote get_mesh_ledger_slice failed');\n }\n const slice = payload?.slice ?? payload;\n if (slice?.protocol !== 'adhdev.mesh.ledger.slice.v1' || !Array.isArray(slice.entries)) {\n throw new Error('remote daemon returned an invalid ledger slice payload');\n }\n const importResult = shouldImport\n ? appendRemoteLedgerEntries(ctx.mesh.id, slice.entries)\n : { accepted: 0, skippedDuplicate: 0, rejectedInvalid: 0, entries: [] };\n if (shouldImport && importResult.accepted > 0) {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'ledger_replicated',\n nodeId: node.id,\n payload: {\n protocol: 'adhdev.mesh.ledger.slice.v1',\n imported: importResult.accepted,\n skippedDuplicate: importResult.skippedDuplicate,\n rejectedInvalid: importResult.rejectedInvalid,\n nextAfterId: slice.cursor?.nextAfterId ?? null,\n via: 'p2p_datachannel',\n },\n });\n }\n return buildMeshLedgerReplicaEvidence({\n nodeId: node.id,\n daemonId: node.daemonId,\n transport: 'p2p_datachannel',\n slice,\n importResult,\n });\n } catch (e: any) {\n return buildMeshLedgerReplicaEvidence({\n nodeId: node.id,\n daemonId: node.daemonId,\n transport: node.daemonId ? 'p2p_datachannel' : 'local',\n status: 'failed',\n error: e?.message ?? String(e),\n });\n }\n };\n\n const settled = await Promise.allSettled(nodes.map(reconcileNode));\n settled.forEach((outcome, idx) => {\n if (outcome.status === 'fulfilled') {\n replicas.push(outcome.value);\n } else {\n // reconcileNode swallows its own errors, so a rejection here is unexpected —\n // fall back to a failed-replica marker rather than dropping the node silently.\n const node = nodes[idx];\n replicas.push(buildMeshLedgerReplicaEvidence({\n nodeId: node.id,\n daemonId: node.daemonId,\n transport: node.daemonId ? 'p2p_datachannel' : 'local',\n status: 'failed',\n error: outcome.reason?.message ?? String(outcome.reason),\n }));\n }\n });\n\n const evidence = buildMeshLedgerReconciliationEvidence(ctx.mesh.id, replicas);\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'ledger_reconciled',\n payload: {\n protocol: evidence.protocol,\n sourceOfTruth: evidence.sourceOfTruth,\n totals: evidence.totals,\n convergence: evidence.convergence,\n },\n });\n return JSON.stringify({ success: true, evidence }, null, 2);\n}\n\nexport async function meshRequeueHeldEvents(\n ctx: MeshContext,\n args: { filter?: { task_id?: string; taskId?: string; node_id?: string; nodeId?: string; event?: string; reason?: string; since?: string } },\n): Promise<string> {\n const { mesh } = ctx;\n const raw = args.filter && typeof args.filter === 'object' ? args.filter : undefined;\n const filter = raw\n ? {\n ...(readString(raw.task_id) || readString(raw.taskId) ? { taskId: (readString(raw.task_id) || readString(raw.taskId)) } : {}),\n ...(readString(raw.node_id) || readString(raw.nodeId) ? { nodeId: (readString(raw.node_id) || readString(raw.nodeId)) } : {}),\n ...(readString(raw.event) ? { event: readString(raw.event) } : {}),\n ...(readString(raw.reason) ? { reason: readString(raw.reason) } : {}),\n ...(readString(raw.since) ? { since: readString(raw.since) } : {}),\n }\n : undefined;\n\n const result = requeueHeldMeshCoordinatorEvents(mesh.id, filter && Object.keys(filter).length > 0 ? filter : undefined);\n\n const note = result.matched === 0\n ? 'No recoverable held events matched. Nothing to requeue.'\n : `${result.requeued} held event(s) restored to the pending queue`\n + (result.dedupSuppressed > 0 ? ` (${result.dedupSuppressed} collapsed onto still-live duplicates)` : '')\n + (result.alreadyRequeued > 0 ? `; ${result.alreadyRequeued} already recovered by a prior pass` : '')\n + (result.unrecoverable > 0 ? `; ${result.unrecoverable} had no restorable original event` : '')\n + '. A coordinator will drain them on its next poll.';\n\n return JSON.stringify({ success: true, ...result, note }, null, 2);\n}\n\nexport async function meshMissionUpsert(\n ctx: MeshContext,\n args: { mission_id?: string; missionId?: string; mission_ids?: unknown; missionIds?: unknown; title?: string; goal?: string; status?: string },\n): Promise<string> {\n // Bulk mode: mission_ids[] + status applies one status to many missions (stale\n // cleanup). Takes precedence over the single mission_id path. title/goal are ignored;\n // each mission keeps its own title (upsertMeshMission needs a non-empty title, so we\n // re-supply the existing one per mission).\n const bulkIds = normalizeMissionIdList(args.mission_ids ?? args.missionIds);\n if (bulkIds.length > 0) {\n return meshMissionUpsertBulk(ctx, bulkIds, readString(args.status));\n }\n\n try {\n const title = readString(args.title);\n if (!title) {\n return JSON.stringify({\n success: false,\n code: 'mission_title_required',\n error: 'mission_title_required: single-mission upsert needs a non-empty title. For a bulk status transition pass mission_ids (array) + status instead.',\n });\n }\n const mission = upsertMeshMission(ctx.mesh.id, {\n id: readString(args.mission_id) || readString(args.missionId) || undefined,\n title,\n goal: typeof args.goal === 'string' ? args.goal : undefined,\n status: readString(args.status) || undefined,\n });\n return JSON.stringify({\n success: true,\n mission,\n nextAction: 'Attach tasks with mesh_enqueue_task mission_id and depends_on. mesh_status shows live task aggregates for this mission.',\n });\n } catch (e: any) {\n const message = e?.message || String(e);\n const code = message.includes('mission_title_required') ? 'mission_title_required'\n : message.includes('invalid_mission_status') ? 'invalid_mission_status'\n : undefined;\n return JSON.stringify({ success: false, ...(code ? { code } : {}), error: message });\n }\n}\n\n/** Coerce a mission_ids input into a de-duplicated list of non-empty string ids. */\nfunction normalizeMissionIdList(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n const seen = new Set<string>();\n for (const raw of value) {\n const id = typeof raw === 'string' ? raw.trim() : '';\n if (id) seen.add(id);\n }\n return [...seen];\n}\n\n/**\n * G3 (step ②) — bulk mission status transition. Applies `status` to every id in\n * `missionIds`, returning a per-mission result so a partial failure (unknown id,\n * invalid status) never silently drops the rest. Each mission keeps its own title —\n * upsertMeshMission requires a non-empty title, so we look up the existing record and\n * re-supply its title while changing only the status. Primary use: the one-time cleanup\n * of accumulated stale missions.\n */\nasync function meshMissionUpsertBulk(\n ctx: MeshContext,\n missionIds: string[],\n status: string | undefined,\n): Promise<string> {\n if (!status) {\n return JSON.stringify({\n success: false,\n code: 'bulk_status_required',\n error: 'bulk mission upsert (mission_ids) requires a status to apply to every listed mission.',\n });\n }\n const results = missionIds.map((id) => {\n try {\n const existing = getMeshMission(ctx.mesh.id, id);\n if (!existing) return { id, ok: false, error: 'mission_not_found' };\n const updated = upsertMeshMission(ctx.mesh.id, {\n id,\n title: existing.title,\n status,\n });\n return { id, ok: true, status: updated.status };\n } catch (e: any) {\n const message = e?.message || String(e);\n const code = message.includes('invalid_mission_status') ? 'invalid_mission_status' : undefined;\n return { id, ok: false, error: message, ...(code ? { code } : {}) };\n }\n });\n const applied = results.filter(r => r.ok).length;\n const failed = results.length - applied;\n return JSON.stringify({\n success: failed === 0,\n mode: 'bulk',\n requestedStatus: status,\n applied,\n failed,\n results,\n nextAction: failed === 0\n ? `Applied status '${status}' to ${applied} mission(s).`\n : `${applied} applied, ${failed} failed — see results[] for per-mission errors.`,\n });\n}\n\nexport async function meshMissionList(\n ctx: MeshContext,\n args: {\n status?: string | string[];\n verbose?: boolean;\n include_magi?: boolean;\n includeMagi?: boolean;\n include_stats?: boolean;\n includeStats?: boolean;\n limit?: number;\n } = {},\n): Promise<string> {\n try {\n const rawStatuses = Array.isArray(args.status)\n ? args.status\n : typeof args.status === 'string' && args.status.trim()\n ? [args.status]\n : [];\n const invalid = rawStatuses.filter(s => !MESH_MISSION_STATUSES.includes(s as any));\n if (invalid.length > 0) {\n return JSON.stringify({\n success: false,\n code: 'invalid_mission_status',\n error: `invalid status filter: ${invalid.join(', ')} (valid: ${MESH_MISSION_STATUSES.join(', ')})`,\n });\n }\n const statuses = rawStatuses.length > 0 ? (rawStatuses as any[]) : undefined;\n const includeMagi = (args.include_magi ?? args.includeMagi) === true;\n const verbose = args.verbose === true;\n // stats are ledger-scanned per mission — off by default so a list view stays\n // bounded. verbose or explicit include_stats opts in. The `tasks` aggregate on\n // each mission already carries progress for the common list case.\n const withStats = verbose || (args.include_stats ?? args.includeStats) === true;\n const limit = typeof args.limit === 'number' && Number.isFinite(args.limit) && args.limit > 0\n ? Math.floor(args.limit)\n : undefined;\n const result = listMeshMissionsForTool(ctx.mesh.id, {\n statuses,\n verbose,\n includeMagi,\n withStats,\n limit,\n });\n return JSON.stringify({\n success: true,\n count: result.missions.length,\n matched: result.matched,\n ...(result.truncated ? { truncated: true, overflowIds: result.overflowIds } : {}),\n ...(statuses ? { statusFilter: statuses } : {}),\n ...(includeMagi ? { includeMagi: true } : { magiCompletedHidden: true }),\n ...(withStats ? {} : { statsHidden: true }),\n missions: result.missions,\n ...(result.historyFold ? { historyFold: result.historyFold } : {}),\n }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e?.message || String(e) });\n }\n}\n\nexport async function meshReviewInbox(\n ctx: MeshContext,\n args: { mesh_id?: string } = {},\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const meshId = (args.mesh_id ?? ctx.mesh.id).trim();\n // OFFLINE-NODE-BLOCKING: the review inbox is read from a single hardcoded node\n // (nodes[0]). If that node is offline (powered off) the read-only `get_mesh_review_inbox`\n // relay would otherwise sink into the 90s connect deadline. Stamp the status-origin\n // marker ({ statusProbe: true }) so the daemon-cloud relay grants the SHORT connect-wait\n // budget and an offline nodes[0] fails fast (~2s) instead of hanging the inbox read.\n const result = await commandForNode(ctx, ctx.mesh.nodes[0], 'get_mesh_review_inbox', {\n meshId,\n inlineMesh: ctx.mesh,\n }, { statusProbe: true });\n return JSON.stringify(result, null, 2);\n}\n","// Mesh tool implementations — MAGI (Multi-Agent Ground-truth Insight) domain.\n//\n// A standing mesh cross-verification quorum for any read-only investigation:\n// fan the SAME question out to N independent (node × provider) replicas, then\n// synthesize consensus / disagreement / unique evidence into a needs_verification\n// list — NOT a majority vote (high agreement among coupled agents ≠ correct).\n//\n// Design: docs/design/2026-06-28-mesh-magi-review.md.\n//\n// The pure core (parseMagiResponse / synthesizeMagiResponses / buildMagiFanoutPlan)\n// is unit-tested in mesh-tools-magi.test.ts; the handlers wire it to the mesh\n// queue/mission/transport. Shared helpers and dependency re-exports live in\n// ./mesh-tools-internal.ts; mesh-tools.ts is the barrel.\n\nimport {\n annotateQueueStaleness,\n appendLedgerEntry,\n buildMeshNodeCapabilityTags,\n commandForNode,\n compactChatPayload,\n enqueueTask,\n findOptionalNodeWithRefresh,\n getMeshMission,\n getQueue,\n isWeakCompletionEvidence,\n isMeshNodeHealthLaunchable,\n resolveEffectiveMeshNodeHealth,\n getMagiKindPanel,\n listMagiKindPanels,\n setMagiKindPanel,\n normalizeMagiSlots,\n MAGI_RAW_ANSWER_CAP,\n meshNodeIdMatches,\n nodeSatisfiesRequiredTags,\n normalizeMeshCapabilityTags,\n randomUUID,\n readProviderPriority,\n readLedgerEntries,\n readString,\n refreshMeshFromDaemon,\n resolveCoordinatorNode,\n triggerMeshQueueAndReport,\n unwrapCommandPayload,\n upsertMeshMission,\n} from './mesh-tools-internal.js';\nimport { resolveMagiSessionCleanupMode, type RepoMeshMagiSessionCleanupMode } from '@adhdev/daemon-core';\nimport type {\n LocalMeshEntry,\n LocalMeshNodeEntry,\n MagiAgentResponse,\n MagiClaim,\n MagiClaimCluster,\n MagiClusterMember,\n MagiGitSkew,\n MagiMode,\n MagiTaskKind,\n MagiSlot,\n MagiReplicaGitRef,\n MagiResponseSource,\n MagiSynthesis,\n MagiSynthesizedResponse,\n MeshContext,\n} from './mesh-tools-internal.js';\n\n// ─── Guards / constants ─────────────────────────\n\n/** Hard cap on total replicas (members × n) per mesh_magi_review invocation. */\nexport const MAGI_MAX_REPLICAS = 12;\n/** Minimum distinct (node, provider) targets a panel must resolve to. */\nconst MAGI_MIN_TARGETS = 2;\n/**\n * Lexical-cluster merge threshold (Jaccard over claim token sets).\n * FIX#2c: relaxed 0.5 → 0.4 so cross-provider same-conclusion claims worded a little\n * differently still merge (they were each becoming distinctProviders=1 singletons). Kept\n * conservative — the existing synthesis unit tests (singleton non-merge etc.) still pass at\n * 0.4 because their non-mergeable claims share zero content tokens (jaccard 0).\n */\nconst MAGI_CLUSTER_JACCARD = 0.4;\n/** Default wall-clock budget for wait=true replica collection. */\nconst MAGI_DEFAULT_WAIT_MS = 180_000;\nconst MAGI_MAX_WAIT_MS = 600_000;\nconst MAGI_POLL_INTERVAL_MS = 5_000;\n\n// ─── Task kinds (MAGI-REDESIGN) ─────────────────\n//\n// A `task_kind` selects ONE output schema that is injected into the replica prompt\n// (no schema-on-schema conflict) and ONE strict parser used at collection. The\n// kinds are: claim_audit (default, backward-compatible), rca, design, freeform.\n// Every kind except freeform requires non-empty evidence[]; an empty-evidence\n// answer is a validation failure that triggers the single delta re-request (E).\n//\n// To avoid rewriting the diversity-weighted synthesis (which is defined over the\n// common-schema MagiAgentResponse — claims/top_findings/open_questions), each kind\n// ADAPTS its typed payload into a MagiAgentResponse so clustering/independence still\n// work, while the raw typed payload is preserved on the source for display.\n\n// MagiTaskKind SSOT lives in the mesh-shared leaf, consumed here through daemon-core's\n// re-export (mesh-tools-internal) — same indirection as the other Magi* types, so this\n// module takes no direct @adhdev/mesh-shared dependency. Re-exported for existing\n// callers that import MagiTaskKind from this module.\nexport type { MagiTaskKind } from './mesh-tools-internal.js';\n\nconst VALID_TASK_KINDS: readonly MagiTaskKind[] = ['claim_audit', 'rca', 'design', 'freeform'];\nconst DEFAULT_TASK_KIND: MagiTaskKind = 'claim_audit';\n\n// ─── MAGI-KIND-PANEL ───\n//\n// A bare `task_kind` (no pre-authored panel name / members) NO LONGER auto-synthesizes\n// a diverse cross-provider panel from the live mesh. It resolves the user's explicitly\n// configured kind-panel binding (magiKindPanels: task_kind → (node × provider × model?)\n// slots). An unconfigured kind is a hard error (magi_kind_not_configured), never a\n// synthetic fallback. The former MAGI_KIND_PRESETS intent table and its resolver\n// (buildPresetMagiPanelForKind + helpers) were removed with that behavior change.\n\nexport function normalizeMagiTaskKind(raw: unknown): MagiTaskKind {\n const s = typeof raw === 'string' ? raw.trim().toLowerCase() : '';\n return (VALID_TASK_KINDS as readonly string[]).includes(s) ? (s as MagiTaskKind) : DEFAULT_TASK_KIND;\n}\n\n/** Parsed rca payload (kind=rca). */\nexport interface MagiRcaResponse {\n rootCause: string;\n failsAt: string;\n mechanism: string;\n evidence: string[];\n fixDirection: string;\n confidence: number;\n}\n\n/** Parsed design payload (kind=design). */\nexport interface MagiDesignResponse {\n recommendation: string;\n rationale: string;\n alternatives: string[];\n tradeoffs: string[];\n risks: string[];\n evidence: string[];\n confidence: number;\n}\n\n/** Parsed freeform payload (kind=freeform) — unstructured natural-language answer. */\nexport interface MagiFreeformResponse {\n text: string;\n}\n\n/**\n * Result of a kind-aware parse: the common-schema response fed to synthesis, the\n * raw typed payload for display, and (on failure) a structured reason that drives\n * the single delta re-request. `ok=false` means the text could not be coerced into\n * a valid response for this kind (missing required fields / empty evidence / no JSON).\n */\nexport interface MagiKindParseResult {\n ok: boolean;\n /** Adapted common-schema response for synthesis (present when ok). */\n response?: MagiAgentResponse;\n /** Raw typed payload (rca/design/freeform) for display (present when ok). */\n payload?: MagiRcaResponse | MagiDesignResponse | MagiFreeformResponse | MagiAgentResponse;\n /** Why the parse failed — surfaced and used to decide the delta re-request. */\n failReason?: 'no_parseable_output' | 'missing_required_fields' | 'empty_evidence';\n}\n\nconst VALID_STANCES = new Set(['support', 'oppose', 'uncertain']);\n\nfunction coerceClaim(raw: unknown): MagiClaim | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;\n const r = raw as Record<string, unknown>;\n const claim = typeof r.claim === 'string' ? r.claim.trim() : '';\n if (!claim) return null;\n const stance = typeof r.stance === 'string' && VALID_STANCES.has(r.stance) ? r.stance as MagiClaim['stance'] : 'uncertain';\n const evidence = Array.isArray(r.evidence)\n ? r.evidence.map(e => typeof e === 'string' ? e.trim() : '').filter(Boolean)\n : [];\n const confidence = typeof r.confidence === 'number' && Number.isFinite(r.confidence)\n ? Math.min(1, Math.max(0, r.confidence))\n : 0.5;\n return { claim, stance, evidence, confidence };\n}\n\nfunction coerceResponse(raw: unknown): MagiAgentResponse | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;\n const r = raw as Record<string, unknown>;\n if (!Array.isArray(r.claims)) return null;\n const claims = r.claims.map(coerceClaim).filter((c): c is MagiClaim => c !== null);\n const top_findings = Array.isArray(r.top_findings)\n ? r.top_findings.map(f => typeof f === 'string' ? f.trim() : '').filter(Boolean)\n : [];\n const open_questions = Array.isArray(r.open_questions)\n ? r.open_questions.map(q => typeof q === 'string' ? q.trim() : '').filter(Boolean)\n : [];\n // A response with no parseable claims is treated as unusable.\n if (claims.length === 0 && top_findings.length === 0) return null;\n return { claims, top_findings, open_questions };\n}\n\n/**\n * Scan text for balanced top-level JSON objects and return their substrings,\n * longest-first. Tolerates prose around the JSON and ```json fences — the agent\n * is asked for raw JSON but providers vary, so we extract defensively.\n */\nfunction extractJsonObjectCandidates(text: string): string[] {\n const candidates: string[] = [];\n let depth = 0;\n let start = -1;\n let inString = false;\n let escape = false;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escape) escape = false;\n else if (ch === '\\\\') escape = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') { inString = true; continue; }\n if (ch === '{') {\n if (depth === 0) start = i;\n depth++;\n } else if (ch === '}') {\n if (depth > 0) {\n depth--;\n if (depth === 0 && start >= 0) {\n candidates.push(text.slice(start, i + 1));\n start = -1;\n }\n }\n }\n }\n // Longest first: the full envelope object is preferred over a nested fragment.\n return candidates.sort((a, b) => b.length - a.length);\n}\n\n/**\n * Parse one agent's raw output text into the common-schema MagiAgentResponse, or\n * null when no parseable response is present. Pure — the unit of synthesis input.\n */\nexport function parseMagiResponse(text: string): MagiAgentResponse | null {\n if (typeof text !== 'string' || !text.trim()) return null;\n // Fast path: the whole text is the JSON object.\n const direct = ((): MagiAgentResponse | null => {\n try { return coerceResponse(JSON.parse(text)); } catch { return null; }\n })();\n if (direct) return direct;\n for (const candidate of extractJsonObjectCandidates(text)) {\n if (!candidate.includes('\"claims\"') && !candidate.includes('\"top_findings\"')) continue;\n try {\n const parsed = coerceResponse(JSON.parse(candidate));\n if (parsed) return parsed;\n } catch { /* try next candidate */ }\n }\n return null;\n}\n\n// ─── Kind-aware parsing (MAGI-REDESIGN C/D) ──────\n\nfunction asStringArray(raw: unknown): string[] {\n return Array.isArray(raw)\n ? raw.map(e => typeof e === 'string' ? e.trim() : '').filter(Boolean)\n : [];\n}\n\nfunction asConfidence(raw: unknown): number {\n return typeof raw === 'number' && Number.isFinite(raw) ? Math.min(1, Math.max(0, raw)) : 0.5;\n}\n\nfunction asTrimmedString(raw: unknown): string {\n return typeof raw === 'string' ? raw.trim() : '';\n}\n\n/**\n * Coerce a parsed JSON object into the rca payload. Returns the typed payload plus a\n * validity verdict separating \"missing required fields\" from \"empty evidence\" so the\n * caller can drive the delta re-request and surface the precise failure. rootCause +\n * mechanism are the minimum structural fields; evidence[] is the common D-rule field.\n */\nfunction coerceRcaResponse(raw: unknown): { payload: MagiRcaResponse; failReason?: MagiKindParseResult['failReason'] } | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;\n const r = raw as Record<string, unknown>;\n const rootCause = asTrimmedString(r.rootCause);\n const mechanism = asTrimmedString(r.mechanism);\n const failsAt = asTrimmedString(r.failsAt);\n const fixDirection = asTrimmedString(r.fixDirection);\n const evidence = asStringArray(r.evidence);\n const confidence = asConfidence(r.confidence);\n // Not an rca envelope at all (no structural field present) → let the caller try other shapes.\n if (!rootCause && !mechanism && !failsAt && !fixDirection && evidence.length === 0) return null;\n const payload: MagiRcaResponse = { rootCause, failsAt, mechanism, evidence, fixDirection, confidence };\n if (!rootCause || !mechanism) return { payload, failReason: 'missing_required_fields' };\n if (evidence.length === 0) return { payload, failReason: 'empty_evidence' };\n return { payload };\n}\n\n/**\n * Coerce a parsed JSON object into the design payload. recommendation + rationale are\n * the minimum structural fields; evidence[] is the common D-rule field.\n */\nfunction coerceDesignResponse(raw: unknown): { payload: MagiDesignResponse; failReason?: MagiKindParseResult['failReason'] } | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;\n const r = raw as Record<string, unknown>;\n const recommendation = asTrimmedString(r.recommendation);\n const rationale = asTrimmedString(r.rationale);\n const alternatives = asStringArray(r.alternatives);\n const tradeoffs = asStringArray(r.tradeoffs);\n const risks = asStringArray(r.risks);\n const evidence = asStringArray(r.evidence);\n const confidence = asConfidence(r.confidence);\n if (!recommendation && !rationale && alternatives.length === 0 && tradeoffs.length === 0 && risks.length === 0 && evidence.length === 0) return null;\n const payload: MagiDesignResponse = { recommendation, rationale, alternatives, tradeoffs, risks, evidence, confidence };\n if (!recommendation || !rationale) return { payload, failReason: 'missing_required_fields' };\n if (evidence.length === 0) return { payload, failReason: 'empty_evidence' };\n return { payload };\n}\n\n/**\n * Adapt an rca payload into the common-schema MagiAgentResponse so the existing\n * diversity-weighted synthesis (which clusters MagiClaim) applies unchanged: the root\n * cause becomes a single supporting claim carrying the rca evidence, mechanism/failsAt/\n * fixDirection become top_findings. Evidence is preserved verbatim so cross-replica\n * file:line independence still drives needs_verification.\n */\nfunction rcaToCommonSchema(p: MagiRcaResponse): MagiAgentResponse {\n return {\n claims: [{ claim: p.rootCause, stance: 'support', evidence: p.evidence, confidence: p.confidence }],\n top_findings: [\n ...(p.failsAt ? [`fails at: ${p.failsAt}`] : []),\n ...(p.mechanism ? [`mechanism: ${p.mechanism}`] : []),\n ...(p.fixDirection ? [`fix direction: ${p.fixDirection}`] : []),\n ],\n open_questions: [],\n };\n}\n\n/**\n * Adapt a design payload into the common-schema MagiAgentResponse: the recommendation\n * becomes the supporting claim (evidence preserved), rationale/alternatives/tradeoffs\n * become top_findings, risks become open_questions (each risk is an unresolved concern).\n */\nfunction designToCommonSchema(p: MagiDesignResponse): MagiAgentResponse {\n return {\n claims: [{ claim: p.recommendation, stance: 'support', evidence: p.evidence, confidence: p.confidence }],\n top_findings: [\n ...(p.rationale ? [`rationale: ${p.rationale}`] : []),\n ...p.alternatives.map(a => `alternative: ${a}`),\n ...p.tradeoffs.map(t => `tradeoff: ${t}`),\n ],\n open_questions: p.risks.map(r => `risk: ${r}`),\n };\n}\n\n/** Walk JSON candidates in text (raw object first, then embedded), applying a coercer. */\nfunction firstJsonCandidate<T>(text: string, coerce: (raw: unknown) => T | null): T | null {\n if (typeof text !== 'string' || !text.trim()) return null;\n try {\n const direct = coerce(JSON.parse(text));\n if (direct) return direct;\n } catch { /* fall through to embedded extraction */ }\n for (const candidate of extractJsonObjectCandidates(text)) {\n try {\n const parsed = coerce(JSON.parse(candidate));\n if (parsed) return parsed;\n } catch { /* try next candidate */ }\n }\n return null;\n}\n\n/**\n * Kind-aware parse of one replica's raw output text. claim_audit reuses the legacy\n * common-schema parser (claims required). rca/design extract their typed envelope from\n * raw or embedded JSON (no claims array required — the claims-less envelopes that the\n * old parser dropped now parse). freeform never fails parsing — any non-empty text is a\n * valid answer with no schema/evidence requirement. Pure.\n *\n * Returns ok=false with a failReason (no JSON / missing fields / empty evidence) so the\n * collection path can fire the single delta re-request (E) and surface the reason.\n */\nexport function parseMagiResponseForKind(text: string, kind: MagiTaskKind): MagiKindParseResult {\n if (kind === 'freeform') {\n const trimmed = typeof text === 'string' ? text.trim() : '';\n if (!trimmed) return { ok: false, failReason: 'no_parseable_output' };\n const payload: MagiFreeformResponse = { text: trimmed };\n // freeform contributes no structured claims to synthesis (cross-verify is weak).\n return { ok: true, response: { claims: [], top_findings: [trimmed], open_questions: [] }, payload };\n }\n if (kind === 'claim_audit') {\n const parsed = parseMagiResponse(text);\n if (!parsed) return { ok: false, failReason: 'no_parseable_output' };\n // D-rule: at least one claim must carry evidence (else it is unverifiable).\n const hasEvidence = parsed.claims.some(c => c.evidence.length > 0) || parsed.top_findings.length > 0;\n if (!hasEvidence && parsed.claims.length > 0) return { ok: false, payload: parsed, failReason: 'empty_evidence' };\n return { ok: true, response: parsed, payload: parsed };\n }\n if (kind === 'rca') {\n const result = firstJsonCandidate(text, coerceRcaResponse);\n if (!result) return { ok: false, failReason: 'no_parseable_output' };\n if (result.failReason) return { ok: false, payload: result.payload, failReason: result.failReason };\n return { ok: true, response: rcaToCommonSchema(result.payload), payload: result.payload };\n }\n // kind === 'design'\n const result = firstJsonCandidate(text, coerceDesignResponse);\n if (!result) return { ok: false, failReason: 'no_parseable_output' };\n if (result.failReason) return { ok: false, payload: result.payload, failReason: result.failReason };\n return { ok: true, response: designToCommonSchema(result.payload), payload: result.payload };\n}\n\n/** Parse the first kind-valid MAGI candidate from a daemon read_chat payload, newest-first. */\nexport function parseFirstMagiCandidateForKind(\n payload: unknown,\n kind: MagiTaskKind,\n opts: { sessionId?: string | null } = {},\n): MagiKindParseResult {\n const rawCandidates = collectMagiCandidateTexts(payload);\n let compactCandidates: string[] = [];\n try {\n compactCandidates = collectMagiCandidateTexts(\n compactChatPayload(payload, { sessionId: opts.sessionId ?? null }),\n );\n } catch { /* compact lift is best-effort */ }\n const seen = new Set<string>();\n let lastFail: MagiKindParseResult = { ok: false, failReason: 'no_parseable_output' };\n for (const candidate of [...rawCandidates, ...compactCandidates]) {\n const trimmed = candidate.trim();\n if (!trimmed || seen.has(trimmed)) continue;\n seen.add(trimmed);\n const result = parseMagiResponseForKind(candidate, kind);\n if (result.ok) return result;\n // Prefer the most specific failure (a parsed-but-invalid envelope over \"no JSON\")\n // so the surfaced reason / re-request is accurate.\n if (result.failReason !== 'no_parseable_output') lastFail = result;\n }\n return lastFail;\n}\n\n// ─── Synthesis (pure) ───────────────────────────\n\nconst CLAIM_STOPWORDS = new Set([\n 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'to', 'of', 'in',\n 'on', 'at', 'and', 'or', 'for', 'this', 'that', 'it', 'its', 'as', 'by', 'with',\n]);\n\nfunction claimTokenSet(claim: string): Set<string> {\n const tokens = claim.toLowerCase().split(/[^a-z0-9]+/).filter(t => t.length >= 2 && !CLAIM_STOPWORDS.has(t));\n return new Set(tokens);\n}\n\nfunction jaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let intersection = 0;\n for (const t of a) if (b.has(t)) intersection++;\n const union = a.size + b.size - intersection;\n return union === 0 ? 0 : intersection / union;\n}\n\n/** Looks like specific source evidence (file:line / path / URL), a strong merge signal. */\nfunction isSpecificEvidence(ev: string): boolean {\n return /[\\w/.\\\\-]+:\\d+/.test(ev) || /[\\w-]+\\.[a-z]{1,5}\\b/i.test(ev) || /https?:\\/\\//i.test(ev);\n}\n\n/**\n * FIX#2c — canonicalize a single concrete evidence TOKEN (file:line or URL) so the SAME\n * source merges across differently-FORMATTED citations. The greedy merge compares\n * specificEvidence sets by exact string membership, so two replicas that cite the same file\n * line as `resolver.ts:128` vs `src/resolver.ts:128` (or the same doc as a bare URL vs a\n * prose \"see https://… (the design doc)\") never merged and each stayed a distinctProviders=1\n * singleton. Canonicalize the recognizable concrete forms; everything else falls back to the\n * old lowercase-collapse. Pure / order-independent.\n *\n * - file:line → `<basename>:<line>` (drop directory prefix + normalize \\\\ vs / so the same\n * file cited with/without a path prefix collides; the basename+line pair is the discriminator)\n * - URL → scheme-less host+path, lowercased, no trailing slash / query / fragment\n */\nfunction canonicalizeSpecificEvidence(ev: string): string {\n const lower = ev.toLowerCase().replace(/\\s+/g, ' ').trim();\n // URL: strip scheme, query, fragment, trailing slash so a bare URL and a prose-embedded\n // citation of the same URL canonicalize identically.\n const urlMatch = lower.match(/https?:\\/\\/([^\\s)\\]>\"']+)/i);\n if (urlMatch) {\n const stripped = urlMatch[1].replace(/[#?].*$/, '').replace(/\\/+$/, '');\n return `url:${stripped}`;\n }\n // file:line — take the LAST path segment (basename) + line number, separator-agnostic.\n const fileLine = lower.match(/([\\w./\\\\-]+):(\\d+)/);\n if (fileLine) {\n const pathPart = fileLine[1].replace(/\\\\/g, '/');\n const basename = pathPart.split('/').filter(Boolean).pop() || pathPart;\n return `${basename}:${fileLine[2]}`;\n }\n return lower;\n}\n\nfunction normalizeEvidence(ev: string): string {\n // For specific (file:line / URL) evidence, use the canonical form so cross-format\n // citations of the same source compare equal; otherwise plain lowercase-collapse.\n return isSpecificEvidence(ev) ? canonicalizeSpecificEvidence(ev) : ev.toLowerCase().replace(/\\s+/g, ' ').trim();\n}\n\ninterface ClusterAccumulator {\n members: MagiClusterMember[];\n tokens: Set<string>;\n specificEvidence: Set<string>;\n}\n\n/**\n * Decide, from a replica's `read_chat` payload, whether it is wedged on an approval\n * prompt that MAGI collect should auto-approve. True when the live session reports an\n * approval/choice status OR carries an active modal — the states in which a readonly\n * MAGI replica sits blocked instead of producing its answer. Pure — unit-testable on\n * synthetic read_chat payloads. See nudgeWedgedReplica for why approving is safe here.\n */\nexport function magiReadIndicatesApprovalWedge(payload: unknown): boolean {\n const p = payload as { status?: unknown; activeModal?: unknown } | null | undefined;\n if (!p || typeof p !== 'object') return false;\n const status = String((p as any).status ?? '');\n if (status === 'waiting_approval' || status === 'waiting_choice') return true;\n return !!(p as any).activeModal;\n}\n\nfunction rankNeedsVerification(c: MagiClaimCluster): number {\n switch (c.category) {\n case 'contested': return 0;\n case 'dissent': return 1;\n case 'source_coupled': return 2;\n case 'singleton': return 3;\n default: return 4;\n }\n}\n\n/**\n * Synthesize an arbitrary set of common-schema responses into agreed / contested /\n * dissent / singleton / source_coupled clusters and the primary needs_verification\n * output. N-agnostic and diversity-weighted (distinct provider × machine × evidence),\n * NOT a vote. Pure — fully unit-testable on synthetic responses.\n */\nexport function synthesizeMagiResponses(\n responses: MagiSynthesizedResponse[],\n opts: { replicasExpected?: number; requireIndependentEvidence?: boolean } = {},\n): MagiSynthesis {\n const answered = responses.filter(r => r.source.ok && r.response);\n const requireEvidence = opts.requireIndependentEvidence !== false;\n\n // 1+2. Flatten claims and greedily cluster by lexical similarity / shared evidence.\n const clusters: ClusterAccumulator[] = [];\n for (const { source, response } of answered) {\n for (const claim of response.claims) {\n const tokens = claimTokenSet(claim.claim);\n const specific = new Set(claim.evidence.filter(isSpecificEvidence).map(normalizeEvidence));\n let best: ClusterAccumulator | null = null;\n let bestScore = 0;\n for (const cluster of clusters) {\n // Shared specific (file:line) evidence forces a merge regardless of wording.\n const evidenceMerge = [...specific].some(e => cluster.specificEvidence.has(e));\n const score = evidenceMerge ? 1 : jaccard(tokens, cluster.tokens);\n if (score > bestScore) { bestScore = score; best = cluster; }\n }\n const member: MagiClusterMember = {\n taskId: source.taskId,\n nodeId: source.nodeId,\n provider: source.provider,\n claim: claim.claim,\n stance: claim.stance,\n evidence: claim.evidence,\n confidence: claim.confidence,\n };\n if (best && bestScore >= MAGI_CLUSTER_JACCARD) {\n best.members.push(member);\n for (const t of tokens) best.tokens.add(t);\n for (const e of specific) best.specificEvidence.add(e);\n } else {\n clusters.push({ members: [member], tokens: new Set(tokens), specificEvidence: new Set(specific) });\n }\n }\n }\n\n // 3+4+5. Stance + independence per cluster, then categorize.\n const built: MagiClaimCluster[] = clusters.map(cluster => {\n const stance = { support: 0, oppose: 0, uncertain: 0 };\n for (const m of cluster.members) stance[m.stance]++;\n const distinctProviders = new Set(cluster.members.map(m => m.provider).filter(Boolean)).size;\n const distinctNodes = new Set(cluster.members.map(m => m.nodeId).filter(Boolean)).size;\n const distinctEvidence = new Set(cluster.members.flatMap(m => m.evidence.map(normalizeEvidence)).filter(Boolean)).size;\n const distinctAgents = new Set(cluster.members.map(m => m.taskId)).size;\n const maxConfidence = cluster.members.reduce((mx, m) => Math.max(mx, m.confidence), 0);\n const independenceScore = Math.max(distinctProviders, 1) * Math.max(distinctNodes, 1);\n const highIndependence = distinctProviders >= 2 && distinctNodes >= 2;\n const representative = cluster.members.map(m => m.claim).sort((a, b) => b.length - a.length)[0];\n\n const reasons: string[] = [];\n let category: MagiClaimCluster['category'];\n const hasSupport = stance.support > 0;\n const hasOppose = stance.oppose > 0;\n if (distinctAgents <= 1) {\n category = 'singleton';\n reasons.push('raised by exactly one agent — cannot be cross-checked');\n } else if (hasSupport && hasOppose) {\n if (stance.support > stance.oppose) {\n category = 'dissent';\n reasons.push(`minority opposition (${stance.oppose} oppose vs ${stance.support} support)`);\n } else {\n category = 'contested';\n reasons.push(`stances split (${stance.support} support / ${stance.oppose} oppose / ${stance.uncertain} uncertain)`);\n }\n } else if (highIndependence) {\n category = 'agreed';\n } else {\n category = 'source_coupled';\n reasons.push(`apparent agreement but low independence (${distinctProviders} provider(s) × ${distinctNodes} machine(s))`);\n }\n\n // require_independent_evidence: a high-impact agreement with no concrete\n // evidence is down-weighted into needs_verification regardless of category.\n let needsVerification = category === 'contested' || category === 'dissent'\n || category === 'singleton' || category === 'source_coupled';\n if (requireEvidence && distinctEvidence === 0 && maxConfidence >= 0.5 && category === 'agreed') {\n needsVerification = true;\n reasons.push('no independent file:line/source evidence for a high-confidence claim');\n }\n\n return {\n claim: representative,\n category,\n members: cluster.members,\n stance,\n distinctProviders,\n distinctNodes,\n distinctEvidence,\n independenceScore,\n needsVerification,\n reasons,\n };\n });\n\n const needsVerification = built\n .filter(c => c.needsVerification)\n .sort((a, b) => rankNeedsVerification(a) - rankNeedsVerification(b) || a.independenceScore - b.independenceScore);\n const agreed = built.filter(c => c.category === 'agreed' && !c.needsVerification);\n\n const distinctProviders = new Set(answered.map(r => r.source.provider).filter(Boolean)).size;\n const distinctNodes = new Set(answered.map(r => r.source.nodeId).filter(Boolean)).size;\n const replicasExpected = opts.replicasExpected ?? responses.length;\n const replicasAnswered = answered.length;\n\n let independenceBanner: string | null = null;\n if (replicasAnswered >= 1 && (distinctProviders < 2 || distinctNodes < 2)) {\n // The provider/machine spans are computed over the ANSWERING replicas only, so a\n // diverse fan-out whose replicas were mostly DROPPED during collection collapses to\n // \"1 provider / 1 machine\" — a collection-reliability failure, not a low-diversity\n // panel. Distinguish the two so the reader is pointed at the right cause: when replica\n // loss dominates (missing ≥ answered and something was actually lost), name the loss\n // and the dropped count instead of implying the panel itself was mono-source.\n const replicasMissing = Math.max(0, replicasExpected - replicasAnswered);\n const lossDominated = replicasMissing > 0 && replicasMissing >= replicasAnswered;\n if (lossDominated) {\n independenceBanner = `independence not achieved — only ${replicasAnswered} of ${replicasExpected} replica(s) answered (${replicasMissing} missing/dropped), collapsing the answering set to ${distinctProviders} provider(s) and ${distinctNodes} machine(s). This is a replica-loss/collection failure, not a low-diversity panel — inspect the dropped replicas (stale/unparseable/no-session) before re-reading the diversity spans. Agreements are routed to needs_verification.`;\n } else {\n independenceBanner = `independence not achieved — the answering replicas span ${distinctProviders} provider(s) and ${distinctNodes} machine(s); their agreements are source-coupled and routed to needs_verification.`;\n }\n }\n\n const openQuestions = [...new Set(answered.flatMap(r => r.response.open_questions))];\n const gitSkew = computeMagiGitSkew(answered);\n\n return {\n replicasExpected,\n replicasAnswered,\n replicasMissing: Math.max(0, replicasExpected - replicasAnswered),\n distinctProviders,\n distinctNodes,\n independenceBanner,\n clusters: built,\n needsVerification,\n agreed,\n openQuestions,\n replicas: responses.map(r => r.source),\n gitSkew,\n };\n}\n\n/**\n * deltaA — cross-replica git skew. The answering replicas may have run on nodes at\n * different branches or with local divergence (ahead/behind). When they do, the panel\n * was NOT all looking at the same code, so file:line evidence and \"agreement\" are\n * git-skewed and should be read with that caveat. Pure over the answering replicas'\n * captured git refs (source.git); refs are best-effort, so a replica with no known\n * branch simply does not contribute one.\n */\nexport function computeMagiGitSkew(answered: MagiSynthesizedResponse[]): MagiGitSkew {\n const branches = new Set<string>();\n let divergentReplicas = 0;\n for (const { source } of answered) {\n const git = source.git;\n if (!git) continue;\n const branch = typeof git.branch === 'string' && git.branch.trim() ? git.branch.trim() : undefined;\n if (branch) branches.add(branch);\n if ((git.ahead ?? 0) > 0 || (git.behind ?? 0) > 0) divergentReplicas++;\n }\n const branchList = [...branches].sort();\n const skewed = branchList.length > 1 || divergentReplicas > 0;\n return {\n skewed,\n distinctBranches: branchList.length,\n branches: branchList,\n divergentReplicas,\n ...(skewed ? {\n note: branchList.length > 1\n ? `replicas span ${branchList.length} branches (${branchList.join(', ')}) — evidence compares different code; treat agreement with caution.`\n : `${divergentReplicas} replica(s) diverge from upstream (ahead/behind) — not all replicas are on identical code.`,\n } : {}),\n };\n}\n\n// ─── Fan-out planning (pure) ────────────────────\n\nexport interface MagiReplicaPlan {\n slotIndex: number;\n provider: string;\n /** Resolved concrete node id (pinned slot), else undefined (tag-routed). */\n targetNodeId?: string;\n capabilityTags: string[];\n /** Tags the enqueued task hard-filters on: ['provider=<p>', ...capabilityTags]. */\n requiredTags: string[];\n /** MAGI-KIND-PANEL model axis: model override forwarded to the replica's launch (initialModel). */\n model?: string;\n}\n\nexport interface MagiUnavailableSlot {\n slotIndex: number;\n provider: string;\n nodeId?: string;\n capabilityTags: string[];\n reason: string;\n}\n\n/** A slot excluded because every candidate node's health is not launch-ready. */\nexport interface MagiUnhealthySlot {\n slotIndex: number;\n provider: string;\n nodeId?: string;\n capabilityTags: string[];\n /** The resolved health that made the slot unhealthy (e.g. 'degraded', 'offline'). */\n health: string;\n reason: string;\n}\n\n/** Per-slot resolution detail (for the git-stale exclusion + the review response surface). */\nexport interface MagiSlotResolution {\n slotIndex: number;\n provider: string;\n nodeId?: string;\n capabilityTags: string[];\n /** Resolves to ≥1 live node (pinned present, or a tag match). */\n available: boolean;\n /** Representative resolved node HEAD commit (best-effort; absent when unknown). */\n headCommit?: string;\n /** True when available AND every candidate node's known HEAD differs from referenceCommit. */\n gitStale: boolean;\n /** True when available but NO candidate node's health is launch-ready (degraded/offline). */\n unhealthy: boolean;\n /** The resolved health of the (representative) candidate node — surfaced for diagnosis. */\n health?: string;\n /** Excluded from the fan-out (unavailable, unhealthy, or git-stale and not include_stale). */\n excluded: boolean;\n reason?: string;\n}\n\nexport interface MagiFanoutPlan {\n replicas: MagiReplicaPlan[];\n totalRequested: number;\n totalAfterCap: number;\n droppedReplicas: number;\n distinctTargets: number;\n distinctProviders: number;\n distinctNodeTargets: number;\n enoughTargets: boolean;\n coupled: boolean;\n unavailableSlots: MagiUnavailableSlot[];\n /** Slots excluded because every candidate node's health is not launch-ready\n * (degraded / offline). Without this gate the replica would be assigned to a node\n * isLaunchableNode refuses, so it parks in `pending` forever — the infinite-wait defect. */\n unhealthySlots: MagiUnhealthySlot[];\n /** The commit the panel is being resolved against (coordinator HEAD); undefined when unknown. */\n referenceCommit?: string;\n /** Per-slot resolution detail, aligned to the kind-panel slot order. */\n slotResolutions: MagiSlotResolution[];\n /** Slots excluded because they are git-stale (different HEAD) and include_stale was not set. */\n staleSlots: MagiSlotResolution[];\n /** Git-stale slots that were nonetheless INCLUDED because include_stale=true (warning surface). */\n includedStaleSlots: MagiSlotResolution[];\n}\n\nfunction replicaCountFor(slot: MagiSlot, defaultN: number | undefined, globalN?: number): number {\n const n = slot.n ?? defaultN ?? globalN ?? 1;\n return Math.max(1, Math.floor(n));\n}\n\n/** Best-effort HEAD commit sha off a live node's git status (GitRepoStatus.headCommit). */\nfunction nodeHeadCommit(node: any): string | undefined {\n const h = node?.git?.headCommit;\n return typeof h === 'string' && h.trim() ? h.trim() : undefined;\n}\n\n/**\n * Canonical, order-independent key of a node's submodule gitlinks\n * (GitSubmoduleStatus[] on node.git.submodules — path + commit). Two nodes on the\n * same root HEAD but different submodule pointers (the oss/adhdev-providers case,\n * where the submodule carries the actual fix code) must NOT be treated as the same\n * base. Returns undefined when the node carries NO submodule telemetry at all\n * (missing / non-array / empty) — so the caller only compares submodule keys when\n * BOTH sides advertise submodules, and a node without submodule telemetry is never\n * silently excluded (mirrors the missing-HEAD \"can't prove → fresh\" rule). An empty\n * array is telemetry-absent (no submodules reported), NOT \"a repo with zero\n * submodules\", so it too yields undefined and falls back to root-HEAD-only compare.\n */\nfunction nodeSubmoduleKey(node: any): string | undefined {\n const subs = node?.git?.submodules;\n if (!Array.isArray(subs) || subs.length === 0) return undefined;\n const parts = subs\n .map((s: any) => {\n const path = typeof s?.path === 'string' ? s.path.trim() : '';\n const commit = typeof s?.commit === 'string' ? s.commit.trim() : '';\n return path && commit ? `${path}@${commit}` : undefined;\n })\n .filter((p: string | undefined): p is string => !!p)\n .sort((a: string, b: string) => a.localeCompare(b));\n return parts.length > 0 ? parts.join(',') : undefined;\n}\n\n/**\n * Whether a candidate node shares the same base as the coordinator reference.\n * Root HEAD must match. Submodule gitlinks are additionally compared ONLY when the\n * reference AND the candidate both carry submodule telemetry — if either side lacks\n * it, we fall back to root-HEAD-only (the pre-fingerprint behavior), so telemetry\n * absence never causes a silent exclusion. A candidate with no known HEAD can't be\n * proven stale and is treated as fresh by the caller (this helper is only consulted\n * once the candidate HEAD is known to match the reference HEAD).\n */\nfunction candidateMatchesReferenceBase(\n candidateHead: string,\n candidateSubKey: string | undefined,\n referenceCommit: string,\n referenceSubKey: string | undefined,\n): boolean {\n if (candidateHead !== referenceCommit) return false;\n // Only diff submodule gitlinks when BOTH sides advertise them.\n if (referenceSubKey !== undefined && candidateSubKey !== undefined) {\n return candidateSubKey === referenceSubKey;\n }\n return true;\n}\n\n/**\n * Fix B fallback: a node's drift from its OWN upstream (GitCompactSummary.behind/ahead).\n * Used only when no coordinator reference commit is known — a node that reports it is\n * behind/ahead of its upstream is provably on different code than the panel baseline even\n * though we cannot diff explicit HEADs. Returns {behind:0,ahead:0} when the node carries no\n * drift telemetry, so a node with no counters is never proven stale (mirrors the\n * missing-HEAD \"can't prove → fresh\" rule).\n */\nfunction nodeGitDrift(node: any): { behind: number; ahead: number } {\n const git = node?.git;\n const behind = git && typeof git.behind === 'number' && Number.isFinite(git.behind) ? Math.max(0, git.behind) : 0;\n const ahead = git && typeof git.ahead === 'number' && Number.isFinite(git.ahead) ? Math.max(0, git.ahead) : 0;\n return { behind, ahead };\n}\nfunction nodeHasGitDrift(node: any): boolean {\n const { behind, ahead } = nodeGitDrift(node);\n return behind > 0 || ahead > 0;\n}\n\n/**\n * Resolve a kind-panel's slots against the live mesh nodes into a concrete fan-out\n * plan: expand each available slot to its replica count, clamp the total to the guard\n * cap (drop logged, never silent), assess (node, provider) target diversity, and\n * flag a panel that collapses to a single provider/machine. Pure.\n */\nexport function buildMagiFanoutPlan(\n slots: MagiSlot[],\n nodes: LocalMeshNodeEntry[],\n opts: { n?: number; defaultN?: number; maxReplicas?: number; referenceCommit?: string; referenceSubmoduleKey?: string; includeStale?: boolean } = {},\n): MagiFanoutPlan {\n const cap = Math.max(1, Math.floor(opts.maxReplicas ?? MAGI_MAX_REPLICAS));\n const slotList = Array.isArray(slots) ? slots : [];\n const defaultN = opts.defaultN;\n const referenceCommit = typeof opts.referenceCommit === 'string' && opts.referenceCommit.trim() ? opts.referenceCommit.trim() : undefined;\n const referenceSubmoduleKey = typeof opts.referenceSubmoduleKey === 'string' && opts.referenceSubmoduleKey.trim() ? opts.referenceSubmoduleKey.trim() : undefined;\n const includeStale = opts.includeStale === true;\n const replicas: MagiReplicaPlan[] = [];\n const unavailableSlots: MagiUnavailableSlot[] = [];\n const unhealthySlots: MagiUnhealthySlot[] = [];\n const slotResolutions: MagiSlotResolution[] = [];\n const targetKeys = new Set<string>();\n const providerSet = new Set<string>();\n const nodeTargetSet = new Set<string>();\n let totalRequested = 0;\n\n slotList.forEach((slot, slotIndex) => {\n const provider = slot.provider;\n const model = typeof slot.model === 'string' && slot.model.trim() ? slot.model.trim() : undefined;\n const capabilityTags = normalizeMeshCapabilityTags(slot.capabilityTags);\n const requiredTags = normalizeMeshCapabilityTags([`provider=${provider}`, ...capabilityTags]);\n const count = replicaCountFor(slot, defaultN, opts.n);\n\n // Resolve availability against the mesh, and gather the candidate node(s) so we\n // can assess git staleness against the reference commit.\n let targetNodeId: string | undefined;\n let candidateNodes: any[] = [];\n if (slot.nodeId) {\n const node = nodes.find(n => meshNodeIdMatches(n as any, slot.nodeId!));\n if (node) { targetNodeId = (node as any).id; candidateNodes = [node]; }\n } else {\n // Match against each node's OWN advertised tags (provider derived from its\n // policy.providerPriority), NOT a provider we inject — passing `provider`\n // here would synthesize a provider= tag and make the filter always pass.\n // Mirrors the queue's availability check (mesh-tools-queue.ts).\n candidateNodes = nodes.filter(n => nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(n)));\n }\n const available = candidateNodes.length > 0;\n\n if (!available) {\n unavailableSlots.push({\n slotIndex,\n provider,\n nodeId: slot.nodeId,\n capabilityTags,\n reason: slot.nodeId\n ? `pinned node '${slot.nodeId}' is not a member of this mesh`\n : `no mesh node satisfies required tags [${requiredTags.join(', ')}]`,\n });\n slotResolutions.push({ slotIndex, provider, nodeId: slot.nodeId, capabilityTags, available: false, gitStale: false, unhealthy: false, excluded: true, reason: 'unavailable' });\n return;\n }\n\n // Health gate (PRIMARY FIX). A slot is available by capability tags, but a node\n // whose P2P/git health is not launch-ready (degraded / offline) is refused by the\n // daemon's auto-launch gate (isLaunchableNode → node_not_launch_ready): the replica\n // task would be assigned yet never launch, parking in `pending` forever with no\n // re-assignment or cancellation — the MAGI infinite-wait defect. So exclude such a\n // slot UP FRONT, exactly as the git-stale gate does. Prefer routing to a launch-ready\n // candidate when the pool is mixed; only exclude when EVERY candidate is unhealthy.\n // 'unknown'/'online' (and absent health) pass — we never exclude on missing telemetry\n // (mirrors the missing-HEAD \"can't prove → fresh\" rule), so a mesh whose nodes carry\n // no health telemetry behaves exactly as before this gate.\n const launchableCandidates = candidateNodes.filter(n => isMeshNodeHealthLaunchable(n));\n if (launchableCandidates.length === 0) {\n const health = resolveEffectiveMeshNodeHealth(candidateNodes[0]);\n unhealthySlots.push({\n slotIndex,\n provider,\n nodeId: targetNodeId ?? slot.nodeId,\n capabilityTags,\n health,\n reason: slot.nodeId\n ? `pinned node '${slot.nodeId}' health is '${health}' (not launch-ready)`\n : `no launch-ready node satisfies required tags [${requiredTags.join(', ')}] — all candidates are '${health}'`,\n });\n slotResolutions.push({\n slotIndex, provider, nodeId: targetNodeId ?? slot.nodeId, capabilityTags,\n available: true, gitStale: false, unhealthy: true, health, excluded: true,\n reason: `node_unhealthy: ${health}`,\n });\n return;\n }\n // Narrow the candidate pool to launch-ready nodes for all downstream resolution\n // (git-staleness, target pinning) so a mixed pool routes to a healthy node.\n if (slot.nodeId && launchableCandidates[0]) targetNodeId = (launchableCandidates[0] as any).id;\n candidateNodes = launchableCandidates;\n\n // Git staleness vs the reference commit. A slot is git-stale only when a\n // reference commit is known AND every candidate node with a known HEAD differs\n // from it (a node with no known HEAD can't be proven stale → treated as fresh,\n // so we never silently exclude on missing telemetry). Prefer routing to a fresh\n // candidate when one exists.\n let headCommit: string | undefined;\n let gitStale = false;\n if (referenceCommit) {\n const freshCandidate = candidateNodes.find(n => {\n const h = nodeHeadCommit(n);\n // No known HEAD → can't be proven stale → fresh (never exclude on missing\n // telemetry). Otherwise same-base iff root HEAD matches AND — when both the\n // reference and this candidate advertise submodules — the submodule gitlinks\n // match too. Two nodes on the same root HEAD but different oss/adhdev-providers\n // pointer are NOT the same base.\n if (!h) return true;\n return candidateMatchesReferenceBase(h, nodeSubmoduleKey(n), referenceCommit, referenceSubmoduleKey);\n });\n if (freshCandidate) {\n headCommit = nodeHeadCommit(freshCandidate);\n if (slot.nodeId) targetNodeId = (freshCandidate as any).id;\n gitStale = false;\n } else {\n headCommit = nodeHeadCommit(candidateNodes[0]);\n gitStale = true;\n }\n } else {\n // Fix B (stale-gate fallback): the coordinator carries no git HEAD telemetry, so\n // there is no reference commit to diff against. Previously this passed EVERY\n // candidate as fresh (gitStale stays false), so a node sitting behind/ahead of its\n // own upstream silently joined the panel on different code. When drift counters ARE\n // present, use them: prefer a candidate with zero drift; if none is clean but some\n // candidate reports drift, mark the slot git-stale (default-excluded like the\n // HEAD-diff path). A candidate with no drift telemetry at all is still treated as\n // fresh — we never exclude on missing data.\n const freshCandidate = candidateNodes.find(n => !nodeHasGitDrift(n));\n if (freshCandidate && candidateNodes.some(nodeHasGitDrift)) {\n // Mixed pool: route to the clean candidate, leave the slot fresh.\n headCommit = nodeHeadCommit(freshCandidate);\n if (slot.nodeId) targetNodeId = (freshCandidate as any).id;\n gitStale = false;\n } else if (!freshCandidate && candidateNodes.some(nodeHasGitDrift)) {\n // Every candidate reports drift → provably stale relative to its upstream.\n headCommit = nodeHeadCommit(candidateNodes[0]);\n gitStale = true;\n } else {\n // No drift telemetry on any candidate → cannot prove staleness; treat as fresh.\n headCommit = nodeHeadCommit(candidateNodes.find(n => nodeHeadCommit(n)) ?? candidateNodes[0]);\n }\n }\n\n const resolution: MagiSlotResolution = {\n slotIndex,\n provider,\n nodeId: targetNodeId ?? slot.nodeId,\n capabilityTags,\n available: true,\n ...(headCommit ? { headCommit } : {}),\n gitStale,\n // Candidate pool was already narrowed to launch-ready nodes above, so an\n // included slot is health-launchable by construction.\n unhealthy: false,\n health: resolveEffectiveMeshNodeHealth(candidateNodes[0]),\n excluded: false,\n };\n\n // Default-exclude a git-stale slot (it would investigate different code than\n // the reference); include_stale=true overrides but the caller surfaces a warning.\n if (gitStale && !includeStale) {\n resolution.excluded = true;\n if (referenceCommit) {\n // Same root HEAD but a differing submodule gitlink is the extended-fingerprint\n // case — name the submodule drift so the surface is not misleading.\n resolution.reason = headCommit && headCommit === referenceCommit\n ? `git-stale: node HEAD ${headCommit} matches reference but submodule gitlink(s) differ from reference base`\n : `git-stale: node HEAD ${headCommit ?? '(unknown)'} differs from reference ${referenceCommit}`;\n } else {\n resolution.reason = `git-stale: node reports drift from its upstream (behind/ahead) and no coordinator reference commit is known`;\n }\n slotResolutions.push(resolution);\n return;\n }\n\n totalRequested += count;\n const targetKey = targetNodeId ? `node:${targetNodeId}` : `tags:${[...requiredTags].sort().join(',')}`;\n targetKeys.add(`${targetKey}|${provider}`);\n providerSet.add(provider);\n nodeTargetSet.add(targetKey);\n slotResolutions.push(resolution);\n for (let i = 0; i < count; i++) {\n replicas.push({ slotIndex, provider, targetNodeId, capabilityTags, requiredTags, ...(model ? { model } : {}) });\n }\n });\n\n // Clamp to the guard cap (drop the tail; the caller logs the drop).\n const droppedReplicas = Math.max(0, replicas.length - cap);\n const capped = droppedReplicas > 0 ? replicas.slice(0, cap) : replicas;\n\n const distinctProviders = providerSet.size;\n const distinctNodeTargets = nodeTargetSet.size;\n // enoughTargets / coupled are computed over INCLUDED targets only — i.e. AFTER the\n // health gate AND the git-stale exclusion (unhealthy/stale slots never add to\n // targetKeys) — so the ≥2-independent-target guard re-checks post-exclusion and never\n // silently degrades to N=1.\n const staleSlots = slotResolutions.filter(m => m.gitStale && m.excluded);\n const includedStaleSlots = slotResolutions.filter(m => m.gitStale && !m.excluded);\n return {\n replicas: capped,\n totalRequested,\n totalAfterCap: capped.length,\n droppedReplicas,\n distinctTargets: targetKeys.size,\n distinctProviders,\n distinctNodeTargets,\n enoughTargets: targetKeys.size >= MAGI_MIN_TARGETS,\n coupled: distinctProviders < 2 || distinctNodeTargets < 2,\n unavailableSlots,\n unhealthySlots,\n ...(referenceCommit ? { referenceCommit } : {}),\n slotResolutions,\n staleSlots,\n includedStaleSlots,\n };\n}\n\n/**\n * The commit the panel is resolved against for git-staleness: the coordinator node's\n * HEAD (the code the investigation question originates from). Members on a different\n * HEAD would investigate different code and are excluded by default. Undefined when the\n * coordinator node carries no git HEAD telemetry → staleness is simply not computed.\n */\nfunction resolveMagiReferenceCommit(ctx: MeshContext): string | undefined {\n const node = resolveCoordinatorNode(ctx);\n return nodeHeadCommit(node);\n}\n\n/**\n * The coordinator node's submodule-gitlink key, paired with the reference commit above\n * to form the base fingerprint (root HEAD + sorted submodule gitlinks). Undefined when\n * the coordinator carries no submodule telemetry → submodule drift is simply not diffed\n * (root-HEAD-only comparison, the pre-fingerprint behavior).\n */\nfunction resolveMagiReferenceSubmoduleKey(ctx: MeshContext): string | undefined {\n const node = resolveCoordinatorNode(ctx);\n return nodeSubmoduleKey(node);\n}\n\n// ─── Task prompt (common-schema contract) ───────\n\nconst MAGI_CLAIM_AUDIT_CONTRACT = `When done, respond with ONLY a single JSON object (no prose, no code fence) matching this exact schema:\n{\n \"claims\": [ { \"claim\": \"string\", \"stance\": \"support | oppose | uncertain\", \"evidence\": [\"file:line or external source\"], \"confidence\": 0.0 } ],\n \"top_findings\": [\"string\"],\n \"open_questions\": [\"string\"]\n}\nEach claim MUST carry concrete evidence (file:line or a cited source) — unevidenced claims are flagged for re-verification. \"stance\" is your stance toward the claim being true. Do not invent agreement; report uncertainty honestly.`;\n\nconst MAGI_RCA_CONTRACT = `When done, respond with ONLY a single JSON object (no prose, no code fence) matching this exact schema:\n{\n \"rootCause\": \"string — the single underlying root cause\",\n \"failsAt\": \"file:line — the precise location the failure manifests\",\n \"mechanism\": \"string — how the root cause produces the observed symptom\",\n \"evidence\": [\"file:line or external source\"],\n \"fixDirection\": \"string — the direction a fix should take (do NOT write the fix)\",\n \"confidence\": 0.0\n}\n\"rootCause\" and \"mechanism\" are REQUIRED. \"evidence\" MUST be non-empty (concrete file:line or cited source) — an empty evidence array is rejected and re-requested. Report uncertainty honestly.`;\n\nconst MAGI_DESIGN_CONTRACT = `When done, respond with ONLY a single JSON object (no prose, no code fence) matching this exact schema:\n{\n \"recommendation\": \"string — the recommended approach\",\n \"rationale\": \"string — why this approach\",\n \"alternatives\": [\"string — approaches considered and not chosen\"],\n \"tradeoffs\": [\"string\"],\n \"risks\": [\"string\"],\n \"evidence\": [\"file:line or external source backing the recommendation\"],\n \"confidence\": 0.0\n}\n\"recommendation\" and \"rationale\" are REQUIRED. \"evidence\" MUST be non-empty — an empty evidence array is rejected and re-requested. Report uncertainty honestly.`;\n\nconst MAGI_FREEFORM_CONTRACT = `Answer the question in natural language. No JSON schema is required for this task — write your analysis directly. (Note: a freeform answer is cross-verified only weakly, because it is unstructured.)`;\n\n/** The single output contract injected for a kind — ONE schema, never two (B: no schema-on-schema conflict). */\nexport function magiOutputContractFor(kind: MagiTaskKind): string {\n switch (kind) {\n case 'rca': return MAGI_RCA_CONTRACT;\n case 'design': return MAGI_DESIGN_CONTRACT;\n case 'freeform': return MAGI_FREEFORM_CONTRACT;\n case 'claim_audit':\n default: return MAGI_CLAIM_AUDIT_CONTRACT;\n }\n}\n\n/**\n * Detect that the coordinator accidentally embedded an OUTPUT-FORMAT schema inside the\n * question text. MAGI injects exactly one output contract per kind (B); a second schema\n * in the question collides with it (the antigravity fusion symptom — the agent merges the\n * two and the result is unparseable). We do NOT strip or block it (the question may\n * legitimately quote a schema as the subject of investigation) — we SURFACE a warning so\n * the coordinator removes it. Pure.\n */\nexport function detectQuestionOutputSchemaConflict(question: string): string | null {\n const q = typeof question === 'string' ? question : '';\n if (!q.trim()) return null;\n const lower = q.toLowerCase();\n const signals = [\n 'respond with only',\n 'respond with a single json',\n 'single json object',\n 'output format',\n 'output schema',\n 'reply with only',\n '\"claims\"',\n '\"top_findings\"',\n 'matching this exact schema',\n ];\n const hit = signals.find(s => lower.includes(s));\n if (!hit) return null;\n return `The question text appears to embed an output-format schema (matched \"${hit}\"). MAGI already injects exactly one output contract for the selected task_kind, so a second schema in the question collides with it and replicas may fuse the two into unparseable output. Move any output-format instructions OUT of the question — describe only WHAT to investigate.`;\n}\n\nexport function buildMagiTaskPrompt(args: {\n question: string;\n target?: string;\n artifacts?: string[];\n mode?: MagiMode;\n taskKind?: MagiTaskKind;\n}): string {\n const kind = args.taskKind ?? DEFAULT_TASK_KIND;\n const parts: string[] = [];\n parts.push('You are one independent member of a multi-agent cross-verification quorum (MAGI). Several other agents on different machines/providers are answering the SAME question independently; your job is a rigorous, READ-ONLY investigation. Do NOT write, edit, commit, or push anything.');\n parts.push(`Task kind: ${kind}.`);\n if (args.mode) parts.push(`Investigation mode: ${args.mode}.`);\n parts.push(`\\n## Question\\n${args.question.trim()}`);\n if (args.target && args.target.trim()) parts.push(`\\n## Target to investigate\\n${args.target.trim()}`);\n if (Array.isArray(args.artifacts) && args.artifacts.length > 0) {\n parts.push(`\\n## Artifacts\\n${args.artifacts.map(a => String(a)).join('\\n\\n---\\n\\n')}`);\n }\n parts.push(`\\n## Output\\n${magiOutputContractFor(kind)}`);\n return parts.join('\\n');\n}\n\n// ─── Worker-output extraction (best-effort) ─────\n\n/**\n * Fix A (summary fallback): ordered list of candidate texts to attempt MAGI parsing on,\n * newest-first. The naive \"last assistant bubble content\" path misses two real shapes:\n * 1. A mid-turn EMPTY final bubble (the premature-collect symptom) — the parseable\n * answer lives in an EARLIER assistant bubble.\n * 2. antigravity-cli, which carries the turn's answer in a `summary` field while the\n * transcript bubble body is empty (_sameAsSummary) — reading the last bubble returns ''\n * and the real JSON answer is never seen.\n * We therefore gather every assistant bubble's content AND every summary-bearing field\n * (per-message summary/summaryMetadata, and the payload-level summary/finalSummary/\n * lastMessagePreview/text), newest-first, and let the caller parse the first that yields a\n * valid MAGI response. Pure; deduped; empties dropped.\n */\nexport function collectMagiCandidateTexts(payload: unknown): string[] {\n if (!payload || typeof payload !== 'object') return [];\n const p = payload as Record<string, any>;\n const out: string[] = [];\n const seen = new Set<string>();\n const push = (value: unknown): void => {\n const text = typeof value === 'string' ? value : '';\n const trimmed = text.trim();\n if (!trimmed || seen.has(trimmed)) return;\n seen.add(trimmed);\n out.push(text);\n };\n const messages = Array.isArray(p.messages) ? p.messages\n : Array.isArray(p.chat) ? p.chat\n : Array.isArray(p.transcript) ? p.transcript\n : [];\n // Walk assistant bubbles newest-first so a finished earlier turn is preferred over an\n // empty in-progress final bubble.\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const msg = messages[i];\n if (!msg || typeof msg !== 'object') continue;\n const role = String((msg as any).role || (msg as any).from || '').toLowerCase();\n if (role && role !== 'assistant' && role !== 'agent' && role !== 'model') continue;\n const content = (msg as any).content ?? (msg as any).text ?? (msg as any).message;\n if (typeof content === 'string') push(content);\n else if (Array.isArray(content)) {\n const joined = content\n .map((part: any) => (typeof part === 'string' ? part : (part && typeof part === 'object' && typeof part.text === 'string' ? part.text : '')))\n .join('');\n push(joined);\n }\n // Per-message summary carriers (antigravity _sameAsSummary case: body empty, answer here).\n push((msg as any).summary);\n push((msg as any).summaryMetadata?.summary);\n }\n // Payload-level summary carriers (compact read_chat lifts the final answer into `summary`).\n push(p.summary);\n push(p.finalSummary);\n push(p.lastMessagePreview);\n push(p.text);\n return out;\n}\n\n/** Parse the first MAGI candidate text that yields a valid response, newest-first. */\nexport function parseFirstMagiCandidate(payload: unknown): MagiAgentResponse | null {\n for (const candidate of collectMagiCandidateTexts(payload)) {\n const parsed = parseMagiResponse(candidate);\n if (parsed) return parsed;\n }\n return null;\n}\n\n/**\n * Fix-A-v2: make the summary-fallback actually fire on the collect read path.\n *\n * The collect path reads RAW daemon read_chat (no `compact: true`), and the v1 read-chat\n * contract (read-chat-contract.ts validateReadChatResultPayload / validateMessage) drops the\n * top-level and per-message `summary` carriers that {@link collectMagiCandidateTexts} harvests.\n * So for antigravity — whose final answer lives ONLY in `summary` while the transcript bubble\n * body is empty (_sameAsSummary) — every candidate is empty on the raw payload and the answer\n * is lost as `unparseable_output`. Fix A's harvesting was structurally inert there.\n *\n * Re-derive the summary locally by running the SAME {@link compactChatPayload} lift the daemon's\n * compact path uses (messageContent(finalAssistant) → `summary`), then parse candidates from\n * BOTH payloads:\n * - the raw payload FIRST — preserves the newest-bubble-first preference and the\n * premature-collect guard for providers (claude-cli etc.) that keep the JSON in the bubble\n * body, and never regresses to an older bubble just because compact lifted a newer one;\n * - the compacted payload as the FALLBACK — surfaces the lifted `summary` so empty-bubble\n * providers (antigravity) are finally recovered.\n * Candidates are deduped across both sources. Compact is best-effort: a throw leaves the raw\n * candidates intact.\n */\nexport function parseFirstMagiCandidateWithCompactFallback(\n payload: unknown,\n opts: { sessionId?: string | null } = {},\n): MagiAgentResponse | null {\n const rawCandidates = collectMagiCandidateTexts(payload);\n let compactCandidates: string[] = [];\n try {\n compactCandidates = collectMagiCandidateTexts(\n compactChatPayload(payload, { sessionId: opts.sessionId ?? null }),\n );\n } catch { /* compact lift is best-effort — raw candidates still apply */ }\n const seen = new Set<string>();\n for (const candidate of [...rawCandidates, ...compactCandidates]) {\n const trimmed = candidate.trim();\n if (!trimmed || seen.has(trimmed)) continue;\n seen.add(trimmed);\n const parsed = parseMagiResponse(candidate);\n if (parsed) return parsed;\n }\n return null;\n}\n\n/**\n * Fix A re-wait gate: a `completed` replica is NOT yet trustworthy for collection when its\n * terminal completion evidence is WEAK (the same insufficient/reviewRecommended/missing-\n * final-assistant signal the daemon shares across the live + ledger paths) OR a short-\n * generating suppressed completion (the early mid-turn bubble that the premature-collect bug\n * mistakes for the final answer). We look up the latest terminal ledger entry for the task —\n * the queue task row does not carry evidenceLevel/completionDiagnostic, but the ledger does\n * (see mesh-event-forwarding terminal payload). Best-effort: a missing/unreadable ledger\n * returns false so we never block collection on telemetry we cannot read.\n */\nfunction replicaCompletionIsWeak(meshId: string, taskId: string): boolean {\n try {\n const entries = readLedgerEntries(meshId, { kind: ['task_completed'], tail: 200 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i] as any;\n const payload = entry?.payload && typeof entry.payload === 'object' ? entry.payload as Record<string, unknown> : undefined;\n const entryTaskId = readString(payload?.taskId) || readString(entry?.taskId);\n if (!entryTaskId || entryTaskId !== taskId) continue;\n if (isWeakCompletionEvidence(payload)) return true;\n const diag = payload?.completionDiagnostic;\n if (diag && typeof diag === 'object' && !Array.isArray(diag)\n && readString((diag as Record<string, unknown>).reason) === 'short_generating_suppressed') {\n return true;\n }\n return false;\n }\n } catch { /* ledger unreadable — do not block collection */ }\n return false;\n}\n\n// ─── Handlers ───────────────────────────────────\n\n/**\n * Set the MAGI kind→panel slot binding for one task_kind (machine-local\n * ~/.adhdev/meshes.json `magiKindPanels`). This is the MCP surface for the daemon\n * `magi_kind_panel_set` command, which was not exposed to the coordinator before.\n *\n * IMPORTANT — kind-slot write is a WHOLESALE REPLACEMENT of the slot list for that\n * kind (a task_kind has exactly one binding; setMagiKindPanel always overwrites). So\n * this is NOT an additive upsert — the passed `slots` become the complete new set and\n * any prior slots for the kind are dropped. It therefore requires explicit user\n * approval before a write (present the current-vs-new slot lists first). Mirrors the\n * mesh_magi_panel_set write/dry-run precedent: defaults to dry-run (write=false).\n * Machine-local config — labeled distinct from the repo-committed .adhdev/* files.\n */\nexport async function meshMagiKindPanelSet(\n ctx: MeshContext,\n args: { task_kind?: string; kind?: string; slots?: unknown; write?: boolean },\n): Promise<string> {\n const kind = readString(args.task_kind) || readString(args.kind);\n if (!kind) return JSON.stringify({ success: false, error: 'task_kind required' });\n const write = args.write === true;\n try {\n // The current binding for this kind, so the coordinator can diff current-vs-new\n // before an overwrite (the write drops any slot not in the new list).\n const current: MagiSlot[] = getMagiKindPanel(kind) ?? [];\n if (!write) {\n // Dry-run: normalize + validate WITHOUT persisting (same normalizer as the\n // persisted write path, so preview and write agree on validation).\n const preview = normalizeMagiSlots(args.slots);\n return JSON.stringify({\n success: true,\n dryRun: true,\n taskKind: kind,\n scope: 'machine_local',\n replacement: true,\n currentSlots: current,\n slots: preview,\n note: 'Dry-run only — no file written. This is a WHOLESALE replacement of the kind\\'s slot list (machine-local ~/.adhdev/meshes.json); the currentSlots would be fully replaced. Re-run with write=true after explicit user approval.',\n }, null, 2);\n }\n const slots = setMagiKindPanel(kind, args.slots);\n return JSON.stringify({\n success: true,\n written: true,\n taskKind: kind,\n scope: 'machine_local',\n replacement: true,\n previousSlots: current,\n slots,\n nextAction: 'Verify with mesh_magi_kind_panel_list, then mesh_magi_review({ task_kind }) resolves this binding.',\n }, null, 2);\n } catch (e: any) {\n const message = e?.message || String(e);\n const code = message.includes('invalid_magi_kind_panel') ? 'invalid_magi_kind_panel' : undefined;\n return JSON.stringify({ success: false, ...(code ? { code } : {}), error: message });\n }\n}\n\n/**\n * List the configured MAGI kind→panel slot bindings (machine-local). Read-only —\n * the sibling of mesh_magi_panel_list for kind-slot bindings. Use to confirm what a\n * `task_kind` resolves to before mesh_magi_review, and to diff before an overwrite.\n */\nexport async function meshMagiKindPanelList(\n ctx: MeshContext,\n args: { task_kind?: string; kind?: string } = {},\n): Promise<string> {\n const only = readString(args.task_kind) || readString(args.kind);\n const all = listMagiKindPanels();\n if (only) {\n const slots = getMagiKindPanel(only);\n if (slots === undefined) {\n return JSON.stringify({\n success: false,\n code: 'magi_kind_not_configured',\n error: `task_kind '${only}' has no configured kind-panel binding`,\n configuredKinds: Object.keys(all),\n }, null, 2);\n }\n return JSON.stringify({ success: true, scope: 'machine_local', taskKind: only, slots }, null, 2);\n }\n return JSON.stringify({ success: true, scope: 'machine_local', kindPanels: all, configuredKinds: Object.keys(all) }, null, 2);\n}\n\n\n// MAGI-KIND-PANEL: the panel a mesh_magi_review fans out to is resolved SOLELY from the\n// user's explicitly configured kind-panel binding (magiKindPanels: task_kind → slots).\n// The former named-panel / inline-members / preset-auto-synthesis paths were REMOVED —\n// an unconfigured task_kind is a hard error (magi_kind_not_configured). See the panel\n// resolution block in meshMagiReview.\n\nexport async function meshMagiReview(\n ctx: MeshContext,\n args: {\n question?: string;\n target?: string;\n artifacts?: string[];\n n?: number;\n mode?: string;\n require_independent_evidence?: boolean;\n requireIndependentEvidence?: boolean;\n include_stale?: boolean;\n includeStale?: boolean;\n wait?: boolean;\n wait_timeout_ms?: number;\n waitTimeoutMs?: number;\n task_kind?: string;\n taskKind?: string;\n use_judge?: boolean;\n useJudge?: boolean;\n auto_cleanup?: boolean;\n autoCleanup?: boolean;\n },\n): Promise<string> {\n const question = readString(args.question);\n if (!question) return JSON.stringify({ success: false, error: 'question required' });\n\n // task_kind is REQUIRED — it is BOTH the output-schema selector AND the sole panel\n // resolution key (magiKindPanels: task_kind → slots). There is no named-panel /\n // inline-members / preset fallback, so an omitted or unrecognized task_kind is a hard\n // error rather than a normalize-to-default.\n const explicitTaskKind = args.task_kind ?? args.taskKind;\n if (typeof explicitTaskKind !== 'string' || !(VALID_TASK_KINDS as readonly string[]).includes(explicitTaskKind.trim().toLowerCase())) {\n return JSON.stringify({\n success: false,\n code: 'task_kind_required',\n error: 'task_kind is required and selects both the output schema and the configured kind-panel slots. Pass one of: claim_audit / rca / design / freeform.',\n validTaskKinds: VALID_TASK_KINDS,\n hint: 'Configure the kind-panel slots for this task_kind in mesh settings (magiKindPanels) or via mesh_magi_kind_panel_set, then call mesh_magi_review({ question, task_kind }).',\n }, null, 2);\n }\n // B: warn (do NOT block) if the coordinator embedded an output schema in the question —\n // it collides with the single kind contract MAGI injects and causes fusion/unparseable.\n const questionSchemaWarning = detectQuestionOutputSchemaConflict(question);\n // G: use_judge is an interface stub only — judge synthesis is not implemented; true\n // falls back to clustering with a warning. Default false.\n const useJudge = (args.use_judge ?? args.useJudge) === true;\n const judgeWarning = useJudge\n ? 'use_judge=true requested, but judge synthesis is not yet implemented — falling back to clustering synthesis.'\n : null;\n\n await refreshMeshFromDaemon(ctx);\n\n // Reference commit (coordinator HEAD) is read here, immediately after the mesh\n // refresh, so slot resolution pins fresh live nodes against the SAME baseline\n // buildMagiFanoutPlan uses for git-staleness. read-only — safe to hoist.\n const referenceCommit = resolveMagiReferenceCommit(ctx);\n // Extend the base fingerprint with the coordinator's submodule gitlinks so two nodes\n // on the SAME root HEAD but a different oss/adhdev-providers pointer are not treated\n // as the same base (that submodule carries the actual fix code). Undefined when the\n // coordinator has no submodule telemetry → root-HEAD-only comparison (pre-fingerprint).\n const referenceSubmoduleKey = resolveMagiReferenceSubmoduleKey(ctx);\n\n // 1. Resolve the panel SOLELY from the user's configured kind→slots binding\n // (magiKindPanels). There is NO named-panel, inline-members, or preset auto-synthesis\n // path — an unconfigured kind is a hard error so the user must explicitly bind\n // (machine + provider + model) slots in mesh settings. The final output kind is the\n // task_kind itself (validated above); there is no panel-level defaultKind to fill in.\n const taskKind = normalizeMagiTaskKind(explicitTaskKind);\n const panelName = `(kind:${taskKind})`;\n const slots = getMagiKindPanel(taskKind);\n if (!slots || slots.length === 0) {\n return JSON.stringify({\n success: false,\n code: 'magi_kind_not_configured',\n error: `No panel slots are configured for this task_kind in mesh settings. Add at least one (machine + provider + model) slot in settings — task_kind '${taskKind}' has no configured kind-panel.`,\n taskKind,\n configuredKinds: Object.keys(listMagiKindPanels()),\n hint: 'Configure this kind in mesh settings (MagiKindPanelEditor), or set it with mesh_magi_kind_panel_set, then retry.',\n }, null, 2);\n }\n // Slots are already normalized at write time (setMagiKindPanel → normalizeMagiSlots),\n // but re-normalize here so a bad stored slot surfaces a clear error before dispatch.\n let planSlots: MagiSlot[];\n try {\n planSlots = normalizeMagiSlots(slots);\n } catch (e: any) {\n return JSON.stringify({\n success: false,\n code: 'invalid_magi_kind_panel',\n error: `configured kind-panel for '${taskKind}' is invalid: ${e?.message || String(e)}`,\n taskKind,\n hint: 'Re-save the kind-panel slots in mesh settings — each slot needs a provider; nodeId / model are optional.',\n }, null, 2);\n }\n\n // 2. Plan the fan-out. Git-stale slots (node HEAD differs from the coordinator's\n // reference commit) are EXCLUDED by default — they would investigate different code;\n // include_stale=true keeps them (with a warning). The ≥2-target guard below is\n // re-checked AFTER this exclusion, so it never silently degrades to N=1.\n const includeStale = (args.include_stale ?? args.includeStale) === true;\n const plan = buildMagiFanoutPlan(planSlots, ctx.mesh.nodes, { n: args.n, referenceCommit, referenceSubmoduleKey, includeStale });\n if (!plan.enoughTargets) {\n const droppedByStale = plan.staleSlots.length > 0;\n const droppedByHealth = plan.unhealthySlots.length > 0;\n // Health exclusion is the PRIMARY new failure cause: a degraded/offline node was\n // excluded up front (it would have parked in `pending` forever). Surface it as a\n // distinct code so the coordinator knows the panel is under-quorum because a node\n // is unhealthy — NOT because the panel is mis-configured — and never silently\n // degrades to N=1.\n const code = droppedByHealth\n ? 'magi_insufficient_targets_after_health_exclusion'\n : droppedByStale\n ? 'magi_insufficient_targets_after_stale_exclusion'\n : 'magi_insufficient_targets';\n const error = droppedByHealth\n ? `Kind-panel '${panelName}' resolves to only ${plan.distinctTargets} independent (node, provider) target(s) AFTER excluding ${plan.unhealthySlots.length} unhealthy slot(s) (${plan.unhealthySlots.map(s => `${s.nodeId ?? `[${s.provider}]`}=${s.health}`).join(', ')}); MAGI requires ≥${MAGI_MIN_TARGETS} and never silently degrades to N=1. A degraded node would leave its replica parked in 'pending' forever, so it is excluded rather than dispatched.`\n : droppedByStale\n ? `Kind-panel '${panelName}' resolves to only ${plan.distinctTargets} independent (node, provider) target(s) AFTER excluding ${plan.staleSlots.length} git-stale slot(s) (HEAD differs from reference ${referenceCommit ?? '(unknown)'}); MAGI requires ≥${MAGI_MIN_TARGETS} and never silently degrades to N=1.`\n : `Kind-panel '${panelName}' resolves to ${plan.distinctTargets} available (node, provider) target(s); MAGI requires ≥${MAGI_MIN_TARGETS} and never silently degrades to N=1.`;\n const hint = droppedByHealth\n ? 'Bring the degraded node(s) back online (check P2P/git health via mesh_status), or configure additional healthy (machine + provider) slots for this kind-panel, then retry.'\n : droppedByStale\n ? 'Bring the stale node(s) to the reference commit, or pass include_stale=true to mesh_magi_review to fan out to them anyway (results will be git-skewed).'\n : 'Fix the kind-panel slots with mesh_magi_kind_panel_set (or in mesh settings), and use mesh_status to confirm nodes/providers are online.';\n return JSON.stringify({\n success: false,\n code,\n error,\n ...(referenceCommit ? { referenceCommit } : {}),\n unavailableSlots: plan.unavailableSlots,\n ...(droppedByHealth ? { unhealthySlots: plan.unhealthySlots } : {}),\n ...(droppedByStale ? { staleSlots: plan.staleSlots } : {}),\n hint,\n }, null, 2);\n }\n\n const mode = readString(args.mode) as MagiMode | '';\n const requireIndependentEvidence = (args.require_independent_evidence ?? args.requireIndependentEvidence) !== false;\n const wait = args.wait !== false;\n const waitTimeoutMs = Math.min(MAGI_MAX_WAIT_MS, Math.max(MAGI_POLL_INTERVAL_MS, Number(args.wait_timeout_ms ?? args.waitTimeoutMs) || MAGI_DEFAULT_WAIT_MS));\n\n // 3. Mission container + shared consensus group id.\n const consensusGroupId = `magi_${randomUUID().replace(/-/g, '')}`;\n const titleQ = question.length > 80 ? `${question.slice(0, 77)}...` : question;\n const mission = upsertMeshMission(ctx.mesh.id, {\n title: `MAGI: ${titleQ}`,\n goal: `Cross-verify (read-only) across panel '${panelName}': ${question}${args.target ? `\\nTarget: ${args.target}` : ''}`,\n // Tag provenance so the completed inline mission is bounded out of the default\n // mesh_mission_list (these accumulate one-per-run and auto-close on collection).\n source: 'magi',\n });\n\n // 4. Enqueue one read-only task per replica, all sharing the consensus group id.\n const prompt = buildMagiTaskPrompt({ question, target: args.target, artifacts: args.artifacts, mode: (mode || undefined) as MagiMode | undefined, taskKind });\n const replicaRecords: Array<{ taskId: string; provider: string; targetNodeId?: string; requiredTags: string[] }> = [];\n for (const replica of plan.replicas) {\n try {\n const task = enqueueTask(ctx.mesh.id, prompt, {\n readonly: true,\n taskMode: 'live_debug_readonly',\n requiredTags: replica.requiredTags,\n missionId: mission.id,\n consensusGroupId,\n ...(replica.targetNodeId ? { targetNodeId: replica.targetNodeId } : {}),\n ...(replica.model ? { model: replica.model } : {}),\n ...(ctx.coordinatorSessionId ? { sourceCoordinatorSessionId: ctx.coordinatorSessionId } : {}),\n });\n replicaRecords.push({ taskId: task.id, provider: replica.provider, targetNodeId: replica.targetNodeId, requiredTags: replica.requiredTags });\n } catch (e: any) {\n // A single replica enqueue failure must not abort the quorum — record and continue.\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'magi_replica_enqueue_failed' as any,\n payload: { consensusGroupId, missionId: mission.id, provider: replica.provider, error: e?.message || String(e) },\n });\n } catch { /* ledger write is best-effort */ }\n }\n }\n if (replicaRecords.length < MAGI_MIN_TARGETS) {\n return JSON.stringify({ success: false, code: 'magi_enqueue_failed', error: 'fewer than 2 replicas enqueued successfully', consensusGroupId, missionId: mission.id });\n }\n\n // deltaE: persist the fan-out so the group is visible in mesh_status (running) and\n // survives a coordinator restart even before any synthesis is collected.\n persistMagiDispatched(ctx, {\n consensusGroupId,\n missionId: mission.id,\n panel: panelName,\n question,\n replicaCount: replicaRecords.length,\n taskKind,\n });\n\n // 5. Trigger queue pickup. This is the SOLE dispatch path for every replica,\n // local AND remote. triggerMeshQueue (on the coordinator's local IPC) drains\n // each pending replica task — including ones pinned to a remote node — to its\n // target: a remote idle session is claimed and send_chat'd over P2P, and a\n // pinned remote target with no idle session is auto-launched, then claims on\n // ready. A previously-eager P2P push to remote replicas (eagerlyDispatchRemote-\n // Replicas) was a SECOND, redundant send of the same prompt: the queue path\n // already delivers the task, so both writes raced and each bypassed the\n // recent-duplicate-send guard — the cross-machine MAGI double-send. Removed so\n // every replica is dispatched exactly once via the queue.\n const queueTrigger = await triggerMeshQueueAndReport(ctx);\n\n const baseResult = {\n success: true,\n consensusGroupId,\n missionId: mission.id,\n panel: panelName,\n taskKind,\n ...(questionSchemaWarning ? { questionSchemaWarning } : {}),\n ...(judgeWarning ? { judgeWarning } : {}),\n question,\n replicaCount: replicaRecords.length,\n replicas: replicaRecords.map(r => ({ taskId: r.taskId, provider: r.provider, targetNodeId: r.targetNodeId })),\n independence: {\n distinctProviders: plan.distinctProviders,\n distinctMachines: plan.distinctNodeTargets,\n coupled: plan.coupled,\n ...(plan.coupled ? { banner: 'Panel collapsed to a single provider or machine — agreements will be flagged source-coupled.' } : {}),\n },\n ...(plan.referenceCommit ? { referenceCommit: plan.referenceCommit } : {}),\n // Surface health-gate exclusions even when quorum still held: these replicas were\n // NEVER dispatched (their node is degraded/offline and would park in `pending`\n // forever), so the coordinator/collect must know not to wait on them.\n ...(plan.unhealthySlots.length > 0 ? {\n excludedSlots: plan.unhealthySlots,\n healthExcludedWarning: `${plan.unhealthySlots.length} slot(s) were excluded from this fan-out because their node health is not launch-ready (${plan.unhealthySlots.map(s => `${s.nodeId ?? `[${s.provider}]`}=${s.health}`).join(', ')}) — those replicas were NOT dispatched. Bring the node(s) online (mesh_status) to include them.`,\n } : {}),\n // Surface git-stale handling: which slots were excluded (default), or included\n // despite being stale (include_stale=true) — the latter makes results git-skewed.\n ...(plan.staleSlots.length > 0 ? {\n gitStaleExcluded: plan.staleSlots,\n gitStaleWarning: `${plan.staleSlots.length} git-stale slot(s) (HEAD ≠ reference ${plan.referenceCommit ?? '(unknown)'}) were excluded from this fan-out; pass include_stale=true to include them.`,\n } : {}),\n ...(plan.includedStaleSlots.length > 0 ? {\n gitStaleIncluded: plan.includedStaleSlots,\n gitStaleWarning: `include_stale=true: ${plan.includedStaleSlots.length} git-stale slot(s) (HEAD ≠ reference ${plan.referenceCommit ?? '(unknown)'}) were INCLUDED — their evidence compares different code, so synthesis will be git-skewed.`,\n } : {}),\n ...(plan.droppedReplicas > 0 ? {\n cappedReplicas: plan.droppedReplicas,\n cappedNote: `Total replicas requested (${plan.totalRequested}) exceeded the guard cap (${MAGI_MAX_REPLICAS}); ${plan.droppedReplicas} dropped (logged, not silent).`,\n } : {}),\n costNote: `MAGI dispatched ${replicaRecords.length} read-only sessions — token spend scales with the replica count.`,\n queueTrigger,\n };\n\n if (!wait) {\n return JSON.stringify({\n ...baseResult,\n waited: false,\n pollWith: { tool: 'mesh_magi_collect', args: { consensus_group_id: consensusGroupId } },\n nextAction: `Replicas are running. Drive off mission completion / pendingCoordinatorEvents rather than polling chat, then collect + synthesize once with mesh_magi_collect({ consensus_group_id: '${consensusGroupId}' }).`,\n }, null, 2);\n }\n\n // 6. Collect by consensus group id (bounded), then synthesize.\n const collected = await collectMagiResponses(ctx, {\n replicaTaskIds: replicaRecords.map(r => r.taskId),\n timeoutMs: waitTimeoutMs,\n taskKind,\n });\n const synthesis = synthesizeMagiResponses(collected.responses, {\n replicasExpected: replicaRecords.length,\n requireIndependentEvidence,\n });\n // mesh_magi_review has no rawAnswer contract — strip the per-replica raw text from\n // both the persisted ledger entry and the returned synthesis. rawAnswer is surfaced\n // only via mesh_magi_collect verbose.\n const synthesisNoRaw = stripRawAnswers(synthesis);\n // freeform contributes no structured claims, so cross-verification is weak — banner it.\n const freeformBanner = taskKind === 'freeform'\n ? 'task_kind=freeform: answers are unstructured natural language; cross-verification is WEAK (no claim clustering / independence scoring). Treat the collected answers as parallel opinions, not a verified consensus.'\n : null;\n\n // deltaE: persist the synthesis (retrievable by consensusGroupId; folds into mesh_status).\n persistMagiSynthesis(ctx, {\n consensusGroupId,\n missionId: mission.id,\n panel: panelName,\n question,\n staleReplicas: collected.staleCount,\n synthesis: synthesisNoRaw,\n });\n // FIX#3: this inline review owns `mission` — auto-close it once all replicas are terminal.\n closeMagiMissionIfTerminal(ctx, mission.id, collected.terminal);\n\n // Post-review auto-cleanup (default ON): stop+delete ONLY the worker sessions this\n // fan-out auto-launched, gated terminal. Re-read the replica tasks from the live queue\n // so we see their final assignedSessionId / autoLaunch.sessionId. Best-effort.\n const cleanupMode = resolveMagiAutoCleanupMode(ctx, args.auto_cleanup ?? args.autoCleanup);\n const cleanupReplicaTasks = findMagiReplicaTasks(getQueue(ctx.mesh.id), consensusGroupId);\n const cleanup = await cleanupMagiAutoLaunchedSessions(ctx, {\n replicaTasks: cleanupReplicaTasks,\n terminal: collected.terminal,\n mode: cleanupMode,\n });\n\n return JSON.stringify({\n ...baseResult,\n waited: true,\n ...(cleanup ? { sessionCleanup: { mode: cleanupMode, cleanedSessionCount: cleanup.cleanedSessionCount, perNode: cleanup.perNode } } : {}),\n collection: {\n terminal: collected.terminal,\n timedOut: collected.timedOut,\n answered: synthesis.replicasAnswered,\n missing: synthesis.replicasMissing,\n staleReplicas: collected.staleCount,\n ...(collected.staleCount > 0 ? { staleNote: `${collected.staleCount} replica(s) were detected STALE — assigned to a node/session no longer present in the live mesh; collection stopped early rather than waiting out the timeout.` } : {}),\n ...(collected.retriedCount > 0 ? { retriedReplicas: collected.retriedCount, retryNote: `${collected.retriedCount} replica(s) failed the ${taskKind} schema and were sent one delta re-request for a corrected single-JSON answer.` } : {}),\n ...(synthesis.replicasMissing > 0 ? { missingNote: `Partial synthesis — ${synthesis.replicasMissing} of ${replicaRecords.length} replicas did not return a parseable response (timed out / failed / unparseable / schema-invalid / stale).` } : {}),\n },\n ...(freeformBanner ? { freeformBanner } : {}),\n synthesis: synthesisNoRaw,\n }, null, 2);\n}\n\n/**\n * Poll-by-group collection (featureC). Re-collect + synthesize a previously\n * dispatched MAGI fan-out by its consensus group id — the async companion to a\n * wait=false mesh_magi_review. Rediscovers the replica tasks from the queue, then\n * reuses the SAME collectMagiResponses + synthesizeMagiResponses code paths as the\n * wait=true review (no duplicated collection/synthesis). Tolerates partial/stale\n * replicas: when wait=false it snapshots whatever is terminal right now.\n */\nexport async function meshMagiCollect(\n ctx: MeshContext,\n args: {\n consensus_group_id?: string;\n consensusGroupId?: string;\n require_independent_evidence?: boolean;\n requireIndependentEvidence?: boolean;\n wait?: boolean;\n wait_timeout_ms?: number;\n waitTimeoutMs?: number;\n task_kind?: string;\n taskKind?: string;\n auto_cleanup?: boolean;\n autoCleanup?: boolean;\n verbose?: boolean;\n },\n): Promise<string> {\n const consensusGroupId = readString(args.consensus_group_id) || readString(args.consensusGroupId);\n if (!consensusGroupId) return JSON.stringify({ success: false, error: 'consensus_group_id required' });\n\n await refreshMeshFromDaemon(ctx);\n\n // MAGI-REDESIGN: recover the kind this group was dispatched with from the ledger so the\n // right schema parser is used (collect rediscovers replicas from the queue, not the call).\n // An explicit task_kind arg overrides (escape hatch if the dispatched ledger was pruned).\n const explicitKind = args.task_kind ?? args.taskKind;\n const taskKind = explicitKind !== undefined\n ? normalizeMagiTaskKind(explicitKind)\n : recoverMagiTaskKind(ctx, consensusGroupId);\n\n const replicaTasks = findMagiReplicaTasks(getQueue(ctx.mesh.id), consensusGroupId);\n if (replicaTasks.length === 0) {\n return JSON.stringify({\n success: false,\n code: 'magi_group_not_found',\n error: `No MAGI replicas found for consensus group '${consensusGroupId}'. It may have been pruned, or the id is wrong.`,\n consensusGroupId,\n });\n }\n\n const requireIndependentEvidence = (args.require_independent_evidence ?? args.requireIndependentEvidence) !== false;\n // Default to a SNAPSHOT (wait=false): poll-by-group is the async path, so the\n // common case is \"collect whatever finished so far\". Pass wait=true to block for\n // the remaining replicas up to wait_timeout_ms.\n const wait = args.wait === true;\n const timeoutMs = wait\n ? Math.min(MAGI_MAX_WAIT_MS, Math.max(MAGI_POLL_INTERVAL_MS, Number(args.wait_timeout_ms ?? args.waitTimeoutMs) || MAGI_DEFAULT_WAIT_MS))\n : 0;\n\n const replicaTaskIds = replicaTasks.map((t: any) => readString(t.id)).filter(Boolean) as string[];\n const collected = await collectMagiResponses(ctx, { replicaTaskIds, timeoutMs, taskKind });\n const synthesis = synthesizeMagiResponses(collected.responses, {\n replicasExpected: replicaTaskIds.length,\n requireIndependentEvidence,\n });\n // rawAnswer gate: always strip from the persisted ledger entry (bounds payload).\n // The RETURNED synthesis carries rawAnswer only when verbose=true; default strips it.\n const verbose = args.verbose === true;\n const synthesisNoRaw = stripRawAnswers(synthesis);\n const returnedSynthesis = verbose ? synthesis : synthesisNoRaw;\n const freeformBanner = taskKind === 'freeform'\n ? 'task_kind=freeform: answers are unstructured natural language; cross-verification is WEAK (no claim clustering / independence scoring). Treat the collected answers as parallel opinions, not a verified consensus.'\n : null;\n\n // deltaE: persist the synthesis (panel/question are merged from the earlier\n // magi_dispatched entry by consensusGroupId, so they need not be re-derived here).\n const replicaMissionId = readString(replicaTasks[0]?.missionId);\n persistMagiSynthesis(ctx, {\n consensusGroupId,\n missionId: replicaMissionId,\n staleReplicas: collected.staleCount,\n synthesis: synthesisNoRaw,\n });\n // FIX#3: the inline mission id comes from the replica tasks' OWN missionId (MAGI-owned,\n // guard a) — auto-close it once all replicas are terminal.\n closeMagiMissionIfTerminal(ctx, replicaMissionId, collected.terminal);\n\n // Post-collect auto-cleanup (default ON), gated terminal so a partial snapshot never\n // kills still-generating replicas. Reuse the rediscovered replicaTasks. Best-effort.\n const cleanupMode = resolveMagiAutoCleanupMode(ctx, args.auto_cleanup ?? args.autoCleanup);\n const cleanup = await cleanupMagiAutoLaunchedSessions(ctx, {\n replicaTasks,\n terminal: collected.terminal,\n mode: cleanupMode,\n });\n\n return JSON.stringify({\n success: true,\n consensusGroupId,\n taskKind,\n replicaCount: replicaTaskIds.length,\n waited: wait,\n ...(cleanup ? { sessionCleanup: { mode: cleanupMode, cleanedSessionCount: cleanup.cleanedSessionCount, perNode: cleanup.perNode } } : {}),\n collection: {\n terminal: collected.terminal,\n timedOut: collected.timedOut,\n answered: synthesis.replicasAnswered,\n missing: synthesis.replicasMissing,\n staleReplicas: collected.staleCount,\n ...(collected.staleCount > 0 ? { staleNote: `${collected.staleCount} replica(s) were detected STALE — assigned to a node/session no longer present in the live mesh.` } : {}),\n ...(collected.retriedCount > 0 ? { retriedReplicas: collected.retriedCount, retryNote: `${collected.retriedCount} replica(s) failed the ${taskKind} schema and were sent one delta re-request for a corrected single-JSON answer.` } : {}),\n ...(!collected.terminal ? { pendingNote: 'Not all replicas are terminal yet — this is a partial snapshot. Re-collect once mission/pendingCoordinatorEvents report more completions.' } : {}),\n },\n ...(freeformBanner ? { freeformBanner } : {}),\n ...(verbose ? { rawAnswersIncluded: true } : {}),\n synthesis: returnedSynthesis,\n }, null, 2);\n}\n\n// ─── Collection (best-effort, bounded) ──────────\n\nconst sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));\n\nconst MAGI_TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled']);\n\n/**\n * Discover the replica tasks of a MAGI fan-out by their shared consensus group id.\n * Drives poll-by-group collection (mesh_magi_collect): a wait=false review returns\n * the group id, and a later call rediscovers the replicas straight from the queue —\n * no need to thread the original task-id list back through the caller. Pure given a\n * queue snapshot.\n */\nexport function findMagiReplicaTasks(queue: any[], consensusGroupId: string): any[] {\n const groupId = typeof consensusGroupId === 'string' ? consensusGroupId.trim() : '';\n if (!groupId) return [];\n return (Array.isArray(queue) ? queue : []).filter((t: any) => readString(t?.consensusGroupId) === groupId);\n}\n\n// ─── Post-review auto-cleanup of MAGI-launched worker sessions ──────────────\n//\n// MAGI fans a question out to N independent (node × provider) replicas. For a pinned\n// target with no idle session the QUEUE auto-launches a fresh worker session, stamping\n// settings.autoLaunchedForQueueTaskId = task.id onto it (mesh-queue-assignment.ts) which\n// the cli-manager mirrors onto the session-host record meta. Those auto-launched workers\n// stay idle-LIVE after their turn, so repeated reviews pile up idle sessions.\n//\n// SAFETY: we compute the cleanup target set ONLY from the replica queue tasks themselves —\n// each replica contributes ITS OWN session ids (autoLaunch.sessionId once the auto-launch\n// completed, and assignedSessionId once it claimed), paired with the replica's task id as the\n// expected autoLaunchedForQueueTaskId marker. We never enumerate arbitrary sessions. The\n// daemon then double-checks the per-session marker (requireAutoLaunchedForTaskIds) before\n// touching anything: a REUSED idle session carries no marker → preserved; the COORDINATOR\n// session carries no marker → preserved; a session whose marker points at a DIFFERENT task\n// (re-assignment skew) → preserved. So only the sessions THIS fan-out actually spawned are\n// stopped+deleted. assignedSessionId is intentionally included even though it can be a reused\n// session — the marker gate filters reused ones out; an auto-launched-then-claimed session\n// has assignedSessionId === autoLaunch.sessionId and IS the one we want gone.\n\n/** One candidate cleanup target: a session a replica may have auto-launched, with the\n * replica's task id that the session-host record marker must match for it to be cleaned. */\nexport interface MagiCleanupCandidate {\n nodeId: string;\n sessionId: string;\n /** The replica task id this session must have been auto-launched FOR (marker check). */\n expectedTaskId: string;\n}\n\n/**\n * Pure: derive the per-node cleanup target set from the replica queue tasks. Returns a map\n * keyed by nodeId → { sessionIds, requireAutoLaunchedForTaskIds }. Session ids are pulled\n * ONLY from each replica task's own autoLaunch.sessionId (when status 'completed') and\n * assignedSessionId — never from an external session listing — and each id is paired with\n * THAT replica's task id as the expected marker (so a re-assignment skew can't smuggle in a\n * sibling's session). A replica with no resolvable node id or no candidate session is skipped.\n */\nexport function computeMagiCleanupTargets(replicaTasks: any[]): Map<string, {\n sessionIds: string[];\n requireAutoLaunchedForTaskIds: Record<string, string>;\n}> {\n const byNode = new Map<string, { sessionIds: Set<string>; requireAutoLaunchedForTaskIds: Record<string, string> }>();\n for (const task of Array.isArray(replicaTasks) ? replicaTasks : []) {\n const replicaTaskId = readString(task?.id);\n if (!replicaTaskId) continue;\n const nodeId = readString(task?.assignedNodeId)\n || readString(task?.autoLaunch?.nodeId)\n || readString(task?.targetNodeId);\n if (!nodeId) continue;\n const candidateSessionIds: string[] = [];\n // The session the queue auto-launched for this replica (authoritative auto-launch id).\n if (readString(task?.autoLaunch?.status) === 'completed') {\n const al = readString(task?.autoLaunch?.sessionId);\n if (al) candidateSessionIds.push(al);\n }\n // The session that actually claimed/ran it. May equal the auto-launched id (then it's\n // the same session) or be a reused idle session (filtered out by the marker gate).\n const assigned = readString(task?.assignedSessionId);\n if (assigned) candidateSessionIds.push(assigned);\n if (candidateSessionIds.length === 0) continue;\n let entry = byNode.get(nodeId);\n if (!entry) {\n entry = { sessionIds: new Set<string>(), requireAutoLaunchedForTaskIds: {} };\n byNode.set(nodeId, entry);\n }\n for (const sid of candidateSessionIds) {\n entry.sessionIds.add(sid);\n // Pair each session id with THIS replica's task id. If two replicas somehow named\n // the same session id (shared-session collision), the marker on the live record can\n // only equal one task id, so at most one replica legitimately owns it; recording the\n // first is fine because the daemon re-verifies the marker == expectedTaskId per id.\n if (!(sid in entry.requireAutoLaunchedForTaskIds)) {\n entry.requireAutoLaunchedForTaskIds[sid] = replicaTaskId;\n }\n }\n }\n const out = new Map<string, { sessionIds: string[]; requireAutoLaunchedForTaskIds: Record<string, string> }>();\n for (const [nodeId, entry] of byNode) {\n out.set(nodeId, {\n sessionIds: Array.from(entry.sessionIds),\n requireAutoLaunchedForTaskIds: entry.requireAutoLaunchedForTaskIds,\n });\n }\n return out;\n}\n\n/**\n * Resolve whether MAGI post-review auto-cleanup is enabled for this call. Per-call\n * auto_cleanup override (boolean) beats the mesh policy (magiSessionCleanup), which\n * defaults ON ('stop_and_delete'). Returns the effective mode.\n */\nexport function resolveMagiAutoCleanupMode(\n ctx: MeshContext,\n perCallOverride: boolean | undefined,\n): RepoMeshMagiSessionCleanupMode {\n if (perCallOverride === true) return 'stop_and_delete';\n if (perCallOverride === false) return 'preserve';\n return resolveMagiSessionCleanupMode((ctx.mesh as any)?.policy?.magiSessionCleanup);\n}\n\n/**\n * Best-effort post-review cleanup. Stops+deletes ONLY the worker sessions THIS MAGI fan-out\n * auto-launched (marker-verified daemon-side). Only runs when `terminal` is true — a partial\n * collect must NOT kill replicas that are still generating. Never throws: cleanup failure\n * never blocks returning the synthesis. Returns a small summary (or null when skipped/disabled).\n */\nexport async function cleanupMagiAutoLaunchedSessions(\n ctx: MeshContext,\n args: { replicaTasks: any[]; terminal: boolean; mode: RepoMeshMagiSessionCleanupMode },\n): Promise<{ cleanedSessionCount: number; perNode: Array<Record<string, unknown>> } | null> {\n if (args.mode === 'preserve') return null;\n if (!args.terminal) return null; // never cleanup a partial collection — replicas may still be live\n const targets = computeMagiCleanupTargets(args.replicaTasks);\n if (targets.size === 0) return null;\n\n let cleanedSessionCount = 0;\n const perNode: Array<Record<string, unknown>> = [];\n // OFFLINE-NODE-BLOCKING: run the per-node cleanup fan-out concurrently with per-node\n // error isolation (Promise.allSettled) so one offline replica node no longer serializes\n // the rest. cleanup_mesh_sessions is a MUTATION (not a pure read), but it is idempotent\n // and safe to skip for an unreachable node — an offline replica has no live sessions we\n // could reach anyway. Stamp it with the status-origin marker ({ statusProbe: true }): the\n // marker is used ONLY to grant the daemon-cloud relay's SHORT connect-wait budget (so an\n // offline node fails fast in ~2s instead of the 90s connect deadline) and is stripped\n // before the command executes, so the server-side cleanup semantics are unchanged.\n const cleanupNode = async (\n nodeId: string,\n group: { sessionIds: string[]; requireAutoLaunchedForTaskIds?: unknown },\n ): Promise<{ cleaned: number; entry: Record<string, unknown> }> => {\n try {\n const node = await findOptionalNodeWithRefresh(ctx, nodeId);\n if (!node) {\n // Node gone from the live mesh — its sessions are unreachable; report, don't fail.\n return { cleaned: 0, entry: { nodeId, skipped: 'node_not_in_live_mesh', sessionIds: group.sessionIds } };\n }\n const result = await commandForNode(ctx, node, 'cleanup_mesh_sessions', {\n meshId: ctx.mesh.id,\n nodeId,\n mode: 'stop_and_delete',\n sessionIds: group.sessionIds,\n source: 'magi_session_cleanup',\n requireAutoLaunchedForTaskIds: group.requireAutoLaunchedForTaskIds,\n inlineMesh: ctx.mesh,\n }, { statusProbe: true });\n const payload = unwrapCommandPayload(result) as any;\n const deleted = Array.isArray(payload?.deletedSessionIds) ? payload.deletedSessionIds.length : 0;\n const stopped = Array.isArray(payload?.stoppedSessionIds) ? payload.stoppedSessionIds.length : 0;\n return {\n cleaned: deleted + stopped,\n entry: {\n nodeId,\n requested: group.sessionIds.length,\n deleted,\n ...(stopped ? { stopped } : {}),\n ...(Array.isArray(payload?.skippedMarkerMismatchSessionIds) && payload.skippedMarkerMismatchSessionIds.length\n ? { skippedMarkerMismatch: payload.skippedMarkerMismatchSessionIds }\n : {}),\n ...(payload?.deleteUnsupported ? { deleteUnsupported: true } : {}),\n },\n };\n } catch (e: any) {\n return { cleaned: 0, entry: { nodeId, error: e?.message || String(e), sessionIds: group.sessionIds } };\n }\n };\n\n const cleanupTargets = Array.from(targets).filter(([, group]) => group.sessionIds.length > 0);\n const settled = await Promise.allSettled(\n cleanupTargets.map(([nodeId, group]) => cleanupNode(nodeId, group)),\n );\n settled.forEach((outcome, idx) => {\n if (outcome.status === 'fulfilled') {\n cleanedSessionCount += outcome.value.cleaned;\n perNode.push(outcome.value.entry);\n } else {\n // cleanupNode swallows its own errors, so a rejection here is unexpected.\n const [nodeId, group] = cleanupTargets[idx];\n perNode.push({ nodeId, error: outcome.reason?.message ?? String(outcome.reason), sessionIds: group.sessionIds });\n }\n });\n return { cleanedSessionCount, perNode };\n}\n\n/**\n * FIX#1 (MAGI tangle): is THIS replica's transcript session also bound to ANOTHER replica of\n * the same fan-out? collect used to resolve a replica's transcript purely by\n * task.assignedSessionId and parse the NEWEST kind-valid JSON across that whole session. But\n * assignedSessionId is NOT unique per replica — it is never cleared on completion, and a\n * provider can reuse one session for >1 replica (sequential idle→claim reuse). When two\n * replicas share a session both resolve to the SAME newest turn → one is dropped as\n * unparseable_output / mis-attributed. There is no per-bubble taskId in the transcript to\n * disambiguate them (the dispatch stamps meshContext.taskId, but bubbles carry only a\n * positional _turnKey, and every MAGI replica is sent the IDENTICAL prompt so the user-bubble\n * text can't separate them either). So we FAIL CLOSED on a detected share: the colliding\n * replica is not attributed the ambiguous turn — it re-waits, and at the deadline finalizes as\n * a `cross_wired_shared_session` error instead of returning another replica's answer.\n *\n * Session ids are node-local, so a match only collides on the SAME node; a coincidental id\n * match across two nodes is not a real share. Pure given a task snapshot.\n */\nexport function sessionSharedWithAnotherReplica(task: any, allTasks: any[]): boolean {\n const sid = readString(task?.assignedSessionId);\n if (!sid) return false;\n const nodeId = readString(task?.assignedNodeId);\n return (Array.isArray(allTasks) ? allTasks : []).some((other: any) => other?.id !== task?.id\n && readString(other?.assignedSessionId) === sid\n && (!nodeId || !readString(other?.assignedNodeId) || readString(other?.assignedNodeId) === nodeId));\n}\n\n/**\n * Classify which non-terminal replica tasks are STALE — assigned to a node/session\n * absent from the live mesh (so they will never reach a terminal state). Reuses the\n * shared queue staleness annotation (annotateQueueStaleness) so MAGI and the queue\n * tools agree on what \"stale\" means. Pure given tasks already annotated. Returns the\n * set of stale (won't-progress) non-terminal task ids and their reasons.\n */\nexport function classifyStaleReplicas(\n annotatedTasks: any[],\n terminal: Set<string> = MAGI_TERMINAL_STATUSES,\n): { staleTaskIds: Set<string>; staleReasons: Record<string, string> } {\n const staleTaskIds = new Set<string>();\n const staleReasons: Record<string, string> = {};\n for (const t of Array.isArray(annotatedTasks) ? annotatedTasks : []) {\n if (terminal.has(String(t?.status))) continue;\n if (t?.staleAssigned === true) {\n const id = readString(t.id);\n if (!id) continue;\n staleTaskIds.add(id);\n staleReasons[id] = readString(t.staleReason) || 'assigned node/session is not present in the live mesh';\n }\n }\n return { staleTaskIds, staleReasons };\n}\n\n// ─── Persistence (deltaE) ───────────────────────\n\n/**\n * Persist the MAGI fan-out as a `magi_dispatched` ledger entry so the consensus group\n * is visible in mesh_status (status=running) and survives a coordinator restart even\n * before any synthesis is collected. Best-effort — a ledger write failure never aborts\n * the review.\n */\nfunction persistMagiDispatched(\n ctx: MeshContext,\n args: { consensusGroupId: string; missionId?: string; panel?: string; question?: string; replicaCount: number; taskKind?: MagiTaskKind },\n): void {\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'magi_dispatched',\n payload: {\n source: 'magi',\n consensusGroupId: args.consensusGroupId,\n ...(args.missionId ? { missionId: args.missionId } : {}),\n ...(args.panel ? { panel: args.panel } : {}),\n ...(args.question ? { question: args.question.slice(0, 300) } : {}),\n replicaCount: args.replicaCount,\n // MAGI-REDESIGN: persist the task_kind so a later mesh_magi_collect\n // (which rediscovers replicas from the queue, not the original call)\n // re-derives the right schema parser for this group.\n ...(args.taskKind ? { taskKind: args.taskKind } : {}),\n },\n });\n } catch { /* ledger write is best-effort */ }\n}\n\n/**\n * Recover the task_kind a MAGI fan-out was dispatched with from its `magi_dispatched`\n * ledger entry (mesh_magi_collect rediscovers replicas from the queue and has no kind in\n * hand). Defaults to claim_audit (the backward-compatible kind) when no entry / no kind\n * is recorded. Best-effort: an unreadable ledger returns the default.\n */\nfunction recoverMagiTaskKind(ctx: MeshContext, consensusGroupId: string): MagiTaskKind {\n try {\n const entries = readLedgerEntries(ctx.mesh.id, { kind: ['magi_dispatched'], tail: 200 });\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const payload = (entries[i] as any)?.payload;\n if (!payload || typeof payload !== 'object') continue;\n if (readString(payload.consensusGroupId) !== consensusGroupId) continue;\n return normalizeMagiTaskKind(payload.taskKind);\n }\n } catch { /* unreadable ledger → default kind */ }\n return DEFAULT_TASK_KIND;\n}\n\n/**\n * Strip per-replica rawAnswer (the captured raw end-user text) from a synthesis's\n * replicas[]. rawAnswer can be up to MAGI_RAW_ANSWER_CAP chars × N replicas, so it is\n * gated: omitted from the persisted ledger entry (bounds ledger payload growth) and from\n * the default mesh_magi_collect response. Returns a shallow copy with rawAnswer/\n * rawAnswerTruncated removed from every replica; the original is never mutated.\n */\nfunction stripRawAnswers(synthesis: MagiSynthesis): MagiSynthesis {\n if (!Array.isArray(synthesis.replicas) || synthesis.replicas.length === 0) return synthesis;\n return {\n ...synthesis,\n replicas: synthesis.replicas.map(r => {\n if (r.rawAnswer === undefined && r.rawAnswerTruncated === undefined) return r;\n const { rawAnswer: _omitRaw, rawAnswerTruncated: _omitTrunc, ...rest } = r;\n return rest;\n }),\n };\n}\n\n/**\n * Persist the synthesis as a `magi_synthesis` ledger entry, retrievable by\n * consensusGroupId (getMeshMagiActivityByGroup) and foldable into mesh_status. The full\n * synthesis is stored MINUS per-replica rawAnswer (the caller strips it to bound ledger\n * payload growth); mesh_status bounds it further on read. Best-effort.\n */\nfunction persistMagiSynthesis(\n ctx: MeshContext,\n args: { consensusGroupId: string; missionId?: string; panel?: string; question?: string; staleReplicas?: number; synthesis: MagiSynthesis },\n): void {\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'magi_synthesis',\n payload: {\n source: 'magi',\n consensusGroupId: args.consensusGroupId,\n ...(args.missionId ? { missionId: args.missionId } : {}),\n ...(args.panel ? { panel: args.panel } : {}),\n ...(args.question ? { question: args.question.slice(0, 300) } : {}),\n ...(typeof args.staleReplicas === 'number' ? { staleReplicas: args.staleReplicas } : {}),\n synthesis: args.synthesis,\n },\n });\n } catch { /* ledger write is best-effort */ }\n}\n\n/**\n * FIX#3 — auto-close the inline MAGI mission once all replicas are terminal.\n *\n * Every mesh_magi_review auto-creates an inline mission (status defaults 'active') for the\n * fan-out; nothing ever closed it, so 'MAGI: …' missions accumulated forever (mission status\n * is, by design, never derived from task status). Call this at the collect-terminal point:\n * when collection is terminal (all replicas reached a terminal verdict) and the synthesis has\n * been persisted, transition the OWNING mission active→completed.\n *\n * Guards:\n * - (a) MAGI-owned only — the caller MUST pass the replica tasks' OWN missionId (never a\n * coordinator-supplied id), so we only ever close the inline MAGI mission.\n * - (b) Never clobber a manual terminal/paused status — upsertMeshMission has NO no-clobber\n * semantics (it overwrites status), so we read the current status first and ONLY transition\n * from 'active'. An 'abandoned'/'paused'/'completed' mission is left untouched.\n * Idempotent: a re-collect that finds the mission already 'completed' is a no-op. Best-effort:\n * a missing mission / read failure never breaks collection.\n */\nfunction closeMagiMissionIfTerminal(ctx: MeshContext, missionId: string | undefined, terminal: boolean): void {\n if (!terminal) return;\n const id = readString(missionId);\n if (!id) return;\n try {\n const mission = getMeshMission(ctx.mesh.id, id);\n // Only close a mission we can see AND that is still active. Skip when missing\n // (already pruned), or already completed/abandoned/paused (guard b).\n if (!mission || mission.status !== 'active') return;\n upsertMeshMission(ctx.mesh.id, {\n id,\n title: mission.title,\n // Preserve goal: upsert defaults goal to the existing value when omitted.\n status: 'completed',\n });\n } catch { /* mission close is best-effort — never break collection */ }\n}\n\n/**\n * Pull a compact git ref off a live mesh node (its GitCompactSummary, populated by the\n * daemon git monitor) for deltaA git-skew. Returns undefined when the node carries no\n * git summary — refs are best-effort, never fabricated.\n */\nfunction extractNodeGitRef(node: any): MagiReplicaGitRef | undefined {\n const git = node?.git;\n if (!git || typeof git !== 'object') return undefined;\n const ref: MagiReplicaGitRef = {};\n if (typeof git.branch === 'string' || git.branch === null) ref.branch = git.branch;\n const headCommit = nodeHeadCommit(node);\n if (headCommit) ref.headCommit = headCommit;\n if (typeof git.ahead === 'number' && Number.isFinite(git.ahead)) ref.ahead = git.ahead;\n if (typeof git.behind === 'number' && Number.isFinite(git.behind)) ref.behind = git.behind;\n if (typeof git.dirty === 'boolean') ref.dirty = git.dirty;\n return Object.keys(ref).length > 0 ? ref : undefined;\n}\n\nasync function collectMagiResponses(\n ctx: MeshContext,\n args: { replicaTaskIds: string[]; timeoutMs: number; taskKind?: MagiTaskKind },\n): Promise<{ responses: MagiSynthesizedResponse[]; terminal: boolean; timedOut: boolean; staleCount: number; retriedCount: number }> {\n const ids = new Set(args.replicaTaskIds);\n const deadline = Date.now() + args.timeoutMs;\n const TERMINAL = MAGI_TERMINAL_STATUSES;\n const kind = args.taskKind ?? DEFAULT_TASK_KIND;\n const emptyResponse = (): MagiAgentResponse => ({ claims: [], top_findings: [], open_questions: [] });\n\n // E: each replica gets at most ONE delta re-request when its terminal answer fails\n // the kind schema. We track which task ids have already been re-requested so a second\n // schema failure drops to unparseable (current behavior) instead of looping.\n const retried = new Set<string>();\n\n // Per-replica FINAL verdict, locked once reached: a parseable answer, a stale dead\n // assignment, a non-readable terminal, or (at deadline) an unparseable confirmation.\n // `provisional` keeps a parseable-but-WEAK answer as the deadline fallback so a re-wait\n // never loses a valid answer it already saw.\n const finalized = new Map<string, MagiSynthesizedResponse>();\n const provisional = new Map<string, MagiSynthesizedResponse>();\n\n // FIX C-rawanswer: capture the replica's raw end-user answer (newest readable\n // candidate text from its transcript), capped to MAGI_RAW_ANSWER_CAP so a long\n // answer can't bloat the synthesis payload / ledger. Returns undefined when no\n // readable text was produced. Gated downstream: stripped from the persisted\n // magi_synthesis ledger entry and the default mesh_magi_collect response; surfaced\n // only in mesh_magi_collect verbose.\n const captureRawAnswer = (source: MagiResponseSource, payload: unknown): void => {\n try {\n const candidates = collectMagiCandidateTexts(payload);\n const raw = candidates.find(c => c.trim().length > 0);\n if (!raw) return;\n if (raw.length > MAGI_RAW_ANSWER_CAP) {\n source.rawAnswer = raw.slice(0, MAGI_RAW_ANSWER_CAP);\n source.rawAnswerTruncated = true;\n } else {\n source.rawAnswer = raw;\n }\n } catch { /* raw-answer capture is best-effort */ }\n };\n\n const buildSource = (task: any): MagiResponseSource => {\n const sourceNodeId = task.assignedNodeId || task.targetNodeId || undefined;\n // deltaA: capture the replica node's git ref so synthesis can flag cross-replica\n // git skew. Best-effort, from the live node's compact git summary.\n const gitRef = extractNodeGitRef(sourceNodeId ? ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, sourceNodeId)) : undefined);\n return {\n taskId: task.id,\n nodeId: sourceNodeId,\n provider: task.assignedProviderType || undefined,\n ok: false,\n ...(gitRef ? { git: gitRef } : {}),\n };\n };\n\n // E: send ONE delta re-request to a replica whose terminal answer failed the kind\n // schema, asking for a single JSON matching exactly that kind's contract. Best-effort —\n // a send failure leaves the replica to be finalized as unparseable at the deadline. The\n // replica stays `completed`; the new turn flips it back to generating, so the poll loop\n // re-reads it naturally. Returns true when the delta was dispatched.\n const sendKindRetry = async (task: any, failReason: MagiKindParseResult['failReason']): Promise<boolean> => {\n const node = ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, task.assignedNodeId));\n if (!node || !task.assignedSessionId) return false;\n const why = failReason === 'empty_evidence'\n ? 'your previous answer had an empty evidence array'\n : failReason === 'missing_required_fields'\n ? 'your previous answer was missing required fields'\n : 'your previous answer did not parse as the required JSON';\n const message = `Your previous MAGI answer could not be accepted (${why}). Respond NOW with ONLY a single JSON object (no prose, no code fence) matching EXACTLY this schema, with non-empty evidence:\\n\\n${magiOutputContractFor(kind)}`;\n try {\n const coordinatorDaemonId = ctx.localDaemonId;\n await commandForNode(ctx, node, 'agent_command', {\n targetSessionId: task.assignedSessionId,\n providerType: task.assignedProviderType,\n cliType: task.assignedProviderType,\n agentType: task.assignedProviderType,\n action: 'send_chat',\n message,\n meshContext: {\n meshId: ctx.mesh.id,\n nodeId: task.assignedNodeId,\n taskId: task.id,\n ...(coordinatorDaemonId ? { coordinatorDaemonId } : {}),\n ...(ctx.coordinatorSessionId ? { coordinatorSessionId: ctx.coordinatorSessionId } : {}),\n },\n });\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'magi_replica_retry' as any,\n payload: { taskId: task.id, kind, failReason },\n });\n } catch { /* ledger write is best-effort */ }\n return true;\n } catch { return false; }\n };\n\n // Recover a replica wedged on an approval modal. A MAGI replica is dispatched\n // readonly:true, so any command-approval prompt it raises (typically the git/read it runs\n // to gather file:line evidence) is safe to approve — and MUST be, because dispatch-time\n // auto-approve is not guaranteed (IDE providers with no resolveAction script no-op it;\n // remote pre-existing sessions never get the autoApprove backfill). Left unresolved, the\n // replica burns the whole collect deadline and is lost as `replica_waiting_approval`.\n // Reads the live session; only approves when it is actually in an approval state. Idempotent\n // — resolve_action reports already_resolved/stale_prompt within its cooldown, so re-calling\n // on later poll ticks is a no-op. Fully best-effort: any failure just leaves the normal\n // re-wait/deadline path intact. Emits one ledger breadcrumb per approval attempt.\n const nudgeWedgedReplica = async (task: any): Promise<void> => {\n const node = ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, task.assignedNodeId));\n if (!node || !task.assignedSessionId) return;\n try {\n const read = await commandForNode(ctx, node, 'read_chat', {\n sessionId: task.assignedSessionId,\n targetSessionId: task.assignedSessionId,\n workspace: (node as any).workspace,\n tailLimit: 1,\n });\n const payload = unwrapCommandPayload(read) as any;\n if (!magiReadIndicatesApprovalWedge(payload)) return;\n const status = String(payload?.status ?? '');\n await commandForNode(ctx, node, 'resolve_action', {\n sessionId: task.assignedSessionId,\n targetSessionId: task.assignedSessionId,\n workspace: (node as any).workspace,\n providerType: task.assignedProviderType,\n agentType: task.assignedProviderType,\n cliType: task.assignedProviderType,\n action: 'approve',\n });\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'magi_replica_auto_approved' as any,\n payload: { taskId: task.id, nodeId: task.assignedNodeId, status },\n });\n } catch { /* ledger write is best-effort */ }\n } catch { /* nudge is best-effort — fall through to the normal re-wait */ }\n };\n\n // Attempt to FINALIZE one replica from its current state. Returns true once a final\n // verdict is locked. `force` (deadline reached / tasks gone) converts any remaining\n // re-wait (weak/unparseable/still-running) into a terminal verdict.\n const tryResolveReplica = async (\n task: any,\n staleTaskIds: Set<string>,\n staleReasons: Record<string, string>,\n force: boolean,\n liveTasks: any[],\n ): Promise<boolean> => {\n const taskId = task.id;\n const source = buildSource(task);\n\n // Not a readable completion yet (failed/cancelled/running, or no session bound).\n if (task.status !== 'completed' || !task.assignedNodeId || !task.assignedSessionId) {\n if (staleTaskIds.has(taskId)) {\n source.stale = true;\n source.error = `stale: ${staleReasons[taskId]}`;\n finalized.set(taskId, { source, response: emptyResponse() });\n return true;\n }\n if (TERMINAL.has(String(task.status))) {\n source.error = task.status === 'completed' ? 'no_session_to_read' : `replica_${task.status || 'incomplete'}`;\n finalized.set(taskId, { source, response: emptyResponse() });\n return true;\n }\n // Still running and not stale. A replica can WEDGE here forever on an approval\n // modal: a MAGI task is dispatched read-only, but dispatch-time auto-approve is\n // conditional (it no-ops for an IDE provider whose auto-approve script is absent,\n // or a remote pre-existing session that never got the autoApprove backfill), so a\n // command-approval prompt (e.g. the git-read the replica runs to gather evidence)\n // is never clicked and the replica is silently lost at the 180s deadline as\n // `replica_waiting_approval`. Because the MAGI task is readonly:true, approving is\n // exactly the intended semantics — so before re-waiting, detect a bound-session\n // approval wedge and drive resolve_action(approve) on it. Best-effort and idempotent\n // (a stale/already-resolved prompt is a no-op); provider-agnostic (recovers both the\n // IDE-provider and remote-adopt gaps). Skipped under `force` (the deadline pass just\n // finalizes) and rate-limited to once per replica per poll tick.\n if (task.assignedNodeId && task.assignedSessionId && !force) {\n await nudgeWedgedReplica(task);\n }\n if (force) {\n source.error = `replica_${task.status || 'incomplete'}`;\n finalized.set(taskId, { source, response: emptyResponse() });\n return true;\n }\n return false;\n }\n\n // FIX#1: cross-wire guard. This completed replica's session is also bound to another\n // replica of THIS group → the newest turn cannot be safely attributed to either. Do NOT\n // grab it (that is exactly the mis-attribution / dropped-as-unparseable bug). Re-wait so a\n // later poll can find them on distinct sessions; at the deadline finalize as a cross-wire\n // error (not another replica's answer).\n if (sessionSharedWithAnotherReplica(task, liveTasks)) {\n if (force) {\n source.error = 'cross_wired_shared_session';\n finalized.set(taskId, { source, response: emptyResponse() });\n return true;\n }\n return false;\n }\n\n // A `completed` replica WITH a session: read the transcript and try to parse a MAGI\n // answer for THIS kind. Fix A: a completed-but-weak completion (early/mid-turn\n // suppressed) or a not-yet-parseable transcript is treated as NOT terminal — re-poll\n // until the deadline rather than collecting a premature mid-turn bubble.\n let kindResult: MagiKindParseResult;\n try {\n const node = ctx.mesh.nodes.find(n => meshNodeIdMatches(n as any, task.assignedNodeId));\n if (!node) throw new Error('assigned node not in mesh');\n const result = await commandForNode(ctx, node, 'read_chat', {\n sessionId: task.assignedSessionId,\n targetSessionId: task.assignedSessionId,\n workspace: (node as any).workspace,\n tailLimit: 6,\n // FIX#1: scope the read to the CURRENT turn so a provider that supports it returns\n // only this turn's bubbles (coverage:'current-turn' / _turnKey), instead of the\n // whole-session tail whose newest kind-valid JSON could belong to an earlier turn.\n coverage: 'current-turn',\n });\n const payload = unwrapCommandPayload(result);\n // Capture the raw answer onto `source` now, so it rides along whether this\n // replica finalizes as a parseable answer or a weak/provisional one. (Stripped\n // for non-verbose consumers downstream.)\n captureRawAnswer(source, payload);\n // Fix-A-v2 summary-fallback (kind-aware): parse candidates from BOTH the raw payload\n // (newest bubble body first, premature-collect guard) AND the compacted payload\n // (surfaces the lifted `summary` so antigravity's empty-bubble / summary-only answer\n // is recovered), validating each against the selected kind's schema.\n kindResult = parseFirstMagiCandidateForKind(payload, kind, {\n sessionId: task.assignedSessionId,\n });\n } catch (e: any) {\n // A transient read failure re-waits (the node/peer may be momentarily busy);\n // finalize the failure only once the deadline is hit.\n if (force) {\n source.error = `read_failed: ${e?.message || String(e)}`;\n finalized.set(taskId, { source, response: emptyResponse() });\n return true;\n }\n return false;\n }\n\n if (kindResult.ok && kindResult.response) {\n const weak = replicaCompletionIsWeak(ctx.mesh.id, taskId);\n if (weak && !force) {\n // Parseable but the completion evidence is weak — keep it as the deadline\n // fallback and re-wait for a stronger/fuller final answer.\n provisional.set(taskId, { source: { ...source, ok: true }, response: kindResult.response });\n return false;\n }\n finalized.set(taskId, { source: { ...source, ok: true }, response: kindResult.response });\n return true;\n }\n\n // Parsed something but it FAILS the kind schema (missing fields / empty evidence) →\n // E: fire exactly one delta re-request, then re-wait for the corrected answer. A\n // second failure (already retried) drops to unparseable below.\n const isSchemaFailure = kindResult.failReason === 'missing_required_fields'\n || kindResult.failReason === 'empty_evidence';\n if (isSchemaFailure && !retried.has(taskId) && !force) {\n retried.add(taskId);\n const sent = await sendKindRetry(task, kindResult.failReason);\n if (sent) return false; // re-wait for the corrected turn\n // Could not dispatch the retry → fall through to the unparseable handling.\n }\n\n // Not parseable / still schema-invalid → the premature-collect guard: re-wait until\n // the deadline, then finalize as unparseable (preferring any provisional answer).\n if (force) {\n const prov = provisional.get(taskId);\n if (prov) {\n finalized.set(taskId, prov);\n return true;\n }\n source.error = isSchemaFailure ? `schema_invalid: ${kindResult.failReason}` : 'unparseable_output';\n finalized.set(taskId, { source, response: emptyResponse() });\n return true;\n }\n return false;\n };\n\n // Poll until every replica reaches a final verdict, every still-outstanding replica is\n // detected STALE (dead assignment), or the deadline elapses.\n for (;;) {\n const tasks = annotateQueueStaleness(getQueue(ctx.mesh.id).filter((t: any) => ids.has(t.id)), ctx.mesh);\n const allPresent = tasks.length === ids.size;\n const { staleTaskIds, staleReasons } = classifyStaleReplicas(tasks, TERMINAL);\n const pastDeadline = Date.now() >= deadline;\n\n for (const task of tasks as any[]) {\n if (finalized.has(task.id)) continue;\n await tryResolveReplica(task, staleTaskIds, staleReasons, pastDeadline, tasks);\n }\n\n if (allPresent && finalized.size >= ids.size) break;\n if (pastDeadline) break;\n // Every still-outstanding replica is stale → stop early (they were just finalized above).\n const outstanding = tasks.filter((t: any) => !finalized.has(t.id));\n if (allPresent && outstanding.length > 0 && outstanding.every((t: any) => staleTaskIds.has(t.id))) break;\n\n await sleep(Math.min(MAGI_POLL_INTERVAL_MS, Math.max(0, deadline - Date.now())));\n }\n\n // Final pass: force-finalize anything still outstanding now that the loop has ended.\n const finalTasks = annotateQueueStaleness(getQueue(ctx.mesh.id).filter((t: any) => ids.has(t.id)), ctx.mesh);\n const { staleTaskIds, staleReasons } = classifyStaleReplicas(finalTasks, TERMINAL);\n const presentIds = new Set(finalTasks.map((t: any) => t.id));\n for (const task of finalTasks as any[]) {\n if (!finalized.has(task.id)) await tryResolveReplica(task, staleTaskIds, staleReasons, true, finalTasks);\n }\n // A replica whose queue row vanished entirely (never observed) is recorded as missing.\n for (const id of ids) {\n if (finalized.has(id)) continue;\n if (!presentIds.has(id)) {\n finalized.set(id, { source: { taskId: id, ok: false, error: 'replica_missing' }, response: emptyResponse() });\n }\n }\n\n // Preserve the caller's replica order.\n const responses = args.replicaTaskIds\n .map(id => finalized.get(id))\n .filter((r): r is MagiSynthesizedResponse => !!r);\n const terminal = presentIds.size === ids.size && finalTasks.every((t: any) => TERMINAL.has(String(t.status)));\n const staleCount = responses.filter(r => r.source.stale === true).length;\n return { responses, terminal, timedOut: !terminal, staleCount, retriedCount: retried.size };\n}\n","/**\n * mesh_node_slots_* — the coordinator's surface for PROPOSING and APPLYING node\n * capability-slot changes (ORCHESTRATION_NODE_SLOTS.md §5: orchestrator autonomous\n * adjustment, propose → approve).\n *\n * A node's capability slots (policy.slots) are the single source of truth for\n * task→node fitness routing and MAGI fan-out. Previously only the human operator\n * could edit them (NodeSlotEditor). This lets the orchestrator, MID-RUN, suggest a\n * profile change — \"add an opus slot to node X so difficult tasks route there\" —\n * and apply it, but ONLY behind an explicit user-approval gate.\n *\n * The gate reuses the mesh_magi_kind_panel_set precedent exactly: default to a\n * dry-run (write=false) that returns the current-vs-proposed slot lists so the\n * coordinator can present the diff for approval, and only mutate on an explicit\n * write=true re-call. No new pending/approval storage is needed — the coordinator\n * presents the dry-run diff in chat, the user approves in chat, the coordinator\n * re-calls with write=true (same flow the design doc prescribes).\n *\n * Apply path reuses the existing seam: commandForNode(update_mesh_node,\n * { policy: { slots } }) → daemon med-family updateNode shallow-merges policy.slots.\n * No daemon change required — update_mesh_node already accepts slots.\n */\nimport { normalizeNodeCapabilitySlots } from '@adhdev/mesh-shared';\nimport {\n commandForNode,\n findNodeWithRefresh,\n syncCoordinatorDaemonMeshCache,\n unwrapCommandPayload,\n type MeshContext,\n} from './mesh-tools-internal.js';\n\n/** Read the node's currently-persisted capability slots (normalized). */\nfunction readNodeSlots(node: any): ReturnType<typeof normalizeNodeCapabilitySlots> {\n return normalizeNodeCapabilitySlots(node?.policy?.slots);\n}\n\n/**\n * List a node's capability slots. Read-only — the sibling of the set command,\n * used to confirm the current profile and to diff before a proposed overwrite.\n */\nexport async function meshNodeSlotsList(\n ctx: MeshContext,\n args: { node_id?: string; nodeId?: string } = {},\n): Promise<string> {\n const nodeId = String(args.node_id || args.nodeId || '').trim();\n if (!nodeId) return JSON.stringify({ success: false, error: 'node_id required' });\n try {\n const node = await findNodeWithRefresh(ctx, nodeId);\n return JSON.stringify({\n success: true,\n nodeId: node.id,\n slots: readNodeSlots(node),\n }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e?.message || String(e) });\n }\n}\n\n/**\n * Propose (dry-run) or apply (write=true) a node's capability-slot list.\n *\n * WHOLESALE REPLACEMENT: the passed `slots` become the node's complete new slot\n * list (policy.slots) — any prior slot not in the new list is dropped. So this\n * requires explicit user approval before a write; the default dry-run returns the\n * current-vs-proposed lists for the coordinator to present.\n */\nexport async function meshNodeSlotsSet(\n ctx: MeshContext,\n args: { node_id?: string; nodeId?: string; slots?: unknown; write?: boolean; reason?: string },\n): Promise<string> {\n const nodeId = String(args.node_id || args.nodeId || '').trim();\n if (!nodeId) return JSON.stringify({ success: false, error: 'node_id required' });\n const write = args.write === true;\n try {\n const node = await findNodeWithRefresh(ctx, nodeId);\n const current = readNodeSlots(node);\n // Normalize the proposal with the SAME normalizer the daemon would apply, so\n // the preview and the eventual write agree on the exact stored shape.\n const proposed = normalizeNodeCapabilitySlots(args.slots);\n\n if (!write) {\n return JSON.stringify({\n success: true,\n dryRun: true,\n nodeId: node.id,\n replacement: true,\n ...(typeof args.reason === 'string' && args.reason.trim() ? { reason: args.reason.trim() } : {}),\n currentSlots: current,\n proposedSlots: proposed,\n note: 'Dry-run only — nothing written. This is a WHOLESALE replacement of the node\\'s capability slots (policy.slots): currentSlots would be fully replaced by proposedSlots. Present this diff to the user and re-run with write=true ONLY after explicit approval.',\n }, null, 2);\n }\n\n // Apply via the existing update_mesh_node seam — daemon shallow-merges\n // policy.slots. Send the normalized proposal so the stored value is clean.\n // inlineMesh lets the remote member daemon resolve the mesh without a local\n // meshes.json entry (same pattern as remove_mesh_node, clone_mesh_node, etc.).\n const raw = await commandForNode(ctx, node, 'update_mesh_node', {\n meshId: ctx.mesh.id,\n nodeId: node.id,\n policy: { slots: proposed },\n inlineMesh: ctx.mesh,\n });\n const result = unwrapCommandPayload(raw);\n if (result?.success === false) {\n return JSON.stringify({ success: false, error: result.error || 'update_mesh_node failed' });\n }\n // Coordinator-side sync (mirror clone_mesh_node / remove_mesh_node above): the\n // write landed on the node's home-daemon and its inline cache, but the\n // coordinator's in-memory ctx.mesh — the view slot-fitness routing reads — still\n // holds the OLD slots, and mesh_node_slots_list resolves off ctx.mesh too. Fold\n // the new slots back into ctx.mesh and push the refreshed snapshot to the\n // coordinator daemon's inline cache via syncCoordinatorDaemonMeshCache so the\n // next queue drain (and an immediate list) sees them. Without this the remote\n // write returns success yet the slots stay invisible coordinator-side.\n // [NODE-SLOTS-REMOTE-WRITE follow-up]\n const idx = ctx.mesh.nodes.findIndex(n => n.id === node.id);\n if (idx >= 0) {\n const target: any = ctx.mesh.nodes[idx];\n target.policy = {\n ...(target.policy && typeof target.policy === 'object' && !Array.isArray(target.policy)\n ? target.policy\n : {}),\n slots: proposed,\n };\n ctx.mesh.updatedAt = new Date().toISOString();\n await syncCoordinatorDaemonMeshCache(ctx);\n }\n return JSON.stringify({\n success: true,\n written: true,\n nodeId: node.id,\n replacement: true,\n previousSlots: current,\n slots: proposed,\n nextAction: 'Verify with mesh_node_slots_list. Slot-fitness routing picks these up on the next queue drain.',\n }, null, 2);\n } catch (e: any) {\n return JSON.stringify({ success: false, error: e?.message || String(e) });\n }\n}\n","// Mesh tool implementations — session domain.\n// Pure move out of mesh-tools.ts (no behavior change). Shared helpers, types, module\n// state and dependency re-exports live in ./mesh-tools-internal.ts; mesh-tools.ts is a barrel.\n\nimport {\n IpcTransport,\n SESSION_PROVIDER_METADATA_TTL_MS,\n annotateRapidReadChatAdvisory,\n appendLedgerEntry,\n buildCoordinatorP2pRelayFailure,\n buildDirectTaskPayload,\n buildMeshActiveWork,\n collectPendingApprovals,\n buildMeshReadChatCacheFallback,\n buildMissingCoordinatorDaemonIdFailure,\n buildMissingNodeReadChatRecovery,\n buildQueueTriggerGuidance,\n collectLiveStatusProbe,\n collectLiveStatusSessions,\n collectMeshViewQueueNodesWithLiveSessions,\n commandForNode,\n compactChatPayload,\n deleteDirectDispatchesByTaskId,\n drainCoordinatorPendingEvents,\n drainPendingMeshCoordinatorEvents,\n enqueueTask,\n extractLaunchPayload,\n extractStatusMetadataSessions,\n findNodeWithRefresh,\n findOptionalNodeWithRefresh,\n getActiveDirectDispatches,\n getQueue,\n getSessionMetadata,\n getWorktreeBootstrapLaunchBlock,\n hasRecentDuplicateDispatch,\n insertDirectDispatch,\n ipcDispatchToRemoteAgent,\n markStaleDirectDispatches,\n reconcileDirectDispatchesFromTranscriptEvidence,\n recordMeshToolCall,\n isIdleSessionRecord,\n isLocalControlPlaneNode,\n isMeshCoordinatorSessionRecord,\n isMeshOwnedDelegateSession,\n isP2pRelayTransportFailure,\n isTerminalSessionRecord,\n isUnmanagedSessionRecord,\n isWorkerTaskMode,\n meshSessionCacheKey,\n meshSessionProviderMetadata,\n missingProviderPriorityMessage,\n pruneStaleDirectDispatches,\n randomUUID,\n readLedgerEntries,\n readProviderPriority,\n readSessionRecordId,\n readSpawnedSessionVisibility,\n readString,\n recordDirectDispatchTask,\n recordRecoverableLaunchFailure,\n refreshMeshFromDaemon,\n resolveCoordinatorDaemonId,\n resolveCoordinatorNode,\n resolveAllowSendKeysDestructive,\n resolveDelegatedWorkerAutoApprove,\n resolveMeshSessionProviderMetadata,\n resolveSessionProviderType,\n triggerMeshQueueAndReport,\n unwrapCommandPayload,\n validateMeshTaskModeRequest,\n} from './mesh-tools-internal.js';\nimport type {\n MeshContext,\n} from './mesh-tools-internal.js';\nimport { normalizeNodeCapabilitySlots } from '@adhdev/mesh-shared';\n\n\n/**\n * Prune orphaned staleDirect dispatch records — direct dispatches whose original node/session is\n * no longer present in the live mesh (or terminal). dry_run (default) reports exactly which\n * taskIds would be pruned without mutating anything; pass execute=true to actually remove them.\n *\n * Safety:\n * - Only records classified as staleDirectWork by buildMeshActiveWork against the CURRENT live\n * mesh are eligible — active/pending/assigned/generating work is never in that set.\n * - Of those, only orphans (node/session gone) are pruned. Fresh unacknowledged dispatch\n * failures (staleDispatchUnacknowledged: node/session still live) are explicitly preserved and\n * reported under preservedUnacknowledged so the caller can recover them.\n * - Pruning deletes only the mesh_direct_dispatches store rows; the append-only mesh ledger\n * (audit history) is left intact, and a direct_dispatch_pruned ledger entry is appended on\n * execute so the prune itself is auditable.\n */\n/**\n * DISPATCH-ACK-RISK-STALE — compute the dispatch-acknowledgement risk fields for a\n * direct (mesh_send_task --session_id) dispatch to an idle session.\n *\n * Before the NOTIF-DROP / CANON-A fix, ANY dispatch to an idle session was flagged\n * `dispatchAcknowledgementRisk:true` because a fast completion could race ahead of the\n * dispatch row and be swallowed by the prior-terminal providerSessionId dedup gate\n * (mesh-event-forwarding.ts). Now that the dispatch row is atomically pre-recorded BEFORE\n * inject, a successful pre-record makes sessionHasActiveAssignment=TRUE at completion time,\n * so the dedup gate is skipped and the completion is delivered — there is NO residual loss\n * risk. The stale warning made coordinators do needless verification polling.\n *\n * Risk is therefore true ONLY when the session was idle AND the dispatch row did not\n * persist (pre-record failed / was rolled back) — the one case where the dedup gate can\n * still swallow the completion. Returns the fields to spread into the success response, or\n * an empty object when there is no risk to surface.\n */\nexport function computeIdleDispatchAckRisk(\n sessionWasIdle: boolean,\n dispatchPreRecorded: boolean,\n sessionId: string,\n): Record<string, unknown> {\n if (!sessionWasIdle || dispatchPreRecorded) return {};\n return {\n dispatchAcknowledgementRisk: true,\n dispatchAcknowledgementRiskReason: 'idle_dispatch_prerecord_failed',\n dispatchAcknowledgementNote: `Session '${sessionId}' was idle at dispatch time and the dispatch row could not be pre-recorded, so its completion may be deduplicated as a prior turn and lost. Use mesh_status to verify; if the session remains idle or the completion never lands, launch a fresh session and retry.`,\n };\n}\n\nexport async function meshPruneStaleDirect(\n ctx: MeshContext,\n args: { execute?: boolean; dry_run?: boolean; include_terminal?: boolean } = {},\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n // execute must be explicit; dry_run is the default unless execute===true.\n const execute = args.execute === true && args.dry_run !== true;\n const includeTerminal = args.include_terminal === true;\n\n const liveNodes = await collectMeshViewQueueNodesWithLiveSessions(ctx);\n const ledgerEntries = readLedgerEntries(ctx.mesh.id, { tail: 500 });\n const directDispatches = getActiveDirectDispatches(ctx.mesh.id);\n\n // Manual prune is immediate (minAgeMs omitted → 0). The same prune core powers the daemon\n // reconcile-loop auto-prune, which passes a conservative age gate. Keeping a single core\n // means the safety classification + audit-ledger behavior can never drift between the two.\n const result = pruneStaleDirectDispatches({\n meshId: ctx.mesh.id,\n queue: getQueue(ctx.mesh.id),\n ledgerEntries,\n directDispatches,\n nodes: liveNodes,\n execute,\n includeTerminal,\n source: 'mesh_prune_stale_direct',\n });\n\n const { prunable, prunedCount, preservedUnacknowledged, preservedLedgerOnly, preservedNotOrphan } = result;\n\n const summarize = (records: typeof prunable) => records.map(r => ({\n taskId: r.taskId,\n nodeId: r.nodeId,\n sessionId: r.sessionId,\n status: r.status,\n terminal: r.terminal === true,\n staleReason: r.staleReason,\n taskTitle: r.taskTitle,\n createdAt: r.createdAt,\n }));\n\n return JSON.stringify({\n success: true,\n mode: result.mode,\n meshId: ctx.mesh.id,\n includeTerminal,\n candidateCount: result.candidateCount,\n prunableCount: prunable.length,\n prunedCount,\n prunable: summarize(prunable),\n preserved: {\n unacknowledgedCount: preservedUnacknowledged.length,\n ledgerOnlyCount: preservedLedgerOnly.length,\n notOrphanCount: preservedNotOrphan.length,\n unacknowledged: summarize(preservedUnacknowledged),\n ledgerOnly: summarize(preservedLedgerOnly),\n notOrphan: summarize(preservedNotOrphan),\n },\n note: execute\n ? `Pruned ${prunedCount} orphaned direct dispatch record(s) from the active staleDirect surface. The append-only mesh ledger audit history is preserved; a direct_dispatch_pruned entry records this prune.`\n : 'Dry run — nothing was deleted. Re-run with execute=true to prune the listed orphaned records. Fresh unacknowledged dispatch failures (node/session still live) and ledger-only audit entries are always preserved.',\n }, null, 2);\n}\n\nexport async function meshSendTask(\n ctx: MeshContext,\n args: {\n node_id: string; session_id?: string; message: string;\n task_mode?: string; taskMode?: string;\n readonly?: boolean; read_only?: boolean;\n mission_id?: string; missionId?: string;\n },\n): Promise<string> {\n // DELIVERY-MSG-GUARD: make the schema's nominal `required: ['message']` real. The\n // tool dispatcher forwards raw args without runtime schema validation, so a caller\n // omitting message (or passing a non-string) would hand undefined down the direct-\n // dispatch path — buildDirectTaskPayload / recordDirectDispatchTask / createSessionDelivery —\n // and crash insertSessionDelivery's NOT NULL. Reject at the tool boundary.\n const message = readString(args.message);\n if (!message) {\n return JSON.stringify({\n success: false,\n code: 'invalid_message',\n error: 'mesh_send_task requires a non-empty string `message`.',\n });\n }\n const requestedTaskMode = readString(args.task_mode) || readString(args.taskMode);\n const readonly = args.readonly === true || args.read_only === true;\n // Optional mission attribution. When set, the direct-dispatched task is also\n // materialised as an assigned queue entry so it counts toward the mission's\n // task aggregates — see recordDirectDispatchTask. Absent → unattributed\n // direct dispatch as before (backward compatible).\n const missionId = readString(args.missionId) || readString(args.mission_id) || undefined;\n const modeValidation = validateMeshTaskModeRequest(requestedTaskMode, message, readonly);\n if (!modeValidation.valid) {\n return JSON.stringify({\n success: false,\n code: 'live_debug_readonly_guardrail_violation',\n taskMode: modeValidation.taskMode || requestedTaskMode,\n violations: modeValidation.violations,\n allowedOperations: modeValidation.allowedOperations,\n error: `live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`,\n });\n }\n const taskMode = modeValidation.taskMode;\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n // Policy check: read-only node cannot receive tasks\n if (node.policy?.readOnly) {\n return JSON.stringify({ error: `Node '${args.node_id}' is read-only` });\n }\n\n // WTDISPATCH-FANOUT: a `convergence` task lands its work onto base (merge → push →\n // cleanup) and is base-only. Refuse a direct dispatch that targets a worktree-clone\n // node, fail-closed — co-located sibling worktree sessions racing a convergence\n // push/production-deploy is exactly the 4-way fan-out the live repro hit. Mirrors the\n // queue claim guard (claimNextQueueTask) and the auto-launch eligibility filter so the\n // base-only invariant holds across every dispatch entry point.\n if (taskMode === 'convergence' && node.isLocalWorktree === true) {\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_convergence_target_is_worktree',\n reason: 'mesh_convergence_target_is_worktree',\n nodeId: args.node_id,\n sessionId: args.session_id,\n taskMode,\n error: `Node '${args.node_id}' is a worktree clone; a convergence task is base-only (it merges/pushes onto base). Dispatching it to a worktree session risks a multi-worktree push/deploy race.`,\n nextAction: `Dispatch the convergence task to the base node for this mesh, or run the deterministic fast-forward convergence path (mesh_fast_forward_node / mesh_refine_node) instead of mesh_send_task.`,\n });\n }\n\n let explicitTargetSession: any | undefined;\n if (args.session_id && isWorkerTaskMode(taskMode, readonly)) {\n try {\n const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {});\n const sessions = extractStatusMetadataSessions(statusResult);\n explicitTargetSession = sessions.find(session => readSessionRecordId(session) === args.session_id);\n if (explicitTargetSession && isMeshCoordinatorSessionRecord(explicitTargetSession)) {\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_target_session_is_coordinator',\n reason: 'mesh_target_session_is_coordinator',\n nodeId: args.node_id,\n sessionId: args.session_id,\n taskMode: taskMode || 'unspecified',\n error: `Session '${args.session_id}' is a Repo Mesh coordinator session, not a visible worker session. Launch or use a visible worker session before dispatching this task.`,\n nextAction: `Call mesh_launch_session for node '${args.node_id}' and then retry mesh_send_task with that worker session_id, or use mesh_enqueue_task for queue-based worker assignment.`,\n });\n }\n if (explicitTargetSession && isUnmanagedSessionRecord(explicitTargetSession)) {\n // Session exists but lacks mesh delegation metadata (no meshNodeFor,\n // meshCoordinatorFor, or launchedByCoordinator). It could be:\n // - The coordinator's own session → self-send risk\n // - A manually launched session not associated with this mesh\n // Completion events from this session would not reach the coordinator\n // ledger. Surface a hard warning but still record the dispatch attempt\n // in the result so the coordinator can decide whether to proceed.\n //\n // Note: if the session happens to have meshCoordinatorFor set, the check\n // above would have already returned mesh_target_session_is_coordinator.\n // This warning fires only for truly unmanaged sessions.\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_target_session_unmanaged',\n reason: 'mesh_target_session_unmanaged',\n nodeId: args.node_id,\n sessionId: args.session_id,\n taskMode: taskMode || 'unspecified',\n unsafeTranscriptAlias: true,\n error: `Session '${args.session_id}' on node '${args.node_id}' has no Repo Mesh delegation metadata (missing meshNodeFor/meshCoordinatorFor/launchedByCoordinator). It may be the coordinator's own session or an unrelated session — dispatching risks self-send and orphaned completion events that never reach the coordinator ledger.`,\n nextAction: `Call mesh_launch_session for node '${args.node_id}' to start a fresh managed worker session, then retry mesh_send_task with the returned session_id. Alternatively use mesh_enqueue_task for queue-based assignment without specifying session_id.`,\n });\n }\n } catch {\n explicitTargetSession = undefined;\n }\n }\n\n // Avoid duplicate side effects when an MCP/tool call is interrupted after\n // the daemon already accepted the send and the coordinator retries the\n // exact same node/session/message immediately.\n const duplicate = hasRecentDuplicateDispatch(ctx, args);\n if (duplicate.duplicate) {\n return JSON.stringify({\n success: true,\n duplicate: true,\n dispatched: false,\n warning: 'Duplicate mesh_send_task suppressed: the same node/session/message was dispatched recently.',\n nodeId: args.node_id,\n sessionId: args.session_id,\n source: duplicate.source,\n previousDispatch: duplicate.entry ? {\n id: duplicate.entry.id,\n timestamp: duplicate.entry.timestamp || duplicate.entry.updatedAt || duplicate.entry.createdAt,\n nodeId: duplicate.entry.nodeId || duplicate.entry.targetNodeId || duplicate.entry.assignedNodeId,\n sessionId: duplicate.entry.sessionId || duplicate.entry.targetSessionId || duplicate.entry.assignedSessionId,\n } : undefined,\n });\n }\n\n try {\n // ── IpcTransport + remote node: direct P2P agent_command dispatch ──────\n //\n // The local queue file (mesh-ledger/*.queue.json) is stored on THIS\n // machine and is inaccessible to the remote daemon. Sending\n // trigger_mesh_queue to the remote daemon would always be a no-op\n // because it cannot read the queue. Instead we relay agent_command\n // directly over P2P so the remote daemon forwards it to its agent.\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {\n const cached = getSessionMetadata(meshSessionCacheKey(args.node_id, args.session_id || ''));\n const taskId = randomUUID();\n const coordinatorDaemonId = resolveCoordinatorDaemonId(ctx);\n const result = await ipcDispatchToRemoteAgent(ctx, node, {\n session_id: args.session_id,\n message: message,\n providerType: cached?.providerType,\n verifiedSession: explicitTargetSession,\n meshContext: {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n taskId,\n ...(coordinatorDaemonId ? { coordinatorDaemonId } : {}),\n // (3) Stamp the originating coordinator session so the worker's completion\n // routes back to THIS coordinator session (multi-coordinator). Survives the\n // P2P dispatch to the remote worker, which echoes it on its completion event.\n ...(ctx.coordinatorSessionId ? { coordinatorSessionId: ctx.coordinatorSessionId } : {}),\n },\n });\n if (result.success) {\n // Record dispatch in ledger so task_history is accurate.\n // Defensive guard: a sessionless dispatch must not record the\n // provider type as a session id (an older ipcDispatch fallback\n // returned resolvedProviderType in result.sessionId). If the\n // returned sessionId equals the provider type, treat it as\n // sessionless so completion matching falls back to taskId.\n const resultSessionId = result.sessionId\n && result.providerType\n && result.sessionId === result.providerType\n ? ''\n : result.sessionId;\n const dispatchedSessionId = args.session_id || resultSessionId;\n const dispatchedAt = new Date().toISOString();\n try {\n const providerType = result.providerType || cached?.providerType;\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'task_dispatched',\n nodeId: args.node_id,\n sessionId: dispatchedSessionId,\n providerType,\n payload: buildDirectTaskPayload(message, 'p2p_direct', {\n taskId,\n taskMode,\n providerType,\n targetSessionId: dispatchedSessionId,\n ...(ctx.coordinatorSessionId ? { coordinatorSessionId: ctx.coordinatorSessionId } : {}),\n // COORD-EVENT-MISROUTE: persist the dispatching coordinator daemon anchor\n // (same value stamped into meshContext above) so a transcript-reconcile\n // synth recovers it instead of the worker's own self-daemon.\n ...(coordinatorDaemonId ? { coordinatorDaemonId } : {}),\n }),\n });\n insertDirectDispatch(ctx.mesh.id, {\n taskId,\n nodeId: args.node_id,\n sessionId: dispatchedSessionId,\n providerType: providerType || undefined,\n message: message,\n taskMode: taskMode || undefined,\n via: 'p2p_direct',\n dispatchedAt,\n });\n if (missionId) {\n recordDirectDispatchTask(ctx.mesh.id, message, {\n id: taskId,\n missionId,\n assignedNodeId: args.node_id,\n assignedSessionId: dispatchedSessionId,\n taskMode,\n ...(readonly ? { readonly: true } : {}),\n dispatchedAt,\n });\n }\n } catch { /* best-effort */ }\n }\n const returnedSessionId = result.sessionId\n && result.providerType\n && result.sessionId === result.providerType\n ? ''\n : result.sessionId;\n return JSON.stringify({\n ...result,\n nodeId: args.node_id,\n sessionId: result.success ? (args.session_id || returnedSessionId) : args.session_id,\n ...(result.success ? { source: 'direct', taskId } : {}),\n taskMode,\n ...(result.success && result.providerType ? { providerType: result.providerType } : {}),\n dispatched: result.success === true,\n });\n }\n\n // ── LocalTransport or local IpcTransport node ────────────────────────\n // If the coordinator explicitly targets a runtime session, push directly\n // and surface route failures immediately instead of creating a queue item\n // that can remain pending forever when the session was already stopped.\n if (args.session_id) {\n const cached = getSessionMetadata(meshSessionCacheKey(args.node_id, args.session_id));\n let resolvedProviderType = cached?.providerType || '';\n if (!resolvedProviderType) {\n let explicitSession = explicitTargetSession;\n if (!explicitSession) {\n const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {});\n const sessions = extractStatusMetadataSessions(statusResult);\n explicitSession = sessions.find(session => readSessionRecordId(session) === args.session_id);\n }\n if (!explicitSession) {\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_target_session_not_found',\n reason: 'mesh_target_session_not_found',\n transport: 'local_ipc',\n retryRecommended: true,\n nodeId: args.node_id,\n sessionId: args.session_id,\n error: `Local session '${args.session_id}' is not present in live status for node '${args.node_id}'.`,\n nextAction: `Launch a fresh session with mesh_launch_session(node_id: '${args.node_id}') or retry without session_id so Repo Mesh can target a live delegate session.`,\n });\n }\n // The early validation block only runs for isWorkerTaskMode (excludes\n // live_debug_readonly). Apply the same coordinator/unmanaged checks here\n // for sessions resolved in this path so no task mode bypasses them.\n if (isMeshCoordinatorSessionRecord(explicitSession)) {\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_target_session_is_coordinator',\n reason: 'mesh_target_session_is_coordinator',\n nodeId: args.node_id,\n sessionId: args.session_id,\n taskMode: taskMode || 'unspecified',\n error: `Session '${args.session_id}' is a Repo Mesh coordinator session, not a visible worker session. Launch or use a visible worker session before dispatching this task.`,\n nextAction: `Call mesh_launch_session for node '${args.node_id}' and then retry mesh_send_task with that worker session_id, or use mesh_enqueue_task for queue-based worker assignment.`,\n });\n }\n if (isUnmanagedSessionRecord(explicitSession)) {\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_target_session_unmanaged',\n reason: 'mesh_target_session_unmanaged',\n nodeId: args.node_id,\n sessionId: args.session_id,\n taskMode: taskMode || 'unspecified',\n unsafeTranscriptAlias: true,\n unsafeDelegateTarget: true,\n error: `Session '${args.session_id}' on node '${args.node_id}' has no Repo Mesh delegation metadata (missing meshNodeFor/meshCoordinatorFor/launchedByCoordinator). It may be the coordinator's own session or an unrelated session — dispatching risks self-send and orphaned completion events that never reach the coordinator ledger.`,\n nextAction: `Call mesh_launch_session for node '${args.node_id}' to start a fresh managed worker session, then retry mesh_send_task with the returned session_id. Alternatively use mesh_enqueue_task for queue-based assignment without specifying session_id.`,\n });\n }\n resolvedProviderType = resolveSessionProviderType(explicitSession);\n if (resolvedProviderType) {\n meshSessionProviderMetadata.set(meshSessionCacheKey(args.node_id, args.session_id), {\n providerType: resolvedProviderType,\n providerSessionId: readString(explicitSession?.providerSessionId) || undefined,\n expiresAt: Date.now() + SESSION_PROVIDER_METADATA_TTL_MS,\n });\n }\n }\n if (!resolvedProviderType) {\n return JSON.stringify({\n success: false,\n recoverable: true,\n code: 'mesh_target_session_provider_unknown',\n reason: 'mesh_target_session_provider_unknown',\n transport: 'local_ipc',\n retryRecommended: false,\n nodeId: args.node_id,\n sessionId: args.session_id,\n error: `Local session '${args.session_id}' is live but does not expose providerType/cliType, so agent_command cannot be routed safely.`,\n nextAction: `Relaunch the target session on node '${args.node_id}' or retry without session_id so Repo Mesh can pick a session with provider metadata.`,\n });\n }\n // Apply delivery policy: check session status and decide immediate vs queued vs rejected.\n // Busy/generating sessions must not receive immediate send_chat injection.\n if (explicitTargetSession && !isIdleSessionRecord(explicitTargetSession) && !isTerminalSessionRecord(explicitTargetSession)) {\n const sessionStatus = typeof explicitTargetSession?.status === 'string' ? explicitTargetSession.status : 'unknown';\n const { createSessionDelivery: createDelivery, resolveDeliveryDecision } = await import('@adhdev/daemon-core');\n const policyResult = resolveDeliveryDecision(sessionStatus, { kind: 'task' });\n if (policyResult.decision === 'queued') {\n const delivery = createDelivery({\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n sessionId: args.session_id,\n providerType: resolvedProviderType,\n kind: 'task',\n message: message,\n status: 'queued',\n });\n return JSON.stringify({\n success: true,\n dispatched: false,\n decision: 'queued_delivery',\n deliveryId: delivery.id,\n reason: policyResult.reason,\n nodeId: args.node_id,\n sessionId: args.session_id,\n sessionStatus,\n taskMode: taskMode || undefined,\n message: policyResult.message,\n nextAction: `Use mesh_status to watch for session idle transition, or use mesh_enqueue_task for queue-based assignment. Check deliveryId '${delivery.id}' to track queued delivery.`,\n });\n }\n }\n\n // Detect whether the session was idle at dispatch time. An idle session that\n // receives agent_command/send_chat should transition to generating. If it stays\n // idle, the dispatch was not acknowledged. Record this for stale detection and\n // surface it as a dispatchAcknowledgementRisk warning in the success response.\n const sessionWasIdle = explicitTargetSession\n ? isIdleSessionRecord(explicitTargetSession)\n : false;\n const taskId = randomUUID();\n const dispatchedAt = new Date().toISOString();\n const coordinatorDaemonId = resolveCoordinatorDaemonId(ctx);\n // CANON-A (direct-dispatch completion race — root fix): record the dispatch row\n // (task_dispatched ledger + insertDirectDispatch) ★BEFORE the agent_command inject,\n // exactly as the enqueue→claim path does (tryAssignQueueTask atomically claims the\n // queue row 'assigned' before deliverTaskToSession injects). A FAST direct dispatch to\n // an already-idle, reused session could otherwise have its genuine completion reach the\n // coordinator forwarder BEFORE this row existed → sessionHasActiveAssignment=false → the\n // prior-terminal providerSessionId dedup (mesh-event-forwarding.ts:551,603) swallowed the\n // new task's completion as a duplicate of the prior turn. Pre-recording makes\n // sessionHasActiveAssignment=true at completion time, so the dedup gate is skipped\n // symmetrically with enqueue. On a dispatch failure below we roll the row back.\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'task_dispatched',\n nodeId: args.node_id,\n sessionId: args.session_id,\n providerType: resolvedProviderType,\n payload: buildDirectTaskPayload(message, 'local_direct', {\n taskId,\n taskMode,\n providerType: resolvedProviderType,\n targetSessionId: args.session_id,\n dispatchedToIdleSession: sessionWasIdle,\n ...(ctx.coordinatorSessionId ? { coordinatorSessionId: ctx.coordinatorSessionId } : {}),\n // COORD-EVENT-MISROUTE: persist the dispatching coordinator daemon anchor so a\n // transcript-reconcile synth recovers it from the ledger rather than stamping\n // the reconcile-runner's own self-daemon.\n ...(coordinatorDaemonId ? { coordinatorDaemonId } : {}),\n }),\n });\n } catch { /* best-effort */ }\n // DISPATCH-ACK-RISK-STALE: track whether the dispatch row was atomically\n // pre-recorded. When it lands, sessionHasActiveAssignment becomes TRUE at\n // completion time, so the prior-terminal dedup gate (mesh-event-forwarding.ts:551)\n // is skipped and the idle-session completion WILL be delivered — i.e. there is no\n // residual loss risk. The risk warning below must reflect THIS, not merely that the\n // session was idle. A genuine residual risk remains only if the pre-record did not\n // persist a row to gate on.\n insertDirectDispatch(ctx.mesh.id, {\n taskId,\n nodeId: args.node_id,\n sessionId: args.session_id,\n providerType: resolvedProviderType || undefined,\n message: message,\n taskMode: taskMode || undefined,\n via: 'local_direct',\n dispatchedToIdleSession: sessionWasIdle,\n dispatchedAt,\n });\n // insertDirectDispatch swallows its own persistence errors (it never throws),\n // so we cannot infer success from the absence of an exception. Verify the row\n // actually exists — this is the exact predicate sessionHasActiveAssignment keys\n // on, so it is the true signal of whether the dedup gate will be skipped.\n let dispatchPreRecorded = false;\n try {\n dispatchPreRecorded = getActiveDirectDispatches(ctx.mesh.id).some(d => d.taskId === taskId);\n } catch { /* read failed — treat as not-recorded → keep the conservative warning */ }\n // Stamp the mesh assignment via meshContext so the daemon can\n // attach it to the target instance BEFORE prompt injection.\n // setupMeshEventForwarding reads state.settings.meshNodeFor +\n // meshActiveTaskId to route completion events back. Without\n // this, plain CLI sessions targeted by mesh_send_task --direct\n // would silently drop generating_completed and the coordinator\n // would never observe task_completed.\n // coordinatorDaemonId is required so the completion event is\n // routed to the correct coordinator pendingCoordinatorEvents queue.\n const dispatchResult = await commandForNode(ctx, node, 'agent_command', {\n targetSessionId: args.session_id,\n agentType: resolvedProviderType,\n cliType: resolvedProviderType,\n providerType: resolvedProviderType,\n action: 'send_chat',\n message: message,\n meshContext: {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n taskId,\n ...(coordinatorDaemonId ? { coordinatorDaemonId } : {}),\n // (3) Originating coordinator session anchor — see the remote-dispatch path above.\n ...(ctx.coordinatorSessionId ? { coordinatorSessionId: ctx.coordinatorSessionId } : {}),\n },\n });\n const dispatchPayload = unwrapCommandPayload(dispatchResult);\n if (dispatchPayload?.success === false || dispatchResult?.success === false) {\n // Roll back the pre-recorded dispatch row: the inject was rejected, so there is no\n // active assignment to gate. The task_dispatched ledger entry stays (append-only),\n // but the dispatch row is the discriminator sessionHasActiveAssignment keys on —\n // leaving it would mask a genuinely-unrelated later idle as an active assignment.\n try { deleteDirectDispatchesByTaskId(ctx.mesh.id, [taskId]); } catch { /* best-effort */ }\n dispatchPreRecorded = false;\n const source = dispatchPayload?.success === false ? dispatchPayload : dispatchResult;\n return JSON.stringify({\n ...(source && typeof source === 'object' ? source : {}),\n success: false,\n nodeId: args.node_id,\n sessionId: args.session_id,\n error: dispatchPayload?.error || dispatchResult?.error || 'agent_command rejected the task',\n });\n }\n if (missionId) {\n try {\n recordDirectDispatchTask(ctx.mesh.id, message, {\n id: taskId,\n missionId,\n assignedNodeId: args.node_id,\n assignedSessionId: args.session_id,\n taskMode,\n ...(readonly ? { readonly: true } : {}),\n dispatchedAt,\n });\n } catch { /* best-effort */ }\n }\n // Create a delivery record for session-level ACK tracking\n let deliveryId: string | undefined;\n try {\n const { createSessionDelivery: createDelivery } = await import('@adhdev/daemon-core');\n const delivery = createDelivery({\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n sessionId: args.session_id,\n providerType: resolvedProviderType || undefined,\n taskId,\n kind: 'task',\n message: message,\n status: sessionWasIdle ? 'delivered' : 'delivering',\n });\n deliveryId = delivery.id;\n } catch { /* best-effort */ }\n return JSON.stringify({\n success: true,\n dispatched: true,\n decision: 'immediate',\n source: 'direct',\n taskId,\n deliveryId,\n taskMode,\n providerType: resolvedProviderType,\n nodeId: args.node_id,\n sessionId: args.session_id,\n // DISPATCH-ACK-RISK-STALE: only warn on a GENUINE residual loss risk — an idle\n // session whose dispatch row did NOT survive pre-record. A successfully\n // pre-recorded idle dispatch (the NOTIF-DROP / CANON-A path) is not at risk.\n ...computeIdleDispatchAckRisk(sessionWasIdle, dispatchPreRecorded, args.session_id),\n });\n }\n\n // ── Untargeted local task: use queue pull ─────────────────────────────\n // COORD-EVENT-MISROUTE (anchor preservation): stamp the originating coordinator\n // SESSION anchor exactly as the sibling meshEnqueueTask does (mesh-tools-queue.ts).\n // Without it the queued task carries no sourceCoordinatorSessionId, so at claim time\n // targetCoordinatorSessionId is empty (mesh-queue-assignment.ts) and the completion\n // loses its session anchor — falling back to daemon-level fan-out across every local\n // coordinator instead of routing back to the coordinator session that issued the task.\n const task = enqueueTask(ctx.mesh.id, message, {\n targetNodeId: args.node_id,\n targetSessionId: args.session_id,\n taskMode,\n ...(readonly ? { readonly: true } : {}),\n ...(missionId ? { missionId } : {}),\n ...(ctx.coordinatorSessionId ? { sourceCoordinatorSessionId: ctx.coordinatorSessionId } : {}),\n });\n\n const queueTrigger = await triggerMeshQueueAndReport(ctx);\n\n // Also drain any pending coordinator events so the caller sees them inline\n const pendingEvents = drainPendingMeshCoordinatorEvents(ctx.mesh.id, ctx.localDaemonId);\n\n const result: Record<string, unknown> = {\n success: true,\n source: 'queue',\n nodeId: args.node_id,\n taskId: task.id,\n status: task.status,\n taskMode: task.taskMode,\n queueTrigger,\n ...buildQueueTriggerGuidance(queueTrigger),\n };\n if (pendingEvents.length > 0) {\n result.pendingCoordinatorEvents = pendingEvents;\n }\n return JSON.stringify(result);\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'mesh_send_task',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n sessionId: args.session_id,\n });\n return JSON.stringify(failure);\n }\n}\n\nexport async function meshReadChat(\n ctx: MeshContext,\n args: { node_id: string; session_id: string; provider_session_id?: string; tail?: number; compact?: boolean },\n): Promise<string> {\n const node = await findOptionalNodeWithRefresh(ctx, args.node_id);\n if (!node) {\n return JSON.stringify(buildMissingNodeReadChatRecovery(ctx, args), null, 2);\n }\n\n await drainCoordinatorPendingEvents(ctx, { nodeIds: [args.node_id] });\n\n const cached = resolveMeshSessionProviderMetadata(ctx, args.node_id, args.session_id);\n const providerSessionId = typeof args.provider_session_id === 'string' && args.provider_session_id.trim()\n ? args.provider_session_id.trim()\n : cached?.providerSessionId;\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n let result: any;\n try {\n result = await commandForNode(ctx, node, 'read_chat', {\n sessionId: args.session_id,\n targetSessionId: args.session_id,\n workspace: node.workspace,\n ...(cached?.providerType ? { agentType: cached.providerType, providerType: cached.providerType } : {}),\n ...(providerSessionId ? { providerSessionId } : {}),\n tailLimit: args.tail ?? 10,\n });\n } catch (e: any) {\n // Local read_chat and non-transport (provider/logic) failures keep the existing\n // throw so genuine errors still surface. The cache fallback covers ONLY a remote\n // P2P transport failure (saturated/unreachable peer): mesh_status already degrades\n // its P2P probe gracefully (collectLiveStatusProbe) — read_chat had no catch and\n // hard-failed at the 30s timeout instead of surfacing the coordinator's cached\n // summary. See buildMeshReadChatCacheFallback.\n if (isLocalNode || !isP2pRelayTransportFailure(e)) throw e;\n return buildMeshReadChatCacheFallback(ctx, args, node, e);\n }\n const payload = annotateRapidReadChatAdvisory(unwrapCommandPayload(result) as Record<string, any>, {\n key: `mesh:${args.node_id}:${args.session_id}`,\n toolName: 'mesh_read_chat',\n completionCallbackExpected: true,\n });\n // Default compact=true to keep coordinator context lean.\n // Pass compact=false explicitly only when full transcript detail is needed for debugging.\n const useCompact = args.compact !== false;\n if (useCompact) {\n const compactPayload = compactChatPayload(payload, {\n nodeId: args.node_id,\n sessionId: args.session_id,\n limit: args.tail ?? 10,\n });\n return JSON.stringify(\n payload.pollingAdvisory ? { ...compactPayload, pollingAdvisory: payload.pollingAdvisory } : compactPayload,\n null,\n 2,\n );\n }\n return JSON.stringify(payload, null, 2);\n}\n\nexport async function meshReadDebug(\n ctx: MeshContext,\n args: { node_id: string; session_id: string; provider_session_id?: string; tail?: number; delivery?: 'daemon_file' | 'inline' },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n const cached = resolveMeshSessionProviderMetadata(ctx, args.node_id, args.session_id);\n const providerSessionId = typeof args.provider_session_id === 'string' && args.provider_session_id.trim()\n ? args.provider_session_id.trim()\n : cached?.providerSessionId;\n const delivery = args.delivery === 'inline' ? undefined : 'daemon_file';\n const result = await commandForNode(ctx, node, 'get_chat_debug_bundle', {\n sessionId: args.session_id,\n targetSessionId: args.session_id,\n workspace: node.workspace,\n ...(cached?.providerType ? { agentType: cached.providerType, providerType: cached.providerType } : {}),\n ...(providerSessionId ? { providerSessionId } : {}),\n tailLimit: args.tail ?? 40,\n ...(delivery ? { delivery } : {}),\n });\n const payload = unwrapCommandPayload(result);\n return JSON.stringify(payload, null, 2);\n}\n\n/**\n * MESH-READ-TERMINAL (feature 2: RAW terminal read). Read the CURRENT rendered\n * PTY viewport (live screen) of a delegated worker session on a mesh node.\n *\n * OWNERSHIP DOUBLE-CHECK (defense-in-depth, per mission 6938892f class):\n * 1. MCP side (here): resolve the session record from the node's live session\n * list and require isMeshOwnedDelegateSession(session, meshId, nodeId) —\n * mesh/session/node identity must match, so a cross-mesh or coordinator-own\n * session id cannot be read.\n * 2. daemon side (read_terminal → getTerminalScreenSnapshot): gated on\n * isMeshWorkerSession(). isMeshWorkerSession alone is a broad \"delegated\"\n * gate, so the MCP-side identity match is what blocks cross-mesh access.\n *\n * The read_terminal daemon verb is in MESH_FORWARDABLE_SESSION_COMMANDS, so when\n * the worker is a REMOTE node the coordinator's daemon forwards it to the owning\n * worker daemon (which holds the live viewport) instead of returning\n * 'Session not found'.\n */\nexport async function meshReadTerminal(\n ctx: MeshContext,\n args: { node_id: string; session_id: string; max_bytes?: number },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n // OWNERSHIP DOUBLE-CHECK (MCP side): the session must be a mesh-owned delegate\n // of THIS mesh + node. Resolve it from the node's live session list; a miss or\n // a non-owned/ cross-mesh record is refused before any command is issued.\n const liveSessions = await collectLiveStatusSessions(ctx, node);\n const record = liveSessions.find((s) => readSessionRecordId(s) === args.session_id);\n if (record && !isMeshOwnedDelegateSession(record, ctx.mesh.id, args.node_id)) {\n return JSON.stringify({\n success: false,\n error: 'session is not a mesh-owned delegate of this mesh/node — mesh_read_terminal is scoped to sessions this coordinator spawned',\n nodeId: args.node_id,\n sessionId: args.session_id,\n }, null, 2);\n }\n\n const cached = resolveMeshSessionProviderMetadata(ctx, args.node_id, args.session_id);\n const result = await commandForNode(ctx, node, 'read_terminal', {\n sessionId: args.session_id,\n targetSessionId: args.session_id,\n workspace: node.workspace,\n ...(cached?.providerType ? { agentType: cached.providerType, providerType: cached.providerType } : {}),\n ...(typeof args.max_bytes === 'number' && Number.isFinite(args.max_bytes) ? { maxBytes: args.max_bytes } : {}),\n });\n const payload = unwrapCommandPayload(result);\n return JSON.stringify(payload, null, 2);\n}\n\nconst MESH_SEND_KEYS_DESTRUCTIVE = new Set(['CTRL_C', 'ESC']);\n\n/**\n * MESH-SEND-KEYS (feature 3: key injection). Inject a structured key sequence into\n * a delegated worker session's live PTY.\n *\n * OWNERSHIP DOUBLE-CHECK (per mission 6938892f class, same as mesh_read_terminal):\n * 1. MCP side (here): the session must be isMeshOwnedDelegateSession of THIS\n * mesh + node — blocks cross-mesh / coordinator-own PTY writes.\n * 2. daemon side (send_keys → injectKeys): gated on isMeshWorkerSession().\n *\n * DESTRUCTIVE DOUBLE GATE (owner-approved): CTRL_C/ESC require BOTH\n * confirm_destructive=true (per-call) AND mesh/node policy allowSendKeysDestructive\n * (opt-in). delegatedWorkerAutoApprove does NOT grant this — it is tool-consent,\n * not PTY-input authority, so a Ctrl-C could otherwise bypass it and kill the\n * worker.\n *\n * The daemon layer independently enforces the submit-race recheck and the\n * actionable-modal fail-closed refusal. Every attempt is AUDITED to the ledger\n * (key enums + result), NEVER the literal text body.\n *\n * send_keys is in MESH_FORWARDABLE_SESSION_COMMANDS so a remote-worker target is\n * forwarded to the owning daemon (which holds the live PTY).\n */\nexport async function meshSendKeys(\n ctx: MeshContext,\n args: {\n node_id: string;\n session_id: string;\n sequence: Array<{ text?: string; key?: string }>;\n confirm_destructive?: boolean;\n allow_modal_override?: boolean;\n },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n const items = Array.isArray(args.sequence) ? args.sequence : [];\n if (items.length === 0) {\n return JSON.stringify({ success: false, error: 'sequence (non-empty array of {text}|{key}) required' }, null, 2);\n }\n\n // OWNERSHIP DOUBLE-CHECK (MCP side): resolve the session from the node's live\n // session list; refuse a non-owned / cross-mesh record before writing anything.\n const liveSessions = await collectLiveStatusSessions(ctx, node);\n const record = liveSessions.find((s) => readSessionRecordId(s) === args.session_id);\n if (record && !isMeshOwnedDelegateSession(record, ctx.mesh.id, args.node_id)) {\n return JSON.stringify({\n success: false,\n error: 'session is not a mesh-owned delegate of this mesh/node — mesh_send_keys is scoped to sessions this coordinator spawned',\n nodeId: args.node_id,\n sessionId: args.session_id,\n }, null, 2);\n }\n\n // DESTRUCTIVE DOUBLE GATE.\n const requestedKeys = items\n .map((it) => (it && typeof it.key === 'string' ? it.key : ''))\n .filter(Boolean);\n const hasDestructive = requestedKeys.some((k) => MESH_SEND_KEYS_DESTRUCTIVE.has(k));\n const auditKeys = requestedKeys.slice(0, 64);\n const recordAudit = (result: string, extra: Record<string, unknown> = {}) => {\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'key_injection',\n nodeId: args.node_id,\n sessionId: args.session_id,\n payload: {\n keys: auditKeys, // key ENUMS only — never the literal text body\n hasDestructive,\n confirmDestructive: args.confirm_destructive === true,\n result,\n ...extra,\n },\n });\n } catch { /* ledger append is best-effort */ }\n };\n\n if (hasDestructive) {\n const policyAllows = resolveAllowSendKeysDestructive(ctx.mesh.policy, node.policy);\n if (args.confirm_destructive !== true || !policyAllows) {\n recordAudit('refused', { refused: 'destructive_gate', policyAllows });\n return JSON.stringify({\n success: false,\n error: 'destructive key (CTRL_C/ESC) requires BOTH confirm_destructive=true AND mesh policy allowSendKeysDestructive=true',\n refused: 'destructive_gate',\n confirmDestructive: args.confirm_destructive === true,\n policyAllowsDestructive: policyAllows,\n }, null, 2);\n }\n }\n\n const cached = resolveMeshSessionProviderMetadata(ctx, args.node_id, args.session_id);\n const result = await commandForNode(ctx, node, 'send_keys', {\n sessionId: args.session_id,\n targetSessionId: args.session_id,\n workspace: node.workspace,\n ...(cached?.providerType ? { agentType: cached.providerType, providerType: cached.providerType } : {}),\n sequence: items,\n confirm_destructive: args.confirm_destructive === true,\n allow_modal_override: args.allow_modal_override === true,\n });\n const payload = unwrapCommandPayload(result) as Record<string, unknown>;\n // Audit the daemon's verdict (injected / refused). The daemon result carries no\n // literal text either, so it is safe to reflect keys/result here.\n if (payload?.success === true) {\n recordAudit('injected', { submits: payload.submits === true });\n } else {\n recordAudit('refused', { refused: readString(payload?.refused) || 'error' });\n }\n return JSON.stringify(payload, null, 2);\n}\n\nexport async function meshLaunchSession(\n ctx: MeshContext,\n args: { node_id: string; type?: string; force?: boolean },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n const bootstrapBlock = getWorktreeBootstrapLaunchBlock(node, ctx.mesh.policy);\n if (bootstrapBlock) return JSON.stringify(bootstrapBlock, null, 2);\n\n {\n const requestedType = typeof args.type === 'string' && args.type.trim() ? args.type.trim() : '';\n let resolvedProviderType = requestedType;\n if (requestedType) {\n // PROVIDER-TYPE-HONORED: an explicit type is validated ONLY against the node's\n // capability slots (policy.slots) — the single authoritative capability list\n // (ORCHESTRATION_NODE_SLOTS.md). When the node declares slots and none names the\n // requested provider, fail closed instead of proceeding: silently resolving to\n // providerPriority[0] was the exact bug (mesh_launch_session(type:\"cursor-cli\")\n // spawned claude-cli). providerPriority is deliberately NOT consulted here — it is\n // an ordered PREFERENCE hint, not a capability whitelist, so a legacy node that\n // declares only providerPriority (no slots) keeps the pre-existing contract that an\n // explicit type may name any provider (the daemon-side launch is the real gate).\n // Provider names are compared raw — slots store canonical provider types.\n const slotProviders = normalizeNodeCapabilitySlots((node.policy as any)?.slots).map(s => s.provider);\n if (slotProviders.length && !slotProviders.includes(requestedType)) {\n return JSON.stringify({\n success: false,\n code: 'mesh_provider_type_unsupported',\n error: `Node '${args.node_id}' does not support provider '${requestedType}'. Its capability slots (policy.slots) declare: ${slotProviders.join(', ')}. Configure a slot for '${requestedType}' via mesh_node_slots_set, or launch with one of the supported types.`,\n nodeId: args.node_id,\n requestedType,\n supportedProviders: slotProviders,\n }, null, 2);\n }\n }\n if (!resolvedProviderType) {\n const providerPriority = readProviderPriority(node.policy);\n if (!providerPriority.length) {\n return JSON.stringify({ success: false, error: missingProviderPriorityMessage(args.node_id) });\n }\n\n // OFFLINE-NODE-BLOCKING: probe each candidate provider until one is detected. Two\n // guards keep an OFFLINE target node from serializing a ~90s × providers stall\n // (~270s for a 3-provider priority list):\n // (a) `detect_provider` is read-only, so stamp it with the status-origin marker\n // ({ statusProbe: true }) — the daemon-cloud relay then grants the SHORT\n // connect-wait budget so a probe to an unconnected peer gives up in ~2s\n // instead of the 90s connect deadline.\n // (b) short-circuit on the FIRST transport-level failure. A per-provider\n // \"not detected\" comes back as a RESOLVED { detected: false } payload (try\n // the next provider); a THROW means the node itself is unreachable (peer not\n // connected / offline / relay timeout) — every remaining provider would fail\n // identically, so break immediately and fail fast with a node-unreachable error.\n const failed: string[] = [];\n let unreachableError: string | null = null;\n for (const providerType of providerPriority) {\n let detectedPayload: any;\n try {\n const detectedResult = await commandForNode(ctx, node, 'detect_provider', { providerType }, { statusProbe: true });\n detectedPayload = unwrapCommandPayload(detectedResult);\n } catch (e: any) {\n // Transport/connection failure: the node is unreachable, not the provider\n // missing. Stop probing the rest of the priority list.\n unreachableError = e?.message || String(e);\n break;\n }\n if (detectedPayload?.success && detectedPayload?.detected) {\n resolvedProviderType = providerType;\n break;\n }\n failed.push(`${providerType}: ${detectedPayload?.error || 'not detected'}`);\n }\n if (!resolvedProviderType) {\n if (unreachableError) {\n return JSON.stringify({ success: false, error: `Node '${args.node_id}' is unreachable — cannot detect a provider (${unreachableError}). The node's daemon may be offline; retry once it reconnects.` });\n }\n return JSON.stringify({ success: false, error: `No usable provider detected for node '${args.node_id}' from providerPriority: ${failed.join('; ')}` });\n }\n }\n\n const coordinatorNode = resolveCoordinatorNode(ctx);\n const coordinatorDaemonId = resolveCoordinatorDaemonId(ctx);\n const spawnedSessionVisibility = readSpawnedSessionVisibility(ctx.mesh.policy);\n // Worker sessions are coordinator-dispatched; a human shouldn't have to approve\n // each one. Resolve the auto-approve policy (node override → mesh policy → default\n // true) and stamp it into the launch settings envelope so it wins over the global\n // per-provider-type autoApprove config via the settingsOverride merge.\n const delegatedWorkerAutoApprove = resolveDelegatedWorkerAutoApprove(ctx.mesh.policy, node.policy);\n const isLocalNode = isLocalControlPlaneNode(ctx, node);\n if (node.daemonId && !isLocalNode && !coordinatorDaemonId) {\n return JSON.stringify(buildMissingCoordinatorDaemonIdFailure(ctx, node, resolvedProviderType), null, 2);\n }\n\n // MESH-LAUNCH-DUP-GUARD: an enqueue auto-launch (queue task → daemon spawns a worker)\n // races a manual mesh_launch_session for the same node/worktree. Without this guard the\n // manual call unconditionally issues a second launch_cli, leaving an empty duplicate\n // worker session alongside the one doing the work (\"채팅 2개\"). Right before launch, probe\n // live status and, if a non-terminal mesh-owned worker session for THIS mesh+node already\n // exists (idle OR still booting/generating), return it idempotently instead of spawning a\n // duplicate. force=true bypasses the guard for a deliberate additional session. Placed\n // AFTER provider resolution + the coordinator-id fail-closed check so an unlaunchable node\n // never burns a status relay (and the relay-blocked invariant holds).\n if (args.force !== true) {\n try {\n const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {});\n const sessions = extractStatusMetadataSessions(statusResult);\n // PROVIDER-MISMATCH-REUSE: only reuse a live session whose provider matches the\n // resolved request. Without this the guard returned ANY non-terminal mesh-owned\n // session — so mesh_launch_session(type:\"claude-cli\", force=false) against a node\n // with an idle antigravity worker handed back the antigravity session (and the\n // subsequent mesh_send_task ran the task on the wrong provider). Only enforce when\n // a concrete provider was requested/resolved (resolvedProviderType truthy); an\n // unconstrained launch keeps the original \"reuse any idle worker\" behaviour, and a\n // definite mismatch (both sides known and unequal) falls through to a fresh launch.\n // force=true still bypasses the whole guard above.\n const existing = sessions.find(session => {\n if (isTerminalSessionRecord(session)) return false;\n if (!isMeshOwnedDelegateSession(session, ctx.mesh.id, args.node_id)) return false;\n if (resolvedProviderType) {\n const sessionProviderType = resolveSessionProviderType(session);\n if (sessionProviderType && sessionProviderType !== resolvedProviderType) return false;\n }\n return true;\n });\n if (existing) {\n const existingSessionId = readSessionRecordId(existing);\n if (existingSessionId) {\n const existingProviderType = resolveSessionProviderType(existing) || resolvedProviderType || undefined;\n const existingStatus = typeof existing?.status === 'string' ? existing.status : 'unknown';\n return JSON.stringify({\n success: true,\n duplicate: true,\n launched: false,\n reused: true,\n sessionId: existingSessionId,\n nodeId: args.node_id,\n ...(existingProviderType ? { resolvedProviderType: existingProviderType, providerType: existingProviderType } : {}),\n sessionStatus: existingStatus,\n idle: isIdleSessionRecord(existing),\n reason: 'mesh_launch_session_duplicate_guard',\n warning: `Node '${args.node_id}' already has a live mesh-owned worker session ('${existingSessionId}', status '${existingStatus}'). Returning it instead of launching an empty duplicate (likely an enqueue auto-launch already spawned it).`,\n nextAction: `Use session '${existingSessionId}' for mesh_send_task/mesh_read_chat. If you intentionally need a second concurrent session on this node, retry mesh_launch_session with force=true.`,\n }, null, 2);\n }\n }\n } catch {\n // Status probe failed (transport/timeout). Fail open — proceed to launch rather\n // than blocking a legitimate launch on an unreachable status probe. A duplicate is\n // recoverable (mesh_cleanup_sessions); a blocked launch on a transient probe error\n // is worse for the coordinator flow.\n }\n }\n\n let result: any;\n try {\n result = await commandForNode(ctx, node, 'launch_cli', {\n cliType: resolvedProviderType,\n dir: node.workspace,\n settings: {\n // Worker launch envelope (A5): structured metadata so worker sessions\n // know their role and can route completion events back correctly.\n role: 'worker',\n meshNodeFor: ctx.mesh.id,\n meshNodeId: args.node_id,\n spawnedSessionVisibility,\n // Delegated worker auto-approval (see resolveDelegatedWorkerAutoApprove).\n // Lands in settingsOverride and beats the global per-provider autoApprove.\n autoApprove: delegatedWorkerAutoApprove,\n ...(coordinatorDaemonId ? { meshCoordinatorDaemonId: coordinatorDaemonId } : {}),\n // (3) Stamp the originating coordinator SESSION at launch too, so a worker\n // launched via mesh_launch_session routes its completions back to the exact\n // coordinator session (multi-coordinator). Absent → daemon-level fallback.\n ...(ctx.coordinatorSessionId ? { meshCoordinatorSessionId: ctx.coordinatorSessionId } : {}),\n ...(coordinatorNode?.id ? { meshCoordinatorNodeId: coordinatorNode.id } : {}),\n launchedByCoordinator: true,\n }\n });\n } catch (e: any) {\n return JSON.stringify(recordRecoverableLaunchFailure(ctx, node, resolvedProviderType, e), null, 2);\n }\n const launchPayload = extractLaunchPayload(result);\n if (launchPayload?.success === false || result?.success === false) {\n const launchError = new Error(launchPayload?.error || result?.error || 'launch_cli rejected the session launch');\n return JSON.stringify(recordRecoverableLaunchFailure(ctx, node, resolvedProviderType, launchError), null, 2);\n }\n const runtimeSessionId = typeof launchPayload?.sessionId === 'string'\n ? launchPayload.sessionId\n : typeof launchPayload?.id === 'string'\n ? launchPayload.id\n : typeof launchPayload?.runtimeSessionId === 'string'\n ? launchPayload.runtimeSessionId\n : '';\n const providerSessionId = typeof launchPayload?.providerSessionId === 'string' && launchPayload.providerSessionId.trim()\n ? launchPayload.providerSessionId.trim()\n : undefined;\n if (runtimeSessionId) {\n meshSessionProviderMetadata.set(meshSessionCacheKey(args.node_id, runtimeSessionId), {\n providerType: resolvedProviderType,\n ...(providerSessionId ? { providerSessionId } : {}),\n expiresAt: Date.now() + SESSION_PROVIDER_METADATA_TTL_MS,\n });\n }\n // Record session launch in ledger\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'session_launched',\n nodeId: args.node_id,\n sessionId: runtimeSessionId || undefined,\n providerType: resolvedProviderType,\n payload: { providerSessionId },\n });\n } catch { /* ledger append is best-effort */ }\n\n // Tell daemon to trigger queue processing so the new session immediately picks up pending tasks.\n // Surface the trigger result so coordinators can distinguish \"session launched\"\n // from \"queued work actually claimed by that session\".\n const queueTrigger = await triggerMeshQueueAndReport(ctx);\n\n return JSON.stringify({\n ...launchPayload,\n resolvedProviderType,\n ...(providerSessionId ? { providerSessionId } : {}),\n queueTrigger,\n ...buildQueueTriggerGuidance(queueTrigger),\n }, null, 2);\n }\n}\n\nexport async function meshApprove(\n ctx: MeshContext,\n args: { node_id: string; session_id: string; action: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id); // membership check\n\n const cached = getSessionMetadata(meshSessionCacheKey(args.node_id, args.session_id));\n const providerSessionId = cached?.providerSessionId;\n const result = await commandForNode(ctx, node, 'resolve_action', {\n sessionId: args.session_id,\n targetSessionId: args.session_id,\n workspace: node.workspace,\n ...(cached?.providerType ? { agentType: cached.providerType, providerType: cached.providerType } : {}),\n ...(providerSessionId ? { providerSessionId } : {}),\n action: args.action === 'reject' ? 'reject' : 'approve',\n });\n return JSON.stringify(result, null, 2);\n}\n\n/**\n * mesh_list_pending_approvals — read-only mesh-wide approval inbox.\n *\n * mesh_approve resolves a SINGLE (node_id, session_id) action; before this tool there was\n * no way to enumerate which sessions are currently blocked awaiting an approval decision —\n * the coordinator had to page mesh_status and eyeball each node's sessions. This lists every\n * session in `awaiting_approval` across the mesh so a coordinator (or the UI approvals inbox)\n * can see the full pending set and drive a follow-up mesh_approve for each.\n *\n * No new store or DB: it reuses the exact derivation mesh_status/mesh_view_queue already run\n * (buildMeshActiveWork over the live-session-decorated nodes + queue + ledger + direct\n * dispatches), then filters to `status === 'awaiting_approval'` via collectPendingApprovals.\n * Read-only — probes node status but mutates no approval/session state.\n */\nexport async function meshListPendingApprovals(\n ctx: MeshContext,\n _args: Record<string, unknown> = {},\n): Promise<string> {\n recordMeshToolCall({ meshId: ctx.mesh.id, tool: 'mesh_list_pending_approvals' });\n await refreshMeshFromDaemon(ctx);\n\n const liveNodes = await collectMeshViewQueueNodesWithLiveSessions(ctx);\n let ledgerEntries = readLedgerEntries(ctx.mesh.id, { tail: 200 });\n let directDispatches = getActiveDirectDispatches(ctx.mesh.id);\n const directReconciliation = await reconcileDirectDispatchesFromTranscriptEvidence(ctx, liveNodes, directDispatches, ledgerEntries);\n if (directReconciliation.reconciled > 0) {\n ledgerEntries = readLedgerEntries(ctx.mesh.id, { tail: 200 });\n directDispatches = getActiveDirectDispatches(ctx.mesh.id);\n }\n markStaleDirectDispatches(ctx.mesh.id);\n directDispatches = getActiveDirectDispatches(ctx.mesh.id);\n\n const activeWorkEvidence = buildMeshActiveWork({\n meshId: ctx.mesh.id,\n queue: getQueue(ctx.mesh.id),\n ledgerEntries,\n directDispatches,\n nodes: liveNodes,\n });\n\n const approvals = collectPendingApprovals(activeWorkEvidence.activeWork);\n\n return JSON.stringify({\n count: approvals.length,\n approvals,\n ...(approvals.length === 0\n ? { note: 'No sessions are currently awaiting an approval decision.' }\n : { nextStep: 'Resolve each with mesh_approve(node_id, session_id, action: \"approve\" | \"reject\").' }),\n }, null, 2);\n}\n\nexport async function meshCleanupSessions(\n ctx: MeshContext,\n args: { node_id: string; mode: string; session_ids?: string[]; dry_run?: boolean },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n const result = await commandForNode(ctx, node, 'cleanup_mesh_sessions', {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n mode: args.mode,\n sessionIds: args.session_ids,\n dryRun: args.dry_run === true,\n inlineMesh: ctx.mesh,\n });\n return JSON.stringify(result, null, 2);\n}\n","// Mesh tool implementations — git domain.\n// Pure move out of mesh-tools.ts (no behavior change). Shared helpers, types, module\n// state and dependency re-exports live in ./mesh-tools-internal.ts; mesh-tools.ts is a barrel.\n\nimport {\n IpcTransport,\n appendLedgerEntry,\n buildCoordinatorP2pRelayFailure,\n buildRemoveNodeArgs,\n collectRelatedRepoStatuses,\n commandForNode,\n extractCloneNodePayload,\n extractGitDiff,\n extractGitStatus,\n extractSubmodules,\n findNodeWithRefresh,\n isP2pTransportUnavailableError,\n refreshMeshFromDaemon,\n syncCoordinatorDaemonMeshCache,\n unwrapCommandPayload,\n} from './mesh-tools-internal.js';\nimport type {\n MeshContext,\n} from './mesh-tools-internal.js';\n\nexport async function meshGitStatus(\n ctx: MeshContext,\n args: { node_id: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n // Determine submodule options from node policy\n const autoDiscoverSubmodules = (node.policy as any)?.autoDiscoverSubmodules !== false;\n const submoduleIgnorePaths = (node.policy as any)?.submoduleIgnorePaths || [];\n\n try {\n const statusResult = await commandForNode(ctx, node, 'git_status', {\n workspace: node.workspace,\n refreshUpstream: true,\n includeSubmodules: autoDiscoverSubmodules,\n submoduleIgnorePaths: submoduleIgnorePaths.length > 0 ? submoduleIgnorePaths : undefined,\n });\n const diffResult = await commandForNode(ctx, node, 'git_diff_summary', {\n workspace: node.workspace,\n });\n return JSON.stringify({\n nodeId: args.node_id,\n workspace: node.workspace,\n status: extractGitStatus(statusResult),\n diff: extractGitDiff(diffResult),\n submodules: autoDiscoverSubmodules ? extractSubmodules(statusResult, submoduleIgnorePaths) : undefined,\n relatedRepos: await collectRelatedRepoStatuses(ctx, node),\n }, null, 2);\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'git_status',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n });\n return JSON.stringify({\n ...failure,\n workspace: node.workspace,\n }, null, 2);\n }\n}\n\nexport async function meshReadNodeLogs(\n ctx: MeshContext,\n args: { node_id: string; grep?: string; since_ms?: number; tail_bytes?: number; date?: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n try {\n const result = await commandForNode(ctx, node, 'get_mesh_node_logs', {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n ...(typeof args.grep === 'string' && args.grep.trim() ? { grep: args.grep.trim() } : {}),\n ...(Number.isFinite(args.since_ms) ? { sinceMs: args.since_ms } : {}),\n ...(Number.isFinite(args.tail_bytes) ? { tailBytes: args.tail_bytes } : {}),\n ...(typeof args.date === 'string' && args.date.trim() ? { date: args.date.trim() } : {}),\n });\n const payload = unwrapCommandPayload(result);\n return JSON.stringify(payload, null, 2);\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'get_mesh_node_logs',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n });\n return JSON.stringify(failure, null, 2);\n }\n}\n\nexport async function meshFastForwardNode(\n ctx: MeshContext,\n args: { node_id: string; mode?: 'merge' | 'push'; branch?: string; execute?: boolean; dry_run?: boolean; update_submodules?: boolean; push_submodules?: boolean },\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const node = await findNodeWithRefresh(ctx, args.node_id);\n const submoduleIgnorePaths = (node.policy as any)?.submoduleIgnorePaths || [];\n\n if (node.policy?.readOnly) {\n return JSON.stringify({\n success: false,\n code: 'node_read_only',\n nodeId: args.node_id,\n workspace: node.workspace,\n allowed: false,\n willRun: false,\n executed: false,\n blockingReasons: ['node_read_only'],\n }, null, 2);\n }\n\n try {\n const dryRun = args.dry_run === true || args.execute !== true;\n const result = await commandForNode(ctx, node, 'fast_forward_mesh_node', {\n meshId: ctx.mesh.id,\n nodeId: node.id,\n workspace: node.workspace,\n mode: args.mode === 'push' ? 'push' : 'merge',\n branch: typeof args.branch === 'string' ? args.branch : undefined,\n execute: args.execute === true && args.dry_run !== true,\n dryRun,\n updateSubmodules: args.update_submodules === true,\n pushSubmodules: args.push_submodules === true,\n submoduleIgnorePaths: submoduleIgnorePaths.length > 0 ? submoduleIgnorePaths : undefined,\n });\n return JSON.stringify(unwrapCommandPayload(result), null, 2);\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'fast_forward_mesh_node',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n });\n return JSON.stringify({\n ...failure,\n workspace: node.workspace,\n allowed: false,\n willRun: false,\n executed: false,\n blockingReasons: [failure.code || 'mesh_fast_forward_unavailable'],\n }, null, 2);\n }\n}\n\nexport async function meshRestartDaemon(\n ctx: MeshContext,\n args: { node_id: string; channel?: 'stable' | 'preview' },\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n try {\n // inlineMesh lets the owning daemon resolve this node for the\n // remote-forward guard; channel is forwarded only when explicitly set so\n // an unset call keeps the daemon on its configured channel.\n const result = await commandForNode(ctx, node, 'restart_daemon_node', {\n meshId: ctx.mesh.id,\n nodeId: node.id,\n inlineMesh: ctx.mesh,\n ...(args.channel ? { channel: args.channel } : {}),\n });\n return JSON.stringify(unwrapCommandPayload(result), null, 2);\n } catch (e: any) {\n const failure = buildCoordinatorP2pRelayFailure(e, {\n command: 'restart_daemon_node',\n targetDaemonId: node.daemonId,\n nodeId: args.node_id,\n });\n return JSON.stringify(failure, null, 2);\n }\n}\n\nexport async function meshCheckpoint(\n ctx: MeshContext,\n args: { node_id: string; message: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n // Policy checks\n if (node.policy?.readOnly) {\n return JSON.stringify({ error: `Node '${args.node_id}' is read-only — cannot checkpoint` });\n }\n\n const result = await commandForNode(ctx, node, 'git_checkpoint', {\n workspace: node.workspace,\n message: args.message,\n includeUntracked: true,\n });\n\n // Record checkpoint in ledger\n try {\n appendLedgerEntry(ctx.mesh.id, {\n kind: 'checkpoint_created',\n nodeId: args.node_id,\n payload: {\n message: args.message,\n commit: (result as any)?.checkpoint?.commit,\n outcome: (result as any)?.checkpoint?.status || ((result as any)?.checkpoint?.noop ? 'skipped' : undefined),\n noop: (result as any)?.checkpoint?.noop === true,\n reason: (result as any)?.checkpoint?.reason,\n },\n });\n } catch { /* ledger append is best-effort */ }\n\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshCloneNode(\n ctx: MeshContext,\n args: { source_node_id: string; branch: string; base_branch?: string },\n): Promise<string> {\n const sourceNode = await findNodeWithRefresh(ctx, args.source_node_id);\n\n const result = await commandForNode(ctx, sourceNode, 'clone_mesh_node', {\n meshId: ctx.mesh.id,\n sourceNodeId: args.source_node_id,\n branch: args.branch,\n baseBranch: args.base_branch,\n inlineMesh: ctx.mesh,\n });\n const clonePayload = extractCloneNodePayload(result);\n if (clonePayload?.success && clonePayload.node?.id) {\n const existingIndex = ctx.mesh.nodes.findIndex(n => n.id === clonePayload.node.id);\n if (existingIndex >= 0) ctx.mesh.nodes[existingIndex] = clonePayload.node;\n else ctx.mesh.nodes.push(clonePayload.node);\n ctx.mesh.updatedAt = new Date().toISOString();\n await syncCoordinatorDaemonMeshCache(ctx);\n }\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshRemoveNode(\n ctx: MeshContext,\n args: { node_id: string; session_cleanup_mode?: string; force?: boolean },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n const removeArgs = buildRemoveNodeArgs(ctx, args.node_id, args.session_cleanup_mode, args.force === true);\n let result: any;\n let transportFallback: Record<string, unknown> | undefined;\n try {\n result = await commandForNode(ctx, node, 'remove_mesh_node', removeArgs);\n } catch (e: any) {\n if (ctx.transport instanceof IpcTransport && (node as any).isLocalWorktree && isP2pTransportUnavailableError(e)) {\n result = await ctx.transport.command('remove_mesh_node', removeArgs);\n transportFallback = {\n from: 'p2p_mesh_relay',\n to: 'local_control_plane',\n reason: e?.message || String(e),\n };\n } else {\n return JSON.stringify({\n success: false,\n code: isP2pTransportUnavailableError(e) ? 'p2p_unavailable' : 'mesh_remove_node_failed',\n error: e?.message || String(e),\n recoveryHint: isP2pTransportUnavailableError(e)\n ? 'If this is an ADHDev-managed local worktree, retry from a coordinator connected to the daemon that owns the worktree; dashboard command/data-plane traffic still requires P2P.'\n : 'Inspect mesh_status and retry after resolving the reported failure.',\n }, null, 2);\n }\n }\n if (result?.success && result.removed !== false) {\n const idx = ctx.mesh.nodes.findIndex(n => n.id === args.node_id);\n if (idx >= 0) {\n ctx.mesh.nodes.splice(idx, 1);\n ctx.mesh.updatedAt = new Date().toISOString();\n }\n }\n return JSON.stringify({ ...(result || {}), ...(transportFallback ? { transportFallback } : {}) }, null, 2);\n}\n","// Mesh tool implementations — refine domain.\n// Pure move out of mesh-tools.ts (no behavior change). Shared helpers, types, module\n// state and dependency re-exports live in ./mesh-tools-internal.ts; mesh-tools.ts is a barrel.\n\nimport {\n commandForNode,\n findNodeWithRefresh,\n refreshMeshFromDaemon,\n resolveRefineConfigNode,\n unwrapCommandPayload,\n} from './mesh-tools-internal.js';\nimport type {\n MeshContext,\n} from './mesh-tools-internal.js';\n\nexport async function meshRefineConfigSchema(ctx: MeshContext): Promise<string> {\n const node = resolveRefineConfigNode(ctx);\n const result = await commandForNode(ctx, node, 'get_mesh_refine_config_schema', {});\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshValidateRefineConfig(\n ctx: MeshContext,\n args: { node_id?: string; config?: Record<string, unknown> },\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'validate_mesh_refine_config', {\n workspace: node.workspace,\n inlineMesh: ctx.mesh,\n ...(args.config ? { config: args.config } : {}),\n });\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshSuggestRefineConfig(\n ctx: MeshContext,\n args: { node_id?: string },\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'suggest_mesh_refine_config', {\n workspace: node.workspace,\n inlineMesh: ctx.mesh,\n });\n return JSON.stringify(result, null, 2);\n}\n\n/**\n * Unified read-only Refinery config helper (MESH-COMPLEXITY-AUDIT Part 8-4).\n * Dispatches on `mode` to the three underlying config operations, each a thin wrapper\n * over its daemon-core low-family refine-config command — internal command API unchanged,\n * zero behavior loss. The former standalone tools (mesh_refine_config_schema /\n * mesh_validate_refine_config / mesh_suggest_refine_config) remain dispatchable as\n * 1-release hidden aliases that forward here with the corresponding mode (see server.ts).\n */\nexport async function meshRefineConfig(\n ctx: MeshContext,\n args: { mode?: string; node_id?: string; config?: Record<string, unknown> } = {},\n): Promise<string> {\n switch (args.mode) {\n case 'schema':\n return meshRefineConfigSchema(ctx);\n case 'validate':\n return meshValidateRefineConfig(ctx, args);\n case 'suggest':\n return meshSuggestRefineConfig(ctx, args);\n default:\n throw new Error(\n `mesh_refine_config: invalid or missing 'mode' (${JSON.stringify(args.mode)}). Expected one of: 'schema' | 'validate' | 'suggest'.`,\n );\n }\n}\n\nexport async function meshChangeImpactConfigSchema(ctx: MeshContext): Promise<string> {\n const node = resolveRefineConfigNode(ctx);\n const result = await commandForNode(ctx, node, 'get_mesh_change_impact_config_schema', {});\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshValidateChangeImpactConfig(\n ctx: MeshContext,\n args: { node_id?: string; config?: Record<string, unknown> },\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'validate_mesh_change_impact_config', {\n workspace: node.workspace,\n ...(args.config ? { config: args.config } : {}),\n });\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshSuggestChangeImpactConfig(\n ctx: MeshContext,\n args: { node_id?: string },\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'suggest_mesh_change_impact_config', {\n workspace: node.workspace,\n });\n return JSON.stringify(result, null, 2);\n}\n\n/**\n * Unified read-only Change Impact config helper (MESH-COMPLEXITY-AUDIT, symmetric to Part 8-4).\n * Dispatches on `mode` to the three underlying change-impact config operations, each a thin\n * wrapper over its daemon-core low-family change-impact command — internal command API\n * unchanged, zero behavior loss. The former standalone tools (mesh_change_impact_config_schema /\n * mesh_validate_change_impact_config / mesh_suggest_change_impact_config) remain dispatchable as\n * 1-release hidden aliases that forward here with the corresponding mode (see server.ts).\n */\nexport async function meshChangeImpactConfig(\n ctx: MeshContext,\n args: { mode?: string; node_id?: string; config?: Record<string, unknown> } = {},\n): Promise<string> {\n switch (args.mode) {\n case 'schema':\n return meshChangeImpactConfigSchema(ctx);\n case 'validate':\n return meshValidateChangeImpactConfig(ctx, args);\n case 'suggest':\n return meshSuggestChangeImpactConfig(ctx, args);\n default:\n throw new Error(\n `mesh_change_impact_config: invalid or missing 'mode' (${JSON.stringify(args.mode)}). Expected one of: 'schema' | 'validate' | 'suggest'.`,\n );\n }\n}\n\nexport async function meshInit(\n ctx: MeshContext,\n args: { node_id?: string; write?: boolean; overwrite?: boolean },\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'mesh_init', {\n workspace: node.workspace,\n inlineMesh: ctx.mesh,\n ...(args.write !== undefined ? { write: args.write } : {}),\n ...(args.overwrite !== undefined ? { overwrite: args.overwrite } : {}),\n });\n return JSON.stringify(result, null, 2);\n}\n\n/**\n * Re-onboarding of an already-initialized repo. This is NOT a separate write engine\n * — it reuses mesh_init's suggest→validate→gated-write engine with OVERWRITE\n * semantics, plus the current-vs-suggested config echo (result.currentConfig) so the\n * coordinator can present a per-section diff before replacing anything.\n *\n * CONTRACT — reinit must NOT silently drop operator hand-edits: overwrite=true is a\n * wholesale replacement of the existing config, so the coordinator MUST load the\n * current config (returned here in `currentConfig`), present a per-section\n * current-vs-suggested diff, and get EXPLICIT per-section user approval before the\n * write. The default is DRY-RUN (write=false): the first reinit call is a preview\n * that surfaces the diff; only after approval does the coordinator re-invoke with\n * write=true. `overwrite` defaults to true here (that is the whole point of reinit —\n * unlike init, an existing config is the expected case), but with write=false it\n * still writes nothing.\n */\nexport async function meshReinit(\n ctx: MeshContext,\n args: { node_id?: string; write?: boolean; overwrite?: boolean },\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n // overwrite defaults to true for reinit (an existing config is expected); callers\n // can still pass overwrite=false to fall back to existing-wins. write defaults to\n // false (dry-run preview surfacing the diff) exactly like mesh_init.\n const overwrite = args.overwrite !== false;\n const result = await commandForNode(ctx, node, 'mesh_init', {\n workspace: node.workspace,\n inlineMesh: ctx.mesh,\n ...(args.write !== undefined ? { write: args.write } : {}),\n overwrite,\n });\n // Annotate the mode so the coordinator reads this as a reinit (diff-then-approve)\n // rather than a fresh init, without inventing a second write engine.\n const annotated = (result && typeof result === 'object')\n ? {\n ...result,\n mode: 'reinit',\n reinitContract: 'Overwrite replaces existing config wholesale. Present the per-section current-vs-suggested diff (see currentConfig) and get EXPLICIT per-section user approval before re-invoking with write=true. Never silently drop operator hand-edits.',\n }\n : result;\n return JSON.stringify(annotated, null, 2);\n}\n\n/**\n * Write `.adhdev/mesh.json` (the repo-committed coordinator prompt + declarative\n * config) from the machine-local mesh entry. Gated WRITE sibling of the draft-only\n * export_mesh_json_config — forwards to the daemon `write_mesh_json_config` command\n * which enforces the same write/overwrite/dry-run contract as mesh_init (dry-run\n * default, existing-wins unless overwrite=true, validate before write). REPO-COMMITTED\n * scope. Resolves the workspace via the same node resolver as mesh_init (non-optional).\n */\nexport async function meshWriteMeshJsonConfig(\n ctx: MeshContext,\n args: { node_id?: string; write?: boolean; overwrite?: boolean; workspace?: string } = {},\n): Promise<string> {\n const node = resolveRefineConfigNode(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'write_mesh_json_config', {\n meshId: ctx.mesh.id,\n workspace: (typeof args.workspace === 'string' && args.workspace.trim()) ? args.workspace.trim() : node.workspace,\n ...(args.write !== undefined ? { write: args.write } : {}),\n ...(args.overwrite !== undefined ? { overwrite: args.overwrite } : {}),\n });\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshRefinePlan(\n ctx: MeshContext,\n args: { node_id: string },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n const result = await commandForNode(ctx, node, 'plan_mesh_refine_node', {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n inlineMesh: ctx.mesh,\n });\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshRefineNode(\n ctx: MeshContext,\n args: { node_id: string; execute?: boolean; dry_run?: boolean },\n): Promise<string> {\n const node = await findNodeWithRefresh(ctx, args.node_id);\n\n const result = await commandForNode(ctx, node, 'refine_mesh_node', {\n meshId: ctx.mesh.id,\n nodeId: args.node_id,\n ...(args.execute !== undefined ? { execute: args.execute } : {}),\n ...(args.dry_run !== undefined ? { dryRun: args.dry_run } : {}),\n inlineMesh: ctx.mesh,\n });\n if (result?.success && result.async !== true && result.removeResult?.removed !== false) {\n const idx = ctx.mesh.nodes.findIndex(n => n.id === args.node_id);\n if (idx >= 0) {\n ctx.mesh.nodes.splice(idx, 1);\n ctx.mesh.updatedAt = new Date().toISOString();\n }\n }\n return JSON.stringify(result, null, 2);\n}\n\nexport async function meshRefineBatch(\n ctx: MeshContext,\n args: { node_ids?: string[]; execute?: boolean; dry_run?: boolean } = {},\n): Promise<string> {\n // Refresh so auto-collection and explicit node IDs resolve against the latest\n // mesh membership (siblings may have been created/removed in this MCP session).\n await refreshMeshFromDaemon(ctx);\n const nodeIds = Array.isArray(args.node_ids)\n ? args.node_ids.filter((v): v is string => typeof v === 'string' && v.trim().length > 0).map(v => v.trim())\n : undefined;\n\n // The batch orchestrator runs on the coordinator daemon that owns the source repo\n // and worktrees. Drive it through the local control-plane transport (the same\n // daemon that hosts these worktree nodes), passing inlineMesh so inline-cache-only\n // clone nodes resolve.\n const result = await ctx.transport.command('batch_refine_mesh_nodes', {\n meshId: ctx.mesh.id,\n ...(nodeIds ? { nodeIds } : {}),\n ...(args.execute !== undefined ? { execute: args.execute } : {}),\n ...(args.dry_run !== undefined ? { dryRun: args.dry_run } : {}),\n inlineMesh: ctx.mesh,\n });\n\n // On a successful synchronous execute, prune merged/skipped nodes from the local\n // mesh snapshot so subsequent tool calls don't re-target already-converged worktrees.\n // The execute path is now async (async:true / status:'accepted') — per-node results\n // arrive later via terminal refine events, so there is nothing to prune yet. Only the\n // legacy/synchronous batch result (with inline `results`) is pruned here.\n const payload = unwrapCommandPayload(result) ?? result;\n if (payload?.batch && payload?.dryRun === false && payload?.async !== true && Array.isArray(payload?.results)) {\n for (const outcome of payload.results) {\n if (outcome?.convergence === 'merged_to_main' || outcome?.convergence === 'skipped_patch_equivalent') {\n const idx = ctx.mesh.nodes.findIndex(n => n.id === outcome.nodeId);\n if (idx >= 0) ctx.mesh.nodes.splice(idx, 1);\n }\n }\n ctx.mesh.updatedAt = new Date().toISOString();\n }\n return JSON.stringify(result, null, 2);\n}\n","import { ALL_MESH_TOOLS } from './tools/mesh-tools.js';\n\nconst STANDARD_TOOLS = [\n 'list_daemons',\n 'list_sessions',\n 'launch_session',\n 'stop_session',\n 'check_pending',\n 'read_chat',\n 'read_chat_debug',\n 'send_chat',\n 'approve',\n 'git_status',\n 'git_log',\n 'git_diff',\n 'git_checkpoint',\n 'git_push',\n 'screenshot',\n];\n\nexport function buildMcpHelpText(): string {\n const meshTools = ALL_MESH_TOOLS.map(tool => tool.name);\n return `\nADHDev MCP Server\n\nUsage:\n adhdev mcp Local mode (requires standalone daemon)\n adhdev mcp --mode ipc --repo-mesh <mesh_id> Cloud daemon IPC mesh mode\n adhdev-mcp --help Compatibility bin (same server, legacy package entrypoint)\n\nOptions:\n --mode <mode> Transport: local or ipc\n --port <n> Standalone or IPC daemon port (defaults: local 3847, ipc 19222)\n --password <pass> Standalone daemon password (if set)\n --repo-mesh <mesh_id> Enable mesh mode — exposes only mesh-scoped coordinator tools\n --help Show this help\n\nEnvironment variables:\n ADHDEV_PASSWORD Daemon password (local mode)\n ADHDEV_MESH_ID Mesh ID (mesh mode)\n ADHDEV_MCP_TRANSPORT Transport: local or ipc\n\nStandard tools: ${STANDARD_TOOLS.join(', ')}\nMesh tools: ${meshTools.join(', ')}\n`.trim();\n}\n","/**\n * ADHDev MCP Server\n *\n * Exposes IDE agent sessions as MCP tools via stdio transport.\n * Two modes:\n * local — talks to standalone daemon at localhost:3847\n * ipc — talks to cloud daemon local IPC at localhost:19222\n */\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport os from 'node:os';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { LocalTransport } from './transports/local.js';\nimport { IpcTransport } from './transports/ipc.js';\nimport type { CommandTransport } from './transports/mode.js';\n\nimport { LIST_SESSIONS_TOOL, listSessions } from './tools/list-sessions.js';\nimport { LIST_DAEMONS_TOOL, listDaemons } from './tools/list-daemons.js';\nimport { READ_CHAT_TOOL, readChat } from './tools/read-chat.js';\nimport { READ_CHAT_DEBUG_TOOL, readChatDebug } from './tools/read-chat-debug.js';\nimport { SPEC_DEBUG_TOOL, specDebug } from './tools/spec-debug.js';\nimport { SEND_CHAT_TOOL, sendChat } from './tools/send-chat.js';\nimport { APPROVE_TOOL, approve } from './tools/approve.js';\nimport { SCREENSHOT_TOOL, screenshot } from './tools/screenshot.js';\nimport { GIT_STATUS_TOOL, gitStatus } from './tools/git-status.js';\nimport { GIT_LOG_TOOL, gitLog } from './tools/git-log.js';\nimport { GIT_DIFF_TOOL, gitDiff } from './tools/git-diff.js';\nimport { GIT_CHECKPOINT_TOOL, gitCheckpoint } from './tools/git-checkpoint.js';\nimport { GIT_PUSH_TOOL, gitPush } from './tools/git-push.js';\nimport { LAUNCH_SESSION_TOOL, launchSession } from './tools/launch-session.js';\nimport { STOP_SESSION_TOOL, stopSession } from './tools/stop-session.js';\nimport { CHECK_PENDING_TOOL, checkPending } from './tools/check-pending.js';\nimport {\n ALL_MESH_TOOLS, meshStatus, meshListNodes, meshSendTask, meshReadChat,\n meshEnqueueTask, meshViewQueue, meshQueueCancel, meshQueueRequeue,\n meshReadDebug, meshReadTerminal, meshSendKeys,\n meshLaunchSession, meshGitStatus, meshReadNodeLogs, meshFastForwardNode, meshRestartDaemon, meshCheckpoint, meshApprove, meshListPendingApprovals,\n meshCloneNode, meshRemoveNode, meshRefineNode,\n meshRefineConfig, meshInit, meshReinit, meshRefinePlan, meshRefineBatch,\n meshChangeImpactConfig,\n meshCleanupSessions, meshPruneStaleDirect, meshTaskHistory, meshLedgerQuery, meshRecordNote, meshForgetNote, meshReconcileLedger, meshRequeueHeldEvents, meshMissionUpsert,\n meshMissionList, meshReviewInbox,\n meshMagiReview, meshMagiCollect,\n meshMagiKindPanelSet, meshMagiKindPanelList, meshWriteMeshJsonConfig,\n meshNodeSlotsSet, meshNodeSlotsList\n} from './tools/mesh-tools.js';\nimport type { MeshContext } from './tools/mesh-tools.js';\n\nexport interface AdhdevMcpServerOptions {\n mode: 'local' | 'ipc';\n // local options\n port?: number;\n password?: string;\n // mesh mode (optional — restricts tools to mesh-scoped set)\n meshId?: string;\n}\n\nexport async function buildMeshModeCoordinatorPrompt(mesh: any): Promise<string> {\n try {\n const { buildCoordinatorSystemPrompt } = await import('@adhdev/daemon-core');\n return buildCoordinatorSystemPrompt({ mesh });\n } catch (e: any) {\n throw new Error(`Failed to build Repo Mesh coordinator prompt: ${e?.message ?? String(e)}`);\n }\n}\n\nexport async function startMcpServer(opts: AdhdevMcpServerOptions): Promise<void> {\n const transport: CommandTransport =\n opts.mode === 'ipc'\n ? new IpcTransport({ port: opts.port })\n : new LocalTransport({ port: opts.port, password: opts.password });\n\n // Verify connectivity before registering tools\n const alive = await transport.ping();\n if (!alive) {\n const hint =\n opts.mode === 'local'\n ? `Make sure the standalone daemon is running (adhdev standalone or npx @adhdev/daemon-standalone).`\n : `Make sure the cloud daemon is running with local IPC enabled (adhdev daemon).`;\n process.stderr.write(`[adhdev-mcp] Cannot reach ${opts.mode} daemon. ${hint}\\n`);\n process.exit(1);\n }\n\n const isLocal = opts.mode === 'local';\n\n // ── Mesh Mode ─────────────────────────────────\n if (opts.meshId) {\n let mesh: any;\n\n // Priority 1: ADHDEV_INLINE_MESH env var (set by daemon in .mcp.json for cloud meshes)\n if (!mesh && process.env.ADHDEV_INLINE_MESH) {\n try {\n mesh = JSON.parse(process.env.ADHDEV_INLINE_MESH);\n process.stderr.write(`[adhdev-mcp] Loaded mesh config from ADHDEV_INLINE_MESH env\\n`);\n } catch (e: any) {\n process.stderr.write(`[adhdev-mcp] Failed to parse ADHDEV_INLINE_MESH: ${e.message}\\n`);\n }\n }\n\n // Priority 2: Local ~/.adhdev/meshes.json\n if (!mesh) {\n try {\n const { getMesh } = await import('@adhdev/daemon-core');\n mesh = getMesh(opts.meshId);\n } catch (e: any) {\n process.stderr.write(`[adhdev-mcp] Local meshes.json lookup failed: ${e.message}\\n`);\n }\n }\n\n // Fallback: query the running daemon (supports cloud-originating meshes\n // launched via inlineMesh that don't exist in local meshes.json)\n if (!mesh && (transport instanceof LocalTransport || transport instanceof IpcTransport)) {\n try {\n const result = await transport.command('get_mesh', { meshId: opts.meshId });\n if (result?.success && result.mesh) {\n mesh = result.mesh;\n process.stderr.write(`[adhdev-mcp] Loaded mesh config from daemon\\n`);\n }\n } catch (e: any) {\n process.stderr.write(`[adhdev-mcp] Daemon mesh query failed: ${e.message}\\n`);\n }\n }\n\n if (!mesh) {\n process.stderr.write(`[adhdev-mcp] Mesh '${opts.meshId}' not found in local config. Use 'adhdev mesh list' to see available meshes.\\n`);\n process.exit(1);\n }\n\n let localDaemonId: string | undefined;\n let localMachineId: string | undefined;\n let coordinatorHostname: string | undefined = os.hostname();\n\n if (transport instanceof LocalTransport || transport instanceof IpcTransport) {\n try {\n const { loadConfig } = await import('@adhdev/daemon-core');\n const cfg = loadConfig();\n if (cfg.machineId) localMachineId = cfg.machineId;\n else if (cfg.registeredMachineId) localMachineId = cfg.registeredMachineId;\n } catch { /* best-effort */ }\n }\n\n if (transport instanceof IpcTransport) {\n try {\n const statusResult = await transport.getStatus();\n const instanceId = typeof statusResult?.status?.instanceId === 'string' ? statusResult.status.instanceId.trim() : '';\n const hostname = typeof statusResult?.status?.hostname === 'string'\n ? statusResult.status.hostname.trim()\n : typeof statusResult?.status?.machine?.hostname === 'string'\n ? statusResult.status.machine.hostname.trim()\n : '';\n if (instanceId) localDaemonId = instanceId;\n if (hostname) coordinatorHostname = hostname;\n } catch { /* best-effort metadata for remote completion forwarding */ }\n }\n\n // (3) Session-anchored routing: the daemon injects this coordinator CLI session's own\n // runtime id via ADHDEV_COORDINATOR_SESSION_ID at launch. Carrying it on MeshContext lets\n // every dispatch stamp the originating coordinator session so the worker's completion\n // routes back to the right session (multi-coordinator). Absent → daemon-level fallback.\n const coordinatorSessionId = typeof process.env.ADHDEV_COORDINATOR_SESSION_ID === 'string' && process.env.ADHDEV_COORDINATOR_SESSION_ID.trim()\n ? process.env.ADHDEV_COORDINATOR_SESSION_ID.trim()\n : undefined;\n\n const meshCtx: MeshContext = { mesh, transport, ...(localDaemonId ? { localDaemonId } : {}), ...(localMachineId ? { localMachineId } : {}), ...(coordinatorHostname ? { coordinatorHostname } : {}), ...(coordinatorSessionId ? { coordinatorSessionId } : {}) };\n\n const coordinatorPrompt = await buildMeshModeCoordinatorPrompt(mesh);\n\n const server = new Server(\n { name: 'adhdev-mcp-server', version: '0.9.82' },\n { capabilities: { tools: {}, resources: {} } },\n );\n\n // Expose coordinator prompt as MCP resource\n const { ListResourcesRequestSchema, ReadResourceRequestSchema } = await import('@modelcontextprotocol/sdk/types.js');\n server.setRequestHandler(ListResourcesRequestSchema, async () => ({\n resources: [{\n uri: 'coordinator://system-prompt',\n name: 'Coordinator System Prompt',\n description: `System prompt for mesh \"${mesh.name}\" coordinator`,\n mimeType: 'text/plain',\n }],\n }));\n server.setRequestHandler(ReadResourceRequestSchema, async (req) => {\n if (req.params.uri === 'coordinator://system-prompt') {\n return { contents: [{ uri: req.params.uri, mimeType: 'text/plain', text: coordinatorPrompt }] };\n }\n throw new Error(`Unknown resource: ${req.params.uri}`);\n });\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: ALL_MESH_TOOLS }));\n\n server.setRequestHandler(CallToolRequestSchema, async (req) => {\n const { name, arguments: args } = req.params;\n const a = (args ?? {}) as Record<string, any>;\n try {\n let text: string;\n switch (name) {\n case 'mesh_status': text = await meshStatus(meshCtx, a as any); break;\n case 'mesh_list_nodes': text = await meshListNodes(meshCtx); break;\n case 'mesh_enqueue_task': text = await meshEnqueueTask(meshCtx, a as any); break;\n case 'mesh_view_queue': text = await meshViewQueue(meshCtx, a as any); break;\n case 'mesh_queue_cancel': text = await meshQueueCancel(meshCtx, a as any); break;\n case 'mesh_queue_requeue': text = await meshQueueRequeue(meshCtx, a as any); break;\n case 'mesh_send_task': text = await meshSendTask(meshCtx, a as any); break;\n case 'mesh_read_chat': text = await meshReadChat(meshCtx, a as any); break;\n case 'mesh_read_debug': text = await meshReadDebug(meshCtx, a as any); break;\n case 'mesh_read_terminal': text = await meshReadTerminal(meshCtx, a as any); break;\n case 'mesh_send_keys': text = await meshSendKeys(meshCtx, a as any); break;\n case 'mesh_launch_session': text = await meshLaunchSession(meshCtx, a as any); break;\n case 'mesh_git_status': text = await meshGitStatus(meshCtx, a as any); break;\n case 'mesh_read_node_logs': text = await meshReadNodeLogs(meshCtx, a as any); break;\n case 'mesh_fast_forward_node': text = await meshFastForwardNode(meshCtx, a as any); break;\n case 'mesh_restart_daemon': text = await meshRestartDaemon(meshCtx, a as any); break;\n case 'mesh_checkpoint': text = await meshCheckpoint(meshCtx, a as any); break;\n case 'mesh_approve': text = await meshApprove(meshCtx, a as any); break;\n case 'mesh_list_pending_approvals': text = await meshListPendingApprovals(meshCtx, a as any); break;\n case 'mesh_clone_node': text = await meshCloneNode(meshCtx, a as any); break;\n case 'mesh_remove_node': text = await meshRemoveNode(meshCtx, a as any); break;\n case 'mesh_refine_node': text = await meshRefineNode(meshCtx, a as any); break;\n case 'mesh_refine_batch': text = await meshRefineBatch(meshCtx, a as any); break;\n case 'mesh_refine_config': text = await meshRefineConfig(meshCtx, a as any); break;\n // Hidden 1-release aliases (Part 8-4): the former standalone config tools are no\n // longer published in ALL_MESH_TOOLS but stay dispatchable, forwarding to the\n // unified mesh_refine_config handler with the corresponding mode so pre-consolidation\n // callers keep working.\n case 'mesh_refine_config_schema': text = await meshRefineConfig(meshCtx, { ...(a as any), mode: 'schema' }); break;\n case 'mesh_validate_refine_config': text = await meshRefineConfig(meshCtx, { ...(a as any), mode: 'validate' }); break;\n case 'mesh_suggest_refine_config': text = await meshRefineConfig(meshCtx, { ...(a as any), mode: 'suggest' }); break;\n case 'mesh_change_impact_config': text = await meshChangeImpactConfig(meshCtx, a as any); break;\n // Hidden 1-release aliases (symmetric to Part 8-4): the former standalone change-impact\n // config tools are no longer published in ALL_MESH_TOOLS but stay dispatchable, forwarding\n // to the unified mesh_change_impact_config handler with the corresponding mode so\n // pre-consolidation callers keep working.\n case 'mesh_change_impact_config_schema': text = await meshChangeImpactConfig(meshCtx, { ...(a as any), mode: 'schema' }); break;\n case 'mesh_validate_change_impact_config': text = await meshChangeImpactConfig(meshCtx, { ...(a as any), mode: 'validate' }); break;\n case 'mesh_suggest_change_impact_config': text = await meshChangeImpactConfig(meshCtx, { ...(a as any), mode: 'suggest' }); break;\n case 'mesh_init': text = await meshInit(meshCtx, a as any); break;\n case 'mesh_reinit': text = await meshReinit(meshCtx, a as any); break;\n case 'mesh_write_mesh_json_config': text = await meshWriteMeshJsonConfig(meshCtx, a as any); break;\n case 'mesh_refine_plan': text = await meshRefinePlan(meshCtx, a as any); break;\n case 'mesh_cleanup_sessions': text = await meshCleanupSessions(meshCtx, a as any); break;\n case 'mesh_prune_stale_direct': text = await meshPruneStaleDirect(meshCtx, a as any); break;\n case 'mesh_task_history': text = await meshTaskHistory(meshCtx, a as any); break;\n case 'mesh_ledger_query': text = await meshLedgerQuery(meshCtx, a as any); break;\n case 'mesh_record_note': text = await meshRecordNote(meshCtx, a as any); break;\n case 'mesh_forget_note': text = await meshForgetNote(meshCtx, a as any); break;\n case 'mesh_reconcile_ledger': text = await meshReconcileLedger(meshCtx, a as any); break;\n case 'mesh_requeue_held_events': text = await meshRequeueHeldEvents(meshCtx, a as any); break;\n case 'mesh_mission_upsert': text = await meshMissionUpsert(meshCtx, a as any); break;\n case 'mesh_mission_list': text = await meshMissionList(meshCtx, a as any); break;\n case 'mesh_review_inbox': text = await meshReviewInbox(meshCtx, a as any); break;\n case 'mesh_magi_review': text = await meshMagiReview(meshCtx, a as any); break;\n case 'mesh_magi_collect': text = await meshMagiCollect(meshCtx, a as any); break;\n case 'mesh_magi_kind_panel_set': text = await meshMagiKindPanelSet(meshCtx, a as any); break;\n case 'mesh_magi_kind_panel_list': text = await meshMagiKindPanelList(meshCtx, a as any); break;\n case 'mesh_node_slots_set': text = await meshNodeSlotsSet(meshCtx, a as any); break;\n case 'mesh_node_slots_list': text = await meshNodeSlotsList(meshCtx, a as any); break;\n default: return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n return { content: [{ type: 'text', text }] };\n } catch (err: any) {\n return { content: [{ type: 'text', text: `Error: ${err?.message ?? String(err)}` }], isError: true };\n }\n });\n\n const stdioTransport = new StdioServerTransport();\n await server.connect(stdioTransport);\n process.stderr.write(`[adhdev-mcp] Server running in ${opts.mode} mesh mode — mesh: ${mesh.name} (${mesh.repoIdentity})\\n`);\n return;\n }\n\n // ── Standard Mode ──────────────────────────────\n\n // Tool availability by mode:\n // both: list_sessions, launch_session, read_chat, send_chat, approve, git_status\n // local: + screenshot (requires P2P / local daemon access)\n const allTools = [\n LIST_DAEMONS_TOOL,\n LIST_SESSIONS_TOOL,\n LAUNCH_SESSION_TOOL,\n STOP_SESSION_TOOL,\n CHECK_PENDING_TOOL,\n READ_CHAT_TOOL,\n READ_CHAT_DEBUG_TOOL,\n SPEC_DEBUG_TOOL,\n SEND_CHAT_TOOL,\n APPROVE_TOOL,\n GIT_STATUS_TOOL,\n GIT_LOG_TOOL,\n GIT_DIFF_TOOL,\n GIT_CHECKPOINT_TOOL,\n GIT_PUSH_TOOL,\n ...(isLocal ? [SCREENSHOT_TOOL] : []),\n ];\n\n const server = new Server(\n { name: 'adhdev-mcp-server', version: '0.9.66' },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: allTools }));\n\n server.setRequestHandler(CallToolRequestSchema, async (req) => {\n const { name, arguments: args } = req.params;\n const a = (args ?? {}) as Record<string, any>;\n\n try {\n switch (name) {\n case 'list_daemons': {\n const text = await listDaemons(transport, { format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'list_sessions': {\n const text = await listSessions(transport, { format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'read_chat': {\n const text = await readChat(transport, a);\n return { content: [{ type: 'text', text }] };\n }\n case 'read_chat_debug': {\n const text = await readChatDebug(transport, a as any);\n return { content: [{ type: 'text', text }] };\n }\n case 'spec_debug': {\n const text = await specDebug(transport, a as any);\n return { content: [{ type: 'text', text }] };\n }\n case 'send_chat': {\n const text = await sendChat(transport, { message: a.message, session_id: a.session_id });\n return { content: [{ type: 'text', text }] };\n }\n case 'approve': {\n const action = a.action === 'reject' ? 'reject' : 'approve';\n const text = await approve(transport, { action, session_id: a.session_id });\n return { content: [{ type: 'text', text }] };\n }\n case 'screenshot': {\n const result = await screenshot(transport, { session_id: a.session_id });\n if (result.type === 'image') {\n return {\n content: [{ type: 'image', data: result.data, mimeType: result.mimeType }],\n };\n }\n return { content: [{ type: 'text', text: result.text }] };\n }\n case 'git_status': {\n const text = await gitStatus(transport, { workspace: a.workspace, include_diff: a.include_diff, format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'git_log': {\n const text = await gitLog(transport, { workspace: a.workspace, limit: a.limit, file: a.file, since: a.since, until: a.until, format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'git_diff': {\n const text = await gitDiff(transport, { workspace: a.workspace, file: a.file, max_lines: a.max_lines, staged: a.staged, format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n case 'git_checkpoint': {\n const text = await gitCheckpoint(transport, { workspace: a.workspace, message: a.message, include_untracked: a.include_untracked });\n return { content: [{ type: 'text', text }] };\n }\n case 'git_push': {\n const text = await gitPush(transport, { workspace: a.workspace, remote: a.remote, branch: a.branch });\n return { content: [{ type: 'text', text }] };\n }\n case 'launch_session': {\n const text = await launchSession(transport, {\n type: a.type,\n workspace: a.workspace,\n model: a.model,\n });\n return { content: [{ type: 'text', text }] };\n }\n case 'stop_session': {\n const text = await stopSession(transport, {\n session_id: a.session_id,\n type: a.type,\n });\n return { content: [{ type: 'text', text }] };\n }\n case 'check_pending': {\n const text = await checkPending(transport, { format: a.format });\n return { content: [{ type: 'text', text }] };\n }\n default:\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n } catch (err: any) {\n return {\n content: [{ type: 'text', text: `Error: ${err?.message ?? String(err)}` }],\n isError: true,\n };\n }\n });\n\n const stdioTransport = new StdioServerTransport();\n await server.connect(stdioTransport);\n process.stderr.write(`[adhdev-mcp] Server running in ${opts.mode} mode.\\n`);\n}\n","/**\n * LocalTransport — HTTP client for standalone daemon at localhost:3847\n */\n\nconst DEFAULT_PORT = 3847;\n\nexport interface LocalTransportOptions {\n port?: number;\n password?: string;\n}\n\nexport class LocalTransport {\n private baseUrl: string;\n private authHeader: string | null;\n\n constructor(opts: LocalTransportOptions = {}) {\n this.baseUrl = `http://localhost:${opts.port ?? DEFAULT_PORT}`;\n this.authHeader = opts.password ? `Bearer ${opts.password}` : null;\n }\n\n private headers(): Record<string, string> {\n const h: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.authHeader) h['Authorization'] = this.authHeader;\n return h;\n }\n\n async getStatus(): Promise<any> {\n const res = await fetch(`${this.baseUrl}/api/v1/status`, { headers: this.headers() });\n if (!res.ok) throw new Error(`Status fetch failed: ${res.status}`);\n return res.json();\n }\n\n async command(type: string, args: Record<string, unknown> = {}): Promise<any> {\n const res = await fetch(`${this.baseUrl}/api/v1/command`, {\n method: 'POST',\n headers: this.headers(),\n body: JSON.stringify({ type, ...args }),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText);\n throw new Error(`Command ${type} failed: ${res.status} ${text}`);\n }\n return res.json();\n }\n\n async ping(): Promise<boolean> {\n try {\n await this.getStatus();\n return true;\n } catch {\n return false;\n }\n }\n}\n","import type { CommandTransport } from '../transports/mode.js';\n\nexport const FORMAT_PROP = {\n format: {\n type: 'string' as const,\n enum: ['text', 'json'],\n description: \"Output format: 'text' (default, human-readable) or 'json' (structured, for programmatic use).\",\n },\n};\n\nexport const LIST_SESSIONS_TOOL = {\n name: 'list_sessions',\n description: 'List all connected agent sessions.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n ...FORMAT_PROP,\n },\n required: [],\n },\n};\n\nexport async function listSessions(\n transport: CommandTransport,\n args: { format?: 'text' | 'json' } = {},\n): Promise<string> {\n const asJson = args.format === 'json';\n\n // Single daemon, status endpoint has full SessionEntry[]\n const status = await transport.getStatus();\n const sessions: any[] = status?.sessions ?? [];\n\n if (asJson) {\n return JSON.stringify({\n sessions: sessions.map((s: any) => ({\n id: s.id,\n type: s.providerType ?? s.type ?? 'unknown',\n label: s.label ?? null,\n status: s.status ?? s.agentStatus ?? null,\n workspace: s.workspace ?? null,\n })),\n }, null, 2);\n }\n\n if (sessions.length === 0) return 'No active sessions.';\n const lines = sessions.map((s: any) => {\n const parts = [`id: ${s.id}`, `type: ${s.providerType ?? s.type ?? 'unknown'}`];\n if (s.label) parts.push(`label: ${s.label}`);\n if (s.status ?? s.agentStatus) parts.push(`status: ${s.status ?? s.agentStatus}`);\n if (s.workspace) parts.push(`workspace: ${s.workspace}`);\n return parts.join(', ');\n });\n return `Sessions (${sessions.length}):\\n${lines.join('\\n')}`;\n}\n","import type { CommandTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const LIST_DAEMONS_TOOL = {\n name: 'list_daemons',\n description:\n 'List the connected daemon (machine running the ADHDev agent). ' +\n 'Returns the daemon identity extracted from its status report.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n ...FORMAT_PROP,\n },\n required: [],\n },\n};\n\nexport async function listDaemons(\n transport: CommandTransport,\n args: { format?: 'text' | 'json' } = {},\n): Promise<string> {\n const asJson = args.format === 'json';\n\n // Single daemon — extract identity from status\n const status = await transport.getStatus();\n const daemon = {\n id: status?.id ?? status?.instanceId ?? 'standalone',\n hostname: status?.hostname ?? status?.machine?.hostname ?? 'localhost',\n platform: status?.platform ?? status?.machine?.platform ?? 'unknown',\n version: status?.version ?? null,\n sessions: (status?.sessions ?? []).length,\n };\n if (asJson) return JSON.stringify({ daemons: [daemon] }, null, 2);\n return `Daemons (1):\\n id: ${daemon.id}, hostname: ${daemon.hostname}, platform: ${daemon.platform}${daemon.version ? `, version: ${daemon.version}` : ''}, sessions: ${daemon.sessions}`;\n}\n","import type { CommandTransport } from '../transports/mode.js';\nimport { compactChatPayload, messageContent } from './chat-compact.js';\nimport { annotateRapidReadChatAdvisory, type RapidReadChatAdvisory } from './read-chat-polling-advisory.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const READ_CHAT_TOOL = {\n name: 'read_chat',\n description: 'Read the current chat conversation from an IDE agent session. Returns recent messages.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Target session ID (from list_sessions). Pass explicitly in local mode when more than one session exists; omitting requires an active target and may fail.',\n },\n limit: {\n type: 'number',\n description: 'Max messages to return (default: 50).',\n },\n compact: {\n type: 'boolean',\n description: 'Opt-in compact mode: filters tool/terminal/system/internal/control/debug/status chatter and returns user-visible messages plus lightweight summary metadata.',\n },\n ...FORMAT_PROP,\n },\n required: [],\n },\n};\n\nexport async function readChat(\n transport: CommandTransport,\n args: { session_id?: string; limit?: number; format?: 'text' | 'json'; compact?: boolean },\n): Promise<string> {\n const limit = args.limit ?? 50;\n\n const result = await transport.command('read_chat', {\n ...(args.session_id ? { targetSessionId: args.session_id } : {}),\n tailLimit: limit,\n });\n const annotated = annotateRapidReadChatAdvisory(result as Record<string, any>, {\n key: `local:${args.session_id ?? '__active__'}`,\n toolName: 'read_chat',\n completionCallbackExpected: false,\n });\n return formatChatResult(annotated, args.session_id, args.format, limit, args.compact);\n}\n\nfunction formatChatResult(result: any, sessionId?: string, format?: 'text' | 'json', limit = 50, compact = false): string {\n if (!result?.success && result?.error) {\n if (format === 'json') return JSON.stringify({ error: result.error, messages: [] }, null, 2);\n return `Error: ${result.error}`;\n }\n\n const messages: any[] = result?.messages ?? result?.data?.messages ?? [];\n const source = { ...result, messages };\n const compactPayload = compact ? compactChatPayload(source, { sessionId: sessionId ?? null, limit }) : null;\n const outputMessages = compact ? compactPayload.messages : messages;\n\n if (format === 'json') {\n if (compact && compactPayload) {\n return JSON.stringify({\n session_id: sessionId ?? null,\n ...compactPayload,\n ...(result?.pollingAdvisory ? { pollingAdvisory: result.pollingAdvisory as RapidReadChatAdvisory } : {}),\n messages: compactPayload.messages.map((m: any) => ({\n role: m.role,\n kind: m.kind ?? null,\n content: messageContent(m),\n timestamp: m.timestamp ?? null,\n // Preserve the dedup flag so consumers know the body lives in `summary`.\n ...(m._sameAsSummary === true ? { _sameAsSummary: true } : {}),\n })),\n }, null, 2);\n }\n return JSON.stringify({\n session_id: sessionId ?? null,\n ...(result?.pollingAdvisory ? { pollingAdvisory: result.pollingAdvisory as RapidReadChatAdvisory } : {}),\n messages: outputMessages.slice(-limit).map((m: any) => ({\n role: m.role,\n kind: m.kind ?? null,\n content: messageContent(m),\n timestamp: m.timestamp ?? null,\n })),\n }, null, 2);\n }\n\n if ((format === 'text' || format === undefined) && compact && compactPayload) {\n const summaryText = typeof compactPayload.summary === 'string' ? compactPayload.summary.trim() : '';\n const tail = outputMessages.slice(-limit);\n const lastIndex = tail.length - 1;\n const lines = tail.flatMap((m: any, idx: number) => {\n const role = m.role === 'user' ? 'User' : m.role === 'assistant' ? 'Agent' : m.role;\n const content = messageContent(m);\n if (idx === lastIndex && (role === 'Agent' || m.role === 'agent') && summaryText && content.trim() === summaryText) {\n return [];\n }\n const truncated = content.length > 500 ? `${content.slice(0, 500)}…` : content;\n return [`[${role}] ${truncated}`];\n });\n if (compactPayload.summary) {\n const truncatedSummary = compactPayload.summary.length > 500\n ? `${compactPayload.summary.slice(0, 500)}…`\n : compactPayload.summary;\n lines.push(`[Summary] ${truncatedSummary}`);\n }\n if (result?.pollingAdvisory) {\n lines.push(`Advisory: ${(result.pollingAdvisory as RapidReadChatAdvisory).message}`);\n }\n return lines.length > 0 ? lines.join('\\n\\n') : 'No messages in chat.';\n }\n\n if (outputMessages.length === 0) {\n return result?.pollingAdvisory\n ? `No messages in chat.\\n\\nAdvisory: ${(result.pollingAdvisory as RapidReadChatAdvisory).message}`\n : 'No messages in chat.';\n }\n const lines = outputMessages.slice(-limit).map((m: any) => {\n const role = m.role === 'user' ? 'User' : m.role === 'assistant' ? 'Agent' : m.role;\n const content = messageContent(m);\n const truncated = content.length > 500 ? `${content.slice(0, 500)}…` : content;\n return `[${role}] ${truncated}`;\n });\n if (result?.pollingAdvisory) {\n lines.push(`Advisory: ${(result.pollingAdvisory as RapidReadChatAdvisory).message}`);\n }\n return lines.join('\\n\\n');\n}\n","import type { CommandTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const READ_CHAT_DEBUG_TOOL = {\n name: 'read_chat_debug',\n description: 'Collect a daemon-side chat/parser debug bundle for an agent session without opening the browser UI. Prefer this when terminal/chat diverge or long CLI transcripts parse incorrectly. Defaults to daemon_file delivery and returns a saved bundle locator.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Target session ID (from list_sessions). Required for reliable routing.',\n },\n agent_type: {\n type: 'string',\n description: 'Optional provider/agent type hint, e.g. hermes-cli, claude-cli, codex-cli.',\n },\n limit: {\n type: 'number',\n description: 'Max read_chat tail messages embedded in the bundle (default: 40).',\n },\n delivery: {\n type: 'string',\n enum: ['daemon_file', 'inline'],\n description: 'daemon_file saves the full sanitized bundle on the daemon and returns a locator; inline returns the sanitized bundle in the MCP response. Default: daemon_file.',\n },\n ...FORMAT_PROP,\n },\n required: ['session_id'],\n },\n};\n\nexport async function readChatDebug(\n transport: CommandTransport,\n args: {\n session_id?: string;\n agent_type?: string;\n limit?: number;\n delivery?: 'daemon_file' | 'inline';\n format?: 'text' | 'json';\n },\n): Promise<string> {\n const sessionId = typeof args.session_id === 'string' ? args.session_id.trim() : '';\n if (!sessionId) throw new Error('session_id is required');\n\n const tailLimit = args.limit ?? 40;\n const delivery = args.delivery === 'inline' ? 'inline' : 'daemon_file';\n const commandArgs = {\n targetSessionId: sessionId,\n tailLimit,\n ...(args.agent_type ? { agentType: args.agent_type, providerType: args.agent_type } : {}),\n ...(delivery === 'daemon_file' ? { delivery: 'daemon_file' } : {}),\n };\n\n const result = await transport.command('get_chat_debug_bundle', commandArgs);\n\n return formatChatDebugResult(result, { sessionId, delivery, format: args.format });\n}\n\nexport function formatChatDebugResult(\n result: any,\n options: { sessionId: string; delivery: 'daemon_file' | 'inline'; format?: 'text' | 'json' },\n): string {\n if (!result?.success && result?.error) {\n if (options.format === 'json') return JSON.stringify({ success: false, error: result.error }, null, 2);\n return `Error: ${result.error}`;\n }\n\n if (options.format === 'json') {\n return JSON.stringify(result, null, 2);\n }\n\n if (result?.delivery === 'daemon_file') {\n const summary = result.summary && typeof result.summary === 'object' ? result.summary : {};\n return [\n 'ADHDev chat debug bundle saved on daemon.',\n `session_id: ${options.sessionId}`,\n `bundle_id: ${String(result.bundleId || '')}`,\n `saved_path: ${String(result.savedPath || '')}`,\n `size_bytes: ${String(result.sizeBytes || '')}`,\n `created_at: ${String(result.createdAt || '')}`,\n `read_chat_status: ${String((summary as any).readChatStatus || '')}`,\n `read_chat_total_messages: ${String((summary as any).readChatTotalMessages ?? '')}`,\n `cli_status: ${String((summary as any).cliStatus || '')}`,\n `cli_message_count: ${String((summary as any).cliMessageCount ?? '')}`,\n ].join('\\n');\n }\n\n if (typeof result?.text === 'string') return result.text;\n if (result?.bundle) return JSON.stringify(result.bundle, null, 2);\n return JSON.stringify(result, null, 2);\n}\n","import type { CommandTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const SPEC_DEBUG_TOOL = {\n name: 'spec_debug',\n description: 'Get current spec state, sections, and state transition history for a spec-driven CLI session (claude-cli, antigravity-cli, etc.). Use to diagnose idle/busy detection issues, inspect section parsing, or verify idle_hold and busy_hold behavior.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Target session ID (from list_sessions).',\n },\n ...FORMAT_PROP,\n },\n required: ['session_id'],\n },\n};\n\nexport async function specDebug(\n transport: CommandTransport,\n args: {\n session_id?: string;\n format?: 'text' | 'json';\n },\n): Promise<string> {\n const sessionId = typeof args.session_id === 'string' ? args.session_id.trim() : '';\n if (!sessionId) throw new Error('session_id is required');\n\n const result = await transport.command('get_spec_debug', { targetSessionId: sessionId });\n\n return formatSpecDebugResult(result, { sessionId, format: args.format });\n}\n\nexport function formatSpecDebugResult(\n result: any,\n options: { sessionId: string; format?: 'text' | 'json' },\n): string {\n if (!result?.success) {\n const err = result?.error || 'Unknown error';\n if (options.format === 'json') return JSON.stringify({ success: false, error: err }, null, 2);\n return `Error: ${err}`;\n }\n\n if (options.format === 'json') return JSON.stringify(result, null, 2);\n\n const snap = result.snapshot;\n if (!snap) {\n return [\n `session_id: ${options.sessionId}`,\n `provider_type: ${String(result.providerType || '')}`,\n 'is_spec_provider: false',\n 'No spec debug data available (not a spec-driven provider).',\n ].join('\\n');\n }\n\n const lines: string[] = [];\n lines.push(`session_id: ${options.sessionId}`);\n lines.push(`provider_type: ${String(result.providerType || snap.cliType || '')}`);\n lines.push(`spec_id: ${String(snap.spec_id || '')}`);\n lines.push(`spec_path: ${String(snap.specPath || '')}`);\n lines.push(`current_state: ${snap.current_state ? `${snap.current_state.id} (${snap.current_state.label})` : 'none'}`);\n lines.push(`idle_hold_pending: ${String(snap.idleHoldPending ?? false)}`);\n lines.push(`last_busy_at: ${snap.lastBusyAt ? new Date(snap.lastBusyAt).toISOString() : 'never'}`);\n lines.push(`exited: ${String(snap.exited ?? false)}`);\n\n if (snap.current_modal) {\n lines.push(`current_modal: ${JSON.stringify(snap.current_modal)}`);\n }\n\n // Sections — full raw text (this is a debugging surface; do NOT truncate or\n // collapse newlines, so the exact text the FSM regexes match against is\n // visible). Each section is fenced and prefixed with its line count.\n if (snap.sections && typeof snap.sections === 'object') {\n lines.push('');\n lines.push('## Sections');\n for (const [id, text] of Object.entries(snap.sections as Record<string, string>)) {\n const raw = String(text ?? '');\n const lineCount = raw.length === 0 ? 0 : raw.split('\\n').length;\n lines.push('');\n lines.push(`### section: ${id} (${lineCount} lines, ${raw.length} chars)`);\n lines.push('```');\n lines.push(raw);\n lines.push('```');\n }\n }\n\n // State history (most recent first) — now includes the fired transition\n // (`via`) and the per-condition rule evaluation (`matchedRules`), so you can\n // see WHICH regex/time-gate fired and, for regex rules, the matched text.\n const history = Array.isArray(snap.stateHistory) ? snap.stateHistory : [];\n if (history.length > 0) {\n lines.push('');\n lines.push('## State History (newest first)');\n const now = Date.now();\n for (const entry of [...history].reverse().slice(0, 20)) {\n const agoMs = now - entry.at;\n const ago = agoMs < 2000 ? `${agoMs}ms ago` : `${(agoMs / 1000).toFixed(1)}s ago`;\n const dur = entry.durationMs > 0 ? ` held ${entry.durationMs}ms` : '';\n const via = entry.via ? ` via ${entry.via}` : '';\n lines.push(` ${String(entry.stateId).padEnd(18)} ${ago}${dur}${via}`);\n const rules = Array.isArray(entry.matchedRules) ? entry.matchedRules : [];\n for (const rule of rules) {\n lines.push(` ${String(rule)}`);\n }\n }\n }\n\n // PTY event timeline (input we injected / output the PTY printed / resize /\n // cursor moves) — correlate by timestamp with the State History above to see\n // what input/output preceded each status transition.\n const timeline = Array.isArray(snap.eventTimeline) ? snap.eventTimeline : [];\n if (timeline.length > 0) {\n lines.push('');\n lines.push('## Event Timeline (oldest first)');\n const now = Date.now();\n const arrow: Record<string, string> = {\n input: '→ in ', output: '← out', resize: '⇲ size', cursor: '⌖ cur', spawn: '⏻ spawn', exit: '⏹ exit',\n };\n for (const ev of timeline.slice(-120)) {\n const agoMs = now - (ev.ts ?? now);\n const ago = agoMs < 2000 ? `${agoMs}ms` : `${(agoMs / 1000).toFixed(1)}s`;\n const tag = arrow[String(ev.kind)] ?? String(ev.kind);\n const bytes = typeof ev.bytes === 'number' ? ` [${ev.bytes}b]` : '';\n lines.push(` -${ago.padStart(6)} ${tag}${bytes} ${String(ev.content ?? '')}`);\n }\n }\n\n return lines.join('\\n');\n}\n","import type { CommandTransport } from '../transports/mode.js';\n\nexport const SEND_CHAT_TOOL = {\n name: 'send_chat',\n description: 'Send a message to an IDE agent session.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n message: {\n type: 'string',\n description: 'The message to send to the agent.',\n },\n session_id: {\n type: 'string',\n description: 'Target session ID (from list_sessions). Omit to use the active session.',\n },\n },\n required: ['message'],\n },\n};\n\nexport async function sendChat(\n transport: CommandTransport,\n args: { message: string; session_id?: string },\n): Promise<string> {\n if (!args.message?.trim()) throw new Error('message is required');\n\n const result = await transport.command('send_chat', {\n message: args.message,\n ...(args.session_id ? { targetSessionId: args.session_id } : {}),\n });\n if (result?.success === false) return `Error: ${result.error ?? 'send_chat failed'}`;\n return 'Message sent.';\n}\n","import type { CommandTransport } from '../transports/mode.js';\n\nexport const APPROVE_TOOL = {\n name: 'approve',\n description: 'Approve or reject a pending agent action (e.g. file write, command execution).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n action: {\n type: 'string',\n enum: ['approve', 'reject'],\n description: 'Whether to approve or reject the pending action.',\n },\n session_id: {\n type: 'string',\n description: 'Target session ID. Omit to use the active session.',\n },\n },\n required: ['action'],\n },\n};\n\nexport async function approve(\n transport: CommandTransport,\n args: { action: 'approve' | 'reject'; session_id?: string },\n): Promise<string> {\n const action = args.action === 'reject' ? 'reject' : 'approve';\n\n const result = await transport.command('resolve_action', {\n action,\n ...(args.session_id ? { targetSessionId: args.session_id } : {}),\n });\n if (result?.success === false) return `Error: ${result.error ?? 'resolve_action failed'}`;\n return `Action ${action}d.`;\n}\n","import type { CommandTransport } from '../transports/mode.js';\n\nexport const SCREENSHOT_TOOL = {\n name: 'screenshot',\n description:\n 'Capture a screenshot of the current IDE window. Returns the image.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Target session ID. Omit to use the active session.',\n },\n },\n required: [],\n },\n};\n\nexport async function screenshot(\n transport: CommandTransport,\n args: { session_id?: string },\n): Promise<{ type: 'image'; data: string; mimeType: string } | { type: 'text'; text: string }> {\n const result: any = await transport.command('screenshot', {\n ...(args.session_id ? { targetSessionId: args.session_id } : {}),\n });\n\n if (result?.success === false) {\n return { type: 'text', text: `Error: ${result.error ?? 'screenshot failed'}` };\n }\n\n const b64: string | undefined = result?.base64 ?? result?.screenshot ?? result?.result;\n if (!b64) {\n return { type: 'text', text: 'Screenshot captured but no image data returned.' };\n }\n\n const mimeType = result?.format === 'png' ? 'image/png' : 'image/webp';\n return { type: 'image', data: b64, mimeType };\n}\n","import type { CommandTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const GIT_STATUS_TOOL = {\n name: 'git_status',\n description: 'Get git repository status for a workspace on the daemon machine.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n include_diff: {\n type: 'boolean',\n description: 'Include changed file list (default: true).',\n },\n ...FORMAT_PROP,\n },\n required: ['workspace'],\n },\n};\n\nexport async function gitStatus(\n transport: CommandTransport,\n args: { workspace: string; include_diff?: boolean; format?: 'text' | 'json' },\n): Promise<string> {\n let diffSummary: any;\n\n const statusResult = await transport.command('git_status', {\n workspace: args.workspace,\n });\n const status: any = statusResult?.status ?? statusResult;\n\n if (args.include_diff !== false) {\n const diffResult = await transport.command('git_diff_summary', {\n workspace: args.workspace,\n });\n diffSummary = diffResult?.diffSummary ?? diffResult;\n }\n\n if (status?.success === false || status?.reason) {\n const msg = status?.error ?? status?.reason ?? 'unknown';\n if (args.format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return `Git error: ${msg}`;\n }\n if (!status?.isGitRepo) {\n if (args.format === 'json') return JSON.stringify({ error: `Not a git repository: ${args.workspace}` }, null, 2);\n return `Not a git repository: ${args.workspace}`;\n }\n\n if (args.format === 'json') {\n const files = diffSummary?.files?.map((f: any) => ({\n path: f.path,\n old_path: f.oldPath ?? null,\n status: f.status ?? 'M',\n insertions: f.insertions ?? 0,\n deletions: f.deletions ?? 0,\n })) ?? [];\n return JSON.stringify({\n branch: status.branch ?? null,\n head_commit: status.headCommit ?? null,\n head_message: status.headMessage ?? null,\n ahead: status.ahead ?? 0,\n behind: status.behind ?? 0,\n staged: status.staged ?? 0,\n modified: status.modified ?? 0,\n untracked: status.untracked ?? 0,\n deleted: status.deleted ?? 0,\n stash_count: status.stashCount ?? 0,\n has_conflicts: status.hasConflicts ?? false,\n dirty: status.dirty ?? false,\n changed_files: files,\n total_insertions: diffSummary?.totalInsertions ?? 0,\n total_deletions: diffSummary?.totalDeletions ?? 0,\n }, null, 2);\n }\n\n const lines: string[] = [];\n if (status.branch) lines.push(`Branch: ${status.branch}`);\n if (status.headCommit) {\n lines.push(`HEAD: ${status.headCommit.slice(0, 7)}${status.headMessage ? ` — ${status.headMessage.slice(0, 80)}` : ''}`);\n }\n if (status.ahead > 0) lines.push(`Ahead: ${status.ahead}`);\n if (status.behind > 0) lines.push(`Behind: ${status.behind}`);\n if (status.staged > 0) lines.push(`Staged: ${status.staged}`);\n if (status.modified > 0) lines.push(`Modified: ${status.modified}`);\n if (status.untracked > 0) lines.push(`Untracked: ${status.untracked}`);\n if (status.deleted > 0) lines.push(`Deleted: ${status.deleted}`);\n if (status.stashCount > 0) lines.push(`Stashes: ${status.stashCount}`);\n if (status.hasConflicts) lines.push('Conflicts: YES');\n if (!status.dirty) lines.push('Working tree: clean');\n\n if (diffSummary?.files?.length > 0) {\n lines.push('');\n lines.push(`Changed files (${diffSummary.files.length}):`);\n for (const f of diffSummary.files.slice(0, 20)) {\n lines.push(` ${f.status ?? 'M'} ${f.path}${f.oldPath ? ` (was ${f.oldPath})` : ''}${f.insertions || f.deletions ? ` +${f.insertions ?? 0}/-${f.deletions ?? 0}` : ''}`);\n }\n if (diffSummary.files.length > 20) lines.push(` … and ${diffSummary.files.length - 20} more`);\n if (diffSummary.totalInsertions || diffSummary.totalDeletions) {\n lines.push(`Total: +${diffSummary.totalInsertions ?? 0}/-${diffSummary.totalDeletions ?? 0}`);\n }\n }\n\n return lines.join('\\n');\n}\n","import type { CommandTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const GIT_LOG_TOOL = {\n name: 'git_log',\n description:\n 'Get commit history for a workspace. Shows hash, message, author, and date for recent commits. ' +\n 'Use this to track what changes an agent has made, verify checkpoint commits, or understand project history.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n limit: {\n type: 'number',\n description: 'Max commits to return (default: 20, max: 100).',\n },\n file: {\n type: 'string',\n description: 'Filter history to commits that touched this repo-relative file path (optional).',\n },\n since: {\n type: 'string',\n description: 'Only commits after this date (ISO 8601 or git date string, optional).',\n },\n until: {\n type: 'string',\n description: 'Only commits before this date (ISO 8601 or git date string, optional).',\n },\n ...FORMAT_PROP,\n },\n required: ['workspace'],\n },\n};\n\nexport async function gitLog(\n transport: CommandTransport,\n args: {\n workspace: string;\n limit?: number;\n file?: string;\n since?: string;\n until?: string;\n format?: 'text' | 'json';\n },\n): Promise<string> {\n const limit = Math.max(1, Math.min(100, args.limit ?? 20));\n\n let raw: any = await transport.command('git_log', {\n workspace: args.workspace,\n limit,\n ...(args.file ? { path: args.file } : {}),\n ...(args.since ? { since: args.since } : {}),\n ...(args.until ? { until: args.until } : {}),\n });\n raw = raw?.log ?? raw;\n\n if (raw?.success === false || raw?.reason) {\n const msg = raw?.error ?? raw?.reason ?? 'unknown';\n if (args.format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return `Git log error: ${msg}`;\n }\n\n if (!raw?.isGitRepo) {\n const msg = `Not a git repository: ${args.workspace}`;\n if (args.format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return msg;\n }\n\n const entries: any[] = raw?.entries ?? [];\n\n if (args.format === 'json') {\n return JSON.stringify({\n workspace: raw.workspace,\n branch: raw.branch ?? null,\n entries: entries.map((e) => ({\n commit: e.commit,\n short: e.commit?.slice(0, 7),\n message: e.message,\n author: e.authorName ?? null,\n author_email: e.authorEmail ?? null,\n authored_at: e.authoredAt ? new Date(e.authoredAt).toISOString() : null,\n })),\n total: entries.length,\n truncated: raw.truncated ?? false,\n }, null, 2);\n }\n\n if (entries.length === 0) return 'No commits found.';\n\n const lines = entries.map((e) => {\n const hash = e.commit?.slice(0, 7) ?? '???????';\n const date = e.authoredAt ? new Date(e.authoredAt).toISOString().slice(0, 10) : '';\n const author = e.authorName ? ` (${e.authorName})` : '';\n return `${hash} ${date}${author} ${e.message}`;\n });\n\n const header = `Commits (${entries.length}${raw.truncated ? ', truncated' : ''}):`;\n return `${header}\\n${lines.join('\\n')}`;\n}\n","import type { CommandTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const GIT_DIFF_TOOL = {\n name: 'git_diff',\n description:\n 'Get the actual diff content for changed files in a workspace. ' +\n 'Without a specific file, returns diffs for up to 5 changed files. ' +\n 'Use this to review what an agent actually changed — file names alone (from git_status) are not enough for code review.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n file: {\n type: 'string',\n description: 'Specific repo-relative file path to diff (optional — if omitted, returns top 5 changed files).',\n },\n max_lines: {\n type: 'number',\n description: 'Max diff lines per file before truncating (default: 300).',\n },\n staged: {\n type: 'boolean',\n description: 'Show staged changes instead of unstaged (default: false).',\n },\n ...FORMAT_PROP,\n },\n required: ['workspace'],\n },\n};\n\ninterface FileDiffResult {\n path: string;\n old_path?: string | null;\n status?: string;\n diff: string;\n truncated: boolean;\n binary: boolean;\n error?: string;\n}\n\nexport async function gitDiff(\n transport: CommandTransport,\n args: {\n workspace: string;\n file?: string;\n max_lines?: number;\n staged?: boolean;\n format?: 'text' | 'json';\n },\n): Promise<string> {\n const maxLines = Math.max(10, Math.min(2000, args.max_lines ?? 300));\n const staged = args.staged ?? false;\n\n return localGitDiff(transport, args.workspace, args.file, maxLines, staged, args.format);\n}\n\nasync function localGitDiff(\n transport: CommandTransport,\n workspace: string,\n file: string | undefined,\n maxLines: number,\n staged: boolean,\n format: 'text' | 'json' | undefined,\n): Promise<string> {\n if (file) {\n const raw = await transport.command('git_diff_file', { workspace, path: file, staged });\n const d = raw?.diff ?? raw;\n\n if (d?.success === false || d?.reason) {\n const msg = d?.error ?? d?.reason ?? 'unknown';\n if (format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return `Git diff error: ${msg}`;\n }\n\n const lines = (d?.diff ?? '').split('\\n');\n const truncated = lines.length > maxLines;\n const result = {\n files: [{\n path: file,\n diff: truncated ? lines.slice(0, maxLines).join('\\n') + '\\n... (truncated)' : (d?.diff ?? ''),\n truncated,\n binary: d?.binary ?? false,\n }],\n total_files: 1,\n shown_files: 1,\n truncated,\n };\n return formatDiffResult(result, format);\n }\n\n // No specific file: get summary then fetch top 5\n const summaryRaw = await transport.command('git_diff_summary', { workspace, staged });\n const summary = summaryRaw?.diffSummary ?? summaryRaw;\n\n if (summary?.success === false || summary?.reason) {\n const msg = summary?.error ?? summary?.reason ?? 'unknown';\n if (format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return `Git diff error: ${msg}`;\n }\n\n if (!summary?.isGitRepo) {\n const msg = `Not a git repository: ${workspace}`;\n if (format === 'json') return JSON.stringify({ error: msg }, null, 2);\n return msg;\n }\n\n const files: any[] = summary?.files ?? [];\n if (files.length === 0) {\n if (format === 'json') return JSON.stringify({ files: [], total_files: 0, shown_files: 0, truncated: false }, null, 2);\n return 'No changed files.';\n }\n\n const topFiles = files.slice(0, 5);\n const fileDiffs: FileDiffResult[] = await Promise.all(\n topFiles.map(async (f: any): Promise<FileDiffResult> => {\n try {\n const raw = await transport.command('git_diff_file', { workspace, path: f.path, staged });\n const d = raw?.diff ?? raw;\n const lines = (d?.diff ?? '').split('\\n');\n const trunc = lines.length > maxLines;\n return {\n path: f.path,\n old_path: f.oldPath ?? null,\n status: f.status ?? 'M',\n diff: trunc ? lines.slice(0, maxLines).join('\\n') + '\\n... (truncated)' : (d?.diff ?? ''),\n truncated: trunc,\n binary: d?.binary ?? false,\n };\n } catch {\n return { path: f.path, diff: '', truncated: false, binary: false, error: 'fetch failed' };\n }\n }),\n );\n\n return formatDiffResult({\n files: fileDiffs,\n total_files: files.length,\n shown_files: topFiles.length,\n truncated: files.length > 5,\n }, format);\n}\n\nfunction formatDiffResult(result: any, format: 'text' | 'json' | undefined): string {\n if (format === 'json') return JSON.stringify(result, null, 2);\n\n const files: FileDiffResult[] = result?.files ?? [];\n if (files.length === 0) return 'No changed files.';\n\n const parts: string[] = [];\n const totalShown = result?.shown_files ?? files.length;\n const totalAll = result?.total_files ?? files.length;\n if (totalAll > totalShown) {\n parts.push(`Showing ${totalShown} of ${totalAll} changed files:\\n`);\n }\n\n for (const f of files) {\n const header = `--- ${f.path}${f.old_path ? ` (was ${f.old_path})` : ''} ---`;\n if (f.error) {\n parts.push(`${header}\\n(error: ${f.error})\\n`);\n } else if (f.binary) {\n parts.push(`${header}\\n(binary file)\\n`);\n } else if (!f.diff) {\n parts.push(`${header}\\n(no diff)\\n`);\n } else {\n parts.push(`${header}\\n${f.diff}${f.truncated ? '' : '\\n'}`);\n }\n }\n\n return parts.join('\\n');\n}\n","import type { CommandTransport } from '../transports/mode.js';\n\nexport const GIT_CHECKPOINT_TOOL = {\n name: 'git_checkpoint',\n description:\n 'Create a checkpoint commit in a workspace. ' +\n 'Stages all tracked changes (or all files including untracked) and commits with a prefixed message. ' +\n 'Use this to save progress before a risky operation, or to create a restore point the orchestrator can reference.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n message: {\n type: 'string',\n description: 'Checkpoint message (max 200 chars). Will be prefixed with \"adhdev: checkpoint \".',\n },\n include_untracked: {\n type: 'boolean',\n description: 'Also stage and commit untracked files (default: false).',\n },\n },\n required: ['workspace', 'message'],\n },\n};\n\nexport async function gitCheckpoint(\n transport: CommandTransport,\n args: {\n workspace: string;\n message: string;\n include_untracked?: boolean;\n },\n): Promise<string> {\n const message = args.message?.trim();\n if (!message) return 'Error: message is required';\n if (message.length > 200) return 'Error: message must be 200 characters or fewer';\n\n let raw: any = await transport.command('git_checkpoint', {\n workspace: args.workspace,\n message,\n includeUntracked: args.include_untracked ?? false,\n });\n raw = raw?.checkpoint ?? raw;\n\n if (raw?.success === false || raw?.reason) {\n const msg = raw?.error ?? raw?.reason ?? 'unknown';\n if (msg.includes('Nothing to commit') || msg.includes('nothing to commit')) {\n return 'Nothing to commit — working tree is clean.';\n }\n return `Git checkpoint error: ${msg}`;\n }\n\n const commit = raw?.commit?.slice(0, 7) ?? '???????';\n const fullMsg = raw?.message ?? `adhdev: checkpoint ${message}`;\n return `Checkpoint created: ${commit} — ${fullMsg}`;\n}\n","import type { CommandTransport } from '../transports/mode.js';\n\nexport const GIT_PUSH_TOOL = {\n name: 'git_push',\n description:\n 'Push a branch to a remote repository on the daemon machine. ' +\n 'If the branch has no upstream configured, sets it automatically. ' +\n 'Key for parallel multi-machine workflows: after git_checkpoint, push each machine\\'s ' +\n 'branch to origin so changes are available for PR/review.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n workspace: {\n type: 'string',\n description: 'Absolute path to the workspace/repository directory.',\n },\n remote: {\n type: 'string',\n description: 'Remote name (default: \"origin\").',\n },\n branch: {\n type: 'string',\n description: 'Branch to push (default: current branch).',\n },\n },\n required: ['workspace'],\n },\n};\n\nexport async function gitPush(\n transport: CommandTransport,\n args: {\n workspace: string;\n remote?: string;\n branch?: string;\n },\n): Promise<string> {\n let raw: any = await transport.command('git_push', {\n workspace: args.workspace,\n remote: args.remote ?? 'origin',\n ...(args.branch ? { branch: args.branch } : {}),\n });\n raw = raw?.push ?? raw;\n\n if (raw?.success === false || raw?.reason) {\n const msg = raw?.error ?? raw?.reason ?? 'unknown';\n return `Git push error: ${msg}`;\n }\n\n const branch = raw?.branch ?? args.branch ?? '(current)';\n const remote = raw?.remote ?? args.remote ?? 'origin';\n const newBranch = raw?.newBranch ? ' [new branch]' : '';\n const output = raw?.output ? `\\n${raw.output}` : '';\n\n return `Pushed ${branch} → ${remote}${newBranch}${output}`;\n}\n","import type { CommandTransport } from '../transports/mode.js';\n\nexport const LAUNCH_SESSION_TOOL = {\n name: 'launch_session',\n description:\n 'Launch a new agent session on the daemon. Supports CLI agents (e.g. hermes-cli, claude-cli, gemini-cli), ACP agents (e.g. claude-acp), and IDEs (e.g. cursor, vscode).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n type: {\n type: 'string',\n description:\n 'Provider type to launch. CLI examples: hermes-cli, claude-cli, gemini-cli. ACP examples: claude-acp. IDE examples: cursor, vscode.',\n },\n workspace: {\n type: 'string',\n description: 'Working directory for the session. Defaults to the daemon default workspace.',\n },\n model: {\n type: 'string',\n description: 'Model override for ACP agents (e.g. claude-opus-4-7).',\n },\n },\n required: ['type'],\n },\n};\n\nexport async function launchSession(\n transport: CommandTransport,\n args: { type: string; workspace?: string; model?: string },\n): Promise<string> {\n const isCliOrAcp =\n args.type.includes('-cli') || args.type.includes('-acp') || args.type === 'codex';\n const commandType = isCliOrAcp ? 'launch_cli' : 'launch_ide';\n const payload: Record<string, unknown> = isCliOrAcp\n ? { cliType: args.type, dir: args.workspace ?? '~', ...(args.model ? { model: args.model } : {}) }\n : { ideType: args.type, enableCdp: true };\n const result = await transport.command(commandType, payload);\n if (result?.success === false) return `Error: ${result.error ?? 'launch failed'}`;\n const id = result?.id ?? result?.sessionId;\n return id ? `Session launched. id: ${id}, type: ${args.type}` : `Launched: ${JSON.stringify(result)}`;\n}\n","import type { CommandTransport } from '../transports/mode.js';\n\nexport const STOP_SESSION_TOOL = {\n name: 'stop_session',\n description:\n 'Stop a running agent session. For CLI agents (hermes-cli, claude-cli, etc.) this sends a graceful stop signal. ' +\n 'Use list_sessions to find the session_id.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n session_id: {\n type: 'string',\n description: 'Session ID to stop (from list_sessions).',\n },\n type: {\n type: 'string',\n description:\n 'Provider type (e.g. hermes-cli, claude-cli). Auto-resolved from session_id if omitted.',\n },\n },\n required: ['session_id'],\n },\n};\n\nexport async function stopSession(\n transport: CommandTransport,\n args: { session_id: string; type?: string },\n): Promise<string> {\n let resolvedType = args.type;\n\n // Auto-resolve type from session status if not provided\n if (!resolvedType) {\n const status = await transport.getStatus();\n const session = (status?.sessions ?? []).find((s: any) => s.id === args.session_id);\n resolvedType = session?.providerType ?? session?.type;\n }\n\n if (!resolvedType) {\n return `Error: could not resolve session type for ${args.session_id}. Pass type= explicitly.`;\n }\n\n const result = await transport.command('stop_cli', {\n targetSessionId: args.session_id,\n cliType: resolvedType,\n });\n if (result?.success === false) return `Error: ${result.error ?? 'stop failed'}`;\n return `Session ${args.session_id} stopped.`;\n}\n","import type { CommandTransport } from '../transports/mode.js';\nimport { FORMAT_PROP } from './list-sessions.js';\n\nexport const CHECK_PENDING_TOOL = {\n name: 'check_pending',\n description:\n 'List all agent sessions currently waiting for user approval (tool-use confirmation). ' +\n 'Returns session ID, daemon ID, workspace, and the approval prompt message when available. ' +\n 'Use approve() with the session_id to approve or reject.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n ...FORMAT_PROP,\n },\n required: [],\n },\n};\n\nexport async function checkPending(\n transport: CommandTransport,\n args: { format?: 'text' | 'json' },\n): Promise<string> {\n const status = await transport.getStatus();\n const sessions: any[] = status?.sessions ?? [];\n\n const pending = sessions.filter(\n (s) => s.status === 'waiting_approval' || s.agentStatus === 'waiting_approval',\n );\n\n if (args.format === 'json') {\n return JSON.stringify({\n pending: pending.map((s) => ({\n session_id: s.id,\n workspace: s.workspace ?? null,\n type: s.providerType ?? null,\n modal_message: s.activeChat?.activeModal?.message ?? null,\n buttons: s.activeChat?.activeModal?.buttons ?? [],\n })),\n }, null, 2);\n }\n\n if (pending.length === 0) return 'No sessions waiting for approval.';\n const lines = pending.map((s) => {\n const modal = s.activeChat?.activeModal;\n const parts = [`session_id: ${s.id}`];\n if (s.workspace) parts.push(`workspace: ${s.workspace}`);\n if (s.providerType) parts.push(`type: ${s.providerType}`);\n if (modal?.message) parts.push(`prompt: ${modal.message}`);\n if (modal?.buttons?.length) parts.push(`buttons: ${modal.buttons.join(', ')}`);\n return parts.join('\\n ');\n });\n return `Pending approvals (${pending.length}):\\n\\n${lines.join('\\n\\n')}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AACzB,IAAM,iCAAiC;AAQvC,IAAM,0BAAkD;AAAA,EACtD,oBAAoB;AAAA,EACpB,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,wBAAwB;AAAA,EACxB,aAAa;AAAA;AAAA;AAAA;AAAA,EAIb,iBAAiB;AAAA,EACjB,kBAAkB;AAAA;AAAA;AAAA;AAAA,EAIlB,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMvB,kBAAkB;AAAA,EAClB,yBAAyB;AAC3B;AAGA,IAAM,gBAAgB;AACtB,IAAM,UAAU;AAQhB,IAAM,qBAAqB,IAAI;AAC/B,IAAM,kBAAkB,KAAK;AAW7B,IAAM,iBAAiB,oBAAI,IAA8B;AAEzD,SAAS,iBAAyB;AAChC,SAAO,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AACpE;AAEO,SAAS,aAAa,MAAc,eAA+B;AACxE,SAAO,KAAK;AAAA,IACV,wBAAwB,IAAI,KA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_core","result","distinctProviders","distinctNodes","needsVerification","staleTaskIds","staleReasons","result","lines","os","server","stdioTransport"]}
|