/**
 * Orchestration handler group: bootstrap, orchestrate, optimize_tokens,
 * mindkit_check, ghost_pass, spawn_workers, session_dna, plan_execution.
 * Extracted from mcp.ts (Phase 3 split).
 */
import { normalizeDetailLevel, normalizeBootstrapDepth, normalizeResponseIntent, normalizeResponseTopology, buildWorkspaceEnvelope, formatBullets, formatJsonDetails, getGuardrailEngine, truncateText, } from '../helpers.js';
import { getTokenEngine } from '../util/token-engine.js';
import { nexusEventBus } from '../../../../engines/event-bus.js';
import { formatBrandedResponse, getRandomQuote } from '../../../../engines/nexus-brand.js';
import { hasValidBootstrapReceipt } from '../../../../engines/bootstrap/index.js';
import { resolveWorkspaceContext, resolveWorkspaceStateRoot } from '../../../../engines/workspace-resolver.js';
import { formatReadingPlan } from '../../../../engines/token-supremacy.js';
import { GhostPass, summarizeExecution } from '../../../../phantom/index.js';
import { applyExecutionPreset, resolveExecutionPreset } from '../../../../engines/execution-presets.js';
import { pLimit } from '../../../../engines/util/p-limit.js';
import { promises as fsPromises } from 'fs';
import * as path from 'path';
import { getSharedLicenseManager } from '../../../../licensing/index.js';
import { SessionDNAManager } from '../../../../engines/session-dna.js';
import { getSharedTelemetry } from '../../../../engines/telemetry-remote.js';
import { requireRuntime } from '../util/require-runtime.js';
import { ensureCrGraphBuilt } from '../../../../engines/code-review-graph-client.js';
import { recordFirstBootstrap } from '../../../../engines/telemetry.js';
function escapeMarkdownTableCell(value) {
    return String(value ?? '')
        .replace(/\r?\n/g, ' ')
        .replace(/\|/g, '\\|')
        .trim();
}
function markdownTable(headers, rows) {
    if (rows.length === 0)
        return '';
    return [
        `| ${headers.map(escapeMarkdownTableCell).join(' | ')} |`,
        `| ${headers.map(() => '---').join(' | ')} |`,
        ...rows.map(row => `| ${row.map(escapeMarkdownTableCell).join(' | ')} |`),
    ].join('\n');
}
export function extractSkillSelectorsFromPrompt(prompt) {
    const selectors = new Set();
    const add = (value) => {
        const cleaned = value?.trim().replace(/^[$@]+/, '');
        if (cleaned && /^[a-z0-9][a-z0-9._-]{1,120}$/i.test(cleaned)) {
            selectors.add(cleaned);
        }
    };
    for (const match of prompt.matchAll(/\[[$@]?([a-z0-9][a-z0-9._-]{1,120})\]\([^)]*\/\.agents?\/skills\/[^)]*\/SKILL\.md\)/gi)) {
        add(match[1]);
    }
    for (const match of prompt.matchAll(/\/\.agents?\/skills\/([^/\s)]+)\/SKILL\.md/gi)) {
        add(match[1]);
    }
    return [...selectors];
}
export function inferSpawnWorkersIntent(actions) {
    return actions.length > 0 ? 'mutate' : 'plan';
}
function namedValue(value) {
    if (typeof value === 'string')
        return value.trim();
    if (!value || typeof value !== 'object')
        return '';
    const record = value;
    return String(record.name ?? record.id ?? record.specialistId ?? record.skillId ?? record.workflowId ?? record.crewId ?? record.workerId ?? '').trim();
}
function asStringList(values, limit = 8) {
    const array = Array.isArray(values) ? values : values ? [values] : [];
    return [...new Set(array.map(namedValue).filter(Boolean))].slice(0, limit);
}
function formatSelectionList(values, fallback = 'none') {
    return values.length > 0 ? values.join(', ') : fallback;
}
function formatModelRoute(route) {
    if (!route)
        return 'default runtime route';
    const worker = String(route.workerTier ?? 'T1');
    const reviewer = route.reviewerTier ? ` + reviewer ${route.reviewerTier}` : '';
    const reason = route.reason ? ` - ${route.reason}` : '';
    return `${worker}${reviewer}${reason}`;
}
function formatBudgetRoute(plan) {
    const budgets = plan?.budgets ?? {};
    const policy = plan?.executionPolicy?.agentFlow ?? {};
    const total = Number(budgets.totalTokens ?? 0);
    const codeBlocks = Number(budgets.codeBlocks ?? budgets.codeBlockPolicy?.reservedTokens ?? 0);
    const cap = Number(policy.maxTaskCostUsd ?? 0);
    const parts = [
        total > 0 ? `${total.toLocaleString()} tokens` : 'budget pending',
        codeBlocks > 0 ? `${codeBlocks.toLocaleString()} code-block tokens` : null,
        cap > 0 ? `$${cap.toFixed(2)} task cap` : null,
    ].filter(Boolean);
    return parts.join(' · ');
}
function buildSelectionSummary(execution, runtimeUsage) {
    const selectionPlan = execution.selectionPlan ?? {};
    const selected = selectionPlan.selected ?? {};
    const planner = execution.plannerState ?? {};
    const taskGraph = runtimeUsage.taskGraph ?? execution.taskGraph ?? {};
    const workerPlan = runtimeUsage.workerPlan ?? execution.workerPlan ?? {};
    const audit = runtimeUsage.artifactSelectionAudit ?? execution.artifactSelectionAudit ?? {};
    const crew = asStringList(selected.crews, 2)[0]
        ?? namedValue(planner.selectedCrew)
        ?? 'baseline path';
    const specialists = asStringList(selected.specialists, 8).length > 0
        ? asStringList(selected.specialists, 8)
        : asStringList(planner.selectedSpecialists, 8);
    const skills = asStringList(selected.skills, 8).length > 0
        ? asStringList(selected.skills, 8)
        : asStringList(execution.activeSkills, 8).concat(asStringList(planner.selectedSkills, 8)).slice(0, 8);
    const workflows = asStringList(selected.workflows, 8).length > 0
        ? asStringList(selected.workflows, 8)
        : asStringList(execution.activeWorkflows, 8).concat(asStringList(planner.selectedWorkflows, 8)).slice(0, 8);
    const workers = asStringList(selected.workers, 8).length > 0
        ? asStringList(selected.workers, 8)
        : asStringList(execution.workerManifests, 8);
    return {
        crew,
        specialists,
        skills: [...new Set(skills)],
        workflows: [...new Set(workflows)],
        hooks: asStringList(selected.hooks, 8),
        automations: asStringList(selected.automations, 8),
        workers,
        modelRoute: selectionPlan.modelRoute ?? execution.requestBrief?.modelPolicy,
        budgetRoute: formatBudgetRoute(selectionPlan),
        agentFlow: selectionPlan.executionPolicy?.agentFlow,
        phaseCount: Array.isArray(taskGraph.phases) ? taskGraph.phases.length : 0,
        workerLaneCount: Number(workerPlan.totalWorkers ?? workers.length ?? execution.workerResults?.length ?? 0),
        mode: String(workerPlan.mode ?? execution.mode ?? 'autonomous'),
        auditSelected: Array.isArray(audit.selected) ? audit.selected.length : 0,
        auditRejected: Array.isArray(audit.rejected) ? audit.rejected.length : 0,
    };
}
export async function handleOrchestrationGroup(toolName, hctx, request, args, ctx) {
    const runtimeError = requireRuntime(hctx);
    if (runtimeError)
        return runtimeError;
    // Variables computed in the original handleToolCall preamble and used by these cases
    const detailLevel = normalizeDetailLevel(args.detailLevel);
    const requestedIntent = normalizeResponseIntent(args.intent);
    const requestedTopology = normalizeResponseTopology(args.topology);
    const workspace = buildWorkspaceEnvelope(hctx.nexusRef.getWorkspaceContext());
    switch (toolName) {
        case 'nexus_session_bootstrap': {
            // Wait for deferred engine startup before attempting bootstrap.
            // If MCP receives this call during the setImmediate window before
            // finishEngineStartup completes, we wait here rather than crashing
            // into a stub runtime (which lacks planExecution and would loop).
            if (hctx.nexusRef) {
                try {
                    await Promise.race([
                        hctx.nexusRef.awaitReady(),
                        new Promise((_, reject) => setTimeout(() => reject(new Error('nexus_startup_timeout')), 8000)),
                    ]);
                }
                catch {
                    return {
                        content: [{
                                type: 'text',
                                text: 'Nexus Prime is still initializing. Please retry nexus_session_bootstrap in a moment.',
                            }],
                    };
                }
            }
            const callStartedAt = Date.now();
            const bootstrapGoal = String(request.params.arguments?.goal ?? request.params.arguments?.prompt ?? '');
            const detailLevel = normalizeDetailLevel(request.params.arguments?.detailLevel);
            const bootstrapDepth = normalizeBootstrapDepth(request.params.arguments?.depth, detailLevel);
            // Fast-path: if already bootstrapped in this MCP session and receipt is still fresh,
            // return a lightweight ack instead of re-running the full expensive bootstrap.
            // This makes bootstrap idempotent for loop-based callers (e.g. /loop skill, Antigravity).
            // Debug calls always bypass the fast-path so callers get the full structured payload.
            if (hctx.telemetry.bootstrapCallCount > 0 && bootstrapDepth !== 'deep') {
                const hasFreshReceipt = (() => {
                    try {
                        const ws = resolveWorkspaceContext();
                        const stateRoot = resolveWorkspaceStateRoot(ws.workspaceRoot);
                        return hasValidBootstrapReceipt(stateRoot);
                    }
                    catch {
                        return false;
                    }
                })();
                if (hasFreshReceipt) {
                    hctx.telemetry.bootstrapCallCount++;
                    return {
                        content: [{
                                type: 'text',
                                text: [
                                    'Session already bootstrapped (fast-path — receipt is fresh).',
                                    'Skipping full re-bootstrap to avoid loop overhead.',
                                    `Goal: ${bootstrapGoal || '(same as prior call)'}`,
                                    'Recommended next step: nexus_orchestrate',
                                    hctx.formatProtocolChecklist(),
                                ].join('\n\n'),
                            }],
                    };
                }
            }
            hctx.telemetry.bootstrapCallCount++;
            hctx.setCurrentTask(bootstrapGoal);
            const files = Array.isArray(request.params.arguments?.files)
                ? request.params.arguments.files.map(String)
                : undefined;
            const include = Array.isArray(request.params.arguments?.include)
                ? request.params.arguments.include.map(String)
                : undefined;
            const requestedIntent = normalizeResponseIntent(request.params.arguments?.intent);
            const requestedTopology = normalizeResponseTopology(request.params.arguments?.topology);
            const bootstrap = await hctx.getOrchestrator().bootstrapSession(bootstrapGoal, {
                files,
                depth: bootstrapDepth,
                include,
            });
            const autoTokenApplied = Boolean(bootstrap.tokenOptimization?.autoApplied);
            if (autoTokenApplied) {
                hctx.telemetry.markTokenAutoApplied();
                if (bootstrap.tokenOptimization?.planMetrics?.savings) {
                    hctx.telemetry.recordTokens(Number(bootstrap.tokenOptimization.planMetrics.savings));
                }
            }
            hctx.getRuntime().recordClientToolCall('nexus_session_bootstrap', {
                bootstrapCalled: true,
                plannerCalled: bootstrap.depth === 'deep',
                tokenOptimizationApplied: autoTokenApplied,
                tokenAutoApplied: autoTokenApplied,
                toolProfile: hctx.getToolProfile(),
            });
            // Remote telemetry: track session start (privacy-safe, opt-in only)
            try {
                const remoteTelemetry = getSharedTelemetry();
                remoteTelemetry.trackSessionStart(hctx.getWorkspace(request.params.arguments ?? {}).repoRoot);
                if (autoTokenApplied && bootstrap.tokenOptimization?.planMetrics?.savings) {
                    remoteTelemetry.trackTokenSavings(Number(bootstrap.tokenOptimization.planMetrics.savings));
                }
            }
            catch (err) {
                nexusEventBus.emit('mcp.handler.best-effort-failed', { toolName, stage: 'track-session-start', error: err instanceof Error ? err.message : String(err) });
            }
            if (ctx) {
                ctx.meta.tokenSavings = Number(bootstrap.tokenOptimization?.planMetrics?.savings ?? 0);
                ctx.meta.projectMemoryBootstrapCount = Number(bootstrap.projectMemoryBootstrap?.count ?? 0);
                ctx.meta.detailLevel = detailLevel;
                ctx.meta.requestedIntent = requestedIntent;
                ctx.meta.requestedTopology = requestedTopology;
                ctx.meta.workspaceRoot = workspace.workspaceRoot;
                ctx.meta.repoRoot = workspace.repoRoot;
                ctx.meta.repoName = workspace.repoName;
            }
            // Surface a session-bootstrap signal on the SSE feed without polluting persistent
            // memory. Audit-log content like "Session bootstrap: ..." was previously stored as
            // a real memory (priority 0.4) which dominated recall results and forced low-signal
            // memories into hippocampus.
            try {
                nexusEventBus.emit('memory.snapshot', {
                    kind: 'session-bootstrap',
                    goal: bootstrapGoal || 'interactive session',
                    memoryStats: bootstrap.memoryStats,
                });
            }
            catch (err) {
                nexusEventBus.emit('mcp.handler.best-effort-failed', { toolName, stage: 'persist-session-summary', error: err instanceof Error ? err.message : String(err) });
            }
            // Non-blocking: ensure cr-graph is fresh after bootstrap. Fires after the handler
            // returns so the response is not delayed. Any failure is silently swallowed.
            try {
                const crRepoRoot = hctx.nexusRef.getWorkspaceContext().repoRoot;
                if (crRepoRoot) {
                    setImmediate(() => { void ensureCrGraphBuilt(crRepoRoot); });
                }
            }
            catch { /* best-effort */ }
            // TTV telemetry: record first successful bootstrap (fire-and-forget).
            void recordFirstBootstrap().catch(() => { });
            const timings = {
                totalMs: Date.now() - callStartedAt,
            };
            const fullBootstrapDetails = detailLevel === 'debug' || detailLevel === 'full';
            const payload = fullBootstrapDetails
                ? {
                    depth: bootstrap.depth,
                    workspace,
                    client: bootstrap.client,
                    memoryRecall: bootstrap.memoryRecall,
                    memoryStats: bootstrap.memoryStats,
                    memoryHealth: bootstrap.memoryHealth,
                    needsDeepBootstrap: bootstrap.needsDeepBootstrap,
                    changedSinceLastSession: bootstrap.changedSinceLastSession,
                    recommendedNextStep: bootstrap.recommendedNextStep,
                    recommendedExecutionMode: bootstrap.recommendedExecutionMode,
                    shortlist: bootstrap.shortlist,
                    tokenOptimization: bootstrap.tokenOptimization,
                    reviewGates: bootstrap.reviewGates,
                    catalogHealth: bootstrap.catalogHealth,
                    sourceMixRecommendation: bootstrap.sourceMixRecommendation,
                    ragCandidateStatus: bootstrap.ragCandidateStatus,
                    clientBootstrapStatus: bootstrap.clientBootstrapStatus,
                    artifactSelectionAudit: bootstrap.artifactSelectionAudit,
                    taskGraphPreview: bootstrap.taskGraphPreview,
                    workerPlanPreview: bootstrap.workerPlanPreview,
                    knowledgeFabric: bootstrap.knowledgeFabric,
                    sessionSummaryBootstrap: bootstrap.sessionSummaryBootstrap,
                    projectMemoryBootstrap: bootstrap.projectMemoryBootstrap,
                    candidateFilesDropped: bootstrap.candidateFilesDropped,
                    timings,
                    payloadRef: {
                        workspaceStateKey: workspace.stateKey,
                        detailLevel,
                        depth: bootstrapDepth,
                        intent: requestedIntent,
                        topology: requestedTopology,
                    },
                    mcpToolProfile: hctx.getToolProfile(),
                }
                : {
                    depth: bootstrap.depth,
                    workspace,
                    client: bootstrap.client,
                    memoryRecall: bootstrap.memoryRecall,
                    memoryStats: bootstrap.memoryStats,
                    memoryHealth: bootstrap.memoryHealth,
                    needsDeepBootstrap: bootstrap.needsDeepBootstrap,
                    changedSinceLastSession: bootstrap.changedSinceLastSession,
                    recommendedNextStep: bootstrap.recommendedNextStep,
                    recommendedExecutionMode: bootstrap.recommendedExecutionMode,
                    shortlist: bootstrap.shortlist,
                    tokenOptimization: {
                        required: bootstrap.tokenOptimization.required,
                        reason: bootstrap.tokenOptimization.reason,
                        autoApplied: bootstrap.tokenOptimization.autoApplied,
                        planMetrics: bootstrap.tokenOptimization.planMetrics,
                        candidateFiles: bootstrap.tokenOptimization.candidateFiles.slice(0, 12),
                    },
                    reviewGates: bootstrap.reviewGates,
                    catalogHealth: bootstrap.catalogHealth,
                    sourceMixRecommendation: bootstrap.sourceMixRecommendation,
                    ragCandidateStatus: bootstrap.ragCandidateStatus,
                    candidateFilesDropped: bootstrap.candidateFilesDropped,
                    timings,
                    payloadRef: {
                        workspaceStateKey: workspace.stateKey,
                        detailLevel,
                        depth: bootstrapDepth,
                        intent: requestedIntent,
                        topology: requestedTopology,
                    },
                    summary: {
                        bootstrapDepth: bootstrap.depth ?? bootstrapDepth,
                        clientBootstrapClients: bootstrap.clientBootstrapStatus?.clients?.length ?? 0,
                        taskGraphPhases: bootstrap.taskGraphPreview?.phases?.length ?? 0,
                        totalWorkers: bootstrap.workerPlanPreview?.totalWorkers ?? 0,
                        selectedArtifacts: bootstrap.artifactSelectionAudit?.selected?.length ?? 0,
                    },
                };
            const bootstrapQuote = getRandomQuote();
            return {
                content: [{
                        type: 'text',
                        text: [
                            formatBrandedResponse({
                                toolName: 'nexus_session_bootstrap',
                                body: 'Session bootstrap ready.',
                                metrics: {
                                    tokensUsed: Number(bootstrap.tokenOptimization?.planMetrics?.compressedTokens ?? 0),
                                    tokensSaved: Number(bootstrap.tokenOptimization?.planMetrics?.savings ?? 0),
                                    memoryHits: bootstrap.memoryRecall?.count ?? 0,
                                    durationMs: timings.totalMs,
                                },
                                includeQuote: true,
                            }),
                            formatBullets([
                                `Workspace: ${workspace.repoName} (${workspace.workspaceSource})`,
                                `Client: ${bootstrap.client?.displayName || bootstrap.client?.clientId || 'unknown'} (${bootstrap.client?.state || 'unknown'})`,
                                `Memory recall: ${bootstrap.memoryRecall?.count ?? 0} result(s)`,
                                `Memory stats: prefrontal ${bootstrap.memoryStats?.prefrontal ?? 0} · hippocampus ${bootstrap.memoryStats?.hippocampus ?? 0} · cortex ${bootstrap.memoryStats?.cortex ?? 0}`,
                                `Recommended next step: ${bootstrap.recommendedNextStep || 'nexus_orchestrate'}`,
                                `Token optimization: ${bootstrap.tokenOptimization?.autoApplied ? `auto-applied — saved ${Number(bootstrap.tokenOptimization?.planMetrics?.savings ?? 0).toLocaleString()} tokens (${bootstrap.tokenOptimization?.planMetrics?.pct ?? 0}% reduction)` : (bootstrap.tokenOptimization?.required ? 'required before broad reading' : 'not required yet')}`,
                                bootstrap.tokenOptimization?.planMetrics
                                    ? `Token budget: original ${Number(bootstrap.tokenOptimization.planMetrics.originalTokens ?? 0).toLocaleString()} → planned ${Number(bootstrap.tokenOptimization.planMetrics.compressedTokens ?? 0).toLocaleString()} across ${Number(bootstrap.tokenOptimization.planMetrics.files ?? 0).toLocaleString()} file action(s)`
                                    : '',
                                `Catalog health: ${bootstrap.catalogHealth?.overall || 'unknown'} · selected ${bootstrap.artifactSelectionAudit?.selected?.length || 0}`,
                                (() => {
                                    try {
                                        const _lic = getSharedLicenseManager().getStatus();
                                        if (_lic.tier === 'free') {
                                            return `Plan: Free — upgrade at https://nexus-prime.cfd/pricing`;
                                        }
                                        return `Plan: ${_lic.tier}${_lic.expiresAt ? ` (expires ${new Date(_lic.expiresAt).toISOString().slice(0, 10)})` : ''}`;
                                    }
                                    catch {
                                        return '';
                                    }
                                })(),
                                ...(fullBootstrapDetails ? [
                                    `Bootstrap depth: ${bootstrap.depth || bootstrapDepth}`,
                                    `Execution mode: ${bootstrap.recommendedExecutionMode || 'autonomous'}`,
                                    `Shortlist: ${bootstrap.shortlist?.skills?.slice(0, 3).join(', ') || 'none'} (skills), ${bootstrap.shortlist?.specialists?.slice(0, 3).join(', ') || 'none'} (specialists)`,
                                    `Knowledge fabric: ${bootstrap.sourceMixRecommendation?.dominantSource || bootstrap.knowledgeFabric?.dominantSource || 'awaiting source mix'}`,
                                    `RAG: ${bootstrap.ragCandidateStatus?.attachedCollections || 0} attached · ${bootstrap.ragCandidateStatus?.retrievedChunks || 0} retrieved`,
                                    `Task graph: ${bootstrap.taskGraphPreview?.phases?.length || 0} phases · ${bootstrap.taskGraphPreview?.independentBranches || 0} branches`,
                                    `Worker plan: ${bootstrap.workerPlanPreview?.totalWorkers || 0} workers planned`,
                                    bootstrap.needsDeepBootstrap ? 'Deep preparation: still recommended before risky or cross-file work' : 'Deep preparation: not currently required',
                                    `Payload ref: ${workspace.stateKey} · ${detailLevel}`,
                                    `Session summary: ${bootstrap.sessionSummaryBootstrap?.savedTokens ? `reused ${Number(bootstrap.sessionSummaryBootstrap.savedTokens || 0).toLocaleString()} tokens from the previous visit` : 'none available yet'}`,
                                    bootstrap.projectMemoryBootstrap?.count
                                        ? `Project memory: recovered ${bootstrap.projectMemoryBootstrap.count} prior project memories`
                                        : 'Project memory: no prior project memories recovered',
                                    bootstrap.autoGhostPass?.applied
                                        ? `Auto ghost-pass: ${bootstrap.autoGhostPass.riskAreas.length} risk area(s) · ${bootstrap.autoGhostPass.workerApproaches} approach(es)`
                                        : `Auto ghost-pass: skipped`,
                                    `Bootstrap status: ${bootstrap.clientBootstrapStatus?.clients?.length || 0} client manifests tracked`,
                                ] : []),
                            ]),
                            fullBootstrapDetails && bootstrap.tokenOptimization?.autoApplied && bootstrap.tokenOptimization?.plan
                                ? `Auto token plan\n\`\`\`txt\n${bootstrap.tokenOptimization.plan}\n\`\`\``
                                : '',
                            formatJsonDetails('Structured details', payload),
                            hctx.formatProtocolChecklist(),
                        ].filter(Boolean).join('\n\n'),
                    }],
            };
        }
        case 'nexus_orchestrate': {
            const callStartedAt = Date.now();
            const prompt = String(request.params.arguments?.prompt ?? request.params.arguments?.goal ?? '');
            hctx.setCurrentTask(prompt);
            const files = Array.isArray(request.params.arguments?.files)
                ? request.params.arguments.files.map(String)
                : undefined;
            const workers = request.params.arguments?.workers == null
                ? undefined
                : Number(request.params.arguments.workers);
            const explicitSkills = Array.isArray(request.params.arguments?.skills)
                ? request.params.arguments.skills.map(String)
                : [];
            const promptSkills = extractSkillSelectorsFromPrompt(prompt);
            const skills = [...new Set([...explicitSkills, ...promptSkills])];
            const workflows = Array.isArray(request.params.arguments?.workflows)
                ? request.params.arguments.workflows.map(String)
                : undefined;
            const hooks = Array.isArray(request.params.arguments?.hooks)
                ? request.params.arguments.hooks.map(String)
                : undefined;
            const automations = Array.isArray(request.params.arguments?.automations)
                ? request.params.arguments.automations.map(String)
                : undefined;
            const crews = Array.isArray(request.params.arguments?.crews)
                ? request.params.arguments.crews.map(String)
                : undefined;
            const specialists = Array.isArray(request.params.arguments?.specialists)
                ? request.params.arguments.specialists.map(String)
                : undefined;
            const optimizationProfile = request.params.arguments?.optimizationProfile
                ? String(request.params.arguments.optimizationProfile)
                : undefined;
            const executionPreset = request.params.arguments?.executionPreset
                ? String(request.params.arguments.executionPreset)
                : undefined;
            // Auto-apply token optimization when explicit files are provided.
            // Gives agents an upfront reading plan before orchestrate runs.
            // No-files path relies on knowledge fabric (handled inside orchestrate).
            let upfrontTokenNote = '';
            if (files && files.length > 3) {
                try {
                    const statLimit = pLimit(8);
                    const fileRefs = await Promise.all(files.map((p) => statLimit(async () => {
                        const resolved = hctx.resolveToolPath(p, request.params.arguments ?? {});
                        try {
                            const stat = await fsPromises.stat(resolved);
                            return { path: resolved, sizeBytes: stat.size, lastModified: stat.mtimeMs };
                        }
                        catch {
                            return { path: resolved, sizeBytes: 0 };
                        }
                    })));
                    const upfrontPlan = await getTokenEngine().plan(prompt, fileRefs);
                    if (upfrontPlan.savings > 0) {
                        const pct = upfrontPlan.totalEstimatedTokens > 0
                            ? Math.round(upfrontPlan.savings / (upfrontPlan.totalEstimatedTokens + upfrontPlan.savings) * 100)
                            : 0;
                        upfrontTokenNote = `Token plan: ${upfrontPlan.files.filter(a => a.action === 'full').length} full reads, ${upfrontPlan.files.filter(a => a.action === 'outline').length} outlines, ${upfrontPlan.files.filter(a => a.action === 'skip').length} skipped. ~${upfrontPlan.savings.toLocaleString()} tokens saved (${pct}%). `;
                        nexusEventBus.emit('tokens.optimized', { savings: upfrontPlan.savings, pct, source: 'orchestrate-preflight' });
                    }
                }
                catch {
                    // Non-fatal: proceed without upfront plan
                }
            }
            try {
                const preset = resolveExecutionPreset(executionPreset);
                const execution = await hctx.nexusRef.orchestrate(prompt, applyExecutionPreset({
                    files,
                    workers,
                    skillNames: skills.length > 0 ? skills : undefined,
                    workflowSelectors: workflows,
                    hookSelectors: hooks,
                    automationSelectors: automations,
                    crewSelectors: crews,
                    specialistSelectors: specialists,
                    optimizationProfile,
                    intent: requestedIntent,
                    topology: requestedTopology,
                }, executionPreset));
                const verifiedWorkers = execution.workerResults.filter((worker) => worker.verified).length;
                const tokenPlan = execution?.knowledgeFabric?.repo?.readingPlan;
                const canAutoApplyTokenPlan = Boolean(tokenPlan
                    && Number(tokenPlan.savings || 0) > 0
                    && !hctx.getRuntime().getUsageSnapshot()?.tokenOptimizationApplied);
                let autoTokenApplyNote = '';
                if (canAutoApplyTokenPlan) {
                    const savings = Number(tokenPlan.savings || 0);
                    const totalBeforeOpt = savings + Number(tokenPlan.totalEstimatedTokens || 0);
                    const pctSaved = totalBeforeOpt > 0 ? Math.round(savings / totalBeforeOpt * 100) : 0;
                    hctx.telemetry.recordTokens(savings);
                    hctx.getRuntime().recordClientToolCall('nexus_orchestrate', {
                        orchestrateCalled: true,
                        plannerCalled: true,
                        tokenOptimizationApplied: true,
                        toolProfile: hctx.getToolProfile(),
                    });
                    autoTokenApplyNote = `Token savings: ${savings.toLocaleString()} tokens saved (${pctSaved}% reduction).`;
                    nexusEventBus.emit('tokens.optimized', { savings, pct: pctSaved, source: 'orchestrate' });
                }
                // Auto-store run summary memory so dashboard and future sessions can see what happened
                try {
                    const modifiedFiles = execution.workerResults.flatMap((w) => w.modifiedFiles);
                    hctx.nexusRef.storeMemory(`Run ${execution.runId} ${execution.state}: ${summarizeExecution(execution)}. Workers: ${verifiedWorkers}/${execution.workerResults.length} verified. Files modified: ${modifiedFiles.slice(0, 5).join(', ') || 'none'}.`, 0.34, ['#run-summary', '#auto', '#system-hidden']);
                }
                catch (err) {
                    nexusEventBus.emit('mcp.handler.best-effort-failed', { toolName, stage: 'auto-memory-store', error: err instanceof Error ? err.message : String(err) });
                }
                execution.activeSkills.forEach((skill) => hctx.sessionDNA.recordSkill(skill.name));
                execution.workerResults.forEach((result) => {
                    result.modifiedFiles.forEach((file) => hctx.sessionDNA.recordFileModified(file));
                });
                const runtimeUsage = hctx.getRuntime().getUsageSnapshot();
                const selectionSummary = buildSelectionSummary(execution, runtimeUsage);
                hctx.sessionDNA.recordDecision('Orchestrated autonomous run completed', execution.result || summarizeExecution(execution), execution.state === 'merged' ? 0.95
                    : execution.state === 'inspected' ? 0.85
                        : execution.state === 'rolled_back' ? 0.55
                            : 0.3);
                const timings = {
                    totalMs: Date.now() - callStartedAt,
                };
                const payloadRef = {
                    workspaceStateKey: workspace.stateKey,
                    detailLevel,
                    intent: requestedIntent,
                    topology: requestedTopology,
                };
                const verboseDetails = detailLevel === 'debug' || detailLevel === 'full';
                const compactPayload = {
                    workspace,
                    runId: execution.runId,
                    state: execution.state,
                    summary: summarizeExecution(execution),
                    resultPreview: truncateText(execution.result || summarizeExecution(execution), 700),
                    artifactsPath: execution.artifactsPath,
                    planner: execution.plannerState
                        ? {
                            selectedCrew: execution.plannerState.selectedCrew?.name,
                            selectedSpecialists: execution.plannerState.selectedSpecialists.slice(0, 4).map((specialist) => specialist.name),
                            selectedWorkflows: execution.plannerState.selectedWorkflows.slice(0, 4),
                        }
                        : undefined,
                    worktreeHealth: runtimeUsage.worktreeHealth
                        ? {
                            repoRoot: runtimeUsage.worktreeHealth.repoRoot,
                            overall: runtimeUsage.worktreeHealth.overall,
                            brokenEntries: runtimeUsage.worktreeHealth.brokenEntries,
                            repairedEntries: runtimeUsage.worktreeHealth.repairedEntries,
                            issues: runtimeUsage.worktreeHealth.issues,
                        }
                        : undefined,
                    modelRoute: selectionSummary.modelRoute,
                    verifiedWorkers,
                    continuationChildren: execution.continuationChildren.length,
                    timings,
                };
                const standardPayload = {
                    workspace,
                    runId: execution.runId,
                    state: execution.state,
                    summary: summarizeExecution(execution),
                    resultPreview: truncateText(execution.result || summarizeExecution(execution), 700),
                    artifactsPath: execution.artifactsPath,
                    planner: execution.plannerState
                        ? {
                            selectedCrew: execution.plannerState.selectedCrew?.name,
                            selectedSpecialists: execution.plannerState.selectedSpecialists.slice(0, 6).map((specialist) => specialist.name),
                            selectedSkills: execution.plannerState.selectedSkills.slice(0, 8),
                            selectedWorkflows: execution.plannerState.selectedWorkflows.slice(0, 8),
                            reviewGates: execution.plannerState.reviewGates.map((gate) => `${gate.gate}:${gate.status}`),
                        }
                        : undefined,
                    catalogHealth: runtimeUsage.catalogHealth,
                    tokenBudget: runtimeUsage.sourceAwareTokenBudget,
                    worktreeHealth: runtimeUsage.worktreeHealth,
                    ragUsageSummary: runtimeUsage.ragUsageSummary ?? execution.ragUsageSummary,
                    memoryScopeUsage: runtimeUsage.memoryScopeUsage ?? execution.memoryScopeUsage,
                    selection: selectionSummary,
                    modelRoute: selectionSummary.modelRoute,
                    verifiedWorkers,
                    continuationChildren: execution.continuationChildren.length,
                    executionPreset: preset ? { id: preset.id, name: preset.name, summary: preset.summary } : undefined,
                    autoTokenApplyNote,
                    timings,
                    payloadRef,
                };
                const debugPayload = {
                    workspace,
                    runId: execution.runId,
                    state: execution.state,
                    result: execution.result,
                    summary: summarizeExecution(execution),
                    artifactsPath: execution.artifactsPath,
                    planner: execution.plannerState
                        ? {
                            selectedCrew: execution.plannerState.selectedCrew?.name,
                            selectedSpecialists: execution.plannerState.selectedSpecialists.map((specialist) => specialist.name),
                            selectedSkills: execution.plannerState.selectedSkills,
                            selectedWorkflows: execution.plannerState.selectedWorkflows,
                            reviewGates: execution.plannerState.reviewGates.map((gate) => `${gate.gate}:${gate.status}`),
                        }
                        : undefined,
                    selectionAudit: runtimeUsage.artifactSelectionAudit,
                    artifactOutcome: runtimeUsage.artifactOutcome ?? execution.artifactOutcome,
                    workerPlan: runtimeUsage.workerPlan ?? execution.workerPlan,
                    taskGraph: runtimeUsage.taskGraph ?? execution.taskGraph,
                    tokenBudget: runtimeUsage.sourceAwareTokenBudget,
                    catalogHealth: runtimeUsage.catalogHealth,
                    bootstrapManifestStatus: runtimeUsage.bootstrapManifestStatus,
                    worktreeHealth: runtimeUsage.worktreeHealth,
                    ragUsageSummary: runtimeUsage.ragUsageSummary ?? execution.ragUsageSummary,
                    memoryScopeUsage: runtimeUsage.memoryScopeUsage ?? execution.memoryScopeUsage,
                    memoryReconciliationSummary: runtimeUsage.memoryReconciliationSummary ?? execution.memoryReconciliationSummary,
                    requestBrief: execution.requestBrief,
                    selectionPlan: execution.selectionPlan,
                    selection: selectionSummary,
                    modelRoute: selectionSummary.modelRoute,
                    tokens: execution.tokenTelemetry,
                    verifiedWorkers,
                    continuationChildren: execution.continuationChildren,
                    executionPreset: preset ? { id: preset.id, name: preset.name, summary: preset.summary } : undefined,
                    autoTokenApplyNote,
                    timings,
                    payloadRef,
                };
                const payload = verboseDetails
                    ? debugPayload
                    : detailLevel === 'standard'
                        ? standardPayload
                        : compactPayload;
                const verboseResponse = detailLevel !== 'compact';
                const stateLine = execution.state === 'inspected'
                    ? 'Orchestrated run inspected (read-only advisory; no diff expected).'
                    : `Orchestrated run ${execution.state}.`;
                return {
                    content: [{
                            type: 'text',
                            text: [
                                upfrontTokenNote ? `[Token plan] ${upfrontTokenNote}` : '',
                                stateLine,
                                formatBullets([
                                    `Workspace: ${workspace.repoName} (${workspace.workspaceSource})`,
                                    `Run ID: ${execution.runId}`,
                                    `Summary: ${summarizeExecution(execution)}`,
                                    `Crew: ${execution.plannerState?.selectedCrew?.name || 'baseline path'}`,
                                    `Hired/selected: crew ${selectionSummary.crew}; specialists ${formatSelectionList(selectionSummary.specialists)}; workflows ${formatSelectionList(selectionSummary.workflows)}; skills ${formatSelectionList(selectionSummary.skills)}`,
                                    ...(verboseResponse ? [
                                        `Decomposition: ${selectionSummary.phaseCount} phase(s), ${selectionSummary.workerLaneCount} worker lane(s), ${selectionSummary.mode}`,
                                        `Model route: ${formatModelRoute(selectionSummary.modelRoute)}`,
                                        `Budget route: ${selectionSummary.budgetRoute || 'budget pending'}`,
                                        selectionSummary.agentFlow?.stages?.length
                                            ? `AgentFlow gates: ${selectionSummary.agentFlow.stages.map((stage) => `${stage.stage}:${stage.ownerRole}`).join(' -> ')}`
                                            : null,
                                        `Selection audit: ${selectionSummary.auditSelected} selected, ${selectionSummary.auditRejected} rejected`,
                                    ] : [
                                        `Model route: ${formatModelRoute(selectionSummary.modelRoute)}`,
                                    ]),
                                    `Verification: ${verifiedWorkers}/${execution.workerResults.length} worker(s) verified`,
                                    verboseResponse ? `Tokens: saved ${Number(execution.tokenTelemetry?.savedTokens || 0).toLocaleString()} · compression ${Number(execution.tokenTelemetry?.compressionPct || 0)}%` : null,
                                    autoTokenApplyNote || null,
                                    verboseResponse ? `Payload ref: ${workspace.stateKey} · ${detailLevel}` : null,
                                    ...(verboseDetails ? [
                                        `Specialists: ${execution.plannerState?.selectedSpecialists.map((specialist) => specialist.name).slice(0, 4).join(', ') || 'none selected'}`,
                                        `Assets: ${(execution.activeSkills || []).length} skills · ${(execution.activeWorkflows || []).length} workflows · ${(runtimeUsage.artifactSelectionAudit?.selected?.length || 0)} audited selections`,
                                        `Task graph: ${runtimeUsage.taskGraph?.phases?.length || execution.taskGraph?.phases?.length || 0} phases · ${runtimeUsage.workerPlan?.totalWorkers || execution.workerPlan?.totalWorkers || 0} workers`,
                                        `Catalog health: ${runtimeUsage.catalogHealth?.overall || 'unknown'}`,
                                        preset ? `Preset: ${preset.name} (${preset.id})` : null,
                                        `Worktrees: ${runtimeUsage.worktreeHealth?.overall || 'unknown'} · repaired ${runtimeUsage.worktreeHealth?.repairedEntries || 0} · broken ${runtimeUsage.worktreeHealth?.brokenEntries || 0}`,
                                        `RAG: ${(runtimeUsage.ragUsageSummary?.attachedCollections || execution.knowledgeFabric?.rag.attachedCollections.length || 0)} attached · ${(runtimeUsage.ragUsageSummary?.retrievedChunks || execution.knowledgeFabric?.rag.hits.length || 0)} retrieved`,
                                        `Memory scopes: ${Object.entries(runtimeUsage.memoryScopeUsage?.byScope || execution.memoryScopeUsage?.byScope || {}).map(([scope, count]) => `${scope}:${count}`).join(' · ') || 'awaiting shared/session reads'}`,
                                        `Payload ref: ${workspace.stateKey} · ${detailLevel}`,
                                    ] : []),
                                ]),
                                verboseDetails && execution.result ? `Result\n\`\`\`\n${execution.result}\n\`\`\`` : `Result preview\n\`\`\`\n${truncateText(execution.result || summarizeExecution(execution), 900)}\n\`\`\``,
                                formatJsonDetails('Structured details', payload),
                                verboseResponse ? hctx.formatRemainingProtocolSteps() : '',
                            ].filter(Boolean).join('\n\n'),
                        }],
                };
            }
            catch (error) {
                const runtimeUsage = hctx.getRuntime().getUsageSnapshot();
                const worktreeHealth = runtimeUsage?.worktreeHealth;
                const remediation = Array.isArray(error?.remediation) ? error.remediation : [];
                const message = String(error?.message || error || 'Unknown orchestrate failure');
                const payload = {
                    state: 'failed',
                    summary: 'Orchestrated run failed before completion.',
                    error: message,
                    remediation,
                    worktreeHealth,
                    skipReasons: runtimeUsage?.skipReasons || [],
                };
                return {
                    content: [{
                            type: 'text',
                            text: [
                                'Orchestrated run failed before completion.',
                                formatBullets([
                                    `Cause: ${message.split('\n')[0]}`,
                                    `Worktrees: ${worktreeHealth?.overall || 'unknown'} · repaired ${worktreeHealth?.repairedEntries || 0} · broken ${worktreeHealth?.brokenEntries || 0}`,
                                    remediation.length ? `Remediation: ${remediation.join(' · ')}` : 'Remediation: rerun after pruning stale worktree metadata or repairing the repo worktree state',
                                    runtimeUsage?.skipReasons?.length ? `Skipped stages: ${runtimeUsage.skipReasons.join(' · ')}` : 'Skipped stages: not recorded',
                                ]),
                                formatJsonDetails('Structured details', payload),
                                detailLevel !== 'compact' ? hctx.formatRemainingProtocolSteps() : '',
                            ].join('\n\n'),
                        }],
                };
            }
        }
        case 'nexus_optimize_tokens': {
            const task = String(request.params.arguments?.goal ?? request.params.arguments?.task ?? '');
            const rawFiles = Array.isArray(request.params.arguments?.files)
                ? request.params.arguments.files.map(String)
                : null;
            const workspaceRoot = hctx.getWorkspace(request.params.arguments ?? {}).repoRoot;
            const scannedFilePaths = rawFiles
                ?? await hctx.scanSourceFiles(workspaceRoot);
            const requestedMaxFiles = Number(request.params.arguments?.maxFiles ?? request.params.arguments?.limit ?? 80);
            const maxFiles = Math.max(1, Math.min(Number.isFinite(requestedMaxFiles) ? Math.floor(requestedMaxFiles) : 80, 200));
            const filePaths = rawFiles ? scannedFilePaths : scannedFilePaths.slice(0, maxFiles);
            const omittedFiles = rawFiles ? 0 : Math.max(0, scannedFilePaths.length - filePaths.length);
            const statLimit = pLimit(8);
            const files = await Promise.all(filePaths.map((p) => statLimit(async () => {
                const resolved = hctx.resolveToolPath(p, request.params.arguments ?? {});
                try {
                    const stat = await fsPromises.stat(resolved);
                    return { path: resolved, sizeBytes: stat.size, lastModified: stat.mtimeMs };
                }
                catch {
                    return { path: resolved, sizeBytes: 0 };
                }
            })));
            // Differential: files unchanged since last session cost 0 tokens (cross-session dedup)
            const engine = getTokenEngine();
            const lastSession = await engine.loadLatestSessionSummary();
            const delta = lastSession ? engine.differential(lastSession, files) : null;
            const planFiles = delta ? [...delta.added, ...delta.changed] : files;
            const plan = await engine.plan(task, planFiles);
            // Inject unchanged files as cached-skip entries; add their token cost to savings
            const dedupTokens = delta
                ? delta.unchanged.reduce((sum, f) => sum + Math.ceil(f.sizeBytes / 4), 0)
                : 0;
            if (delta && delta.unchanged.length > 0) {
                const cachedEntries = delta.unchanged.map(f => ({
                    file: f,
                    action: 'skip',
                    tier: 'L0',
                    reason: 'unchanged since last session (cached)',
                    estimatedTokens: 0,
                }));
                plan.files.push(...cachedEntries);
                plan.savings += dedupTokens;
            }
            const formatted = formatReadingPlan(plan);
            // Persist the decision
            hctx.nexusRef.storeMemory(`Token plan for "${task.slice(0, 80)}": ` +
                `${plan.files.filter(a => a.action === 'full').length} full reads, ` +
                `${delta?.unchanged.length ?? 0} cached, ` +
                `saved ~${plan.savings.toLocaleString()} tokens.`, 0.5, ['#token-plan']);
            hctx.telemetry.recordTokens(plan.savings);
            const pct = plan.totalEstimatedTokens > 0 ? Math.round(plan.savings / (plan.totalEstimatedTokens + plan.savings) * 100) : 0;
            nexusEventBus.emit('tokens.optimized', { savings: plan.savings, pct, files: filePaths.length });
            // Persist token savings to the global ledger so the dashboard
            // hero KPI grows on day-one (not just from nexus_orchestrate runs).
            // Best-effort — never block the response.
            try {
                const orchestrator = hctx.getOrchestrator?.(request.params.arguments ?? {});
                const memory = orchestrator?.getMemoryEngine?.();
                if (memory && typeof memory.insertTokenTelemetry === 'function' && plan.savings > 0) {
                    const grossInput = plan.totalEstimatedTokens + plan.savings;
                    memory.insertTokenTelemetry({
                        sessionId: 'optimize-tokens',
                        task: String(task ?? 'optimize-tokens').slice(0, 200),
                        model: 'optimize-tokens',
                        tokensOptimized: plan.totalEstimatedTokens,
                        tokensSaved: plan.savings,
                        tokensForwarded: plan.totalEstimatedTokens,
                        compressionRatio: grossInput > 0 ? plan.totalEstimatedTokens / grossInput : 0,
                        fileCount: filePaths.length,
                        usdValueSaved: plan.savings / 1000 * 0.0006,
                    });
                }
            }
            catch { /* best-effort; ledger writer is non-critical */ }
            const notification = hctx.telemetry.notifyTokens(task, plan.savings, pct, filePaths.length);
            const fullReads = plan.files.filter((a) => a.action === 'full').length;
            const nudge = hctx.telemetry.planningNudge('optimize', { fullReads });
            // Per-call receipt: honest token + cost accounting (dedup shown separately)
            const COST_PER_1K_IN = 0.003; // Sonnet-class baseline $/1K tokens
            const estimatedCostUsd = (plan.totalEstimatedTokens / 1_000) * COST_PER_1K_IN;
            const savedCostUsd = (plan.savings / 1_000) * COST_PER_1K_IN;
            const dedupLine = dedupTokens > 0
                ? `\n           ${dedupTokens.toLocaleString()} tok deduped (${delta.unchanged.length} unchanged files)`
                : '';
            const scanLine = rawFiles
                ? `\n           explicit file set: ${filePaths.length.toLocaleString()} file(s)`
                : `\n           auto-scan capped: ${filePaths.length.toLocaleString()}/${scannedFilePaths.length.toLocaleString()} file(s)${omittedFiles ? ` (${omittedFiles.toLocaleString()} omitted; pass files or maxFiles to override)` : ''}`;
            const receipt = [
                '',
                `▸ Receipt  ${plan.totalEstimatedTokens.toLocaleString()} tok in`,
                `           ${plan.savings.toLocaleString()} tok saved (${pct}% vs full read)${dedupLine}`,
                scanLine.trimStart(),
                `           ~$${estimatedCostUsd.toFixed(4)} estimated · ~$${savedCostUsd.toFixed(4)} saved`,
            ].join('\n');
            return { content: [{ type: 'text', text: formatted + receipt + notification + nudge }] };
        }
        case 'nexus_mindkit_check': {
            const args = request.params.arguments ?? {};
            const ctx = {
                action: String(args?.action ?? ''),
                tokenCount: args?.tokenCount,
                filesToModify: Array.isArray(args?.filesToModify)
                    ? args.filesToModify.map(String)
                    : (Array.isArray(args?.files) ? args.files.map(String) : undefined),
                isDestructive: args?.isDestructive,
            };
            const result = getGuardrailEngine().check(ctx);
            // Store violations in Nexus memory
            if (result.violations.length > 0) {
                hctx.nexusRef.storeMemory(`[GUARDRAIL BLOCK] ${ctx.action.slice(0, 80)} — ${result.violations.map(v => v.id).join(', ')}`, 0.7, ['#guardrail', '#mindkit']);
            }
            nexusEventBus.emit('guardrail.check', { action: ctx.action, passed: result.passed, score: result.score });
            const nudge = result.passed
                ? hctx.telemetry.planningNudge('high_call_count', {})
                : hctx.telemetry.planningNudge('mindkit_fail', {});
            const verdict = result.passed ? 'PASS' : 'FAIL';
            const violationRows = result.violations.map((v) => {
                const item = v;
                return [
                    item.id ?? 'violation',
                    item.severity ?? 'high',
                    item.message ?? item.description ?? 'blocked by guardrail',
                ];
            });
            const warningRows = result.warnings.map((w) => {
                const item = w;
                return [
                    item.id ?? 'warning',
                    item.severity ?? 'warn',
                    item.message ?? item.description ?? 'review recommended',
                ];
            });
            const detailJson = JSON.stringify({
                passed: result.passed,
                score: Math.round(result.score * 100),
                filesToModify: ctx.filesToModify ?? [],
                violations: result.violations,
                warnings: result.warnings,
                summary: getGuardrailEngine().format(result)
            }, null, 2);
            return {
                content: [{
                        type: 'text',
                        text: [
                            `Mindkit check: ${verdict}`,
                            formatBullets([
                                `Score: ${Math.round(result.score * 100)}/100`,
                                `Files: ${ctx.filesToModify?.length ? ctx.filesToModify.join(', ') : 'none declared'}`,
                                `Decision: ${result.passed ? 'proceed' : 'stop and resolve guardrail violations'}`,
                                `Summary: ${getGuardrailEngine().format(result)}`,
                            ]),
                            violationRows.length ? `Violations\n${markdownTable(['Rule', 'Severity', 'Message'], violationRows)}` : '',
                            warningRows.length ? `Warnings\n${markdownTable(['Rule', 'Severity', 'Message'], warningRows)}` : '',
                            `Details\n\`\`\`json\n${detailJson}\n\`\`\``,
                            nudge,
                        ].filter(Boolean).join('\n\n')
                    }]
            };
        }
        case 'nexus_ghost_pass': {
            const goal = String(request.params.arguments?.goal ?? '');
            const rawFiles = Array.isArray(request.params.arguments?.files)
                ? request.params.arguments.files.map(String)
                : [];
            const files = await Promise.all(rawFiles.map(async (p) => {
                const resolved = hctx.resolveToolPath(p, request.params.arguments ?? {});
                try {
                    const stat = await fsPromises.stat(resolved);
                    return { path: resolved, sizeBytes: stat.size, lastModified: stat.mtimeMs };
                }
                catch {
                    return { path: resolved, sizeBytes: 0 };
                }
            }));
            const ghost = new GhostPass(hctx.getWorkspace(request.params.arguments ?? {}).repoRoot);
            const report = await ghost.analyze(goal, files);
            hctx.nexusRef.storeMemory(`Ghost pass for "${goal.slice(0, 80)}": ${report.riskAreas.length} risks identified.`, 0.6, ['#ghost-pass']);
            nexusEventBus.emit('ghost.pass', { task: goal, risks: report.riskAreas.length, workers: report.workerAssignments.length });
            const ghostNudge = hctx.telemetry.planningNudge('ghost_pass', { risks: report.riskAreas.length });
            const workerTable = markdownTable(['Worker', 'Approach', 'Token Budget', 'Files'], report.workerAssignments.map((worker, index) => [
                `Worker ${index + 1}`,
                worker.approach,
                worker.tokenBudget.toLocaleString(),
                worker.files.map(file => path.basename(file.path)).slice(0, 4).join(', ') || 'n/a',
            ]));
            const riskTable = markdownTable(['Risk', 'Severity', 'Mitigation'], report.riskAreas.map((risk) => [
                risk,
                'review',
                'Use the reading plan and isolate edits before mutation',
            ]));
            // Console ASCII UI
            const rCount = report.riskAreas.length;
            hctx.box('👻 GHOST PASS PRE-FLIGHT', [
                `Task: ${goal.replace(/\n/g, ' ').substring(0, 58).padEnd(60, ' ')}`,
                `${rCount > 0 ? `\x1b[31m⚠️  ${rCount} Risks Detected\x1b[0m` : '✅ No obvious risks'}`.padEnd(76, ' '),
                `Workers Suggested: ${report.workerAssignments.length.toString().padEnd(46, ' ')}`
            ], '33');
            return {
                content: [{
                        type: 'text',
                        text: [
                            'Ghost pass complete.',
                            formatBullets([
                                `Task ID: ${report.taskId}`,
                                `Estimated tokens: ${report.totalEstimatedTokens.toLocaleString()}`,
                                `Risks: ${report.riskAreas.length ? report.riskAreas.join(' | ') : 'none detected'}`,
                                `Worker approaches: ${report.workerAssignments.length}`,
                            ]),
                            riskTable ? `Risk table\n${riskTable}` : 'Risk table\nNo risks detected.',
                            workerTable ? `Worker table\n${workerTable}` : '',
                            'Reading plan\n```txt\n' + formatReadingPlan(report.readingPlan) + '\n```',
                            ghostNudge,
                        ].filter(Boolean).join('\n\n'),
                    }],
            };
        }
        case 'nexus_spawn_workers': {
            const goal = String(request.params.arguments?.goal ?? '');
            const workersCount = Number(request.params.arguments?.workers ?? 3);
            const rawFiles = Array.isArray(request.params.arguments?.files)
                ? request.params.arguments.files.map(String)
                : [];
            const verifyCommands = Array.isArray(request.params.arguments?.verify)
                ? request.params.arguments.verify.map(String)
                : undefined;
            const strategies = Array.isArray(request.params.arguments?.strategies)
                ? request.params.arguments.strategies.map(String)
                : undefined;
            const actions = Array.isArray(request.params.arguments?.actions)
                ? request.params.arguments.actions
                : [];
            const skills = Array.isArray(request.params.arguments?.skills)
                ? request.params.arguments.skills.map(String)
                : undefined;
            const workflows = Array.isArray(request.params.arguments?.workflows)
                ? request.params.arguments.workflows.map(String)
                : undefined;
            const crews = Array.isArray(request.params.arguments?.crews)
                ? request.params.arguments.crews.map(String)
                : undefined;
            const specialists = Array.isArray(request.params.arguments?.specialists)
                ? request.params.arguments.specialists.map(String)
                : undefined;
            const memoryBackend = request.params.arguments?.memoryBackend
                ? String(request.params.arguments.memoryBackend)
                : undefined;
            const compressionBackend = request.params.arguments?.compressionBackend
                ? String(request.params.arguments.compressionBackend)
                : undefined;
            const dslCompiler = request.params.arguments?.dslCompiler
                ? String(request.params.arguments.dslCompiler)
                : undefined;
            const backendMode = request.params.arguments?.backendMode
                ? String(request.params.arguments.backendMode)
                : undefined;
            const optimizationProfile = request.params.arguments?.optimizationProfile
                ? String(request.params.arguments.optimizationProfile)
                : undefined;
            const executionPreset = request.params.arguments?.executionPreset
                ? String(request.params.arguments.executionPreset)
                : undefined;
            const preset = resolveExecutionPreset(executionPreset);
            const inferredIntent = inferSpawnWorkersIntent(actions);
            // Surface worker-plan intent on the SSE feed without persisting it as a memory.
            try {
                nexusEventBus.emit('memory.snapshot', {
                    kind: 'worker-plan',
                    goal: goal.slice(0, 100),
                    workers: workersCount,
                    files: rawFiles.length,
                });
            }
            catch (err) {
                nexusEventBus.emit('mcp.handler.best-effort-failed', { toolName, stage: 'worker-plan-summary', error: err instanceof Error ? err.message : String(err) });
            }
            const execution = await hctx.getRuntime().run(applyExecutionPreset({
                goal,
                files: rawFiles,
                workers: workersCount,
                roles: ['planner', 'coder', 'verifier', 'skill-maker', 'research-shadow'],
                verifyCommands,
                strategies,
                actions,
                skillNames: skills,
                workflowSelectors: workflows,
                crewSelectors: crews,
                specialistSelectors: specialists,
                backendSelectors: { memoryBackend, compressionBackend, dslCompiler },
                backendMode,
                optimizationProfile,
                intent: inferredIntent,
                executionMode: 'manual-low-level',
                manualOverrides: ['nexus_spawn_workers'],
            }, executionPreset));
            const verifiedWorkers = execution.workerResults.filter(result => result.verified).length;
            const modifiedFiles = execution.workerResults.reduce((sum, result) => sum + result.modifiedFiles.length, 0);
            const noDiffInspected = execution.state === 'inspected'
                && modifiedFiles === 0
                && !execution.workerResults.some((result) => result.diff?.trim());
            const displayedDecision = noDiffInspected
                ? 'no-applicable-diff'
                : execution.finalDecision?.action ?? 'none';
            execution.activeSkills.forEach(skill => {
                hctx.sessionDNA.recordSkill(skill.name);
                if (skill.scope === 'global' || skill.rolloutStatus === 'promoted') {
                    hctx.sessionDNA.recordSkillLearned(skill.name);
                }
            });
            execution.workerResults.forEach(result => {
                result.modifiedFiles.forEach(file => hctx.sessionDNA.recordFileModified(file));
            });
            hctx.sessionDNA.recordDecision('Runtime swarm execution completed', execution.result || summarizeExecution(execution), execution.state === 'merged' ? 0.94
                : execution.state === 'inspected' ? 0.85
                    : execution.state === 'rolled_back' ? 0.45
                        : 0.3);
            hctx.nexusRef.storeMemory(`Runtime swarm: state=${execution.state}, workers=${execution.workerResults.length}, verified=${verifiedWorkers}, decision=${execution.finalDecision?.action ?? 'none'}`, execution.state === 'merged' ? 0.92 : 0.72, ['#phantom', '#decision', execution.state]);
            if (execution.finalDecision) {
                nexusEventBus.emit('phantom.merge', {
                    action: execution.finalDecision.action,
                    winner: execution.finalDecision.recommendedStrategy,
                });
                await hctx.nexusRef.analyzeLearning(goal, execution.finalDecision);
            }
            hctx.box('🐝 PHANTOM RUNTIME', [
                `Run: ${execution.runId.padEnd(28, ' ')} State: ${execution.state.padEnd(18, ' ')}`,
                `Workers: ${execution.workerResults.length.toString().padEnd(5, ' ')} Verified: ${verifiedWorkers.toString().padEnd(10, ' ')} Files: ${String(modifiedFiles).padEnd(12, ' ')}`,
                `${`Preset: ${preset?.name ?? 'manual'}`.padEnd(61, ' ')}`,
                `Decision: ${displayedDecision.padEnd(52, ' ')}`
            ], execution.state === 'merged' || execution.state === 'inspected' ? '32' : execution.state === 'rolled_back' ? '33' : '31');
            return {
                content: [{
                        type: 'text',
                        text: [
                            `🐝 Phantom Runtime — ${summarizeExecution(execution)}`,
                            '',
                            `Run ID: ${execution.runId}`,
                            `State: ${execution.state}`,
                            `Artifacts: ${execution.artifactsPath}`,
                            `Workers: ${execution.workerResults.length}`,
                            preset ? `Preset: ${preset.name} (${preset.id})` : null,
                            `Verified Workers: ${verifiedWorkers}`,
                            `Modified Files: ${modifiedFiles}`,
                            `Decision: ${displayedDecision}`,
                            `Recommended Strategy: ${execution.finalDecision?.recommendedStrategy ?? 'n/a'}`,
                            `Planner: ${execution.plannerResult?.summary ?? 'n/a'}`,
                            `Crew: ${execution.plannerResult?.selectedCrew?.name ?? 'n/a'}`,
                            `Specialists: ${execution.plannerResult?.selectedSpecialists?.length ? execution.plannerResult.selectedSpecialists.map((specialist) => specialist.name).join(', ') : 'none'}`,
                            `Fallback: ${execution.plannerResult?.fallbackPlan?.summary ?? 'current runtime fallback'}`,
                            `Backends: memory=${execution.selectedBackends.memoryBackend}, compression=${execution.selectedBackends.compressionBackend}, consensus=${execution.selectedBackends.consensusPolicy}, dsl=${execution.selectedBackends.dslCompiler}`,
                            `Active Skills: ${execution.activeSkills.length > 0 ? execution.activeSkills.map(skill => `${skill.name}(${skill.riskClass})`).join(', ') : 'none'}`,
                            `Active Workflows: ${execution.activeWorkflows.length > 0 ? execution.activeWorkflows.map(workflow => workflow.name).join(', ') : 'none'}`,
                            `Promotions: ${execution.promotionDecisions.length > 0 ? execution.promotionDecisions.map(decision => `${decision.kind}:${decision.target}:${decision.approved ? 'approved' : 'held'}`).join(', ') : 'none'}`,
                            '',
                            `Result: ${execution.result}`
                        ].join('\n')
                    }]
            };
        }
        case 'nexus_session_dna': {
            const action = String(request.params.arguments?.action ?? 'load');
            const sessionId = request.params.arguments?.sessionId
                ? String(request.params.arguments.sessionId)
                : undefined;
            if (action === 'generate') {
                hctx.telemetry.observeSuccessfulToolCall('nexus_session_dna', { action });
                // Tier promotion sweep: migrate frequently-accessed memories up the
                // hierarchy (prefrontal → hippocampus → cortex). Fire-and-forget —
                // the sweep runs synchronously but is cheap (~1-5ms on typical stores).
                try {
                    const promoted = hctx.nexusRef.runTierPromotion?.();
                    if (promoted)
                        nexusEventBus.emit('memory.tier.promoted', promoted);
                }
                catch (err) {
                    nexusEventBus.emit('mcp.handler.failed', {
                        toolName: 'nexus_session_dna.tierPromotion',
                        code: 'internal',
                        attempts: 1,
                        durationMs: 0,
                    });
                }
                // Sync counters from telemetry before generating
                const telemetry = hctx.telemetry.snapshot();
                hctx.sessionDNA.syncFromTelemetry({
                    callCount: telemetry.callCount,
                    memoriesStored: telemetry.memoriesStored,
                    memoriesRecalled: telemetry.memoriesRecalled,
                    tokensOptimized: telemetry.tokensOptimized,
                });
                const dna = hctx.sessionDNA.flush();
                const formatted = SessionDNAManager.format(dna);
                // Trigger self-summarization at session end
                try {
                    hctx.getOrchestrator(request.params.arguments ?? {}).persistSessionSummary(telemetry.tokensOptimized || hctx.getRuntime(request.params.arguments ?? {}).getUsageSnapshot().tokens?.grossInputTokens || 0);
                }
                catch (err) {
                    nexusEventBus.emit('mcp.handler.failed', {
                        toolName: 'nexus_session_dna.persistSessionSummary',
                        code: 'internal',
                        attempts: 1,
                        durationMs: 0,
                    });
                }
                await getSharedTelemetry().trackSessionEnd(hctx.telemetry.elapsedMs(), {
                    projectId: hctx.getWorkspace(request.params.arguments ?? {}).repoRoot,
                    tokensSaved: telemetry.tokensOptimized,
                    memoriesCreated: telemetry.memoriesStored,
                    memoriesRecalled: telemetry.memoriesRecalled,
                    toolsUsed: telemetry.callCount,
                    sessionId: dna.sessionId,
                }).catch((err) => {
                    nexusEventBus.emit('mcp.handler.failed', {
                        toolName: 'nexus_session_dna.trackSessionEnd',
                        code: 'internal',
                        attempts: 1,
                        durationMs: 0,
                    });
                });
                return {
                    content: [{
                            type: 'text',
                            text: `✅ Session DNA generated and saved.\n\n${formatted}`,
                        }],
                };
            }
            else {
                // Load latest or by ID
                const dna = sessionId
                    ? SessionDNAManager.loadById(sessionId)
                    : SessionDNAManager.loadLatest();
                if (!dna) {
                    return {
                        content: [{
                                type: 'text',
                                text: '📭 No previous Session DNA found. This appears to be a fresh start.',
                            }],
                    };
                }
                const formatted = SessionDNAManager.format(dna);
                return {
                    content: [{
                            type: 'text',
                            text: `📦 Previous Session DNA loaded:\n\n${formatted}`,
                        }],
                };
            }
        }
        case 'nexus_plan_execution': {
            const goal = String(request.params.arguments?.goal ?? '');
            const files = Array.isArray(request.params.arguments?.files)
                ? request.params.arguments.files.map(String)
                : undefined;
            const skills = Array.isArray(request.params.arguments?.skills)
                ? request.params.arguments.skills.map(String)
                : undefined;
            const workflows = Array.isArray(request.params.arguments?.workflows)
                ? request.params.arguments.workflows.map(String)
                : undefined;
            const crews = Array.isArray(request.params.arguments?.crews)
                ? request.params.arguments.crews.map(String)
                : undefined;
            const specialists = Array.isArray(request.params.arguments?.specialists)
                ? request.params.arguments.specialists.map(String)
                : undefined;
            const optimizationProfile = request.params.arguments?.optimizationProfile
                ? String(request.params.arguments.optimizationProfile)
                : undefined;
            const executionPreset = request.params.arguments?.executionPreset
                ? String(request.params.arguments.executionPreset)
                : undefined;
            const preset = resolveExecutionPreset(executionPreset);
            const planner = await hctx.getRuntime().planExecution(applyExecutionPreset({
                goal,
                files,
                skillNames: skills,
                workflowSelectors: workflows,
                crewSelectors: crews,
                specialistSelectors: specialists,
                optimizationProfile,
            }, executionPreset));
            return {
                content: [{
                        type: 'text',
                        text: [
                            `🧭 Execution Plan — ${planner.objective}`,
                            '',
                            preset ? `Preset: ${preset.name} (${preset.id})` : 'Preset: manual',
                            `Crew: ${planner.selectedCrew.name} (${planner.selectedCrew.confidence.score.toFixed(2)})`,
                            `Specialists: ${planner.selectedSpecialists.length > 0 ? planner.selectedSpecialists.map((specialist) => `${specialist.name}(${specialist.authority})`).join(', ') : 'none'}`,
                            `Skills: ${planner.selectedSkills.length > 0 ? planner.selectedSkills.join(', ') : 'none'}`,
                            `Workflows: ${planner.selectedWorkflows.length > 0 ? planner.selectedWorkflows.join(', ') : 'none'}`,
                            `Tools: ${planner.toolPolicy.allowedTools.join(', ')}`,
                            `Swarm: ${planner.swarmDecision.mode} (${planner.swarmDecision.workers} workers)`,
                            `Fallback: ${planner.fallbackPlan.summary}`,
                            `Review Gates: ${planner.reviewGates.map((gate) => gate.gate).join(', ')}`,
                            '',
                            `Planning Ledger:`,
                            ...planner.ledger.map((row, index) => `${index + 1}. ${row.stage} · ${row.status} · ${row.owner} · ${row.selectedAssets.join(', ') || 'n/a'} · ${row.notes}`),
                        ].join('\n'),
                    }],
            };
        }
    }
    return undefined;
}
