@cleocode/adapters 2026.4.40 → 2026.4.42
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/cant-context.js +284 -0
- package/dist/cant-context.js.map +1 -0
- package/dist/index.js +14 -4
- package/dist/index.js.map +2 -2
- package/dist/providers/claude-code/adapter.js +3 -0
- package/dist/providers/claude-code/adapter.js.map +1 -1
- package/dist/providers/claude-code/hooks.js +114 -11
- package/dist/providers/claude-code/hooks.js.map +1 -1
- package/dist/providers/claude-code/install.d.ts.map +1 -1
- package/dist/providers/claude-code/spawn.d.ts.map +1 -1
- package/dist/providers/claude-code/spawn.js +15 -1
- package/dist/providers/claude-code/spawn.js.map +1 -1
- package/dist/providers/opencode/spawn.js +26 -11
- package/dist/providers/opencode/spawn.js.map +1 -1
- package/package.json +3 -3
- package/src/cant-context.ts +3 -3
- package/src/providers/claude-code/install.ts +5 -1
- package/src/providers/claude-code/spawn.ts +11 -2
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/cant-context.ts", "../src/providers/claude-code/paths.ts", "../src/providers/claude-code/context-monitor.ts", "../src/providers/claude-code/hooks.ts", "../src/providers/claude-code/install.ts", "../../contracts/src/errors.ts", "../../contracts/src/exit-codes.ts", "../../contracts/src/facade.ts", "../../contracts/src/lafs.ts", "../../contracts/src/operations/issues.ts", "../../contracts/src/operations/lifecycle.ts", "../../contracts/src/operations/orchestrate.ts", "../../contracts/src/operations/release.ts", "../../contracts/src/operations/research.ts", "../../contracts/src/operations/session.ts", "../../contracts/src/operations/skills.ts", "../../contracts/src/operations/system.ts", "../../contracts/src/operations/tasks.ts", "../../contracts/src/operations/validate.ts", "../../contracts/src/operations/index.ts", "../../contracts/src/orchestration-hierarchy.ts", "../../contracts/src/session.ts", "../../contracts/src/status-registry.ts", "../../contracts/src/index.ts", "../src/providers/claude-code/spawn.ts", "../src/providers/claude-code/task-sync.ts", "../src/providers/claude-code/transport.ts", "../src/providers/claude-code/adapter.ts", "../src/providers/claude-code/statusline.ts", "../src/providers/claude-code/index.ts", "../src/providers/cursor/hooks.ts", "../src/providers/cursor/install.ts", "../src/providers/cursor/adapter.ts", "../src/providers/cursor/index.ts", "../src/providers/opencode/hooks.ts", "../src/providers/opencode/install.ts", "../src/providers/opencode/spawn.ts", "../src/providers/opencode/adapter.ts", "../src/providers/opencode/index.ts", "../src/providers/pi/hooks.ts", "../src/providers/pi/install.ts", "../src/providers/pi/spawn.ts", "../src/providers/pi/adapter.ts", "../src/providers/pi/index.ts", "../src/index.ts", "../src/providers/codex/adapter.ts", "../src/providers/codex/hooks.ts", "../src/providers/shared/transcript-reader.ts", "../src/providers/codex/install.ts", "../src/providers/codex/index.ts", "../src/providers/gemini-cli/adapter.ts", "../src/providers/gemini-cli/hooks.ts", "../src/providers/gemini-cli/install.ts", "../src/providers/gemini-cli/index.ts", "../src/providers/kimi/adapter.ts", "../src/providers/kimi/hooks.ts", "../src/providers/kimi/install.ts", "../src/providers/kimi/index.ts", "../src/registry.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Shared CANT context builder for all spawn providers.\n *\n * Extracts the Pi bridge's CANT discovery/compile/inject logic into a reusable\n * module that any spawn provider (Claude Code, OpenCode, Cursor, etc.) can call\n * to enrich agent prompts with:\n *\n * 1. Compiled CANT bundle (team topology, agent personas, tool ACLs)\n * 2. Memory bridge (recent decisions, handoff notes, key patterns)\n * 3. Mental model injection (validate-on-load agent-specific observations)\n *\n * All operations are best-effort: if any step fails (missing packages, empty\n * directories, compilation errors), the base prompt is returned unchanged.\n * This guarantees agents always spawn \u2014 CANT context is an enrichment, not a gate.\n *\n * Reference implementation: packages/cleo-os/extensions/cleo-cant-bridge.ts\n * (Pi-only; this module generalizes the same logic for all providers)\n *\n * @task T555\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, join } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Per-tier file counts for diagnostic reporting. */\nexport interface TierDiscoveryStats {\n global: number;\n user: number;\n project: number;\n overrides: number;\n merged: number;\n}\n\n/** Minimal observation shape returned by memoryFind / searchBrainCompact. */\nexport interface MentalModelObservation {\n id: string;\n type: string;\n title: string;\n date?: string;\n}\n\n/** Options for the main enrichment function. */\nexport interface BuildCantEnrichedPromptOptions {\n /** Project root directory for .cleo/cant/ discovery and brain.db access. */\n projectDir: string;\n /** The raw prompt to enrich. Returned unchanged if no CANT context is available. */\n basePrompt: string;\n /** Agent name for mental model injection. Omit to skip mental model fetch. */\n agentName?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Preamble text injected when an agent has mental model observations.\n * The agent MUST re-evaluate each observation against current project state.\n */\nconst VALIDATE_ON_LOAD_PREAMBLE =\n '===== MENTAL MODEL (validate-on-load) =====\\n' +\n 'These are your prior observations, patterns, and learnings for this project.\\n' +\n 'Before acting, you MUST re-evaluate each entry against current project state.\\n' +\n 'If an entry is stale, note it and proceed with fresh understanding.';\n\n// ---------------------------------------------------------------------------\n// Discovery functions (ported from cleo-cant-bridge.ts lines 418-526)\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively discover `.cant` files in a directory.\n *\n * @param dir - The directory to scan recursively.\n * @returns An array of absolute paths to `.cant` files found.\n */\nexport function discoverCantFiles(dir: string): string[] {\n try {\n const entries = readdirSync(dir, { recursive: true, withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.cant')) {\n const parent = (entry as unknown as { parentPath?: string }).parentPath ?? dir;\n files.push(join(parent, entry.name));\n }\n }\n return files;\n } catch {\n return [];\n }\n}\n\n/**\n * Resolve XDG-compliant paths for the 3-tier CANT hierarchy.\n *\n * Respects `XDG_DATA_HOME` and `XDG_CONFIG_HOME` environment variables.\n * Falls back to XDG defaults (`~/.local/share/` and `~/.config/`).\n *\n * @param projectDir - The project root directory (for the project tier).\n * @returns An object with `global`, `user`, and `project` CANT directory paths.\n */\nexport function resolveThreeTierPaths(projectDir: string): {\n global: string;\n user: string;\n project: string;\n} {\n const home = homedir();\n const xdgData = process.env['XDG_DATA_HOME'] ?? join(home, '.local', 'share');\n const xdgConfig = process.env['XDG_CONFIG_HOME'] ?? join(home, '.config');\n\n return {\n global: join(xdgData, 'cleo', 'cant'),\n user: join(xdgConfig, 'cleo', 'cant'),\n project: join(projectDir, '.cleo', 'cant'),\n };\n}\n\n/**\n * Discover `.cant` files across all three tiers with override semantics.\n *\n * Scans global, user, and project tiers. Files in higher-precedence tiers\n * override files in lower-precedence tiers that share the same basename.\n * The precedence order is: project > user > global.\n *\n * @param projectDir - The project root directory.\n * @returns An object containing the merged file list and per-tier statistics.\n */\nexport function discoverCantFilesMultiTier(projectDir: string): {\n files: string[];\n stats: TierDiscoveryStats;\n} {\n const paths = resolveThreeTierPaths(projectDir);\n\n const globalFiles = discoverCantFiles(paths.global);\n const userFiles = discoverCantFiles(paths.user);\n const projectFiles = discoverCantFiles(paths.project);\n\n // Build basename-keyed map; lowest precedence first so higher tiers override\n const fileMap = new Map<string, string>();\n\n for (const file of globalFiles) {\n fileMap.set(basename(file), file);\n }\n\n for (const file of userFiles) {\n fileMap.set(basename(file), file);\n }\n\n for (const file of projectFiles) {\n fileMap.set(basename(file), file);\n }\n\n const totalUniqueInputs = globalFiles.length + userFiles.length + projectFiles.length;\n const overrides = totalUniqueInputs - fileMap.size;\n\n return {\n files: Array.from(fileMap.values()),\n stats: {\n global: globalFiles.length,\n user: userFiles.length,\n project: projectFiles.length,\n overrides,\n merged: fileMap.size,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Memory bridge (ported from cleo-cant-bridge.ts lines 376-404)\n// ---------------------------------------------------------------------------\n\n/**\n * Read the memory bridge file from a project's .cleo/ directory.\n *\n * @param projectDir - The project root directory.\n * @returns The memory bridge content, or null if not found or empty.\n */\nexport function readMemoryBridge(projectDir: string): string | null {\n try {\n const bridgePath = join(projectDir, '.cleo', 'memory-bridge.md');\n if (!existsSync(bridgePath)) return null;\n const content = readFileSync(bridgePath, 'utf-8');\n return content.length > 0 ? content : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Build the memory-bridge system-prompt block appended to every agent.\n *\n * Wraps the raw memory-bridge.md content in a clearly labeled section\n * so the agent knows this is the CLEO project memory context.\n *\n * @param content - The raw memory-bridge.md content.\n * @returns The formatted memory-bridge block for system prompt injection.\n */\nexport function buildMemoryBridgeBlock(content: string): string {\n return (\n '\\n\\n===== CLEO MEMORY BRIDGE =====\\n' +\n 'This is your project memory context from .cleo/memory-bridge.md.\\n' +\n 'Use it to understand recent decisions, handoff notes, and key patterns.\\n\\n' +\n content.trim() +\n '\\n===== END MEMORY BRIDGE ====='\n );\n}\n\n// ---------------------------------------------------------------------------\n// Mental model injection (ported from cleo-cant-bridge.ts lines 113-135, 543-589)\n// ---------------------------------------------------------------------------\n\n/**\n * Build the validate-on-load mental-model injection string.\n *\n * Pure function \u2014 no I/O, safe to call in tests without a real DB.\n *\n * @param agentName - Name of the spawned agent (used in the header line).\n * @param observations - Prior mental-model observations to list.\n * @returns System-prompt block with preamble and numbered observations,\n * or empty string when `observations` is empty.\n */\nexport function buildMentalModelInjection(\n agentName: string,\n observations: MentalModelObservation[],\n): string {\n if (observations.length === 0) return '';\n\n const lines: string[] = ['', `// Agent: ${agentName}`, VALIDATE_ON_LOAD_PREAMBLE, ''];\n\n for (let i = 0; i < observations.length; i++) {\n const obs = observations[i];\n const datePart = obs.date ? ` [${obs.date}]` : '';\n lines.push(`${i + 1}. [${obs.id}] (${obs.type})${datePart}: ${obs.title}`);\n }\n\n lines.push('===== END MENTAL MODEL =====');\n return lines.join('\\n');\n}\n\n/**\n * Fetch mental model observations for an agent from brain.db.\n *\n * Uses dynamic import of `@cleocode/core` to avoid circular dependencies.\n * Returns empty string on any failure (best-effort, never throws).\n *\n * @param agentName - The agent's name for scoped observation lookup.\n * @param projectRoot - Project root directory for brain.db access.\n * @returns The validate-on-load system-prompt block, or \"\" on failure/empty.\n */\nasync function fetchMentalModelInjection(agentName: string, projectRoot: string): Promise<string> {\n try {\n // Dynamic import \u2014 @cleocode/core is NOT a compile-time dependency of adapters.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const coreModule = (await import(/* webpackIgnore: true */ '@cleocode/core' as string)) as {\n memoryFind?: (\n params: {\n query: string;\n agent?: string;\n limit?: number;\n tables?: string[];\n },\n projectRoot?: string,\n ) => Promise<{\n success: boolean;\n data?: {\n results?: MentalModelObservation[];\n };\n }>;\n };\n\n if (typeof coreModule.memoryFind !== 'function') return '';\n\n const result = await coreModule.memoryFind(\n {\n query: agentName,\n agent: agentName,\n limit: 10,\n tables: ['observations'],\n },\n projectRoot,\n );\n\n if (!result.success || !result.data?.results?.length) return '';\n\n return buildMentalModelInjection(agentName, result.data.results);\n } catch {\n return '';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Build an enriched prompt with CANT context, memory bridge, and mental model.\n *\n * This is the universal entry point for all spawn providers. It performs the\n * same operations as the Pi bridge (cleo-cant-bridge.ts) but returns a string\n * rather than hooking into Pi events:\n *\n * 1. Discovers `.cant` files across 3 tiers (global \u2192 user \u2192 project)\n * 2. Compiles the CANT bundle via `@cleocode/cant`'s `compileBundle()`\n * 3. Renders the compiled system prompt\n * 4. Reads the memory bridge from `.cleo/memory-bridge.md`\n * 5. Fetches mental model observations for the named agent\n * 6. Concatenates: basePrompt + CANT bundle + memory bridge + mental model\n *\n * All operations are best-effort. If any step fails, the base prompt is\n * returned unchanged. CANT context is an enrichment, not a gate \u2014 agents\n * always spawn regardless of CANT availability.\n *\n * @param options - Project dir, base prompt, and optional agent name.\n * @returns The enriched prompt string, or basePrompt unchanged on failure.\n */\nexport async function buildCantEnrichedPrompt(\n options: BuildCantEnrichedPromptOptions,\n): Promise<string> {\n const { projectDir, basePrompt, agentName } = options;\n let appendix = '';\n\n // Step 1-3: Discover and compile CANT bundle\n try {\n const { files } = discoverCantFilesMultiTier(projectDir);\n\n if (files.length > 0) {\n // Dynamic import \u2014 @cleocode/cant is NOT a compile-time dependency of adapters.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const cantModule = (await import(/* webpackIgnore: true */ '@cleocode/cant' as string)) as {\n compileBundle?: (paths: string[]) => {\n renderSystemPrompt: () => string;\n valid: boolean;\n diagnostics: unknown[];\n };\n };\n\n if (typeof cantModule.compileBundle === 'function') {\n const bundle = cantModule.compileBundle(files);\n if (bundle.valid) {\n const rendered = bundle.renderSystemPrompt();\n if (rendered) {\n appendix += `\\n\\n${rendered}`;\n }\n }\n }\n }\n } catch {\n // CANT compilation failure \u2014 continue without bundle context\n }\n\n // Step 4: Append memory bridge\n try {\n const bridge = readMemoryBridge(projectDir);\n if (bridge) {\n appendix += buildMemoryBridgeBlock(bridge);\n }\n } catch {\n // Memory bridge read failure \u2014 non-fatal\n }\n\n // Step 5: Append mental model for named agent\n if (agentName) {\n try {\n const mentalModel = await fetchMentalModelInjection(agentName, projectDir);\n if (mentalModel) {\n appendix += `\\n\\n${mentalModel}`;\n }\n } catch {\n // Mental model fetch failure \u2014 non-fatal\n }\n }\n\n // Step 6: Return enriched prompt (or unchanged basePrompt if no context found)\n return appendix ? basePrompt + appendix : basePrompt;\n}\n", "/**\n * Claude Code path provider.\n *\n * Implements AdapterPathProvider with Claude Code-specific directory locations.\n *\n * @task T5240\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterPathProvider } from '@cleocode/contracts';\n\n/**\n * Path provider for Anthropic Claude Code CLI.\n *\n * Resolves Claude Code's standard directory layout:\n * - Config dir: ~/.claude (or CLAUDE_HOME)\n * - Settings: ~/.claude/settings.json (or CLAUDE_SETTINGS)\n * - Agents: ~/.claude/agents\n * - Memory DB: ~/.claude-mem/claude-mem.db (or CLAUDE_MEM_DB)\n *\n * @remarks\n * All paths respect environment variable overrides for CI and non-standard\n * installations. When env vars are unset, the canonical default paths are used.\n */\nexport class ClaudeCodePathProvider implements AdapterPathProvider {\n /** Get the provider's root configuration directory. */\n getProviderDir(): string {\n return process.env['CLAUDE_HOME'] ?? join(homedir(), '.claude');\n }\n\n /** Get the path to the provider's settings file, or null if unavailable. */\n getSettingsPath(): string | null {\n return process.env['CLAUDE_SETTINGS'] ?? join(this.getProviderDir(), 'settings.json');\n }\n\n /** Get the directory where agents are installed, or null if unsupported. */\n getAgentInstallDir(): string | null {\n return join(this.getProviderDir(), 'agents');\n }\n\n /** Get the path to the provider's memory database, or null if unsupported. */\n getMemoryDbPath(): string | null {\n return process.env['CLAUDE_MEM_DB'] ?? join(homedir(), '.claude-mem', 'claude-mem.db');\n }\n}\n", "/**\n * Claude Code context monitor provider.\n *\n * Implements AdapterContextMonitorProvider for Claude Code's context window\n * tracking and statusline integration.\n *\n * @task T5240\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { AdapterContextMonitorProvider } from '@cleocode/contracts';\nimport { ClaudeCodePathProvider } from './paths.js';\n\n/** Context window input from Claude Code. */\ninterface ContextWindowInput {\n context_window: {\n context_window_size?: number;\n current_usage?: {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n };\n };\n}\n\n/** Thresholds for context window status levels. */\nconst THRESHOLDS = {\n WARNING: 50,\n CAUTION: 70,\n CRITICAL: 85,\n EMERGENCY: 95,\n} as const;\n\ntype ContextStatus = 'ok' | 'warning' | 'caution' | 'critical' | 'emergency';\n\nfunction getContextStatusFromPercentage(percentage: number): ContextStatus {\n if (percentage >= THRESHOLDS.EMERGENCY) return 'emergency';\n if (percentage >= THRESHOLDS.CRITICAL) return 'critical';\n if (percentage >= THRESHOLDS.CAUTION) return 'caution';\n if (percentage >= THRESHOLDS.WARNING) return 'warning';\n return 'ok';\n}\n\n/**\n * Context monitor provider for Claude Code.\n *\n * Processes context window JSON from Claude Code and writes state files\n * for statusline display. Also provides statusline configuration\n * and setup instructions specific to Claude Code's settings.json.\n *\n * @remarks\n * The provider writes a JSON state file to `.cleo/context-states/.context-state.json`\n * which can be read by external statusline scripts (e.g. tmux, starship).\n * Context thresholds at 50%, 70%, 85%, and 95% map to warning, caution,\n * critical, and emergency status levels respectively.\n */\nexport class ClaudeCodeContextMonitorProvider implements AdapterContextMonitorProvider {\n /** Path provider for resolving Claude Code directory locations. */\n private pathProvider = new ClaudeCodePathProvider();\n\n /** Process raw context window JSON and return a formatted summary string. */\n async processContextInput(input: unknown, cwd?: string): Promise<string> {\n const typed = input as ContextWindowInput;\n const contextSize = typed.context_window?.context_window_size ?? 200000;\n const usage = typed.context_window?.current_usage;\n\n if (!usage) return '-- no data';\n\n const inputTokens = usage.input_tokens ?? 0;\n const outputTokens = usage.output_tokens ?? 0;\n const cacheCreate = usage.cache_creation_input_tokens ?? 0;\n\n const totalTokens = inputTokens + outputTokens + cacheCreate;\n const percentage = Math.floor((totalTokens * 100) / contextSize);\n const status = getContextStatusFromPercentage(percentage);\n\n // Write state file if CLEO dir exists\n const cleoDir = cwd ? join(cwd, '.cleo') : '.cleo';\n if (existsSync(cleoDir)) {\n const stateDir = join(cleoDir, 'context-states');\n const statePath = join(stateDir, '.context-state.json');\n\n const state = {\n $schema: 'https://cleo-dev.com/schemas/v1/context-state.schema.json',\n version: '1.0.0',\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, 'Z'),\n staleAfterMs: 5000,\n contextWindow: {\n maxTokens: contextSize,\n currentTokens: totalTokens,\n percentage,\n breakdown: {\n inputTokens,\n outputTokens,\n cacheCreationTokens: cacheCreate,\n cacheReadTokens: usage.cache_read_input_tokens ?? 0,\n },\n },\n thresholds: {\n warning: THRESHOLDS.WARNING,\n caution: THRESHOLDS.CAUTION,\n critical: THRESHOLDS.CRITICAL,\n emergency: THRESHOLDS.EMERGENCY,\n },\n status,\n cleoSessionId: '',\n };\n\n try {\n await mkdir(dirname(statePath), { recursive: true });\n writeFileSync(statePath, JSON.stringify(state, null, 2));\n } catch {\n // Non-fatal\n }\n }\n\n return `${percentage}% | ${totalTokens}/${contextSize}`;\n }\n\n /** Check the current statusline integration status in Claude Code settings. */\n checkStatuslineIntegration(): 'configured' | 'not_configured' | 'custom_no_cleo' | 'no_settings' {\n const settingsPath = this.pathProvider.getSettingsPath();\n if (!settingsPath || !existsSync(settingsPath)) return 'no_settings';\n\n try {\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const statusLine = settings.statusLine;\n\n if (!statusLine?.type) return 'not_configured';\n if (statusLine.type !== 'command') return 'custom_no_cleo';\n\n const cmd = statusLine.command ?? '';\n\n if (\n cmd.includes('context-monitor.sh') ||\n cmd.includes('cleo-statusline') ||\n cmd.includes('.context-state.json') ||\n cmd.includes('context-states')\n ) {\n return 'configured';\n }\n\n const scriptPath = cmd.startsWith('~') ? cmd.replace('~', homedir()) : cmd;\n if (existsSync(scriptPath)) {\n try {\n const content = readFileSync(scriptPath, 'utf-8');\n if (content.includes('context-state.json')) return 'configured';\n } catch {\n /* unreadable */\n }\n }\n\n return 'custom_no_cleo';\n } catch {\n return 'no_settings';\n }\n }\n\n /** Get the recommended statusline configuration object for Claude Code settings. */\n getStatuslineConfig(): Record<string, unknown> {\n return {\n statusLine: {\n type: 'command',\n command: join(homedir(), '.cleo', 'lib', 'session', 'context-monitor.sh'),\n },\n };\n }\n\n /** Get human-readable setup instructions for enabling context monitoring. */\n getSetupInstructions(): string {\n const settingsPath = this.pathProvider.getSettingsPath() ?? '~/.claude/settings.json';\n\n return [\n 'To enable context monitoring, add to your Claude Code settings:',\n `File: ${settingsPath}`,\n '',\n JSON.stringify(this.getStatuslineConfig(), null, 2),\n '',\n 'This enables real-time context window tracking in the CLI.',\n ].join('\\n');\n }\n}\n", "/**\n * Claude Code Hook Provider\n *\n * Maps Claude Code's native hook events to CAAMP canonical hook events.\n * Claude Code supports 14 of 16 canonical events (all except PreModel, PostModel).\n *\n * Event translation uses CAAMP normalizer APIs:\n * - `toCanonical(nativeName, 'claude-code')` for runtime event name resolution\n * - `getSupportedEvents('claude-code')` to enumerate supported canonical events\n * - `getProviderHookProfile('claude-code')` for the full provider profile\n *\n * A static map derived from CAAMP 1.9.1 hook-mappings.json is maintained as\n * a fallback for environments where CAAMP's runtime resolution is unavailable.\n *\n * @task T164\n * @epic T134\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/** CAAMP provider identifier for Claude Code. */\nconst PROVIDER_ID = 'claude-code' as const;\n\n/**\n * Fallback map from Claude Code native event names to CAAMP canonical names.\n *\n * Derived from `getProviderHookProfile('claude-code').mappings` in CAAMP 1.9.1.\n * Covers all 14 supported events. PreModel and PostModel are not supported\n * by Claude Code and are absent from this map.\n *\n * Used as fallback when CAAMP runtime is unavailable, and as the synchronous\n * implementation of `mapProviderEvent()`.\n */\nconst CLAUDE_CODE_EVENT_MAP: Record<string, string> = {\n // CAAMP: toNative('SessionStart', 'claude-code') = 'SessionStart'\n SessionStart: 'SessionStart',\n // CAAMP: toNative('SessionEnd', 'claude-code') = 'SessionEnd'\n SessionEnd: 'SessionEnd',\n // CAAMP: toNative('PromptSubmit', 'claude-code') = 'UserPromptSubmit'\n UserPromptSubmit: 'PromptSubmit',\n // CAAMP: toNative('ResponseComplete', 'claude-code') = 'Stop'\n Stop: 'ResponseComplete',\n // CAAMP: toNative('PreToolUse', 'claude-code') = 'PreToolUse'\n PreToolUse: 'PreToolUse',\n // CAAMP: toNative('PostToolUse', 'claude-code') = 'PostToolUse'\n PostToolUse: 'PostToolUse',\n // CAAMP: toNative('PostToolUseFailure','claude-code') = 'PostToolUseFailure'\n PostToolUseFailure: 'PostToolUseFailure',\n // CAAMP: toNative('PermissionRequest', 'claude-code') = 'PermissionRequest'\n PermissionRequest: 'PermissionRequest',\n // CAAMP: toNative('SubagentStart', 'claude-code') = 'SubagentStart'\n SubagentStart: 'SubagentStart',\n // CAAMP: toNative('SubagentStop', 'claude-code') = 'SubagentStop'\n SubagentStop: 'SubagentStop',\n // CAAMP: toNative('PreCompact', 'claude-code') = 'PreCompact'\n PreCompact: 'PreCompact',\n // CAAMP: toNative('PostCompact', 'claude-code') = 'PostCompact'\n PostCompact: 'PostCompact',\n // CAAMP: toNative('Notification', 'claude-code') = 'Notification'\n Notification: 'Notification',\n // CAAMP: toNative('ConfigChange', 'claude-code') = 'ConfigChange'\n ConfigChange: 'ConfigChange',\n};\n\n/**\n * Hook provider for Claude Code.\n *\n * Claude Code registers hooks via its global config at `~/.claude/settings.json`.\n * Supported handler types: command, http, prompt, agent.\n *\n * Event mapping is based on `getProviderHookProfile('claude-code')` from\n * CAAMP 1.9.1. Async accessors (`getSupportedCanonicalEvents`,\n * `getProviderProfile`) call CAAMP directly when available.\n *\n * Since hooks are registered through the config system (managed by the install\n * provider), `registerNativeHooks` and `unregisterNativeHooks` track registration\n * state without performing filesystem operations.\n *\n * @remarks\n * Claude Code is the only provider that supports all 14 of its declared\n * canonical events at runtime. The static event map is maintained as a\n * synchronous fallback; async methods like {@link getSupportedCanonicalEvents}\n * and {@link getProviderProfile} call CAAMP directly when available.\n *\n * @task T164\n * @epic T134\n */\nexport class ClaudeCodeHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Claude Code native event name to a CAAMP canonical hook event name.\n *\n * Looks up the native event name in the map derived from\n * `getProviderHookProfile('claude-code').mappings` (CAAMP 1.9.1).\n * Returns null for unrecognised events (e.g. PreModel, PostModel which\n * Claude Code does not support).\n *\n * @param providerEvent - Claude Code native event (e.g. \"UserPromptSubmit\", \"Stop\")\n * @returns CAAMP canonical event name, or null if unmapped\n * @task T164\n */\n mapProviderEvent(providerEvent: string): string | null {\n return CLAUDE_CODE_EVENT_MAP[providerEvent] ?? null;\n }\n\n /** Project directory this hook provider was registered for. */\n private projectDir: string | null = null;\n\n /**\n * Register native hooks for a project.\n *\n * Writes CLEO hook entries to `~/.claude/settings.json` so that Claude Code's\n * native event system calls cleo CLI commands when events fire. This bridges\n * Claude Code's event loop to CLEO's internal hook dispatch.\n *\n * Idempotent: skips writing if CLEO hooks already exist in settings.json.\n *\n * Hook entries registered:\n * - `Stop` \u2192 `cleo session end --quiet` (triggers LLM extraction, reflector, consolidation)\n * - `PostToolUse` (Write|Edit) \u2192 brain observation for file modifications\n * - `SubagentStop` \u2192 brain observation for agent completion\n *\n * @param projectDir - Project directory for context-scoped hook commands\n * @task T164 @task T555\n */\n async registerNativeHooks(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.registered = true;\n\n // Write CLEO hook entries to ~/.claude/settings.json (idempotent)\n try {\n const home = homedir();\n const settingsPath = join(home, '.claude', 'settings.json');\n\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n // Start fresh if settings.json is corrupt\n }\n }\n\n const hooks = (settings.hooks ?? {}) as Record<string, unknown[]>;\n\n // Check if CLEO hooks already registered (look for our marker comment in commands)\n const alreadyRegistered = Object.values(hooks).some(\n (entries) =>\n Array.isArray(entries) &&\n entries.some(\n (e) =>\n typeof e === 'object' &&\n e !== null &&\n Array.isArray((e as Record<string, unknown>).hooks) &&\n ((e as Record<string, unknown>).hooks as Array<Record<string, string>>).some(\n (h) => typeof h.command === 'string' && h.command.includes('# cleo-hook'),\n ),\n ),\n );\n\n if (alreadyRegistered) {\n return; // Already wired \u2014 idempotent\n }\n\n // Register Stop hook \u2192 triggers cleo session end (LLM extraction, reflector, consolidation)\n if (!hooks.Stop) hooks.Stop = [];\n (hooks.Stop as unknown[]).push({\n matcher: '',\n hooks: [\n {\n type: 'command',\n command: `cleo session end --quiet # cleo-hook`,\n },\n ],\n });\n\n // Register PostToolUse hook \u2192 brain observation for file writes\n if (!hooks.PostToolUse) hooks.PostToolUse = [];\n (hooks.PostToolUse as unknown[]).push({\n matcher: 'Write|Edit',\n hooks: [\n {\n type: 'command',\n command: `cleo observe \"File modified via $TOOL_NAME\" --title \"tool-use\" --quiet # cleo-hook`,\n },\n ],\n });\n\n settings.hooks = hooks;\n mkdirSync(join(home, '.claude'), { recursive: true });\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n } catch {\n // Settings write failure is non-fatal \u2014 hooks can be registered manually\n }\n }\n\n /**\n * Unregister native hooks.\n *\n * Removes CLEO hook entries from `~/.claude/settings.json` by filtering out\n * entries containing the `# cleo-hook` marker.\n *\n * @task T164 @task T555\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n this.projectDir = null;\n\n try {\n const home = homedir();\n const settingsPath = join(home, '.claude', 'settings.json');\n if (!existsSync(settingsPath)) return;\n\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) as Record<string, unknown>;\n const hooks = settings.hooks as Record<string, unknown[]> | undefined;\n if (!hooks) return;\n\n // Filter out entries with the cleo-hook marker\n let changed = false;\n for (const [event, entries] of Object.entries(hooks)) {\n if (!Array.isArray(entries)) continue;\n const filtered = entries.filter(\n (e) =>\n !(\n typeof e === 'object' &&\n e !== null &&\n Array.isArray((e as Record<string, unknown>).hooks) &&\n ((e as Record<string, unknown>).hooks as Array<Record<string, string>>).some(\n (h) => typeof h.command === 'string' && h.command.includes('# cleo-hook'),\n )\n ),\n );\n if (filtered.length !== entries.length) {\n hooks[event] = filtered;\n changed = true;\n }\n }\n\n if (changed) {\n settings.hooks = hooks;\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n }\n } catch {\n // Cleanup failure is non-fatal\n }\n }\n\n /**\n * Check whether hooks have been registered via `registerNativeHooks`.\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the project directory this hook provider was registered for.\n *\n * Returns null if hooks have not been registered yet.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n\n /**\n * Get the native\u2192canonical event mapping for introspection and debugging.\n *\n * Returns the map derived from `getProviderHookProfile('claude-code').mappings`\n * (CAAMP 1.9.1). Use `getSupportedCanonicalEvents()` to enumerate canonical\n * names via live CAAMP APIs.\n *\n * @returns Immutable record of native event name \u2192 canonical event name\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...CLAUDE_CODE_EVENT_MAP };\n }\n\n /**\n * Enumerate supported canonical events via CAAMP's `getSupportedEvents()`.\n *\n * Calls `getSupportedEvents('claude-code')` from the CAAMP normalizer to\n * get the authoritative list. Claude Code supports 14 of 16 canonical events\n * (PreModel and PostModel are not supported). Falls back to the values of\n * the static event map when CAAMP is unavailable at runtime.\n *\n * @returns Array of CAAMP canonical event names supported by Claude Code\n * @task T164\n */\n async getSupportedCanonicalEvents(): Promise<string[]> {\n try {\n const { getSupportedEvents } = await import('@cleocode/caamp');\n return getSupportedEvents(PROVIDER_ID) as string[];\n } catch {\n return [...new Set(Object.values(CLAUDE_CODE_EVENT_MAP))];\n }\n }\n\n /**\n * Retrieve the full provider hook profile from CAAMP.\n *\n * Calls `getProviderHookProfile('claude-code')` from the CAAMP normalizer to\n * get the complete profile: hook system type (`config`), config path\n * (`~/.claude/settings.json`), handler types, and all event mappings.\n * Returns null when CAAMP is unavailable at runtime.\n *\n * @returns Provider hook profile or null if CAAMP is unavailable\n * @task T164\n */\n async getProviderProfile(): Promise<unknown | null> {\n try {\n const { getProviderHookProfile } = await import('@cleocode/caamp');\n return getProviderHookProfile(PROVIDER_ID) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Translate a CAAMP canonical event to its Claude Code native name via CAAMP.\n *\n * Calls `toNative(canonical, 'claude-code')` from the CAAMP normalizer.\n * Returns null for unsupported events (PreModel, PostModel) or when\n * CAAMP is unavailable.\n *\n * @param canonical - CAAMP canonical event name (e.g. \"PromptSubmit\")\n * @returns Claude Code native event name or null\n * @task T164\n */\n async toNativeEvent(canonical: string): Promise<string | null> {\n try {\n const { toNative } = await import('@cleocode/caamp');\n return toNative(canonical as Parameters<typeof toNative>[0], PROVIDER_ID);\n } catch {\n // Invert the static map as fallback\n const entry = Object.entries(CLAUDE_CODE_EVENT_MAP).find(([, v]) => v === canonical);\n return entry?.[0] ?? null;\n }\n }\n\n /**\n * Extract a plain-text transcript from Claude Code session JSONL files.\n *\n * Reads the most recent .jsonl file under `~/.claude/projects/` and\n * extracts user/assistant turn text into a flat string for brain\n * observation extraction.\n *\n * Returns null when no session data is found or on any read error.\n *\n * @param _sessionId - CLEO session ID (unused; reads the most recent file)\n * @param _projectDir - Project directory (unused; Claude Code uses global paths)\n * @task T144 @epic T134\n */\n async getTranscript(_sessionId: string, _projectDir: string): Promise<string | null> {\n try {\n const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? '/root';\n const projectsDir = join(homeDir, '.claude', 'projects');\n\n // Find all JSONL files across project subdirectories\n let allFiles: Array<{ path: string; mtime: number }> = [];\n try {\n const projectDirs = await readdir(projectsDir, { withFileTypes: true });\n for (const entry of projectDirs) {\n if (!entry.isDirectory()) continue;\n const subDir = join(projectsDir, entry.name);\n try {\n const files = await readdir(subDir);\n for (const file of files) {\n if (!file.endsWith('.jsonl')) continue;\n const filePath = join(subDir, file);\n // Use file path modification heuristic (filename usually includes timestamp)\n allFiles.push({ path: filePath, mtime: 0 });\n }\n } catch {\n // Skip unreadable subdirectories\n }\n }\n } catch {\n return null;\n }\n\n if (allFiles.length === 0) return null;\n\n // Sort by path descending (timestamps in filenames sort naturally)\n allFiles = allFiles.sort((a, b) => b.path.localeCompare(a.path));\n const mostRecent = allFiles[0];\n if (!mostRecent) return null;\n\n const raw = await readFile(mostRecent.path, 'utf-8');\n const lines = raw.split('\\n').filter((l) => l.trim());\n\n const turns: string[] = [];\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as Record<string, unknown>;\n const role = entry.role as string | undefined;\n const content = entry.content;\n if (role === 'assistant' && typeof content === 'string') {\n turns.push(`assistant: ${content}`);\n } else if (role === 'user' && typeof content === 'string') {\n turns.push(`user: ${content}`);\n }\n } catch {\n // Skip malformed lines\n }\n }\n\n return turns.length > 0 ? turns.join('\\n') : null;\n } catch {\n return null;\n }\n }\n}\n", "/**\n * Claude Code Install Provider\n *\n * Handles CLEO installation into Claude Code environments:\n * - Ensures CLAUDE.md has CLEO @-references\n * - Manages plugin registration in ~/.claude/settings.json\n *\n * Migrated from src/core/install/claude-plugin.ts\n *\n * @task T5240\n */\n\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in CLAUDE.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/** Resolve the commands directory bundled with this adapter. */\nfunction getAdapterCommandsDir(): string {\n // Works in both ESM (import.meta.url) and compiled output\n const thisDir = dirname(fileURLToPath(import.meta.url));\n return join(thisDir, 'commands');\n}\n\n/**\n * Install provider for Claude Code.\n *\n * Manages CLEO's integration with Claude Code by:\n * 1. Ensuring CLAUDE.md contains @-references to CLEO instruction files\n * 2. Installing adapter-provided commands to .claude/commands/\n * 3. Registering the brain observation plugin in ~/.claude/settings.json\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. The provider disables the legacy\n * `claude-mem\\@thedotmack` plugin if present and enables the unified\n * `cleo\\@cleocode` plugin instead.\n */\nexport class ClaudeCodeInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Claude Code project.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure CLAUDE.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'CLAUDE.md');\n }\n\n // Step 2: Install adapter-provided commands to .claude/commands/\n const commandsInstalled = this.installCommands(projectDir);\n if (commandsInstalled.length > 0) {\n details.commands = commandsInstalled;\n }\n\n // Step 3: Register plugin in ~/.claude/settings.json\n const pluginResult = this.registerPlugin();\n if (pluginResult) {\n details.plugin = pluginResult;\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the current Claude Code project.\n *\n * Does not remove CLAUDE.md references (they are harmless if CLEO is not present).\n */\n async uninstall(): Promise<void> {}\n\n /**\n * Check whether CLEO is installed in the current environment.\n *\n * Checks for plugin enabled in ~/.claude/settings.json.\n */\n async isInstalled(): Promise<boolean> {\n // Check ~/.claude/settings.json for plugin registration\n const settingsPath = join(homedir(), '.claude', 'settings.json');\n if (existsSync(settingsPath)) {\n try {\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const plugins = settings.enabledPlugins as Record<string, boolean> | undefined;\n if (plugins && plugins['cleo@cleocode'] === true) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure CLAUDE.md contains @-references to CLEO instruction files.\n *\n * Creates CLAUDE.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update CLAUDE.md with CLEO @-references.\n *\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const claudeMdPath = join(projectDir, 'CLAUDE.md');\n let content = '';\n let existed = false;\n\n if (existsSync(claudeMdPath)) {\n content = readFileSync(claudeMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n // Append missing references\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n // Create new CLAUDE.md with references\n content = refsBlock + '\\n';\n }\n\n writeFileSync(claudeMdPath, content, 'utf-8');\n return true;\n }\n\n /**\n * Install Claude Code-specific commands to .claude/commands/ in the project.\n *\n * These commands extend CLEO's provider-neutral skills with Claude Code-specific\n * operational patterns (Agent tool spawn templates, model assignment, context guardrails).\n *\n * @param projectDir - Project root directory\n * @returns Array of installed command filenames\n */\n private installCommands(projectDir: string): string[] {\n const adapterCommandsDir = getAdapterCommandsDir();\n if (!existsSync(adapterCommandsDir)) {\n return [];\n }\n\n const targetDir = join(projectDir, '.claude', 'commands');\n mkdirSync(targetDir, { recursive: true });\n\n const installed: string[] = [];\n const files = readdirSync(adapterCommandsDir).filter((f) => f.endsWith('.md'));\n\n for (const file of files) {\n const src = join(adapterCommandsDir, file);\n const dest = join(targetDir, file);\n copyFileSync(src, dest);\n installed.push(file);\n }\n\n return installed;\n }\n\n /**\n * Register the CLEO brain plugin in ~/.claude/settings.json.\n *\n * @returns Description of what was registered, or null if no change needed\n */\n private registerPlugin(): string | null {\n const home = homedir();\n const settingsPath = join(home, '.claude', 'settings.json');\n\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n // Start fresh\n }\n }\n\n const enabledPlugins = (settings.enabledPlugins as Record<string, boolean>) ?? {};\n const pluginKey = 'cleo@cleocode';\n\n if (enabledPlugins[pluginKey] === true) {\n return null;\n }\n\n // Disable old claude-mem if present\n if (enabledPlugins['claude-mem@thedotmack'] === true) {\n enabledPlugins['claude-mem@thedotmack'] = false;\n }\n\n enabledPlugins[pluginKey] = true;\n settings.enabledPlugins = enabledPlugins;\n\n mkdirSync(join(home, '.claude'), { recursive: true });\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n\n return `Enabled ${pluginKey} in ~/.claude/settings.json`;\n }\n}\n", "/**\n * Central error utilities for CLEO.\n *\n * Provides consistent error handling patterns across the codebase.\n * DRY error formatting, normalization, and transformation utilities.\n *\n * @task T5702\n */\n\n/**\n * Normalize any thrown value into a standardized error object.\n *\n * Handles:\n * - Error instances (preserves stack trace info)\n * - Strings (wraps in Error)\n * - Objects with message property\n * - null/undefined (provides fallback)\n *\n * @param error - The thrown value to normalize\n * @param fallbackMessage - Message to use if error provides none\n * @returns Normalized error with consistent shape\n *\n * @remarks\n * This function is safe to call on any value thrown by a `catch` clause.\n * It guarantees the returned object is always an `Error` instance with a\n * non-empty `message` property.\n *\n * @example\n * ```typescript\n * try {\n * await riskyOperation();\n * } catch (err) {\n * const error = normalizeError(err, 'Operation failed');\n * console.error(error.message);\n * }\n * ```\n */\nexport function normalizeError(\n error: unknown,\n fallbackMessage = 'An unexpected error occurred',\n): Error {\n if (error instanceof Error) {\n return error;\n }\n\n if (typeof error === 'string') {\n return new Error(error);\n }\n\n if (\n error !== null &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n return new Error(error.message);\n }\n\n return new Error(fallbackMessage);\n}\n\n/**\n * Extract a human-readable message from any error value.\n *\n * Safe to use on unknown thrown values without type guards.\n *\n * @param error - The error value\n * @param fallback - Fallback message if extraction fails\n * @returns The error message string\n *\n * @remarks\n * Inspects the value for an `Error` instance, a plain string, or an object\n * with a `message` property before falling back to the provided default.\n *\n * @example\n * ```typescript\n * const message = getErrorMessage(err, 'Unknown error');\n * ```\n */\nexport function getErrorMessage(error: unknown, fallback = 'Unknown error'): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (\n error !== null &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n\n return fallback;\n}\n\n/**\n * Format error details for logging or display.\n *\n * Includes stack trace for Error instances when includeStack is true.\n *\n * @param error - The error to format\n * @param context - Optional context to prepend\n * @param includeStack - Whether to include stack traces (default: false)\n * @returns Formatted error string\n *\n * @remarks\n * When `context` is provided it is prefixed in square brackets (e.g.\n * `[Database] Connection refused`). Stack traces are appended on a new line\n * only when `includeStack` is `true` and the value is an `Error` with a stack.\n *\n * @example\n * ```typescript\n * console.error(formatError(err, 'Database connection'));\n * // Output: [Database connection] Connection refused\n * ```\n */\nexport function formatError(error: unknown, context?: string, includeStack = false): string {\n const message = getErrorMessage(error);\n const prefix = context ? `[${context}] ` : '';\n let result = `${prefix}${message}`;\n\n if (includeStack && error instanceof Error && error.stack) {\n result += `\\n${error.stack}`;\n }\n\n return result;\n}\n\n/**\n * Check if an error represents a specific error type by code or name.\n *\n * Useful for conditional error handling based on error types.\n *\n * @param error - The error to check\n * @param codeOrName - The error code or name to match\n * @returns True if the error matches\n *\n * @remarks\n * Checks both `Error.name` and a custom `code` property, supporting both\n * standard and LAFS-style error codes (e.g. `\"E_NOT_FOUND\"`).\n *\n * @example\n * ```typescript\n * if (isErrorType(err, 'E_NOT_FOUND')) {\n * // Handle not found specifically\n * }\n * ```\n */\nexport function isErrorType(error: unknown, codeOrName: string): boolean {\n if (error instanceof Error) {\n if (error.name === codeOrName) {\n return true;\n }\n // Check for custom code property\n if ('code' in error && error.code === codeOrName) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Create a standardized error result object.\n *\n * Common pattern for operations that return { success: boolean, error?: string }\n *\n * @param error - The error value\n * @returns Error result object\n *\n * @remarks\n * Pairs with {@link createSuccessResult} and {@link isErrorResult} to provide\n * a consistent result-or-error pattern without exceptions.\n *\n * @example\n * ```typescript\n * return createErrorResult(err);\n * // Returns: { success: false, error: \"Something went wrong\" }\n * ```\n */\nexport function createErrorResult(error: unknown): { success: false; error: string } {\n return {\n success: false,\n error: getErrorMessage(error),\n };\n}\n\n/**\n * Create a standardized success result object.\n *\n * @returns Success result object\n *\n * @remarks\n * Pairs with {@link createErrorResult} and {@link isErrorResult} to provide\n * a consistent result-or-error pattern without exceptions.\n *\n * @example\n * ```typescript\n * return createSuccessResult();\n * // Returns: { success: true }\n * ```\n */\nexport function createSuccessResult(): { success: true } {\n return { success: true };\n}\n\n/**\n * Type guard for error results.\n *\n * @param result - The result to check\n * @returns True if the result is an error result\n *\n * @remarks\n * Narrows the result type so that `result.error` is guaranteed to be a string\n * after the guard returns `true`.\n *\n * @example\n * ```typescript\n * const result = await someOperation();\n * if (isErrorResult(result)) {\n * console.error(result.error);\n * }\n * ```\n */\nexport function isErrorResult(result: {\n success: boolean;\n error?: string;\n}): result is { success: false; error: string } {\n return !result.success;\n}\n", "/**\n * CLEO exit codes \u2014 canonical definitions shared across all layers.\n *\n * Ranges: 0 = success, 1-99 = errors, 100+ = special (non-error) states.\n *\n * @epic T4454\n * @task T4456\n * @task T5710\n */\n\nexport enum ExitCode {\n // === SUCCESS (0) ===\n SUCCESS = 0,\n\n // === GENERAL ERRORS (1-9) ===\n GENERAL_ERROR = 1,\n INVALID_INPUT = 2,\n FILE_ERROR = 3,\n NOT_FOUND = 4,\n DEPENDENCY_ERROR = 5,\n VALIDATION_ERROR = 6,\n LOCK_TIMEOUT = 7,\n CONFIG_ERROR = 8,\n\n // === HIERARCHY ERRORS (10-19) ===\n PARENT_NOT_FOUND = 10,\n DEPTH_EXCEEDED = 11,\n SIBLING_LIMIT = 12,\n INVALID_PARENT_TYPE = 13,\n CIRCULAR_REFERENCE = 14,\n ORPHAN_DETECTED = 15,\n HAS_CHILDREN = 16,\n TASK_COMPLETED = 17,\n CASCADE_FAILED = 18,\n HAS_DEPENDENTS = 19,\n\n // === CONCURRENCY ERRORS (20-29) ===\n CHECKSUM_MISMATCH = 20,\n CONCURRENT_MODIFICATION = 21,\n ID_COLLISION = 22,\n\n // === SESSION ERRORS (30-39) ===\n SESSION_EXISTS = 30,\n SESSION_NOT_FOUND = 31,\n SCOPE_CONFLICT = 32,\n SCOPE_INVALID = 33,\n TASK_NOT_IN_SCOPE = 34,\n TASK_CLAIMED = 35,\n SESSION_REQUIRED = 36,\n SESSION_CLOSE_BLOCKED = 37,\n ACTIVE_TASK_REQUIRED = 38,\n NOTES_REQUIRED = 39,\n\n // === VERIFICATION ERRORS (40-47) ===\n VERIFICATION_INIT_FAILED = 40,\n GATE_UPDATE_FAILED = 41,\n INVALID_GATE = 42,\n INVALID_AGENT = 43,\n MAX_ROUNDS_EXCEEDED = 44,\n GATE_DEPENDENCY = 45,\n VERIFICATION_LOCKED = 46,\n ROUND_MISMATCH = 47,\n\n // === CONTEXT SAFEGUARD (50-54) ===\n CONTEXT_WARNING = 50,\n CONTEXT_CAUTION = 51,\n CONTEXT_CRITICAL = 52,\n CONTEXT_EMERGENCY = 53,\n CONTEXT_STALE = 54,\n\n // === ORCHESTRATOR ERRORS (60-67) ===\n PROTOCOL_MISSING = 60,\n INVALID_RETURN_MESSAGE = 61,\n MANIFEST_ENTRY_MISSING = 62,\n SPAWN_VALIDATION_FAILED = 63,\n AUTONOMOUS_BOUNDARY = 64,\n HANDOFF_REQUIRED = 65,\n RESUME_FAILED = 66,\n CONCURRENT_SESSION = 67,\n\n // === NEXUS ERRORS (70-79) ===\n NEXUS_NOT_INITIALIZED = 70,\n NEXUS_PROJECT_NOT_FOUND = 71,\n NEXUS_PERMISSION_DENIED = 72,\n NEXUS_INVALID_SYNTAX = 73,\n NEXUS_SYNC_FAILED = 74,\n NEXUS_REGISTRY_CORRUPT = 75,\n NEXUS_PROJECT_EXISTS = 76,\n NEXUS_QUERY_FAILED = 77,\n NEXUS_GRAPH_ERROR = 78,\n NEXUS_RESERVED = 79,\n\n // === LIFECYCLE ENFORCEMENT (80-84) ===\n LIFECYCLE_GATE_FAILED = 80,\n AUDIT_MISSING = 81,\n CIRCULAR_VALIDATION = 82,\n LIFECYCLE_TRANSITION_INVALID = 83,\n PROVENANCE_REQUIRED = 84,\n\n // === ARTIFACT PUBLISH (85-89) ===\n ARTIFACT_TYPE_UNKNOWN = 85,\n ARTIFACT_VALIDATION_FAILED = 86,\n ARTIFACT_BUILD_FAILED = 87,\n ARTIFACT_PUBLISH_FAILED = 88,\n ARTIFACT_ROLLBACK_FAILED = 89,\n\n // === PROVENANCE (90-94) ===\n PROVENANCE_CONFIG_INVALID = 90,\n SIGNING_KEY_MISSING = 91,\n SIGNATURE_INVALID = 92,\n DIGEST_MISMATCH = 93,\n ATTESTATION_INVALID = 94,\n\n // === ADAPTER ERRORS (95-99) ===\n ADAPTER_NOT_FOUND = 95,\n ADAPTER_INIT_FAILED = 96,\n ADAPTER_HOOK_FAILED = 97,\n ADAPTER_SPAWN_FAILED = 98,\n ADAPTER_INSTALL_FAILED = 99,\n\n // === SPECIAL CODES (100+) - NOT errors ===\n NO_DATA = 100,\n ALREADY_EXISTS = 101,\n NO_CHANGE = 102,\n TESTS_SKIPPED = 103,\n\n // === LAFS ENVELOPE VALIDATION (Phase 6) ===\n /**\n * E_LAFS_VIOLATION \u2014 CLI output did not conform to the LAFS envelope\n * schema. Emitted by the CLI renderer middleware when `zod.parse()` on\n * the emitted envelope fails. This is an INTERNAL failure: CLEO itself\n * produced a malformed envelope.\n *\n * @task Phase 6 \u2014 LAFS formalization + schema consolidation\n */\n LAFS_VIOLATION = 104,\n}\n\n/** Check if an exit code represents an error (1-99). */\nexport function isErrorCode(code: ExitCode): boolean {\n return code >= 1 && code < 100;\n}\n\n/** Check if an exit code represents success (0 or 100+). */\nexport function isSuccessCode(code: ExitCode): boolean {\n return code === 0 || code >= 100;\n}\n\n/** Check if an exit code indicates no change (idempotent operation). */\nexport function isNoChangeCode(code: ExitCode): boolean {\n return code === ExitCode.NO_CHANGE;\n}\n\n/** Check if an exit code is recoverable (retry may succeed). */\nexport function isRecoverableCode(code: ExitCode): boolean {\n const nonRecoverable = new Set<ExitCode>([\n ExitCode.FILE_ERROR,\n ExitCode.DEPENDENCY_ERROR,\n ExitCode.CIRCULAR_REFERENCE,\n ExitCode.CASCADE_FAILED,\n ExitCode.SESSION_CLOSE_BLOCKED,\n ExitCode.VERIFICATION_LOCKED,\n ExitCode.CONTEXT_WARNING,\n ExitCode.CONTEXT_CAUTION,\n ExitCode.CONTEXT_CRITICAL,\n ExitCode.CONTEXT_EMERGENCY,\n ExitCode.CONTEXT_STALE,\n ExitCode.AUTONOMOUS_BOUNDARY,\n ExitCode.HANDOFF_REQUIRED,\n ExitCode.NEXUS_PERMISSION_DENIED,\n ExitCode.NEXUS_REGISTRY_CORRUPT,\n ExitCode.CIRCULAR_VALIDATION,\n ExitCode.LIFECYCLE_TRANSITION_INVALID,\n ExitCode.ARTIFACT_TYPE_UNKNOWN,\n ExitCode.ARTIFACT_ROLLBACK_FAILED,\n ExitCode.DIGEST_MISMATCH,\n ]);\n\n if (!isErrorCode(code)) return false;\n return !nonRecoverable.has(code);\n}\n\n/** Human-readable name for an exit code. */\nexport function getExitCodeName(code: ExitCode): string {\n return ExitCode[code] ?? 'UNKNOWN';\n}\n", "/**\n * Facade API interfaces for the Cleo class.\n *\n * These define the public API surface that consumers (e.g. CleoOS) use\n * to interact with @cleocode/core via the `Cleo` facade. Defined here\n * in contracts so downstream packages can import types without depending\n * on core directly.\n *\n * @module facade\n */\n\nimport type { ConduitMessage } from './conduit.js';\nimport type {\n DataAccessor,\n ExternalTask,\n ExternalTaskLink,\n ReconcileOptions,\n ReconcileResult,\n Task,\n TaskPriority,\n TaskSize,\n TaskStatus,\n TaskType,\n} from './index.js';\n\n// ============================================================================\n// Supporting types (previously scattered across core modules)\n// ============================================================================\n\n// --- Brain / Memory ---\n\n/** Observation type categories for brain entries. */\nexport const BRAIN_OBSERVATION_TYPES = [\n 'discovery',\n 'change',\n 'feature',\n 'bugfix',\n 'decision',\n 'refactor',\n] as const;\n\n/** Brain observation type. */\nexport type BrainObservationType = (typeof BRAIN_OBSERVATION_TYPES)[number];\n\n/** Options for hybrid (FTS + vector + graph) brain search. */\nexport interface HybridSearchOptions {\n /** Weight for full-text search results (0-1). */\n ftsWeight?: number;\n /** Weight for vector similarity results (0-1). */\n vecWeight?: number;\n /** Weight for graph-based results (0-1). */\n graphWeight?: number;\n /** Maximum number of results to return. */\n limit?: number;\n}\n\n// --- Admin / Import ---\n\n/** Strategy for handling duplicate tasks during import. */\nexport type DuplicateStrategy = 'skip' | 'overwrite' | 'rename';\n\n/** Parameters for task import operations. */\nexport interface ImportParams {\n /** Path to the import file. */\n file: string;\n /** Parent task ID for imported tasks. */\n parent?: string;\n /** Phase assignment for imported tasks. */\n phase?: string;\n /** Strategy when a duplicate task ID is found. */\n onDuplicate?: DuplicateStrategy;\n /** Label to add to all imported tasks. */\n addLabel?: string;\n /** If true, simulate the import without persisting. */\n dryRun?: boolean;\n /** Working directory for resolving paths. */\n cwd?: string;\n}\n\n// --- Agents ---\n\n/** Agent instance status values. */\nexport const AGENT_INSTANCE_STATUSES = [\n 'starting',\n 'active',\n 'idle',\n 'error',\n 'crashed',\n 'stopped',\n] as const;\n\n/** Agent instance status type. */\nexport type AgentInstanceStatus = (typeof AGENT_INSTANCE_STATUSES)[number];\n\n/** Agent type classification values. */\nexport const AGENT_TYPES = [\n 'orchestrator',\n 'executor',\n 'researcher',\n 'architect',\n 'validator',\n 'documentor',\n 'custom',\n] as const;\n\n/** Agent type classification. */\nexport type AgentType = (typeof AGENT_TYPES)[number];\n\n/**\n * Row shape for the `agent_instances` table.\n *\n * Manually defined to avoid Drizzle dependency in contracts.\n * Must stay in sync with `packages/core/src/agents/agent-schema.ts`.\n */\nexport interface AgentInstanceRow {\n /** Unique agent instance ID. */\n id: string;\n /** Agent type classification. */\n agentType: AgentType;\n /** Current status. */\n status: AgentInstanceStatus;\n /** Associated session ID (nullable). */\n sessionId: string | null;\n /** Associated task ID (nullable). */\n taskId: string | null;\n /** ISO timestamp when the agent started. */\n startedAt: string;\n /** ISO timestamp of the last heartbeat. */\n lastHeartbeat: string;\n /** ISO timestamp when the agent stopped (nullable). */\n stoppedAt: string | null;\n /** Number of errors encountered. */\n errorCount: number;\n /** Total tasks completed by this agent. */\n totalTasksCompleted: number;\n /** Agent capacity as a string (e.g. \"1.0\"). */\n capacity: string;\n /** JSON-encoded metadata. */\n metadataJson: string | null;\n /** Parent agent ID for hierarchical orchestration (nullable). */\n parentAgentId: string | null;\n}\n\n/** Options for registering a new agent instance. */\nexport interface RegisterAgentOptions {\n /** Agent type classification. */\n agentType: AgentType;\n /** Session to associate with. */\n sessionId?: string;\n /** Task to associate with. */\n taskId?: string;\n /** Parent agent ID for hierarchical orchestration. */\n parentAgentId?: string;\n /** Arbitrary metadata. */\n metadata?: Record<string, unknown>;\n}\n\n/** Agent capacity information. */\nexport interface AgentCapacity {\n /** Agent instance ID. */\n agentId: string;\n /** Agent type classification. */\n agentType: AgentType;\n /** Current status of the agent. */\n status: AgentInstanceStatus;\n /** Number of tasks currently assigned to this agent. */\n activeTasks: number;\n /** Number of additional tasks this agent can accept (max - active). */\n remainingCapacity: number;\n /** Maximum tasks this agent can hold. */\n maxCapacity: number;\n /** Whether this agent can accept new tasks. */\n available: boolean;\n}\n\n/** Agent health status from heartbeat monitoring. */\nexport interface AgentHealthStatus {\n /** Agent instance ID. */\n agentId: string;\n /** Current DB status. */\n status: AgentInstanceStatus;\n /** ISO timestamp of the last recorded heartbeat. */\n lastHeartbeat: string;\n /** Milliseconds since the last recorded heartbeat (at call time). */\n heartbeatAgeMs: number;\n /** Whether the agent is considered healthy (heartbeat within threshold). */\n healthy: boolean;\n /** Whether the agent is considered stale (heartbeat older than threshold). */\n stale: boolean;\n /** Threshold used for staleness determination (ms). */\n thresholdMs: number;\n}\n\n// --- Intelligence ---\n\n/** Severity classification for blast radius. */\nexport type BlastRadiusSeverity = 'isolated' | 'moderate' | 'widespread' | 'critical';\n\n/** A single task predicted to be affected by a change. */\nexport interface ImpactedTask {\n /** Task ID. */\n id: string;\n /** Task title. */\n title: string;\n /** Current task status. */\n status: string;\n /** Current task priority. */\n priority: string;\n /** Severity of exposure to the change. */\n exposure: 'direct' | 'dependent' | 'transitive';\n /** Number of downstream tasks that depend on this task. */\n downstreamCount: number;\n /** Why this task is predicted to be affected. */\n reason: string;\n}\n\n/** Full impact prediction report for a free-text change description. */\nexport interface ImpactReport {\n /** The original free-text change description. */\n change: string;\n /** Tasks directly matched by the change description (fuzzy search). */\n matchedTasks: ImpactedTask[];\n /** All tasks predicted to be affected, ordered by exposure severity. */\n affectedTasks: ImpactedTask[];\n /** Total count of distinct affected tasks (including direct matches). */\n totalAffected: number;\n /** Human-readable summary of predicted impact scope. */\n summary: string;\n}\n\n/** Quantified scope of a task's impact across the project. */\nexport interface BlastRadius {\n /** Number of direct dependents. */\n directCount: number;\n /** Number of transitive dependents (full downstream tree). */\n transitiveCount: number;\n /** Number of distinct epics affected. */\n epicCount: number;\n /** Percentage of the total project impacted (0-100). */\n projectPercentage: number;\n /** Classification of impact severity. */\n severity: BlastRadiusSeverity;\n}\n\n// ============================================================================\n// Task work types\n// ============================================================================\n\n/** Result of starting work on a task. */\nexport interface TaskStartResult {\n /** The task ID that was started. */\n taskId: string;\n /** The task title. */\n title: string;\n /** Previous task ID if one was active (auto-stopped). */\n previousTask?: string | null;\n}\n\n// ============================================================================\n// Facade API interfaces\n// ============================================================================\n\n/** Tasks domain API. */\nexport interface TasksAPI {\n /** Add a new task. */\n add(params: {\n title: string;\n description: string;\n parent?: string;\n priority?: TaskPriority;\n type?: TaskType;\n size?: TaskSize;\n phase?: string;\n labels?: string[];\n depends?: string[];\n notes?: string;\n }): Promise<unknown>;\n /** Find tasks by query, ID, status, or limit. */\n find(params: {\n query?: string;\n id?: string;\n status?: TaskStatus;\n limit?: number;\n }): Promise<unknown>;\n /** Show full details of a task. */\n show(taskId: string): Promise<unknown>;\n /** List tasks with optional filters. */\n list(params?: {\n status?: TaskStatus;\n priority?: TaskPriority;\n parentId?: string;\n phase?: string;\n limit?: number;\n }): Promise<unknown>;\n /** Update task fields. */\n update(params: {\n taskId: string;\n title?: string;\n status?: TaskStatus;\n priority?: TaskPriority;\n description?: string;\n notes?: string;\n }): Promise<unknown>;\n /** Complete a task with optional notes. */\n complete(params: { taskId: string; notes?: string }): Promise<unknown>;\n /** Delete a task. */\n delete(params: { taskId: string; force?: boolean }): Promise<unknown>;\n /** Archive tasks by date or IDs. */\n archive(params?: { before?: string; taskIds?: string[]; dryRun?: boolean }): Promise<unknown>;\n /** Start working on a specific task (sets focus). */\n start(taskId: string): Promise<unknown>;\n /** Stop working on the current task (clears focus). */\n stop(): Promise<{ previousTask: string | null }>;\n /** Get the current task work state. */\n current(): Promise<unknown>;\n}\n\n/** Sessions domain API. */\nexport interface SessionsAPI {\n /** Start a new session. */\n start(params: {\n name: string;\n scope: string;\n agent?: string;\n startTask?: string;\n }): Promise<unknown>;\n /** End the current session. */\n end(params?: { note?: string }): Promise<unknown>;\n /** Get current session status. */\n status(): Promise<unknown>;\n /** Resume an existing session. */\n resume(sessionId: string): Promise<unknown>;\n /** List sessions with optional filters. */\n list(params?: { status?: string; limit?: number }): Promise<unknown>;\n /** Find sessions by criteria. */\n find(params?: {\n status?: string;\n scope?: string;\n query?: string;\n limit?: number;\n }): Promise<unknown>;\n /** Show full details of a session. */\n show(sessionId: string): Promise<unknown>;\n /** Suspend a session. */\n suspend(sessionId: string, reason?: string): Promise<unknown>;\n /** Compute session briefing. */\n briefing(params?: { maxNextTasks?: number; scope?: string }): Promise<unknown>;\n /** Compute session handoff. */\n handoff(sessionId: string, options?: { note?: string; nextAction?: string }): Promise<unknown>;\n /** Garbage-collect stale sessions. */\n gc(maxAgeHours?: number): Promise<unknown>;\n /** Record a decision in a session. */\n recordDecision(params: {\n sessionId: string;\n taskId: string;\n decision: string;\n rationale: string;\n alternatives?: string[];\n }): Promise<unknown>;\n /** Record an assumption. */\n recordAssumption(params: {\n assumption: string;\n confidence: 'high' | 'medium' | 'low';\n sessionId?: string;\n taskId?: string;\n }): Promise<unknown>;\n /** Get context drift metrics. */\n contextDrift(params?: { sessionId?: string }): Promise<unknown>;\n /** Get decision log. */\n decisionLog(params?: { sessionId?: string; taskId?: string }): Promise<unknown>;\n /** Get last handoff for a scope. */\n lastHandoff(scope?: { type: string; epicId?: string }): Promise<unknown>;\n /** Serialize a session into a complete snapshot for persistence. */\n serialize(params?: { sessionId?: string; maxObservations?: number }): Promise<unknown>;\n /** Restore a session from a previously serialized snapshot. */\n restore(snapshot: unknown, params?: { agent?: string; activate?: boolean }): Promise<unknown>;\n}\n\n/** Memory/Brain domain API. */\nexport interface MemoryAPI {\n /** Record a brain observation. */\n observe(params: { text: string; title?: string; type?: BrainObservationType }): Promise<unknown>;\n /** Find brain entries by query. */\n find(params: {\n query: string;\n limit?: number;\n tables?: Array<'decisions' | 'patterns' | 'learnings' | 'observations'>;\n }): Promise<unknown>;\n /** Fetch brain entries by IDs. */\n fetch(params: { ids: string[] }): Promise<unknown>;\n /** Get temporal context around an anchor entry. */\n timeline(params: { anchor: string; depthBefore?: number; depthAfter?: number }): Promise<unknown>;\n /** Search brain entries. */\n search(query: string, options?: { limit?: number }): Promise<unknown>;\n /** Hybrid search combining FTS, vector, and graph. */\n hybridSearch(query: string, options?: HybridSearchOptions): Promise<unknown>;\n}\n\n/** Orchestration domain API. */\nexport interface OrchestrationAPI {\n /** Start orchestration for an epic. */\n start(epicId: string): Promise<unknown>;\n /** Analyze an epic's structure and dependencies. */\n analyze(epicId: string): Promise<unknown>;\n /** Get tasks ready to execute in an epic. */\n readyTasks(epicId: string): Promise<unknown>;\n /** Get the next recommended task in an epic. */\n nextTask(epicId: string): Promise<unknown>;\n /** Get orchestrator context for an epic. */\n context(epicId: string): Promise<unknown>;\n /** Build a dependency graph from tasks. */\n dependencyGraph(tasks: Task[]): unknown;\n /** Compute epic status summary. */\n epicStatus(epicId: string, title: string, children: Task[]): unknown;\n /** Compute progress metrics for tasks. */\n progress(tasks: Task[]): unknown;\n}\n\n/** Lifecycle pipeline domain API. */\nexport interface LifecycleAPI {\n /** Get lifecycle status for an epic. */\n status(epicId: string): Promise<unknown>;\n /** Start a pipeline stage. */\n startStage(epicId: string, stage: string): Promise<unknown>;\n /** Complete a pipeline stage. */\n completeStage(epicId: string, stage: string, artifacts?: string[]): Promise<unknown>;\n /** Skip a pipeline stage. */\n skipStage(epicId: string, stage: string, reason: string): Promise<unknown>;\n /** Check gate requirements for a stage. */\n checkGate(epicId: string, targetStage: string): Promise<unknown>;\n /** Get lifecycle history for an epic. */\n history(epicId: string): Promise<unknown>;\n /** Reset a pipeline stage. */\n resetStage(epicId: string, stage: string, reason: string): Promise<unknown>;\n /** Pass a gate check. */\n passGate(epicId: string, gateName: string, agent?: string): Promise<unknown>;\n /** Fail a gate check. */\n failGate(epicId: string, gateName: string, reason?: string): Promise<unknown>;\n /** Available pipeline stages. */\n stages: readonly string[];\n}\n\n/** Release management domain API. */\nexport interface ReleaseAPI {\n /** Prepare a release. */\n prepare(params: { version: string; tasks?: string[]; notes?: string }): Promise<unknown>;\n /** Commit a release. */\n commit(params: { version: string }): Promise<unknown>;\n /** Tag a release. */\n tag(params: { version: string }): Promise<unknown>;\n /** Push a release. */\n push(params: { version: string; remote?: string; explicitPush?: boolean }): Promise<unknown>;\n /** Rollback a release. */\n rollback(params: { version: string; reason?: string }): Promise<unknown>;\n /** Calculate new version from bump type. */\n calculateVersion(current: string, bumpType: string): string;\n /** Bump version from config. */\n bumpVersion(): Promise<unknown>;\n}\n\n/** Admin domain API. */\nexport interface AdminAPI {\n /** Export tasks. */\n export(params?: Record<string, unknown>): Promise<unknown>;\n /** Import tasks from file. */\n import(params: Omit<ImportParams, 'cwd'>): Promise<unknown>;\n}\n\n/** Sticky notes domain API. */\nexport interface StickyAPI {\n /** Add a sticky note. */\n add(params: {\n content: string;\n tags?: string[];\n priority?: string;\n color?: string;\n }): Promise<unknown>;\n /** Show a sticky note. */\n show(stickyId: string): Promise<unknown>;\n /** List sticky notes with optional filters. */\n list(params?: {\n status?: string;\n color?: string;\n priority?: string;\n limit?: number;\n }): Promise<unknown>;\n /** Archive a sticky note. */\n archive(stickyId: string): Promise<unknown>;\n /** Purge a sticky note. */\n purge(stickyId: string): Promise<unknown>;\n /** Convert a sticky note to task or memory. */\n convert(params: {\n stickyId: string;\n targetType: 'task' | 'memory' | 'task_note' | 'session_note';\n title?: string;\n memoryType?: string;\n taskId?: string;\n }): Promise<unknown>;\n}\n\n/** Cross-project Nexus domain API. */\nexport interface NexusAPI {\n /** Initialize nexus for the current project. */\n init(): Promise<unknown>;\n /** Register a project in the nexus. */\n register(params: { path: string; name?: string; permissions?: string }): Promise<unknown>;\n /** Unregister a project from the nexus. */\n unregister(params: { name: string }): Promise<unknown>;\n /** List registered projects. */\n list(): Promise<unknown>;\n /** Show details of a registered project. */\n show(params: { name: string }): Promise<unknown>;\n /** Sync a project or all projects. */\n sync(params?: { name?: string }): Promise<unknown>;\n /** Discover related content across projects. */\n discover(params: { query: string; method?: string; limit?: number }): Promise<unknown>;\n /** Search across registered projects. */\n search(params: { pattern: string; project?: string; limit?: number }): Promise<unknown>;\n /** Set permission level for a project. */\n setPermission(params: { name: string; level: 'read' | 'write' | 'execute' }): Promise<unknown>;\n /** Get sharing status. */\n sharingStatus(): Promise<unknown>;\n /** Route a Conduit directive message to the correct project (ORCH-PLAN B.2). */\n route(message: ConduitMessage): Promise<unknown>;\n /** Get aggregated task status across all registered projects (ORCH-PLAN B.3). */\n workspaceStatus(): Promise<unknown>;\n /** Get all agents registered across all projects (ORCH-PLAN B.4). */\n workspaceAgents(): Promise<unknown>;\n}\n\n/** Task reconciliation / sync domain API. */\nexport interface SyncAPI {\n /** Reconcile external tasks with CLEO as SSoT. */\n reconcile(params: {\n externalTasks: ExternalTask[];\n providerId: string;\n dryRun?: boolean;\n conflictPolicy?: ReconcileOptions['conflictPolicy'];\n defaultPhase?: string;\n defaultLabels?: string[];\n }): Promise<ReconcileResult>;\n /** Get all external task links for a provider. */\n getLinks(providerId: string): Promise<ExternalTaskLink[]>;\n /** Get all external task links for a CLEO task. */\n getTaskLinks(taskId: string): Promise<ExternalTaskLink[]>;\n /** Remove all external task links for a provider. */\n removeProviderLinks(providerId: string): Promise<number>;\n}\n\n/** Agent registry domain API. */\nexport interface AgentsAPI {\n /** Register a new agent instance. */\n register(options: RegisterAgentOptions): Promise<AgentInstanceRow>;\n /** Deregister an agent instance. */\n deregister(agentId: string): Promise<AgentInstanceRow | null>;\n /** Get health status for a specific agent. */\n health(agentId: string): Promise<AgentHealthStatus | null>;\n /** Detect agents that have crashed (missed heartbeats). */\n detectCrashed(thresholdMs?: number): Promise<AgentInstanceRow[]>;\n /** Record a heartbeat for an agent. */\n recordHeartbeat(agentId: string): Promise<unknown>;\n /** Get capacity info for an agent. */\n capacity(agentId: string): Promise<AgentCapacity | null>;\n /** Check if system is overloaded (available capacity below threshold). */\n isOverloaded(threshold?: number): Promise<boolean>;\n /** List all agent instances with optional filters. */\n list(params?: { status?: string; agentType?: string }): Promise<AgentInstanceRow[]>;\n}\n\n/** Intelligence / impact analysis domain API. */\nexport interface IntelligenceAPI {\n /** Predict impact of a change description on related tasks. */\n predictImpact(change: string): Promise<ImpactReport>;\n /** Calculate blast radius for a task change. */\n blastRadius(taskId: string): Promise<BlastRadius>;\n}\n\n/** Options for initializing the Cleo facade. */\nexport interface CleoInitOptions {\n /** Custom data accessor (store backend). */\n store?: DataAccessor;\n /** Enable CAAMP injection. */\n caamp?: boolean;\n}\n", "/**\n * LAFS (LLM-Agent-First Schema) unified envelope types.\n *\n * Defines canonical LAFS types inline (contracts has ZERO external dependencies).\n * In the main CLEO codebase these are re-exported from @cleocode/lafs;\n * here they are defined as plain interfaces for maximum portability.\n *\n * @epic T4654\n * @task T4655\n */\n\n// ---------------------------------------------------------------------------\n// Canonical LAFS types (inlined from @cleocode/lafs)\n// ---------------------------------------------------------------------------\n\n/** LAFS error category. */\nexport type LAFSErrorCategory =\n | 'validation'\n | 'not_found'\n | 'conflict'\n | 'authorization'\n | 'internal'\n | 'rate_limit'\n | 'timeout'\n | 'dependency';\n\n/** LAFS error object. */\nexport interface LAFSError {\n /** Stable error code (numeric HTTP status or string identifier). */\n code: number | string;\n /** High-level error classification category. */\n category: LAFSErrorCategory;\n /** Human-readable error description. */\n message: string;\n /**\n * Suggested fix or recovery action for the caller.\n *\n * @defaultValue undefined\n */\n fix?: string;\n /**\n * Arbitrary key-value pairs with additional error context.\n *\n * @defaultValue undefined\n */\n details?: Record<string, unknown>;\n}\n\n/** LAFS warning. */\nexport interface Warning {\n /** Machine-readable warning code. */\n code: string;\n /** Human-readable warning description. */\n message: string;\n}\n\n/** LAFS transport metadata. */\nexport type LAFSTransport = 'cli' | 'http' | 'sdk';\n\n/** MVI (Minimal Viable Information) level. */\nexport type MVILevel = 'minimal' | 'standard' | 'full';\n\n/** LAFS page \u2014 no pagination. */\nexport interface LAFSPageNone {\n /** Discriminant indicating no pagination is applied. */\n strategy: 'none';\n}\n\n/** LAFS page \u2014 offset-based pagination. */\nexport interface LAFSPageOffset {\n /** Discriminant identifying offset-based pagination. */\n strategy: 'offset';\n /** Zero-based index of the first item in this page. */\n offset: number;\n /** Maximum number of items per page. */\n limit: number;\n /** Total number of items across all pages. */\n total: number;\n /** Whether additional pages exist beyond the current one. */\n hasMore: boolean;\n}\n\n/** LAFS page union. */\nexport type LAFSPage = LAFSPageNone | LAFSPageOffset;\n\n/** LAFS metadata block. */\nexport interface LAFSMeta {\n /** Transport protocol used for this envelope. */\n transport: LAFSTransport;\n /** Minimum Viable Information level controlling verbosity. */\n mvi: MVILevel;\n /**\n * Pagination metadata when the result is a paginated collection.\n *\n * @defaultValue undefined\n */\n page?: LAFSPage;\n /**\n * Non-fatal warnings to surface to the consuming agent.\n *\n * @defaultValue undefined\n */\n warnings?: Warning[];\n /**\n * Operation duration in milliseconds.\n *\n * @defaultValue undefined\n */\n durationMs?: number;\n}\n\n/** LAFS envelope (canonical protocol type). */\nexport interface LAFSEnvelope<T = unknown> {\n /** Whether the operation completed successfully. */\n success: boolean;\n /**\n * Operation result payload on success.\n *\n * @defaultValue undefined\n */\n data?: T;\n /**\n * Structured error payload on failure.\n *\n * @defaultValue undefined\n */\n error?: LAFSError;\n /**\n * Protocol and transport metadata.\n *\n * @defaultValue undefined\n */\n _meta?: LAFSMeta;\n}\n\n/** Flag input for conformance checks. */\nexport interface FlagInput {\n /** Name of the flag being checked. */\n flag: string;\n /** Value of the flag to validate. */\n value: unknown;\n}\n\n/** Conformance report. */\nexport interface ConformanceReport {\n /** Whether all conformance checks passed. */\n valid: boolean;\n /** List of conformance violation descriptions. */\n violations: string[];\n /** List of non-fatal warning descriptions. */\n warnings: string[];\n}\n\n// ---------------------------------------------------------------------------\n// CLEO-specific error detail (backward compatible)\n// ---------------------------------------------------------------------------\n\n/** Actionable alternative the caller can try. */\nexport interface LafsAlternative {\n /** Description of the alternative action. */\n action: string;\n /** CLI command the caller can run instead. */\n command: string;\n}\n\n/** LAFS error detail shared between CLI and gateway. */\nexport interface LafsErrorDetail {\n /** Stable error code (numeric HTTP status or string identifier). */\n code: number | string;\n /**\n * Optional human-readable error name (e.g. `\"NOT_FOUND\"`).\n *\n * @defaultValue undefined\n */\n name?: string;\n /** Human-readable error description. */\n message: string;\n /**\n * Suggested fix or recovery action for the caller.\n *\n * @defaultValue undefined\n */\n fix?: string;\n /**\n * Alternative commands the caller can try.\n *\n * @defaultValue undefined\n */\n alternatives?: LafsAlternative[];\n /**\n * Arbitrary key-value pairs with additional error context.\n *\n * @defaultValue undefined\n */\n details?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// CLI envelope (base) - backward compatible\n// ---------------------------------------------------------------------------\n\n/** LAFS success envelope (CLI). */\nexport interface LafsSuccess<T = unknown> {\n /** Discriminant: always `true` for success envelopes. */\n success: true;\n /** Operation result payload. */\n data: T;\n /**\n * Optional human-readable summary of the operation outcome.\n *\n * @defaultValue undefined\n */\n message?: string;\n /**\n * When `true`, the operation was a no-op (data is unchanged).\n *\n * @defaultValue undefined\n */\n noChange?: boolean;\n}\n\n/** LAFS error envelope (CLI). */\nexport interface LafsError {\n /** Discriminant: always `false` for error envelopes. */\n success: false;\n /** Structured error detail with code, message, and fix guidance. */\n error: LafsErrorDetail;\n}\n\n/** CLI envelope union type. */\nexport type LafsEnvelope<T = unknown> = LafsSuccess<T> | LafsError;\n\n// ---------------------------------------------------------------------------\n// Gateway envelope extension (extends LAFSMeta)\n// ---------------------------------------------------------------------------\n\n/**\n * Metadata attached to every gateway response.\n * Extends the canonical LAFSMeta with CLEO gateway-specific fields.\n *\n * @task T4655\n */\nexport interface GatewayMeta extends LAFSMeta {\n /** Gateway identifier that processed this request. */\n gateway: string;\n /** CLEO domain that handled the operation (e.g. `\"tasks\"`, `\"session\"`). */\n domain: string;\n /** Operation duration in milliseconds. */\n duration_ms: number;\n}\n\n/** Gateway success envelope (extends CLI base with _meta). */\nexport interface GatewaySuccess<T = unknown> extends LafsSuccess<T> {\n /** Gateway-specific metadata including domain and timing. */\n _meta: GatewayMeta;\n}\n\n/** Gateway error envelope (extends CLI base with _meta). */\nexport interface GatewayError extends LafsError {\n /** Gateway-specific metadata including domain and timing. */\n _meta: GatewayMeta;\n}\n\n/** Gateway envelope union type. */\nexport type GatewayEnvelope<T = unknown> = GatewaySuccess<T> | GatewayError;\n\n// ---------------------------------------------------------------------------\n// Unified envelope (covers both CLI and Gateway)\n// ---------------------------------------------------------------------------\n\n/**\n * Unified CLEO response envelope.\n *\n * Every CLEO response (CLI or Gateway) is a CleoResponse. Gateway responses\n * include the _meta field; CLI responses do not.\n */\nexport type CleoResponse<T = unknown> = LafsEnvelope<T> | GatewayEnvelope<T>;\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\n/**\n * Type guard for success responses.\n *\n * @typeParam T - The data payload type of the envelope.\n * @param envelope - The envelope to check.\n * @returns `true` if the envelope represents a successful operation.\n *\n * @remarks\n * Narrows a {@link LafsEnvelope} to {@link LafsSuccess} so that `envelope.data`\n * is accessible without additional type assertions.\n *\n * @example\n * ```ts\n * const result: LafsEnvelope<Task[]> = await fetchTasks();\n * if (isLafsSuccess(result)) {\n * console.log(result.data); // Task[]\n * }\n * ```\n */\nexport function isLafsSuccess<T>(envelope: LafsEnvelope<T>): envelope is LafsSuccess<T> {\n return envelope.success === true;\n}\n\n/**\n * Type guard for error responses.\n *\n * @typeParam T - The data payload type of the envelope.\n * @param envelope - The envelope to check.\n * @returns `true` if the envelope represents a failed operation.\n *\n * @remarks\n * Narrows a {@link LafsEnvelope} to {@link LafsError} so that `envelope.error`\n * is accessible without additional type assertions.\n *\n * @example\n * ```ts\n * const result: LafsEnvelope<Task[]> = await fetchTasks();\n * if (isLafsError(result)) {\n * console.error(result.error.message);\n * }\n * ```\n */\nexport function isLafsError<T>(envelope: LafsEnvelope<T>): envelope is LafsError {\n return envelope.success === false;\n}\n\n/**\n * Type guard for gateway responses (has _meta).\n *\n * @typeParam T - The data payload type of the envelope.\n * @param envelope - The response to check.\n * @returns `true` if the response includes gateway metadata.\n *\n * @remarks\n * Distinguishes gateway responses from plain CLI responses by checking for the\n * presence of the `_meta` field, which carries gateway-specific routing and timing data.\n *\n * @example\n * ```ts\n * const response: CleoResponse<Task> = await handleRequest();\n * if (isGatewayEnvelope(response)) {\n * console.log(response._meta.gateway);\n * }\n * ```\n */\nexport function isGatewayEnvelope<T>(envelope: CleoResponse<T>): envelope is GatewayEnvelope<T> {\n return '_meta' in envelope && envelope._meta !== undefined;\n}\n", "/**\n * Issues Domain Operations (4 operations)\n *\n * Query operations: 1 (diagnostics)\n * Mutate operations: 3 (add.bug, add.feature, add.help)\n *\n * @task T4494\n */\n\n/**\n * Common issue types\n */\nexport type IssueSeverity = 'low' | 'medium' | 'high' | 'critical';\nexport type IssueArea = 'cli' | 'dispatch' | 'docs' | 'tests' | 'other';\nexport type IssueType = 'bug' | 'feature' | 'help';\n\nexport interface Diagnostics {\n cleoVersion: string;\n bashVersion: string;\n jqVersion: string;\n os: string;\n shell: string;\n cleoHome: string;\n ghVersion: string;\n installLocation: string;\n}\n\n/**\n * Query Operations\n */\n\n// issues.diagnostics\nexport type IssuesDiagnosticsParams = Record<string, never>;\nexport interface IssuesDiagnosticsResult {\n diagnostics: Diagnostics;\n}\n\n/**\n * Mutate Operations\n */\n\n// issues.add.bug (alias: create.bug)\nexport interface IssuesCreateBugParams {\n title: string;\n body: string;\n severity?: IssueSeverity;\n area?: IssueArea;\n dryRun?: boolean;\n}\nexport interface IssuesCreateBugResult {\n type: 'bug';\n url: string;\n number: number;\n title: string;\n labels: string[];\n}\n\n// issues.add.feature (alias: create.feature)\nexport interface IssuesCreateFeatureParams {\n title: string;\n body: string;\n area?: IssueArea;\n dryRun?: boolean;\n}\nexport interface IssuesCreateFeatureResult {\n type: 'feature';\n url: string;\n number: number;\n title: string;\n labels: string[];\n}\n\n// issues.add.help (alias: create.help)\nexport interface IssuesCreateHelpParams {\n title: string;\n body: string;\n area?: IssueArea;\n dryRun?: boolean;\n}\nexport interface IssuesCreateHelpResult {\n type: 'help';\n url: string;\n number: number;\n title: string;\n labels: string[];\n}\n", "/**\n * Lifecycle Domain Operations (10 operations)\n *\n * Query operations: 5\n * Mutate operations: 5\n */\n\nimport type { StageStatus } from '../status-registry.js';\n\nexport type { StageStatus };\n\n/**\n * Common lifecycle types\n */\nexport type LifecycleStage =\n | 'research'\n | 'consensus'\n | 'architecture_decision'\n | 'specification'\n | 'decomposition'\n | 'implementation'\n | 'validation'\n | 'testing'\n | 'release';\n\nexport type GateStatus = 'passed' | 'failed' | 'blocked' | null;\n\nexport interface StageRecord {\n stage: LifecycleStage;\n status: StageStatus;\n started?: string;\n completed?: string;\n agent?: string;\n notes?: string;\n}\n\nexport interface Gate {\n name: string;\n stage: LifecycleStage;\n status: GateStatus;\n agent?: string;\n timestamp?: string;\n reason?: string;\n}\n\n/**\n * Query Operations\n */\n\n// lifecycle.check\nexport interface LifecycleCheckParams {\n taskId: string;\n targetStage: LifecycleStage;\n}\nexport interface LifecycleCheckResult {\n taskId: string;\n targetStage: LifecycleStage;\n canProceed: boolean;\n missingPrerequisites: LifecycleStage[];\n gateStatus: 'passed' | 'failed' | 'pending';\n}\n\n// lifecycle.status\nexport interface LifecycleStatusParams {\n taskId?: string;\n epicId?: string;\n}\nexport interface LifecycleStatusResult {\n id: string;\n currentStage: LifecycleStage;\n stages: StageRecord[];\n completedStages: LifecycleStage[];\n pendingStages: LifecycleStage[];\n}\n\n// lifecycle.history\nexport interface LifecycleHistoryParams {\n taskId: string;\n}\nexport interface LifecycleHistoryEntry {\n stage: LifecycleStage;\n from: StageStatus;\n to: StageStatus;\n timestamp: string;\n agent?: string;\n notes?: string;\n}\nexport type LifecycleHistoryResult = LifecycleHistoryEntry[];\n\n// lifecycle.gates\nexport interface LifecycleGatesParams {\n taskId: string;\n}\nexport type LifecycleGatesResult = Gate[];\n\n// lifecycle.prerequisites\nexport interface LifecyclePrerequisitesParams {\n targetStage: LifecycleStage;\n}\nexport interface LifecyclePrerequisitesResult {\n targetStage: LifecycleStage;\n prerequisites: LifecycleStage[];\n optional: LifecycleStage[];\n}\n\n/**\n * Mutate Operations\n */\n\n// lifecycle.progress\nexport interface LifecycleProgressParams {\n taskId: string;\n stage: LifecycleStage;\n status: StageStatus;\n notes?: string;\n}\nexport interface LifecycleProgressResult {\n taskId: string;\n stage: LifecycleStage;\n status: StageStatus;\n timestamp: string;\n}\n\n// lifecycle.skip\nexport interface LifecycleSkipParams {\n taskId: string;\n stage: LifecycleStage;\n reason: string;\n}\nexport interface LifecycleSkipResult {\n taskId: string;\n stage: LifecycleStage;\n skipped: string;\n reason: string;\n}\n\n// lifecycle.reset\nexport interface LifecycleResetParams {\n taskId: string;\n stage: LifecycleStage;\n reason: string;\n}\nexport interface LifecycleResetResult {\n taskId: string;\n stage: LifecycleStage;\n reset: string;\n reason: string;\n warning: string;\n}\n\n// lifecycle.gate.pass\nexport interface LifecycleGatePassParams {\n taskId: string;\n gateName: string;\n agent: string;\n notes?: string;\n}\nexport interface LifecycleGatePassResult {\n taskId: string;\n gateName: string;\n status: 'passed';\n timestamp: string;\n}\n\n// lifecycle.gate.fail\nexport interface LifecycleGateFailParams {\n taskId: string;\n gateName: string;\n reason: string;\n}\nexport interface LifecycleGateFailResult {\n taskId: string;\n gateName: string;\n status: 'failed';\n reason: string;\n timestamp: string;\n}\n", "/**\n * Orchestrate Domain Operations (13 operations)\n *\n * Query operations: 7\n * Mutate operations: 6\n */\n\n/**\n * Common orchestration types\n */\nexport interface Wave {\n wave: number;\n taskIds: string[];\n canRunParallel: boolean;\n dependencies: string[];\n}\n\nexport interface SkillDefinition {\n name: string;\n description: string;\n tags: string[];\n model?: string;\n protocols: string[];\n}\n\n/**\n * Query Operations\n */\n\n// orchestrate.status\nexport interface OrchestrateStatusParams {\n epicId: string;\n}\nexport interface OrchestrateStatusResult {\n epicId: string;\n totalTasks: number;\n completedTasks: number;\n pendingTasks: number;\n blockedTasks: number;\n currentWave: number;\n totalWaves: number;\n parallelCapacity: number;\n}\n\n// orchestrate.next\nexport interface OrchestrateNextParams {\n epicId: string;\n}\nexport interface OrchestrateNextResult {\n taskId: string;\n title: string;\n recommendedSkill: string;\n reasoning: string;\n}\n\n// orchestrate.ready\nexport interface OrchestrateReadyParams {\n epicId: string;\n}\nexport interface OrchestrateReadyResult {\n wave: number;\n taskIds: string[];\n parallelSafe: boolean;\n}\n\n// orchestrate.analyze\nexport interface OrchestrateAnalyzeParams {\n epicId: string;\n}\nexport interface OrchestrateAnalyzeResult {\n waves: Wave[];\n criticalPath: string[];\n estimatedParallelism: number;\n bottlenecks: string[];\n}\n\n// orchestrate.context\nexport interface OrchestrateContextParams {\n tokens?: number;\n}\nexport interface OrchestrateContextResult {\n currentTokens: number;\n maxTokens: number;\n percentUsed: number;\n level: 'safe' | 'medium' | 'high' | 'critical';\n recommendation: string;\n}\n\n// orchestrate.waves\nexport interface OrchestrateWavesParams {\n epicId: string;\n}\nexport type OrchestrateWavesResult = Wave[];\n\n// orchestrate.skill.list\nexport interface OrchestrateSkillListParams {\n filter?: string;\n}\nexport type OrchestrateSkillListResult = SkillDefinition[];\n\n// orchestrate.bootstrap\nexport interface OrchestrateBootstrapParams {\n speed?: 'fast' | 'full' | 'complete';\n}\nexport interface BrainState {\n session?: { id: string; name: string; status: string; startedAt: string };\n currentTask?: { id: string; title: string; status: string };\n nextSuggestion?: { id: string; title: string; score: number };\n recentDecisions?: Array<{ id: string; decision: string; timestamp: string }>;\n blockers?: Array<{ taskId: string; title: string; blockedBy: string[] }>;\n progress?: { total: number; done: number; active: number; blocked: number; pending: number };\n contextDrift?: { score: number; factors: string[] };\n _meta: { speed: 'fast' | 'full' | 'complete'; generatedAt: string; version: string };\n}\n\n/**\n * Mutate Operations\n */\n\n// orchestrate.startup\nexport interface OrchestrateStartupParams {\n epicId: string;\n}\nexport interface OrchestrateStartupResult {\n epicId: string;\n status: OrchestrateStatusResult;\n analysis: OrchestrateAnalyzeResult;\n firstTask: OrchestrateNextResult;\n}\n\n// orchestrate.spawn\nexport interface OrchestrateSpawnParams {\n taskId: string;\n skill?: string;\n model?: string;\n}\nexport interface OrchestrateSpawnResult {\n taskId: string;\n skill: string;\n model: string;\n prompt: string;\n metadata: {\n tokensUsed: number;\n protocolsInjected: string[];\n dependencies: string[];\n };\n}\n\n// orchestrate.handoff\nexport interface OrchestrateHandoffParams {\n taskId: string;\n protocolType: string;\n note?: string;\n nextAction?: string;\n variant?: string;\n tier?: 0 | 1 | 2;\n idempotencyKey?: string;\n}\nexport interface OrchestrateHandoffResult {\n taskId: string;\n predecessorSessionId: string;\n endedSessionId: string;\n protocolType: string;\n}\n\n// orchestrate.validate\nexport interface OrchestrateValidateParams {\n taskId: string;\n}\nexport interface OrchestrateValidateResult {\n taskId: string;\n ready: boolean;\n blockers: string[];\n lifecycleGate: 'passed' | 'failed' | 'pending';\n recommendations: string[];\n}\n\n// orchestrate.parallel.start\nexport interface OrchestrateParallelStartParams {\n epicId: string;\n wave: number;\n}\nexport interface OrchestrateParallelStartResult {\n wave: number;\n taskIds: string[];\n started: string;\n}\n\n// orchestrate.parallel.end\nexport interface OrchestrateParallelEndParams {\n epicId: string;\n wave: number;\n}\nexport interface OrchestrateParallelEndResult {\n wave: number;\n completed: number;\n failed: number;\n duration: string;\n}\n", "/**\n * Release Domain Operations (7 operations)\n *\n * All mutate operations\n */\n\n/**\n * Common release types\n */\nexport type ReleaseType = 'major' | 'minor' | 'patch';\n\nexport interface ReleaseGate {\n name: string;\n description: string;\n passed: boolean;\n reason?: string;\n}\n\nexport interface ChangelogSection {\n type: 'feat' | 'fix' | 'docs' | 'test' | 'refactor' | 'chore';\n entries: Array<{\n taskId: string;\n message: string;\n }>;\n}\n\n/**\n * Mutate Operations\n */\n\n// release.prepare\nexport interface ReleasePrepareParams {\n version: string;\n type: ReleaseType;\n}\nexport interface ReleasePrepareResult {\n version: string;\n type: ReleaseType;\n currentVersion: string;\n files: string[];\n ready: boolean;\n warnings: string[];\n}\n\n// release.changelog\nexport interface ReleaseChangelogParams {\n version: string;\n sections?: Array<'feat' | 'fix' | 'docs' | 'test' | 'refactor' | 'chore'>;\n}\nexport interface ReleaseChangelogResult {\n version: string;\n content: string;\n sections: ChangelogSection[];\n commitCount: number;\n}\n\n// release.commit\nexport interface ReleaseCommitParams {\n version: string;\n files?: string[];\n}\nexport interface ReleaseCommitResult {\n version: string;\n commitHash: string;\n message: string;\n filesCommitted: string[];\n}\n\n// release.tag\nexport interface ReleaseTagParams {\n version: string;\n message?: string;\n}\nexport interface ReleaseTagResult {\n version: string;\n tagName: string;\n created: string;\n}\n\n// release.push\nexport interface ReleasePushParams {\n version: string;\n remote?: string;\n}\nexport interface ReleasePushResult {\n version: string;\n remote: string;\n pushed: string;\n tagsPushed: string[];\n}\n\n// release.gates.run\nexport interface ReleaseGatesRunParams {\n gates?: string[];\n}\nexport interface ReleaseGatesRunResult {\n total: number;\n passed: number;\n failed: number;\n gates: ReleaseGate[];\n canRelease: boolean;\n}\n\n// release.rollback\nexport interface ReleaseRollbackParams {\n version: string;\n reason: string;\n}\nexport interface ReleaseRollbackResult {\n version: string;\n rolledBack: string;\n restoredVersion: string;\n reason: string;\n}\n", "/**\n * Research Domain Operations (legacy alias for memory domain)\n *\n * Query operations: 12 (derived from memory domain)\n * Mutate operations: 5 (derived from memory domain)\n *\n * Note: manifest.* operations moved to pipeline domain (T5241).\n * inject operation moved to session.context.inject (T5241).\n */\n\n/**\n * Common research types\n */\nexport interface ResearchEntry {\n id: string;\n taskId: string;\n title: string;\n file: string;\n date: string;\n status: 'completed' | 'partial' | 'blocked';\n agentType: string;\n topics: string[];\n keyFindings: string[];\n actionable: boolean;\n needsFollowup: string[];\n linkedTasks: string[];\n confidence?: number;\n}\n\nexport interface ManifestEntry {\n id: string;\n file: string;\n title: string;\n date: string;\n status: 'completed' | 'partial' | 'blocked';\n agent_type: string;\n topics: string[];\n key_findings: string[];\n actionable: boolean;\n needs_followup: string[];\n linked_tasks: string[];\n}\n\n/**\n * Query Operations\n */\n\n// research.show\nexport interface ResearchShowParams {\n researchId: string;\n}\nexport type ResearchShowResult = ResearchEntry;\n\n// research.list\nexport interface ResearchListParams {\n epicId?: string;\n status?: 'completed' | 'partial' | 'blocked';\n}\nexport type ResearchListResult = ResearchEntry[];\n\n// research.query\nexport interface ResearchQueryParams {\n query: string;\n confidence?: number;\n}\nexport interface ResearchQueryResult {\n entries: ResearchEntry[];\n matchCount: number;\n avgConfidence: number;\n}\n\n// research.pending\nexport interface ResearchPendingParams {\n epicId?: string;\n}\nexport type ResearchPendingResult = ResearchEntry[];\n\n// research.stats\nexport interface ResearchStatsParams {\n epicId?: string;\n}\nexport interface ResearchStatsResult {\n total: number;\n complete: number;\n partial: number;\n blocked: number;\n byAgentType: Record<string, number>;\n byTopic: Record<string, number>;\n avgConfidence: number;\n}\n\n// pipeline.manifest.list (was research.manifest.read, moved to pipeline T5241)\nexport interface ResearchManifestReadParams {\n filter?: string;\n limit?: number;\n offset?: number;\n}\nexport type ResearchManifestReadResult = ManifestEntry[];\n\n/**\n * Mutate Operations\n */\n\n// session.context.inject (was research.inject, moved to session domain T5241)\nexport interface ResearchInjectParams {\n protocolType:\n | 'research'\n | 'consensus'\n | 'specification'\n | 'decomposition'\n | 'implementation'\n | 'contribution'\n | 'release';\n taskId?: string;\n variant?: string;\n}\nexport interface ResearchInjectResult {\n protocol: string;\n content: string;\n tokensUsed: number;\n}\n\n// research.link\nexport interface ResearchLinkParams {\n researchId: string;\n taskId: string;\n relationship?: 'supports' | 'blocks' | 'references' | 'supersedes';\n}\nexport interface ResearchLinkResult {\n researchId: string;\n taskId: string;\n relationship: string;\n linked: string;\n}\n\n// pipeline.manifest.append (was research.manifest.append, moved to pipeline T5241)\nexport interface ResearchManifestAppendParams {\n entry: ManifestEntry;\n validateFile?: boolean;\n}\nexport interface ResearchManifestAppendResult {\n id: string;\n appended: string;\n validated: boolean;\n}\n\n// pipeline.manifest.archive (was research.manifest.archive, moved to pipeline T5241)\nexport interface ResearchManifestArchiveParams {\n beforeDate?: string;\n moveFiles?: boolean;\n}\nexport interface ResearchManifestArchiveResult {\n archived: number;\n entryIds: string[];\n filesMovedCount?: number;\n}\n", "/**\n * Session Domain Operations (9 operations)\n *\n * Query operations: 4\n * Mutate operations: 5\n *\n * SYNC: Canonical type definitions live in the CLI package at:\n * src/types/session.ts (Session, SessionScope, etc.)\n * These operation types are the API contract (wire format).\n */\n\n/**\n * Common session types\n */\nexport interface SessionOp {\n id: string;\n name: string;\n scope: string;\n started: string;\n ended?: string;\n startedTask?: string;\n status: 'active' | 'suspended' | 'ended';\n notes?: string[];\n}\n\n/**\n * Query Operations\n */\n\n// session.status\nexport type SessionStatusParams = Record<string, never>;\nexport interface SessionStatusResult {\n current: SessionOp | null;\n hasStartedTask: boolean;\n startedTask?: string;\n}\n\n// session.list\nexport interface SessionListParams {\n active?: boolean;\n status?: string;\n limit?: number;\n offset?: number;\n}\nexport interface SessionListResult {\n sessions: SessionOp[];\n total: number;\n filtered: number;\n}\n\n// session.show\nexport interface SessionShowParams {\n sessionId: string;\n}\nexport type SessionShowResult = SessionOp;\n\n// session.history\nexport interface SessionHistoryParams {\n limit?: number;\n}\nexport interface SessionHistoryEntry {\n sessionId: string;\n name: string;\n started: string;\n ended: string;\n tasksCompleted: number;\n duration: string;\n}\nexport type SessionHistoryResult = SessionHistoryEntry[];\n\n/**\n * Mutate Operations\n */\n\n// session.start\nexport interface SessionStartParams {\n scope: string;\n name?: string;\n autoStart?: boolean;\n startTask?: string;\n}\nexport type SessionStartResult = SessionOp;\n\n// session.end\nexport interface SessionEndParams {\n notes?: string;\n /**\n * Structured session summary for direct ingestion into brain.db.\n * When provided, CLEO persists key learnings, decisions, patterns, and next actions.\n * @task T140 @epic T134\n */\n sessionSummary?: import('../config.js').SessionSummaryInput;\n}\nexport interface SessionEndResult {\n session: SessionOp;\n summary: {\n duration: string;\n tasksCompleted: number;\n tasksCreated: number;\n };\n /**\n * A summarization prompt built from this session's debrief data.\n * Populated when `brain.summarization.enabled` is true.\n * @task T140 @epic T134\n */\n memoryPrompt?: string;\n}\n\n// session.resume\nexport interface SessionResumeParams {\n sessionId: string;\n}\nexport type SessionResumeResult = SessionOp;\n\n// session.suspend\nexport interface SessionSuspendParams {\n notes?: string;\n}\nexport interface SessionSuspendResult {\n sessionId: string;\n suspended: string;\n}\n\n// session.gc\nexport interface SessionGcParams {\n olderThan?: string;\n}\nexport interface SessionGcResult {\n cleaned: number;\n sessionIds: string[];\n}\n", "/**\n * Skills Domain Operations (12 operations)\n *\n * Query operations: 6 (list, show, find, dispatch, verify, dependencies)\n * Mutate operations: 6 (install, uninstall, enable, disable, configure, refresh)\n *\n * @task T4387\n */\n\n/**\n * Common skill types\n */\nexport type SkillCategory = 'core' | 'recommended' | 'specialist' | 'composition' | 'meta';\nexport type SkillStatus = 'active' | 'disabled' | 'deprecated' | 'missing';\nexport type DispatchStrategy = 'label' | 'type' | 'keyword' | 'fallback';\n\nexport interface SkillSummary {\n name: string;\n version: string;\n description: string;\n category: SkillCategory;\n core: boolean;\n tier: number;\n status: SkillStatus;\n protocol: string | null;\n}\n\nexport interface SkillDetail extends SkillSummary {\n path: string;\n references: string[];\n dependencies: string[];\n sharedResources: string[];\n compatibility: string[];\n license: string;\n metadata: Record<string, unknown>;\n capabilities?: {\n inputs: string[];\n outputs: string[];\n dispatch_triggers: string[];\n compatible_subagent_types: string[];\n chains_to: string[];\n dispatch_keywords: {\n primary: string[];\n secondary: string[];\n };\n };\n constraints?: {\n max_context_tokens: number;\n requires_session: boolean;\n requires_epic: boolean;\n };\n}\n\nexport interface DispatchCandidate {\n skill: string;\n score: number;\n strategy: DispatchStrategy;\n reason: string;\n}\n\nexport interface DependencyNode {\n name: string;\n version: string;\n direct: boolean;\n depth: number;\n}\n\nexport interface ValidationIssue {\n level: 'error' | 'warn';\n field: string;\n message: string;\n}\n\n/**\n * Query Operations\n */\n\n// skills.list\nexport interface SkillsListParams {\n category?: SkillCategory;\n core?: boolean;\n filter?: string;\n}\nexport type SkillsListResult = SkillSummary[];\n\n// skills.show\nexport interface SkillsShowParams {\n name: string;\n}\nexport type SkillsShowResult = SkillDetail;\n\n// skills.find\nexport interface SkillsFindParams {\n query: string;\n limit?: number;\n}\nexport interface SkillsFindResult {\n query: string;\n results: Array<SkillSummary & { score: number; matchReason: string }>;\n}\n\n// skills.dispatch\nexport interface SkillsDispatchParams {\n taskId?: string;\n taskType?: string;\n labels?: string[];\n title?: string;\n description?: string;\n}\nexport interface SkillsDispatchResult {\n selectedSkill: string;\n reason: string;\n strategy: DispatchStrategy;\n candidates: DispatchCandidate[];\n}\n\n// skills.verify\nexport interface SkillsVerifyParams {\n name?: string;\n}\nexport interface SkillsVerifyResult {\n valid: boolean;\n total: number;\n passed: number;\n failed: number;\n results: Array<{\n name: string;\n valid: boolean;\n issues: ValidationIssue[];\n }>;\n}\n\n// skills.dependencies\nexport interface SkillsDependenciesParams {\n name: string;\n transitive?: boolean;\n}\nexport interface SkillsDependenciesResult {\n name: string;\n dependencies: DependencyNode[];\n resolved: string[];\n}\n\n/**\n * Mutate Operations\n */\n\n// skills.install\nexport interface SkillsInstallParams {\n name: string;\n source?: string;\n}\nexport interface SkillsInstallResult {\n name: string;\n installed: boolean;\n version: string;\n path: string;\n}\n\n// skills.uninstall\nexport interface SkillsUninstallParams {\n name: string;\n force?: boolean;\n}\nexport interface SkillsUninstallResult {\n name: string;\n uninstalled: boolean;\n}\n\n// skills.enable\nexport interface SkillsEnableParams {\n name: string;\n}\nexport interface SkillsEnableResult {\n name: string;\n enabled: boolean;\n status: SkillStatus;\n}\n\n// skills.disable\nexport interface SkillsDisableParams {\n name: string;\n reason?: string;\n}\nexport interface SkillsDisableResult {\n name: string;\n disabled: boolean;\n status: SkillStatus;\n}\n\n// skills.configure\nexport interface SkillsConfigureParams {\n name: string;\n config: Record<string, unknown>;\n}\nexport interface SkillsConfigureResult {\n name: string;\n configured: boolean;\n config: Record<string, unknown>;\n}\n\n// skills.refresh\nexport interface SkillsRefreshParams {\n force?: boolean;\n}\nexport interface SkillsRefreshResult {\n refreshed: boolean;\n skillCount: number;\n timestamp: string;\n}\n", "/**\n * System Domain Operations (12 operations)\n *\n * Query operations: 5\n * Mutate operations: 7\n */\n\n/**\n * Common system types\n */\nexport interface HealthCheck {\n component: string;\n healthy: boolean;\n message?: string;\n}\n\nexport interface ProjectStats {\n tasks: {\n total: number;\n pending: number;\n active: number;\n blocked: number;\n done: number;\n };\n sessions: {\n total: number;\n active: number;\n };\n research: {\n total: number;\n complete: number;\n };\n}\n\n/**\n * Query Operations\n */\n\n// system.version\nexport type SystemVersionParams = Record<string, never>;\nexport interface SystemVersionResult {\n version: string;\n schemaVersion: string;\n buildDate: string;\n}\n\n// system.doctor\nexport type SystemDoctorParams = Record<string, never>;\nexport interface SystemDoctorResult {\n healthy: boolean;\n checks: HealthCheck[];\n warnings: string[];\n errors: string[];\n}\n\n// system.config.get\nexport interface SystemConfigGetParams {\n key: string;\n}\nexport interface SystemConfigGetResult {\n key: string;\n value: unknown;\n type: string;\n}\n\n// system.stats\nexport type SystemStatsParams = Record<string, never>;\nexport type SystemStatsResult = ProjectStats;\n\n// system.context\nexport type SystemContextParams = Record<string, never>;\nexport interface SystemContextResult {\n currentTokens: number;\n maxTokens: number;\n percentUsed: number;\n level: 'safe' | 'medium' | 'high' | 'critical';\n estimatedFiles: number;\n largestFile: {\n path: string;\n tokens: number;\n };\n}\n\n/**\n * Mutate Operations\n */\n\n// system.init\nexport interface SystemInitParams {\n projectType?: 'nodejs' | 'python' | 'bash' | 'typescript' | 'rust' | 'go';\n detect?: boolean;\n}\nexport interface SystemInitResult {\n initialized: boolean;\n projectType?: string;\n filesCreated: string[];\n detectedFeatures?: Record<string, boolean>;\n}\n\n// system.config.set\nexport interface SystemConfigSetParams {\n key: string;\n value: unknown;\n}\nexport interface SystemConfigSetResult {\n key: string;\n value: unknown;\n previousValue?: unknown;\n}\n\n// system.backup\nexport interface SystemBackupParams {\n type?: 'snapshot' | 'safety' | 'archive' | 'migration';\n note?: string;\n}\nexport interface SystemBackupResult {\n backupId: string;\n type: string;\n timestamp: string;\n files: string[];\n size: number;\n}\n\n// system.restore\nexport interface SystemRestoreParams {\n backupId: string;\n}\nexport interface SystemRestoreResult {\n backupId: string;\n restored: string;\n filesRestored: string[];\n}\n\n// system.migrate\nexport interface SystemMigrateParams {\n version?: string;\n dryRun?: boolean;\n}\nexport interface SystemMigrateResult {\n fromVersion: string;\n toVersion: string;\n migrations: Array<{\n name: string;\n applied: boolean;\n error?: string;\n }>;\n dryRun: boolean;\n}\n\n// system.sync\nexport interface SystemSyncParams {\n direction?: 'push' | 'pull' | 'bidirectional';\n}\nexport interface SystemSyncResult {\n direction: string;\n synced: string;\n tasksSynced: number;\n conflicts: Array<{\n taskId: string;\n resolution: string;\n }>;\n}\n\n// system.cleanup\nexport interface SystemCleanupParams {\n type: 'backups' | 'logs' | 'archive' | 'sessions';\n olderThan?: string;\n}\nexport interface SystemCleanupResult {\n type: string;\n cleaned: number;\n freed: number;\n items: string[];\n}\n", "/**\n * Tasks Domain Operations (22 operations)\n *\n * Query operations: 10\n * Mutate operations: 12\n *\n * SYNC: Canonical type definitions live in the CLI package at:\n * src/types/task.ts (TaskStatus, TaskPriority, Task, etc.)\n * These operation types are the API contract (wire format).\n * Internal domain types must stay aligned with CLI definitions.\n */\n\n/**\n * Common task types (API contract \u2014 matches CLI src/types/task.ts)\n */\nimport type { TaskStatus } from '../status-registry.js';\n\nexport type { TaskStatus };\nexport type TaskPriority = 'low' | 'medium' | 'high' | 'critical';\n\nexport interface TaskOp {\n id: string;\n title: string;\n description: string;\n status: TaskStatus;\n priority?: TaskPriority;\n parent?: string;\n depends?: string[];\n labels?: string[];\n created: string;\n updated: string;\n completed?: string;\n notes?: string[];\n}\n\nexport interface MinimalTask {\n id: string;\n title: string;\n status: TaskStatus;\n parent?: string;\n}\n\n/**\n * Query Operations\n */\n\n// tasks.get\nexport interface TasksGetParams {\n taskId: string;\n}\nexport type TasksGetResult = TaskOp;\n\n// tasks.list\nexport interface TasksListParams {\n parent?: string;\n status?: TaskStatus;\n priority?: TaskPriority;\n type?: string;\n phase?: string;\n label?: string;\n children?: boolean;\n limit?: number;\n offset?: number;\n compact?: boolean;\n}\nexport interface TasksListResult {\n tasks: TaskOp[];\n total: number;\n filtered: number;\n}\n\n// tasks.find\nexport interface TasksFindParams {\n query: string;\n limit?: number;\n}\nexport type TasksFindResult = MinimalTask[];\n\n// tasks.exists\nexport interface TasksExistsParams {\n taskId: string;\n}\nexport interface TasksExistsResult {\n exists: boolean;\n taskId: string;\n}\n\n// tasks.tree\nexport interface TasksTreeParams {\n rootId?: string;\n depth?: number;\n}\nexport interface TaskTreeNode {\n task: TaskOp;\n children: TaskTreeNode[];\n depth: number;\n}\nexport type TasksTreeResult = TaskTreeNode[];\n\n// tasks.blockers\nexport interface TasksBlockersParams {\n taskId: string;\n}\nexport interface Blocker {\n taskId: string;\n title: string;\n status: TaskStatus;\n blockType: 'dependency' | 'parent' | 'gate';\n}\nexport type TasksBlockersResult = Blocker[];\n\n// tasks.deps\nexport interface TasksDepsParams {\n taskId: string;\n direction?: 'upstream' | 'downstream' | 'both';\n}\nexport interface TaskDependencyNode {\n taskId: string;\n title: string;\n status: TaskStatus;\n distance: number;\n}\nexport interface TasksDepsResult {\n taskId: string;\n upstream: TaskDependencyNode[];\n downstream: TaskDependencyNode[];\n}\n\n// tasks.analyze\nexport interface TasksAnalyzeParams {\n epicId?: string;\n}\nexport interface TriageRecommendation {\n taskId: string;\n title: string;\n priority: number;\n reason: string;\n readiness: 'ready' | 'blocked' | 'pending';\n}\nexport type TasksAnalyzeResult = TriageRecommendation[];\n\n// tasks.next\nexport interface TasksNextParams {\n epicId?: string;\n count?: number;\n}\nexport interface SuggestedTask {\n taskId: string;\n title: string;\n score: number;\n rationale: string;\n}\nexport type TasksNextResult = SuggestedTask[];\n\n/**\n * Mutate Operations\n */\n\n// tasks.create\nexport interface TasksCreateParams {\n title: string;\n description: string;\n parent?: string;\n depends?: string[];\n priority?: TaskPriority;\n labels?: string[];\n}\nexport type TasksCreateResult = TaskOp;\n\n// tasks.update\nexport interface TasksUpdateParams {\n taskId: string;\n title?: string;\n description?: string;\n status?: TaskStatus;\n priority?: TaskPriority;\n notes?: string;\n parent?: string | null; // Set parent ID, or null/\"\" to promote to root\n labels?: string[];\n addLabels?: string[];\n removeLabels?: string[];\n depends?: string[];\n addDepends?: string[];\n removeDepends?: string[];\n type?: string;\n size?: string;\n}\nexport type TasksUpdateResult = TaskOp;\n\n// tasks.complete\nexport interface TasksCompleteParams {\n taskId: string;\n notes?: string;\n archive?: boolean;\n}\nexport interface TasksCompleteResult {\n taskId: string;\n completed: string;\n archived: boolean;\n}\n\n// tasks.delete\nexport interface TasksDeleteParams {\n taskId: string;\n force?: boolean;\n}\nexport interface TasksDeleteResult {\n taskId: string;\n deleted: true;\n}\n\n// tasks.archive\nexport interface TasksArchiveParams {\n taskId?: string;\n before?: string;\n}\nexport interface TasksArchiveResult {\n archived: number;\n taskIds: string[];\n}\n\n// tasks.unarchive\nexport interface TasksUnarchiveParams {\n taskId: string;\n}\nexport type TasksUnarchiveResult = TaskOp;\n\n// tasks.reparent\nexport interface TasksReparentParams {\n taskId: string;\n newParent: string;\n}\nexport type TasksReparentResult = TaskOp;\n\n// tasks.promote\nexport interface TasksPromoteParams {\n taskId: string;\n}\nexport type TasksPromoteResult = TaskOp;\n\n// tasks.reorder\nexport interface TasksReorderParams {\n taskId: string;\n position: number;\n}\nexport interface TasksReorderResult {\n taskId: string;\n newPosition: number;\n}\n\n// tasks.restore (completed tasks) \u2014 alias: reopen\nexport interface TasksReopenParams {\n taskId: string;\n}\nexport type TasksReopenResult = TaskOp;\n\n// tasks.start (begin working on a task)\nexport interface TasksStartParams {\n taskId: string;\n}\nexport interface TasksStartResult {\n taskId: string;\n sessionId: string;\n timestamp: string;\n}\n\n// tasks.stop (stop working on current task)\nexport type TasksStopParams = Record<string, never>;\nexport interface TasksStopResult {\n stopped: true;\n previousTask?: string;\n}\n\n// tasks.current (get currently active task)\nexport type TasksCurrentParams = Record<string, never>;\nexport interface TasksCurrentResult {\n taskId: string | null;\n since?: string;\n sessionId?: string;\n}\n", "/**\n * Validate Domain Operations (11 operations)\n *\n * Query operations: 9\n * Mutate operations: 2\n */\n\n/**\n * Common validation types\n */\nexport type ValidationSeverity = 'error' | 'warning' | 'info';\n\nexport interface ValidationViolation {\n rule: string;\n severity: ValidationSeverity;\n message: string;\n field?: string;\n value?: unknown;\n expected?: unknown;\n line?: number;\n}\n\nexport interface ComplianceMetrics {\n total: number;\n passed: number;\n failed: number;\n score: number;\n byProtocol: Record<string, { passed: number; failed: number }>;\n bySeverity: Record<ValidationSeverity, number>;\n}\n\n/**\n * Query Operations\n */\n\n// validate.schema\nexport interface ValidateSchemaParams {\n fileType: 'todo' | 'config' | 'archive' | 'log' | 'manifest';\n filePath?: string;\n}\nexport interface ValidateSchemaResult {\n valid: boolean;\n schemaVersion: string;\n violations: ValidationViolation[];\n}\n\n// validate.protocol\nexport interface ValidateProtocolParams {\n taskId: string;\n protocolType:\n | 'research'\n | 'consensus'\n | 'specification'\n | 'decomposition'\n | 'implementation'\n | 'contribution'\n | 'release';\n}\nexport interface ValidateProtocolResult {\n taskId: string;\n protocol: string;\n passed: boolean;\n score: number;\n violations: ValidationViolation[];\n requirements: {\n total: number;\n met: number;\n failed: number;\n };\n}\n\n// validate.task\nexport interface ValidateTaskParams {\n taskId: string;\n checkMode: 'basic' | 'strict' | 'anti-hallucination';\n}\nexport interface ValidateTaskResult {\n taskId: string;\n valid: boolean;\n violations: ValidationViolation[];\n checks: {\n idUniqueness: boolean;\n titleDescriptionDifferent: boolean;\n validStatus: boolean;\n noFutureTimestamps: boolean;\n noDuplicateDescription: boolean;\n };\n}\n\n// validate.manifest\nexport interface ValidateManifestParams {\n entry?: string;\n taskId?: string;\n}\nexport interface ValidateManifestResult {\n valid: boolean;\n entry: {\n id: string;\n file: string;\n exists: boolean;\n };\n violations: ValidationViolation[];\n}\n\n// validate.output\nexport interface ValidateOutputParams {\n taskId: string;\n filePath: string;\n}\nexport interface ValidateOutputResult {\n taskId: string;\n filePath: string;\n valid: boolean;\n checks: {\n fileExists: boolean;\n hasTaskHeader: boolean;\n hasStatus: boolean;\n hasSummary: boolean;\n linkedToTask: boolean;\n };\n violations: ValidationViolation[];\n}\n\n// validate.compliance.summary\nexport interface ValidateComplianceSummaryParams {\n scope?: string;\n since?: string;\n}\nexport type ValidateComplianceSummaryResult = ComplianceMetrics;\n\n// validate.compliance.violations\nexport interface ValidateComplianceViolationsParams {\n severity?: ValidationSeverity;\n protocol?: string;\n}\nexport interface ValidateComplianceViolationsResult {\n violations: Array<\n ValidationViolation & {\n taskId: string;\n protocol: string;\n timestamp: string;\n }\n >;\n total: number;\n}\n\n// validate.test.status\nexport interface ValidateTestStatusParams {\n taskId?: string;\n}\nexport interface ValidateTestStatusResult {\n total: number;\n passed: number;\n failed: number;\n skipped: number;\n passRate: number;\n byTask?: Record<string, { passed: number; failed: number }>;\n}\n\n// validate.test.coverage\nexport interface ValidateTestCoverageParams {\n taskId?: string;\n}\nexport interface ValidateTestCoverageResult {\n lineCoverage: number;\n branchCoverage: number;\n functionCoverage: number;\n statementCoverage: number;\n threshold: number;\n meetsThreshold: boolean;\n}\n\n/**\n * Mutate Operations\n */\n\n// validate.compliance.record\nexport interface ValidateComplianceRecordParams {\n taskId: string;\n result: ValidateProtocolResult;\n}\nexport interface ValidateComplianceRecordResult {\n taskId: string;\n recorded: string;\n metrics: ComplianceMetrics;\n}\n\n// validate.test.run\nexport interface ValidateTestRunParams {\n scope?: string;\n pattern?: string;\n parallel?: boolean;\n}\nexport interface ValidateTestRunResult {\n status: ValidateTestStatusResult;\n coverage: ValidateTestCoverageResult;\n duration: string;\n output?: string;\n}\n", "/**\n * Operations types barrel \u2014 API wire format types for all CLEO domains.\n *\n * These are re-exported under `ops` namespace from the package root\n * to avoid name collisions with canonical domain types.\n */\n\nexport * from './issues.js';\nexport * from './lifecycle.js';\nexport * from './orchestrate.js';\nexport * from './release.js';\nexport * from './research.js';\nexport * from './session.js';\nexport * from './skills.js';\nexport * from './system.js';\nexport * from './tasks.js';\nexport * from './validate.js';\n", "/**\n * Orchestration Hierarchy \u2014 5-level agent hierarchy types.\n *\n * Codifies the agent authority chain from ORCH-PLAN.md:\n * Level 0: HITL (Human-In-The-Loop) \u2014 Owner, final authority\n * Level 1: Prime Orchestrator \u2014 Cross-project coordination\n * Level 2: Project Lead \u2014 Project-level architecture decisions\n * Level 3: Team Lead \u2014 Team-level task management, can spawn ephemeral agents\n * Level 4: Ephemeral \u2014 Task-scoped agents spawned by Team Leads\n *\n * @see docs/specs/CLEO-ORCH-PLAN.md\n * @task T217\n */\n\n// ============================================================================\n// Hierarchy levels\n// ============================================================================\n\n/** The 5 orchestration levels in order of authority. */\nexport enum OrchestrationLevel {\n /** Level 0: Human owner. Final authority. Never contacted by agents directly. */\n HITL = 0,\n /** Level 1: Prime Orchestrator. Cross-project coordination. Breaks ties. */\n Prime = 1,\n /** Level 2: Project Lead. Architecture decisions within a project. */\n ProjectLead = 2,\n /** Level 3: Team Lead. Task management. Can spawn ephemeral agents. */\n TeamLead = 3,\n /** Level 4: Ephemeral agent. Task-scoped, short-lived. */\n Ephemeral = 4,\n}\n\n// ============================================================================\n// Agent hierarchy membership\n// ============================================================================\n\n/** An agent's position in the orchestration hierarchy. */\nexport interface AgentHierarchyEntry {\n /** The agent's unique ID (e.g. 'cleo-rust-lead'). */\n agentId: string;\n /** Display name for human-readable output. */\n displayName: string;\n /** The agent's orchestration level. */\n level: OrchestrationLevel;\n /** The agent's direct superior (null for HITL). */\n reportsTo: string | null;\n /** Agents this agent directly manages (empty for Ephemeral). */\n manages: string[];\n /** Project scope (null for cross-project agents like Prime). */\n projectId: string | null;\n /** Team scope within a project (e.g. 'cleocode', 'signaldock'). */\n teamId: string | null;\n /** Whether this agent can spawn ephemeral sub-agents. */\n canSpawn: boolean;\n}\n\n/** The full agent hierarchy tree. */\nexport interface AgentHierarchy {\n /** All agents in the hierarchy, keyed by agentId. */\n agents: Record<string, AgentHierarchyEntry>;\n /** The Prime Orchestrator agent ID. */\n primeId: string;\n /** Project IDs in this hierarchy. */\n projectIds: string[];\n}\n\n// ============================================================================\n// Escalation chain\n// ============================================================================\n\n/** An escalation path from an agent to its authority chain. */\nexport interface EscalationChain {\n /** The requesting agent. */\n fromAgentId: string;\n /** Ordered list of agents to escalate to (nearest first). */\n chain: string[];\n /** The final authority (PRIME or HITL). */\n finalAuthority: string;\n}\n\n// ============================================================================\n// Hierarchy API\n// ============================================================================\n\n/** API for querying and managing the agent hierarchy. */\nexport interface OrchestrationHierarchyAPI {\n /** Get the full hierarchy. */\n getHierarchy(): AgentHierarchy;\n\n /** Get a single agent's hierarchy entry. */\n getAgent(agentId: string): AgentHierarchyEntry | null;\n\n /** Get all agents at a specific level. */\n getAgentsAtLevel(level: OrchestrationLevel): AgentHierarchyEntry[];\n\n /** Get the escalation chain for an agent. */\n getEscalationChain(agentId: string): EscalationChain;\n\n /** Get all agents managed by a specific agent (direct reports). */\n getDirectReports(agentId: string): AgentHierarchyEntry[];\n\n /** Check if agent A has authority over agent B. */\n hasAuthority(agentIdA: string, agentIdB: string): boolean;\n\n /** Get all agents scoped to a project. */\n getProjectAgents(projectId: string): AgentHierarchyEntry[];\n}\n", "/**\n * Session type definitions for CLEO V2.\n *\n * Plain TypeScript interfaces derived from the Drizzle/Zod schemas\n * in src/store/validation-schemas.ts. Contracts must not depend on Zod/Drizzle.\n *\n * @epic T4454\n */\n\nimport type { SessionStatus } from './status-registry.js';\n\nexport type { SessionStatus };\n\n/** Session scope JSON blob shape. */\nexport interface SessionScope {\n /** Scope type (e.g. `\"global\"`, `\"epic\"`, `\"task\"`, `\"custom\"`). */\n type: string;\n /**\n * Epic ID when scope type is `\"epic\"`.\n * @defaultValue undefined\n */\n epicId?: string;\n /**\n * Root task ID when scope is narrowed to a subtree.\n * @defaultValue undefined\n */\n rootTaskId?: string;\n /**\n * Whether to include descendant tasks of the root task.\n * @defaultValue undefined\n */\n includeDescendants?: boolean;\n /**\n * Phase slug to filter tasks by.\n * @defaultValue undefined\n */\n phaseFilter?: string | null;\n /**\n * Label filter to narrow the scope to specific labels.\n * @defaultValue undefined\n */\n labelFilter?: string[] | null;\n /**\n * Maximum hierarchy depth to include.\n * @defaultValue undefined\n */\n maxDepth?: number | null;\n /**\n * Explicit task IDs to include regardless of other filters.\n * @defaultValue undefined\n */\n explicitTaskIds?: string[] | null;\n /**\n * Task IDs to exclude from the scope.\n * @defaultValue undefined\n */\n excludeTaskIds?: string[] | null;\n /**\n * Task IDs computed from the scope definition at resolution time.\n * @defaultValue undefined\n */\n computedTaskIds?: string[];\n /**\n * ISO 8601 timestamp of when computed task IDs were last resolved.\n * @defaultValue undefined\n */\n computedAt?: string;\n}\n\n/** Session statistics. */\nexport interface SessionStats {\n /** Number of tasks completed during this session. */\n tasksCompleted: number;\n /** Number of new tasks created during this session. */\n tasksCreated: number;\n /** Number of task updates performed during this session. */\n tasksUpdated: number;\n /** Number of times the focus task was changed. */\n focusChanges: number;\n /** Total minutes the session was in active status. */\n totalActiveMinutes: number;\n /** Number of times the session was suspended and resumed. */\n suspendCount: number;\n}\n\n/** Active task work state within a session. */\nexport interface SessionTaskWork {\n /** ID of the task currently being worked on, or `null` if none. */\n taskId: string | null;\n /** ISO 8601 timestamp of when the current task was set, or `null`. */\n setAt: string | null;\n}\n\n/** Session domain type \u2014 plain interface aligned with Drizzle sessions table. */\nexport interface Session {\n /** Unique session identifier (e.g. `\"ses_20260401...\"`) . */\n id: string;\n /** Human-readable session name. */\n name: string;\n /** Current session lifecycle status. */\n status: SessionStatus;\n /** Scope definition controlling which tasks are visible. */\n scope: SessionScope;\n /** Active task work state within the session. */\n taskWork: SessionTaskWork;\n /** ISO 8601 timestamp of when the session started. */\n startedAt: string;\n /** ISO 8601 timestamp of when the session ended. @defaultValue undefined */\n endedAt?: string;\n /** Agent identifier that owns this session. @defaultValue undefined */\n agent?: string;\n /** Timestamped notes appended during the session. @defaultValue undefined */\n notes?: string[];\n /** IDs of tasks completed during this session. @defaultValue undefined */\n tasksCompleted?: string[];\n /** IDs of tasks created during this session. @defaultValue undefined */\n tasksCreated?: string[];\n /** Serialized handoff JSON for session continuity. @defaultValue undefined */\n handoffJson?: string | null;\n /** ID of the session that preceded this one. @defaultValue undefined */\n previousSessionId?: string | null;\n /** ID of the session that follows this one. @defaultValue undefined */\n nextSessionId?: string | null;\n /** Provider-specific agent identifier string. @defaultValue undefined */\n agentIdentifier?: string | null;\n /** ISO 8601 timestamp of when the handoff was consumed. @defaultValue undefined */\n handoffConsumedAt?: string | null;\n /** Agent that consumed the handoff. @defaultValue undefined */\n handoffConsumedBy?: string | null;\n /** Serialized debrief JSON from session end. @defaultValue undefined */\n debriefJson?: string | null;\n /** Aggregate session statistics. @defaultValue undefined */\n stats?: SessionStats;\n /** Number of times this session has been resumed. @defaultValue undefined */\n resumeCount?: number;\n /** Whether this session is in grade/evaluation mode. @defaultValue undefined */\n gradeMode?: boolean;\n /** ID of the provider adapter used for this session. @defaultValue undefined */\n providerId?: string | null;\n}\n\n/**\n * Result of a session start operation.\n *\n * The `sessionId` field is a convenience alias for `session.id`,\n * provided for consumers that expect it at the top level of the result.\n */\nexport interface SessionStartResult {\n /** The newly created or resumed session. */\n session: Session;\n /** Convenience alias for `session.id`. */\n sessionId: string;\n}\n\n/**\n * SessionView \u2014 typed wrapper over Session[] with collection helpers.\n *\n * Provides discoverable query methods for common session lookups.\n * Does NOT change the DataAccessor interface \u2014 consumers create views from Session[].\n *\n * @remarks\n * SessionView is a read-only collection wrapper that provides convenience\n * methods for filtering, searching, and sorting sessions. It does not own\n * the data and performs no mutations on the underlying array.\n */\nexport class SessionView {\n private readonly _sessions: Session[];\n\n constructor(sessions: Session[]) {\n this._sessions = sessions;\n }\n\n /** Create a SessionView from a Session array. */\n static from(sessions: Session[]): SessionView {\n return new SessionView(sessions);\n }\n\n /** All sessions in the view (readonly). */\n get all(): readonly Session[] {\n return this._sessions;\n }\n\n /** Number of sessions. */\n get length(): number {\n return this._sessions.length;\n }\n\n /** Find the currently active session (if any). */\n findActive(): Session | undefined {\n return this._sessions.find((s) => s.status === 'active');\n }\n\n /** Find a session by ID. */\n findById(id: string): Session | undefined {\n return this._sessions.find((s) => s.id === id);\n }\n\n /** Filter sessions by one or more statuses. */\n filterByStatus(...statuses: SessionStatus[]): Session[] {\n return this._sessions.filter((s) => (statuses as string[]).includes(s.status));\n }\n\n /** Find sessions matching a scope type and optional rootTaskId. */\n findByScope(type: string, rootTaskId?: string): Session[] {\n return this._sessions.filter((s) => {\n if (s.scope?.type !== type) return false;\n if (rootTaskId && s.scope?.rootTaskId !== rootTaskId) return false;\n return true;\n });\n }\n\n /** Sort sessions by a date field. Returns a new array (does not mutate). */\n sortByDate(field: 'startedAt' | 'endedAt', descending = true): Session[] {\n return [...this._sessions].sort((a, b) => {\n const aDate = new Date(a[field] || '').getTime();\n const bDate = new Date(b[field] || '').getTime();\n return descending ? bDate - aDate : aDate - bDate;\n });\n }\n\n /** Get the most recently started session. */\n mostRecent(): Session | undefined {\n if (this._sessions.length === 0) return undefined;\n return this.sortByDate('startedAt', true)[0];\n }\n\n /** Convert back to a plain Session array (shallow copy). */\n toArray(): Session[] {\n return [...this._sessions];\n }\n\n /** Support for-of iteration. */\n [Symbol.iterator](): Iterator<Session> {\n return this._sessions[Symbol.iterator]();\n }\n}\n", "/**\n * Unified Status Registry \u2014 single source of truth for all status enums.\n *\n * ADR-018: All status constants and types MUST be defined here.\n * No other file may define status enum arrays as constants.\n *\n * Dependency direction:\n * status-registry.ts \u2192 schema.ts, types/task.ts, validation/engine.ts,\n * dispatch/lib/security.ts, ...\n */\n\n// === WORKFLOW NAMESPACE ===\n// Statuses for entities representing work being performed.\n\nexport const TASK_STATUSES = [\n 'pending',\n 'active',\n 'blocked',\n 'done',\n 'cancelled',\n 'archived',\n] as const;\n\nexport const SESSION_STATUSES = ['active', 'ended', 'orphaned', 'suspended'] as const;\n\nexport const LIFECYCLE_PIPELINE_STATUSES = [\n 'active',\n 'completed',\n 'blocked',\n 'failed',\n 'cancelled',\n 'aborted',\n] as const;\n\nexport const LIFECYCLE_STAGE_STATUSES = [\n 'not_started',\n 'in_progress',\n 'blocked',\n 'completed',\n 'skipped',\n 'failed',\n] as const;\n\n// === GOVERNANCE NAMESPACE ===\n// Statuses for decisions and approvals.\n\nexport const ADR_STATUSES = ['proposed', 'accepted', 'superseded', 'deprecated'] as const;\n\nexport const GATE_STATUSES = ['pending', 'passed', 'failed', 'waived'] as const;\n\n// === MANIFEST NAMESPACE ===\n// Statuses for protocol output artifacts.\n// NOTE: 'complete' was the old value \u2014 it is now 'completed' everywhere.\n\nexport const MANIFEST_STATUSES = ['completed', 'partial', 'blocked', 'archived'] as const;\n\n// === DERIVED TYPES ===\n\nexport type TaskStatus = (typeof TASK_STATUSES)[number];\nexport type SessionStatus = (typeof SESSION_STATUSES)[number];\nexport type PipelineStatus = (typeof LIFECYCLE_PIPELINE_STATUSES)[number];\nexport type StageStatus = (typeof LIFECYCLE_STAGE_STATUSES)[number];\nexport type AdrStatus = (typeof ADR_STATUSES)[number];\nexport type GateStatus = (typeof GATE_STATUSES)[number];\nexport type ManifestStatus = (typeof MANIFEST_STATUSES)[number];\n\n// === TERMINAL STATE SETS ===\n\nexport const TERMINAL_TASK_STATUSES: ReadonlySet<TaskStatus> = new Set([\n 'done',\n 'cancelled',\n 'archived',\n]);\n\nexport const TERMINAL_PIPELINE_STATUSES: ReadonlySet<PipelineStatus> = new Set([\n 'completed',\n 'failed',\n 'cancelled',\n 'aborted',\n]);\n\nexport const TERMINAL_STAGE_STATUSES: ReadonlySet<StageStatus> = new Set([\n 'completed',\n 'skipped',\n 'failed',\n]);\n\n// === REGISTRY (for runtime queryability) ===\n\nexport type EntityType =\n | 'task'\n | 'session'\n | 'lifecycle_pipeline'\n | 'lifecycle_stage'\n | 'adr'\n | 'gate'\n | 'manifest';\n\nexport const STATUS_REGISTRY: Record<EntityType, readonly string[]> = {\n task: TASK_STATUSES,\n session: SESSION_STATUSES,\n lifecycle_pipeline: LIFECYCLE_PIPELINE_STATUSES,\n lifecycle_stage: LIFECYCLE_STAGE_STATUSES,\n adr: ADR_STATUSES,\n gate: GATE_STATUSES,\n manifest: MANIFEST_STATUSES,\n} as const;\n\nexport function isValidStatus(entityType: EntityType, value: string): boolean {\n return (STATUS_REGISTRY[entityType] as readonly string[]).includes(value);\n}\n\n// === DISPLAY ICONS ===\n// Typed Record maps \u2014 exhaustiveness is enforced by the compiler.\n// All icon consumers MUST import from here instead of hardcoding comparisons.\n\n/**\n * Pipeline status \u2192 Unicode progress icon.\n * Used wherever lifecycle pipeline status is rendered to a terminal.\n */\nexport const PIPELINE_STATUS_ICONS: Record<PipelineStatus, string> = {\n active: '\\u25b6', // pipeline is running\n completed: '\\u2713', // all stages done successfully\n blocked: '\\u23f8', // cannot advance; waiting\n failed: '\\u2717', // terminal failure\n cancelled: '\\u2298', // user-initiated abandonment\n aborted: '\\u23f9', // system-forced termination\n};\n\n/**\n * Stage status \u2192 Unicode progress icon.\n * Used wherever pipeline stage status is rendered to a terminal.\n */\nexport const STAGE_STATUS_ICONS: Record<StageStatus, string> = {\n not_started: '\\u23f9', // not yet entered\n in_progress: '\\u25b6', // actively running\n blocked: '\\u23f8', // paused / waiting\n completed: '\\u2713', // finished successfully\n skipped: '\\u23ed', // intentionally bypassed\n failed: '\\u2717', // terminal failure\n};\n\n/**\n * Task status \u2192 Unicode symbol (rich terminal / Unicode-enabled).\n * Falls back to TASK_STATUS_SYMBOLS_ASCII when Unicode is unavailable.\n */\nexport const TASK_STATUS_SYMBOLS_UNICODE: Record<TaskStatus, string> = {\n pending: '\\u25cb', // \u25CB not yet started\n active: '\\u25c9', // \u25C9 in progress\n blocked: '\\u2297', // \u2297 cannot advance\n done: '\\u2713', // \u2713 complete\n cancelled: '\\u2717', // \u2717 abandoned\n archived: '\\u25a3', // \u25A3 stored, inactive\n};\n\n/**\n * Task status \u2192 ASCII fallback symbol (non-Unicode terminals, CI output).\n */\nexport const TASK_STATUS_SYMBOLS_ASCII: Record<TaskStatus, string> = {\n pending: '-',\n active: '*',\n blocked: 'x',\n done: '+',\n cancelled: '~',\n archived: '#',\n};\n", "/**\n * @cleocode/contracts \u2014 Domain types, interfaces, and contracts for the CLEO ecosystem.\n *\n * This is the LEAF package in the dependency graph \u2014 ZERO runtime dependencies.\n * All domain types (Task, Session, DataAccessor, etc.) are defined here.\n * Implementation packages (@cleocode/core, @cleocode/cleo) import from here.\n */\n\n// === Provider Adapter Contracts ===\nexport type { AdapterHealthStatus, CLEOProviderAdapter } from './adapter.js';\n// === Agent Registry (credential management) ===\nexport type {\n AgentCredential,\n AgentListFilter,\n AgentRegistryAPI,\n AgentWithProjectOverride,\n ProjectAgentRef,\n TransportConfig,\n} from './agent-registry.js';\n// === Archive Types ===\nexport type {\n ArchiveCycleTimesReport,\n ArchiveDailyTrend,\n ArchivedTask,\n ArchiveLabelEntry,\n ArchiveMetadata,\n ArchiveMonthlyTrend,\n ArchivePhaseEntry,\n ArchivePriorityEntry,\n ArchiveReportType,\n ArchiveStatsEnvelope,\n ArchiveSummaryReport,\n ArchiveTrendsReport,\n CycleTimeDistribution,\n CycleTimePercentiles,\n} from './archive.js';\n// === Backup Manifest Types ===\nexport type {\n BackupDatabaseEntry,\n BackupGlobalFileEntry,\n BackupIntegrity,\n BackupJsonEntry,\n BackupManifest,\n BackupMetadata,\n BackupScope,\n} from './backup-manifest.js';\n// === Brain/Memory Types ===\nexport type {\n BrainCognitiveType,\n BrainEntryRef,\n BrainEntrySummary,\n BrainMemoryTier,\n BrainSourceConfidence,\n ContradictionDetail,\n SupersededEntry,\n} from './brain.js';\nexport type { AdapterCapabilities } from './capabilities.js';\n// === Code Symbol Types (tree-sitter AST) ===\nexport type {\n BatchParseResult,\n CodeSymbol,\n CodeSymbolKind,\n ParseResult,\n} from './code-symbol.js';\n// === Conduit Protocol (agent-to-agent communication) ===\nexport type {\n Conduit,\n ConduitConfig,\n ConduitMessage,\n ConduitSendOptions,\n ConduitSendResult,\n ConduitState,\n ConduitStateChange,\n ConduitUnsubscribe,\n} from './conduit.js';\n// === Configuration Types ===\nexport type {\n BackupConfig,\n BrainConfig,\n BrainEmbeddingConfig,\n BrainLlmExtractionConfig,\n BrainMemoryBridgeConfig,\n BrainSummarizationConfig,\n BrainTieringConfig,\n CleoConfig,\n ConfigSource,\n DateFormat,\n EnforcementProfile,\n HierarchyConfig,\n LifecycleConfig,\n LifecycleEnforcementMode,\n LoggingConfig,\n LogLevel,\n OutputConfig,\n OutputFormat,\n ResolvedValue,\n SessionConfig,\n SessionSummaryInput,\n SharingConfig,\n SharingMode,\n SignalDockConfig,\n SignalDockMode,\n} from './config.js';\nexport type { AdapterContextMonitorProvider } from './context-monitor.js';\n// === DataAccessor Interface ===\nexport type {\n ArchiveFields,\n ArchiveFile,\n DataAccessor,\n DataAccessorAgentInstance,\n QueryTasksResult,\n TaskFieldUpdates,\n TaskQueryFilters,\n TransactionAccessor,\n} from './data-accessor.js';\n// === Dependency Registry Contracts ===\nexport type {\n DependencyCategory,\n DependencyCheckResult,\n DependencyReport,\n DependencySpec,\n} from './dependency.js';\nexport type { AdapterManifest, DetectionPattern } from './discovery.js';\n// === Error Utilities ===\nexport {\n createErrorResult,\n createSuccessResult,\n formatError,\n getErrorMessage,\n isErrorResult,\n isErrorType,\n normalizeError,\n} from './errors.js';\n// === Exit Codes ===\nexport {\n ExitCode,\n getExitCodeName,\n isErrorCode,\n isNoChangeCode,\n isRecoverableCode,\n isSuccessCode,\n} from './exit-codes.js';\nexport type {\n AdminAPI,\n AgentCapacity,\n AgentHealthStatus,\n AgentInstanceRow,\n AgentInstanceStatus,\n AgentsAPI,\n AgentType,\n BlastRadius,\n BlastRadiusSeverity,\n BrainObservationType,\n CleoInitOptions,\n DuplicateStrategy,\n HybridSearchOptions,\n ImpactedTask,\n ImpactReport,\n ImportParams,\n IntelligenceAPI,\n LifecycleAPI,\n MemoryAPI,\n NexusAPI,\n OrchestrationAPI,\n RegisterAgentOptions,\n ReleaseAPI,\n SessionsAPI,\n StickyAPI,\n SyncAPI,\n TaskStartResult,\n TasksAPI,\n} from './facade.js';\n// === Facade API Interfaces ===\nexport {\n AGENT_INSTANCE_STATUSES,\n AGENT_TYPES,\n BRAIN_OBSERVATION_TYPES,\n} from './facade.js';\n// === Graph Intelligence Types (T512, T529) ===\nexport type {\n CommunityNode,\n GraphNode,\n GraphNodeKind,\n GraphRelation,\n GraphRelationType,\n ImpactResult,\n KnowledgeGraph,\n ProcessNode,\n SymbolIndex,\n} from './graph.js';\nexport type { AdapterHookProvider } from './hooks.js';\nexport type { AdapterInstallProvider, InstallOptions, InstallResult } from './install.js';\nexport type {\n CleoResponse,\n ConformanceReport,\n FlagInput,\n GatewayEnvelope,\n GatewayError,\n GatewayMeta,\n GatewaySuccess,\n LAFSEnvelope,\n LAFSError,\n LAFSErrorCategory,\n LAFSMeta,\n LAFSPage,\n LAFSPageNone,\n LAFSPageOffset,\n LAFSTransport,\n LafsAlternative,\n LafsEnvelope,\n LafsError,\n LafsErrorDetail,\n LafsSuccess,\n MVILevel,\n Warning,\n} from './lafs.js';\n// === LAFS Envelope Types ===\nexport {\n isGatewayEnvelope,\n isLafsError,\n isLafsSuccess,\n} from './lafs.js';\nexport type {\n BridgeDecision,\n BridgeLearning,\n BridgeObservation,\n BridgePattern,\n MemoryBridgeConfig,\n MemoryBridgeContent,\n SessionSummary,\n} from './memory.js';\n// === Operations Types (API wire format, namespaced to avoid collision with domain types) ===\nexport * as ops from './operations/index.js';\n// Commonly used ops types re-exported at top level for convenience\nexport type { BrainState } from './operations/orchestrate.js';\n// === Orchestration Hierarchy ===\nexport {\n type AgentHierarchy,\n type AgentHierarchyEntry,\n type EscalationChain,\n type OrchestrationHierarchyAPI,\n OrchestrationLevel,\n} from './orchestration-hierarchy.js';\nexport type { AdapterPathProvider } from './provider-paths.js';\n// === Result Types (Dashboard, Stats, Log, Context, Sequence, Analysis, Deps) ===\nexport type {\n BottleneckTask,\n CompleteTaskUnblocked,\n ContextResult,\n DashboardResult,\n LabelCount,\n LeveragedTask,\n LogQueryResult,\n SequenceResult,\n StatsActivityMetrics,\n StatsAllTime,\n StatsCompletionMetrics,\n StatsCurrentState,\n StatsCycleTimes,\n StatsResult,\n TaskAnalysisResult,\n TaskDepsResult,\n TaskRef,\n TaskRefPriority,\n TaskSummary,\n} from './results.js';\n// === Session Start Result ===\nexport type {\n Session,\n SessionScope,\n SessionStartResult,\n SessionStats,\n SessionTaskWork,\n} from './session.js';\n// === Session Types ===\nexport { SessionView } from './session.js';\nexport type { AdapterSpawnProvider, SpawnContext, SpawnResult } from './spawn.js';\n// === CLEO Spawn Types (distinct from adapter spawn) ===\nexport type {\n CAAMPSpawnOptions,\n CAAMPSpawnResult,\n CLEOSpawnAdapter,\n CLEOSpawnContext,\n CLEOSpawnResult,\n Provider,\n SpawnStatus,\n TokenResolution,\n} from './spawn-types.js';\n// === Status Registry (MUST be first \u2014 everything depends on this) ===\nexport {\n ADR_STATUSES,\n type AdrStatus,\n // Registry\n type EntityType,\n GATE_STATUSES,\n type GateStatus,\n isValidStatus,\n LIFECYCLE_PIPELINE_STATUSES,\n LIFECYCLE_STAGE_STATUSES,\n MANIFEST_STATUSES,\n type ManifestStatus,\n // Display icons\n PIPELINE_STATUS_ICONS,\n type PipelineStatus,\n SESSION_STATUSES,\n type SessionStatus,\n STAGE_STATUS_ICONS,\n STATUS_REGISTRY,\n type StageStatus,\n TASK_STATUS_SYMBOLS_ASCII,\n TASK_STATUS_SYMBOLS_UNICODE,\n // Constants\n TASK_STATUSES,\n // Derived types\n type TaskStatus,\n TERMINAL_PIPELINE_STATUSES,\n TERMINAL_STAGE_STATUSES,\n // Terminal state sets\n TERMINAL_TASK_STATUSES,\n} from './status-registry.js';\n// === Task Types ===\nexport type {\n CancelledTask,\n CompletedTask,\n EpicLifecycle,\n FileMeta,\n Phase,\n PhaseStatus,\n PhaseTransition,\n ProjectMeta,\n Release,\n ReleaseStatus,\n SessionNote,\n Task,\n TaskCreate,\n TaskOrigin,\n TaskPriority,\n TaskProvenance,\n TaskRelation,\n TaskSize,\n TaskType,\n TaskVerification,\n TaskWorkState,\n VerificationAgent,\n VerificationFailure,\n VerificationGate,\n} from './task.js';\n// === TaskRecord Types (string-widened for dispatch/LAFS) ===\nexport type {\n MinimalTaskRecord,\n TaskRecord,\n TaskRecordRelation,\n ValidationHistoryEntry,\n} from './task-record.js';\n// === Task Sync Types (provider-agnostic reconciliation) ===\nexport type {\n ConflictPolicy,\n ExternalLinkType,\n ExternalTask,\n ExternalTaskLink,\n ExternalTaskProvider,\n ExternalTaskStatus,\n ReconcileAction,\n ReconcileActionType,\n ReconcileOptions,\n ReconcileResult,\n SyncDirection,\n} from './task-sync.js';\n// === Tessera Types ===\nexport type {\n TesseraInstantiationInput,\n TesseraTemplate,\n TesseraVariable,\n} from './tessera.js';\n// === Transport (low-level wire protocol) ===\nexport type {\n AdapterTransportProvider,\n Transport,\n TransportConnectConfig,\n} from './transport.js';\n// === WarpChain Types ===\nexport type {\n ChainShape,\n ChainValidation,\n GateCheck,\n GateContract,\n GateName,\n GateResult,\n ProtocolType,\n WarpChain,\n WarpChainExecution,\n WarpChainInstance,\n WarpLink,\n WarpStage,\n} from './warp-chain.js';\n\n// === WASM SDK (Rust crate bindings) ===\n", "/**\n * Claude Code Spawn Provider\n *\n * Implements AdapterSpawnProvider for Claude Code CLI.\n * Migrated from src/core/spawn/adapters/claude-code-adapter.ts\n *\n * Uses the native `claude` CLI to spawn subagent processes with prompts\n * written to temporary files. Processes run detached and are tracked\n * by PID for listing and termination.\n *\n * @task T5240\n */\n\nimport { exec, spawn as nodeSpawn } from 'node:child_process';\nimport { unlink, writeFile } from 'node:fs/promises';\nimport { promisify } from 'node:util';\nimport type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/contracts';\nimport { getErrorMessage } from '@cleocode/contracts';\n\nconst execAsync = promisify(exec);\n\n/** Internal tracking entry for a spawned process. */\ninterface TrackedProcess {\n pid: number;\n taskId: string;\n startTime: string;\n}\n\n/**\n * Spawn provider for Claude Code.\n *\n * Spawns detached Claude CLI processes for subagent execution.\n * Each spawn writes its prompt to a temporary file, then runs\n * `claude --allow-insecure --no-upgrade-check <tmpFile>` as a\n * detached, unref'd child process.\n *\n * @remarks\n * The provider uses `--allow-insecure --no-upgrade-check` flags to\n * ensure the Claude CLI starts without interactive prompts. Prompts are\n * written to temporary files under `/tmp/` and cleaned up after the\n * child process exits. Processes are tracked by instance ID in an\n * in-memory map and verified via `kill(pid, 0)` liveness checks.\n */\nexport class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {\n /** Map of instance IDs to tracked process info. */\n private processMap = new Map<string, TrackedProcess>();\n\n /**\n * Check if the Claude CLI is available in PATH.\n *\n * @returns true if `claude` is found via `which`\n */\n async canSpawn(): Promise<boolean> {\n try {\n await execAsync('which claude');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Spawn a subagent via Claude CLI.\n *\n * Writes the prompt to a temporary file and spawns a detached Claude\n * process. The process runs independently of the parent.\n *\n * @param context - Spawn context with taskId, prompt, and options\n * @returns Spawn result with instance ID and status\n */\n async spawn(context: SpawnContext): Promise<SpawnResult> {\n const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const startTime = new Date().toISOString();\n let tmpFile: string | undefined;\n\n try {\n // Enrich prompt with CANT bundle, memory bridge, and mental model (T555).\n // Best-effort: if CANT context is unavailable, the raw prompt is used.\n let enrichedPrompt = context.prompt;\n try {\n const { buildCantEnrichedPrompt } = await import('../../cant-context.js');\n enrichedPrompt = await buildCantEnrichedPrompt({\n projectDir: context.workingDirectory ?? process.cwd(),\n basePrompt: context.prompt,\n agentName: (context.options?.agentName as string) ?? undefined,\n });\n } catch {\n // CANT enrichment unavailable \u2014 use raw prompt\n }\n\n tmpFile = `/tmp/claude-spawn-${instanceId}.txt`;\n await writeFile(tmpFile, enrichedPrompt, 'utf-8');\n\n const args = ['--allow-insecure', '--no-upgrade-check', tmpFile];\n const spawnOpts: Parameters<typeof nodeSpawn>[2] = {\n detached: true,\n stdio: 'ignore',\n };\n\n if (context.workingDirectory) {\n spawnOpts.cwd = context.workingDirectory;\n }\n\n const child = nodeSpawn('claude', args, spawnOpts);\n child.unref();\n\n if (child.pid) {\n this.processMap.set(instanceId, {\n pid: child.pid,\n taskId: context.taskId,\n startTime,\n });\n }\n\n const capturedTmpFile = tmpFile;\n child.on('exit', async () => {\n this.processMap.delete(instanceId);\n try {\n await unlink(capturedTmpFile);\n } catch {\n // Ignore cleanup errors\n }\n });\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'claude-code',\n status: 'running',\n startTime,\n };\n } catch (error) {\n // Log spawn failure for debugging\n console.error(`[ClaudeCodeSpawnProvider] Failed to spawn: ${getErrorMessage(error)}`);\n\n if (tmpFile) {\n try {\n await unlink(tmpFile);\n } catch {\n // Ignore cleanup errors\n }\n }\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'claude-code',\n status: 'failed',\n startTime,\n endTime: new Date().toISOString(),\n error: getErrorMessage(error),\n };\n }\n }\n\n /**\n * List currently running Claude subagent processes.\n *\n * Checks each tracked process via kill(pid, 0) to verify it is still alive.\n * Dead processes are automatically cleaned from the tracking map.\n *\n * @returns Array of spawn results for running processes\n */\n async listRunning(): Promise<SpawnResult[]> {\n const running: SpawnResult[] = [];\n\n for (const [instanceId, tracked] of this.processMap.entries()) {\n try {\n process.kill(tracked.pid, 0);\n running.push({\n instanceId,\n taskId: tracked.taskId,\n providerId: 'claude-code',\n status: 'running',\n startTime: tracked.startTime,\n });\n } catch {\n this.processMap.delete(instanceId);\n }\n }\n\n return running;\n }\n\n /**\n * Terminate a running spawn by instance ID.\n *\n * Sends SIGTERM to the tracked process. If the process is not found\n * or has already exited, this is a no-op.\n *\n * @param instanceId - ID of the spawn instance to terminate\n */\n async terminate(instanceId: string): Promise<void> {\n const tracked = this.processMap.get(instanceId);\n if (!tracked) return;\n\n try {\n process.kill(tracked.pid, 'SIGTERM');\n } catch {\n // Process may have already exited\n }\n this.processMap.delete(instanceId);\n }\n}\n", "/**\n * Claude Code TaskSyncProvider \u2014 bridges Claude's TodoWrite format\n * to the provider-agnostic reconciliation system.\n *\n * All Claude Code / TodoWrite-specific parsing lives here.\n * The core reconciliation engine never sees TodoWrite formats.\n */\n\nimport { readFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport type { ExternalTask, ExternalTaskProvider, ExternalTaskStatus } from '@cleocode/contracts';\n\n// ---------------------------------------------------------------------------\n// TodoWrite native types (Claude-specific, never exposed beyond this file)\n// ---------------------------------------------------------------------------\n\ninterface TodoWriteItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n activeForm?: string;\n}\n\ninterface TodoWriteState {\n todos: TodoWriteItem[];\n}\n\n// ---------------------------------------------------------------------------\n// Parsing helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a CLEO task ID from TodoWrite content prefix: \"[T001] ...\" -> \"T001\".\n */\nfunction parseTaskId(content: string): string | null {\n const match = content.match(/^\\[T(\\d+)\\]/);\n return match ? `T${match[1]}` : null;\n}\n\n/**\n * Strip ID and status prefixes from content to extract the clean title.\n */\nfunction stripPrefixes(content: string): string {\n return content\n .replace(/^\\[T\\d+\\]\\s*/, '')\n .replace(/^\\[!\\]\\s*/, '')\n .replace(/^\\[BLOCKED\\]\\s*/, '');\n}\n\n/**\n * Map TodoWrite status to normalized ExternalTaskStatus.\n */\nfunction mapStatus(twStatus: TodoWriteItem['status']): ExternalTaskStatus {\n switch (twStatus) {\n case 'completed':\n return 'completed';\n case 'in_progress':\n return 'active';\n case 'pending':\n return 'pending';\n default:\n return 'pending';\n }\n}\n\n/**\n * Resolve the TodoWrite state file path.\n * Claude Code writes its TodoWrite state to a known location.\n */\nfunction getTodoWriteFilePath(projectDir: string): string {\n return join(projectDir, '.cleo', 'sync', 'todowrite-state.json');\n}\n\n// ---------------------------------------------------------------------------\n// Provider implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Claude Code TaskSyncProvider.\n *\n * Reads Claude's TodoWrite JSON state, parses [T001]-prefixed task IDs\n * and status, and returns normalized ExternalTask[].\n *\n * Optional: accepts a custom file path for testing.\n *\n * @remarks\n * TodoWrite items with `[T001]`-style prefixes are mapped to their CLEO\n * task IDs. Items without a prefix receive a synthetic `tw-new-N` ID\n * for reconciliation. The provider reads from\n * `.cleo/sync/todowrite-state.json` by default.\n */\nexport class ClaudeCodeTaskSyncProvider implements ExternalTaskProvider {\n /** Optional override path for the TodoWrite state file (used in tests). */\n private readonly customFilePath?: string;\n\n constructor(options?: { filePath?: string }) {\n this.customFilePath = options?.filePath;\n }\n\n /** Retrieve external tasks from Claude's TodoWrite state file. */\n async getExternalTasks(projectDir: string): Promise<ExternalTask[]> {\n const filePath = this.customFilePath ?? getTodoWriteFilePath(projectDir);\n\n // Check file exists\n try {\n await stat(filePath);\n } catch {\n // No TodoWrite state \u2014 return empty (no tasks to sync)\n return [];\n }\n\n // Parse the TodoWrite JSON\n const raw = await readFile(filePath, 'utf-8');\n let state: TodoWriteState;\n try {\n state = JSON.parse(raw) as TodoWriteState;\n } catch {\n return []; // Malformed JSON \u2014 treat as empty\n }\n\n if (!state.todos || !Array.isArray(state.todos)) {\n return [];\n }\n\n const tasks: ExternalTask[] = [];\n let syntheticIndex = 0;\n\n for (const item of state.todos) {\n const cleoTaskId = parseTaskId(item.content);\n const title = cleoTaskId ? stripPrefixes(item.content).trim() : item.content.trim();\n\n if (!title) continue;\n\n tasks.push({\n externalId: cleoTaskId ?? `tw-new-${syntheticIndex++}`,\n title,\n status: mapStatus(item.status),\n providerMeta: {\n source: 'todowrite',\n cleoTaskId,\n activeForm: item.activeForm,\n rawContent: item.content,\n },\n });\n }\n\n return tasks;\n }\n}\n", "/**\n * Transport provider for the Claude Code adapter.\n *\n * Implements AdapterTransportProvider to supply Claude Code's\n * native inter-agent transport mechanism.\n *\n * @task T5240\n */\n\nimport type { AdapterTransportProvider } from '@cleocode/contracts';\n\n/**\n * Transport provider for Claude Code inter-agent communication.\n *\n * @remarks\n * Currently returns null from {@link createTransport} because actual transport\n * creation is handled by the signaldock factory which checks for this adapter's\n * transport capability flag. Full wiring will be completed in Phase 5 of the\n * adapter system rollout.\n */\nexport class ClaudeCodeTransportProvider implements AdapterTransportProvider {\n /** Provider-specific transport name used for capability negotiation. */\n readonly transportName = 'claude-code';\n\n /** Create a transport instance for inter-agent messaging. */\n createTransport(): unknown {\n // Returns null \u2014 actual transport creation is handled by the signaldock factory\n // which checks for this adapter's transport capability.\n // Full wiring will be completed in Phase 5.\n return null;\n }\n}\n", "/**\n * Claude Code Adapter\n *\n * Main CLEOProviderAdapter implementation for Anthropic's Claude Code CLI.\n * Provides spawn, hooks, and install capabilities for CLEO integration.\n *\n * @task T5240\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { ClaudeCodeContextMonitorProvider } from './context-monitor.js';\nimport { ClaudeCodeHookProvider } from './hooks.js';\nimport { ClaudeCodeInstallProvider } from './install.js';\nimport { ClaudeCodePathProvider } from './paths.js';\nimport { ClaudeCodeSpawnProvider } from './spawn.js';\nimport { ClaudeCodeTaskSyncProvider } from './task-sync.js';\nimport { ClaudeCodeTransportProvider } from './transport.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for Anthropic Claude Code CLI.\n *\n * Bridges CLEO's adapter system with Claude Code's native capabilities:\n * - Hooks: Maps Claude Code events (SessionStart, PostToolUse, etc.) to CAAMP events\n * - Spawn: Launches subagent processes via the `claude` CLI\n * - Install: Manages instruction files and brain observation plugin registration\n *\n * @remarks\n * This is the most feature-complete adapter in the CLEO system, supporting\n * 14 of 16 CAAMP canonical events, subagent spawning via the `claude` CLI,\n * context monitoring with statusline integration, task sync via TodoWrite,\n * and inter-agent transport. It serves as the reference implementation for\n * other provider adapters.\n */\nexport class ClaudeCodeAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'claude-code';\n /** Human-readable provider name. */\n readonly name = 'Claude Code';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n // 14/16 canonical events \u2014 derived from getProviderHookProfile('claude-code') in CAAMP 1.9.1.\n // PreModel and PostModel are not supported by Claude Code.\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'PromptSubmit',\n 'ResponseComplete',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'PermissionRequest',\n 'SubagentStart',\n 'SubagentStop',\n 'PreCompact',\n 'PostCompact',\n 'Notification',\n 'ConfigChange',\n ],\n supportsSpawn: true,\n supportsInstall: true,\n supportsInstructionFiles: true,\n instructionFilePattern: 'CLAUDE.md',\n supportsContextMonitor: true,\n supportsStatusline: true,\n supportsProviderPaths: true,\n supportsTransport: true,\n supportsTaskSync: true,\n };\n\n /** Hook provider for CAAMP event mapping and registration. */\n hooks: ClaudeCodeHookProvider;\n /** Spawn provider for launching subagent processes via `claude` CLI. */\n spawn: ClaudeCodeSpawnProvider;\n /** Install provider for managing instruction files and plugin registration. */\n install: ClaudeCodeInstallProvider;\n /** Path provider for resolving Claude Code directory locations. */\n paths: ClaudeCodePathProvider;\n /** Context monitor for tracking context window usage and statusline output. */\n contextMonitor: ClaudeCodeContextMonitorProvider;\n /** Transport provider for inter-agent communication. */\n transport: ClaudeCodeTransportProvider;\n /** Task sync provider bridging Claude's TodoWrite format to CLEO tasks. */\n taskSync: ClaudeCodeTaskSyncProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new ClaudeCodeHookProvider();\n this.spawn = new ClaudeCodeSpawnProvider();\n this.install = new ClaudeCodeInstallProvider();\n this.paths = new ClaudeCodePathProvider();\n this.contextMonitor = new ClaudeCodeContextMonitorProvider();\n this.transport = new ClaudeCodeTransportProvider();\n this.taskSync = new ClaudeCodeTaskSyncProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * Validates the environment by checking for the Claude CLI\n * and Claude Code configuration directory.\n *\n * @param projectDir - Root directory of the project\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n\n // Activate CLEO hook bridge for this project \u2014 connects Claude Code\n // native events to CLEO's internal hook dispatch (T555).\n await this.hooks.registerNativeHooks(projectDir);\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Claude Code is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Claude CLI is available in PATH\n * 3. ~/.claude/ configuration directory exists\n *\n * @returns Health status with details about each check\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Claude CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which claude');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Claude Code config directory\n const claudeConfigDir = join(homedir(), '.claude');\n const configExists = existsSync(claudeConfigDir);\n details.configDirExists = configExists;\n\n // Check for CLAUDE_CODE_ENTRYPOINT env var\n const entrypointSet = process.env.CLAUDE_CODE_ENTRYPOINT !== undefined;\n details.entrypointEnvSet = entrypointSet;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * Statusline integration for the Claude Code adapter.\n *\n * Implements the statusline portion of AdapterContextMonitorProvider.\n * Checks and configures Claude Code status line for context monitoring.\n *\n * @task T5240\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\ntype StatuslineStatus = 'configured' | 'not_configured' | 'custom_no_cleo' | 'no_settings';\n\n/**\n * Get the path to Claude Code's settings.json.\n * Respects CLAUDE_SETTINGS env var, defaults to ~/.claude/settings.json.\n */\nfunction getClaudeSettingsPath(): string {\n return (\n process.env['CLAUDE_SETTINGS'] ??\n join(process.env['CLAUDE_HOME'] ?? join(homedir(), '.claude'), 'settings.json')\n );\n}\n\n/**\n * Check if statusline integration is configured.\n * Returns the current integration status.\n *\n * @remarks\n * Reads Claude Code's settings.json and inspects the `statusLine` field\n * to determine whether CLEO context monitoring is active.\n *\n * @returns One of: 'configured', 'not_configured', 'custom_no_cleo', 'no_settings'\n *\n * @example\n * ```typescript\n * import { checkStatuslineIntegration } from './statusline.js';\n *\n * const status = checkStatuslineIntegration();\n * if (status === 'not_configured') {\n * console.log('Run cleo install to set up context monitoring');\n * }\n * ```\n */\nexport function checkStatuslineIntegration(): StatuslineStatus {\n const settingsPath = getClaudeSettingsPath();\n\n if (!existsSync(settingsPath)) return 'no_settings';\n\n try {\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const statusLine = settings.statusLine;\n\n if (!statusLine?.type) return 'not_configured';\n if (statusLine.type !== 'command') return 'custom_no_cleo';\n\n const cmd = statusLine.command ?? '';\n\n // Check if it's a CLEO statusline integration\n if (\n cmd.includes('context-monitor.sh') ||\n cmd.includes('cleo-statusline') ||\n cmd.includes('.context-state.json') ||\n cmd.includes('context-states')\n ) {\n return 'configured';\n }\n\n // Check if the script writes to CLEO state file\n const scriptPath = cmd.startsWith('~') ? cmd.replace('~', homedir()) : cmd;\n\n if (existsSync(scriptPath)) {\n try {\n const content = readFileSync(scriptPath, 'utf-8');\n if (content.includes('context-state.json')) return 'configured';\n } catch {\n /* unreadable */\n }\n }\n\n return 'custom_no_cleo';\n } catch {\n return 'no_settings';\n }\n}\n\n/**\n * Get the statusline setup command for Claude Code settings.\n *\n * @remarks\n * Returns a JSON-serializable object that can be merged into\n * Claude Code's settings.json to enable context monitoring.\n *\n * @param cleoHome - Absolute path to the CLEO home directory\n * @returns Settings object containing the statusLine configuration\n *\n * @example\n * ```typescript\n * import { getStatuslineConfig } from './statusline.js';\n *\n * const config = getStatuslineConfig('/home/user/.cleo');\n * ```\n */\nexport function getStatuslineConfig(cleoHome: string): Record<string, unknown> {\n return {\n statusLine: {\n type: 'command',\n command: join(cleoHome, 'lib', 'session', 'context-monitor.sh'),\n },\n };\n}\n\n/**\n * Get human-readable setup instructions.\n *\n * @remarks\n * Returns a multi-line string with file path, JSON config, and explanation\n * suitable for display to the user.\n *\n * @param cleoHome - Absolute path to the CLEO home directory\n * @returns Formatted setup instructions string\n *\n * @example\n * ```typescript\n * import { getSetupInstructions } from './statusline.js';\n *\n * console.log(getSetupInstructions('/home/user/.cleo'));\n * ```\n */\nexport function getSetupInstructions(cleoHome: string): string {\n const settingsPath = getClaudeSettingsPath();\n\n return [\n 'To enable context monitoring, add to your Claude Code settings:',\n `File: ${settingsPath}`,\n '',\n JSON.stringify(getStatuslineConfig(cleoHome), null, 2),\n '',\n 'This enables real-time context window tracking in the CLI.',\n ].join('\\n');\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Anthropic Claude Code CLI.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T5240\n */\n\nimport { ClaudeCodeAdapter } from './adapter.js';\n\nexport { ClaudeCodeAdapter } from './adapter.js';\nexport { ClaudeCodeContextMonitorProvider } from './context-monitor.js';\nexport { ClaudeCodeHookProvider } from './hooks.js';\nexport { ClaudeCodeInstallProvider } from './install.js';\nexport { ClaudeCodePathProvider } from './paths.js';\nexport { ClaudeCodeSpawnProvider } from './spawn.js';\nexport {\n checkStatuslineIntegration,\n getSetupInstructions,\n getStatuslineConfig,\n} from './statusline.js';\nexport { ClaudeCodeTransportProvider } from './transport.js';\n\nexport default ClaudeCodeAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the claude-code\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link ClaudeCodeAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/claude-code';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n */\nexport function createAdapter(): ClaudeCodeAdapter {\n return new ClaudeCodeAdapter();\n}\n", "/**\n * Cursor Hook Provider\n *\n * Maps Cursor's native hook events to CAAMP canonical hook events.\n * Cursor supports 10 of 16 canonical events through its config-based hook system.\n *\n * Event translation uses CAAMP normalizer APIs:\n * - `toCanonical(nativeName, 'cursor')` for runtime event name resolution\n * - `getSupportedEvents('cursor')` to enumerate supported canonical events\n * - `getProviderHookProfile('cursor')` for the full provider profile\n *\n * Cursor uses camelCase native event names (e.g. `sessionStart`, `preToolUse`).\n * Hooks are configured via `.cursor/hooks.json`. Supported handler types:\n * command, prompt.\n *\n * Unsupported events: PermissionRequest, PreModel, PostModel, PostCompact,\n * Notification, ConfigChange.\n *\n * @task T165\n * @epic T134\n */\n\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/** CAAMP provider identifier for Cursor. */\nconst PROVIDER_ID = 'cursor' as const;\n\n/**\n * Fallback map from Cursor native event names to CAAMP canonical names.\n *\n * Derived from `getProviderHookProfile('cursor').mappings` in CAAMP 1.9.1.\n * Covers all 10 supported events. PermissionRequest, PreModel, PostModel,\n * PostCompact, Notification, and ConfigChange are not supported by Cursor.\n *\n * Cursor uses camelCase names while CAAMP canonical names are PascalCase.\n */\nconst CURSOR_EVENT_MAP: Record<string, string> = {\n // CAAMP: toNative('SessionStart', 'cursor') = 'sessionStart'\n sessionStart: 'SessionStart',\n // CAAMP: toNative('SessionEnd', 'cursor') = 'sessionEnd'\n sessionEnd: 'SessionEnd',\n // CAAMP: toNative('PromptSubmit', 'cursor') = 'beforeSubmitPrompt'\n beforeSubmitPrompt: 'PromptSubmit',\n // CAAMP: toNative('ResponseComplete', 'cursor') = 'stop'\n stop: 'ResponseComplete',\n // CAAMP: toNative('PreToolUse', 'cursor') = 'preToolUse'\n preToolUse: 'PreToolUse',\n // CAAMP: toNative('PostToolUse', 'cursor') = 'postToolUse'\n postToolUse: 'PostToolUse',\n // CAAMP: toNative('PostToolUseFailure', 'cursor') = 'postToolUseFailure'\n postToolUseFailure: 'PostToolUseFailure',\n // CAAMP: toNative('SubagentStart', 'cursor') = 'subagentStart'\n subagentStart: 'SubagentStart',\n // CAAMP: toNative('SubagentStop', 'cursor') = 'subagentStop'\n subagentStop: 'SubagentStop',\n // CAAMP: toNative('PreCompact', 'cursor') = 'preCompact'\n preCompact: 'PreCompact',\n};\n\n/**\n * Hook provider for Cursor.\n *\n * Cursor registers hooks via its config system at `.cursor/hooks.json`.\n * Supported handler types: command, prompt.\n *\n * CAAMP 1.9.1 reveals Cursor supports 10 of 16 canonical events. Previously\n * this provider was a no-op stub. It now provides full event mapping and CAAMP\n * normalizer integration.\n *\n * Event mapping is based on `getProviderHookProfile('cursor')` from CAAMP 1.9.1.\n * Async accessors (`getSupportedCanonicalEvents`, `getProviderProfile`) call\n * CAAMP directly when available.\n *\n * Since hooks are registered through the config system (managed by the install\n * provider), `registerNativeHooks` and `unregisterNativeHooks` track registration\n * state without performing filesystem operations.\n *\n * @remarks\n * This provider was originally a no-op stub. It now provides full event\n * mapping for all 10 canonical events supported by Cursor, plus CAAMP\n * normalizer integration via async accessors. Registration state is\n * tracked in-memory because Cursor manages hooks through its own config.\n *\n * @task T165\n * @epic T134\n */\nexport class CursorHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Cursor native event name to a CAAMP canonical hook event name.\n *\n * Looks up the native event name in the map derived from\n * `getProviderHookProfile('cursor').mappings` (CAAMP 1.9.1). Cursor uses\n * camelCase names (e.g. \"preToolUse\", \"sessionStart\").\n *\n * Returns null for unsupported events (PermissionRequest, PreModel,\n * PostModel, PostCompact, Notification, ConfigChange).\n *\n * @param providerEvent - Cursor native event name (e.g. \"preToolUse\", \"sessionStart\")\n * @returns CAAMP canonical event name, or null if unmapped\n * @task T165\n */\n mapProviderEvent(providerEvent: string): string | null {\n return CURSOR_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For Cursor, hooks are registered via the config system\n * (`.cursor/hooks.json`), managed by the install provider.\n * This method marks hooks as registered without performing filesystem operations.\n *\n * Iterating supported events is handled at install time using\n * `getSupportedCanonicalEvents()` to enumerate all 10 supported hooks.\n *\n * @param _projectDir - Project directory (unused; Cursor config manages registration)\n * @task T165\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For Cursor, this is a no-op since hooks are managed through the config\n * system. Unregistration happens via the install provider's uninstall method.\n *\n * @task T165\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via `registerNativeHooks`.\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the native\u2192canonical event mapping for introspection and debugging.\n *\n * Returns the map derived from `getProviderHookProfile('cursor').mappings`\n * (CAAMP 1.9.1). Use `getSupportedCanonicalEvents()` to enumerate canonical\n * names via live CAAMP APIs.\n *\n * @returns Immutable record of native event name \u2192 canonical event name\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...CURSOR_EVENT_MAP };\n }\n\n /**\n * Enumerate supported canonical events via CAAMP's `getSupportedEvents()`.\n *\n * Calls `getSupportedEvents('cursor')` from the CAAMP normalizer to get the\n * authoritative list. Cursor supports 10 of 16 canonical events. Falls back\n * to the values of the static event map when CAAMP is unavailable at runtime.\n *\n * @returns Array of CAAMP canonical event names supported by Cursor\n * @task T165\n */\n async getSupportedCanonicalEvents(): Promise<string[]> {\n try {\n const { getSupportedEvents } = await import('@cleocode/caamp');\n return getSupportedEvents(PROVIDER_ID) as string[];\n } catch {\n return [...new Set(Object.values(CURSOR_EVENT_MAP))];\n }\n }\n\n /**\n * Retrieve the full provider hook profile from CAAMP.\n *\n * Calls `getProviderHookProfile('cursor')` from the CAAMP normalizer to\n * get the complete profile: hook system type (`config`), config path\n * (`.cursor/hooks.json`), handler types (command, prompt), and all event\n * mappings. Returns null when CAAMP is unavailable at runtime.\n *\n * @returns Provider hook profile or null if CAAMP is unavailable\n * @task T165\n */\n async getProviderProfile(): Promise<unknown | null> {\n try {\n const { getProviderHookProfile } = await import('@cleocode/caamp');\n return getProviderHookProfile(PROVIDER_ID) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Translate a CAAMP canonical event to its Cursor native name via CAAMP.\n *\n * Calls `toNative(canonical, 'cursor')` from the CAAMP normalizer.\n * Returns null for unsupported events or when CAAMP is unavailable.\n *\n * @param canonical - CAAMP canonical event name (e.g. \"PreToolUse\")\n * @returns Cursor native event name (e.g. \"preToolUse\") or null\n * @task T165\n */\n async toNativeEvent(canonical: string): Promise<string | null> {\n try {\n const { toNative } = await import('@cleocode/caamp');\n return toNative(canonical as Parameters<typeof toNative>[0], PROVIDER_ID);\n } catch {\n // Invert the static map as fallback\n const entry = Object.entries(CURSOR_EVENT_MAP).find(([, v]) => v === canonical);\n return entry?.[0] ?? null;\n }\n }\n}\n", "/**\n * Cursor Install Provider\n *\n * Handles CLEO installation into Cursor environments:\n * - Ensures .cursorrules has CLEO @-references (legacy format)\n * - Creates .cursor/rules/cleo.mdc with CLEO references (modern format)\n *\n * Cursor supports two instruction file formats:\n * 1. Legacy: .cursorrules (flat file, project root)\n * 2. Modern: .cursor/rules/*.mdc (MDC format, per-rule files)\n *\n * This provider writes to both for maximum compatibility.\n *\n * @task T5240\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in instruction files to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for Cursor.\n *\n * Manages CLEO's integration with Cursor by:\n * 1. Creating/updating .cursorrules with @-references (legacy)\n * 2. Creating .cursor/rules/cleo.mdc with @-references (modern)\n *\n * @remarks\n * Installation is idempotent and writes to both instruction file formats\n * for maximum compatibility. The legacy `.cursorrules` file is only modified\n * if it already exists (never created from scratch). The modern MDC file\n * is always created or updated to ensure Cursor's rule engine picks it up.\n */\nexport class CursorInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Cursor project.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure instruction files have @-references\n instructionFileUpdated = this.updateInstructionFiles(projectDir);\n if (instructionFileUpdated) {\n details.instructionFiles = this.getUpdatedFileList(projectDir);\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the current Cursor project.\n *\n * Does not remove instruction file references (they are harmless if CLEO is not present).\n */\n async uninstall(): Promise<void> {}\n\n /**\n * Check whether CLEO is installed in the current environment.\n *\n * Checks for .cursor/rules/cleo.mdc or .cursorrules with CLEO references.\n */\n async isInstalled(): Promise<boolean> {\n const mdcPath = join(process.cwd(), '.cursor', 'rules', 'cleo.mdc');\n if (existsSync(mdcPath)) {\n return true;\n }\n\n const rulesPath = join(process.cwd(), '.cursorrules');\n if (existsSync(rulesPath)) {\n try {\n const content = readFileSync(rulesPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure instruction files contain @-references to CLEO.\n *\n * Updates .cursorrules (legacy) and creates .cursor/rules/cleo.mdc (modern).\n *\n * @param projectDir - Project root directory\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFiles(projectDir);\n }\n\n /**\n * Update instruction files with CLEO @-references.\n *\n * Handles both legacy (.cursorrules) and modern (.cursor/rules/cleo.mdc) formats.\n *\n * @returns true if any file was created or modified\n */\n private updateInstructionFiles(projectDir: string): boolean {\n let updated = false;\n\n // Update legacy .cursorrules if it exists\n if (this.updateLegacyRules(projectDir)) {\n updated = true;\n }\n\n // Create/update modern .cursor/rules/cleo.mdc\n if (this.updateModernRules(projectDir)) {\n updated = true;\n }\n\n return updated;\n }\n\n /**\n * Update legacy .cursorrules file with @-references.\n * Only modifies the file if it already exists (does not create it).\n *\n * @returns true if the file was modified\n */\n private updateLegacyRules(projectDir: string): boolean {\n const rulesPath = join(projectDir, '.cursorrules');\n if (!existsSync(rulesPath)) {\n return false;\n }\n\n let content = readFileSync(rulesPath, 'utf-8');\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + missingRefs.join('\\n') + '\\n';\n writeFileSync(rulesPath, content, 'utf-8');\n return true;\n }\n\n /**\n * Create or update .cursor/rules/cleo.mdc with CLEO references.\n *\n * MDC (Markdown Component) format is Cursor's modern rule file format.\n * Each .mdc file in .cursor/rules/ is loaded as a rule set.\n *\n * @returns true if the file was created or modified\n */\n private updateModernRules(projectDir: string): boolean {\n const rulesDir = join(projectDir, '.cursor', 'rules');\n const mdcPath = join(rulesDir, 'cleo.mdc');\n\n const expectedContent = [\n '---',\n 'description: CLEO task management protocol references',\n 'globs: \"**/*\"',\n 'alwaysApply: true',\n '---',\n '',\n ...INSTRUCTION_REFERENCES,\n '',\n ].join('\\n');\n\n if (existsSync(mdcPath)) {\n const existing = readFileSync(mdcPath, 'utf-8');\n if (existing === expectedContent) {\n return false;\n }\n }\n\n mkdirSync(rulesDir, { recursive: true });\n writeFileSync(mdcPath, expectedContent, 'utf-8');\n return true;\n }\n\n /**\n * Get list of instruction files that were updated.\n */\n private getUpdatedFileList(projectDir: string): string[] {\n const files: string[] = [];\n if (existsSync(join(projectDir, '.cursorrules'))) {\n files.push(join(projectDir, '.cursorrules'));\n }\n files.push(join(projectDir, '.cursor', 'rules', 'cleo.mdc'));\n return files;\n }\n}\n", "/**\n * Cursor Adapter\n *\n * Main CLEOProviderAdapter implementation for Cursor AI code editor.\n * Provides install capabilities for CLEO integration. Hooks and spawn\n * are not supported since Cursor lacks CLI-based lifecycle events\n * and subagent spawning.\n *\n * @task T5240\n */\n\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { CursorHookProvider } from './hooks.js';\nimport { CursorInstallProvider } from './install.js';\n\n/**\n * CLEO provider adapter for Cursor AI code editor.\n *\n * Bridges CLEO's adapter system with Cursor's capabilities:\n * - Install: Manages .cursorrules and .cursor/rules/cleo.mdc rule files\n * - Hooks: Stub provider (Cursor has no lifecycle event system)\n * - Spawn: Not supported (Cursor has no CLI for subagent spawning)\n *\n * @remarks\n * Cursor is a GUI-based editor, so many CLI-oriented capabilities\n * (spawn, transport, task sync, context monitor) are unsupported.\n * Integration is primarily through instruction rule files placed in\n * `.cursor/rules/` (modern MDC format) and `.cursorrules` (legacy).\n */\nexport class CursorAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'cursor';\n /** Human-readable provider name. */\n readonly name = 'Cursor';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n // 10/16 canonical events \u2014 derived from getProviderHookProfile('cursor') in CAAMP 1.9.1.\n // PermissionRequest, PreModel, PostModel, PostCompact, Notification, ConfigChange are\n // not supported by Cursor's hook system.\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'PromptSubmit',\n 'ResponseComplete',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'SubagentStart',\n 'SubagentStop',\n 'PreCompact',\n ],\n supportsSpawn: false,\n supportsInstall: true,\n supportsInstructionFiles: true,\n instructionFilePattern: '.cursor/rules/*.mdc',\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: true,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping. */\n hooks: CursorHookProvider;\n /** Install provider for managing rule files. */\n install: CursorInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new CursorHookProvider();\n this.install = new CursorInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * @param projectDir - Root directory of the project\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Cursor is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. .cursor/ configuration directory exists in the project\n * 3. CURSOR_EDITOR env var is set\n *\n * @returns Health status with details about each check\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check for Cursor config directory in the project\n let configExists = false;\n if (this.projectDir) {\n const cursorConfigDir = join(this.projectDir, '.cursor');\n configExists = existsSync(cursorConfigDir);\n details.configDirExists = configExists;\n }\n\n // Check for CURSOR_EDITOR env var\n const editorEnvSet = process.env.CURSOR_EDITOR !== undefined;\n details.editorEnvSet = editorEnvSet;\n\n // Check for legacy .cursorrules file\n if (this.projectDir) {\n const legacyRulesExist = existsSync(join(this.projectDir, '.cursorrules'));\n details.legacyRulesExist = legacyRulesExist;\n }\n\n // Healthy if we detect Cursor presence (config dir or env var)\n const healthy = configExists || editorEnvSet;\n details.detected = healthy;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Cursor AI code editor.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T5240\n */\n\nimport { CursorAdapter } from './adapter.js';\n\nexport { CursorAdapter } from './adapter.js';\nexport { CursorHookProvider } from './hooks.js';\nexport { CursorInstallProvider } from './install.js';\n\nexport default CursorAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the cursor\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link CursorAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/cursor';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n */\nexport function createAdapter(): CursorAdapter {\n return new CursorAdapter();\n}\n", "/**\n * OpenCode Hook Provider\n *\n * Maps OpenCode's native hook events to CAAMP canonical hook events.\n * OpenCode supports 10 of 16 canonical events through its plugin system.\n *\n * Event translation uses CAAMP normalizer APIs:\n * - `toCanonical(nativeName, 'opencode')` for runtime event name resolution\n * - `getSupportedEvents('opencode')` to enumerate supported canonical events\n * - `getProviderHookProfile('opencode')` for the full provider profile\n *\n * OpenCode uses a JavaScript plugin system with event-prefixed names\n * (e.g. `event:session.created`) for some hooks and bare names for others.\n * The map is derived from `getProviderHookProfile('opencode').mappings` in\n * CAAMP 1.9.1. PostToolUseFailure, SubagentStart, SubagentStop, Notification,\n * and ConfigChange are not supported by OpenCode.\n *\n * @task T164\n * @epic T134\n */\n\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/** CAAMP provider identifier for OpenCode. */\nconst PROVIDER_ID = 'opencode' as const;\n\n/**\n * Fallback map from OpenCode native event names to CAAMP canonical names.\n *\n * Derived from `getProviderHookProfile('opencode').mappings` in CAAMP 1.9.1.\n * Covers all 10 supported events. PostToolUseFailure, SubagentStart,\n * SubagentStop, Notification, and ConfigChange are not supported by OpenCode\n * and are absent from this map.\n *\n * OpenCode uses dot-delimited and event-prefixed names (e.g. \"event:session.created\")\n * while CAAMP canonical names are PascalCase (e.g. \"SessionStart\").\n */\nconst OPENCODE_EVENT_MAP: Record<string, string> = {\n // CAAMP: toNative('SessionStart', 'opencode') = 'event:session.created'\n 'event:session.created': 'SessionStart',\n // CAAMP: toNative('SessionEnd', 'opencode') = 'event:session.deleted'\n 'event:session.deleted': 'SessionEnd',\n // CAAMP: toNative('PromptSubmit', 'opencode') = 'chat.message'\n 'chat.message': 'PromptSubmit',\n // CAAMP: toNative('ResponseComplete', 'opencode') = 'event:session.idle'\n 'event:session.idle': 'ResponseComplete',\n // CAAMP: toNative('PreToolUse', 'opencode') = 'tool.execute.before'\n 'tool.execute.before': 'PreToolUse',\n // CAAMP: toNative('PostToolUse', 'opencode') = 'tool.execute.after'\n 'tool.execute.after': 'PostToolUse',\n // CAAMP: toNative('PermissionRequest', 'opencode') = 'permission.ask'\n 'permission.ask': 'PermissionRequest',\n // CAAMP: toNative('PreModel', 'opencode') = 'chat.params'\n 'chat.params': 'PreModel',\n // CAAMP: toNative('PreCompact', 'opencode') = 'experimental.session.compacting'\n 'experimental.session.compacting': 'PreCompact',\n // CAAMP: toNative('PostCompact', 'opencode') = 'event:session.compacted'\n 'event:session.compacted': 'PostCompact',\n};\n\n/**\n * Hook provider for OpenCode.\n *\n * OpenCode registers hooks via its JavaScript plugin system at\n * `.opencode/plugins/`. Supported handler type: plugin (JavaScript).\n *\n * Event mapping is based on `getProviderHookProfile('opencode')` from\n * CAAMP 1.9.1. Async accessors (`getSupportedCanonicalEvents`,\n * `getProviderProfile`) call CAAMP directly when available.\n *\n * Since hooks are registered through the plugin system (managed by the install\n * provider), `registerNativeHooks` and `unregisterNativeHooks` track registration\n * state without performing filesystem operations.\n *\n * @remarks\n * OpenCode uses dot-delimited and `event:`-prefixed event names\n * (e.g. `event:session.created`, `tool.execute.before`) which differ\n * significantly from the PascalCase CAAMP canonical names. The static\n * event map covers all 10 supported events. Async CAAMP accessors\n * (`getSupportedCanonicalEvents`, `getProviderProfile`, `toNativeEvent`)\n * call the normalizer directly when available and fall back to the static map.\n *\n * @task T164\n * @epic T134\n */\nexport class OpenCodeHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map an OpenCode native event name to a CAAMP canonical hook event name.\n *\n * Looks up the native event name in the map derived from\n * `getProviderHookProfile('opencode').mappings` (CAAMP 1.9.1).\n * Returns null for unsupported events (PostToolUseFailure, SubagentStart,\n * SubagentStop, Notification, ConfigChange).\n *\n * @param providerEvent - OpenCode native event (e.g. \"event:session.created\", \"tool.execute.before\")\n * @returns CAAMP canonical event name, or null if unmapped\n * @task T164\n */\n mapProviderEvent(providerEvent: string): string | null {\n return OPENCODE_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For OpenCode, hooks are registered via the plugin system\n * (`.opencode/plugins/`), managed by the install provider.\n * This method marks hooks as registered without performing filesystem operations.\n *\n * Iterating supported events is handled at install time using\n * `getSupportedCanonicalEvents()` to enumerate all 10 supported hooks.\n *\n * @param _projectDir - Project directory (unused; config manages registration)\n * @task T164\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For OpenCode, this is a no-op since hooks are managed through the plugin\n * system. Unregistration happens via the install provider's uninstall method.\n *\n * @task T164\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via `registerNativeHooks`.\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the native\u2192canonical event mapping for introspection and debugging.\n *\n * Returns the map derived from `getProviderHookProfile('opencode').mappings`\n * (CAAMP 1.9.1). Use `getSupportedCanonicalEvents()` to enumerate canonical\n * names via live CAAMP APIs.\n *\n * @returns Immutable record of native event name \u2192 canonical event name\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...OPENCODE_EVENT_MAP };\n }\n\n /**\n * Enumerate supported canonical events via CAAMP's `getSupportedEvents()`.\n *\n * Calls `getSupportedEvents('opencode')` from the CAAMP normalizer to get the\n * authoritative list. OpenCode supports 10 of 16 canonical events via its\n * plugin system. Falls back to the values of the static event map when\n * CAAMP is unavailable at runtime.\n *\n * @returns Array of CAAMP canonical event names supported by OpenCode\n * @task T164\n */\n async getSupportedCanonicalEvents(): Promise<string[]> {\n try {\n const { getSupportedEvents } = await import('@cleocode/caamp');\n return getSupportedEvents(PROVIDER_ID) as string[];\n } catch {\n return [...new Set(Object.values(OPENCODE_EVENT_MAP))];\n }\n }\n\n /**\n * Retrieve the full provider hook profile from CAAMP.\n *\n * Calls `getProviderHookProfile('opencode')` from the CAAMP normalizer to\n * get the complete profile: hook system type (`plugin`), config path\n * (`.opencode/plugins/`), handler types, and all event mappings.\n * Returns null when CAAMP is unavailable at runtime.\n *\n * @returns Provider hook profile or null if CAAMP is unavailable\n * @task T164\n */\n async getProviderProfile(): Promise<unknown | null> {\n try {\n const { getProviderHookProfile } = await import('@cleocode/caamp');\n return getProviderHookProfile(PROVIDER_ID) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Translate a CAAMP canonical event to its OpenCode native name via CAAMP.\n *\n * Calls `toNative(canonical, 'opencode')` from the CAAMP normalizer.\n * Returns null for unsupported events or when CAAMP is unavailable.\n *\n * @param canonical - CAAMP canonical event name (e.g. \"PreToolUse\")\n * @returns OpenCode native event name or null\n * @task T164\n */\n async toNativeEvent(canonical: string): Promise<string | null> {\n try {\n const { toNative } = await import('@cleocode/caamp');\n return toNative(canonical as Parameters<typeof toNative>[0], PROVIDER_ID);\n } catch {\n // Invert the static map as fallback\n const entry = Object.entries(OPENCODE_EVENT_MAP).find(([, v]) => v === canonical);\n return entry?.[0] ?? null;\n }\n }\n}\n", "/**\n * OpenCode Install Provider\n *\n * Handles CLEO installation into OpenCode environments:\n * - Ensures AGENTS.md has CLEO @-references\n *\n * @task T5240\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for OpenCode.\n *\n * Manages CLEO's integration with OpenCode by:\n * 1. Ensuring AGENTS.md contains @-references to CLEO instruction files\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. Only AGENTS.md is managed; OpenCode's\n * plugin system is handled separately by the hook provider.\n */\nexport class OpenCodeInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into an OpenCode project.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure AGENTS.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the current OpenCode project.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n */\n async uninstall(): Promise<void> {}\n\n /**\n * Check whether CLEO is installed in the current environment.\n *\n * Checks for CLEO references in AGENTS.md.\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update AGENTS.md with CLEO @-references.\n *\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const agentsMdPath = join(projectDir, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsMdPath)) {\n content = readFileSync(agentsMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n // Append missing references\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n // Create new AGENTS.md with references\n content = refsBlock + '\\n';\n }\n\n writeFileSync(agentsMdPath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * OpenCode Spawn Provider\n *\n * Implements AdapterSpawnProvider for OpenCode CLI.\n * Migrated from src/core/spawn/adapters/opencode-adapter.ts\n *\n * Uses `opencode run --agent ... --format json` to spawn subagent\n * processes. Processes run detached and are tracked by PID for\n * listing and termination.\n *\n * @task T5240\n */\n\nimport { exec, spawn as nodeSpawn } from 'node:child_process';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/contracts';\n\nconst execAsync = promisify(exec);\n\n/** Name used for the CLEO subagent definition in OpenCode's agent directory. */\nconst OPENCODE_SUBAGENT_NAME = 'cleo-subagent';\n\n/** Fallback agent name when custom agent definition cannot be created. */\nconst OPENCODE_FALLBACK_AGENT = 'general';\n\n/** Internal tracking entry for a spawned process. */\ninterface TrackedProcess {\n pid: number;\n taskId: string;\n startTime: string;\n}\n\n/**\n * Build the markdown content for an OpenCode agent definition file.\n *\n * OpenCode agents are defined as markdown files with YAML frontmatter\n * in the .opencode/agent/ directory.\n *\n * @remarks\n * The generated markdown uses YAML frontmatter with `mode: subagent`\n * and `hidden: true` so the agent does not appear in OpenCode's\n * interactive agent selection menu.\n *\n * @param description - Agent description for frontmatter\n * @param instructions - Markdown instructions body\n * @returns Complete agent definition markdown with YAML frontmatter\n *\n * @example\n * ```typescript\n * import { buildOpenCodeAgentMarkdown } from '@cleocode/adapters/providers/opencode/spawn';\n *\n * const md = buildOpenCodeAgentMarkdown(\n * 'CLEO task executor',\n * '# Subagent\\n\\nExecute the delegated task.',\n * );\n * ```\n */\nexport function buildOpenCodeAgentMarkdown(description: string, instructions: string): string {\n const normalizedDesc = description.replace(/\\s+/g, ' ').trim();\n return [\n '---',\n `description: ${JSON.stringify(normalizedDesc)}`,\n 'mode: subagent',\n 'hidden: true',\n '---',\n '',\n instructions.trim(),\n '',\n ].join('\\n');\n}\n\n/**\n * Ensure the CLEO subagent definition exists in the project's\n * .opencode/agent/ directory.\n *\n * Creates or updates the agent definition file if the content has changed.\n *\n * @param workingDirectory - Project root directory\n * @returns The agent name to use for spawning\n */\nasync function ensureSubagentDefinition(\n workingDirectory: string,\n enrichedInstructions?: string,\n): Promise<string> {\n const agentDir = join(workingDirectory, '.opencode', 'agent');\n const agentPath = join(agentDir, `${OPENCODE_SUBAGENT_NAME}.md`);\n const description = 'CLEO task executor with protocol compliance and CANT context.';\n const instructions =\n enrichedInstructions ??\n [\n '# CLEO Subagent',\n '',\n 'You are a CLEO subagent executing a delegated task.',\n 'Follow the CLEO protocol and complete the assigned work.',\n '',\n '@~/.cleo/templates/CLEO-INJECTION.md',\n ].join('\\n');\n\n const content = buildOpenCodeAgentMarkdown(description, instructions);\n\n await mkdir(agentDir, { recursive: true });\n\n let existing: string | null = null;\n try {\n existing = await readFile(agentPath, 'utf-8');\n } catch {\n existing = null;\n }\n\n if (existing !== content) {\n await writeFile(agentPath, content, 'utf-8');\n }\n\n return OPENCODE_SUBAGENT_NAME;\n}\n\n/**\n * Spawn provider for OpenCode.\n *\n * Spawns detached OpenCode CLI processes for subagent execution.\n * Each spawn ensures a CLEO subagent definition exists, then runs\n * `opencode run --format json --agent <name> --title <title> <prompt>`\n * as a detached, unref'd child process.\n *\n * @remarks\n * Before spawning, the provider ensures a `cleo-subagent` agent definition\n * exists in `.opencode/agent/`. If the definition cannot be created, it\n * falls back to the built-in `general` agent. Processes are tracked by\n * instance ID in an in-memory map and verified via `kill(pid, 0)` liveness\n * checks.\n */\nexport class OpenCodeSpawnProvider implements AdapterSpawnProvider {\n /** Map of instance IDs to tracked process info. */\n private processMap = new Map<string, TrackedProcess>();\n\n /**\n * Check if the OpenCode CLI is available in PATH.\n *\n * @returns true if `opencode` is found via `which`\n */\n async canSpawn(): Promise<boolean> {\n try {\n await execAsync('which opencode');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Spawn a subagent via OpenCode CLI.\n *\n * Ensures the CLEO subagent definition exists in the project's\n * .opencode/agent/ directory, then spawns a detached OpenCode\n * process. The process runs independently of the parent.\n *\n * @param context - Spawn context with taskId, prompt, and options\n * @returns Spawn result with instance ID and status\n */\n async spawn(context: SpawnContext): Promise<SpawnResult> {\n const instanceId = `opencode-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const startTime = new Date().toISOString();\n const workingDirectory = context.workingDirectory ?? process.cwd();\n\n try {\n // Enrich prompt with CANT bundle, memory bridge, and mental model (T555).\n // Best-effort: if CANT context is unavailable, the raw prompt is used.\n let enrichedInstructions: string | undefined;\n try {\n const { buildCantEnrichedPrompt } = await import('../../cant-context.js');\n enrichedInstructions = await buildCantEnrichedPrompt({\n projectDir: workingDirectory,\n basePrompt: context.prompt,\n agentName: (context.options?.agentName as string) ?? undefined,\n });\n } catch {\n // CANT enrichment unavailable \u2014 use raw prompt\n }\n\n let agentName: string;\n try {\n agentName = await ensureSubagentDefinition(workingDirectory, enrichedInstructions);\n } catch {\n agentName = OPENCODE_FALLBACK_AGENT;\n }\n\n const child = nodeSpawn(\n 'opencode',\n [\n 'run',\n '--format',\n 'json',\n '--agent',\n agentName,\n '--title',\n `CLEO ${context.taskId}`,\n context.prompt,\n ],\n {\n cwd: workingDirectory,\n detached: true,\n stdio: 'ignore',\n },\n );\n\n child.unref();\n\n if (child.pid) {\n this.processMap.set(instanceId, {\n pid: child.pid,\n taskId: context.taskId,\n startTime,\n });\n }\n\n child.on('exit', () => {\n this.processMap.delete(instanceId);\n });\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'opencode',\n status: 'running',\n startTime,\n };\n } catch {\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'opencode',\n status: 'failed',\n startTime,\n endTime: new Date().toISOString(),\n };\n }\n }\n\n /**\n * List currently running OpenCode subagent processes.\n *\n * Checks each tracked process via kill(pid, 0) to verify it is still alive.\n * Dead processes are automatically cleaned from the tracking map.\n *\n * @returns Array of spawn results for running processes\n */\n async listRunning(): Promise<SpawnResult[]> {\n const running: SpawnResult[] = [];\n\n for (const [instanceId, tracked] of this.processMap.entries()) {\n try {\n process.kill(tracked.pid, 0);\n running.push({\n instanceId,\n taskId: tracked.taskId,\n providerId: 'opencode',\n status: 'running',\n startTime: tracked.startTime,\n });\n } catch {\n this.processMap.delete(instanceId);\n }\n }\n\n return running;\n }\n\n /**\n * Terminate a running spawn by instance ID.\n *\n * Sends SIGTERM to the tracked process. If the process is not found\n * or has already exited, this is a no-op.\n *\n * @param instanceId - ID of the spawn instance to terminate\n */\n async terminate(instanceId: string): Promise<void> {\n const tracked = this.processMap.get(instanceId);\n if (!tracked) return;\n\n try {\n process.kill(tracked.pid, 'SIGTERM');\n } catch {\n // Process may have already exited\n }\n this.processMap.delete(instanceId);\n }\n}\n", "/**\n * OpenCode Adapter\n *\n * Main CLEOProviderAdapter implementation for OpenCode AI coding assistant.\n * Provides spawn, hooks, and install capabilities for CLEO integration.\n *\n * @task T5240\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { OpenCodeHookProvider } from './hooks.js';\nimport { OpenCodeInstallProvider } from './install.js';\nimport { OpenCodeSpawnProvider } from './spawn.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for OpenCode AI coding assistant.\n *\n * Bridges CLEO's adapter system with OpenCode's native capabilities:\n * - Hooks: Maps OpenCode events (session.start, tool.complete, etc.) to CAAMP events\n * - Spawn: Launches subagent processes via the `opencode` CLI\n * - Install: Ensures AGENTS.md references for CLEO instruction files\n *\n * @remarks\n * OpenCode is the second-most feature-complete adapter after Claude Code,\n * supporting 10 canonical events through its JavaScript plugin system,\n * subagent spawning via the `opencode run` CLI command, and instruction\n * file management via AGENTS.md. It uniquely supports PreModel via the\n * `chat.params` event, which allows pre-inference parameter injection.\n */\nexport class OpenCodeAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'opencode';\n /** Human-readable provider name. */\n readonly name = 'OpenCode';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n // 10/16 canonical events \u2014 derived from getProviderHookProfile('opencode') in CAAMP 1.9.1.\n // PostToolUseFailure, SubagentStart, SubagentStop, Notification, ConfigChange are\n // not supported by OpenCode's plugin system.\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'PromptSubmit',\n 'ResponseComplete',\n 'PreToolUse',\n 'PostToolUse',\n 'PermissionRequest',\n 'PreModel',\n 'PreCompact',\n 'PostCompact',\n ],\n supportsSpawn: true,\n supportsInstall: true,\n supportsInstructionFiles: true,\n instructionFilePattern: 'AGENTS.md',\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: true,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping via OpenCode's plugin system. */\n hooks: OpenCodeHookProvider;\n /** Spawn provider for launching subagent processes via `opencode run`. */\n spawn: OpenCodeSpawnProvider;\n /** Install provider for managing AGENTS.md instruction files. */\n install: OpenCodeInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new OpenCodeHookProvider();\n this.spawn = new OpenCodeSpawnProvider();\n this.install = new OpenCodeInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * Validates the environment by checking for the OpenCode CLI\n * and OpenCode configuration directory.\n *\n * @param projectDir - Root directory of the project\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify OpenCode is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. OpenCode CLI is available in PATH\n * 3. .opencode/ configuration directory exists in the project\n *\n * @returns Health status with details about each check\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check OpenCode CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which opencode');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for OpenCode config directory in the project\n if (this.projectDir) {\n const openCodeConfigDir = join(this.projectDir, '.opencode');\n const configExists = existsSync(openCodeConfigDir);\n details.configDirExists = configExists;\n }\n\n // Check for OPENCODE_VERSION env var\n const versionEnvSet = process.env.OPENCODE_VERSION !== undefined;\n details.versionEnvSet = versionEnvSet;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for OpenCode AI coding assistant.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T5240\n */\n\nimport { OpenCodeAdapter } from './adapter.js';\n\nexport { OpenCodeAdapter } from './adapter.js';\nexport { OpenCodeHookProvider } from './hooks.js';\nexport { OpenCodeInstallProvider } from './install.js';\nexport { OpenCodeSpawnProvider } from './spawn.js';\n\nexport default OpenCodeAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the opencode\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link OpenCodeAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/opencode';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n */\nexport function createAdapter(): OpenCodeAdapter {\n return new OpenCodeAdapter();\n}\n", "/**\n * Pi Hook Provider\n *\n * Maps Pi coding agent native event names to CAAMP canonical hook events.\n * Pi supports 11 of 16 canonical events through its extension/event system.\n *\n * Event translation uses CAAMP normalizer APIs:\n * - `toCanonical(nativeName, 'pi')` for runtime event name resolution\n * - `getSupportedEvents('pi')` to enumerate supported canonical events\n * - `getProviderHookProfile('pi')` for the full provider profile\n *\n * A static map derived from CAAMP hook-mappings.json piEventCatalog is\n * maintained as a fallback for environments where CAAMP's runtime\n * resolution is unavailable.\n *\n * Mappings (11/16 supported):\n * session_start \u2192 SessionStart\n * session_shutdown \u2192 SessionEnd\n * input \u2192 PromptSubmit\n * turn_end \u2192 Notification (assistant turn complete)\n * tool_call \u2192 PreToolUse\n * tool_result \u2192 PostToolUse\n * before_agent_start \u2192 SubagentStart\n * agent_end \u2192 SubagentStop\n * before_provider_request \u2192 PreModel\n * context \u2192 PreCompact (context assembly = pre-compaction proxy)\n *\n * Unsupported (5/16):\n * ResponseComplete, PostToolUseFailure, PermissionRequest,\n * PostModel, PostCompact, ConfigChange\n *\n * @task T553\n */\n\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/** CAAMP provider identifier for Pi. */\nconst PROVIDER_ID = 'pi' as const;\n\n/**\n * Fallback map from Pi native event names to CAAMP canonical names.\n *\n * Derived from the `piEventCatalog` block in CAAMP hook-mappings.json.\n * Covers all 11 supported events. ResponseComplete, PostToolUseFailure,\n * PermissionRequest, PostModel, PostCompact, and ConfigChange are not\n * supported by Pi and are absent from this map.\n *\n * Used as fallback when CAAMP runtime is unavailable, and as the\n * synchronous implementation of `mapProviderEvent()`.\n */\nconst PI_EVENT_MAP: Record<string, string> = {\n // piEventCatalog: session_start \u2192 SessionStart\n session_start: 'SessionStart',\n // piEventCatalog: session_shutdown \u2192 SessionEnd\n session_shutdown: 'SessionEnd',\n // piEventCatalog: input \u2192 PromptSubmit\n input: 'PromptSubmit',\n // piEventCatalog: turn_end \u2192 Notification (assistant turn complete)\n turn_end: 'Notification',\n // piEventCatalog: tool_call \u2192 PreToolUse\n tool_call: 'PreToolUse',\n // piEventCatalog: tool_execution_start \u2192 PreToolUse (duplicate path)\n tool_execution_start: 'PreToolUse',\n // piEventCatalog: tool_result \u2192 PostToolUse\n tool_result: 'PostToolUse',\n // piEventCatalog: tool_execution_end \u2192 PostToolUse (duplicate path)\n tool_execution_end: 'PostToolUse',\n // piEventCatalog: before_agent_start \u2192 SubagentStart\n before_agent_start: 'SubagentStart',\n // piEventCatalog: agent_end \u2192 SubagentStop\n agent_end: 'SubagentStop',\n // piEventCatalog: before_provider_request \u2192 PreModel\n before_provider_request: 'PreModel',\n // piEventCatalog: context \u2192 PreCompact (context assembly is the pre-compaction proxy for Pi)\n context: 'PreCompact',\n};\n\n/**\n * Hook provider for Pi coding agent.\n *\n * Pi registers hooks via its TypeScript extension system. Extensions are\n * loaded from `~/.pi/agent/extensions/*.ts` (global) or\n * `<projectDir>/.pi/extensions/*.ts` (project scope).\n *\n * Event mapping is based on the `piEventCatalog` block in CAAMP\n * hook-mappings.json. Async accessors (`getSupportedCanonicalEvents`,\n * `getProviderProfile`) call CAAMP directly when available.\n *\n * Since hooks are registered through the extension system (managed by the\n * install provider), `registerNativeHooks` and `unregisterNativeHooks`\n * track registration state without performing filesystem operations.\n *\n * @remarks\n * Pi is CAAMP's first-class primary harness (ADR-035). Its native events\n * use snake_case (e.g. `session_start`, `tool_call`) unlike the PascalCase\n * CAAMP canonical names. The static event map covers all 11 supported events.\n * Async CAAMP accessors fall back to the static map when CAAMP is unavailable.\n *\n * Pi does NOT support ResponseComplete, PostToolUseFailure, PermissionRequest,\n * PostModel, PostCompact, or ConfigChange canonical events.\n *\n * All hook dispatch is best-effort \u2014 hooks MUST never block or crash Pi.\n *\n * @task T553\n */\nexport class PiHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Pi native event name to a CAAMP canonical hook event name.\n *\n * Looks up the native event name in the map derived from the\n * `piEventCatalog` block in CAAMP hook-mappings.json.\n * Returns null for unrecognised or unsupported events.\n *\n * @param providerEvent - Pi native event (e.g. \"session_start\", \"tool_call\")\n * @returns CAAMP canonical event name, or null if unmapped\n * @task T553\n */\n mapProviderEvent(providerEvent: string): string | null {\n return PI_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For Pi, hooks are registered via the extension system, managed by\n * the install provider. This method marks hooks as registered without\n * performing filesystem operations.\n *\n * Iterating supported events is handled at install time using\n * `getSupportedCanonicalEvents()` to enumerate all 11 supported hooks.\n *\n * @param _projectDir - Project directory (unused; Pi uses extension system)\n * @task T553\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For Pi, this is a no-op since hooks are managed through the extension\n * system. Unregistration happens via the install provider's uninstall method.\n *\n * @task T553\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via `registerNativeHooks`.\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the native\u2192canonical event mapping for introspection and debugging.\n *\n * Returns the map derived from the `piEventCatalog` block in CAAMP\n * hook-mappings.json. Use `getSupportedCanonicalEvents()` to enumerate\n * canonical names via live CAAMP APIs.\n *\n * @returns Immutable record of native event name \u2192 canonical event name\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...PI_EVENT_MAP };\n }\n\n /**\n * Enumerate supported canonical events via CAAMP's `getSupportedEvents()`.\n *\n * Calls `getSupportedEvents('pi')` from the CAAMP normalizer to get the\n * authoritative list. Pi supports 11 of 16 canonical events. Falls back\n * to the unique values of the static event map when CAAMP is unavailable.\n *\n * @returns Array of CAAMP canonical event names supported by Pi\n * @task T553\n */\n async getSupportedCanonicalEvents(): Promise<string[]> {\n try {\n const { getSupportedEvents } = await import('@cleocode/caamp');\n return getSupportedEvents(PROVIDER_ID) as string[];\n } catch {\n return [...new Set(Object.values(PI_EVENT_MAP))];\n }\n }\n\n /**\n * Retrieve the full provider hook profile from CAAMP.\n *\n * Calls `getProviderHookProfile('pi')` from the CAAMP normalizer to get\n * the complete profile including hook system type, config path, handler\n * types, and all event mappings. Returns null when CAAMP is unavailable.\n *\n * @returns Provider hook profile or null if CAAMP is unavailable\n * @task T553\n */\n async getProviderProfile(): Promise<unknown | null> {\n try {\n const { getProviderHookProfile } = await import('@cleocode/caamp');\n return getProviderHookProfile(PROVIDER_ID) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Translate a CAAMP canonical event to its Pi native name via CAAMP.\n *\n * Calls `toNative(canonical, 'pi')` from the CAAMP normalizer.\n * Returns null for unsupported events or when CAAMP is unavailable.\n *\n * @param canonical - CAAMP canonical event name (e.g. \"PreToolUse\")\n * @returns Pi native event name or null\n * @task T553\n */\n async toNativeEvent(canonical: string): Promise<string | null> {\n try {\n const { toNative } = await import('@cleocode/caamp');\n return toNative(canonical as Parameters<typeof toNative>[0], PROVIDER_ID);\n } catch {\n // Invert the static map as fallback \u2014 return the first match\n const entry = Object.entries(PI_EVENT_MAP).find(([, v]) => v === canonical);\n return entry?.[0] ?? null;\n }\n }\n}\n", "/**\n * Pi Install Provider\n *\n * Handles CLEO installation into Pi coding agent environments:\n * - Ensures AGENTS.md has CLEO @-references (project and global scope)\n * - Manages Pi settings.json to register CLEO extension path\n *\n * Pi uses AGENTS.md (not CLAUDE.md) as its instruction file. The global\n * instruction file lives at `~/.pi/agent/AGENTS.md`; the project-level\n * file lives at `<projectDir>/AGENTS.md`.\n *\n * Detection: Pi is detected by the `PI_CODING_AGENT_DIR` or `PI_HOME`\n * environment variables, or by presence of `~/.pi/agent/` directory.\n *\n * @task T553\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Resolve the Pi global state root directory.\n *\n * Honours `PI_CODING_AGENT_DIR` env var when set (with `~` expansion),\n * then `PI_HOME`, then falls back to `~/.pi/agent`.\n */\nfunction getPiAgentDir(): string {\n const env = process.env['PI_CODING_AGENT_DIR'];\n if (env !== undefined && env.length > 0) {\n if (env === '~') return homedir();\n if (env.startsWith('~/')) return join(homedir(), env.slice(2));\n return env;\n }\n const piHome = process.env['PI_HOME'];\n if (piHome !== undefined && piHome.length > 0) {\n return join(piHome, 'agent');\n }\n return join(homedir(), '.pi', 'agent');\n}\n\n/**\n * Install provider for Pi coding agent.\n *\n * Manages CLEO's integration with Pi by:\n * 1. Ensuring project AGENTS.md contains @-references to CLEO instruction files\n * 2. Ensuring global AGENTS.md (~/.pi/agent/AGENTS.md) contains @-references\n *\n * @remarks\n * Installation is idempotent \u2014 running install multiple times on the same\n * project produces the same result. Pi's AGENTS.md is auto-discovered from\n * the working directory upwards, so project-level injection is the primary\n * mechanism. Global injection ensures fresh sessions always load CLEO context.\n */\nexport class PiInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Pi coding agent project.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure project AGENTS.md has @-references\n const projectUpdated = this.updateInstructionFile(projectDir, 'AGENTS.md');\n if (projectUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n // Step 2: Ensure global AGENTS.md has @-references (best-effort)\n let globalUpdated = false;\n try {\n const globalDir = getPiAgentDir();\n globalUpdated = this.updateInstructionFile(globalDir, 'AGENTS.md');\n if (globalUpdated) {\n details.globalInstructionFile = join(globalDir, 'AGENTS.md');\n }\n } catch {\n // Global install is best-effort \u2014 never block project install\n }\n\n const instructionFileUpdated = projectUpdated || globalUpdated;\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the current Pi project.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n */\n async uninstall(): Promise<void> {}\n\n /**\n * Check whether CLEO is installed in the current environment.\n *\n * Checks for CLEO references in the project AGENTS.md.\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n // Also check global AGENTS.md\n try {\n const globalPath = join(getPiAgentDir(), 'AGENTS.md');\n if (existsSync(globalPath)) {\n const content = readFileSync(globalPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n }\n } catch {\n // Fall through\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir, 'AGENTS.md');\n }\n\n /**\n * Update an instruction file with CLEO @-references.\n *\n * @param dir - Directory containing the instruction file\n * @param filename - Name of the instruction file (e.g. \"AGENTS.md\")\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(dir: string, filename: string): boolean {\n const filePath = join(dir, filename);\n let content = '';\n let existed = false;\n\n if (existsSync(filePath)) {\n content = readFileSync(filePath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n // Append missing references\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n // Create new file with references \u2014 ensure parent dir exists\n mkdirSync(dir, { recursive: true });\n content = refsBlock + '\\n';\n }\n\n writeFileSync(filePath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * Pi Spawn Provider\n *\n * Implements AdapterSpawnProvider for Pi coding agent CLI.\n *\n * Uses the `pi` CLI (or the path from `PI_CLI_PATH` env var) to spawn\n * subagent processes with prompts written to temporary files. Processes\n * run detached and are tracked by PID for listing and termination.\n *\n * Pi detection: `PI_CLI_PATH` env var or `which pi`.\n *\n * @task T553\n */\n\nimport { exec, spawn as nodeSpawn } from 'node:child_process';\nimport { unlink, writeFile } from 'node:fs/promises';\nimport { promisify } from 'node:util';\nimport type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/contracts';\nimport { getErrorMessage } from '@cleocode/contracts';\n\nconst execAsync = promisify(exec);\n\n/** Internal tracking entry for a spawned process. */\ninterface TrackedProcess {\n pid: number;\n taskId: string;\n startTime: string;\n}\n\n/**\n * Resolve the Pi CLI executable path.\n *\n * Honours `PI_CLI_PATH` env var when set, otherwise uses `pi` (expects\n * the binary on PATH).\n */\nfunction getPiCliPath(): string {\n return process.env['PI_CLI_PATH'] ?? 'pi';\n}\n\n/**\n * Spawn provider for Pi coding agent.\n *\n * Spawns detached Pi CLI processes for subagent execution. Each spawn\n * writes its prompt to a temporary file, then runs the Pi CLI with the\n * prompt file as the primary argument as a detached, unref'd child process.\n *\n * @remarks\n * Prompts are written to temporary files under `/tmp/` and cleaned up\n * after the child process exits. Processes are tracked by instance ID in\n * an in-memory map and verified via `kill(pid, 0)` liveness checks.\n * All failures are best-effort and non-blocking.\n */\nexport class PiSpawnProvider implements AdapterSpawnProvider {\n /** Map of instance IDs to tracked process info. */\n private processMap = new Map<string, TrackedProcess>();\n\n /**\n * Check if the Pi CLI is available.\n *\n * Checks `PI_CLI_PATH` env var first, then tries `which pi`.\n *\n * @returns true if the Pi CLI is accessible\n */\n async canSpawn(): Promise<boolean> {\n const cliPath = getPiCliPath();\n try {\n if (cliPath !== 'pi') {\n // Custom path \u2014 check if it exists\n const { stdout } = await execAsync(`test -x \"${cliPath}\" && echo ok`);\n return stdout.trim() === 'ok';\n }\n await execAsync('which pi');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Spawn a subagent via Pi CLI.\n *\n * Writes the prompt to a temporary file and spawns a detached Pi\n * process. The process runs independently of the parent.\n *\n * @param context - Spawn context with taskId, prompt, and options\n * @returns Spawn result with instance ID and status\n */\n async spawn(context: SpawnContext): Promise<SpawnResult> {\n const instanceId = `pi-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const startTime = new Date().toISOString();\n let tmpFile: string | undefined;\n\n try {\n tmpFile = `/tmp/pi-spawn-${instanceId}.txt`;\n await writeFile(tmpFile, context.prompt, 'utf-8');\n\n const cliPath = getPiCliPath();\n const args = [tmpFile];\n const spawnOpts: Parameters<typeof nodeSpawn>[2] = {\n detached: true,\n stdio: 'ignore',\n };\n\n if (context.workingDirectory) {\n spawnOpts.cwd = context.workingDirectory;\n }\n\n const child = nodeSpawn(cliPath, args, spawnOpts);\n child.unref();\n\n if (child.pid) {\n this.processMap.set(instanceId, {\n pid: child.pid,\n taskId: context.taskId,\n startTime,\n });\n }\n\n const capturedTmpFile = tmpFile;\n child.on('exit', async () => {\n this.processMap.delete(instanceId);\n try {\n await unlink(capturedTmpFile);\n } catch {\n // Ignore cleanup errors\n }\n });\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'pi',\n status: 'running',\n startTime,\n };\n } catch (error) {\n console.error(`[PiSpawnProvider] Failed to spawn: ${getErrorMessage(error)}`);\n\n if (tmpFile) {\n try {\n await unlink(tmpFile);\n } catch {\n // Ignore cleanup errors\n }\n }\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'pi',\n status: 'failed',\n startTime,\n endTime: new Date().toISOString(),\n error: getErrorMessage(error),\n };\n }\n }\n\n /**\n * List currently running Pi subagent processes.\n *\n * Checks each tracked process via kill(pid, 0) to verify it is still alive.\n * Dead processes are automatically cleaned from the tracking map.\n *\n * @returns Array of spawn results for running processes\n */\n async listRunning(): Promise<SpawnResult[]> {\n const running: SpawnResult[] = [];\n\n for (const [instanceId, tracked] of this.processMap.entries()) {\n try {\n process.kill(tracked.pid, 0);\n running.push({\n instanceId,\n taskId: tracked.taskId,\n providerId: 'pi',\n status: 'running',\n startTime: tracked.startTime,\n });\n } catch {\n this.processMap.delete(instanceId);\n }\n }\n\n return running;\n }\n\n /**\n * Terminate a running spawn by instance ID.\n *\n * Sends SIGTERM to the tracked process. If the process is not found\n * or has already exited, this is a no-op.\n *\n * @param instanceId - ID of the spawn instance to terminate\n */\n async terminate(instanceId: string): Promise<void> {\n const tracked = this.processMap.get(instanceId);\n if (!tracked) return;\n\n try {\n process.kill(tracked.pid, 'SIGTERM');\n } catch {\n // Process may have already exited\n }\n this.processMap.delete(instanceId);\n }\n}\n", "/**\n * Pi Adapter\n *\n * Main CLEOProviderAdapter implementation for the Pi coding agent\n * (https://github.com/badlogic/pi-mono). Pi is CAAMP's first-class primary\n * harness and owns skills, instructions, extensions, and subagent spawning\n * through native filesystem conventions.\n *\n * Pi supports 11 of 16 CAAMP canonical events through its TypeScript extension\n * system (session_start, session_shutdown, input, turn_end, tool_call,\n * tool_result, before_agent_start, agent_end, before_provider_request, context).\n *\n * Detection: PI_CLI_PATH env var, PI_CODING_AGENT_DIR env var, PI_HOME env var,\n * or presence of ~/.pi/agent/ directory.\n *\n * @task T553\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { PiHookProvider } from './hooks.js';\nimport { PiInstallProvider } from './install.js';\nimport { PiSpawnProvider } from './spawn.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * Resolve the Pi global state root directory.\n *\n * Honours `PI_CODING_AGENT_DIR` env var when set (with `~` expansion),\n * then `PI_HOME`, then falls back to `~/.pi/agent`.\n */\nfunction getPiAgentDir(): string {\n const env = process.env['PI_CODING_AGENT_DIR'];\n if (env !== undefined && env.length > 0) {\n if (env === '~') return homedir();\n if (env.startsWith('~/')) return join(homedir(), env.slice(2));\n return env;\n }\n const piHome = process.env['PI_HOME'];\n if (piHome !== undefined && piHome.length > 0) {\n return join(piHome, 'agent');\n }\n return join(homedir(), '.pi', 'agent');\n}\n\n/**\n * CLEO provider adapter for Pi coding agent.\n *\n * Bridges CLEO's adapter system with Pi's native capabilities:\n * - Hooks: Maps Pi events (session_start, tool_call, etc.) to CAAMP events\n * - Spawn: Launches subagent processes via the `pi` CLI\n * - Install: Manages AGENTS.md instruction files and global Pi state root\n *\n * @remarks\n * Pi is CAAMP's first-class primary harness (ADR-035). It supports 11 of 16\n * canonical hook events through its TypeScript extension system. Extensions\n * live at `~/.pi/agent/extensions/` (global) or `<projectDir>/.pi/extensions/`\n * (project scope).\n *\n * The session_shutdown event handler in `cleo-cant-bridge.ts` clears module\n * cache. The adapter's hook mapping ensures that Pi's session lifecycle events\n * are visible in the CAAMP event stream for downstream listeners (e.g. memory\n * refresh triggers, backup triggers).\n *\n * Detection hierarchy (first match wins):\n * 1. `PI_CLI_PATH` env var set\n * 2. `PI_CODING_AGENT_DIR` env var set\n * 3. `PI_HOME` env var set\n * 4. `~/.pi/agent/` directory exists\n * 5. `pi` CLI available in PATH\n */\nexport class PiAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'pi';\n /** Human-readable provider name. */\n readonly name = 'Pi';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n // 11/16 canonical events \u2014 derived from piEventCatalog in CAAMP hook-mappings.json.\n // ResponseComplete, PostToolUseFailure, PermissionRequest, PostModel, PostCompact,\n // and ConfigChange are not supported by Pi's extension system.\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'PromptSubmit',\n 'Notification',\n 'PreToolUse',\n 'PostToolUse',\n 'SubagentStart',\n 'SubagentStop',\n 'PreModel',\n 'PreCompact',\n ],\n supportsSpawn: true,\n supportsInstall: true,\n supportsInstructionFiles: true,\n instructionFilePattern: 'AGENTS.md',\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: true,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping and registration. */\n hooks: PiHookProvider;\n /** Spawn provider for launching subagent processes via `pi` CLI. */\n spawn: PiSpawnProvider;\n /** Install provider for managing AGENTS.md instruction files. */\n install: PiInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new PiHookProvider();\n this.spawn = new PiSpawnProvider();\n this.install = new PiInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * Validates the environment by checking for the Pi CLI and Pi state root.\n *\n * @param projectDir - Root directory of the project\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Pi is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Pi CLI is available (via PI_CLI_PATH or `which pi`)\n * 3. Pi global state root (~/.pi/agent/ or PI_CODING_AGENT_DIR) exists\n *\n * @returns Health status with details about each check\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Pi CLI availability\n let cliAvailable = false;\n const cliPath = process.env['PI_CLI_PATH'] ?? 'pi';\n try {\n if (cliPath !== 'pi') {\n const { stdout } = await execAsync(`test -x \"${cliPath}\" && echo ok`);\n cliAvailable = stdout.trim() === 'ok';\n details.cliPath = cliPath;\n } else {\n const { stdout } = await execAsync('which pi');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n }\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Pi global state root\n const agentDir = getPiAgentDir();\n const agentDirExists = existsSync(agentDir);\n details.agentDirExists = agentDirExists;\n details.agentDir = agentDir;\n\n // Check for project-level .pi/ directory\n if (this.projectDir) {\n const projectPiDir = join(this.projectDir, '.pi');\n details.projectPiDirExists = existsSync(projectPiDir);\n }\n\n // Check detection env vars\n details.piCodingAgentDirSet = process.env['PI_CODING_AGENT_DIR'] !== undefined;\n details.piHomeSet = process.env['PI_HOME'] !== undefined;\n details.piCliPathSet = process.env['PI_CLI_PATH'] !== undefined;\n\n // Healthy if either CLI is available or global state root exists\n const healthy = cliAvailable || agentDirExists;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Pi coding agent (https://github.com/badlogic/pi-mono).\n * Pi is CAAMP's first-class primary harness with 11/16 canonical hook events.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T553\n */\n\nimport { PiAdapter } from './adapter.js';\n\nexport { PiAdapter } from './adapter.js';\nexport { PiHookProvider } from './hooks.js';\nexport { PiInstallProvider } from './install.js';\nexport { PiSpawnProvider } from './spawn.js';\n\nexport default PiAdapter;\n\n/**\n * Factory function for creating Pi adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the pi provider\n * via its import-based discovery mechanism.\n *\n * @returns A new {@link PiAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/pi';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n */\nexport function createAdapter(): PiAdapter {\n return new PiAdapter();\n}\n", "/**\n * @packageDocumentation\n *\n * Unified provider adapter package for CLEO.\n * Exports all provider adapters and a registry for manifest discovery.\n *\n * @remarks\n * This package is the single entry point for all CLEO provider adapters.\n * Each provider (Claude Code, Cursor, OpenCode, Codex, Gemini CLI, Kimi)\n * exposes an adapter class implementing {@link CLEOProviderAdapter} from\n * `@cleocode/contracts`, plus supporting hook, install, and spawn providers.\n * The {@link discoverProviders} function and {@link getProviderManifests}\n * registry enable dynamic adapter loading by AdapterManager.\n */\n\nexport type { BuildCantEnrichedPromptOptions, TierDiscoveryStats } from './cant-context.js';\n// Shared CANT context builder \u2014 used by all spawn providers\nexport { buildCantEnrichedPrompt } from './cant-context.js';\n// Re-export adapter classes for direct use\n// Per-provider factory functions (renamed to avoid collisions)\nexport {\n ClaudeCodeAdapter,\n ClaudeCodeContextMonitorProvider,\n ClaudeCodeHookProvider,\n ClaudeCodeInstallProvider,\n ClaudeCodePathProvider,\n ClaudeCodeSpawnProvider,\n ClaudeCodeTransportProvider,\n checkStatuslineIntegration,\n createAdapter as createClaudeCodeAdapter,\n getSetupInstructions,\n getStatuslineConfig,\n} from './providers/claude-code/index.js';\nexport {\n CodexAdapter,\n CodexHookProvider,\n CodexInstallProvider,\n createAdapter as createCodexAdapter,\n} from './providers/codex/index.js';\nexport {\n CursorAdapter,\n CursorHookProvider,\n CursorInstallProvider,\n createAdapter as createCursorAdapter,\n} from './providers/cursor/index.js';\nexport {\n createAdapter as createGeminiCliAdapter,\n GeminiCliAdapter,\n GeminiCliHookProvider,\n GeminiCliInstallProvider,\n} from './providers/gemini-cli/index.js';\nexport {\n createAdapter as createKimiAdapter,\n KimiAdapter,\n KimiHookProvider,\n KimiInstallProvider,\n} from './providers/kimi/index.js';\nexport {\n createAdapter as createOpenCodeAdapter,\n OpenCodeAdapter,\n OpenCodeHookProvider,\n OpenCodeInstallProvider,\n OpenCodeSpawnProvider,\n} from './providers/opencode/index.js';\nexport type { AdapterManifest } from './registry.js';\nexport { discoverProviders, getProviderManifests } from './registry.js';\n", "/**\n * Codex CLI Adapter\n *\n * Main CLEOProviderAdapter implementation for OpenAI Codex CLI.\n * Provides hooks and install capabilities for CLEO integration.\n *\n * @task T162\n * @epic T134\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { CodexHookProvider } from './hooks.js';\nimport { CodexInstallProvider } from './install.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for OpenAI Codex CLI.\n *\n * Bridges CLEO's adapter system with Codex CLI's native capabilities:\n * - Hooks: Maps Codex events (SessionStart, PromptSubmit, ResponseComplete) to CAAMP events\n * - Install: Ensures AGENTS.md references for CLEO instruction files\n *\n * @remarks\n * Codex CLI supports only 3 canonical events (SessionStart, PromptSubmit,\n * ResponseComplete) and has no spawn or transport capabilities. Integration\n * is primarily through instruction files (AGENTS.md).\n *\n * @task T162\n * @epic T134\n */\nexport class CodexAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'codex';\n /** Human-readable provider name. */\n readonly name = 'Codex';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n supportedHookEvents: ['SessionStart', 'UserPromptSubmit', 'Stop'],\n supportsSpawn: false,\n supportsInstall: true,\n supportsInstructionFiles: false,\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: false,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping. */\n hooks: CodexHookProvider;\n /** Install provider for managing instruction files. */\n install: CodexInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new CodexHookProvider();\n this.install = new CodexInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * @param projectDir - Root directory of the project\n * @task T162\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n * @task T162\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Codex CLI is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Codex CLI binary is available in PATH\n * 3. ~/.codex/ configuration directory exists\n *\n * @returns Health status with details about each check\n * @task T162\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Codex CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which codex');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Codex CLI config directory\n const codexConfigDir = join(homedir(), '.codex');\n const configExists = existsSync(codexConfigDir);\n details.configDirExists = configExists;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n * @task T162\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n * @task T162\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * Codex CLI Hook Provider\n *\n * Maps Codex CLI's native hook events to CAAMP canonical hook events.\n * Codex CLI supports 3 canonical events through its hook system.\n *\n * Codex CLI event mapping:\n * - SessionStart -> SessionStart\n * - PromptSubmit -> UserPromptSubmit\n * - ResponseComplete -> Stop\n *\n * @task T162\n * @epic T134\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterHookProvider } from '@cleocode/contracts';\nimport { readLatestTranscript } from '../shared/transcript-reader.js';\n\n/**\n * Mapping from Codex CLI native event names to CAAMP canonical event names.\n */\nconst CODEX_EVENT_MAP: Record<string, string> = {\n SessionStart: 'SessionStart',\n PromptSubmit: 'UserPromptSubmit',\n ResponseComplete: 'Stop',\n};\n\n/**\n * Hook provider for Codex CLI.\n *\n * Codex CLI registers hooks via its configuration system at\n * ~/.codex/. Hook handlers are shell commands or script paths that\n * execute when the corresponding event fires.\n *\n * Since hooks are registered through the config system (managed by\n * the install provider), registerNativeHooks and unregisterNativeHooks\n * track registration state without performing filesystem operations.\n *\n * @remarks\n * Codex CLI has a minimal hook surface with only 3 canonical events.\n * Registration state is tracked in-memory because Codex CLI manages\n * hooks through its own configuration system at `~/.codex/`.\n *\n * @task T162\n * @epic T134\n */\nexport class CodexHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Codex CLI native event name to a CAAMP hook event name.\n *\n * @param providerEvent - Codex CLI event name (e.g. \"SessionStart\", \"PromptSubmit\")\n * @returns CAAMP event name or null if unmapped\n * @task T162\n */\n mapProviderEvent(providerEvent: string): string | null {\n return CODEX_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For Codex CLI, hooks are registered via the config system\n * (~/.codex/), which is handled by the install provider.\n * This method marks hooks as registered without performing\n * filesystem operations.\n *\n * @param _projectDir - Project directory (unused; hooks are global)\n * @task T162\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For Codex CLI, this is a no-op since hooks are managed through\n * the config system. Unregistration happens via the install\n * provider's uninstall method.\n * @task T162\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via registerNativeHooks.\n * @task T162\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the full event mapping for introspection/debugging.\n * @task T162\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...CODEX_EVENT_MAP };\n }\n\n /**\n * Extract a plain-text transcript from Codex CLI session data.\n *\n * Reads the most recent JSON/JSONL session file under `~/.codex/`\n * and returns its turns as a flat string for brain observation extraction.\n *\n * Returns null when no session data is found or on any read error.\n *\n * @param _sessionId - CLEO session ID (unused; reads the most recent file)\n * @param _projectDir - Project directory (unused; Codex CLI uses global paths)\n * @task T162 @epic T134\n */\n async getTranscript(_sessionId: string, _projectDir: string): Promise<string | null> {\n return readLatestTranscript(join(homedir(), '.codex'));\n }\n}\n", "/**\n * Shared transcript-reading utility for provider hook adapters.\n *\n * Several providers (Gemini CLI, Codex CLI) store session data in a\n * flat directory of JSON/JSONL files using the same role/content schema.\n * This module centralises the \"find most-recent file, parse turns\"\n * logic to avoid duplicating it in each hook provider.\n *\n * Usage:\n * ```ts\n * import { readLatestTranscript } from '../shared/transcript-reader.js';\n *\n * async getTranscript(_sessionId: string, _projectDir: string) {\n * return readLatestTranscript(join(homedir(), '.gemini'));\n * }\n * ```\n *\n * @task T161\n * @epic T134\n */\n\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A single parsed conversation turn from a provider session file. */\ninterface TranscriptTurn {\n role: string;\n content: string;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a raw JSONL or JSON session file into an array of transcript turns.\n *\n * Lines that are not valid JSON, or that lack a string `role` and string\n * `content`, are silently skipped.\n *\n * @param raw - Raw file contents (UTF-8 string).\n * @returns Array of `{ role, content }` pairs, in file order.\n */\nfunction parseTranscriptLines(raw: string): TranscriptTurn[] {\n const turns: TranscriptTurn[] = [];\n const lines = raw.split('\\n').filter((l) => l.trim());\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as Record<string, unknown>;\n const role = entry.role;\n const content = entry.content;\n if (typeof role === 'string' && typeof content === 'string') {\n turns.push({ role, content });\n }\n } catch {\n // Skip malformed lines\n }\n }\n\n return turns;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Read the most recent JSON or JSONL session file from `providerDir` and\n * return its contents as a flat transcript string.\n *\n * Files are sorted in descending order by filename \u2014 this works naturally\n * for providers that embed timestamps in filenames. The most recently named\n * file is read first.\n *\n * Returns `null` when:\n * - `providerDir` does not exist or cannot be read\n * - No JSON/JSONL files are present\n * - The most recent file contains no parseable turns\n *\n * @remarks\n * This utility is shared by Gemini CLI and Codex CLI hook providers which\n * both store session data in the same flat JSON/JSONL format. Only the\n * most recent file is read to keep memory usage bounded.\n *\n * @param providerDir - Absolute path to the provider's session directory\n * (e.g. `~/.gemini` or `~/.codex`).\n * @returns A plain-text transcript with lines of the form `role: content`,\n * or `null` if no transcript could be extracted.\n *\n * @example\n * ```typescript\n * import { readLatestTranscript } from '../shared/transcript-reader.js';\n *\n * const transcript = await readLatestTranscript('/home/user/.gemini');\n * if (transcript) {\n * console.log(transcript);\n * }\n * ```\n *\n * @task T161\n * @epic T134\n */\nexport async function readLatestTranscript(providerDir: string): Promise<string | null> {\n let allFiles: string[] = [];\n\n try {\n const entries = await readdir(providerDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const name = entry.name;\n if (name.endsWith('.json') || name.endsWith('.jsonl')) {\n allFiles.push(join(providerDir, name));\n }\n }\n } catch {\n return null;\n }\n\n if (allFiles.length === 0) return null;\n\n // Sort descending \u2014 timestamps in filenames sort naturally\n allFiles = allFiles.sort((a, b) => b.localeCompare(a));\n const mostRecent = allFiles[0];\n if (!mostRecent) return null;\n\n try {\n const raw = await readFile(mostRecent, 'utf-8');\n const turns = parseTranscriptLines(raw);\n return turns.length > 0 ? turns.map((t) => `${t.role}: ${t.content}`).join('\\n') : null;\n } catch {\n return null;\n }\n}\n", "/**\n * Codex CLI Install Provider\n *\n * Handles CLEO installation into Codex CLI environments:\n * - Ensures AGENTS.md has CLEO @-references\n *\n * @task T162\n * @epic T134\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for Codex CLI.\n *\n * Manages CLEO's integration with Codex CLI by:\n * 1. Ensuring AGENTS.md contains @-references to CLEO instruction files\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. Only AGENTS.md is managed; Codex CLI\n * does not have an MCP or plugin registration mechanism.\n *\n * @task T162\n * @epic T134\n */\nexport class CodexInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Codex CLI environment.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n * @task T162\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure AGENTS.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the Codex CLI environment.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n * @task T162\n */\n async uninstall(): Promise<void> {\n // No-op: no MCP registration to remove\n }\n\n /**\n * Check whether CLEO is installed in the Codex CLI environment.\n *\n * Checks for CLEO references in AGENTS.md.\n * @task T162\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n * @task T162\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update AGENTS.md with CLEO @-references.\n *\n * @param projectDir - Project root directory\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const agentsMdPath = join(projectDir, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsMdPath)) {\n content = readFileSync(agentsMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n content = refsBlock + '\\n';\n }\n\n writeFileSync(agentsMdPath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for OpenAI Codex CLI.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T162\n * @epic T134\n */\n\nimport { CodexAdapter } from './adapter.js';\n\nexport { CodexAdapter } from './adapter.js';\nexport { CodexHookProvider } from './hooks.js';\nexport { CodexInstallProvider } from './install.js';\n\nexport default CodexAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the codex\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link CodexAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/codex';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n *\n * @task T162\n */\nexport function createAdapter(): CodexAdapter {\n return new CodexAdapter();\n}\n", "/**\n * Gemini CLI Adapter\n *\n * Main CLEOProviderAdapter implementation for Google Gemini CLI.\n * Provides hooks and install capabilities for CLEO integration.\n *\n * @task T161\n * @epic T134\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { GeminiCliHookProvider } from './hooks.js';\nimport { GeminiCliInstallProvider } from './install.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for Google Gemini CLI.\n *\n * Bridges CLEO's adapter system with Gemini CLI's native capabilities:\n * - Hooks: Maps Gemini CLI events (SessionStart, PreToolUse, etc.) to CAAMP events\n * - Install: Ensures AGENTS.md references for CLEO instruction files\n *\n * @remarks\n * Gemini CLI supports 10 canonical CAAMP events through its hook system,\n * including PreModel and PostModel which most other providers lack. It has\n * no spawn or transport capabilities. Integration is through AGENTS.md\n * instruction files and the Gemini CLI's configuration at `~/.gemini/`.\n *\n * @task T161\n * @epic T134\n */\nexport class GeminiCliAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'gemini-cli';\n /** Human-readable provider name. */\n readonly name = 'Gemini CLI';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'BeforeAgent',\n 'AfterAgent',\n 'BeforeTool',\n 'AfterTool',\n 'BeforeModel',\n 'AfterModel',\n 'PreCompress',\n 'Notification',\n ],\n supportsSpawn: false,\n supportsInstall: true,\n supportsInstructionFiles: false,\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: false,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping. */\n hooks: GeminiCliHookProvider;\n /** Install provider for managing instruction files. */\n install: GeminiCliInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new GeminiCliHookProvider();\n this.install = new GeminiCliInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * @param projectDir - Root directory of the project\n * @task T161\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n * @task T161\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Gemini CLI is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Gemini CLI binary is available in PATH\n * 3. ~/.gemini/ configuration directory exists\n *\n * @returns Health status with details about each check\n * @task T161\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Gemini CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which gemini');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Gemini CLI config directory\n const geminiConfigDir = join(homedir(), '.gemini');\n const configExists = existsSync(geminiConfigDir);\n details.configDirExists = configExists;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n * @task T161\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n * @task T161\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * Gemini CLI Hook Provider\n *\n * Maps Gemini CLI's native hook events to CAAMP canonical hook events.\n * Gemini CLI supports 11 canonical events through its hook system.\n *\n * Gemini CLI event mapping:\n * - SessionStart -> SessionStart\n * - SessionEnd -> SessionEnd\n * - PromptSubmit -> BeforeAgent\n * - ResponseComplete -> AfterAgent\n * - PreToolUse -> BeforeTool\n * - PostToolUse -> AfterTool\n * - PreModel -> BeforeModel\n * - PostModel -> AfterModel\n * - PreCompact -> PreCompress\n * - Notification -> Notification\n *\n * @task T161\n * @epic T134\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterHookProvider } from '@cleocode/contracts';\nimport { readLatestTranscript } from '../shared/transcript-reader.js';\n\n/**\n * Mapping from Gemini CLI native event names to CAAMP canonical event names.\n */\nconst GEMINI_CLI_EVENT_MAP: Record<string, string> = {\n SessionStart: 'SessionStart',\n SessionEnd: 'SessionEnd',\n PromptSubmit: 'BeforeAgent',\n ResponseComplete: 'AfterAgent',\n PreToolUse: 'BeforeTool',\n PostToolUse: 'AfterTool',\n PreModel: 'BeforeModel',\n PostModel: 'AfterModel',\n PreCompact: 'PreCompress',\n Notification: 'Notification',\n};\n\n/**\n * Hook provider for Gemini CLI.\n *\n * Gemini CLI registers hooks via its configuration system at\n * ~/.gemini/. Hook handlers are shell scripts or commands that\n * execute when the corresponding event fires.\n *\n * Since hooks are registered through the config system (managed by\n * the install provider), registerNativeHooks and unregisterNativeHooks\n * track registration state without performing filesystem operations.\n *\n * @remarks\n * Gemini CLI uses its own event naming convention (e.g. BeforeAgent,\n * AfterTool, PreCompress) which differs from both the PascalCase CAAMP\n * canonical names and other providers' conventions. The static event map\n * covers all 10 supported canonical events.\n *\n * @task T161\n * @epic T134\n */\nexport class GeminiCliHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Gemini CLI native event name to a CAAMP hook event name.\n *\n * @param providerEvent - Gemini CLI event name (e.g. \"SessionStart\", \"PreToolUse\")\n * @returns CAAMP event name or null if unmapped\n * @task T161\n */\n mapProviderEvent(providerEvent: string): string | null {\n return GEMINI_CLI_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For Gemini CLI, hooks are registered via the config system\n * (~/.gemini/), which is handled by the install provider.\n * This method marks hooks as registered without performing\n * filesystem operations.\n *\n * @param _projectDir - Project directory (unused; hooks are global)\n * @task T161\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For Gemini CLI, this is a no-op since hooks are managed through\n * the config system. Unregistration happens via the install\n * provider's uninstall method.\n * @task T161\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via registerNativeHooks.\n * @task T161\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the full event mapping for introspection/debugging.\n * @task T161\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...GEMINI_CLI_EVENT_MAP };\n }\n\n /**\n * Extract a plain-text transcript from Gemini CLI session data.\n *\n * Reads the most recent JSON/JSONL session file under `~/.gemini/`\n * and returns its turns as a flat string for brain observation extraction.\n *\n * Returns null when no session data is found or on any read error.\n *\n * @param _sessionId - CLEO session ID (unused; reads the most recent file)\n * @param _projectDir - Project directory (unused; Gemini CLI uses global paths)\n * @task T161 @epic T134\n */\n async getTranscript(_sessionId: string, _projectDir: string): Promise<string | null> {\n return readLatestTranscript(join(homedir(), '.gemini'));\n }\n}\n", "/**\n * Gemini CLI Install Provider\n *\n * Handles CLEO installation into Gemini CLI environments:\n * - Ensures AGENTS.md has CLEO @-references\n *\n * @task T161\n * @epic T134\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for Gemini CLI.\n *\n * Manages CLEO's integration with Gemini CLI by:\n * 1. Ensuring AGENTS.md contains @-references to CLEO instruction files\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. Only AGENTS.md is managed; Gemini CLI\n * does not have an MCP or plugin registration mechanism.\n *\n * @task T161\n * @epic T134\n */\nexport class GeminiCliInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Gemini CLI environment.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n * @task T161\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure AGENTS.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the Gemini CLI environment.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n * @task T161\n */\n async uninstall(): Promise<void> {\n // No-op: no MCP registration to remove\n }\n\n /**\n * Check whether CLEO is installed in the Gemini CLI environment.\n *\n * Checks for CLEO references in AGENTS.md.\n * @task T161\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n * @task T161\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update AGENTS.md with CLEO @-references.\n *\n * @param projectDir - Project root directory\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const agentsMdPath = join(projectDir, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsMdPath)) {\n content = readFileSync(agentsMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n content = refsBlock + '\\n';\n }\n\n writeFileSync(agentsMdPath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Google Gemini CLI.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T161\n * @epic T134\n */\n\nimport { GeminiCliAdapter } from './adapter.js';\n\nexport { GeminiCliAdapter } from './adapter.js';\nexport { GeminiCliHookProvider } from './hooks.js';\nexport { GeminiCliInstallProvider } from './install.js';\n\nexport default GeminiCliAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the gemini-cli\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link GeminiCliAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/gemini-cli';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n *\n * @task T161\n */\nexport function createAdapter(): GeminiCliAdapter {\n return new GeminiCliAdapter();\n}\n", "/**\n * Kimi Adapter\n *\n * Main CLEOProviderAdapter implementation for Moonshot AI Kimi.\n * Provides install-only capabilities for CLEO integration.\n * Kimi has no native hook system; integration is via instruction files.\n *\n * @task T163\n * @epic T134\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { KimiHookProvider } from './hooks.js';\nimport { KimiInstallProvider } from './install.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for Moonshot AI Kimi.\n *\n * Bridges CLEO's adapter system with Kimi's integration surface:\n * - Hooks: No-op (Kimi has no native hook system)\n * - Install: Ensures AGENTS.md references for CLEO instruction files\n *\n * @remarks\n * Kimi has no native hook or event system, so all hook-related capabilities\n * are disabled. The adapter is install-only, managing AGENTS.md references\n * for CLEO instruction injection.\n *\n * @task T163\n * @epic T134\n */\nexport class KimiAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'kimi';\n /** Human-readable provider name. */\n readonly name = 'Kimi';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: false,\n supportedHookEvents: [],\n supportsSpawn: false,\n supportsInstall: true,\n supportsInstructionFiles: false,\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: false,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider (no-op since Kimi has no event system). */\n hooks: KimiHookProvider;\n /** Install provider for managing instruction files. */\n install: KimiInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new KimiHookProvider();\n this.install = new KimiInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * @param projectDir - Root directory of the project\n * @task T163\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Releases tracked state. No hooks to unregister since Kimi\n * has no native hook system.\n * @task T163\n */\n async dispose(): Promise<void> {\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Kimi is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Kimi CLI binary is available in PATH\n * 3. ~/.kimi/ configuration directory exists\n *\n * @returns Health status with details about each check\n * @task T163\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Kimi CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which kimi');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Kimi config directory\n const kimiConfigDir = join(homedir(), '.kimi');\n const configExists = existsSync(kimiConfigDir);\n details.configDirExists = configExists;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n * @task T163\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n * @task T163\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * Kimi Hook Provider\n *\n * Kimi has no native hook system (hookSystem is \"none\").\n * This provider implements the minimal AdapterHookProvider interface\n * with a no-op mapProviderEvent that always returns null.\n *\n * @task T163\n * @epic T134\n */\n\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/**\n * Hook provider for Kimi.\n *\n * Kimi does not expose a native hook or event system.\n * All hook-related methods are no-ops; mapProviderEvent always\n * returns null since there are no events to map.\n *\n * @remarks\n * Since Kimi has no hookable events, the event map is empty and\n * `mapProviderEvent` always returns null. Registration state is tracked\n * purely for interface compliance with {@link AdapterHookProvider}.\n *\n * @task T163\n * @epic T134\n */\nexport class KimiHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered (always a no-op for Kimi). */\n private registered = false;\n\n /**\n * Map a Kimi native event name to a CAAMP hook event name.\n *\n * Kimi has no hook system, so this always returns null.\n *\n * @param _providerEvent - Unused; Kimi emits no hookable events\n * @returns Always null\n * @task T163\n */\n mapProviderEvent(_providerEvent: string): string | null {\n return null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * Kimi has no hook system. This method is a no-op and only\n * tracks registration state for interface compliance.\n *\n * @param _projectDir - Project directory (unused)\n * @task T163\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * Kimi has no hook system. This method is a no-op.\n * @task T163\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via registerNativeHooks.\n * @task T163\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the full event mapping for introspection/debugging.\n *\n * Returns an empty map since Kimi has no hookable events.\n * @task T163\n */\n getEventMap(): Readonly<Record<string, string>> {\n return {};\n }\n}\n", "/**\n * Kimi Install Provider\n *\n * Handles CLEO installation into Kimi environments:\n * - Ensures AGENTS.md has CLEO @-references\n *\n * @task T163\n * @epic T134\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for Kimi.\n *\n * Manages CLEO's integration with Kimi by:\n * 1. Ensuring AGENTS.md contains @-references to CLEO instruction files\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. Only AGENTS.md is managed; Kimi does\n * not have an MCP or plugin registration mechanism.\n *\n * @task T163\n * @epic T134\n */\nexport class KimiInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Kimi environment.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n * @task T163\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure AGENTS.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the Kimi environment.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n * @task T163\n */\n async uninstall(): Promise<void> {\n // No-op: no MCP registration to remove\n }\n\n /**\n * Check whether CLEO is installed in the Kimi environment.\n *\n * Checks for CLEO references in AGENTS.md.\n * @task T163\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n * @task T163\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update AGENTS.md with CLEO @-references.\n *\n * @param projectDir - Project root directory\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const agentsMdPath = join(projectDir, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsMdPath)) {\n content = readFileSync(agentsMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n content = refsBlock + '\\n';\n }\n\n writeFileSync(agentsMdPath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Moonshot AI Kimi.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T163\n * @epic T134\n */\n\nimport { KimiAdapter } from './adapter.js';\n\nexport { KimiAdapter } from './adapter.js';\nexport { KimiHookProvider } from './hooks.js';\nexport { KimiInstallProvider } from './install.js';\n\nexport default KimiAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the kimi\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link KimiAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/kimi';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n *\n * @task T163\n */\nexport function createAdapter(): KimiAdapter {\n return new KimiAdapter();\n}\n", "/**\n * Adapter registry \u2014 discovers and provides access to provider manifests.\n *\n * Scans the providers/ directory for manifest.json files and returns\n * the discovered adapter manifests for use by AdapterManager.\n *\n * @task T5240\n */\n\nimport { readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Minimal manifest shape for provider discovery.\n *\n * @remarks\n * Each provider adapter ships a `manifest.json` in its directory under\n * `providers/`. The registry reads these at startup to populate the\n * adapter discovery surface. The shape is intentionally minimal -- only\n * the fields needed for dynamic loading and detection are required.\n */\nexport interface AdapterManifest {\n /** Unique provider identifier (e.g. \"claude-code\", \"cursor\"). */\n id: string;\n /** Human-readable display name for the provider. */\n name: string;\n /** Semantic version of the adapter. */\n version: string;\n /** Short description of what the provider integrates with. */\n description: string;\n /** Provider slug used for directory lookups. */\n provider: string;\n /** Relative path to the adapter's entry point module. */\n entryPoint: string;\n /** Capability flags declared by the adapter. */\n capabilities: Record<string, unknown>;\n /** Patterns used to auto-detect the provider in a project. */\n detectionPatterns: Array<{\n /** Detection strategy type (e.g. \"file\", \"env\"). */\n type: string;\n /** Glob or regex pattern to match. */\n pattern: string;\n /** Human-readable explanation of this detection rule. */\n description: string;\n }>;\n}\n\n/** Known provider IDs bundled with @cleocode/adapters. */\nconst PROVIDER_IDS = ['claude-code', 'opencode', 'cursor', 'pi'] as const;\n\n/**\n * Get the manifests for all bundled provider adapters.\n *\n * @remarks\n * Scans the known provider directories for `manifest.json` files.\n * Providers whose manifests cannot be loaded (missing or malformed)\n * are silently skipped.\n *\n * @returns Array of adapter manifests for successfully loaded providers\n *\n * @example\n * ```typescript\n * import { getProviderManifests } from '@cleocode/adapters';\n *\n * const manifests = getProviderManifests();\n * for (const m of manifests) {\n * console.log(`${m.id}: ${m.name} v${m.version}`);\n * }\n * ```\n */\nexport function getProviderManifests(): AdapterManifest[] {\n const manifests: AdapterManifest[] = [];\n const baseDir = resolve(dirname(fileURLToPath(import.meta.url)), 'providers');\n\n for (const providerId of PROVIDER_IDS) {\n try {\n const manifestPath = join(baseDir, providerId, 'manifest.json');\n const raw = readFileSync(manifestPath, 'utf-8');\n manifests.push(JSON.parse(raw) as AdapterManifest);\n } catch {\n // Skip providers whose manifests cannot be loaded\n }\n }\n\n return manifests;\n}\n\n/**\n * Discover all available provider adapters.\n *\n * Returns a map of provider ID to adapter factory function.\n *\n * @remarks\n * Each factory lazily imports the provider module and constructs a new\n * adapter instance. This avoids loading all provider code upfront and\n * keeps startup fast.\n *\n * @returns Map of provider ID to async factory function that creates an adapter instance\n *\n * @example\n * ```typescript\n * import { discoverProviders } from '@cleocode/adapters';\n *\n * const providers = await discoverProviders();\n * const factory = providers.get('claude-code');\n * if (factory) {\n * const adapter = await factory();\n * }\n * ```\n */\nexport async function discoverProviders(): Promise<Map<string, () => Promise<unknown>>> {\n const providers = new Map<string, () => Promise<unknown>>();\n\n providers.set('claude-code', async () => {\n const { ClaudeCodeAdapter } = await import('./providers/claude-code/index.js');\n return new ClaudeCodeAdapter();\n });\n\n providers.set('opencode', async () => {\n const { OpenCodeAdapter } = await import('./providers/opencode/index.js');\n return new OpenCodeAdapter();\n });\n\n providers.set('cursor', async () => {\n const { CursorAdapter } = await import('./providers/cursor/index.js');\n return new CursorAdapter();\n });\n\n providers.set('pi', async () => {\n const { PiAdapter } = await import('./providers/pi/index.js');\n return new PiAdapter();\n });\n\n return providers;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,SAAS,YAAY,aAAa,oBAAoB;AACtD,SAAS,eAAe;AACxB,SAAS,UAAU,YAAY;AAyDxB,SAAS,kBAAkB,KAAuB;AACvD,MAAI;AACF,UAAM,UAAU,YAAY,KAAK,EAAE,WAAW,MAAM,eAAe,KAAK,CAAC;AACzE,UAAM,QAAkB,CAAC;AACzB,eAAW,SAAS,SAAS;AAC3B,UAAI,MAAM,OAAO,KAAK,MAAM,KAAK,SAAS,OAAO,GAAG;AAClD,cAAM,SAAU,MAA6C,cAAc;AAC3E,cAAM,KAAK,KAAK,QAAQ,MAAM,IAAI,CAAC;AAAA,MACrC;AAAA,IACF;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAWO,SAAS,sBAAsB,YAIpC;AACA,QAAM,OAAO,QAAQ;AACrB,QAAM,UAAU,QAAQ,IAAI,eAAe,KAAK,KAAK,MAAM,UAAU,OAAO;AAC5E,QAAM,YAAY,QAAQ,IAAI,iBAAiB,KAAK,KAAK,MAAM,SAAS;AAExE,SAAO;AAAA,IACL,QAAQ,KAAK,SAAS,QAAQ,MAAM;AAAA,IACpC,MAAM,KAAK,WAAW,QAAQ,MAAM;A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A,EACvB,CAAC;AAED,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["/**\n * Shared CANT context builder for all spawn providers.\n *\n * Extracts the Pi bridge's CANT discovery/compile/inject logic into a reusable\n * module that any spawn provider (Claude Code, OpenCode, Cursor, etc.) can call\n * to enrich agent prompts with:\n *\n * 1. Compiled CANT bundle (team topology, agent personas, tool ACLs)\n * 2. Memory bridge (recent decisions, handoff notes, key patterns)\n * 3. Mental model injection (validate-on-load agent-specific observations)\n *\n * All operations are best-effort: if any step fails (missing packages, empty\n * directories, compilation errors), the base prompt is returned unchanged.\n * This guarantees agents always spawn \u2014 CANT context is an enrichment, not a gate.\n *\n * Reference implementation: packages/cleo-os/extensions/cleo-cant-bridge.ts\n * (Pi-only; this module generalizes the same logic for all providers)\n *\n * @task T555\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, join } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Per-tier file counts for diagnostic reporting. */\nexport interface TierDiscoveryStats {\n global: number;\n user: number;\n project: number;\n overrides: number;\n merged: number;\n}\n\n/** Minimal observation shape returned by memoryFind / searchBrainCompact. */\nexport interface MentalModelObservation {\n id: string;\n type: string;\n title: string;\n date?: string;\n}\n\n/** Options for the main enrichment function. */\nexport interface BuildCantEnrichedPromptOptions {\n /** Project root directory for .cleo/cant/ discovery and brain.db access. */\n projectDir: string;\n /** The raw prompt to enrich. Returned unchanged if no CANT context is available. */\n basePrompt: string;\n /** Agent name for mental model injection. Omit to skip mental model fetch. */\n agentName?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Preamble text injected when an agent has mental model observations.\n * The agent MUST re-evaluate each observation against current project state.\n */\nconst VALIDATE_ON_LOAD_PREAMBLE =\n '===== MENTAL MODEL (validate-on-load) =====\\n' +\n 'These are your prior observations, patterns, and learnings for this project.\\n' +\n 'Before acting, you MUST re-evaluate each entry against current project state.\\n' +\n 'If an entry is stale, note it and proceed with fresh understanding.';\n\n// ---------------------------------------------------------------------------\n// Discovery functions (ported from cleo-cant-bridge.ts lines 418-526)\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively discover `.cant` files in a directory.\n *\n * @param dir - The directory to scan recursively.\n * @returns An array of absolute paths to `.cant` files found.\n */\nexport function discoverCantFiles(dir: string): string[] {\n try {\n const entries = readdirSync(dir, { recursive: true, withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.cant')) {\n const parent = (entry as unknown as { parentPath?: string }).parentPath ?? dir;\n files.push(join(parent, entry.name));\n }\n }\n return files;\n } catch {\n return [];\n }\n}\n\n/**\n * Resolve XDG-compliant paths for the 3-tier CANT hierarchy.\n *\n * Respects `XDG_DATA_HOME` and `XDG_CONFIG_HOME` environment variables.\n * Falls back to XDG defaults (`~/.local/share/` and `~/.config/`).\n *\n * @param projectDir - The project root directory (for the project tier).\n * @returns An object with `global`, `user`, and `project` CANT directory paths.\n */\nexport function resolveThreeTierPaths(projectDir: string): {\n global: string;\n user: string;\n project: string;\n} {\n const home = homedir();\n const xdgData = process.env['XDG_DATA_HOME'] ?? join(home, '.local', 'share');\n const xdgConfig = process.env['XDG_CONFIG_HOME'] ?? join(home, '.config');\n\n return {\n global: join(xdgData, 'cleo', 'cant'),\n user: join(xdgConfig, 'cleo', 'cant'),\n project: join(projectDir, '.cleo', 'cant'),\n };\n}\n\n/**\n * Discover `.cant` files across all three tiers with override semantics.\n *\n * Scans global, user, and project tiers. Files in higher-precedence tiers\n * override files in lower-precedence tiers that share the same basename.\n * The precedence order is: project > user > global.\n *\n * @param projectDir - The project root directory.\n * @returns An object containing the merged file list and per-tier statistics.\n */\nexport function discoverCantFilesMultiTier(projectDir: string): {\n files: string[];\n stats: TierDiscoveryStats;\n} {\n const paths = resolveThreeTierPaths(projectDir);\n\n const globalFiles = discoverCantFiles(paths.global);\n const userFiles = discoverCantFiles(paths.user);\n const projectFiles = discoverCantFiles(paths.project);\n\n // Build basename-keyed map; lowest precedence first so higher tiers override\n const fileMap = new Map<string, string>();\n\n for (const file of globalFiles) {\n fileMap.set(basename(file), file);\n }\n\n for (const file of userFiles) {\n fileMap.set(basename(file), file);\n }\n\n for (const file of projectFiles) {\n fileMap.set(basename(file), file);\n }\n\n const totalUniqueInputs = globalFiles.length + userFiles.length + projectFiles.length;\n const overrides = totalUniqueInputs - fileMap.size;\n\n return {\n files: Array.from(fileMap.values()),\n stats: {\n global: globalFiles.length,\n user: userFiles.length,\n project: projectFiles.length,\n overrides,\n merged: fileMap.size,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Memory bridge (ported from cleo-cant-bridge.ts lines 376-404)\n// ---------------------------------------------------------------------------\n\n/**\n * Read the memory bridge file from a project's .cleo/ directory.\n *\n * @param projectDir - The project root directory.\n * @returns The memory bridge content, or null if not found or empty.\n */\nexport function readMemoryBridge(projectDir: string): string | null {\n try {\n const bridgePath = join(projectDir, '.cleo', 'memory-bridge.md');\n if (!existsSync(bridgePath)) return null;\n const content = readFileSync(bridgePath, 'utf-8');\n return content.length > 0 ? content : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Build the memory-bridge system-prompt block appended to every agent.\n *\n * Wraps the raw memory-bridge.md content in a clearly labeled section\n * so the agent knows this is the CLEO project memory context.\n *\n * @param content - The raw memory-bridge.md content.\n * @returns The formatted memory-bridge block for system prompt injection.\n */\nexport function buildMemoryBridgeBlock(content: string): string {\n return (\n '\\n\\n===== CLEO MEMORY BRIDGE =====\\n' +\n 'This is your project memory context from .cleo/memory-bridge.md.\\n' +\n 'Use it to understand recent decisions, handoff notes, and key patterns.\\n\\n' +\n content.trim() +\n '\\n===== END MEMORY BRIDGE ====='\n );\n}\n\n// ---------------------------------------------------------------------------\n// Mental model injection (ported from cleo-cant-bridge.ts lines 113-135, 543-589)\n// ---------------------------------------------------------------------------\n\n/**\n * Build the validate-on-load mental-model injection string.\n *\n * Pure function \u2014 no I/O, safe to call in tests without a real DB.\n *\n * @param agentName - Name of the spawned agent (used in the header line).\n * @param observations - Prior mental-model observations to list.\n * @returns System-prompt block with preamble and numbered observations,\n * or empty string when `observations` is empty.\n */\nexport function buildMentalModelInjection(\n agentName: string,\n observations: MentalModelObservation[],\n): string {\n if (observations.length === 0) return '';\n\n const lines: string[] = ['', `// Agent: ${agentName}`, VALIDATE_ON_LOAD_PREAMBLE, ''];\n\n for (let i = 0; i < observations.length; i++) {\n const obs = observations[i];\n const datePart = obs.date ? ` [${obs.date}]` : '';\n lines.push(`${i + 1}. [${obs.id}] (${obs.type})${datePart}: ${obs.title}`);\n }\n\n lines.push('===== END MENTAL MODEL =====');\n return lines.join('\\n');\n}\n\n/**\n * Fetch mental model observations for an agent from brain.db.\n *\n * Uses dynamic import of `@cleocode/core` to avoid circular dependencies.\n * Returns empty string on any failure (best-effort, never throws).\n *\n * @param agentName - The agent's name for scoped observation lookup.\n * @param projectRoot - Project root directory for brain.db access.\n * @returns The validate-on-load system-prompt block, or \"\" on failure/empty.\n */\nasync function fetchMentalModelInjection(agentName: string, projectRoot: string): Promise<string> {\n try {\n // Dynamic import \u2014 @cleocode/core is NOT a compile-time dependency of adapters.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const coreModule = (await import(/* webpackIgnore: true */ '@cleocode/core' as string)) as {\n memoryFind?: (\n params: {\n query: string;\n agent?: string;\n limit?: number;\n tables?: string[];\n },\n projectRoot?: string,\n ) => Promise<{\n success: boolean;\n data?: {\n results?: MentalModelObservation[];\n };\n }>;\n };\n\n if (typeof coreModule.memoryFind !== 'function') return '';\n\n const result = await coreModule.memoryFind(\n {\n query: agentName,\n agent: agentName,\n limit: 10,\n tables: ['observations'],\n },\n projectRoot,\n );\n\n if (!result.success || !result.data?.results?.length) return '';\n\n return buildMentalModelInjection(agentName, result.data.results);\n } catch {\n return '';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Build an enriched prompt with CANT context, memory bridge, and mental model.\n *\n * This is the universal entry point for all spawn providers. It performs the\n * same operations as the Pi bridge (cleo-cant-bridge.ts) but returns a string\n * rather than hooking into Pi events:\n *\n * 1. Discovers `.cant` files across 3 tiers (global \u2192 user \u2192 project)\n * 2. Compiles the CANT bundle via `@cleocode/cant`'s `compileBundle()`\n * 3. Renders the compiled system prompt\n * 4. Reads the memory bridge from `.cleo/memory-bridge.md`\n * 5. Fetches mental model observations for the named agent\n * 6. Concatenates: basePrompt + CANT bundle + memory bridge + mental model\n *\n * All operations are best-effort. If any step fails, the base prompt is\n * returned unchanged. CANT context is an enrichment, not a gate \u2014 agents\n * always spawn regardless of CANT availability.\n *\n * @param options - Project dir, base prompt, and optional agent name.\n * @returns The enriched prompt string, or basePrompt unchanged on failure.\n */\nexport async function buildCantEnrichedPrompt(\n options: BuildCantEnrichedPromptOptions,\n): Promise<string> {\n const { projectDir, basePrompt, agentName } = options;\n let appendix = '';\n\n // Step 1-3: Discover and compile CANT bundle\n try {\n const { files } = discoverCantFilesMultiTier(projectDir);\n\n if (files.length > 0) {\n // Dynamic import \u2014 @cleocode/cant is NOT a compile-time dependency of adapters.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const cantModule = (await import(/* webpackIgnore: true */ '@cleocode/cant' as string)) as {\n compileBundle?: (paths: string[]) => Promise<{\n renderSystemPrompt: () => string;\n valid: boolean;\n diagnostics: unknown[];\n }>;\n };\n\n if (typeof cantModule.compileBundle === 'function') {\n const bundle = await cantModule.compileBundle(files);\n if (bundle.valid) {\n const rendered = bundle.renderSystemPrompt();\n if (rendered) {\n appendix += `\\n\\n${rendered}`;\n }\n }\n }\n }\n } catch {\n // CANT compilation failure \u2014 continue without bundle context\n }\n\n // Step 4: Append memory bridge\n try {\n const bridge = readMemoryBridge(projectDir);\n if (bridge) {\n appendix += buildMemoryBridgeBlock(bridge);\n }\n } catch {\n // Memory bridge read failure \u2014 non-fatal\n }\n\n // Step 5: Append mental model for named agent\n if (agentName) {\n try {\n const mentalModel = await fetchMentalModelInjection(agentName, projectDir);\n if (mentalModel) {\n appendix += `\\n\\n${mentalModel}`;\n }\n } catch {\n // Mental model fetch failure \u2014 non-fatal\n }\n }\n\n // Step 6: Return enriched prompt (or unchanged basePrompt if no context found)\n return appendix ? basePrompt + appendix : basePrompt;\n}\n", "/**\n * Claude Code path provider.\n *\n * Implements AdapterPathProvider with Claude Code-specific directory locations.\n *\n * @task T5240\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterPathProvider } from '@cleocode/contracts';\n\n/**\n * Path provider for Anthropic Claude Code CLI.\n *\n * Resolves Claude Code's standard directory layout:\n * - Config dir: ~/.claude (or CLAUDE_HOME)\n * - Settings: ~/.claude/settings.json (or CLAUDE_SETTINGS)\n * - Agents: ~/.claude/agents\n * - Memory DB: ~/.claude-mem/claude-mem.db (or CLAUDE_MEM_DB)\n *\n * @remarks\n * All paths respect environment variable overrides for CI and non-standard\n * installations. When env vars are unset, the canonical default paths are used.\n */\nexport class ClaudeCodePathProvider implements AdapterPathProvider {\n /** Get the provider's root configuration directory. */\n getProviderDir(): string {\n return process.env['CLAUDE_HOME'] ?? join(homedir(), '.claude');\n }\n\n /** Get the path to the provider's settings file, or null if unavailable. */\n getSettingsPath(): string | null {\n return process.env['CLAUDE_SETTINGS'] ?? join(this.getProviderDir(), 'settings.json');\n }\n\n /** Get the directory where agents are installed, or null if unsupported. */\n getAgentInstallDir(): string | null {\n return join(this.getProviderDir(), 'agents');\n }\n\n /** Get the path to the provider's memory database, or null if unsupported. */\n getMemoryDbPath(): string | null {\n return process.env['CLAUDE_MEM_DB'] ?? join(homedir(), '.claude-mem', 'claude-mem.db');\n }\n}\n", "/**\n * Claude Code context monitor provider.\n *\n * Implements AdapterContextMonitorProvider for Claude Code's context window\n * tracking and statusline integration.\n *\n * @task T5240\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { AdapterContextMonitorProvider } from '@cleocode/contracts';\nimport { ClaudeCodePathProvider } from './paths.js';\n\n/** Context window input from Claude Code. */\ninterface ContextWindowInput {\n context_window: {\n context_window_size?: number;\n current_usage?: {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n };\n };\n}\n\n/** Thresholds for context window status levels. */\nconst THRESHOLDS = {\n WARNING: 50,\n CAUTION: 70,\n CRITICAL: 85,\n EMERGENCY: 95,\n} as const;\n\ntype ContextStatus = 'ok' | 'warning' | 'caution' | 'critical' | 'emergency';\n\nfunction getContextStatusFromPercentage(percentage: number): ContextStatus {\n if (percentage >= THRESHOLDS.EMERGENCY) return 'emergency';\n if (percentage >= THRESHOLDS.CRITICAL) return 'critical';\n if (percentage >= THRESHOLDS.CAUTION) return 'caution';\n if (percentage >= THRESHOLDS.WARNING) return 'warning';\n return 'ok';\n}\n\n/**\n * Context monitor provider for Claude Code.\n *\n * Processes context window JSON from Claude Code and writes state files\n * for statusline display. Also provides statusline configuration\n * and setup instructions specific to Claude Code's settings.json.\n *\n * @remarks\n * The provider writes a JSON state file to `.cleo/context-states/.context-state.json`\n * which can be read by external statusline scripts (e.g. tmux, starship).\n * Context thresholds at 50%, 70%, 85%, and 95% map to warning, caution,\n * critical, and emergency status levels respectively.\n */\nexport class ClaudeCodeContextMonitorProvider implements AdapterContextMonitorProvider {\n /** Path provider for resolving Claude Code directory locations. */\n private pathProvider = new ClaudeCodePathProvider();\n\n /** Process raw context window JSON and return a formatted summary string. */\n async processContextInput(input: unknown, cwd?: string): Promise<string> {\n const typed = input as ContextWindowInput;\n const contextSize = typed.context_window?.context_window_size ?? 200000;\n const usage = typed.context_window?.current_usage;\n\n if (!usage) return '-- no data';\n\n const inputTokens = usage.input_tokens ?? 0;\n const outputTokens = usage.output_tokens ?? 0;\n const cacheCreate = usage.cache_creation_input_tokens ?? 0;\n\n const totalTokens = inputTokens + outputTokens + cacheCreate;\n const percentage = Math.floor((totalTokens * 100) / contextSize);\n const status = getContextStatusFromPercentage(percentage);\n\n // Write state file if CLEO dir exists\n const cleoDir = cwd ? join(cwd, '.cleo') : '.cleo';\n if (existsSync(cleoDir)) {\n const stateDir = join(cleoDir, 'context-states');\n const statePath = join(stateDir, '.context-state.json');\n\n const state = {\n $schema: 'https://cleo-dev.com/schemas/v1/context-state.schema.json',\n version: '1.0.0',\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, 'Z'),\n staleAfterMs: 5000,\n contextWindow: {\n maxTokens: contextSize,\n currentTokens: totalTokens,\n percentage,\n breakdown: {\n inputTokens,\n outputTokens,\n cacheCreationTokens: cacheCreate,\n cacheReadTokens: usage.cache_read_input_tokens ?? 0,\n },\n },\n thresholds: {\n warning: THRESHOLDS.WARNING,\n caution: THRESHOLDS.CAUTION,\n critical: THRESHOLDS.CRITICAL,\n emergency: THRESHOLDS.EMERGENCY,\n },\n status,\n cleoSessionId: '',\n };\n\n try {\n await mkdir(dirname(statePath), { recursive: true });\n writeFileSync(statePath, JSON.stringify(state, null, 2));\n } catch {\n // Non-fatal\n }\n }\n\n return `${percentage}% | ${totalTokens}/${contextSize}`;\n }\n\n /** Check the current statusline integration status in Claude Code settings. */\n checkStatuslineIntegration(): 'configured' | 'not_configured' | 'custom_no_cleo' | 'no_settings' {\n const settingsPath = this.pathProvider.getSettingsPath();\n if (!settingsPath || !existsSync(settingsPath)) return 'no_settings';\n\n try {\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const statusLine = settings.statusLine;\n\n if (!statusLine?.type) return 'not_configured';\n if (statusLine.type !== 'command') return 'custom_no_cleo';\n\n const cmd = statusLine.command ?? '';\n\n if (\n cmd.includes('context-monitor.sh') ||\n cmd.includes('cleo-statusline') ||\n cmd.includes('.context-state.json') ||\n cmd.includes('context-states')\n ) {\n return 'configured';\n }\n\n const scriptPath = cmd.startsWith('~') ? cmd.replace('~', homedir()) : cmd;\n if (existsSync(scriptPath)) {\n try {\n const content = readFileSync(scriptPath, 'utf-8');\n if (content.includes('context-state.json')) return 'configured';\n } catch {\n /* unreadable */\n }\n }\n\n return 'custom_no_cleo';\n } catch {\n return 'no_settings';\n }\n }\n\n /** Get the recommended statusline configuration object for Claude Code settings. */\n getStatuslineConfig(): Record<string, unknown> {\n return {\n statusLine: {\n type: 'command',\n command: join(homedir(), '.cleo', 'lib', 'session', 'context-monitor.sh'),\n },\n };\n }\n\n /** Get human-readable setup instructions for enabling context monitoring. */\n getSetupInstructions(): string {\n const settingsPath = this.pathProvider.getSettingsPath() ?? '~/.claude/settings.json';\n\n return [\n 'To enable context monitoring, add to your Claude Code settings:',\n `File: ${settingsPath}`,\n '',\n JSON.stringify(this.getStatuslineConfig(), null, 2),\n '',\n 'This enables real-time context window tracking in the CLI.',\n ].join('\\n');\n }\n}\n", "/**\n * Claude Code Hook Provider\n *\n * Maps Claude Code's native hook events to CAAMP canonical hook events.\n * Claude Code supports 14 of 16 canonical events (all except PreModel, PostModel).\n *\n * Event translation uses CAAMP normalizer APIs:\n * - `toCanonical(nativeName, 'claude-code')` for runtime event name resolution\n * - `getSupportedEvents('claude-code')` to enumerate supported canonical events\n * - `getProviderHookProfile('claude-code')` for the full provider profile\n *\n * A static map derived from CAAMP 1.9.1 hook-mappings.json is maintained as\n * a fallback for environments where CAAMP's runtime resolution is unavailable.\n *\n * @task T164\n * @epic T134\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/** CAAMP provider identifier for Claude Code. */\nconst PROVIDER_ID = 'claude-code' as const;\n\n/**\n * Fallback map from Claude Code native event names to CAAMP canonical names.\n *\n * Derived from `getProviderHookProfile('claude-code').mappings` in CAAMP 1.9.1.\n * Covers all 14 supported events. PreModel and PostModel are not supported\n * by Claude Code and are absent from this map.\n *\n * Used as fallback when CAAMP runtime is unavailable, and as the synchronous\n * implementation of `mapProviderEvent()`.\n */\nconst CLAUDE_CODE_EVENT_MAP: Record<string, string> = {\n // CAAMP: toNative('SessionStart', 'claude-code') = 'SessionStart'\n SessionStart: 'SessionStart',\n // CAAMP: toNative('SessionEnd', 'claude-code') = 'SessionEnd'\n SessionEnd: 'SessionEnd',\n // CAAMP: toNative('PromptSubmit', 'claude-code') = 'UserPromptSubmit'\n UserPromptSubmit: 'PromptSubmit',\n // CAAMP: toNative('ResponseComplete', 'claude-code') = 'Stop'\n Stop: 'ResponseComplete',\n // CAAMP: toNative('PreToolUse', 'claude-code') = 'PreToolUse'\n PreToolUse: 'PreToolUse',\n // CAAMP: toNative('PostToolUse', 'claude-code') = 'PostToolUse'\n PostToolUse: 'PostToolUse',\n // CAAMP: toNative('PostToolUseFailure','claude-code') = 'PostToolUseFailure'\n PostToolUseFailure: 'PostToolUseFailure',\n // CAAMP: toNative('PermissionRequest', 'claude-code') = 'PermissionRequest'\n PermissionRequest: 'PermissionRequest',\n // CAAMP: toNative('SubagentStart', 'claude-code') = 'SubagentStart'\n SubagentStart: 'SubagentStart',\n // CAAMP: toNative('SubagentStop', 'claude-code') = 'SubagentStop'\n SubagentStop: 'SubagentStop',\n // CAAMP: toNative('PreCompact', 'claude-code') = 'PreCompact'\n PreCompact: 'PreCompact',\n // CAAMP: toNative('PostCompact', 'claude-code') = 'PostCompact'\n PostCompact: 'PostCompact',\n // CAAMP: toNative('Notification', 'claude-code') = 'Notification'\n Notification: 'Notification',\n // CAAMP: toNative('ConfigChange', 'claude-code') = 'ConfigChange'\n ConfigChange: 'ConfigChange',\n};\n\n/**\n * Hook provider for Claude Code.\n *\n * Claude Code registers hooks via its global config at `~/.claude/settings.json`.\n * Supported handler types: command, http, prompt, agent.\n *\n * Event mapping is based on `getProviderHookProfile('claude-code')` from\n * CAAMP 1.9.1. Async accessors (`getSupportedCanonicalEvents`,\n * `getProviderProfile`) call CAAMP directly when available.\n *\n * Since hooks are registered through the config system (managed by the install\n * provider), `registerNativeHooks` and `unregisterNativeHooks` track registration\n * state without performing filesystem operations.\n *\n * @remarks\n * Claude Code is the only provider that supports all 14 of its declared\n * canonical events at runtime. The static event map is maintained as a\n * synchronous fallback; async methods like {@link getSupportedCanonicalEvents}\n * and {@link getProviderProfile} call CAAMP directly when available.\n *\n * @task T164\n * @epic T134\n */\nexport class ClaudeCodeHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Claude Code native event name to a CAAMP canonical hook event name.\n *\n * Looks up the native event name in the map derived from\n * `getProviderHookProfile('claude-code').mappings` (CAAMP 1.9.1).\n * Returns null for unrecognised events (e.g. PreModel, PostModel which\n * Claude Code does not support).\n *\n * @param providerEvent - Claude Code native event (e.g. \"UserPromptSubmit\", \"Stop\")\n * @returns CAAMP canonical event name, or null if unmapped\n * @task T164\n */\n mapProviderEvent(providerEvent: string): string | null {\n return CLAUDE_CODE_EVENT_MAP[providerEvent] ?? null;\n }\n\n /** Project directory this hook provider was registered for. */\n private projectDir: string | null = null;\n\n /**\n * Register native hooks for a project.\n *\n * Writes CLEO hook entries to `~/.claude/settings.json` so that Claude Code's\n * native event system calls cleo CLI commands when events fire. This bridges\n * Claude Code's event loop to CLEO's internal hook dispatch.\n *\n * Idempotent: skips writing if CLEO hooks already exist in settings.json.\n *\n * Hook entries registered:\n * - `Stop` \u2192 `cleo session end --quiet` (triggers LLM extraction, reflector, consolidation)\n * - `PostToolUse` (Write|Edit) \u2192 brain observation for file modifications\n * - `SubagentStop` \u2192 brain observation for agent completion\n *\n * @param projectDir - Project directory for context-scoped hook commands\n * @task T164 @task T555\n */\n async registerNativeHooks(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.registered = true;\n\n // Write CLEO hook entries to ~/.claude/settings.json (idempotent)\n try {\n const home = homedir();\n const settingsPath = join(home, '.claude', 'settings.json');\n\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n // Start fresh if settings.json is corrupt\n }\n }\n\n const hooks = (settings.hooks ?? {}) as Record<string, unknown[]>;\n\n // Check if CLEO hooks already registered (look for our marker comment in commands)\n const alreadyRegistered = Object.values(hooks).some(\n (entries) =>\n Array.isArray(entries) &&\n entries.some(\n (e) =>\n typeof e === 'object' &&\n e !== null &&\n Array.isArray((e as Record<string, unknown>).hooks) &&\n ((e as Record<string, unknown>).hooks as Array<Record<string, string>>).some(\n (h) => typeof h.command === 'string' && h.command.includes('# cleo-hook'),\n ),\n ),\n );\n\n if (alreadyRegistered) {\n return; // Already wired \u2014 idempotent\n }\n\n // Register Stop hook \u2192 triggers cleo session end (LLM extraction, reflector, consolidation)\n if (!hooks.Stop) hooks.Stop = [];\n (hooks.Stop as unknown[]).push({\n matcher: '',\n hooks: [\n {\n type: 'command',\n command: `cleo session end --quiet # cleo-hook`,\n },\n ],\n });\n\n // Register PostToolUse hook \u2192 brain observation for file writes\n if (!hooks.PostToolUse) hooks.PostToolUse = [];\n (hooks.PostToolUse as unknown[]).push({\n matcher: 'Write|Edit',\n hooks: [\n {\n type: 'command',\n command: `cleo observe \"File modified via $TOOL_NAME\" --title \"tool-use\" --quiet # cleo-hook`,\n },\n ],\n });\n\n settings.hooks = hooks;\n mkdirSync(join(home, '.claude'), { recursive: true });\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n } catch {\n // Settings write failure is non-fatal \u2014 hooks can be registered manually\n }\n }\n\n /**\n * Unregister native hooks.\n *\n * Removes CLEO hook entries from `~/.claude/settings.json` by filtering out\n * entries containing the `# cleo-hook` marker.\n *\n * @task T164 @task T555\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n this.projectDir = null;\n\n try {\n const home = homedir();\n const settingsPath = join(home, '.claude', 'settings.json');\n if (!existsSync(settingsPath)) return;\n\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) as Record<string, unknown>;\n const hooks = settings.hooks as Record<string, unknown[]> | undefined;\n if (!hooks) return;\n\n // Filter out entries with the cleo-hook marker\n let changed = false;\n for (const [event, entries] of Object.entries(hooks)) {\n if (!Array.isArray(entries)) continue;\n const filtered = entries.filter(\n (e) =>\n !(\n typeof e === 'object' &&\n e !== null &&\n Array.isArray((e as Record<string, unknown>).hooks) &&\n ((e as Record<string, unknown>).hooks as Array<Record<string, string>>).some(\n (h) => typeof h.command === 'string' && h.command.includes('# cleo-hook'),\n )\n ),\n );\n if (filtered.length !== entries.length) {\n hooks[event] = filtered;\n changed = true;\n }\n }\n\n if (changed) {\n settings.hooks = hooks;\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n }\n } catch {\n // Cleanup failure is non-fatal\n }\n }\n\n /**\n * Check whether hooks have been registered via `registerNativeHooks`.\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the project directory this hook provider was registered for.\n *\n * Returns null if hooks have not been registered yet.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n\n /**\n * Get the native\u2192canonical event mapping for introspection and debugging.\n *\n * Returns the map derived from `getProviderHookProfile('claude-code').mappings`\n * (CAAMP 1.9.1). Use `getSupportedCanonicalEvents()` to enumerate canonical\n * names via live CAAMP APIs.\n *\n * @returns Immutable record of native event name \u2192 canonical event name\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...CLAUDE_CODE_EVENT_MAP };\n }\n\n /**\n * Enumerate supported canonical events via CAAMP's `getSupportedEvents()`.\n *\n * Calls `getSupportedEvents('claude-code')` from the CAAMP normalizer to\n * get the authoritative list. Claude Code supports 14 of 16 canonical events\n * (PreModel and PostModel are not supported). Falls back to the values of\n * the static event map when CAAMP is unavailable at runtime.\n *\n * @returns Array of CAAMP canonical event names supported by Claude Code\n * @task T164\n */\n async getSupportedCanonicalEvents(): Promise<string[]> {\n try {\n const { getSupportedEvents } = await import('@cleocode/caamp');\n return getSupportedEvents(PROVIDER_ID) as string[];\n } catch {\n return [...new Set(Object.values(CLAUDE_CODE_EVENT_MAP))];\n }\n }\n\n /**\n * Retrieve the full provider hook profile from CAAMP.\n *\n * Calls `getProviderHookProfile('claude-code')` from the CAAMP normalizer to\n * get the complete profile: hook system type (`config`), config path\n * (`~/.claude/settings.json`), handler types, and all event mappings.\n * Returns null when CAAMP is unavailable at runtime.\n *\n * @returns Provider hook profile or null if CAAMP is unavailable\n * @task T164\n */\n async getProviderProfile(): Promise<unknown | null> {\n try {\n const { getProviderHookProfile } = await import('@cleocode/caamp');\n return getProviderHookProfile(PROVIDER_ID) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Translate a CAAMP canonical event to its Claude Code native name via CAAMP.\n *\n * Calls `toNative(canonical, 'claude-code')` from the CAAMP normalizer.\n * Returns null for unsupported events (PreModel, PostModel) or when\n * CAAMP is unavailable.\n *\n * @param canonical - CAAMP canonical event name (e.g. \"PromptSubmit\")\n * @returns Claude Code native event name or null\n * @task T164\n */\n async toNativeEvent(canonical: string): Promise<string | null> {\n try {\n const { toNative } = await import('@cleocode/caamp');\n return toNative(canonical as Parameters<typeof toNative>[0], PROVIDER_ID);\n } catch {\n // Invert the static map as fallback\n const entry = Object.entries(CLAUDE_CODE_EVENT_MAP).find(([, v]) => v === canonical);\n return entry?.[0] ?? null;\n }\n }\n\n /**\n * Extract a plain-text transcript from Claude Code session JSONL files.\n *\n * Reads the most recent .jsonl file under `~/.claude/projects/` and\n * extracts user/assistant turn text into a flat string for brain\n * observation extraction.\n *\n * Returns null when no session data is found or on any read error.\n *\n * @param _sessionId - CLEO session ID (unused; reads the most recent file)\n * @param _projectDir - Project directory (unused; Claude Code uses global paths)\n * @task T144 @epic T134\n */\n async getTranscript(_sessionId: string, _projectDir: string): Promise<string | null> {\n try {\n const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? '/root';\n const projectsDir = join(homeDir, '.claude', 'projects');\n\n // Find all JSONL files across project subdirectories\n let allFiles: Array<{ path: string; mtime: number }> = [];\n try {\n const projectDirs = await readdir(projectsDir, { withFileTypes: true });\n for (const entry of projectDirs) {\n if (!entry.isDirectory()) continue;\n const subDir = join(projectsDir, entry.name);\n try {\n const files = await readdir(subDir);\n for (const file of files) {\n if (!file.endsWith('.jsonl')) continue;\n const filePath = join(subDir, file);\n // Use file path modification heuristic (filename usually includes timestamp)\n allFiles.push({ path: filePath, mtime: 0 });\n }\n } catch {\n // Skip unreadable subdirectories\n }\n }\n } catch {\n return null;\n }\n\n if (allFiles.length === 0) return null;\n\n // Sort by path descending (timestamps in filenames sort naturally)\n allFiles = allFiles.sort((a, b) => b.path.localeCompare(a.path));\n const mostRecent = allFiles[0];\n if (!mostRecent) return null;\n\n const raw = await readFile(mostRecent.path, 'utf-8');\n const lines = raw.split('\\n').filter((l) => l.trim());\n\n const turns: string[] = [];\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as Record<string, unknown>;\n const role = entry.role as string | undefined;\n const content = entry.content;\n if (role === 'assistant' && typeof content === 'string') {\n turns.push(`assistant: ${content}`);\n } else if (role === 'user' && typeof content === 'string') {\n turns.push(`user: ${content}`);\n }\n } catch {\n // Skip malformed lines\n }\n }\n\n return turns.length > 0 ? turns.join('\\n') : null;\n } catch {\n return null;\n }\n }\n}\n", "/**\n * Claude Code Install Provider\n *\n * Handles CLEO installation into Claude Code environments:\n * - Ensures CLAUDE.md has CLEO @-references\n * - Manages plugin registration in ~/.claude/settings.json\n *\n * Migrated from src/core/install/claude-plugin.ts\n *\n * @task T5240\n */\n\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in CLAUDE.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = [\n '@.cleo/CLEOOS-IDENTITY.md',\n '@~/.cleo/templates/CLEO-INJECTION.md',\n '@.cleo/memory-bridge.md',\n];\n\n/** Resolve the commands directory bundled with this adapter. */\nfunction getAdapterCommandsDir(): string {\n // Works in both ESM (import.meta.url) and compiled output\n const thisDir = dirname(fileURLToPath(import.meta.url));\n return join(thisDir, 'commands');\n}\n\n/**\n * Install provider for Claude Code.\n *\n * Manages CLEO's integration with Claude Code by:\n * 1. Ensuring CLAUDE.md contains @-references to CLEO instruction files\n * 2. Installing adapter-provided commands to .claude/commands/\n * 3. Registering the brain observation plugin in ~/.claude/settings.json\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. The provider disables the legacy\n * `claude-mem\\@thedotmack` plugin if present and enables the unified\n * `cleo\\@cleocode` plugin instead.\n */\nexport class ClaudeCodeInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Claude Code project.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure CLAUDE.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'CLAUDE.md');\n }\n\n // Step 2: Install adapter-provided commands to .claude/commands/\n const commandsInstalled = this.installCommands(projectDir);\n if (commandsInstalled.length > 0) {\n details.commands = commandsInstalled;\n }\n\n // Step 3: Register plugin in ~/.claude/settings.json\n const pluginResult = this.registerPlugin();\n if (pluginResult) {\n details.plugin = pluginResult;\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the current Claude Code project.\n *\n * Does not remove CLAUDE.md references (they are harmless if CLEO is not present).\n */\n async uninstall(): Promise<void> {}\n\n /**\n * Check whether CLEO is installed in the current environment.\n *\n * Checks for plugin enabled in ~/.claude/settings.json.\n */\n async isInstalled(): Promise<boolean> {\n // Check ~/.claude/settings.json for plugin registration\n const settingsPath = join(homedir(), '.claude', 'settings.json');\n if (existsSync(settingsPath)) {\n try {\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const plugins = settings.enabledPlugins as Record<string, boolean> | undefined;\n if (plugins && plugins['cleo@cleocode'] === true) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure CLAUDE.md contains @-references to CLEO instruction files.\n *\n * Creates CLAUDE.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update CLAUDE.md with CLEO @-references.\n *\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const claudeMdPath = join(projectDir, 'CLAUDE.md');\n let content = '';\n let existed = false;\n\n if (existsSync(claudeMdPath)) {\n content = readFileSync(claudeMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n // Append missing references\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n // Create new CLAUDE.md with references\n content = refsBlock + '\\n';\n }\n\n writeFileSync(claudeMdPath, content, 'utf-8');\n return true;\n }\n\n /**\n * Install Claude Code-specific commands to .claude/commands/ in the project.\n *\n * These commands extend CLEO's provider-neutral skills with Claude Code-specific\n * operational patterns (Agent tool spawn templates, model assignment, context guardrails).\n *\n * @param projectDir - Project root directory\n * @returns Array of installed command filenames\n */\n private installCommands(projectDir: string): string[] {\n const adapterCommandsDir = getAdapterCommandsDir();\n if (!existsSync(adapterCommandsDir)) {\n return [];\n }\n\n const targetDir = join(projectDir, '.claude', 'commands');\n mkdirSync(targetDir, { recursive: true });\n\n const installed: string[] = [];\n const files = readdirSync(adapterCommandsDir).filter((f) => f.endsWith('.md'));\n\n for (const file of files) {\n const src = join(adapterCommandsDir, file);\n const dest = join(targetDir, file);\n copyFileSync(src, dest);\n installed.push(file);\n }\n\n return installed;\n }\n\n /**\n * Register the CLEO brain plugin in ~/.claude/settings.json.\n *\n * @returns Description of what was registered, or null if no change needed\n */\n private registerPlugin(): string | null {\n const home = homedir();\n const settingsPath = join(home, '.claude', 'settings.json');\n\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n // Start fresh\n }\n }\n\n const enabledPlugins = (settings.enabledPlugins as Record<string, boolean>) ?? {};\n const pluginKey = 'cleo@cleocode';\n\n if (enabledPlugins[pluginKey] === true) {\n return null;\n }\n\n // Disable old claude-mem if present\n if (enabledPlugins['claude-mem@thedotmack'] === true) {\n enabledPlugins['claude-mem@thedotmack'] = false;\n }\n\n enabledPlugins[pluginKey] = true;\n settings.enabledPlugins = enabledPlugins;\n\n mkdirSync(join(home, '.claude'), { recursive: true });\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n\n return `Enabled ${pluginKey} in ~/.claude/settings.json`;\n }\n}\n", "/**\n * Central error utilities for CLEO.\n *\n * Provides consistent error handling patterns across the codebase.\n * DRY error formatting, normalization, and transformation utilities.\n *\n * @task T5702\n */\n\n/**\n * Normalize any thrown value into a standardized error object.\n *\n * Handles:\n * - Error instances (preserves stack trace info)\n * - Strings (wraps in Error)\n * - Objects with message property\n * - null/undefined (provides fallback)\n *\n * @param error - The thrown value to normalize\n * @param fallbackMessage - Message to use if error provides none\n * @returns Normalized error with consistent shape\n *\n * @remarks\n * This function is safe to call on any value thrown by a `catch` clause.\n * It guarantees the returned object is always an `Error` instance with a\n * non-empty `message` property.\n *\n * @example\n * ```typescript\n * try {\n * await riskyOperation();\n * } catch (err) {\n * const error = normalizeError(err, 'Operation failed');\n * console.error(error.message);\n * }\n * ```\n */\nexport function normalizeError(\n error: unknown,\n fallbackMessage = 'An unexpected error occurred',\n): Error {\n if (error instanceof Error) {\n return error;\n }\n\n if (typeof error === 'string') {\n return new Error(error);\n }\n\n if (\n error !== null &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n return new Error(error.message);\n }\n\n return new Error(fallbackMessage);\n}\n\n/**\n * Extract a human-readable message from any error value.\n *\n * Safe to use on unknown thrown values without type guards.\n *\n * @param error - The error value\n * @param fallback - Fallback message if extraction fails\n * @returns The error message string\n *\n * @remarks\n * Inspects the value for an `Error` instance, a plain string, or an object\n * with a `message` property before falling back to the provided default.\n *\n * @example\n * ```typescript\n * const message = getErrorMessage(err, 'Unknown error');\n * ```\n */\nexport function getErrorMessage(error: unknown, fallback = 'Unknown error'): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (\n error !== null &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n\n return fallback;\n}\n\n/**\n * Format error details for logging or display.\n *\n * Includes stack trace for Error instances when includeStack is true.\n *\n * @param error - The error to format\n * @param context - Optional context to prepend\n * @param includeStack - Whether to include stack traces (default: false)\n * @returns Formatted error string\n *\n * @remarks\n * When `context` is provided it is prefixed in square brackets (e.g.\n * `[Database] Connection refused`). Stack traces are appended on a new line\n * only when `includeStack` is `true` and the value is an `Error` with a stack.\n *\n * @example\n * ```typescript\n * console.error(formatError(err, 'Database connection'));\n * // Output: [Database connection] Connection refused\n * ```\n */\nexport function formatError(error: unknown, context?: string, includeStack = false): string {\n const message = getErrorMessage(error);\n const prefix = context ? `[${context}] ` : '';\n let result = `${prefix}${message}`;\n\n if (includeStack && error instanceof Error && error.stack) {\n result += `\\n${error.stack}`;\n }\n\n return result;\n}\n\n/**\n * Check if an error represents a specific error type by code or name.\n *\n * Useful for conditional error handling based on error types.\n *\n * @param error - The error to check\n * @param codeOrName - The error code or name to match\n * @returns True if the error matches\n *\n * @remarks\n * Checks both `Error.name` and a custom `code` property, supporting both\n * standard and LAFS-style error codes (e.g. `\"E_NOT_FOUND\"`).\n *\n * @example\n * ```typescript\n * if (isErrorType(err, 'E_NOT_FOUND')) {\n * // Handle not found specifically\n * }\n * ```\n */\nexport function isErrorType(error: unknown, codeOrName: string): boolean {\n if (error instanceof Error) {\n if (error.name === codeOrName) {\n return true;\n }\n // Check for custom code property\n if ('code' in error && error.code === codeOrName) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Create a standardized error result object.\n *\n * Common pattern for operations that return { success: boolean, error?: string }\n *\n * @param error - The error value\n * @returns Error result object\n *\n * @remarks\n * Pairs with {@link createSuccessResult} and {@link isErrorResult} to provide\n * a consistent result-or-error pattern without exceptions.\n *\n * @example\n * ```typescript\n * return createErrorResult(err);\n * // Returns: { success: false, error: \"Something went wrong\" }\n * ```\n */\nexport function createErrorResult(error: unknown): { success: false; error: string } {\n return {\n success: false,\n error: getErrorMessage(error),\n };\n}\n\n/**\n * Create a standardized success result object.\n *\n * @returns Success result object\n *\n * @remarks\n * Pairs with {@link createErrorResult} and {@link isErrorResult} to provide\n * a consistent result-or-error pattern without exceptions.\n *\n * @example\n * ```typescript\n * return createSuccessResult();\n * // Returns: { success: true }\n * ```\n */\nexport function createSuccessResult(): { success: true } {\n return { success: true };\n}\n\n/**\n * Type guard for error results.\n *\n * @param result - The result to check\n * @returns True if the result is an error result\n *\n * @remarks\n * Narrows the result type so that `result.error` is guaranteed to be a string\n * after the guard returns `true`.\n *\n * @example\n * ```typescript\n * const result = await someOperation();\n * if (isErrorResult(result)) {\n * console.error(result.error);\n * }\n * ```\n */\nexport function isErrorResult(result: {\n success: boolean;\n error?: string;\n}): result is { success: false; error: string } {\n return !result.success;\n}\n", "/**\n * CLEO exit codes \u2014 canonical definitions shared across all layers.\n *\n * Ranges: 0 = success, 1-99 = errors, 100+ = special (non-error) states.\n *\n * @epic T4454\n * @task T4456\n * @task T5710\n */\n\nexport enum ExitCode {\n // === SUCCESS (0) ===\n SUCCESS = 0,\n\n // === GENERAL ERRORS (1-9) ===\n GENERAL_ERROR = 1,\n INVALID_INPUT = 2,\n FILE_ERROR = 3,\n NOT_FOUND = 4,\n DEPENDENCY_ERROR = 5,\n VALIDATION_ERROR = 6,\n LOCK_TIMEOUT = 7,\n CONFIG_ERROR = 8,\n\n // === HIERARCHY ERRORS (10-19) ===\n PARENT_NOT_FOUND = 10,\n DEPTH_EXCEEDED = 11,\n SIBLING_LIMIT = 12,\n INVALID_PARENT_TYPE = 13,\n CIRCULAR_REFERENCE = 14,\n ORPHAN_DETECTED = 15,\n HAS_CHILDREN = 16,\n TASK_COMPLETED = 17,\n CASCADE_FAILED = 18,\n HAS_DEPENDENTS = 19,\n\n // === CONCURRENCY ERRORS (20-29) ===\n CHECKSUM_MISMATCH = 20,\n CONCURRENT_MODIFICATION = 21,\n ID_COLLISION = 22,\n\n // === SESSION ERRORS (30-39) ===\n SESSION_EXISTS = 30,\n SESSION_NOT_FOUND = 31,\n SCOPE_CONFLICT = 32,\n SCOPE_INVALID = 33,\n TASK_NOT_IN_SCOPE = 34,\n TASK_CLAIMED = 35,\n SESSION_REQUIRED = 36,\n SESSION_CLOSE_BLOCKED = 37,\n ACTIVE_TASK_REQUIRED = 38,\n NOTES_REQUIRED = 39,\n\n // === VERIFICATION ERRORS (40-47) ===\n VERIFICATION_INIT_FAILED = 40,\n GATE_UPDATE_FAILED = 41,\n INVALID_GATE = 42,\n INVALID_AGENT = 43,\n MAX_ROUNDS_EXCEEDED = 44,\n GATE_DEPENDENCY = 45,\n VERIFICATION_LOCKED = 46,\n ROUND_MISMATCH = 47,\n\n // === CONTEXT SAFEGUARD (50-54) ===\n CONTEXT_WARNING = 50,\n CONTEXT_CAUTION = 51,\n CONTEXT_CRITICAL = 52,\n CONTEXT_EMERGENCY = 53,\n CONTEXT_STALE = 54,\n\n // === ORCHESTRATOR ERRORS (60-67) ===\n PROTOCOL_MISSING = 60,\n INVALID_RETURN_MESSAGE = 61,\n MANIFEST_ENTRY_MISSING = 62,\n SPAWN_VALIDATION_FAILED = 63,\n AUTONOMOUS_BOUNDARY = 64,\n HANDOFF_REQUIRED = 65,\n RESUME_FAILED = 66,\n CONCURRENT_SESSION = 67,\n\n // === NEXUS ERRORS (70-79) ===\n NEXUS_NOT_INITIALIZED = 70,\n NEXUS_PROJECT_NOT_FOUND = 71,\n NEXUS_PERMISSION_DENIED = 72,\n NEXUS_INVALID_SYNTAX = 73,\n NEXUS_SYNC_FAILED = 74,\n NEXUS_REGISTRY_CORRUPT = 75,\n NEXUS_PROJECT_EXISTS = 76,\n NEXUS_QUERY_FAILED = 77,\n NEXUS_GRAPH_ERROR = 78,\n NEXUS_RESERVED = 79,\n\n // === LIFECYCLE ENFORCEMENT (80-84) ===\n LIFECYCLE_GATE_FAILED = 80,\n AUDIT_MISSING = 81,\n CIRCULAR_VALIDATION = 82,\n LIFECYCLE_TRANSITION_INVALID = 83,\n PROVENANCE_REQUIRED = 84,\n\n // === ARTIFACT PUBLISH (85-89) ===\n ARTIFACT_TYPE_UNKNOWN = 85,\n ARTIFACT_VALIDATION_FAILED = 86,\n ARTIFACT_BUILD_FAILED = 87,\n ARTIFACT_PUBLISH_FAILED = 88,\n ARTIFACT_ROLLBACK_FAILED = 89,\n\n // === PROVENANCE (90-94) ===\n PROVENANCE_CONFIG_INVALID = 90,\n SIGNING_KEY_MISSING = 91,\n SIGNATURE_INVALID = 92,\n DIGEST_MISMATCH = 93,\n ATTESTATION_INVALID = 94,\n\n // === ADAPTER ERRORS (95-99) ===\n ADAPTER_NOT_FOUND = 95,\n ADAPTER_INIT_FAILED = 96,\n ADAPTER_HOOK_FAILED = 97,\n ADAPTER_SPAWN_FAILED = 98,\n ADAPTER_INSTALL_FAILED = 99,\n\n // === SPECIAL CODES (100+) - NOT errors ===\n NO_DATA = 100,\n ALREADY_EXISTS = 101,\n NO_CHANGE = 102,\n TESTS_SKIPPED = 103,\n\n // === LAFS ENVELOPE VALIDATION (Phase 6) ===\n /**\n * E_LAFS_VIOLATION \u2014 CLI output did not conform to the LAFS envelope\n * schema. Emitted by the CLI renderer middleware when `zod.parse()` on\n * the emitted envelope fails. This is an INTERNAL failure: CLEO itself\n * produced a malformed envelope.\n *\n * @task Phase 6 \u2014 LAFS formalization + schema consolidation\n */\n LAFS_VIOLATION = 104,\n}\n\n/** Check if an exit code represents an error (1-99). */\nexport function isErrorCode(code: ExitCode): boolean {\n return code >= 1 && code < 100;\n}\n\n/** Check if an exit code represents success (0 or 100+). */\nexport function isSuccessCode(code: ExitCode): boolean {\n return code === 0 || code >= 100;\n}\n\n/** Check if an exit code indicates no change (idempotent operation). */\nexport function isNoChangeCode(code: ExitCode): boolean {\n return code === ExitCode.NO_CHANGE;\n}\n\n/** Check if an exit code is recoverable (retry may succeed). */\nexport function isRecoverableCode(code: ExitCode): boolean {\n const nonRecoverable = new Set<ExitCode>([\n ExitCode.FILE_ERROR,\n ExitCode.DEPENDENCY_ERROR,\n ExitCode.CIRCULAR_REFERENCE,\n ExitCode.CASCADE_FAILED,\n ExitCode.SESSION_CLOSE_BLOCKED,\n ExitCode.VERIFICATION_LOCKED,\n ExitCode.CONTEXT_WARNING,\n ExitCode.CONTEXT_CAUTION,\n ExitCode.CONTEXT_CRITICAL,\n ExitCode.CONTEXT_EMERGENCY,\n ExitCode.CONTEXT_STALE,\n ExitCode.AUTONOMOUS_BOUNDARY,\n ExitCode.HANDOFF_REQUIRED,\n ExitCode.NEXUS_PERMISSION_DENIED,\n ExitCode.NEXUS_REGISTRY_CORRUPT,\n ExitCode.CIRCULAR_VALIDATION,\n ExitCode.LIFECYCLE_TRANSITION_INVALID,\n ExitCode.ARTIFACT_TYPE_UNKNOWN,\n ExitCode.ARTIFACT_ROLLBACK_FAILED,\n ExitCode.DIGEST_MISMATCH,\n ]);\n\n if (!isErrorCode(code)) return false;\n return !nonRecoverable.has(code);\n}\n\n/** Human-readable name for an exit code. */\nexport function getExitCodeName(code: ExitCode): string {\n return ExitCode[code] ?? 'UNKNOWN';\n}\n", "/**\n * Facade API interfaces for the Cleo class.\n *\n * These define the public API surface that consumers (e.g. CleoOS) use\n * to interact with @cleocode/core via the `Cleo` facade. Defined here\n * in contracts so downstream packages can import types without depending\n * on core directly.\n *\n * @module facade\n */\n\nimport type { ConduitMessage } from './conduit.js';\nimport type {\n DataAccessor,\n ExternalTask,\n ExternalTaskLink,\n ReconcileOptions,\n ReconcileResult,\n Task,\n TaskPriority,\n TaskSize,\n TaskStatus,\n TaskType,\n} from './index.js';\n\n// ============================================================================\n// Supporting types (previously scattered across core modules)\n// ============================================================================\n\n// --- Brain / Memory ---\n\n/** Observation type categories for brain entries. */\nexport const BRAIN_OBSERVATION_TYPES = [\n 'discovery',\n 'change',\n 'feature',\n 'bugfix',\n 'decision',\n 'refactor',\n] as const;\n\n/** Brain observation type. */\nexport type BrainObservationType = (typeof BRAIN_OBSERVATION_TYPES)[number];\n\n/** Options for hybrid (FTS + vector + graph) brain search. */\nexport interface HybridSearchOptions {\n /** Weight for full-text search results (0-1). */\n ftsWeight?: number;\n /** Weight for vector similarity results (0-1). */\n vecWeight?: number;\n /** Weight for graph-based results (0-1). */\n graphWeight?: number;\n /** Maximum number of results to return. */\n limit?: number;\n}\n\n// --- Admin / Import ---\n\n/** Strategy for handling duplicate tasks during import. */\nexport type DuplicateStrategy = 'skip' | 'overwrite' | 'rename';\n\n/** Parameters for task import operations. */\nexport interface ImportParams {\n /** Path to the import file. */\n file: string;\n /** Parent task ID for imported tasks. */\n parent?: string;\n /** Phase assignment for imported tasks. */\n phase?: string;\n /** Strategy when a duplicate task ID is found. */\n onDuplicate?: DuplicateStrategy;\n /** Label to add to all imported tasks. */\n addLabel?: string;\n /** If true, simulate the import without persisting. */\n dryRun?: boolean;\n /** Working directory for resolving paths. */\n cwd?: string;\n}\n\n// --- Agents ---\n\n/** Agent instance status values. */\nexport const AGENT_INSTANCE_STATUSES = [\n 'starting',\n 'active',\n 'idle',\n 'error',\n 'crashed',\n 'stopped',\n] as const;\n\n/** Agent instance status type. */\nexport type AgentInstanceStatus = (typeof AGENT_INSTANCE_STATUSES)[number];\n\n/** Agent type classification values. */\nexport const AGENT_TYPES = [\n 'orchestrator',\n 'executor',\n 'researcher',\n 'architect',\n 'validator',\n 'documentor',\n 'custom',\n] as const;\n\n/** Agent type classification. */\nexport type AgentType = (typeof AGENT_TYPES)[number];\n\n/**\n * Row shape for the `agent_instances` table.\n *\n * Manually defined to avoid Drizzle dependency in contracts.\n * Must stay in sync with `packages/core/src/agents/agent-schema.ts`.\n */\nexport interface AgentInstanceRow {\n /** Unique agent instance ID. */\n id: string;\n /** Agent type classification. */\n agentType: AgentType;\n /** Current status. */\n status: AgentInstanceStatus;\n /** Associated session ID (nullable). */\n sessionId: string | null;\n /** Associated task ID (nullable). */\n taskId: string | null;\n /** ISO timestamp when the agent started. */\n startedAt: string;\n /** ISO timestamp of the last heartbeat. */\n lastHeartbeat: string;\n /** ISO timestamp when the agent stopped (nullable). */\n stoppedAt: string | null;\n /** Number of errors encountered. */\n errorCount: number;\n /** Total tasks completed by this agent. */\n totalTasksCompleted: number;\n /** Agent capacity as a string (e.g. \"1.0\"). */\n capacity: string;\n /** JSON-encoded metadata. */\n metadataJson: string | null;\n /** Parent agent ID for hierarchical orchestration (nullable). */\n parentAgentId: string | null;\n}\n\n/** Options for registering a new agent instance. */\nexport interface RegisterAgentOptions {\n /** Agent type classification. */\n agentType: AgentType;\n /** Session to associate with. */\n sessionId?: string;\n /** Task to associate with. */\n taskId?: string;\n /** Parent agent ID for hierarchical orchestration. */\n parentAgentId?: string;\n /** Arbitrary metadata. */\n metadata?: Record<string, unknown>;\n}\n\n/** Agent capacity information. */\nexport interface AgentCapacity {\n /** Agent instance ID. */\n agentId: string;\n /** Agent type classification. */\n agentType: AgentType;\n /** Current status of the agent. */\n status: AgentInstanceStatus;\n /** Number of tasks currently assigned to this agent. */\n activeTasks: number;\n /** Number of additional tasks this agent can accept (max - active). */\n remainingCapacity: number;\n /** Maximum tasks this agent can hold. */\n maxCapacity: number;\n /** Whether this agent can accept new tasks. */\n available: boolean;\n}\n\n/** Agent health status from heartbeat monitoring. */\nexport interface AgentHealthStatus {\n /** Agent instance ID. */\n agentId: string;\n /** Current DB status. */\n status: AgentInstanceStatus;\n /** ISO timestamp of the last recorded heartbeat. */\n lastHeartbeat: string;\n /** Milliseconds since the last recorded heartbeat (at call time). */\n heartbeatAgeMs: number;\n /** Whether the agent is considered healthy (heartbeat within threshold). */\n healthy: boolean;\n /** Whether the agent is considered stale (heartbeat older than threshold). */\n stale: boolean;\n /** Threshold used for staleness determination (ms). */\n thresholdMs: number;\n}\n\n// --- Intelligence ---\n\n/** Severity classification for blast radius. */\nexport type BlastRadiusSeverity = 'isolated' | 'moderate' | 'widespread' | 'critical';\n\n/** A single task predicted to be affected by a change. */\nexport interface ImpactedTask {\n /** Task ID. */\n id: string;\n /** Task title. */\n title: string;\n /** Current task status. */\n status: string;\n /** Current task priority. */\n priority: string;\n /** Severity of exposure to the change. */\n exposure: 'direct' | 'dependent' | 'transitive';\n /** Number of downstream tasks that depend on this task. */\n downstreamCount: number;\n /** Why this task is predicted to be affected. */\n reason: string;\n}\n\n/** Full impact prediction report for a free-text change description. */\nexport interface ImpactReport {\n /** The original free-text change description. */\n change: string;\n /** Tasks directly matched by the change description (fuzzy search). */\n matchedTasks: ImpactedTask[];\n /** All tasks predicted to be affected, ordered by exposure severity. */\n affectedTasks: ImpactedTask[];\n /** Total count of distinct affected tasks (including direct matches). */\n totalAffected: number;\n /** Human-readable summary of predicted impact scope. */\n summary: string;\n}\n\n/** Quantified scope of a task's impact across the project. */\nexport interface BlastRadius {\n /** Number of direct dependents. */\n directCount: number;\n /** Number of transitive dependents (full downstream tree). */\n transitiveCount: number;\n /** Number of distinct epics affected. */\n epicCount: number;\n /** Percentage of the total project impacted (0-100). */\n projectPercentage: number;\n /** Classification of impact severity. */\n severity: BlastRadiusSeverity;\n}\n\n// ============================================================================\n// Task work types\n// ============================================================================\n\n/** Result of starting work on a task. */\nexport interface TaskStartResult {\n /** The task ID that was started. */\n taskId: string;\n /** The task title. */\n title: string;\n /** Previous task ID if one was active (auto-stopped). */\n previousTask?: string | null;\n}\n\n// ============================================================================\n// Facade API interfaces\n// ============================================================================\n\n/** Tasks domain API. */\nexport interface TasksAPI {\n /** Add a new task. */\n add(params: {\n title: string;\n description: string;\n parent?: string;\n priority?: TaskPriority;\n type?: TaskType;\n size?: TaskSize;\n phase?: string;\n labels?: string[];\n depends?: string[];\n notes?: string;\n }): Promise<unknown>;\n /** Find tasks by query, ID, status, or limit. */\n find(params: {\n query?: string;\n id?: string;\n status?: TaskStatus;\n limit?: number;\n }): Promise<unknown>;\n /** Show full details of a task. */\n show(taskId: string): Promise<unknown>;\n /** List tasks with optional filters. */\n list(params?: {\n status?: TaskStatus;\n priority?: TaskPriority;\n parentId?: string;\n phase?: string;\n limit?: number;\n }): Promise<unknown>;\n /** Update task fields. */\n update(params: {\n taskId: string;\n title?: string;\n status?: TaskStatus;\n priority?: TaskPriority;\n description?: string;\n notes?: string;\n }): Promise<unknown>;\n /** Complete a task with optional notes. */\n complete(params: { taskId: string; notes?: string }): Promise<unknown>;\n /** Delete a task. */\n delete(params: { taskId: string; force?: boolean }): Promise<unknown>;\n /** Archive tasks by date or IDs. */\n archive(params?: { before?: string; taskIds?: string[]; dryRun?: boolean }): Promise<unknown>;\n /** Start working on a specific task (sets focus). */\n start(taskId: string): Promise<unknown>;\n /** Stop working on the current task (clears focus). */\n stop(): Promise<{ previousTask: string | null }>;\n /** Get the current task work state. */\n current(): Promise<unknown>;\n}\n\n/** Sessions domain API. */\nexport interface SessionsAPI {\n /** Start a new session. */\n start(params: {\n name: string;\n scope: string;\n agent?: string;\n startTask?: string;\n }): Promise<unknown>;\n /** End the current session. */\n end(params?: { note?: string }): Promise<unknown>;\n /** Get current session status. */\n status(): Promise<unknown>;\n /** Resume an existing session. */\n resume(sessionId: string): Promise<unknown>;\n /** List sessions with optional filters. */\n list(params?: { status?: string; limit?: number }): Promise<unknown>;\n /** Find sessions by criteria. */\n find(params?: {\n status?: string;\n scope?: string;\n query?: string;\n limit?: number;\n }): Promise<unknown>;\n /** Show full details of a session. */\n show(sessionId: string): Promise<unknown>;\n /** Suspend a session. */\n suspend(sessionId: string, reason?: string): Promise<unknown>;\n /** Compute session briefing. */\n briefing(params?: { maxNextTasks?: number; scope?: string }): Promise<unknown>;\n /** Compute session handoff. */\n handoff(sessionId: string, options?: { note?: string; nextAction?: string }): Promise<unknown>;\n /** Garbage-collect stale sessions. */\n gc(maxAgeHours?: number): Promise<unknown>;\n /** Record a decision in a session. */\n recordDecision(params: {\n sessionId: string;\n taskId: string;\n decision: string;\n rationale: string;\n alternatives?: string[];\n }): Promise<unknown>;\n /** Record an assumption. */\n recordAssumption(params: {\n assumption: string;\n confidence: 'high' | 'medium' | 'low';\n sessionId?: string;\n taskId?: string;\n }): Promise<unknown>;\n /** Get context drift metrics. */\n contextDrift(params?: { sessionId?: string }): Promise<unknown>;\n /** Get decision log. */\n decisionLog(params?: { sessionId?: string; taskId?: string }): Promise<unknown>;\n /** Get last handoff for a scope. */\n lastHandoff(scope?: { type: string; epicId?: string }): Promise<unknown>;\n /** Serialize a session into a complete snapshot for persistence. */\n serialize(params?: { sessionId?: string; maxObservations?: number }): Promise<unknown>;\n /** Restore a session from a previously serialized snapshot. */\n restore(snapshot: unknown, params?: { agent?: string; activate?: boolean }): Promise<unknown>;\n}\n\n/** Memory/Brain domain API. */\nexport interface MemoryAPI {\n /** Record a brain observation. */\n observe(params: { text: string; title?: string; type?: BrainObservationType }): Promise<unknown>;\n /** Find brain entries by query. */\n find(params: {\n query: string;\n limit?: number;\n tables?: Array<'decisions' | 'patterns' | 'learnings' | 'observations'>;\n }): Promise<unknown>;\n /** Fetch brain entries by IDs. */\n fetch(params: { ids: string[] }): Promise<unknown>;\n /** Get temporal context around an anchor entry. */\n timeline(params: { anchor: string; depthBefore?: number; depthAfter?: number }): Promise<unknown>;\n /** Search brain entries. */\n search(query: string, options?: { limit?: number }): Promise<unknown>;\n /** Hybrid search combining FTS, vector, and graph. */\n hybridSearch(query: string, options?: HybridSearchOptions): Promise<unknown>;\n}\n\n/** Orchestration domain API. */\nexport interface OrchestrationAPI {\n /** Start orchestration for an epic. */\n start(epicId: string): Promise<unknown>;\n /** Analyze an epic's structure and dependencies. */\n analyze(epicId: string): Promise<unknown>;\n /** Get tasks ready to execute in an epic. */\n readyTasks(epicId: string): Promise<unknown>;\n /** Get the next recommended task in an epic. */\n nextTask(epicId: string): Promise<unknown>;\n /** Get orchestrator context for an epic. */\n context(epicId: string): Promise<unknown>;\n /** Build a dependency graph from tasks. */\n dependencyGraph(tasks: Task[]): unknown;\n /** Compute epic status summary. */\n epicStatus(epicId: string, title: string, children: Task[]): unknown;\n /** Compute progress metrics for tasks. */\n progress(tasks: Task[]): unknown;\n}\n\n/** Lifecycle pipeline domain API. */\nexport interface LifecycleAPI {\n /** Get lifecycle status for an epic. */\n status(epicId: string): Promise<unknown>;\n /** Start a pipeline stage. */\n startStage(epicId: string, stage: string): Promise<unknown>;\n /** Complete a pipeline stage. */\n completeStage(epicId: string, stage: string, artifacts?: string[]): Promise<unknown>;\n /** Skip a pipeline stage. */\n skipStage(epicId: string, stage: string, reason: string): Promise<unknown>;\n /** Check gate requirements for a stage. */\n checkGate(epicId: string, targetStage: string): Promise<unknown>;\n /** Get lifecycle history for an epic. */\n history(epicId: string): Promise<unknown>;\n /** Reset a pipeline stage. */\n resetStage(epicId: string, stage: string, reason: string): Promise<unknown>;\n /** Pass a gate check. */\n passGate(epicId: string, gateName: string, agent?: string): Promise<unknown>;\n /** Fail a gate check. */\n failGate(epicId: string, gateName: string, reason?: string): Promise<unknown>;\n /** Available pipeline stages. */\n stages: readonly string[];\n}\n\n/** Release management domain API. */\nexport interface ReleaseAPI {\n /** Prepare a release. */\n prepare(params: { version: string; tasks?: string[]; notes?: string }): Promise<unknown>;\n /** Commit a release. */\n commit(params: { version: string }): Promise<unknown>;\n /** Tag a release. */\n tag(params: { version: string }): Promise<unknown>;\n /** Push a release. */\n push(params: { version: string; remote?: string; explicitPush?: boolean }): Promise<unknown>;\n /** Rollback a release. */\n rollback(params: { version: string; reason?: string }): Promise<unknown>;\n /** Calculate new version from bump type. */\n calculateVersion(current: string, bumpType: string): string;\n /** Bump version from config. */\n bumpVersion(): Promise<unknown>;\n}\n\n/** Admin domain API. */\nexport interface AdminAPI {\n /** Export tasks. */\n export(params?: Record<string, unknown>): Promise<unknown>;\n /** Import tasks from file. */\n import(params: Omit<ImportParams, 'cwd'>): Promise<unknown>;\n}\n\n/** Sticky notes domain API. */\nexport interface StickyAPI {\n /** Add a sticky note. */\n add(params: {\n content: string;\n tags?: string[];\n priority?: string;\n color?: string;\n }): Promise<unknown>;\n /** Show a sticky note. */\n show(stickyId: string): Promise<unknown>;\n /** List sticky notes with optional filters. */\n list(params?: {\n status?: string;\n color?: string;\n priority?: string;\n limit?: number;\n }): Promise<unknown>;\n /** Archive a sticky note. */\n archive(stickyId: string): Promise<unknown>;\n /** Purge a sticky note. */\n purge(stickyId: string): Promise<unknown>;\n /** Convert a sticky note to task or memory. */\n convert(params: {\n stickyId: string;\n targetType: 'task' | 'memory' | 'task_note' | 'session_note';\n title?: string;\n memoryType?: string;\n taskId?: string;\n }): Promise<unknown>;\n}\n\n/** Cross-project Nexus domain API. */\nexport interface NexusAPI {\n /** Initialize nexus for the current project. */\n init(): Promise<unknown>;\n /** Register a project in the nexus. */\n register(params: { path: string; name?: string; permissions?: string }): Promise<unknown>;\n /** Unregister a project from the nexus. */\n unregister(params: { name: string }): Promise<unknown>;\n /** List registered projects. */\n list(): Promise<unknown>;\n /** Show details of a registered project. */\n show(params: { name: string }): Promise<unknown>;\n /** Sync a project or all projects. */\n sync(params?: { name?: string }): Promise<unknown>;\n /** Discover related content across projects. */\n discover(params: { query: string; method?: string; limit?: number }): Promise<unknown>;\n /** Search across registered projects. */\n search(params: { pattern: string; project?: string; limit?: number }): Promise<unknown>;\n /** Set permission level for a project. */\n setPermission(params: { name: string; level: 'read' | 'write' | 'execute' }): Promise<unknown>;\n /** Get sharing status. */\n sharingStatus(): Promise<unknown>;\n /** Route a Conduit directive message to the correct project (ORCH-PLAN B.2). */\n route(message: ConduitMessage): Promise<unknown>;\n /** Get aggregated task status across all registered projects (ORCH-PLAN B.3). */\n workspaceStatus(): Promise<unknown>;\n /** Get all agents registered across all projects (ORCH-PLAN B.4). */\n workspaceAgents(): Promise<unknown>;\n}\n\n/** Task reconciliation / sync domain API. */\nexport interface SyncAPI {\n /** Reconcile external tasks with CLEO as SSoT. */\n reconcile(params: {\n externalTasks: ExternalTask[];\n providerId: string;\n dryRun?: boolean;\n conflictPolicy?: ReconcileOptions['conflictPolicy'];\n defaultPhase?: string;\n defaultLabels?: string[];\n }): Promise<ReconcileResult>;\n /** Get all external task links for a provider. */\n getLinks(providerId: string): Promise<ExternalTaskLink[]>;\n /** Get all external task links for a CLEO task. */\n getTaskLinks(taskId: string): Promise<ExternalTaskLink[]>;\n /** Remove all external task links for a provider. */\n removeProviderLinks(providerId: string): Promise<number>;\n}\n\n/** Agent registry domain API. */\nexport interface AgentsAPI {\n /** Register a new agent instance. */\n register(options: RegisterAgentOptions): Promise<AgentInstanceRow>;\n /** Deregister an agent instance. */\n deregister(agentId: string): Promise<AgentInstanceRow | null>;\n /** Get health status for a specific agent. */\n health(agentId: string): Promise<AgentHealthStatus | null>;\n /** Detect agents that have crashed (missed heartbeats). */\n detectCrashed(thresholdMs?: number): Promise<AgentInstanceRow[]>;\n /** Record a heartbeat for an agent. */\n recordHeartbeat(agentId: string): Promise<unknown>;\n /** Get capacity info for an agent. */\n capacity(agentId: string): Promise<AgentCapacity | null>;\n /** Check if system is overloaded (available capacity below threshold). */\n isOverloaded(threshold?: number): Promise<boolean>;\n /** List all agent instances with optional filters. */\n list(params?: { status?: string; agentType?: string }): Promise<AgentInstanceRow[]>;\n}\n\n/** Intelligence / impact analysis domain API. */\nexport interface IntelligenceAPI {\n /** Predict impact of a change description on related tasks. */\n predictImpact(change: string): Promise<ImpactReport>;\n /** Calculate blast radius for a task change. */\n blastRadius(taskId: string): Promise<BlastRadius>;\n}\n\n/** Options for initializing the Cleo facade. */\nexport interface CleoInitOptions {\n /** Custom data accessor (store backend). */\n store?: DataAccessor;\n /** Enable CAAMP injection. */\n caamp?: boolean;\n}\n", "/**\n * LAFS (LLM-Agent-First Schema) unified envelope types.\n *\n * Defines canonical LAFS types inline (contracts has ZERO external dependencies).\n * In the main CLEO codebase these are re-exported from @cleocode/lafs;\n * here they are defined as plain interfaces for maximum portability.\n *\n * @epic T4654\n * @task T4655\n */\n\n// ---------------------------------------------------------------------------\n// Canonical LAFS types (inlined from @cleocode/lafs)\n// ---------------------------------------------------------------------------\n\n/** LAFS error category. */\nexport type LAFSErrorCategory =\n | 'validation'\n | 'not_found'\n | 'conflict'\n | 'authorization'\n | 'internal'\n | 'rate_limit'\n | 'timeout'\n | 'dependency';\n\n/** LAFS error object. */\nexport interface LAFSError {\n /** Stable error code (numeric HTTP status or string identifier). */\n code: number | string;\n /** High-level error classification category. */\n category: LAFSErrorCategory;\n /** Human-readable error description. */\n message: string;\n /**\n * Suggested fix or recovery action for the caller.\n *\n * @defaultValue undefined\n */\n fix?: string;\n /**\n * Arbitrary key-value pairs with additional error context.\n *\n * @defaultValue undefined\n */\n details?: Record<string, unknown>;\n}\n\n/** LAFS warning. */\nexport interface Warning {\n /** Machine-readable warning code. */\n code: string;\n /** Human-readable warning description. */\n message: string;\n}\n\n/** LAFS transport metadata. */\nexport type LAFSTransport = 'cli' | 'http' | 'sdk';\n\n/** MVI (Minimal Viable Information) level. */\nexport type MVILevel = 'minimal' | 'standard' | 'full';\n\n/** LAFS page \u2014 no pagination. */\nexport interface LAFSPageNone {\n /** Discriminant indicating no pagination is applied. */\n strategy: 'none';\n}\n\n/** LAFS page \u2014 offset-based pagination. */\nexport interface LAFSPageOffset {\n /** Discriminant identifying offset-based pagination. */\n strategy: 'offset';\n /** Zero-based index of the first item in this page. */\n offset: number;\n /** Maximum number of items per page. */\n limit: number;\n /** Total number of items across all pages. */\n total: number;\n /** Whether additional pages exist beyond the current one. */\n hasMore: boolean;\n}\n\n/** LAFS page union. */\nexport type LAFSPage = LAFSPageNone | LAFSPageOffset;\n\n/** LAFS metadata block. */\nexport interface LAFSMeta {\n /** Transport protocol used for this envelope. */\n transport: LAFSTransport;\n /** Minimum Viable Information level controlling verbosity. */\n mvi: MVILevel;\n /**\n * Pagination metadata when the result is a paginated collection.\n *\n * @defaultValue undefined\n */\n page?: LAFSPage;\n /**\n * Non-fatal warnings to surface to the consuming agent.\n *\n * @defaultValue undefined\n */\n warnings?: Warning[];\n /**\n * Operation duration in milliseconds.\n *\n * @defaultValue undefined\n */\n durationMs?: number;\n}\n\n/** LAFS envelope (canonical protocol type). */\nexport interface LAFSEnvelope<T = unknown> {\n /** Whether the operation completed successfully. */\n success: boolean;\n /**\n * Operation result payload on success.\n *\n * @defaultValue undefined\n */\n data?: T;\n /**\n * Structured error payload on failure.\n *\n * @defaultValue undefined\n */\n error?: LAFSError;\n /**\n * Protocol and transport metadata.\n *\n * @defaultValue undefined\n */\n _meta?: LAFSMeta;\n}\n\n/** Flag input for conformance checks. */\nexport interface FlagInput {\n /** Name of the flag being checked. */\n flag: string;\n /** Value of the flag to validate. */\n value: unknown;\n}\n\n/** Conformance report. */\nexport interface ConformanceReport {\n /** Whether all conformance checks passed. */\n valid: boolean;\n /** List of conformance violation descriptions. */\n violations: string[];\n /** List of non-fatal warning descriptions. */\n warnings: string[];\n}\n\n// ---------------------------------------------------------------------------\n// CLEO-specific error detail (backward compatible)\n// ---------------------------------------------------------------------------\n\n/** Actionable alternative the caller can try. */\nexport interface LafsAlternative {\n /** Description of the alternative action. */\n action: string;\n /** CLI command the caller can run instead. */\n command: string;\n}\n\n/** LAFS error detail shared between CLI and gateway. */\nexport interface LafsErrorDetail {\n /** Stable error code (numeric HTTP status or string identifier). */\n code: number | string;\n /**\n * Optional human-readable error name (e.g. `\"NOT_FOUND\"`).\n *\n * @defaultValue undefined\n */\n name?: string;\n /** Human-readable error description. */\n message: string;\n /**\n * Suggested fix or recovery action for the caller.\n *\n * @defaultValue undefined\n */\n fix?: string;\n /**\n * Alternative commands the caller can try.\n *\n * @defaultValue undefined\n */\n alternatives?: LafsAlternative[];\n /**\n * Arbitrary key-value pairs with additional error context.\n *\n * @defaultValue undefined\n */\n details?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// CLI envelope (base) - backward compatible\n// ---------------------------------------------------------------------------\n\n/** LAFS success envelope (CLI). */\nexport interface LafsSuccess<T = unknown> {\n /** Discriminant: always `true` for success envelopes. */\n success: true;\n /** Operation result payload. */\n data: T;\n /**\n * Optional human-readable summary of the operation outcome.\n *\n * @defaultValue undefined\n */\n message?: string;\n /**\n * When `true`, the operation was a no-op (data is unchanged).\n *\n * @defaultValue undefined\n */\n noChange?: boolean;\n}\n\n/** LAFS error envelope (CLI). */\nexport interface LafsError {\n /** Discriminant: always `false` for error envelopes. */\n success: false;\n /** Structured error detail with code, message, and fix guidance. */\n error: LafsErrorDetail;\n}\n\n/** CLI envelope union type. */\nexport type LafsEnvelope<T = unknown> = LafsSuccess<T> | LafsError;\n\n// ---------------------------------------------------------------------------\n// Gateway envelope extension (extends LAFSMeta)\n// ---------------------------------------------------------------------------\n\n/**\n * Metadata attached to every gateway response.\n * Extends the canonical LAFSMeta with CLEO gateway-specific fields.\n *\n * @task T4655\n */\nexport interface GatewayMeta extends LAFSMeta {\n /** Gateway identifier that processed this request. */\n gateway: string;\n /** CLEO domain that handled the operation (e.g. `\"tasks\"`, `\"session\"`). */\n domain: string;\n /** Operation duration in milliseconds. */\n duration_ms: number;\n}\n\n/** Gateway success envelope (extends CLI base with _meta). */\nexport interface GatewaySuccess<T = unknown> extends LafsSuccess<T> {\n /** Gateway-specific metadata including domain and timing. */\n _meta: GatewayMeta;\n}\n\n/** Gateway error envelope (extends CLI base with _meta). */\nexport interface GatewayError extends LafsError {\n /** Gateway-specific metadata including domain and timing. */\n _meta: GatewayMeta;\n}\n\n/** Gateway envelope union type. */\nexport type GatewayEnvelope<T = unknown> = GatewaySuccess<T> | GatewayError;\n\n// ---------------------------------------------------------------------------\n// Unified envelope (covers both CLI and Gateway)\n// ---------------------------------------------------------------------------\n\n/**\n * Unified CLEO response envelope.\n *\n * Every CLEO response (CLI or Gateway) is a CleoResponse. Gateway responses\n * include the _meta field; CLI responses do not.\n */\nexport type CleoResponse<T = unknown> = LafsEnvelope<T> | GatewayEnvelope<T>;\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\n/**\n * Type guard for success responses.\n *\n * @typeParam T - The data payload type of the envelope.\n * @param envelope - The envelope to check.\n * @returns `true` if the envelope represents a successful operation.\n *\n * @remarks\n * Narrows a {@link LafsEnvelope} to {@link LafsSuccess} so that `envelope.data`\n * is accessible without additional type assertions.\n *\n * @example\n * ```ts\n * const result: LafsEnvelope<Task[]> = await fetchTasks();\n * if (isLafsSuccess(result)) {\n * console.log(result.data); // Task[]\n * }\n * ```\n */\nexport function isLafsSuccess<T>(envelope: LafsEnvelope<T>): envelope is LafsSuccess<T> {\n return envelope.success === true;\n}\n\n/**\n * Type guard for error responses.\n *\n * @typeParam T - The data payload type of the envelope.\n * @param envelope - The envelope to check.\n * @returns `true` if the envelope represents a failed operation.\n *\n * @remarks\n * Narrows a {@link LafsEnvelope} to {@link LafsError} so that `envelope.error`\n * is accessible without additional type assertions.\n *\n * @example\n * ```ts\n * const result: LafsEnvelope<Task[]> = await fetchTasks();\n * if (isLafsError(result)) {\n * console.error(result.error.message);\n * }\n * ```\n */\nexport function isLafsError<T>(envelope: LafsEnvelope<T>): envelope is LafsError {\n return envelope.success === false;\n}\n\n/**\n * Type guard for gateway responses (has _meta).\n *\n * @typeParam T - The data payload type of the envelope.\n * @param envelope - The response to check.\n * @returns `true` if the response includes gateway metadata.\n *\n * @remarks\n * Distinguishes gateway responses from plain CLI responses by checking for the\n * presence of the `_meta` field, which carries gateway-specific routing and timing data.\n *\n * @example\n * ```ts\n * const response: CleoResponse<Task> = await handleRequest();\n * if (isGatewayEnvelope(response)) {\n * console.log(response._meta.gateway);\n * }\n * ```\n */\nexport function isGatewayEnvelope<T>(envelope: CleoResponse<T>): envelope is GatewayEnvelope<T> {\n return '_meta' in envelope && envelope._meta !== undefined;\n}\n", "/**\n * Issues Domain Operations (4 operations)\n *\n * Query operations: 1 (diagnostics)\n * Mutate operations: 3 (add.bug, add.feature, add.help)\n *\n * @task T4494\n */\n\n/**\n * Common issue types\n */\nexport type IssueSeverity = 'low' | 'medium' | 'high' | 'critical';\nexport type IssueArea = 'cli' | 'dispatch' | 'docs' | 'tests' | 'other';\nexport type IssueType = 'bug' | 'feature' | 'help';\n\nexport interface Diagnostics {\n cleoVersion: string;\n bashVersion: string;\n jqVersion: string;\n os: string;\n shell: string;\n cleoHome: string;\n ghVersion: string;\n installLocation: string;\n}\n\n/**\n * Query Operations\n */\n\n// issues.diagnostics\nexport type IssuesDiagnosticsParams = Record<string, never>;\nexport interface IssuesDiagnosticsResult {\n diagnostics: Diagnostics;\n}\n\n/**\n * Mutate Operations\n */\n\n// issues.add.bug (alias: create.bug)\nexport interface IssuesCreateBugParams {\n title: string;\n body: string;\n severity?: IssueSeverity;\n area?: IssueArea;\n dryRun?: boolean;\n}\nexport interface IssuesCreateBugResult {\n type: 'bug';\n url: string;\n number: number;\n title: string;\n labels: string[];\n}\n\n// issues.add.feature (alias: create.feature)\nexport interface IssuesCreateFeatureParams {\n title: string;\n body: string;\n area?: IssueArea;\n dryRun?: boolean;\n}\nexport interface IssuesCreateFeatureResult {\n type: 'feature';\n url: string;\n number: number;\n title: string;\n labels: string[];\n}\n\n// issues.add.help (alias: create.help)\nexport interface IssuesCreateHelpParams {\n title: string;\n body: string;\n area?: IssueArea;\n dryRun?: boolean;\n}\nexport interface IssuesCreateHelpResult {\n type: 'help';\n url: string;\n number: number;\n title: string;\n labels: string[];\n}\n", "/**\n * Lifecycle Domain Operations (10 operations)\n *\n * Query operations: 5\n * Mutate operations: 5\n */\n\nimport type { StageStatus } from '../status-registry.js';\n\nexport type { StageStatus };\n\n/**\n * Common lifecycle types\n */\nexport type LifecycleStage =\n | 'research'\n | 'consensus'\n | 'architecture_decision'\n | 'specification'\n | 'decomposition'\n | 'implementation'\n | 'validation'\n | 'testing'\n | 'release';\n\nexport type GateStatus = 'passed' | 'failed' | 'blocked' | null;\n\nexport interface StageRecord {\n stage: LifecycleStage;\n status: StageStatus;\n started?: string;\n completed?: string;\n agent?: string;\n notes?: string;\n}\n\nexport interface Gate {\n name: string;\n stage: LifecycleStage;\n status: GateStatus;\n agent?: string;\n timestamp?: string;\n reason?: string;\n}\n\n/**\n * Query Operations\n */\n\n// lifecycle.check\nexport interface LifecycleCheckParams {\n taskId: string;\n targetStage: LifecycleStage;\n}\nexport interface LifecycleCheckResult {\n taskId: string;\n targetStage: LifecycleStage;\n canProceed: boolean;\n missingPrerequisites: LifecycleStage[];\n gateStatus: 'passed' | 'failed' | 'pending';\n}\n\n// lifecycle.status\nexport interface LifecycleStatusParams {\n taskId?: string;\n epicId?: string;\n}\nexport interface LifecycleStatusResult {\n id: string;\n currentStage: LifecycleStage;\n stages: StageRecord[];\n completedStages: LifecycleStage[];\n pendingStages: LifecycleStage[];\n}\n\n// lifecycle.history\nexport interface LifecycleHistoryParams {\n taskId: string;\n}\nexport interface LifecycleHistoryEntry {\n stage: LifecycleStage;\n from: StageStatus;\n to: StageStatus;\n timestamp: string;\n agent?: string;\n notes?: string;\n}\nexport type LifecycleHistoryResult = LifecycleHistoryEntry[];\n\n// lifecycle.gates\nexport interface LifecycleGatesParams {\n taskId: string;\n}\nexport type LifecycleGatesResult = Gate[];\n\n// lifecycle.prerequisites\nexport interface LifecyclePrerequisitesParams {\n targetStage: LifecycleStage;\n}\nexport interface LifecyclePrerequisitesResult {\n targetStage: LifecycleStage;\n prerequisites: LifecycleStage[];\n optional: LifecycleStage[];\n}\n\n/**\n * Mutate Operations\n */\n\n// lifecycle.progress\nexport interface LifecycleProgressParams {\n taskId: string;\n stage: LifecycleStage;\n status: StageStatus;\n notes?: string;\n}\nexport interface LifecycleProgressResult {\n taskId: string;\n stage: LifecycleStage;\n status: StageStatus;\n timestamp: string;\n}\n\n// lifecycle.skip\nexport interface LifecycleSkipParams {\n taskId: string;\n stage: LifecycleStage;\n reason: string;\n}\nexport interface LifecycleSkipResult {\n taskId: string;\n stage: LifecycleStage;\n skipped: string;\n reason: string;\n}\n\n// lifecycle.reset\nexport interface LifecycleResetParams {\n taskId: string;\n stage: LifecycleStage;\n reason: string;\n}\nexport interface LifecycleResetResult {\n taskId: string;\n stage: LifecycleStage;\n reset: string;\n reason: string;\n warning: string;\n}\n\n// lifecycle.gate.pass\nexport interface LifecycleGatePassParams {\n taskId: string;\n gateName: string;\n agent: string;\n notes?: string;\n}\nexport interface LifecycleGatePassResult {\n taskId: string;\n gateName: string;\n status: 'passed';\n timestamp: string;\n}\n\n// lifecycle.gate.fail\nexport interface LifecycleGateFailParams {\n taskId: string;\n gateName: string;\n reason: string;\n}\nexport interface LifecycleGateFailResult {\n taskId: string;\n gateName: string;\n status: 'failed';\n reason: string;\n timestamp: string;\n}\n", "/**\n * Orchestrate Domain Operations (13 operations)\n *\n * Query operations: 7\n * Mutate operations: 6\n */\n\n/**\n * Common orchestration types\n */\nexport interface Wave {\n wave: number;\n taskIds: string[];\n canRunParallel: boolean;\n dependencies: string[];\n}\n\nexport interface SkillDefinition {\n name: string;\n description: string;\n tags: string[];\n model?: string;\n protocols: string[];\n}\n\n/**\n * Query Operations\n */\n\n// orchestrate.status\nexport interface OrchestrateStatusParams {\n epicId: string;\n}\nexport interface OrchestrateStatusResult {\n epicId: string;\n totalTasks: number;\n completedTasks: number;\n pendingTasks: number;\n blockedTasks: number;\n currentWave: number;\n totalWaves: number;\n parallelCapacity: number;\n}\n\n// orchestrate.next\nexport interface OrchestrateNextParams {\n epicId: string;\n}\nexport interface OrchestrateNextResult {\n taskId: string;\n title: string;\n recommendedSkill: string;\n reasoning: string;\n}\n\n// orchestrate.ready\nexport interface OrchestrateReadyParams {\n epicId: string;\n}\nexport interface OrchestrateReadyResult {\n wave: number;\n taskIds: string[];\n parallelSafe: boolean;\n}\n\n// orchestrate.analyze\nexport interface OrchestrateAnalyzeParams {\n epicId: string;\n}\nexport interface OrchestrateAnalyzeResult {\n waves: Wave[];\n criticalPath: string[];\n estimatedParallelism: number;\n bottlenecks: string[];\n}\n\n// orchestrate.context\nexport interface OrchestrateContextParams {\n tokens?: number;\n}\nexport interface OrchestrateContextResult {\n currentTokens: number;\n maxTokens: number;\n percentUsed: number;\n level: 'safe' | 'medium' | 'high' | 'critical';\n recommendation: string;\n}\n\n// orchestrate.waves\nexport interface OrchestrateWavesParams {\n epicId: string;\n}\nexport type OrchestrateWavesResult = Wave[];\n\n// orchestrate.skill.list\nexport interface OrchestrateSkillListParams {\n filter?: string;\n}\nexport type OrchestrateSkillListResult = SkillDefinition[];\n\n// orchestrate.bootstrap\nexport interface OrchestrateBootstrapParams {\n speed?: 'fast' | 'full' | 'complete';\n}\nexport interface BrainState {\n session?: { id: string; name: string; status: string; startedAt: string };\n currentTask?: { id: string; title: string; status: string };\n nextSuggestion?: { id: string; title: string; score: number };\n recentDecisions?: Array<{ id: string; decision: string; timestamp: string }>;\n blockers?: Array<{ taskId: string; title: string; blockedBy: string[] }>;\n progress?: { total: number; done: number; active: number; blocked: number; pending: number };\n contextDrift?: { score: number; factors: string[] };\n _meta: { speed: 'fast' | 'full' | 'complete'; generatedAt: string; version: string };\n}\n\n/**\n * Mutate Operations\n */\n\n// orchestrate.startup\nexport interface OrchestrateStartupParams {\n epicId: string;\n}\nexport interface OrchestrateStartupResult {\n epicId: string;\n status: OrchestrateStatusResult;\n analysis: OrchestrateAnalyzeResult;\n firstTask: OrchestrateNextResult;\n}\n\n// orchestrate.spawn\nexport interface OrchestrateSpawnParams {\n taskId: string;\n skill?: string;\n model?: string;\n}\nexport interface OrchestrateSpawnResult {\n taskId: string;\n skill: string;\n model: string;\n prompt: string;\n metadata: {\n tokensUsed: number;\n protocolsInjected: string[];\n dependencies: string[];\n };\n}\n\n// orchestrate.handoff\nexport interface OrchestrateHandoffParams {\n taskId: string;\n protocolType: string;\n note?: string;\n nextAction?: string;\n variant?: string;\n tier?: 0 | 1 | 2;\n idempotencyKey?: string;\n}\nexport interface OrchestrateHandoffResult {\n taskId: string;\n predecessorSessionId: string;\n endedSessionId: string;\n protocolType: string;\n}\n\n// orchestrate.validate\nexport interface OrchestrateValidateParams {\n taskId: string;\n}\nexport interface OrchestrateValidateResult {\n taskId: string;\n ready: boolean;\n blockers: string[];\n lifecycleGate: 'passed' | 'failed' | 'pending';\n recommendations: string[];\n}\n\n// orchestrate.parallel.start\nexport interface OrchestrateParallelStartParams {\n epicId: string;\n wave: number;\n}\nexport interface OrchestrateParallelStartResult {\n wave: number;\n taskIds: string[];\n started: string;\n}\n\n// orchestrate.parallel.end\nexport interface OrchestrateParallelEndParams {\n epicId: string;\n wave: number;\n}\nexport interface OrchestrateParallelEndResult {\n wave: number;\n completed: number;\n failed: number;\n duration: string;\n}\n", "/**\n * Release Domain Operations (7 operations)\n *\n * All mutate operations\n */\n\n/**\n * Common release types\n */\nexport type ReleaseType = 'major' | 'minor' | 'patch';\n\nexport interface ReleaseGate {\n name: string;\n description: string;\n passed: boolean;\n reason?: string;\n}\n\nexport interface ChangelogSection {\n type: 'feat' | 'fix' | 'docs' | 'test' | 'refactor' | 'chore';\n entries: Array<{\n taskId: string;\n message: string;\n }>;\n}\n\n/**\n * Mutate Operations\n */\n\n// release.prepare\nexport interface ReleasePrepareParams {\n version: string;\n type: ReleaseType;\n}\nexport interface ReleasePrepareResult {\n version: string;\n type: ReleaseType;\n currentVersion: string;\n files: string[];\n ready: boolean;\n warnings: string[];\n}\n\n// release.changelog\nexport interface ReleaseChangelogParams {\n version: string;\n sections?: Array<'feat' | 'fix' | 'docs' | 'test' | 'refactor' | 'chore'>;\n}\nexport interface ReleaseChangelogResult {\n version: string;\n content: string;\n sections: ChangelogSection[];\n commitCount: number;\n}\n\n// release.commit\nexport interface ReleaseCommitParams {\n version: string;\n files?: string[];\n}\nexport interface ReleaseCommitResult {\n version: string;\n commitHash: string;\n message: string;\n filesCommitted: string[];\n}\n\n// release.tag\nexport interface ReleaseTagParams {\n version: string;\n message?: string;\n}\nexport interface ReleaseTagResult {\n version: string;\n tagName: string;\n created: string;\n}\n\n// release.push\nexport interface ReleasePushParams {\n version: string;\n remote?: string;\n}\nexport interface ReleasePushResult {\n version: string;\n remote: string;\n pushed: string;\n tagsPushed: string[];\n}\n\n// release.gates.run\nexport interface ReleaseGatesRunParams {\n gates?: string[];\n}\nexport interface ReleaseGatesRunResult {\n total: number;\n passed: number;\n failed: number;\n gates: ReleaseGate[];\n canRelease: boolean;\n}\n\n// release.rollback\nexport interface ReleaseRollbackParams {\n version: string;\n reason: string;\n}\nexport interface ReleaseRollbackResult {\n version: string;\n rolledBack: string;\n restoredVersion: string;\n reason: string;\n}\n", "/**\n * Research Domain Operations (legacy alias for memory domain)\n *\n * Query operations: 12 (derived from memory domain)\n * Mutate operations: 5 (derived from memory domain)\n *\n * Note: manifest.* operations moved to pipeline domain (T5241).\n * inject operation moved to session.context.inject (T5241).\n */\n\n/**\n * Common research types\n */\nexport interface ResearchEntry {\n id: string;\n taskId: string;\n title: string;\n file: string;\n date: string;\n status: 'completed' | 'partial' | 'blocked';\n agentType: string;\n topics: string[];\n keyFindings: string[];\n actionable: boolean;\n needsFollowup: string[];\n linkedTasks: string[];\n confidence?: number;\n}\n\nexport interface ManifestEntry {\n id: string;\n file: string;\n title: string;\n date: string;\n status: 'completed' | 'partial' | 'blocked';\n agent_type: string;\n topics: string[];\n key_findings: string[];\n actionable: boolean;\n needs_followup: string[];\n linked_tasks: string[];\n}\n\n/**\n * Query Operations\n */\n\n// research.show\nexport interface ResearchShowParams {\n researchId: string;\n}\nexport type ResearchShowResult = ResearchEntry;\n\n// research.list\nexport interface ResearchListParams {\n epicId?: string;\n status?: 'completed' | 'partial' | 'blocked';\n}\nexport type ResearchListResult = ResearchEntry[];\n\n// research.query\nexport interface ResearchQueryParams {\n query: string;\n confidence?: number;\n}\nexport interface ResearchQueryResult {\n entries: ResearchEntry[];\n matchCount: number;\n avgConfidence: number;\n}\n\n// research.pending\nexport interface ResearchPendingParams {\n epicId?: string;\n}\nexport type ResearchPendingResult = ResearchEntry[];\n\n// research.stats\nexport interface ResearchStatsParams {\n epicId?: string;\n}\nexport interface ResearchStatsResult {\n total: number;\n complete: number;\n partial: number;\n blocked: number;\n byAgentType: Record<string, number>;\n byTopic: Record<string, number>;\n avgConfidence: number;\n}\n\n// pipeline.manifest.list (was research.manifest.read, moved to pipeline T5241)\nexport interface ResearchManifestReadParams {\n filter?: string;\n limit?: number;\n offset?: number;\n}\nexport type ResearchManifestReadResult = ManifestEntry[];\n\n/**\n * Mutate Operations\n */\n\n// session.context.inject (was research.inject, moved to session domain T5241)\nexport interface ResearchInjectParams {\n protocolType:\n | 'research'\n | 'consensus'\n | 'specification'\n | 'decomposition'\n | 'implementation'\n | 'contribution'\n | 'release';\n taskId?: string;\n variant?: string;\n}\nexport interface ResearchInjectResult {\n protocol: string;\n content: string;\n tokensUsed: number;\n}\n\n// research.link\nexport interface ResearchLinkParams {\n researchId: string;\n taskId: string;\n relationship?: 'supports' | 'blocks' | 'references' | 'supersedes';\n}\nexport interface ResearchLinkResult {\n researchId: string;\n taskId: string;\n relationship: string;\n linked: string;\n}\n\n// pipeline.manifest.append (was research.manifest.append, moved to pipeline T5241)\nexport interface ResearchManifestAppendParams {\n entry: ManifestEntry;\n validateFile?: boolean;\n}\nexport interface ResearchManifestAppendResult {\n id: string;\n appended: string;\n validated: boolean;\n}\n\n// pipeline.manifest.archive (was research.manifest.archive, moved to pipeline T5241)\nexport interface ResearchManifestArchiveParams {\n beforeDate?: string;\n moveFiles?: boolean;\n}\nexport interface ResearchManifestArchiveResult {\n archived: number;\n entryIds: string[];\n filesMovedCount?: number;\n}\n", "/**\n * Session Domain Operations (9 operations)\n *\n * Query operations: 4\n * Mutate operations: 5\n *\n * SYNC: Canonical type definitions live in the CLI package at:\n * src/types/session.ts (Session, SessionScope, etc.)\n * These operation types are the API contract (wire format).\n */\n\n/**\n * Common session types\n */\nexport interface SessionOp {\n id: string;\n name: string;\n scope: string;\n started: string;\n ended?: string;\n startedTask?: string;\n status: 'active' | 'suspended' | 'ended';\n notes?: string[];\n}\n\n/**\n * Query Operations\n */\n\n// session.status\nexport type SessionStatusParams = Record<string, never>;\nexport interface SessionStatusResult {\n current: SessionOp | null;\n hasStartedTask: boolean;\n startedTask?: string;\n}\n\n// session.list\nexport interface SessionListParams {\n active?: boolean;\n status?: string;\n limit?: number;\n offset?: number;\n}\nexport interface SessionListResult {\n sessions: SessionOp[];\n total: number;\n filtered: number;\n}\n\n// session.show\nexport interface SessionShowParams {\n sessionId: string;\n}\nexport type SessionShowResult = SessionOp;\n\n// session.history\nexport interface SessionHistoryParams {\n limit?: number;\n}\nexport interface SessionHistoryEntry {\n sessionId: string;\n name: string;\n started: string;\n ended: string;\n tasksCompleted: number;\n duration: string;\n}\nexport type SessionHistoryResult = SessionHistoryEntry[];\n\n/**\n * Mutate Operations\n */\n\n// session.start\nexport interface SessionStartParams {\n scope: string;\n name?: string;\n autoStart?: boolean;\n startTask?: string;\n}\nexport type SessionStartResult = SessionOp;\n\n// session.end\nexport interface SessionEndParams {\n notes?: string;\n /**\n * Structured session summary for direct ingestion into brain.db.\n * When provided, CLEO persists key learnings, decisions, patterns, and next actions.\n * @task T140 @epic T134\n */\n sessionSummary?: import('../config.js').SessionSummaryInput;\n}\nexport interface SessionEndResult {\n session: SessionOp;\n summary: {\n duration: string;\n tasksCompleted: number;\n tasksCreated: number;\n };\n /**\n * A summarization prompt built from this session's debrief data.\n * Populated when `brain.summarization.enabled` is true.\n * @task T140 @epic T134\n */\n memoryPrompt?: string;\n}\n\n// session.resume\nexport interface SessionResumeParams {\n sessionId: string;\n}\nexport type SessionResumeResult = SessionOp;\n\n// session.suspend\nexport interface SessionSuspendParams {\n notes?: string;\n}\nexport interface SessionSuspendResult {\n sessionId: string;\n suspended: string;\n}\n\n// session.gc\nexport interface SessionGcParams {\n olderThan?: string;\n}\nexport interface SessionGcResult {\n cleaned: number;\n sessionIds: string[];\n}\n", "/**\n * Skills Domain Operations (12 operations)\n *\n * Query operations: 6 (list, show, find, dispatch, verify, dependencies)\n * Mutate operations: 6 (install, uninstall, enable, disable, configure, refresh)\n *\n * @task T4387\n */\n\n/**\n * Common skill types\n */\nexport type SkillCategory = 'core' | 'recommended' | 'specialist' | 'composition' | 'meta';\nexport type SkillStatus = 'active' | 'disabled' | 'deprecated' | 'missing';\nexport type DispatchStrategy = 'label' | 'type' | 'keyword' | 'fallback';\n\nexport interface SkillSummary {\n name: string;\n version: string;\n description: string;\n category: SkillCategory;\n core: boolean;\n tier: number;\n status: SkillStatus;\n protocol: string | null;\n}\n\nexport interface SkillDetail extends SkillSummary {\n path: string;\n references: string[];\n dependencies: string[];\n sharedResources: string[];\n compatibility: string[];\n license: string;\n metadata: Record<string, unknown>;\n capabilities?: {\n inputs: string[];\n outputs: string[];\n dispatch_triggers: string[];\n compatible_subagent_types: string[];\n chains_to: string[];\n dispatch_keywords: {\n primary: string[];\n secondary: string[];\n };\n };\n constraints?: {\n max_context_tokens: number;\n requires_session: boolean;\n requires_epic: boolean;\n };\n}\n\nexport interface DispatchCandidate {\n skill: string;\n score: number;\n strategy: DispatchStrategy;\n reason: string;\n}\n\nexport interface DependencyNode {\n name: string;\n version: string;\n direct: boolean;\n depth: number;\n}\n\nexport interface ValidationIssue {\n level: 'error' | 'warn';\n field: string;\n message: string;\n}\n\n/**\n * Query Operations\n */\n\n// skills.list\nexport interface SkillsListParams {\n category?: SkillCategory;\n core?: boolean;\n filter?: string;\n}\nexport type SkillsListResult = SkillSummary[];\n\n// skills.show\nexport interface SkillsShowParams {\n name: string;\n}\nexport type SkillsShowResult = SkillDetail;\n\n// skills.find\nexport interface SkillsFindParams {\n query: string;\n limit?: number;\n}\nexport interface SkillsFindResult {\n query: string;\n results: Array<SkillSummary & { score: number; matchReason: string }>;\n}\n\n// skills.dispatch\nexport interface SkillsDispatchParams {\n taskId?: string;\n taskType?: string;\n labels?: string[];\n title?: string;\n description?: string;\n}\nexport interface SkillsDispatchResult {\n selectedSkill: string;\n reason: string;\n strategy: DispatchStrategy;\n candidates: DispatchCandidate[];\n}\n\n// skills.verify\nexport interface SkillsVerifyParams {\n name?: string;\n}\nexport interface SkillsVerifyResult {\n valid: boolean;\n total: number;\n passed: number;\n failed: number;\n results: Array<{\n name: string;\n valid: boolean;\n issues: ValidationIssue[];\n }>;\n}\n\n// skills.dependencies\nexport interface SkillsDependenciesParams {\n name: string;\n transitive?: boolean;\n}\nexport interface SkillsDependenciesResult {\n name: string;\n dependencies: DependencyNode[];\n resolved: string[];\n}\n\n/**\n * Mutate Operations\n */\n\n// skills.install\nexport interface SkillsInstallParams {\n name: string;\n source?: string;\n}\nexport interface SkillsInstallResult {\n name: string;\n installed: boolean;\n version: string;\n path: string;\n}\n\n// skills.uninstall\nexport interface SkillsUninstallParams {\n name: string;\n force?: boolean;\n}\nexport interface SkillsUninstallResult {\n name: string;\n uninstalled: boolean;\n}\n\n// skills.enable\nexport interface SkillsEnableParams {\n name: string;\n}\nexport interface SkillsEnableResult {\n name: string;\n enabled: boolean;\n status: SkillStatus;\n}\n\n// skills.disable\nexport interface SkillsDisableParams {\n name: string;\n reason?: string;\n}\nexport interface SkillsDisableResult {\n name: string;\n disabled: boolean;\n status: SkillStatus;\n}\n\n// skills.configure\nexport interface SkillsConfigureParams {\n name: string;\n config: Record<string, unknown>;\n}\nexport interface SkillsConfigureResult {\n name: string;\n configured: boolean;\n config: Record<string, unknown>;\n}\n\n// skills.refresh\nexport interface SkillsRefreshParams {\n force?: boolean;\n}\nexport interface SkillsRefreshResult {\n refreshed: boolean;\n skillCount: number;\n timestamp: string;\n}\n", "/**\n * System Domain Operations (12 operations)\n *\n * Query operations: 5\n * Mutate operations: 7\n */\n\n/**\n * Common system types\n */\nexport interface HealthCheck {\n component: string;\n healthy: boolean;\n message?: string;\n}\n\nexport interface ProjectStats {\n tasks: {\n total: number;\n pending: number;\n active: number;\n blocked: number;\n done: number;\n };\n sessions: {\n total: number;\n active: number;\n };\n research: {\n total: number;\n complete: number;\n };\n}\n\n/**\n * Query Operations\n */\n\n// system.version\nexport type SystemVersionParams = Record<string, never>;\nexport interface SystemVersionResult {\n version: string;\n schemaVersion: string;\n buildDate: string;\n}\n\n// system.doctor\nexport type SystemDoctorParams = Record<string, never>;\nexport interface SystemDoctorResult {\n healthy: boolean;\n checks: HealthCheck[];\n warnings: string[];\n errors: string[];\n}\n\n// system.config.get\nexport interface SystemConfigGetParams {\n key: string;\n}\nexport interface SystemConfigGetResult {\n key: string;\n value: unknown;\n type: string;\n}\n\n// system.stats\nexport type SystemStatsParams = Record<string, never>;\nexport type SystemStatsResult = ProjectStats;\n\n// system.context\nexport type SystemContextParams = Record<string, never>;\nexport interface SystemContextResult {\n currentTokens: number;\n maxTokens: number;\n percentUsed: number;\n level: 'safe' | 'medium' | 'high' | 'critical';\n estimatedFiles: number;\n largestFile: {\n path: string;\n tokens: number;\n };\n}\n\n/**\n * Mutate Operations\n */\n\n// system.init\nexport interface SystemInitParams {\n projectType?: 'nodejs' | 'python' | 'bash' | 'typescript' | 'rust' | 'go';\n detect?: boolean;\n}\nexport interface SystemInitResult {\n initialized: boolean;\n projectType?: string;\n filesCreated: string[];\n detectedFeatures?: Record<string, boolean>;\n}\n\n// system.config.set\nexport interface SystemConfigSetParams {\n key: string;\n value: unknown;\n}\nexport interface SystemConfigSetResult {\n key: string;\n value: unknown;\n previousValue?: unknown;\n}\n\n// system.backup\nexport interface SystemBackupParams {\n type?: 'snapshot' | 'safety' | 'archive' | 'migration';\n note?: string;\n}\nexport interface SystemBackupResult {\n backupId: string;\n type: string;\n timestamp: string;\n files: string[];\n size: number;\n}\n\n// system.restore\nexport interface SystemRestoreParams {\n backupId: string;\n}\nexport interface SystemRestoreResult {\n backupId: string;\n restored: string;\n filesRestored: string[];\n}\n\n// system.migrate\nexport interface SystemMigrateParams {\n version?: string;\n dryRun?: boolean;\n}\nexport interface SystemMigrateResult {\n fromVersion: string;\n toVersion: string;\n migrations: Array<{\n name: string;\n applied: boolean;\n error?: string;\n }>;\n dryRun: boolean;\n}\n\n// system.sync\nexport interface SystemSyncParams {\n direction?: 'push' | 'pull' | 'bidirectional';\n}\nexport interface SystemSyncResult {\n direction: string;\n synced: string;\n tasksSynced: number;\n conflicts: Array<{\n taskId: string;\n resolution: string;\n }>;\n}\n\n// system.cleanup\nexport interface SystemCleanupParams {\n type: 'backups' | 'logs' | 'archive' | 'sessions';\n olderThan?: string;\n}\nexport interface SystemCleanupResult {\n type: string;\n cleaned: number;\n freed: number;\n items: string[];\n}\n", "/**\n * Tasks Domain Operations (22 operations)\n *\n * Query operations: 10\n * Mutate operations: 12\n *\n * SYNC: Canonical type definitions live in the CLI package at:\n * src/types/task.ts (TaskStatus, TaskPriority, Task, etc.)\n * These operation types are the API contract (wire format).\n * Internal domain types must stay aligned with CLI definitions.\n */\n\n/**\n * Common task types (API contract \u2014 matches CLI src/types/task.ts)\n */\nimport type { TaskStatus } from '../status-registry.js';\n\nexport type { TaskStatus };\nexport type TaskPriority = 'low' | 'medium' | 'high' | 'critical';\n\nexport interface TaskOp {\n id: string;\n title: string;\n description: string;\n status: TaskStatus;\n priority?: TaskPriority;\n parent?: string;\n depends?: string[];\n labels?: string[];\n created: string;\n updated: string;\n completed?: string;\n notes?: string[];\n}\n\nexport interface MinimalTask {\n id: string;\n title: string;\n status: TaskStatus;\n parent?: string;\n}\n\n/**\n * Query Operations\n */\n\n// tasks.get\nexport interface TasksGetParams {\n taskId: string;\n}\nexport type TasksGetResult = TaskOp;\n\n// tasks.list\nexport interface TasksListParams {\n parent?: string;\n status?: TaskStatus;\n priority?: TaskPriority;\n type?: string;\n phase?: string;\n label?: string;\n children?: boolean;\n limit?: number;\n offset?: number;\n compact?: boolean;\n}\nexport interface TasksListResult {\n tasks: TaskOp[];\n total: number;\n filtered: number;\n}\n\n// tasks.find\nexport interface TasksFindParams {\n query: string;\n limit?: number;\n}\nexport type TasksFindResult = MinimalTask[];\n\n// tasks.exists\nexport interface TasksExistsParams {\n taskId: string;\n}\nexport interface TasksExistsResult {\n exists: boolean;\n taskId: string;\n}\n\n// tasks.tree\nexport interface TasksTreeParams {\n rootId?: string;\n depth?: number;\n}\nexport interface TaskTreeNode {\n task: TaskOp;\n children: TaskTreeNode[];\n depth: number;\n}\nexport type TasksTreeResult = TaskTreeNode[];\n\n// tasks.blockers\nexport interface TasksBlockersParams {\n taskId: string;\n}\nexport interface Blocker {\n taskId: string;\n title: string;\n status: TaskStatus;\n blockType: 'dependency' | 'parent' | 'gate';\n}\nexport type TasksBlockersResult = Blocker[];\n\n// tasks.deps\nexport interface TasksDepsParams {\n taskId: string;\n direction?: 'upstream' | 'downstream' | 'both';\n}\nexport interface TaskDependencyNode {\n taskId: string;\n title: string;\n status: TaskStatus;\n distance: number;\n}\nexport interface TasksDepsResult {\n taskId: string;\n upstream: TaskDependencyNode[];\n downstream: TaskDependencyNode[];\n}\n\n// tasks.analyze\nexport interface TasksAnalyzeParams {\n epicId?: string;\n}\nexport interface TriageRecommendation {\n taskId: string;\n title: string;\n priority: number;\n reason: string;\n readiness: 'ready' | 'blocked' | 'pending';\n}\nexport type TasksAnalyzeResult = TriageRecommendation[];\n\n// tasks.next\nexport interface TasksNextParams {\n epicId?: string;\n count?: number;\n}\nexport interface SuggestedTask {\n taskId: string;\n title: string;\n score: number;\n rationale: string;\n}\nexport type TasksNextResult = SuggestedTask[];\n\n/**\n * Mutate Operations\n */\n\n// tasks.create\nexport interface TasksCreateParams {\n title: string;\n description: string;\n parent?: string;\n depends?: string[];\n priority?: TaskPriority;\n labels?: string[];\n}\nexport type TasksCreateResult = TaskOp;\n\n// tasks.update\nexport interface TasksUpdateParams {\n taskId: string;\n title?: string;\n description?: string;\n status?: TaskStatus;\n priority?: TaskPriority;\n notes?: string;\n parent?: string | null; // Set parent ID, or null/\"\" to promote to root\n labels?: string[];\n addLabels?: string[];\n removeLabels?: string[];\n depends?: string[];\n addDepends?: string[];\n removeDepends?: string[];\n type?: string;\n size?: string;\n}\nexport type TasksUpdateResult = TaskOp;\n\n// tasks.complete\nexport interface TasksCompleteParams {\n taskId: string;\n notes?: string;\n archive?: boolean;\n}\nexport interface TasksCompleteResult {\n taskId: string;\n completed: string;\n archived: boolean;\n}\n\n// tasks.delete\nexport interface TasksDeleteParams {\n taskId: string;\n force?: boolean;\n}\nexport interface TasksDeleteResult {\n taskId: string;\n deleted: true;\n}\n\n// tasks.archive\nexport interface TasksArchiveParams {\n taskId?: string;\n before?: string;\n}\nexport interface TasksArchiveResult {\n archived: number;\n taskIds: string[];\n}\n\n// tasks.unarchive\nexport interface TasksUnarchiveParams {\n taskId: string;\n}\nexport type TasksUnarchiveResult = TaskOp;\n\n// tasks.reparent\nexport interface TasksReparentParams {\n taskId: string;\n newParent: string;\n}\nexport type TasksReparentResult = TaskOp;\n\n// tasks.promote\nexport interface TasksPromoteParams {\n taskId: string;\n}\nexport type TasksPromoteResult = TaskOp;\n\n// tasks.reorder\nexport interface TasksReorderParams {\n taskId: string;\n position: number;\n}\nexport interface TasksReorderResult {\n taskId: string;\n newPosition: number;\n}\n\n// tasks.restore (completed tasks) \u2014 alias: reopen\nexport interface TasksReopenParams {\n taskId: string;\n}\nexport type TasksReopenResult = TaskOp;\n\n// tasks.start (begin working on a task)\nexport interface TasksStartParams {\n taskId: string;\n}\nexport interface TasksStartResult {\n taskId: string;\n sessionId: string;\n timestamp: string;\n}\n\n// tasks.stop (stop working on current task)\nexport type TasksStopParams = Record<string, never>;\nexport interface TasksStopResult {\n stopped: true;\n previousTask?: string;\n}\n\n// tasks.current (get currently active task)\nexport type TasksCurrentParams = Record<string, never>;\nexport interface TasksCurrentResult {\n taskId: string | null;\n since?: string;\n sessionId?: string;\n}\n", "/**\n * Validate Domain Operations (11 operations)\n *\n * Query operations: 9\n * Mutate operations: 2\n */\n\n/**\n * Common validation types\n */\nexport type ValidationSeverity = 'error' | 'warning' | 'info';\n\nexport interface ValidationViolation {\n rule: string;\n severity: ValidationSeverity;\n message: string;\n field?: string;\n value?: unknown;\n expected?: unknown;\n line?: number;\n}\n\nexport interface ComplianceMetrics {\n total: number;\n passed: number;\n failed: number;\n score: number;\n byProtocol: Record<string, { passed: number; failed: number }>;\n bySeverity: Record<ValidationSeverity, number>;\n}\n\n/**\n * Query Operations\n */\n\n// validate.schema\nexport interface ValidateSchemaParams {\n fileType: 'todo' | 'config' | 'archive' | 'log' | 'manifest';\n filePath?: string;\n}\nexport interface ValidateSchemaResult {\n valid: boolean;\n schemaVersion: string;\n violations: ValidationViolation[];\n}\n\n// validate.protocol\nexport interface ValidateProtocolParams {\n taskId: string;\n protocolType:\n | 'research'\n | 'consensus'\n | 'specification'\n | 'decomposition'\n | 'implementation'\n | 'contribution'\n | 'release';\n}\nexport interface ValidateProtocolResult {\n taskId: string;\n protocol: string;\n passed: boolean;\n score: number;\n violations: ValidationViolation[];\n requirements: {\n total: number;\n met: number;\n failed: number;\n };\n}\n\n// validate.task\nexport interface ValidateTaskParams {\n taskId: string;\n checkMode: 'basic' | 'strict' | 'anti-hallucination';\n}\nexport interface ValidateTaskResult {\n taskId: string;\n valid: boolean;\n violations: ValidationViolation[];\n checks: {\n idUniqueness: boolean;\n titleDescriptionDifferent: boolean;\n validStatus: boolean;\n noFutureTimestamps: boolean;\n noDuplicateDescription: boolean;\n };\n}\n\n// validate.manifest\nexport interface ValidateManifestParams {\n entry?: string;\n taskId?: string;\n}\nexport interface ValidateManifestResult {\n valid: boolean;\n entry: {\n id: string;\n file: string;\n exists: boolean;\n };\n violations: ValidationViolation[];\n}\n\n// validate.output\nexport interface ValidateOutputParams {\n taskId: string;\n filePath: string;\n}\nexport interface ValidateOutputResult {\n taskId: string;\n filePath: string;\n valid: boolean;\n checks: {\n fileExists: boolean;\n hasTaskHeader: boolean;\n hasStatus: boolean;\n hasSummary: boolean;\n linkedToTask: boolean;\n };\n violations: ValidationViolation[];\n}\n\n// validate.compliance.summary\nexport interface ValidateComplianceSummaryParams {\n scope?: string;\n since?: string;\n}\nexport type ValidateComplianceSummaryResult = ComplianceMetrics;\n\n// validate.compliance.violations\nexport interface ValidateComplianceViolationsParams {\n severity?: ValidationSeverity;\n protocol?: string;\n}\nexport interface ValidateComplianceViolationsResult {\n violations: Array<\n ValidationViolation & {\n taskId: string;\n protocol: string;\n timestamp: string;\n }\n >;\n total: number;\n}\n\n// validate.test.status\nexport interface ValidateTestStatusParams {\n taskId?: string;\n}\nexport interface ValidateTestStatusResult {\n total: number;\n passed: number;\n failed: number;\n skipped: number;\n passRate: number;\n byTask?: Record<string, { passed: number; failed: number }>;\n}\n\n// validate.test.coverage\nexport interface ValidateTestCoverageParams {\n taskId?: string;\n}\nexport interface ValidateTestCoverageResult {\n lineCoverage: number;\n branchCoverage: number;\n functionCoverage: number;\n statementCoverage: number;\n threshold: number;\n meetsThreshold: boolean;\n}\n\n/**\n * Mutate Operations\n */\n\n// validate.compliance.record\nexport interface ValidateComplianceRecordParams {\n taskId: string;\n result: ValidateProtocolResult;\n}\nexport interface ValidateComplianceRecordResult {\n taskId: string;\n recorded: string;\n metrics: ComplianceMetrics;\n}\n\n// validate.test.run\nexport interface ValidateTestRunParams {\n scope?: string;\n pattern?: string;\n parallel?: boolean;\n}\nexport interface ValidateTestRunResult {\n status: ValidateTestStatusResult;\n coverage: ValidateTestCoverageResult;\n duration: string;\n output?: string;\n}\n", "/**\n * Operations types barrel \u2014 API wire format types for all CLEO domains.\n *\n * These are re-exported under `ops` namespace from the package root\n * to avoid name collisions with canonical domain types.\n */\n\nexport * from './issues.js';\nexport * from './lifecycle.js';\nexport * from './orchestrate.js';\nexport * from './release.js';\nexport * from './research.js';\nexport * from './session.js';\nexport * from './skills.js';\nexport * from './system.js';\nexport * from './tasks.js';\nexport * from './validate.js';\n", "/**\n * Orchestration Hierarchy \u2014 5-level agent hierarchy types.\n *\n * Codifies the agent authority chain from ORCH-PLAN.md:\n * Level 0: HITL (Human-In-The-Loop) \u2014 Owner, final authority\n * Level 1: Prime Orchestrator \u2014 Cross-project coordination\n * Level 2: Project Lead \u2014 Project-level architecture decisions\n * Level 3: Team Lead \u2014 Team-level task management, can spawn ephemeral agents\n * Level 4: Ephemeral \u2014 Task-scoped agents spawned by Team Leads\n *\n * @see docs/specs/CLEO-ORCH-PLAN.md\n * @task T217\n */\n\n// ============================================================================\n// Hierarchy levels\n// ============================================================================\n\n/** The 5 orchestration levels in order of authority. */\nexport enum OrchestrationLevel {\n /** Level 0: Human owner. Final authority. Never contacted by agents directly. */\n HITL = 0,\n /** Level 1: Prime Orchestrator. Cross-project coordination. Breaks ties. */\n Prime = 1,\n /** Level 2: Project Lead. Architecture decisions within a project. */\n ProjectLead = 2,\n /** Level 3: Team Lead. Task management. Can spawn ephemeral agents. */\n TeamLead = 3,\n /** Level 4: Ephemeral agent. Task-scoped, short-lived. */\n Ephemeral = 4,\n}\n\n// ============================================================================\n// Agent hierarchy membership\n// ============================================================================\n\n/** An agent's position in the orchestration hierarchy. */\nexport interface AgentHierarchyEntry {\n /** The agent's unique ID (e.g. 'cleo-rust-lead'). */\n agentId: string;\n /** Display name for human-readable output. */\n displayName: string;\n /** The agent's orchestration level. */\n level: OrchestrationLevel;\n /** The agent's direct superior (null for HITL). */\n reportsTo: string | null;\n /** Agents this agent directly manages (empty for Ephemeral). */\n manages: string[];\n /** Project scope (null for cross-project agents like Prime). */\n projectId: string | null;\n /** Team scope within a project (e.g. 'cleocode', 'signaldock'). */\n teamId: string | null;\n /** Whether this agent can spawn ephemeral sub-agents. */\n canSpawn: boolean;\n}\n\n/** The full agent hierarchy tree. */\nexport interface AgentHierarchy {\n /** All agents in the hierarchy, keyed by agentId. */\n agents: Record<string, AgentHierarchyEntry>;\n /** The Prime Orchestrator agent ID. */\n primeId: string;\n /** Project IDs in this hierarchy. */\n projectIds: string[];\n}\n\n// ============================================================================\n// Escalation chain\n// ============================================================================\n\n/** An escalation path from an agent to its authority chain. */\nexport interface EscalationChain {\n /** The requesting agent. */\n fromAgentId: string;\n /** Ordered list of agents to escalate to (nearest first). */\n chain: string[];\n /** The final authority (PRIME or HITL). */\n finalAuthority: string;\n}\n\n// ============================================================================\n// Hierarchy API\n// ============================================================================\n\n/** API for querying and managing the agent hierarchy. */\nexport interface OrchestrationHierarchyAPI {\n /** Get the full hierarchy. */\n getHierarchy(): AgentHierarchy;\n\n /** Get a single agent's hierarchy entry. */\n getAgent(agentId: string): AgentHierarchyEntry | null;\n\n /** Get all agents at a specific level. */\n getAgentsAtLevel(level: OrchestrationLevel): AgentHierarchyEntry[];\n\n /** Get the escalation chain for an agent. */\n getEscalationChain(agentId: string): EscalationChain;\n\n /** Get all agents managed by a specific agent (direct reports). */\n getDirectReports(agentId: string): AgentHierarchyEntry[];\n\n /** Check if agent A has authority over agent B. */\n hasAuthority(agentIdA: string, agentIdB: string): boolean;\n\n /** Get all agents scoped to a project. */\n getProjectAgents(projectId: string): AgentHierarchyEntry[];\n}\n", "/**\n * Session type definitions for CLEO V2.\n *\n * Plain TypeScript interfaces derived from the Drizzle/Zod schemas\n * in src/store/validation-schemas.ts. Contracts must not depend on Zod/Drizzle.\n *\n * @epic T4454\n */\n\nimport type { SessionStatus } from './status-registry.js';\n\nexport type { SessionStatus };\n\n/** Session scope JSON blob shape. */\nexport interface SessionScope {\n /** Scope type (e.g. `\"global\"`, `\"epic\"`, `\"task\"`, `\"custom\"`). */\n type: string;\n /**\n * Epic ID when scope type is `\"epic\"`.\n * @defaultValue undefined\n */\n epicId?: string;\n /**\n * Root task ID when scope is narrowed to a subtree.\n * @defaultValue undefined\n */\n rootTaskId?: string;\n /**\n * Whether to include descendant tasks of the root task.\n * @defaultValue undefined\n */\n includeDescendants?: boolean;\n /**\n * Phase slug to filter tasks by.\n * @defaultValue undefined\n */\n phaseFilter?: string | null;\n /**\n * Label filter to narrow the scope to specific labels.\n * @defaultValue undefined\n */\n labelFilter?: string[] | null;\n /**\n * Maximum hierarchy depth to include.\n * @defaultValue undefined\n */\n maxDepth?: number | null;\n /**\n * Explicit task IDs to include regardless of other filters.\n * @defaultValue undefined\n */\n explicitTaskIds?: string[] | null;\n /**\n * Task IDs to exclude from the scope.\n * @defaultValue undefined\n */\n excludeTaskIds?: string[] | null;\n /**\n * Task IDs computed from the scope definition at resolution time.\n * @defaultValue undefined\n */\n computedTaskIds?: string[];\n /**\n * ISO 8601 timestamp of when computed task IDs were last resolved.\n * @defaultValue undefined\n */\n computedAt?: string;\n}\n\n/** Session statistics. */\nexport interface SessionStats {\n /** Number of tasks completed during this session. */\n tasksCompleted: number;\n /** Number of new tasks created during this session. */\n tasksCreated: number;\n /** Number of task updates performed during this session. */\n tasksUpdated: number;\n /** Number of times the focus task was changed. */\n focusChanges: number;\n /** Total minutes the session was in active status. */\n totalActiveMinutes: number;\n /** Number of times the session was suspended and resumed. */\n suspendCount: number;\n}\n\n/** Active task work state within a session. */\nexport interface SessionTaskWork {\n /** ID of the task currently being worked on, or `null` if none. */\n taskId: string | null;\n /** ISO 8601 timestamp of when the current task was set, or `null`. */\n setAt: string | null;\n}\n\n/** Session domain type \u2014 plain interface aligned with Drizzle sessions table. */\nexport interface Session {\n /** Unique session identifier (e.g. `\"ses_20260401...\"`) . */\n id: string;\n /** Human-readable session name. */\n name: string;\n /** Current session lifecycle status. */\n status: SessionStatus;\n /** Scope definition controlling which tasks are visible. */\n scope: SessionScope;\n /** Active task work state within the session. */\n taskWork: SessionTaskWork;\n /** ISO 8601 timestamp of when the session started. */\n startedAt: string;\n /** ISO 8601 timestamp of when the session ended. @defaultValue undefined */\n endedAt?: string;\n /** Agent identifier that owns this session. @defaultValue undefined */\n agent?: string;\n /** Timestamped notes appended during the session. @defaultValue undefined */\n notes?: string[];\n /** IDs of tasks completed during this session. @defaultValue undefined */\n tasksCompleted?: string[];\n /** IDs of tasks created during this session. @defaultValue undefined */\n tasksCreated?: string[];\n /** Serialized handoff JSON for session continuity. @defaultValue undefined */\n handoffJson?: string | null;\n /** ID of the session that preceded this one. @defaultValue undefined */\n previousSessionId?: string | null;\n /** ID of the session that follows this one. @defaultValue undefined */\n nextSessionId?: string | null;\n /** Provider-specific agent identifier string. @defaultValue undefined */\n agentIdentifier?: string | null;\n /** ISO 8601 timestamp of when the handoff was consumed. @defaultValue undefined */\n handoffConsumedAt?: string | null;\n /** Agent that consumed the handoff. @defaultValue undefined */\n handoffConsumedBy?: string | null;\n /** Serialized debrief JSON from session end. @defaultValue undefined */\n debriefJson?: string | null;\n /** Aggregate session statistics. @defaultValue undefined */\n stats?: SessionStats;\n /** Number of times this session has been resumed. @defaultValue undefined */\n resumeCount?: number;\n /** Whether this session is in grade/evaluation mode. @defaultValue undefined */\n gradeMode?: boolean;\n /** ID of the provider adapter used for this session. @defaultValue undefined */\n providerId?: string | null;\n}\n\n/**\n * Result of a session start operation.\n *\n * The `sessionId` field is a convenience alias for `session.id`,\n * provided for consumers that expect it at the top level of the result.\n */\nexport interface SessionStartResult {\n /** The newly created or resumed session. */\n session: Session;\n /** Convenience alias for `session.id`. */\n sessionId: string;\n}\n\n/**\n * SessionView \u2014 typed wrapper over Session[] with collection helpers.\n *\n * Provides discoverable query methods for common session lookups.\n * Does NOT change the DataAccessor interface \u2014 consumers create views from Session[].\n *\n * @remarks\n * SessionView is a read-only collection wrapper that provides convenience\n * methods for filtering, searching, and sorting sessions. It does not own\n * the data and performs no mutations on the underlying array.\n */\nexport class SessionView {\n private readonly _sessions: Session[];\n\n constructor(sessions: Session[]) {\n this._sessions = sessions;\n }\n\n /** Create a SessionView from a Session array. */\n static from(sessions: Session[]): SessionView {\n return new SessionView(sessions);\n }\n\n /** All sessions in the view (readonly). */\n get all(): readonly Session[] {\n return this._sessions;\n }\n\n /** Number of sessions. */\n get length(): number {\n return this._sessions.length;\n }\n\n /** Find the currently active session (if any). */\n findActive(): Session | undefined {\n return this._sessions.find((s) => s.status === 'active');\n }\n\n /** Find a session by ID. */\n findById(id: string): Session | undefined {\n return this._sessions.find((s) => s.id === id);\n }\n\n /** Filter sessions by one or more statuses. */\n filterByStatus(...statuses: SessionStatus[]): Session[] {\n return this._sessions.filter((s) => (statuses as string[]).includes(s.status));\n }\n\n /** Find sessions matching a scope type and optional rootTaskId. */\n findByScope(type: string, rootTaskId?: string): Session[] {\n return this._sessions.filter((s) => {\n if (s.scope?.type !== type) return false;\n if (rootTaskId && s.scope?.rootTaskId !== rootTaskId) return false;\n return true;\n });\n }\n\n /** Sort sessions by a date field. Returns a new array (does not mutate). */\n sortByDate(field: 'startedAt' | 'endedAt', descending = true): Session[] {\n return [...this._sessions].sort((a, b) => {\n const aDate = new Date(a[field] || '').getTime();\n const bDate = new Date(b[field] || '').getTime();\n return descending ? bDate - aDate : aDate - bDate;\n });\n }\n\n /** Get the most recently started session. */\n mostRecent(): Session | undefined {\n if (this._sessions.length === 0) return undefined;\n return this.sortByDate('startedAt', true)[0];\n }\n\n /** Convert back to a plain Session array (shallow copy). */\n toArray(): Session[] {\n return [...this._sessions];\n }\n\n /** Support for-of iteration. */\n [Symbol.iterator](): Iterator<Session> {\n return this._sessions[Symbol.iterator]();\n }\n}\n", "/**\n * Unified Status Registry \u2014 single source of truth for all status enums.\n *\n * ADR-018: All status constants and types MUST be defined here.\n * No other file may define status enum arrays as constants.\n *\n * Dependency direction:\n * status-registry.ts \u2192 schema.ts, types/task.ts, validation/engine.ts,\n * dispatch/lib/security.ts, ...\n */\n\n// === WORKFLOW NAMESPACE ===\n// Statuses for entities representing work being performed.\n\nexport const TASK_STATUSES = [\n 'pending',\n 'active',\n 'blocked',\n 'done',\n 'cancelled',\n 'archived',\n] as const;\n\nexport const SESSION_STATUSES = ['active', 'ended', 'orphaned', 'suspended'] as const;\n\nexport const LIFECYCLE_PIPELINE_STATUSES = [\n 'active',\n 'completed',\n 'blocked',\n 'failed',\n 'cancelled',\n 'aborted',\n] as const;\n\nexport const LIFECYCLE_STAGE_STATUSES = [\n 'not_started',\n 'in_progress',\n 'blocked',\n 'completed',\n 'skipped',\n 'failed',\n] as const;\n\n// === GOVERNANCE NAMESPACE ===\n// Statuses for decisions and approvals.\n\nexport const ADR_STATUSES = ['proposed', 'accepted', 'superseded', 'deprecated'] as const;\n\nexport const GATE_STATUSES = ['pending', 'passed', 'failed', 'waived'] as const;\n\n// === MANIFEST NAMESPACE ===\n// Statuses for protocol output artifacts.\n// NOTE: 'complete' was the old value \u2014 it is now 'completed' everywhere.\n\nexport const MANIFEST_STATUSES = ['completed', 'partial', 'blocked', 'archived'] as const;\n\n// === DERIVED TYPES ===\n\nexport type TaskStatus = (typeof TASK_STATUSES)[number];\nexport type SessionStatus = (typeof SESSION_STATUSES)[number];\nexport type PipelineStatus = (typeof LIFECYCLE_PIPELINE_STATUSES)[number];\nexport type StageStatus = (typeof LIFECYCLE_STAGE_STATUSES)[number];\nexport type AdrStatus = (typeof ADR_STATUSES)[number];\nexport type GateStatus = (typeof GATE_STATUSES)[number];\nexport type ManifestStatus = (typeof MANIFEST_STATUSES)[number];\n\n// === TERMINAL STATE SETS ===\n\nexport const TERMINAL_TASK_STATUSES: ReadonlySet<TaskStatus> = new Set([\n 'done',\n 'cancelled',\n 'archived',\n]);\n\nexport const TERMINAL_PIPELINE_STATUSES: ReadonlySet<PipelineStatus> = new Set([\n 'completed',\n 'failed',\n 'cancelled',\n 'aborted',\n]);\n\nexport const TERMINAL_STAGE_STATUSES: ReadonlySet<StageStatus> = new Set([\n 'completed',\n 'skipped',\n 'failed',\n]);\n\n// === REGISTRY (for runtime queryability) ===\n\nexport type EntityType =\n | 'task'\n | 'session'\n | 'lifecycle_pipeline'\n | 'lifecycle_stage'\n | 'adr'\n | 'gate'\n | 'manifest';\n\nexport const STATUS_REGISTRY: Record<EntityType, readonly string[]> = {\n task: TASK_STATUSES,\n session: SESSION_STATUSES,\n lifecycle_pipeline: LIFECYCLE_PIPELINE_STATUSES,\n lifecycle_stage: LIFECYCLE_STAGE_STATUSES,\n adr: ADR_STATUSES,\n gate: GATE_STATUSES,\n manifest: MANIFEST_STATUSES,\n} as const;\n\nexport function isValidStatus(entityType: EntityType, value: string): boolean {\n return (STATUS_REGISTRY[entityType] as readonly string[]).includes(value);\n}\n\n// === DISPLAY ICONS ===\n// Typed Record maps \u2014 exhaustiveness is enforced by the compiler.\n// All icon consumers MUST import from here instead of hardcoding comparisons.\n\n/**\n * Pipeline status \u2192 Unicode progress icon.\n * Used wherever lifecycle pipeline status is rendered to a terminal.\n */\nexport const PIPELINE_STATUS_ICONS: Record<PipelineStatus, string> = {\n active: '\\u25b6', // pipeline is running\n completed: '\\u2713', // all stages done successfully\n blocked: '\\u23f8', // cannot advance; waiting\n failed: '\\u2717', // terminal failure\n cancelled: '\\u2298', // user-initiated abandonment\n aborted: '\\u23f9', // system-forced termination\n};\n\n/**\n * Stage status \u2192 Unicode progress icon.\n * Used wherever pipeline stage status is rendered to a terminal.\n */\nexport const STAGE_STATUS_ICONS: Record<StageStatus, string> = {\n not_started: '\\u23f9', // not yet entered\n in_progress: '\\u25b6', // actively running\n blocked: '\\u23f8', // paused / waiting\n completed: '\\u2713', // finished successfully\n skipped: '\\u23ed', // intentionally bypassed\n failed: '\\u2717', // terminal failure\n};\n\n/**\n * Task status \u2192 Unicode symbol (rich terminal / Unicode-enabled).\n * Falls back to TASK_STATUS_SYMBOLS_ASCII when Unicode is unavailable.\n */\nexport const TASK_STATUS_SYMBOLS_UNICODE: Record<TaskStatus, string> = {\n pending: '\\u25cb', // \u25CB not yet started\n active: '\\u25c9', // \u25C9 in progress\n blocked: '\\u2297', // \u2297 cannot advance\n done: '\\u2713', // \u2713 complete\n cancelled: '\\u2717', // \u2717 abandoned\n archived: '\\u25a3', // \u25A3 stored, inactive\n};\n\n/**\n * Task status \u2192 ASCII fallback symbol (non-Unicode terminals, CI output).\n */\nexport const TASK_STATUS_SYMBOLS_ASCII: Record<TaskStatus, string> = {\n pending: '-',\n active: '*',\n blocked: 'x',\n done: '+',\n cancelled: '~',\n archived: '#',\n};\n", "/**\n * @cleocode/contracts \u2014 Domain types, interfaces, and contracts for the CLEO ecosystem.\n *\n * This is the LEAF package in the dependency graph \u2014 ZERO runtime dependencies.\n * All domain types (Task, Session, DataAccessor, etc.) are defined here.\n * Implementation packages (@cleocode/core, @cleocode/cleo) import from here.\n */\n\n// === Provider Adapter Contracts ===\nexport type { AdapterHealthStatus, CLEOProviderAdapter } from './adapter.js';\n// === Agent Registry (credential management) ===\nexport type {\n AgentCredential,\n AgentListFilter,\n AgentRegistryAPI,\n AgentWithProjectOverride,\n ProjectAgentRef,\n TransportConfig,\n} from './agent-registry.js';\n// === Archive Types ===\nexport type {\n ArchiveCycleTimesReport,\n ArchiveDailyTrend,\n ArchivedTask,\n ArchiveLabelEntry,\n ArchiveMetadata,\n ArchiveMonthlyTrend,\n ArchivePhaseEntry,\n ArchivePriorityEntry,\n ArchiveReportType,\n ArchiveStatsEnvelope,\n ArchiveSummaryReport,\n ArchiveTrendsReport,\n CycleTimeDistribution,\n CycleTimePercentiles,\n} from './archive.js';\n// === Backup Manifest Types ===\nexport type {\n BackupDatabaseEntry,\n BackupGlobalFileEntry,\n BackupIntegrity,\n BackupJsonEntry,\n BackupManifest,\n BackupMetadata,\n BackupScope,\n} from './backup-manifest.js';\n// === Brain/Memory Types ===\nexport type {\n BrainCognitiveType,\n BrainEntryRef,\n BrainEntrySummary,\n BrainMemoryTier,\n BrainSourceConfidence,\n ContradictionDetail,\n SupersededEntry,\n} from './brain.js';\nexport type { AdapterCapabilities } from './capabilities.js';\n// === Code Symbol Types (tree-sitter AST) ===\nexport type {\n BatchParseResult,\n CodeSymbol,\n CodeSymbolKind,\n ParseResult,\n} from './code-symbol.js';\n// === Conduit Protocol (agent-to-agent communication) ===\nexport type {\n Conduit,\n ConduitConfig,\n ConduitMessage,\n ConduitSendOptions,\n ConduitSendResult,\n ConduitState,\n ConduitStateChange,\n ConduitUnsubscribe,\n} from './conduit.js';\n// === Configuration Types ===\nexport type {\n BackupConfig,\n BrainConfig,\n BrainEmbeddingConfig,\n BrainLlmExtractionConfig,\n BrainMemoryBridgeConfig,\n BrainSummarizationConfig,\n BrainTieringConfig,\n CleoConfig,\n ConfigSource,\n DateFormat,\n EnforcementProfile,\n HierarchyConfig,\n LifecycleConfig,\n LifecycleEnforcementMode,\n LoggingConfig,\n LogLevel,\n OutputConfig,\n OutputFormat,\n ResolvedValue,\n SessionConfig,\n SessionSummaryInput,\n SharingConfig,\n SharingMode,\n SignalDockConfig,\n SignalDockMode,\n} from './config.js';\nexport type { AdapterContextMonitorProvider } from './context-monitor.js';\n// === DataAccessor Interface ===\nexport type {\n ArchiveFields,\n ArchiveFile,\n DataAccessor,\n DataAccessorAgentInstance,\n QueryTasksResult,\n TaskFieldUpdates,\n TaskQueryFilters,\n TransactionAccessor,\n} from './data-accessor.js';\n// === Dependency Registry Contracts ===\nexport type {\n DependencyCategory,\n DependencyCheckResult,\n DependencyReport,\n DependencySpec,\n} from './dependency.js';\nexport type { AdapterManifest, DetectionPattern } from './discovery.js';\n// === Error Utilities ===\nexport {\n createErrorResult,\n createSuccessResult,\n formatError,\n getErrorMessage,\n isErrorResult,\n isErrorType,\n normalizeError,\n} from './errors.js';\n// === Exit Codes ===\nexport {\n ExitCode,\n getExitCodeName,\n isErrorCode,\n isNoChangeCode,\n isRecoverableCode,\n isSuccessCode,\n} from './exit-codes.js';\nexport type {\n AdminAPI,\n AgentCapacity,\n AgentHealthStatus,\n AgentInstanceRow,\n AgentInstanceStatus,\n AgentsAPI,\n AgentType,\n BlastRadius,\n BlastRadiusSeverity,\n BrainObservationType,\n CleoInitOptions,\n DuplicateStrategy,\n HybridSearchOptions,\n ImpactedTask,\n ImpactReport,\n ImportParams,\n IntelligenceAPI,\n LifecycleAPI,\n MemoryAPI,\n NexusAPI,\n OrchestrationAPI,\n RegisterAgentOptions,\n ReleaseAPI,\n SessionsAPI,\n StickyAPI,\n SyncAPI,\n TaskStartResult,\n TasksAPI,\n} from './facade.js';\n// === Facade API Interfaces ===\nexport {\n AGENT_INSTANCE_STATUSES,\n AGENT_TYPES,\n BRAIN_OBSERVATION_TYPES,\n} from './facade.js';\n// === Graph Intelligence Types (T512, T529) ===\nexport type {\n CommunityNode,\n GraphNode,\n GraphNodeKind,\n GraphRelation,\n GraphRelationType,\n ImpactResult,\n KnowledgeGraph,\n ProcessNode,\n SymbolIndex,\n} from './graph.js';\nexport type { AdapterHookProvider } from './hooks.js';\nexport type { AdapterInstallProvider, InstallOptions, InstallResult } from './install.js';\nexport type {\n CleoResponse,\n ConformanceReport,\n FlagInput,\n GatewayEnvelope,\n GatewayError,\n GatewayMeta,\n GatewaySuccess,\n LAFSEnvelope,\n LAFSError,\n LAFSErrorCategory,\n LAFSMeta,\n LAFSPage,\n LAFSPageNone,\n LAFSPageOffset,\n LAFSTransport,\n LafsAlternative,\n LafsEnvelope,\n LafsError,\n LafsErrorDetail,\n LafsSuccess,\n MVILevel,\n Warning,\n} from './lafs.js';\n// === LAFS Envelope Types ===\nexport {\n isGatewayEnvelope,\n isLafsError,\n isLafsSuccess,\n} from './lafs.js';\nexport type {\n BridgeDecision,\n BridgeLearning,\n BridgeObservation,\n BridgePattern,\n MemoryBridgeConfig,\n MemoryBridgeContent,\n SessionSummary,\n} from './memory.js';\n// === Operations Types (API wire format, namespaced to avoid collision with domain types) ===\nexport * as ops from './operations/index.js';\n// Commonly used ops types re-exported at top level for convenience\nexport type { BrainState } from './operations/orchestrate.js';\n// === Orchestration Hierarchy ===\nexport {\n type AgentHierarchy,\n type AgentHierarchyEntry,\n type EscalationChain,\n type OrchestrationHierarchyAPI,\n OrchestrationLevel,\n} from './orchestration-hierarchy.js';\nexport type { AdapterPathProvider } from './provider-paths.js';\n// === Result Types (Dashboard, Stats, Log, Context, Sequence, Analysis, Deps) ===\nexport type {\n BottleneckTask,\n CompleteTaskUnblocked,\n ContextResult,\n DashboardResult,\n LabelCount,\n LeveragedTask,\n LogQueryResult,\n SequenceResult,\n StatsActivityMetrics,\n StatsAllTime,\n StatsCompletionMetrics,\n StatsCurrentState,\n StatsCycleTimes,\n StatsResult,\n TaskAnalysisResult,\n TaskDepsResult,\n TaskRef,\n TaskRefPriority,\n TaskSummary,\n} from './results.js';\n// === Session Start Result ===\nexport type {\n Session,\n SessionScope,\n SessionStartResult,\n SessionStats,\n SessionTaskWork,\n} from './session.js';\n// === Session Types ===\nexport { SessionView } from './session.js';\nexport type { AdapterSpawnProvider, SpawnContext, SpawnResult } from './spawn.js';\n// === CLEO Spawn Types (distinct from adapter spawn) ===\nexport type {\n CAAMPSpawnOptions,\n CAAMPSpawnResult,\n CLEOSpawnAdapter,\n CLEOSpawnContext,\n CLEOSpawnResult,\n Provider,\n SpawnStatus,\n TokenResolution,\n} from './spawn-types.js';\n// === Status Registry (MUST be first \u2014 everything depends on this) ===\nexport {\n ADR_STATUSES,\n type AdrStatus,\n // Registry\n type EntityType,\n GATE_STATUSES,\n type GateStatus,\n isValidStatus,\n LIFECYCLE_PIPELINE_STATUSES,\n LIFECYCLE_STAGE_STATUSES,\n MANIFEST_STATUSES,\n type ManifestStatus,\n // Display icons\n PIPELINE_STATUS_ICONS,\n type PipelineStatus,\n SESSION_STATUSES,\n type SessionStatus,\n STAGE_STATUS_ICONS,\n STATUS_REGISTRY,\n type StageStatus,\n TASK_STATUS_SYMBOLS_ASCII,\n TASK_STATUS_SYMBOLS_UNICODE,\n // Constants\n TASK_STATUSES,\n // Derived types\n type TaskStatus,\n TERMINAL_PIPELINE_STATUSES,\n TERMINAL_STAGE_STATUSES,\n // Terminal state sets\n TERMINAL_TASK_STATUSES,\n} from './status-registry.js';\n// === Task Types ===\nexport type {\n CancelledTask,\n CompletedTask,\n EpicLifecycle,\n FileMeta,\n Phase,\n PhaseStatus,\n PhaseTransition,\n ProjectMeta,\n Release,\n ReleaseStatus,\n SessionNote,\n Task,\n TaskCreate,\n TaskOrigin,\n TaskPriority,\n TaskProvenance,\n TaskRelation,\n TaskSize,\n TaskType,\n TaskVerification,\n TaskWorkState,\n VerificationAgent,\n VerificationFailure,\n VerificationGate,\n} from './task.js';\n// === TaskRecord Types (string-widened for dispatch/LAFS) ===\nexport type {\n MinimalTaskRecord,\n TaskRecord,\n TaskRecordRelation,\n ValidationHistoryEntry,\n} from './task-record.js';\n// === Task Sync Types (provider-agnostic reconciliation) ===\nexport type {\n ConflictPolicy,\n ExternalLinkType,\n ExternalTask,\n ExternalTaskLink,\n ExternalTaskProvider,\n ExternalTaskStatus,\n ReconcileAction,\n ReconcileActionType,\n ReconcileOptions,\n ReconcileResult,\n SyncDirection,\n} from './task-sync.js';\n// === Tessera Types ===\nexport type {\n TesseraInstantiationInput,\n TesseraTemplate,\n TesseraVariable,\n} from './tessera.js';\n// === Transport (low-level wire protocol) ===\nexport type {\n AdapterTransportProvider,\n Transport,\n TransportConnectConfig,\n} from './transport.js';\n// === WarpChain Types ===\nexport type {\n ChainShape,\n ChainValidation,\n GateCheck,\n GateContract,\n GateName,\n GateResult,\n ProtocolType,\n WarpChain,\n WarpChainExecution,\n WarpChainInstance,\n WarpLink,\n WarpStage,\n} from './warp-chain.js';\n\n// === WASM SDK (Rust crate bindings) ===\n", "/**\n * Claude Code Spawn Provider\n *\n * Implements AdapterSpawnProvider for Claude Code CLI.\n * Migrated from src/core/spawn/adapters/claude-code-adapter.ts\n *\n * Uses the native `claude` CLI to spawn subagent processes with prompts\n * written to temporary files. Processes run detached and are tracked\n * by PID for listing and termination.\n *\n * @task T5240\n */\n\nimport { exec, spawn as nodeSpawn } from 'node:child_process';\nimport { unlink, writeFile } from 'node:fs/promises';\nimport { promisify } from 'node:util';\nimport type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/contracts';\nimport { getErrorMessage } from '@cleocode/contracts';\n\nconst execAsync = promisify(exec);\n\n/** Internal tracking entry for a spawned process. */\ninterface TrackedProcess {\n pid: number;\n taskId: string;\n startTime: string;\n}\n\n/**\n * Spawn provider for Claude Code.\n *\n * Spawns detached Claude CLI processes for subagent execution.\n * Each spawn writes its prompt to a temporary file, then runs\n * `claude --allow-insecure --no-upgrade-check <tmpFile>` as a\n * detached, unref'd child process.\n *\n * @remarks\n * The provider uses `--allow-insecure --no-upgrade-check` flags to\n * ensure the Claude CLI starts without interactive prompts. Prompts are\n * written to temporary files under `/tmp/` and cleaned up after the\n * child process exits. Processes are tracked by instance ID in an\n * in-memory map and verified via `kill(pid, 0)` liveness checks.\n */\nexport class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {\n /** Map of instance IDs to tracked process info. */\n private processMap = new Map<string, TrackedProcess>();\n\n /**\n * Check if the Claude CLI is available in PATH.\n *\n * @returns true if `claude` is found via `which`\n */\n async canSpawn(): Promise<boolean> {\n try {\n await execAsync('which claude');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Spawn a subagent via Claude CLI.\n *\n * Writes the prompt to a temporary file and spawns a detached Claude\n * process. The process runs independently of the parent.\n *\n * @param context - Spawn context with taskId, prompt, and options\n * @returns Spawn result with instance ID and status\n */\n async spawn(context: SpawnContext): Promise<SpawnResult> {\n const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const startTime = new Date().toISOString();\n let tmpFile: string | undefined;\n\n try {\n // Enrich prompt with CANT bundle, memory bridge, and mental model (T555).\n // Best-effort: if CANT context is unavailable, the raw prompt is used.\n let enrichedPrompt = context.prompt;\n try {\n const { buildCantEnrichedPrompt } = await import('../../cant-context.js');\n enrichedPrompt = await buildCantEnrichedPrompt({\n projectDir: context.workingDirectory ?? process.cwd(),\n basePrompt: context.prompt,\n agentName: (context.options?.agentName as string) ?? undefined,\n });\n } catch {\n // CANT enrichment unavailable \u2014 use raw prompt\n }\n\n tmpFile = `/tmp/claude-spawn-${instanceId}.txt`;\n await writeFile(tmpFile, enrichedPrompt, 'utf-8');\n\n // --print: non-interactive batch mode (process prompt, output response, exit)\n // --dangerously-skip-permissions: allow all tool calls without human approval\n // --output-format json: structured output for parsing\n const args = [\n '--print',\n '--dangerously-skip-permissions',\n '--output-format',\n 'json',\n tmpFile,\n ];\n const spawnOpts: Parameters<typeof nodeSpawn>[2] = {\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n };\n\n if (context.workingDirectory) {\n spawnOpts.cwd = context.workingDirectory;\n }\n\n const child = nodeSpawn('claude', args, spawnOpts);\n child.unref();\n\n if (child.pid) {\n this.processMap.set(instanceId, {\n pid: child.pid,\n taskId: context.taskId,\n startTime,\n });\n }\n\n const capturedTmpFile = tmpFile;\n child.on('exit', async () => {\n this.processMap.delete(instanceId);\n try {\n await unlink(capturedTmpFile);\n } catch {\n // Ignore cleanup errors\n }\n });\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'claude-code',\n status: 'running',\n startTime,\n };\n } catch (error) {\n // Log spawn failure for debugging\n console.error(`[ClaudeCodeSpawnProvider] Failed to spawn: ${getErrorMessage(error)}`);\n\n if (tmpFile) {\n try {\n await unlink(tmpFile);\n } catch {\n // Ignore cleanup errors\n }\n }\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'claude-code',\n status: 'failed',\n startTime,\n endTime: new Date().toISOString(),\n error: getErrorMessage(error),\n };\n }\n }\n\n /**\n * List currently running Claude subagent processes.\n *\n * Checks each tracked process via kill(pid, 0) to verify it is still alive.\n * Dead processes are automatically cleaned from the tracking map.\n *\n * @returns Array of spawn results for running processes\n */\n async listRunning(): Promise<SpawnResult[]> {\n const running: SpawnResult[] = [];\n\n for (const [instanceId, tracked] of this.processMap.entries()) {\n try {\n process.kill(tracked.pid, 0);\n running.push({\n instanceId,\n taskId: tracked.taskId,\n providerId: 'claude-code',\n status: 'running',\n startTime: tracked.startTime,\n });\n } catch {\n this.processMap.delete(instanceId);\n }\n }\n\n return running;\n }\n\n /**\n * Terminate a running spawn by instance ID.\n *\n * Sends SIGTERM to the tracked process. If the process is not found\n * or has already exited, this is a no-op.\n *\n * @param instanceId - ID of the spawn instance to terminate\n */\n async terminate(instanceId: string): Promise<void> {\n const tracked = this.processMap.get(instanceId);\n if (!tracked) return;\n\n try {\n process.kill(tracked.pid, 'SIGTERM');\n } catch {\n // Process may have already exited\n }\n this.processMap.delete(instanceId);\n }\n}\n", "/**\n * Claude Code TaskSyncProvider \u2014 bridges Claude's TodoWrite format\n * to the provider-agnostic reconciliation system.\n *\n * All Claude Code / TodoWrite-specific parsing lives here.\n * The core reconciliation engine never sees TodoWrite formats.\n */\n\nimport { readFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport type { ExternalTask, ExternalTaskProvider, ExternalTaskStatus } from '@cleocode/contracts';\n\n// ---------------------------------------------------------------------------\n// TodoWrite native types (Claude-specific, never exposed beyond this file)\n// ---------------------------------------------------------------------------\n\ninterface TodoWriteItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n activeForm?: string;\n}\n\ninterface TodoWriteState {\n todos: TodoWriteItem[];\n}\n\n// ---------------------------------------------------------------------------\n// Parsing helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a CLEO task ID from TodoWrite content prefix: \"[T001] ...\" -> \"T001\".\n */\nfunction parseTaskId(content: string): string | null {\n const match = content.match(/^\\[T(\\d+)\\]/);\n return match ? `T${match[1]}` : null;\n}\n\n/**\n * Strip ID and status prefixes from content to extract the clean title.\n */\nfunction stripPrefixes(content: string): string {\n return content\n .replace(/^\\[T\\d+\\]\\s*/, '')\n .replace(/^\\[!\\]\\s*/, '')\n .replace(/^\\[BLOCKED\\]\\s*/, '');\n}\n\n/**\n * Map TodoWrite status to normalized ExternalTaskStatus.\n */\nfunction mapStatus(twStatus: TodoWriteItem['status']): ExternalTaskStatus {\n switch (twStatus) {\n case 'completed':\n return 'completed';\n case 'in_progress':\n return 'active';\n case 'pending':\n return 'pending';\n default:\n return 'pending';\n }\n}\n\n/**\n * Resolve the TodoWrite state file path.\n * Claude Code writes its TodoWrite state to a known location.\n */\nfunction getTodoWriteFilePath(projectDir: string): string {\n return join(projectDir, '.cleo', 'sync', 'todowrite-state.json');\n}\n\n// ---------------------------------------------------------------------------\n// Provider implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Claude Code TaskSyncProvider.\n *\n * Reads Claude's TodoWrite JSON state, parses [T001]-prefixed task IDs\n * and status, and returns normalized ExternalTask[].\n *\n * Optional: accepts a custom file path for testing.\n *\n * @remarks\n * TodoWrite items with `[T001]`-style prefixes are mapped to their CLEO\n * task IDs. Items without a prefix receive a synthetic `tw-new-N` ID\n * for reconciliation. The provider reads from\n * `.cleo/sync/todowrite-state.json` by default.\n */\nexport class ClaudeCodeTaskSyncProvider implements ExternalTaskProvider {\n /** Optional override path for the TodoWrite state file (used in tests). */\n private readonly customFilePath?: string;\n\n constructor(options?: { filePath?: string }) {\n this.customFilePath = options?.filePath;\n }\n\n /** Retrieve external tasks from Claude's TodoWrite state file. */\n async getExternalTasks(projectDir: string): Promise<ExternalTask[]> {\n const filePath = this.customFilePath ?? getTodoWriteFilePath(projectDir);\n\n // Check file exists\n try {\n await stat(filePath);\n } catch {\n // No TodoWrite state \u2014 return empty (no tasks to sync)\n return [];\n }\n\n // Parse the TodoWrite JSON\n const raw = await readFile(filePath, 'utf-8');\n let state: TodoWriteState;\n try {\n state = JSON.parse(raw) as TodoWriteState;\n } catch {\n return []; // Malformed JSON \u2014 treat as empty\n }\n\n if (!state.todos || !Array.isArray(state.todos)) {\n return [];\n }\n\n const tasks: ExternalTask[] = [];\n let syntheticIndex = 0;\n\n for (const item of state.todos) {\n const cleoTaskId = parseTaskId(item.content);\n const title = cleoTaskId ? stripPrefixes(item.content).trim() : item.content.trim();\n\n if (!title) continue;\n\n tasks.push({\n externalId: cleoTaskId ?? `tw-new-${syntheticIndex++}`,\n title,\n status: mapStatus(item.status),\n providerMeta: {\n source: 'todowrite',\n cleoTaskId,\n activeForm: item.activeForm,\n rawContent: item.content,\n },\n });\n }\n\n return tasks;\n }\n}\n", "/**\n * Transport provider for the Claude Code adapter.\n *\n * Implements AdapterTransportProvider to supply Claude Code's\n * native inter-agent transport mechanism.\n *\n * @task T5240\n */\n\nimport type { AdapterTransportProvider } from '@cleocode/contracts';\n\n/**\n * Transport provider for Claude Code inter-agent communication.\n *\n * @remarks\n * Currently returns null from {@link createTransport} because actual transport\n * creation is handled by the signaldock factory which checks for this adapter's\n * transport capability flag. Full wiring will be completed in Phase 5 of the\n * adapter system rollout.\n */\nexport class ClaudeCodeTransportProvider implements AdapterTransportProvider {\n /** Provider-specific transport name used for capability negotiation. */\n readonly transportName = 'claude-code';\n\n /** Create a transport instance for inter-agent messaging. */\n createTransport(): unknown {\n // Returns null \u2014 actual transport creation is handled by the signaldock factory\n // which checks for this adapter's transport capability.\n // Full wiring will be completed in Phase 5.\n return null;\n }\n}\n", "/**\n * Claude Code Adapter\n *\n * Main CLEOProviderAdapter implementation for Anthropic's Claude Code CLI.\n * Provides spawn, hooks, and install capabilities for CLEO integration.\n *\n * @task T5240\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { ClaudeCodeContextMonitorProvider } from './context-monitor.js';\nimport { ClaudeCodeHookProvider } from './hooks.js';\nimport { ClaudeCodeInstallProvider } from './install.js';\nimport { ClaudeCodePathProvider } from './paths.js';\nimport { ClaudeCodeSpawnProvider } from './spawn.js';\nimport { ClaudeCodeTaskSyncProvider } from './task-sync.js';\nimport { ClaudeCodeTransportProvider } from './transport.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for Anthropic Claude Code CLI.\n *\n * Bridges CLEO's adapter system with Claude Code's native capabilities:\n * - Hooks: Maps Claude Code events (SessionStart, PostToolUse, etc.) to CAAMP events\n * - Spawn: Launches subagent processes via the `claude` CLI\n * - Install: Manages instruction files and brain observation plugin registration\n *\n * @remarks\n * This is the most feature-complete adapter in the CLEO system, supporting\n * 14 of 16 CAAMP canonical events, subagent spawning via the `claude` CLI,\n * context monitoring with statusline integration, task sync via TodoWrite,\n * and inter-agent transport. It serves as the reference implementation for\n * other provider adapters.\n */\nexport class ClaudeCodeAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'claude-code';\n /** Human-readable provider name. */\n readonly name = 'Claude Code';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n // 14/16 canonical events \u2014 derived from getProviderHookProfile('claude-code') in CAAMP 1.9.1.\n // PreModel and PostModel are not supported by Claude Code.\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'PromptSubmit',\n 'ResponseComplete',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'PermissionRequest',\n 'SubagentStart',\n 'SubagentStop',\n 'PreCompact',\n 'PostCompact',\n 'Notification',\n 'ConfigChange',\n ],\n supportsSpawn: true,\n supportsInstall: true,\n supportsInstructionFiles: true,\n instructionFilePattern: 'CLAUDE.md',\n supportsContextMonitor: true,\n supportsStatusline: true,\n supportsProviderPaths: true,\n supportsTransport: true,\n supportsTaskSync: true,\n };\n\n /** Hook provider for CAAMP event mapping and registration. */\n hooks: ClaudeCodeHookProvider;\n /** Spawn provider for launching subagent processes via `claude` CLI. */\n spawn: ClaudeCodeSpawnProvider;\n /** Install provider for managing instruction files and plugin registration. */\n install: ClaudeCodeInstallProvider;\n /** Path provider for resolving Claude Code directory locations. */\n paths: ClaudeCodePathProvider;\n /** Context monitor for tracking context window usage and statusline output. */\n contextMonitor: ClaudeCodeContextMonitorProvider;\n /** Transport provider for inter-agent communication. */\n transport: ClaudeCodeTransportProvider;\n /** Task sync provider bridging Claude's TodoWrite format to CLEO tasks. */\n taskSync: ClaudeCodeTaskSyncProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new ClaudeCodeHookProvider();\n this.spawn = new ClaudeCodeSpawnProvider();\n this.install = new ClaudeCodeInstallProvider();\n this.paths = new ClaudeCodePathProvider();\n this.contextMonitor = new ClaudeCodeContextMonitorProvider();\n this.transport = new ClaudeCodeTransportProvider();\n this.taskSync = new ClaudeCodeTaskSyncProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * Validates the environment by checking for the Claude CLI\n * and Claude Code configuration directory.\n *\n * @param projectDir - Root directory of the project\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n\n // Activate CLEO hook bridge for this project \u2014 connects Claude Code\n // native events to CLEO's internal hook dispatch (T555).\n await this.hooks.registerNativeHooks(projectDir);\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Claude Code is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Claude CLI is available in PATH\n * 3. ~/.claude/ configuration directory exists\n *\n * @returns Health status with details about each check\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Claude CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which claude');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Claude Code config directory\n const claudeConfigDir = join(homedir(), '.claude');\n const configExists = existsSync(claudeConfigDir);\n details.configDirExists = configExists;\n\n // Check for CLAUDE_CODE_ENTRYPOINT env var\n const entrypointSet = process.env.CLAUDE_CODE_ENTRYPOINT !== undefined;\n details.entrypointEnvSet = entrypointSet;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * Statusline integration for the Claude Code adapter.\n *\n * Implements the statusline portion of AdapterContextMonitorProvider.\n * Checks and configures Claude Code status line for context monitoring.\n *\n * @task T5240\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\ntype StatuslineStatus = 'configured' | 'not_configured' | 'custom_no_cleo' | 'no_settings';\n\n/**\n * Get the path to Claude Code's settings.json.\n * Respects CLAUDE_SETTINGS env var, defaults to ~/.claude/settings.json.\n */\nfunction getClaudeSettingsPath(): string {\n return (\n process.env['CLAUDE_SETTINGS'] ??\n join(process.env['CLAUDE_HOME'] ?? join(homedir(), '.claude'), 'settings.json')\n );\n}\n\n/**\n * Check if statusline integration is configured.\n * Returns the current integration status.\n *\n * @remarks\n * Reads Claude Code's settings.json and inspects the `statusLine` field\n * to determine whether CLEO context monitoring is active.\n *\n * @returns One of: 'configured', 'not_configured', 'custom_no_cleo', 'no_settings'\n *\n * @example\n * ```typescript\n * import { checkStatuslineIntegration } from './statusline.js';\n *\n * const status = checkStatuslineIntegration();\n * if (status === 'not_configured') {\n * console.log('Run cleo install to set up context monitoring');\n * }\n * ```\n */\nexport function checkStatuslineIntegration(): StatuslineStatus {\n const settingsPath = getClaudeSettingsPath();\n\n if (!existsSync(settingsPath)) return 'no_settings';\n\n try {\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const statusLine = settings.statusLine;\n\n if (!statusLine?.type) return 'not_configured';\n if (statusLine.type !== 'command') return 'custom_no_cleo';\n\n const cmd = statusLine.command ?? '';\n\n // Check if it's a CLEO statusline integration\n if (\n cmd.includes('context-monitor.sh') ||\n cmd.includes('cleo-statusline') ||\n cmd.includes('.context-state.json') ||\n cmd.includes('context-states')\n ) {\n return 'configured';\n }\n\n // Check if the script writes to CLEO state file\n const scriptPath = cmd.startsWith('~') ? cmd.replace('~', homedir()) : cmd;\n\n if (existsSync(scriptPath)) {\n try {\n const content = readFileSync(scriptPath, 'utf-8');\n if (content.includes('context-state.json')) return 'configured';\n } catch {\n /* unreadable */\n }\n }\n\n return 'custom_no_cleo';\n } catch {\n return 'no_settings';\n }\n}\n\n/**\n * Get the statusline setup command for Claude Code settings.\n *\n * @remarks\n * Returns a JSON-serializable object that can be merged into\n * Claude Code's settings.json to enable context monitoring.\n *\n * @param cleoHome - Absolute path to the CLEO home directory\n * @returns Settings object containing the statusLine configuration\n *\n * @example\n * ```typescript\n * import { getStatuslineConfig } from './statusline.js';\n *\n * const config = getStatuslineConfig('/home/user/.cleo');\n * ```\n */\nexport function getStatuslineConfig(cleoHome: string): Record<string, unknown> {\n return {\n statusLine: {\n type: 'command',\n command: join(cleoHome, 'lib', 'session', 'context-monitor.sh'),\n },\n };\n}\n\n/**\n * Get human-readable setup instructions.\n *\n * @remarks\n * Returns a multi-line string with file path, JSON config, and explanation\n * suitable for display to the user.\n *\n * @param cleoHome - Absolute path to the CLEO home directory\n * @returns Formatted setup instructions string\n *\n * @example\n * ```typescript\n * import { getSetupInstructions } from './statusline.js';\n *\n * console.log(getSetupInstructions('/home/user/.cleo'));\n * ```\n */\nexport function getSetupInstructions(cleoHome: string): string {\n const settingsPath = getClaudeSettingsPath();\n\n return [\n 'To enable context monitoring, add to your Claude Code settings:',\n `File: ${settingsPath}`,\n '',\n JSON.stringify(getStatuslineConfig(cleoHome), null, 2),\n '',\n 'This enables real-time context window tracking in the CLI.',\n ].join('\\n');\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Anthropic Claude Code CLI.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T5240\n */\n\nimport { ClaudeCodeAdapter } from './adapter.js';\n\nexport { ClaudeCodeAdapter } from './adapter.js';\nexport { ClaudeCodeContextMonitorProvider } from './context-monitor.js';\nexport { ClaudeCodeHookProvider } from './hooks.js';\nexport { ClaudeCodeInstallProvider } from './install.js';\nexport { ClaudeCodePathProvider } from './paths.js';\nexport { ClaudeCodeSpawnProvider } from './spawn.js';\nexport {\n checkStatuslineIntegration,\n getSetupInstructions,\n getStatuslineConfig,\n} from './statusline.js';\nexport { ClaudeCodeTransportProvider } from './transport.js';\n\nexport default ClaudeCodeAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the claude-code\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link ClaudeCodeAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/claude-code';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n */\nexport function createAdapter(): ClaudeCodeAdapter {\n return new ClaudeCodeAdapter();\n}\n", "/**\n * Cursor Hook Provider\n *\n * Maps Cursor's native hook events to CAAMP canonical hook events.\n * Cursor supports 10 of 16 canonical events through its config-based hook system.\n *\n * Event translation uses CAAMP normalizer APIs:\n * - `toCanonical(nativeName, 'cursor')` for runtime event name resolution\n * - `getSupportedEvents('cursor')` to enumerate supported canonical events\n * - `getProviderHookProfile('cursor')` for the full provider profile\n *\n * Cursor uses camelCase native event names (e.g. `sessionStart`, `preToolUse`).\n * Hooks are configured via `.cursor/hooks.json`. Supported handler types:\n * command, prompt.\n *\n * Unsupported events: PermissionRequest, PreModel, PostModel, PostCompact,\n * Notification, ConfigChange.\n *\n * @task T165\n * @epic T134\n */\n\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/** CAAMP provider identifier for Cursor. */\nconst PROVIDER_ID = 'cursor' as const;\n\n/**\n * Fallback map from Cursor native event names to CAAMP canonical names.\n *\n * Derived from `getProviderHookProfile('cursor').mappings` in CAAMP 1.9.1.\n * Covers all 10 supported events. PermissionRequest, PreModel, PostModel,\n * PostCompact, Notification, and ConfigChange are not supported by Cursor.\n *\n * Cursor uses camelCase names while CAAMP canonical names are PascalCase.\n */\nconst CURSOR_EVENT_MAP: Record<string, string> = {\n // CAAMP: toNative('SessionStart', 'cursor') = 'sessionStart'\n sessionStart: 'SessionStart',\n // CAAMP: toNative('SessionEnd', 'cursor') = 'sessionEnd'\n sessionEnd: 'SessionEnd',\n // CAAMP: toNative('PromptSubmit', 'cursor') = 'beforeSubmitPrompt'\n beforeSubmitPrompt: 'PromptSubmit',\n // CAAMP: toNative('ResponseComplete', 'cursor') = 'stop'\n stop: 'ResponseComplete',\n // CAAMP: toNative('PreToolUse', 'cursor') = 'preToolUse'\n preToolUse: 'PreToolUse',\n // CAAMP: toNative('PostToolUse', 'cursor') = 'postToolUse'\n postToolUse: 'PostToolUse',\n // CAAMP: toNative('PostToolUseFailure', 'cursor') = 'postToolUseFailure'\n postToolUseFailure: 'PostToolUseFailure',\n // CAAMP: toNative('SubagentStart', 'cursor') = 'subagentStart'\n subagentStart: 'SubagentStart',\n // CAAMP: toNative('SubagentStop', 'cursor') = 'subagentStop'\n subagentStop: 'SubagentStop',\n // CAAMP: toNative('PreCompact', 'cursor') = 'preCompact'\n preCompact: 'PreCompact',\n};\n\n/**\n * Hook provider for Cursor.\n *\n * Cursor registers hooks via its config system at `.cursor/hooks.json`.\n * Supported handler types: command, prompt.\n *\n * CAAMP 1.9.1 reveals Cursor supports 10 of 16 canonical events. Previously\n * this provider was a no-op stub. It now provides full event mapping and CAAMP\n * normalizer integration.\n *\n * Event mapping is based on `getProviderHookProfile('cursor')` from CAAMP 1.9.1.\n * Async accessors (`getSupportedCanonicalEvents`, `getProviderProfile`) call\n * CAAMP directly when available.\n *\n * Since hooks are registered through the config system (managed by the install\n * provider), `registerNativeHooks` and `unregisterNativeHooks` track registration\n * state without performing filesystem operations.\n *\n * @remarks\n * This provider was originally a no-op stub. It now provides full event\n * mapping for all 10 canonical events supported by Cursor, plus CAAMP\n * normalizer integration via async accessors. Registration state is\n * tracked in-memory because Cursor manages hooks through its own config.\n *\n * @task T165\n * @epic T134\n */\nexport class CursorHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Cursor native event name to a CAAMP canonical hook event name.\n *\n * Looks up the native event name in the map derived from\n * `getProviderHookProfile('cursor').mappings` (CAAMP 1.9.1). Cursor uses\n * camelCase names (e.g. \"preToolUse\", \"sessionStart\").\n *\n * Returns null for unsupported events (PermissionRequest, PreModel,\n * PostModel, PostCompact, Notification, ConfigChange).\n *\n * @param providerEvent - Cursor native event name (e.g. \"preToolUse\", \"sessionStart\")\n * @returns CAAMP canonical event name, or null if unmapped\n * @task T165\n */\n mapProviderEvent(providerEvent: string): string | null {\n return CURSOR_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For Cursor, hooks are registered via the config system\n * (`.cursor/hooks.json`), managed by the install provider.\n * This method marks hooks as registered without performing filesystem operations.\n *\n * Iterating supported events is handled at install time using\n * `getSupportedCanonicalEvents()` to enumerate all 10 supported hooks.\n *\n * @param _projectDir - Project directory (unused; Cursor config manages registration)\n * @task T165\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For Cursor, this is a no-op since hooks are managed through the config\n * system. Unregistration happens via the install provider's uninstall method.\n *\n * @task T165\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via `registerNativeHooks`.\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the native\u2192canonical event mapping for introspection and debugging.\n *\n * Returns the map derived from `getProviderHookProfile('cursor').mappings`\n * (CAAMP 1.9.1). Use `getSupportedCanonicalEvents()` to enumerate canonical\n * names via live CAAMP APIs.\n *\n * @returns Immutable record of native event name \u2192 canonical event name\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...CURSOR_EVENT_MAP };\n }\n\n /**\n * Enumerate supported canonical events via CAAMP's `getSupportedEvents()`.\n *\n * Calls `getSupportedEvents('cursor')` from the CAAMP normalizer to get the\n * authoritative list. Cursor supports 10 of 16 canonical events. Falls back\n * to the values of the static event map when CAAMP is unavailable at runtime.\n *\n * @returns Array of CAAMP canonical event names supported by Cursor\n * @task T165\n */\n async getSupportedCanonicalEvents(): Promise<string[]> {\n try {\n const { getSupportedEvents } = await import('@cleocode/caamp');\n return getSupportedEvents(PROVIDER_ID) as string[];\n } catch {\n return [...new Set(Object.values(CURSOR_EVENT_MAP))];\n }\n }\n\n /**\n * Retrieve the full provider hook profile from CAAMP.\n *\n * Calls `getProviderHookProfile('cursor')` from the CAAMP normalizer to\n * get the complete profile: hook system type (`config`), config path\n * (`.cursor/hooks.json`), handler types (command, prompt), and all event\n * mappings. Returns null when CAAMP is unavailable at runtime.\n *\n * @returns Provider hook profile or null if CAAMP is unavailable\n * @task T165\n */\n async getProviderProfile(): Promise<unknown | null> {\n try {\n const { getProviderHookProfile } = await import('@cleocode/caamp');\n return getProviderHookProfile(PROVIDER_ID) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Translate a CAAMP canonical event to its Cursor native name via CAAMP.\n *\n * Calls `toNative(canonical, 'cursor')` from the CAAMP normalizer.\n * Returns null for unsupported events or when CAAMP is unavailable.\n *\n * @param canonical - CAAMP canonical event name (e.g. \"PreToolUse\")\n * @returns Cursor native event name (e.g. \"preToolUse\") or null\n * @task T165\n */\n async toNativeEvent(canonical: string): Promise<string | null> {\n try {\n const { toNative } = await import('@cleocode/caamp');\n return toNative(canonical as Parameters<typeof toNative>[0], PROVIDER_ID);\n } catch {\n // Invert the static map as fallback\n const entry = Object.entries(CURSOR_EVENT_MAP).find(([, v]) => v === canonical);\n return entry?.[0] ?? null;\n }\n }\n}\n", "/**\n * Cursor Install Provider\n *\n * Handles CLEO installation into Cursor environments:\n * - Ensures .cursorrules has CLEO @-references (legacy format)\n * - Creates .cursor/rules/cleo.mdc with CLEO references (modern format)\n *\n * Cursor supports two instruction file formats:\n * 1. Legacy: .cursorrules (flat file, project root)\n * 2. Modern: .cursor/rules/*.mdc (MDC format, per-rule files)\n *\n * This provider writes to both for maximum compatibility.\n *\n * @task T5240\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in instruction files to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for Cursor.\n *\n * Manages CLEO's integration with Cursor by:\n * 1. Creating/updating .cursorrules with @-references (legacy)\n * 2. Creating .cursor/rules/cleo.mdc with @-references (modern)\n *\n * @remarks\n * Installation is idempotent and writes to both instruction file formats\n * for maximum compatibility. The legacy `.cursorrules` file is only modified\n * if it already exists (never created from scratch). The modern MDC file\n * is always created or updated to ensure Cursor's rule engine picks it up.\n */\nexport class CursorInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Cursor project.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure instruction files have @-references\n instructionFileUpdated = this.updateInstructionFiles(projectDir);\n if (instructionFileUpdated) {\n details.instructionFiles = this.getUpdatedFileList(projectDir);\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the current Cursor project.\n *\n * Does not remove instruction file references (they are harmless if CLEO is not present).\n */\n async uninstall(): Promise<void> {}\n\n /**\n * Check whether CLEO is installed in the current environment.\n *\n * Checks for .cursor/rules/cleo.mdc or .cursorrules with CLEO references.\n */\n async isInstalled(): Promise<boolean> {\n const mdcPath = join(process.cwd(), '.cursor', 'rules', 'cleo.mdc');\n if (existsSync(mdcPath)) {\n return true;\n }\n\n const rulesPath = join(process.cwd(), '.cursorrules');\n if (existsSync(rulesPath)) {\n try {\n const content = readFileSync(rulesPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure instruction files contain @-references to CLEO.\n *\n * Updates .cursorrules (legacy) and creates .cursor/rules/cleo.mdc (modern).\n *\n * @param projectDir - Project root directory\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFiles(projectDir);\n }\n\n /**\n * Update instruction files with CLEO @-references.\n *\n * Handles both legacy (.cursorrules) and modern (.cursor/rules/cleo.mdc) formats.\n *\n * @returns true if any file was created or modified\n */\n private updateInstructionFiles(projectDir: string): boolean {\n let updated = false;\n\n // Update legacy .cursorrules if it exists\n if (this.updateLegacyRules(projectDir)) {\n updated = true;\n }\n\n // Create/update modern .cursor/rules/cleo.mdc\n if (this.updateModernRules(projectDir)) {\n updated = true;\n }\n\n return updated;\n }\n\n /**\n * Update legacy .cursorrules file with @-references.\n * Only modifies the file if it already exists (does not create it).\n *\n * @returns true if the file was modified\n */\n private updateLegacyRules(projectDir: string): boolean {\n const rulesPath = join(projectDir, '.cursorrules');\n if (!existsSync(rulesPath)) {\n return false;\n }\n\n let content = readFileSync(rulesPath, 'utf-8');\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + missingRefs.join('\\n') + '\\n';\n writeFileSync(rulesPath, content, 'utf-8');\n return true;\n }\n\n /**\n * Create or update .cursor/rules/cleo.mdc with CLEO references.\n *\n * MDC (Markdown Component) format is Cursor's modern rule file format.\n * Each .mdc file in .cursor/rules/ is loaded as a rule set.\n *\n * @returns true if the file was created or modified\n */\n private updateModernRules(projectDir: string): boolean {\n const rulesDir = join(projectDir, '.cursor', 'rules');\n const mdcPath = join(rulesDir, 'cleo.mdc');\n\n const expectedContent = [\n '---',\n 'description: CLEO task management protocol references',\n 'globs: \"**/*\"',\n 'alwaysApply: true',\n '---',\n '',\n ...INSTRUCTION_REFERENCES,\n '',\n ].join('\\n');\n\n if (existsSync(mdcPath)) {\n const existing = readFileSync(mdcPath, 'utf-8');\n if (existing === expectedContent) {\n return false;\n }\n }\n\n mkdirSync(rulesDir, { recursive: true });\n writeFileSync(mdcPath, expectedContent, 'utf-8');\n return true;\n }\n\n /**\n * Get list of instruction files that were updated.\n */\n private getUpdatedFileList(projectDir: string): string[] {\n const files: string[] = [];\n if (existsSync(join(projectDir, '.cursorrules'))) {\n files.push(join(projectDir, '.cursorrules'));\n }\n files.push(join(projectDir, '.cursor', 'rules', 'cleo.mdc'));\n return files;\n }\n}\n", "/**\n * Cursor Adapter\n *\n * Main CLEOProviderAdapter implementation for Cursor AI code editor.\n * Provides install capabilities for CLEO integration. Hooks and spawn\n * are not supported since Cursor lacks CLI-based lifecycle events\n * and subagent spawning.\n *\n * @task T5240\n */\n\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { CursorHookProvider } from './hooks.js';\nimport { CursorInstallProvider } from './install.js';\n\n/**\n * CLEO provider adapter for Cursor AI code editor.\n *\n * Bridges CLEO's adapter system with Cursor's capabilities:\n * - Install: Manages .cursorrules and .cursor/rules/cleo.mdc rule files\n * - Hooks: Stub provider (Cursor has no lifecycle event system)\n * - Spawn: Not supported (Cursor has no CLI for subagent spawning)\n *\n * @remarks\n * Cursor is a GUI-based editor, so many CLI-oriented capabilities\n * (spawn, transport, task sync, context monitor) are unsupported.\n * Integration is primarily through instruction rule files placed in\n * `.cursor/rules/` (modern MDC format) and `.cursorrules` (legacy).\n */\nexport class CursorAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'cursor';\n /** Human-readable provider name. */\n readonly name = 'Cursor';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n // 10/16 canonical events \u2014 derived from getProviderHookProfile('cursor') in CAAMP 1.9.1.\n // PermissionRequest, PreModel, PostModel, PostCompact, Notification, ConfigChange are\n // not supported by Cursor's hook system.\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'PromptSubmit',\n 'ResponseComplete',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'SubagentStart',\n 'SubagentStop',\n 'PreCompact',\n ],\n supportsSpawn: false,\n supportsInstall: true,\n supportsInstructionFiles: true,\n instructionFilePattern: '.cursor/rules/*.mdc',\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: true,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping. */\n hooks: CursorHookProvider;\n /** Install provider for managing rule files. */\n install: CursorInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new CursorHookProvider();\n this.install = new CursorInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * @param projectDir - Root directory of the project\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Cursor is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. .cursor/ configuration directory exists in the project\n * 3. CURSOR_EDITOR env var is set\n *\n * @returns Health status with details about each check\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check for Cursor config directory in the project\n let configExists = false;\n if (this.projectDir) {\n const cursorConfigDir = join(this.projectDir, '.cursor');\n configExists = existsSync(cursorConfigDir);\n details.configDirExists = configExists;\n }\n\n // Check for CURSOR_EDITOR env var\n const editorEnvSet = process.env.CURSOR_EDITOR !== undefined;\n details.editorEnvSet = editorEnvSet;\n\n // Check for legacy .cursorrules file\n if (this.projectDir) {\n const legacyRulesExist = existsSync(join(this.projectDir, '.cursorrules'));\n details.legacyRulesExist = legacyRulesExist;\n }\n\n // Healthy if we detect Cursor presence (config dir or env var)\n const healthy = configExists || editorEnvSet;\n details.detected = healthy;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Cursor AI code editor.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T5240\n */\n\nimport { CursorAdapter } from './adapter.js';\n\nexport { CursorAdapter } from './adapter.js';\nexport { CursorHookProvider } from './hooks.js';\nexport { CursorInstallProvider } from './install.js';\n\nexport default CursorAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the cursor\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link CursorAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/cursor';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n */\nexport function createAdapter(): CursorAdapter {\n return new CursorAdapter();\n}\n", "/**\n * OpenCode Hook Provider\n *\n * Maps OpenCode's native hook events to CAAMP canonical hook events.\n * OpenCode supports 10 of 16 canonical events through its plugin system.\n *\n * Event translation uses CAAMP normalizer APIs:\n * - `toCanonical(nativeName, 'opencode')` for runtime event name resolution\n * - `getSupportedEvents('opencode')` to enumerate supported canonical events\n * - `getProviderHookProfile('opencode')` for the full provider profile\n *\n * OpenCode uses a JavaScript plugin system with event-prefixed names\n * (e.g. `event:session.created`) for some hooks and bare names for others.\n * The map is derived from `getProviderHookProfile('opencode').mappings` in\n * CAAMP 1.9.1. PostToolUseFailure, SubagentStart, SubagentStop, Notification,\n * and ConfigChange are not supported by OpenCode.\n *\n * @task T164\n * @epic T134\n */\n\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/** CAAMP provider identifier for OpenCode. */\nconst PROVIDER_ID = 'opencode' as const;\n\n/**\n * Fallback map from OpenCode native event names to CAAMP canonical names.\n *\n * Derived from `getProviderHookProfile('opencode').mappings` in CAAMP 1.9.1.\n * Covers all 10 supported events. PostToolUseFailure, SubagentStart,\n * SubagentStop, Notification, and ConfigChange are not supported by OpenCode\n * and are absent from this map.\n *\n * OpenCode uses dot-delimited and event-prefixed names (e.g. \"event:session.created\")\n * while CAAMP canonical names are PascalCase (e.g. \"SessionStart\").\n */\nconst OPENCODE_EVENT_MAP: Record<string, string> = {\n // CAAMP: toNative('SessionStart', 'opencode') = 'event:session.created'\n 'event:session.created': 'SessionStart',\n // CAAMP: toNative('SessionEnd', 'opencode') = 'event:session.deleted'\n 'event:session.deleted': 'SessionEnd',\n // CAAMP: toNative('PromptSubmit', 'opencode') = 'chat.message'\n 'chat.message': 'PromptSubmit',\n // CAAMP: toNative('ResponseComplete', 'opencode') = 'event:session.idle'\n 'event:session.idle': 'ResponseComplete',\n // CAAMP: toNative('PreToolUse', 'opencode') = 'tool.execute.before'\n 'tool.execute.before': 'PreToolUse',\n // CAAMP: toNative('PostToolUse', 'opencode') = 'tool.execute.after'\n 'tool.execute.after': 'PostToolUse',\n // CAAMP: toNative('PermissionRequest', 'opencode') = 'permission.ask'\n 'permission.ask': 'PermissionRequest',\n // CAAMP: toNative('PreModel', 'opencode') = 'chat.params'\n 'chat.params': 'PreModel',\n // CAAMP: toNative('PreCompact', 'opencode') = 'experimental.session.compacting'\n 'experimental.session.compacting': 'PreCompact',\n // CAAMP: toNative('PostCompact', 'opencode') = 'event:session.compacted'\n 'event:session.compacted': 'PostCompact',\n};\n\n/**\n * Hook provider for OpenCode.\n *\n * OpenCode registers hooks via its JavaScript plugin system at\n * `.opencode/plugins/`. Supported handler type: plugin (JavaScript).\n *\n * Event mapping is based on `getProviderHookProfile('opencode')` from\n * CAAMP 1.9.1. Async accessors (`getSupportedCanonicalEvents`,\n * `getProviderProfile`) call CAAMP directly when available.\n *\n * Since hooks are registered through the plugin system (managed by the install\n * provider), `registerNativeHooks` and `unregisterNativeHooks` track registration\n * state without performing filesystem operations.\n *\n * @remarks\n * OpenCode uses dot-delimited and `event:`-prefixed event names\n * (e.g. `event:session.created`, `tool.execute.before`) which differ\n * significantly from the PascalCase CAAMP canonical names. The static\n * event map covers all 10 supported events. Async CAAMP accessors\n * (`getSupportedCanonicalEvents`, `getProviderProfile`, `toNativeEvent`)\n * call the normalizer directly when available and fall back to the static map.\n *\n * @task T164\n * @epic T134\n */\nexport class OpenCodeHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map an OpenCode native event name to a CAAMP canonical hook event name.\n *\n * Looks up the native event name in the map derived from\n * `getProviderHookProfile('opencode').mappings` (CAAMP 1.9.1).\n * Returns null for unsupported events (PostToolUseFailure, SubagentStart,\n * SubagentStop, Notification, ConfigChange).\n *\n * @param providerEvent - OpenCode native event (e.g. \"event:session.created\", \"tool.execute.before\")\n * @returns CAAMP canonical event name, or null if unmapped\n * @task T164\n */\n mapProviderEvent(providerEvent: string): string | null {\n return OPENCODE_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For OpenCode, hooks are registered via the plugin system\n * (`.opencode/plugins/`), managed by the install provider.\n * This method marks hooks as registered without performing filesystem operations.\n *\n * Iterating supported events is handled at install time using\n * `getSupportedCanonicalEvents()` to enumerate all 10 supported hooks.\n *\n * @param _projectDir - Project directory (unused; config manages registration)\n * @task T164\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For OpenCode, this is a no-op since hooks are managed through the plugin\n * system. Unregistration happens via the install provider's uninstall method.\n *\n * @task T164\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via `registerNativeHooks`.\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the native\u2192canonical event mapping for introspection and debugging.\n *\n * Returns the map derived from `getProviderHookProfile('opencode').mappings`\n * (CAAMP 1.9.1). Use `getSupportedCanonicalEvents()` to enumerate canonical\n * names via live CAAMP APIs.\n *\n * @returns Immutable record of native event name \u2192 canonical event name\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...OPENCODE_EVENT_MAP };\n }\n\n /**\n * Enumerate supported canonical events via CAAMP's `getSupportedEvents()`.\n *\n * Calls `getSupportedEvents('opencode')` from the CAAMP normalizer to get the\n * authoritative list. OpenCode supports 10 of 16 canonical events via its\n * plugin system. Falls back to the values of the static event map when\n * CAAMP is unavailable at runtime.\n *\n * @returns Array of CAAMP canonical event names supported by OpenCode\n * @task T164\n */\n async getSupportedCanonicalEvents(): Promise<string[]> {\n try {\n const { getSupportedEvents } = await import('@cleocode/caamp');\n return getSupportedEvents(PROVIDER_ID) as string[];\n } catch {\n return [...new Set(Object.values(OPENCODE_EVENT_MAP))];\n }\n }\n\n /**\n * Retrieve the full provider hook profile from CAAMP.\n *\n * Calls `getProviderHookProfile('opencode')` from the CAAMP normalizer to\n * get the complete profile: hook system type (`plugin`), config path\n * (`.opencode/plugins/`), handler types, and all event mappings.\n * Returns null when CAAMP is unavailable at runtime.\n *\n * @returns Provider hook profile or null if CAAMP is unavailable\n * @task T164\n */\n async getProviderProfile(): Promise<unknown | null> {\n try {\n const { getProviderHookProfile } = await import('@cleocode/caamp');\n return getProviderHookProfile(PROVIDER_ID) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Translate a CAAMP canonical event to its OpenCode native name via CAAMP.\n *\n * Calls `toNative(canonical, 'opencode')` from the CAAMP normalizer.\n * Returns null for unsupported events or when CAAMP is unavailable.\n *\n * @param canonical - CAAMP canonical event name (e.g. \"PreToolUse\")\n * @returns OpenCode native event name or null\n * @task T164\n */\n async toNativeEvent(canonical: string): Promise<string | null> {\n try {\n const { toNative } = await import('@cleocode/caamp');\n return toNative(canonical as Parameters<typeof toNative>[0], PROVIDER_ID);\n } catch {\n // Invert the static map as fallback\n const entry = Object.entries(OPENCODE_EVENT_MAP).find(([, v]) => v === canonical);\n return entry?.[0] ?? null;\n }\n }\n}\n", "/**\n * OpenCode Install Provider\n *\n * Handles CLEO installation into OpenCode environments:\n * - Ensures AGENTS.md has CLEO @-references\n *\n * @task T5240\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for OpenCode.\n *\n * Manages CLEO's integration with OpenCode by:\n * 1. Ensuring AGENTS.md contains @-references to CLEO instruction files\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. Only AGENTS.md is managed; OpenCode's\n * plugin system is handled separately by the hook provider.\n */\nexport class OpenCodeInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into an OpenCode project.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure AGENTS.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the current OpenCode project.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n */\n async uninstall(): Promise<void> {}\n\n /**\n * Check whether CLEO is installed in the current environment.\n *\n * Checks for CLEO references in AGENTS.md.\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update AGENTS.md with CLEO @-references.\n *\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const agentsMdPath = join(projectDir, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsMdPath)) {\n content = readFileSync(agentsMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n // Append missing references\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n // Create new AGENTS.md with references\n content = refsBlock + '\\n';\n }\n\n writeFileSync(agentsMdPath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * OpenCode Spawn Provider\n *\n * Implements AdapterSpawnProvider for OpenCode CLI.\n * Migrated from src/core/spawn/adapters/opencode-adapter.ts\n *\n * Uses `opencode run --agent ... --format json` to spawn subagent\n * processes. Processes run detached and are tracked by PID for\n * listing and termination.\n *\n * @task T5240\n */\n\nimport { exec, spawn as nodeSpawn } from 'node:child_process';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/contracts';\n\nconst execAsync = promisify(exec);\n\n/** Name used for the CLEO subagent definition in OpenCode's agent directory. */\nconst OPENCODE_SUBAGENT_NAME = 'cleo-subagent';\n\n/** Fallback agent name when custom agent definition cannot be created. */\nconst OPENCODE_FALLBACK_AGENT = 'general';\n\n/** Internal tracking entry for a spawned process. */\ninterface TrackedProcess {\n pid: number;\n taskId: string;\n startTime: string;\n}\n\n/**\n * Build the markdown content for an OpenCode agent definition file.\n *\n * OpenCode agents are defined as markdown files with YAML frontmatter\n * in the .opencode/agent/ directory.\n *\n * @remarks\n * The generated markdown uses YAML frontmatter with `mode: subagent`\n * and `hidden: true` so the agent does not appear in OpenCode's\n * interactive agent selection menu.\n *\n * @param description - Agent description for frontmatter\n * @param instructions - Markdown instructions body\n * @returns Complete agent definition markdown with YAML frontmatter\n *\n * @example\n * ```typescript\n * import { buildOpenCodeAgentMarkdown } from '@cleocode/adapters/providers/opencode/spawn';\n *\n * const md = buildOpenCodeAgentMarkdown(\n * 'CLEO task executor',\n * '# Subagent\\n\\nExecute the delegated task.',\n * );\n * ```\n */\nexport function buildOpenCodeAgentMarkdown(description: string, instructions: string): string {\n const normalizedDesc = description.replace(/\\s+/g, ' ').trim();\n return [\n '---',\n `description: ${JSON.stringify(normalizedDesc)}`,\n 'mode: subagent',\n 'hidden: true',\n '---',\n '',\n instructions.trim(),\n '',\n ].join('\\n');\n}\n\n/**\n * Ensure the CLEO subagent definition exists in the project's\n * .opencode/agent/ directory.\n *\n * Creates or updates the agent definition file if the content has changed.\n *\n * @param workingDirectory - Project root directory\n * @returns The agent name to use for spawning\n */\nasync function ensureSubagentDefinition(\n workingDirectory: string,\n enrichedInstructions?: string,\n): Promise<string> {\n const agentDir = join(workingDirectory, '.opencode', 'agent');\n const agentPath = join(agentDir, `${OPENCODE_SUBAGENT_NAME}.md`);\n const description = 'CLEO task executor with protocol compliance and CANT context.';\n const instructions =\n enrichedInstructions ??\n [\n '# CLEO Subagent',\n '',\n 'You are a CLEO subagent executing a delegated task.',\n 'Follow the CLEO protocol and complete the assigned work.',\n '',\n '@~/.cleo/templates/CLEO-INJECTION.md',\n ].join('\\n');\n\n const content = buildOpenCodeAgentMarkdown(description, instructions);\n\n await mkdir(agentDir, { recursive: true });\n\n let existing: string | null = null;\n try {\n existing = await readFile(agentPath, 'utf-8');\n } catch {\n existing = null;\n }\n\n if (existing !== content) {\n await writeFile(agentPath, content, 'utf-8');\n }\n\n return OPENCODE_SUBAGENT_NAME;\n}\n\n/**\n * Spawn provider for OpenCode.\n *\n * Spawns detached OpenCode CLI processes for subagent execution.\n * Each spawn ensures a CLEO subagent definition exists, then runs\n * `opencode run --format json --agent <name> --title <title> <prompt>`\n * as a detached, unref'd child process.\n *\n * @remarks\n * Before spawning, the provider ensures a `cleo-subagent` agent definition\n * exists in `.opencode/agent/`. If the definition cannot be created, it\n * falls back to the built-in `general` agent. Processes are tracked by\n * instance ID in an in-memory map and verified via `kill(pid, 0)` liveness\n * checks.\n */\nexport class OpenCodeSpawnProvider implements AdapterSpawnProvider {\n /** Map of instance IDs to tracked process info. */\n private processMap = new Map<string, TrackedProcess>();\n\n /**\n * Check if the OpenCode CLI is available in PATH.\n *\n * @returns true if `opencode` is found via `which`\n */\n async canSpawn(): Promise<boolean> {\n try {\n await execAsync('which opencode');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Spawn a subagent via OpenCode CLI.\n *\n * Ensures the CLEO subagent definition exists in the project's\n * .opencode/agent/ directory, then spawns a detached OpenCode\n * process. The process runs independently of the parent.\n *\n * @param context - Spawn context with taskId, prompt, and options\n * @returns Spawn result with instance ID and status\n */\n async spawn(context: SpawnContext): Promise<SpawnResult> {\n const instanceId = `opencode-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const startTime = new Date().toISOString();\n const workingDirectory = context.workingDirectory ?? process.cwd();\n\n try {\n // Enrich prompt with CANT bundle, memory bridge, and mental model (T555).\n // Best-effort: if CANT context is unavailable, the raw prompt is used.\n let enrichedInstructions: string | undefined;\n try {\n const { buildCantEnrichedPrompt } = await import('../../cant-context.js');\n enrichedInstructions = await buildCantEnrichedPrompt({\n projectDir: workingDirectory,\n basePrompt: context.prompt,\n agentName: (context.options?.agentName as string) ?? undefined,\n });\n } catch {\n // CANT enrichment unavailable \u2014 use raw prompt\n }\n\n let agentName: string;\n try {\n agentName = await ensureSubagentDefinition(workingDirectory, enrichedInstructions);\n } catch {\n agentName = OPENCODE_FALLBACK_AGENT;\n }\n\n const child = nodeSpawn(\n 'opencode',\n [\n 'run',\n '--format',\n 'json',\n '--agent',\n agentName,\n '--title',\n `CLEO ${context.taskId}`,\n context.prompt,\n ],\n {\n cwd: workingDirectory,\n detached: true,\n stdio: 'ignore',\n },\n );\n\n child.unref();\n\n if (child.pid) {\n this.processMap.set(instanceId, {\n pid: child.pid,\n taskId: context.taskId,\n startTime,\n });\n }\n\n child.on('exit', () => {\n this.processMap.delete(instanceId);\n });\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'opencode',\n status: 'running',\n startTime,\n };\n } catch {\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'opencode',\n status: 'failed',\n startTime,\n endTime: new Date().toISOString(),\n };\n }\n }\n\n /**\n * List currently running OpenCode subagent processes.\n *\n * Checks each tracked process via kill(pid, 0) to verify it is still alive.\n * Dead processes are automatically cleaned from the tracking map.\n *\n * @returns Array of spawn results for running processes\n */\n async listRunning(): Promise<SpawnResult[]> {\n const running: SpawnResult[] = [];\n\n for (const [instanceId, tracked] of this.processMap.entries()) {\n try {\n process.kill(tracked.pid, 0);\n running.push({\n instanceId,\n taskId: tracked.taskId,\n providerId: 'opencode',\n status: 'running',\n startTime: tracked.startTime,\n });\n } catch {\n this.processMap.delete(instanceId);\n }\n }\n\n return running;\n }\n\n /**\n * Terminate a running spawn by instance ID.\n *\n * Sends SIGTERM to the tracked process. If the process is not found\n * or has already exited, this is a no-op.\n *\n * @param instanceId - ID of the spawn instance to terminate\n */\n async terminate(instanceId: string): Promise<void> {\n const tracked = this.processMap.get(instanceId);\n if (!tracked) return;\n\n try {\n process.kill(tracked.pid, 'SIGTERM');\n } catch {\n // Process may have already exited\n }\n this.processMap.delete(instanceId);\n }\n}\n", "/**\n * OpenCode Adapter\n *\n * Main CLEOProviderAdapter implementation for OpenCode AI coding assistant.\n * Provides spawn, hooks, and install capabilities for CLEO integration.\n *\n * @task T5240\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { OpenCodeHookProvider } from './hooks.js';\nimport { OpenCodeInstallProvider } from './install.js';\nimport { OpenCodeSpawnProvider } from './spawn.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for OpenCode AI coding assistant.\n *\n * Bridges CLEO's adapter system with OpenCode's native capabilities:\n * - Hooks: Maps OpenCode events (session.start, tool.complete, etc.) to CAAMP events\n * - Spawn: Launches subagent processes via the `opencode` CLI\n * - Install: Ensures AGENTS.md references for CLEO instruction files\n *\n * @remarks\n * OpenCode is the second-most feature-complete adapter after Claude Code,\n * supporting 10 canonical events through its JavaScript plugin system,\n * subagent spawning via the `opencode run` CLI command, and instruction\n * file management via AGENTS.md. It uniquely supports PreModel via the\n * `chat.params` event, which allows pre-inference parameter injection.\n */\nexport class OpenCodeAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'opencode';\n /** Human-readable provider name. */\n readonly name = 'OpenCode';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n // 10/16 canonical events \u2014 derived from getProviderHookProfile('opencode') in CAAMP 1.9.1.\n // PostToolUseFailure, SubagentStart, SubagentStop, Notification, ConfigChange are\n // not supported by OpenCode's plugin system.\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'PromptSubmit',\n 'ResponseComplete',\n 'PreToolUse',\n 'PostToolUse',\n 'PermissionRequest',\n 'PreModel',\n 'PreCompact',\n 'PostCompact',\n ],\n supportsSpawn: true,\n supportsInstall: true,\n supportsInstructionFiles: true,\n instructionFilePattern: 'AGENTS.md',\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: true,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping via OpenCode's plugin system. */\n hooks: OpenCodeHookProvider;\n /** Spawn provider for launching subagent processes via `opencode run`. */\n spawn: OpenCodeSpawnProvider;\n /** Install provider for managing AGENTS.md instruction files. */\n install: OpenCodeInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new OpenCodeHookProvider();\n this.spawn = new OpenCodeSpawnProvider();\n this.install = new OpenCodeInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * Validates the environment by checking for the OpenCode CLI\n * and OpenCode configuration directory.\n *\n * @param projectDir - Root directory of the project\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify OpenCode is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. OpenCode CLI is available in PATH\n * 3. .opencode/ configuration directory exists in the project\n *\n * @returns Health status with details about each check\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check OpenCode CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which opencode');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for OpenCode config directory in the project\n if (this.projectDir) {\n const openCodeConfigDir = join(this.projectDir, '.opencode');\n const configExists = existsSync(openCodeConfigDir);\n details.configDirExists = configExists;\n }\n\n // Check for OPENCODE_VERSION env var\n const versionEnvSet = process.env.OPENCODE_VERSION !== undefined;\n details.versionEnvSet = versionEnvSet;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for OpenCode AI coding assistant.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T5240\n */\n\nimport { OpenCodeAdapter } from './adapter.js';\n\nexport { OpenCodeAdapter } from './adapter.js';\nexport { OpenCodeHookProvider } from './hooks.js';\nexport { OpenCodeInstallProvider } from './install.js';\nexport { OpenCodeSpawnProvider } from './spawn.js';\n\nexport default OpenCodeAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the opencode\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link OpenCodeAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/opencode';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n */\nexport function createAdapter(): OpenCodeAdapter {\n return new OpenCodeAdapter();\n}\n", "/**\n * Pi Hook Provider\n *\n * Maps Pi coding agent native event names to CAAMP canonical hook events.\n * Pi supports 11 of 16 canonical events through its extension/event system.\n *\n * Event translation uses CAAMP normalizer APIs:\n * - `toCanonical(nativeName, 'pi')` for runtime event name resolution\n * - `getSupportedEvents('pi')` to enumerate supported canonical events\n * - `getProviderHookProfile('pi')` for the full provider profile\n *\n * A static map derived from CAAMP hook-mappings.json piEventCatalog is\n * maintained as a fallback for environments where CAAMP's runtime\n * resolution is unavailable.\n *\n * Mappings (11/16 supported):\n * session_start \u2192 SessionStart\n * session_shutdown \u2192 SessionEnd\n * input \u2192 PromptSubmit\n * turn_end \u2192 Notification (assistant turn complete)\n * tool_call \u2192 PreToolUse\n * tool_result \u2192 PostToolUse\n * before_agent_start \u2192 SubagentStart\n * agent_end \u2192 SubagentStop\n * before_provider_request \u2192 PreModel\n * context \u2192 PreCompact (context assembly = pre-compaction proxy)\n *\n * Unsupported (5/16):\n * ResponseComplete, PostToolUseFailure, PermissionRequest,\n * PostModel, PostCompact, ConfigChange\n *\n * @task T553\n */\n\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/** CAAMP provider identifier for Pi. */\nconst PROVIDER_ID = 'pi' as const;\n\n/**\n * Fallback map from Pi native event names to CAAMP canonical names.\n *\n * Derived from the `piEventCatalog` block in CAAMP hook-mappings.json.\n * Covers all 11 supported events. ResponseComplete, PostToolUseFailure,\n * PermissionRequest, PostModel, PostCompact, and ConfigChange are not\n * supported by Pi and are absent from this map.\n *\n * Used as fallback when CAAMP runtime is unavailable, and as the\n * synchronous implementation of `mapProviderEvent()`.\n */\nconst PI_EVENT_MAP: Record<string, string> = {\n // piEventCatalog: session_start \u2192 SessionStart\n session_start: 'SessionStart',\n // piEventCatalog: session_shutdown \u2192 SessionEnd\n session_shutdown: 'SessionEnd',\n // piEventCatalog: input \u2192 PromptSubmit\n input: 'PromptSubmit',\n // piEventCatalog: turn_end \u2192 Notification (assistant turn complete)\n turn_end: 'Notification',\n // piEventCatalog: tool_call \u2192 PreToolUse\n tool_call: 'PreToolUse',\n // piEventCatalog: tool_execution_start \u2192 PreToolUse (duplicate path)\n tool_execution_start: 'PreToolUse',\n // piEventCatalog: tool_result \u2192 PostToolUse\n tool_result: 'PostToolUse',\n // piEventCatalog: tool_execution_end \u2192 PostToolUse (duplicate path)\n tool_execution_end: 'PostToolUse',\n // piEventCatalog: before_agent_start \u2192 SubagentStart\n before_agent_start: 'SubagentStart',\n // piEventCatalog: agent_end \u2192 SubagentStop\n agent_end: 'SubagentStop',\n // piEventCatalog: before_provider_request \u2192 PreModel\n before_provider_request: 'PreModel',\n // piEventCatalog: context \u2192 PreCompact (context assembly is the pre-compaction proxy for Pi)\n context: 'PreCompact',\n};\n\n/**\n * Hook provider for Pi coding agent.\n *\n * Pi registers hooks via its TypeScript extension system. Extensions are\n * loaded from `~/.pi/agent/extensions/*.ts` (global) or\n * `<projectDir>/.pi/extensions/*.ts` (project scope).\n *\n * Event mapping is based on the `piEventCatalog` block in CAAMP\n * hook-mappings.json. Async accessors (`getSupportedCanonicalEvents`,\n * `getProviderProfile`) call CAAMP directly when available.\n *\n * Since hooks are registered through the extension system (managed by the\n * install provider), `registerNativeHooks` and `unregisterNativeHooks`\n * track registration state without performing filesystem operations.\n *\n * @remarks\n * Pi is CAAMP's first-class primary harness (ADR-035). Its native events\n * use snake_case (e.g. `session_start`, `tool_call`) unlike the PascalCase\n * CAAMP canonical names. The static event map covers all 11 supported events.\n * Async CAAMP accessors fall back to the static map when CAAMP is unavailable.\n *\n * Pi does NOT support ResponseComplete, PostToolUseFailure, PermissionRequest,\n * PostModel, PostCompact, or ConfigChange canonical events.\n *\n * All hook dispatch is best-effort \u2014 hooks MUST never block or crash Pi.\n *\n * @task T553\n */\nexport class PiHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Pi native event name to a CAAMP canonical hook event name.\n *\n * Looks up the native event name in the map derived from the\n * `piEventCatalog` block in CAAMP hook-mappings.json.\n * Returns null for unrecognised or unsupported events.\n *\n * @param providerEvent - Pi native event (e.g. \"session_start\", \"tool_call\")\n * @returns CAAMP canonical event name, or null if unmapped\n * @task T553\n */\n mapProviderEvent(providerEvent: string): string | null {\n return PI_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For Pi, hooks are registered via the extension system, managed by\n * the install provider. This method marks hooks as registered without\n * performing filesystem operations.\n *\n * Iterating supported events is handled at install time using\n * `getSupportedCanonicalEvents()` to enumerate all 11 supported hooks.\n *\n * @param _projectDir - Project directory (unused; Pi uses extension system)\n * @task T553\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For Pi, this is a no-op since hooks are managed through the extension\n * system. Unregistration happens via the install provider's uninstall method.\n *\n * @task T553\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via `registerNativeHooks`.\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the native\u2192canonical event mapping for introspection and debugging.\n *\n * Returns the map derived from the `piEventCatalog` block in CAAMP\n * hook-mappings.json. Use `getSupportedCanonicalEvents()` to enumerate\n * canonical names via live CAAMP APIs.\n *\n * @returns Immutable record of native event name \u2192 canonical event name\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...PI_EVENT_MAP };\n }\n\n /**\n * Enumerate supported canonical events via CAAMP's `getSupportedEvents()`.\n *\n * Calls `getSupportedEvents('pi')` from the CAAMP normalizer to get the\n * authoritative list. Pi supports 11 of 16 canonical events. Falls back\n * to the unique values of the static event map when CAAMP is unavailable.\n *\n * @returns Array of CAAMP canonical event names supported by Pi\n * @task T553\n */\n async getSupportedCanonicalEvents(): Promise<string[]> {\n try {\n const { getSupportedEvents } = await import('@cleocode/caamp');\n return getSupportedEvents(PROVIDER_ID) as string[];\n } catch {\n return [...new Set(Object.values(PI_EVENT_MAP))];\n }\n }\n\n /**\n * Retrieve the full provider hook profile from CAAMP.\n *\n * Calls `getProviderHookProfile('pi')` from the CAAMP normalizer to get\n * the complete profile including hook system type, config path, handler\n * types, and all event mappings. Returns null when CAAMP is unavailable.\n *\n * @returns Provider hook profile or null if CAAMP is unavailable\n * @task T553\n */\n async getProviderProfile(): Promise<unknown | null> {\n try {\n const { getProviderHookProfile } = await import('@cleocode/caamp');\n return getProviderHookProfile(PROVIDER_ID) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Translate a CAAMP canonical event to its Pi native name via CAAMP.\n *\n * Calls `toNative(canonical, 'pi')` from the CAAMP normalizer.\n * Returns null for unsupported events or when CAAMP is unavailable.\n *\n * @param canonical - CAAMP canonical event name (e.g. \"PreToolUse\")\n * @returns Pi native event name or null\n * @task T553\n */\n async toNativeEvent(canonical: string): Promise<string | null> {\n try {\n const { toNative } = await import('@cleocode/caamp');\n return toNative(canonical as Parameters<typeof toNative>[0], PROVIDER_ID);\n } catch {\n // Invert the static map as fallback \u2014 return the first match\n const entry = Object.entries(PI_EVENT_MAP).find(([, v]) => v === canonical);\n return entry?.[0] ?? null;\n }\n }\n}\n", "/**\n * Pi Install Provider\n *\n * Handles CLEO installation into Pi coding agent environments:\n * - Ensures AGENTS.md has CLEO @-references (project and global scope)\n * - Manages Pi settings.json to register CLEO extension path\n *\n * Pi uses AGENTS.md (not CLAUDE.md) as its instruction file. The global\n * instruction file lives at `~/.pi/agent/AGENTS.md`; the project-level\n * file lives at `<projectDir>/AGENTS.md`.\n *\n * Detection: Pi is detected by the `PI_CODING_AGENT_DIR` or `PI_HOME`\n * environment variables, or by presence of `~/.pi/agent/` directory.\n *\n * @task T553\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Resolve the Pi global state root directory.\n *\n * Honours `PI_CODING_AGENT_DIR` env var when set (with `~` expansion),\n * then `PI_HOME`, then falls back to `~/.pi/agent`.\n */\nfunction getPiAgentDir(): string {\n const env = process.env['PI_CODING_AGENT_DIR'];\n if (env !== undefined && env.length > 0) {\n if (env === '~') return homedir();\n if (env.startsWith('~/')) return join(homedir(), env.slice(2));\n return env;\n }\n const piHome = process.env['PI_HOME'];\n if (piHome !== undefined && piHome.length > 0) {\n return join(piHome, 'agent');\n }\n return join(homedir(), '.pi', 'agent');\n}\n\n/**\n * Install provider for Pi coding agent.\n *\n * Manages CLEO's integration with Pi by:\n * 1. Ensuring project AGENTS.md contains @-references to CLEO instruction files\n * 2. Ensuring global AGENTS.md (~/.pi/agent/AGENTS.md) contains @-references\n *\n * @remarks\n * Installation is idempotent \u2014 running install multiple times on the same\n * project produces the same result. Pi's AGENTS.md is auto-discovered from\n * the working directory upwards, so project-level injection is the primary\n * mechanism. Global injection ensures fresh sessions always load CLEO context.\n */\nexport class PiInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Pi coding agent project.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure project AGENTS.md has @-references\n const projectUpdated = this.updateInstructionFile(projectDir, 'AGENTS.md');\n if (projectUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n // Step 2: Ensure global AGENTS.md has @-references (best-effort)\n let globalUpdated = false;\n try {\n const globalDir = getPiAgentDir();\n globalUpdated = this.updateInstructionFile(globalDir, 'AGENTS.md');\n if (globalUpdated) {\n details.globalInstructionFile = join(globalDir, 'AGENTS.md');\n }\n } catch {\n // Global install is best-effort \u2014 never block project install\n }\n\n const instructionFileUpdated = projectUpdated || globalUpdated;\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the current Pi project.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n */\n async uninstall(): Promise<void> {}\n\n /**\n * Check whether CLEO is installed in the current environment.\n *\n * Checks for CLEO references in the project AGENTS.md.\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n // Also check global AGENTS.md\n try {\n const globalPath = join(getPiAgentDir(), 'AGENTS.md');\n if (existsSync(globalPath)) {\n const content = readFileSync(globalPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n }\n } catch {\n // Fall through\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir, 'AGENTS.md');\n }\n\n /**\n * Update an instruction file with CLEO @-references.\n *\n * @param dir - Directory containing the instruction file\n * @param filename - Name of the instruction file (e.g. \"AGENTS.md\")\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(dir: string, filename: string): boolean {\n const filePath = join(dir, filename);\n let content = '';\n let existed = false;\n\n if (existsSync(filePath)) {\n content = readFileSync(filePath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n // Append missing references\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n // Create new file with references \u2014 ensure parent dir exists\n mkdirSync(dir, { recursive: true });\n content = refsBlock + '\\n';\n }\n\n writeFileSync(filePath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * Pi Spawn Provider\n *\n * Implements AdapterSpawnProvider for Pi coding agent CLI.\n *\n * Uses the `pi` CLI (or the path from `PI_CLI_PATH` env var) to spawn\n * subagent processes with prompts written to temporary files. Processes\n * run detached and are tracked by PID for listing and termination.\n *\n * Pi detection: `PI_CLI_PATH` env var or `which pi`.\n *\n * @task T553\n */\n\nimport { exec, spawn as nodeSpawn } from 'node:child_process';\nimport { unlink, writeFile } from 'node:fs/promises';\nimport { promisify } from 'node:util';\nimport type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/contracts';\nimport { getErrorMessage } from '@cleocode/contracts';\n\nconst execAsync = promisify(exec);\n\n/** Internal tracking entry for a spawned process. */\ninterface TrackedProcess {\n pid: number;\n taskId: string;\n startTime: string;\n}\n\n/**\n * Resolve the Pi CLI executable path.\n *\n * Honours `PI_CLI_PATH` env var when set, otherwise uses `pi` (expects\n * the binary on PATH).\n */\nfunction getPiCliPath(): string {\n return process.env['PI_CLI_PATH'] ?? 'pi';\n}\n\n/**\n * Spawn provider for Pi coding agent.\n *\n * Spawns detached Pi CLI processes for subagent execution. Each spawn\n * writes its prompt to a temporary file, then runs the Pi CLI with the\n * prompt file as the primary argument as a detached, unref'd child process.\n *\n * @remarks\n * Prompts are written to temporary files under `/tmp/` and cleaned up\n * after the child process exits. Processes are tracked by instance ID in\n * an in-memory map and verified via `kill(pid, 0)` liveness checks.\n * All failures are best-effort and non-blocking.\n */\nexport class PiSpawnProvider implements AdapterSpawnProvider {\n /** Map of instance IDs to tracked process info. */\n private processMap = new Map<string, TrackedProcess>();\n\n /**\n * Check if the Pi CLI is available.\n *\n * Checks `PI_CLI_PATH` env var first, then tries `which pi`.\n *\n * @returns true if the Pi CLI is accessible\n */\n async canSpawn(): Promise<boolean> {\n const cliPath = getPiCliPath();\n try {\n if (cliPath !== 'pi') {\n // Custom path \u2014 check if it exists\n const { stdout } = await execAsync(`test -x \"${cliPath}\" && echo ok`);\n return stdout.trim() === 'ok';\n }\n await execAsync('which pi');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Spawn a subagent via Pi CLI.\n *\n * Writes the prompt to a temporary file and spawns a detached Pi\n * process. The process runs independently of the parent.\n *\n * @param context - Spawn context with taskId, prompt, and options\n * @returns Spawn result with instance ID and status\n */\n async spawn(context: SpawnContext): Promise<SpawnResult> {\n const instanceId = `pi-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const startTime = new Date().toISOString();\n let tmpFile: string | undefined;\n\n try {\n tmpFile = `/tmp/pi-spawn-${instanceId}.txt`;\n await writeFile(tmpFile, context.prompt, 'utf-8');\n\n const cliPath = getPiCliPath();\n const args = [tmpFile];\n const spawnOpts: Parameters<typeof nodeSpawn>[2] = {\n detached: true,\n stdio: 'ignore',\n };\n\n if (context.workingDirectory) {\n spawnOpts.cwd = context.workingDirectory;\n }\n\n const child = nodeSpawn(cliPath, args, spawnOpts);\n child.unref();\n\n if (child.pid) {\n this.processMap.set(instanceId, {\n pid: child.pid,\n taskId: context.taskId,\n startTime,\n });\n }\n\n const capturedTmpFile = tmpFile;\n child.on('exit', async () => {\n this.processMap.delete(instanceId);\n try {\n await unlink(capturedTmpFile);\n } catch {\n // Ignore cleanup errors\n }\n });\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'pi',\n status: 'running',\n startTime,\n };\n } catch (error) {\n console.error(`[PiSpawnProvider] Failed to spawn: ${getErrorMessage(error)}`);\n\n if (tmpFile) {\n try {\n await unlink(tmpFile);\n } catch {\n // Ignore cleanup errors\n }\n }\n\n return {\n instanceId,\n taskId: context.taskId,\n providerId: 'pi',\n status: 'failed',\n startTime,\n endTime: new Date().toISOString(),\n error: getErrorMessage(error),\n };\n }\n }\n\n /**\n * List currently running Pi subagent processes.\n *\n * Checks each tracked process via kill(pid, 0) to verify it is still alive.\n * Dead processes are automatically cleaned from the tracking map.\n *\n * @returns Array of spawn results for running processes\n */\n async listRunning(): Promise<SpawnResult[]> {\n const running: SpawnResult[] = [];\n\n for (const [instanceId, tracked] of this.processMap.entries()) {\n try {\n process.kill(tracked.pid, 0);\n running.push({\n instanceId,\n taskId: tracked.taskId,\n providerId: 'pi',\n status: 'running',\n startTime: tracked.startTime,\n });\n } catch {\n this.processMap.delete(instanceId);\n }\n }\n\n return running;\n }\n\n /**\n * Terminate a running spawn by instance ID.\n *\n * Sends SIGTERM to the tracked process. If the process is not found\n * or has already exited, this is a no-op.\n *\n * @param instanceId - ID of the spawn instance to terminate\n */\n async terminate(instanceId: string): Promise<void> {\n const tracked = this.processMap.get(instanceId);\n if (!tracked) return;\n\n try {\n process.kill(tracked.pid, 'SIGTERM');\n } catch {\n // Process may have already exited\n }\n this.processMap.delete(instanceId);\n }\n}\n", "/**\n * Pi Adapter\n *\n * Main CLEOProviderAdapter implementation for the Pi coding agent\n * (https://github.com/badlogic/pi-mono). Pi is CAAMP's first-class primary\n * harness and owns skills, instructions, extensions, and subagent spawning\n * through native filesystem conventions.\n *\n * Pi supports 11 of 16 CAAMP canonical events through its TypeScript extension\n * system (session_start, session_shutdown, input, turn_end, tool_call,\n * tool_result, before_agent_start, agent_end, before_provider_request, context).\n *\n * Detection: PI_CLI_PATH env var, PI_CODING_AGENT_DIR env var, PI_HOME env var,\n * or presence of ~/.pi/agent/ directory.\n *\n * @task T553\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { PiHookProvider } from './hooks.js';\nimport { PiInstallProvider } from './install.js';\nimport { PiSpawnProvider } from './spawn.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * Resolve the Pi global state root directory.\n *\n * Honours `PI_CODING_AGENT_DIR` env var when set (with `~` expansion),\n * then `PI_HOME`, then falls back to `~/.pi/agent`.\n */\nfunction getPiAgentDir(): string {\n const env = process.env['PI_CODING_AGENT_DIR'];\n if (env !== undefined && env.length > 0) {\n if (env === '~') return homedir();\n if (env.startsWith('~/')) return join(homedir(), env.slice(2));\n return env;\n }\n const piHome = process.env['PI_HOME'];\n if (piHome !== undefined && piHome.length > 0) {\n return join(piHome, 'agent');\n }\n return join(homedir(), '.pi', 'agent');\n}\n\n/**\n * CLEO provider adapter for Pi coding agent.\n *\n * Bridges CLEO's adapter system with Pi's native capabilities:\n * - Hooks: Maps Pi events (session_start, tool_call, etc.) to CAAMP events\n * - Spawn: Launches subagent processes via the `pi` CLI\n * - Install: Manages AGENTS.md instruction files and global Pi state root\n *\n * @remarks\n * Pi is CAAMP's first-class primary harness (ADR-035). It supports 11 of 16\n * canonical hook events through its TypeScript extension system. Extensions\n * live at `~/.pi/agent/extensions/` (global) or `<projectDir>/.pi/extensions/`\n * (project scope).\n *\n * The session_shutdown event handler in `cleo-cant-bridge.ts` clears module\n * cache. The adapter's hook mapping ensures that Pi's session lifecycle events\n * are visible in the CAAMP event stream for downstream listeners (e.g. memory\n * refresh triggers, backup triggers).\n *\n * Detection hierarchy (first match wins):\n * 1. `PI_CLI_PATH` env var set\n * 2. `PI_CODING_AGENT_DIR` env var set\n * 3. `PI_HOME` env var set\n * 4. `~/.pi/agent/` directory exists\n * 5. `pi` CLI available in PATH\n */\nexport class PiAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'pi';\n /** Human-readable provider name. */\n readonly name = 'Pi';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n // 11/16 canonical events \u2014 derived from piEventCatalog in CAAMP hook-mappings.json.\n // ResponseComplete, PostToolUseFailure, PermissionRequest, PostModel, PostCompact,\n // and ConfigChange are not supported by Pi's extension system.\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'PromptSubmit',\n 'Notification',\n 'PreToolUse',\n 'PostToolUse',\n 'SubagentStart',\n 'SubagentStop',\n 'PreModel',\n 'PreCompact',\n ],\n supportsSpawn: true,\n supportsInstall: true,\n supportsInstructionFiles: true,\n instructionFilePattern: 'AGENTS.md',\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: true,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping and registration. */\n hooks: PiHookProvider;\n /** Spawn provider for launching subagent processes via `pi` CLI. */\n spawn: PiSpawnProvider;\n /** Install provider for managing AGENTS.md instruction files. */\n install: PiInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new PiHookProvider();\n this.spawn = new PiSpawnProvider();\n this.install = new PiInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * Validates the environment by checking for the Pi CLI and Pi state root.\n *\n * @param projectDir - Root directory of the project\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Pi is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Pi CLI is available (via PI_CLI_PATH or `which pi`)\n * 3. Pi global state root (~/.pi/agent/ or PI_CODING_AGENT_DIR) exists\n *\n * @returns Health status with details about each check\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Pi CLI availability\n let cliAvailable = false;\n const cliPath = process.env['PI_CLI_PATH'] ?? 'pi';\n try {\n if (cliPath !== 'pi') {\n const { stdout } = await execAsync(`test -x \"${cliPath}\" && echo ok`);\n cliAvailable = stdout.trim() === 'ok';\n details.cliPath = cliPath;\n } else {\n const { stdout } = await execAsync('which pi');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n }\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Pi global state root\n const agentDir = getPiAgentDir();\n const agentDirExists = existsSync(agentDir);\n details.agentDirExists = agentDirExists;\n details.agentDir = agentDir;\n\n // Check for project-level .pi/ directory\n if (this.projectDir) {\n const projectPiDir = join(this.projectDir, '.pi');\n details.projectPiDirExists = existsSync(projectPiDir);\n }\n\n // Check detection env vars\n details.piCodingAgentDirSet = process.env['PI_CODING_AGENT_DIR'] !== undefined;\n details.piHomeSet = process.env['PI_HOME'] !== undefined;\n details.piCliPathSet = process.env['PI_CLI_PATH'] !== undefined;\n\n // Healthy if either CLI is available or global state root exists\n const healthy = cliAvailable || agentDirExists;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Pi coding agent (https://github.com/badlogic/pi-mono).\n * Pi is CAAMP's first-class primary harness with 11/16 canonical hook events.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T553\n */\n\nimport { PiAdapter } from './adapter.js';\n\nexport { PiAdapter } from './adapter.js';\nexport { PiHookProvider } from './hooks.js';\nexport { PiInstallProvider } from './install.js';\nexport { PiSpawnProvider } from './spawn.js';\n\nexport default PiAdapter;\n\n/**\n * Factory function for creating Pi adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the pi provider\n * via its import-based discovery mechanism.\n *\n * @returns A new {@link PiAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/pi';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n */\nexport function createAdapter(): PiAdapter {\n return new PiAdapter();\n}\n", "/**\n * @packageDocumentation\n *\n * Unified provider adapter package for CLEO.\n * Exports all provider adapters and a registry for manifest discovery.\n *\n * @remarks\n * This package is the single entry point for all CLEO provider adapters.\n * Each provider (Claude Code, Cursor, OpenCode, Codex, Gemini CLI, Kimi)\n * exposes an adapter class implementing {@link CLEOProviderAdapter} from\n * `@cleocode/contracts`, plus supporting hook, install, and spawn providers.\n * The {@link discoverProviders} function and {@link getProviderManifests}\n * registry enable dynamic adapter loading by AdapterManager.\n */\n\nexport type { BuildCantEnrichedPromptOptions, TierDiscoveryStats } from './cant-context.js';\n// Shared CANT context builder \u2014 used by all spawn providers\nexport { buildCantEnrichedPrompt } from './cant-context.js';\n// Re-export adapter classes for direct use\n// Per-provider factory functions (renamed to avoid collisions)\nexport {\n ClaudeCodeAdapter,\n ClaudeCodeContextMonitorProvider,\n ClaudeCodeHookProvider,\n ClaudeCodeInstallProvider,\n ClaudeCodePathProvider,\n ClaudeCodeSpawnProvider,\n ClaudeCodeTransportProvider,\n checkStatuslineIntegration,\n createAdapter as createClaudeCodeAdapter,\n getSetupInstructions,\n getStatuslineConfig,\n} from './providers/claude-code/index.js';\nexport {\n CodexAdapter,\n CodexHookProvider,\n CodexInstallProvider,\n createAdapter as createCodexAdapter,\n} from './providers/codex/index.js';\nexport {\n CursorAdapter,\n CursorHookProvider,\n CursorInstallProvider,\n createAdapter as createCursorAdapter,\n} from './providers/cursor/index.js';\nexport {\n createAdapter as createGeminiCliAdapter,\n GeminiCliAdapter,\n GeminiCliHookProvider,\n GeminiCliInstallProvider,\n} from './providers/gemini-cli/index.js';\nexport {\n createAdapter as createKimiAdapter,\n KimiAdapter,\n KimiHookProvider,\n KimiInstallProvider,\n} from './providers/kimi/index.js';\nexport {\n createAdapter as createOpenCodeAdapter,\n OpenCodeAdapter,\n OpenCodeHookProvider,\n OpenCodeInstallProvider,\n OpenCodeSpawnProvider,\n} from './providers/opencode/index.js';\nexport type { AdapterManifest } from './registry.js';\nexport { discoverProviders, getProviderManifests } from './registry.js';\n", "/**\n * Codex CLI Adapter\n *\n * Main CLEOProviderAdapter implementation for OpenAI Codex CLI.\n * Provides hooks and install capabilities for CLEO integration.\n *\n * @task T162\n * @epic T134\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { CodexHookProvider } from './hooks.js';\nimport { CodexInstallProvider } from './install.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for OpenAI Codex CLI.\n *\n * Bridges CLEO's adapter system with Codex CLI's native capabilities:\n * - Hooks: Maps Codex events (SessionStart, PromptSubmit, ResponseComplete) to CAAMP events\n * - Install: Ensures AGENTS.md references for CLEO instruction files\n *\n * @remarks\n * Codex CLI supports only 3 canonical events (SessionStart, PromptSubmit,\n * ResponseComplete) and has no spawn or transport capabilities. Integration\n * is primarily through instruction files (AGENTS.md).\n *\n * @task T162\n * @epic T134\n */\nexport class CodexAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'codex';\n /** Human-readable provider name. */\n readonly name = 'Codex';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n supportedHookEvents: ['SessionStart', 'UserPromptSubmit', 'Stop'],\n supportsSpawn: false,\n supportsInstall: true,\n supportsInstructionFiles: false,\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: false,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping. */\n hooks: CodexHookProvider;\n /** Install provider for managing instruction files. */\n install: CodexInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new CodexHookProvider();\n this.install = new CodexInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * @param projectDir - Root directory of the project\n * @task T162\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n * @task T162\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Codex CLI is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Codex CLI binary is available in PATH\n * 3. ~/.codex/ configuration directory exists\n *\n * @returns Health status with details about each check\n * @task T162\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Codex CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which codex');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Codex CLI config directory\n const codexConfigDir = join(homedir(), '.codex');\n const configExists = existsSync(codexConfigDir);\n details.configDirExists = configExists;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n * @task T162\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n * @task T162\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * Codex CLI Hook Provider\n *\n * Maps Codex CLI's native hook events to CAAMP canonical hook events.\n * Codex CLI supports 3 canonical events through its hook system.\n *\n * Codex CLI event mapping:\n * - SessionStart -> SessionStart\n * - PromptSubmit -> UserPromptSubmit\n * - ResponseComplete -> Stop\n *\n * @task T162\n * @epic T134\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterHookProvider } from '@cleocode/contracts';\nimport { readLatestTranscript } from '../shared/transcript-reader.js';\n\n/**\n * Mapping from Codex CLI native event names to CAAMP canonical event names.\n */\nconst CODEX_EVENT_MAP: Record<string, string> = {\n SessionStart: 'SessionStart',\n PromptSubmit: 'UserPromptSubmit',\n ResponseComplete: 'Stop',\n};\n\n/**\n * Hook provider for Codex CLI.\n *\n * Codex CLI registers hooks via its configuration system at\n * ~/.codex/. Hook handlers are shell commands or script paths that\n * execute when the corresponding event fires.\n *\n * Since hooks are registered through the config system (managed by\n * the install provider), registerNativeHooks and unregisterNativeHooks\n * track registration state without performing filesystem operations.\n *\n * @remarks\n * Codex CLI has a minimal hook surface with only 3 canonical events.\n * Registration state is tracked in-memory because Codex CLI manages\n * hooks through its own configuration system at `~/.codex/`.\n *\n * @task T162\n * @epic T134\n */\nexport class CodexHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Codex CLI native event name to a CAAMP hook event name.\n *\n * @param providerEvent - Codex CLI event name (e.g. \"SessionStart\", \"PromptSubmit\")\n * @returns CAAMP event name or null if unmapped\n * @task T162\n */\n mapProviderEvent(providerEvent: string): string | null {\n return CODEX_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For Codex CLI, hooks are registered via the config system\n * (~/.codex/), which is handled by the install provider.\n * This method marks hooks as registered without performing\n * filesystem operations.\n *\n * @param _projectDir - Project directory (unused; hooks are global)\n * @task T162\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For Codex CLI, this is a no-op since hooks are managed through\n * the config system. Unregistration happens via the install\n * provider's uninstall method.\n * @task T162\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via registerNativeHooks.\n * @task T162\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the full event mapping for introspection/debugging.\n * @task T162\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...CODEX_EVENT_MAP };\n }\n\n /**\n * Extract a plain-text transcript from Codex CLI session data.\n *\n * Reads the most recent JSON/JSONL session file under `~/.codex/`\n * and returns its turns as a flat string for brain observation extraction.\n *\n * Returns null when no session data is found or on any read error.\n *\n * @param _sessionId - CLEO session ID (unused; reads the most recent file)\n * @param _projectDir - Project directory (unused; Codex CLI uses global paths)\n * @task T162 @epic T134\n */\n async getTranscript(_sessionId: string, _projectDir: string): Promise<string | null> {\n return readLatestTranscript(join(homedir(), '.codex'));\n }\n}\n", "/**\n * Shared transcript-reading utility for provider hook adapters.\n *\n * Several providers (Gemini CLI, Codex CLI) store session data in a\n * flat directory of JSON/JSONL files using the same role/content schema.\n * This module centralises the \"find most-recent file, parse turns\"\n * logic to avoid duplicating it in each hook provider.\n *\n * Usage:\n * ```ts\n * import { readLatestTranscript } from '../shared/transcript-reader.js';\n *\n * async getTranscript(_sessionId: string, _projectDir: string) {\n * return readLatestTranscript(join(homedir(), '.gemini'));\n * }\n * ```\n *\n * @task T161\n * @epic T134\n */\n\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A single parsed conversation turn from a provider session file. */\ninterface TranscriptTurn {\n role: string;\n content: string;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a raw JSONL or JSON session file into an array of transcript turns.\n *\n * Lines that are not valid JSON, or that lack a string `role` and string\n * `content`, are silently skipped.\n *\n * @param raw - Raw file contents (UTF-8 string).\n * @returns Array of `{ role, content }` pairs, in file order.\n */\nfunction parseTranscriptLines(raw: string): TranscriptTurn[] {\n const turns: TranscriptTurn[] = [];\n const lines = raw.split('\\n').filter((l) => l.trim());\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as Record<string, unknown>;\n const role = entry.role;\n const content = entry.content;\n if (typeof role === 'string' && typeof content === 'string') {\n turns.push({ role, content });\n }\n } catch {\n // Skip malformed lines\n }\n }\n\n return turns;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Read the most recent JSON or JSONL session file from `providerDir` and\n * return its contents as a flat transcript string.\n *\n * Files are sorted in descending order by filename \u2014 this works naturally\n * for providers that embed timestamps in filenames. The most recently named\n * file is read first.\n *\n * Returns `null` when:\n * - `providerDir` does not exist or cannot be read\n * - No JSON/JSONL files are present\n * - The most recent file contains no parseable turns\n *\n * @remarks\n * This utility is shared by Gemini CLI and Codex CLI hook providers which\n * both store session data in the same flat JSON/JSONL format. Only the\n * most recent file is read to keep memory usage bounded.\n *\n * @param providerDir - Absolute path to the provider's session directory\n * (e.g. `~/.gemini` or `~/.codex`).\n * @returns A plain-text transcript with lines of the form `role: content`,\n * or `null` if no transcript could be extracted.\n *\n * @example\n * ```typescript\n * import { readLatestTranscript } from '../shared/transcript-reader.js';\n *\n * const transcript = await readLatestTranscript('/home/user/.gemini');\n * if (transcript) {\n * console.log(transcript);\n * }\n * ```\n *\n * @task T161\n * @epic T134\n */\nexport async function readLatestTranscript(providerDir: string): Promise<string | null> {\n let allFiles: string[] = [];\n\n try {\n const entries = await readdir(providerDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const name = entry.name;\n if (name.endsWith('.json') || name.endsWith('.jsonl')) {\n allFiles.push(join(providerDir, name));\n }\n }\n } catch {\n return null;\n }\n\n if (allFiles.length === 0) return null;\n\n // Sort descending \u2014 timestamps in filenames sort naturally\n allFiles = allFiles.sort((a, b) => b.localeCompare(a));\n const mostRecent = allFiles[0];\n if (!mostRecent) return null;\n\n try {\n const raw = await readFile(mostRecent, 'utf-8');\n const turns = parseTranscriptLines(raw);\n return turns.length > 0 ? turns.map((t) => `${t.role}: ${t.content}`).join('\\n') : null;\n } catch {\n return null;\n }\n}\n", "/**\n * Codex CLI Install Provider\n *\n * Handles CLEO installation into Codex CLI environments:\n * - Ensures AGENTS.md has CLEO @-references\n *\n * @task T162\n * @epic T134\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for Codex CLI.\n *\n * Manages CLEO's integration with Codex CLI by:\n * 1. Ensuring AGENTS.md contains @-references to CLEO instruction files\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. Only AGENTS.md is managed; Codex CLI\n * does not have an MCP or plugin registration mechanism.\n *\n * @task T162\n * @epic T134\n */\nexport class CodexInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Codex CLI environment.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n * @task T162\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure AGENTS.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the Codex CLI environment.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n * @task T162\n */\n async uninstall(): Promise<void> {\n // No-op: no MCP registration to remove\n }\n\n /**\n * Check whether CLEO is installed in the Codex CLI environment.\n *\n * Checks for CLEO references in AGENTS.md.\n * @task T162\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n * @task T162\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update AGENTS.md with CLEO @-references.\n *\n * @param projectDir - Project root directory\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const agentsMdPath = join(projectDir, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsMdPath)) {\n content = readFileSync(agentsMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n content = refsBlock + '\\n';\n }\n\n writeFileSync(agentsMdPath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for OpenAI Codex CLI.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T162\n * @epic T134\n */\n\nimport { CodexAdapter } from './adapter.js';\n\nexport { CodexAdapter } from './adapter.js';\nexport { CodexHookProvider } from './hooks.js';\nexport { CodexInstallProvider } from './install.js';\n\nexport default CodexAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the codex\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link CodexAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/codex';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n *\n * @task T162\n */\nexport function createAdapter(): CodexAdapter {\n return new CodexAdapter();\n}\n", "/**\n * Gemini CLI Adapter\n *\n * Main CLEOProviderAdapter implementation for Google Gemini CLI.\n * Provides hooks and install capabilities for CLEO integration.\n *\n * @task T161\n * @epic T134\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { GeminiCliHookProvider } from './hooks.js';\nimport { GeminiCliInstallProvider } from './install.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for Google Gemini CLI.\n *\n * Bridges CLEO's adapter system with Gemini CLI's native capabilities:\n * - Hooks: Maps Gemini CLI events (SessionStart, PreToolUse, etc.) to CAAMP events\n * - Install: Ensures AGENTS.md references for CLEO instruction files\n *\n * @remarks\n * Gemini CLI supports 10 canonical CAAMP events through its hook system,\n * including PreModel and PostModel which most other providers lack. It has\n * no spawn or transport capabilities. Integration is through AGENTS.md\n * instruction files and the Gemini CLI's configuration at `~/.gemini/`.\n *\n * @task T161\n * @epic T134\n */\nexport class GeminiCliAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'gemini-cli';\n /** Human-readable provider name. */\n readonly name = 'Gemini CLI';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: true,\n supportedHookEvents: [\n 'SessionStart',\n 'SessionEnd',\n 'BeforeAgent',\n 'AfterAgent',\n 'BeforeTool',\n 'AfterTool',\n 'BeforeModel',\n 'AfterModel',\n 'PreCompress',\n 'Notification',\n ],\n supportsSpawn: false,\n supportsInstall: true,\n supportsInstructionFiles: false,\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: false,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider for CAAMP event mapping. */\n hooks: GeminiCliHookProvider;\n /** Install provider for managing instruction files. */\n install: GeminiCliInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new GeminiCliHookProvider();\n this.install = new GeminiCliInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * @param projectDir - Root directory of the project\n * @task T161\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Unregisters hooks and releases any tracked state.\n * @task T161\n */\n async dispose(): Promise<void> {\n if (this.hooks.isRegistered()) {\n await this.hooks.unregisterNativeHooks();\n }\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Gemini CLI is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Gemini CLI binary is available in PATH\n * 3. ~/.gemini/ configuration directory exists\n *\n * @returns Health status with details about each check\n * @task T161\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Gemini CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which gemini');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Gemini CLI config directory\n const geminiConfigDir = join(homedir(), '.gemini');\n const configExists = existsSync(geminiConfigDir);\n details.configDirExists = configExists;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n * @task T161\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n * @task T161\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * Gemini CLI Hook Provider\n *\n * Maps Gemini CLI's native hook events to CAAMP canonical hook events.\n * Gemini CLI supports 11 canonical events through its hook system.\n *\n * Gemini CLI event mapping:\n * - SessionStart -> SessionStart\n * - SessionEnd -> SessionEnd\n * - PromptSubmit -> BeforeAgent\n * - ResponseComplete -> AfterAgent\n * - PreToolUse -> BeforeTool\n * - PostToolUse -> AfterTool\n * - PreModel -> BeforeModel\n * - PostModel -> AfterModel\n * - PreCompact -> PreCompress\n * - Notification -> Notification\n *\n * @task T161\n * @epic T134\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { AdapterHookProvider } from '@cleocode/contracts';\nimport { readLatestTranscript } from '../shared/transcript-reader.js';\n\n/**\n * Mapping from Gemini CLI native event names to CAAMP canonical event names.\n */\nconst GEMINI_CLI_EVENT_MAP: Record<string, string> = {\n SessionStart: 'SessionStart',\n SessionEnd: 'SessionEnd',\n PromptSubmit: 'BeforeAgent',\n ResponseComplete: 'AfterAgent',\n PreToolUse: 'BeforeTool',\n PostToolUse: 'AfterTool',\n PreModel: 'BeforeModel',\n PostModel: 'AfterModel',\n PreCompact: 'PreCompress',\n Notification: 'Notification',\n};\n\n/**\n * Hook provider for Gemini CLI.\n *\n * Gemini CLI registers hooks via its configuration system at\n * ~/.gemini/. Hook handlers are shell scripts or commands that\n * execute when the corresponding event fires.\n *\n * Since hooks are registered through the config system (managed by\n * the install provider), registerNativeHooks and unregisterNativeHooks\n * track registration state without performing filesystem operations.\n *\n * @remarks\n * Gemini CLI uses its own event naming convention (e.g. BeforeAgent,\n * AfterTool, PreCompress) which differs from both the PascalCase CAAMP\n * canonical names and other providers' conventions. The static event map\n * covers all 10 supported canonical events.\n *\n * @task T161\n * @epic T134\n */\nexport class GeminiCliHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered for the current session. */\n private registered = false;\n\n /**\n * Map a Gemini CLI native event name to a CAAMP hook event name.\n *\n * @param providerEvent - Gemini CLI event name (e.g. \"SessionStart\", \"PreToolUse\")\n * @returns CAAMP event name or null if unmapped\n * @task T161\n */\n mapProviderEvent(providerEvent: string): string | null {\n return GEMINI_CLI_EVENT_MAP[providerEvent] ?? null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * For Gemini CLI, hooks are registered via the config system\n * (~/.gemini/), which is handled by the install provider.\n * This method marks hooks as registered without performing\n * filesystem operations.\n *\n * @param _projectDir - Project directory (unused; hooks are global)\n * @task T161\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * For Gemini CLI, this is a no-op since hooks are managed through\n * the config system. Unregistration happens via the install\n * provider's uninstall method.\n * @task T161\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via registerNativeHooks.\n * @task T161\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the full event mapping for introspection/debugging.\n * @task T161\n */\n getEventMap(): Readonly<Record<string, string>> {\n return { ...GEMINI_CLI_EVENT_MAP };\n }\n\n /**\n * Extract a plain-text transcript from Gemini CLI session data.\n *\n * Reads the most recent JSON/JSONL session file under `~/.gemini/`\n * and returns its turns as a flat string for brain observation extraction.\n *\n * Returns null when no session data is found or on any read error.\n *\n * @param _sessionId - CLEO session ID (unused; reads the most recent file)\n * @param _projectDir - Project directory (unused; Gemini CLI uses global paths)\n * @task T161 @epic T134\n */\n async getTranscript(_sessionId: string, _projectDir: string): Promise<string | null> {\n return readLatestTranscript(join(homedir(), '.gemini'));\n }\n}\n", "/**\n * Gemini CLI Install Provider\n *\n * Handles CLEO installation into Gemini CLI environments:\n * - Ensures AGENTS.md has CLEO @-references\n *\n * @task T161\n * @epic T134\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for Gemini CLI.\n *\n * Manages CLEO's integration with Gemini CLI by:\n * 1. Ensuring AGENTS.md contains @-references to CLEO instruction files\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. Only AGENTS.md is managed; Gemini CLI\n * does not have an MCP or plugin registration mechanism.\n *\n * @task T161\n * @epic T134\n */\nexport class GeminiCliInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Gemini CLI environment.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n * @task T161\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure AGENTS.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the Gemini CLI environment.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n * @task T161\n */\n async uninstall(): Promise<void> {\n // No-op: no MCP registration to remove\n }\n\n /**\n * Check whether CLEO is installed in the Gemini CLI environment.\n *\n * Checks for CLEO references in AGENTS.md.\n * @task T161\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n * @task T161\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update AGENTS.md with CLEO @-references.\n *\n * @param projectDir - Project root directory\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const agentsMdPath = join(projectDir, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsMdPath)) {\n content = readFileSync(agentsMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n content = refsBlock + '\\n';\n }\n\n writeFileSync(agentsMdPath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Google Gemini CLI.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T161\n * @epic T134\n */\n\nimport { GeminiCliAdapter } from './adapter.js';\n\nexport { GeminiCliAdapter } from './adapter.js';\nexport { GeminiCliHookProvider } from './hooks.js';\nexport { GeminiCliInstallProvider } from './install.js';\n\nexport default GeminiCliAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the gemini-cli\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link GeminiCliAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/gemini-cli';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n *\n * @task T161\n */\nexport function createAdapter(): GeminiCliAdapter {\n return new GeminiCliAdapter();\n}\n", "/**\n * Kimi Adapter\n *\n * Main CLEOProviderAdapter implementation for Moonshot AI Kimi.\n * Provides install-only capabilities for CLEO integration.\n * Kimi has no native hook system; integration is via instruction files.\n *\n * @task T163\n * @epic T134\n */\n\nimport { exec } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AdapterCapabilities,\n AdapterHealthStatus,\n CLEOProviderAdapter,\n} from '@cleocode/contracts';\nimport { KimiHookProvider } from './hooks.js';\nimport { KimiInstallProvider } from './install.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * CLEO provider adapter for Moonshot AI Kimi.\n *\n * Bridges CLEO's adapter system with Kimi's integration surface:\n * - Hooks: No-op (Kimi has no native hook system)\n * - Install: Ensures AGENTS.md references for CLEO instruction files\n *\n * @remarks\n * Kimi has no native hook or event system, so all hook-related capabilities\n * are disabled. The adapter is install-only, managing AGENTS.md references\n * for CLEO instruction injection.\n *\n * @task T163\n * @epic T134\n */\nexport class KimiAdapter implements CLEOProviderAdapter {\n /** Unique provider identifier. */\n readonly id = 'kimi';\n /** Human-readable provider name. */\n readonly name = 'Kimi';\n /** Adapter version string. */\n readonly version = '1.0.0';\n\n /** Declared capabilities for this provider. */\n capabilities: AdapterCapabilities = {\n supportsHooks: false,\n supportedHookEvents: [],\n supportsSpawn: false,\n supportsInstall: true,\n supportsInstructionFiles: false,\n supportsContextMonitor: false,\n supportsStatusline: false,\n supportsProviderPaths: false,\n supportsTransport: false,\n supportsTaskSync: false,\n };\n\n /** Hook provider (no-op since Kimi has no event system). */\n hooks: KimiHookProvider;\n /** Install provider for managing instruction files. */\n install: KimiInstallProvider;\n\n /** Project directory this adapter was initialized with, or null. */\n private projectDir: string | null = null;\n /** Whether {@link initialize} has been called. */\n private initialized = false;\n\n constructor() {\n this.hooks = new KimiHookProvider();\n this.install = new KimiInstallProvider();\n }\n\n /**\n * Initialize the adapter for a given project directory.\n *\n * @param projectDir - Root directory of the project\n * @task T163\n */\n async initialize(projectDir: string): Promise<void> {\n this.projectDir = projectDir;\n this.initialized = true;\n }\n\n /**\n * Dispose the adapter and clean up resources.\n *\n * Releases tracked state. No hooks to unregister since Kimi\n * has no native hook system.\n * @task T163\n */\n async dispose(): Promise<void> {\n this.initialized = false;\n this.projectDir = null;\n }\n\n /**\n * Run a health check to verify Kimi is accessible.\n *\n * Checks:\n * 1. Adapter has been initialized\n * 2. Kimi CLI binary is available in PATH\n * 3. ~/.kimi/ configuration directory exists\n *\n * @returns Health status with details about each check\n * @task T163\n */\n async healthCheck(): Promise<AdapterHealthStatus> {\n const details: Record<string, unknown> = {};\n\n if (!this.initialized) {\n return {\n healthy: false,\n provider: this.id,\n details: { error: 'Adapter not initialized' },\n };\n }\n\n // Check Kimi CLI availability\n let cliAvailable = false;\n try {\n const { stdout } = await execAsync('which kimi');\n cliAvailable = stdout.trim().length > 0;\n details.cliPath = stdout.trim();\n } catch {\n details.cliAvailable = false;\n }\n\n // Check for Kimi config directory\n const kimiConfigDir = join(homedir(), '.kimi');\n const configExists = existsSync(kimiConfigDir);\n details.configDirExists = configExists;\n\n // Healthy if CLI is available (primary requirement)\n const healthy = cliAvailable;\n details.cliAvailable = cliAvailable;\n\n return {\n healthy,\n provider: this.id,\n details,\n };\n }\n\n /**\n * Check whether the adapter has been initialized.\n * @task T163\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the project directory this adapter was initialized with.\n * @task T163\n */\n getProjectDir(): string | null {\n return this.projectDir;\n }\n}\n", "/**\n * Kimi Hook Provider\n *\n * Kimi has no native hook system (hookSystem is \"none\").\n * This provider implements the minimal AdapterHookProvider interface\n * with a no-op mapProviderEvent that always returns null.\n *\n * @task T163\n * @epic T134\n */\n\nimport type { AdapterHookProvider } from '@cleocode/contracts';\n\n/**\n * Hook provider for Kimi.\n *\n * Kimi does not expose a native hook or event system.\n * All hook-related methods are no-ops; mapProviderEvent always\n * returns null since there are no events to map.\n *\n * @remarks\n * Since Kimi has no hookable events, the event map is empty and\n * `mapProviderEvent` always returns null. Registration state is tracked\n * purely for interface compliance with {@link AdapterHookProvider}.\n *\n * @task T163\n * @epic T134\n */\nexport class KimiHookProvider implements AdapterHookProvider {\n /** Whether hooks have been registered (always a no-op for Kimi). */\n private registered = false;\n\n /**\n * Map a Kimi native event name to a CAAMP hook event name.\n *\n * Kimi has no hook system, so this always returns null.\n *\n * @param _providerEvent - Unused; Kimi emits no hookable events\n * @returns Always null\n * @task T163\n */\n mapProviderEvent(_providerEvent: string): string | null {\n return null;\n }\n\n /**\n * Register native hooks for a project.\n *\n * Kimi has no hook system. This method is a no-op and only\n * tracks registration state for interface compliance.\n *\n * @param _projectDir - Project directory (unused)\n * @task T163\n */\n async registerNativeHooks(_projectDir: string): Promise<void> {\n this.registered = true;\n }\n\n /**\n * Unregister native hooks.\n *\n * Kimi has no hook system. This method is a no-op.\n * @task T163\n */\n async unregisterNativeHooks(): Promise<void> {\n this.registered = false;\n }\n\n /**\n * Check whether hooks have been registered via registerNativeHooks.\n * @task T163\n */\n isRegistered(): boolean {\n return this.registered;\n }\n\n /**\n * Get the full event mapping for introspection/debugging.\n *\n * Returns an empty map since Kimi has no hookable events.\n * @task T163\n */\n getEventMap(): Readonly<Record<string, string>> {\n return {};\n }\n}\n", "/**\n * Kimi Install Provider\n *\n * Handles CLEO installation into Kimi environments:\n * - Ensures AGENTS.md has CLEO @-references\n *\n * @task T163\n * @epic T134\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';\n\n/** Lines that should appear in AGENTS.md to reference CLEO. */\nconst INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];\n\n/**\n * Install provider for Kimi.\n *\n * Manages CLEO's integration with Kimi by:\n * 1. Ensuring AGENTS.md contains @-references to CLEO instruction files\n *\n * @remarks\n * Installation is idempotent -- running install multiple times on the same\n * project produces the same result. Only AGENTS.md is managed; Kimi does\n * not have an MCP or plugin registration mechanism.\n *\n * @task T163\n * @epic T134\n */\nexport class KimiInstallProvider implements AdapterInstallProvider {\n /**\n * Install CLEO into a Kimi environment.\n *\n * @param options - Installation options including project directory\n * @returns Result describing what was installed\n * @task T163\n */\n async install(options: InstallOptions): Promise<InstallResult> {\n const { projectDir } = options;\n const installedAt = new Date().toISOString();\n let instructionFileUpdated = false;\n const details: Record<string, unknown> = {};\n\n // Step 1: Ensure AGENTS.md has @-references\n instructionFileUpdated = this.updateInstructionFile(projectDir);\n if (instructionFileUpdated) {\n details.instructionFile = join(projectDir, 'AGENTS.md');\n }\n\n return {\n success: true,\n installedAt,\n instructionFileUpdated,\n details,\n };\n }\n\n /**\n * Uninstall CLEO from the Kimi environment.\n *\n * Does not remove AGENTS.md references (they are harmless if CLEO is not present).\n * @task T163\n */\n async uninstall(): Promise<void> {\n // No-op: no MCP registration to remove\n }\n\n /**\n * Check whether CLEO is installed in the Kimi environment.\n *\n * Checks for CLEO references in AGENTS.md.\n * @task T163\n */\n async isInstalled(): Promise<boolean> {\n const agentsMdPath = join(process.cwd(), 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n try {\n const content = readFileSync(agentsMdPath, 'utf-8');\n if (INSTRUCTION_REFERENCES.some((ref) => content.includes(ref))) {\n return true;\n }\n } catch {\n // Fall through\n }\n }\n\n return false;\n }\n\n /**\n * Ensure AGENTS.md contains @-references to CLEO instruction files.\n *\n * Creates AGENTS.md if it does not exist. Appends any missing references.\n *\n * @param projectDir - Project root directory\n * @task T163\n */\n async ensureInstructionReferences(projectDir: string): Promise<void> {\n this.updateInstructionFile(projectDir);\n }\n\n /**\n * Update AGENTS.md with CLEO @-references.\n *\n * @param projectDir - Project root directory\n * @returns true if the file was created or modified\n */\n private updateInstructionFile(projectDir: string): boolean {\n const agentsMdPath = join(projectDir, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsMdPath)) {\n content = readFileSync(agentsMdPath, 'utf-8');\n existed = true;\n }\n\n const missingRefs = INSTRUCTION_REFERENCES.filter((ref) => !content.includes(ref));\n\n if (missingRefs.length === 0) {\n return false;\n }\n\n const refsBlock = missingRefs.join('\\n');\n\n if (existed) {\n const separator = content.endsWith('\\n') ? '' : '\\n';\n content = content + separator + refsBlock + '\\n';\n } else {\n content = refsBlock + '\\n';\n }\n\n writeFileSync(agentsMdPath, content, 'utf-8');\n return true;\n }\n}\n", "/**\n * @packageDocumentation\n *\n * CLEO provider adapter for Moonshot AI Kimi.\n * Default export is the adapter class for dynamic loading by AdapterManager.\n *\n * @task T163\n * @epic T134\n */\n\nimport { KimiAdapter } from './adapter.js';\n\nexport { KimiAdapter } from './adapter.js';\nexport { KimiHookProvider } from './hooks.js';\nexport { KimiInstallProvider } from './install.js';\n\nexport default KimiAdapter;\n\n/**\n * Factory function for creating adapter instances.\n * Used by AdapterManager's dynamic import fallback.\n *\n * @remarks\n * This is the primary entry point for dynamic adapter loading.\n * AdapterManager calls this function when it resolves the kimi\n * provider via its import-based discovery mechanism.\n *\n * @returns A new {@link KimiAdapter} instance ready for initialization\n *\n * @example\n * ```typescript\n * import { createAdapter } from '@cleocode/adapters/providers/kimi';\n *\n * const adapter = createAdapter();\n * await adapter.initialize('/path/to/project');\n * ```\n *\n * @task T163\n */\nexport function createAdapter(): KimiAdapter {\n return new KimiAdapter();\n}\n", "/**\n * Adapter registry \u2014 discovers and provides access to provider manifests.\n *\n * Scans the providers/ directory for manifest.json files and returns\n * the discovered adapter manifests for use by AdapterManager.\n *\n * @task T5240\n */\n\nimport { readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Minimal manifest shape for provider discovery.\n *\n * @remarks\n * Each provider adapter ships a `manifest.json` in its directory under\n * `providers/`. The registry reads these at startup to populate the\n * adapter discovery surface. The shape is intentionally minimal -- only\n * the fields needed for dynamic loading and detection are required.\n */\nexport interface AdapterManifest {\n /** Unique provider identifier (e.g. \"claude-code\", \"cursor\"). */\n id: string;\n /** Human-readable display name for the provider. */\n name: string;\n /** Semantic version of the adapter. */\n version: string;\n /** Short description of what the provider integrates with. */\n description: string;\n /** Provider slug used for directory lookups. */\n provider: string;\n /** Relative path to the adapter's entry point module. */\n entryPoint: string;\n /** Capability flags declared by the adapter. */\n capabilities: Record<string, unknown>;\n /** Patterns used to auto-detect the provider in a project. */\n detectionPatterns: Array<{\n /** Detection strategy type (e.g. \"file\", \"env\"). */\n type: string;\n /** Glob or regex pattern to match. */\n pattern: string;\n /** Human-readable explanation of this detection rule. */\n description: string;\n }>;\n}\n\n/** Known provider IDs bundled with @cleocode/adapters. */\nconst PROVIDER_IDS = ['claude-code', 'opencode', 'cursor', 'pi'] as const;\n\n/**\n * Get the manifests for all bundled provider adapters.\n *\n * @remarks\n * Scans the known provider directories for `manifest.json` files.\n * Providers whose manifests cannot be loaded (missing or malformed)\n * are silently skipped.\n *\n * @returns Array of adapter manifests for successfully loaded providers\n *\n * @example\n * ```typescript\n * import { getProviderManifests } from '@cleocode/adapters';\n *\n * const manifests = getProviderManifests();\n * for (const m of manifests) {\n * console.log(`${m.id}: ${m.name} v${m.version}`);\n * }\n * ```\n */\nexport function getProviderManifests(): AdapterManifest[] {\n const manifests: AdapterManifest[] = [];\n const baseDir = resolve(dirname(fileURLToPath(import.meta.url)), 'providers');\n\n for (const providerId of PROVIDER_IDS) {\n try {\n const manifestPath = join(baseDir, providerId, 'manifest.json');\n const raw = readFileSync(manifestPath, 'utf-8');\n manifests.push(JSON.parse(raw) as AdapterManifest);\n } catch {\n // Skip providers whose manifests cannot be loaded\n }\n }\n\n return manifests;\n}\n\n/**\n * Discover all available provider adapters.\n *\n * Returns a map of provider ID to adapter factory function.\n *\n * @remarks\n * Each factory lazily imports the provider module and constructs a new\n * adapter instance. This avoids loading all provider code upfront and\n * keeps startup fast.\n *\n * @returns Map of provider ID to async factory function that creates an adapter instance\n *\n * @example\n * ```typescript\n * import { discoverProviders } from '@cleocode/adapters';\n *\n * const providers = await discoverProviders();\n * const factory = providers.get('claude-code');\n * if (factory) {\n * const adapter = await factory();\n * }\n * ```\n */\nexport async function discoverProviders(): Promise<Map<string, () => Promise<unknown>>> {\n const providers = new Map<string, () => Promise<unknown>>();\n\n providers.set('claude-code', async () => {\n const { ClaudeCodeAdapter } = await import('./providers/claude-code/index.js');\n return new ClaudeCodeAdapter();\n });\n\n providers.set('opencode', async () => {\n const { OpenCodeAdapter } = await import('./providers/opencode/index.js');\n return new OpenCodeAdapter();\n });\n\n providers.set('cursor', async () => {\n const { CursorAdapter } = await import('./providers/cursor/index.js');\n return new CursorAdapter();\n });\n\n providers.set('pi', async () => {\n const { PiAdapter } = await import('./providers/pi/index.js');\n return new PiAdapter();\n });\n\n return providers;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,S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CAAC;AACtC,QAAM,UAAU,QAAQF,SAAQE,eAAc,YAAY,GAAG,CAAC,GAAG,WAAW;AAE5E,aAAW,cAAc,cAAc;AACrC,QAAI;AACF,YAAM,eAAeD,OAAK,SAAS,YAAY,eAAe;AAC9D,YAAM,MAAMF,eAAa,cAAc,OAAO;AAC9C,gBAAU,KAAK,KAAK,MAAM,GAAG,CAAoB;AAAA,IACnD,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,SAAO;AACT;AAyBA,eAAsB,oBAAkE;AACtF,QAAM,YAAY,oBAAI,IAAoC;AAE1D,YAAU,IAAI,eAAe,YAAY;AACvC,UAAM,EAAE,mBAAAI,mBAAkB,IAAI,MAAM;AACpC,WAAO,IAAIA,mBAAkB;AAAA,EAC/B,CAAC;AAED,YAAU,IAAI,YAAY,YAAY;AACpC,UAAM,EAAE,iBAAAC,iBAAgB,IAAI,MAAM;AAClC,WAAO,IAAIA,iBAAgB;AAAA,EAC7B,CAAC;AAED,YAAU,IAAI,UAAU,YAAY;AAClC,UAAM,EAAE,eAAAC,eAAc,IAAI,MAAM;AAChC,WAAO,IAAIA,eAAc;AAAA,EAC3B,CAAC;AAED,YAAU,IAAI,MAAM,YAAY;AAC9B,UAAM,EAAE,WAAAC,WAAU,IAAI,MAAM;AAC5B,WAAO,IAAIA,WAAU;AAAA,EACvB,CAAC;AAED,SAAO;AACT;",
|
|
6
6
|
"names": ["homedir", "join", "existsSync", "readFileSync", "homedir", "join", "existsSync", "readFileSync", "writeFileSync", "homedir", "join", "existsSync", "mkdirSync", "readdirSync", "readFileSync", "writeFileSync", "homedir", "dirname", "join", "init_session", "init_session", "buildCantEnrichedPrompt", "readFile", "join", "exec", "existsSync", "homedir", "join", "promisify", "execAsync", "existsSync", "readFileSync", "homedir", "join", "PROVIDER_ID", "init_hooks", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "join", "INSTRUCTION_REFERENCES", "init_install", "existsSync", "join", "init_adapter", "init_hooks", "init_install", "createAdapter", "init_adapter", "init_hooks", "init_install", "PROVIDER_ID", "init_hooks", "existsSync", "readFileSync", "writeFileSync", "join", "INSTRUCTION_REFERENCES", "init_install", "exec", "nodeSpawn", "mkdir", "readFile", "writeFile", "join", "promisify", "execAsync", "init_spawn", "buildCantEnrichedPrompt", "exec", "existsSync", "join", "promisify", "execAsync", "init_adapter", "init_hooks", "init_install", "init_spawn", "createAdapter", "init_adapter", "init_hooks", "init_install", "init_spawn", "PROVIDER_ID", "init_hooks", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "homedir", "join", "INSTRUCTION_REFERENCES", "init_install", "exec", "nodeSpawn", "unlink", "writeFile", "promisify", "execAsync", "init_spawn", "exec", "existsSync", "homedir", "join", "promisify", "getPiAgentDir", "execAsync", "init_adapter", "init_hooks", "init_install", "init_spawn", "createAdapter", "init_adapter", "init_hooks", "init_install", "init_spawn", "exec", "existsSync", "homedir", "join", "promisify", "homedir", "join", "readdir", "readFile", "join", "join", "homedir", "existsSync", "readFileSync", "writeFileSync", "join", "INSTRUCTION_REFERENCES", "execAsync", "promisify", "exec", "join", "homedir", "existsSync", "createAdapter", "exec", "existsSync", "homedir", "join", "promisify", "homedir", "join", "join", "homedir", "existsSync", "readFileSync", "writeFileSync", "join", "INSTRUCTION_REFERENCES", "execAsync", "promisify", "exec", "join", "homedir", "existsSync", "createAdapter", "exec", "existsSync", "homedir", "join", "promisify", "existsSync", "readFileSync", "writeFileSync", "join", "INSTRUCTION_REFERENCES", "execAsync", "promisify", "exec", "join", "homedir", "existsSync", "createAdapter", "readFileSync", "dirname", "join", "fileURLToPath", "ClaudeCodeAdapter", "OpenCodeAdapter", "CursorAdapter", "PiAdapter"]
|
|
7
7
|
}
|