nexus-agents 2.71.0 → 2.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adaptive-memory-MKSYEBST.js → adaptive-memory-UPE76IP6.js} +5 -5
- package/dist/{chunk-DWLATKBK.js → child-mcp-config-5HRJGLCR.js} +6 -4
- package/dist/child-mcp-config-5HRJGLCR.js.map +1 -0
- package/dist/{chunk-7LHQBMBM.js → chunk-2JMUX5UA.js} +25 -12
- package/dist/{chunk-7LHQBMBM.js.map → chunk-2JMUX5UA.js.map} +1 -1
- package/dist/{chunk-ZPPX2K57.js → chunk-2KB63QGE.js} +2 -2
- package/dist/{chunk-L2LQ3TSV.js → chunk-2MD5MWCK.js} +2 -2
- package/dist/{chunk-ANC3HU6F.js → chunk-345KMHWH.js} +6 -6
- package/dist/chunk-345KMHWH.js.map +1 -0
- package/dist/{chunk-NER7H3RJ.js → chunk-3FIDMWFC.js} +2 -2
- package/dist/{chunk-AGVLFRN7.js → chunk-3HR6UJ2E.js} +2269 -7188
- package/dist/chunk-3HR6UJ2E.js.map +1 -0
- package/dist/{chunk-POQQ7A5E.js → chunk-53K3KEKT.js} +51 -707
- package/dist/chunk-53K3KEKT.js.map +1 -0
- package/dist/chunk-5MHIWRKB.js +691 -0
- package/dist/chunk-5MHIWRKB.js.map +1 -0
- package/dist/{chunk-VGZJIR22.js → chunk-5WQ3SRSE.js} +2 -2
- package/dist/{chunk-TOYPY5XA.js → chunk-A35XORXU.js} +73 -10
- package/dist/chunk-A35XORXU.js.map +1 -0
- package/dist/chunk-BVETPIOQ.js +556 -0
- package/dist/chunk-BVETPIOQ.js.map +1 -0
- package/dist/{chunk-OF7CYMMA.js → chunk-DA5UDQYW.js} +2 -2
- package/dist/{chunk-XATH462F.js → chunk-ES6GFP35.js} +186 -34
- package/dist/chunk-ES6GFP35.js.map +1 -0
- package/dist/chunk-GOT7OAL5.js +59 -0
- package/dist/chunk-GOT7OAL5.js.map +1 -0
- package/dist/{chunk-LJT65EA7.js → chunk-I7ORMAO7.js} +2 -2
- package/dist/{chunk-LMRKHQG5.js → chunk-L6N2S3UB.js} +2 -2
- package/dist/{chunk-7OBFO4GF.js → chunk-O4KUCF5S.js} +125 -40
- package/dist/chunk-O4KUCF5S.js.map +1 -0
- package/dist/chunk-P5OFZWDW.js +303 -0
- package/dist/chunk-P5OFZWDW.js.map +1 -0
- package/dist/{chunk-MJHOSM5U.js → chunk-QECRZ3YA.js} +2 -2
- package/dist/{chunk-WYSHXPKK.js → chunk-QL4HCYRD.js} +4 -44
- package/dist/chunk-QL4HCYRD.js.map +1 -0
- package/dist/{chunk-E66KFRSJ.js → chunk-TF3GROMO.js} +2 -2
- package/dist/{chunk-U3HZQTUF.js → chunk-TQFRPFMG.js} +2 -2
- package/dist/{chunk-KJCSRP34.js → chunk-V7ATY4BG.js} +3 -3
- package/dist/{chunk-32RIOULO.js → chunk-VPC3YNFR.js} +2 -2
- package/dist/{chunk-3BKVYSY6.js → chunk-VTVKC4FS.js} +4 -4
- package/dist/{chunk-U6BK5DQU.js → chunk-XHVDKY3X.js} +315 -31
- package/dist/chunk-XHVDKY3X.js.map +1 -0
- package/dist/cli-circuit-breaker-GFF2RLBZ.js +14 -0
- package/dist/cli.d.ts +3 -1
- package/dist/cli.js +1038 -1581
- package/dist/cli.js.map +1 -1
- package/dist/{composite-router-AYVJPIOS.js → composite-router-33F3F74I.js} +4 -4
- package/dist/{consensus-vote-EXWACBMR.js → consensus-vote-5V4KVHBE.js} +12 -11
- package/dist/doctor-deep-AHDTNURD.js +13 -0
- package/dist/expert-bridge-DMDHHDEU.js +11 -0
- package/dist/factory-FVD7PZ6S.js +15 -0
- package/dist/{factory-KMBWFIX2.js → factory-VQS3HJ7V.js} +6 -6
- package/dist/index.d.ts +358 -3357
- package/dist/index.js +70 -807
- package/dist/index.js.map +1 -1
- package/dist/init-opencode-EIOIPVWL.js +158 -0
- package/dist/init-opencode-EIOIPVWL.js.map +1 -0
- package/dist/issue-triage-HJUJWGAD.js +16 -0
- package/dist/{learning-persistence-FILWP3IR.js → learning-persistence-N6ILD2HX.js} +3 -3
- package/dist/{mobimem-77W5ED4Z.js → mobimem-BOJFXQ7B.js} +4 -4
- package/dist/{nexus-data-dir-M6DYKIHJ.js → nexus-data-dir-77UO7N6J.js} +2 -2
- package/dist/{registry-command-BBLIXULQ.js → registry-command-NCWUJKAF.js} +4 -4
- package/dist/{repo-security-plan-7SNM7JQN.js → repo-security-plan-3J45VAD6.js} +5 -5
- package/dist/research-helpers-synthesize-UGQHZZJN.js +12 -0
- package/dist/{routing-memory-DCIZEEVC.js → routing-memory-NO7QEH7T.js} +4 -4
- package/dist/{session-memory-5TSAASQW.js → session-memory-DOXLEWEU.js} +5 -5
- package/dist/{setup-command-5VGIQETA.js → setup-command-DVEBFKR2.js} +10 -10
- package/dist/setup-config-E3JZYSLR.js +11 -0
- package/dist/{setup-custom-api-IQX3GD2D.js → setup-custom-api-DHJ5DRH2.js} +6 -6
- package/dist/{weather-report-NETGWTJX.js → weather-report-FNN4OX3N.js} +4 -4
- package/package.json +1 -1
- package/dist/chunk-7OBFO4GF.js.map +0 -1
- package/dist/chunk-AGVLFRN7.js.map +0 -1
- package/dist/chunk-ANC3HU6F.js.map +0 -1
- package/dist/chunk-DWLATKBK.js.map +0 -1
- package/dist/chunk-FDNWRZNJ.js +0 -22
- package/dist/chunk-FDNWRZNJ.js.map +0 -1
- package/dist/chunk-POQQ7A5E.js.map +0 -1
- package/dist/chunk-TOYPY5XA.js.map +0 -1
- package/dist/chunk-U6BK5DQU.js.map +0 -1
- package/dist/chunk-WYSHXPKK.js.map +0 -1
- package/dist/chunk-XATH462F.js.map +0 -1
- package/dist/cli-circuit-breaker-2CJ6NV52.js +0 -14
- package/dist/doctor-deep-BJFDBGPO.js +0 -13
- package/dist/expert-bridge-75WNNWI4.js +0 -11
- package/dist/factory-H5BYL4V5.js +0 -15
- package/dist/issue-triage-4SEP4WID.js +0 -16
- package/dist/mcp-config-OCWIXE2Y.js +0 -13
- package/dist/research-helpers-synthesize-7CI2FJE5.js +0 -12
- package/dist/setup-config-EA5RDIO2.js +0 -11
- package/dist/weather-report-NETGWTJX.js.map +0 -1
- /package/dist/{adaptive-memory-MKSYEBST.js.map → adaptive-memory-UPE76IP6.js.map} +0 -0
- /package/dist/{chunk-ZPPX2K57.js.map → chunk-2KB63QGE.js.map} +0 -0
- /package/dist/{chunk-L2LQ3TSV.js.map → chunk-2MD5MWCK.js.map} +0 -0
- /package/dist/{chunk-NER7H3RJ.js.map → chunk-3FIDMWFC.js.map} +0 -0
- /package/dist/{chunk-VGZJIR22.js.map → chunk-5WQ3SRSE.js.map} +0 -0
- /package/dist/{chunk-OF7CYMMA.js.map → chunk-DA5UDQYW.js.map} +0 -0
- /package/dist/{chunk-LJT65EA7.js.map → chunk-I7ORMAO7.js.map} +0 -0
- /package/dist/{chunk-LMRKHQG5.js.map → chunk-L6N2S3UB.js.map} +0 -0
- /package/dist/{chunk-MJHOSM5U.js.map → chunk-QECRZ3YA.js.map} +0 -0
- /package/dist/{chunk-E66KFRSJ.js.map → chunk-TF3GROMO.js.map} +0 -0
- /package/dist/{chunk-U3HZQTUF.js.map → chunk-TQFRPFMG.js.map} +0 -0
- /package/dist/{chunk-KJCSRP34.js.map → chunk-V7ATY4BG.js.map} +0 -0
- /package/dist/{chunk-32RIOULO.js.map → chunk-VPC3YNFR.js.map} +0 -0
- /package/dist/{chunk-3BKVYSY6.js.map → chunk-VTVKC4FS.js.map} +0 -0
- /package/dist/{cli-circuit-breaker-2CJ6NV52.js.map → cli-circuit-breaker-GFF2RLBZ.js.map} +0 -0
- /package/dist/{composite-router-AYVJPIOS.js.map → composite-router-33F3F74I.js.map} +0 -0
- /package/dist/{consensus-vote-EXWACBMR.js.map → consensus-vote-5V4KVHBE.js.map} +0 -0
- /package/dist/{doctor-deep-BJFDBGPO.js.map → doctor-deep-AHDTNURD.js.map} +0 -0
- /package/dist/{expert-bridge-75WNNWI4.js.map → expert-bridge-DMDHHDEU.js.map} +0 -0
- /package/dist/{factory-H5BYL4V5.js.map → factory-FVD7PZ6S.js.map} +0 -0
- /package/dist/{factory-KMBWFIX2.js.map → factory-VQS3HJ7V.js.map} +0 -0
- /package/dist/{issue-triage-4SEP4WID.js.map → issue-triage-HJUJWGAD.js.map} +0 -0
- /package/dist/{learning-persistence-FILWP3IR.js.map → learning-persistence-N6ILD2HX.js.map} +0 -0
- /package/dist/{mcp-config-OCWIXE2Y.js.map → mobimem-BOJFXQ7B.js.map} +0 -0
- /package/dist/{mobimem-77W5ED4Z.js.map → nexus-data-dir-77UO7N6J.js.map} +0 -0
- /package/dist/{registry-command-BBLIXULQ.js.map → registry-command-NCWUJKAF.js.map} +0 -0
- /package/dist/{nexus-data-dir-M6DYKIHJ.js.map → repo-security-plan-3J45VAD6.js.map} +0 -0
- /package/dist/{repo-security-plan-7SNM7JQN.js.map → research-helpers-synthesize-UGQHZZJN.js.map} +0 -0
- /package/dist/{research-helpers-synthesize-7CI2FJE5.js.map → routing-memory-NO7QEH7T.js.map} +0 -0
- /package/dist/{routing-memory-DCIZEEVC.js.map → session-memory-DOXLEWEU.js.map} +0 -0
- /package/dist/{session-memory-5TSAASQW.js.map → setup-command-DVEBFKR2.js.map} +0 -0
- /package/dist/{setup-command-5VGIQETA.js.map → setup-config-E3JZYSLR.js.map} +0 -0
- /package/dist/{setup-custom-api-IQX3GD2D.js.map → setup-custom-api-DHJ5DRH2.js.map} +0 -0
- /package/dist/{setup-config-EA5RDIO2.js.map → weather-report-FNN4OX3N.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts","../src/config/schemas-core.ts","../src/config/schemas-expert.ts","../src/config/schemas-security.ts","../src/config/schemas.ts","../src/config/schemas-observability.ts","../src/config/schemas-skills.ts","../src/config/schemas-sica.ts","../src/config/schemas-gateway.ts","../src/config/schemas-routing.ts","../src/config/env-schema.ts","../src/config/model-availability.ts","../src/config/routing-config-adapter.ts","../src/config/config-manager.ts","../src/config/config-loader.ts","../src/cli/setup-data-dir.ts","../src/cli/doctor.ts","../src/mcp/server.ts","../src/mcp/task-store.ts","../src/cli/doctor-formatting.ts"],"sourcesContent":["/**\n * nexus-agents - Version constant\n *\n * Injected at build time via tsup define from package.json.\n * Do NOT edit this value manually — it is replaced during build.\n */\n\ndeclare const __NEXUS_VERSION__: string;\n\nexport const VERSION: string = typeof __NEXUS_VERSION__ !== 'undefined' ? __NEXUS_VERSION__ : 'dev';\n","/**\n * nexus-agents/config - Core Configuration Schemas\n *\n * Basic infrastructure schemas: Logging, Provider, Model configuration.\n */\n\nimport { z } from 'zod';\n\n/**\n * Logging configuration schema.\n */\nexport const LoggingConfigSchema = z.object({\n level: z.enum(['debug', 'info', 'warn', 'error']).default('info'),\n format: z.enum(['json', 'pretty']).default('json'),\n // Default to stderr: MCP stdio transport reserves stdout for JSON-RPC frames.\n destination: z.enum(['stdout', 'stderr', 'file']).default('stderr'),\n filePath: z.string().optional(),\n});\n\nexport type LoggingConfig = z.infer<typeof LoggingConfigSchema>;\n\n/**\n * Provider configuration schema.\n */\nexport const ProviderConfigSchema = z.object({\n apiKey: z.string().optional(),\n baseUrl: z.url().optional(),\n timeout: z.number().positive().default(30000),\n maxRetries: z.number().nonnegative().default(3),\n});\n\nexport type ProviderConfig = z.infer<typeof ProviderConfigSchema>;\n\n/**\n * Model tier configuration.\n */\nexport const ModelTiersSchema = z.object({\n fast: z.array(z.string()).min(1),\n balanced: z.array(z.string()).min(1),\n powerful: z.array(z.string()).min(1),\n});\n\nexport type ModelTiers = z.infer<typeof ModelTiersSchema>;\n\n/**\n * Model configuration schema.\n */\nexport const ModelConfigSchema = z.object({\n default: z.string(),\n tiers: ModelTiersSchema,\n providers: z.record(z.string(), ProviderConfigSchema).optional(),\n});\n\nexport type ModelConfig = z.infer<typeof ModelConfigSchema>;\n\n/**\n * Workflow configuration schema.\n */\nexport const WorkflowConfigSchema = z.object({\n templatesDir: z.string().default('./workflows'),\n timeout: z.number().positive().default(300000),\n maxParallel: z.number().positive().default(5),\n});\n\nexport type WorkflowConfig = z.infer<typeof WorkflowConfigSchema>;\n","/**\n * nexus-agents/config - Expert Configuration Schemas\n *\n * Schemas for expert definitions, custom experts, and related constants.\n */\n\nimport { z } from 'zod';\n\n/**\n * Valid model tiers for custom experts.\n */\nexport const VALID_EXPERT_TIERS = ['fast', 'balanced', 'powerful'] as const;\nexport type ExpertTier = (typeof VALID_EXPERT_TIERS)[number];\n\n/**\n * Valid task domains for custom experts.\n */\nexport const VALID_EXPERT_DOMAINS = [\n 'code',\n 'security',\n 'architecture',\n 'documentation',\n 'testing',\n 'general',\n] as const;\nexport type ExpertDomain = (typeof VALID_EXPERT_DOMAINS)[number];\n\n/**\n * Maximum system prompt length (4000 characters).\n * This matches typical LLM system prompt limits while allowing detailed instructions.\n */\nexport const MAX_SYSTEM_PROMPT_LENGTH = 4000;\n\n/**\n * Custom expert definition schema from YAML config.\n *\n * Defines a user-configurable expert with:\n * - systemPrompt: The expert's persona and instructions (max 4000 chars)\n * - tier: Model tier for routing (fast, balanced, powerful)\n * - domain: Primary domain of expertise\n * - capabilities: What this expert can do\n * - temperature: Model temperature (0-1)\n * - tools: Optional tool restrictions\n *\n * (Source: Issue #300)\n */\nexport const CustomExpertDefinitionSchema = z.object({\n /** System prompt defining the expert's persona (max 4000 characters) */\n systemPrompt: z\n .string()\n .min(1, 'System prompt is required')\n .max(\n MAX_SYSTEM_PROMPT_LENGTH,\n `System prompt must be at most ${String(MAX_SYSTEM_PROMPT_LENGTH)} characters`\n ),\n\n /** Model tier for routing */\n tier: z\n .enum(VALID_EXPERT_TIERS, {\n error: `Invalid tier. Valid options: ${VALID_EXPERT_TIERS.join(', ')}`,\n })\n .default('balanced'),\n\n /** Primary domain of expertise */\n domain: z\n .enum(VALID_EXPERT_DOMAINS, {\n error: `Invalid domain. Valid options: ${VALID_EXPERT_DOMAINS.join(', ')}`,\n })\n .default('general'),\n\n /** Secondary domains (optional) */\n secondaryDomains: z.array(z.enum(VALID_EXPERT_DOMAINS)).optional(),\n\n /** Expert capabilities */\n capabilities: z\n .array(z.string().min(1))\n .min(1, 'At least one capability is required')\n .default(['task_execution']),\n\n /** Model temperature (0-1) */\n temperature: z.number().min(0).max(1).default(0.3),\n\n /** Allowed tools (optional, unrestricted if not specified) */\n tools: z.array(z.string()).optional(),\n\n /** Human-readable description */\n description: z.string().optional(),\n\n /** Weight for expert selection scoring (0-1) */\n weight: z.number().min(0).max(1).default(1.0),\n\n /** Whether this expert is currently available */\n available: z.boolean().default(true),\n});\n\nexport type CustomExpertDefinition = z.infer<typeof CustomExpertDefinitionSchema>;\n\n/**\n * Legacy expert definition schema (for backwards compatibility).\n * Use CustomExpertDefinitionSchema for new implementations.\n */\nexport const ExpertDefinitionSchema = z.object({\n prompt: z.string().min(1),\n tier: z.enum(['fast', 'balanced', 'powerful']).default('balanced'),\n temperature: z.number().min(0).max(1).default(0.3),\n tools: z.array(z.string()).optional(),\n});\n\nexport type ExpertDefinition = z.infer<typeof ExpertDefinitionSchema>;\n\n/**\n * Expert configuration schema.\n */\nexport const ExpertConfigSchema = z.object({\n /** Enable built-in experts */\n builtin: z.boolean().default(true),\n\n /** Custom expert definitions keyed by expert ID */\n custom: z\n .record(\n z.string().regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Expert ID must start with a letter and contain only lowercase letters, numbers, and underscores',\n }),\n CustomExpertDefinitionSchema\n )\n .optional(),\n});\n\nexport type ExpertConfig = z.infer<typeof ExpertConfigSchema>;\n","/**\n * nexus-agents/config - Security Configuration Schemas\n *\n * Schemas for security, policy, sandbox, timeout, and rate limiting.\n */\n\nimport { z } from 'zod';\n\n/**\n * Policy configuration schema.\n *\n * Controls authorization behavior for tool operations.\n * - defaultMode: Whether operations default to read-only or read-write\n * - policyMode: Whether to enforce denials or just warn (for migration)\n *\n * (Source: OWASP ASVS 4.0, Authorization Controls)\n */\nexport const PolicyConfigSchema = z.object({\n /** Default execution mode for tool operations (default: 'read-only') */\n defaultMode: z.enum(['read-only', 'read-write']).default('read-only'),\n /** Policy enforcement mode (default: 'enforce') */\n policyMode: z.enum(['enforce', 'warn']).default('enforce'),\n});\n\nexport type PolicyConfig = z.infer<typeof PolicyConfigSchema>;\n\n/**\n * Sandbox configuration schema.\n *\n * Controls agent execution isolation.\n * - mode: 'none' (no isolation), 'policy' (allowlist enforcement), 'container' (Docker)\n * - fallbackToPolicy: Whether to fall back to policy mode if container unavailable\n *\n * (Source: Issue #175, ALIGNMENT_ROADMAP Phase 4)\n */\nexport const SandboxConfigSchema = z.object({\n /** Sandbox execution mode (default: 'policy') */\n mode: z.enum(['none', 'policy', 'container']).default('policy'),\n /** Fall back to policy mode if container mode unavailable (default: true) */\n fallbackToPolicy: z.boolean().default(true),\n /** Docker image to use in container mode (default: 'node:22-alpine') */\n dockerImage: z.string().optional(),\n /** Enable network access in container mode (default: false) */\n networkEnabled: z.boolean().default(false),\n});\n\nexport type SandboxConfig = z.infer<typeof SandboxConfigSchema>;\n\n/**\n * Timeout configuration schema.\n *\n * Controls timeout behavior for MCP operations to mitigate CVE-2026-0621.\n * - defaultTimeoutMs: Default timeout for operations\n * - maxTimeoutMs: Maximum allowed timeout\n * - enableLogging: Whether to log timeout events\n * - uriValidation: Whether to validate URIs against ReDoS patterns\n *\n * (Source: Issue #271, CVE-2026-0621 mitigation)\n */\nexport const TimeoutConfigSchema = z.object({\n /** Default timeout in milliseconds (default: 30000) */\n defaultTimeoutMs: z.number().positive().default(30000),\n /** Maximum timeout in milliseconds (default: 300000) */\n maxTimeoutMs: z.number().positive().default(300000),\n /** Whether to log timeout events (default: true) */\n enableLogging: z.boolean().default(true),\n /** Enable URI validation to prevent ReDoS (default: true) */\n uriValidation: z.boolean().default(true),\n /** Per-tool timeout overrides in milliseconds (Issue #657) */\n perToolTimeout: z.record(z.string(), z.number().positive().max(600000)).optional(),\n});\n\nexport type TimeoutConfig = z.infer<typeof TimeoutConfigSchema>;\n\n/**\n * Per-tool rate limit configuration.\n * Allows different limits for each tool category.\n *\n * (Source: Issue #274 Phase 2 - per-tool rate limits)\n */\nexport const ToolRateLimitSchema = z.object({\n /** Maximum tokens (burst capacity) */\n capacity: z.number().positive().default(10),\n /** Tokens refilled per interval */\n refillRate: z.number().positive().default(10),\n /** Refill interval in milliseconds (default: 60000 = 1 minute) */\n refillIntervalMs: z.number().positive().default(60000),\n});\n\nexport type ToolRateLimit = z.infer<typeof ToolRateLimitSchema>;\n\n/**\n * Default per-tool rate limits per Issue #274.\n */\nexport const DEFAULT_TOOL_RATE_LIMITS = {\n orchestrate: { capacity: 10, refillRate: 10, refillIntervalMs: 60000 },\n delegate: { capacity: 20, refillRate: 20, refillIntervalMs: 60000 },\n workflow: { capacity: 5, refillRate: 5, refillIntervalMs: 60000 },\n expert: { capacity: 30, refillRate: 30, refillIntervalMs: 60000 },\n} as const satisfies Record<string, ToolRateLimit>;\n\n/**\n * Tool categories for rate limiting.\n */\nexport type ToolCategory = keyof typeof DEFAULT_TOOL_RATE_LIMITS;\n\n/**\n * Security configuration schema.\n */\nexport const SecurityConfigSchema = z.object({\n allowedPaths: z.array(z.string()).default(['./']),\n blockedPatterns: z.array(z.string()).default([]),\n rateLimit: z\n .object({\n enabled: z.boolean().default(true),\n requestsPerMinute: z.number().positive().default(60),\n /** Per-tool rate limits (Issue #274 Phase 2) */\n perTool: z.record(z.string(), ToolRateLimitSchema).optional(),\n })\n .default(() => ({ enabled: true, requestsPerMinute: 60 })),\n secretsFile: z.string().optional(),\n /** Policy firewall configuration */\n policy: PolicyConfigSchema.optional(),\n /** Sandbox execution configuration (Issue #175) */\n sandbox: SandboxConfigSchema.optional(),\n /** Timeout configuration (Issue #271, CVE-2026-0621) */\n timeout: TimeoutConfigSchema.optional(),\n /** Tool allowlist — when set, only listed tools are registered (Issue #740) */\n toolAllowlist: z.array(z.string()).optional(),\n /** Audit logging configuration (Issue #740 Phase 2) */\n audit: z\n .object({\n /** Enable audit logging (default: true) */\n enabled: z.boolean().default(true),\n /** Log directory (default: ~/.nexus-agents/audit) */\n logDir: z.string().optional(),\n /** Minimum severity to log (default: 'info') */\n minSeverity: z.enum(['info', 'warning', 'critical']).default('info'),\n /** Enable tamper-evident hash chain (default: true) */\n enableHashChain: z.boolean().default(true),\n /** Maximum log file size in bytes (default: 10MB) */\n maxFileSizeBytes: z\n .number()\n .positive()\n .default(10 * 1024 * 1024),\n /** Maximum number of log files to retain (default: 10) */\n maxFiles: z.number().positive().default(10),\n })\n .optional(),\n /** Authentication configuration (Issue #739) */\n auth: z\n .object({\n /** Enable authentication for network-exposed transports (default: true) */\n enabled: z.boolean().default(true),\n /** Authentication method (default: 'token') */\n method: z.enum(['token', 'oauth2']).default('token'),\n /** Header name for bearer token (default: 'Authorization') */\n tokenHeader: z.string().default('Authorization'),\n /** Token file path (default: ~/.nexus-agents/auth/server-token) */\n tokenFile: z.string().optional(),\n })\n .optional(),\n});\n\nexport type SecurityConfig = z.infer<typeof SecurityConfigSchema>;\n\n/**\n * Authentication configuration type.\n * (Source: Issue #739 - enable MCP authentication by default)\n */\nexport type AuthConfig = NonNullable<SecurityConfig['auth']>;\n","/**\n * nexus-agents/config - Configuration Schemas\n *\n * Aggregation module that re-exports all configuration schemas.\n * Individual schema categories are organized in separate files:\n * - schemas-core.ts: Logging, Provider, Model, Workflow\n * - schemas-expert.ts: Expert definitions and constants\n * - schemas-security.ts: Security, Policy, Sandbox, Timeout, RateLimit\n * - schemas-observability.ts: EventBus, Observability\n */\n\nimport { z } from 'zod';\n\n// Re-export core schemas\nexport {\n LoggingConfigSchema,\n ProviderConfigSchema,\n ModelTiersSchema,\n ModelConfigSchema,\n WorkflowConfigSchema,\n} from './schemas-core.js';\n\nexport type {\n LoggingConfig,\n ProviderConfig,\n ModelTiers,\n ModelConfig,\n WorkflowConfig,\n} from './schemas-core.js';\n\n// Re-export expert schemas\nexport {\n VALID_EXPERT_TIERS,\n VALID_EXPERT_DOMAINS,\n MAX_SYSTEM_PROMPT_LENGTH,\n CustomExpertDefinitionSchema,\n ExpertDefinitionSchema,\n ExpertConfigSchema,\n} from './schemas-expert.js';\n\nexport type {\n ExpertTier,\n ExpertDomain,\n CustomExpertDefinition,\n ExpertDefinition,\n ExpertConfig,\n} from './schemas-expert.js';\n\n// Re-export security schemas\nexport {\n PolicyConfigSchema,\n SandboxConfigSchema,\n TimeoutConfigSchema,\n ToolRateLimitSchema,\n DEFAULT_TOOL_RATE_LIMITS,\n SecurityConfigSchema,\n} from './schemas-security.js';\n\nexport type {\n PolicyConfig,\n SandboxConfig,\n TimeoutConfig,\n ToolRateLimit,\n ToolCategory,\n SecurityConfig,\n} from './schemas-security.js';\n\n// Re-export observability schemas\nexport { EventBusConfigSchema, ObservabilityConfigSchema } from './schemas-observability.js';\n\nexport type { EventBusConfig, ObservabilityConfig } from './schemas-observability.js';\n\n// Re-export skills schemas (Issue #491)\nexport {\n SkillLibraryConfigSchema,\n ExternalPackSourceSchema,\n DEFAULT_SKILL_LIBRARY_CONFIG as DEFAULT_SKILLS_CONFIG,\n} from './schemas-skills.js';\n\nexport type { SkillLibraryConfig, ExternalPackSource } from './schemas-skills.js';\n\n// Re-export SICA schemas (Issue #492)\nexport { SicaConfigSchema, DEFAULT_SICA_CONFIG } from './schemas-sica.js';\n\nexport type { SicaConfig } from './schemas-sica.js';\n\n// Re-export gateway schemas (Issue #897)\nexport { GatewayConfigSchema } from './schemas-gateway.js';\n\nexport type { GatewayConfigType } from './schemas-gateway.js';\n\n// Re-export routing schemas (Issue #475)\nexport {\n BudgetConstraintsSchema,\n TopsisCriterionSchema,\n TopsisConfigSchema,\n DifficultyWeightsConfigSchema,\n DifficultyThresholdsSchema,\n ZeroRouterConfigSchema,\n LatencyTrackerConfigSchema,\n RoutingMemoryConfigSchema,\n RoutingConfigSchema,\n DEFAULT_ROUTING_CONFIG,\n} from './schemas-routing.js';\n\nexport type {\n BudgetConstraints,\n TopsisCriterion,\n TopsisConfig,\n DifficultyWeightsConfig,\n DifficultyThresholds,\n ZeroRouterConfig,\n LatencyTrackerConfig,\n RoutingMemoryConfig,\n RoutingConfig,\n} from './schemas-routing.js';\n\n// Import for local use in AppConfigSchema\nimport { ModelConfigSchema, WorkflowConfigSchema, LoggingConfigSchema } from './schemas-core.js';\nimport { ExpertConfigSchema } from './schemas-expert.js';\nimport { SecurityConfigSchema } from './schemas-security.js';\nimport { ObservabilityConfigSchema } from './schemas-observability.js';\nimport { RoutingConfigSchema } from './schemas-routing.js';\nimport { SkillLibraryConfigSchema } from './schemas-skills.js';\nimport { SicaConfigSchema } from './schemas-sica.js';\nimport { GatewayConfigSchema } from './schemas-gateway.js';\n\n/**\n * Complete application configuration schema.\n */\nexport const AppConfigSchema = z.object({\n models: ModelConfigSchema,\n experts: ExpertConfigSchema.optional(),\n workflows: WorkflowConfigSchema.optional(),\n security: SecurityConfigSchema.optional(),\n logging: LoggingConfigSchema.optional(),\n /** Observability configuration (Issue #307) */\n observability: ObservabilityConfigSchema.optional(),\n /** Routing configuration (Issue #475) - used in orchestrator mode */\n routing: RoutingConfigSchema.optional(),\n /** Skill library configuration (Issue #491) */\n skills: SkillLibraryConfigSchema.optional(),\n /** SICA self-improvement configuration (Issue #492) */\n sica: SicaConfigSchema.optional(),\n /** Gateway middleware configuration (Issue #897) */\n gateway: GatewayConfigSchema.optional(),\n});\n\nexport type AppConfig = z.infer<typeof AppConfigSchema>;\n\n/**\n * Default configuration values.\n */\nexport const defaultConfig: Partial<AppConfig> = {\n models: {\n default: 'claude-sonnet',\n tiers: {\n fast: ['claude-haiku', 'gemini-flash'],\n balanced: ['claude-sonnet', 'gemini-pro'],\n powerful: ['claude-opus', 'codex-5.3'],\n },\n },\n logging: {\n level: 'info',\n format: 'json',\n // stderr is the safe default: MCP stdio transport reserves stdout for\n // JSON-RPC frames. Any log written to stdout corrupts the transport.\n destination: 'stderr',\n },\n security: {\n allowedPaths: ['./'],\n blockedPatterns: [],\n rateLimit: {\n enabled: true,\n requestsPerMinute: 60,\n },\n policy: {\n defaultMode: 'read-only',\n policyMode: 'enforce',\n },\n timeout: {\n defaultTimeoutMs: 30000,\n maxTimeoutMs: 300000,\n enableLogging: true,\n uriValidation: true,\n },\n },\n};\n","/**\n * nexus-agents/config - Observability Configuration Schemas\n *\n * Schemas for EventBus and observability configuration.\n */\n\nimport { z } from 'zod';\n\n/**\n * EventBus observability configuration schema.\n *\n * Controls EventBus integration with MCP server for agent-to-agent\n * communication visibility in Claude Desktop context.\n *\n * (Source: Issue #307 - EventBus MCP integration)\n */\nexport const EventBusConfigSchema = z.object({\n /** Enable EventBus integration (default: true) */\n enabled: z.boolean().default(true),\n /** Maximum events to retain in history (default: 1000) */\n maxHistorySize: z.number().positive().default(1000),\n /** Event patterns to subscribe to (default: all major patterns) */\n subscriptions: z\n .object({\n /** Subscribe to consensus events (consensus.*) */\n consensus: z.boolean().default(true),\n /** Subscribe to agent events (agent.*) */\n agent: z.boolean().default(true),\n /** Subscribe to protocol events (protocol.*) */\n protocol: z.boolean().default(true),\n /** Subscribe to session events (session.*) */\n session: z.boolean().default(true),\n /** Subscribe to message events (message.*) */\n message: z.boolean().default(false), // Off by default (high volume)\n /** Subscribe to byzantine detection events (byzantine.*) */\n byzantine: z.boolean().default(true),\n })\n .default(() => ({\n consensus: true,\n agent: true,\n protocol: true,\n session: true,\n message: false,\n byzantine: true,\n })),\n /** Logging configuration for events */\n logging: z\n .object({\n /** Log level for frequent events (default: debug) */\n frequentEventLevel: z.enum(['debug', 'info']).default('debug'),\n /** Log level for important events (default: info) */\n importantEventLevel: z.enum(['debug', 'info']).default('info'),\n })\n .default(() => ({\n frequentEventLevel: 'debug' as const,\n importantEventLevel: 'info' as const,\n })),\n});\n\nexport type EventBusConfig = z.infer<typeof EventBusConfigSchema>;\n\n/**\n * Observability configuration schema.\n *\n * Controls swarm-level observability features including EventBus integration.\n *\n * (Source: Issue #307 - EventBus MCP integration)\n */\nexport const ObservabilityConfigSchema = z.object({\n /** EventBus configuration */\n eventBus: EventBusConfigSchema.optional(),\n /** SwarmObserver maximum events (default: 10000) */\n swarmObserverMaxEvents: z.number().positive().default(10000),\n});\n\nexport type ObservabilityConfig = z.infer<typeof ObservabilityConfigSchema>;\n","/**\n * nexus-agents/config - Skills Configuration Schemas\n *\n * Zod schemas for SkillLibrary configuration.\n * Implements the Voyager skill library pattern configuration.\n *\n * @module config/schemas-skills\n * (Source: Issue #491 - Wire SkillLibrary to orchestration)\n */\n\nimport { z } from 'zod';\n\n/**\n * Schema for an external skill pack source (Issue #654).\n */\nexport const ExternalPackSourceSchema = z.object({\n /** Pack name for identification */\n name: z.string().min(1),\n /** Source: npm package name or local file path */\n source: z.string().min(1),\n /** Whether the pack is enabled (default: true) */\n enabled: z.boolean().default(true),\n});\n\nexport type ExternalPackSource = z.infer<typeof ExternalPackSourceSchema>;\n\n/**\n * SkillLibrary configuration schema.\n *\n * Maps to SkillLibraryConfig in agents/skills/skill-types.ts\n */\nexport const SkillLibraryConfigSchema = z.object({\n /** Whether skill library is enabled (default: true) */\n enabled: z.boolean().default(true),\n\n /** Maximum skills to store (default: 1000) */\n maxSkills: z.number().int().positive().default(1000),\n\n /** Minimum success rate to keep skill (0-1, default: 0.3) */\n minSuccessRateForRetention: z.number().min(0).max(1).default(0.3),\n\n /** Number of executions before evaluating retention (default: 5) */\n executionsBeforeEvaluation: z.number().int().nonnegative().default(5),\n\n /** Enable automatic skill pruning (default: true) */\n enablePruning: z.boolean().default(true),\n\n /** Whether to track detailed execution history (default: true) */\n trackExecutionHistory: z.boolean().default(true),\n\n /** Maximum execution history entries per skill (default: 100) */\n maxHistoryPerSkill: z.number().int().positive().default(100),\n\n /** External skill pack sources (Issue #654) */\n externalPacks: z.array(ExternalPackSourceSchema).optional(),\n});\n\nexport type SkillLibraryConfig = z.infer<typeof SkillLibraryConfigSchema>;\n\n/**\n * Default SkillLibrary configuration values.\n */\nexport const DEFAULT_SKILL_LIBRARY_CONFIG: SkillLibraryConfig = {\n enabled: true,\n maxSkills: 1000,\n minSuccessRateForRetention: 0.3,\n executionsBeforeEvaluation: 5,\n enablePruning: true,\n trackExecutionHistory: true,\n maxHistoryPerSkill: 100,\n};\n","/**\n * nexus-agents/config - SICA Configuration Schemas\n *\n * Zod schemas for Self-Improving Coding Agent configuration.\n * Implements SICA pattern configuration for agent self-improvement.\n *\n * @module config/schemas-sica\n * (Source: Issue #492 - Wire SicaAgent to orchestration)\n */\n\nimport { z } from 'zod';\n\n/**\n * SICA (Self-Improving Coding Agent) configuration schema.\n *\n * Maps to SicaConfig in agents/self-improving/sica-types.ts\n */\nexport const SicaConfigSchema = z.object({\n /** Whether SICA wrapping is enabled (default: false) */\n enabled: z.boolean().default(false),\n\n /** Minimum executions before considering improvement (default: 10) */\n minExecutionsForImprovement: z.number().int().positive().default(10),\n\n /** Success rate threshold to trigger improvement (0-1, default: 0.7) */\n improvementThreshold: z.number().min(0).max(1).default(0.7),\n\n /** Maximum concurrent versions to evaluate (default: 3) */\n maxActiveVersions: z.number().int().positive().max(10).default(3),\n\n /** Whether to auto-select best version (default: true) */\n autoSelectBest: z.boolean().default(true),\n\n /** Improvement cooldown in milliseconds (default: 60000) */\n improvementCooldownMs: z.number().int().nonnegative().default(60000),\n\n /** Enable observability logging for SICA events (default: true) */\n enableObservability: z.boolean().default(true),\n});\n\nexport type SicaConfig = z.infer<typeof SicaConfigSchema>;\n\n/**\n * Default SICA configuration values.\n *\n * SICA is disabled by default as it wraps agents with self-improvement\n * capabilities which adds overhead. Enable explicitly when needed.\n */\nexport const DEFAULT_SICA_CONFIG: SicaConfig = {\n enabled: false,\n minExecutionsForImprovement: 10,\n improvementThreshold: 0.7,\n maxActiveVersions: 3,\n autoSelectBest: true,\n improvementCooldownMs: 60000,\n enableObservability: true,\n};\n","/**\n * nexus-agents/config - Gateway Configuration Schema\n *\n * Schema for the MCP gateway middleware configuration.\n * Controls tier-aware dispatch logging, per-tool tier overrides,\n * and upstream MCP server composition (#1498).\n *\n * (Source: Issue #897, Epic #888, Issue #1498)\n */\n\nimport { z } from 'zod';\n\n/**\n * Valid tier names for configuration.\n * Maps to RequestTier enum values in tier-classifier.ts.\n */\nconst TierNameSchema = z.enum(['DIRECT', 'ANALYZED', 'ORCHESTRATED']);\n\n/** Allowed commands for upstream MCP servers (security: no arbitrary exec). */\nconst ALLOWED_COMMANDS = ['node', 'npx', 'python', 'python3', 'uvx', 'docker'] as const;\n\n/**\n * Upstream MCP server configuration (#1498).\n * Defines an external MCP server to connect to via stdio transport.\n */\nexport const UpstreamServerSchema = z.object({\n /** Unique name for this upstream server (used as tool prefix). */\n name: z\n .string()\n .min(1)\n .max(50)\n .regex(/^[a-z0-9_-]+$/),\n /** Command to spawn the server. Must be in allowlist. */\n command: z.enum(ALLOWED_COMMANDS),\n /** Arguments to pass to the command. */\n args: z.array(z.string().max(500)).default([]),\n /** Environment variables (use {env:VAR} references, not plaintext secrets). */\n env: z.record(z.string(), z.string()).optional(),\n /** Whether to connect lazily on first tool call (default: true). */\n lazy: z.boolean().default(true),\n /** Connection timeout in ms (default: 10000). */\n timeoutMs: z.number().int().min(1000).max(60000).default(10000),\n});\n\nexport type UpstreamServerConfig = z.infer<typeof UpstreamServerSchema>;\n\n/** Maximum number of upstream servers (resource limit). */\nexport const MAX_UPSTREAM_SERVERS = 5;\n\n/**\n * Gateway middleware configuration schema.\n *\n * Controls whether tier-aware dispatch logging is active,\n * allows per-tool tier overrides, and defines upstream MCP servers.\n */\nexport const GatewayConfigSchema = z.object({\n /** Enable gateway tier dispatch logging (default: true). */\n enabled: z.boolean().default(true),\n /**\n * Per-tool tier overrides.\n * Keys are tool names (e.g., 'delegate_to_model'), values are tier names.\n * Overrides the default tier from TOOL_TIER_MAP in tier-classifier.ts.\n */\n tierOverrides: z.record(z.string(), TierNameSchema).optional(),\n /**\n * Upstream MCP servers to compose with (#1498).\n * Tools from upstream servers are available as prefixed tools (e.g., tavily.search).\n */\n upstreamServers: z.array(UpstreamServerSchema).max(MAX_UPSTREAM_SERVERS).optional(),\n});\n\nexport type GatewayConfigType = z.infer<typeof GatewayConfigSchema>;\n","/**\n * nexus-agents/config - Routing Configuration Schemas\n *\n * Zod schemas for routing configuration exposed via nexus-agents.yaml.\n * Allows users to configure the CompositeRouter pipeline, TOPSIS criteria,\n * ZeroRouter thresholds, and other routing parameters.\n *\n * @module config/schemas-routing\n * (Source: Issue #475 - Add routing configuration section to nexus-agents.yaml)\n */\n\nimport { z } from 'zod';\nimport { CliNameSchema } from './model-capabilities-types.js';\n\n/**\n * Budget constraints schema for cost/token/latency limits.\n */\nexport const BudgetConstraintsSchema = z\n .object({\n /** Maximum tokens per request */\n maxTokens: z.number().positive().optional(),\n /** Maximum cost per request in USD */\n maxCostUsd: z.number().positive().optional(),\n /** Maximum latency per request in milliseconds */\n maxLatencyMs: z.number().positive().optional(),\n })\n .optional();\n\nexport type BudgetConstraints = z.infer<typeof BudgetConstraintsSchema>;\n\n/**\n * TOPSIS criterion schema for multi-criteria decision making.\n */\nexport const TopsisCriterionSchema = z.object({\n /** Criterion name (e.g., 'quality', 'cost', 'latency') */\n name: z.string().min(1),\n /** Weight for this criterion (0-1, should sum to 1 across all criteria) */\n weight: z.number().min(0).max(1),\n /** Whether higher values are better (true) or lower is better (false) */\n beneficial: z.boolean(),\n});\n\nexport type TopsisCriterion = z.infer<typeof TopsisCriterionSchema>;\n\n/**\n * TOPSIS configuration schema.\n */\nexport const TopsisConfigSchema = z\n .object({\n /** Criteria with weights (must sum to 1.0) */\n criteria: z.array(TopsisCriterionSchema).optional(),\n /** Minimum acceptable quality score (0-10) */\n minQualityThreshold: z.number().min(0).max(10).default(5),\n /** Maximum acceptable latency in milliseconds (optional) */\n maxLatencyMs: z.number().positive().optional(),\n /** Maximum acceptable cost per request in USD (optional) */\n maxCostPerRequest: z.number().positive().optional(),\n /** Whether to log detailed scoring info */\n verbose: z.boolean().default(false),\n })\n .optional();\n\nexport type TopsisConfig = z.infer<typeof TopsisConfigSchema>;\n\n/**\n * Difficulty weights schema for ZeroRouter aggregation.\n */\nexport const DifficultyWeightsConfigSchema = z.object({\n /** Weight for reasoning difficulty (0-1) */\n reasoning: z.number().min(0).max(1).default(0.3),\n /** Weight for knowledge difficulty (0-1) */\n knowledge: z.number().min(0).max(1).default(0.15),\n /** Weight for creativity difficulty (0-1) */\n creativity: z.number().min(0).max(1).default(0.15),\n /** Weight for precision difficulty (0-1) */\n precision: z.number().min(0).max(1).default(0.25),\n /** Weight for context length difficulty (0-1) */\n context_length: z.number().min(0).max(1).default(0.15),\n});\n\nexport type DifficultyWeightsConfig = z.infer<typeof DifficultyWeightsConfigSchema>;\n\n/**\n * Difficulty thresholds schema for level classification.\n */\nexport const DifficultyThresholdsSchema = z.object({\n /** Upper bound for 'easy' classification (0-1) */\n easyUpperBound: z.number().min(0).max(1).default(0.3),\n /** Lower bound for 'hard' classification (0-1) */\n hardLowerBound: z.number().min(0).max(1).default(0.7),\n});\n\nexport type DifficultyThresholds = z.infer<typeof DifficultyThresholdsSchema>;\n\n// CliNameSchema imported from model-capabilities-types.ts (canonical source)\n\n/**\n * Valid difficulty levels.\n */\nconst DifficultyLevelSchema = z.enum(['easy', 'medium', 'hard']);\n\n/**\n * Valid model tiers.\n */\nconst ModelTierSchema = z.enum(['fast', 'balanced', 'powerful']);\n\n/**\n * ZeroRouter configuration schema.\n */\nexport const ZeroRouterConfigSchema = z\n .object({\n /** Difficulty thresholds for level classification */\n thresholds: DifficultyThresholdsSchema.optional(),\n /** Weights for difficulty aggregation */\n weights: DifficultyWeightsConfigSchema.optional(),\n /** Mapping from difficulty level to model tier */\n difficultyToTier: z.record(DifficultyLevelSchema, ModelTierSchema).optional(),\n /** Mapping from model tier to CLI preference order */\n tierToClis: z.record(ModelTierSchema, z.array(CliNameSchema)).optional(),\n /** Enable adaptive calibration from outcomes */\n enableCalibration: z.boolean().default(true),\n /** Maximum outcomes to store for calibration */\n maxCalibrationOutcomes: z.number().int().positive().default(1000),\n /** Minimum outcomes before applying calibration adjustments */\n minCalibrationOutcomes: z.number().int().positive().default(50),\n /** Verbose logging */\n verbose: z.boolean().default(false),\n })\n .optional();\n\nexport type ZeroRouterConfig = z.infer<typeof ZeroRouterConfigSchema>;\n\n/**\n * Latency tracker configuration schema.\n */\nexport const LatencyTrackerConfigSchema = z\n .object({\n /** Maximum number of samples to keep per CLI */\n windowSize: z.number().int().positive().default(100),\n /** Time-weighted decay factor (0-1, higher = more weight to recent) */\n decayFactor: z.number().min(0).max(1).default(0.95),\n /** Maximum age of samples in milliseconds before forced eviction */\n maxSampleAgeMs: z.number().int().positive().default(3600000),\n /** Percentiles to calculate */\n percentiles: z.array(z.number().min(0).max(100)).max(20).default([50, 95, 99]),\n })\n .optional();\n\nexport type LatencyTrackerConfig = z.infer<typeof LatencyTrackerConfigSchema>;\n\n/**\n * Routing memory configuration schema.\n */\nexport const RoutingMemoryConfigSchema = z\n .object({\n /** Minimum observations before using learned routing */\n minObservations: z.number().int().positive().default(5),\n /** Confidence threshold for using cached decisions */\n confidenceThreshold: z.number().min(0).max(1).default(0.6),\n /** Success rate threshold for trusting a routing pattern */\n successRateThreshold: z.number().min(0).max(1).default(0.7),\n /** Maximum age of cached actions in milliseconds */\n actionCacheMaxAgeMs: z.number().int().positive().default(3600000),\n })\n .optional();\n\nexport type RoutingMemoryConfig = z.infer<typeof RoutingMemoryConfigSchema>;\n\n/**\n * Complete routing configuration schema.\n * Exposes all routing subsystem parameters via nexus-agents.yaml.\n */\nexport const RoutingConfigSchema = z.object({\n /**\n * Pipeline stage toggles.\n * Enable or disable individual routing stages.\n */\n stages: z\n .object({\n /** Enable budget filtering stage */\n budgetFilter: z.boolean().default(true),\n /** Enable ZeroRouter difficulty-based routing */\n zeroRouter: z.boolean().default(true),\n /** Enable preference-trained routing */\n preferenceRouting: z.boolean().default(false),\n /** Enable TOPSIS ranking */\n topsisRanking: z.boolean().default(true),\n /** Enable LinUCB selection */\n linucbSelection: z.boolean().default(true),\n /** Enable latency tracking */\n latencyTracking: z.boolean().default(true),\n /** Enable routing memory for learned routing */\n routingMemory: z.boolean().default(false),\n /** Enable confidence cascade stage (Issue #755, ADR-0005) */\n confidenceCascade: z.boolean().default(false),\n /** Enable capability match stage (Issue #755, ADR-0005) */\n capabilityMatch: z.boolean().default(false),\n /** Enable quality constraint stage (Issue #755, ADR-0005) */\n qualityConstraint: z.boolean().default(false),\n /** Enable resource strategy stage for budget-aware oscillation (Issue #998) */\n resourceStrategy: z.boolean().default(true),\n /** Enable strategy distillation for learned routing rules (Issue #999) */\n strategyDistillation: z.boolean().default(false),\n })\n .optional(),\n\n /**\n * Budget constraints for routing decisions.\n */\n budget: BudgetConstraintsSchema,\n\n /**\n * TOPSIS multi-criteria decision making configuration.\n */\n topsis: TopsisConfigSchema,\n\n /**\n * ZeroRouter difficulty-based routing configuration.\n */\n zeroRouter: ZeroRouterConfigSchema,\n\n /**\n * Latency tracker configuration.\n */\n latencyTracker: LatencyTrackerConfigSchema,\n\n /**\n * Routing memory configuration.\n */\n routingMemory: RoutingMemoryConfigSchema,\n\n /**\n * LinUCB bandit parameters.\n */\n linucb: z\n .object({\n /** Exploration parameter (higher = more exploration) */\n alpha: z.number().positive().default(1.0),\n /** Maximum routing decision time in milliseconds */\n maxDecisionTimeMs: z.number().positive().default(50),\n })\n .optional(),\n\n /**\n * Preference router parameters.\n */\n preference: z\n .object({\n /** Minimum data points before using learned preferences */\n minDataPoints: z.number().int().positive().default(10),\n })\n .optional(),\n\n /**\n * Weight for latency score in final routing (0-1).\n */\n latencyScoreWeight: z.number().min(0).max(1).default(0.2),\n});\n\nexport type RoutingConfig = z.infer<typeof RoutingConfigSchema>;\n\n/**\n * Default routing configuration values.\n * Used when no routing config is provided in nexus-agents.yaml.\n */\nexport const DEFAULT_ROUTING_CONFIG: RoutingConfig = {\n stages: {\n budgetFilter: true,\n zeroRouter: true,\n preferenceRouting: false,\n topsisRanking: true,\n linucbSelection: true,\n latencyTracking: true,\n routingMemory: false,\n // Issue #755: New replacement stages (disabled by default for backward compatibility)\n confidenceCascade: false,\n capabilityMatch: false,\n qualityConstraint: false,\n // Issue #998: Resource strategy (enabled by default)\n resourceStrategy: true,\n // Issue #999: Strategy distillation (opt-in)\n strategyDistillation: false,\n },\n topsis: {\n minQualityThreshold: 5,\n verbose: false,\n },\n zeroRouter: {\n enableCalibration: true,\n maxCalibrationOutcomes: 1000,\n minCalibrationOutcomes: 50,\n verbose: false,\n },\n latencyTracker: {\n windowSize: 100,\n decayFactor: 0.95,\n maxSampleAgeMs: 3600000,\n percentiles: [50, 95, 99],\n },\n routingMemory: {\n minObservations: 5,\n confidenceThreshold: 0.6,\n successRateThreshold: 0.7,\n actionCacheMaxAgeMs: 3600000,\n },\n linucb: {\n alpha: 1.0,\n maxDecisionTimeMs: 50,\n },\n preference: {\n minDataPoints: 10,\n },\n latencyScoreWeight: 0.2,\n};\n","/**\n * Centralized Zod schema for NEXUS_* environment variables (Issue #1016)\n *\n * Validates all known NEXUS_* env vars at startup (warn-only, never blocks).\n * Detects typos via Levenshtein distance and suggests corrections.\n *\n * Does NOT replace per-module parsing (parseIntEnv, resolveV2Config, etc.).\n * This is an additional safety net run once at startup.\n *\n * @module config/env-schema\n */\n\nimport { z } from 'zod';\nimport type { ILogger } from '../core/index.js';\n\n// ============================================================================\n// Helper Zod types for string-encoded values\n// ============================================================================\n\n/** String that parses to a positive integer. */\nconst positiveIntStr = z.string().regex(/^\\d+$/, 'Must be a positive integer string');\n\n/** String \"true\" or \"false\". */\nconst boolStr = z.enum(['true', 'false']);\n\n/** String that parses to a non-negative float. */\nconst floatStr = z.string().regex(/^\\d+(\\.\\d+)?$/, 'Must be a non-negative number string');\n\n// ============================================================================\n// Known NEXUS_* environment variables schema\n// ============================================================================\n\n/**\n * Schema for all known NEXUS_* environment variables.\n * Each field is optional (env vars may not be set).\n * Values are validated as strings matching expected patterns.\n */\nconst NexusEnvSchema = z.object({\n // --- Timeouts ---\n NEXUS_TIMEOUT_CLI: positiveIntStr.optional(),\n NEXUS_TIMEOUT_CLISIMPLE: positiveIntStr.optional(),\n NEXUS_TIMEOUT_CLICOMPLEX: positiveIntStr.optional(),\n NEXUS_TIMEOUT_API: positiveIntStr.optional(),\n NEXUS_TIMEOUT_WORKFLOW: positiveIntStr.optional(),\n NEXUS_TIMEOUT_MCP: positiveIntStr.optional(),\n NEXUS_VOTE_TIMEOUT_MS: positiveIntStr.optional(),\n NEXUS_MCP_TIMEOUT_MS: positiveIntStr.optional(),\n NEXUS_WORKFLOW_TIMEOUT_MS: positiveIntStr.optional(),\n NEXUS_GRAPH_TIMEOUT_MS: positiveIntStr.optional(),\n NEXUS_TEST_TIMEOUT_MS: positiveIntStr.optional(),\n NEXUS_EXPERT_TIMEOUT_MS: positiveIntStr.optional(),\n NEXUS_WORKER_TIMEOUT_MS: positiveIntStr.optional(),\n\n // --- Retry ---\n NEXUS_RETRY_MAX_RETRIES: positiveIntStr.optional(),\n NEXUS_RETRY_BASE_DELAY: positiveIntStr.optional(),\n NEXUS_RETRY_MAX_DELAY: positiveIntStr.optional(),\n NEXUS_RETRY_JITTER: floatStr.optional(),\n\n // --- Rate Limit ---\n NEXUS_RATE_LIMIT_ENABLED: boolStr.optional(),\n NEXUS_RATE_LIMIT_RPM: positiveIntStr.optional(),\n NEXUS_RATE_LIMIT_MAX_CONCURRENT: positiveIntStr.optional(),\n NEXUS_RATE_LIMIT_CAPACITY: positiveIntStr.optional(),\n NEXUS_RATE_LIMIT_REFILL_RATE: positiveIntStr.optional(),\n NEXUS_RATE_LIMIT_REFILL_INTERVAL: positiveIntStr.optional(),\n\n // --- Workers & Concurrency ---\n NEXUS_MAX_CONCURRENT_EXPERTS: positiveIntStr.optional(),\n NEXUS_WORKERS_MAX: positiveIntStr.optional(),\n NEXUS_WORKERS_POOL_SIZE: positiveIntStr.optional(),\n NEXUS_WORKERS_IDLE_TIMEOUT: positiveIntStr.optional(),\n NEXUS_WORKFLOW_MAX_PARALLEL: positiveIntStr.optional(),\n NEXUS_TEST_PARALLELISM: positiveIntStr.optional(),\n NEXUS_EVALUATION_MAX_WORKERS: positiveIntStr.optional(),\n NEXUS_SWARM_OBSERVER_MAX_EVENTS: positiveIntStr.optional(),\n\n // --- Circuit Breaker ---\n NEXUS_CIRCUIT_BREAKER_THRESHOLD: positiveIntStr.optional(),\n NEXUS_CIRCUIT_BREAKER_RESET_TIMEOUT: positiveIntStr.optional(),\n\n // --- V2 Pipeline ---\n NEXUS_V2_MODE: z.enum(['off', 'partial', 'full']).optional(),\n NEXUS_V2_DELEGATE: boolStr.optional(),\n NEXUS_V2_ORCHESTRATE: boolStr.optional(),\n NEXUS_V2_POLICY_MODE: z.enum(['off', 'warn', 'block']).optional(),\n NEXUS_AORCHESTRA: boolStr.optional(),\n NEXUS_AORCHESTRA_DISPATCH: boolStr.optional(),\n NEXUS_WORKER_MAX_CALLS: positiveIntStr.optional(),\n\n // --- Server ---\n NEXUS_AUTH_ENABLED: boolStr.optional(),\n NEXUS_AUTH_METHOD: z.string().optional(),\n\n // --- Logging ---\n NEXUS_LOG_LEVEL: z\n .enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal', 'silent'])\n .optional(),\n\n // --- Features ---\n NEXUS_PERSIST_LEARNING: boolStr.optional(),\n NEXUS_REFLECTIVE_MEMORY: z.enum(['true', 'false', 'shadow']).optional(),\n NEXUS_EVENTBUS_ENABLED: boolStr.optional(),\n NEXUS_EVENTBUS_MAX_HISTORY: positiveIntStr.optional(),\n NEXUS_BILLING_MODE: z.enum(['plan', 'api']).optional(),\n NEXUS_CONFIG_PATH: z.string().optional(),\n NEXUS_ALLOW_MOCK_ORCHESTRATION: boolStr.optional(),\n\n // --- Hooks & Sessions ---\n NEXUS_HOOK_VERBOSE: boolStr.optional(),\n NEXUS_SESSIONS_DB: z.string().optional(),\n NEXUS_DISABLE_SESSIONS: boolStr.optional(),\n NEXUS_DISABLE_METRICS: boolStr.optional(),\n});\n\n// ============================================================================\n// Known variable names (derived from schema)\n// ============================================================================\n\nconst KNOWN_NAMES: readonly string[] = Object.keys(NexusEnvSchema.shape);\n\n// ============================================================================\n// Levenshtein distance\n// ============================================================================\n\n/** Safe array accessor — indices are always in-bounds by construction. */\nfunction at(arr: number[], i: number): number {\n return arr[i] ?? 0;\n}\n\n/** Standard Levenshtein edit distance between two strings. */\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n\n let prev = Array.from({ length: n + 1 }, (_, j) => j);\n let curr = new Array<number>(n + 1).fill(0);\n\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(at(prev, j) + 1, at(curr, j - 1) + 1, at(prev, j - 1) + cost);\n }\n [prev, curr] = [curr, prev];\n }\n\n return at(prev, n);\n}\n\n/** Returns the closest known var name if edit distance <= 3, or null. */\nfunction suggestSimilar(name: string, known: readonly string[]): string | null {\n let best: string | null = null;\n let bestDist = 4; // threshold: must be strictly less than 4\n\n for (const candidate of known) {\n const dist = levenshtein(name, candidate);\n if (dist < bestDist) {\n bestDist = dist;\n best = candidate;\n }\n }\n\n return best;\n}\n\n// ============================================================================\n// Validation result types\n// ============================================================================\n\n/** An unknown NEXUS_* env var with optional typo suggestion. */\nexport interface UnknownVar {\n readonly name: string;\n readonly suggestion: string | null;\n}\n\n/** An invalid NEXUS_* env var with error message. */\nexport interface InvalidVar {\n readonly name: string;\n readonly value: string;\n readonly error: string;\n}\n\n/** Result of validating NEXUS_* environment variables. */\nexport interface EnvValidationResult {\n readonly unknownVars: readonly UnknownVar[];\n readonly invalidVars: readonly InvalidVar[];\n}\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\n/** Classifies NEXUS_* keys into known (with values) and unknown. */\nfunction classifyEnvKeys(\n nexusKeys: readonly string[],\n env: NodeJS.ProcessEnv\n): { knownRecord: Record<string, string>; unknownVars: UnknownVar[] } {\n const knownRecord: Record<string, string> = {};\n const unknownVars: UnknownVar[] = [];\n\n for (const key of nexusKeys) {\n if (KNOWN_NAMES.includes(key)) {\n const value = env[key];\n if (value !== undefined) {\n knownRecord[key] = value;\n }\n } else {\n unknownVars.push({\n name: key,\n suggestion: suggestSimilar(key, KNOWN_NAMES),\n });\n }\n }\n\n return { knownRecord, unknownVars };\n}\n\n/** Logs validation warnings via the provided logger. */\nfunction logValidationWarnings(\n logger: ILogger,\n unknownVars: readonly UnknownVar[],\n invalidVars: readonly InvalidVar[]\n): void {\n for (const u of unknownVars) {\n const hint = u.suggestion !== null ? ` (did you mean ${u.suggestion}?)` : '';\n logger.warn(`Unknown environment variable: ${u.name}${hint}`);\n }\n for (const inv of invalidVars) {\n logger.warn(`Invalid environment variable ${inv.name}=\"${inv.value}\": ${inv.error}`);\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Validates all NEXUS_* environment variables.\n *\n * - Detects unknown vars (potential typos) with Levenshtein suggestions\n * - Detects invalid values for known vars\n * - Warn-only: never throws, never blocks startup\n *\n * @param logger - Optional logger for direct warning output\n * @returns Validation result with unknown and invalid var lists\n */\nexport function validateNexusEnv(logger?: ILogger): EnvValidationResult {\n const nexusKeys = Object.keys(process.env).filter((k) => k.startsWith('NEXUS_'));\n const { knownRecord, unknownVars } = classifyEnvKeys(nexusKeys, process.env);\n\n // Validate known vars against the schema\n const invalidVars: InvalidVar[] = [];\n const result = NexusEnvSchema.safeParse(knownRecord);\n if (!result.success) {\n for (const issue of result.error.issues) {\n const varName = String(issue.path[0]);\n invalidVars.push({\n name: varName,\n value: knownRecord[varName] ?? '',\n error: issue.message,\n });\n }\n }\n\n if (logger !== undefined) {\n logValidationWarnings(logger, unknownVars, invalidVars);\n }\n\n return { unknownVars, invalidVars };\n}\n\n/**\n * Returns all known NEXUS_* variable names from the schema.\n */\nexport function getKnownNexusVarNames(): readonly string[] {\n return KNOWN_NAMES;\n}\n","/**\n * nexus-agents/config - Model Availability Probes & Fallback Chains\n *\n * Runtime availability tracking for model APIs. Maintains a bounded\n * TTL cache of probe results and provides fallback chain resolution\n * when a model is unavailable.\n *\n * @module config/model-availability\n * (Source: Issue #869)\n */\n\nimport { getTimeProvider } from '../core/index.js';\nimport type { ModelId, CliNameLiteral } from './model-capabilities-types.js';\nimport { DEFAULT_MODEL_PER_CLI } from './model-capabilities.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Status of a model probe. */\nexport interface ProbeResult {\n readonly modelId: ModelId;\n readonly available: boolean;\n readonly latencyMs: number;\n readonly checkedAt: number;\n readonly error?: string;\n}\n\n/** Configuration for the availability cache. */\nexport interface AvailabilityCacheConfig {\n /** Time-to-live in ms for probe results. Default: 60_000 (1 min). */\n readonly ttlMs?: number;\n /** Maximum entries in the cache. Default: 50. */\n readonly maxEntries?: number;\n}\n\n/** A function that probes whether a model is reachable. */\nexport type ProbeFn = (modelId: ModelId) => Promise<ProbeResult>;\n\n/** Fallback chain entry with model and reason for fallback. */\nexport interface FallbackEntry {\n readonly modelId: ModelId;\n readonly reason: string;\n}\n\n// ---------------------------------------------------------------------------\n// Availability Cache\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_MAX_ENTRIES = 50;\n\n/**\n * Bounded TTL cache for model availability probe results.\n * Thread-safe for single-threaded Node.js; no locks needed.\n */\nexport class AvailabilityCache {\n private readonly cache = new Map<ModelId, ProbeResult>();\n private readonly ttlMs: number;\n private readonly maxEntries: number;\n\n constructor(config: AvailabilityCacheConfig = {}) {\n this.ttlMs = config.ttlMs ?? DEFAULT_TTL_MS;\n this.maxEntries = config.maxEntries ?? DEFAULT_MAX_ENTRIES;\n }\n\n /** Get a cached probe result, or undefined if expired/missing. */\n get(modelId: ModelId): ProbeResult | undefined {\n const entry = this.cache.get(modelId);\n if (entry === undefined) return undefined;\n if (getTimeProvider().now() - entry.checkedAt > this.ttlMs) {\n this.cache.delete(modelId);\n return undefined;\n }\n return entry;\n }\n\n /** Store a probe result, evicting oldest if at capacity. */\n set(result: ProbeResult): void {\n if (this.cache.size >= this.maxEntries && !this.cache.has(result.modelId)) {\n const oldest = this.cache.keys().next();\n if (oldest.done !== true) {\n this.cache.delete(oldest.value);\n }\n }\n this.cache.set(result.modelId, result);\n }\n\n /** Mark a model as unavailable without a full probe. */\n markUnavailable(modelId: ModelId, error: string): void {\n this.set({\n modelId,\n available: false,\n latencyMs: 0,\n checkedAt: getTimeProvider().now(),\n error,\n });\n }\n\n /** Mark a model as available. */\n markAvailable(modelId: ModelId, latencyMs: number): void {\n this.set({\n modelId,\n available: true,\n latencyMs,\n checkedAt: getTimeProvider().now(),\n });\n }\n\n /** Check if a model is known-unavailable (cached and not expired). */\n isKnownUnavailable(modelId: ModelId): boolean {\n const entry = this.get(modelId);\n return entry !== undefined && !entry.available;\n }\n\n /** Get all cached entries (for diagnostics). */\n entries(): ReadonlyArray<ProbeResult> {\n return [...this.cache.values()];\n }\n\n /** Number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Clear all cached entries. */\n clear(): void {\n this.cache.clear();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Fallback Chain Resolution\n// ---------------------------------------------------------------------------\n\n/** Default fallback order per CLI (strongest → weakest). */\nconst FALLBACK_CHAINS: Readonly<Record<CliNameLiteral, readonly ModelId[]>> = {\n claude: ['claude-opus', 'claude-sonnet', 'claude-haiku'],\n gemini: ['gemini-3-pro', 'gemini-pro', 'gemini-3-flash', 'gemini-flash'],\n codex: ['codex-5.3', 'codex-5.2', 'codex-5.1-mini'],\n opencode: ['opencode-custom-opus', 'opencode-custom-sonnet', 'opencode-default'],\n};\n\n/**\n * Resolves a fallback chain for a given model.\n * Returns the first available model in the chain, skipping known-unavailable ones.\n */\nexport function resolveFallback(modelId: ModelId, cache: AvailabilityCache): FallbackEntry | null {\n const cli = getCliForModelId(modelId);\n if (cli === undefined) return null;\n\n const chain = FALLBACK_CHAINS[cli];\n for (const candidate of chain) {\n if (candidate === modelId) continue;\n if (!cache.isKnownUnavailable(candidate)) {\n return {\n modelId: candidate,\n reason: `Fallback from ${modelId} (unavailable) to ${candidate}`,\n };\n }\n }\n return null;\n}\n\n/**\n * Get the fallback chain for a CLI tool.\n */\nexport function getFallbackChain(cli: CliNameLiteral): readonly ModelId[] {\n return FALLBACK_CHAINS[cli];\n}\n\n/**\n * Get the CLI name for a model ID.\n */\nexport function getCliForModelId(modelId: ModelId): CliNameLiteral | undefined {\n for (const [cli, defaultModel] of Object.entries(DEFAULT_MODEL_PER_CLI)) {\n const chain = FALLBACK_CHAINS[cli as CliNameLiteral];\n if (chain.includes(modelId)) return cli as CliNameLiteral;\n if (defaultModel === modelId) return cli as CliNameLiteral;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Singleton Cache (shared across the process)\n// ---------------------------------------------------------------------------\n\nlet globalCache: AvailabilityCache | undefined;\n\n/** Get the shared availability cache (lazy-init). */\nexport function getAvailabilityCache(): AvailabilityCache {\n globalCache ??= new AvailabilityCache();\n return globalCache;\n}\n\n/** Reset the global cache (for testing). */\nexport function resetAvailabilityCache(): void {\n globalCache = undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Filter Integration\n// ---------------------------------------------------------------------------\n\n/**\n * Filters out known-unavailable models from a set of model IDs.\n * Returns the filtered set, or null if no models were removed.\n * Used by scoreAllModels() to skip unavailable models.\n */\nexport function filterAvailableModels(\n modelIds: readonly string[],\n cache: AvailabilityCache\n): { available: string[]; removed: string[] } {\n const available: string[] = [];\n const removed: string[] = [];\n for (const id of modelIds) {\n if (cache.isKnownUnavailable(id as ModelId)) {\n removed.push(id);\n } else {\n available.push(id);\n }\n }\n return { available, removed };\n}\n","/**\n * nexus-agents/config - Routing Config Adapter\n *\n * Converts RoutingConfig from YAML schema to CompositeRouterConfigWithPreference\n * that the runtime routing system expects.\n *\n * @module config/routing-config-adapter\n * (Source: Issue #475 - Add routing configuration section to nexus-agents.yaml)\n */\n\nimport type {\n CompositeRouterConfig,\n CompositeRouterConfigWithPreference,\n} from '../cli-adapters/composite-router-types.js';\nimport { DEFAULT_COMPOSITE_CONFIG } from '../cli-adapters/composite-router-types.js';\nimport type { TopsisConfig as RuntimeTopsisConfig } from '../cli-adapters/topsis-types.js';\nimport { DEFAULT_TOPSIS_CONFIG, DEFAULT_TOPSIS_CRITERIA } from '../cli-adapters/topsis-types.js';\nimport type { ZeroRouterConfig as RuntimeZeroRouterConfig } from '../cli-adapters/zero-router-types.js';\nimport { DEFAULT_ZERO_ROUTER_CONFIG } from '../cli-adapters/zero-router-types.js';\nimport type { LatencyTrackerConfig as RuntimeLatencyConfig } from '../cli-adapters/latency-tracker-types.js';\nimport type { RoutingMemoryConfig as RuntimeMemoryConfig } from '../context/routing-memory.js';\nimport type {\n RoutingConfig,\n TopsisConfig as YamlTopsisConfig,\n ZeroRouterConfig as YamlZeroRouterConfig,\n LatencyTrackerConfig as YamlLatencyTrackerConfig,\n RoutingMemoryConfig as YamlRoutingMemoryConfig,\n} from './schemas-routing.js';\nimport { isPersistenceEnabled } from './learning-persistence.js';\n\n/** Non-nullable routing config for internal use. */\ntype DefinedRoutingConfig = NonNullable<RoutingConfig>;\n\n/** Default routing config with proper typing.\n * Note: `stages` is intentionally omitted so that persistence-aware flags\n * (routingMemory, strategyDistillation, preferenceRouting) resolve dynamically\n * via `resolveStageFlags()` instead of being hardcoded to false. (#1353)\n */\nconst ADAPTER_DEFAULTS: DefinedRoutingConfig = {\n latencyScoreWeight: 0.2,\n};\n\n/**\n * Converts YAML TopsisConfig to runtime TopsisConfig.\n */\nfunction adaptTopsisConfig(yaml: YamlTopsisConfig | undefined): Partial<RuntimeTopsisConfig> {\n if (yaml === undefined) return {};\n\n const result: Partial<RuntimeTopsisConfig> = {\n criteria: yaml.criteria ?? DEFAULT_TOPSIS_CRITERIA,\n minQualityThreshold: yaml.minQualityThreshold,\n verbose: yaml.verbose,\n };\n\n if (yaml.maxLatencyMs !== undefined) {\n (result as { maxLatencyMs?: number }).maxLatencyMs = yaml.maxLatencyMs;\n }\n if (yaml.maxCostPerRequest !== undefined) {\n (result as { maxCostPerRequest?: number }).maxCostPerRequest = yaml.maxCostPerRequest;\n }\n\n return result;\n}\n\n/**\n * Converts YAML ZeroRouterConfig to runtime ZeroRouterConfig.\n */\nfunction adaptZeroRouterConfig(\n yaml: YamlZeroRouterConfig | undefined\n): Partial<RuntimeZeroRouterConfig> {\n if (yaml === undefined) return {};\n\n return {\n thresholds: yaml.thresholds ?? DEFAULT_ZERO_ROUTER_CONFIG.thresholds,\n weights: yaml.weights ?? DEFAULT_ZERO_ROUTER_CONFIG.weights,\n difficultyToTier: yaml.difficultyToTier ?? DEFAULT_ZERO_ROUTER_CONFIG.difficultyToTier,\n tierToClis: yaml.tierToClis ?? DEFAULT_ZERO_ROUTER_CONFIG.tierToClis,\n enableCalibration: yaml.enableCalibration,\n maxCalibrationOutcomes: yaml.maxCalibrationOutcomes,\n minCalibrationOutcomes: yaml.minCalibrationOutcomes,\n verbose: yaml.verbose,\n };\n}\n\n/**\n * Converts YAML LatencyTrackerConfig to runtime LatencyTrackerConfig.\n */\nfunction adaptLatencyTrackerConfig(\n yaml: YamlLatencyTrackerConfig | undefined\n): Partial<RuntimeLatencyConfig> {\n if (yaml === undefined) return {};\n\n return {\n windowSize: yaml.windowSize,\n decayFactor: yaml.decayFactor,\n maxSampleAgeMs: yaml.maxSampleAgeMs,\n percentiles: yaml.percentiles,\n };\n}\n\n/**\n * Converts YAML RoutingMemoryConfig to runtime RoutingMemoryConfig.\n */\nfunction adaptRoutingMemoryConfig(\n yaml: YamlRoutingMemoryConfig | undefined\n): Partial<RuntimeMemoryConfig> {\n if (yaml === undefined) return {};\n\n return {\n minObservations: yaml.minObservations,\n confidenceThreshold: yaml.confidenceThreshold,\n successRateThreshold: yaml.successRateThreshold,\n actionCacheMaxAgeMs: yaml.actionCacheMaxAgeMs,\n };\n}\n\n/**\n * Converts YAML stages config to CompositeRouterConfig flags.\n */\nfunction adaptStagesConfig(\n yaml: DefinedRoutingConfig['stages'] | undefined\n): Partial<CompositeRouterConfig> {\n if (yaml === undefined) return {};\n\n return {\n enableBudgetFilter: yaml.budgetFilter,\n enableZeroRouter: yaml.zeroRouter,\n enablePreferenceRouting: yaml.preferenceRouting,\n enableTopsisRanking: yaml.topsisRanking,\n enableLinUCBSelection: yaml.linucbSelection,\n enableLatencyTracking: yaml.latencyTracking,\n enableRoutingMemory: yaml.routingMemory,\n // Issue #755: New replacement stages\n enableConfidenceCascade: yaml.confidenceCascade,\n enableCapabilityMatch: yaml.capabilityMatch,\n enableQualityConstraint: yaml.qualityConstraint,\n // Issue #998: Resource strategy\n enableResourceStrategy: yaml.resourceStrategy,\n // Issue #999: Strategy distillation\n enableStrategyDistillation: yaml.strategyDistillation,\n };\n}\n\n/** Stage flag keys that need to be resolved with defaults. */\nconst STAGE_FLAG_KEYS = [\n 'enableBudgetFilter',\n 'enableZeroRouter',\n 'enablePreferenceRouting',\n 'enableTopsisRanking',\n 'enableLinUCBSelection',\n 'enableLatencyTracking',\n 'enableRoutingMemory',\n 'enableConfidenceCascade',\n 'enableCapabilityMatch',\n 'enableQualityConstraint',\n 'enableResourceStrategy',\n 'enableStrategyDistillation',\n 'enableKnnRouting',\n 'enableCapacityBalancing',\n] as const;\n\ntype StageFlagKey = (typeof STAGE_FLAG_KEYS)[number];\ntype StageFlagsResult = Pick<CompositeRouterConfig, StageFlagKey>;\n\n/**\n * Stage flags that default to `true` when learning persistence is enabled.\n * These features consume data already recorded by OutcomeStore and add\n * no new data collection surface. (#1347, #1353)\n */\nconst PERSISTENCE_AWARE_FLAGS: ReadonlySet<StageFlagKey> = new Set([\n 'enableRoutingMemory',\n 'enableStrategyDistillation',\n 'enablePreferenceRouting',\n]);\n\n/**\n * Resolves stage flags with defaults using a data-driven approach.\n * routingMemory and strategyDistillation default to true when persistence is on.\n */\nfunction resolveStageFlags(stagesConfig: Partial<CompositeRouterConfig>): StageFlagsResult {\n const persistenceOn = isPersistenceEnabled();\n const result = {} as StageFlagsResult;\n for (const key of STAGE_FLAG_KEYS) {\n const explicit = stagesConfig[key];\n if (explicit !== undefined) {\n result[key] = explicit;\n } else if (PERSISTENCE_AWARE_FLAGS.has(key) && persistenceOn) {\n result[key] = true;\n } else {\n result[key] = DEFAULT_COMPOSITE_CONFIG[key];\n }\n }\n return result;\n}\n\n/**\n * Builds the base CompositeRouterConfig from YAML config and defaults.\n */\nfunction buildBaseConfig(\n config: DefinedRoutingConfig,\n stagesConfig: Partial<CompositeRouterConfig>\n): CompositeRouterConfig {\n const stageFlags = resolveStageFlags(stagesConfig);\n\n return {\n ...stageFlags,\n billingMode: DEFAULT_COMPOSITE_CONFIG.billingMode,\n latencyScoreWeight: config.latencyScoreWeight,\n budgetConstraints: config.budget,\n linucbAlpha: config.linucb?.alpha ?? DEFAULT_COMPOSITE_CONFIG.linucbAlpha,\n maxDecisionTimeMs:\n config.linucb?.maxDecisionTimeMs ?? DEFAULT_COMPOSITE_CONFIG.maxDecisionTimeMs,\n preferenceMinDataPoints:\n config.preference?.minDataPoints ?? DEFAULT_COMPOSITE_CONFIG.preferenceMinDataPoints,\n };\n}\n\n/**\n * Converts RoutingConfig from YAML schema to CompositeRouterConfigWithPreference.\n *\n * @param yamlConfig - Routing config from nexus-agents.yaml\n * @returns Runtime config for CompositeRouter\n */\nexport function adaptRoutingConfig(\n yamlConfig?: RoutingConfig\n): CompositeRouterConfigWithPreference {\n const config: DefinedRoutingConfig = yamlConfig ?? ADAPTER_DEFAULTS;\n const stagesConfig = adaptStagesConfig(config.stages);\n const baseConfig = buildBaseConfig(config, stagesConfig);\n\n return {\n ...baseConfig,\n zeroRouterConfig: adaptZeroRouterConfig(config.zeroRouter),\n latencyTrackerConfig: adaptLatencyTrackerConfig(config.latencyTracker),\n routingMemoryConfig: adaptRoutingMemoryConfig(config.routingMemory),\n };\n}\n\n/**\n * Gets TOPSIS config from YAML routing config.\n * Useful when TOPSIS is used independently of CompositeRouter.\n *\n * @param yamlConfig - Routing config from nexus-agents.yaml\n * @returns Runtime TOPSIS config\n */\nexport function getTopsisConfigFromYaml(yamlConfig?: RoutingConfig): RuntimeTopsisConfig {\n const config: DefinedRoutingConfig = yamlConfig ?? ADAPTER_DEFAULTS;\n const adapted = adaptTopsisConfig(config.topsis);\n\n const result: RuntimeTopsisConfig = {\n criteria: adapted.criteria ?? DEFAULT_TOPSIS_CONFIG.criteria,\n minQualityThreshold: adapted.minQualityThreshold ?? DEFAULT_TOPSIS_CONFIG.minQualityThreshold,\n verbose: adapted.verbose ?? DEFAULT_TOPSIS_CONFIG.verbose,\n };\n\n if (adapted.maxLatencyMs !== undefined) {\n (result as { maxLatencyMs?: number }).maxLatencyMs = adapted.maxLatencyMs;\n }\n if (adapted.maxCostPerRequest !== undefined) {\n (result as { maxCostPerRequest?: number }).maxCostPerRequest = adapted.maxCostPerRequest;\n }\n\n return result;\n}\n","/**\n * ConfigManager - Runtime Configuration Management (Issue #360 Phase 1)\n *\n * Precedence (highest to lowest):\n * 1. CLI overrides 2. Session overrides 3. Environment variables 4. Package defaults\n *\n * @module config/config-manager\n */\n\nimport { z } from 'zod';\nimport { getTimeProvider } from '../core/index.js';\nimport { DEFAULTS } from './defaults.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Configuration source indicating where a value originated. */\nexport type ConfigSource = 'package' | 'env' | 'user_file' | 'session' | 'cli';\n\n/** Metadata about a configuration value. */\nexport interface ConfigValueMeta<T> {\n readonly value: T;\n readonly source: ConfigSource;\n readonly key: string;\n readonly isOverride: boolean;\n readonly defaultValue: T;\n}\n\n/** An active override entry. */\nexport interface ConfigOverride<T = unknown> {\n readonly value: T;\n readonly source: ConfigSource;\n readonly setAt: Date;\n}\n\n/** Configuration categories matching DEFAULTS structure. */\nexport type ConfigCategory = keyof typeof DEFAULTS;\n\n/** Keys for a specific category. */\nexport type ConfigKey<C extends ConfigCategory> = keyof (typeof DEFAULTS)[C];\n\n/** Widens literal types: 60000 -> number, true -> boolean, 'foo' -> string */\ntype Widen<T> = T extends number\n ? number\n : T extends boolean\n ? boolean\n : T extends string\n ? string\n : T;\n\n/** Value type for category/key (widened for assignment). */\nexport type ConfigValue<C extends ConfigCategory, K extends ConfigKey<C>> = Widen<\n (typeof DEFAULTS)[C][K]\n>;\n\n// ============================================================================\n// Validation\n// ============================================================================\n\nconst NumericValueSchema = z.number();\nconst BooleanValueSchema = z.boolean();\nconst StringValueSchema = z.string();\n\nfunction validateValue<T>(value: unknown, expectedType: T): value is T {\n if (typeof expectedType === 'number') return NumericValueSchema.safeParse(value).success;\n if (typeof expectedType === 'boolean') return BooleanValueSchema.safeParse(value).success;\n if (typeof expectedType === 'string') return StringValueSchema.safeParse(value).success;\n return false;\n}\n\n// ============================================================================\n// Environment Variable Mapping\n// ============================================================================\n\n/** Maps category.key to NEXUS_* environment variable names. */\nconst ENV_VAR_MAP: Partial<Record<string, string>> = {\n 'TIMEOUT_DEFAULTS.cliMs': 'NEXUS_TIMEOUT_CLI',\n 'TIMEOUT_DEFAULTS.apiMs': 'NEXUS_TIMEOUT_API',\n 'TIMEOUT_DEFAULTS.workflowMs': 'NEXUS_TIMEOUT_WORKFLOW',\n 'TIMEOUT_DEFAULTS.mcpMs': 'NEXUS_TIMEOUT_MCP',\n 'RATE_LIMIT_DEFAULTS.requestsPerMinute': 'NEXUS_RATE_LIMIT_RPM',\n 'RATE_LIMIT_DEFAULTS.enabled': 'NEXUS_RATE_LIMIT_ENABLED',\n 'RATE_LIMIT_DEFAULTS.maxConcurrent': 'NEXUS_RATE_LIMIT_MAX_CONCURRENT',\n 'RATE_LIMIT_DEFAULTS.capacity': 'NEXUS_RATE_LIMIT_CAPACITY',\n 'RATE_LIMIT_DEFAULTS.refillRate': 'NEXUS_RATE_LIMIT_REFILL_RATE',\n 'RATE_LIMIT_DEFAULTS.refillIntervalMs': 'NEXUS_RATE_LIMIT_REFILL_INTERVAL',\n 'RETRY_DEFAULTS.maxRetries': 'NEXUS_RETRY_MAX_RETRIES',\n 'RETRY_DEFAULTS.baseDelayMs': 'NEXUS_RETRY_BASE_DELAY',\n 'RETRY_DEFAULTS.maxDelayMs': 'NEXUS_RETRY_MAX_DELAY',\n 'RETRY_DEFAULTS.jitterFactor': 'NEXUS_RETRY_JITTER',\n 'WORKER_DEFAULTS.maxWorkers': 'NEXUS_WORKERS_MAX',\n 'WORKER_DEFAULTS.poolSize': 'NEXUS_WORKERS_POOL_SIZE',\n 'WORKER_DEFAULTS.idleTimeoutMs': 'NEXUS_WORKERS_IDLE_TIMEOUT',\n 'WORKER_DEFAULTS.workflowMaxParallel': 'NEXUS_WORKFLOW_MAX_PARALLEL',\n 'WORKER_DEFAULTS.testParallelism': 'NEXUS_TEST_PARALLELISM',\n 'WORKER_DEFAULTS.evaluationMaxWorkers': 'NEXUS_EVALUATION_MAX_WORKERS',\n 'WORKER_DEFAULTS.eventBusMaxHistory': 'NEXUS_EVENTBUS_MAX_HISTORY',\n 'WORKER_DEFAULTS.swarmObserverMaxEvents': 'NEXUS_SWARM_OBSERVER_MAX_EVENTS',\n 'CIRCUIT_BREAKER_DEFAULTS.failureThreshold': 'NEXUS_CIRCUIT_BREAKER_THRESHOLD',\n 'CIRCUIT_BREAKER_DEFAULTS.resetTimeoutMs': 'NEXUS_CIRCUIT_BREAKER_RESET_TIMEOUT',\n};\n\nfunction parseEnvValue<T>(envValue: string, defaultValue: T): T | undefined {\n if (typeof defaultValue === 'number') {\n const parsed = Number(envValue);\n return !isNaN(parsed) && isFinite(parsed) ? (parsed as T) : undefined;\n }\n if (typeof defaultValue === 'boolean') {\n const lower = envValue.toLowerCase();\n if (lower === 'true' || lower === '1') return true as T;\n if (lower === 'false' || lower === '0') return false as T;\n return undefined; // Unknown value — use default\n }\n if (typeof defaultValue === 'string') return envValue as T;\n return undefined;\n}\n\n// ============================================================================\n// ConfigManager Class\n// ============================================================================\n\n/**\n * Singleton ConfigManager for runtime configuration management.\n *\n * @example\n * const config = ConfigManager.getInstance();\n * const timeout = config.get('TIMEOUT_DEFAULTS', 'cliMs');\n * config.setOverride('TIMEOUT_DEFAULTS', 'cliMs', 90000, 'session');\n */\nexport class ConfigManager {\n private static instance: ConfigManager | null = null;\n private readonly overrides: Map<string, ConfigOverride> = new Map();\n\n private constructor() {}\n\n /** Gets the singleton instance. */\n static getInstance(): ConfigManager {\n ConfigManager.instance ??= new ConfigManager();\n return ConfigManager.instance;\n }\n\n /** Resets the singleton instance (for testing). */\n static resetInstance(): void {\n ConfigManager.instance = null;\n }\n\n /** Gets the effective value for a configuration key. */\n get<C extends ConfigCategory, K extends ConfigKey<C>>(category: C, key: K): ConfigValue<C, K> {\n return this.getWithMeta(category, key).value;\n }\n\n /** Gets the effective value with source metadata. */\n getWithMeta<C extends ConfigCategory, K extends ConfigKey<C>>(\n category: C,\n key: K\n ): ConfigValueMeta<ConfigValue<C, K>> {\n const fullKey = `${category}.${String(key)}`;\n const defaultValue = DEFAULTS[category][key] as ConfigValue<C, K>;\n\n // Check overrides (CLI > session)\n const override = this.overrides.get(fullKey);\n if (override) {\n return {\n value: override.value as ConfigValue<C, K>,\n source: override.source,\n key: fullKey,\n isOverride: true,\n defaultValue,\n };\n }\n\n // Check environment variable\n const envVar = ENV_VAR_MAP[fullKey];\n if (envVar !== undefined && envVar.length > 0) {\n const envValue = process.env[envVar];\n if (envValue !== undefined) {\n const parsed = parseEnvValue(envValue, defaultValue);\n if (parsed !== undefined) {\n return { value: parsed, source: 'env', key: fullKey, isOverride: true, defaultValue };\n }\n }\n }\n\n return {\n value: defaultValue,\n source: 'package',\n key: fullKey,\n isOverride: false,\n defaultValue,\n };\n }\n\n /**\n * Sets an override for a configuration key.\n * @throws {Error} If value fails type validation\n */\n setOverride<C extends ConfigCategory, K extends ConfigKey<C>>(\n category: C,\n key: K,\n value: ConfigValue<C, K>,\n source: ConfigSource\n ): void {\n const fullKey = `${category}.${String(key)}`;\n const defaultValue = DEFAULTS[category][key];\n\n if (!validateValue(value, defaultValue)) {\n throw new Error(\n `Invalid value type for ${fullKey}: expected ${typeof defaultValue}, got ${typeof value}`\n );\n }\n\n this.overrides.set(fullKey, { value, source, setAt: new Date(getTimeProvider().now()) });\n }\n\n /** Clears an override. Returns true if it existed. */\n clearOverride<C extends ConfigCategory>(category: C, key: ConfigKey<C>): boolean {\n return this.overrides.delete(`${category}.${String(key)}`);\n }\n\n /** Clears all overrides. */\n clearAllOverrides(): void {\n this.overrides.clear();\n }\n\n /** Lists all active overrides. */\n listOverrides(): ReadonlyArray<{\n key: string;\n value: unknown;\n source: ConfigSource;\n setAt: Date;\n }> {\n return Array.from(this.overrides.entries()).map(([key, override]) => ({\n key,\n value: override.value,\n source: override.source,\n setAt: override.setAt,\n }));\n }\n\n /** Lists all configuration keys with their effective values. */\n listAll(categoryFilter?: ConfigCategory): ReadonlyArray<{\n category: string;\n key: string;\n value: unknown;\n source: ConfigSource;\n envVar: string | undefined;\n }> {\n const categories = categoryFilter\n ? [categoryFilter]\n : (Object.keys(DEFAULTS) as ConfigCategory[]);\n const result: Array<{\n category: string;\n key: string;\n value: unknown;\n source: ConfigSource;\n envVar: string | undefined;\n }> = [];\n\n for (const category of categories) {\n for (const key of Object.keys(DEFAULTS[category])) {\n const fullKey = `${category}.${key}`;\n const meta = this.getWithMeta(category, key as ConfigKey<typeof category>);\n result.push({\n category,\n key,\n value: meta.value,\n source: meta.source,\n envVar: ENV_VAR_MAP[fullKey],\n });\n }\n }\n return result;\n }\n\n /** Gets the environment variable name for a config key. */\n getEnvVarName<C extends ConfigCategory>(category: C, key: ConfigKey<C>): string | undefined {\n return ENV_VAR_MAP[`${category}.${String(key)}`];\n }\n\n /** Checks if a key has an active override. */\n hasOverride<C extends ConfigCategory>(category: C, key: ConfigKey<C>): boolean {\n return this.overrides.has(`${category}.${String(key)}`);\n }\n}\n\n/** Gets the ConfigManager singleton instance. */\nexport function getConfigManager(): ConfigManager {\n return ConfigManager.getInstance();\n}\n","/**\n * nexus-agents/config - Config File Loader\n *\n * Loads and validates nexus-agents.yaml using AppConfigSchema.\n * This module provides the missing link between the config file and runtime.\n *\n * @module config/config-loader\n * (Source: Issue #472 - Wire AppConfigSchema to runtime)\n */\n\nimport { readFileSync, existsSync } from 'node:fs';\nimport { resolve, join } from 'node:path';\nimport { resolveInsideRoot } from '../security/safe-path.js';\nimport { getNexusDataDir } from './nexus-data-dir.js';\nimport * as yaml from 'yaml';\nimport { AppConfigSchema, type AppConfig, defaultConfig } from './schemas.js';\nimport type { Result } from '../core/index.js';\nimport { ok, err, formatZodIssuesAsArray } from '../core/index.js';\nimport type { ILogger } from '../core/index.js';\nimport { createLogger } from '../core/logger.js';\n\n/**\n * Default config file name.\n */\nconst DEFAULT_CONFIG_FILE = 'nexus-agents.yaml';\n\n/**\n * Alternate config file name.\n */\nconst ALTERNATE_CONFIG_FILE = 'nexus-agents.yml';\n\n/**\n * Result of loading configuration.\n */\nexport interface ConfigLoadResult {\n /** The validated configuration */\n config: AppConfig;\n /** Path to config file (if loaded from file) */\n configPath?: string;\n /** Whether defaults were used */\n usingDefaults: boolean;\n /** Validation warnings (partial config merged with defaults) */\n warnings: string[];\n}\n\n/**\n * Error when config loading fails.\n */\nexport class ConfigLoadError extends Error {\n public readonly code: ConfigLoadErrorCode;\n\n constructor(message: string, code: ConfigLoadErrorCode, cause?: Error) {\n super(message, { cause });\n this.name = 'ConfigLoadError';\n this.code = code;\n }\n}\n\nexport type ConfigLoadErrorCode =\n | 'FILE_READ_ERROR'\n | 'YAML_PARSE_ERROR'\n | 'VALIDATION_ERROR'\n | 'PATH_TRAVERSAL';\n\n/**\n * Options for loading configuration.\n */\nexport interface ConfigLoadOptions {\n /** Explicit path to config file */\n configPath?: string;\n /** Logger for diagnostics */\n logger?: ILogger;\n /** Working directory for relative paths (default: process.cwd()) */\n cwd?: string;\n /** Whether to merge with defaults (default: true) */\n mergeDefaults?: boolean;\n}\n\n/**\n * Validates that a path doesn't escape the allowed root.\n */\nfunction validatePath(userPath: string, root: string): Result<string, ConfigLoadError> {\n const resolved = resolveInsideRoot(userPath, root);\n if (resolved === null) {\n return err(\n new ConfigLoadError(\n `Config path traversal detected: ${userPath} escapes ${root}`,\n 'PATH_TRAVERSAL'\n )\n );\n }\n return ok(resolved);\n}\n\n/**\n * Finds the config file path.\n */\nfunction findConfigPath(cwd: string): string | undefined {\n // Check environment variable first\n const envPath = process.env['NEXUS_CONFIG_PATH'];\n if (envPath !== undefined && envPath !== '') {\n const validation = validatePath(envPath, cwd);\n if (validation.ok && existsSync(validation.value)) {\n return validation.value;\n }\n }\n\n // Check current directory for .yaml\n const yamlPath = resolve(cwd, DEFAULT_CONFIG_FILE);\n if (existsSync(yamlPath)) {\n return yamlPath;\n }\n\n // Check current directory for .yml\n const ymlPath = resolve(cwd, ALTERNATE_CONFIG_FILE);\n if (existsSync(ymlPath)) {\n return ymlPath;\n }\n\n // Check global config directory (resolved data dir) as fallback (#1265 + #2316)\n const globalDir = getNexusDataDir();\n const globalYamlPath = join(globalDir, DEFAULT_CONFIG_FILE);\n if (existsSync(globalYamlPath)) {\n return globalYamlPath;\n }\n const globalYmlPath = join(globalDir, ALTERNATE_CONFIG_FILE);\n if (existsSync(globalYmlPath)) {\n return globalYmlPath;\n }\n\n return undefined;\n}\n\n/**\n * Parses YAML content safely.\n */\nfunction parseYaml(content: string): Result<unknown, ConfigLoadError> {\n try {\n const parsed: unknown = yaml.parse(content);\n return ok(parsed);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown YAML parse error';\n return err(\n new ConfigLoadError(`YAML parse error: ${message}`, 'YAML_PARSE_ERROR', error as Error)\n );\n }\n}\n\n/** Keys that must never be merged — they target the prototype chain (CWE-1321). */\nconst PROTOTYPE_POLLUTION_KEYS: ReadonlySet<string> = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n]);\n\n/** True when both values are mergeable plain objects (not arrays/null). */\nfunction isMergeableObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Deep merges two objects, with source taking precedence.\n *\n * Exported for direct unit testing of the prototype-pollution guard.\n * @internal\n */\nexport function deepMerge(\n target: Record<string, unknown>,\n source: Record<string, unknown>\n): Record<string, unknown> {\n const result: Record<string, unknown> = { ...target };\n\n for (const key of Object.keys(source)) {\n if (PROTOTYPE_POLLUTION_KEYS.has(key)) continue;\n const sourceValue = source[key];\n if (sourceValue === undefined) continue;\n const targetValue = target[key];\n\n if (isMergeableObject(sourceValue) && isMergeableObject(targetValue)) {\n result[key] = deepMerge(targetValue, sourceValue);\n } else {\n result[key] = sourceValue;\n }\n }\n\n return result;\n}\n\n/** Returns default config when no file is found. */\nfunction loadDefaultConfig(logger: ILogger): Result<ConfigLoadResult, ConfigLoadError> {\n logger.debug('No config file found, using defaults');\n const validated = AppConfigSchema.safeParse(defaultConfig);\n if (!validated.success) {\n return err(\n new ConfigLoadError(\n `Default config validation failed: ${validated.error.message}`,\n 'VALIDATION_ERROR'\n )\n );\n }\n return ok({\n config: validated.data,\n usingDefaults: true,\n warnings: ['No config file found, using default configuration'],\n });\n}\n\n/** Reads and parses config file content. */\nfunction readAndParseConfig(\n configPath: string,\n mergeDefaults: boolean,\n logger: ILogger\n): Result<unknown, ConfigLoadError> {\n let content: string;\n try {\n content = readFileSync(configPath, 'utf-8');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return err(\n new ConfigLoadError(\n `Failed to read config file: ${message}`,\n 'FILE_READ_ERROR',\n error as Error\n )\n );\n }\n\n const parseResult = parseYaml(content);\n if (!parseResult.ok) return err(parseResult.error);\n\n if (mergeDefaults && typeof parseResult.value === 'object' && parseResult.value !== null) {\n logger.debug('Merged config with defaults');\n return ok(\n deepMerge(\n defaultConfig as Record<string, unknown>,\n parseResult.value as Record<string, unknown>\n )\n );\n }\n return ok(parseResult.value);\n}\n\n/** Validates parsed config against schema. */\nfunction validateConfig(\n configData: unknown,\n configPath: string,\n logger: ILogger\n): Result<ConfigLoadResult, ConfigLoadError> {\n const validation = AppConfigSchema.safeParse(configData);\n if (!validation.success) {\n const issues = formatZodIssuesAsArray(validation.error);\n return err(\n new ConfigLoadError(`Config validation failed:\\n${issues.join('\\n')}`, 'VALIDATION_ERROR')\n );\n }\n logger.info('Configuration loaded successfully', { configPath });\n return ok({ config: validation.data, configPath, usingDefaults: false, warnings: [] });\n}\n\n/**\n * Loads and validates configuration from a file.\n */\nexport function loadConfig(\n options: ConfigLoadOptions = {}\n): Result<ConfigLoadResult, ConfigLoadError> {\n const { configPath: explicitPath, cwd = process.cwd(), mergeDefaults = true } = options;\n const logger = options.logger ?? createLogger({ component: 'ConfigLoader' });\n\n // Resolve config file path\n let configPath: string | undefined;\n if (explicitPath !== undefined) {\n const validation = validatePath(explicitPath, cwd);\n if (!validation.ok) return err(validation.error);\n configPath = validation.value;\n } else {\n configPath = findConfigPath(cwd);\n }\n\n // Use defaults if no config file found\n if (configPath === undefined) return loadDefaultConfig(logger);\n\n // Read, parse, and validate\n const parseResult = readAndParseConfig(configPath, mergeDefaults, logger);\n if (!parseResult.ok) return err(parseResult.error);\n\n return validateConfig(parseResult.value, configPath, logger);\n}\n\n/**\n * Singleton instance of loaded configuration.\n * Lazily initialized on first access.\n */\nlet loadedConfig: ConfigLoadResult | undefined;\n\n/**\n * Gets the currently loaded configuration.\n * Loads from file on first call, then returns cached result.\n *\n * @param options - Load options (only used on first call)\n * @returns The loaded configuration\n * @throws ConfigLoadError if loading fails\n */\nexport function getConfig(options?: ConfigLoadOptions): ConfigLoadResult {\n if (loadedConfig !== undefined) {\n return loadedConfig;\n }\n\n const result = loadConfig(options);\n if (!result.ok) {\n throw result.error;\n }\n loadedConfig = result.value;\n return loadedConfig;\n}\n\n/**\n * Clears the cached configuration.\n * Useful for testing or hot-reloading.\n */\nexport function clearConfigCache(): void {\n loadedConfig = undefined;\n}\n\n/**\n * Reloads configuration from file.\n * Replaces the cached configuration.\n *\n * @param options - Load options\n * @returns Result with new configuration or error\n */\nexport function reloadConfig(\n options?: ConfigLoadOptions\n): Result<ConfigLoadResult, ConfigLoadError> {\n clearConfigCache();\n const result = loadConfig(options);\n if (result.ok) {\n loadedConfig = result.value;\n }\n return result;\n}\n","/**\n * nexus-agents data directory initialization\n *\n * Pre-creates ~/.nexus-agents/ directory structure with proper permissions.\n * Used by `nexus-agents setup` to ensure data directories exist before first use.\n *\n * @module cli/setup-data-dir\n * (Source: Issue #1249 - Developer experience improvements)\n */\n\nimport { mkdirSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { DATA_SUBDIRECTORIES } from './doctor.js';\nimport { getNexusDataDir } from '../config/nexus-data-dir.js';\n\n/**\n * Root data directory path.\n *\n * Resolves to `$NEXUS_DATA_DIR` when set, else `<homedir>/.nexus-agents`.\n * See `src/config/nexus-data-dir.ts` for resolution rules (#2302).\n *\n * Evaluated at module-import time. Tests that mutate `NEXUS_DATA_DIR`\n * mid-process should call `resetNexusDataDirCache()` and re-import, or\n * call `getNexusDataDir()` directly.\n */\nexport const NEXUS_DATA_DIR = getNexusDataDir();\n\n/** Subdirectories requiring restricted permissions (owner-only). */\nconst RESTRICTED_DIRS = new Set(['auth']);\n\n/**\n * Result of data directory initialization.\n */\nexport interface DataDirInitResult {\n readonly success: boolean;\n readonly rootPath: string;\n readonly created: readonly string[];\n readonly alreadyExisted: readonly string[];\n readonly error: string | null;\n}\n\n/**\n * Creates the ~/.nexus-agents/ directory structure.\n * Sets restrictive permissions (0o700) on auth/ directory.\n *\n * @param dryRun - If true, reports what would be created without creating.\n * @returns Result of initialization.\n */\nexport function initDataDirectories(dryRun: boolean = false): DataDirInitResult {\n const created: string[] = [];\n const alreadyExisted: string[] = [];\n\n try {\n ensureDir(NEXUS_DATA_DIR, dryRun, created, alreadyExisted);\n\n for (const subdir of DATA_SUBDIRECTORIES) {\n const mode = RESTRICTED_DIRS.has(subdir) ? 0o700 : undefined;\n ensureDir(join(NEXUS_DATA_DIR, subdir), dryRun, created, alreadyExisted, mode);\n }\n\n return { success: true, rootPath: NEXUS_DATA_DIR, created, alreadyExisted, error: null };\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n return { success: false, rootPath: NEXUS_DATA_DIR, created, alreadyExisted, error: msg };\n }\n}\n\n/** Creates a single directory if it doesn't exist, tracking the result. */\nfunction ensureDir(\n dirPath: string,\n dryRun: boolean,\n created: string[],\n alreadyExisted: string[],\n mode?: number\n): void {\n if (existsSync(dirPath)) {\n alreadyExisted.push(dirPath);\n return;\n }\n if (!dryRun) {\n mkdirSync(dirPath, { recursive: true, ...(mode !== undefined ? { mode } : {}) });\n }\n created.push(dirPath);\n}\n","/* eslint-disable max-lines -- Cohesive doctor command module (governance: 400-600 OK if cohesive) */\n/**\n * nexus-agents doctor command\n *\n * Health check utility for CLI integration validation.\n * Verifies CLI installations, versions, authentication, Node.js version,\n * API keys, configuration files, and MCP server readiness.\n *\n * (Source: Issue #91, cli-project_plan.md DevEx amendment)\n * (Source: Issue #422 - Doctor command validations)\n */\n\nimport { existsSync, readFileSync, accessSync, constants as fsConstants } from 'node:fs';\nimport { join } from 'node:path';\nimport { getNexusDataDir } from '../config/nexus-data-dir.js';\nimport { getTimeProvider, getErrorMessage } from '../core/index.js';\nimport {\n isPersistenceEnabled,\n getLearningDir,\n getOutcomesFile,\n getRulesFile,\n} from '../config/learning-persistence.js';\nimport { createAllAdapters } from '../cli-adapters/factory.js';\nimport type { CliName, HealthStatus, CapacityStatus } from '../cli-adapters/types.js';\nimport { DEFAULT_MODEL_CAPABILITIES } from '../config/model-capabilities.js';\nimport { createServer } from '../mcp/server.js';\nimport { printDoctorResults } from './doctor-formatting.js';\n\n/** Required Node.js major version. */\nconst REQUIRED_NODE_MAJOR = 22;\n\n/** API key environment variable names. */\nconst API_KEY_VARS = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GOOGLE_AI_API_KEY'] as const;\n\n/** Configuration file paths to check (in order of priority). */\nconst CONFIG_FILE_PATHS = ['./nexus-agents.yaml', './nexus-agents.yml'] as const;\n\n/**\n * Check result for a single CLI.\n */\nexport interface CliCheckResult {\n readonly name: CliName;\n readonly installed: boolean;\n readonly version: string;\n readonly versionStatus: 'supported' | 'outdated' | 'unsupported' | 'breaking';\n readonly authenticated: boolean;\n readonly authMethod?: string;\n readonly capacity?: CapacityStatus;\n readonly error?: string;\n readonly fix?: string;\n}\n\n/**\n * Node.js version check result.\n */\nexport interface NodeVersionCheck {\n readonly version: string;\n readonly major: number;\n readonly supported: boolean;\n}\n\n/**\n * API key check result.\n */\nexport interface ApiKeyCheck {\n readonly name: string;\n readonly configured: boolean;\n}\n\n/**\n * Configuration file check result.\n */\nexport interface ConfigFileCheck {\n readonly found: boolean;\n readonly path: string | null;\n}\n\n/**\n * Model availability advisory entry (#890).\n */\nexport interface ModelAdvisory {\n readonly modelId: string;\n readonly displayName: string;\n readonly cliName: string;\n readonly available: boolean;\n readonly reason: string;\n}\n\n/**\n * Learning persistence health check result (#1017).\n */\nexport interface LearningPersistenceCheck {\n readonly enabled: boolean;\n readonly dirExists: boolean;\n readonly dirWritable: boolean;\n readonly outcomeCount: number;\n readonly ruleCount: number;\n readonly rulesLastSaved: string | null;\n readonly error: string | null;\n}\n\n/**\n * Registry advisory summary (#890).\n */\nexport interface RegistryAdvisory {\n readonly totalModels: number;\n readonly availableModels: number;\n readonly unavailableModels: number;\n readonly models: readonly ModelAdvisory[];\n /** Days since the registry was last updated. */\n readonly registryAgeDays: number;\n /** True if the registry is >30 days old and may have stale model data. */\n readonly registryStale: boolean;\n}\n\n/**\n * SQLite (better-sqlite3) availability check (#1249).\n */\nexport interface SqliteCheck {\n readonly available: boolean;\n readonly error: string | null;\n}\n\n/**\n * Data directory health check (#1249).\n * Reports status of ~/.nexus-agents/ and its subdirectories.\n */\nexport interface DataDirectoryCheck {\n readonly rootExists: boolean;\n readonly rootPath: string;\n readonly subdirectories: readonly DataSubdirStatus[];\n}\n\n/**\n * Status of a single data subdirectory.\n */\nexport interface DataSubdirStatus {\n readonly name: string;\n readonly path: string;\n readonly exists: boolean;\n readonly writable: boolean;\n}\n\n/** Standard data subdirectories under ~/.nexus-agents/. */\nexport const DATA_SUBDIRECTORIES = [\n 'memory',\n 'memory/beliefs',\n 'learning',\n 'sessions',\n 'audit',\n 'voting',\n 'auth',\n 'research',\n 'checkpoints',\n] as const;\n\n/**\n * Complete doctor check results.\n */\nexport interface DoctorResult {\n readonly clis: CliCheckResult[];\n readonly nodeVersion: NodeVersionCheck;\n readonly apiKeys: ApiKeyCheck[];\n readonly configFile: ConfigFileCheck;\n readonly mcpServerReady: boolean;\n readonly mcpClientReady: boolean;\n /** Model registry advisory — which models are available (#890). */\n readonly registryAdvisory: RegistryAdvisory;\n /** Learning persistence health check (#1017). */\n readonly learningPersistence: LearningPersistenceCheck;\n /** SQLite (better-sqlite3) availability (#1249). */\n readonly sqliteCheck: SqliteCheck;\n /** Data directory health (#1249). */\n readonly dataDirectory: DataDirectoryCheck;\n readonly allHealthy: boolean;\n readonly timestamp: Date;\n}\n\n/**\n * Gets the CLI install/upgrade fix command.\n */\nfunction getFixCommand(name: CliName, issue: 'install' | 'upgrade' | 'auth'): string {\n const commands: Record<CliName, Record<string, string>> = {\n claude: {\n install: 'npm install -g @anthropic-ai/claude-code',\n upgrade: 'npm update -g @anthropic-ai/claude-code',\n auth: 'claude auth login',\n },\n gemini: {\n install: 'npm install -g @google/gemini-cli',\n upgrade: 'npm update -g @google/gemini-cli',\n auth: 'gemini auth login',\n },\n codex: {\n install: 'npm install -g @openai/codex',\n upgrade: 'npm update -g @openai/codex',\n auth: 'codex auth login',\n },\n opencode: {\n install: 'npm install -g opencode-ai',\n upgrade: 'npm update -g opencode-ai',\n auth: 'opencode auth login',\n },\n };\n return commands[name][issue] ?? '';\n}\n\n/**\n * Creates a result for when a CLI is not found.\n */\nfunction createNotFoundResult(name: CliName, errorMsg: string): CliCheckResult {\n return {\n name,\n installed: false,\n version: 'N/A',\n versionStatus: 'unsupported',\n authenticated: false,\n error: errorMsg,\n fix: getFixCommand(name, 'install'),\n };\n}\n\n/**\n * Determines the authentication method based on CLI name.\n * CLIs use their own auth mechanisms - we report the method type\n * rather than assuming a specific one like 'OAuth'.\n */\nfunction detectAuthMethod(name: CliName): string {\n const authMethods: Record<CliName, string> = {\n claude: 'CLI auth',\n gemini: 'ADC/CLI auth',\n codex: 'CLI auth',\n opencode: 'CLI auth',\n };\n return authMethods[name];\n}\n\n/**\n * Creates a result from a successful health check.\n */\nfunction createHealthyResult(\n name: CliName,\n health: HealthStatus,\n capacity?: CapacityStatus\n): CliCheckResult {\n const authenticated = health.healthy;\n\n const result: CliCheckResult = {\n name,\n installed: true,\n version: health.version,\n versionStatus: health.versionStatus,\n authenticated,\n ...(authenticated && { authMethod: detectAuthMethod(name) }),\n ...(capacity !== undefined && { capacity }),\n };\n\n if (health.message !== undefined && health.message !== '') {\n return { ...result, error: health.message };\n }\n if (!authenticated) {\n return { ...result, fix: getFixCommand(name, 'auth') };\n }\n if (health.versionStatus === 'outdated') {\n return { ...result, fix: getFixCommand(name, 'upgrade') };\n }\n\n return result;\n}\n\n/**\n * Runs health check on a single CLI adapter.\n */\nasync function checkCli(name: CliName): Promise<CliCheckResult> {\n const adapters = createAllAdapters();\n const adapter = adapters.get(name);\n\n if (!adapter) {\n return createNotFoundResult(name, 'Adapter not available');\n }\n\n try {\n const health: HealthStatus = await adapter.healthCheck();\n let capacity: CapacityStatus | undefined;\n\n try {\n capacity = await adapter.getCapacity();\n } catch (capErr: unknown) {\n // Capacity check is optional — some adapters don't support it\n void capErr; // Logged at debug via adapter internals\n }\n\n return createHealthyResult(name, health, capacity);\n } catch (error) {\n const message = getErrorMessage(error);\n const isNotFound = message.includes('ENOENT') || message.includes('not found');\n return createNotFoundResult(name, isNotFound ? 'Not found in PATH' : message);\n }\n}\n\n/**\n * Checks the Node.js version against the required version.\n */\nfunction checkNodeVersion(): NodeVersionCheck {\n const version = process.version;\n const major = Number(version.slice(1).split('.')[0]);\n return {\n version,\n major,\n supported: major >= REQUIRED_NODE_MAJOR,\n };\n}\n\n/**\n * Checks which API keys are configured in the environment.\n * Does NOT expose the actual key values - only reports presence.\n *\n * Exported so `verify` (#2136) and other health gates can reuse it without\n * running the full doctor pipeline.\n */\nexport function checkApiKeys(): ApiKeyCheck[] {\n return API_KEY_VARS.map((name) => ({\n name,\n configured: typeof process.env[name] === 'string' && process.env[name] !== '',\n }));\n}\n\n/**\n * Checks for the existence of a configuration file.\n */\nfunction checkConfigFile(): ConfigFileCheck {\n for (const configPath of CONFIG_FILE_PATHS) {\n if (existsSync(configPath)) {\n return { found: true, path: configPath };\n }\n }\n return { found: false, path: null };\n}\n\n/**\n * Validates that the MCP server can be created successfully.\n * This is a lightweight check that verifies server instantiation works.\n */\nfunction checkMcpServerReady(): boolean {\n try {\n const result = createServer({ name: 'nexus-agents-doctor-check' });\n return result.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Builds model registry advisory based on detected CLI availability (#890).\n */\nfunction buildRegistryAdvisory(cliResults: CliCheckResult[]): RegistryAdvisory {\n const installedClis = new Set(cliResults.filter((c) => c.installed).map((c) => c.name));\n\n const models: ModelAdvisory[] = DEFAULT_MODEL_CAPABILITIES.models\n .filter((m) => m.cliName !== undefined)\n .map((m) => {\n const cliName = m.cliName ?? '';\n const available = cliName.length > 0 && installedClis.has(cliName as CliName);\n const reason = available ? `${cliName} CLI is installed` : `${cliName} CLI is not installed`;\n return { modelId: m.id, displayName: m.displayName, cliName, available, reason };\n });\n\n // Registry staleness check (#1549)\n const STALE_THRESHOLD_DAYS = 30;\n const updatedAt = new Date(DEFAULT_MODEL_CAPABILITIES.updatedAt);\n const nowMs = getTimeProvider().now();\n const ageDays = Math.floor((nowMs - updatedAt.getTime()) / (1000 * 60 * 60 * 24));\n\n return {\n totalModels: models.length,\n availableModels: models.filter((m) => m.available).length,\n unavailableModels: models.filter((m) => !m.available).length,\n models,\n registryAgeDays: ageDays,\n registryStale: ageDays > STALE_THRESHOLD_DAYS,\n };\n}\n\n/** Counts non-empty lines in a JSONL file. Returns 0 if file doesn't exist. */\nfunction countJsonlLines(filePath: string): number {\n if (!existsSync(filePath)) return 0;\n return readFileSync(filePath, 'utf-8')\n .split('\\n')\n .filter((l) => l.trim().length > 0).length;\n}\n\n/** Reads rules snapshot metadata. Returns count and savedAt. */\nfunction readRulesMetadata(filePath: string): { count: number; savedAt: string | null } {\n if (!existsSync(filePath)) return { count: 0, savedAt: null };\n try {\n const raw = JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, unknown>;\n const rules = raw['rules'];\n const saved = raw['savedAt'];\n return {\n count: Array.isArray(rules) ? rules.length : 0,\n savedAt: typeof saved === 'string' ? saved : null,\n };\n } catch {\n return { count: 0, savedAt: null };\n }\n}\n\n/** Checks if a directory exists and is writable. */\nfunction checkDirAccess(dir: string): { exists: boolean; writable: boolean } {\n const exists = existsSync(dir);\n if (!exists) return { exists: false, writable: false };\n try {\n accessSync(dir, fsConstants.W_OK);\n return { exists: true, writable: true };\n } catch {\n return { exists: true, writable: false };\n }\n}\n\nconst DISABLED_CHECK: LearningPersistenceCheck = {\n enabled: false,\n dirExists: false,\n dirWritable: false,\n outcomeCount: 0,\n ruleCount: 0,\n rulesLastSaved: null,\n error: null,\n};\n\n/** Checks learning persistence health (#1017). */\nfunction checkLearningPersistence(): LearningPersistenceCheck {\n if (!isPersistenceEnabled()) return DISABLED_CHECK;\n try {\n const { exists: dirExists, writable: dirWritable } = checkDirAccess(getLearningDir());\n const outcomeCount = countJsonlLines(getOutcomesFile());\n const { count: ruleCount, savedAt: rulesLastSaved } = readRulesMetadata(getRulesFile());\n return {\n enabled: true,\n dirExists,\n dirWritable,\n outcomeCount,\n ruleCount,\n rulesLastSaved,\n error: null,\n };\n } catch (error: unknown) {\n return {\n enabled: true,\n dirExists: false,\n dirWritable: false,\n outcomeCount: 0,\n ruleCount: 0,\n rulesLastSaved: null,\n error: getErrorMessage(error),\n };\n }\n}\n\n/**\n * Checks if better-sqlite3 is available (#1249).\n * Memory backends (agentic, adaptive, typed, mobimem, decay) require it.\n *\n * Exported so `verify` (#2136) can reuse it without running the full doctor\n * pipeline.\n */\nexport async function checkSqlite(): Promise<SqliteCheck> {\n try {\n await import('better-sqlite3');\n return { available: true, error: null };\n } catch (error: unknown) {\n const msg = getErrorMessage(error);\n const isNotFound = msg.includes('Cannot find') || msg.includes('MODULE_NOT_FOUND');\n return {\n available: false,\n error: isNotFound\n ? 'better-sqlite3 not installed — 5 memory backends unavailable'\n : `better-sqlite3 load error: ${msg}`,\n };\n }\n}\n\n/**\n * Checks the ~/.nexus-agents/ data directory health (#1249).\n *\n * Exported so `verify` (#2136) can reuse it without running the full doctor\n * pipeline.\n */\nexport function checkDataDirectory(): DataDirectoryCheck {\n const rootPath = getNexusDataDir();\n const rootExists = existsSync(rootPath);\n\n const subdirectories: DataSubdirStatus[] = DATA_SUBDIRECTORIES.map((name) => {\n const fullPath = join(rootPath, name);\n const exists = existsSync(fullPath);\n return { name, path: fullPath, exists, writable: exists && isWritable(fullPath) };\n });\n\n return { rootExists, rootPath, subdirectories };\n}\n\n/** Checks if a directory is writable by the current user. */\nfunction isWritable(dirPath: string): boolean {\n try {\n accessSync(dirPath, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Runs the complete doctor check.\n */\nexport async function runDoctor(): Promise<DoctorResult> {\n const clis = await Promise.all([\n checkCli('claude'),\n checkCli('gemini'),\n checkCli('codex'),\n checkCli('opencode'),\n ]);\n const nodeVersion = checkNodeVersion();\n const apiKeys = checkApiKeys();\n const configFile = checkConfigFile();\n const mcpServerReady = checkMcpServerReady();\n const codexCheck = clis.find((c) => c.name === 'codex');\n const mcpClientReady = codexCheck?.installed ?? false;\n const registryAdvisory = buildRegistryAdvisory(clis);\n const learningPersistence = checkLearningPersistence();\n const sqliteCheck = await checkSqlite();\n const dataDirectory = checkDataDirectory();\n\n // At least one API key configured or one CLI authenticated\n const hasAuthMethod =\n apiKeys.some((k) => k.configured) || clis.some((c) => c.installed && c.authenticated);\n\n const allHealthy =\n nodeVersion.supported &&\n hasAuthMethod &&\n mcpServerReady &&\n clis.every((c) => c.installed && c.authenticated && c.versionStatus !== 'unsupported');\n\n return {\n clis,\n nodeVersion,\n apiKeys,\n configFile,\n mcpServerReady,\n mcpClientReady,\n registryAdvisory,\n learningPersistence,\n sqliteCheck,\n dataDirectory,\n allHealthy,\n timestamp: new Date(getTimeProvider().now()),\n };\n}\n\n/** Doctor command options. */\nexport interface DoctorOptions {\n /** Auto-fix safe issues (run setup, generate config). */\n readonly fix?: boolean;\n}\n\n/**\n * Runs the doctor command and prints results.\n * Returns exit code (0 = healthy, 1 = issues found).\n */\nexport async function doctorCommand(options: DoctorOptions = {}): Promise<number> {\n const result = await runDoctor();\n printDoctorResults(result);\n\n if (options.fix === true) {\n await runDoctorFix(result);\n }\n\n return result.allHealthy ? 0 : 1;\n}\n\n/**\n * Auto-fixes safe issues found by doctor (#1254).\n * Only runs our own code — never execs external package managers.\n */\nasync function runDoctorFix(result: DoctorResult): Promise<void> {\n const writeLine = (text: string): void => {\n process.stdout.write(text + '\\n');\n };\n\n writeLine('');\n writeLine('\\x1b[1mAuto-fix\\x1b[0m');\n writeLine('─'.repeat(40));\n\n let fixCount = 0;\n\n // Fix: data directories (missing or not writable)\n if (\n !result.dataDirectory.rootExists ||\n result.dataDirectory.subdirectories.some((d) => !d.exists || !d.writable)\n ) {\n const { runSetup } = await import('./setup-command.js');\n const setupResult = runSetup({\n skipMcp: true,\n skipRules: true,\n skipHooks: true,\n skipConfig: true,\n skipOpencode: true,\n });\n if (setupResult.success) {\n writeLine('✓ Created missing data directories');\n fixCount++;\n }\n }\n\n // Fix: config file\n if (!result.configFile.found) {\n const { runConfigInitSync } = await import('./setup-config.js');\n const configResult = runConfigInitSync(process.cwd(), false, false);\n if (configResult.success && configResult.created) {\n writeLine(`✓ Generated config: ${configResult.path}`);\n fixCount++;\n }\n }\n\n // Display-only: better-sqlite3\n if (!result.sqliteCheck.available) {\n writeLine('');\n writeLine('⚠ better-sqlite3 not installed (manual step required):');\n writeLine(' npm install -g better-sqlite3');\n }\n\n if (fixCount > 0) {\n writeLine('');\n writeLine(\n `\\x1b[32m${String(fixCount)} issue(s) fixed.\\x1b[0m Re-run \\x1b[1mnexus-agents doctor\\x1b[0m to verify.`\n );\n } else {\n writeLine('No auto-fixable issues found.');\n }\n writeLine('');\n}\n\n// Re-export printDoctorResults for backward compatibility\nexport { printDoctorResults } from './doctor-formatting.js';\n","/**\n * nexus-agents/mcp - MCP Server\n *\n * Main MCP server implementation for Nexus Agents orchestration.\n * Provides factory functions to create and start the server with\n * stdio or custom transports.\n *\n * (Source: MCP Protocol 2025-11-25)\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\n\nimport {\n getErrorMessage,\n createLogger,\n type Result,\n ok,\n err,\n type ILogger,\n} from '../core/index.js';\nimport { VERSION } from '../version.js';\nimport { getTaskStore } from './task-store.js';\nimport { initDataDirectories } from '../cli/setup-data-dir.js';\n\n/**\n * Server configuration options.\n */\nexport interface ServerConfig {\n /** Server name (default: \"nexus-agents\") */\n readonly name?: string;\n /** Server version (default: package version) */\n readonly version?: string;\n /** Logger instance */\n readonly logger?: ILogger;\n}\n\n/**\n * Server creation result containing the server and logger.\n */\nexport interface ServerInstance {\n /** The MCP server instance */\n readonly server: McpServer;\n /** The logger instance for this server */\n readonly logger: ILogger;\n}\n\n/**\n * Error type for server operations.\n */\nexport interface ServerError {\n code: 'SERVER_CREATION_FAILED' | 'SERVER_START_FAILED' | 'SERVER_STOP_FAILED';\n message: string;\n cause?: Error;\n}\n\nconst DEFAULT_SERVER_NAME = 'nexus-agents';\n\n/**\n * Creates a ServerError with the given code, message, and optional cause.\n */\nfunction createServerError(\n code: ServerError['code'],\n message: string,\n error: unknown\n): ServerError {\n const serverError: ServerError = { code, message };\n if (error instanceof Error) {\n serverError.cause = error;\n }\n return serverError;\n}\n\n/**\n * Creates a new MCP server instance.\n *\n * @param config - Optional server configuration\n * @returns Result containing the server instance or an error\n *\n * @example\n * ```typescript\n * const result = createServer({ name: 'my-server' });\n * if (result.ok) {\n * const { server, logger } = result.value;\n * // Register tools on server\n * }\n * ```\n */\nexport function createServer(config?: ServerConfig): Result<ServerInstance, ServerError> {\n const serverName = config?.name ?? DEFAULT_SERVER_NAME;\n const serverVersion = config?.version ?? VERSION;\n const logger = config?.logger ?? createLogger({ component: 'mcp-server' });\n\n try {\n // Ensure data directories exist on first MCP server startup (#1398)\n initDataDirectories();\n\n logger.info('Creating MCP server', {\n name: serverName,\n version: serverVersion,\n });\n\n const server = new McpServer(\n {\n name: serverName,\n version: serverVersion,\n },\n {\n capabilities: {\n logging: {},\n prompts: {},\n resources: {},\n tasks: {},\n },\n taskStore: getTaskStore(),\n }\n );\n\n logger.debug('MCP server created successfully');\n\n return ok({ server, logger });\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n logger.error('Failed to create MCP server', error instanceof Error ? error : undefined);\n return err(\n createServerError(\n 'SERVER_CREATION_FAILED',\n `Failed to create MCP server: ${errorMessage}`,\n error\n )\n );\n }\n}\n\n/**\n * Connects the server to a transport.\n *\n * @param server - The MCP server instance\n * @param transport - The transport to connect to\n * @param logger - Logger for the operation\n * @returns Result indicating success or failure\n */\nexport async function connectTransport(\n server: McpServer,\n transport: Transport,\n logger?: ILogger\n): Promise<Result<void, ServerError>> {\n const log = logger ?? createLogger({ component: 'mcp-server' });\n\n try {\n log.info('Connecting server to transport');\n await server.connect(transport);\n log.debug('Server connected to transport successfully');\n return ok(undefined);\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n log.error('Failed to connect to transport', error instanceof Error ? error : undefined);\n return err(\n createServerError(\n 'SERVER_START_FAILED',\n `Failed to connect to transport: ${errorMessage}`,\n error\n )\n );\n }\n}\n\n/**\n * Starts the MCP server with stdio transport.\n *\n * This is the main entry point for running the server as a standalone process.\n * The server will communicate over stdin/stdout using the MCP protocol.\n *\n * @param config - Optional server configuration\n * @returns Result indicating success or failure\n *\n * @example\n * ```typescript\n * const result = await startStdioServer();\n * if (!result.ok) {\n * console.error('Failed to start server:', result.error.message);\n * process.exit(1);\n * }\n * ```\n */\nexport async function startStdioServer(\n config?: ServerConfig\n): Promise<Result<ServerInstance, ServerError>> {\n const serverResult = createServer(config);\n if (!serverResult.ok) {\n return serverResult;\n }\n\n const { server, logger } = serverResult.value;\n\n try {\n // Defense-in-depth: stdio transport owns stdout for JSON-RPC frames.\n logger.setDestination?.('stderr');\n logger.info('Starting stdio transport');\n const transport = new StdioServerTransport();\n\n const connectResult = await connectTransport(server, transport, logger);\n if (!connectResult.ok) {\n return connectResult;\n }\n\n logger.info('MCP server running with stdio transport');\n return ok({ server, logger });\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n logger.error('Failed to start stdio server', error instanceof Error ? error : undefined);\n return err(\n createServerError(\n 'SERVER_START_FAILED',\n `Failed to start stdio server: ${errorMessage}`,\n error\n )\n );\n }\n}\n\n/**\n * Gracefully closes the server connection.\n *\n * @param server - The MCP server to close\n * @param logger - Optional logger\n * @returns Result indicating success or failure\n */\nexport async function closeServer(\n server: McpServer,\n logger?: ILogger\n): Promise<Result<void, ServerError>> {\n const log = logger ?? createLogger({ component: 'mcp-server' });\n\n try {\n log.info('Closing MCP server');\n await server.close();\n log.info('MCP server closed successfully');\n return ok(undefined);\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n log.error('Failed to close server', error instanceof Error ? error : undefined);\n return err(\n createServerError('SERVER_STOP_FAILED', `Failed to close server: ${errorMessage}`, error)\n );\n }\n}\n","/**\n * Nexus-Agents Task Store — wraps SDK InMemoryTaskStore with security controls.\n *\n * Provides:\n * - TTL enforcement (max 10 minutes per task)\n * - Capacity cap (max 50 tasks, FIFO eviction when exceeded)\n * - Singleton access via `getTaskStore()`\n * - Periodic cleanup of expired tasks\n *\n * @module mcp/task-store\n * (Source: Issue #1298 — Layer 2 MCP Tasks async execution)\n */\n\nimport { InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental/tasks';\nimport type { TaskStore } from '@modelcontextprotocol/sdk/experimental/tasks';\nimport { createLogger } from '../core/index.js';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Maximum TTL for any task (10 minutes). */\nexport const MAX_TASK_TTL_MS = 600_000;\n\n/** Default TTL applied when none specified (5 minutes). */\nexport const DEFAULT_TASK_TTL_MS = 300_000;\n\n/** Maximum number of tasks before FIFO eviction. */\nexport const MAX_TASK_CAPACITY = 50;\n\n/** Interval for periodic cleanup of expired tasks (60 seconds). */\nconst CLEANUP_INTERVAL_MS = 60_000;\n\n// ============================================================================\n// Singleton\n// ============================================================================\n\nconst logger = createLogger({ component: 'task-store' });\n\nlet singletonStore: InMemoryTaskStore | undefined;\nlet cleanupTimer: ReturnType<typeof setInterval> | undefined;\n\n/**\n * Returns the singleton InMemoryTaskStore, creating it on first call.\n *\n * The SDK's InMemoryTaskStore handles TTL cleanup internally.\n * We enforce our MAX_TASK_TTL_MS via `clampTaskTtl()` at task creation\n * (done by the ToolTaskHandler, not the store itself).\n */\nexport function getTaskStore(): TaskStore {\n if (singletonStore === undefined) {\n singletonStore = new InMemoryTaskStore();\n logger.info('Task store created', { maxCapacity: MAX_TASK_CAPACITY });\n\n // Periodic cleanup: evict oldest tasks if capacity exceeded\n cleanupTimer = setInterval(() => {\n evictExcessTasks();\n }, CLEANUP_INTERVAL_MS);\n\n // Prevent cleanup timer from keeping Node alive\n if (typeof cleanupTimer === 'object' && 'unref' in cleanupTimer) {\n cleanupTimer.unref();\n }\n }\n return singletonStore;\n}\n\n/**\n * Clamps a requested TTL to the maximum allowed value.\n * Returns DEFAULT_TASK_TTL_MS if no TTL is specified or null.\n */\nexport function clampTaskTtl(requestedTtl?: number | null): number {\n if (requestedTtl === undefined || requestedTtl === null) {\n return DEFAULT_TASK_TTL_MS;\n }\n if (requestedTtl > MAX_TASK_TTL_MS) {\n logger.warn('Task TTL clamped to maximum', {\n requested: requestedTtl,\n max: MAX_TASK_TTL_MS,\n });\n return MAX_TASK_TTL_MS;\n }\n return requestedTtl;\n}\n\n/**\n * Evicts oldest tasks when capacity is exceeded (FIFO).\n * Best-effort — logs warnings but does not throw.\n */\nfunction evictExcessTasks(): void {\n if (singletonStore === undefined) return;\n\n const allTasks = singletonStore.getAllTasks();\n if (allTasks.length <= MAX_TASK_CAPACITY) return;\n\n // Sort by creation time ascending (oldest first)\n const sorted = [...allTasks].sort(\n (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()\n );\n\n const evictCount = sorted.length - MAX_TASK_CAPACITY;\n for (let i = 0; i < evictCount; i++) {\n const task = sorted[i];\n if (task === undefined) continue;\n singletonStore\n .updateTaskStatus(task.taskId, 'cancelled', 'Evicted: capacity exceeded')\n .catch((err: unknown) => {\n logger.debug('Failed to evict task', {\n taskId: task.taskId,\n error: String(err),\n });\n });\n }\n\n logger.info('Evicted excess tasks', { evicted: evictCount, total: sorted.length });\n}\n\n/**\n * Shuts down the task store and cleanup timer.\n * Call during server shutdown. Safe to call multiple times.\n * @internal\n */\nexport function shutdownTaskStore(): void {\n if (cleanupTimer !== undefined) {\n clearInterval(cleanupTimer);\n cleanupTimer = undefined;\n }\n if (singletonStore !== undefined) {\n singletonStore.cleanup();\n singletonStore = undefined;\n logger.info('Task store shut down');\n }\n}\n\n/** Resets the singleton for testing. @internal */\nexport function resetTaskStore(): void {\n shutdownTaskStore();\n}\n","/**\n * nexus-agents doctor command - Formatting utilities\n *\n * Terminal output formatting for doctor command results.\n * Extracted to comply with 400-line file limit.\n *\n * (Source: Issue #422 - Doctor command validations)\n */\n\nimport { DEFAULT_CAPABILITIES } from '../cli-adapters/types.js';\nimport type { CapacityStatus } from '../cli-adapters/types.js';\nimport type {\n CliCheckResult,\n NodeVersionCheck,\n ApiKeyCheck,\n ConfigFileCheck,\n RegistryAdvisory,\n LearningPersistenceCheck,\n SqliteCheck,\n DataDirectoryCheck,\n DoctorResult,\n} from './doctor.js';\nimport { colors, symbols, writeLine } from './ansi-output.js';\nimport { capitalize } from '../utils/text-utils.js';\n\n/** Required Node.js major version (for warning message). */\nconst REQUIRED_NODE_MAJOR = 22;\n\n/**\n * Formats a status symbol with color.\n */\nfunction formatStatus(healthy: boolean, warn = false): string {\n if (healthy) return `${colors.green}${symbols.check}${colors.reset}`;\n if (warn) return `${colors.yellow}${symbols.warn}${colors.reset}`;\n return `${colors.red}${symbols.cross}${colors.reset}`;\n}\n\n/**\n * Formats version status with color.\n */\nfunction formatVersionStatus(status: string): string {\n switch (status) {\n case 'supported':\n return `${colors.green}supported${colors.reset}`;\n case 'outdated':\n return `${colors.yellow}outdated${colors.reset}`;\n case 'unsupported':\n case 'breaking':\n return `${colors.red}${status}${colors.reset}`;\n default:\n return status;\n }\n}\n\n/**\n * Formats capacity as percentage string.\n */\nfunction formatCapacity(capacity?: CapacityStatus): string {\n if (capacity === undefined) return 'Unknown';\n const remaining = 100 - capacity.utilizationPercent;\n const remainingStr = String(remaining);\n if (remaining > 80) return `${colors.green}${remainingStr}% remaining${colors.reset}`;\n if (remaining > 20) return `${colors.yellow}${remainingStr}% remaining${colors.reset}`;\n return `${colors.red}${remainingStr}% remaining${colors.reset}`;\n}\n\n/**\n * Prints details for an installed CLI.\n */\nfunction printInstalledCliDetails(cli: CliCheckResult): void {\n writeLine(` Version: ${cli.version} (${formatVersionStatus(cli.versionStatus)})`);\n\n const authText = cli.authenticated\n ? `${colors.green}${cli.authMethod ?? 'Authenticated'}${colors.reset}`\n : `${colors.red}Not authenticated${colors.reset}`;\n writeLine(` Auth: ${authText}`);\n\n if (cli.capacity !== undefined) {\n writeLine(` Capacity: ${formatCapacity(cli.capacity)}`);\n }\n}\n\n/**\n * Prints a single CLI result.\n */\nfunction printCliResult(cli: CliCheckResult): void {\n const status = cli.installed && cli.authenticated;\n const warn = cli.installed && (!cli.authenticated || cli.versionStatus === 'outdated');\n\n writeLine(\n `${formatStatus(status, warn)} ${colors.bold}${capitalize(cli.name)} CLI${colors.reset}`\n );\n\n if (cli.installed) {\n printInstalledCliDetails(cli);\n } else {\n const errorText = cli.error ?? 'Not installed';\n writeLine(` ${colors.red}Error: ${errorText}${colors.reset}`);\n }\n\n if (cli.fix !== undefined && cli.fix !== '') {\n writeLine(` ${colors.dim}Fix: ${cli.fix}${colors.reset}`);\n }\n\n writeLine('');\n}\n\n/**\n * Prints capability summary for installed CLIs.\n */\nfunction printCapabilities(clis: CliCheckResult[]): void {\n const installedClis = clis.filter((c) => c.installed);\n\n if (installedClis.length === 0) {\n writeLine(`${formatStatus(false)} No CLIs installed`);\n return;\n }\n\n const caps = DEFAULT_CAPABILITIES;\n const bestReasoning = installedClis.reduce((best, c) =>\n caps[c.name].reasoning > caps[best.name].reasoning ? c : best\n );\n const bestContext = installedClis.reduce((best, c) =>\n caps[c.name].contextWindow > caps[best.name].contextWindow ? c : best\n );\n const bestSpeed = installedClis.reduce((best, c) =>\n caps[c.name].speed > caps[best.name].speed ? c : best\n );\n\n const contextTokensK = (caps[bestContext.name].contextWindow / 1000).toFixed(0);\n\n writeLine(\n `${formatStatus(true)} Complex reasoning: ${colors.bold}${capitalize(bestReasoning.name)}${colors.reset}`\n );\n writeLine(\n `${formatStatus(true)} Large context: ${colors.bold}${capitalize(bestContext.name)}${colors.reset} (${contextTokensK}K tokens)`\n );\n writeLine(\n `${formatStatus(true)} Fast execution: ${colors.bold}${capitalize(bestSpeed.name)}${colors.reset}`\n );\n}\n\n/**\n * Prints Node.js version check result.\n */\nfunction printNodeVersionCheck(check: NodeVersionCheck): void {\n const versionText = check.supported\n ? `${colors.green}${check.version}${colors.reset}`\n : `${colors.yellow}${check.version}${colors.reset}`;\n writeLine(`${formatStatus(check.supported, !check.supported)} Node.js version: ${versionText}`);\n if (!check.supported) {\n writeLine(\n ` ${colors.dim}Warning: Node.js ${String(REQUIRED_NODE_MAJOR)}.x LTS required${colors.reset}`\n );\n }\n}\n\n/**\n * Prints API key configuration check results.\n */\nfunction printApiKeysCheck(keys: ApiKeyCheck[]): void {\n const configuredCount = keys.filter((k) => k.configured).length;\n const configuredNames = keys.filter((k) => k.configured).map((k) => k.name);\n const hasAny = configuredCount > 0;\n\n writeLine(\n `${formatStatus(hasAny, !hasAny)} API keys configured: ${String(configuredCount)} of ${String(keys.length)}`\n );\n if (hasAny) {\n writeLine(` ${colors.dim}Keys: ${configuredNames.join(', ')}${colors.reset}`);\n } else {\n writeLine(\n ` ${colors.dim}Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_AI_API_KEY${colors.reset}`\n );\n }\n}\n\n/**\n * Prints configuration file check result.\n */\nfunction printConfigFileCheck(check: ConfigFileCheck): void {\n if (check.found && check.path !== null) {\n writeLine(`${formatStatus(true)} Configuration loaded: ${check.path}`);\n } else {\n writeLine(`${formatStatus(false, true)} Configuration file: Not found`);\n writeLine(` ${colors.dim}Run: nexus-agents config init${colors.reset}`);\n }\n}\n\n/**\n * Prints model registry advisory (#890).\n */\nfunction printRegistryAdvisory(advisory: RegistryAdvisory): void {\n const allAvailable = advisory.unavailableModels === 0;\n const countText = `${String(advisory.availableModels)} of ${String(advisory.totalModels)}`;\n writeLine(`${formatStatus(allAvailable, !allAvailable)} Models available: ${countText}`);\n if (advisory.unavailableModels > 0) {\n const missing = advisory.models.filter((m) => !m.available);\n for (const m of missing) {\n writeLine(` ${colors.dim}${m.displayName} — ${m.reason}${colors.reset}`);\n }\n }\n // Registry staleness warning (#1549)\n const ageText = `${String(advisory.registryAgeDays)} days old`;\n if (advisory.registryStale) {\n writeLine(\n `${colors.yellow}${symbols.warn}${colors.reset} Model registry is ${ageText} — may have stale model data`\n );\n writeLine(` ${colors.dim}Run: npx tsx scripts/probe-models.ts${colors.reset}`);\n } else {\n writeLine(`${formatStatus(true)} Model registry: ${ageText}`);\n }\n}\n\n/**\n * Prints learning persistence health check (#1017).\n */\nfunction printLearningPersistence(check: LearningPersistenceCheck): void {\n if (!check.enabled) {\n writeLine(`${formatStatus(true)} Learning persistence: ${colors.dim}Disabled${colors.reset}`);\n writeLine(` ${colors.dim}Set NEXUS_PERSIST_LEARNING=true to enable${colors.reset}`);\n return;\n }\n\n const healthy = check.dirExists && check.dirWritable && check.error === null;\n writeLine(`${formatStatus(healthy, !healthy)} Learning persistence: Enabled`);\n\n if (check.error !== null) {\n writeLine(` ${colors.red}Error: ${check.error}${colors.reset}`);\n return;\n }\n\n const dirStatus = check.dirExists\n ? check.dirWritable\n ? `${colors.green}writable${colors.reset}`\n : `${colors.red}not writable${colors.reset}`\n : `${colors.yellow}not created yet${colors.reset}`;\n writeLine(` Data directory: ${dirStatus}`);\n writeLine(` Outcomes: ${String(check.outcomeCount)} recorded`);\n writeLine(` Distilled rules: ${String(check.ruleCount)} active`);\n if (check.rulesLastSaved !== null) {\n writeLine(` Rules last saved: ${check.rulesLastSaved}`);\n }\n}\n\n/**\n * Prints SQLite (better-sqlite3) availability check (#1249).\n */\nfunction printSqliteCheck(check: SqliteCheck): void {\n if (check.available) {\n writeLine(\n `${formatStatus(true)} SQLite (better-sqlite3): ${colors.green}Available${colors.reset}`\n );\n } else {\n writeLine(\n `${formatStatus(false, true)} SQLite (better-sqlite3): ${colors.yellow}Not available${colors.reset}`\n );\n writeLine(\n ` ${colors.dim}Memory backends (agentic, adaptive, typed) require it${colors.reset}`\n );\n writeLine(` ${colors.dim}Fix: npm install -g better-sqlite3${colors.reset}`);\n }\n}\n\n/**\n * Prints data directory health check (#1249).\n */\nfunction printDataDirectory(check: DataDirectoryCheck): void {\n if (check.rootExists) {\n const existCount = check.subdirectories.filter((d) => d.exists).length;\n const totalCount = check.subdirectories.length;\n const allExist = existCount === totalCount;\n const allWritable = check.subdirectories.every((d) => !d.exists || d.writable);\n const healthy = allExist && allWritable;\n writeLine(\n `${formatStatus(healthy, !healthy)} Data directory: ${check.rootPath} (${String(existCount)}/${String(totalCount)} subdirs)`\n );\n if (!allExist) {\n const missing = check.subdirectories.filter((d) => !d.exists);\n for (const dir of missing) {\n writeLine(` ${colors.dim}Missing: ${dir.name}/${colors.reset}`);\n }\n writeLine(` ${colors.dim}Fix: nexus-agents setup${colors.reset}`);\n }\n if (!allWritable) {\n const readonly_ = check.subdirectories.filter((d) => d.exists && !d.writable);\n for (const dir of readonly_) {\n writeLine(` ${colors.yellow}Not writable: ${dir.name}/${colors.reset}`);\n }\n }\n } else {\n writeLine(\n `${formatStatus(false, true)} Data directory: ${colors.yellow}Not created${colors.reset}`\n );\n writeLine(` ${colors.dim}Run: nexus-agents setup${colors.reset}`);\n }\n}\n\n/** Prints the summary line with issue count. */\nfunction printDoctorSummary(result: DoctorResult): void {\n const unhealthyCount = result.clis.filter((c) => !c.installed || !c.authenticated).length;\n const nodeIssue = result.nodeVersion.supported ? 0 : 1;\n const totalIssues = unhealthyCount + nodeIssue + (result.mcpServerReady ? 0 : 1);\n const summary = result.allHealthy\n ? `${colors.green}${colors.bold}Status: Ready${colors.reset}`\n : `${colors.yellow}${colors.bold}Summary: ${String(totalIssues)} issue(s) found${colors.reset}`;\n writeLine(summary);\n writeLine('');\n}\n\n/**\n * Prints the doctor results to stdout.\n */\nexport function printDoctorResults(result: DoctorResult): void {\n writeLine('');\n writeLine(`${colors.bold}Nexus Agents Doctor${colors.reset}`);\n writeLine('===================');\n writeLine('');\n\n writeLine(`${colors.cyan}Checking environment...${colors.reset}`);\n writeLine('');\n printNodeVersionCheck(result.nodeVersion);\n printApiKeysCheck(result.apiKeys);\n printConfigFileCheck(result.configFile);\n writeLine('');\n\n writeLine(`${colors.cyan}Checking CLI installations...${colors.reset}`);\n writeLine('');\n for (const cli of result.clis) {\n printCliResult(cli);\n }\n\n writeLine(`${colors.cyan}Checking MCP configuration...${colors.reset}`);\n writeLine('');\n writeLine(\n `${formatStatus(result.mcpServerReady)} MCP Server mode: ${result.mcpServerReady ? 'Ready' : 'Not ready'}`\n );\n writeLine(\n `${formatStatus(result.mcpClientReady)} MCP Client mode: ${result.mcpClientReady ? 'Ready (Codex mcp-server)' : 'Not ready (Codex not installed)'}`\n );\n writeLine('');\n\n writeLine(`${colors.cyan}Checking capabilities...${colors.reset}`);\n writeLine('');\n printCapabilities(result.clis);\n writeLine('');\n\n writeLine(`${colors.cyan}Checking model registry...${colors.reset}`);\n writeLine('');\n printRegistryAdvisory(result.registryAdvisory);\n writeLine('');\n\n writeLine(`${colors.cyan}Checking learning subsystem...${colors.reset}`);\n writeLine('');\n printLearningPersistence(result.learningPersistence);\n writeLine('');\n\n writeLine(`${colors.cyan}Checking data storage...${colors.reset}`);\n writeLine('');\n printSqliteCheck(result.sqliteCheck);\n printDataDirectory(result.dataDirectory);\n writeLine('');\n\n printDoctorSummary(result);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,IAAM,UAAkB,OAA2C,WAAoB;;;ACH9F,SAAS,SAAS;AAKX,IAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,OAAO,EAAE,KAAK,CAAC,SAAS,QAAQ,QAAQ,OAAO,CAAC,EAAE,QAAQ,MAAM;AAAA,EAChE,QAAQ,EAAE,KAAK,CAAC,QAAQ,QAAQ,CAAC,EAAE,QAAQ,MAAM;AAAA;AAAA,EAEjD,aAAa,EAAE,KAAK,CAAC,UAAU,UAAU,MAAM,CAAC,EAAE,QAAQ,QAAQ;AAAA,EAClE,UAAU,EAAE,OAAO,EAAE,SAAS;AAChC,CAAC;AAOM,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,SAAS,EAAE,IAAI,EAAE,SAAS;AAAA,EAC1B,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,GAAK;AAAA,EAC5C,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,CAAC;AAChD,CAAC;AAOM,IAAM,mBAAmB,EAAE,OAAO;AAAA,EACvC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC;AAAA,EAC/B,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC;AAAA,EACnC,UAAU,EA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KAAK,IAAI,CAAC,EAAG,CAAC;AAAA,EACjF;AACA,UAAQ,KAAK,OAAO;AACtB;","names":["z","z","z","z","z","z","z","z","z","z","z","logger","yaml","z","z","logger","existsSync","join","existsSync","readFileSync","join","err","logger","REQUIRED_NODE_MAJOR","existsSync","readFileSync","join","writeLine","join","existsSync"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli-adapters/fallback-chains.ts","../src/cli-adapters/cli-circuit-breaker.ts"],"sourcesContent":["/**\n * nexus-agents/cli-adapters - Fallback Chain Registry\n *\n * Configurable fallback chains per task type with metrics tracking.\n * Provides ordered CLI preferences based on task classification.\n *\n * @module cli-adapters/fallback-chains\n * (Source: Issue #362 - Task-type-aware fallback chains)\n */\n\nimport { z } from 'zod';\nimport type { CliName } from './types-core.js';\nimport type { FallbackTaskType } from './task-classifier.js';\nimport type { TaskCategory } from '../config/task-specialization-types.js';\n\n/**\n * Fallback chain: ordered list of CLIs to try for a task type.\n */\nexport type FallbackChain = readonly CliName[];\n\n/**\n * Registry mapping task types to fallback chains.\n */\nexport type FallbackChainRegistry = Readonly<Record<FallbackTaskType, FallbackChain>>;\n\n/**\n * Metrics for tracking fallback chain success rates.\n */\nexport interface FallbackChainMetrics {\n /** Total attempts for this task type */\n readonly totalAttempts: number;\n /** Successes by position in chain (0-indexed) */\n readonly successByPosition: readonly number[];\n /** Failures (exhausted all positions) */\n readonly exhaustedCount: number;\n /** Average position of successful attempt (lower is better) */\n readonly avgSuccessPosition: number;\n}\n\n/**\n * Metrics for all task types.\n */\nexport type FallbackMetricsRegistry = Readonly<Record<FallbackTaskType, FallbackChainMetrics>>;\n\n/**\n * Outcome of a fallback chain execution.\n */\nexport interface FallbackOutcome {\n /** Task type that was classified */\n readonly taskType: FallbackTaskType;\n /** Position in chain that succeeded (0-indexed), or -1 if exhausted */\n readonly successPosition: number;\n /** CLI that succeeded, or undefined if exhausted */\n readonly successfulCli?: CliName | undefined;\n /** Whether the chain was exhausted without success */\n readonly exhausted: boolean;\n}\n\n/**\n * Zod schema for fallback chain validation.\n */\nexport const FallbackChainSchema = z\n .array(z.enum(['claude', 'gemini', 'codex', 'opencode']))\n .min(1)\n .readonly();\n\n/**\n * Zod schema for fallback chain registry.\n */\nexport const FallbackChainRegistrySchema = z.object({\n code: FallbackChainSchema,\n research: FallbackChainSchema,\n documentation: FallbackChainSchema,\n analysis: FallbackChainSchema,\n general: FallbackChainSchema,\n});\n\n/**\n * Default fallback chains derived from the task specialization matrix.\n * Each chain orders CLIs by: primary → secondary → others.\n *\n * - code: Codex primary (92.4% code_gen), Claude secondary\n * - research: Gemini primary (86.8% research), Claude secondary\n * - documentation: Gemini primary (71.4% docs), Claude secondary\n * - analysis: Claude primary (architecture/security/planning), Codex secondary\n * - general: Balanced fallback order\n */\nexport const DEFAULT_FALLBACK_CHAINS: FallbackChainRegistry = {\n // code_generation/code_review/testing: codex primary, claude secondary\n code: ['codex', 'claude', 'gemini', 'opencode'],\n // research/exploration: gemini primary, claude secondary\n research: ['gemini', 'claude', 'codex', 'opencode'],\n // documentation: gemini primary, claude secondary\n documentation: ['gemini', 'claude', 'codex', 'opencode'],\n // architecture/security/planning: claude primary, gemini secondary\n // Weather data: gemini arch 66.7% (n=24) > codex 33.3% (n=3)\n analysis: ['claude', 'gemini', 'codex', 'opencode'],\n // general: balanced order\n general: ['claude', 'gemini', 'codex', 'opencode'],\n} as const;\n\n/**\n * Per-category fallback chain overrides.\n *\n * Categories in the same FallbackTaskType bucket may need different CLI ordering.\n * Entries here override the bucket-level chain from DEFAULT_FALLBACK_CHAINS.\n *\n * Weather data 2026-03-09:\n * - architecture: gemini 69.6% (n=23) > claude 40.9% (n=235) → gemini first\n * - planning: claude 92.2% → keep claude first (bucket default)\n * - security_review: codex 60% (n=5) > gemini 53.8% (n=13) > claude 54.2% (n=382) → codex first\n * - exploration: gemini 100% (n=307) > claude 83.9% (n=380) → gemini first, codex secondary (#1526)\n * - devops: claude 80% (n=5), gemini 100% (n=1) → keep claude first, gemini secondary (#1526)\n * - research: gemini 86.8% (n=38) > claude 84.1% (n=44) > codex 15% (n=20) → gemini first, codex last (#1536)\n * - documentation: gemini 71.4% (n=35) > claude 64.7% (n=17) > codex 33.3% (n=6) → gemini first, codex last (#1536)\n * - code_review: claude 91% (n=200) > codex 89.2% (n=93) > gemini 37.5% (n=8) → claude first (#1401)\n */\nexport const CATEGORY_CHAIN_OVERRIDES: Partial<Record<TaskCategory, FallbackChain>> = {\n architecture: ['gemini', 'claude', 'codex', 'opencode'],\n security_review: ['codex', 'gemini', 'claude', 'opencode'],\n code_review: ['claude', 'codex', 'gemini', 'opencode'],\n exploration: ['gemini', 'codex', 'claude', 'opencode'],\n devops: ['claude', 'gemini', 'codex', 'opencode'],\n // codex has 15% research success (n=20) — push to last position (#1536)\n research: ['gemini', 'claude', 'opencode', 'codex'],\n // codex has 33.3% docs success (n=6) — push to last position (#1536)\n documentation: ['gemini', 'claude', 'opencode', 'codex'],\n} as const;\n\n/**\n * Gets the fallback chain for a specific TaskCategory.\n * Returns a category-specific override if available, otherwise falls through\n * to the bucket-level chain via CATEGORY_TO_FALLBACK mapping.\n */\nexport function getFallbackChainForCategory(\n category: TaskCategory,\n bucketType: FallbackTaskType,\n registry: FallbackChainRegistry = DEFAULT_FALLBACK_CHAINS\n): FallbackChain {\n const override = CATEGORY_CHAIN_OVERRIDES[category];\n if (override !== undefined) return override;\n return registry[bucketType];\n}\n\n/**\n * Creates initial empty metrics for a task type.\n */\nfunction createEmptyMetrics(): FallbackChainMetrics {\n return {\n totalAttempts: 0,\n successByPosition: [0, 0, 0, 0],\n avgSuccessPosition: 0,\n exhaustedCount: 0,\n };\n}\n\n/**\n * Creates initial metrics registry with empty metrics for all types.\n */\nfunction createEmptyMetricsRegistry(): Record<FallbackTaskType, FallbackChainMetrics> {\n return {\n code: createEmptyMetrics(),\n research: createEmptyMetrics(),\n documentation: createEmptyMetrics(),\n analysis: createEmptyMetrics(),\n general: createEmptyMetrics(),\n };\n}\n\n/**\n * Gets the fallback chain for a task type.\n *\n * @param taskType - Task type to get chain for\n * @param registry - Optional custom registry (uses default if not provided)\n * @returns Ordered list of CLIs to try\n *\n * @example\n * ```typescript\n * const chain = getFallbackChain('code');\n * // chain === ['claude', 'codex', 'gemini']\n * ```\n */\nexport function getFallbackChain(\n taskType: FallbackTaskType,\n registry: FallbackChainRegistry = DEFAULT_FALLBACK_CHAINS\n): FallbackChain {\n return registry[taskType];\n}\n\n/**\n * Filters a fallback chain to only include available CLIs.\n *\n * @param chain - Original fallback chain\n * @param availableClis - Set of currently available CLI names\n * @returns Filtered chain with only available CLIs\n *\n * @example\n * ```typescript\n * const filtered = filterAvailableClis(['claude', 'codex', 'gemini'], new Set(['claude', 'gemini']));\n * // filtered === ['claude', 'gemini']\n * ```\n */\nexport function filterAvailableClis(\n chain: FallbackChain,\n availableClis: ReadonlySet<CliName>\n): CliName[] {\n return chain.filter((cli) => availableClis.has(cli));\n}\n\n/**\n * Gets the next CLI to try in a fallback chain.\n *\n * @param chain - Fallback chain\n * @param currentPosition - Current position (0-indexed)\n * @returns Next CLI to try, or undefined if chain is exhausted\n */\nexport function getNextCli(chain: FallbackChain, currentPosition: number): CliName | undefined {\n const nextPosition = currentPosition + 1;\n return chain[nextPosition];\n}\n\n/**\n * Checks if a fallback chain is exhausted at the given position.\n *\n * @param chain - Fallback chain\n * @param currentPosition - Current position (0-indexed)\n * @returns True if no more CLIs to try\n */\nexport function isChainExhausted(chain: FallbackChain, currentPosition: number): boolean {\n return currentPosition >= chain.length - 1;\n}\n\n/**\n * Fallback chain manager with metrics tracking.\n */\nexport class FallbackChainManager {\n private readonly registry: FallbackChainRegistry;\n private readonly metrics: Record<FallbackTaskType, FallbackChainMetrics>;\n\n constructor(registry: FallbackChainRegistry = DEFAULT_FALLBACK_CHAINS) {\n this.registry = registry;\n this.metrics = createEmptyMetricsRegistry();\n }\n\n /**\n * Gets the fallback chain for a task type.\n */\n getChain(taskType: FallbackTaskType): FallbackChain {\n return getFallbackChain(taskType, this.registry);\n }\n\n /**\n * Gets the chain filtered by available CLIs.\n */\n getAvailableChain(taskType: FallbackTaskType, availableClis: ReadonlySet<CliName>): CliName[] {\n const chain = this.getChain(taskType);\n return filterAvailableClis(chain, availableClis);\n }\n\n /**\n * Records an outcome and updates metrics.\n *\n * @param outcome - The outcome to record\n */\n recordOutcome(outcome: FallbackOutcome): void {\n const currentMetrics = this.metrics[outcome.taskType];\n const newSuccessByPosition = [...currentMetrics.successByPosition];\n\n // Update success counts\n if (!outcome.exhausted && outcome.successPosition >= 0) {\n const position = outcome.successPosition;\n if (position < newSuccessByPosition.length) {\n const currentCount = newSuccessByPosition[position] ?? 0;\n newSuccessByPosition[position] = currentCount + 1;\n } else {\n // Extend array if needed\n while (newSuccessByPosition.length <= position) {\n newSuccessByPosition.push(0);\n }\n newSuccessByPosition[position] = 1;\n }\n }\n\n // Calculate new average success position\n const totalSuccesses = newSuccessByPosition.reduce((sum, count) => sum + count, 0);\n const weightedSum = newSuccessByPosition.reduce((sum, count, pos) => sum + count * pos, 0);\n const avgSuccessPosition = totalSuccesses > 0 ? weightedSum / totalSuccesses : 0;\n\n // Update metrics\n this.metrics[outcome.taskType] = {\n totalAttempts: currentMetrics.totalAttempts + 1,\n successByPosition: newSuccessByPosition,\n exhaustedCount: currentMetrics.exhaustedCount + (outcome.exhausted ? 1 : 0),\n avgSuccessPosition,\n };\n }\n\n /**\n * Gets metrics for a specific task type.\n */\n getMetrics(taskType: FallbackTaskType): FallbackChainMetrics {\n return this.metrics[taskType];\n }\n\n /**\n * Gets metrics for all task types.\n */\n getAllMetrics(): FallbackMetricsRegistry {\n return { ...this.metrics };\n }\n\n /**\n * Gets the success rate at each position for a task type.\n *\n * @param taskType - Task type to get rates for\n * @returns Array of success rates (0-1) by position\n */\n getSuccessRatesByPosition(taskType: FallbackTaskType): readonly number[] {\n const metrics = this.metrics[taskType];\n if (metrics.totalAttempts === 0) {\n return [];\n }\n return metrics.successByPosition.map((count) => count / metrics.totalAttempts);\n }\n\n /**\n * Gets overall success rate for a task type.\n */\n getOverallSuccessRate(taskType: FallbackTaskType): number {\n const metrics = this.metrics[taskType];\n if (metrics.totalAttempts === 0) {\n return 0;\n }\n const totalSuccesses = metrics.successByPosition.reduce((sum, count) => sum + count, 0);\n return totalSuccesses / metrics.totalAttempts;\n }\n\n /**\n * Resets metrics for all task types.\n */\n resetMetrics(): void {\n const types: FallbackTaskType[] = ['code', 'research', 'documentation', 'analysis', 'general'];\n for (const type of types) {\n this.metrics[type] = createEmptyMetrics();\n }\n }\n}\n\n/**\n * Creates a new FallbackChainManager instance.\n *\n * @param registry - Optional custom fallback chain registry\n * @returns New FallbackChainManager instance\n */\nexport function createFallbackChainManager(registry?: FallbackChainRegistry): FallbackChainManager {\n return new FallbackChainManager(registry);\n}\n\n/**\n * Creates a custom fallback chain registry by merging with defaults.\n *\n * @param overrides - Partial registry with overrides\n * @returns Complete registry with defaults for unspecified types\n */\nexport function createFallbackChainRegistry(\n overrides: Partial<FallbackChainRegistry>\n): FallbackChainRegistry {\n return {\n ...DEFAULT_FALLBACK_CHAINS,\n ...overrides,\n };\n}\n","/**\n * nexus-agents/cli-adapters - CLI Circuit Breaker Integration\n *\n * Wraps CLI adapter calls with circuit breaker pattern for resilient\n * multi-CLI execution with automatic fallback on failures.\n *\n * (Source: Issue #359 - Integrate circuit breaker with CLI adapters)\n */\n\nimport type { Result, ILogger } from '../core/index.js';\nimport { ok, err, createLogger, getTimeProvider } from '../core/index.js';\nimport type { TaskCategory } from '../config/task-specialization-types.js';\nimport type { FallbackTaskType } from './task-classifier.js';\nimport { getFallbackChainForCategory } from './fallback-chains.js';\nimport type { ICliAdapter, CliName, CliTask, CliResponse, CliError } from './types.js';\nimport {\n CircuitBreakerRegistry,\n CircuitError,\n mapCliErrorToCategory,\n type CircuitBreakerConfig,\n type CircuitBreakerSnapshot,\n type CircuitStateChangeListener,\n} from './circuit-breaker.js';\n\n/** Maps canonical TaskCategory (10 types) to FallbackTaskType (5 types). */\nconst CATEGORY_TO_FALLBACK: Record<TaskCategory, FallbackTaskType> = {\n code_generation: 'code',\n code_review: 'code',\n testing: 'code',\n research: 'research',\n exploration: 'research',\n documentation: 'documentation',\n architecture: 'analysis',\n security_review: 'analysis',\n planning: 'analysis',\n devops: 'general',\n};\n\n/** Configuration for CLI circuit breaker integration. */\nexport interface CliCircuitBreakerConfig {\n readonly perCliConfig?: Partial<Record<CliName, Partial<CircuitBreakerConfig>>>;\n readonly fallbackChain?: ReadonlyArray<CliName>;\n readonly enableFallback?: boolean;\n readonly maxFallbackAttempts?: number;\n}\n\n/** Result of a circuit-protected execution with fallback info. */\nexport interface CircuitProtectedResult {\n readonly response: CliResponse;\n readonly executedBy: CliName;\n readonly usedFallback: boolean;\n readonly fallbackAttempts?: ReadonlyArray<CliName>;\n}\n\n/** Health status for all CLIs with circuit state. */\nexport interface CliCircuitHealthStatus {\n readonly clis: ReadonlyArray<{\n readonly name: CliName;\n readonly healthy: boolean;\n readonly circuitState: 'closed' | 'open' | 'half-open';\n readonly failureCount: number;\n readonly lastFailureTime: number | null;\n }>;\n readonly systemHealthy: boolean;\n readonly healthyCount: number;\n readonly timestamp: number;\n}\n\n/** Interface for CLI circuit breaker integration. */\nexport interface ICliCircuitBreakerIntegration {\n execute(\n adapter: ICliAdapter,\n task: CliTask,\n taskCategory?: TaskCategory\n ): Promise<Result<CircuitProtectedResult, CircuitError | CliError>>;\n getHealthStatus(): CliCircuitHealthStatus;\n getCircuitSnapshots(): Map<CliName, CircuitBreakerSnapshot>;\n resetCircuit(cliName: CliName): void;\n resetAllCircuits(): void;\n addStateChangeListener(listener: CircuitStateChangeListener): void;\n}\n\nconst DEFAULT_FALLBACK_CHAIN: ReadonlyArray<CliName> = ['claude', 'gemini', 'codex', 'opencode'];\nconst DEFAULT_CONFIG: Required<CliCircuitBreakerConfig> = {\n perCliConfig: {},\n fallbackChain: DEFAULT_FALLBACK_CHAIN,\n enableFallback: true,\n maxFallbackAttempts: 2,\n};\n\n/**\n * Integrates circuit breaker pattern with CLI adapters.\n * Provides automatic fallback when a CLI's circuit opens.\n */\nexport class CliCircuitBreakerIntegration implements ICliCircuitBreakerIntegration {\n private readonly registry: CircuitBreakerRegistry;\n private readonly adapters: Map<CliName, ICliAdapter> = new Map();\n private readonly config: Required<CliCircuitBreakerConfig>;\n private readonly logger: ILogger;\n\n constructor(\n adapters: ReadonlyArray<ICliAdapter>,\n config?: CliCircuitBreakerConfig,\n logger?: ILogger\n ) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.logger = logger ?? createLogger({ component: 'cli-circuit-breaker-integration' });\n this.registry = new CircuitBreakerRegistry();\n for (const adapter of adapters) {\n this.adapters.set(adapter.name, adapter);\n this.registry.getBreaker(adapter.name, this.config.perCliConfig[adapter.name]);\n }\n }\n\n async execute(\n adapter: ICliAdapter,\n task: CliTask,\n taskCategory?: TaskCategory\n ): Promise<Result<CircuitProtectedResult, CircuitError | CliError>> {\n const primaryCli = adapter.name;\n const fallbackAttempts: CliName[] = [];\n let lastError: CircuitError | CliError | undefined;\n\n const primaryResult = await this.executeWithBreaker(adapter, task);\n if (primaryResult.ok) {\n return ok({ response: primaryResult.value, executedBy: primaryCli, usedFallback: false });\n }\n lastError = primaryResult.error;\n\n if (!this.config.enableFallback || !(lastError instanceof CircuitError)) {\n return err(lastError);\n }\n\n for (const cli of this.getFallbackClis(primaryCli, taskCategory).slice(\n 0,\n this.config.maxFallbackAttempts\n )) {\n const fallbackAdapter = this.adapters.get(cli);\n if (!fallbackAdapter) continue;\n fallbackAttempts.push(cli);\n this.logger.info('Attempting fallback', { from: primaryCli, to: cli });\n const result = await this.executeWithBreaker(fallbackAdapter, task);\n if (result.ok) {\n return ok({\n response: result.value,\n executedBy: cli,\n usedFallback: true,\n fallbackAttempts,\n });\n }\n lastError = result.error;\n }\n\n this.logger.warn('All fallback attempts failed', { primaryCli, fallbackAttempts });\n return err(lastError);\n }\n\n getHealthStatus(): CliCircuitHealthStatus {\n const snapshots = this.registry.getAllSnapshots();\n const clis: CliCircuitHealthStatus['clis'][number][] = [];\n let healthyCount = 0;\n for (const name of this.adapters.keys()) {\n const snapshot = snapshots.get(name);\n if (!snapshot) continue;\n const healthy = snapshot.state === 'closed';\n if (healthy) healthyCount++;\n clis.push({\n name,\n healthy,\n circuitState: snapshot.state,\n failureCount: snapshot.failureCount,\n lastFailureTime: snapshot.lastFailureTime,\n });\n }\n return {\n clis,\n systemHealthy: healthyCount > 0,\n healthyCount,\n timestamp: getTimeProvider().now(),\n };\n }\n\n getCircuitSnapshots(): Map<CliName, CircuitBreakerSnapshot> {\n return this.registry.getAllSnapshots();\n }\n\n resetCircuit(cliName: CliName): void {\n this.registry.reset(cliName);\n this.logger.info('Circuit reset', { cliName });\n }\n\n resetAllCircuits(): void {\n this.registry.resetAll();\n this.logger.info('All circuits reset');\n }\n\n addStateChangeListener(listener: CircuitStateChangeListener): void {\n this.registry.addGlobalStateChangeListener(listener);\n }\n\n private async executeWithBreaker(\n adapter: ICliAdapter,\n task: CliTask\n ): Promise<Result<CliResponse, CircuitError | CliError>> {\n const breaker = this.registry.getBreaker(adapter.name);\n const result = await breaker.execute(async () => {\n const execResult = await adapter.execute(task);\n if (!execResult.ok) {\n breaker.recordFailure(mapCliErrorToCategory(execResult.error.code));\n const wrappedError = new Error(execResult.error.message);\n (wrappedError as Error & { cliError: CliError }).cliError = execResult.error;\n throw wrappedError;\n }\n return execResult.value;\n });\n\n if (!result.ok) {\n if (result.error.circuitErrorCode === 'CIRCUIT_OPEN') return err(result.error);\n const wrapped = result.error.cause as (Error & { cliError?: CliError }) | undefined;\n if (wrapped?.cliError) return err(wrapped.cliError);\n return err(result.error);\n }\n return ok(result.value);\n }\n\n private getFallbackClis(excludeCli: CliName, taskCategory?: TaskCategory): CliName[] {\n const chain =\n taskCategory !== undefined\n ? getFallbackChainForCategory(taskCategory, CATEGORY_TO_FALLBACK[taskCategory])\n : this.config.fallbackChain;\n return [...chain].filter(\n (cli) => cli !== excludeCli && !this.registry.isOpen(cli) && this.adapters.has(cli)\n );\n }\n}\n\n/** Creates a CLI circuit breaker integration with the specified adapters. */\nexport function createCliCircuitBreakerIntegration(\n adapters: ReadonlyArray<ICliAdapter>,\n config?: CliCircuitBreakerConfig,\n logger?: ILogger\n): CliCircuitBreakerIntegration {\n return new CliCircuitBreakerIntegration(adapters, config, logger);\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,SAAS,SAAS;AAmDX,IAAM,sBAAsB,EAChC,MAAM,EAAE,KAAK,CAAC,UAAU,UAAU,SAAS,UAAU,CAAC,CAAC,EACvD,IAAI,CAAC,EACL,SAAS;AAKL,IAAM,8BAA8B,EAAE,OAAO;AAAA,EAClD,MAAM;AAAA,EACN,UAAU;AAAA,EACV,eAAe;AAAA,EACf,UAAU;AAAA,EACV,SAAS;AACX,CAAC;AAYM,IAAM,0BAAiD;AAAA;AAAA,EAE5D,MAAM,CAAC,SAAS,UAAU,UAAU,UAAU;AAAA;AAAA,EAE9C,UAAU,CAAC,UAAU,UAAU,SAAS,UAAU;AAAA;AAAA,EAElD,eAAe,CAAC,UAAU,UAAU,SAAS,UAAU;AAAA;AAAA;AAAA,EAGvD,UAAU,CAAC,UAAU,UAAU,SAAS,UAAU;AAAA;AAAA,EAElD,SAAS,CAAC,UAAU,UAAU,SAAS,UAAU;AACnD;AAkBO,IAAM,2BAAyE;AAAA,EACpF,cAAc,CAAC,UAAU,UAAU,SAAS,UAAU;AAAA,EACtD,iBAAiB,CAAC,SAAS,UAAU,UAAU,UAAU;AAAA,EACzD,aAAa,CAAC,UAAU,SAAS,UAAU,UAAU;AAAA,EACrD,aAAa,CAAC,UAAU,SAAS,UAAU,UAAU;AAAA,EACrD,QAAQ,CAAC,UAAU,UAAU,SAAS,UAAU;AAAA;AAAA,EAEhD,UAAU,CAAC,UAAU,UAAU,YAAY,OAAO;AAAA;AAAA,EAElD,eAAe,CAAC,UAAU,UAAU,YAAY,OAAO;AACzD;AAOO,SAAS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