adhdev 0.9.82-rc.436 → 0.9.82-rc.437
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/cli/adhdev-mcp.js +5 -5
- package/dist/cli/index.js +5 -5
- package/dist/index.js +5 -5
- package/package.json +3 -3
- package/vendor/mcp-server/index.js +100 -5
- package/vendor/mcp-server/index.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/transports/ipc.ts","../src/tools/chat-compact.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-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 if (payload?.success === false) {\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 * 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 * 29 tools: mesh_status, mesh_mission_upsert, mesh_mission_list, 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 * mesh_review_inbox\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 type { LocalMeshEntry, LocalMeshNodeEntry, MeshActiveWorkSummary, RepoMeshPolicy, RepoMeshRelatedRepo } from '@adhdev/daemon-core';\nimport {\n daemonIdsEquivalent,\n meshNodeIdMatches,\n appendLedgerEntry,\n appendRemoteLedgerEntries,\n buildCompactStaleDirectWorkSummary,\n buildMeshActiveWork,\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 drainPendingMeshCoordinatorEvents,\n enqueueTask,\n computeMeshMissionStats,\n computeMeshTaskStats,\n getActiveMeshMissionSummaries,\n getMeshStatusMissionSummaries,\n getMeshStatusMissionsCompact,\n listMeshMissionSummaries,\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 readLedgerEntries,\n readLedgerSlice,\n readLedgerSliceFromStore,\n reconcileDirectDispatchCompletionFromTranscript,\n recordMeshToolCall,\n requeueTask,\n resolveMeshSurfacedSessionPreview,\n resolveDelegatedWorkerAutoApprove,\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_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_RECONCILE_LEDGER_TOOL,\n MESH_PRUNE_STALE_DIRECT_TOOL,\n MESH_REFINE_NODE_TOOL,\n MESH_REFINE_BATCH_TOOL,\n MESH_REFINE_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_REFINE_CONFIG_TOOL,\n MESH_SUGGEST_REFINE_CONFIG_TOOL,\n MESH_CHANGE_IMPACT_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_SUGGEST_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_INIT_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 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 drainPendingMeshCoordinatorEvents,\n enqueueTask,\n getActiveDirectDispatches,\n getActiveMeshMissionSummaries,\n getLedgerSummary,\n getMagiPanel,\n getMeshMission,\n getMeshStatusMissionSummaries,\n getMeshStatusMissionsCompact,\n getQueue,\n listMagiPanels,\n getSessionRecoveryContext,\n insertDirectDispatch,\n isP2pRelayTransportFailure,\n isWeakCompletionEvidence,\n listMeshMissionSummaries,\n markStaleDirectDispatches,\n meshNodeIdMatches,\n nodeSatisfiesRequiredTags,\n normalizeMagiPanel,\n normalizeMeshCapabilityTags,\n pruneStaleDirectDispatches,\n readLedgerEntries,\n readLedgerSlice,\n readLedgerSliceFromStore,\n reconcileDirectDispatchCompletionFromTranscript,\n recordDirectDispatchTask,\n recordMeshToolCall,\n requeueTask,\n resolveDelegatedWorkerAutoApprove,\n resolveMeshSurfacedSessionPreview,\n summarizeMeshAsyncRefineJobs,\n upsertMagiPanel,\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 MagiPanelDefaultKind,\n MagiPanel,\n MagiPanelMember,\n MagiReplicaGitRef,\n MagiResponseSource,\n MagiSynthesis,\n MagiSynthesizedResponse,\n MeshActiveWorkSummary,\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\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 },\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 };\n}\n\nexport function findNode(mesh: LocalMeshEntry, nodeId: string): LocalMeshNodeEntry {\n const node = mesh.nodes.find(n => meshNodeIdMatches(n, 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, nodeId));\n if (hit && !hit.isLocalWorktree) return hit;\n\n await refreshMeshFromDaemon(ctx);\n\n const refreshed = ctx.mesh.nodes.find(n => meshNodeIdMatches(n, 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, nodeId));\n if (hit && !hit.isLocalWorktree) return hit;\n\n await refreshMeshFromDaemon(ctx);\n\n return ctx.mesh.nodes.find(n => meshNodeIdMatches(n, 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\nexport function readFinalAssistantTranscriptEvidence(payload: any): { finalSummary?: string; transcriptMessageAt?: string } {\n const rawMessages = Array.isArray(payload?.messages) ? payload.messages : [];\n const finalAssistant = [...rawMessages]\n .reverse()\n .filter(isCoordinatorVisibleMessage)\n .find((message: any) => {\n const role = String(message?.role ?? '').toLowerCase();\n return (role === 'assistant' || role === 'agent') && messageContent(message).trim();\n });\n const finalSummary = messageContent(finalAssistant).trim()\n || (typeof payload?.summary === 'string' && payload.summary.trim() ? payload.summary.trim() : undefined);\n return {\n finalSummary,\n transcriptMessageAt: finalAssistant ? readMessageTimestampIso(finalAssistant) : undefined,\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 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.\nexport const COMPACT_NODES_TOTAL_BYTE_BUDGET = 13000;\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 const statusResult = 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\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/**\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 const providers = readProviderPriority(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 const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {});\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): 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 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 };\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\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', pendingEventArgs) as any;\n const hasLiveCliCoordinator = unwrapCommandPayload(raw)?.hasLiveCliCoordinator === true\n || raw?.hasLiveCliCoordinator === 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) {\n // Pure-MCP coordinator: the LLM tool result is the only surface. Do NOT\n // re-forward (that re-queues with no PTY → the drain-without-inject loop).\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 const events = (drainPendingMeshCoordinatorEvents(ctx.mesh.id, ctx.localDaemonId) 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, 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 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 },\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_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. 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 inputSchema: {\n type: 'object' as const,\n properties: {\n mission_id: { type: 'string', description: 'Mission id to update. Omit to create a new mission.' },\n title: { type: 'string', description: 'Short mission title.' },\n goal: { type: 'string', description: 'Free-text mission goal/definition of done.' },\n status: { type: 'string', enum: ['active', 'paused', 'completed', 'abandoned'], description: 'Mission lifecycle status. Defaults to active on create.' },\n },\n required: ['title'],\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 + 'Unlike mesh_status (which surfaces live + recent missions), this returns every mission regardless of status by default, '\n + 'so paused/abandoned/completed missions are never hidden. Filter with `status` to scope (e.g. [\"paused\"] to find paused missions). '\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 + '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 to return missions of every status.',\n },\n verbose: { type: 'boolean', description: 'Return full goal text instead of a capped preview. Defaults to false (compact).' },\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_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_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_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_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\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_CHANGE_IMPACT_CONFIG_SCHEMA_TOOL = {\n name: 'mesh_change_impact_config_schema',\n description: 'Return the Change Impact config JSON schema and supported repo-local config locations. 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. Declarative only — config is parsed, never executed.',\n inputSchema: { type: 'object' as const, properties: {} },\n};\n\nexport const MESH_VALIDATE_CHANGE_IMPACT_CONFIG_TOOL = {\n name: 'mesh_validate_change_impact_config',\n description: '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) from the repo unless an inline config is provided.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Optional node/workspace whose change-impact 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_CHANGE_IMPACT_CONFIG_TOOL = {\n name: 'mesh_suggest_change_impact_config',\n description: 'Suggest a Change Impact config scaffold from the repo package layout (web-* → web-only, others → daemon-runtime, plus docs/license markers as non-runtime). Heuristic scaffold only — the draft must be reviewed and saved before it takes effect; nothing is executed.',\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_INIT_TOOL = {\n name: 'mesh_init',\n description: 'One-click mesh onboarding for an existing git project. Detects installed CLI providers, suggests Refinery (.adhdev/refine.json) and worktree bootstrap (.adhdev/worktree_bootstrap.json) configs, optionally writes them to disk, and recommends a node providerPriority from the detected providers. 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.',\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_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). Requires a configured panel (mesh_magi_panel_set) resolving to ≥2 (node, provider) targets; never silently degrades to N=1.',\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 panel: { type: 'string', description: 'Named panel from meshes.json (mesh_magi_panel_set). Falls back to a panel named \"default\" if omitted; errors clearly if none exists. Ignored when inline members are provided.' },\n members: {\n type: 'array',\n description: 'Inline ad-hoc panel override (NOT persisted): same member shape as a configured panel. When present, the named panel is ignored. Maximize distinct providers AND machines for real independence.',\n items: {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Optional — pin to a specific mesh node id.' },\n capabilityTags: { type: 'array', items: { type: 'string' }, description: 'Optional routing tags (ANDed with the provider tag) when nodeId is absent.' },\n provider: { type: 'string', description: 'REQUIRED — provider type, e.g. claude-cli / codex-cli / hermes-cli / gemini-cli.' },\n n: { type: 'number', description: 'Optional per-member replica count (default 1).' },\n },\n required: ['provider'],\n },\n },\n n: { type: 'number', description: 'Global replica override per member (clamped by the total-replica guard cap, default 12).' },\n task_kind: { type: 'string', enum: ['claim_audit', 'rca', 'design', 'freeform'], description: 'Selects the SINGLE output schema injected into each replica prompt and the strict parser used at collection (no schema-on-schema conflict). claim_audit (DEFAULT, backward-compatible): {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 members 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'],\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_PANEL_SET_TOOL = {\n name: 'mesh_magi_panel_set',\n description: 'Upsert a named MAGI panel into machine-local ~/.adhdev/meshes.json. A panel is a standing set of independent (node × provider) members that a future mesh_magi_review fans the same question out to. Maximize DISTINCT providers AND distinct machines — that diversity is exactly what synthesis rewards; a single-provider/single-machine panel still runs but its agreements are flagged source-coupled. Follows the mesh_init write/overwrite/dry-run precedent: defaults to dry-run (write=false) and never clobbers an existing panel unless overwrite=true.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n panel_name: { type: 'string', description: 'Panel name key, e.g. \"design-review\".' },\n config: {\n type: 'object',\n description: 'Panel config: { description?, members:[{ provider (REQUIRED), nodeId?, capabilityTags?, n? }], defaultN?, defaultKind? }.',\n properties: {\n description: { type: 'string' },\n defaultKind: {\n type: 'string',\n enum: ['claim_audit', 'rca', 'design'],\n description: 'Optional NON-binding default output kind applied when a mesh_magi_review on this panel omits task_kind. Priority is always task_kind > defaultKind > claim_audit, so it never overrides an explicit per-run kind. \"freeform\" is NOT allowed (it contributes no structured claims to cross-verification) and is dropped with a warning.',\n },\n members: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Optional — pin to a specific mesh node id.' },\n capabilityTags: { type: 'array', items: { type: 'string' }, description: 'Optional routing tags (ANDed with the provider tag) when nodeId is absent.' },\n provider: { type: 'string', description: 'REQUIRED — provider type, e.g. claude-cli / codex-cli / hermes-cli / gemini-cli.' },\n n: { type: 'number', description: 'Optional per-member replica count (default 1).' },\n },\n required: ['provider'],\n },\n },\n defaultN: { type: 'number', description: 'Replicas per member when member.n is absent (default 1).' },\n },\n required: ['members'],\n },\n write: { type: 'boolean', description: 'When true, persist to meshes.json. Defaults false (dry-run preview of the normalized panel).' },\n overwrite: { type: 'boolean', description: 'When true, replace an existing panel of the same name. Defaults false.' },\n },\n required: ['panel_name', 'config'],\n },\n};\n\nexport const MESH_MAGI_PANEL_LIST_TOOL = {\n name: 'mesh_magi_panel_list',\n description: 'List configured MAGI panels and resolve each member\\'s (node, provider) availability against the current mesh. Read-only. Use to confirm a panel resolves to ≥2 independent targets before mesh_magi_review, and to see whether a panel would collapse to a single provider/machine (source-coupled).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n panel: { type: 'string', description: 'Optional — list only this panel. Omit to list all configured panels.' },\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_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_CLONE_NODE_TOOL,\n MESH_REMOVE_NODE_TOOL,\n MESH_REFINE_NODE_TOOL,\n MESH_REFINE_BATCH_TOOL,\n MESH_REFINE_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_REFINE_CONFIG_TOOL,\n MESH_SUGGEST_REFINE_CONFIG_TOOL,\n MESH_CHANGE_IMPACT_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_SUGGEST_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_INIT_TOOL,\n MESH_REFINE_PLAN_TOOL,\n MESH_CLEANUP_SESSIONS_TOOL,\n MESH_PRUNE_STALE_DIRECT_TOOL,\n MESH_TASK_HISTORY_TOOL,\n MESH_RECORD_NOTE_TOOL,\n MESH_RECONCILE_LEDGER_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_PANEL_SET_TOOL,\n MESH_MAGI_PANEL_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\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 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 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 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 };\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 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 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 } 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 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 triggerMeshQueueAndReport,\n unwrapCommandPayload,\n} from './mesh-tools-internal.js';\nimport type {\n MeshContext,\n QueueViewMode,\n} from './mesh-tools-internal.js';\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 },\n): Promise<string> {\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 // 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 try {\n const task = enqueueTask(ctx.mesh.id, args.message, { taskMode, ...(readonly ? { readonly: true } : {}), requiredTags, dependsOn, missionId, targetNodeId, ...(ctx.coordinatorSessionId ? { sourceCoordinatorSessionId: ctx.coordinatorSessionId } : {}) });\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 ...(targetNodeId ? { targetNodeId } : {}),\n ...(preferWorktree && !explicitTargetRaw && !targetNodeId ? { preferWorktreeNoOp: true } : {}),\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 const coordinatorDaemonId = resolveCoordinatorDaemonId(ctx);\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 // 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: args.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(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((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 ...(targetNodeId ? { targetNodeId } : {}),\n ...(preferWorktree && !explicitTargetRaw && !targetNodeId ? { preferWorktreeNoOp: true } : {}),\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 computeMeshMissionStats,\n computeMeshTaskStats,\n drainCoordinatorPendingEvents,\n getLedgerSummary,\n isLocalControlPlaneNode,\n listMeshMissionSummaries,\n readLedgerEntries,\n readLedgerSlice,\n readLedgerSliceFromStore,\n readString,\n refreshMeshFromDaemon,\n slimLedgerPayload,\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 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 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 // 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 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 meshMissionUpsert(\n ctx: MeshContext,\n args: { mission_id?: string; missionId?: string; title: string; goal?: string; status?: string },\n): Promise<string> {\n try {\n const mission = upsertMeshMission(ctx.mesh.id, {\n id: readString(args.mission_id) || readString(args.missionId) || undefined,\n title: args.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\nexport async function meshMissionList(\n ctx: MeshContext,\n args: { status?: string | string[]; verbose?: boolean; include_magi?: boolean; includeMagi?: boolean } = {},\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 missions = listMeshMissionSummaries(ctx.mesh.id, {\n statuses,\n verbose: args.verbose === true,\n includeMagi,\n }).map(mission => {\n try {\n return { ...mission, stats: computeMeshMissionStats(ctx.mesh.id, mission.id) };\n } catch {\n return mission;\n }\n });\n return JSON.stringify({\n success: true,\n count: missions.length,\n ...(statuses ? { statusFilter: statuses } : {}),\n ...(includeMagi ? { includeMagi: true } : { magiCompletedHidden: true }),\n missions,\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 const result = await commandForNode(ctx, ctx.mesh.nodes[0], 'get_mesh_review_inbox', {\n meshId,\n inlineMesh: ctx.mesh,\n });\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 getMagiPanel,\n getMeshMission,\n getQueue,\n isWeakCompletionEvidence,\n listMagiPanels,\n MAGI_RAW_ANSWER_CAP,\n meshNodeIdMatches,\n nodeSatisfiesRequiredTags,\n normalizeMagiPanel,\n normalizeMeshCapabilityTags,\n randomUUID,\n readLedgerEntries,\n readString,\n refreshMeshFromDaemon,\n resolveCoordinatorNode,\n triggerMeshQueueAndReport,\n unwrapCommandPayload,\n upsertMagiPanel,\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 MagiPanel,\n MagiPanelMember,\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, MagiPanelDefaultKind } 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\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\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 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 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 memberIndex: number;\n provider: string;\n /** Resolved concrete node id (pinned member), 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}\n\nexport interface MagiUnavailableMember {\n memberIndex: number;\n provider: string;\n nodeId?: string;\n capabilityTags: string[];\n reason: string;\n}\n\n/** Per-member resolution detail (for mesh_magi_panel_list + the git-stale exclusion). */\nexport interface MagiMemberResolution {\n memberIndex: 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 /** Excluded from the fan-out (unavailable, 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 unavailableMembers: MagiUnavailableMember[];\n /** The commit the panel is being resolved against (coordinator HEAD); undefined when unknown. */\n referenceCommit?: string;\n /** Per-member resolution detail, aligned to panel.members order. */\n memberResolutions: MagiMemberResolution[];\n /** Members excluded because they are git-stale (different HEAD) and include_stale was not set. */\n staleMembers: MagiMemberResolution[];\n /** Git-stale members that were nonetheless INCLUDED because include_stale=true (warning surface). */\n includedStaleMembers: MagiMemberResolution[];\n}\n\nfunction replicaCountFor(member: MagiPanelMember, panel: MagiPanel, globalN?: number): number {\n const n = member.n ?? panel.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 * 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 panel against the live mesh nodes into a concrete fan-out plan:\n * expand each available member 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 panel: MagiPanel,\n nodes: LocalMeshNodeEntry[],\n opts: { n?: number; maxReplicas?: number; referenceCommit?: string; includeStale?: boolean } = {},\n): MagiFanoutPlan {\n const cap = Math.max(1, Math.floor(opts.maxReplicas ?? MAGI_MAX_REPLICAS));\n const members = Array.isArray(panel.members) ? panel.members : [];\n const referenceCommit = typeof opts.referenceCommit === 'string' && opts.referenceCommit.trim() ? opts.referenceCommit.trim() : undefined;\n const includeStale = opts.includeStale === true;\n const replicas: MagiReplicaPlan[] = [];\n const unavailableMembers: MagiUnavailableMember[] = [];\n const memberResolutions: MagiMemberResolution[] = [];\n const targetKeys = new Set<string>();\n const providerSet = new Set<string>();\n const nodeTargetSet = new Set<string>();\n let totalRequested = 0;\n\n members.forEach((member, memberIndex) => {\n const provider = member.provider;\n const capabilityTags = normalizeMeshCapabilityTags(member.capabilityTags);\n const requiredTags = normalizeMeshCapabilityTags([`provider=${provider}`, ...capabilityTags]);\n const count = replicaCountFor(member, panel, 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 (member.nodeId) {\n const node = nodes.find(n => meshNodeIdMatches(n as any, member.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 unavailableMembers.push({\n memberIndex,\n provider,\n nodeId: member.nodeId,\n capabilityTags,\n reason: member.nodeId\n ? `pinned node '${member.nodeId}' is not a member of this mesh`\n : `no mesh node satisfies required tags [${requiredTags.join(', ')}]`,\n });\n memberResolutions.push({ memberIndex, provider, nodeId: member.nodeId, capabilityTags, available: false, gitStale: false, excluded: true, reason: 'unavailable' });\n return;\n }\n\n // Git staleness vs the reference commit. A member 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 return !h || h === referenceCommit;\n });\n if (freshCandidate) {\n headCommit = nodeHeadCommit(freshCandidate);\n if (member.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 member 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 member fresh.\n headCommit = nodeHeadCommit(freshCandidate);\n if (member.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: MagiMemberResolution = {\n memberIndex,\n provider,\n nodeId: targetNodeId ?? member.nodeId,\n capabilityTags,\n available: true,\n ...(headCommit ? { headCommit } : {}),\n gitStale,\n excluded: false,\n };\n\n // Default-exclude a git-stale member (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 resolution.reason = referenceCommit\n ? `git-stale: node HEAD ${headCommit ?? '(unknown)'} differs from reference ${referenceCommit}`\n : `git-stale: node reports drift from its upstream (behind/ahead) and no coordinator reference commit is known`;\n memberResolutions.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 memberResolutions.push(resolution);\n for (let i = 0; i < count; i++) {\n replicas.push({ memberIndex, provider, targetNodeId, capabilityTags, requiredTags });\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 // git-stale exclusion — so the ≥2-independent-target guard re-checks post-exclusion\n // and never silently degrades to N=1.\n const staleMembers = memberResolutions.filter(m => m.gitStale && m.excluded);\n const includedStaleMembers = memberResolutions.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 unavailableMembers,\n ...(referenceCommit ? { referenceCommit } : {}),\n memberResolutions,\n staleMembers,\n includedStaleMembers,\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// ─── 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\nexport async function meshMagiPanelSet(\n ctx: MeshContext,\n args: { panel_name?: string; panelName?: string; config?: unknown; write?: boolean; overwrite?: boolean },\n): Promise<string> {\n const panelName = readString(args.panel_name) || readString(args.panelName);\n if (!panelName) return JSON.stringify({ success: false, error: 'panel_name required' });\n const write = args.write === true;\n try {\n if (!write) {\n // Dry-run: normalize + validate via a throwaway upsert path WITHOUT persisting.\n // We re-use the same validation by constructing the normalized panel through\n // the accessor only on write; for dry-run we validate shape inline here.\n const preview = previewMagiPanel(args.config);\n return JSON.stringify({\n success: true,\n dryRun: true,\n panelName,\n panel: preview,\n note: 'Dry-run only — no file written. Re-run with write=true to persist to ~/.adhdev/meshes.json.',\n }, null, 2);\n }\n const panel = upsertMagiPanel(panelName, args.config, { overwrite: args.overwrite === true });\n return JSON.stringify({\n success: true,\n written: true,\n panelName,\n panel,\n nextAction: 'Verify resolution with mesh_magi_panel_list, then invoke mesh_magi_review({ panel, question, target }).',\n }, null, 2);\n } catch (e: any) {\n const message = e?.message || String(e);\n const code = message.includes('magi_panel_exists') ? 'magi_panel_exists'\n : message.includes('invalid_magi_panel') ? 'invalid_magi_panel'\n : undefined;\n return JSON.stringify({ success: false, ...(code ? { code } : {}), error: message });\n }\n}\n\n/**\n * Validate + normalize a panel config for dry-run preview. Delegates to the single\n * source-of-truth normalizer (daemon-core normalizeMagiPanel) so dry-run preview,\n * persisted upsert, and the inline-member ad-hoc path all share identical validation\n * (provider required, tag dedup, replica clamp, member cap) — no duplicated rules.\n */\nfunction previewMagiPanel(config: unknown): MagiPanel {\n return normalizeMagiPanel(config);\n}\n\n/**\n * Build a one-off ad-hoc MAGI panel from inline `members` (mesh_magi_review members\n * override) WITHOUT persisting anything to meshes.json. Same member shape and same\n * normalizer as a named panel, so an inline panel resolves through the identical\n * fan-out / synthesis pipeline. Pure. Throws invalid_magi_panel on a malformed list.\n */\nexport function buildInlineMagiPanel(members: unknown, opts: { defaultN?: number; description?: string } = {}): MagiPanel {\n return normalizeMagiPanel({\n members,\n ...(opts.defaultN !== undefined ? { defaultN: opts.defaultN } : {}),\n description: opts.description ?? 'inline ad-hoc panel',\n });\n}\n\nexport async function meshMagiPanelList(\n ctx: MeshContext,\n args: { panel?: string } = {},\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const all = listMagiPanels();\n const only = readString(args.panel);\n const names = only ? (all[only] ? [only] : []) : Object.keys(all);\n if (only && names.length === 0) {\n return JSON.stringify({ success: false, code: 'magi_panel_not_found', error: `panel '${only}' is not configured`, configuredPanels: Object.keys(all) });\n }\n const referenceCommit = resolveMagiReferenceCommit(ctx);\n const panels = names.map(name => {\n const panel = all[name];\n // Resolve with the reference commit so the listing reflects which members are\n // git-stale and would be excluded by default (panel_list itself never dispatches).\n const plan = buildMagiFanoutPlan(panel, ctx.mesh.nodes, { referenceCommit });\n return {\n name,\n description: panel.description,\n // Per-member gitStale boolean alongside the raw member definition.\n members: panel.members.map((m, i) => {\n const res = plan.memberResolutions.find(r => r.memberIndex === i);\n return {\n ...m,\n gitStale: res?.gitStale === true,\n ...(res?.headCommit ? { headCommit: res.headCommit } : {}),\n };\n }),\n defaultN: panel.defaultN ?? 1,\n resolution: {\n referenceCommit: referenceCommit ?? null,\n totalReplicas: plan.totalAfterCap,\n distinctTargets: plan.distinctTargets,\n distinctProviders: plan.distinctProviders,\n distinctMachines: plan.distinctNodeTargets,\n enoughTargets: plan.enoughTargets,\n coupled: plan.coupled,\n unavailableMembers: plan.unavailableMembers,\n staleMembers: plan.staleMembers,\n },\n ...(plan.staleMembers.length > 0 ? { gitStaleWarning: `${plan.staleMembers.length} member(s) are git-stale (HEAD differs from reference ${referenceCommit ?? '(unknown)'}) and are excluded by default; pass include_stale=true to mesh_magi_review to include them.` } : {}),\n ...(plan.coupled ? { warning: 'This panel collapses to a single provider or single machine — its agreements would be flagged source-coupled.' } : {}),\n ...(!plan.enoughTargets ? { error: `Resolves to ${plan.distinctTargets} distinct (node, provider) target(s) after git-stale exclusion; MAGI requires ≥${MAGI_MIN_TARGETS}.` } : {}),\n };\n });\n return JSON.stringify({ success: true, count: panels.length, ...(referenceCommit ? { referenceCommit } : {}), panels }, null, 2);\n}\n\nexport async function meshMagiReview(\n ctx: MeshContext,\n args: {\n question?: string;\n target?: string;\n artifacts?: string[];\n panel?: string;\n members?: unknown;\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 // MAGI-REDESIGN: capture the EXPLICIT output kind (if any) here; the final taskKind\n // is resolved AFTER the panel is loaded so a named panel's optional defaultKind can\n // fill in. Strict priority: args.task_kind > panel.defaultKind > claim_audit. We must\n // not normalize-to-default yet — that would erase the \"no explicit kind\" signal and\n // make panel.defaultKind unreachable.\n const explicitTaskKind = args.task_kind ?? args.taskKind;\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 // 1. Resolve the panel. Inline `members` take precedence (ad-hoc panel, not\n // persisted); otherwise look up the named panel (falling back to \"default\").\n const hasInlineMembers = Array.isArray(args.members) && args.members.length > 0;\n let panel: MagiPanel | undefined;\n let panelName: string;\n if (hasInlineMembers) {\n panelName = '(inline)';\n try {\n panel = buildInlineMagiPanel(args.members, { defaultN: args.n });\n } catch (e: any) {\n return JSON.stringify({\n success: false,\n code: 'invalid_magi_panel',\n error: e?.message || String(e),\n hint: 'Inline members use the same shape as a configured panel: [{ provider (REQUIRED), nodeId?, capabilityTags?, n? }].',\n });\n }\n } else {\n panelName = readString(args.panel) || 'default';\n panel = getMagiPanel(panelName);\n }\n if (!panel) {\n return JSON.stringify({\n success: false,\n code: 'magi_panel_missing',\n error: `MAGI panel '${panelName}' is not configured. Define it first with mesh_magi_panel_set, pass inline members, and inspect resolution with mesh_magi_panel_list.`,\n configuredPanels: Object.keys(listMagiPanels()),\n });\n }\n\n // Resolve the final output kind now that the panel is loaded. Strict priority:\n // explicit args.task_kind > panel.defaultKind > claim_audit (the DEFAULT_TASK_KIND\n // fallback inside normalizeMagiTaskKind). An explicit kind always wins, so an\n // automation already passing task_kind keeps its exact schema (backward-compatible).\n // INLINE-MEMBER ASYMMETRY (intentional): buildInlineMagiPanel never sets defaultKind,\n // so the inline path naturally falls through to claim_audit — there is no panel\n // identity to carry a default. normalizeMagiTaskKind also drops a panel-stored\n // 'freeform' defensively (it should already be rejected at write time).\n const taskKind = normalizeMagiTaskKind(explicitTaskKind ?? panel.defaultKind);\n\n // 2. Plan the fan-out. Git-stale members (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 referenceCommit = resolveMagiReferenceCommit(ctx);\n const plan = buildMagiFanoutPlan(panel, ctx.mesh.nodes, { n: args.n, referenceCommit, includeStale });\n if (!plan.enoughTargets) {\n const droppedByStale = plan.staleMembers.length > 0;\n return JSON.stringify({\n success: false,\n code: droppedByStale ? 'magi_insufficient_targets_after_stale_exclusion' : 'magi_insufficient_targets',\n error: droppedByStale\n ? `Panel '${panelName}' resolves to only ${plan.distinctTargets} independent (node, provider) target(s) AFTER excluding ${plan.staleMembers.length} git-stale member(s) (HEAD differs from reference ${referenceCommit ?? '(unknown)'}); MAGI requires ≥${MAGI_MIN_TARGETS} and never silently degrades to N=1.`\n : `Panel '${panelName}' resolves to ${plan.distinctTargets} available (node, provider) target(s); MAGI requires ≥${MAGI_MIN_TARGETS} and never silently degrades to N=1.`,\n ...(referenceCommit ? { referenceCommit } : {}),\n unavailableMembers: plan.unavailableMembers,\n ...(droppedByStale ? { staleMembers: plan.staleMembers } : {}),\n hint: 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). Use mesh_magi_panel_list to inspect resolution.'\n : 'Use mesh_magi_panel_list to see resolution, mesh_magi_panel_set to fix members, mesh_status to confirm nodes/providers are online.',\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 ...(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 ...(hasInlineMembers ? { inline: true } : {}),\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 git-stale handling: which members were excluded (default), or included\n // despite being stale (include_stale=true) — the latter makes results git-skewed.\n ...(plan.staleMembers.length > 0 ? {\n gitStaleExcluded: plan.staleMembers,\n gitStaleWarning: `${plan.staleMembers.length} git-stale member(s) (HEAD ≠ reference ${plan.referenceCommit ?? '(unknown)'}) were excluded from this fan-out; pass include_stale=true to include them.`,\n } : {}),\n ...(plan.includedStaleMembers.length > 0 ? {\n gitStaleIncluded: plan.includedStaleMembers,\n gitStaleWarning: `include_stale=true: ${plan.includedStaleMembers.length} git-stale member(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 for (const [nodeId, group] of targets) {\n if (group.sessionIds.length === 0) continue;\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 perNode.push({ nodeId, skipped: 'node_not_in_live_mesh', sessionIds: group.sessionIds });\n continue;\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 });\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 cleanedSessionCount += deleted + stopped;\n perNode.push({\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 } catch (e: any) {\n perNode.push({ nodeId, error: e?.message || String(e), 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 // 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 → only finalize at the deadline.\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","// 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 buildMeshReadChatCacheFallback,\n buildMissingCoordinatorDaemonIdFailure,\n buildMissingNodeReadChatRecovery,\n buildQueueTriggerGuidance,\n collectLiveStatusProbe,\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 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 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';\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 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, args.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: args.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(args.message, 'p2p_direct', {\n taskId,\n taskMode,\n providerType,\n targetSessionId: dispatchedSessionId,\n ...(ctx.coordinatorSessionId ? { coordinatorSessionId: ctx.coordinatorSessionId } : {}),\n }),\n });\n insertDirectDispatch(ctx.mesh.id, {\n taskId,\n nodeId: args.node_id,\n sessionId: dispatchedSessionId,\n providerType: providerType || undefined,\n message: args.message,\n taskMode: taskMode || undefined,\n via: 'p2p_direct',\n dispatchedAt,\n });\n if (missionId) {\n recordDirectDispatchTask(ctx.mesh.id, args.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: args.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(args.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 }),\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: args.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: args.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, args.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: args.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 const task = enqueueTask(ctx.mesh.id, args.message, {\n targetNodeId: args.node_id,\n targetSessionId: args.session_id,\n taskMode,\n ...(readonly ? { readonly: true } : {}),\n ...(missionId ? { missionId } : {}),\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\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 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 = 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 const existing = sessions.find(session =>\n !isTerminalSessionRecord(session)\n && isMeshOwnedDelegateSession(session, ctx.mesh.id, args.node_id));\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\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\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\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\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,\n meshLaunchSession, meshGitStatus, meshReadNodeLogs, meshFastForwardNode, meshRestartDaemon, meshCheckpoint, meshApprove,\n meshCloneNode, meshRemoveNode, meshRefineNode,\n meshRefineConfigSchema, meshValidateRefineConfig, meshSuggestRefineConfig, meshInit, meshRefinePlan, meshRefineBatch,\n meshChangeImpactConfigSchema, meshValidateChangeImpactConfig, meshSuggestChangeImpactConfig,\n meshCleanupSessions, meshPruneStaleDirect, meshTaskHistory, meshRecordNote, meshReconcileLedger, meshMissionUpsert,\n meshMissionList, meshReviewInbox,\n meshMagiReview, meshMagiCollect, meshMagiPanelSet, meshMagiPanelList\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_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_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_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_change_impact_config_schema': text = await meshChangeImpactConfigSchema(meshCtx); break;\n case 'mesh_validate_change_impact_config': text = await meshValidateChangeImpactConfig(meshCtx, a as any); break;\n case 'mesh_suggest_change_impact_config': text = await meshSuggestChangeImpactConfig(meshCtx, a as any); break;\n case 'mesh_init': text = await meshInit(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_record_note': text = await meshRecordNote(meshCtx, a as any); break;\n case 'mesh_reconcile_ledger': text = await meshReconcileLedger(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_panel_set': text = await meshMagiPanelSet(meshCtx, a as any); break;\n case 'mesh_magi_panel_list': text = await meshMagiPanelList(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,w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Y,QAAQ,iBAAiB,QAAQ,aAAa,KAAK,IAAI,CAAC,GAAG;AACrE,eAAS,KAAK,EAAE,CAAC;AAAA,IACnB,WAAW,KAAK,WAAW,cAAc,GAAG;AAC1C,eAAS,IAAI,MAAM,eAAe,MAAM;AAAA,IAC1C,WAAW,QAAQ,YAAY,QAAQ,MAAM;AAC3C,gBAAU;AACV,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AAGA,MAAI,CAAC,YAAY,IAAI,gBAAiB,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,MAAO,gBAAe;AAAA,EAC3D;AAEA,QAAM,OAAO,iBAAiB,UAAU,IAAI,qBAAqB,QAAQ;AACzE,SAAO,EAAE,MAAM,MAAM,UAAU,OAAO;AACxC;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":["now","import_daemon_core","import_daemon_core","import_daemon_core","task","triggerPreferredNodeId","slice","import_daemon_core","result","distinctProviders","distinctNodes","needsVerification","staleTaskIds","staleReasons","result","lines","os","server","stdioTransport"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/transports/ipc.ts","../src/tools/chat-compact.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-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 if (payload?.success === false) {\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 * 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 * 29 tools: mesh_status, mesh_mission_upsert, mesh_mission_list, 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 * mesh_review_inbox\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 type { LocalMeshEntry, LocalMeshNodeEntry, MeshActiveWorkSummary, RepoMeshPolicy, RepoMeshRelatedRepo } from '@adhdev/daemon-core';\nimport {\n daemonIdsEquivalent,\n meshNodeIdMatches,\n appendLedgerEntry,\n appendRemoteLedgerEntries,\n buildCompactStaleDirectWorkSummary,\n buildMeshActiveWork,\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 drainPendingMeshCoordinatorEvents,\n enqueueTask,\n computeMeshMissionStats,\n computeMeshTaskStats,\n getActiveMeshMissionSummaries,\n getMeshStatusMissionSummaries,\n getMeshStatusMissionsCompact,\n listMeshMissionSummaries,\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 readLedgerEntries,\n readLedgerSlice,\n readLedgerSliceFromStore,\n reconcileDirectDispatchCompletionFromTranscript,\n recordMeshToolCall,\n requeueTask,\n resolveMeshSurfacedSessionPreview,\n resolveDelegatedWorkerAutoApprove,\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_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_RECONCILE_LEDGER_TOOL,\n MESH_PRUNE_STALE_DIRECT_TOOL,\n MESH_REFINE_NODE_TOOL,\n MESH_REFINE_BATCH_TOOL,\n MESH_REFINE_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_REFINE_CONFIG_TOOL,\n MESH_SUGGEST_REFINE_CONFIG_TOOL,\n MESH_CHANGE_IMPACT_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_SUGGEST_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_INIT_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 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 drainPendingMeshCoordinatorEvents,\n enqueueTask,\n getActiveDirectDispatches,\n getActiveMeshMissionSummaries,\n getLedgerSummary,\n getMagiPanel,\n getMeshMission,\n getMeshStatusMissionSummaries,\n getMeshStatusMissionsCompact,\n getQueue,\n listMagiPanels,\n getSessionRecoveryContext,\n insertDirectDispatch,\n isP2pRelayTransportFailure,\n isWeakCompletionEvidence,\n listMeshMissionSummaries,\n markStaleDirectDispatches,\n meshNodeIdMatches,\n nodeSatisfiesRequiredTags,\n normalizeMagiPanel,\n normalizeMeshCapabilityTags,\n pruneStaleDirectDispatches,\n readLedgerEntries,\n readLedgerSlice,\n readLedgerSliceFromStore,\n reconcileDirectDispatchCompletionFromTranscript,\n recordDirectDispatchTask,\n recordMeshToolCall,\n requeueTask,\n resolveDelegatedWorkerAutoApprove,\n resolveMeshSurfacedSessionPreview,\n summarizeMeshAsyncRefineJobs,\n upsertMagiPanel,\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 MagiPanelDefaultKind,\n MagiPanel,\n MagiPanelMember,\n MagiReplicaGitRef,\n MagiResponseSource,\n MagiSynthesis,\n MagiSynthesizedResponse,\n MeshActiveWorkSummary,\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\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 },\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 };\n}\n\nexport function findNode(mesh: LocalMeshEntry, nodeId: string): LocalMeshNodeEntry {\n const node = mesh.nodes.find(n => meshNodeIdMatches(n, 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, nodeId));\n if (hit && !hit.isLocalWorktree) return hit;\n\n await refreshMeshFromDaemon(ctx);\n\n const refreshed = ctx.mesh.nodes.find(n => meshNodeIdMatches(n, 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, nodeId));\n if (hit && !hit.isLocalWorktree) return hit;\n\n await refreshMeshFromDaemon(ctx);\n\n return ctx.mesh.nodes.find(n => meshNodeIdMatches(n, 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\nexport function readFinalAssistantTranscriptEvidence(payload: any): { finalSummary?: string; transcriptMessageAt?: string } {\n const rawMessages = Array.isArray(payload?.messages) ? payload.messages : [];\n const finalAssistant = [...rawMessages]\n .reverse()\n .filter(isCoordinatorVisibleMessage)\n .find((message: any) => {\n const role = String(message?.role ?? '').toLowerCase();\n return (role === 'assistant' || role === 'agent') && messageContent(message).trim();\n });\n const finalSummary = messageContent(finalAssistant).trim()\n || (typeof payload?.summary === 'string' && payload.summary.trim() ? payload.summary.trim() : undefined);\n return {\n finalSummary,\n transcriptMessageAt: finalAssistant ? readMessageTimestampIso(finalAssistant) : undefined,\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 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.\nexport const COMPACT_NODES_TOTAL_BYTE_BUDGET = 13000;\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 const statusResult = 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\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/**\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 const providers = readProviderPriority(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 const statusResult = await commandForNode(ctx, node, 'get_status_metadata', {});\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): 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 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 };\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\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', pendingEventArgs) as any;\n const hasLiveCliCoordinator = unwrapCommandPayload(raw)?.hasLiveCliCoordinator === true\n || raw?.hasLiveCliCoordinator === 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) {\n // Pure-MCP coordinator: the LLM tool result is the only surface. Do NOT\n // re-forward (that re-queues with no PTY → the drain-without-inject loop).\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 const events = (drainPendingMeshCoordinatorEvents(ctx.mesh.id, ctx.localDaemonId) 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, 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 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 },\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_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. 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 inputSchema: {\n type: 'object' as const,\n properties: {\n mission_id: { type: 'string', description: 'Mission id to update. Omit to create a new mission.' },\n title: { type: 'string', description: 'Short mission title.' },\n goal: { type: 'string', description: 'Free-text mission goal/definition of done.' },\n status: { type: 'string', enum: ['active', 'paused', 'completed', 'abandoned'], description: 'Mission lifecycle status. Defaults to active on create.' },\n },\n required: ['title'],\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 + 'Unlike mesh_status (which surfaces live + recent missions), this returns every mission regardless of status by default, '\n + 'so paused/abandoned/completed missions are never hidden. Filter with `status` to scope (e.g. [\"paused\"] to find paused missions). '\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 + '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 to return missions of every status.',\n },\n verbose: { type: 'boolean', description: 'Return full goal text instead of a capped preview. Defaults to false (compact).' },\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_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_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_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_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\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_CHANGE_IMPACT_CONFIG_SCHEMA_TOOL = {\n name: 'mesh_change_impact_config_schema',\n description: 'Return the Change Impact config JSON schema and supported repo-local config locations. 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. Declarative only — config is parsed, never executed.',\n inputSchema: { type: 'object' as const, properties: {} },\n};\n\nexport const MESH_VALIDATE_CHANGE_IMPACT_CONFIG_TOOL = {\n name: 'mesh_validate_change_impact_config',\n description: '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) from the repo unless an inline config is provided.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n node_id: { type: 'string', description: 'Optional node/workspace whose change-impact 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_CHANGE_IMPACT_CONFIG_TOOL = {\n name: 'mesh_suggest_change_impact_config',\n description: 'Suggest a Change Impact config scaffold from the repo package layout (web-* → web-only, others → daemon-runtime, plus docs/license markers as non-runtime). Heuristic scaffold only — the draft must be reviewed and saved before it takes effect; nothing is executed.',\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_INIT_TOOL = {\n name: 'mesh_init',\n description: 'One-click mesh onboarding for an existing git project. Detects installed CLI providers, suggests Refinery (.adhdev/refine.json) and worktree bootstrap (.adhdev/worktree_bootstrap.json) configs, optionally writes them to disk, and recommends a node providerPriority from the detected providers. 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.',\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_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). NO pre-authored panel is required: omit `panel` and `members` and pass only `task_kind` (plus the question) to auto-synthesize a maximally-diverse cross-provider PRESET panel from the LIVE mesh — the resolver enumerates every routable (node × provider) pair (seeing a node\\'s 2nd+ priority providers, matching the queue\\'s per-provider claim check) and greedily picks the most independent set for that kind. Still resolves to ≥2 (node, provider) targets; never silently degrades to N=1 (errors magi_insufficient_providers if the live mesh cannot supply them).',\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 panel: { type: 'string', description: 'Named panel from meshes.json (mesh_magi_panel_set). When omitted: if task_kind is given (and no inline members), a maximally-diverse cross-provider preset panel is auto-synthesized from the live mesh; otherwise falls back to a panel named \"default\" and errors clearly if none exists. Ignored when inline members are provided.' },\n members: {\n type: 'array',\n description: 'Inline ad-hoc panel override (NOT persisted): same member shape as a configured panel. When present, the named panel is ignored. Maximize distinct providers AND machines for real independence.',\n items: {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Optional — pin to a specific mesh node id.' },\n capabilityTags: { type: 'array', items: { type: 'string' }, description: 'Optional routing tags (ANDed with the provider tag) when nodeId is absent.' },\n provider: { type: 'string', description: 'REQUIRED — provider type, e.g. claude-cli / codex-cli / hermes-cli / gemini-cli.' },\n n: { type: 'number', description: 'Optional per-member replica count (default 1).' },\n },\n required: ['provider'],\n },\n },\n n: { type: 'number', description: 'Global replica override per member (clamped by the total-replica guard cap, default 12).' },\n task_kind: { type: 'string', enum: ['claim_audit', 'rca', 'design', 'freeform'], description: 'Selects the SINGLE output schema injected into each replica prompt and the strict parser used at collection (no schema-on-schema conflict). claim_audit (DEFAULT, backward-compatible): {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. When `panel` and `members` are both omitted, task_kind ALSO drives auto-synthesis of a maximally-diverse cross-provider preset panel from the live mesh (design fans out widest, claim_audit/rca a triad, freeform the minimum pair). 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 members 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'],\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_PANEL_SET_TOOL = {\n name: 'mesh_magi_panel_set',\n description: 'Upsert a named MAGI panel into machine-local ~/.adhdev/meshes.json. A panel is a standing set of independent (node × provider) members that a future mesh_magi_review fans the same question out to. Maximize DISTINCT providers AND distinct machines — that diversity is exactly what synthesis rewards; a single-provider/single-machine panel still runs but its agreements are flagged source-coupled. Follows the mesh_init write/overwrite/dry-run precedent: defaults to dry-run (write=false) and never clobbers an existing panel unless overwrite=true.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n panel_name: { type: 'string', description: 'Panel name key, e.g. \"design-review\".' },\n config: {\n type: 'object',\n description: 'Panel config: { description?, members:[{ provider (REQUIRED), nodeId?, capabilityTags?, n? }], defaultN?, defaultKind? }.',\n properties: {\n description: { type: 'string' },\n defaultKind: {\n type: 'string',\n enum: ['claim_audit', 'rca', 'design'],\n description: 'Optional NON-binding default output kind applied when a mesh_magi_review on this panel omits task_kind. Priority is always task_kind > defaultKind > claim_audit, so it never overrides an explicit per-run kind. \"freeform\" is NOT allowed (it contributes no structured claims to cross-verification) and is dropped with a warning.',\n },\n members: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Optional — pin to a specific mesh node id.' },\n capabilityTags: { type: 'array', items: { type: 'string' }, description: 'Optional routing tags (ANDed with the provider tag) when nodeId is absent.' },\n provider: { type: 'string', description: 'REQUIRED — provider type, e.g. claude-cli / codex-cli / hermes-cli / gemini-cli.' },\n n: { type: 'number', description: 'Optional per-member replica count (default 1).' },\n },\n required: ['provider'],\n },\n },\n defaultN: { type: 'number', description: 'Replicas per member when member.n is absent (default 1).' },\n },\n required: ['members'],\n },\n write: { type: 'boolean', description: 'When true, persist to meshes.json. Defaults false (dry-run preview of the normalized panel).' },\n overwrite: { type: 'boolean', description: 'When true, replace an existing panel of the same name. Defaults false.' },\n },\n required: ['panel_name', 'config'],\n },\n};\n\nexport const MESH_MAGI_PANEL_LIST_TOOL = {\n name: 'mesh_magi_panel_list',\n description: 'List configured MAGI panels and resolve each member\\'s (node, provider) availability against the current mesh. Read-only. Use to confirm a panel resolves to ≥2 independent targets before mesh_magi_review, and to see whether a panel would collapse to a single provider/machine (source-coupled).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n panel: { type: 'string', description: 'Optional — list only this panel. Omit to list all configured panels.' },\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_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_CLONE_NODE_TOOL,\n MESH_REMOVE_NODE_TOOL,\n MESH_REFINE_NODE_TOOL,\n MESH_REFINE_BATCH_TOOL,\n MESH_REFINE_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_REFINE_CONFIG_TOOL,\n MESH_SUGGEST_REFINE_CONFIG_TOOL,\n MESH_CHANGE_IMPACT_CONFIG_SCHEMA_TOOL,\n MESH_VALIDATE_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_SUGGEST_CHANGE_IMPACT_CONFIG_TOOL,\n MESH_INIT_TOOL,\n MESH_REFINE_PLAN_TOOL,\n MESH_CLEANUP_SESSIONS_TOOL,\n MESH_PRUNE_STALE_DIRECT_TOOL,\n MESH_TASK_HISTORY_TOOL,\n MESH_RECORD_NOTE_TOOL,\n MESH_RECONCILE_LEDGER_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_PANEL_SET_TOOL,\n MESH_MAGI_PANEL_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\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 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 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 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 };\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 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 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 } 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 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 triggerMeshQueueAndReport,\n unwrapCommandPayload,\n} from './mesh-tools-internal.js';\nimport type {\n MeshContext,\n QueueViewMode,\n} from './mesh-tools-internal.js';\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 },\n): Promise<string> {\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 // 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 try {\n const task = enqueueTask(ctx.mesh.id, args.message, { taskMode, ...(readonly ? { readonly: true } : {}), requiredTags, dependsOn, missionId, targetNodeId, ...(ctx.coordinatorSessionId ? { sourceCoordinatorSessionId: ctx.coordinatorSessionId } : {}) });\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 ...(targetNodeId ? { targetNodeId } : {}),\n ...(preferWorktree && !explicitTargetRaw && !targetNodeId ? { preferWorktreeNoOp: true } : {}),\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 const coordinatorDaemonId = resolveCoordinatorDaemonId(ctx);\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 // 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: args.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(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((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 ...(targetNodeId ? { targetNodeId } : {}),\n ...(preferWorktree && !explicitTargetRaw && !targetNodeId ? { preferWorktreeNoOp: true } : {}),\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 computeMeshMissionStats,\n computeMeshTaskStats,\n drainCoordinatorPendingEvents,\n getLedgerSummary,\n isLocalControlPlaneNode,\n listMeshMissionSummaries,\n readLedgerEntries,\n readLedgerSlice,\n readLedgerSliceFromStore,\n readString,\n refreshMeshFromDaemon,\n slimLedgerPayload,\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 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 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 // 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 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 meshMissionUpsert(\n ctx: MeshContext,\n args: { mission_id?: string; missionId?: string; title: string; goal?: string; status?: string },\n): Promise<string> {\n try {\n const mission = upsertMeshMission(ctx.mesh.id, {\n id: readString(args.mission_id) || readString(args.missionId) || undefined,\n title: args.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\nexport async function meshMissionList(\n ctx: MeshContext,\n args: { status?: string | string[]; verbose?: boolean; include_magi?: boolean; includeMagi?: boolean } = {},\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 missions = listMeshMissionSummaries(ctx.mesh.id, {\n statuses,\n verbose: args.verbose === true,\n includeMagi,\n }).map(mission => {\n try {\n return { ...mission, stats: computeMeshMissionStats(ctx.mesh.id, mission.id) };\n } catch {\n return mission;\n }\n });\n return JSON.stringify({\n success: true,\n count: missions.length,\n ...(statuses ? { statusFilter: statuses } : {}),\n ...(includeMagi ? { includeMagi: true } : { magiCompletedHidden: true }),\n missions,\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 const result = await commandForNode(ctx, ctx.mesh.nodes[0], 'get_mesh_review_inbox', {\n meshId,\n inlineMesh: ctx.mesh,\n });\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 getMagiPanel,\n getMeshMission,\n getQueue,\n isWeakCompletionEvidence,\n listMagiPanels,\n MAGI_RAW_ANSWER_CAP,\n meshNodeIdMatches,\n nodeSatisfiesRequiredTags,\n normalizeMagiPanel,\n normalizeMeshCapabilityTags,\n randomUUID,\n readProviderPriority,\n readLedgerEntries,\n readString,\n refreshMeshFromDaemon,\n resolveCoordinatorNode,\n triggerMeshQueueAndReport,\n unwrapCommandPayload,\n upsertMagiPanel,\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 MagiPanel,\n MagiPanelMember,\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, MagiPanelDefaultKind } 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// ─── Kind → preset intent table (MAGI-KIND-PRESET) ───\n//\n// A `task_kind` alone (no pre-authored panel name / members) auto-synthesizes the\n// most diverse cross-provider panel the LIVE mesh can supply. This static table is\n// pure INTENT — how wide a spectrum a kind wants, never WHICH provider. The resolver\n// (buildPresetMagiPanelForKind) treats providerPreference as an ordering hint only and\n// is satisfied by ANY mesh that has ≥2 distinct providers (or ≥2 distinct nodes); it\n// must never hard-restrict to a named provider.\nexport interface MagiKindPreset {\n /** Desired number of distinct (node, provider) targets to fan out to. */\n targetK: number;\n /** Hard floor — below this the handler errors (magi_insufficient_providers). */\n minK: number;\n /** Ordering hint ONLY (scarce/lexical break ties after it). Never a restriction. */\n providerPreference?: readonly string[];\n /** Providers that are fragile / cross-wire-prone: ≤1 replica per node, spread across distinct nodes. */\n avoidConcurrentProviders?: readonly string[];\n}\n\n/**\n * Static per-kind intent. design wants the widest independent spectrum (targetK 4);\n * audit/rca a solid triad; freeform the minimum cross-check pair. providerPreference is\n * a soft ordering nudge — the resolver still satisfies any ≥2-distinct-provider mesh.\n * antigravity-cli is fragile (cross-wire prone) so it is capped at one replica per node.\n */\nexport const MAGI_KIND_PRESETS: Readonly<Record<MagiTaskKind, MagiKindPreset>> = {\n claim_audit: { targetK: 3, minK: 2, providerPreference: ['claude-cli', 'codex-cli', 'gemini-cli', 'hermes-cli'], avoidConcurrentProviders: ['antigravity-cli'] },\n rca: { targetK: 3, minK: 2, providerPreference: ['claude-cli', 'codex-cli', 'gemini-cli', 'hermes-cli'], avoidConcurrentProviders: ['antigravity-cli'] },\n design: { targetK: 4, minK: 2, providerPreference: ['claude-cli', 'codex-cli', 'gemini-cli', 'hermes-cli'], avoidConcurrentProviders: ['antigravity-cli'] },\n freeform: { targetK: 2, minK: 2, providerPreference: ['claude-cli', 'codex-cli', 'gemini-cli', 'hermes-cli'], avoidConcurrentProviders: ['antigravity-cli'] },\n};\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\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 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 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 memberIndex: number;\n provider: string;\n /** Resolved concrete node id (pinned member), 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}\n\nexport interface MagiUnavailableMember {\n memberIndex: number;\n provider: string;\n nodeId?: string;\n capabilityTags: string[];\n reason: string;\n}\n\n/** Per-member resolution detail (for mesh_magi_panel_list + the git-stale exclusion). */\nexport interface MagiMemberResolution {\n memberIndex: 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 /** Excluded from the fan-out (unavailable, 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 unavailableMembers: MagiUnavailableMember[];\n /** The commit the panel is being resolved against (coordinator HEAD); undefined when unknown. */\n referenceCommit?: string;\n /** Per-member resolution detail, aligned to panel.members order. */\n memberResolutions: MagiMemberResolution[];\n /** Members excluded because they are git-stale (different HEAD) and include_stale was not set. */\n staleMembers: MagiMemberResolution[];\n /** Git-stale members that were nonetheless INCLUDED because include_stale=true (warning surface). */\n includedStaleMembers: MagiMemberResolution[];\n}\n\nfunction replicaCountFor(member: MagiPanelMember, panel: MagiPanel, globalN?: number): number {\n const n = member.n ?? panel.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 * 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 panel against the live mesh nodes into a concrete fan-out plan:\n * expand each available member 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 panel: MagiPanel,\n nodes: LocalMeshNodeEntry[],\n opts: { n?: number; maxReplicas?: number; referenceCommit?: string; includeStale?: boolean } = {},\n): MagiFanoutPlan {\n const cap = Math.max(1, Math.floor(opts.maxReplicas ?? MAGI_MAX_REPLICAS));\n const members = Array.isArray(panel.members) ? panel.members : [];\n const referenceCommit = typeof opts.referenceCommit === 'string' && opts.referenceCommit.trim() ? opts.referenceCommit.trim() : undefined;\n const includeStale = opts.includeStale === true;\n const replicas: MagiReplicaPlan[] = [];\n const unavailableMembers: MagiUnavailableMember[] = [];\n const memberResolutions: MagiMemberResolution[] = [];\n const targetKeys = new Set<string>();\n const providerSet = new Set<string>();\n const nodeTargetSet = new Set<string>();\n let totalRequested = 0;\n\n members.forEach((member, memberIndex) => {\n const provider = member.provider;\n const capabilityTags = normalizeMeshCapabilityTags(member.capabilityTags);\n const requiredTags = normalizeMeshCapabilityTags([`provider=${provider}`, ...capabilityTags]);\n const count = replicaCountFor(member, panel, 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 (member.nodeId) {\n const node = nodes.find(n => meshNodeIdMatches(n as any, member.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 unavailableMembers.push({\n memberIndex,\n provider,\n nodeId: member.nodeId,\n capabilityTags,\n reason: member.nodeId\n ? `pinned node '${member.nodeId}' is not a member of this mesh`\n : `no mesh node satisfies required tags [${requiredTags.join(', ')}]`,\n });\n memberResolutions.push({ memberIndex, provider, nodeId: member.nodeId, capabilityTags, available: false, gitStale: false, excluded: true, reason: 'unavailable' });\n return;\n }\n\n // Git staleness vs the reference commit. A member 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 return !h || h === referenceCommit;\n });\n if (freshCandidate) {\n headCommit = nodeHeadCommit(freshCandidate);\n if (member.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 member 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 member fresh.\n headCommit = nodeHeadCommit(freshCandidate);\n if (member.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: MagiMemberResolution = {\n memberIndex,\n provider,\n nodeId: targetNodeId ?? member.nodeId,\n capabilityTags,\n available: true,\n ...(headCommit ? { headCommit } : {}),\n gitStale,\n excluded: false,\n };\n\n // Default-exclude a git-stale member (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 resolution.reason = referenceCommit\n ? `git-stale: node HEAD ${headCommit ?? '(unknown)'} differs from reference ${referenceCommit}`\n : `git-stale: node reports drift from its upstream (behind/ahead) and no coordinator reference commit is known`;\n memberResolutions.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 memberResolutions.push(resolution);\n for (let i = 0; i < count; i++) {\n replicas.push({ memberIndex, provider, targetNodeId, capabilityTags, requiredTags });\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 // git-stale exclusion — so the ≥2-independent-target guard re-checks post-exclusion\n // and never silently degrades to N=1.\n const staleMembers = memberResolutions.filter(m => m.gitStale && m.excluded);\n const includedStaleMembers = memberResolutions.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 unavailableMembers,\n ...(referenceCommit ? { referenceCommit } : {}),\n memberResolutions,\n staleMembers,\n includedStaleMembers,\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// ─── 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\nexport async function meshMagiPanelSet(\n ctx: MeshContext,\n args: { panel_name?: string; panelName?: string; config?: unknown; write?: boolean; overwrite?: boolean },\n): Promise<string> {\n const panelName = readString(args.panel_name) || readString(args.panelName);\n if (!panelName) return JSON.stringify({ success: false, error: 'panel_name required' });\n const write = args.write === true;\n try {\n if (!write) {\n // Dry-run: normalize + validate via a throwaway upsert path WITHOUT persisting.\n // We re-use the same validation by constructing the normalized panel through\n // the accessor only on write; for dry-run we validate shape inline here.\n const preview = previewMagiPanel(args.config);\n return JSON.stringify({\n success: true,\n dryRun: true,\n panelName,\n panel: preview,\n note: 'Dry-run only — no file written. Re-run with write=true to persist to ~/.adhdev/meshes.json.',\n }, null, 2);\n }\n const panel = upsertMagiPanel(panelName, args.config, { overwrite: args.overwrite === true });\n return JSON.stringify({\n success: true,\n written: true,\n panelName,\n panel,\n nextAction: 'Verify resolution with mesh_magi_panel_list, then invoke mesh_magi_review({ panel, question, target }).',\n }, null, 2);\n } catch (e: any) {\n const message = e?.message || String(e);\n const code = message.includes('magi_panel_exists') ? 'magi_panel_exists'\n : message.includes('invalid_magi_panel') ? 'invalid_magi_panel'\n : undefined;\n return JSON.stringify({ success: false, ...(code ? { code } : {}), error: message });\n }\n}\n\n/**\n * Validate + normalize a panel config for dry-run preview. Delegates to the single\n * source-of-truth normalizer (daemon-core normalizeMagiPanel) so dry-run preview,\n * persisted upsert, and the inline-member ad-hoc path all share identical validation\n * (provider required, tag dedup, replica clamp, member cap) — no duplicated rules.\n */\nfunction previewMagiPanel(config: unknown): MagiPanel {\n return normalizeMagiPanel(config);\n}\n\n/**\n * Build a one-off ad-hoc MAGI panel from inline `members` (mesh_magi_review members\n * override) WITHOUT persisting anything to meshes.json. Same member shape and same\n * normalizer as a named panel, so an inline panel resolves through the identical\n * fan-out / synthesis pipeline. Pure. Throws invalid_magi_panel on a malformed list.\n */\nexport function buildInlineMagiPanel(members: unknown, opts: { defaultN?: number; description?: string } = {}): MagiPanel {\n return normalizeMagiPanel({\n members,\n ...(opts.defaultN !== undefined ? { defaultN: opts.defaultN } : {}),\n description: opts.description ?? 'inline ad-hoc panel',\n });\n}\n\n/** One live, individually-routable (node × provider) candidate pair for preset synthesis. */\ninterface MagiPresetCandidate {\n nodeId: string;\n provider: string;\n}\n\n/**\n * Enumerate every live (node, provider) pair that is INDIVIDUALLY routable — i.e. the\n * node would actually claim a task whose required tag is `provider=<provider>`. This is\n * the bug-fix core (MAGI-KIND-PRESET §1): we advertise each provider with the provider\n * arg passed to buildMeshNodeCapabilityTags so a node's 2nd-and-lower priority providers\n * are visible, matching the queue's per-provider claim check (mesh-queue-assignment.ts)\n * rather than buildMagiFanoutPlan's tag-routed path which only sees the FIRST provider.\n * Pure / order-stable (nodes in mesh order, providers in each node's priority order).\n */\nfunction enumerateLivePresetCandidates(nodes: LocalMeshNodeEntry[]): MagiPresetCandidate[] {\n const out: MagiPresetCandidate[] = [];\n const seen = new Set<string>();\n for (const node of Array.isArray(nodes) ? nodes : []) {\n const nodeId = (node as any)?.id;\n if (typeof nodeId !== 'string' || !nodeId.trim()) continue;\n for (const provider of readProviderPriority((node as any)?.policy)) {\n // Per-provider availability: does THIS provider on THIS node satisfy a\n // `provider=<provider>` filter? Pass the provider so the advertised tag set\n // carries provider=<provider> (the queue's per-provider check); without it\n // only the node's first provider would ever match.\n const tags = buildMeshNodeCapabilityTags(node as any, provider);\n if (!nodeSatisfiesRequiredTags([`provider=${provider}`], tags)) continue;\n const key = `${nodeId}|${provider}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push({ nodeId, provider });\n }\n }\n return out;\n}\n\n/**\n * Greedily pick up to targetK MAXIMALLY-DIVERSE (node, provider) pairs from the live\n * candidate set. Diversity = introduce a NEW provider AND a NEW node at each step when\n * possible; when one axis is exhausted, allow a new value on the other. Ordering is a\n * stable sort by: providerPreference rank → provider scarcity (rarest provider first, so\n * a singleton provider is never crowded out) → nodeId → provider (lexical). Deterministic:\n * same live mesh + same preset → same pairs. Fragile providers\n * (preset.avoidConcurrentProviders) are capped at one pick per node and never picked twice\n * on the same node. Pure.\n */\nfunction selectDiversePresetPairs(\n candidates: MagiPresetCandidate[],\n preset: MagiKindPreset,\n): MagiPresetCandidate[] {\n const prefRank = new Map<string, number>();\n (preset.providerPreference ?? []).forEach((p, i) => prefRank.set(p, i));\n const prefOf = (provider: string): number => prefRank.has(provider) ? prefRank.get(provider)! : Number.MAX_SAFE_INTEGER;\n const fragile = new Set(preset.avoidConcurrentProviders ?? []);\n\n // Provider scarcity: how many candidate pairs each provider appears in (rarer first).\n const scarcity = new Map<string, number>();\n for (const c of candidates) scarcity.set(c.provider, (scarcity.get(c.provider) ?? 0) + 1);\n\n const sorted = [...candidates].sort((a, b) =>\n (prefOf(a.provider) - prefOf(b.provider))\n || ((scarcity.get(a.provider) ?? 0) - (scarcity.get(b.provider) ?? 0))\n || (a.nodeId < b.nodeId ? -1 : a.nodeId > b.nodeId ? 1 : 0)\n || (a.provider < b.provider ? -1 : a.provider > b.provider ? 1 : 0),\n );\n\n const picked: MagiPresetCandidate[] = [];\n const usedNodes = new Set<string>();\n const usedProviders = new Set<string>();\n const fragileNodes = new Set<string>(); // nodes that already carry a fragile-provider pick\n\n // Greedy passes over the SAME sorted order. Pass 1 demands both axes fresh; pass 2\n // relaxes to either axis fresh; pass 3 fills any remaining distinct pair. Each pass\n // walks the stable sorted list so the result is deterministic.\n const tryPick = (c: MagiPresetCandidate): void => {\n if (picked.length >= preset.targetK) return;\n if (fragile.has(c.provider) && fragileNodes.has(c.nodeId)) return; // ≤1 fragile per node\n picked.push(c);\n usedNodes.add(c.nodeId);\n usedProviders.add(c.provider);\n if (fragile.has(c.provider)) fragileNodes.add(c.nodeId);\n };\n const isPicked = (c: MagiPresetCandidate): boolean =>\n picked.some(p => p.nodeId === c.nodeId && p.provider === c.provider);\n\n // Pass 1: both new provider AND new node.\n for (const c of sorted) {\n if (picked.length >= preset.targetK) break;\n if (isPicked(c)) continue;\n if (!usedProviders.has(c.provider) && !usedNodes.has(c.nodeId)) tryPick(c);\n }\n // Pass 2: either new provider OR new node (extend diversity on whichever axis survives).\n for (const c of sorted) {\n if (picked.length >= preset.targetK) break;\n if (isPicked(c)) continue;\n if (!usedProviders.has(c.provider) || !usedNodes.has(c.nodeId)) tryPick(c);\n }\n // Pass 3: any remaining distinct pair (fills targetK when the mesh is small/coupled).\n for (const c of sorted) {\n if (picked.length >= preset.targetK) break;\n if (isPicked(c)) continue;\n tryPick(c);\n }\n return picked;\n}\n\n/**\n * Synthesize an ad-hoc MAGI panel for a bare `task_kind` (no pre-authored panel name /\n * members) by selecting the most diverse cross-provider (node × provider) pairs the LIVE\n * mesh supports. Each selected pair becomes a PINNED member { provider, nodeId, n }, so it\n * routes through buildMagiFanoutPlan's deterministic pinned path — no new resolution path\n * is introduced. The returned panel flows through the identical normalizeMagiPanel →\n * buildMagiFanoutPlan → synthesis pipeline as named/inline panels.\n *\n * Degrades gracefully (MAGI-KIND-PRESET §5): a single-provider mesh spreads the same\n * provider across distinct nodes (synthesis still gets distinct nodes); only when the live\n * mesh has exactly one (node, provider) pair does it return < minK members, which the\n * handler surfaces as magi_insufficient_providers (never silently N=1). Deterministic.\n */\nexport function buildPresetMagiPanelForKind(\n kind: MagiTaskKind,\n nodes: LocalMeshNodeEntry[],\n opts: { n?: number; referenceCommit?: string; maxReplicas?: number } = {},\n): MagiPanel {\n const preset = MAGI_KIND_PRESETS[kind] ?? MAGI_KIND_PRESETS[DEFAULT_TASK_KIND];\n const candidates = enumerateLivePresetCandidates(nodes);\n const pairs = selectDiversePresetPairs(candidates, preset);\n const members: MagiPanelMember[] = pairs.map(p => ({\n provider: p.provider,\n nodeId: p.nodeId,\n ...(opts.n !== undefined ? { n: Math.max(1, Math.floor(opts.n)) } : { n: 1 }),\n }));\n // Reuse the inline normalizer so the preset panel is validated identically. An empty\n // member list would throw invalid_magi_panel; the handler checks minK BEFORE relying on\n // a valid panel, but guard here too so a 0-candidate mesh yields a clear panel object\n // (the handler's minK gate produces the user-facing magi_insufficient_providers error).\n if (members.length === 0) {\n // Return an un-normalized empty panel shape; the caller's minK check rejects it.\n return { members: [], description: `preset:${kind}` };\n }\n return buildInlineMagiPanel(members, { defaultN: opts.n, description: `preset:${kind}` });\n}\n\nexport async function meshMagiPanelList(\n ctx: MeshContext,\n args: { panel?: string } = {},\n): Promise<string> {\n await refreshMeshFromDaemon(ctx);\n const all = listMagiPanels();\n const only = readString(args.panel);\n const names = only ? (all[only] ? [only] : []) : Object.keys(all);\n if (only && names.length === 0) {\n return JSON.stringify({ success: false, code: 'magi_panel_not_found', error: `panel '${only}' is not configured`, configuredPanels: Object.keys(all) });\n }\n const referenceCommit = resolveMagiReferenceCommit(ctx);\n const panels = names.map(name => {\n const panel = all[name];\n // Resolve with the reference commit so the listing reflects which members are\n // git-stale and would be excluded by default (panel_list itself never dispatches).\n const plan = buildMagiFanoutPlan(panel, ctx.mesh.nodes, { referenceCommit });\n return {\n name,\n description: panel.description,\n // Per-member gitStale boolean alongside the raw member definition.\n members: panel.members.map((m, i) => {\n const res = plan.memberResolutions.find(r => r.memberIndex === i);\n return {\n ...m,\n gitStale: res?.gitStale === true,\n ...(res?.headCommit ? { headCommit: res.headCommit } : {}),\n };\n }),\n defaultN: panel.defaultN ?? 1,\n resolution: {\n referenceCommit: referenceCommit ?? null,\n totalReplicas: plan.totalAfterCap,\n distinctTargets: plan.distinctTargets,\n distinctProviders: plan.distinctProviders,\n distinctMachines: plan.distinctNodeTargets,\n enoughTargets: plan.enoughTargets,\n coupled: plan.coupled,\n unavailableMembers: plan.unavailableMembers,\n staleMembers: plan.staleMembers,\n },\n ...(plan.staleMembers.length > 0 ? { gitStaleWarning: `${plan.staleMembers.length} member(s) are git-stale (HEAD differs from reference ${referenceCommit ?? '(unknown)'}) and are excluded by default; pass include_stale=true to mesh_magi_review to include them.` } : {}),\n ...(plan.coupled ? { warning: 'This panel collapses to a single provider or single machine — its agreements would be flagged source-coupled.' } : {}),\n ...(!plan.enoughTargets ? { error: `Resolves to ${plan.distinctTargets} distinct (node, provider) target(s) after git-stale exclusion; MAGI requires ≥${MAGI_MIN_TARGETS}.` } : {}),\n };\n });\n return JSON.stringify({ success: true, count: panels.length, ...(referenceCommit ? { referenceCommit } : {}), panels }, null, 2);\n}\n\nexport async function meshMagiReview(\n ctx: MeshContext,\n args: {\n question?: string;\n target?: string;\n artifacts?: string[];\n panel?: string;\n members?: unknown;\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 // MAGI-REDESIGN: capture the EXPLICIT output kind (if any) here; the final taskKind\n // is resolved AFTER the panel is loaded so a named panel's optional defaultKind can\n // fill in. Strict priority: args.task_kind > panel.defaultKind > claim_audit. We must\n // not normalize-to-default yet — that would erase the \"no explicit kind\" signal and\n // make panel.defaultKind unreachable.\n const explicitTaskKind = args.task_kind ?? args.taskKind;\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 the preset resolver below pins fresh live nodes against the SAME\n // baseline buildMagiFanoutPlan uses for git-staleness. read-only — safe to hoist.\n const referenceCommit = resolveMagiReferenceCommit(ctx);\n\n // 1. Resolve the panel. Inline `members` take precedence (ad-hoc panel, not\n // persisted); next, a bare `task_kind` with no panel name auto-synthesizes a\n // maximally-diverse cross-provider PRESET panel from the live mesh; otherwise look\n // up the named panel (falling back to \"default\").\n const hasInlineMembers = Array.isArray(args.members) && args.members.length > 0;\n const explicitPanelName = readString(args.panel);\n // The preset path fires ONLY when the caller passed an explicit task_kind, named no\n // panel, and gave no inline members — i.e. `mesh_magi_review({question, task_kind})`.\n // A named/default panel or inline members always take their existing path unchanged.\n const usePresetPath = !hasInlineMembers\n && !explicitPanelName\n && typeof explicitTaskKind === 'string'\n && (VALID_TASK_KINDS as readonly string[]).includes(explicitTaskKind.trim().toLowerCase());\n let panel: MagiPanel | undefined;\n let panelName: string;\n let presetKind: MagiTaskKind | undefined;\n if (hasInlineMembers) {\n panelName = '(inline)';\n try {\n panel = buildInlineMagiPanel(args.members, { defaultN: args.n });\n } catch (e: any) {\n return JSON.stringify({\n success: false,\n code: 'invalid_magi_panel',\n error: e?.message || String(e),\n hint: 'Inline members use the same shape as a configured panel: [{ provider (REQUIRED), nodeId?, capabilityTags?, n? }].',\n });\n }\n } else if (usePresetPath) {\n // Auto-synthesize the preset panel from the live mesh — no pre-authored members.\n presetKind = normalizeMagiTaskKind(explicitTaskKind);\n panelName = `(preset:${presetKind})`;\n const preset = MAGI_KIND_PRESETS[presetKind];\n const maxReplicas = Math.max(1, Math.floor(Number(args.n) > 0 ? Number(args.n) : MAGI_MAX_REPLICAS));\n panel = buildPresetMagiPanelForKind(presetKind, ctx.mesh.nodes, { n: args.n, referenceCommit, maxReplicas });\n if (panel.members.length < preset.minK) {\n return JSON.stringify({\n success: false,\n code: 'magi_insufficient_providers',\n error: `task_kind '${presetKind}' auto-synthesis found only ${panel.members.length} independent (node, provider) target(s) in the live mesh; MAGI requires ≥${preset.minK} and never silently degrades to N=1.`,\n resolvedMembers: panel.members,\n hint: 'Bring a second provider or a second node online (mesh_status to inspect), or pass explicit inline members to mesh_magi_review.',\n }, null, 2);\n }\n } else {\n panelName = explicitPanelName || 'default';\n panel = getMagiPanel(panelName);\n }\n if (!panel) {\n return JSON.stringify({\n success: false,\n code: 'magi_panel_missing',\n error: `MAGI panel '${panelName}' is not configured. Define it first with mesh_magi_panel_set, pass inline members, and inspect resolution with mesh_magi_panel_list.`,\n configuredPanels: Object.keys(listMagiPanels()),\n });\n }\n\n // Resolve the final output kind now that the panel is loaded. Strict priority:\n // explicit args.task_kind > panel.defaultKind > claim_audit (the DEFAULT_TASK_KIND\n // fallback inside normalizeMagiTaskKind). An explicit kind always wins, so an\n // automation already passing task_kind keeps its exact schema (backward-compatible).\n // INLINE-MEMBER ASYMMETRY (intentional): buildInlineMagiPanel never sets defaultKind,\n // so the inline path naturally falls through to claim_audit — there is no panel\n // identity to carry a default. normalizeMagiTaskKind also drops a panel-stored\n // 'freeform' defensively (it should already be rejected at write time). The preset\n // path already resolved presetKind from the explicit kind, so this is idempotent.\n const taskKind = normalizeMagiTaskKind(explicitTaskKind ?? panel.defaultKind);\n\n // 2. Plan the fan-out. Git-stale members (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(panel, ctx.mesh.nodes, { n: args.n, referenceCommit, includeStale });\n if (!plan.enoughTargets) {\n const droppedByStale = plan.staleMembers.length > 0;\n return JSON.stringify({\n success: false,\n code: droppedByStale ? 'magi_insufficient_targets_after_stale_exclusion' : 'magi_insufficient_targets',\n error: droppedByStale\n ? `Panel '${panelName}' resolves to only ${plan.distinctTargets} independent (node, provider) target(s) AFTER excluding ${plan.staleMembers.length} git-stale member(s) (HEAD differs from reference ${referenceCommit ?? '(unknown)'}); MAGI requires ≥${MAGI_MIN_TARGETS} and never silently degrades to N=1.`\n : `Panel '${panelName}' resolves to ${plan.distinctTargets} available (node, provider) target(s); MAGI requires ≥${MAGI_MIN_TARGETS} and never silently degrades to N=1.`,\n ...(referenceCommit ? { referenceCommit } : {}),\n unavailableMembers: plan.unavailableMembers,\n ...(droppedByStale ? { staleMembers: plan.staleMembers } : {}),\n hint: 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). Use mesh_magi_panel_list to inspect resolution.'\n : 'Use mesh_magi_panel_list to see resolution, mesh_magi_panel_set to fix members, mesh_status to confirm nodes/providers are online.',\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 ...(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 ...(hasInlineMembers ? { inline: true } : {}),\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 git-stale handling: which members were excluded (default), or included\n // despite being stale (include_stale=true) — the latter makes results git-skewed.\n ...(plan.staleMembers.length > 0 ? {\n gitStaleExcluded: plan.staleMembers,\n gitStaleWarning: `${plan.staleMembers.length} git-stale member(s) (HEAD ≠ reference ${plan.referenceCommit ?? '(unknown)'}) were excluded from this fan-out; pass include_stale=true to include them.`,\n } : {}),\n ...(plan.includedStaleMembers.length > 0 ? {\n gitStaleIncluded: plan.includedStaleMembers,\n gitStaleWarning: `include_stale=true: ${plan.includedStaleMembers.length} git-stale member(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 for (const [nodeId, group] of targets) {\n if (group.sessionIds.length === 0) continue;\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 perNode.push({ nodeId, skipped: 'node_not_in_live_mesh', sessionIds: group.sessionIds });\n continue;\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 });\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 cleanedSessionCount += deleted + stopped;\n perNode.push({\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 } catch (e: any) {\n perNode.push({ nodeId, error: e?.message || String(e), 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 // 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 → only finalize at the deadline.\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","// 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 buildMeshReadChatCacheFallback,\n buildMissingCoordinatorDaemonIdFailure,\n buildMissingNodeReadChatRecovery,\n buildQueueTriggerGuidance,\n collectLiveStatusProbe,\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 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 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';\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 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, args.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: args.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(args.message, 'p2p_direct', {\n taskId,\n taskMode,\n providerType,\n targetSessionId: dispatchedSessionId,\n ...(ctx.coordinatorSessionId ? { coordinatorSessionId: ctx.coordinatorSessionId } : {}),\n }),\n });\n insertDirectDispatch(ctx.mesh.id, {\n taskId,\n nodeId: args.node_id,\n sessionId: dispatchedSessionId,\n providerType: providerType || undefined,\n message: args.message,\n taskMode: taskMode || undefined,\n via: 'p2p_direct',\n dispatchedAt,\n });\n if (missionId) {\n recordDirectDispatchTask(ctx.mesh.id, args.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: args.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(args.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 }),\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: args.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: args.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, args.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: args.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 const task = enqueueTask(ctx.mesh.id, args.message, {\n targetNodeId: args.node_id,\n targetSessionId: args.session_id,\n taskMode,\n ...(readonly ? { readonly: true } : {}),\n ...(missionId ? { missionId } : {}),\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\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 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 = 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 const existing = sessions.find(session =>\n !isTerminalSessionRecord(session)\n && isMeshOwnedDelegateSession(session, ctx.mesh.id, args.node_id));\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\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\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\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\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,\n meshLaunchSession, meshGitStatus, meshReadNodeLogs, meshFastForwardNode, meshRestartDaemon, meshCheckpoint, meshApprove,\n meshCloneNode, meshRemoveNode, meshRefineNode,\n meshRefineConfigSchema, meshValidateRefineConfig, meshSuggestRefineConfig, meshInit, meshRefinePlan, meshRefineBatch,\n meshChangeImpactConfigSchema, meshValidateChangeImpactConfig, meshSuggestChangeImpactConfig,\n meshCleanupSessions, meshPruneStaleDirect, meshTaskHistory, meshRecordNote, meshReconcileLedger, meshMissionUpsert,\n meshMissionList, meshReviewInbox,\n meshMagiReview, meshMagiCollect, meshMagiPanelSet, meshMagiPanelList\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_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_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_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_change_impact_config_schema': text = await meshChangeImpactConfigSchema(meshCtx); break;\n case 'mesh_validate_change_impact_config': text = await meshValidateChangeImpactConfig(meshCtx, a as any); break;\n case 'mesh_suggest_change_impact_config': text = await meshSuggestChangeImpactConfig(meshCtx, a as any); break;\n case 'mesh_init': text = await meshInit(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_record_note': text = await meshRecordNote(meshCtx, a as any); break;\n case 'mesh_reconcile_ledger': text = await meshReconcileLedger(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_panel_set': text = await meshMagiPanelSet(meshCtx, a as any); break;\n case 'mesh_magi_panel_list': text = await meshMagiPanelList(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.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C,CAAC;AAAA,IACzB,WAAW,KAAK,WAAW,SAAS,GAAG;AACrC,aAAO,OAAO,IAAI,MAAM,UAAU,MAAM,CAAC;AAAA,IAC3C,WAAW,QAAQ,gBAAgB,KAAK,IAAI,CAAC,GAAG;AAC9C,iBAAW,KAAK,EAAE,CAAC;AAAA,IACrB,YAAY,QAAQ,iBAAiB,QAAQ,aAAa,KAAK,IAAI,CAAC,GAAG;AACrE,eAAS,KAAK,EAAE,CAAC;AAAA,IACnB,WAAW,KAAK,WAAW,cAAc,GAAG;AAC1C,eAAS,IAAI,MAAM,eAAe,MAAM;AAAA,IAC1C,WAAW,QAAQ,YAAY,QAAQ,MAAM;AAC3C,gBAAU;AACV,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AAGA,MAAI,CAAC,YAAY,IAAI,gBAAiB,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,MAAO,gBAAe;AAAA,EAC3D;AAEA,QAAM,OAAO,iBAAiB,UAAU,IAAI,qBAAqB,QAAQ;AACzE,SAAO,EAAE,MAAM,MAAM,UAAU,OAAO;AACxC;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":["now","import_daemon_core","import_daemon_core","import_daemon_core","task","triggerPreferredNodeId","slice","import_daemon_core","result","distinctProviders","distinctNodes","needsVerification","staleTaskIds","staleReasons","result","lines","os","server","stdioTransport"]}
|