@cleocode/runtime 2026.10.4 → 2026.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/{chunk-L5BLVQDA.js → chunk-4PUSKGDO.js} +2 -2
  2. package/dist/chunk-4PUSKGDO.js.map +1 -0
  3. package/dist/{chunk-KQBVXGOL.js → chunk-GULKX44R.js} +5 -3
  4. package/dist/chunk-GULKX44R.js.map +1 -0
  5. package/dist/{chunk-7Q7BEWM7.js → chunk-HXTRXEFI.js} +7 -9
  6. package/dist/chunk-HXTRXEFI.js.map +1 -0
  7. package/dist/{chunk-U2ESNIJ5.js → chunk-NOPLC5WS.js} +4 -2
  8. package/dist/chunk-NOPLC5WS.js.map +1 -0
  9. package/dist/chunk-PDZ5T4LO.js +597 -0
  10. package/dist/chunk-PDZ5T4LO.js.map +1 -0
  11. package/dist/{chunk-XJOMQIXL.js → chunk-WO6LJMDC.js} +4 -2
  12. package/dist/chunk-WO6LJMDC.js.map +1 -0
  13. package/dist/daemon/index.js +1 -1
  14. package/dist/dispatch-BWjVeeMg.d.ts +290 -0
  15. package/dist/gateway/dispatch.d.ts +5 -0
  16. package/dist/gateway/dispatch.js +53 -0
  17. package/dist/gateway/dispatch.js.map +1 -0
  18. package/dist/gateway/http/index.d.ts +897 -11
  19. package/dist/gateway/http/index.js +2 -2
  20. package/dist/gateway/index.d.ts +549 -4
  21. package/dist/gateway/index.js +26 -581
  22. package/dist/gateway/index.js.map +1 -1
  23. package/dist/gateway/mcp/index.d.ts +232 -10
  24. package/dist/gateway/mcp/index.js +2 -2
  25. package/dist/gateway/rpc/index.d.ts +5 -2036
  26. package/dist/gateway/rpc/index.js +1 -1
  27. package/dist/gateway-handler-DCU6E0a2.d.ts +80 -0
  28. package/dist/index.d.ts +4 -3
  29. package/dist/index.js +9 -6
  30. package/dist/index.js.map +1 -1
  31. package/package.json +7 -3
  32. package/dist/chunk-7Q7BEWM7.js.map +0 -1
  33. package/dist/chunk-KQBVXGOL.js.map +0 -1
  34. package/dist/chunk-L5BLVQDA.js.map +0 -1
  35. package/dist/chunk-U2ESNIJ5.js.map +0 -1
  36. package/dist/chunk-XJOMQIXL.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gateway/meta.ts","../src/gateway/pipeline.ts","../src/gateway/dispatcher.ts","../src/gateway/engine-error.ts","../src/gateway/exit-codes.ts","../src/gateway/gateway-handler.ts","../src/gateway/nexus-decorator.ts","../src/gateway/paths.ts"],"sourcesContent":["/**\n * Dispatch-local metadata factory.\n *\n * Generates LAFS-conformant metadata for dispatch layer responses.\n * Generates LAFS-conformant metadata for dispatch responses.\n *\n * @task T4772\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { DispatchResponse, Source } from '@cleocode/contracts/gateway';\n\n/**\n * Create metadata for a dispatch response.\n *\n * @param gateway - Gateway name (e.g., 'query', 'mutate')\n * @param domain - Domain name (e.g., 'tasks', 'session')\n * @param operation - Operation name (e.g., 'show', 'list')\n * @param startTime - Timestamp from Date.now() at start of request\n * @param source - Where the request originated\n * @param requestId - Optional pre-generated request ID\n * @param sessionId - Optional session ID to include in metadata\n * @param originSessionId - Optional root workflow/saga session ID\n * @param executionSessionId - Optional execution-attempt session ID\n * @returns Metadata conforming to DispatchResponse['meta']\n *\n * @task T4772\n * @task T4959\n */\nexport function createDispatchMeta(\n gateway: string,\n domain: string,\n operation: string,\n startTime: number,\n source: Source = 'cli',\n requestId?: string,\n sessionId?: string | null,\n originSessionId?: string | null,\n executionSessionId?: string | null,\n): DispatchResponse['meta'] {\n return {\n gateway: gateway as DispatchResponse['meta']['gateway'],\n domain,\n operation,\n timestamp: new Date().toISOString(),\n duration_ms: Date.now() - startTime,\n source,\n requestId: requestId ?? randomUUID(),\n ...(sessionId != null && { sessionId }),\n ...(originSessionId != null && { originSessionId }),\n ...(executionSessionId != null && { executionSessionId }),\n };\n}\n","/**\n * Unified CQRS Dispatch Layer -- Middleware Pipeline\n *\n * Provides compose() to chain multiple Middleware functions together\n * into a single executable pipeline.\n *\n * @epic T4820\n * @task T4815\n */\n\nimport type {\n DispatchNext,\n DispatchRequest,\n DispatchResponse,\n Middleware,\n} from '@cleocode/contracts/gateway';\n\n/**\n * Composes an array of Middleware functions into a single Middleware function.\n * Execution flows through the array from first to last, and returns bubble\n * back up from last to first.\n *\n * @remarks\n * Uses an index-tracked dispatch function to prevent `next()` from being\n * called multiple times within a single middleware. If the array is empty,\n * a passthrough middleware that immediately calls `next()` is returned.\n *\n * @param middlewares - Array of middleware functions to chain\n * @returns A single composed Middleware function\n *\n * @example\n * ```typescript\n * import { compose } from './pipeline.js';\n *\n * const pipeline = compose([sanitizer, rateLimiter, protocolEnforcement]);\n * const response = await pipeline(request, handler);\n * ```\n */\nexport function compose(middlewares: Middleware[]): Middleware {\n if (middlewares.length === 0) {\n return async (_req: DispatchRequest, next: DispatchNext) => next();\n }\n\n return async (request: DispatchRequest, next: DispatchNext): Promise<DispatchResponse> => {\n let index = -1;\n\n async function dispatch(i: number): Promise<DispatchResponse> {\n if (i <= index) {\n throw new Error('next() called multiple times in middleware');\n }\n index = i;\n\n let fn: Middleware | undefined = middlewares[i];\n if (i === middlewares.length) {\n // We've reached the end of the middleware chain; call the final handler\n fn = async (_req, nxt) => nxt();\n }\n\n if (!fn) {\n return next();\n }\n\n return fn(request, async () => {\n if (i === middlewares.length) {\n return next();\n }\n return dispatch(i + 1);\n });\n }\n\n return dispatch(0);\n };\n}\n","/**\n * Central Dispatcher -- Routes requests through middleware to domain handlers.\n *\n * The dispatcher is the single entry point for the CLI adapter.\n * It resolves operations, validates parameters, runs the middleware pipeline,\n * and delegates to the appropriate domain handler.\n *\n * Flow: DispatchRequest → resolve → param validation → middleware → handler\n *\n * ## T1088 — Dialectic Evaluator Hook (PSYCHE Wave 3)\n *\n * After each successful mutate operation, the dispatcher fires a background\n * `evaluateDialectic` call via `setImmediate` if all of the following apply:\n *\n * 1. The response indicates `success: true`.\n * 2. The request gateway is `\"mutate\"` (state-modifying user-facing commands).\n * 3. A `sessionId` is present on the request (identifies conversation context).\n * 4. The in-memory rate limiter allows the evaluation (1 per 10s per session).\n *\n * Errors from the background evaluation are caught and logged at `warn` level\n * so they never affect the caller.\n *\n * ## T12024 — Bounded deadline for background LLM calls\n *\n * The dialectic evaluation makes an HTTP call to an LLM backend (Ollama,\n * Anthropic, etc.) which keeps the Node.js event loop alive. After the CLI\n * success-path `finally` tears down workers and databases via\n * `shutdownCliRuntime`, the pending HTTP connection is the sole remaining\n * reference — preventing the process from draining the loop and exiting rc:0.\n *\n * Each evaluation now runs against an unrefed deadline so the deadline\n * timer itself never holds the loop open, while the abort signal cancels the\n * underlying HTTP request when the deadline fires, releasing the connection\n * and allowing natural exit. The timeout is generous enough for normal\n * responses but prevents hung connections from blocking shutdown.\n *\n * @epic T4820\n * @task T1088\n * @task T12024\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type {\n DispatchRequest,\n DispatchResponse,\n DomainHandler,\n Middleware,\n} from '@cleocode/contracts/gateway';\nimport { getLogger } from '@cleocode/core/logger';\nimport { getProjectRoot } from '@cleocode/core/project-scope';\n// Deep import, not the barrel: this is a small dependency-free module, and\n// pulling it through the core barrel would load the full core module graph for\n// one function. Spelled WITHOUT `.js` because core's `./*` export maps to\n// `./dist/*.js`, so the extension is supplied by the pattern — adding it here\n// resolves to `dist/teardown-signal.js.js` and fails.\nimport { registerTeardownAbort } from '@cleocode/core/teardown-signal';\nimport { createDispatchMeta } from './meta.js';\nimport { compose } from './pipeline.js';\nimport { resolve, validateRequiredParams } from './registry.js';\n\n// ============================================================================\n// T1088: In-memory rate limiter for dialectic evaluation\n// ============================================================================\n\n/** Rate limit window in milliseconds (1 evaluation per 10 seconds per session). */\nconst DIALECTIC_RATE_LIMIT_MS = 10_000;\n\n/**\n * Maximum time the dialectic LLM call is allowed to run before aborting.\n *\n * The deadline uses an unrefed timer so it never blocks process exit by\n * itself. When triggered, the abort signal cancels the underlying HTTP\n * request, allowing the event loop to drain and the CLI process to exit.\n *\n * @task T12024\n */\nconst DIALECTIC_DEADLINE_MS = 10_000;\n\n/** In-memory last-evaluation timestamp per session ID. */\nconst _dialecticLastEvalMs = new Map<string, number>();\n\nfunction ensureRequestSessionLineage(request: DispatchRequest): void {\n request.executionSessionId ??=\n process.env.CLEO_EXECUTION_SESSION_ID ?? process.env.CLEO_SESSION_EXECUTION_ID ?? randomUUID();\n request.originSessionId ??=\n process.env.CLEO_ORIGIN_SESSION_ID ??\n process.env.CLEO_SESSION_ORIGIN_ID ??\n request.sessionId ??\n request.executionSessionId;\n}\n\n/**\n * Check whether a new dialectic evaluation is allowed for a session.\n *\n * Rate limit: 1 evaluation per `DIALECTIC_RATE_LIMIT_MS` per session.\n * Records the timestamp when allowed.\n *\n * @param sessionId - The session to check.\n * @returns `true` when the evaluation is allowed.\n */\nfunction isDialecticEvalAllowed(sessionId: string): boolean {\n const last = _dialecticLastEvalMs.get(sessionId) ?? 0;\n const now = Date.now();\n if (now - last < DIALECTIC_RATE_LIMIT_MS) {\n return false;\n }\n _dialecticLastEvalMs.set(sessionId, now);\n return true;\n}\n\n// ============================================================================\n// Dispatcher\n// ============================================================================\n\nexport interface DispatcherConfig {\n handlers: Map<string, DomainHandler>;\n middlewares?: Middleware[];\n}\n\nexport class Dispatcher {\n private handlers: Map<string, DomainHandler>;\n private pipeline: Middleware;\n\n constructor(config: DispatcherConfig) {\n this.handlers = config.handlers;\n this.pipeline = config.middlewares?.length\n ? compose(config.middlewares)\n : (_req, next) => next();\n }\n\n async dispatch(request: DispatchRequest): Promise<DispatchResponse> {\n const startTime = Date.now();\n ensureRequestSessionLineage(request);\n\n // 1. Resolve operation from registry\n const resolved = resolve(request.gateway, request.domain, request.operation);\n if (!resolved) {\n return {\n meta: createDispatchMeta(\n request.gateway,\n request.domain,\n request.operation,\n startTime,\n request.source,\n request.requestId,\n request.sessionId,\n request.originSessionId,\n request.executionSessionId,\n ),\n success: false,\n error: {\n code: 'E_INVALID_OPERATION',\n message: `Unknown operation: ${request.gateway}:${request.domain}.${request.operation}`,\n },\n };\n }\n\n // 2. Validate required params\n const missing = validateRequiredParams(resolved.def, request.params);\n if (missing.length > 0) {\n return {\n meta: createDispatchMeta(\n request.gateway,\n resolved.domain,\n resolved.operation,\n startTime,\n request.source,\n request.requestId,\n request.sessionId,\n request.originSessionId,\n request.executionSessionId,\n ),\n success: false,\n error: {\n code: 'E_MISSING_PARAMS',\n message: `Missing required parameters: ${missing.join(', ')}`,\n details: { missing },\n },\n };\n }\n\n // 3. Look up domain handler\n const handler = this.handlers.get(resolved.domain);\n if (!handler) {\n return {\n meta: createDispatchMeta(\n request.gateway,\n resolved.domain,\n resolved.operation,\n startTime,\n request.source,\n request.requestId,\n request.sessionId,\n request.originSessionId,\n request.executionSessionId,\n ),\n success: false,\n error: {\n code: 'E_NO_HANDLER',\n message: `No handler for domain: ${resolved.domain}`,\n },\n };\n }\n\n // 4. Run middleware pipeline with terminal handler\n const terminal = async (): Promise<DispatchResponse> => {\n if (request.gateway === 'query') {\n return handler.query(resolved.operation, request.params);\n } else {\n return handler.mutate(resolved.operation, request.params);\n }\n };\n\n const response = await this.pipeline(request, terminal);\n\n // 5. Stamp timing and tracing metadata\n response.meta.duration_ms = Date.now() - startTime;\n response.meta.requestId = request.requestId;\n response.meta.source = request.source;\n\n // 6. Stamp session identity and lineage (T4959/T10620)\n if (request.sessionId) {\n response.meta.sessionId = request.sessionId;\n }\n if (request.originSessionId) {\n response.meta.originSessionId = request.originSessionId;\n }\n if (request.executionSessionId) {\n response.meta.executionSessionId = request.executionSessionId;\n }\n\n // 7. T1088: Background dialectic evaluation hook\n //\n // Fires asynchronously via setImmediate so the response is returned to the\n // caller immediately. Conditions:\n // a) Response was successful\n // b) This was a mutate (state-modifying, user-facing) operation\n // c) A session ID is present (needed for narrative + source tagging)\n // d) Rate limiter allows this session to be evaluated right now\n //\n // The userMessage is synthesised from the operation + params since the\n // raw CLI string is not available at this layer. Future Wave 4 work can\n // thread the original raw command string through DispatchRequest.\n if (\n response.success &&\n request.gateway === 'mutate' &&\n request.sessionId &&\n isDialecticEvalAllowed(request.sessionId)\n ) {\n const capturedRequest = request;\n const capturedSessionId = request.sessionId;\n\n setImmediate(() => {\n // Lazy import to avoid loading the evaluator at startup (it pulls in\n // the Vercel AI SDK and zod which add ~50ms to cold start).\n //\n // T10351: ALL brain.db row inserts from this hook now flow through\n // the single-writer chokepoint (`enqueueBrainWrite`). The hook still\n // opens a brain handle for the evaluator's reads (RCA confirms WAL\n // reads are not the race vector), and `applyInsights` internally\n // calls `observeBrain` — which now auto-routes every write through\n // the writer queue. Global traits go to nexus.db which is out of\n // scope for the brain chokepoint.\n //\n // T12024: bound the LLM call with an AbortController whose timer is\n // unrefed so the deadline never extends CLI lifetime. The signal\n // cascades through evaluateDialectic → generateObject → the AI-SDK\n // HTTP request; when the signal fires, the fetch is cancelled and\n // the event loop can drain after shutdownCliRuntime.\n const controller = new AbortController();\n const deadline = setTimeout(\n () => controller.abort(new DOMException('DIALECTIC_DEADLINE', 'AbortError')),\n DIALECTIC_DEADLINE_MS,\n );\n deadline.unref();\n\n // T12239: the deadline above is 10s and the exit backstop is 3s, so a\n // dialectic in flight at teardown holds its TCPSocketWrap for up to\n // seven seconds PAST the \"event loop still alive\" warning. Unrefing the\n // TIMER does not unref the SOCKET. Register the controller so\n // shutdownCliRuntime can cancel the fetch itself; if teardown has\n // already begun this aborts immediately.\n const unregisterAbort = registerTeardownAbort(controller);\n\n Promise.all([\n import('@cleocode/core/memory/dialectic-evaluator.js'),\n import('@cleocode/core/store/nexus-sqlite.js'),\n import('@cleocode/core/store/memory-sqlite.js'),\n ])\n .then(async ([{ evaluateDialectic, applyInsights }, { getNexusDb }, { getBrainDb }]) => {\n const projectRoot = getProjectRoot();\n const turn = {\n userMessage: `cleo ${capturedRequest.domain} ${capturedRequest.operation} ${JSON.stringify(capturedRequest.params ?? {})}`,\n systemResponse: `Operation succeeded in domain \"${capturedRequest.domain}\".`,\n activePeerId: (capturedRequest.params?.['peerId'] as string | undefined) ?? 'global',\n sessionId: capturedSessionId,\n // T12543: this turn is an operation and its result envelope,\n // not a user utterance — the evaluator must never mint user\n // traits from it.\n origin: 'operation-envelope' as const,\n };\n\n const insights = await evaluateDialectic(turn, {\n abortSignal: controller.signal,\n });\n\n // applyInsights routes peer-insight writes through\n // `observeBrain → enqueueBrainWrite` automatically. Narrative\n // delta still uses the direct INSERT path (not in the high-volume\n // race surface that the T10301 RCA identified — plasticity_events\n // and weight_history dominate by ~94%). Tracked as a follow-up\n // refinement; out of scope for T10351 chokepoint.\n const [nexusDb, brainDb] = await Promise.all([getNexusDb(), getBrainDb()]);\n await applyInsights(insights, nexusDb, brainDb, {\n sessionId: capturedSessionId,\n activePeerId: turn.activePeerId,\n projectRoot,\n });\n })\n .catch((err: unknown) => {\n const log = getLogger('dialectic-hook');\n log.warn({ err }, 'dialectic-evaluator failed');\n })\n .finally(() => {\n clearTimeout(deadline);\n unregisterAbort();\n });\n });\n }\n\n return response;\n }\n}\n","/**\n * Centralized engine error helper for the transport-agnostic gateway.\n *\n * Every domain handler (and the engine barrel) imports `engineError()` /\n * `engineSuccess()` from this module to produce consistently typed error\n * results with correct exit codes and pino logging.\n *\n * The STRING_TO_EXIT map is the canonical mapping from string error codes\n * to numeric exit codes. It mirrors ERROR_CODE_TO_EXIT in cli.ts.\n *\n * @remarks\n * Relocated from `packages/cleo/src/dispatch/engines/_error.ts` into\n * `@cleocode/runtime/gateway` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION) so the\n * runtime owns the shared handler dependencies and can assemble the handler map\n * without importing `@cleocode/cleo`. A thin re-export shim remains at the old\n * `engines/_error.ts` path so in-package import sites compile unchanged.\n *\n * Error codes are organized into numeric ranges:\n * - 1-9: General errors (invalid input, file, dependency, validation)\n * - 10-19: Hierarchy errors (parent, depth, siblings, circular deps)\n * - 20-29: Concurrency errors (checksum, modification, collision)\n * - 30-39: Session errors (scope, claims, active task)\n * - 40-47: Verification errors (gates, agents, rounds)\n * - 50-54: Context safeguard (warning through emergency)\n * - 60-67: Orchestrator / protocol errors\n * - 70-79: Nexus errors\n * - 80-94: Lifecycle, artifact, provenance errors\n * - 95-99: Adapter errors\n * - 100+: Special informational codes (not errors)\n */\n\nimport type { EngineResult, ProblemDetails } from '@cleocode/contracts';\nimport { engineError as coreEngineError } from '@cleocode/contracts/engine-result.js';\nimport { getLogger } from '@cleocode/core/logger';\nimport { mapNumericExitCodeToString } from './exit-codes.js';\n\n// Re-export EngineResult from core (canonical location)\nexport type { EngineResult } from '@cleocode/core';\n\n/**\n * Canonical mapping from string error codes to numeric exit codes.\n *\n * Source of truth: src/types/exit-codes.ts (ExitCode enum).\n * Must stay in sync with ERROR_CODE_TO_EXIT in src/dispatch/adapters/cli.ts.\n */\nexport const STRING_TO_EXIT: Record<string, number> = {\n // General Errors (1-9)\n E_GENERAL: 1,\n E_GENERAL_ERROR: 1,\n E_INVALID_INPUT: 2,\n E_MISSING_PARAMS: 2,\n E_INVALID_OPERATION: 2,\n E_FILE_ERROR: 3,\n E_NOT_FOUND: 4,\n E_DEPENDENCY: 5,\n E_DEPENDENCY_ERROR: 5,\n E_VALIDATION: 6,\n E_VALIDATION_FAILED: 6,\n E_VALIDATION_ERROR: 6,\n E_RETRYABLE: 7,\n E_LOCK_TIMEOUT: 7,\n E_CONFIG_ERROR: 8,\n E_PROJECT_MOVED: 9,\n\n // Hierarchy Errors (10-19)\n E_PARENT_NOT_FOUND: 10,\n E_DEPTH_EXCEEDED: 11,\n E_SIBLING_LIMIT: 12,\n E_INVALID_PARENT_TYPE: 13,\n E_INVALID_PARENT: 13,\n E_CIRCULAR_DEP: 14,\n E_CIRCULAR_REFERENCE: 14,\n E_ORPHAN_DETECTED: 15,\n E_HAS_CHILDREN: 16,\n E_TASK_COMPLETED: 17, // ExitCode.TASK_COMPLETED — canonical value from @cleocode/contracts\n E_CASCADE_FAILED: 18,\n E_HAS_DEPENDENTS: 19,\n\n // Concurrency Errors (20-29)\n E_CHECKSUM_MISMATCH: 20,\n E_CONCURRENT_MODIFICATION: 21,\n E_ID_COLLISION: 22,\n E_CONFLICT: 23,\n E_SESSION_UNBOUND: 24,\n E_WORKTREE_LOCKED: 25,\n E_TASK_RENAMED: 26,\n\n // Session Errors (30-39)\n E_SESSION_EXISTS: 30,\n E_SESSION_CONFLICT: 30,\n E_SESSION_NOT_FOUND: 31,\n E_SCOPE_CONFLICT: 32,\n E_SCOPE_INVALID: 33,\n E_TASK_NOT_IN_SCOPE: 34,\n E_TASK_CLAIMED: 35,\n E_SESSION_REQUIRED: 36,\n E_SESSION_CLOSE_BLOCKED: 37,\n E_ACTIVE_TASK_REQUIRED: 38,\n E_NOTES_REQUIRED: 39,\n\n // Verification Errors (40-47)\n E_VERIFICATION_INIT_FAILED: 40,\n E_GATE_UPDATE_FAILED: 41,\n E_INVALID_GATE: 42,\n E_INVALID_AGENT: 43,\n E_MAX_ROUNDS_EXCEEDED: 44,\n E_GATE_DEPENDENCY: 45,\n E_VERIFICATION_LOCKED: 46,\n E_ROUND_MISMATCH: 47,\n // T1590 — Acceptance-criteria immutability after implementation stage\n E_AC_LOCKED: 48,\n\n // Context Safeguard (50-54)\n E_CONTEXT_WARNING: 50,\n E_CONTEXT_CAUTION: 51,\n E_CONTEXT_CRITICAL: 52,\n E_CONTEXT_EMERGENCY: 53,\n E_CONTEXT_STALE: 54,\n\n // Orchestrator / Protocol Errors (60-67)\n E_PROTOCOL_MISSING: 60,\n E_PROTOCOL_RESEARCH: 60,\n E_INVALID_RETURN_MESSAGE: 61,\n E_PROTOCOL_CONSENSUS: 61,\n E_MANIFEST_ENTRY_MISSING: 62,\n E_PROTOCOL_SPECIFICATION: 62,\n E_SPAWN_VALIDATION_FAILED: 63,\n E_PROTOCOL_DECOMPOSITION: 63,\n E_AUTONOMOUS_BOUNDARY: 64,\n E_PROTOCOL_IMPLEMENTATION: 64,\n E_HANDOFF_REQUIRED: 65,\n E_PROTOCOL_CONTRIBUTION: 65,\n E_RESUME_FAILED: 66,\n E_PROTOCOL_RELEASE: 66,\n E_CONCURRENT_SESSION: 67,\n E_PROTOCOL_GENERIC: 67,\n\n // Nexus Errors (70-79)\n E_NEXUS_NOT_INITIALIZED: 70,\n E_NEXUS_PROJECT_NOT_FOUND: 71,\n E_NEXUS_PERMISSION_DENIED: 72,\n E_NEXUS_INVALID_SYNTAX: 73,\n E_NEXUS_SYNC_FAILED: 74,\n E_NEXUS_REGISTRY_CORRUPT: 75,\n // T12512: the registry could not be read (unreadable, locked, missing table).\n // Shares 75 with E_NEXUS_REGISTRY_CORRUPT: both mean \"registry unusable\".\n E_NEXUS_REGISTRY_READ: 75,\n // T12513: a fleet `--device` filter named no known device.\n E_NEXUS_DEVICE_NOT_FOUND: 4,\n E_NEXUS_PROJECT_EXISTS: 76,\n E_NEXUS_QUERY_FAILED: 77,\n E_NEXUS_GRAPH_ERROR: 78,\n\n // Lifecycle Enforcement (80-84)\n E_LIFECYCLE_GATE_FAILED: 80,\n E_AUDIT_MISSING: 81,\n E_CIRCULAR_VALIDATION: 82,\n E_LIFECYCLE_TRANSITION_INVALID: 83,\n E_IVTR_INCOMPLETE: 83,\n E_PROVENANCE_REQUIRED: 84,\n // T1162: lifecycle scope guard — maps to ExitCode.TASK_NOT_IN_SCOPE (34)\n // because a subagent attempting to mutate a parent epic's lifecycle is\n // operating outside the scope granted by its session.\n E_LIFECYCLE_SCOPE_DENIED: 34,\n\n // Artifact Publish (85-89)\n E_ARTIFACT_TYPE_UNKNOWN: 85,\n E_ARTIFACT_VALIDATION_FAILED: 86,\n E_ARTIFACT_BUILD_FAILED: 87,\n E_ARTIFACT_PUBLISH_FAILED: 88,\n E_ARTIFACT_ROLLBACK_FAILED: 89,\n\n // Provenance (90-94)\n E_PROVENANCE_CONFIG_INVALID: 90,\n E_SIGNING_KEY_MISSING: 91,\n E_SIGNATURE_INVALID: 92,\n E_DIGEST_MISMATCH: 93,\n E_ATTESTATION_INVALID: 94,\n\n // Special Codes (100+) - NOT errors\n E_NO_DATA: 100,\n E_ALREADY_EXISTS: 101,\n E_NO_CHANGE: 102,\n E_TESTS_SKIPPED: 103,\n\n // Adapter Errors (95-99)\n E_ADAPTER_NOT_FOUND: 95,\n E_ADAPTER_INIT_FAILED: 96,\n E_ADAPTER_HOOK_FAILED: 97,\n E_ADAPTER_SPAWN_FAILED: 98,\n E_ADAPTER_INSTALL_FAILED: 99,\n\n // Common engine-specific aliases\n E_NOT_INITIALIZED: 3,\n E_NO_HANDLER: 1,\n E_INTERNAL: 1,\n E_LIST_FAILED: 3,\n E_READ_FAILED: 3,\n E_WRITE_FAILED: 3,\n E_PARSE_ERROR: 2,\n E_TEMPLATE_ERROR: 2,\n};\n\n/**\n * Derive pino log level from exit code.\n *\n * - 100+: special/informational -> 'debug'\n * - 1-9 internal errors (1, 3): -> 'error'\n * - 10-99 user/domain errors: -> 'warn'\n * - 0: success (should not be called for errors) -> 'debug'\n */\nfunction logLevel(exitCode: number): 'error' | 'warn' | 'debug' {\n if (exitCode === 0 || exitCode >= 100) return 'debug';\n // Internal errors: general (1), file (3) — these indicate bugs or system issues\n if (exitCode === 1 || exitCode === 3) return 'error';\n // Everything else is a user/domain error\n return 'warn';\n}\n\n/**\n * Create a typed engine error result with pino logging and correct exit code.\n *\n * @remarks\n * The exit code is derived from the {@link STRING_TO_EXIT} mapping. If the\n * code is not found in the map, exit code 1 (general error) is used.\n * Pino logging is automatically triggered at the appropriate level\n * (error for internal issues, warn for user/domain errors, debug for\n * informational codes). Logging is suppressed under Vitest to keep\n * test output clean.\n *\n * @param code - String error code (e.g., 'E_NOT_FOUND')\n * @param message - Human-readable error message\n * @param options - Optional details, fix command, and alternatives\n * @returns EngineResult with success=false and properly structured error\n *\n * @example\n * ```typescript\n * import { engineError } from './_error.js';\n *\n * return engineError('E_NOT_FOUND', `Task ${id} not found`, {\n * fix: `cleo show ${id}`,\n * details: { taskId: id },\n * });\n * ```\n */\nexport function engineError<T>(\n code: string,\n message: string,\n options?: {\n exitCode?: number;\n details?: Record<string, unknown>;\n fix?: string;\n alternatives?: Array<{ action: string; command: string }>;\n problemDetails?: ProblemDetails;\n },\n): EngineResult<T> {\n const resolvedExitCode = options?.exitCode ?? STRING_TO_EXIT[code] ?? 1;\n const level = logLevel(resolvedExitCode);\n\n // Keep test output clean: skip engine logging under Vitest.\n const isVitest = process.env['VITEST'] === 'true';\n if (!isVitest) {\n // Lazy logger acquisition: avoids capturing the stderr fallback logger\n // at module load time (before CLI's preAction hook calls initLogger()).\n // This prevents the double-output envelope bug (T5148).\n const logger = getLogger('engine');\n logger[level](\n { code, exitCode: resolvedExitCode, ...(options?.details && { details: options.details }) },\n message,\n );\n }\n\n // Delegate construction to canonical core helper (DRY).\n // The dispatch-layer wrapper adds: numeric exitCode resolution + structured logging.\n return coreEngineError<T>(code, message, { ...options, exitCode: resolvedExitCode });\n}\n\n/**\n * Create an engine success result (re-export of canonical core helper).\n *\n * @see {@link import('@cleocode/core').engineSuccess}\n *\n * @example\n * ```typescript\n * import { engineSuccess } from './_error.js';\n *\n * return engineSuccess({ tasks: filteredTasks, total: count });\n * ```\n */\nexport { engineSuccess } from '@cleocode/contracts/engine-result.js';\n\n/**\n * Minimal meta shape carrying the request ID for RFC 7807 `instance` population.\n *\n * Callers may pass the dispatch-layer `DispatchRequest.requestId` (or any\n * other correlation identifier) so that the resulting `problemDetails.instance`\n * URI uniquely identifies the specific error occurrence.\n */\nexport interface ErrorMeta {\n /** Unique request identifier (used as the RFC 7807 `instance` field). */\n requestId?: string;\n}\n\n/**\n * Shape of a caught value that may be a `CleoError` instance.\n *\n * We cannot import `CleoError` from `@cleocode/core` here without risking a\n * circular dependency (core → engine → core), so we use a structural type.\n */\ninterface CaughtCleoErrorShape {\n code?: number;\n message?: string;\n fix?: string;\n details?: Record<string, unknown>;\n alternatives?: Array<{ action: string; command: string }>;\n}\n\n/**\n * Convert any caught value into an {@link EngineResult}, forwarding the rich\n * `fix`, `details`, and `alternatives` fields when the caught value is a\n * `CleoError` (or structurally compatible object).\n *\n * @remarks\n * This is the canonical catch-block helper for all dispatch engines. It\n * replaces the previous pattern of:\n * ```typescript\n * const code = (err as { code?: number })?.code;\n * if (code === 4) return engineError('E_NOT_FOUND', …);\n * …\n * ```\n * with a single call that preserves every field the core layer attached.\n *\n * The `fallbackCode` is used when the numeric `err.code` is not present in\n * the {@link STRING_TO_EXIT} mapping (e.g. unknown exit codes, plain `Error`\n * instances, or values thrown by non-CLEO code).\n *\n * RFC 7807 `problemDetails` is always populated from the resolved code, message,\n * and exit code. The optional `meta.requestId` is forwarded to the `instance`\n * field so every error occurrence is uniquely identifiable.\n *\n * @param err - The caught value (unknown type)\n * @param fallbackCode - String error code to use when mapping fails\n * @param fallbackMessage - Human-readable message when `err.message` is absent\n * @param meta - Optional dispatch meta carrying `requestId` for RFC 7807 `instance`\n * @returns EngineResult with all available rich fields propagated\n *\n * @example\n * ```typescript\n * import { cleoErrorToEngineError } from './_error.js';\n *\n * } catch (err: unknown) {\n * return cleoErrorToEngineError(err, 'E_NOT_INITIALIZED', 'Task database not initialized');\n * }\n * ```\n *\n * @example With requestId for RFC 7807 instance field:\n * ```typescript\n * } catch (err: unknown) {\n * return cleoErrorToEngineError(err, 'E_NOT_FOUND', 'Not found', { requestId });\n * }\n * ```\n */\nexport function cleoErrorToEngineError<T>(\n err: unknown,\n fallbackCode: string,\n fallbackMessage: string,\n meta?: ErrorMeta,\n): EngineResult<T> {\n // Non-Error thrown values: a raw string is its own message; other primitives\n // coerce to their String() form. Structured CleoError-like objects are\n // handled in the branch below via `CaughtCleoErrorShape`.\n if (typeof err === 'string') {\n const exitCode = STRING_TO_EXIT[fallbackCode] ?? 1;\n return engineError<T>(fallbackCode, err, {\n exitCode,\n problemDetails: {\n type: `https://cleocode.dev/errors/${fallbackCode}`,\n title: fallbackCode,\n status: exitCode,\n detail: err,\n ...(meta?.requestId !== undefined ? { instance: meta.requestId } : {}),\n },\n });\n }\n if (err !== null && typeof err !== 'object') {\n const exitCode = STRING_TO_EXIT[fallbackCode] ?? 1;\n const message = String(err);\n return engineError<T>(fallbackCode, message, {\n exitCode,\n problemDetails: {\n type: `https://cleocode.dev/errors/${fallbackCode}`,\n title: fallbackCode,\n status: exitCode,\n detail: message,\n ...(meta?.requestId !== undefined ? { instance: meta.requestId } : {}),\n },\n });\n }\n\n const e = err as CaughtCleoErrorShape;\n const code = mapNumericExitCodeToString(e.code) ?? fallbackCode;\n const message = e.message ?? fallbackMessage;\n const exitCode = STRING_TO_EXIT[code] ?? 1;\n\n return engineError<T>(code, message, {\n exitCode,\n ...(e.fix !== undefined && { fix: e.fix }),\n ...(e.details !== undefined && { details: e.details }),\n ...(e.alternatives !== undefined && { alternatives: e.alternatives }),\n problemDetails: {\n type: `https://cleocode.dev/errors/${code}`,\n title: code,\n status: exitCode,\n detail: message,\n ...(meta?.requestId !== undefined ? { instance: meta.requestId } : {}),\n },\n });\n}\n","/**\n * Shared exit-code mapping utilities for the transport-agnostic gateway.\n *\n * Provides a canonical reverse lookup from numeric exit code to string error code,\n * shared between the gateway engine helpers and every transport adapter (CLI,\n * MCP, RPC, HTTP).\n *\n * @remarks\n * Relocated from `packages/cleo/src/dispatch/lib/exit-codes.ts` into\n * `@cleocode/runtime/gateway` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION) so the\n * runtime can host the shared handler dependencies without importing\n * `@cleocode/cleo`. A thin re-export shim remains at the old path.\n *\n * The forward mapping (string → number) lives in `engine-error.ts` as\n * `STRING_TO_EXIT`. This module derives the inverse on first call and memoises\n * it so engines can resolve a caught `CleoError.code` (numeric) to the\n * string code expected by `engineError()`.\n *\n * @task T374\n * @task T11455\n * @epic T335\n */\n\nimport { STRING_TO_EXIT } from './engine-error.js';\n\n/** Lazily built inverse of STRING_TO_EXIT (number → string). */\nlet _inverseCache: Map<number, string> | null = null;\n\n/**\n * Build and memoize the inverse of STRING_TO_EXIT.\n *\n * When multiple string codes map to the same exit number (e.g. E_GENERAL\n * and E_GENERAL_ERROR both map to 1), the first occurrence wins.\n */\nfunction getInverseMap(): Map<number, string> {\n if (_inverseCache) return _inverseCache;\n\n const map = new Map<number, string>();\n for (const [key, value] of Object.entries(STRING_TO_EXIT)) {\n if (!map.has(value)) {\n map.set(value, key);\n }\n }\n _inverseCache = map;\n return map;\n}\n\n/**\n * Map a numeric CleoError exit code to the canonical string engine error code.\n *\n * @remarks\n * Returns `undefined` when the numeric code is not present in the\n * `STRING_TO_EXIT` map, allowing callers to fall back to their own default.\n *\n * @param numericCode - Numeric exit code from a caught `CleoError.code`\n * @returns Canonical string error code (e.g. `'E_NOT_FOUND'`), or `undefined`\n *\n * @example\n * ```typescript\n * import { mapNumericExitCodeToString } from '../lib/exit-codes.js';\n *\n * const code = mapNumericExitCodeToString(4) ?? 'E_NOT_INITIALIZED';\n * // → 'E_NOT_FOUND'\n * ```\n */\nexport function mapNumericExitCodeToString(numericCode: number | undefined): string | undefined {\n if (numericCode === undefined) return undefined;\n return getInverseMap().get(numericCode);\n}\n","/**\n * The transport-neutral gateway handler (relocated from `gateway/index.ts`,\n * T13126) so the light `@cleocode/runtime/gateway/dispatch` entry can export\n * it without loading the HTTP, MCP and RPC transports.\n *\n * @task T13126\n */\n\nimport type { DispatchRequest, DispatchResponse } from '@cleocode/contracts/gateway';\nimport { Dispatcher, type DispatcherConfig } from './dispatcher.js';\n\n/**\n * Transport-agnostic gateway entrypoint. Wraps a configured {@link Dispatcher}\n * (`compose(middlewares) → DomainHandler`) behind a single `handle()` call that\n * every transport adapter (CLI/MCP/RPC/HTTP) invokes uniformly. The adapter\n * owns wire concerns (error-render, `process.exit`, serialization); the handler\n * only resolves, validates, runs middleware, and returns a {@link DispatchResponse}.\n */\nexport interface GatewayHandler {\n /** Route one gateway request through the dispatch pipeline. */\n handle(req: DispatchRequest): Promise<DispatchResponse>;\n}\n\n/**\n * Build a {@link GatewayHandler} from a {@link DispatcherConfig} (injected\n * domain handlers + middleware). The returned handler is transport-neutral.\n */\nexport function createGatewayHandler(config: DispatcherConfig): GatewayHandler {\n const dispatcher = new Dispatcher(config);\n return { handle: (req: DispatchRequest): Promise<DispatchResponse> => dispatcher.dispatch(req) };\n}\n","/**\n * nexus-decorator — stamps `meta._nexus` on every nexus-domain dispatch response.\n *\n * Wave 2 of the Nexus Restructure (T9146). Reads `getNexusDescriptor(opId)` from\n * the W1 SSoT (`NEXUS_SCOPE_MAP`) and injects the namespaced `_nexus` block into\n * `DispatchResponse['meta']`.\n *\n * Usage:\n * ```ts\n * const decorated = stampNexusMeta(response, operation, params);\n * ```\n *\n * The `suggestedNext` field uses a structured form (not literal display strings).\n * Display strings are derived by `formatSuggestedNext()` for human/markdown renderers.\n *\n * Typed-registry gate: `validateSuggestedNext()` fails the build (throws at import-time\n * in test mode) if any `suggestedNext.op` is absent from `NEXUS_SCOPE_MAP`.\n *\n * @remarks\n * Relocated from `packages/cleo/src/dispatch/nexus-decorator.ts` into\n * `@cleocode/runtime/gateway` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION) so the\n * nexus domain handler can import it from the runtime layer rather than a\n * cleo-internal path. The module is pure (`@cleocode/contracts` only). A thin\n * re-export shim remains at the old path for the renderer / CLI import sites.\n *\n * @task T9146\n * @task T11455\n * @module runtime/gateway/nexus-decorator\n */\n\nimport type {\n NexusBindingSource,\n NexusOps,\n NexusScopeMeta,\n SuggestedNextOp,\n} from '@cleocode/contracts';\nimport type { DispatchResponse, DispatchResponseMeta } from '@cleocode/contracts/gateway';\nimport {\n getNexusDescriptor,\n NEXUS_SCOPE_MAP,\n} from '@cleocode/contracts/operations/nexus-scope-map.js';\n\n// ---------------------------------------------------------------------------\n// Binding-source resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve how the `projectId` was bound for a given operation call.\n *\n * Priority: explicit `--project-id` arg > `--path` arg > cwd resolution >\n * registry lookup > none (for global/living-brain scope ops).\n */\nfunction resolveBindingSource(\n descriptor: ReturnType<typeof getNexusDescriptor>,\n params: Record<string, unknown>,\n): NexusBindingSource {\n if (!descriptor.requiresProject) return 'none';\n if (typeof params['projectId'] === 'string' && params['projectId']) {\n return 'arg-project-id';\n }\n if (typeof params['path'] === 'string' && params['path']) {\n return 'arg-path';\n }\n // Distinguish cwd vs registry: if a projectId was resolved (e.g. by the\n // engine from cwd) it comes through as projectId in params; absence means\n // the registry was consulted.\n if (typeof params['_resolvedFrom'] === 'string') {\n return params['_resolvedFrom'] === 'cwd' ? 'cwd' : 'registry';\n }\n return 'cwd';\n}\n\n// ---------------------------------------------------------------------------\n// indexFreshness\n// ---------------------------------------------------------------------------\n\n/**\n * Determine index freshness for `indexSensitive` operations.\n *\n * Only called for top-level CLI invocations (sub-calls inherit via\n * `meta.requestId` lineage to avoid per-call git-status shell-outs).\n * Returns `'unknown'` when freshness cannot be determined cheaply.\n */\nfunction resolveIndexFreshness(params: Record<string, unknown>): NexusScopeMeta['indexFreshness'] {\n // If the engine already stamped freshness on the response params, use it.\n const fromParams = params['_indexFreshness'];\n if (fromParams === 'fresh' || fromParams === 'stale') return fromParams;\n return 'unknown';\n}\n\n// ---------------------------------------------------------------------------\n// Canonical command\n// ---------------------------------------------------------------------------\n\n/** Derive the canonical CLI command string from the operation key. */\nfunction canonicalCommandFor(op: string): string {\n return `cleo nexus ${op}`;\n}\n\n// ---------------------------------------------------------------------------\n// Typed-registry gate\n// ---------------------------------------------------------------------------\n\n/**\n * Assert that every `suggestedNext.op` in a list resolves to a known\n * NEXUS_SCOPE_MAP entry.\n *\n * Throws `TypeError` at runtime (caught by tests and CI) if an unknown op\n * is referenced — acting as a build-time gate when imported in test suites.\n *\n * @throws {TypeError} if any `op` is absent from `NEXUS_SCOPE_MAP`\n * @task T9146\n */\nexport function validateSuggestedNext(suggestions: ReadonlyArray<SuggestedNextOp>): void {\n for (const s of suggestions) {\n if (!(s.op in NEXUS_SCOPE_MAP)) {\n throw new TypeError(\n `[nexus-decorator] suggestedNext.op \"${s.op}\" is not a known NEXUS_SCOPE_MAP entry. ` +\n `Add it to packages/contracts/src/operations/nexus-scope-map.ts first.`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Display formatter\n// ---------------------------------------------------------------------------\n\n/**\n * Derive a human-readable display string from a {@link SuggestedNextOp}.\n *\n * Example: `\"cleo nexus context --project-id myproj (read-only, no confirmation needed)\"`\n */\nexport function formatSuggestedNext(s: SuggestedNextOp): string {\n const argParts = Object.entries(s.args)\n .map(([k, v]) => `--${k} ${String(v)}`)\n .join(' ');\n const cmd = `cleo nexus ${s.op}${argParts ? ` ${argParts}` : ''}`;\n const confirm = s.requiresConfirmation ? 'confirm before running' : 'no confirmation needed';\n return `${cmd} (${s.effect}, ${confirm}) — ${s.reason}`;\n}\n\n// ---------------------------------------------------------------------------\n// stampNexusMeta — core decorator\n// ---------------------------------------------------------------------------\n\n/**\n * Stamp `meta._nexus` onto a nexus-domain {@link DispatchResponse}.\n *\n * Call this after every nexus handler produces its `DispatchResponse`. The\n * function is a pure transformer — it returns a new object with `meta._nexus`\n * merged in.\n *\n * @param response - The original dispatch response from the nexus handler.\n * @param operation - The nexus operation key (must be a `keyof NexusOps`).\n * @param params - Raw params passed to the handler (used for binding-source resolution).\n * @param isTopLevel - Whether this is a top-level CLI invocation (not a sub-call).\n * @returns A new `DispatchResponse` with `meta._nexus` populated.\n *\n * @task T9146\n */\nexport function stampNexusMeta(\n response: DispatchResponse,\n operation: string,\n params: Record<string, unknown>,\n isTopLevel = true,\n): DispatchResponse {\n // Unknown ops (not in NEXUS_SCOPE_MAP) fall through without decoration —\n // the handler already returned an unsupported-op error.\n if (!(operation in NEXUS_SCOPE_MAP)) {\n return response;\n }\n\n const descriptor = getNexusDescriptor(operation as keyof NexusOps);\n const bindingSource = resolveBindingSource(descriptor, params);\n\n const projectId = typeof params['projectId'] === 'string' ? params['projectId'] : undefined;\n const projectName =\n typeof params['_projectName'] === 'string' ? params['_projectName'] : undefined;\n const projectPath =\n typeof params['_projectPath'] === 'string' ? params['_projectPath'] : undefined;\n const registryPath =\n typeof params['_registryPath'] === 'string' ? params['_registryPath'] : undefined;\n const counterpartProjectId =\n descriptor.scope === 'cross' || descriptor.scope === 'hybrid'\n ? typeof params['counterpartProjectId'] === 'string'\n ? params['counterpartProjectId']\n : undefined\n : undefined;\n\n const indexFreshness =\n descriptor.indexSensitive && isTopLevel ? resolveIndexFreshness(params) : undefined;\n\n const legacyAliasFor =\n typeof params['_legacyAliasFor'] === 'string' ? params['_legacyAliasFor'] : undefined;\n\n const nexusMeta: NexusScopeMeta = {\n scope: descriptor.scope,\n effect: descriptor.effect,\n ...(projectId !== undefined && { projectId }),\n ...(projectName !== undefined && { projectName }),\n ...(projectPath !== undefined && { projectPath }),\n ...(registryPath !== undefined && { registryPath }),\n bindingSource,\n ...(counterpartProjectId !== undefined && { counterpartProjectId }),\n ...(indexFreshness !== undefined && { indexFreshness }),\n canonicalCommand: canonicalCommandFor(operation),\n ...(legacyAliasFor !== undefined && { legacyAliasFor }),\n };\n\n return {\n ...response,\n meta: {\n ...response.meta,\n _nexus: nexusMeta,\n // Stamp top-level deprecated field for alias shims (T9147)\n ...(legacyAliasFor !== undefined && {\n deprecated: {\n since: 'v2026.6.5',\n removeIn: 'v2026.8.0',\n replacement: `cleo graph ${operation}`,\n },\n }),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// pickDecoratorMetaExtensions — forward decorator fields into CLI envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Pick the decorator-stamped fields (`_nexus`, `deprecated`) from a dispatch\n * response's `meta` so they can be forwarded via `cliOutput`'s `extensions`\n * option into the emitted LAFS envelope.\n *\n * Without this, `cliOutput(response.data, ...)` discards `response.meta._nexus`\n * + `response.meta.deprecated` (T9393 defect). Canonical CLI meta fields\n * (`operation`, `requestId`, `timestamp`) are intentionally NOT forwarded —\n * those are produced by {@link createCliMeta} on the CLI side.\n *\n * @task T9393\n */\nexport function pickDecoratorMetaExtensions(\n responseMeta: DispatchResponseMeta | undefined,\n): Record<string, unknown> {\n if (!responseMeta) return {};\n const out: Record<string, unknown> = {};\n if (responseMeta['_nexus'] !== undefined) out['_nexus'] = responseMeta['_nexus'];\n if (responseMeta['deprecated'] !== undefined) out['deprecated'] = responseMeta['deprecated'];\n if (responseMeta.sessionId !== undefined) out['sessionId'] = responseMeta.sessionId;\n if (responseMeta.originSessionId !== undefined) {\n out['originSessionId'] = responseMeta.originSessionId;\n }\n if (responseMeta.executionSessionId !== undefined) {\n out['executionSessionId'] = responseMeta.executionSessionId;\n }\n // T9921\n if (responseMeta['suggestedNext'] !== undefined) {\n out['suggestedNext'] = responseMeta['suggestedNext'];\n }\n return out;\n}\n\n/**\n * Build CLI envelope extensions for nexus commands that bypass the dispatcher\n * (e.g. `cleo nexus status` SSoT-EXEMPT path). Runs the same {@link stampNexusMeta}\n * logic against a synthetic response so the resulting envelope still carries\n * `meta._nexus` (and `meta.deprecated` for alias shims).\n *\n * Use this only where the command does NOT call `dispatchRaw`. When you have a\n * real dispatch response, use {@link pickDecoratorMetaExtensions} on\n * `response.meta` instead — that path already ran the decorator.\n *\n * @task T9393\n */\nexport function buildNexusMetaExtensions(\n operation: string,\n params: Record<string, unknown> = {},\n): Record<string, unknown> {\n const synthetic: DispatchResponse = {\n success: true,\n data: undefined,\n meta: {\n gateway: 'query',\n domain: 'nexus',\n operation,\n timestamp: new Date().toISOString(),\n duration_ms: 0,\n source: 'cli',\n requestId: '',\n },\n } as DispatchResponse;\n const stamped = stampNexusMeta(synthetic, operation, params);\n return pickDecoratorMetaExtensions(stamped.meta);\n}\n","/**\n * Gateway-level path constants shared by domain handlers.\n *\n * @remarks\n * The `orchestrate` and `admin` (smoke-provider) domain handlers join a handful\n * of well-known `.cleo/` path segments when locating workflow definitions and\n * the BRAIN database. Those constants were previously defined in\n * `packages/cleo/src/cli/paths.ts` (a CLI-internal leaf), which coupled the\n * handler subgraph to `@cleocode/cleo`.\n *\n * To let `@cleocode/runtime` assemble the handler map WITHOUT importing\n * `@cleocode/cleo` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION), the constants the\n * handlers actually consume are hosted here as the canonical source. The\n * CLI-side `cli/paths.ts` re-exports them so the rest of the CLI (backup /\n * restore / doctor) keeps importing from its established surface — there is a\n * single definition, no drift.\n *\n * @task T090\n * @task T11455\n */\n\n/** Name of the project-local CLEO data directory (`.cleo`). */\nexport const CLEO_DIR_NAME = '.cleo' as const;\n\n/** Subdirectory under `.cleo/` that stores CANT workflow definitions. */\nexport const WORKFLOWS_SUBDIR = 'workflows' as const;\n\n/** Project-local SQLite database filename for cognitive memory (BRAIN). */\nexport const BRAIN_DB_FILENAME = 'brain.db' as const;\n"],"mappings":";;;;;;AASA,SAAS,kBAAkB;AAoBpB,SAAS,mBACd,SACA,QACA,WACA,WACA,SAAiB,OACjB,WACA,WACA,iBACA,oBAC0B;AAC1B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IAClC,aAAa,KAAK,IAAI,IAAI;AAAA,IAC1B;AAAA,IACA,WAAW,aAAa,WAAW;AAAA,IACnC,GAAI,aAAa,QAAQ,EAAE,UAAU;AAAA,IACrC,GAAI,mBAAmB,QAAQ,EAAE,gBAAgB;AAAA,IACjD,GAAI,sBAAsB,QAAQ,EAAE,mBAAmB;AAAA,EACzD;AACF;;;ACdO,SAAS,QAAQ,aAAuC;AAC7D,MAAI,YAAY,WAAW,GAAG;AAC5B,WAAO,OAAO,MAAuB,SAAuB,KAAK;AAAA,EACnE;AAEA,SAAO,OAAO,SAA0B,SAAkD;AACxF,QAAI,QAAQ;AAEZ,mBAAe,SAAS,GAAsC;AAC5D,UAAI,KAAK,OAAO;AACd,cAAM,IAAI,MAAM,4CAA4C;AAAA,MAC9D;AACA,cAAQ;AAER,UAAI,KAA6B,YAAY,CAAC;AAC9C,UAAI,MAAM,YAAY,QAAQ;AAE5B,aAAK,OAAO,MAAM,QAAQ,IAAI;AAAA,MAChC;AAEA,UAAI,CAAC,IAAI;AACP,eAAO,K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AAI,aAAa,uBAAuB,QAAW;AACjD,QAAI,oBAAoB,IAAI,aAAa;AAAA,EAC3C;AAEA,MAAI,aAAa,eAAe,MAAM,QAAW;AAC/C,QAAI,eAAe,IAAI,aAAa,eAAe;AAAA,EACrD;AACA,SAAO;AACT;AAcO,SAAS,yBACd,WACA,SAAkC,CAAC,GACV;AACzB,QAAM,YAA8B;AAAA,IAClC,SAAS;AAAA,IACT,MAAM;AAAA,IACN,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,QAAQ;AAAA,MACR;AAAA,MACA,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MAClC,aAAa;AAAA,MACb,QAAQ;AAAA,MACR,WAAW;AAAA,IACb;AAAA,EACF;AACA,QAAM,UAAU,eAAe,WAAW,WAAW,MAAM;AAC3D,SAAO,4BAA4B,QAAQ,IAAI;AACjD;;;ACjRO,IAAM,gBAAgB;AAGtB,IAAM,mBAAmB;AAGzB,IAAM,oBAAoB;","names":["randomUUID","randomUUID","getLogger","getLogger","exitCode","message"]}
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  OPERATIONS
3
- } from "./chunk-L5BLVQDA.js";
3
+ } from "./chunk-4PUSKGDO.js";
4
4
 
5
5
  // src/gateway/mcp/server.ts
6
6
  import { randomUUID } from "crypto";
7
7
  import * as readline from "readline";
8
8
  import { getLogger } from "@cleocode/core";
9
+ import { useBrainWriterThread } from "@cleocode/core/memory/brain-writer-thread";
9
10
 
10
11
  // src/gateway/mcp/tool-naming.ts
11
12
  var MCP_TOOL_PREFIX = "cleo_";
@@ -136,6 +137,7 @@ async function handleRequest(handler, req) {
136
137
  }
137
138
  }
138
139
  function startMcpServer(handler, opts) {
140
+ useBrainWriterThread();
139
141
  const input = opts?.input ?? process.stdin;
140
142
  const output = opts?.output ?? process.stdout;
141
143
  const exitOnClose = opts?.exitOnClose ?? true;
@@ -179,4 +181,4 @@ export {
179
181
  callTool,
180
182
  startMcpServer
181
183
  };
182
- //# sourceMappingURL=chunk-XJOMQIXL.js.map
184
+ //# sourceMappingURL=chunk-WO6LJMDC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gateway/mcp/server.ts","../src/gateway/mcp/tool-naming.ts","../src/gateway/mcp/tools-list.ts"],"sourcesContent":["/**\n * MCP stdio transport adapter — routes `tools/call` through the gateway.\n *\n * Serves the Model Context Protocol over stdio (newline-delimited JSON-RPC 2.0)\n * so any MCP-compatible client (Claude Code, LLM-agnostic tools) can discover\n * and invoke CLEO operations. Unlike the legacy standalone `@cleocode/mcp-adapter`\n * — which called the `@cleocode/core` SDK directly — this adapter is a thin\n * TRANSPORT over the unified gateway:\n *\n * MCP `tools/call` { name, arguments }\n * → {@link GatewayOperationKey} (via the `mcpExposed` registry subset)\n * → DispatchRequest { source: 'mcp', gateway, domain, operation, params }\n * → injected {@link GatewayHandler}.handle()\n * → DispatchResponse (LAFS envelope) → MCP tool result (JSON text content)\n *\n * The adapter owns ONLY wire concerns: JSON-RPC framing, the stdio read loop,\n * `tools/list` generation, error rendering, and `process.exit` on stream close.\n * All domain logic (resolution, validation, middleware, handler execution) lives\n * behind the {@link GatewayHandler} — exactly mirroring how the CLI adapter\n * wraps the same handler. `process.exit` and error-render stay HERE, never in\n * the handlers (R3-T4 contract).\n *\n * `tools/list` is generated from the OPERATIONS registry behind the default-deny\n * `mcpExposed` flag, so the external tool surface is identical to the historical\n * standalone adapter (no behavior change).\n *\n * @task T11448\n * @epic T11254\n * @saga T11243\n */\n\nimport { randomUUID } from 'node:crypto';\nimport * as readline from 'node:readline';\nimport type { DispatchRequest, DispatchResponse } from '@cleocode/contracts/gateway';\nimport { getLogger } from '@cleocode/core';\nimport { useBrainWriterThread } from '@cleocode/core/memory/brain-writer-thread';\nimport type { GatewayHandler } from '../index.js';\nimport { toolNameToOperationKey } from './tool-naming.js';\nimport { buildToolsList, exposedOperations } from './tools-list.js';\nimport type { McpTool, McpToolResult } from './types.js';\n\n// ---------------------------------------------------------------------------\n// JSON-RPC 2.0 envelope helpers\n// ---------------------------------------------------------------------------\n\n/** Inbound JSON-RPC request frame. */\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id: number | string | null;\n method: string;\n params?: unknown;\n}\n\n/** Outbound JSON-RPC response frame. */\ninterface JsonRpcResponse {\n jsonrpc: '2.0';\n id: number | string | null;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\n/** Build a JSON-RPC success response. */\nfunction ok(id: number | string | null, result: unknown): JsonRpcResponse {\n return { jsonrpc: '2.0', id, result };\n}\n\n/** Build a JSON-RPC error response. */\nfunction rpcError(id: number | string | null, code: number, message: string): JsonRpcResponse {\n return { jsonrpc: '2.0', id, error: { code, message } };\n}\n\n// ---------------------------------------------------------------------------\n// Server identity\n// ---------------------------------------------------------------------------\n\n/** Advertised MCP server name. */\nconst SERVER_NAME = 'cleo-gateway-mcp';\n/** MCP protocol revision the adapter speaks. */\nconst PROTOCOL_VERSION = '2024-11-05';\n/** Version string advertised in the `initialize` handshake. */\nconst GATEWAY_MCP_VERSION = '1.0.0';\n\n// ---------------------------------------------------------------------------\n// tools/call → gateway routing\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap a {@link DispatchResponse} envelope into an MCP tool result.\n *\n * The full LAFS envelope is serialized as the text content so MCP clients see\n * the same `{ success, data, meta, error }` payload every other transport\n * returns. `isError` is set from the envelope's `success` flag.\n *\n * @param response - The gateway dispatch response.\n * @returns An MCP {@link McpToolResult}.\n */\nfunction responseToToolResult(response: DispatchResponse): McpToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(response) }],\n isError: response.success ? undefined : true,\n };\n}\n\n/**\n * Route a single MCP `tools/call` through the gateway handler.\n *\n * Resolves the tool name to a `(domain, operation)` key against the exposed\n * (`mcpExposed`) registry subset, builds a `source: 'mcp'` {@link DispatchRequest},\n * and delegates to the injected {@link GatewayHandler}. Unknown tool names and\n * thrown handler errors are rendered as MCP error results — never propagated as\n * `process.exit` from this layer.\n *\n * @param handler - The injected transport-neutral gateway handler.\n * @param toolName - The MCP `tools/call` tool name.\n * @param args - The parsed tool arguments (already JSON-decoded by the client).\n * @returns An MCP {@link McpToolResult}.\n */\nexport async function callTool(\n handler: GatewayHandler,\n toolName: string,\n args: Record<string, unknown>,\n): Promise<McpToolResult> {\n const exposed = exposedOperations();\n const key = toolNameToOperationKey(toolName, exposed);\n if (!key) {\n return {\n content: [{ type: 'text', text: `Unknown tool: ${toolName}` }],\n isError: true,\n };\n }\n\n // The exposed def carries the CQRS gateway — no second lookup needed.\n const def = exposed.find((op) => op.domain === key.domain && op.operation === key.operation);\n if (!def) {\n return {\n content: [{ type: 'text', text: `Unknown tool: ${toolName}` }],\n isError: true,\n };\n }\n\n const request: DispatchRequest = {\n gateway: def.gateway,\n domain: key.domain,\n operation: key.operation,\n params: args,\n source: 'mcp',\n requestId: randomUUID(),\n };\n\n try {\n const response = await handler.handle(request);\n return responseToToolResult(response);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: 'text', text: `Tool execution failed: ${message}` }],\n isError: true,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// JSON-RPC method handlers\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single decoded JSON-RPC request frame.\n *\n * @param handler - The injected gateway handler.\n * @param req - The decoded JSON-RPC request.\n * @returns The JSON-RPC response frame to write back.\n */\nasync function handleRequest(\n handler: GatewayHandler,\n req: JsonRpcRequest,\n): Promise<JsonRpcResponse> {\n const { id, method, params } = req;\n\n switch (method) {\n case 'initialize':\n return ok(id, {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: { name: SERVER_NAME, version: GATEWAY_MCP_VERSION },\n });\n\n case 'tools/list':\n return ok(id, { tools: buildToolsList() satisfies McpTool[] });\n\n case 'tools/call': {\n const p = params as { name?: string; arguments?: Record<string, unknown> } | undefined;\n const toolName = p?.name;\n if (!toolName) {\n return rpcError(id, -32602, 'Missing tool name in params.name');\n }\n const result = await callTool(handler, toolName, p?.arguments ?? {});\n return ok(id, result);\n }\n\n case 'notifications/initialized':\n case 'ping':\n return ok(id, {});\n\n default:\n return rpcError(id, -32601, `Method not found: ${method}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// stdio server entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Options for {@link startMcpServer}.\n */\nexport interface McpServerOptions {\n /** Inbound stream (defaults to `process.stdin`). */\n input?: NodeJS.ReadableStream;\n /** Outbound stream (defaults to `process.stdout`). */\n output?: NodeJS.WritableStream;\n /**\n * Whether to call `process.exit(0)` when the input stream closes.\n * Defaults to `true` (production stdio). Tests pass `false`.\n */\n exitOnClose?: boolean;\n}\n\n/**\n * Start the MCP stdio server over the gateway.\n *\n * Reads newline-delimited JSON-RPC 2.0 requests from the input stream, routes\n * `tools/call` through the injected {@link GatewayHandler}, and writes responses\n * to the output stream. Each inbound line must be one complete JSON-RPC request.\n *\n * The caller assembles the {@link GatewayHandler} (via `createGatewayHandler`\n * with its domain handlers + middleware) and injects it here — this adapter\n * never builds handlers itself, keeping the runtime free of any\n * `@cleocode/cleo` dependency.\n *\n * @param handler - The transport-neutral gateway handler to route through.\n * @param opts - Optional stream + lifecycle overrides (defaults to stdio).\n */\nexport function startMcpServer(handler: GatewayHandler, opts?: McpServerOptions): void {\n // A long-lived host: brain writes run on the worker thread (T13126).\n useBrainWriterThread();\n const input = opts?.input ?? process.stdin;\n const output = opts?.output ?? process.stdout;\n const exitOnClose = opts?.exitOnClose ?? true;\n const log = getLogger('gateway-mcp');\n\n const rl = readline.createInterface({ input, terminal: false });\n\n rl.on('line', (line) => {\n const trimmed = line.trim();\n if (!trimmed) return;\n\n let req: JsonRpcRequest;\n try {\n req = JSON.parse(trimmed) as JsonRpcRequest;\n } catch {\n output.write(`${JSON.stringify(rpcError(null, -32700, 'Parse error: invalid JSON'))}\\n`);\n return;\n }\n\n handleRequest(handler, req)\n .then((response) => {\n output.write(`${JSON.stringify(response)}\\n`);\n })\n .catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n log.warn({ err }, 'mcp request handling failed');\n output.write(\n `${JSON.stringify(rpcError(req.id ?? null, -32603, `Internal error: ${message}`))}\\n`,\n );\n });\n });\n\n rl.on('close', () => {\n if (exitOnClose) process.exit(0);\n });\n}\n","/**\n * MCP tool-name <-> gateway-operation mapping.\n *\n * The MCP wire protocol identifies a tool by a single flat `name` string\n * (snake_case, e.g. `cleo_sentient_propose_list`), whereas the gateway routes\n * on a `(gateway, domain, operation)` triple (e.g.\n * `query / sentient / propose.list`). This module is the bijective bridge\n * between the two surfaces:\n *\n * gateway op → MCP tool name {@link operationToToolName}\n * MCP tool name → domain+operation {@link toolNameToOperationKey}\n *\n * ## Naming convention (frozen — matches the legacy `@cleocode/mcp-adapter`)\n *\n * `cleo_<domain>_<operation>` where every `.` and `-` in the dotted operation\n * name becomes `_`. The three historically-exposed tools therefore map as:\n *\n * | gateway op | MCP tool name |\n * |-----------------------------|--------------------------------|\n * | `sentient` · `status` | `cleo_sentient_status` |\n * | `sentient` · `propose.list` | `cleo_sentient_propose_list` |\n * | `sentient` · `propose.enable` | `cleo_sentient_propose_enable` |\n *\n * Preserving this exact mapping is what guarantees R3-T4's \"no behavior change\n * to the MCP tool surface\" acceptance criterion.\n *\n * @task T11448\n * @epic T11254\n * @saga T11243\n */\n\nimport type { OperationDef } from '@cleocode/contracts';\n\n/** Prefix every CLEO MCP tool name carries. */\nexport const MCP_TOOL_PREFIX = 'cleo_';\n\n/**\n * Identifies a gateway operation by its `(domain, operation)` pair. The CQRS\n * gateway resolves which `Gateway` ('query' | 'mutate') the pair belongs to via\n * the operation registry, so the MCP adapter does not need to carry it.\n */\nexport interface GatewayOperationKey {\n /** Canonical domain (e.g. `'sentient'`). */\n readonly domain: string;\n /** Dotted operation name (e.g. `'propose.list'`). */\n readonly operation: string;\n}\n\n/**\n * Convert a dotted operation segment into its MCP-safe snake_case form.\n *\n * @param segment - A domain or operation string (may contain `.`/`-`).\n * @returns The segment with every `.`/`-` replaced by `_`.\n */\nfunction toSnake(segment: string): string {\n return segment.replace(/[.-]/g, '_');\n}\n\n/**\n * Derive the flat MCP tool name for a gateway operation.\n *\n * @param op - An {@link OperationDef} (or any object carrying `domain` +\n * `operation`) from the registry.\n * @returns The MCP tool name, e.g. `'cleo_sentient_propose_list'`.\n */\nexport function operationToToolName(op: Pick<OperationDef, 'domain' | 'operation'>): string {\n return `${MCP_TOOL_PREFIX}${toSnake(op.domain)}_${toSnake(op.operation)}`;\n}\n\n/**\n * Resolve an MCP tool name back to its `(domain, operation)` gateway key.\n *\n * The reverse of {@link operationToToolName} cannot recover dots vs dashes from\n * the snake_case wire form, so resolution is performed against the provided\n * `exposed` set (the same `mcpExposed: true` subset used to build `tools/list`).\n * This keeps the mapping exact and rejects unknown tool names.\n *\n * @param toolName - The MCP `tools/call` tool name.\n * @param exposed - The exposed operation defs (the `mcpExposed` subset).\n * @returns The matching {@link GatewayOperationKey}, or `undefined` when the\n * tool name does not correspond to any exposed operation.\n */\nexport function toolNameToOperationKey(\n toolName: string,\n exposed: readonly OperationDef[],\n): GatewayOperationKey | undefined {\n const match = exposed.find((op) => operationToToolName(op) === toolName);\n return match ? { domain: match.domain, operation: match.operation } : undefined;\n}\n","/**\n * MCP `tools/list` generation from the OPERATIONS registry.\n *\n * The MCP tool surface is **default-deny**: only {@link OperationDef} entries\n * that explicitly set `mcpExposed: true` are surfaced. This replaces the legacy\n * `@cleocode/mcp-adapter`'s hand-maintained `ALL_TOOLS` array with a single\n * generation point driven by the canonical registry — promoting a new tool is\n * now one `mcpExposed: true` edit in `@cleocode/contracts`, not a fork-and-copy\n * into a standalone adapter.\n *\n * @task T11448\n * @epic T11254\n * @saga T11243\n */\n\nimport type { OperationDef, ParamDef } from '@cleocode/contracts';\nimport { OPERATIONS } from '../registry.js';\nimport { operationToToolName } from './tool-naming.js';\nimport type { McpInputProperty, McpTool } from './types.js';\n\n/**\n * The subset of OPERATIONS surfaced over MCP (default-deny `mcpExposed` filter).\n *\n * @returns Every {@link OperationDef} with `mcpExposed === true`, in registry\n * order. Empty when no operation opts in.\n */\nexport function exposedOperations(): OperationDef[] {\n return OPERATIONS.filter((op) => op.mcpExposed === true);\n}\n\n/**\n * Map a JSON-ish {@link ParamDef} type to its JSON Schema primitive.\n *\n * MCP clients consume standard JSON Schema, so `'array'` widens to `'string'`\n * the same way the CLI's citty bridge does (callers split/parse) and every\n * other type passes through unchanged.\n *\n * @param type - The {@link ParamDef} runtime type.\n * @returns The JSON Schema `type` keyword.\n */\nfunction paramTypeToJsonSchema(type: ParamDef['type']): string {\n return type === 'array' ? 'string' : type;\n}\n\n/**\n * Build the MCP `inputSchema` for a single operation from its `params`.\n *\n * Hidden params (`hidden: true`) are excluded from the public tool surface,\n * matching the JSON Schema generation policy declared on {@link ParamDef}.\n *\n * @param op - The exposed operation definition.\n * @returns A JSON Schema object describing the tool's input.\n */\nfunction buildInputSchema(op: OperationDef): McpTool['inputSchema'] {\n const properties: Record<string, McpInputProperty> = {};\n const required: string[] = [];\n\n for (const param of op.params ?? []) {\n if (param.hidden === true) continue;\n const prop: McpInputProperty = {\n type: paramTypeToJsonSchema(param.type),\n description: param.description,\n };\n if (param.enum !== undefined && param.enum.length > 0) {\n prop.enum = param.enum;\n }\n properties[param.name] = prop;\n if (param.required) required.push(param.name);\n }\n\n const schema: McpTool['inputSchema'] = { type: 'object', properties };\n if (required.length > 0) schema.required = required;\n return schema;\n}\n\n/**\n * Convert a single exposed {@link OperationDef} into its MCP tool definition.\n *\n * @param op - An operation with `mcpExposed === true`.\n * @returns The MCP {@link McpTool} (name + description + inputSchema).\n */\nexport function operationToMcpTool(op: OperationDef): McpTool {\n return {\n name: operationToToolName(op),\n description: op.description,\n inputSchema: buildInputSchema(op),\n };\n}\n\n/**\n * Generate the full MCP `tools/list` payload from the registry.\n *\n * @returns Every exposed operation rendered as an {@link McpTool}, in registry\n * order (stable across calls).\n */\nexport function buildToolsList(): McpTool[] {\n return exposedOperations().map(operationToMcpTool);\n}\n"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Aa;AAEnC,QAAM,KAAc,yBAAgB,EAAE,OAAO,UAAU,MAAM,CAAC;AAE9D,KAAG,GAAG,QAAQ,CAAC,SAAS;AACtB,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,CAAC,QAAS;AAEd,QAAI;AACJ,QAAI;AACF,YAAM,KAAK,MAAM,OAAO;AAAA,IAC1B,QAAQ;AACN,aAAO,MAAM,GAAG,KAAK,UAAU,SAAS,MAAM,QAAQ,2BAA2B,CAAC,CAAC;AAAA,CAAI;AACvF;AAAA,IACF;AAEA,kBAAc,SAAS,GAAG,EACvB,KAAK,CAAC,aAAa;AAClB,aAAO,MAAM,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,CAAI;AAAA,IAC9C,CAAC,EACA,MAAM,CAAC,QAAiB;AACvB,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,UAAI,KAAK,EAAE,IAAI,GAAG,6BAA6B;AAC/C,aAAO;AAAA,QACL,GAAG,KAAK,UAAU,SAAS,IAAI,MAAM,MAAM,QAAQ,mBAAmB,OAAO,EAAE,CAAC,CAAC;AAAA;AAAA,MACnF;AAAA,IACF,CAAC;AAAA,EACL,CAAC;AAED,KAAG,GAAG,SAAS,MAAM;AACnB,QAAI,YAAa,SAAQ,KAAK,CAAC;AAAA,EACjC,CAAC;AACH;","names":[]}
@@ -7,7 +7,7 @@ import {
7
7
  createSubsystemLogger,
8
8
  createSupervisorIpcClient,
9
9
  defineSubsystem
10
- } from "../chunk-7Q7BEWM7.js";
10
+ } from "../chunk-HXTRXEFI.js";
11
11
  export {
12
12
  MalformedIpcFrameError,
13
13
  MalformedLeaseIpcFrameError,
@@ -0,0 +1,290 @@
1
+ import './gateway-handler-DCU6E0a2.js';
2
+ import { SuggestedNextOp, OperationDef, Resolution } from '@cleocode/contracts';
3
+ import '@cleocode/contracts/engine-result.js';
4
+ import { Source, DispatchResponse, DispatchResponseMeta, Middleware, Gateway, CanonicalDomain, Tier } from '@cleocode/contracts/gateway';
5
+
6
+ /**
7
+ * Dispatch-local metadata factory.
8
+ *
9
+ * Generates LAFS-conformant metadata for dispatch layer responses.
10
+ * Generates LAFS-conformant metadata for dispatch responses.
11
+ *
12
+ * @task T4772
13
+ */
14
+
15
+ /**
16
+ * Create metadata for a dispatch response.
17
+ *
18
+ * @param gateway - Gateway name (e.g., 'query', 'mutate')
19
+ * @param domain - Domain name (e.g., 'tasks', 'session')
20
+ * @param operation - Operation name (e.g., 'show', 'list')
21
+ * @param startTime - Timestamp from Date.now() at start of request
22
+ * @param source - Where the request originated
23
+ * @param requestId - Optional pre-generated request ID
24
+ * @param sessionId - Optional session ID to include in metadata
25
+ * @param originSessionId - Optional root workflow/saga session ID
26
+ * @param executionSessionId - Optional execution-attempt session ID
27
+ * @returns Metadata conforming to DispatchResponse['meta']
28
+ *
29
+ * @task T4772
30
+ * @task T4959
31
+ */
32
+ declare function createDispatchMeta(gateway: string, domain: string, operation: string, startTime: number, source?: Source, requestId?: string, sessionId?: string | null, originSessionId?: string | null, executionSessionId?: string | null): DispatchResponse['meta'];
33
+
34
+ /**
35
+ * nexus-decorator — stamps `meta._nexus` on every nexus-domain dispatch response.
36
+ *
37
+ * Wave 2 of the Nexus Restructure (T9146). Reads `getNexusDescriptor(opId)` from
38
+ * the W1 SSoT (`NEXUS_SCOPE_MAP`) and injects the namespaced `_nexus` block into
39
+ * `DispatchResponse['meta']`.
40
+ *
41
+ * Usage:
42
+ * ```ts
43
+ * const decorated = stampNexusMeta(response, operation, params);
44
+ * ```
45
+ *
46
+ * The `suggestedNext` field uses a structured form (not literal display strings).
47
+ * Display strings are derived by `formatSuggestedNext()` for human/markdown renderers.
48
+ *
49
+ * Typed-registry gate: `validateSuggestedNext()` fails the build (throws at import-time
50
+ * in test mode) if any `suggestedNext.op` is absent from `NEXUS_SCOPE_MAP`.
51
+ *
52
+ * @remarks
53
+ * Relocated from `packages/cleo/src/dispatch/nexus-decorator.ts` into
54
+ * `@cleocode/runtime/gateway` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION) so the
55
+ * nexus domain handler can import it from the runtime layer rather than a
56
+ * cleo-internal path. The module is pure (`@cleocode/contracts` only). A thin
57
+ * re-export shim remains at the old path for the renderer / CLI import sites.
58
+ *
59
+ * @task T9146
60
+ * @task T11455
61
+ * @module runtime/gateway/nexus-decorator
62
+ */
63
+
64
+ /**
65
+ * Assert that every `suggestedNext.op` in a list resolves to a known
66
+ * NEXUS_SCOPE_MAP entry.
67
+ *
68
+ * Throws `TypeError` at runtime (caught by tests and CI) if an unknown op
69
+ * is referenced — acting as a build-time gate when imported in test suites.
70
+ *
71
+ * @throws {TypeError} if any `op` is absent from `NEXUS_SCOPE_MAP`
72
+ * @task T9146
73
+ */
74
+ declare function validateSuggestedNext(suggestions: ReadonlyArray<SuggestedNextOp>): void;
75
+ /**
76
+ * Derive a human-readable display string from a {@link SuggestedNextOp}.
77
+ *
78
+ * Example: `"cleo nexus context --project-id myproj (read-only, no confirmation needed)"`
79
+ */
80
+ declare function formatSuggestedNext(s: SuggestedNextOp): string;
81
+ /**
82
+ * Stamp `meta._nexus` onto a nexus-domain {@link DispatchResponse}.
83
+ *
84
+ * Call this after every nexus handler produces its `DispatchResponse`. The
85
+ * function is a pure transformer — it returns a new object with `meta._nexus`
86
+ * merged in.
87
+ *
88
+ * @param response - The original dispatch response from the nexus handler.
89
+ * @param operation - The nexus operation key (must be a `keyof NexusOps`).
90
+ * @param params - Raw params passed to the handler (used for binding-source resolution).
91
+ * @param isTopLevel - Whether this is a top-level CLI invocation (not a sub-call).
92
+ * @returns A new `DispatchResponse` with `meta._nexus` populated.
93
+ *
94
+ * @task T9146
95
+ */
96
+ declare function stampNexusMeta(response: DispatchResponse, operation: string, params: Record<string, unknown>, isTopLevel?: boolean): DispatchResponse;
97
+ /**
98
+ * Pick the decorator-stamped fields (`_nexus`, `deprecated`) from a dispatch
99
+ * response's `meta` so they can be forwarded via `cliOutput`'s `extensions`
100
+ * option into the emitted LAFS envelope.
101
+ *
102
+ * Without this, `cliOutput(response.data, ...)` discards `response.meta._nexus`
103
+ * + `response.meta.deprecated` (T9393 defect). Canonical CLI meta fields
104
+ * (`operation`, `requestId`, `timestamp`) are intentionally NOT forwarded —
105
+ * those are produced by {@link createCliMeta} on the CLI side.
106
+ *
107
+ * @task T9393
108
+ */
109
+ declare function pickDecoratorMetaExtensions(responseMeta: DispatchResponseMeta | undefined): Record<string, unknown>;
110
+ /**
111
+ * Build CLI envelope extensions for nexus commands that bypass the dispatcher
112
+ * (e.g. `cleo nexus status` SSoT-EXEMPT path). Runs the same {@link stampNexusMeta}
113
+ * logic against a synthetic response so the resulting envelope still carries
114
+ * `meta._nexus` (and `meta.deprecated` for alias shims).
115
+ *
116
+ * Use this only where the command does NOT call `dispatchRaw`. When you have a
117
+ * real dispatch response, use {@link pickDecoratorMetaExtensions} on
118
+ * `response.meta` instead — that path already ran the decorator.
119
+ *
120
+ * @task T9393
121
+ */
122
+ declare function buildNexusMetaExtensions(operation: string, params?: Record<string, unknown>): Record<string, unknown>;
123
+
124
+ /**
125
+ * Gateway-level path constants shared by domain handlers.
126
+ *
127
+ * @remarks
128
+ * The `orchestrate` and `admin` (smoke-provider) domain handlers join a handful
129
+ * of well-known `.cleo/` path segments when locating workflow definitions and
130
+ * the BRAIN database. Those constants were previously defined in
131
+ * `packages/cleo/src/cli/paths.ts` (a CLI-internal leaf), which coupled the
132
+ * handler subgraph to `@cleocode/cleo`.
133
+ *
134
+ * To let `@cleocode/runtime` assemble the handler map WITHOUT importing
135
+ * `@cleocode/cleo` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION), the constants the
136
+ * handlers actually consume are hosted here as the canonical source. The
137
+ * CLI-side `cli/paths.ts` re-exports them so the rest of the CLI (backup /
138
+ * restore / doctor) keeps importing from its established surface — there is a
139
+ * single definition, no drift.
140
+ *
141
+ * @task T090
142
+ * @task T11455
143
+ */
144
+ /** Name of the project-local CLEO data directory (`.cleo`). */
145
+ declare const CLEO_DIR_NAME: ".cleo";
146
+ /** Subdirectory under `.cleo/` that stores CANT workflow definitions. */
147
+ declare const WORKFLOWS_SUBDIR: "workflows";
148
+ /** Project-local SQLite database filename for cognitive memory (BRAIN). */
149
+ declare const BRAIN_DB_FILENAME: "brain.db";
150
+
151
+ /**
152
+ * Unified CQRS Dispatch Layer -- Middleware Pipeline
153
+ *
154
+ * Provides compose() to chain multiple Middleware functions together
155
+ * into a single executable pipeline.
156
+ *
157
+ * @epic T4820
158
+ * @task T4815
159
+ */
160
+
161
+ /**
162
+ * Composes an array of Middleware functions into a single Middleware function.
163
+ * Execution flows through the array from first to last, and returns bubble
164
+ * back up from last to first.
165
+ *
166
+ * @remarks
167
+ * Uses an index-tracked dispatch function to prevent `next()` from being
168
+ * called multiple times within a single middleware. If the array is empty,
169
+ * a passthrough middleware that immediately calls `next()` is returned.
170
+ *
171
+ * @param middlewares - Array of middleware functions to chain
172
+ * @returns A single composed Middleware function
173
+ *
174
+ * @example
175
+ * ```typescript
176
+ * import { compose } from './pipeline.js';
177
+ *
178
+ * const pipeline = compose([sanitizer, rateLimiter, protocolEnforcement]);
179
+ * const response = await pipeline(request, handler);
180
+ * ```
181
+ */
182
+ declare function compose(middlewares: Middleware[]): Middleware;
183
+
184
+ /**
185
+ * Unified CQRS Dispatch Layer -- Operation Registry (shim)
186
+ *
187
+ * The `OPERATIONS` data array was relocated to
188
+ * `@cleocode/contracts/dispatch/operations-registry` in T10061 / T9833b
189
+ * (E-CLI-BOUNDARY · Saga T9831 SG-ARCH-SOLID). This file is now a thin
190
+ * re-export shim that:
191
+ *
192
+ * 1. Re-exports `OPERATIONS` from contracts so every downstream consumer
193
+ * that already imports `{ OPERATIONS }` from this path continues to
194
+ * compile unchanged.
195
+ * 2. Keeps the pure utility / derivation functions (`resolve`,
196
+ * `validateRequiredParams`, `getByDomain`, etc.) that operate on
197
+ * the data and are rightly colocated with the CLI package.
198
+ *
199
+ * @epic T4820
200
+ * @task T4814, T5241, T5615, T10061
201
+ */
202
+
203
+ /** The single source of truth for all operations in CLEO (data lives in @cleocode/contracts). */
204
+ declare const OPERATIONS: OperationDef[];
205
+ /**
206
+ * Derive a gateway operation matrix from the registry.
207
+ *
208
+ * Returns `Record<string, string[]>` containing:
209
+ * - All canonical domains with their operations
210
+ *
211
+ * This is the SINGLE derivation point — gateways use this instead of
212
+ * maintaining independent operation lists.
213
+ */
214
+ declare function deriveGatewayMatrix(gateway: Gateway): Record<string, string[]>;
215
+ /**
216
+ * Get all accepted domain names for a gateway (canonical only).
217
+ */
218
+ declare function getGatewayDomains(gateway: Gateway): string[];
219
+ /**
220
+ * Resolves a domain + operation to its registered definition.
221
+ */
222
+ declare function resolve(gateway: Gateway, domain: string, operation: string): Resolution | undefined;
223
+ /**
224
+ * Infer the CQRS {@link Gateway} for a `(domain, operation)` pair from the
225
+ * registry, without the caller naming `query`/`mutate` up front.
226
+ *
227
+ * This backs the versioned `/v1/<domain>/<operation>` REST facade (T11919),
228
+ * where — unlike the legacy `/<gateway>/<domain>/<operation>` form — the client
229
+ * does not spell the gateway segment: the registry is the single source of truth
230
+ * for whether an operation is a read (`query`) or a write (`mutate`). Each
231
+ * `(domain, operation)` pair maps to exactly one gateway in {@link OPERATIONS},
232
+ * so the inference is unambiguous.
233
+ *
234
+ * @param domain - The canonical domain segment (e.g. `'tasks'`).
235
+ * @param operation - The operation segment (e.g. `'show'`).
236
+ * @returns The owning gateway, or `undefined` when no registered operation
237
+ * matches the pair (the wire edge then renders a `404`).
238
+ */
239
+ declare function inferGateway(domain: string, operation: string): Gateway | undefined;
240
+ /**
241
+ * The result of resolving a streaming route: the owning gateway plus the matched
242
+ * {@link OperationDef} (so the caller has the op's tier/params on hand without a
243
+ * second lookup).
244
+ */
245
+ interface StreamResolution {
246
+ /** The CQRS gateway the streaming op is registered under. */
247
+ gateway: Gateway;
248
+ /** The matched streaming operation definition. */
249
+ def: OperationDef;
250
+ }
251
+ /**
252
+ * Resolve a `(domain, operation)` pair to a registered **streaming** operation.
253
+ *
254
+ * Backs the `GET /v1/<domain>/<operation>` SSE route (T11921): the listener only
255
+ * opens a `text/event-stream` for a `(domain, operation)` pair that is BOTH
256
+ * registered AND explicitly flagged `streaming: true` in {@link OPERATIONS}. A
257
+ * unary-only op (or an unknown pair) resolves to `undefined`, so the listener
258
+ * never streams an operation that was not declared streamable — a GET to a
259
+ * unary op stays a `405` (method-not-allowed) rather than silently opening a
260
+ * never-ending stream.
261
+ *
262
+ * @param domain - The canonical domain segment (e.g. `'orchestrate'`).
263
+ * @param operation - The operation segment (e.g. `'events'`).
264
+ * @returns The streaming resolution, or `undefined` when no registered op
265
+ * matches the pair OR the matched op is not flagged `streaming: true`.
266
+ */
267
+ declare function resolveStreamRoute(domain: string, operation: string): StreamResolution | undefined;
268
+ /**
269
+ * Validates that all required parameters are present in the request.
270
+ * Returns an array of missing parameter keys.
271
+ */
272
+ declare function validateRequiredParams(def: OperationDef, params?: Record<string, unknown>): string[];
273
+ /** Get all operations for a specific canonical domain. */
274
+ declare function getByDomain(domain: CanonicalDomain): OperationDef[];
275
+ /** Get all operations for a specific gateway. */
276
+ declare function getByGateway(gateway: Gateway): OperationDef[];
277
+ /** Get all operations available at or below a specific tier. */
278
+ declare function getByTier(tier: Tier): OperationDef[];
279
+ /** Get a list of canonical domains that actually have operations registered. */
280
+ declare function getActiveDomains(): CanonicalDomain[];
281
+ /**
282
+ * Returns summary counts of operations for module validation.
283
+ */
284
+ declare function getCounts(): {
285
+ query: number;
286
+ mutate: number;
287
+ total: number;
288
+ };
289
+
290
+ export { BRAIN_DB_FILENAME as B, CLEO_DIR_NAME as C, OPERATIONS as O, type StreamResolution as S, WORKFLOWS_SUBDIR as W, createDispatchMeta as a, buildNexusMetaExtensions as b, compose as c, deriveGatewayMatrix as d, getByDomain as e, formatSuggestedNext as f, getActiveDomains as g, getByGateway as h, getByTier as i, getCounts as j, getGatewayDomains as k, inferGateway as l, resolveStreamRoute as m, validateSuggestedNext as n, pickDecoratorMetaExtensions as p, resolve as r, stampNexusMeta as s, validateRequiredParams as v };
@@ -0,0 +1,5 @@
1
+ export { D as Dispatcher, a as DispatcherConfig, G as GatewayHandler, c as createGatewayHandler } from '../gateway-handler-DCU6E0a2.js';
2
+ export { OperationDef, Resolution } from '@cleocode/contracts';
3
+ export { engineSuccess } from '@cleocode/contracts/engine-result.js';
4
+ export { B as BRAIN_DB_FILENAME, C as CLEO_DIR_NAME, O as OPERATIONS, W as WORKFLOWS_SUBDIR, b as buildNexusMetaExtensions, c as compose, a as createDispatchMeta, d as deriveGatewayMatrix, f as formatSuggestedNext, g as getActiveDomains, e as getByDomain, h as getByGateway, i as getByTier, j as getCounts, k as getGatewayDomains, p as pickDecoratorMetaExtensions, r as resolve, s as stampNexusMeta, v as validateRequiredParams, n as validateSuggestedNext } from '../dispatch-BWjVeeMg.js';
5
+ import '@cleocode/contracts/gateway';
@@ -0,0 +1,53 @@
1
+ import {
2
+ BRAIN_DB_FILENAME,
3
+ CLEO_DIR_NAME,
4
+ Dispatcher,
5
+ WORKFLOWS_SUBDIR,
6
+ buildNexusMetaExtensions,
7
+ compose,
8
+ createDispatchMeta,
9
+ createGatewayHandler,
10
+ engineSuccess,
11
+ formatSuggestedNext,
12
+ pickDecoratorMetaExtensions,
13
+ stampNexusMeta,
14
+ validateSuggestedNext
15
+ } from "../chunk-PDZ5T4LO.js";
16
+ import {
17
+ OPERATIONS,
18
+ deriveGatewayMatrix,
19
+ getActiveDomains,
20
+ getByDomain,
21
+ getByGateway,
22
+ getByTier,
23
+ getCounts,
24
+ getGatewayDomains,
25
+ resolve,
26
+ validateRequiredParams
27
+ } from "../chunk-4PUSKGDO.js";
28
+ export {
29
+ BRAIN_DB_FILENAME,
30
+ CLEO_DIR_NAME,
31
+ Dispatcher,
32
+ OPERATIONS,
33
+ WORKFLOWS_SUBDIR,
34
+ buildNexusMetaExtensions,
35
+ compose,
36
+ createDispatchMeta,
37
+ createGatewayHandler,
38
+ deriveGatewayMatrix,
39
+ engineSuccess,
40
+ formatSuggestedNext,
41
+ getActiveDomains,
42
+ getByDomain,
43
+ getByGateway,
44
+ getByTier,
45
+ getCounts,
46
+ getGatewayDomains,
47
+ pickDecoratorMetaExtensions,
48
+ resolve,
49
+ stampNexusMeta,
50
+ validateRequiredParams,
51
+ validateSuggestedNext
52
+ };
53
+ //# sourceMappingURL=dispatch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}