import { synapseToolDefinitions } from '../../../synapse/index.js';
import { architectsToolDefinitions } from '../../../architects/index.js';
import { getGstackBridge } from '../../../engines/gstack-bridge.js';
export const FIRST_CLASS_TOOLS = new Set([
    'nexus_session_bootstrap',
    'nexus_orchestrate',
    'nexus_session_dna',
    'nexus_store_memory',
    'nexus_recall_memory',
    'nexus_memory_stats',
    'nexus_optimize_tokens',
    'nexus_mindkit_check',
    'nexus_ghost_pass',
    'nexus_describe_tool',
    'nexus_search',
    'nexus_runtime_health',
    'nexus_run_status',
    'nexus_user_workflow_trace',
    'kernel_run_step',
    'kernel_run_verify',
    'kernel_run_merge',
]);
export function buildMcpToolDefinitions() {
    const tools = [
        // ── Memory ────────────────────────────────────────────────────────
        {
            name: 'nexus_store_memory',
            description: 'Store a finding, insight, or memory into Nexus Prime. MANDATORY after significant findings and at session end. Priority 0-1 (1.0 = critical). High-priority items auto-fission to long-term memory.',
            inputSchema: {
                type: 'object',
                properties: {
                    content: { type: 'string', description: 'The knowledge to store' },
                    priority: { type: 'number', description: 'Priority 0-1 (default 0.7). Use 1.0 for critical insights.' },
                    tags: { type: 'array', items: { type: 'string' }, description: 'Tags e.g. bug, architecture, decision' },
                    verbatim: { type: 'boolean', description: 'When true, stores content as-is without compression. Adds #verbatim tag so compaction passes skip this item.' },
                },
                required: ['content'],
            },
        },
        // ── Memory ────────────────────────────────────────────────────────
        {
            name: 'nexus_recall_memory',
            description: 'Retrieve relevant context from Nexus Prime. Call at the START of each session to recover prior knowledge. Also call mid-session when encountering a topic that may have been researched before.',
            inputSchema: {
                type: 'object',
                properties: {
                    query: { type: 'string', description: 'What are you trying to remember or find?' },
                    k: { type: 'number', description: 'Number of results (default 5)' }
                },
                required: ['query'],
            },
        },
        {
            name: 'nexus_memory_stats',
            description: 'Get deep stats about the Graph Knowledge Engine: tier counts, top tags, and Zettelkasten links. Use this to gauge available knowledge depth before starting research.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_temporal_query',
            description: 'Query the knowledge graph at a specific point in time. Answers "what was true about X at time T?" using the graph\'s valid_from/valid_until temporal schema. Useful for understanding how knowledge evolved.',
            inputSchema: {
                type: 'object',
                properties: {
                    query: { type: 'string', description: 'Keyword search for the topic or entity to query' },
                    at: { type: 'string', description: 'ISO 8601 datetime or Unix timestamp (ms) to evaluate the knowledge graph at. Omit for current state.' },
                    k: { type: 'number', description: 'Max results to return (default 10)' },
                },
                required: ['query'],
            },
        },
        {
            name: 'nexus_memory_export',
            description: 'Expert surface: export a portable Nexus memory bundle by scope/state/session.',
            inputSchema: {
                type: 'object',
                properties: {
                    limit: { type: 'number', description: 'Optional maximum exported items' },
                    scope: { type: 'string', enum: ['session', 'project', 'user', 'promoted', 'shared'], description: 'Optional memory scope filter' },
                    state: { type: 'string', enum: ['active', 'quarantined', 'scrap'], description: 'Optional memory state filter' },
                    sessionId: { type: 'string', description: 'Optional session filter' },
                },
                required: [],
            },
        },
        {
            name: 'nexus_memory_backup',
            description: 'Expert surface: export a portable memory bundle and persist it to the Nexus memory vault exports directory.',
            inputSchema: {
                type: 'object',
                properties: {
                    limit: { type: 'number', description: 'Optional maximum exported items' },
                    scope: { type: 'string', enum: ['session', 'project', 'user', 'promoted', 'shared'], description: 'Optional memory scope filter' },
                    state: { type: 'string', enum: ['active', 'quarantined', 'scrap'], description: 'Optional memory state filter' },
                    sessionId: { type: 'string', description: 'Optional session filter' },
                },
                required: [],
            },
        },
        {
            name: 'nexus_memory_import',
            description: 'Expert surface: import a previously exported portable memory bundle into Nexus memory.',
            inputSchema: {
                type: 'object',
                properties: {
                    path: { type: 'string', description: 'Absolute path to a previously exported memory bundle' },
                    bundle: { type: 'object', description: 'Inline memory bundle payload when importing programmatically' },
                },
                required: [],
            },
        },
        {
            name: 'nexus_memory_trace',
            description: 'Expert surface: inspect one memory item with lineage, backlinks, and reconciliation details.',
            inputSchema: {
                type: 'object',
                properties: {
                    id: { type: 'string', description: 'Memory ID to inspect' },
                },
                required: ['id'],
            },
        },
        {
            name: 'nexus_memory_update',
            description: 'Expert surface: update an existing memory item, including content, tags, scope, state, retention, and actor-scoped provenance.',
            inputSchema: {
                type: 'object',
                properties: {
                    id: { type: 'string', description: 'Memory ID to update' },
                    content: { type: 'string', description: 'Optional replacement content' },
                    priority: { type: 'number', description: 'Optional replacement priority' },
                    tags: { type: 'array', items: { type: 'string' }, description: 'Optional replacement tags' },
                    scope: { type: 'string', enum: ['session', 'project', 'user', 'promoted', 'shared'], description: 'Optional replacement scope' },
                    state: { type: 'string', enum: ['active', 'quarantined', 'scrap', 'expired'], description: 'Optional replacement state' },
                    trust: { type: 'number', description: 'Optional replacement trust score' },
                    expiresAt: { type: 'number', description: 'Optional replacement expiry timestamp in milliseconds since epoch' },
                    retentionHint: { type: 'string', enum: ['default', 'session', 'short', 'standard', 'long', 'forever'], description: 'Optional retention policy hint' },
                    provenance: { type: 'object', description: 'Optional actor scope and provenance overrides' },
                },
                required: ['id'],
            },
        },
        {
            name: 'nexus_memory_delete',
            description: 'Expert surface: soft-delete or permanently delete a memory item while preserving deletion history.',
            inputSchema: {
                type: 'object',
                properties: {
                    id: { type: 'string', description: 'Memory ID to delete' },
                    hardDelete: { type: 'boolean', description: 'When true, permanently remove the memory row instead of expiring it' },
                    reason: { type: 'string', description: 'Optional deletion reason recorded in memory history' },
                    provenance: { type: 'object', description: 'Optional actor scope and provenance overrides' },
                },
                required: ['id'],
            },
        },
        {
            name: 'nexus_memory_history',
            description: 'Expert surface: inspect the mutation and feedback history for a memory item.',
            inputSchema: {
                type: 'object',
                properties: {
                    id: { type: 'string', description: 'Memory ID to inspect' },
                    limit: { type: 'number', description: 'Maximum history entries to return (default 20)' },
                },
                required: ['id'],
            },
        },
        {
            name: 'nexus_memory_feedback',
            description: 'Expert surface: attach explicit operator feedback to a memory item to promote, demote, quarantine, or re-score it.',
            inputSchema: {
                type: 'object',
                properties: {
                    id: { type: 'string', description: 'Memory ID to score' },
                    reaction: { type: 'string', enum: ['positive', 'negative', 'promote', 'demote', 'quarantine'], description: 'Feedback reaction to apply' },
                    rating: { type: 'number', description: 'Optional numeric score from -1 to 1' },
                    note: { type: 'string', description: 'Optional operator note stored in history' },
                    provenance: { type: 'object', description: 'Optional actor scope and provenance overrides' },
                },
                required: ['id'],
            },
        },
        {
            name: 'nexus_runtime_health',
            description: 'Return the unified runtime health envelope shared by MCP, dashboard, and terminal cockpit surfaces.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_doctor',
            description: 'Run a structured runtime doctor pass covering workspace resolution, client bootstrap drift, mandatory engine readiness, and worktree health.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_autofix',
            description: 'Apply safe self-healing steps: refresh bootstrap state, compact noisy memory, and report any remaining runtime issues.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_memory_hygiene',
            description: 'Summarize and optionally run memory hygiene so duplicate, quarantined, and low-signal memories do not pollute active recall surfaces.',
            inputSchema: {
                type: 'object',
                properties: {
                    mode: { type: 'string', enum: ['report', 'apply'], description: 'Report hygiene status only, or apply one bounded hygiene pass before reporting' },
                    apply: { type: 'boolean', description: 'When true, run memory maintenance before returning the hygiene report' },
                    batchSize: { type: 'number', description: 'Maximum number of rows to touch in one hygiene pass (default 250, max 250)' },
                    states: { type: 'array', items: { type: 'string', enum: ['active', 'quarantined', 'scrap', 'expired'] }, description: 'Optional memory states to include in the hygiene pass' },
                    limit: { type: 'number', description: 'Optional audit sample size (default 80)' },
                },
                required: [],
            },
        },
        {
            name: 'nexus_operative_journal',
            description: 'Read, append to, or list per-operative memory journals. Each Synapse operative maintains its own persistent diary of learnings and decisions across sessions.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: { type: 'string', enum: ['append', 'read', 'list', 'recent'], description: 'append — add an entry; read — get all entries for an operative; list — list operative IDs with journals; recent — newest entries across all operatives' },
                    operativeId: { type: 'string', description: 'Operative ID (required for append and read)' },
                    content: { type: 'string', description: 'Journal entry content (required for append)' },
                    tags: { type: 'array', items: { type: 'string' }, description: 'Tags for this entry (append only)' },
                    limit: { type: 'number', description: 'Max results to return for recent/read (default 20)' },
                },
                required: ['action'],
            },
        },
        {
            name: 'nexus_selection_ledger',
            description: 'Inspect the latest selection ledger: candidate assets, chosen assets, rejected assets, and execution-ledger reasoning.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_session_bootstrap',
            description: 'Read-only session-start summary. Defaults to fast readiness mode and returns current client identity, memory recall summary, memory stats, recommended next step, recommended execution mode, shortlist recommendations, and whether deeper preparation is still needed.',
            inputSchema: {
                type: 'object',
                properties: {
                    goal: { type: 'string', description: 'Raw goal or task description for this session' },
                    files: { type: 'array', items: { type: 'string' }, description: 'Optional candidate file constraints' },
                    detailLevel: { type: 'string', enum: ['compact', 'standard', 'debug', 'full'], description: 'Response verbosity; defaults to compact for MCP callers' },
                    depth: { type: 'string', enum: ['fast', 'deep'], description: 'Optional bootstrap depth override; defaults to fast unless debug mode is requested' },
                    include: { type: 'array', items: { type: 'string' }, description: 'Optional rich payload sections to include for advanced clients' },
                    intent: { type: 'string', enum: ['inspect', 'plan', 'mutate'], description: 'Requested orchestration stance for the bootstrap summary' },
                    topology: { type: 'string', enum: ['auto', 'manager-tools', 'handoff', 'dag-pool', 'worktree-swarm'], description: 'Requested orchestration topology hint' },
                },
                required: ['goal'],
            },
        },
        // ── License & Usage ───────────────────────────────────────────────
        {
            name: 'nexus_license_usage',
            description: 'View current license status, plan tier, and platform currency unit (PCU) consumption. Shows memory entries, projects, operatives, skill profile, Darwin scope, value metrics (tokens saved, USD saved, orchestrations), and upgrade path.',
            inputSchema: {
                type: 'object',
                properties: {
                    format: { type: 'string', enum: ['summary', 'json', 'bars'], description: 'Output format: summary (default) — human-friendly overview, json — raw PCU snapshot, bars — CLI progress bars' },
                },
                required: [],
            },
        },
        // ── Token optimization ────────────────────────────────────────────
        {
            name: 'nexus_orchestrate',
            description: 'Primary raw-prompt entrypoint. Let Nexus Prime classify intent, recall memory, plan, choose crews/specialists/skills/workflows/hooks/automations, optimize tokens, and execute a bounded autonomous run.',
            inputSchema: {
                type: 'object',
                properties: {
                    prompt: { type: 'string', description: 'Raw prompt or objective to orchestrate end-to-end' },
                    files: { type: 'array', items: { type: 'string' }, description: 'Optional hard constraints for candidate files' },
                    detailLevel: { type: 'string', enum: ['compact', 'standard', 'debug', 'full'], description: 'Response verbosity; defaults to compact for MCP callers' },
                    intent: { type: 'string', enum: ['inspect', 'plan', 'mutate'], description: 'Requested orchestration stance; inspect/plan should stay read-only' },
                    topology: { type: 'string', enum: ['auto', 'manager-tools', 'handoff', 'dag-pool', 'worktree-swarm'], description: 'Requested orchestration topology hint' },
                    workers: { type: 'number', description: 'Optional worker override' },
                    skills: { type: 'array', items: { type: 'string' }, description: 'Optional hard skill selectors' },
                    workflows: { type: 'array', items: { type: 'string' }, description: 'Optional hard workflow selectors' },
                    hooks: { type: 'array', items: { type: 'string' }, description: 'Optional hard hook selectors' },
                    automations: { type: 'array', items: { type: 'string' }, description: 'Optional hard automation selectors' },
                    crews: { type: 'array', items: { type: 'string' }, description: 'Optional hard crew selectors' },
                    specialists: { type: 'array', items: { type: 'string' }, description: 'Optional hard specialist selectors' },
                    optimizationProfile: { type: 'string', enum: ['standard', 'max'], description: 'Planner optimization profile override' },
                    executionPreset: { type: 'string', enum: ['fast', 'balanced', 'deep', 'release'], description: 'Optional execution preset that maps orchestration depth, verification strictness, and backend routing' },
                    background: { type: 'boolean', description: 'Compatibility flag; nexus_orchestrate already returns a queued hiring preflight by default and continues in the async gate.' },
                    async: { type: 'boolean', description: 'Alias for background; useful for clients that prefer explicit async orchestration.' },
                    wait: { type: 'boolean', description: 'Alias for inline/sync execution. Waits up to the MCP-safe bounded window and returns the final result when it completes in time.' },
                    waitMs: { type: 'number', description: 'Advanced/debug bounded wait for inline execution. Clamped to 45 seconds; normal orchestrate calls return a queued preflight immediately.' },
                    inline: { type: 'boolean', description: 'Advanced/debug only: wait for inline orchestrate output instead of the default fast queued preflight.' }
                },
                required: ['prompt'],
            },
        },
        {
            name: 'nexus_optimize_tokens',
            description: 'Generate a token-efficient file reading plan. Always-on: auto-applies during bootstrap for any files. Returns which files to read fully, outline-only, or skip. Typically saves 50-90% tokens per session.',
            inputSchema: {
                type: 'object',
                properties: {
                    goal: { type: 'string', description: 'What you are trying to accomplish' },
                    task: { type: 'string', description: 'Alias for goal (deprecated, use goal)' },
                    files: { type: 'array', items: { type: 'string' }, description: 'File paths to analyze. If omitted, auto-scans a capped source shortlist instead of the whole repo.' },
                    budget: { type: 'number', description: 'Token budget override' },
                    maxFiles: { type: 'number', description: 'Maximum files to include when files are omitted (default 80, max 200)' }
                },
                required: [],
            },
        },
        // ── Search ──────────────────────────────────────────────────────
        {
            name: 'nexus_search',
            description: 'Fast codebase search using sparse n-gram index. Returns matching documents ranked by relevance. Much faster and cheaper than reading full files — reports token savings vs brute-force file reads.',
            inputSchema: {
                type: 'object',
                properties: {
                    query: { type: 'string', description: 'Search query (text or pattern)' },
                    limit: { type: 'number', description: 'Max results to return (default 20)' },
                    sparse: { type: 'boolean', description: 'Use sparse n-gram search for higher selectivity (default false)' },
                },
                required: ['query'],
            },
        },
        // ── Context Discovery ────────────────────────────────────────────
        {
            name: 'nexus_describe_tool',
            description: 'Get full description and schema for any Nexus tool on demand. Use when you need details about a specific capability without loading all tool descriptions upfront. Saves tokens via lazy loading.',
            inputSchema: {
                type: 'object',
                properties: {
                    tool_name: { type: 'string', description: 'Name of the Nexus tool to describe' },
                },
                required: ['tool_name'],
            },
        },
        // ── Mindkit ──────────────────────────────────────────────────────
        {
            name: 'nexus_mindkit_check',
            description: 'Check an action against Mindkit guardrails before executing. MANDATORY before destructive operations (deleting files, installing packages, modifying production configs). Returns PASS/FAIL with score 0-100, violations, and suggestions.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: {
                        type: 'string',
                        description: 'The action or prompt to validate'
                    },
                    tokenCount: {
                        type: 'number',
                        description: 'Estimated token count of current context'
                    },
                    filesToModify: {
                        type: 'array',
                        items: { type: 'string' },
                        description: 'Files that will be modified'
                    },
                    isDestructive: {
                        type: 'boolean',
                        description: 'True if operation could cause data loss'
                    }
                },
                required: ['action']
            }
        },
        {
            name: 'nexus_ghost_pass',
            description: 'Read-only pre-flight analysis. Call BEFORE modifying 3+ interrelated files. Returns risk areas, optimal reading plan, and whether to use Phantom Workers. If it suggests parallel approaches, follow up with nexus_spawn_workers.',
            inputSchema: {
                type: 'object',
                properties: {
                    goal: { type: 'string', description: 'What you want to accomplish' },
                    files: { type: 'array', items: { type: 'string' }, description: 'Relevant file paths' }
                },
                required: ['goal'],
            },
        },
        {
            name: 'nexus_spawn_workers',
            description: 'Spawn parallel Phantom Workers when modifying 3+ interrelated files OR when Ghost Pass recommends parallel exploration. Each worker gets an isolated git worktree to execute actions, run verification, and return artifacts. The runtime applies merge consensus and reports the final decision truthfully.',
            inputSchema: {
                type: 'object',
                properties: {
                    goal: { type: 'string', description: 'The overall goal for the swarm' },
                    files: { type: 'array', items: { type: 'string' }, description: 'Files relevant to the task' },
                    workers: { type: 'number', description: 'Number of phantom workers to spawn (max 7)', default: 3 },
                    verify: { type: 'array', items: { type: 'string' }, description: 'Verification commands to run in verifier worktrees' },
                    strategies: { type: 'array', items: { type: 'string' }, description: 'Optional worker strategies such as minimal, standard, thorough' },
                    actions: { type: 'array', items: { type: 'object' }, description: 'Optional runtime actions or skill bindings to execute in worker worktrees' },
                    skills: { type: 'array', items: { type: 'string' }, description: 'Runtime skill selectors' },
                    workflows: { type: 'array', items: { type: 'string' }, description: 'Workflow selectors' },
                    crews: { type: 'array', items: { type: 'string' }, description: 'Crew selectors' },
                    specialists: { type: 'array', items: { type: 'string' }, description: 'Specialist selectors' },
                    memoryBackend: { type: 'string', description: 'Memory backend selector' },
                    compressionBackend: { type: 'string', description: 'Compression backend selector' },
                    dslCompiler: { type: 'string', description: 'DSL compiler selector' },
                    backendMode: { type: 'string', enum: ['default', 'shadow', 'experimental'], description: 'Backend execution mode' },
                    optimizationProfile: { type: 'string', enum: ['standard', 'max'], description: 'Planner optimization profile' },
                    executionPreset: { type: 'string', enum: ['fast', 'balanced', 'deep', 'release'], description: 'Optional execution preset for cheap, balanced, deep, or release-grade runs' },
                },
                required: ['goal', 'files'],
            },
        },
        {
            name: 'nexus_plan_execution',
            description: 'Run the additive task planner without executing mutations. Returns selected crew, specialists, skills, tools, fallback plan, and review gates.',
            inputSchema: {
                type: 'object',
                properties: {
                    goal: { type: 'string', description: 'The overall goal to plan' },
                    files: { type: 'array', items: { type: 'string' }, description: 'Optional focused files' },
                    skills: { type: 'array', items: { type: 'string' }, description: 'Optional skill selectors' },
                    workflows: { type: 'array', items: { type: 'string' }, description: 'Optional workflow selectors' },
                    crews: { type: 'array', items: { type: 'string' }, description: 'Optional crew selectors' },
                    specialists: { type: 'array', items: { type: 'string' }, description: 'Optional specialist selectors' },
                    optimizationProfile: { type: 'string', enum: ['standard', 'max'], description: 'Planner optimization profile' },
                    executionPreset: { type: 'string', enum: ['fast', 'balanced', 'deep', 'release'], description: 'Optional execution preset for cheap, balanced, deep, or release-grade planning' }
                },
                required: ['goal'],
            },
        },
        {
            name: 'nexus_list_execution_presets',
            description: 'List the execution presets that map user intent onto runtime depth, verification strictness, and backend selection.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_audit_evolution',
            description: 'Identify recurring failure patterns, file hotspots, and code areas needing refactoring. Call at sprint boundaries, after major bug fixes, or when the same files keep breaking. Returns prioritized recommendations.',
            inputSchema: {
                type: 'object',
                properties: {},
            },
        },
        // ── Session DNA ──────────────────────────────────────────────────
        {
            name: 'nexus_token_report',
            description: 'Get persistent token usage analytics, including lifetime tokens optimized, saved, forwarded, and cost savings across sessions.',
            inputSchema: {
                type: 'object',
                properties: {
                    scope: { type: 'string', enum: ['lifetime', 'recent'], description: 'Whether to get lifetime aggregate or recent sessions summary (default: lifetime)' },
                    limit: { type: 'number', description: 'Number of recent sessions to view if scope is recent (default: 10)' }
                },
                required: [],
            },
        },
        {
            name: 'nexus_session_dna',
            description: 'Generate or load a Session DNA snapshot. MANDATORY at session end when using "generate". Captures files accessed/modified, decisions made, skills used, and recommended next steps for perfect session handover.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: { type: 'string', enum: ['generate', 'load'], description: 'Whether to generate current session DNA or load the latest previous session DNA' },
                    sessionId: { type: 'string', description: 'Optional: load a specific session by ID instead of the latest' }
                },
                required: ['action'],
            },
        },
        {
            name: 'nexus_session_search',
            description: 'Search prior Session DNA snapshots without promoting transcripts into long-term memory.',
            inputSchema: {
                type: 'object',
                properties: {
                    query: { type: 'string', description: 'Terms to search across prior session snapshots' },
                    limit: { type: 'number', description: 'Maximum hits to return (default 5)' },
                    minScore: { type: 'number', description: 'Minimum deterministic score threshold' },
                    sessionsDir: { type: 'string', description: 'Optional alternate sessions directory' },
                },
                required: ['query'],
            },
        },
        {
            name: 'nexus_channel_map_thread',
            description: 'Map an inbound Slack, Telegram, or Feishu/Lark thread onto a Nexus session or mission while preserving external thread identity.',
            inputSchema: {
                type: 'object',
                properties: {
                    provider: { type: 'string', enum: ['slack', 'telegram', 'feishu', 'lark', 'feishu-lark'], description: 'Channel provider' },
                    conversationId: { type: 'string', description: 'Provider-native conversation or channel identifier' },
                    threadId: { type: 'string', description: 'Provider-native thread identifier' },
                    messageId: { type: 'string', description: 'Provider-native message identifier' },
                    parentMessageId: { type: 'string', description: 'Optional parent message identifier' },
                    workspaceId: { type: 'string', description: 'Optional workspace or tenant identifier' },
                    targetKind: { type: 'string', enum: ['session', 'mission'], description: 'Nexus target type' },
                    targetId: { type: 'string', description: 'Nexus session or mission identifier' },
                    sourceUrl: { type: 'string', description: 'Optional canonical source URL' },
                },
                required: ['provider', 'conversationId', 'targetKind', 'targetId'],
            },
        },
        {
            name: 'nexus_channel_artifact_envelope',
            description: 'Wrap a Nexus artifact for delivery back to Slack, Telegram, or Feishu/Lark with preserved thread metadata and attachments.',
            inputSchema: {
                type: 'object',
                properties: {
                    provider: { type: 'string', enum: ['slack', 'telegram', 'feishu', 'lark', 'feishu-lark'], description: 'Channel provider' },
                    thread: { type: 'object', description: 'Channel thread mapping object returned by nexus_channel_map_thread' },
                    artifactType: { type: 'string', description: 'Artifact category such as session-summary or mission-status' },
                    artifactId: { type: 'string', description: 'Optional artifact identifier' },
                    title: { type: 'string', description: 'Artifact title' },
                    summary: { type: 'string', description: 'Artifact summary' },
                    body: { type: 'string', description: 'Optional artifact body' },
                    attachments: { type: 'array', items: { type: 'object' }, description: 'Optional attachment descriptors' },
                    metadata: { type: 'object', description: 'Optional metadata payload' },
                },
                required: ['provider', 'thread', 'artifactType', 'title', 'summary'],
            },
        },
        // ── HyperTune Max ─────────────────────────────────────────────────
        {
            name: 'nexus_hypertune_max',
            description: 'Mathematical context-token optimization. Chunks files at function/class boundaries, scores each chunk by relevance+recency+connectivity+novelty, then selects the optimal combination via greedy knapsack that maximizes quality within the adaptive token budget. Use when you want the most token-efficient reading plan possible.',
            inputSchema: {
                type: 'object',
                properties: {
                    task: { type: 'string', description: 'Task description for context scoring' },
                    files: { type: 'array', items: { type: 'string' }, description: 'File paths to optimize. If omitted, auto-scans src/' },
                },
                required: ['task'],
            },
        },
        // ── Graph Query ──────────────────────────────────────────────────
        {
            name: 'nexus_graph_query',
            description: 'Query the knowledge graph. Actions: "query" (hybrid keyword+graph search), "traverse" (N-hop BFS from entity), "centrality" (find most connected entities), "ingest" (extract and store entities from text). Returns entities, relations, and facts.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: { type: 'string', enum: ['query', 'traverse', 'centrality', 'ingest'], description: 'Graph operation to perform' },
                    query: { type: 'string', description: 'Search query or entity name' },
                    depth: { type: 'number', description: 'Traversal depth (default: 2)' },
                    text: { type: 'string', description: 'Text to ingest (for action=ingest)' },
                    tags: { type: 'array', items: { type: 'string' }, description: 'Tags to associate (for action=ingest)' },
                },
                required: ['action'],
            },
        },
        // ── Skill Cards ──────────────────────────────────────────────────
        {
            name: 'nexus_list_skills',
            description: 'List runtime skills available to the orchestrator and planner, including scope, status, and concise instructions.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_skill_register',
            description: 'Register a declarative Skill Card into the Graph Knowledge Engine. Skill cards define contextual triggers and reusable tool execution templates without using arbitrary eval().',
            inputSchema: {
                type: 'object',
                properties: {
                    card: {
                        type: 'object',
                        description: 'The SkillCard object containing name, trigger DSL, actions, confidence, origin, and adoptions.',
                    }
                },
                required: ['card'],
            },
        },
        {
            name: 'nexus_skill_generate',
            description: 'Generate a live runtime skill artifact that can be deployed to future runs or promoted after evidence-backed execution.',
            inputSchema: {
                type: 'object',
                properties: {
                    name: { type: 'string', description: 'Skill name' },
                    instructions: { type: 'string', description: 'Instructions for the generated skill' },
                    riskClass: { type: 'string', enum: ['read', 'orchestrate', 'mutate'], description: 'Risk class for the skill' },
                    scope: { type: 'string', enum: ['session', 'worker', 'global'], description: 'Initial scope for the skill' }
                },
                required: ['name', 'instructions'],
            },
        },
        {
            name: 'nexus_skill_deploy',
            description: 'Promote or deploy a live runtime skill artifact so future runs can activate it.',
            inputSchema: {
                type: 'object',
                properties: {
                    skillId: { type: 'string', description: 'Skill artifact ID or exact name' },
                    scope: { type: 'string', enum: ['session', 'worker', 'global'], description: 'Deployment scope' }
                },
                required: ['skillId'],
            },
        },
        {
            name: 'nexus_skill_revoke',
            description: 'Revoke a live runtime skill artifact.',
            inputSchema: {
                type: 'object',
                properties: {
                    skillId: { type: 'string', description: 'Skill artifact ID or exact name' }
                },
                required: ['skillId'],
            },
        },
        {
            name: 'nexus_list_workflows',
            description: 'List runtime workflows available to the orchestrator and planner, including scope, status, and intended domain.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_workflow_generate',
            description: 'Generate a workflow artifact that can be deployed to runs or promoted through runtime evidence.',
            inputSchema: {
                type: 'object',
                properties: {
                    name: { type: 'string', description: 'Workflow name' },
                    description: { type: 'string', description: 'Workflow description' },
                    domain: { type: 'string', description: 'Optional workflow domain' },
                    scope: { type: 'string', enum: ['session', 'worker', 'global'], description: 'Initial workflow scope' }
                },
                required: ['name', 'description'],
            },
        },
        {
            name: 'nexus_workflow_deploy',
            description: 'Deploy or promote a workflow artifact for future runs.',
            inputSchema: {
                type: 'object',
                properties: {
                    workflowId: { type: 'string', description: 'Workflow artifact ID or exact name' },
                    scope: { type: 'string', enum: ['session', 'worker', 'global'], description: 'Deployment scope' }
                },
                required: ['workflowId'],
            },
        },
        {
            name: 'nexus_workflow_run',
            description: 'Run a workflow artifact through the real execution runtime.',
            inputSchema: {
                type: 'object',
                properties: {
                    workflowId: { type: 'string', description: 'Workflow artifact ID or exact name' },
                    goal: { type: 'string', description: 'Optional override goal' }
                },
                required: ['workflowId'],
            },
        },
        {
            name: 'nexus_list_hooks',
            description: 'List runtime hooks available to the orchestrator, including trigger, scope, rollout state, and effect summary.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_hook_generate',
            description: 'Generate a runtime hook artifact for checkpoint and system-event execution.',
            inputSchema: {
                type: 'object',
                properties: {
                    name: { type: 'string', description: 'Hook name' },
                    description: { type: 'string', description: 'Hook description' },
                    trigger: { type: 'string', enum: ['run.created', 'before-read', 'before-mutate', 'before-verify', 'retry', 'run.failed', 'run.verified', 'promotion.approved', 'memory.stored', 'shield.blocked'], description: 'Hook trigger' },
                    riskClass: { type: 'string', enum: ['read', 'orchestrate', 'mutate'], description: 'Risk class for the hook' },
                    scope: { type: 'string', enum: ['session', 'worker', 'global'], description: 'Initial hook scope' }
                },
                required: ['name', 'description', 'trigger'],
            },
        },
        {
            name: 'nexus_hook_deploy',
            description: 'Deploy or promote a hook artifact for future runs.',
            inputSchema: {
                type: 'object',
                properties: {
                    hookId: { type: 'string', description: 'Hook artifact ID or exact name' },
                    scope: { type: 'string', enum: ['session', 'worker', 'global'], description: 'Deployment scope' }
                },
                required: ['hookId'],
            },
        },
        {
            name: 'nexus_hook_revoke',
            description: 'Revoke a runtime hook artifact.',
            inputSchema: {
                type: 'object',
                properties: {
                    hookId: { type: 'string', description: 'Hook artifact ID or exact name' }
                },
                required: ['hookId'],
            },
        },
        {
            name: 'nexus_list_automations',
            description: 'List runtime automations available to the orchestrator, including trigger mode, scope, rollout state, and queued-run behavior.',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        {
            name: 'nexus_automation_generate',
            description: 'Generate a runtime automation artifact for event, schedule, or connector triggers.',
            inputSchema: {
                type: 'object',
                properties: {
                    name: { type: 'string', description: 'Automation name' },
                    description: { type: 'string', description: 'Automation description' },
                    triggerMode: { type: 'string', enum: ['event', 'schedule', 'connector'], description: 'Trigger mode' },
                    eventTrigger: { type: 'string', enum: ['run.created', 'before-read', 'before-mutate', 'before-verify', 'retry', 'run.failed', 'run.verified', 'promotion.approved', 'memory.stored', 'shield.blocked'], description: 'Event trigger when triggerMode=event' },
                    scope: { type: 'string', enum: ['session', 'worker', 'global'], description: 'Initial automation scope' }
                },
                required: ['name', 'description'],
            },
        },
        {
            name: 'nexus_automation_deploy',
            description: 'Deploy or promote an automation artifact.',
            inputSchema: {
                type: 'object',
                properties: {
                    automationId: { type: 'string', description: 'Automation artifact ID or exact name' },
                    scope: { type: 'string', enum: ['session', 'worker', 'global'], description: 'Deployment scope' }
                },
                required: ['automationId'],
            },
        },
        {
            name: 'nexus_automation_run',
            description: 'Run an automation artifact through the real execution runtime.',
            inputSchema: {
                type: 'object',
                properties: {
                    automationId: { type: 'string', description: 'Automation artifact ID or exact name' },
                    goal: { type: 'string', description: 'Optional override goal' }
                },
                required: ['automationId'],
            },
        },
        {
            name: 'nexus_automation_revoke',
            description: 'Revoke a runtime automation artifact.',
            inputSchema: {
                type: 'object',
                properties: {
                    automationId: { type: 'string', description: 'Automation artifact ID or exact name' }
                },
                required: ['automationId'],
            },
        },
        {
            name: 'nexus_memory_audit',
            description: 'Audit stored memories for duplicates, contradictions, quarantine candidates, and promotion safety.',
            inputSchema: {
                type: 'object',
                properties: {
                    limit: { type: 'number', description: 'Maximum memories to scan' }
                },
            },
        },
        {
            name: 'nexus_federation_status',
            description: 'Return local federation status, peer inventory, relay learnings, and active peer links.',
            inputSchema: {
                type: 'object',
                properties: {},
            },
        },
        {
            name: 'nexus_list_specialists',
            description: 'List the built-in imported specialist roster available to the planner and runtime.',
            inputSchema: {
                type: 'object',
                properties: {},
            },
        },
        {
            name: 'nexus_list_crews',
            description: 'List the preset crews available to the planner and runtime.',
            inputSchema: {
                type: 'object',
                properties: {},
            },
        },
        {
            name: 'nexus_rag_list_collections',
            description: 'Expert surface: list session-first RAG collections managed by Nexus Prime.',
            inputSchema: {
                type: 'object',
                properties: {},
            },
        },
        {
            name: 'nexus_rag_create_collection',
            description: 'Expert surface: create a session-first RAG collection outside the git repo.',
            inputSchema: {
                type: 'object',
                properties: {
                    name: { type: 'string', description: 'Collection name' },
                    description: { type: 'string', description: 'Optional collection description' },
                    tags: { type: 'array', items: { type: 'string' }, description: 'Collection tags' },
                    scope: { type: 'string', enum: ['session', 'project'], description: 'Collection scope' },
                },
                required: ['name'],
            },
        },
        {
            name: 'nexus_rag_ingest_collection',
            description: 'Expert surface: ingest local files, folders, URLs, or raw text into a RAG collection. Use folderPath to ingest an entire directory recursively.',
            inputSchema: {
                type: 'object',
                properties: {
                    collectionId: { type: 'string', description: 'Collection id' },
                    inputs: {
                        type: 'array',
                        items: {
                            type: 'object',
                            properties: {
                                filePath: { type: 'string', description: 'Single file path' },
                                folderPath: { type: 'string', description: 'Directory path to recursively ingest all supported files' },
                                folderGlob: { type: 'string', description: 'Optional extension filter for folder ingestion (e.g. "*.ts")' },
                                url: { type: 'string' },
                                text: { type: 'string' },
                                label: { type: 'string' },
                                tags: { type: 'array', items: { type: 'string' } },
                            },
                        },
                        description: 'Collection sources (supports file, folder, url, or text)',
                    },
                },
                required: ['collectionId', 'inputs'],
            },
        },
        {
            name: 'nexus_rag_attach_collection',
            description: 'Expert surface: attach an existing RAG collection to the active runtime/session.',
            inputSchema: {
                type: 'object',
                properties: {
                    collectionId: { type: 'string', description: 'Collection id' },
                },
                required: ['collectionId'],
            },
        },
        {
            name: 'nexus_rag_detach_collection',
            description: 'Expert surface: detach a RAG collection from the active runtime/session.',
            inputSchema: {
                type: 'object',
                properties: {
                    collectionId: { type: 'string', description: 'Collection id' },
                },
                required: ['collectionId'],
            },
        },
        {
            name: 'nexus_rag_delete_collection',
            description: 'Expert surface: delete a RAG collection from Nexus state.',
            inputSchema: {
                type: 'object',
                properties: {
                    collectionId: { type: 'string', description: 'Collection id' },
                },
                required: ['collectionId'],
            },
        },
        {
            name: 'nexus_pattern_search',
            description: 'Expert surface: search bounded orchestration pattern cards that can shape a run.',
            inputSchema: {
                type: 'object',
                properties: {
                    query: { type: 'string', description: 'Pattern search query' },
                    limit: { type: 'number', description: 'Optional result limit' },
                },
                required: ['query'],
            },
        },
        {
            name: 'nexus_pattern_list',
            description: 'Expert surface: list the top bounded orchestration pattern cards available to Nexus Prime.',
            inputSchema: {
                type: 'object',
                properties: {
                    limit: { type: 'number', description: 'Optional result limit' },
                },
            },
        },
        {
            name: 'nexus_knowledge_provenance',
            description: 'Expert surface: inspect the latest knowledge-fabric provenance trace for the active runtime.',
            inputSchema: {
                type: 'object',
                properties: {},
            },
        },
        {
            name: 'nexus_run_status',
            description: 'Return the current recorded state of a runtime execution run.',
            inputSchema: {
                type: 'object',
                properties: {
                    runId: { type: 'string', description: 'Execution run ID' }
                },
                required: ['runId'],
            },
        },
        {
            name: 'nexus_user_workflow_trace',
            description: 'Return the local user-agent workflow trace for a run: user goal, agent actions, context, verification, failure signals, and next actions.',
            inputSchema: {
                type: 'object',
                properties: {
                    runId: { type: 'string', description: 'Execution run ID' },
                    format: { type: 'string', enum: ['text', 'json'], description: 'Response format' },
                },
                required: ['runId'],
            },
        },
        // ── Darwin Loop ──────────────────────────────────────────────────
        {
            name: 'nexus_darwin_propose',
            description: 'Propose a self-improvement cycle for Nexus Prime. Forces validation against the Bounded Improvement Space (forbidding core changes). Use when you have a specific hypothesis to improve an engine or phantom worker.',
            inputSchema: {
                type: 'object',
                properties: {
                    hypothesis: { type: 'string', description: 'What you are trying to improve and why' },
                    targetFile: { type: 'string', description: 'The specific file you want to change (must be in src/engines/ or src/phantom/)' },
                    approach: { type: 'string', description: 'How you plan to implement it' }
                },
                required: ['hypothesis', 'targetFile', 'approach'],
            },
        },
        {
            name: 'nexus_darwin_review',
            description: 'Review and finalize a pending Darwin Cycle after validation.',
            inputSchema: {
                type: 'object',
                properties: {
                    cycleId: { type: 'string', description: 'ID of the pending Darwin Cycle' },
                    action: { type: 'string', enum: ['apply', 'reject', 'defer'], description: 'Outcome of the review' },
                    learnings: { type: 'array', items: { type: 'string' }, description: 'Lessons learned from attempting this cycle' }
                },
                required: ['cycleId', 'action'],
            },
        },
        {
            name: 'nexus_darwin_status',
            description: 'Show pending Darwin self-improvement proposals and their status. Useful after orchestration runs when NEXUS_SELF_IMPROVE=1 (default).',
            inputSchema: { type: 'object', properties: {}, required: [] },
        },
        // ── NexusNet Relay ───────────────────────────────────────────────
        {
            name: 'nexus_net_publish',
            description: 'Publish an anonymized knowledge snippet or SkillCard to the shared NexusNet relay (MVP via GitHub Gists). Use this to share valuable insights or templates with other agents across machines.',
            inputSchema: {
                type: 'object',
                properties: {
                    type: { type: 'string', enum: ['knowledge', 'skill'], description: 'Type of content' },
                    content: { type: 'string', description: 'The knowledge string or SkillCard YAML to share' },
                    tags: { type: 'array', items: { type: 'string' }, description: 'Tags to associate with this message' }
                },
                required: ['type', 'content', 'tags'],
            },
        },
        {
            name: 'nexus_net_sync',
            description: 'Sync and retrieve new messages (insights and skills) published by other Nexus agents on the NexusNet Relay.',
            inputSchema: {
                type: 'object',
                properties: {}
            },
        },
        {
            name: 'nexus_assemble_context',
            description: 'Declare the active working set of files explicitly to the user. Outputs a visual map of the loaded context dependencies.',
            inputSchema: {
                type: 'object',
                properties: {
                    files: { type: 'array', items: { type: 'string' }, description: 'List of files currently focused on' },
                    reason: { type: 'string', description: 'Why this context was assembled' }
                },
                required: ['files', 'reason'],
            },
        },
        // ── Nexus Layer (v1.5) ──────────────────────────────────────────
        {
            name: 'nexus_publish_trace',
            description: 'Publish a successful execution trace or research chain to the Federated Knowledge Relay (Gists).',
            inputSchema: {
                type: 'object',
                properties: {
                    taskId: { type: 'string', description: 'ID of the task being summarized' },
                    goal: { type: 'string', description: 'The original goal' },
                    findings: { type: 'array', items: { type: 'string' }, description: 'Key findings or steps' },
                    confidence: { type: 'number', description: 'Confidence score 0-1' }
                },
                required: ['taskId', 'goal', 'findings'],
            },
        },
        // When NEXUS_DISABLE_WORKFORCE=1 (explicit break-glass mode),
        // strip the 24 nexus_synapse_* / nexus_architects_* tools from the
        // catalog so the model doesn't see surface area for engines that
        // aren't initialized at runtime.
        ...(process.env.NEXUS_DISABLE_WORKFORCE === '1' ? [] : synapseToolDefinitions),
        ...(process.env.NEXUS_DISABLE_WORKFORCE === '1' ? [] : architectsToolDefinitions),
        // ── Workforce (unified worker+job layer) ──────────────────────────
        {
            name: 'nexus_work_enqueue',
            description: 'Enqueue a new job into the workforce queue. Jobs with dependsOn start in backlog; others start ready.',
            inputSchema: {
                type: 'object',
                properties: {
                    title: { type: 'string' },
                    tier: { type: 'string', enum: ['strategy', 'tactical'] },
                    priority: { type: 'number' },
                    parentId: { type: 'string' },
                    dependsOn: { type: 'array', items: { type: 'string' } },
                    budgetCapUsd: { type: 'number' },
                    payload: { type: 'object' },
                    client: { type: 'string' },
                },
                required: ['title'],
            },
        },
        {
            name: 'nexus_work_claim',
            description: 'Atomically claim a specific job (by jobId) or the next highest-priority ready job.',
            inputSchema: {
                type: 'object',
                properties: {
                    workerId: { type: 'string' },
                    jobId: { type: 'string' },
                    leaseMs: { type: 'number' },
                },
                required: ['workerId'],
            },
        },
        {
            name: 'nexus_work_progress',
            description: 'Advance a claimed job (claimed→wip or wip→review) and record token usage.',
            inputSchema: {
                type: 'object',
                properties: {
                    jobId: { type: 'string' },
                    workerId: { type: 'string' },
                    stage: { type: 'string', enum: ['wip', 'review'] },
                    tokens: { type: 'number' },
                },
                required: ['jobId', 'workerId'],
            },
        },
        {
            name: 'nexus_work_complete',
            description: 'Mark a job as done, failed, or blocked. Triggers DAG promotion.',
            inputSchema: {
                type: 'object',
                properties: {
                    jobId: { type: 'string' },
                    workerId: { type: 'string' },
                    outcome: { type: 'string', enum: ['done', 'failed', 'blocked'] },
                },
                required: ['jobId', 'workerId', 'outcome'],
            },
        },
        {
            name: 'nexus_work_block',
            description: 'Mark a job as blocked.',
            inputSchema: {
                type: 'object',
                properties: {
                    jobId: { type: 'string' },
                    workerId: { type: 'string' },
                },
                required: ['jobId', 'workerId'],
            },
        },
        {
            name: 'nexus_work_kanban',
            description: 'Kanban board showing jobs grouped by status lane.',
            inputSchema: {
                type: 'object',
                properties: { client: { type: 'string' } },
            },
        },
        {
            name: 'nexus_work_workers',
            description: 'List registered workers with status, load, and budget.',
            inputSchema: {
                type: 'object',
                properties: {
                    status: { type: 'string', enum: ['idle', 'active', 'stale', 'retired'] },
                },
            },
        },
        {
            name: 'nexus_work_hire',
            description: 'Register a new worker (agent) into the workforce pool.',
            inputSchema: {
                type: 'object',
                properties: {
                    name: { type: 'string' },
                    role: { type: 'string' },
                    client: { type: 'string' },
                    budgetCapUsd: { type: 'number' },
                },
            },
        },
        {
            name: 'kernel_run_step',
            description: 'Run a mutation step inside an isolated git worktree and record it in the kernel ledger. Returns worktreeRef, commitSha, changedFiles. Merge requires a subsequent kernel_run_verify.',
            inputSchema: {
                type: 'object',
                properties: {
                    runId: { type: 'string' },
                    stepId: { type: 'string' },
                    task: { type: 'string' },
                    intent: { type: 'string' },
                    baseRef: { type: 'string', description: 'Ref/branch/sha to branch off. Defaults to HEAD.' },
                    worktreeHintRef: { type: 'string', description: 'Optional branch label override.' },
                    mutations: {
                        type: 'array',
                        items: {
                            type: 'object',
                            properties: {
                                kind: { type: 'string', enum: ['write_file', 'append_file', 'delete_file', 'run_command'] },
                                path: { type: 'string' },
                                content: { type: 'string' },
                                command: { type: 'string' },
                                cwd: { type: 'string' },
                            },
                            required: ['kind'],
                        },
                    },
                    metadata: { type: 'object' },
                },
                required: ['runId', 'stepId', 'task'],
            },
        },
        {
            name: 'kernel_run_verify',
            description: 'Hash the files changed by a kernel step and optionally run registered verifiers. Records the snapshot used to detect stale-verify at merge time.',
            inputSchema: {
                type: 'object',
                properties: {
                    runId: { type: 'string' },
                    stepId: { type: 'string' },
                    verifierIds: { type: 'array', items: { type: 'string' } },
                    metadata: { type: 'object' },
                },
                required: ['runId', 'stepId'],
            },
        },
        {
            name: 'kernel_run_merge',
            description: 'Fast-forward targetRef to a verified kernel step. Rejects when verify is missing, failed, or stale.',
            inputSchema: {
                type: 'object',
                properties: {
                    runId: { type: 'string' },
                    stepId: { type: 'string' },
                    verifyId: { type: 'string', description: 'Explicit verify pin. If omitted, latest passed verify is used.' },
                    targetRef: { type: 'string' },
                    reason: { type: 'string' },
                    metadata: { type: 'object' },
                },
                required: ['runId', 'stepId', 'targetRef'],
            },
        },
        // ── Embedded capabilities (auto-detected from installed skills) ──
        ...getGstackBridge().getToolDefinitions(),
    ];
    return tools.map((tool) => FIRST_CLASS_TOOLS.has(tool.name)
        ? tool
        : { ...tool, deprecated: true, deprecatedReplacement: tool.deprecatedReplacement ?? 'nexus_orchestrate' });
}
