kairn-cli 2.9.0 → 2.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +128 -9
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/keychain.ts","../src/providers.ts","../src/llm.ts","../src/evolve/baseline.ts","../src/evolve/trace.ts","../src/evolve/exec.ts","../src/evolve/scorers.ts","../src/evolve/runner.ts","../src/evolve/memory.ts","../src/evolve/proposer.ts","../src/ir/types.ts","../src/ir/parser.ts","../src/ir/translate.ts","../src/ir/mutations.ts","../src/ir/renderer.ts","../src/ir/diff.ts","../src/evolve/mutator.ts","../src/evolve/sampling.ts","../src/evolve/regularization.ts","../src/evolve/targeting.ts","../src/evolve/loop.ts","../src/evolve/synthesis.ts","../src/evolve/population.ts","../src/cli.ts","../src/commands/init.ts","../src/config.ts","../src/ui.ts","../src/logo.ts","../src/commands/describe.ts","../src/compiler/compile.ts","../src/compiler/prompt.ts","../src/registry/loader.ts","../src/intent/patterns.ts","../src/intent/prompt-template.ts","../src/intent/router-template.ts","../src/intent/learner-template.ts","../src/adapter/claude-code.ts","../src/autonomy.ts","../src/adapter/hermes-agent.ts","../src/secrets.ts","../src/commands/list.ts","../src/commands/activate.ts","../src/commands/update-registry.ts","../src/commands/optimize.ts","../src/scanner/scan.ts","../src/commands/doctor.ts","../src/commands/registry.ts","../src/commands/templates.ts","../src/commands/keys.ts","../src/commands/evolve.ts","../src/evolve/init.ts","../src/evolve/templates.ts","../src/evolve/report.ts","../src/evolve/diagnosis.ts","../src/evolve/apply.ts"],"sourcesContent":["import { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nconst KEYCHAIN_SERVICE = 'Claude Code-credentials';\nconst TOKEN_EXPIRY_BUFFER_MS = 60_000; // Treat tokens as expired 60s early\n\nexport interface OAuthCredentials {\n accessToken: string;\n refreshToken: string;\n expiresAt: number;\n subscriptionType: string;\n}\n\n/**\n * Parse raw keychain JSON into OAuthCredentials.\n * Returns null if the JSON is invalid or missing required fields.\n */\nexport function parseKeychainCredentials(raw: string): OAuthCredentials | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n\n if (typeof parsed !== 'object' || parsed === null) return null;\n\n const obj = parsed as Record<string, unknown>;\n const oauth = obj['claudeAiOauth'];\n if (typeof oauth !== 'object' || oauth === null) return null;\n\n const oauthObj = oauth as Record<string, unknown>;\n const accessToken = oauthObj['accessToken'];\n const refreshToken = oauthObj['refreshToken'];\n const expiresAt = oauthObj['expiresAt'];\n const subscriptionType = oauthObj['subscriptionType'];\n\n if (typeof accessToken !== 'string' || !accessToken) return null;\n if (typeof refreshToken !== 'string') return null;\n if (typeof expiresAt !== 'number') return null;\n\n return {\n accessToken,\n refreshToken,\n expiresAt,\n subscriptionType: typeof subscriptionType === 'string' ? subscriptionType : 'unknown',\n };\n}\n\n/**\n * Check if an OAuth token is expired (or within the expiry buffer).\n */\nexport function isTokenExpired(credentials: OAuthCredentials): boolean {\n return Date.now() + TOKEN_EXPIRY_BUFFER_MS >= credentials.expiresAt;\n}\n\n/**\n * Read Claude Code OAuth credentials from macOS Keychain.\n * Returns null if not on macOS, keychain entry doesn't exist, or parsing fails.\n */\nexport async function readClaudeCodeCredentials(\n account?: string,\n): Promise<OAuthCredentials | null> {\n if (process.platform !== 'darwin') return null;\n\n try {\n const acct = account ?? '';\n const cmd = acct\n ? `security find-generic-password -s \"${KEYCHAIN_SERVICE}\" -a \"${acct}\" -w`\n : `security find-generic-password -s \"${KEYCHAIN_SERVICE}\" -w`;\n\n const { stdout } = await execAsync(cmd, { timeout: 5000 });\n return parseKeychainCredentials(stdout.trim());\n } catch {\n return null;\n }\n}\n\n/**\n * Get a valid access token, reading from keychain.\n * Returns the token string or null if unavailable/expired.\n *\n * Note: Token refresh is not implemented — when the token expires,\n * Claude Code itself will refresh it on next launch. The user can\n * re-run `kairn init` if the token is stale.\n */\nexport async function getAccessToken(\n account?: string,\n): Promise<string | null> {\n const creds = await readClaudeCodeCredentials(account);\n if (!creds) return null;\n if (isTokenExpired(creds)) return null;\n return creds.accessToken;\n}\n","import type { LLMProvider } from \"./types.js\";\n\nexport interface ProviderConfig {\n name: string;\n baseURL?: string;\n verifyModel: string;\n cheapModel: string;\n}\n\nexport const PROVIDER_CONFIGS: Record<Exclude<LLMProvider, \"other\">, ProviderConfig> = {\n anthropic: {\n name: \"Anthropic\",\n verifyModel: \"claude-haiku-4-5-20251001\",\n cheapModel: \"claude-haiku-4-5-20251001\",\n },\n openai: {\n name: \"OpenAI\",\n verifyModel: \"gpt-4.1-nano\",\n cheapModel: \"gpt-4.1-nano\",\n },\n google: {\n name: \"Google Gemini\",\n baseURL: \"https://generativelanguage.googleapis.com/v1beta/openai/\",\n verifyModel: \"gemini-2.5-flash\",\n cheapModel: \"gemini-2.5-flash\",\n },\n xai: {\n name: \"xAI (Grok)\",\n baseURL: \"https://api.x.ai/v1\",\n verifyModel: \"grok-4-1-fast-non-reasoning\",\n cheapModel: \"grok-4-1-fast-non-reasoning\",\n },\n deepseek: {\n name: \"DeepSeek\",\n baseURL: \"https://api.deepseek.com\",\n verifyModel: \"deepseek-chat\",\n cheapModel: \"deepseek-chat\",\n },\n mistral: {\n name: \"Mistral\",\n baseURL: \"https://api.mistral.ai/v1\",\n verifyModel: \"mistral-small-latest\",\n cheapModel: \"mistral-small-latest\",\n },\n groq: {\n name: \"Groq (open-source models)\",\n baseURL: \"https://api.groq.com/openai/v1\",\n verifyModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n cheapModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n },\n};\n\nexport const PROVIDER_MODELS: Record<Exclude<LLMProvider, \"other\">, { name: string; value: string }[]> = {\n anthropic: [\n { name: \"Claude Sonnet 4.6 (recommended)\", value: \"claude-sonnet-4-6\" },\n { name: \"Claude Opus 4.6 (highest quality)\", value: \"claude-opus-4-6\" },\n { name: \"Claude Haiku 4.5 (fastest, cheapest)\", value: \"claude-haiku-4-5-20251001\" },\n ],\n openai: [\n { name: \"GPT-4.1 (recommended — smartest non-reasoning)\", value: \"gpt-4.1\" },\n { name: \"GPT-4.1 mini (faster, cheaper)\", value: \"gpt-4.1-mini\" },\n { name: \"o4-mini (reasoning, cost-efficient)\", value: \"o4-mini\" },\n { name: \"GPT-5 mini (frontier)\", value: \"gpt-5-mini\" },\n ],\n google: [\n { name: \"Gemini 2.5 Flash (recommended — best value)\", value: \"gemini-2.5-flash\" },\n { name: \"Gemini 3 Flash (newest frontier)\", value: \"gemini-3-flash\" },\n { name: \"Gemini 2.5 Pro (highest quality)\", value: \"gemini-2.5-pro\" },\n { name: \"Gemini 3.1 Pro Preview (most advanced)\", value: \"gemini-3.1-pro-preview\" },\n ],\n xai: [\n { name: \"Grok 4.1 Fast (recommended — $0.20/M, very fast)\", value: \"grok-4-1-fast-non-reasoning\" },\n { name: \"Grok 4.20 (frontier quality, 2M context)\", value: \"grok-4.20-0309-non-reasoning\" },\n ],\n deepseek: [\n { name: \"DeepSeek V3.2 Chat (recommended — cheapest good model)\", value: \"deepseek-chat\" },\n { name: \"DeepSeek V3.2 Reasoner (with chain-of-thought)\", value: \"deepseek-reasoner\" },\n ],\n mistral: [\n { name: \"Mistral Large 3 (recommended — open-weight flagship)\", value: \"mistral-large-latest\" },\n { name: \"Codestral (code-optimized, 256K context)\", value: \"codestral-latest\" },\n { name: \"Mistral Small 4 (cheapest)\", value: \"mistral-small-latest\" },\n ],\n groq: [\n { name: \"Llama 4 Maverick (recommended — free, fast)\", value: \"meta-llama/llama-4-maverick-17b-128e-instruct\" },\n { name: \"Llama 4 Scout (free, fast)\", value: \"meta-llama/llama-4-scout-17b-16e-instruct\" },\n { name: \"DeepSeek R1 70B (free reasoning)\", value: \"deepseek-r1-distill-llama-70b\" },\n { name: \"Qwen 3 32B (free, multilingual)\", value: \"qwen/qwen3-32b\" },\n ],\n};\n\nexport const PROVIDER_CHOICES: { name: string; value: LLMProvider }[] = [\n { name: \"Anthropic (Claude) — recommended\", value: \"anthropic\" },\n { name: \"OpenAI (GPT)\", value: \"openai\" },\n { name: \"Google (Gemini)\", value: \"google\" },\n { name: \"xAI (Grok)\", value: \"xai\" },\n { name: \"DeepSeek — cheapest\", value: \"deepseek\" },\n { name: \"Mistral — open-weight\", value: \"mistral\" },\n { name: \"Groq — free tier, open-source models\", value: \"groq\" },\n { name: \"Other (OpenAI-compatible endpoint)\", value: \"other\" },\n];\n\nexport function getProviderName(provider: LLMProvider): string {\n if (provider === \"other\") return \"Custom endpoint\";\n return PROVIDER_CONFIGS[provider].name;\n}\n\nexport function getBaseURL(provider: LLMProvider, customBaseURL?: string): string | undefined {\n if (provider === \"other\") return customBaseURL;\n return PROVIDER_CONFIGS[provider]?.baseURL;\n}\n\nexport function getCheapModel(provider: LLMProvider, fallbackModel: string): string {\n if (provider === \"other\") return fallbackModel;\n return PROVIDER_CONFIGS[provider].cheapModel;\n}\n\nexport function getVerifyModel(provider: LLMProvider, fallbackModel: string): string {\n if (provider === \"other\") return fallbackModel;\n return PROVIDER_CONFIGS[provider].verifyModel;\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport OpenAI from \"openai\";\nimport { getProviderName, getBaseURL } from \"./providers.js\";\nimport { getAccessToken } from \"./auth/keychain.js\";\nimport type { KairnConfig } from \"./types.js\";\n\n/**\n * Classify an API error into a user-friendly, actionable message.\n *\n * Inspects the error's `status`, `code`, and message text to produce\n * guidance specific to the provider (e.g. \"Run `kairn init` to reconfigure\").\n */\nexport function classifyError(err: unknown, provider: string): string {\n const msg = err instanceof Error ? err.message : String(err);\n const status = (err as { status?: number })?.status;\n const code = (err as { code?: string })?.code;\n\n // Network errors\n if (code === \"ECONNREFUSED\" || code === \"ENOTFOUND\" || code === \"ETIMEDOUT\") {\n return `Network error: could not reach ${provider} API. Check your internet connection.`;\n }\n\n // Auth errors\n if (status === 401 || (msg.includes(\"invalid\") && msg.includes(\"key\"))) {\n return `Invalid API key for ${provider}. Run \\`kairn init\\` to reconfigure.`;\n }\n if (status === 403) {\n return `Access denied by ${provider}. Your API key may lack permissions for this model.`;\n }\n\n // Rate limiting\n if (status === 429 || msg.includes(\"rate limit\") || msg.includes(\"quota\")) {\n return `Rate limited by ${provider}. Wait a moment and try again, or switch to a cheaper model with \\`kairn init\\`.`;\n }\n\n // Model errors\n if (status === 404 || msg.includes(\"not found\") || msg.includes(\"does not exist\")) {\n return `Model not found on ${provider}. Run \\`kairn init\\` to select a valid model.`;\n }\n\n // Overloaded\n if (status === 529 || status === 503 || msg.includes(\"overloaded\")) {\n return `${provider} is temporarily overloaded. Try again in a few seconds.`;\n }\n\n // Token/context limit\n if (msg.includes(\"token\") && (msg.includes(\"limit\") || msg.includes(\"exceed\"))) {\n return `Request too large for the selected model. Try a shorter workflow description.`;\n }\n\n // Billing\n if (msg.includes(\"billing\") || msg.includes(\"payment\") || msg.includes(\"insufficient\")) {\n return `Billing issue with your ${provider} account. Check your account dashboard.`;\n }\n\n // Fallback\n return `${provider} API error: ${msg}`;\n}\n\n/**\n * Call an LLM provider with a user message and system prompt.\n *\n * Routes to the Anthropic SDK for `anthropic` provider, and to the\n * OpenAI-compatible SDK for all other providers.\n *\n * @param config - Kairn configuration with provider, API key, and model\n * @param userMessage - The user message to send\n * @param options - Must include `systemPrompt`; `maxTokens` defaults to 8192\n * @returns The text response from the LLM\n */\nexport async function callLLM(\n config: KairnConfig,\n userMessage: string,\n options: { maxTokens?: number; systemPrompt: string; jsonMode?: boolean; cacheControl?: boolean }\n): Promise<string> {\n const maxTokens = options.maxTokens ?? 8192;\n const { systemPrompt } = options;\n const jsonMode = options.jsonMode ?? false;\n const cacheControl = options.cacheControl ?? false;\n const providerName = getProviderName(config.provider);\n\n // Resolve API key — use OAuth token from keychain if configured\n let apiKey = config.api_key;\n if (config.auth_type === 'claude-code-oauth') {\n const oauthToken = await getAccessToken();\n if (!oauthToken) {\n throw new Error(\n 'Claude Code OAuth token unavailable or expired. Run `kairn init` to reconfigure, or launch Claude Code to refresh the token.'\n );\n }\n apiKey = oauthToken;\n }\n\n if (config.provider === \"anthropic\") {\n const client = new Anthropic({ apiKey });\n\n const messages: Array<{ role: \"user\" | \"assistant\"; content: string }> = [\n { role: \"user\", content: userMessage },\n ];\n\n try {\n const response = await client.messages.create({\n model: config.model,\n max_tokens: maxTokens,\n system: cacheControl\n ? [{ type: \"text\" as const, text: systemPrompt, cache_control: { type: \"ephemeral\" as const } }]\n : systemPrompt,\n messages,\n });\n const textBlock = response.content.find((block) => block.type === \"text\");\n if (!textBlock || textBlock.type !== \"text\") {\n throw new Error(\"No text response from compiler LLM\");\n }\n return textBlock.text;\n } catch (err) {\n throw new Error(classifyError(err, providerName));\n }\n }\n\n // All other providers use OpenAI-compatible API\n const resolvedBaseURL = getBaseURL(config.provider, config.base_url);\n const clientOptions: { apiKey: string; baseURL?: string } = { apiKey };\n if (resolvedBaseURL) clientOptions.baseURL = resolvedBaseURL;\n\n const client = new OpenAI(clientOptions);\n try {\n const response = await client.chat.completions.create({\n model: config.model,\n max_tokens: maxTokens,\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userMessage },\n ],\n ...(jsonMode ? { response_format: { type: \"json_object\" as const } } : {}),\n });\n const text = response.choices[0]?.message?.content;\n if (!text) {\n throw new Error(\"No text response from compiler LLM\");\n }\n return text;\n } catch (err) {\n throw new Error(classifyError(err, providerName));\n }\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { HarnessSnapshot } from './types.js';\n\n/**\n * Creates a baseline snapshot of the .claude/ directory.\n * Copies to both baseline/ and iterations/0/harness/ in the workspace.\n */\nexport async function snapshotBaseline(\n projectRoot: string,\n workspacePath: string,\n): Promise<void> {\n const claudeDir = path.join(projectRoot, '.claude');\n const baselineDir = path.join(workspacePath, 'baseline');\n const iter0Dir = path.join(workspacePath, 'iterations', '0', 'harness');\n\n try {\n await fs.access(claudeDir);\n } catch {\n throw new Error(`.claude/ directory not found in ${projectRoot}`);\n }\n\n await copyDir(claudeDir, baselineDir);\n await copyDir(claudeDir, iter0Dir);\n\n // Include .mcp.json in harness scope if it exists\n const mcpJsonPath = path.join(projectRoot, '.mcp.json');\n try {\n await fs.access(mcpJsonPath);\n await fs.copyFile(mcpJsonPath, path.join(baselineDir, '.mcp.json'));\n await fs.copyFile(mcpJsonPath, path.join(iter0Dir, '.mcp.json'));\n } catch {\n // .mcp.json doesn't exist — skip\n }\n}\n\n/**\n * Recursively copies a directory from src to dest.\n * Creates dest (and any missing parent directories) if it does not exist.\n */\nexport async function copyDir(src: string, dest: string): Promise<void> {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Loads a HarnessSnapshot from a harness directory path.\n * Verifies the directory exists before returning.\n */\nexport async function loadHarnessSnapshot(\n harnessDir: string,\n iteration: number,\n): Promise<HarnessSnapshot> {\n try {\n await fs.access(harnessDir);\n } catch {\n throw new Error(`Harness directory not found: ${harnessDir}`);\n }\n\n return { path: harnessDir, iteration };\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { Trace, Score, IterationLog, Proposal } from './types.js';\n\n/**\n * Load a trace from filesystem.\n * Parses tool_calls.jsonl (one JSON object per line) and extracts\n * the iteration number from the parent directory name.\n */\nexport async function loadTrace(traceDir: string): Promise<Trace> {\n const stdout = await fs.readFile(path.join(traceDir, 'stdout.log'), 'utf-8').catch(() => '');\n const stderr = await fs.readFile(path.join(traceDir, 'stderr.log'), 'utf-8').catch(() => '');\n const filesChangedStr = await fs.readFile(\n path.join(traceDir, 'files_changed.json'),\n 'utf-8',\n ).catch(() => '{}');\n const timingStr = await fs.readFile(\n path.join(traceDir, 'timing.json'),\n 'utf-8',\n ).catch(() => '{}');\n const scoreStr = await fs.readFile(\n path.join(traceDir, 'score.json'),\n 'utf-8',\n ).catch(() => '{\"pass\": false}');\n\n // Parse tool_calls.jsonl — one JSON object per line\n const toolCallsStr = await fs.readFile(\n path.join(traceDir, 'tool_calls.jsonl'),\n 'utf-8',\n ).catch(() => '');\n const toolCalls = toolCallsStr\n .split('\\n')\n .filter(line => line.trim())\n .map(line => JSON.parse(line) as unknown);\n\n // Extract iteration from parent directory name (traces/{iteration}/{taskId})\n const parentDir = path.basename(path.dirname(traceDir));\n const iteration = parseInt(parentDir, 10) || 0;\n\n return {\n taskId: path.basename(traceDir),\n iteration,\n stdout,\n stderr,\n toolCalls,\n filesChanged: JSON.parse(filesChangedStr) as Record<string, 'created' | 'modified' | 'deleted'>,\n score: JSON.parse(scoreStr) as Trace['score'],\n timing: JSON.parse(timingStr) as Trace['timing'],\n };\n}\n\n/**\n * Load all traces for an iteration.\n */\nexport async function loadIterationTraces(\n workspacePath: string,\n iteration: number,\n): Promise<Trace[]> {\n const tracesDir = path.join(workspacePath, 'traces', iteration.toString());\n const traces: Trace[] = [];\n\n try {\n const taskDirs = await fs.readdir(tracesDir);\n for (const taskId of taskDirs) {\n const trace = await loadTrace(path.join(tracesDir, taskId));\n traces.push(trace);\n }\n } catch {\n // Directory doesn't exist yet\n }\n\n return traces;\n}\n\n/**\n * Write all trace files to the given directory.\n * Writes stdout.log, stderr.log, tool_calls.jsonl, files_changed.json,\n * timing.json, and score.json.\n */\nexport async function writeTrace(traceDir: string, trace: Trace): Promise<void> {\n await fs.mkdir(traceDir, { recursive: true });\n await fs.writeFile(path.join(traceDir, 'stdout.log'), trace.stdout, 'utf-8');\n await fs.writeFile(path.join(traceDir, 'stderr.log'), trace.stderr, 'utf-8');\n\n // Write tool_calls.jsonl — one JSON object per line\n const toolCallsLines = trace.toolCalls\n .map(tc => JSON.stringify(tc))\n .join('\\n');\n await fs.writeFile(path.join(traceDir, 'tool_calls.jsonl'), toolCallsLines, 'utf-8');\n\n await fs.writeFile(\n path.join(traceDir, 'files_changed.json'),\n JSON.stringify(trace.filesChanged, null, 2),\n 'utf-8',\n );\n await fs.writeFile(\n path.join(traceDir, 'timing.json'),\n JSON.stringify(trace.timing, null, 2),\n 'utf-8',\n );\n await fs.writeFile(\n path.join(traceDir, 'score.json'),\n JSON.stringify(trace.score, null, 2),\n 'utf-8',\n );\n}\n\n/**\n * Write or overwrite only the score.json file in an existing trace directory.\n * Used to update the score after scoring runs separately from trace capture.\n */\nexport async function writeScore(traceDir: string, score: Score): Promise<void> {\n await fs.writeFile(\n path.join(traceDir, 'score.json'),\n JSON.stringify(score, null, 2),\n 'utf-8',\n );\n}\n\n/**\n * Check whether a trace directory has been populated.\n * Returns true if stdout.log exists inside traceDir.\n */\nexport async function traceExists(traceDir: string): Promise<boolean> {\n try {\n await fs.access(path.join(traceDir, 'stdout.log'));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Write iteration log files to .kairn-evolve/iterations/{N}/.\n * Creates: scores.json, proposer_reasoning.md, mutation_diff.patch\n */\nexport async function writeIterationLog(\n workspacePath: string,\n log: IterationLog,\n): Promise<void> {\n const iterDir = path.join(workspacePath, 'iterations', log.iteration.toString());\n await fs.mkdir(iterDir, { recursive: true });\n\n // Write scores\n await fs.writeFile(\n path.join(iterDir, 'scores.json'),\n JSON.stringify({ score: log.score, taskResults: log.taskResults }, null, 2),\n 'utf-8',\n );\n\n // Write proposer reasoning\n await fs.writeFile(\n path.join(iterDir, 'proposer_reasoning.md'),\n log.proposal?.reasoning ?? 'Baseline evaluation (no proposal)',\n 'utf-8',\n );\n\n // Write mutation diff\n await fs.writeFile(\n path.join(iterDir, 'mutation_diff.patch'),\n log.diffPatch ?? '',\n 'utf-8',\n );\n}\n\n/**\n * Load an iteration log from .kairn-evolve/iterations/{N}/.\n * Returns null if the iteration directory doesn't exist.\n */\nexport async function loadIterationLog(\n workspacePath: string,\n iteration: number,\n): Promise<IterationLog | null> {\n const iterDir = path.join(workspacePath, 'iterations', iteration.toString());\n\n try {\n await fs.access(iterDir);\n } catch {\n return null;\n }\n\n const scoresStr = await fs.readFile(path.join(iterDir, 'scores.json'), 'utf-8').catch(() => '{}');\n const reasoning = await fs.readFile(path.join(iterDir, 'proposer_reasoning.md'), 'utf-8').catch(() => '');\n const diffPatch = await fs.readFile(path.join(iterDir, 'mutation_diff.patch'), 'utf-8').catch(() => '');\n\n const scoresData = JSON.parse(scoresStr) as { score?: number; taskResults?: Record<string, Score> };\n\n const proposal: Proposal | null = reasoning\n ? { reasoning, mutations: [], expectedImpact: {} }\n : null;\n\n return {\n iteration,\n score: scoresData.score ?? 0,\n taskResults: scoresData.taskResults ?? {},\n proposal,\n diffPatch: diffPatch || null,\n timestamp: '',\n };\n}\n","import { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\n/**\n * Execute a shell command in a given directory with a timeout.\n * Returns `{ stdout, stderr }` on success; throws on non-zero exit.\n */\nexport async function execCommand(\n cmd: string,\n cwd: string,\n timeoutMs: number = 30_000,\n): Promise<{ stdout: string; stderr: string }> {\n return execAsync(cmd, { cwd, timeout: timeoutMs });\n}\n","import { execCommand } from './exec.js';\nimport { callLLM } from '../llm.js';\nimport type { KairnConfig } from '../types.js';\nimport type { Task, Score } from './types.js';\n\n/** Pattern to identify lines that look like shell commands. */\nconst COMMAND_PATTERN =\n /^(npm |npx |node |python |make |cargo |go |git |test |ls |cat |grep |curl )/;\n\n/** Shell metacharacters that could enable command injection. */\nconst SHELL_METACHAR_PATTERN = /[;|&`$()<>]/;\n\n/** System prompt for LLM-as-judge scoring. */\nexport const JUDGE_SYSTEM_PROMPT = `You are an eval judge for Claude Code agent tasks. Given a task description, expected outcome, and actual execution results, determine if the task was completed successfully.\n\nReturn ONLY valid JSON with this structure:\n{\n \"pass\": true/false,\n \"score\": 0-100,\n \"reasoning\": \"Brief explanation of your judgment\"\n}`;\n\n/** System prompt for rubric criterion scoring. */\nexport const RUBRIC_SYSTEM_PROMPT = `You are an eval judge scoring a specific criterion. Given the task, the criterion to evaluate, and the execution results, score the criterion.\n\nReturn ONLY valid JSON:\n{\n \"score\": 0.0-1.0,\n \"reasoning\": \"Brief explanation\"\n}`;\n\n// ── Deterministic criterion scoring heuristics ──\n\n/** Evidence keywords for \"Ran {command}\" pattern, keyed by command keyword. */\nconst RAN_COMMAND_EVIDENCE: Array<{ keywords: string[]; evidence: string[] }> = [\n { keywords: ['npm run build', 'build', 'tsup'], evidence: ['build success', 'tsup', 'built in', 'build completed'] },\n { keywords: ['tsc', 'typecheck'], evidence: ['tsc', 'typecheck'] },\n { keywords: ['npm run lint', 'eslint', 'lint'], evidence: ['lint', 'eslint'] },\n { keywords: ['npm test', 'vitest', 'test'], evidence: ['vitest', 'test files', 'tests passed', 'passed (', 'tests '] },\n];\n\n/** Patterns for \"Zero/No {pattern}\" — items to search for absence. */\nconst ABSENCE_PATTERNS: Array<{ keywords: string[]; search: string[] }> = [\n { keywords: ['.then()', '.catch()'], search: ['.then(', '.catch('] },\n { keywords: ['readfilesync', 'writefilesync'], search: ['readfilesync', 'writefilesync'] },\n { keywords: ['sync'], search: ['sync'] },\n];\n\n/** Patterns for \"Uses {pattern}\" — keyword in criterion text mapped to output search terms. */\nconst PRESENCE_PATTERNS: Array<{ keyword: string; search: string[] }> = [\n { keyword: 'chalk.green', search: ['chalk.green'] },\n { keyword: 'chalk.yellow', search: ['chalk.yellow'] },\n { keyword: 'chalk.red', search: ['chalk.red'] },\n { keyword: 'chalk.cyan', search: ['chalk.cyan'] },\n { keyword: 'fs.promises', search: ['fs.promises', 'fs/promises'] },\n { keyword: 'fs/promises', search: ['fs.promises', 'fs/promises'] },\n { keyword: 'async/await', search: ['async ', 'await '] },\n { keyword: '@inquirer/prompts', search: ['@inquirer/prompts'] },\n];\n\n/** Patterns for \"Calls {function}\" — items to search for presence. */\nconst CALL_PATTERNS: string[] = [\n 'process.exit(1)',\n 'process.exit',\n];\n\n/**\n * Attempt to score a rubric criterion deterministically using stdout/stderr\n * pattern matching. Returns null if the criterion cannot be scored this way\n * (falls back to LLM).\n */\nexport function scoreCriterionDeterministic(\n criterionText: string,\n stdout: string,\n stderr: string,\n): { score: number; reasoning: string } | null {\n const combined = `${stdout}\\n${stderr}`.toLowerCase();\n const criterionLower = criterionText.toLowerCase().trim();\n\n // Pattern 1: \"Ran {command}\" — check if command was executed\n if (/^ran\\b/i.test(criterionText.trim())) {\n for (const entry of RAN_COMMAND_EVIDENCE) {\n // Check if the criterion text mentions any of this entry's command keywords\n const matchesKeyword = entry.keywords.some((kw) =>\n criterionLower.includes(kw.toLowerCase()),\n );\n if (matchesKeyword) {\n const found = entry.evidence.some((ev) => combined.includes(ev.toLowerCase()));\n if (found) {\n const matchedEvidence = entry.evidence.find((ev) =>\n combined.includes(ev.toLowerCase()),\n );\n return {\n score: 1.0,\n reasoning: `Deterministic: found evidence of '${matchedEvidence}' in output`,\n };\n }\n return {\n score: 0.0,\n reasoning: `Deterministic: no evidence of '${entry.keywords[0]}' found`,\n };\n }\n }\n // \"Ran\" prefix matched but no known command pattern — fall through to null\n return null;\n }\n\n // Pattern 2: \"Zero/No {pattern}\" — check absence\n if (/^(zero|no)\\b/i.test(criterionText.trim())) {\n for (const entry of ABSENCE_PATTERNS) {\n const matchesKeyword = entry.keywords.some((kw) =>\n criterionLower.includes(kw.toLowerCase()),\n );\n if (matchesKeyword) {\n const found = entry.search.some((pat) => combined.includes(pat.toLowerCase()));\n if (found) {\n const matchedPattern = entry.search.find((pat) =>\n combined.includes(pat.toLowerCase()),\n );\n return {\n score: 0.0,\n reasoning: `Deterministic: found '${matchedPattern}' which should be absent`,\n };\n }\n return {\n score: 1.0,\n reasoning: `Deterministic: no prohibited pattern found in output`,\n };\n }\n }\n // \"Zero/No\" prefix matched but no known pattern — fall through to null\n return null;\n }\n\n // Pattern 3: \"Uses {specific pattern}\" — check presence\n if (/^uses?\\b/i.test(criterionText.trim())) {\n for (const entry of PRESENCE_PATTERNS) {\n if (criterionLower.includes(entry.keyword.toLowerCase())) {\n const found = entry.search.some((s) => combined.includes(s.toLowerCase()));\n if (found) {\n return {\n score: 1.0,\n reasoning: `Deterministic: found '${entry.keyword}' in output`,\n };\n }\n return {\n score: 0.0,\n reasoning: `Deterministic: '${entry.keyword}' not found in output`,\n };\n }\n }\n // \"Uses\" prefix matched but no known pattern — fall through to null\n return null;\n }\n\n // Pattern 4: \"Calls {function}\" — check presence\n if (/^calls?\\b/i.test(criterionText.trim())) {\n for (const pattern of CALL_PATTERNS) {\n if (criterionLower.includes(pattern.toLowerCase())) {\n const found = combined.includes(pattern.toLowerCase());\n if (found) {\n return {\n score: 1.0,\n reasoning: `Deterministic: found '${pattern}' in output`,\n };\n }\n return {\n score: 0.0,\n reasoning: `Deterministic: '${pattern}' not found in output`,\n };\n }\n }\n // \"Calls\" prefix matched but no known pattern — fall through to null\n return null;\n }\n\n // No pattern matched — fall back to LLM\n return null;\n}\n\n/**\n * Pass/fail scorer: execute verification commands from expected_outcome,\n * falling back to stderr analysis when no commands are found.\n */\nexport async function passFailScorer(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n): Promise<Score> {\n const outcomes = Array.isArray(task.expected_outcome)\n ? task.expected_outcome\n : task.expected_outcome.split('\\n');\n\n // Look for lines that look like shell commands\n const commands = outcomes\n .map((line) => line.replace(/^-\\s*/, '').trim())\n .filter((line) => COMMAND_PATTERN.test(line));\n\n if (commands.length > 0) {\n // Execute verification commands — reject commands with shell metacharacters\n // to prevent injection from LLM-generated expected_outcome strings\n const failures: string[] = [];\n for (const cmd of commands) {\n if (SHELL_METACHAR_PATTERN.test(cmd)) {\n failures.push(`Rejected unsafe command (shell metacharacters): ${cmd}`);\n continue;\n }\n try {\n await execCommand(cmd, workspacePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n failures.push(`Command failed: ${cmd}\\n${msg}`);\n }\n }\n\n const passed = failures.length === 0;\n return {\n pass: passed,\n score: passed ? 100 : 0,\n details: passed\n ? `All ${commands.length} verification commands passed`\n : failures.join('\\n'),\n };\n }\n\n // Fallback: check stderr for error indicators\n // Strip lines from setup (prefixed with [setup]) — these are not Claude's errors\n const filteredStderr = stderr\n .split('\\n')\n .filter(line => !line.startsWith('[setup]'))\n .join('\\n');\n const hasErrors =\n filteredStderr.toLowerCase().includes('error') ||\n filteredStderr.toLowerCase().includes('failed') ||\n filteredStderr.toLowerCase().includes('exception');\n const passed = !hasErrors;\n\n return {\n pass: passed,\n score: passed ? 100 : 0,\n details: passed ? 'No errors detected in output' : 'Errors found in stderr',\n };\n}\n\n/**\n * LLM-as-judge scorer: ask an LLM to evaluate whether the task outcome\n * matches the expected result.\n */\nexport async function llmJudgeScorer(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n config: KairnConfig,\n): Promise<Score> {\n const expectedOutcome = Array.isArray(task.expected_outcome)\n ? task.expected_outcome.join('\\n')\n : task.expected_outcome;\n\n const userMessage = [\n '## Task',\n task.description,\n '',\n '## Expected Outcome',\n expectedOutcome,\n '',\n '## Actual stdout (last 2000 chars)',\n stdout.slice(-2000),\n '',\n '## Actual stderr (last 1000 chars)',\n stderr.slice(-1000),\n ].join('\\n');\n\n try {\n const response = await callLLM(config, userMessage, {\n systemPrompt: JUDGE_SYSTEM_PROMPT,\n maxTokens: 1024,\n cacheControl: true,\n });\n\n // Parse JSON response, stripping markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```')) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '');\n }\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n return { pass: false, score: 0, reasoning: 'Judge returned invalid JSON' };\n }\n const result = JSON.parse(jsonMatch[0]) as {\n pass: boolean;\n score: number;\n reasoning: string;\n };\n return {\n pass: result.pass,\n score: result.score,\n reasoning: result.reasoning,\n };\n } catch (err) {\n return {\n pass: false,\n score: 0,\n reasoning: `LLM judge error: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n\n/**\n * Rubric scorer: evaluate multiple weighted criteria via LLM,\n * producing a weighted aggregate score.\n *\n * Falls back to passFailScorer when no rubric criteria are defined.\n */\nexport async function rubricScorer(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n config: KairnConfig,\n): Promise<Score> {\n if (!task.rubric || task.rubric.length === 0) {\n return passFailScorer(task, workspacePath, stdout, stderr);\n }\n\n const breakdown: Array<{ criterion: string; score: number; weight: number }> =\n [];\n let weightedSum = 0;\n\n for (const criterion of task.rubric) {\n // Try deterministic scoring first to avoid unnecessary LLM calls\n const deterministicResult = scoreCriterionDeterministic(\n criterion.criterion,\n stdout,\n stderr,\n );\n\n if (deterministicResult !== null) {\n breakdown.push({\n criterion: criterion.criterion,\n score: deterministicResult.score,\n weight: criterion.weight,\n });\n weightedSum += deterministicResult.score * criterion.weight;\n continue; // Skip LLM call\n }\n\n // Fall through to LLM scoring\n const userMessage = [\n '## Task',\n task.description,\n '',\n '## Criterion to Evaluate',\n `\"${criterion.criterion}\" (weight: ${criterion.weight})`,\n '',\n '## Actual stdout (last 2000 chars)',\n stdout.slice(-2000),\n '',\n '## Actual stderr (last 500 chars)',\n stderr.slice(-500),\n ].join('\\n');\n\n try {\n const response = await callLLM(config, userMessage, {\n systemPrompt: RUBRIC_SYSTEM_PROMPT,\n maxTokens: 512,\n cacheControl: true,\n });\n\n let cleaned = response.trim();\n if (cleaned.startsWith('```')) {\n cleaned = cleaned\n .replace(/^```(?:json)?\\n?/, '')\n .replace(/\\n?```$/, '');\n }\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n const result = JSON.parse(jsonMatch[0]) as {\n score: number;\n reasoning: string;\n };\n const clampedScore = Math.max(0, Math.min(1, result.score));\n breakdown.push({\n criterion: criterion.criterion,\n score: clampedScore,\n weight: criterion.weight,\n });\n weightedSum += clampedScore * criterion.weight;\n } else {\n breakdown.push({\n criterion: criterion.criterion,\n score: 0,\n weight: criterion.weight,\n });\n }\n } catch {\n breakdown.push({\n criterion: criterion.criterion,\n score: 0,\n weight: criterion.weight,\n });\n }\n }\n\n const totalWeight = task.rubric.reduce((sum, c) => sum + c.weight, 0);\n const totalScore = totalWeight > 0 ? Math.round((weightedSum / totalWeight) * 100) : 0;\n return {\n pass: totalScore >= 60,\n score: totalScore,\n reasoning: `Rubric score: ${totalScore}%`,\n breakdown,\n };\n}\n\n/**\n * Classify why a task failed based on trace data.\n * Only called for non-passing scores.\n */\nexport function classifyFailure(\n score: Score,\n stdout: string,\n stderr: string,\n): Score {\n if (score.pass) return score;\n\n const combined = `${stdout}\\n${stderr}`.toLowerCase();\n const scoreValue = score.score ?? 0;\n\n let failureCategory: Score['failureCategory'] = 'unknown';\n let failureReason = '';\n\n // Setup/task errors: task definition is broken or ambiguous\n if (\n stderr.includes('[setup]') && stderr.includes('Error') ||\n combined.includes('command not found') ||\n combined.includes('no such file or directory')\n ) {\n failureCategory = 'task';\n failureReason = 'Task setup failed or references missing resources';\n }\n // Model errors: API failures, token limits, context overflow\n else if (\n combined.includes('token limit') ||\n combined.includes('context length') ||\n combined.includes('rate limit') ||\n combined.includes('api error') ||\n combined.includes('429') ||\n combined.includes('overloaded')\n ) {\n failureCategory = 'model';\n failureReason = 'Model API error, token limit, or rate limit';\n }\n // Repo errors: pre-existing build failures, dirty state\n else if (\n combined.includes('build failed') && combined.includes('before') ||\n combined.includes('merge conflict') ||\n combined.includes('git dirty') ||\n combined.includes('uncommitted changes')\n ) {\n failureCategory = 'repo';\n failureReason = 'Pre-existing repo issues (build failure, dirty state)';\n }\n // Harness errors: agent tried but got it wrong (partial score)\n else if (scoreValue >= 20 && scoreValue < 80) {\n failureCategory = 'harness';\n failureReason = 'Agent attempted the task but did not follow harness conventions';\n }\n\n return { ...score, failureCategory, failureReason };\n}\n\nexport async function scoreTask(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n config?: KairnConfig,\n): Promise<Score> {\n let score: Score;\n if (task.scoring === 'pass-fail') {\n score = await passFailScorer(task, workspacePath, stdout, stderr);\n } else if (task.scoring === 'llm-judge' && config) {\n score = await llmJudgeScorer(task, workspacePath, stdout, stderr, config);\n } else if (task.scoring === 'rubric' && config) {\n score = await rubricScorer(task, workspacePath, stdout, stderr, config);\n } else {\n score = await passFailScorer(task, workspacePath, stdout, stderr);\n }\n\n if (!score.pass) {\n score = classifyFailure(score, stdout, stderr);\n }\n\n return score;\n}\n","import { exec, spawn } from 'child_process';\nimport { promisify } from 'util';\nimport fs from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport { writeTrace, writeScore } from './trace.js';\nimport { scoreTask } from './scorers.js';\nimport type { KairnConfig } from '../types.js';\nimport type { Task, TaskResult, Trace, Score, LoopProgressEvent } from './types.js';\n\nconst execAsync = promisify(exec);\n\n/** Directories to skip when copying the project directory as fallback. */\nconst COPY_SKIP_DIRS = new Set(['.git', 'node_modules', '.kairn-evolve', '.claude']);\n\n/**\n * Copy .mcp.json from the harness into the workspace root if present.\n */\nasync function deployMcpJson(harnessPath: string, workDir: string): Promise<void> {\n const src = path.join(harnessPath, '.mcp.json');\n await fs.copyFile(src, path.join(workDir, '.mcp.json')).catch(() => {});\n}\n\n/**\n * Create an isolated workspace with project files and a swapped harness.\n * Tries git worktree first for speed and proper isolation.\n * Falls back to copying the project directory if not in a git repo.\n */\nasync function createIsolatedWorkspace(\n projectRoot: string,\n harnessPath: string,\n): Promise<{ workDir: string; isWorktree: boolean }> {\n const suffix = `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n\n // Try git worktree first\n try {\n await execAsync('git rev-parse --is-inside-work-tree', {\n cwd: projectRoot,\n timeout: 5000,\n });\n const tmpDir = path.join(os.tmpdir(), `kairn-evolve-wt-${suffix}`);\n await execAsync(`git worktree add --detach \"${tmpDir}\" HEAD`, {\n cwd: projectRoot,\n timeout: 30_000,\n });\n // Replace .claude with iteration harness\n await fs.rm(path.join(tmpDir, '.claude'), { recursive: true, force: true });\n await copyDir(harnessPath, path.join(tmpDir, '.claude'));\n await deployMcpJson(harnessPath, tmpDir);\n return { workDir: tmpDir, isWorktree: true };\n } catch {\n // Not a git repo or worktree creation failed — fall back to copy\n }\n\n // Fallback: copy project directory (skip large/irrelevant dirs)\n const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), `kairn-evolve-cp-`));\n await copyProjectDir(projectRoot, tmpDir);\n await fs.rm(path.join(tmpDir, '.claude'), { recursive: true, force: true });\n await copyDir(harnessPath, path.join(tmpDir, '.claude'));\n await deployMcpJson(harnessPath, tmpDir);\n return { workDir: tmpDir, isWorktree: false };\n}\n\n/**\n * Copy project directory to dest, skipping .git, node_modules, .kairn-evolve, .claude.\n */\nasync function copyProjectDir(src: string, dest: string): Promise<void> {\n await fs.mkdir(dest, { recursive: true });\n let entries;\n try {\n entries = await fs.readdir(src, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (COPY_SKIP_DIRS.has(entry.name)) continue;\n\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Clean up an isolated workspace.\n */\nasync function cleanupIsolatedWorkspace(\n workDir: string,\n isWorktree: boolean,\n projectRoot: string,\n): Promise<void> {\n if (isWorktree) {\n try {\n await execAsync(`git worktree remove \"${workDir}\" --force`, {\n cwd: projectRoot,\n timeout: 10_000,\n });\n } catch {\n await fs.rm(workDir, { recursive: true, force: true }).catch(() => {});\n await execAsync('git worktree prune', {\n cwd: projectRoot,\n timeout: 5000,\n }).catch(() => {});\n }\n } else {\n await fs.rm(workDir, { recursive: true, force: true }).catch(() => {});\n }\n}\n\n/**\n * Run a single task against a harness in an isolated workspace.\n *\n * 1. Creates isolated workspace (git worktree or project copy)\n * 2. Swaps .claude/ with the iteration's harness\n * 3. Runs task.setup commands\n * 4. Spawns `claude` CLI with --print flag\n * 5. Captures stdout, stderr, files changed\n * 6. Writes all trace files\n * 7. Cleans up workspace\n *\n * @param projectRoot - Root directory of the project (contains package.json, src/, etc.)\n */\nexport async function runTask(\n task: Task,\n harnessPath: string,\n traceDir: string,\n iteration: number,\n projectRoot?: string,\n): Promise<TaskResult> {\n await fs.mkdir(traceDir, { recursive: true });\n const startedAt = new Date().toISOString();\n const startMs = Date.now();\n\n const root = projectRoot ?? process.cwd();\n const { workDir, isWorktree } = await createIsolatedWorkspace(root, harnessPath);\n\n try {\n // Run setup commands if any\n // Trust boundary: setup commands come from tasks.yaml which is user-reviewed\n // before execution. The user is the trust anchor for these commands.\n let setupStderr = '';\n if (task.setup.trim()) {\n try {\n await execAsync(task.setup, { cwd: workDir, timeout: 60_000 });\n } catch (err) {\n setupStderr =\n err instanceof Error ? err.message : String(err);\n }\n }\n\n // Snapshot file list before execution for diffing\n const filesBefore = await snapshotFileList(workDir);\n\n // Spawn claude CLI\n const spawnResult = await spawnClaude(task.description, workDir, task.timeout);\n\n // Diff files to detect changes\n const filesAfter = await snapshotFileList(workDir);\n const filesChanged = diffFileLists(filesBefore, filesAfter);\n\n // Parse tool calls from JSON output (if available)\n const toolCalls = parseToolCalls(spawnResult.stdout);\n\n const completedAt = new Date().toISOString();\n const durationMs = Date.now() - startMs;\n\n // Build trace\n const combinedStderr = setupStderr\n ? `[setup] ${setupStderr}\\n${spawnResult.stderr}`\n : spawnResult.stderr;\n\n const trace: Trace = {\n taskId: task.id,\n iteration,\n stdout: spawnResult.stdout,\n stderr: combinedStderr,\n toolCalls,\n filesChanged,\n score: { pass: false, details: 'Pending scoring' },\n timing: { startedAt, completedAt, durationMs },\n };\n\n // Write trace files\n await writeTrace(traceDir, trace);\n\n // Return result (scoring is done by the caller / CLI command)\n return {\n taskId: task.id,\n score: trace.score,\n traceDir,\n };\n } finally {\n await cleanupIsolatedWorkspace(workDir, isWorktree, root);\n }\n}\n\n/**\n * Spawn the claude CLI with --print flag and capture output.\n */\nexport async function spawnClaude(\n instruction: string,\n cwd: string,\n timeoutSec: number,\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n return new Promise((resolve) => {\n const args = ['--print', '--output-format', 'text', '--max-turns', '50', '--dangerously-skip-permissions'];\n const child = spawn('claude', args, {\n cwd,\n stdio: ['pipe', 'pipe', 'pipe'],\n timeout: timeoutSec * 1000,\n env: { ...process.env },\n });\n\n let stdout = '';\n let stderr = '';\n\n child.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n // Send the instruction via stdin\n child.stdin.write(instruction);\n child.stdin.end();\n\n child.on('close', (code) => {\n resolve({ stdout, stderr, exitCode: code ?? 1 });\n });\n\n child.on('error', (err) => {\n resolve({\n stdout,\n stderr: stderr + `\\nSpawn error: ${err.message}`,\n exitCode: 1,\n });\n });\n });\n}\n\n/**\n * Snapshot all file paths + mtimes in a directory recursively.\n * Used for before/after diffing to detect file changes.\n */\nexport async function snapshotFileList(\n dir: string,\n): Promise<Record<string, number>> {\n const result: Record<string, number> = {};\n\n async function walk(current: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = path.join(current, entry.name);\n const relativePath = path.relative(dir, fullPath);\n\n // Skip .claude directory (that's the harness, not task output)\n if (relativePath.startsWith('.claude')) continue;\n // Skip node_modules\n if (relativePath.startsWith('node_modules')) continue;\n // Skip .git\n if (relativePath.startsWith('.git')) continue;\n\n if (entry.isDirectory()) {\n await walk(fullPath);\n } else {\n try {\n const stat = await fs.stat(fullPath);\n result[relativePath] = stat.mtimeMs;\n } catch {\n // File might have been deleted between readdir and stat\n }\n }\n }\n }\n\n await walk(dir);\n return result;\n}\n\n/**\n * Compare before/after file snapshots to determine what changed.\n */\nexport function diffFileLists(\n before: Record<string, number>,\n after: Record<string, number>,\n): Record<string, 'created' | 'modified' | 'deleted'> {\n const changes: Record<string, 'created' | 'modified' | 'deleted'> = {};\n\n // Check for new and modified files\n for (const [file, mtime] of Object.entries(after)) {\n if (!(file in before)) {\n changes[file] = 'created';\n } else if (before[file] !== mtime) {\n changes[file] = 'modified';\n }\n }\n\n // Check for deleted files\n for (const file of Object.keys(before)) {\n if (!(file in after)) {\n changes[file] = 'deleted';\n }\n }\n\n return changes;\n}\n\n/**\n * Try to parse tool calls from claude output.\n * Looks for JSON lines containing tool_use type or tool_name field.\n * Falls back to empty array if output is plain text.\n */\nexport function parseToolCalls(stdout: string): unknown[] {\n try {\n const lines = stdout.split('\\n').filter((l) => l.trim());\n const toolCalls: unknown[] = [];\n for (const line of lines) {\n try {\n const obj = JSON.parse(line) as Record<string, unknown>;\n if (obj.type === 'tool_use' || obj.tool_name) {\n toolCalls.push(obj);\n }\n } catch {\n // Not JSON, skip\n }\n }\n return toolCalls;\n } catch {\n return [];\n }\n}\n\n/**\n * Run async tasks with a concurrency limit.\n * Returns results in the same order as the input tasks array.\n */\nexport async function runWithConcurrency<T>(\n tasks: (() => Promise<T>)[],\n limit: number,\n): Promise<T[]> {\n const results: T[] = new Array(tasks.length);\n const executing = new Set<Promise<void>>();\n const errors: unknown[] = [];\n const effectiveLimit = Math.max(1, limit);\n\n for (let i = 0; i < tasks.length; i++) {\n const p = tasks[i]().then(\n (result) => { results[i] = result; },\n (err) => { errors.push(err); },\n );\n const tracked = p.then(() => { executing.delete(tracked); });\n executing.add(tracked);\n if (executing.size >= effectiveLimit) {\n await Promise.race(executing);\n }\n }\n\n await Promise.all(executing);\n\n if (errors.length > 0) {\n throw errors[0];\n }\n\n return results;\n}\n\n/**\n * Compute population standard deviation for a list of numbers.\n *\n * Uses population stddev (divide by N) rather than sample stddev (divide by N-1).\n * For typical run counts (3-5), this slightly underestimates variance compared\n * to sample stddev, but is consistent with reporting the observed spread of\n * the actual runs performed rather than estimating the population parameter.\n */\nfunction computeStddev(values: number[], mean: number): number {\n if (values.length <= 1) return 0;\n const sumSqDiffs = values.reduce((sum, v) => sum + (v - mean) ** 2, 0);\n return Math.sqrt(sumSqDiffs / values.length);\n}\n\n/**\n * Run all tasks against a harness and return aggregated results.\n *\n * Each task is run sequentially via `runTask`, scored (optionally via\n * `scoreTask` when a `KairnConfig` is provided), and its score written\n * to the trace directory.\n *\n * The aggregate score is the arithmetic mean of all task scores.\n * For scores that have a numeric `score` field, that value is used directly.\n * For pass/fail scores without a numeric value, `pass=true` counts as 100\n * and `pass=false` counts as 0.\n */\nexport async function evaluateAll(\n tasks: Task[],\n harnessPath: string,\n workspacePath: string,\n iteration: number,\n config: KairnConfig | null,\n onProgress?: (event: LoopProgressEvent) => void,\n runsPerTask: number = 1,\n parallelTasks: number = 1,\n): Promise<{ results: Record<string, Score>; aggregate: number }> {\n const results: Record<string, Score> = {};\n const projectRoot = path.resolve(workspacePath, '..');\n const effectiveRuns = Math.max(1, runsPerTask);\n const concurrency = Math.max(1, parallelTasks);\n\n const evaluateTask = async (task: Task): Promise<{ id: string; score: Score }> => {\n onProgress?.({ type: 'task-start', iteration, taskId: task.id });\n\n let finalScore: Score;\n\n if (effectiveRuns > 1 && config) {\n const runScores: number[] = [];\n let passCount = 0;\n\n for (let run = 0; run < effectiveRuns; run++) {\n const traceDir = path.join(\n workspacePath,\n 'traces',\n iteration.toString(),\n `${task.id}_run${run}`,\n );\n\n onProgress?.({\n type: 'task-run',\n iteration,\n taskId: task.id,\n message: `Run ${run + 1}/${effectiveRuns} of ${task.id}`,\n });\n\n await runTask(task, harnessPath, traceDir, iteration, projectRoot);\n\n const stdout = await fs\n .readFile(path.join(traceDir, 'stdout.log'), 'utf-8')\n .catch(() => '');\n const stderr = await fs\n .readFile(path.join(traceDir, 'stderr.log'), 'utf-8')\n .catch(() => '');\n const score = await scoreTask(task, traceDir, stdout, stderr, config);\n await writeScore(traceDir, score);\n\n runScores.push(score.score ?? (score.pass ? 100 : 0));\n if (score.pass) passCount++;\n }\n\n const mean = runScores.reduce((a, b) => a + b, 0) / runScores.length;\n const stddev = computeStddev(runScores, mean);\n\n finalScore = {\n pass: passCount > effectiveRuns / 2,\n score: mean,\n details: `Mean of ${effectiveRuns} runs`,\n variance: {\n runs: effectiveRuns,\n scores: runScores,\n mean,\n stddev,\n },\n };\n } else {\n const traceDir = path.join(\n workspacePath,\n 'traces',\n iteration.toString(),\n task.id,\n );\n\n const taskResult = await runTask(task, harnessPath, traceDir, iteration, projectRoot);\n\n finalScore = taskResult.score;\n if (config) {\n const stdout = await fs\n .readFile(path.join(traceDir, 'stdout.log'), 'utf-8')\n .catch(() => '');\n const stderr = await fs\n .readFile(path.join(traceDir, 'stderr.log'), 'utf-8')\n .catch(() => '');\n finalScore = await scoreTask(task, traceDir, stdout, stderr, config);\n await writeScore(traceDir, finalScore);\n }\n }\n\n onProgress?.({\n type: 'task-scored',\n iteration,\n taskId: task.id,\n score: finalScore.score ?? (finalScore.pass ? 100 : 0),\n });\n\n return { id: task.id, score: finalScore };\n };\n\n const taskResults = await runWithConcurrency(\n tasks.map((task) => () => evaluateTask(task)),\n concurrency,\n );\n\n for (const { id, score } of taskResults) {\n results[id] = score;\n }\n\n const scores = Object.values(results);\n const total = scores.reduce(\n (sum, s) => sum + (s.score ?? (s.pass ? 100 : 0)),\n 0,\n );\n const aggregate = scores.length > 0 ? total / scores.length : 0;\n\n return { results, aggregate };\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { IterationLog } from './types.js';\n\nconst MEMORY_FILE = 'proposer-memory.json';\nconst MAX_ENTRIES = 10;\n\nexport interface RunSummary {\n timestamp: string;\n baselineScore: number;\n bestScore: number;\n improvement: number;\n effectiveMutations: string[];\n regressiveMutations: string[];\n insights: string;\n}\n\n/**\n * Load proposer memory from the workspace.\n * Returns empty array if no memory file exists.\n */\nexport async function loadProposerMemory(workspacePath: string): Promise<RunSummary[]> {\n const memoryPath = path.join(workspacePath, MEMORY_FILE);\n try {\n const raw = await fs.readFile(memoryPath, 'utf-8');\n const parsed = JSON.parse(raw) as unknown;\n if (Array.isArray(parsed)) return parsed as RunSummary[];\n return [];\n } catch {\n return [];\n }\n}\n\n/**\n * Build a run summary from iteration history.\n */\nexport function buildRunSummary(history: IterationLog[], baselineScore: number, bestScore: number): RunSummary {\n const effectiveMutations: string[] = [];\n const regressiveMutations: string[] = [];\n\n for (let i = 1; i < history.length; i++) {\n const prev = history[i - 1];\n const curr = history[i];\n if (!curr.proposal?.mutations.length) continue;\n\n const delta = curr.score - prev.score;\n const summary = curr.proposal.mutations\n .map(m => `${m.action} ${m.file}: ${m.rationale}`)\n .join('; ');\n\n if (delta > 0) {\n effectiveMutations.push(`+${delta.toFixed(1)}: ${summary}`);\n } else if (delta < -5) {\n regressiveMutations.push(`${delta.toFixed(1)}: ${summary}`);\n }\n }\n\n const improvement = bestScore - baselineScore;\n const insights = improvement > 0\n ? `Improved ${improvement.toFixed(1)} points. ${effectiveMutations.length} helpful mutations, ${regressiveMutations.length} regressions.`\n : `No improvement. ${regressiveMutations.length} regressions observed.`;\n\n return {\n timestamp: new Date().toISOString(),\n baselineScore,\n bestScore,\n improvement,\n effectiveMutations,\n regressiveMutations,\n insights,\n };\n}\n\n/**\n * Save a run summary to the workspace. Keeps last MAX_ENTRIES entries.\n */\nexport async function saveRunSummary(workspacePath: string, summary: RunSummary): Promise<void> {\n const existing = await loadProposerMemory(workspacePath);\n existing.push(summary);\n const trimmed = existing.slice(-MAX_ENTRIES);\n const memoryPath = path.join(workspacePath, MEMORY_FILE);\n await fs.writeFile(memoryPath, JSON.stringify(trimmed, null, 2), 'utf-8');\n}\n\n/**\n * Format proposer memory for inclusion in the proposer context.\n */\nexport function formatMemoryForProposer(memory: RunSummary[]): string {\n if (memory.length === 0) return '';\n\n const lines: string[] = ['## Prior Run History\\n'];\n for (const entry of memory) {\n lines.push(`### Run at ${entry.timestamp}`);\n lines.push(`- Baseline: ${entry.baselineScore.toFixed(1)}%, Best: ${entry.bestScore.toFixed(1)}%, Improvement: ${entry.improvement >= 0 ? '+' : ''}${entry.improvement.toFixed(1)}`);\n if (entry.effectiveMutations.length > 0) {\n lines.push('- Effective mutations:');\n for (const m of entry.effectiveMutations.slice(0, 3)) {\n lines.push(` - ${m}`);\n }\n }\n if (entry.regressiveMutations.length > 0) {\n lines.push('- Regressive mutations (AVOID these):');\n for (const m of entry.regressiveMutations.slice(0, 3)) {\n lines.push(` - ${m}`);\n }\n }\n lines.push('');\n }\n return lines.join('\\n');\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { callLLM } from '../llm.js';\nimport { loadIterationTraces } from './trace.js';\nimport type { Task, Trace, Proposal, Mutation, IterationLog } from './types.js';\nimport type { KairnConfig } from '../types.js';\n\nexport const PROPOSER_SYSTEM_PROMPT = `You are an expert agent environment optimizer. Your job is to improve a Claude Code\nagent environment (.claude/ directory) based on execution traces from real tasks.\n\n## What You Have Access To\n1. Current harness: The .claude/ directory files (CLAUDE.md, commands/, rules/, agents/)\n2. Execution traces: Full stdout/stderr, tool call sequences, file changes, and scores\n3. History: Previous iterations' proposals, diffs, and resulting score changes\n\n## Your Task\nAnalyze the traces to identify WHY tasks fail or underperform. Then propose specific,\nminimal changes to the harness files that will fix those failures.\n\n## Diagnosis Process\n1. For each failed/low-scoring task:\n a. Read the full trace (stdout, tool calls, file changes)\n b. Identify the ROOT CAUSE: bad instruction? Missing tool? Wrong rule?\n c. Trace the failure back to a specific harness decision\n d. Propose a fix\n\n2. For each successful task:\n a. Note what worked well\n b. Ensure proposed changes don't break what's working\n\n3. Check history for counterfactual evidence\n\n## Available Mutation Actions\n1. **replace** — Replace old_text with new_text in a file: { \"file\": \"...\", \"action\": \"replace\", \"old_text\": \"...\", \"new_text\": \"...\", \"rationale\": \"...\" }\n2. **add_section** — Append new content to a file (or create it): { \"file\": \"...\", \"action\": \"add_section\", \"new_text\": \"...\", \"rationale\": \"...\" }\n3. **create_file** — Create a new file: { \"file\": \"...\", \"action\": \"create_file\", \"new_text\": \"...\", \"rationale\": \"...\" }\n4. **delete_section** — Remove specific text from a file: { \"file\": \"...\", \"action\": \"delete_section\", \"old_text\": \"...\", \"rationale\": \"...\" }\n5. **delete_file** — Delete an entire file: { \"file\": \"...\", \"action\": \"delete_file\", \"rationale\": \"...\" }\n\n## Output Format\nReturn a JSON object:\n{\n \"reasoning\": \"Your full causal analysis...\",\n \"mutations\": [\n { \"file\": \"CLAUDE.md\", \"action\": \"replace\", \"old_text\": \"...\", \"new_text\": \"...\", \"rationale\": \"...\" },\n { \"file\": \"commands/develop.md\", \"action\": \"add_section\", \"new_text\": \"...\", \"rationale\": \"...\" },\n { \"file\": \"rules/obsolete.md\", \"action\": \"delete_file\", \"rationale\": \"...\" }\n ],\n \"expected_impact\": { \"task-id\": \"+15% — explanation\" }\n}\n\n## MCP Configuration\nYou can also mutate .mcp.json to add, remove, or reconfigure MCP servers.\nTreat .mcp.json like any other harness file — propose changes when traces show\nthe agent lacks a tool it needs, or has tools that add noise without benefit.\n\n## Rules\n- Propose AT MOST 3 mutations per iteration. Fewer, targeted mutations are more stable than many broad ones.\n- Each mutation must have a clear rationale tied to a specific trace observation.\n- Never remove something that's working for another task.\n- If a previous iteration's change caused a regression, REVERT it.\n- Consider both additions AND removals. Remove sections that add noise without improving task performance.\n- Bloated harnesses hurt performance — trim what isn't earning its keep.\n\n## Anti-Gaming (CRITICAL)\n- Mutations must improve GENERAL-PURPOSE development quality, not target specific eval criteria.\n- You do NOT have access to scoring rubrics or expected outcomes. Diagnose problems from traces only.\n- Do NOT add over-specified rules that restate existing conventions with stronger emphasis (e.g., changing \"use chalk.green for success\" to \"MUST use chalk.green, no exceptions\"). If a convention already exists, trust it.\n- Do NOT add rules that only apply to a narrow eval scenario (e.g., write permissions for a specific directory just because one task needed it).\n- Ask: \"Would this mutation help a developer working on ANY task in this project?\" If not, don't propose it.\n\nReturn ONLY valid JSON.`;\n\n/** Maximum characters of stdout to include per trace in the prompt. */\nconst STDOUT_TRUNCATION_LIMIT = 1000;\n\n/** Maximum total characters for the proposer user message. */\nconst MAX_CONTEXT_CHARS = 100_000;\n\n/**\n * Recursively read all files in a harness directory.\n *\n * Returns a record mapping relative file paths (e.g. \"commands/develop.md\")\n * to their string contents. Missing or unreadable directories return an\n * empty record.\n */\nexport async function readHarnessFiles(\n harnessPath: string,\n): Promise<Record<string, string>> {\n const result: Record<string, string> = {};\n\n async function walk(dir: string, prefix: string): Promise<void> {\n let entries: import('fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const relativePath = prefix ? path.join(prefix, entry.name) : entry.name;\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await walk(fullPath, relativePath);\n } else if (entry.isFile()) {\n try {\n result[relativePath] = await fs.readFile(fullPath, 'utf-8');\n } catch {\n // Skip unreadable files\n }\n }\n }\n }\n\n await walk(harnessPath, '');\n return result;\n}\n\nfunction truncateStdout(stdout: string, limit: number): string {\n if (stdout.length <= limit) {\n return stdout;\n }\n return `[...truncated, showing last ${limit} chars...]\\n${stdout.slice(-limit)}`;\n}\n\n/**\n * Build the user-facing prompt for the proposer LLM call.\n *\n * Assembles current harness file contents, trace summaries (with truncated\n * stdout), task definitions, and iteration history into a single string.\n */\nexport function buildProposerUserMessage(\n harnessFiles: Record<string, string>,\n traces: Trace[],\n tasks: Task[],\n history: IterationLog[],\n memorySection?: string,\n): string {\n // Priority-based context assembly: harness + tasks are never truncated,\n // traces and history are progressively reduced to fit within budget.\n\n // Section 1: Current harness files (highest priority — never truncated)\n const harnessSection: string[] = ['## Current Harness Files\\n'];\n const fileEntries = Object.entries(harnessFiles);\n if (fileEntries.length === 0) {\n harnessSection.push('(No harness files found)\\n');\n } else {\n for (const [filePath, content] of fileEntries) {\n harnessSection.push(`### ${filePath}\\n\\`\\`\\`\\n${content}\\n\\`\\`\\`\\n`);\n }\n }\n\n // Section 2: Task definitions (description only — rubrics and expected_outcome\n // are intentionally excluded to prevent the proposer from gaming eval criteria)\n const taskSection: string[] = ['## Task Definitions\\n'];\n if (tasks.length === 0) {\n taskSection.push('(No tasks defined)\\n');\n } else {\n for (const task of tasks) {\n taskSection.push(\n `### Task: ${task.id}\\n` +\n `- Template: ${task.template}\\n` +\n `- Description: ${task.description}\\n`,\n );\n }\n }\n\n const fixedContent = harnessSection.join('\\n') + '\\n' + taskSection.join('\\n');\n const remainingBudget = MAX_CONTEXT_CHARS - fixedContent.length;\n\n if (remainingBudget <= 0) {\n return fixedContent + '\\n\\n[...traces and history omitted — harness + tasks fill context budget...]';\n }\n\n // Section 3: Execution traces (medium priority — stdout truncated progressively)\n // Allocate 70% of remaining budget to traces, 30% to history\n const traceBudget = Math.floor(remainingBudget * 0.7);\n const historyBudget = remainingBudget - traceBudget;\n\n const traceSection = buildTraceSection(traces, traceBudget);\n const historySection = buildHistorySection(history, historyBudget);\n\n const memoryPart = memorySection ? '\\n' + memorySection : '';\n return fixedContent + '\\n' + traceSection + '\\n' + historySection + memoryPart;\n}\n\n/**\n * Build the trace section, fitting within the given character budget.\n * Progressively reduces per-trace stdout limit if the section exceeds budget.\n */\nfunction buildTraceSection(traces: Trace[], budget: number): string {\n if (traces.length === 0) return '## Execution Traces\\n\\n(No traces available)\\n';\n\n // Sort traces by score ascending (worst-first) so the proposer focuses on what's broken\n const sortedTraces = [...traces].sort((a, b) => {\n const scoreA = a.score.score ?? (a.score.pass ? 100 : 0);\n const scoreB = b.score.score ?? (b.score.pass ? 100 : 0);\n return scoreA - scoreB;\n });\n\n // Try with default limit, halve stdout limit until it fits\n let stdoutLimit = STDOUT_TRUNCATION_LIMIT;\n for (let attempt = 0; attempt < 4; attempt++) {\n const parts: string[] = ['## Execution Traces (sorted worst-first)\\n'];\n for (const trace of sortedTraces) {\n const scoreNum = trace.score.score !== undefined ? trace.score.score : (trace.score.pass ? 100 : 0);\n const truncatedStdout = truncateStdout(trace.stdout, stdoutLimit);\n const filesChangedList = Object.entries(trace.filesChanged)\n .map(([f, action]) => ` - ${f}: ${action}`)\n .join('\\n');\n\n parts.push(\n `### Trace: ${trace.taskId}\\n` +\n `- Pass: ${trace.score.pass}\\n` +\n `- Score: ${scoreNum}\\n` +\n (trace.score.details ? `- Details: ${trace.score.details}\\n` : '') +\n `- Duration: ${trace.timing.durationMs}ms\\n` +\n `- Files changed:\\n${filesChangedList || ' (none)'}\\n` +\n `- Stdout (last ${stdoutLimit} chars):\\n\\`\\`\\`\\n${truncatedStdout}\\n\\`\\`\\`\\n`,\n );\n }\n const result = parts.join('\\n');\n if (result.length <= budget) return result;\n stdoutLimit = Math.floor(stdoutLimit / 2);\n }\n\n // Final fallback: scores-only summary\n const summary = ['## Execution Traces (summary — stdout omitted to fit budget)\\n'];\n for (const trace of traces) {\n const scoreNum = trace.score.score !== undefined ? trace.score.score : (trace.score.pass ? 100 : 0);\n summary.push(`- ${trace.taskId}: ${scoreNum} (pass=${trace.score.pass})\\n`);\n }\n return summary.join('\\n');\n}\n\n/**\n * Build the history section, fitting within the given character budget.\n * Drops oldest iterations first if it exceeds budget.\n */\nfunction buildHistorySection(history: IterationLog[], budget: number): string {\n if (history.length === 0) return '## Iteration History\\n\\n(No previous iterations)\\n';\n\n // Try with full history, then drop oldest entries until it fits\n let entries = [...history];\n while (entries.length > 0) {\n const parts: string[] = ['## Iteration History\\n'];\n if (entries.length < history.length) {\n parts.push(`(Showing ${entries.length}/${history.length} most recent iterations)\\n`);\n }\n for (const log of entries) {\n const taskScores = Object.entries(log.taskResults)\n .map(([id, s]) => ` - ${id}: ${s.score !== undefined ? s.score : (s.pass ? 100 : 0)} (pass=${s.pass})`)\n .join('\\n');\n\n parts.push(\n `### Iteration ${log.iteration} — Score: ${log.score}\\n` +\n `- Task results:\\n${taskScores}\\n`,\n );\n\n if (log.proposal) {\n parts.push(\n `- Proposal reasoning: ${log.proposal.reasoning}\\n` +\n `- Mutations: ${log.proposal.mutations.length} change(s)\\n`,\n );\n }\n }\n const result = parts.join('\\n');\n if (result.length <= budget) return result;\n entries = entries.slice(1); // drop oldest\n }\n\n return '## Iteration History\\n\\n(History omitted to fit context budget)\\n';\n}\n\n/**\n * Parse a raw LLM response string into a validated Proposal.\n *\n * Strips markdown code fences, extracts JSON, maps snake_case keys\n * (old_text, new_text, expected_impact) to camelCase, and filters out\n * any mutations with path traversal in the file field.\n *\n * @throws Error if the response is not valid JSON or lacks required fields.\n */\nexport function parseProposerResponse(raw: string): Proposal {\n let cleaned = raw.trim();\n\n // Strip markdown code fences (```json ... ``` or ``` ... ```)\n const fenceMatch = cleaned.match(/^```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```$/);\n if (fenceMatch) {\n cleaned = fenceMatch[1].trim();\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(cleaned);\n } catch {\n // Fallback: extract JSON object from prose-wrapped text (first '{' to last '}')\n const firstBrace = cleaned.indexOf('{');\n const lastBrace = cleaned.lastIndexOf('}');\n if (firstBrace !== -1 && lastBrace > firstBrace) {\n const extracted = cleaned.slice(firstBrace, lastBrace + 1);\n try {\n parsed = JSON.parse(extracted);\n } catch {\n throw new Error(`Proposer returned invalid JSON: ${cleaned.slice(0, 200)}`);\n }\n } else {\n throw new Error(`Proposer returned invalid JSON: ${cleaned.slice(0, 200)}`);\n }\n }\n\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('Proposer response is not a JSON object');\n }\n\n const obj = parsed as Record<string, unknown>;\n\n if (typeof obj['reasoning'] !== 'string') {\n throw new Error('Proposer response missing required \"reasoning\" string field');\n }\n\n if (!Array.isArray(obj['mutations'])) {\n throw new Error('Proposer response missing required \"mutations\" array field');\n }\n\n const mutations: Mutation[] = [];\n for (const entry of obj['mutations'] as unknown[]) {\n if (typeof entry !== 'object' || entry === null) {\n continue;\n }\n const m = entry as Record<string, unknown>;\n\n const file = typeof m['file'] === 'string' ? m['file'] : '';\n const action = typeof m['action'] === 'string' ? m['action'] : '';\n const newText = typeof m['new_text'] === 'string'\n ? m['new_text']\n : (typeof m['newText'] === 'string' ? m['newText'] : '');\n const oldText = typeof m['old_text'] === 'string'\n ? m['old_text']\n : (typeof m['oldText'] === 'string' ? m['oldText'] : undefined);\n const rationale = typeof m['rationale'] === 'string' ? m['rationale'] : '';\n\n // Security: reject path traversal\n if (file.includes('..')) {\n continue;\n }\n\n const validActions = new Set(['replace', 'add_section', 'create_file', 'delete_section', 'delete_file']);\n if (!validActions.has(action)) {\n continue;\n }\n\n // For replace and delete_section actions, oldText is required\n if ((action === 'replace' || action === 'delete_section') && !oldText) {\n continue;\n }\n\n const mutation: Mutation = {\n file,\n action: action as Mutation['action'],\n newText,\n rationale,\n };\n\n if (oldText !== undefined) {\n mutation.oldText = oldText;\n }\n\n mutations.push(mutation);\n }\n\n // Parse expectedImpact (accept both snake_case and camelCase)\n const rawImpact = obj['expected_impact'] ?? obj['expectedImpact'] ?? {};\n const expectedImpact: Record<string, string> = {};\n if (typeof rawImpact === 'object' && rawImpact !== null) {\n for (const [key, value] of Object.entries(rawImpact as Record<string, unknown>)) {\n expectedImpact[key] = typeof value === 'string' ? value : String(value);\n }\n }\n\n return {\n reasoning: obj['reasoning'] as string,\n mutations,\n expectedImpact,\n };\n}\n\n/**\n * Run the proposer agent: read harness, load traces, call LLM, return a Proposal.\n *\n * The proposer analyzes execution traces from the current iteration, diagnoses\n * root causes of failures, and proposes minimal mutations to the harness files.\n *\n * @param iteration - Current iteration number\n * @param workspacePath - Path to the .kairn-evolve workspace\n * @param harnessPath - Path to the current harness (.claude/) directory\n * @param history - Logs from previous iterations\n * @param tasks - Task definitions being evaluated\n * @param config - Kairn configuration (for LLM access)\n * @param proposerModel - Model ID to use for the proposer call\n * @returns A validated Proposal with reasoning, mutations, and expected impact\n */\nexport async function propose(\n iteration: number,\n workspacePath: string,\n harnessPath: string,\n history: IterationLog[],\n tasks: Task[],\n config: KairnConfig,\n proposerModel: string,\n): Promise<Proposal> {\n const harnessFiles = await readHarnessFiles(harnessPath);\n const traces = await loadIterationTraces(workspacePath, iteration);\n const { loadProposerMemory, formatMemoryForProposer } = await import('./memory.js');\n const memory = await loadProposerMemory(workspacePath);\n const memorySection = formatMemoryForProposer(memory);\n const userMessage = buildProposerUserMessage(harnessFiles, traces, tasks, history, memorySection);\n\n // Override model with proposer-specific model\n const proposerConfig: KairnConfig = { ...config, model: proposerModel };\n const response = await callLLM(proposerConfig, userMessage, {\n systemPrompt: PROPOSER_SYSTEM_PROMPT,\n maxTokens: 8192,\n jsonMode: true,\n cacheControl: true,\n });\n\n return parseProposerResponse(response);\n}\n","/**\n * Harness IR — Structured intermediate representation for .claude/ directories.\n *\n * This module defines every node type that the parser emits and the emitter consumes.\n * Types are intentionally simple value objects with no behaviour.\n */\n\n// ---------------------------------------------------------------------------\n// Meta\n// ---------------------------------------------------------------------------\n\n/** Top-level metadata extracted from the CLAUDE.md preamble and tech-stack section. */\nexport interface HarnessMeta {\n name: string;\n purpose: string;\n techStack: {\n language: string;\n framework?: string;\n buildTool?: string;\n testRunner?: string;\n packageManager?: string;\n };\n autonomyLevel: 1 | 2 | 3 | 4;\n}\n\n// ---------------------------------------------------------------------------\n// Content nodes\n// ---------------------------------------------------------------------------\n\n/** A heading-delimited section inside CLAUDE.md. */\nexport interface Section {\n id: string;\n heading: string;\n content: string;\n order: number;\n}\n\n/** A file under `.claude/commands/`. */\nexport interface CommandNode {\n name: string;\n description: string;\n content: string;\n}\n\n/** A file under `.claude/rules/` — may carry YAML frontmatter with `paths`. */\nexport interface RuleNode {\n name: string;\n paths?: string[];\n content: string;\n}\n\n/** A file under `.claude/agents/` — may carry YAML frontmatter with `model` / `disallowedTools`. */\nexport interface AgentNode {\n name: string;\n model?: string;\n disallowedTools?: string[];\n modelRouting?: {\n default: 'haiku' | 'sonnet' | 'opus';\n escalateTo?: 'sonnet' | 'opus';\n escalateWhen?: string;\n };\n extraFrontmatter?: Record<string, unknown>; // preserve all other YAML frontmatter fields\n content: string;\n}\n\n/** A file under `.claude/skills/`. */\nexport interface SkillNode {\n name: string;\n content: string;\n}\n\n/** A file under `.claude/docs/`. */\nexport interface DocNode {\n name: string;\n content: string;\n}\n\n/** A file under `.claude/hooks/` (ESM `.mjs`). */\nexport interface HookNode {\n name: string;\n content: string;\n type: \"command\" | \"prompt\";\n}\n\n// ---------------------------------------------------------------------------\n// Settings\n// ---------------------------------------------------------------------------\n\n/** A single hook entry inside `settings.json` hooks map. */\nexport interface HookEntry {\n matcher: string;\n hooks: Array<{\n type: \"command\" | \"prompt\";\n command?: string;\n prompt?: string;\n timeout?: number;\n }>;\n}\n\n/** Parsed representation of `settings.json`. */\nexport interface SettingsIR {\n statusLine?: { command: string };\n hooks: {\n PreToolUse?: HookEntry[];\n PostToolUse?: HookEntry[];\n UserPromptSubmit?: HookEntry[];\n SessionStart?: HookEntry[];\n PostCompact?: HookEntry[];\n };\n denyPatterns?: string[];\n raw: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// MCP\n// ---------------------------------------------------------------------------\n\n/** An MCP server declaration from `.mcp.json`. */\nexport interface McpServerNode {\n id: string;\n command: string;\n args: string[];\n env?: Record<string, string>;\n}\n\n// ---------------------------------------------------------------------------\n// Intent\n// ---------------------------------------------------------------------------\n\n/** Maps natural-language patterns to slash-commands for intent routing. */\nexport interface IntentNode {\n commandName: string;\n patterns: string[];\n priority: number;\n}\n\n// ---------------------------------------------------------------------------\n// Root IR\n// ---------------------------------------------------------------------------\n\n/** The complete intermediate representation of a `.claude/` harness directory. */\nexport interface HarnessIR {\n meta: HarnessMeta;\n sections: Section[];\n commands: CommandNode[];\n rules: RuleNode[];\n agents: AgentNode[];\n skills: SkillNode[];\n docs: DocNode[];\n hooks: HookNode[];\n settings: SettingsIR;\n mcpServers: McpServerNode[];\n intents: IntentNode[];\n}\n\n// ---------------------------------------------------------------------------\n// Factory helpers\n// ---------------------------------------------------------------------------\n\n/** Create a HarnessIR with all fields set to safe defaults. */\nexport function createEmptyIR(): HarnessIR {\n return {\n meta: {\n name: \"\",\n purpose: \"\",\n techStack: { language: \"\" },\n autonomyLevel: 2,\n },\n sections: [],\n commands: [],\n rules: [],\n agents: [],\n skills: [],\n docs: [],\n hooks: [],\n settings: createEmptySettings(),\n mcpServers: [],\n intents: [],\n };\n}\n\n/** Create a SettingsIR with all fields set to safe defaults. */\nexport function createEmptySettings(): SettingsIR {\n return { hooks: {}, raw: {} };\n}\n\n/** Convenience factory for Section nodes. */\nexport function createSection(\n id: string,\n heading: string,\n content: string,\n order: number,\n): Section {\n return { id, heading, content, order };\n}\n\n/** Convenience factory for CommandNode with an optional description (defaults to empty string). */\nexport function createCommandNode(\n name: string,\n content: string,\n description?: string,\n): CommandNode {\n return { name, description: description ?? \"\", content };\n}\n\n/** Convenience factory for RuleNode with optional path scoping. */\nexport function createRuleNode(\n name: string,\n content: string,\n paths?: string[],\n): RuleNode {\n const node: RuleNode = { name, content };\n if (paths !== undefined) {\n node.paths = paths;\n }\n return node;\n}\n\n/** Convenience factory for AgentNode with optional model hint. */\nexport function createAgentNode(\n name: string,\n content: string,\n model?: string,\n): AgentNode {\n const node: AgentNode = { name, content };\n if (model !== undefined) {\n node.model = model;\n }\n return node;\n}\n\n// ---------------------------------------------------------------------------\n// Mutation types\n// ---------------------------------------------------------------------------\n\n/** Discriminated union of all possible IR mutations. */\nexport type IRMutation =\n | { type: \"update_section\"; sectionId: string; content: string; rationale: string }\n | { type: \"add_section\"; section: Section; rationale: string }\n | { type: \"remove_section\"; sectionId: string; rationale: string }\n | { type: \"reorder_section\"; sectionId: string; newOrder: number; rationale: string }\n | { type: \"add_command\"; command: CommandNode; rationale: string }\n | { type: \"update_command\"; name: string; content: string; rationale: string }\n | { type: \"remove_command\"; name: string; rationale: string }\n | { type: \"add_rule\"; rule: RuleNode; rationale: string }\n | { type: \"update_rule\"; name: string; content: string; rationale: string }\n | { type: \"remove_rule\"; name: string; rationale: string }\n | { type: \"add_agent\"; agent: AgentNode; rationale: string }\n | { type: \"update_agent\"; name: string; changes: Partial<AgentNode>; rationale: string }\n | { type: \"remove_agent\"; name: string; rationale: string }\n | { type: \"add_mcp_server\"; server: McpServerNode; rationale: string }\n | { type: \"remove_mcp_server\"; id: string; rationale: string }\n | { type: \"update_settings\"; path: string; value: unknown; rationale: string }\n | {\n type: \"raw_text\";\n file: string;\n action: \"replace\" | \"add_section\" | \"create_file\" | \"delete_section\" | \"delete_file\";\n oldText?: string;\n newText: string;\n rationale: string;\n };\n\n// ---------------------------------------------------------------------------\n// Diff types\n// ---------------------------------------------------------------------------\n\n/** Structural diff between two HarnessIR snapshots. */\nexport interface IRDiff {\n sections: {\n added: Section[];\n removed: Section[];\n modified: Array<{ id: string; before: string; after: string }>;\n reordered: Array<{ id: string; oldOrder: number; newOrder: number }>;\n };\n commands: {\n added: CommandNode[];\n removed: string[];\n modified: Array<{ name: string; before: string; after: string }>;\n };\n rules: {\n added: RuleNode[];\n removed: string[];\n modified: Array<{ name: string; before: string; after: string }>;\n };\n agents: {\n added: AgentNode[];\n removed: string[];\n modified: Array<{ name: string; changes: string }>;\n };\n mcpServers: {\n added: McpServerNode[];\n removed: string[];\n };\n settings: {\n changes: Array<{ path: string; before: unknown; after: unknown }>;\n };\n}\n\n/** Create an empty IRDiff with all collections empty. */\nexport function createEmptyDiff(): IRDiff {\n return {\n sections: {\n added: [],\n removed: [],\n modified: [],\n reordered: [],\n },\n commands: {\n added: [],\n removed: [],\n modified: [],\n },\n rules: {\n added: [],\n removed: [],\n modified: [],\n },\n agents: {\n added: [],\n removed: [],\n modified: [],\n },\n mcpServers: {\n added: [],\n removed: [],\n },\n settings: {\n changes: [],\n },\n };\n}\n","/**\n * Harness Parser — reads a `.claude/` directory and produces a HarnessIR.\n *\n * All file I/O uses `fs.promises`. Missing directories/files are handled\n * gracefully (empty arrays, empty strings) rather than throwing.\n */\n\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type {\n HarnessIR,\n HarnessMeta,\n Section,\n CommandNode,\n RuleNode,\n AgentNode,\n SkillNode,\n DocNode,\n HookNode,\n McpServerNode,\n SettingsIR,\n HookEntry,\n} from \"./types.js\";\nimport { createEmptyIR, createEmptySettings } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Section ID mapping\n// ---------------------------------------------------------------------------\n\n/** Maps heading keywords to well-known section IDs. */\nconst SECTION_ID_MAP: Array<{ pattern: RegExp; id: string }> = [\n { pattern: /^(purpose|about|what)\\b/i, id: \"purpose\" },\n { pattern: /^(tech\\s*stack|technology|stack)\\b/i, id: \"tech-stack\" },\n { pattern: /^(commands|key\\s*commands)\\b/i, id: \"commands\" },\n { pattern: /^architecture\\b/i, id: \"architecture\" },\n { pattern: /^conventions?\\b/i, id: \"conventions\" },\n { pattern: /^verification\\b/i, id: \"verification\" },\n { pattern: /^(known\\s*gotchas|gotchas)\\b/i, id: \"gotchas\" },\n { pattern: /^output\\b/i, id: \"output\" },\n { pattern: /^debugging\\b/i, id: \"debugging\" },\n { pattern: /^git\\b/i, id: \"git\" },\n];\n\n/**\n * Slugify a heading into a CSS-style ID: lowercase, spaces to hyphens,\n * strip anything that isn't alphanumeric or hyphen.\n */\nfunction slugify(heading: string): string {\n return heading\n .toLowerCase()\n .trim()\n .replace(/\\s+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n/** Resolve a heading string to a well-known section ID or a custom-* slug. */\nexport function resolveSectionId(heading: string): string {\n const trimmed = heading.trim();\n for (const entry of SECTION_ID_MAP) {\n if (entry.pattern.test(trimmed)) {\n return entry.id;\n }\n }\n return `custom-${slugify(trimmed)}`;\n}\n\n// ---------------------------------------------------------------------------\n// parseYamlFrontmatter\n// ---------------------------------------------------------------------------\n\n/**\n * Extract simple YAML frontmatter delimited by `---` lines.\n *\n * Handles:\n * - `key: value` pairs (string values)\n * - `key:` followed by indented ` - item` list items (arrays)\n * - Quoted values have their quotes stripped\n *\n * Does **not** depend on an external YAML library.\n */\nexport function parseYamlFrontmatter(content: string): {\n frontmatter: Record<string, unknown>;\n body: string;\n} {\n if (!content.startsWith(\"---\\n\") && !content.startsWith(\"---\\r\\n\")) {\n return { frontmatter: {}, body: content };\n }\n\n // Find the closing ---\n const secondDash = content.indexOf(\"\\n---\", 3);\n if (secondDash === -1) {\n return { frontmatter: {}, body: content };\n }\n\n const yamlBlock = content.slice(4, secondDash); // skip opening \"---\\n\"\n const afterClose = secondDash + 4; // skip \"\\n---\"\n const body = content.slice(afterClose).replace(/^\\r?\\n/, \"\");\n\n const frontmatter: Record<string, unknown> = {};\n const lines = yamlBlock.split(\"\\n\");\n\n let currentKey: string | null = null;\n let currentList: string[] | null = null;\n\n for (const line of lines) {\n const trimmed = line.trimEnd();\n\n // List item under the current key\n if (currentKey !== null && /^\\s+-\\s+/.test(trimmed)) {\n if (currentList === null) {\n currentList = [];\n }\n let value = trimmed.replace(/^\\s+-\\s+/, \"\").trim();\n // Strip surrounding quotes\n value = stripQuotes(value);\n currentList.push(value);\n continue;\n }\n\n // Flush any pending list\n if (currentKey !== null && currentList !== null) {\n frontmatter[currentKey] = currentList;\n currentKey = null;\n currentList = null;\n }\n\n // key: value pair\n const colonIdx = trimmed.indexOf(\":\");\n if (colonIdx > 0) {\n const key = trimmed.slice(0, colonIdx).trim();\n const rawValue = trimmed.slice(colonIdx + 1).trim();\n\n if (rawValue === \"\") {\n // Could be the start of a list\n currentKey = key;\n currentList = null;\n } else {\n frontmatter[key] = stripQuotes(rawValue);\n currentKey = null;\n currentList = null;\n }\n }\n }\n\n // Flush final pending list\n if (currentKey !== null && currentList !== null) {\n frontmatter[currentKey] = currentList;\n }\n\n return { frontmatter, body };\n}\n\n/** Remove surrounding single or double quotes from a string value. */\nfunction stripQuotes(value: string): string {\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n return value.slice(1, -1);\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// parseClaudeMd\n// ---------------------------------------------------------------------------\n\n/**\n * Parse the content of a CLAUDE.md file into partial metadata and sections.\n *\n * Splits on `## ` boundaries. The chunk before the first `## ` becomes the\n * preamble section. Each subsequent chunk is assigned a well-known or custom\n * section ID based on its heading text.\n */\nexport function parseClaudeMd(content: string): {\n meta: Partial<HarnessMeta>;\n sections: Section[];\n} {\n const meta: Partial<HarnessMeta> = {\n techStack: { language: \"\" },\n autonomyLevel: 2,\n };\n const sections: Section[] = [];\n\n // Split on ## boundaries (keeping the delimiter for all but the first chunk)\n const chunks = content.split(/^## /gm);\n\n // First chunk is the preamble (everything before the first ## )\n const preamble = chunks[0];\n\n // Extract name from `# Title` line\n const titleMatch = preamble.match(/^# (.+)$/m);\n if (titleMatch) {\n meta.name = titleMatch[1].trim();\n } else {\n meta.name = \"\";\n }\n\n // Build preamble section\n const preambleHeading = meta.name ? `# ${meta.name}` : \"\";\n // Content is everything after the title line (if any)\n const preambleContent = titleMatch\n ? preamble.slice(preamble.indexOf(titleMatch[0]) + titleMatch[0].length).trim()\n : preamble.trim();\n\n sections.push({\n id: \"preamble\",\n heading: preambleHeading,\n content: preambleContent,\n order: 0,\n });\n\n // Process each ## section\n for (let i = 1; i < chunks.length; i++) {\n const chunk = chunks[i];\n const newlineIdx = chunk.indexOf(\"\\n\");\n const heading =\n newlineIdx >= 0 ? chunk.slice(0, newlineIdx).trim() : chunk.trim();\n const sectionContent =\n newlineIdx >= 0 ? chunk.slice(newlineIdx + 1).trim() : \"\";\n\n const sectionId = resolveSectionId(heading);\n\n sections.push({\n id: sectionId,\n heading: `## ${heading}`,\n content: sectionContent,\n order: i,\n });\n\n // Extract purpose from purpose section (first paragraph only)\n if (sectionId === \"purpose\") {\n const firstParagraph = sectionContent.split(/\\n\\n/)[0].trim();\n meta.purpose = firstParagraph;\n }\n\n // Extract tech stack from tech-stack section\n if (sectionId === \"tech-stack\") {\n meta.techStack = extractTechStack(sectionContent);\n }\n }\n\n return { meta, sections };\n}\n\n/**\n * Extract technology details from bullet-point content in a Tech Stack section.\n */\nfunction extractTechStack(content: string): HarnessMeta[\"techStack\"] {\n const stack: HarnessMeta[\"techStack\"] = { language: \"\" };\n const lines = content.split(\"\\n\");\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"-\")) continue;\n const bullet = trimmed.slice(1).trim().toLowerCase();\n\n // Language detection\n if (\n !stack.language &&\n (bullet.includes(\"typescript\") || bullet.includes(\"javascript\"))\n ) {\n stack.language = bullet.includes(\"typescript\")\n ? \"TypeScript\"\n : \"JavaScript\";\n } else if (!stack.language && bullet.includes(\"python\")) {\n stack.language = \"Python\";\n } else if (!stack.language && bullet.includes(\"rust\")) {\n stack.language = \"Rust\";\n } else if (!stack.language && bullet.includes(\"go \") || !stack.language && bullet.startsWith(\"go,\")) {\n stack.language = \"Go\";\n }\n\n // Build tool detection\n if (!stack.buildTool) {\n const buildTools = [\n \"tsup\", \"webpack\", \"vite\", \"esbuild\", \"rollup\", \"parcel\",\n \"turbopack\", \"swc\", \"cargo\", \"make\", \"cmake\",\n ];\n for (const tool of buildTools) {\n if (bullet.includes(tool)) {\n stack.buildTool = tool;\n break;\n }\n }\n }\n\n // Test runner detection\n if (!stack.testRunner) {\n const testRunners = [\n \"vitest\", \"jest\", \"mocha\", \"ava\", \"tap\", \"pytest\", \"cargo test\",\n ];\n for (const runner of testRunners) {\n if (bullet.includes(runner)) {\n stack.testRunner = runner;\n break;\n }\n }\n }\n\n // Framework detection\n if (!stack.framework) {\n const frameworks = [\n \"commander.js\", \"commander\", \"express\", \"fastify\", \"next.js\",\n \"nextjs\", \"react\", \"vue\", \"angular\", \"svelte\", \"django\", \"flask\",\n \"actix\", \"axum\",\n ];\n for (const fw of frameworks) {\n if (bullet.includes(fw)) {\n // Normalize: \"commander.js\" → \"Commander.js\"\n stack.framework =\n fw.charAt(0).toUpperCase() + fw.slice(1);\n break;\n }\n }\n }\n\n // Package manager detection\n if (!stack.packageManager) {\n const pkgManagers = [\"pnpm\", \"yarn\", \"bun\", \"npm\", \"cargo\", \"pip\"];\n for (const pm of pkgManagers) {\n if (bullet.includes(`${pm} `)) {\n stack.packageManager = pm;\n break;\n }\n }\n }\n }\n\n return stack;\n}\n\n// ---------------------------------------------------------------------------\n// parseSettings\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a `settings.json` string into a SettingsIR.\n *\n * Extracts:\n * - `permissions.deny` → `denyPatterns`\n * - `hooks.*` → typed hook entries\n * - `statusLine` → status line config\n * - Everything else → `raw`\n */\nexport function parseSettings(content: string): SettingsIR {\n const parsed = JSON.parse(content) as Record<string, unknown>;\n const settings = createEmptySettings();\n\n // Extract deny patterns\n const permissions = parsed[\"permissions\"] as\n | Record<string, unknown>\n | undefined;\n if (permissions) {\n const deny = permissions[\"deny\"];\n if (Array.isArray(deny) && deny.length > 0) {\n settings.denyPatterns = deny as string[];\n }\n }\n\n // Extract status line\n const statusLine = parsed[\"statusLine\"] as\n | { command: string }\n | undefined;\n if (statusLine && typeof statusLine.command === \"string\") {\n settings.statusLine = { command: statusLine.command };\n }\n\n // Extract hooks\n const hooksRaw = parsed[\"hooks\"] as Record<string, unknown> | undefined;\n if (hooksRaw && typeof hooksRaw === \"object\") {\n const knownEvents = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"UserPromptSubmit\",\n \"SessionStart\",\n \"PostCompact\",\n ] as const;\n\n for (const event of knownEvents) {\n const entries = hooksRaw[event];\n if (Array.isArray(entries) && entries.length > 0) {\n settings.hooks[event] = entries as HookEntry[];\n }\n }\n }\n\n // Put everything into raw (excluding already-extracted top-level keys)\n const extractedKeys = new Set([\"permissions\", \"hooks\", \"statusLine\"]);\n for (const [key, value] of Object.entries(parsed)) {\n if (!extractedKeys.has(key)) {\n settings.raw[key] = value;\n }\n }\n\n return settings;\n}\n\n// ---------------------------------------------------------------------------\n// parseMcpConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a `.mcp.json` string into an array of McpServerNode.\n *\n * Each key in the `mcpServers` object becomes a node with `id` = key.\n */\nexport function parseMcpConfig(content: string): McpServerNode[] {\n const parsed = JSON.parse(content) as Record<string, unknown>;\n const servers = parsed[\"mcpServers\"] as\n | Record<string, Record<string, unknown>>\n | undefined;\n\n if (!servers || typeof servers !== \"object\") {\n return [];\n }\n\n const nodes: McpServerNode[] = [];\n\n for (const [id, config] of Object.entries(servers)) {\n const command = config[\"command\"] as string;\n const args = (config[\"args\"] as string[]) ?? [];\n const env = config[\"env\"] as Record<string, string> | undefined;\n\n const node: McpServerNode = { id, command, args };\n\n // Only include env if it's a non-empty object\n if (env && typeof env === \"object\" && Object.keys(env).length > 0) {\n node.env = env;\n }\n\n nodes.push(node);\n }\n\n return nodes;\n}\n\n// ---------------------------------------------------------------------------\n// Directory reading helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Safely read a directory, returning an empty array if it doesn't exist.\n */\nasync function readDirSafe(dirPath: string): Promise<string[]> {\n try {\n return await fs.readdir(dirPath);\n } catch {\n return [];\n }\n}\n\n/**\n * Safely read a file, returning null if it doesn't exist.\n */\nasync function readFileSafe(filePath: string): Promise<string | null> {\n try {\n return await fs.readFile(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\n/**\n * Safely check whether a path is a directory.\n */\nasync function isDirectory(filePath: string): Promise<boolean> {\n try {\n const stat = await fs.stat(filePath);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Sub-parsers for harness subdirectories\n// ---------------------------------------------------------------------------\n\n/** Read `commands/*.md` files into CommandNode[]. */\nasync function parseCommands(harnessPath: string): Promise<CommandNode[]> {\n const dirPath = path.join(harnessPath, \"commands\");\n const entries = await readDirSafe(dirPath);\n const nodes: CommandNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const content = await readFileSafe(filePath);\n if (content === null) continue;\n\n const name = entry.replace(/\\.md$/, \"\");\n const firstLine = content.split(\"\\n\")[0].trim();\n // Use first line as description if it's not a heading or code block\n const description =\n firstLine && !firstLine.startsWith(\"#\") && !firstLine.startsWith(\"```\")\n ? firstLine\n : \"\";\n\n nodes.push({ name, description, content });\n }\n\n return nodes;\n}\n\n/** Read `rules/*.md` files into RuleNode[], parsing YAML frontmatter for `paths`. */\nasync function parseRules(harnessPath: string): Promise<RuleNode[]> {\n const dirPath = path.join(harnessPath, \"rules\");\n const entries = await readDirSafe(dirPath);\n const nodes: RuleNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const rawContent = await readFileSafe(filePath);\n if (rawContent === null) continue;\n\n const name = entry.replace(/\\.md$/, \"\");\n const { frontmatter, body } = parseYamlFrontmatter(rawContent);\n\n const node: RuleNode = { name, content: body };\n\n const paths = frontmatter[\"paths\"];\n if (Array.isArray(paths) && paths.length > 0) {\n node.paths = paths as string[];\n }\n\n nodes.push(node);\n }\n\n return nodes;\n}\n\n/** Read `agents/*.md` files into AgentNode[], parsing YAML frontmatter for `model` and `disallowedTools`. */\nasync function parseAgents(harnessPath: string): Promise<AgentNode[]> {\n const dirPath = path.join(harnessPath, \"agents\");\n const entries = await readDirSafe(dirPath);\n const nodes: AgentNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const rawContent = await readFileSafe(filePath);\n if (rawContent === null) continue;\n\n const fileBaseName = entry.replace(/\\.md$/, \"\");\n const { frontmatter, body } = parseYamlFrontmatter(rawContent);\n\n // Use frontmatter name if present, otherwise file name\n const name =\n typeof frontmatter[\"name\"] === \"string\"\n ? frontmatter[\"name\"]\n : fileBaseName;\n\n const node: AgentNode = { name, content: body };\n\n if (typeof frontmatter[\"model\"] === \"string\") {\n node.model = frontmatter[\"model\"];\n }\n\n const disallowedTools = frontmatter[\"disallowedTools\"];\n if (Array.isArray(disallowedTools)) {\n node.disallowedTools = disallowedTools as string[];\n }\n\n // Parse modelRouting if present\n const modelRouting = frontmatter[\"modelRouting\"];\n if (typeof modelRouting === \"object\" && modelRouting !== null) {\n const mr = modelRouting as Record<string, unknown>;\n if (typeof mr[\"default\"] === \"string\") {\n node.modelRouting = {\n default: mr[\"default\"] as 'haiku' | 'sonnet' | 'opus',\n };\n if (typeof mr[\"escalateTo\"] === \"string\") {\n node.modelRouting.escalateTo = mr[\"escalateTo\"] as 'sonnet' | 'opus';\n }\n if (typeof mr[\"escalateWhen\"] === \"string\") {\n node.modelRouting.escalateWhen = mr[\"escalateWhen\"];\n }\n }\n }\n\n // Preserve all other frontmatter fields not already handled\n const knownKeys = new Set([\"name\", \"model\", \"disallowedTools\", \"modelRouting\"]);\n const extra: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(frontmatter)) {\n if (!knownKeys.has(key)) {\n extra[key] = value;\n }\n }\n if (Object.keys(extra).length > 0) {\n node.extraFrontmatter = extra;\n }\n\n nodes.push(node);\n }\n\n return nodes;\n}\n\n/**\n * Read `skills/` directory into SkillNode[].\n *\n * Skills can be either:\n * - A direct `.md` file: `skills/tdd.md`\n * - A directory with a `skill.md` inside: `skills/tdd/skill.md`\n */\nasync function parseSkills(harnessPath: string): Promise<SkillNode[]> {\n const dirPath = path.join(harnessPath, \"skills\");\n const entries = await readDirSafe(dirPath);\n const nodes: SkillNode[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry);\n\n if (entry.endsWith(\".md\")) {\n // Direct file\n const content = await readFileSafe(entryPath);\n if (content === null) continue;\n const name = entry.replace(/\\.md$/, \"\");\n nodes.push({ name, content });\n } else if (await isDirectory(entryPath)) {\n // Directory — look for skill.md or SKILL.md inside (case-insensitive)\n let content = await readFileSafe(path.join(entryPath, \"skill.md\"));\n if (content === null) {\n content = await readFileSafe(path.join(entryPath, \"SKILL.md\"));\n }\n if (content === null) continue;\n nodes.push({ name: entry, content });\n }\n }\n\n return nodes;\n}\n\n/** Read `docs/*.md` files into DocNode[]. */\nasync function parseDocs(harnessPath: string): Promise<DocNode[]> {\n const dirPath = path.join(harnessPath, \"docs\");\n const entries = await readDirSafe(dirPath);\n const nodes: DocNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const content = await readFileSafe(filePath);\n if (content === null) continue;\n\n const name = entry.replace(/\\.md$/, \"\");\n nodes.push({ name, content });\n }\n\n return nodes;\n}\n\n/** Read `hooks/*.mjs` files into HookNode[]. */\nasync function parseHooks(harnessPath: string): Promise<HookNode[]> {\n const dirPath = path.join(harnessPath, \"hooks\");\n const entries = await readDirSafe(dirPath);\n const nodes: HookNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".mjs\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const content = await readFileSafe(filePath);\n if (content === null) continue;\n\n const name = entry.replace(/\\.mjs$/, \"\");\n nodes.push({ name, content, type: \"command\" });\n }\n\n return nodes;\n}\n\n// ---------------------------------------------------------------------------\n// parseHarness — main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Read an entire `.claude/` directory (or compatible harness directory) and\n * produce a complete HarnessIR.\n *\n * Missing files/directories are handled gracefully — the resulting IR simply\n * has empty arrays/strings for the missing parts.\n *\n * @param harnessPath - Absolute path to the `.claude/` directory.\n */\nexport async function parseHarness(harnessPath: string): Promise<HarnessIR> {\n const ir = createEmptyIR();\n\n // 1. Parse CLAUDE.md\n const claudeMdContent = await readFileSafe(\n path.join(harnessPath, \"CLAUDE.md\"),\n );\n if (claudeMdContent !== null) {\n const { meta, sections } = parseClaudeMd(claudeMdContent);\n ir.meta = {\n ...ir.meta,\n ...meta,\n techStack: { ...ir.meta.techStack, ...meta.techStack },\n };\n ir.sections = sections;\n }\n\n // 2. Parse settings.json\n const settingsContent = await readFileSafe(\n path.join(harnessPath, \"settings.json\"),\n );\n if (settingsContent !== null) {\n ir.settings = parseSettings(settingsContent);\n }\n\n // 3. Parse subdirectories in parallel\n const [commands, rules, agents, skills, docs, hooks] = await Promise.all([\n parseCommands(harnessPath),\n parseRules(harnessPath),\n parseAgents(harnessPath),\n parseSkills(harnessPath),\n parseDocs(harnessPath),\n parseHooks(harnessPath),\n ]);\n\n ir.commands = commands;\n ir.rules = rules;\n ir.agents = agents;\n ir.skills = skills;\n ir.docs = docs;\n ir.hooks = hooks;\n\n // 4. Parse .mcp.json — check both parent directory and harness directory itself\n const mcpServers: McpServerNode[] = [];\n const seenIds = new Set<string>();\n\n // Check parent directory (standard location: project root has .mcp.json, .claude/ is the harness)\n const parentMcpPath = path.join(path.dirname(harnessPath), \".mcp.json\");\n const parentMcpContent = await readFileSafe(parentMcpPath);\n if (parentMcpContent !== null) {\n for (const node of parseMcpConfig(parentMcpContent)) {\n if (!seenIds.has(node.id)) {\n seenIds.add(node.id);\n mcpServers.push(node);\n }\n }\n }\n\n // Check inside the harness directory itself (evolution may copy it here)\n const innerMcpPath = path.join(harnessPath, \".mcp.json\");\n const innerMcpContent = await readFileSafe(innerMcpPath);\n if (innerMcpContent !== null) {\n for (const node of parseMcpConfig(innerMcpContent)) {\n if (!seenIds.has(node.id)) {\n seenIds.add(node.id);\n mcpServers.push(node);\n }\n }\n }\n\n ir.mcpServers = mcpServers;\n\n return ir;\n}\n","/**\n * Legacy Mutation Translator — converts evolve-era `Mutation` objects into\n * structured `IRMutation` values that the IR mutation engine can apply.\n *\n * This bridge allows the existing proposer (which emits file-level text mutations)\n * to target the structured IR without rewriting the proposer prompt.\n */\n\nimport type { HarnessIR, IRMutation } from \"./types.js\";\nimport type { Mutation } from \"../evolve/types.js\";\nimport {\n createSection,\n createCommandNode,\n createRuleNode,\n createAgentNode,\n} from \"./types.js\";\nimport { resolveSectionId } from \"./parser.js\";\n\n// ---------------------------------------------------------------------------\n// Path matching helpers\n// ---------------------------------------------------------------------------\n\n/** Regex for paths targeting command files: `commands/X.md` or `commands/X`. */\nconst COMMANDS_PATH_RE = /^commands\\/([^/]+?)(?:\\.md)?$/;\n\n/** Regex for paths targeting rule files: `rules/X.md` or `rules/X`. */\nconst RULES_PATH_RE = /^rules\\/([^/]+?)(?:\\.md)?$/;\n\n/** Regex for paths targeting agent files: `agents/X.md` or `agents/X`. */\nconst AGENTS_PATH_RE = /^agents\\/([^/]+?)(?:\\.md)?$/;\n\n/**\n * Extract a name from a file path using the given regex.\n * Returns the first capture group (the bare file name) or `null` if no match.\n */\nfunction extractName(filePath: string, pattern: RegExp): string | null {\n const match = filePath.match(pattern);\n return match ? match[1] : null;\n}\n\n// ---------------------------------------------------------------------------\n// Section search helper\n// ---------------------------------------------------------------------------\n\n/**\n * Find the first section whose `content` includes the given text.\n * Returns the section or `undefined` if not found.\n */\nfunction findSectionContaining(\n ir: HarnessIR,\n text: string,\n): HarnessIR[\"sections\"][number] | undefined {\n return ir.sections.find((s) => s.content.includes(text));\n}\n\n// ---------------------------------------------------------------------------\n// CLAUDE.md translation\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a mutation targeting `CLAUDE.md` into a structured IR mutation.\n */\nfunction translateClaudeMdMutation(\n mutation: Mutation,\n ir: HarnessIR,\n): IRMutation {\n switch (mutation.action) {\n case \"replace\": {\n if (mutation.oldText === undefined) {\n return buildRawText(mutation);\n }\n const section = findSectionContaining(ir, mutation.oldText);\n if (!section) {\n return buildRawText(mutation);\n }\n return {\n type: \"update_section\",\n sectionId: section.id,\n content: section.content.replace(mutation.oldText, mutation.newText),\n rationale: mutation.rationale,\n };\n }\n\n case \"add_section\": {\n const headingMatch = mutation.newText.match(/^## (.+)/);\n if (!headingMatch) {\n return buildRawText(mutation);\n }\n const headingText = headingMatch[1].trim();\n const sectionId = resolveSectionId(headingText);\n const heading = `## ${headingText}`;\n\n // Content is everything after the heading line\n const newlineIdx = mutation.newText.indexOf(\"\\n\");\n const content =\n newlineIdx >= 0 ? mutation.newText.slice(newlineIdx + 1).trim() : \"\";\n\n const nextOrder = ir.sections.length;\n\n return {\n type: \"add_section\",\n section: createSection(sectionId, heading, content, nextOrder),\n rationale: mutation.rationale,\n };\n }\n\n case \"delete_section\": {\n if (mutation.oldText === undefined) {\n return buildRawText(mutation);\n }\n const section = findSectionContaining(ir, mutation.oldText);\n if (!section) {\n return buildRawText(mutation);\n }\n return {\n type: \"remove_section\",\n sectionId: section.id,\n rationale: mutation.rationale,\n };\n }\n\n default:\n return buildRawText(mutation);\n }\n}\n\n// ---------------------------------------------------------------------------\n// commands/ translation\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a mutation targeting a `commands/*.md` file into a structured IR mutation.\n */\nfunction translateCommandMutation(\n mutation: Mutation,\n name: string,\n): IRMutation {\n switch (mutation.action) {\n case \"create_file\":\n return {\n type: \"add_command\",\n command: createCommandNode(name, mutation.newText),\n rationale: mutation.rationale,\n };\n\n case \"delete_file\":\n return {\n type: \"remove_command\",\n name,\n rationale: mutation.rationale,\n };\n\n case \"replace\":\n return {\n type: \"update_command\",\n name,\n content: mutation.newText,\n rationale: mutation.rationale,\n };\n\n default:\n return buildRawText(mutation);\n }\n}\n\n// ---------------------------------------------------------------------------\n// rules/ translation\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a mutation targeting a `rules/*.md` file into a structured IR mutation.\n */\nfunction translateRuleMutation(\n mutation: Mutation,\n name: string,\n): IRMutation {\n switch (mutation.action) {\n case \"create_file\":\n return {\n type: \"add_rule\",\n rule: createRuleNode(name, mutation.newText),\n rationale: mutation.rationale,\n };\n\n case \"delete_file\":\n return {\n type: \"remove_rule\",\n name,\n rationale: mutation.rationale,\n };\n\n case \"replace\":\n return {\n type: \"update_rule\",\n name,\n content: mutation.newText,\n rationale: mutation.rationale,\n };\n\n default:\n return buildRawText(mutation);\n }\n}\n\n// ---------------------------------------------------------------------------\n// agents/ translation\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a mutation targeting an `agents/*.md` file into a structured IR mutation.\n */\nfunction translateAgentMutation(\n mutation: Mutation,\n name: string,\n): IRMutation {\n switch (mutation.action) {\n case \"create_file\":\n return {\n type: \"add_agent\",\n agent: createAgentNode(name, mutation.newText),\n rationale: mutation.rationale,\n };\n\n case \"delete_file\":\n return {\n type: \"remove_agent\",\n name,\n rationale: mutation.rationale,\n };\n\n case \"replace\":\n return {\n type: \"update_agent\",\n name,\n changes: { content: mutation.newText },\n rationale: mutation.rationale,\n };\n\n default:\n return buildRawText(mutation);\n }\n}\n\n// ---------------------------------------------------------------------------\n// raw_text fallback builder\n// ---------------------------------------------------------------------------\n\n/** Build a `raw_text` IRMutation from a legacy Mutation (passthrough). */\nfunction buildRawText(mutation: Mutation): IRMutation {\n return {\n type: \"raw_text\",\n file: mutation.file,\n action: mutation.action,\n oldText: mutation.oldText,\n newText: mutation.newText,\n rationale: mutation.rationale,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a single legacy `Mutation` (file-level text operation) into a\n * structured `IRMutation` by inspecting the file path and action.\n *\n * The IR is used to look up which section contains text being replaced.\n *\n * @param mutation - A legacy evolve-era Mutation.\n * @param ir - The current HarnessIR state (used for section lookups).\n * @returns The equivalent structured IRMutation.\n */\nexport function translateMutation(mutation: Mutation, ir: HarnessIR): IRMutation {\n // CLAUDE.md mutations\n if (mutation.file === \"CLAUDE.md\") {\n return translateClaudeMdMutation(mutation, ir);\n }\n\n // commands/*.md mutations\n const commandName = extractName(mutation.file, COMMANDS_PATH_RE);\n if (commandName !== null) {\n return translateCommandMutation(mutation, commandName);\n }\n\n // rules/*.md mutations\n const ruleName = extractName(mutation.file, RULES_PATH_RE);\n if (ruleName !== null) {\n return translateRuleMutation(mutation, ruleName);\n }\n\n // agents/*.md mutations\n const agentName = extractName(mutation.file, AGENTS_PATH_RE);\n if (agentName !== null) {\n return translateAgentMutation(mutation, agentName);\n }\n\n // Fallback: anything else becomes a raw_text passthrough\n return buildRawText(mutation);\n}\n\n/**\n * Translate an array of legacy `Mutation` values into structured `IRMutation` values.\n *\n * @param mutations - Array of legacy Mutations.\n * @param ir - The current HarnessIR state.\n * @returns Array of equivalent IRMutations, in the same order.\n */\nexport function translateMutations(mutations: Mutation[], ir: HarnessIR): IRMutation[] {\n return mutations.map((m) => translateMutation(m, ir));\n}\n","/**\n * IR Mutation Engine — Immutable transformations on HarnessIR.\n *\n * Every `applyIRMutation` call returns a **new** HarnessIR; the input is never mutated.\n * `validateIRMutation` checks pre-conditions without side-effects.\n */\n\nimport type {\n HarnessIR,\n IRMutation,\n SettingsIR,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Validation result\n// ---------------------------------------------------------------------------\n\n/** Result of a pre-condition check on a mutation. */\nexport interface ValidationResult {\n valid: boolean;\n reason?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Internal lookup helpers\n// ---------------------------------------------------------------------------\n\nfunction sectionExists(ir: HarnessIR, id: string): boolean {\n return ir.sections.some((s) => s.id === id);\n}\n\nfunction commandExists(ir: HarnessIR, name: string): boolean {\n return ir.commands.some((c) => c.name === name);\n}\n\nfunction ruleExists(ir: HarnessIR, name: string): boolean {\n return ir.rules.some((r) => r.name === name);\n}\n\nfunction agentExists(ir: HarnessIR, name: string): boolean {\n return ir.agents.some((a) => a.name === name);\n}\n\nfunction mcpServerExists(ir: HarnessIR, id: string): boolean {\n return ir.mcpServers.some((s) => s.id === id);\n}\n\n// ---------------------------------------------------------------------------\n// Deep-set helper for settings paths\n// ---------------------------------------------------------------------------\n\n/** Known top-level keys in SettingsIR that map to structured fields. */\nconst STRUCTURED_SETTINGS_KEYS = new Set([\"statusLine\", \"hooks\", \"denyPatterns\"]);\n\n/**\n * Immutably deep-set a dotted path on an object, returning a new object tree.\n *\n * Example: `deepSet({}, \"a.b.c\", 42)` => `{ a: { b: { c: 42 } } }`\n */\nfunction deepSet(\n obj: Record<string, unknown>,\n segments: string[],\n value: unknown,\n): Record<string, unknown> {\n if (segments.length === 0) return obj;\n\n const [head, ...rest] = segments;\n\n if (rest.length === 0) {\n return { ...obj, [head]: value };\n }\n\n const existing = obj[head];\n const child =\n existing !== null && typeof existing === \"object\" && !Array.isArray(existing)\n ? (existing as Record<string, unknown>)\n : {};\n\n return { ...obj, [head]: deepSet(child, rest, value) };\n}\n\n/**\n * Apply a dotted-path setting update to SettingsIR immutably.\n *\n * If the top-level key maps to a structured field (statusLine, hooks, denyPatterns),\n * we set it directly on the SettingsIR. Otherwise, we store it in `settings.raw`.\n */\nfunction applySettingsUpdate(\n settings: SettingsIR,\n path: string,\n value: unknown,\n): SettingsIR {\n const segments = path.split(\".\");\n const topKey = segments[0];\n\n if (STRUCTURED_SETTINGS_KEYS.has(topKey)) {\n // Deep-set into the structured settings object\n const settingsRecord = { ...settings } as unknown as Record<string, unknown>;\n const updated = deepSet(settingsRecord, segments, value);\n return {\n ...settings,\n ...updated,\n // Preserve raw as-is (deepSet may have overwritten it if path happened to be \"raw\")\n raw: settings.raw,\n } as SettingsIR;\n }\n\n // Unrecognized key — store in raw\n const updatedRaw = deepSet({ ...settings.raw }, segments, value);\n return {\n ...settings,\n raw: updatedRaw,\n };\n}\n\n// ---------------------------------------------------------------------------\n// applyIRMutation\n// ---------------------------------------------------------------------------\n\n/**\n * Apply a single mutation to a HarnessIR, returning a new immutable IR.\n *\n * Throws if a pre-condition is violated (e.g., updating a section that doesn't exist).\n */\nexport function applyIRMutation(ir: HarnessIR, mutation: IRMutation): HarnessIR {\n switch (mutation.type) {\n // -- Sections ----------------------------------------------------------\n\n case \"update_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n throw new Error(`Section '${mutation.sectionId}' not found`);\n }\n return {\n ...ir,\n sections: ir.sections.map((s) =>\n s.id === mutation.sectionId ? { ...s, content: mutation.content } : s,\n ),\n };\n }\n\n case \"add_section\": {\n if (sectionExists(ir, mutation.section.id)) {\n throw new Error(`Section '${mutation.section.id}' already exists`);\n }\n return {\n ...ir,\n sections: [...ir.sections, { ...mutation.section }],\n };\n }\n\n case \"remove_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n throw new Error(`Section '${mutation.sectionId}' not found`);\n }\n return {\n ...ir,\n sections: ir.sections.filter((s) => s.id !== mutation.sectionId),\n };\n }\n\n case \"reorder_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n throw new Error(`Section '${mutation.sectionId}' not found`);\n }\n return {\n ...ir,\n sections: ir.sections.map((s) =>\n s.id === mutation.sectionId ? { ...s, order: mutation.newOrder } : s,\n ),\n };\n }\n\n // -- Commands ----------------------------------------------------------\n\n case \"add_command\": {\n if (commandExists(ir, mutation.command.name)) {\n throw new Error(`Command '${mutation.command.name}' already exists`);\n }\n return {\n ...ir,\n commands: [...ir.commands, { ...mutation.command }],\n };\n }\n\n case \"update_command\": {\n if (!commandExists(ir, mutation.name)) {\n throw new Error(`Command '${mutation.name}' not found`);\n }\n return {\n ...ir,\n commands: ir.commands.map((c) =>\n c.name === mutation.name ? { ...c, content: mutation.content } : c,\n ),\n };\n }\n\n case \"remove_command\": {\n if (!commandExists(ir, mutation.name)) {\n throw new Error(`Command '${mutation.name}' not found`);\n }\n return {\n ...ir,\n commands: ir.commands.filter((c) => c.name !== mutation.name),\n };\n }\n\n // -- Rules -------------------------------------------------------------\n\n case \"add_rule\": {\n if (ruleExists(ir, mutation.rule.name)) {\n throw new Error(`Rule '${mutation.rule.name}' already exists`);\n }\n return {\n ...ir,\n rules: [...ir.rules, { ...mutation.rule }],\n };\n }\n\n case \"update_rule\": {\n if (!ruleExists(ir, mutation.name)) {\n throw new Error(`Rule '${mutation.name}' not found`);\n }\n return {\n ...ir,\n rules: ir.rules.map((r) =>\n r.name === mutation.name ? { ...r, content: mutation.content } : r,\n ),\n };\n }\n\n case \"remove_rule\": {\n if (!ruleExists(ir, mutation.name)) {\n throw new Error(`Rule '${mutation.name}' not found`);\n }\n return {\n ...ir,\n rules: ir.rules.filter((r) => r.name !== mutation.name),\n };\n }\n\n // -- Agents ------------------------------------------------------------\n\n case \"add_agent\": {\n if (agentExists(ir, mutation.agent.name)) {\n throw new Error(`Agent '${mutation.agent.name}' already exists`);\n }\n return {\n ...ir,\n agents: [...ir.agents, { ...mutation.agent }],\n };\n }\n\n case \"update_agent\": {\n if (!agentExists(ir, mutation.name)) {\n throw new Error(`Agent '${mutation.name}' not found`);\n }\n return {\n ...ir,\n agents: ir.agents.map((a) =>\n a.name === mutation.name ? { ...a, ...mutation.changes } : a,\n ),\n };\n }\n\n case \"remove_agent\": {\n if (!agentExists(ir, mutation.name)) {\n throw new Error(`Agent '${mutation.name}' not found`);\n }\n return {\n ...ir,\n agents: ir.agents.filter((a) => a.name !== mutation.name),\n };\n }\n\n // -- MCP Servers -------------------------------------------------------\n\n case \"add_mcp_server\": {\n if (mcpServerExists(ir, mutation.server.id)) {\n throw new Error(`MCP server '${mutation.server.id}' already exists`);\n }\n return {\n ...ir,\n mcpServers: [...ir.mcpServers, { ...mutation.server }],\n };\n }\n\n case \"remove_mcp_server\": {\n if (!mcpServerExists(ir, mutation.id)) {\n throw new Error(`MCP server '${mutation.id}' not found`);\n }\n return {\n ...ir,\n mcpServers: ir.mcpServers.filter((s) => s.id !== mutation.id),\n };\n }\n\n // -- Settings ----------------------------------------------------------\n\n case \"update_settings\": {\n return {\n ...ir,\n settings: applySettingsUpdate(ir.settings, mutation.path, mutation.value),\n };\n }\n\n // -- Raw text (legacy fallback) ----------------------------------------\n\n case \"raw_text\": {\n console.warn(\n \"raw_text mutation is a legacy fallback — the text operation will be applied during rendering\",\n );\n return { ...ir };\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// applyIRMutations\n// ---------------------------------------------------------------------------\n\n/**\n * Apply a sequence of mutations to a HarnessIR, returning the final IR.\n *\n * Mutations are applied in order. If any mutation fails, the error propagates immediately.\n */\nexport function applyIRMutations(ir: HarnessIR, mutations: IRMutation[]): HarnessIR {\n return mutations.reduce<HarnessIR>(\n (acc, mut) => applyIRMutation(acc, mut),\n ir,\n );\n}\n\n// ---------------------------------------------------------------------------\n// validateIRMutation\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether a mutation's pre-conditions are satisfied without applying it.\n *\n * Returns `{ valid: true }` if the mutation can be applied, or\n * `{ valid: false, reason: \"...\" }` describing why it cannot.\n */\nexport function validateIRMutation(\n ir: HarnessIR,\n mutation: IRMutation,\n): ValidationResult {\n switch (mutation.type) {\n // -- Sections ----------------------------------------------------------\n\n case \"update_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n return { valid: false, reason: `Section '${mutation.sectionId}' not found` };\n }\n return { valid: true };\n }\n\n case \"add_section\": {\n if (sectionExists(ir, mutation.section.id)) {\n return { valid: false, reason: `Section '${mutation.section.id}' already exists` };\n }\n return { valid: true };\n }\n\n case \"remove_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n return { valid: false, reason: `Section '${mutation.sectionId}' not found` };\n }\n return { valid: true };\n }\n\n case \"reorder_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n return { valid: false, reason: `Section '${mutation.sectionId}' not found` };\n }\n return { valid: true };\n }\n\n // -- Commands ----------------------------------------------------------\n\n case \"add_command\": {\n if (commandExists(ir, mutation.command.name)) {\n return { valid: false, reason: `Command '${mutation.command.name}' already exists` };\n }\n return { valid: true };\n }\n\n case \"update_command\": {\n if (!commandExists(ir, mutation.name)) {\n return { valid: false, reason: `Command '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n case \"remove_command\": {\n if (!commandExists(ir, mutation.name)) {\n return { valid: false, reason: `Command '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n // -- Rules -------------------------------------------------------------\n\n case \"add_rule\": {\n if (ruleExists(ir, mutation.rule.name)) {\n return { valid: false, reason: `Rule '${mutation.rule.name}' already exists` };\n }\n return { valid: true };\n }\n\n case \"update_rule\": {\n if (!ruleExists(ir, mutation.name)) {\n return { valid: false, reason: `Rule '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n case \"remove_rule\": {\n if (!ruleExists(ir, mutation.name)) {\n return { valid: false, reason: `Rule '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n // -- Agents ------------------------------------------------------------\n\n case \"add_agent\": {\n if (agentExists(ir, mutation.agent.name)) {\n return { valid: false, reason: `Agent '${mutation.agent.name}' already exists` };\n }\n return { valid: true };\n }\n\n case \"update_agent\": {\n if (!agentExists(ir, mutation.name)) {\n return { valid: false, reason: `Agent '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n case \"remove_agent\": {\n if (!agentExists(ir, mutation.name)) {\n return { valid: false, reason: `Agent '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n // -- MCP Servers -------------------------------------------------------\n\n case \"add_mcp_server\": {\n if (mcpServerExists(ir, mutation.server.id)) {\n return { valid: false, reason: `MCP server '${mutation.server.id}' already exists` };\n }\n return { valid: true };\n }\n\n case \"remove_mcp_server\": {\n if (!mcpServerExists(ir, mutation.id)) {\n return { valid: false, reason: `MCP server '${mutation.id}' not found` };\n }\n return { valid: true };\n }\n\n // -- Settings & raw_text always valid at pre-condition level ------------\n\n case \"update_settings\": {\n return { valid: true };\n }\n\n case \"raw_text\": {\n return { valid: true };\n }\n }\n}\n","/**\n * Harness Renderer — produces a `.claude/` directory structure from a HarnessIR.\n *\n * This is the inverse of the parser: given a HarnessIR, it emits the file\n * contents that `parseHarness` would read back into the same IR.\n *\n * All file I/O uses `fs.promises`. Directories are created on demand.\n */\n\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type {\n HarnessIR,\n HarnessMeta,\n Section,\n SettingsIR,\n McpServerNode,\n RuleNode,\n AgentNode,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// renderClaudeMd\n// ---------------------------------------------------------------------------\n\n/**\n * Render the CLAUDE.md file content from metadata and sections.\n *\n * Sections are sorted by `order`. Each section is output as\n * `{heading}\\n\\n{content}` — the heading already includes its `## ` prefix\n * (or `# ` for the preamble). Sections are joined with double newlines.\n *\n * @param _meta - Harness metadata (name used only if no preamble section provides a title)\n * @param sections - The ordered sections to render\n * @returns The full CLAUDE.md content string with trailing newline\n */\nexport function renderClaudeMd(_meta: HarnessMeta, sections: Section[]): string {\n const sorted = [...sections].sort((a, b) => a.order - b.order);\n\n const blocks: string[] = [];\n\n for (const section of sorted) {\n if (section.heading && section.content) {\n blocks.push(`${section.heading}\\n\\n${section.content}`);\n } else if (section.heading) {\n blocks.push(section.heading);\n } else if (section.content) {\n blocks.push(section.content);\n }\n // Skip sections with neither heading nor content\n }\n\n if (blocks.length === 0) {\n return \"\\n\";\n }\n\n return blocks.join(\"\\n\\n\") + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// renderSettings\n// ---------------------------------------------------------------------------\n\n/**\n * Render a `settings.json` string from a SettingsIR.\n *\n * Reconstructs the JSON structure that `parseSettings` would parse:\n * - `raw` fields are spread as the base\n * - `denyPatterns` → `permissions.deny`\n * - `statusLine` → `statusLine`\n * - Non-empty hook arrays → `hooks.{EventType}`\n *\n * @param settings - The settings IR to render\n * @returns JSON string with 2-space indent and trailing newline\n */\nexport function renderSettings(settings: SettingsIR): string {\n // Deep-clone raw as the base\n const result: Record<string, unknown> = JSON.parse(\n JSON.stringify(settings.raw),\n );\n\n // Add deny patterns\n if (settings.denyPatterns && settings.denyPatterns.length > 0) {\n const permissions =\n (result[\"permissions\"] as Record<string, unknown>) ?? {};\n permissions[\"deny\"] = settings.denyPatterns;\n result[\"permissions\"] = permissions;\n }\n\n // Add status line\n if (settings.statusLine) {\n result[\"statusLine\"] = settings.statusLine;\n }\n\n // Add hooks\n const hookEvents = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"UserPromptSubmit\",\n \"SessionStart\",\n \"PostCompact\",\n ] as const;\n\n const hooksObj: Record<string, unknown> = {};\n let hasHooks = false;\n\n for (const event of hookEvents) {\n const entries = settings.hooks[event];\n if (entries && entries.length > 0) {\n hooksObj[event] = entries;\n hasHooks = true;\n }\n }\n\n if (hasHooks) {\n result[\"hooks\"] = hooksObj;\n }\n\n return JSON.stringify(result, null, 2) + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// renderMcpConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Render a `.mcp.json` string from an array of MCP server nodes.\n *\n * Builds the `{ mcpServers: { id: { command, args, env? } } }` structure.\n * Returns an empty string if the servers array is empty (no file needed).\n *\n * @param servers - Array of MCP server declarations\n * @returns JSON string with 2-space indent and trailing newline, or empty string\n */\nexport function renderMcpConfig(servers: McpServerNode[]): string {\n if (servers.length === 0) {\n return \"\";\n }\n\n const mcpServers: Record<string, Record<string, unknown>> = {};\n\n for (const server of servers) {\n const entry: Record<string, unknown> = {\n command: server.command,\n args: server.args,\n };\n\n if (server.env && Object.keys(server.env).length > 0) {\n entry[\"env\"] = server.env;\n }\n\n mcpServers[server.id] = entry;\n }\n\n return JSON.stringify({ mcpServers }, null, 2) + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// renderRuleWithFrontmatter\n// ---------------------------------------------------------------------------\n\n/**\n * Render a rule's content, prepending YAML frontmatter if the rule has paths.\n *\n * The frontmatter format matches what `parseYamlFrontmatter` expects:\n * ```\n * ---\n * paths:\n * - path1\n * - path2\n * ---\n *\n * {content}\n * ```\n *\n * @param rule - The rule node to render\n * @returns The rendered string (with or without frontmatter)\n */\nexport function renderRuleWithFrontmatter(rule: RuleNode): string {\n if (!rule.paths || rule.paths.length === 0) {\n return rule.content;\n }\n\n const yamlLines = [\"---\", \"paths:\"];\n for (const p of rule.paths) {\n yamlLines.push(` - ${p}`);\n }\n yamlLines.push(\"---\");\n\n return yamlLines.join(\"\\n\") + \"\\n\\n\" + rule.content;\n}\n\n// ---------------------------------------------------------------------------\n// renderAgentWithFrontmatter\n// ---------------------------------------------------------------------------\n\n/**\n * Render an agent's content, prepending YAML frontmatter if the agent has\n * `model` or `disallowedTools`.\n *\n * The frontmatter format matches what `parseYamlFrontmatter` expects:\n * ```\n * ---\n * model: opus\n * disallowedTools:\n * - Tool1\n * ---\n *\n * {content}\n * ```\n *\n * @param agent - The agent node to render\n * @returns The rendered string (with or without frontmatter)\n */\nexport function renderAgentWithFrontmatter(agent: AgentNode): string {\n const hasModel = agent.model !== undefined;\n const hasDisallowed =\n agent.disallowedTools !== undefined && agent.disallowedTools.length > 0;\n const hasRouting = agent.modelRouting !== undefined;\n const hasExtra =\n agent.extraFrontmatter !== undefined &&\n Object.keys(agent.extraFrontmatter).length > 0;\n\n if (!hasModel && !hasDisallowed && !hasRouting && !hasExtra) {\n return agent.content;\n }\n\n const yamlLines = [\"---\"];\n\n if (hasModel) {\n yamlLines.push(`model: ${agent.model}`);\n }\n\n if (hasDisallowed) {\n yamlLines.push(\"disallowedTools:\");\n for (const tool of agent.disallowedTools!) {\n yamlLines.push(` - ${tool}`);\n }\n }\n\n // Emit modelRouting as nested YAML\n if (hasRouting) {\n yamlLines.push(\"modelRouting:\");\n yamlLines.push(` default: ${agent.modelRouting!.default}`);\n if (agent.modelRouting!.escalateTo) {\n yamlLines.push(` escalateTo: ${agent.modelRouting!.escalateTo}`);\n }\n if (agent.modelRouting!.escalateWhen) {\n yamlLines.push(` escalateWhen: ${agent.modelRouting!.escalateWhen}`);\n }\n }\n\n // Re-emit all extra frontmatter fields preserved from the original file\n if (hasExtra) {\n for (const [key, value] of Object.entries(agent.extraFrontmatter!)) {\n if (Array.isArray(value)) {\n yamlLines.push(`${key}:`);\n for (const item of value) {\n yamlLines.push(` - ${String(item)}`);\n }\n } else if (typeof value === 'object' && value !== null) {\n // Nested objects — render as indented YAML\n yamlLines.push(`${key}:`);\n for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {\n yamlLines.push(` ${subKey}: ${String(subVal)}`);\n }\n } else {\n yamlLines.push(`${key}: ${String(value)}`);\n }\n }\n }\n\n yamlLines.push(\"---\");\n\n return yamlLines.join(\"\\n\") + \"\\n\\n\" + agent.content;\n}\n\n// ---------------------------------------------------------------------------\n// settingsHasContent\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether a SettingsIR has any meaningful content beyond empty defaults.\n *\n * Returns false for `{ hooks: {}, raw: {} }` (the output of `createEmptySettings`).\n */\nfunction settingsHasContent(settings: SettingsIR): boolean {\n if (settings.statusLine) return true;\n if (settings.denyPatterns && settings.denyPatterns.length > 0) return true;\n if (Object.keys(settings.raw).length > 0) return true;\n\n // Check if any hook event has entries\n const hookEvents = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"UserPromptSubmit\",\n \"SessionStart\",\n \"PostCompact\",\n ] as const;\n\n for (const event of hookEvents) {\n const entries = settings.hooks[event];\n if (entries && entries.length > 0) return true;\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// renderHarness\n// ---------------------------------------------------------------------------\n\n/**\n * Render a complete HarnessIR into a file map.\n *\n * Returns a `Map<string, string>` where keys are relative file paths\n * (e.g., `CLAUDE.md`, `commands/build.md`) and values are file contents.\n *\n * Only files with actual content are included in the map.\n *\n * @param ir - The complete harness IR to render\n * @returns Map of relative file path to file content\n */\nexport function renderHarness(ir: HarnessIR): Map<string, string> {\n const files = new Map<string, string>();\n\n // CLAUDE.md — only if sections exist or meta.name is set\n if (ir.sections.length > 0 || ir.meta.name) {\n files.set(\"CLAUDE.md\", renderClaudeMd(ir.meta, ir.sections));\n }\n\n // settings.json — only if settings has content beyond empty defaults\n if (settingsHasContent(ir.settings)) {\n files.set(\"settings.json\", renderSettings(ir.settings));\n }\n\n // Commands\n for (const cmd of ir.commands) {\n files.set(`commands/${cmd.name}.md`, cmd.content);\n }\n\n // Rules\n for (const rule of ir.rules) {\n files.set(`rules/${rule.name}.md`, renderRuleWithFrontmatter(rule));\n }\n\n // Agents\n for (const agent of ir.agents) {\n files.set(`agents/${agent.name}.md`, renderAgentWithFrontmatter(agent));\n }\n\n // Skills\n for (const skill of ir.skills) {\n files.set(`skills/${skill.name}.md`, skill.content);\n }\n\n // Docs\n for (const doc of ir.docs) {\n files.set(`docs/${doc.name}.md`, doc.content);\n }\n\n // Hooks\n for (const hook of ir.hooks) {\n files.set(`hooks/${hook.name}.mjs`, hook.content);\n }\n\n // .mcp.json — only if servers exist\n const mcpContent = renderMcpConfig(ir.mcpServers);\n if (mcpContent) {\n files.set(\".mcp.json\", mcpContent);\n }\n\n return files;\n}\n\n// ---------------------------------------------------------------------------\n// renderHarnessToDir\n// ---------------------------------------------------------------------------\n\n/**\n * Render a HarnessIR to a target directory on disk.\n *\n * Calls `renderHarness` to produce the file map, then writes each file\n * to `path.join(targetDir, relativePath)`, creating directories as needed.\n *\n * @param ir - The complete harness IR to render\n * @param targetDir - Absolute path to write files into\n * @returns Array of relative file paths that were written\n */\nexport async function renderHarnessToDir(\n ir: HarnessIR,\n targetDir: string,\n): Promise<string[]> {\n const fileMap = renderHarness(ir);\n const writtenPaths: string[] = [];\n\n for (const [relativePath, content] of fileMap) {\n const fullPath = path.join(targetDir, relativePath);\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n await fs.writeFile(fullPath, content, \"utf-8\");\n writtenPaths.push(relativePath);\n }\n\n return writtenPaths;\n}\n","/**\n * Structural diff engine for HarnessIR snapshots.\n *\n * Compares two HarnessIR trees and produces an IRDiff describing\n * every addition, removal, modification, and reordering across\n * sections, commands, rules, agents, MCP servers, and settings.\n */\n\nimport type {\n HarnessIR,\n IRDiff,\n Section,\n CommandNode,\n RuleNode,\n AgentNode,\n McpServerNode,\n SettingsIR,\n} from \"./types.js\";\nimport { createEmptyDiff } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Compute a structural diff between two HarnessIR snapshots.\n *\n * Every category is compared by its natural key (id for sections/servers,\n * name for commands/rules/agents). Settings are deep-compared field by field.\n */\nexport function diffIR(before: HarnessIR, after: HarnessIR): IRDiff {\n const diff = createEmptyDiff();\n\n diffSections(before.sections, after.sections, diff);\n diffByName(before.commands, after.commands, diff.commands);\n diffByName(before.rules, after.rules, diff.rules);\n diffAgents(before.agents, after.agents, diff);\n diffMcpServers(before.mcpServers, after.mcpServers, diff);\n diffSettings(before.settings, after.settings, diff);\n\n return diff;\n}\n\n/**\n * Format an IRDiff into a human-readable, plain-text summary.\n *\n * Categories with no changes are omitted. If the entire diff is empty\n * the string \"No changes.\" is returned.\n */\nexport function formatIRDiff(diff: IRDiff): string {\n const blocks: string[] = [];\n\n // Sections\n const sectionLines = formatSectionBlock(diff);\n if (sectionLines.length > 0) {\n blocks.push([\"Sections:\", ...sectionLines].join(\"\\n\"));\n }\n\n // Commands\n const commandLines = formatNamedBlock(diff.commands, \"commands\");\n if (commandLines.length > 0) {\n blocks.push([\"Commands:\", ...commandLines].join(\"\\n\"));\n }\n\n // Rules\n const ruleLines = formatNamedBlock(diff.rules, \"rules\");\n if (ruleLines.length > 0) {\n blocks.push([\"Rules:\", ...ruleLines].join(\"\\n\"));\n }\n\n // Agents\n const agentLines = formatAgentBlock(diff);\n if (agentLines.length > 0) {\n blocks.push([\"Agents:\", ...agentLines].join(\"\\n\"));\n }\n\n // MCP Servers\n const mcpLines = formatMcpBlock(diff);\n if (mcpLines.length > 0) {\n blocks.push([\"MCP Servers:\", ...mcpLines].join(\"\\n\"));\n }\n\n // Settings\n const settingsLines = formatSettingsBlock(diff);\n if (settingsLines.length > 0) {\n blocks.push([\"Settings:\", ...settingsLines].join(\"\\n\"));\n }\n\n if (blocks.length === 0) {\n return \"No changes.\";\n }\n\n return blocks.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Diff internals\n// ---------------------------------------------------------------------------\n\n/** Compare sections by `id`, detecting adds, removes, modifications, and reorderings. */\nfunction diffSections(\n beforeList: Section[],\n afterList: Section[],\n diff: IRDiff,\n): void {\n const beforeMap = new Map<string, Section>();\n for (const s of beforeList) {\n beforeMap.set(s.id, s);\n }\n\n const afterMap = new Map<string, Section>();\n for (const s of afterList) {\n afterMap.set(s.id, s);\n }\n\n // Added: in after but not in before\n for (const s of afterList) {\n if (!beforeMap.has(s.id)) {\n diff.sections.added.push(s);\n }\n }\n\n // Removed: in before but not in after\n for (const s of beforeList) {\n if (!afterMap.has(s.id)) {\n diff.sections.removed.push(s);\n }\n }\n\n // Modified & reordered: present in both\n for (const [id, afterSection] of afterMap) {\n const beforeSection = beforeMap.get(id);\n if (beforeSection === undefined) continue;\n\n if (beforeSection.content !== afterSection.content) {\n diff.sections.modified.push({\n id,\n before: beforeSection.content,\n after: afterSection.content,\n });\n }\n\n if (beforeSection.order !== afterSection.order) {\n diff.sections.reordered.push({\n id,\n oldOrder: beforeSection.order,\n newOrder: afterSection.order,\n });\n }\n }\n}\n\n/**\n * Generic diff for node lists keyed by `name` (commands and rules share this shape).\n * Populates `added`, `removed`, and `modified` arrays on the target bucket.\n */\nfunction diffByName<T extends { name: string; content: string }>(\n beforeList: T[],\n afterList: T[],\n target: {\n added: T[];\n removed: string[];\n modified: Array<{ name: string; before: string; after: string }>;\n },\n): void {\n const beforeMap = new Map<string, T>();\n for (const n of beforeList) {\n beforeMap.set(n.name, n);\n }\n\n const afterMap = new Map<string, T>();\n for (const n of afterList) {\n afterMap.set(n.name, n);\n }\n\n // Added\n for (const n of afterList) {\n if (!beforeMap.has(n.name)) {\n target.added.push(n);\n }\n }\n\n // Removed\n for (const n of beforeList) {\n if (!afterMap.has(n.name)) {\n target.removed.push(n.name);\n }\n }\n\n // Modified\n for (const [name, afterNode] of afterMap) {\n const beforeNode = beforeMap.get(name);\n if (beforeNode === undefined) continue;\n\n if (beforeNode.content !== afterNode.content) {\n target.modified.push({\n name,\n before: beforeNode.content,\n after: afterNode.content,\n });\n }\n }\n}\n\n/** Compare agents by `name`, building a human-readable `changes` description. */\nfunction diffAgents(\n beforeList: AgentNode[],\n afterList: AgentNode[],\n diff: IRDiff,\n): void {\n const beforeMap = new Map<string, AgentNode>();\n for (const a of beforeList) {\n beforeMap.set(a.name, a);\n }\n\n const afterMap = new Map<string, AgentNode>();\n for (const a of afterList) {\n afterMap.set(a.name, a);\n }\n\n // Added\n for (const a of afterList) {\n if (!beforeMap.has(a.name)) {\n diff.agents.added.push(a);\n }\n }\n\n // Removed\n for (const a of beforeList) {\n if (!afterMap.has(a.name)) {\n diff.agents.removed.push(a.name);\n }\n }\n\n // Modified\n for (const [name, afterAgent] of afterMap) {\n const beforeAgent = beforeMap.get(name);\n if (beforeAgent === undefined) continue;\n\n const changeParts: string[] = [];\n\n if (beforeAgent.model !== afterAgent.model) {\n const from = beforeAgent.model ?? \"none\";\n const to = afterAgent.model ?? \"none\";\n changeParts.push(`model changed from ${from} to ${to}`);\n }\n\n if (beforeAgent.content !== afterAgent.content) {\n changeParts.push(\"content updated\");\n }\n\n const beforeTools = JSON.stringify(beforeAgent.disallowedTools ?? []);\n const afterTools = JSON.stringify(afterAgent.disallowedTools ?? []);\n if (beforeTools !== afterTools) {\n changeParts.push(\"disallowedTools changed\");\n }\n\n if (changeParts.length > 0) {\n diff.agents.modified.push({\n name,\n changes: changeParts.join(\"; \"),\n });\n }\n }\n}\n\n/** Compare MCP servers by `id`. */\nfunction diffMcpServers(\n beforeList: McpServerNode[],\n afterList: McpServerNode[],\n diff: IRDiff,\n): void {\n const beforeIds = new Set(beforeList.map((s) => s.id));\n const afterIds = new Set(afterList.map((s) => s.id));\n\n for (const s of afterList) {\n if (!beforeIds.has(s.id)) {\n diff.mcpServers.added.push(s);\n }\n }\n\n for (const s of beforeList) {\n if (!afterIds.has(s.id)) {\n diff.mcpServers.removed.push(s.id);\n }\n }\n}\n\n/** Deep-compare settings fields: statusLine, denyPatterns, and hooks. */\nfunction diffSettings(\n before: SettingsIR,\n after: SettingsIR,\n diff: IRDiff,\n): void {\n // statusLine\n if (!deepEqual(before.statusLine, after.statusLine)) {\n diff.settings.changes.push({\n path: \"statusLine\",\n before: before.statusLine,\n after: after.statusLine,\n });\n }\n\n // denyPatterns\n if (!deepEqual(before.denyPatterns, after.denyPatterns)) {\n diff.settings.changes.push({\n path: \"denyPatterns\",\n before: before.denyPatterns,\n after: after.denyPatterns,\n });\n }\n\n // hooks\n if (!deepEqual(before.hooks, after.hooks)) {\n diff.settings.changes.push({\n path: \"hooks\",\n before: before.hooks,\n after: after.hooks,\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Format internals\n// ---------------------------------------------------------------------------\n\n/** Format the Sections block lines. */\nfunction formatSectionBlock(diff: IRDiff): string[] {\n const lines: string[] = [];\n\n for (const s of diff.sections.added) {\n lines.push(` + Added: ${s.heading}`);\n }\n for (const s of diff.sections.removed) {\n lines.push(` - Removed: ${s.heading}`);\n }\n for (const m of diff.sections.modified) {\n lines.push(` ~ Modified: ${m.id} (content changed)`);\n }\n for (const r of diff.sections.reordered) {\n lines.push(\n ` \\u2195 Reordered: ${r.id} (${r.oldOrder} \\u2192 ${r.newOrder})`,\n );\n }\n\n return lines;\n}\n\n/**\n * Format a generic named block (commands or rules).\n * The `_category` parameter is unused but kept for clarity at the call site.\n */\nfunction formatNamedBlock(\n bucket: {\n added: Array<{ name: string }>;\n removed: string[];\n modified: Array<{ name: string }>;\n },\n _category: string,\n): string[] {\n const lines: string[] = [];\n\n for (const n of bucket.added) {\n lines.push(` + Added: ${n.name}`);\n }\n for (const name of bucket.removed) {\n lines.push(` - Removed: ${name}`);\n }\n for (const m of bucket.modified) {\n lines.push(` ~ Modified: ${m.name} (content changed)`);\n }\n\n return lines;\n}\n\n/** Format the Agents block. */\nfunction formatAgentBlock(diff: IRDiff): string[] {\n const lines: string[] = [];\n\n for (const a of diff.agents.added) {\n lines.push(` + Added: ${a.name}`);\n }\n for (const name of diff.agents.removed) {\n lines.push(` - Removed: ${name}`);\n }\n for (const m of diff.agents.modified) {\n lines.push(` ~ Modified: ${m.name} (${m.changes})`);\n }\n\n return lines;\n}\n\n/** Format the MCP Servers block. */\nfunction formatMcpBlock(diff: IRDiff): string[] {\n const lines: string[] = [];\n\n for (const s of diff.mcpServers.added) {\n lines.push(` + Added: ${s.id}`);\n }\n for (const id of diff.mcpServers.removed) {\n lines.push(` - Removed: ${id}`);\n }\n\n return lines;\n}\n\n/** Format the Settings block. */\nfunction formatSettingsBlock(diff: IRDiff): string[] {\n const lines: string[] = [];\n\n for (const c of diff.settings.changes) {\n lines.push(` ~ ${c.path} changed`);\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Utility\n// ---------------------------------------------------------------------------\n\n/** Simple deep-equality check using JSON serialisation. */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport type { Mutation } from './types.js';\nimport { parseHarness } from '../ir/parser.js';\nimport { translateMutations } from '../ir/translate.js';\nimport { applyIRMutation } from '../ir/mutations.js';\nimport { renderHarness } from '../ir/renderer.js';\nimport { diffIR, formatIRDiff } from '../ir/diff.js';\nimport type { HarnessIR } from '../ir/types.js';\n\n/**\n * Apply mutations to a copy of the current harness using the IR pipeline.\n *\n * Pipeline:\n * 1. Parse the current harness into an IR\n * 2. Translate legacy Mutations into IRMutations\n * 3. Apply each IRMutation immutably (skip failures silently)\n * 4. Render the new IR to disk\n * 5. Apply any raw_text mutations via file-based string surgery (backward compat)\n * 6. Generate a structural diff between baseline and new IR\n *\n * Falls back to the legacy file-copy + string-surgery approach if IR parsing fails.\n *\n * @returns Path to new harness and diff patch string\n */\nexport async function applyMutations(\n currentHarnessPath: string,\n nextIterationDir: string,\n mutations: Mutation[],\n): Promise<{ newHarnessPath: string; diffPatch: string }> {\n const newHarnessPath = path.join(nextIterationDir, 'harness');\n\n // Try the IR pipeline first\n let baselineIR: HarnessIR | null = null;\n try {\n baselineIR = await parseHarness(currentHarnessPath);\n } catch {\n // IR parsing failed — fall back to legacy approach\n }\n\n if (baselineIR !== null) {\n return applyMutationsViaIR(\n currentHarnessPath,\n newHarnessPath,\n mutations,\n baselineIR,\n );\n }\n\n // Legacy fallback: file-copy + string surgery\n return applyMutationsLegacy(currentHarnessPath, newHarnessPath, mutations);\n}\n\n/**\n * IR-based mutation pipeline.\n *\n * Strategy: copy the original harness first (preserving exact byte content),\n * then apply mutations through the IR engine. Only files affected by IR\n * mutations get re-rendered, so untouched files remain byte-identical.\n *\n * raw_text mutations are applied via legacy file-based string surgery after\n * the IR mutations, preserving backward compatibility for non-IR-translatable\n * mutations.\n */\nasync function applyMutationsViaIR(\n currentHarnessPath: string,\n newHarnessPath: string,\n mutations: Mutation[],\n baselineIR: HarnessIR,\n): Promise<{ newHarnessPath: string; diffPatch: string }> {\n // 1. Copy the original harness to preserve exact byte content\n await copyDir(currentHarnessPath, newHarnessPath);\n\n // 2. Translate legacy mutations to IR mutations\n const irMutations = translateMutations(mutations, baselineIR);\n\n // 3. Apply IR mutations one by one, skipping failures silently.\n // Track which IR node categories were touched so we only re-render those files.\n let currentIR = baselineIR;\n const rawTextMutations: Mutation[] = [];\n const touchedCategories = new Set<string>();\n\n for (let i = 0; i < irMutations.length; i++) {\n const irMut = irMutations[i];\n\n if (irMut.type === 'raw_text') {\n // Collect raw_text mutations for file-based application later\n rawTextMutations.push(mutations[i]);\n continue;\n }\n\n try {\n currentIR = applyIRMutation(currentIR, irMut);\n // Track which file category this mutation touched\n touchedCategories.add(getMutationCategory(irMut.type));\n } catch {\n // Skip failed mutations silently — matches old behavior where\n // a replace with missing oldText was simply skipped\n continue;\n }\n }\n\n // 4. Selectively re-render only files affected by IR mutations.\n // This preserves byte-identical content for untouched files while\n // applying structural changes through the IR engine.\n if (touchedCategories.size > 0) {\n await renderAffectedFiles(currentIR, newHarnessPath, touchedCategories);\n }\n\n // 5. Apply raw_text mutations via file-based string surgery\n for (const mutation of rawTextMutations) {\n await applyLegacyMutation(newHarnessPath, mutation);\n }\n\n // 6. Generate structural diff\n const irDiff = diffIR(baselineIR, currentIR);\n let diffPatch = formatIRDiff(irDiff);\n\n // If the IR diff says \"No changes.\" but raw_text mutations were applied,\n // fall back to a file-based diff to capture those changes\n if (diffPatch === 'No changes.' && rawTextMutations.length > 0) {\n diffPatch = await generateDiffLegacy(currentHarnessPath, newHarnessPath);\n }\n\n // Normalize \"No changes.\" to empty string for backward compatibility\n if (diffPatch === 'No changes.') {\n diffPatch = '';\n }\n\n return { newHarnessPath, diffPatch };\n}\n\n/**\n * Map an IR mutation type to the file category it affects.\n * Used to determine which files need re-rendering after IR mutations.\n */\nfunction getMutationCategory(mutationType: string): string {\n if (mutationType.includes('section') || mutationType.includes('reorder')) {\n return 'claude_md';\n }\n if (mutationType.includes('command')) {\n return 'commands';\n }\n if (mutationType.includes('rule')) {\n return 'rules';\n }\n if (mutationType.includes('agent')) {\n return 'agents';\n }\n if (mutationType.includes('mcp')) {\n return 'mcp';\n }\n if (mutationType.includes('settings')) {\n return 'settings';\n }\n return 'unknown';\n}\n\n/**\n * Re-render only the files affected by IR mutations.\n *\n * Instead of re-rendering the entire harness (which can alter whitespace\n * in untouched files), this function renders the full file map from IR\n * and then selectively writes only files belonging to touched categories.\n *\n * For \"remove\" mutations (remove_rule, remove_command, etc.), the affected\n * file is deleted from disk since it won't appear in the rendered map.\n */\nasync function renderAffectedFiles(\n ir: HarnessIR,\n targetDir: string,\n touchedCategories: Set<string>,\n): Promise<void> {\n const fileMap = renderHarness(ir);\n\n // Determine which rendered file paths belong to touched categories\n for (const [relativePath, content] of fileMap) {\n const category = getFileCategory(relativePath);\n if (touchedCategories.has(category)) {\n const fullPath = path.join(targetDir, relativePath);\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n await fs.writeFile(fullPath, content, 'utf-8');\n }\n }\n\n // Handle deletions: for removed commands/rules/agents, delete files that\n // existed in the copy but are absent from the rendered map.\n if (touchedCategories.has('commands')) {\n await deleteOrphanedFiles(targetDir, 'commands', fileMap);\n }\n if (touchedCategories.has('rules')) {\n await deleteOrphanedFiles(targetDir, 'rules', fileMap);\n }\n if (touchedCategories.has('agents')) {\n await deleteOrphanedFiles(targetDir, 'agents', fileMap);\n }\n\n // Handle singleton file deletions: when a category is touched but\n // the rendered map has no entry for its file, delete the stale file.\n if (touchedCategories.has('mcp') && !fileMap.has('.mcp.json')) {\n await fs.unlink(path.join(targetDir, '.mcp.json')).catch(() => {});\n }\n if (touchedCategories.has('settings') && !fileMap.has('settings.json')) {\n await fs.unlink(path.join(targetDir, 'settings.json')).catch(() => {});\n }\n}\n\n/**\n * Map a relative file path to its category for selective rendering.\n */\nfunction getFileCategory(relativePath: string): string {\n if (relativePath === 'CLAUDE.md') return 'claude_md';\n if (relativePath.startsWith('commands/')) return 'commands';\n if (relativePath.startsWith('rules/')) return 'rules';\n if (relativePath.startsWith('agents/')) return 'agents';\n if (relativePath.startsWith('skills/')) return 'skills';\n if (relativePath.startsWith('docs/')) return 'docs';\n if (relativePath.startsWith('hooks/')) return 'hooks';\n if (relativePath === 'settings.json') return 'settings';\n if (relativePath === '.mcp.json') return 'mcp';\n return 'unknown';\n}\n\n/**\n * Delete files in a subdirectory that are present on disk but absent from\n * the rendered file map. This handles \"remove\" IR mutations (e.g., remove_rule).\n */\nasync function deleteOrphanedFiles(\n targetDir: string,\n subdir: string,\n renderedMap: Map<string, string>,\n): Promise<void> {\n const subdirPath = path.join(targetDir, subdir);\n let entries;\n try {\n entries = await fs.readdir(subdirPath);\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const relativePath = `${subdir}/${entry}`;\n if (!renderedMap.has(relativePath)) {\n await fs.unlink(path.join(subdirPath, entry)).catch(() => {});\n }\n }\n}\n\n/**\n * Legacy file-copy + string surgery approach (fallback when IR parsing fails).\n * Preserves the original v2.5.2 behavior exactly.\n */\nasync function applyMutationsLegacy(\n currentHarnessPath: string,\n newHarnessPath: string,\n mutations: Mutation[],\n): Promise<{ newHarnessPath: string; diffPatch: string }> {\n // 1. Copy current harness to new iteration\n await copyDir(currentHarnessPath, newHarnessPath);\n\n // 2. Apply each mutation\n for (const mutation of mutations) {\n await applyLegacyMutation(newHarnessPath, mutation);\n }\n\n // 3. Generate diff\n const diffPatch = await generateDiffLegacy(currentHarnessPath, newHarnessPath);\n\n return { newHarnessPath, diffPatch };\n}\n\n/**\n * Apply a single legacy mutation to a file in the harness directory.\n * This is the original string-surgery approach used in v2.5.2.\n */\nasync function applyLegacyMutation(\n harnessPath: string,\n mutation: Mutation,\n): Promise<void> {\n // Security: reject path traversal\n if (mutation.file.includes('..')) {\n return;\n }\n\n const filePath = path.join(harnessPath, mutation.file);\n\n if (mutation.action === 'replace') {\n if (!mutation.oldText) {\n return;\n }\n let content: string;\n try {\n content = await fs.readFile(filePath, 'utf-8');\n } catch {\n return;\n }\n if (!content.includes(mutation.oldText)) {\n return;\n }\n // Replace first occurrence only — intentional for surgical mutations\n await fs.writeFile(\n filePath,\n content.replace(mutation.oldText, mutation.newText),\n 'utf-8',\n );\n } else if (mutation.action === 'add_section') {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n await fs.writeFile(\n filePath,\n content + '\\n\\n' + mutation.newText,\n 'utf-8',\n );\n } catch {\n // File doesn't exist — create it\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, mutation.newText, 'utf-8');\n }\n } else if (mutation.action === 'create_file') {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, mutation.newText, 'utf-8');\n } else if (mutation.action === 'delete_section') {\n if (!mutation.oldText) {\n return;\n }\n let sectionContent: string;\n try {\n sectionContent = await fs.readFile(filePath, 'utf-8');\n } catch {\n return;\n }\n if (!sectionContent.includes(mutation.oldText)) {\n return;\n }\n await fs.writeFile(filePath, sectionContent.replace(mutation.oldText, ''), 'utf-8');\n } else if (mutation.action === 'delete_file') {\n await fs.unlink(filePath).catch(() => {});\n }\n}\n\n/**\n * Generate a simple unified-diff-style patch between two directories.\n * Compares files in both directories and outputs differences.\n *\n * Attempts to use the IR-based structural diff first. Falls back to the\n * legacy character-diff approach if IR parsing fails for either directory\n * or if the directories don't contain recognizable harness content.\n */\nexport async function generateDiff(\n oldDir: string,\n newDir: string,\n): Promise<string> {\n // Try IR-based diff first — only if both directories have harness content\n try {\n const oldIR = await parseHarness(oldDir);\n const newIR = await parseHarness(newDir);\n\n // Only use IR diff if at least one directory has meaningful harness content\n // (sections, commands, rules, etc.). Otherwise fall through to legacy.\n const oldHasContent = oldIR.sections.length > 0 || oldIR.commands.length > 0 ||\n oldIR.rules.length > 0 || oldIR.agents.length > 0;\n const newHasContent = newIR.sections.length > 0 || newIR.commands.length > 0 ||\n newIR.rules.length > 0 || newIR.agents.length > 0;\n\n if (oldHasContent || newHasContent) {\n const irDiff = diffIR(oldIR, newIR);\n const formatted = formatIRDiff(irDiff);\n\n // \"No changes.\" means identical — normalize to empty string for backward compat\n if (formatted === 'No changes.') {\n // Double-check with legacy diff in case there are non-IR file changes\n const legacyDiff = await generateDiffLegacy(oldDir, newDir);\n return legacyDiff;\n }\n\n // IR diff found structural changes — but also check for non-IR file changes\n const legacyDiff = await generateDiffLegacy(oldDir, newDir);\n if (legacyDiff && !formatted.includes(legacyDiff)) {\n return formatted + '\\n\\n' + legacyDiff;\n }\n return formatted;\n }\n } catch {\n // IR parsing failed — fall back to legacy diff\n }\n\n return generateDiffLegacy(oldDir, newDir);\n}\n\n/**\n * Legacy diff implementation: character-by-character comparison of all files.\n */\nasync function generateDiffLegacy(\n oldDir: string,\n newDir: string,\n): Promise<string> {\n const oldFiles = await readAllFiles(oldDir);\n const newFiles = await readAllFiles(newDir);\n\n const allPaths = new Set([\n ...Object.keys(oldFiles),\n ...Object.keys(newFiles),\n ]);\n const patches: string[] = [];\n\n for (const filePath of [...allPaths].sort()) {\n const oldContent = oldFiles[filePath] ?? '';\n const newContent = newFiles[filePath] ?? '';\n\n if (oldContent === newContent) continue;\n\n patches.push(`--- a/${filePath}`);\n patches.push(`+++ b/${filePath}`);\n\n if (!oldContent) {\n // New file\n for (const line of newContent.split('\\n')) {\n patches.push(`+${line}`);\n }\n } else if (!newContent) {\n // Deleted file\n for (const line of oldContent.split('\\n')) {\n patches.push(`-${line}`);\n }\n } else {\n // Modified — show old lines as removed, new lines as added\n const oldLines = oldContent.split('\\n');\n const newLines = newContent.split('\\n');\n for (const line of oldLines) {\n patches.push(`-${line}`);\n }\n for (const line of newLines) {\n patches.push(`+${line}`);\n }\n }\n patches.push('');\n }\n\n return patches.join('\\n');\n}\n\n/**\n * Recursively read all files in a directory into a map of relative path -> content.\n */\nasync function readAllFiles(dir: string): Promise<Record<string, string>> {\n const result: Record<string, string> = {};\n\n async function walk(current: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const fullPath = path.join(current, entry.name);\n const relativePath = path.relative(dir, fullPath);\n if (entry.isDirectory()) {\n await walk(fullPath);\n } else {\n result[relativePath] = await fs.readFile(fullPath, 'utf-8');\n }\n }\n }\n\n await walk(dir);\n return result;\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { Task } from './types.js';\n\n/**\n * Represents a Beta distribution belief about a task's success rate.\n * Used by Thompson Sampling to select tasks with high uncertainty.\n */\nexport interface TaskBelief {\n taskId: string;\n alpha: number; // successes + 1 (Beta distribution parameter)\n beta: number; // failures + 1 (Beta distribution parameter)\n}\n\n/**\n * Initialize uniform prior beliefs for all tasks.\n * Each task starts with alpha=1, beta=1 (uniform distribution).\n */\nexport function initBeliefs(tasks: Task[]): TaskBelief[] {\n return tasks.map(task => ({\n taskId: task.id,\n alpha: 1,\n beta: 1,\n }));\n}\n\n/**\n * Sample from a Beta distribution using the Joehnk algorithm.\n * Returns a value in [0, 1].\n */\nfunction sampleBeta(alpha: number, beta: number, rng: () => number): number {\n // For alpha=1, beta=1 (uniform), just return rng directly\n if (alpha === 1 && beta === 1) return rng();\n\n // Joehnk's algorithm for general Beta(a, b)\n // Uses rejection sampling via Gamma variates approximation\n // For small alpha/beta, use the inverse CDF method via Gamma ratio\n const gammaA = sampleGamma(alpha, rng);\n const gammaB = sampleGamma(beta, rng);\n return gammaA / (gammaA + gammaB);\n}\n\n/**\n * Sample from Gamma(alpha, 1) using Marsaglia and Tsang's method.\n */\nfunction sampleGamma(alpha: number, rng: () => number): number {\n if (alpha < 1) {\n // Boost: Gamma(alpha) = Gamma(alpha+1) * U^(1/alpha)\n return sampleGamma(alpha + 1, rng) * Math.pow(rng(), 1 / alpha);\n }\n\n const d = alpha - 1 / 3;\n const c = 1 / Math.sqrt(9 * d);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let x: number;\n let v: number;\n do {\n x = sampleNormal(rng);\n v = 1 + c * x;\n } while (v <= 0);\n\n v = v * v * v;\n const u = rng();\n if (u < 1 - 0.0331 * (x * x) * (x * x)) return d * v;\n if (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v))) return d * v;\n }\n}\n\n/**\n * Sample from standard normal using Box-Muller transform.\n */\nfunction sampleNormal(rng: () => number): number {\n const u1 = rng();\n const u2 = rng();\n return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n}\n\n/**\n * Select tasks using Thompson Sampling.\n *\n * For each task, sample from its Beta(alpha, beta) distribution.\n * Select the top-K tasks by sampled value. Tasks with high uncertainty\n * (wide distributions) are more likely to produce extreme samples and\n * thus more likely to be selected.\n *\n * @param beliefs - Current beliefs about each task\n * @param sampleSize - Number of tasks to select\n * @param rng - Random number generator (0-1)\n * @returns Array of selected task IDs (length = sampleSize)\n */\nexport function sampleThompson(\n beliefs: TaskBelief[],\n sampleSize: number,\n rng: () => number,\n): string[] {\n if (sampleSize >= beliefs.length) {\n return beliefs.map(b => b.taskId);\n }\n\n // Sample from each task's Beta distribution\n const samples = beliefs.map(belief => ({\n taskId: belief.taskId,\n sample: sampleBeta(belief.alpha, belief.beta, rng),\n }));\n\n // Sort by sampled value descending, take top-K\n samples.sort((a, b) => b.sample - a.sample);\n return samples.slice(0, sampleSize).map(s => s.taskId);\n}\n\n/**\n * Update beliefs after observing task results.\n *\n * If score >= 70%, increment alpha (success).\n * If score < 70%, increment beta (failure).\n *\n * @param beliefs - Current beliefs\n * @param results - Task scores from this iteration (taskId -> score value 0-100)\n * @returns Updated beliefs (new array, does not mutate input)\n */\nexport function updateBeliefs(\n beliefs: TaskBelief[],\n results: Record<string, number>,\n): TaskBelief[] {\n return beliefs.map(belief => {\n const score = results[belief.taskId];\n if (score === undefined) return belief; // task wasn't evaluated this round\n\n if (score >= 70) {\n return { ...belief, alpha: belief.alpha + 1 };\n } else {\n return { ...belief, beta: belief.beta + 1 };\n }\n });\n}\n\n/**\n * Load persisted beliefs from disk.\n * Returns null if no beliefs file exists.\n */\nexport async function loadBeliefs(workspacePath: string): Promise<TaskBelief[] | null> {\n const beliefsPath = path.join(workspacePath, 'task-beliefs.json');\n try {\n const content = await fs.readFile(beliefsPath, 'utf-8');\n const parsed = JSON.parse(content) as unknown;\n if (!Array.isArray(parsed)) return null;\n // Validate structure\n for (const entry of parsed) {\n if (\n typeof entry !== 'object' || entry === null ||\n typeof (entry as Record<string, unknown>).taskId !== 'string' ||\n typeof (entry as Record<string, unknown>).alpha !== 'number' ||\n typeof (entry as Record<string, unknown>).beta !== 'number'\n ) {\n return null;\n }\n }\n return parsed as TaskBelief[];\n } catch {\n return null;\n }\n}\n\n/**\n * Persist beliefs to disk.\n */\nexport async function saveBeliefs(workspacePath: string, beliefs: TaskBelief[]): Promise<void> {\n const beliefsPath = path.join(workspacePath, 'task-beliefs.json');\n await fs.mkdir(path.dirname(beliefsPath), { recursive: true });\n await fs.writeFile(beliefsPath, JSON.stringify(beliefs, null, 2), 'utf-8');\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { HarnessIR } from '../ir/types.js';\n\n/**\n * Metrics capturing the complexity of a harness directory.\n */\nexport interface ComplexityMetrics {\n totalLines: number; // total lines across all harness files\n totalFiles: number; // number of files in harness\n totalSections: number; // number of ## sections in CLAUDE.md\n totalRules: number; // number of files in rules/\n totalCommands: number; // number of files in commands/\n diffFromBaseline: number; // character-level diff ratio (normalized 0-1)\n}\n\n/**\n * Measure the complexity of a harness directory.\n *\n * Counts total lines, files, CLAUDE.md sections, rules/ files, and commands/ files.\n * The diffFromBaseline field is set to 0 here — use computeComplexityCost for comparison.\n */\nexport async function measureComplexity(harnessPath: string): Promise<ComplexityMetrics> {\n let totalLines = 0;\n let totalFiles = 0;\n let totalSections = 0;\n let totalRules = 0;\n let totalCommands = 0;\n\n const allContent = await readAllFilesRecursive(harnessPath);\n\n for (const [relativePath, content] of Object.entries(allContent)) {\n totalFiles++;\n totalLines += content.split('\\n').length;\n\n // Count ## sections in CLAUDE.md\n if (relativePath === 'CLAUDE.md') {\n const sectionMatches = content.match(/^##\\s/gm);\n totalSections = sectionMatches ? sectionMatches.length : 0;\n }\n\n // Count rules/ and commands/ files\n if (relativePath.startsWith('rules/') || relativePath.startsWith('rules\\\\')) {\n totalRules++;\n }\n if (relativePath.startsWith('commands/') || relativePath.startsWith('commands\\\\')) {\n totalCommands++;\n }\n }\n\n return {\n totalLines,\n totalFiles,\n totalSections,\n totalRules,\n totalCommands,\n diffFromBaseline: 0,\n };\n}\n\n/**\n * Measure the complexity of a harness from its in-memory IR representation.\n *\n * This is the IR-native counterpart to `measureComplexity(harnessPath)`.\n * It avoids disk I/O by computing metrics directly from the HarnessIR tree.\n *\n * Counts:\n * - `totalSections`: number of sections in the IR\n * - `totalRules`: number of rule nodes\n * - `totalCommands`: number of command nodes\n * - `totalFiles`: total count of all renderable nodes (sections count as 1 for\n * CLAUDE.md, plus commands, rules, agents, skills, docs, hooks, settings if\n * non-empty, mcp if servers exist)\n * - `totalLines`: sum of content line counts across all content-bearing nodes\n * - `diffFromBaseline`: always 0 (set externally if needed)\n */\nexport function measureComplexityFromIR(ir: HarnessIR): ComplexityMetrics {\n const totalSections = ir.sections.length;\n const totalRules = ir.rules.length;\n const totalCommands = ir.commands.length;\n\n // Count total files: each node type contributes its count\n let totalFiles = 0;\n\n // CLAUDE.md counts as 1 file if there are sections or a name\n if (ir.sections.length > 0 || ir.meta.name) {\n totalFiles += 1;\n }\n\n totalFiles += ir.commands.length;\n totalFiles += ir.rules.length;\n totalFiles += ir.agents.length;\n totalFiles += ir.skills.length;\n totalFiles += ir.docs.length;\n totalFiles += ir.hooks.length;\n\n // settings.json counts as 1 file if it has meaningful content\n const hasSettings =\n ir.settings.statusLine !== undefined ||\n (ir.settings.denyPatterns !== undefined && ir.settings.denyPatterns.length > 0) ||\n Object.keys(ir.settings.raw).length > 0 ||\n Object.values(ir.settings.hooks).some(\n (entries) => entries !== undefined && entries.length > 0,\n );\n if (hasSettings) {\n totalFiles += 1;\n }\n\n // .mcp.json counts as 1 file if servers exist\n if (ir.mcpServers.length > 0) {\n totalFiles += 1;\n }\n\n // Count total lines across all content-bearing nodes\n let totalLines = 0;\n for (const section of ir.sections) {\n totalLines += countLines(section.content);\n }\n for (const cmd of ir.commands) {\n totalLines += countLines(cmd.content);\n }\n for (const rule of ir.rules) {\n totalLines += countLines(rule.content);\n }\n for (const agent of ir.agents) {\n totalLines += countLines(agent.content);\n }\n for (const skill of ir.skills) {\n totalLines += countLines(skill.content);\n }\n for (const doc of ir.docs) {\n totalLines += countLines(doc.content);\n }\n for (const hook of ir.hooks) {\n totalLines += countLines(hook.content);\n }\n\n return {\n totalLines,\n totalFiles,\n totalSections,\n totalRules,\n totalCommands,\n diffFromBaseline: 0,\n };\n}\n\n/**\n * Count the number of lines in a content string.\n * An empty string has 0 lines. A non-empty string has at least 1.\n */\nfunction countLines(content: string): number {\n if (!content) return 0;\n return content.split('\\n').length;\n}\n\n/**\n * Compute a weighted complexity cost between current and baseline harness metrics.\n *\n * Cost components:\n * - Lines added beyond baseline: +0.3 per line (normalized by baseline)\n * - Files added beyond baseline: +5.0 per file (normalized by baseline)\n * - Net character diff ratio (0 = identical, 1 = completely rewritten)\n *\n * Returns a non-negative number. A return of 0 means identical to baseline.\n * Can return negative values when the current harness is simpler (complexity bonus).\n */\nexport function computeComplexityCost(\n current: ComplexityMetrics,\n baseline: ComplexityMetrics,\n): number {\n // Line cost: normalized by baseline size (capped at a minimum of 1 to avoid division by zero)\n const baselineLines = Math.max(baseline.totalLines, 1);\n const lineDelta = (current.totalLines - baseline.totalLines) / baselineLines;\n const lineCost = lineDelta * 0.3;\n\n // File cost: each added file is expensive\n const baselineFiles = Math.max(baseline.totalFiles, 1);\n const fileDelta = (current.totalFiles - baseline.totalFiles) / baselineFiles;\n const fileCost = fileDelta * 5.0;\n\n // Diff ratio is stored in current.diffFromBaseline if pre-computed\n const diffCost = current.diffFromBaseline;\n\n return lineCost + fileCost + diffCost;\n}\n\n/**\n * Apply KL penalty to a raw score.\n *\n * effective_score = rawScore - lambda * complexityCost * 100\n *\n * When lambda = 0, returns rawScore unchanged (regularization disabled).\n *\n * @param rawScore - The raw aggregate score (0-100)\n * @param complexityCost - Complexity cost from computeComplexityCost\n * @param lambda - Regularization strength (default 0.1)\n * @returns Penalized score\n */\nexport function applyKLPenalty(\n rawScore: number,\n complexityCost: number,\n lambda: number,\n): number {\n if (lambda === 0) return rawScore;\n return rawScore - lambda * complexityCost * 100;\n}\n\n/**\n * Compute a character-level diff ratio between two harness directories.\n * Returns a value in [0, 1] where 0 means identical content and 1 means completely different.\n */\nexport async function computeDiffRatio(\n currentPath: string,\n baselinePath: string,\n): Promise<number> {\n const currentFiles = await readAllFilesRecursive(currentPath);\n const baselineFiles = await readAllFilesRecursive(baselinePath);\n\n const allPaths = new Set([\n ...Object.keys(currentFiles),\n ...Object.keys(baselineFiles),\n ]);\n\n if (allPaths.size === 0) return 0;\n\n let totalChars = 0;\n let diffChars = 0;\n\n for (const filePath of allPaths) {\n const currentContent = currentFiles[filePath] ?? '';\n const baselineContent = baselineFiles[filePath] ?? '';\n\n const maxLen = Math.max(currentContent.length, baselineContent.length);\n totalChars += maxLen;\n\n if (currentContent !== baselineContent) {\n // Simple character-level diff: count differing characters\n const minLen = Math.min(currentContent.length, baselineContent.length);\n let charDiffs = Math.abs(currentContent.length - baselineContent.length);\n for (let i = 0; i < minLen; i++) {\n if (currentContent[i] !== baselineContent[i]) charDiffs++;\n }\n diffChars += charDiffs;\n }\n }\n\n return totalChars > 0 ? diffChars / totalChars : 0;\n}\n\n/**\n * Recursively read all files in a directory into a map of relative path -> content.\n */\nasync function readAllFilesRecursive(dir: string): Promise<Record<string, string>> {\n const result: Record<string, string> = {};\n\n async function walk(current: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const fullPath = path.join(current, entry.name);\n const relativePath = path.relative(dir, fullPath);\n if (entry.isDirectory()) {\n await walk(fullPath);\n } else {\n try {\n result[relativePath] = await fs.readFile(fullPath, 'utf-8');\n } catch {\n // Skip unreadable files\n }\n }\n }\n }\n\n await walk(dir);\n return result;\n}\n","/**\n * IR-Aware Targeted Re-evaluation — maps IR mutations to harness aspects\n * and tasks to aspects, enabling the loop to skip tasks unaffected by\n * the current iteration's mutations.\n */\n\nimport type { IRMutation } from '../ir/types.js';\nimport type { Task, EvalTemplate } from './types.js';\n\n/** Semantic aspects of a harness that mutations can affect. */\nexport type HarnessAspect =\n | 'conventions'\n | 'commands'\n | 'rules'\n | 'agents'\n | 'settings'\n | 'mcp'\n | 'architecture'\n | 'verification'\n | 'general';\n\n/** Map a single IR mutation to the harness aspect it affects. */\nfunction mutationToAspect(mutation: IRMutation): HarnessAspect {\n switch (mutation.type) {\n case 'update_section': {\n const id = mutation.sectionId;\n if (id === 'conventions' || id === 'gotchas' || id === 'debugging' || id === 'git') return 'conventions';\n if (id === 'commands' || id === 'custom-key-commands') return 'commands';\n if (id === 'verification') return 'verification';\n if (id === 'architecture') return 'architecture';\n return 'general';\n }\n case 'add_section': {\n const id = mutation.section.id;\n if (id === 'conventions' || id === 'gotchas' || id === 'debugging' || id === 'git') return 'conventions';\n if (id === 'commands' || id === 'custom-key-commands') return 'commands';\n if (id === 'verification') return 'verification';\n if (id === 'architecture') return 'architecture';\n return 'general';\n }\n case 'remove_section':\n case 'reorder_section':\n return 'general';\n case 'add_command':\n case 'update_command':\n case 'remove_command':\n return 'commands';\n case 'add_rule':\n case 'update_rule':\n case 'remove_rule':\n return 'rules';\n case 'add_agent':\n case 'update_agent':\n case 'remove_agent':\n return 'agents';\n case 'add_mcp_server':\n case 'remove_mcp_server':\n return 'mcp';\n case 'update_settings':\n return 'settings';\n case 'raw_text':\n return 'general';\n }\n}\n\n/** Map which eval templates depend on which harness aspects. */\nconst TEMPLATE_ASPECTS: Record<EvalTemplate, HarnessAspect[]> = {\n 'convention-adherence': ['conventions', 'rules'],\n 'workflow-compliance': ['commands', 'verification'],\n 'rule-compliance': ['rules'],\n 'intent-routing': ['settings'],\n 'add-feature': ['general'],\n 'fix-bug': ['general'],\n 'refactor': ['architecture', 'conventions'],\n 'test-writing': ['verification', 'commands'],\n 'config-change': ['settings', 'mcp'],\n 'documentation': ['general'],\n};\n\n/**\n * Map IR mutations to the harness aspects they affect.\n */\nexport function mutationsToAspects(mutations: IRMutation[]): Set<HarnessAspect> {\n const aspects = new Set<HarnessAspect>();\n for (const m of mutations) {\n aspects.add(mutationToAspect(m));\n }\n return aspects;\n}\n\n/**\n * Determine which harness aspects a task depends on based on its template.\n */\nexport function taskDependsOnAspects(task: Task): Set<HarnessAspect> {\n const aspects = TEMPLATE_ASPECTS[task.template];\n return new Set(aspects ?? ['general']);\n}\n\n/**\n * Determine if a task should be re-evaluated given the changed aspects.\n */\nexport function shouldReEvaluate(task: Task, changedAspects: Set<HarnessAspect>): boolean {\n if (changedAspects.has('general')) return true;\n if (changedAspects.size === 0) return false;\n\n const taskAspects = taskDependsOnAspects(task);\n if (taskAspects.has('general')) return true;\n\n for (const aspect of taskAspects) {\n if (changedAspects.has(aspect)) return true;\n }\n return false;\n}\n\n/**\n * Filter a task list to only tasks that need re-evaluation.\n */\nexport function filterTasksByAspects(tasks: Task[], changedAspects: Set<HarnessAspect>): Task[] {\n return tasks.filter(t => shouldReEvaluate(t, changedAspects));\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { evaluateAll } from './runner.js';\nimport { propose } from './proposer.js';\nimport { applyMutations } from './mutator.js';\nimport { writeIterationLog } from './trace.js';\nimport { copyDir } from './baseline.js';\nimport { initBeliefs, sampleThompson, updateBeliefs, loadBeliefs, saveBeliefs } from './sampling.js';\nimport { measureComplexity, measureComplexityFromIR, computeComplexityCost, applyKLPenalty, computeDiffRatio } from './regularization.js';\nimport { parseHarness } from '../ir/parser.js';\nimport { translateMutations } from '../ir/translate.js';\nimport { filterTasksByAspects, mutationsToAspects } from './targeting.js';\nimport type { HarnessAspect } from './targeting.js';\nimport type { HarnessIR } from '../ir/types.js';\nimport type { TaskBelief } from './sampling.js';\nimport type { ComplexityMetrics } from './regularization.js';\nimport type { KairnConfig } from '../types.js';\nimport type {\n Task,\n Score,\n EvolveConfig,\n IterationLog,\n EvolveResult,\n LoopProgressEvent,\n} from './types.js';\n\n/**\n * Compute dynamic mutation cap based on iteration progress.\n * First 40% of iterations: full cap (exploration).\n * Last 60%: linearly decays to 1 (exploitation).\n */\nexport function computeMutationCap(iter: number, maxIterations: number, maxMutations: number): number {\n if (maxIterations <= 1) return maxMutations;\n const progress = iter / (maxIterations - 1); // 0.0 to 1.0\n if (progress <= 0.4) return maxMutations;\n // Linear decay from maxMutations at 40% to 1 at 100%\n const decayProgress = (progress - 0.4) / 0.6; // 0.0 to 1.0 within decay phase\n return Math.max(1, Math.round(maxMutations * (1 - decayProgress * (1 - 1 / maxMutations))));\n}\n\n/**\n * Run the evolution loop: evaluate -> diagnose -> mutate -> re-evaluate.\n *\n * Each iteration follows these steps:\n * 1. Evaluate all tasks against the current harness\n * 2. Check for regression — if score dropped below best, rollback\n * 3. Check for perfect score — exit early if 100%\n * 4. Propose mutations via the proposer LLM agent\n * 5. Apply mutations to create the next iteration's harness\n * 6. Log iteration results\n * 7. Advance to the next iteration\n *\n * @param workspacePath - Path to .kairn-evolve/ directory\n * @param tasks - Task definitions from tasks.yaml\n * @param kairnConfig - Kairn config with API key and model\n * @param evolveConfig - Evolution config with iterations, proposer model, etc.\n * @param onProgress - Optional callback for real-time progress updates\n * @returns Final evolution result with iteration history and best score\n */\nexport async function evolve(\n workspacePath: string,\n tasks: Task[],\n kairnConfig: KairnConfig,\n evolveConfig: EvolveConfig,\n onProgress?: (event: LoopProgressEvent) => void,\n): Promise<EvolveResult> {\n const history: IterationLog[] = [];\n let bestScore = -1;\n let bestIteration = 0;\n let baselineScore = 0;\n\n // Thompson Sampling: initialize or load beliefs\n const useThompson = evolveConfig.samplingStrategy === 'thompson' && evolveConfig.evalSampleSize > 0;\n let beliefs: TaskBelief[] = useThompson\n ? (await loadBeliefs(workspacePath) ?? initBeliefs(tasks))\n : [];\n\n // KL Regularization: measure baseline complexity\n const useKL = evolveConfig.klLambda > 0;\n let baselineComplexity: ComplexityMetrics | null = null;\n let baselineIR: HarnessIR | null = null;\n if (useKL) {\n const baselineHarness = path.join(workspacePath, 'iterations', '0', 'harness');\n try {\n baselineIR = await parseHarness(baselineHarness);\n baselineComplexity = measureComplexityFromIR(baselineIR);\n } catch {\n // IR parsing failed — fall back to file-based measurement\n try {\n baselineComplexity = await measureComplexity(baselineHarness);\n } catch {\n // Baseline not available yet — will be measured after iteration 0\n }\n }\n }\n\n // Targeted re-evaluation: track which harness aspects changed last iteration\n let lastChangedAspects: Set<HarnessAspect> | null = null;\n\n // Seeded RNG for Thompson Sampling (deterministic per-run, per-branch via rngSeed)\n let rngState = evolveConfig.rngSeed ?? 42;\n const rng = (): number => {\n rngState = (rngState * 1664525 + 1013904223) & 0xffffffff;\n return (rngState >>> 0) / 0x100000000;\n };\n\n for (let iter = 0; iter < evolveConfig.maxIterations; iter++) {\n const harnessPath = path.join(\n workspacePath,\n 'iterations',\n iter.toString(),\n 'harness',\n );\n\n // Verify harness exists for this iteration\n try {\n await fs.access(harnessPath);\n } catch {\n if (iter === 0) {\n throw new Error(\n 'No baseline harness found. Run `kairn evolve baseline` first.',\n );\n }\n break; // No more iterations to run\n }\n\n // 1. EVALUATE (with adaptive pruning on middle iterations)\n onProgress?.({ type: 'iteration-start', iteration: iter });\n\n const isFirstIter = iter === 0;\n const isLastIter = iter === evolveConfig.maxIterations - 1;\n const prevLog = history.length > 0 ? history[history.length - 1] : null;\n\n let tasksToRun = tasks;\n const carriedScores: Record<string, Score> = {};\n const threshold = evolveConfig.pruneThreshold;\n\n if (!isFirstIter && !isLastIter && prevLog) {\n tasksToRun = [];\n for (const task of tasks) {\n const prevScore = prevLog.taskResults[task.id];\n const prevValue = prevScore ? (prevScore.score ?? (prevScore.pass ? 100 : 0)) : 0;\n if (prevValue >= threshold) {\n carriedScores[task.id] = { pass: true, score: prevValue };\n onProgress?.({\n type: 'task-skipped',\n iteration: iter,\n taskId: task.id,\n message: `Skipped ${task.id} (scored ${prevValue.toFixed(0)}% >= ${threshold}% threshold)`,\n });\n } else {\n tasksToRun.push(task);\n }\n }\n\n // Targeted re-evaluation: skip tasks unaffected by last mutation\n if (lastChangedAspects !== null) {\n const targetedTasks = filterTasksByAspects(tasksToRun, lastChangedAspects);\n const skippedByTargeting = tasksToRun.filter(t => !targetedTasks.includes(t));\n for (const task of skippedByTargeting) {\n const prev = prevLog.taskResults[task.id];\n const prevVal = prev ? (prev.score ?? (prev.pass ? 100 : 0)) : 0;\n carriedScores[task.id] = { pass: prevVal >= 50, score: prevVal };\n onProgress?.({\n type: 'task-skipped',\n iteration: iter,\n taskId: task.id,\n message: `Skipped ${task.id} (unaffected by mutations)`,\n });\n }\n tasksToRun = targetedTasks;\n }\n\n // Mini-batch sampling: Thompson or uniform\n const sampleSize = evolveConfig.evalSampleSize;\n if (sampleSize > 0 && sampleSize < tasksToRun.length) {\n let sampled: Set<string>;\n\n if (useThompson) {\n // Thompson Sampling: select tasks proportional to uncertainty\n const relevantBeliefs = beliefs.filter(b => tasksToRun.some(t => t.id === b.taskId));\n const selectedIds = sampleThompson(relevantBeliefs, sampleSize, rng);\n sampled = new Set(selectedIds);\n } else {\n // Uniform: seeded shuffle (v2.5.2 behavior)\n const shuffled = [...tasksToRun].sort((a, b) => {\n const hashA = (iter * 31 + a.id.charCodeAt(0)) % 1000;\n const hashB = (iter * 31 + b.id.charCodeAt(0)) % 1000;\n return hashA - hashB;\n });\n sampled = new Set(shuffled.slice(0, sampleSize).map(t => t.id));\n }\n\n // Carry forward unsampled tasks\n for (const task of tasksToRun) {\n if (!sampled.has(task.id)) {\n const prev = prevLog.taskResults[task.id];\n const prevVal = prev ? (prev.score ?? (prev.pass ? 100 : 0)) : 0;\n carriedScores[task.id] = { pass: prevVal >= 50, score: prevVal };\n onProgress?.({\n type: 'task-skipped',\n iteration: iter,\n taskId: task.id,\n message: `Sampled out ${task.id} (${useThompson ? 'thompson' : 'uniform'} ${sampleSize}/${tasksToRun.length})`,\n });\n }\n }\n tasksToRun = tasksToRun.filter(t => sampled.has(t.id));\n }\n }\n\n const { results: evalResults, aggregate: evalAggregate } = await evaluateAll(\n tasksToRun,\n harnessPath,\n workspacePath,\n iter,\n kairnConfig,\n onProgress,\n evolveConfig.runsPerTask,\n evolveConfig.parallelTasks,\n );\n\n // Merge carried-forward scores with evaluated results\n const results = { ...carriedScores, ...evalResults };\n const allScores = Object.values(results);\n const total = allScores.reduce(\n (sum, s) => sum + (s.score ?? (s.pass ? 100 : 0)),\n 0,\n );\n const rawAggregate = allScores.length > 0 ? total / allScores.length : 0;\n\n // KL Regularization: penalize complexity drift\n let aggregate = rawAggregate;\n let iterComplexityCost: number | undefined;\n if (useKL && baselineComplexity) {\n let currentComplexity: ComplexityMetrics;\n try {\n const iterIR = await parseHarness(harnessPath);\n currentComplexity = measureComplexityFromIR(iterIR);\n } catch {\n currentComplexity = await measureComplexity(harnessPath);\n }\n const diffRatio = await computeDiffRatio(\n harnessPath,\n path.join(workspacePath, 'iterations', '0', 'harness'),\n );\n currentComplexity.diffFromBaseline = diffRatio;\n iterComplexityCost = computeComplexityCost(currentComplexity, baselineComplexity);\n aggregate = applyKLPenalty(rawAggregate, iterComplexityCost, evolveConfig.klLambda);\n }\n\n // Thompson Sampling: update beliefs with EVALUATED results only\n // Carried-forward scores are stale — treating them as fresh observations\n // makes the sampler artificially overconfident and freezes beliefs.\n if (useThompson) {\n const scoreMap: Record<string, number> = {};\n for (const [taskId, score] of Object.entries(evalResults)) {\n scoreMap[taskId] = score.score ?? (score.pass ? 100 : 0);\n }\n beliefs = updateBeliefs(beliefs, scoreMap);\n await saveBeliefs(workspacePath, beliefs);\n }\n\n onProgress?.({ type: 'iteration-scored', iteration: iter, score: aggregate });\n\n if (iter === 0) {\n baselineScore = aggregate;\n // Measure baseline complexity if not yet available\n if (useKL && !baselineComplexity) {\n try {\n baselineIR = await parseHarness(harnessPath);\n baselineComplexity = measureComplexityFromIR(baselineIR);\n } catch {\n baselineComplexity = await measureComplexity(harnessPath);\n }\n }\n }\n\n // 2. ROLLBACK CHECK (aggregate regression OR per-task drop exceeding maxTaskDrop)\n let shouldRollback = iter > 0 && aggregate < bestScore;\n let rollbackMessage = shouldRollback\n ? `Regression: ${aggregate.toFixed(1)}% < ${bestScore.toFixed(1)}%. Rolling back.`\n : '';\n\n // Compare per-task scores against the best iteration (not previous — previous may be a rejected rollback)\n const bestLog = history.find(h => h.iteration === bestIteration);\n if (iter > 0 && !shouldRollback && bestLog) {\n for (const [taskId, score] of Object.entries(results)) {\n const currValue = score.score ?? (score.pass ? 100 : 0);\n const bestTaskScore = bestLog.taskResults[taskId];\n const bestValue = bestTaskScore ? (bestTaskScore.score ?? (bestTaskScore.pass ? 100 : 0)) : currValue;\n const drop = bestValue - currValue;\n if (drop > evolveConfig.maxTaskDrop) {\n shouldRollback = true;\n rollbackMessage = `Task ${taskId} dropped ${drop.toFixed(0)} points (${bestValue.toFixed(0)}% → ${currValue.toFixed(0)}%). Rolling back.`;\n onProgress?.({\n type: 'task-regression',\n iteration: iter,\n taskId,\n score: currValue,\n message: `dropped ${drop.toFixed(0)} points (limit: ${evolveConfig.maxTaskDrop})`,\n });\n break;\n }\n }\n }\n\n if (shouldRollback) {\n onProgress?.({\n type: 'rollback',\n iteration: iter,\n score: aggregate,\n message: rollbackMessage,\n });\n\n // Log the regression\n const rollbackLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal: null,\n diffPatch: null,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, rollbackLog);\n history.push(rollbackLog);\n\n // Instead of just copying the best harness unchanged, propose NEW mutations\n // on the best harness so the next iteration has something different to evaluate.\n const bestHarnessPath = path.join(\n workspacePath,\n 'iterations',\n bestIteration.toString(),\n 'harness',\n );\n\n if (iter + 1 < evolveConfig.maxIterations) {\n onProgress?.({ type: 'proposing', iteration: iter, message: 'Proposing new mutations after rollback' });\n try {\n let rollbackProposal = await propose(\n iter,\n workspacePath,\n bestHarnessPath,\n history,\n tasks,\n kairnConfig,\n evolveConfig.proposerModel,\n );\n const rollbackCap = computeMutationCap(iter, evolveConfig.maxIterations, evolveConfig.maxMutationsPerIteration);\n if (rollbackProposal.mutations.length > rollbackCap) {\n rollbackProposal = {\n ...rollbackProposal,\n mutations: rollbackProposal.mutations.slice(0, rollbackCap),\n };\n }\n const nextIterDir = path.join(workspacePath, 'iterations', (iter + 1).toString());\n await applyMutations(bestHarnessPath, nextIterDir, rollbackProposal.mutations);\n // Compute changed aspects for targeted re-evaluation\n try {\n const rollbackIR = await parseHarness(bestHarnessPath);\n const irMuts = translateMutations(rollbackProposal.mutations, rollbackIR);\n lastChangedAspects = mutationsToAspects(irMuts);\n } catch {\n lastChangedAspects = null;\n }\n onProgress?.({\n type: 'mutations-applied',\n iteration: iter,\n mutationCount: rollbackProposal.mutations.length,\n });\n } catch {\n // Proposer or mutation failed — fall back to copying best harness unchanged\n const nextIterDir = path.join(workspacePath, 'iterations', (iter + 1).toString());\n await copyDir(bestHarnessPath, path.join(nextIterDir, 'harness'));\n }\n }\n continue;\n }\n\n // 3. UPDATE BEST\n bestScore = aggregate;\n bestIteration = iter;\n\n // 4. PERFECT SCORE CHECK\n if (aggregate >= 100) {\n onProgress?.({ type: 'perfect-score', iteration: iter, score: aggregate });\n const perfectLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal: null,\n diffPatch: null,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, perfectLog);\n history.push(perfectLog);\n break;\n }\n\n // 5. PROPOSE (skip on last iteration — no point mutating if we won't eval)\n if (iter === evolveConfig.maxIterations - 1) {\n const finalLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal: null,\n diffPatch: null,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, finalLog);\n history.push(finalLog);\n break;\n }\n\n onProgress?.({ type: 'proposing', iteration: iter });\n let proposal;\n try {\n proposal = await propose(\n iter,\n workspacePath,\n harnessPath,\n history,\n tasks,\n kairnConfig,\n evolveConfig.proposerModel,\n );\n // Enforce mutation cap\n const iterCap = computeMutationCap(iter, evolveConfig.maxIterations, evolveConfig.maxMutationsPerIteration);\n if (proposal.mutations.length > iterCap) {\n proposal = {\n ...proposal,\n mutations: proposal.mutations.slice(0, iterCap),\n };\n }\n } catch (err) {\n // Proposer failed — log the error and copy current harness forward unchanged\n const errMsg = err instanceof Error ? err.message : String(err);\n onProgress?.({\n type: 'proposer-error',\n iteration: iter,\n message: `Proposer failed: ${errMsg}`,\n });\n const nextIterDir = path.join(\n workspacePath,\n 'iterations',\n (iter + 1).toString(),\n );\n await copyDir(harnessPath, path.join(nextIterDir, 'harness'));\n const skipLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal: null,\n diffPatch: null,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, skipLog);\n history.push(skipLog);\n continue;\n }\n\n // 6. APPLY MUTATIONS\n const nextIterDir = path.join(\n workspacePath,\n 'iterations',\n (iter + 1).toString(),\n );\n let diffPatch = '';\n try {\n const mutationResult = await applyMutations(\n harnessPath,\n nextIterDir,\n proposal.mutations,\n );\n diffPatch = mutationResult.diffPatch;\n // Compute changed aspects for targeted re-evaluation\n try {\n const currentIR = await parseHarness(harnessPath);\n const irMuts = translateMutations(proposal.mutations, currentIR);\n lastChangedAspects = mutationsToAspects(irMuts);\n } catch {\n lastChangedAspects = null;\n }\n } catch {\n // Mutation failed — copy current harness forward unchanged\n await copyDir(harnessPath, path.join(nextIterDir, 'harness'));\n lastChangedAspects = null;\n }\n\n onProgress?.({\n type: 'mutations-applied',\n iteration: iter,\n mutationCount: proposal.mutations.length,\n });\n\n // 7. LOG\n const iterLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal,\n diffPatch,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, iterLog);\n history.push(iterLog);\n }\n\n // PRINCIPAL PROPOSER: after normal loop, synthesize the best harness from all learnings\n if (evolveConfig.usePrincipal && history.length >= 2) {\n onProgress?.({ type: 'proposing', iteration: history.length, message: 'Principal Proposer synthesizing final harness' });\n\n const baselineHarnessPath = path.join(workspacePath, 'iterations', '0', 'harness');\n try {\n const principalProposal = await propose(\n history.length,\n workspacePath,\n baselineHarnessPath,\n history,\n tasks,\n kairnConfig,\n evolveConfig.proposerModel,\n );\n\n if (principalProposal.mutations.length > evolveConfig.maxMutationsPerIteration) {\n principalProposal.mutations = principalProposal.mutations.slice(0, evolveConfig.maxMutationsPerIteration);\n }\n\n const principalIterNum = history.length;\n const principalIterDir = path.join(workspacePath, 'iterations', principalIterNum.toString());\n const mutResult = await applyMutations(baselineHarnessPath, principalIterDir, principalProposal.mutations);\n\n onProgress?.({ type: 'iteration-start', iteration: principalIterNum });\n const { results: principalResults, aggregate: principalAggregate } = await evaluateAll(\n tasks,\n mutResult.newHarnessPath,\n workspacePath,\n principalIterNum,\n kairnConfig,\n onProgress,\n evolveConfig.runsPerTask,\n evolveConfig.parallelTasks,\n );\n onProgress?.({ type: 'iteration-scored', iteration: principalIterNum, score: principalAggregate });\n\n const principalLog: IterationLog = {\n iteration: principalIterNum,\n score: principalAggregate,\n taskResults: principalResults,\n proposal: principalProposal,\n diffPatch: mutResult.diffPatch,\n timestamp: new Date().toISOString(),\n };\n await writeIterationLog(workspacePath, principalLog);\n history.push(principalLog);\n\n if (principalAggregate > bestScore) {\n bestScore = principalAggregate;\n bestIteration = principalIterNum;\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n onProgress?.({ type: 'proposer-error', iteration: history.length, message: `Principal failed: ${errMsg}` });\n }\n }\n\n // Save run summary to proposer memory for cross-run learning\n try {\n const { buildRunSummary, saveRunSummary } = await import('./memory.js');\n const summary = buildRunSummary(history, baselineScore, bestScore);\n await saveRunSummary(workspacePath, summary);\n } catch {\n // Memory save is non-critical — don't fail the run\n }\n\n onProgress?.({\n type: 'complete',\n iteration: history.length > 0 ? history.length - 1 : 0,\n score: bestScore,\n });\n\n return {\n iterations: history,\n bestIteration,\n bestScore,\n baselineScore,\n };\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { callLLM } from '../llm.js';\nimport { readHarnessFiles } from './proposer.js';\nimport { parseProposerResponse } from './proposer.js';\nimport { applyMutations } from './mutator.js';\nimport { evaluateAll } from './runner.js';\nimport { copyDir } from './baseline.js';\nimport type { KairnConfig } from '../types.js';\nimport type {\n Task,\n Score,\n EvolveConfig,\n Mutation,\n IterationLog,\n} from './types.js';\nimport type { BranchResult } from './population.js';\nimport type { TaskBelief } from './sampling.js';\n\n/**\n * Context passed to the Meta-Principal for cross-branch synthesis.\n */\nexport interface SynthesisContext {\n branches: BranchResult[];\n tasks: Task[];\n baselineHarnessPath: string;\n}\n\n/**\n * Build the system prompt for the Meta-Principal.\n */\nfunction buildMetaPrincipalSystemPrompt(numBranches: number): string {\n return `You are reviewing the COMPLETE results of ${numBranches} independent evolution runs.\nEach branch explored different mutations and saw different task subsets.\n\nYour job is SYNTHESIS, not iteration:\n1. Identify mutations that helped across multiple branches (high-confidence wins)\n2. Identify mutations that helped in one branch but weren't tested in others (potential wins)\n3. Identify mutations that consistently hurt scores (high-confidence losses)\n4. Resolve conflicts: if Branch 0 says \"add verbose error rules\" but Branch 2 says \"remove verbose rules\", use the per-task evidence to decide\n\nApply your selected mutations to the BASELINE harness (not any branch's final harness).\nThis ensures a clean synthesis — no accumulated branch-specific artifacts.\n\n## Output Format\nReturn a JSON object:\n{\n \"reasoning\": \"Your synthesis analysis — which mutations from which branches, why...\",\n \"mutations\": [\n { \"file\": \"CLAUDE.md\", \"action\": \"replace\", \"old_text\": \"...\", \"new_text\": \"...\", \"rationale\": \"...\" }\n ],\n \"expected_impact\": { \"task-id\": \"+N% — explanation\" }\n}\n\n## Rules\n- Apply mutations to the BASELINE, not any branch's final harness\n- Prefer mutations with cross-branch evidence over single-branch evidence\n- If two mutations conflict, choose the one with stronger per-task evidence\n- Keep it concise: harness bloat defeats the purpose\n\nReturn ONLY valid JSON.`;\n}\n\n/**\n * Build the user message for the Meta-Principal with all branch evidence.\n *\n * Includes: iteration logs, per-task score matrices, Thompson beliefs,\n * complexity metrics, and the baseline harness.\n */\nexport function buildSynthesisPrompt(context: SynthesisContext): string {\n const parts: string[] = [];\n\n // Section 1: Baseline harness summary\n parts.push('## Baseline Harness\\n');\n parts.push(`Path: ${context.baselineHarnessPath}\\n`);\n\n // Section 2: Per-branch results\n for (const branch of context.branches) {\n parts.push(`\\n## Branch ${branch.branchId}\\n`);\n parts.push(`Best Score: ${branch.result.bestScore.toFixed(1)}% (iteration ${branch.result.bestIteration})\\n`);\n parts.push(`Baseline Score: ${branch.result.baselineScore.toFixed(1)}%\\n`);\n\n // Iteration logs with proposals\n for (const log of branch.result.iterations) {\n parts.push(`\\n### Branch ${branch.branchId} — Iteration ${log.iteration} (score: ${log.score.toFixed(1)}%)\\n`);\n\n // Raw vs penalized score\n if (log.rawScore !== undefined) {\n parts.push(`Raw score: ${log.rawScore.toFixed(1)}%, Complexity cost: ${log.complexityCost?.toFixed(3) ?? 'N/A'}\\n`);\n }\n\n // Task results\n const taskLines = Object.entries(log.taskResults)\n .map(([id, s]) => ` - ${id}: ${s.score !== undefined ? s.score : (s.pass ? 100 : 0)}%`)\n .join('\\n');\n parts.push(`Task results:\\n${taskLines}\\n`);\n\n // Proposal\n if (log.proposal) {\n parts.push(`Proposal reasoning: ${log.proposal.reasoning}\\n`);\n parts.push(`Mutations (${log.proposal.mutations.length}):\\n`);\n for (const m of log.proposal.mutations) {\n parts.push(` - ${m.action} ${m.file}: ${m.rationale}\\n`);\n }\n } else {\n parts.push('(No proposal — baseline or rollback)\\n');\n }\n }\n\n // Thompson beliefs\n if (branch.beliefs.length > 0) {\n parts.push(`\\nThompson Beliefs (Branch ${branch.branchId}):\\n`);\n for (const belief of branch.beliefs) {\n const mean = belief.alpha / (belief.alpha + belief.beta);\n const uncertainty = 1 / (belief.alpha + belief.beta);\n parts.push(` - ${belief.taskId}: mean=${mean.toFixed(2)}, uncertainty=${uncertainty.toFixed(3)} (α=${belief.alpha}, β=${belief.beta})\\n`);\n }\n }\n }\n\n // Section 3: Cross-branch score matrix\n parts.push('\\n## Cross-Branch Score Matrix\\n');\n parts.push('Task | ' + context.branches.map(b => `Branch ${b.branchId}`).join(' | ') + '\\n');\n\n const allTaskIds = new Set<string>();\n for (const branch of context.branches) {\n const lastIter = branch.result.iterations[branch.result.iterations.length - 1];\n if (lastIter) {\n for (const taskId of Object.keys(lastIter.taskResults)) {\n allTaskIds.add(taskId);\n }\n }\n }\n\n for (const taskId of [...allTaskIds].sort()) {\n const scores = context.branches.map(b => {\n const bestIter = b.result.iterations.find(i => i.iteration === b.result.bestIteration);\n const score = bestIter?.taskResults[taskId];\n return score ? (score.score ?? (score.pass ? 100 : 0)).toFixed(0) + '%' : 'N/A';\n });\n parts.push(`${taskId} | ${scores.join(' | ')}\\n`);\n }\n\n // Section 4: Task definitions (description only — no rubrics)\n parts.push('\\n## Task Definitions\\n');\n for (const task of context.tasks) {\n parts.push(`- ${task.id} (${task.template}): ${task.description}\\n`);\n }\n\n return parts.join('');\n}\n\n/**\n * Call the Meta-Principal LLM to synthesize the best harness from all branches.\n *\n * @param context - All branch results, tasks, and baseline path\n * @param kairnConfig - Kairn config (API key, model)\n * @param evolveConfig - Evolution config (proposer model)\n * @returns Synthesized mutations and reasoning\n */\nexport async function synthesizeBranches(\n context: SynthesisContext,\n kairnConfig: KairnConfig,\n evolveConfig: EvolveConfig,\n): Promise<{ mutations: Mutation[]; reasoning: string }> {\n const userMessage = buildSynthesisPrompt(context);\n const systemPrompt = buildMetaPrincipalSystemPrompt(context.branches.length);\n\n // Read baseline harness to include in context\n const harnessFiles = await readHarnessFiles(context.baselineHarnessPath);\n const harnessSection = Object.entries(harnessFiles)\n .map(([file, content]) => `### ${file}\\n\\`\\`\\`\\n${content}\\n\\`\\`\\``)\n .join('\\n\\n');\n\n const fullMessage = `## Current Baseline Harness Files\\n\\n${harnessSection}\\n\\n${userMessage}`;\n\n const proposerConfig: KairnConfig = { ...kairnConfig, model: evolveConfig.proposerModel };\n const response = await callLLM(proposerConfig, fullMessage, {\n systemPrompt,\n maxTokens: 8192,\n jsonMode: true,\n cacheControl: true,\n });\n\n const proposal = parseProposerResponse(response);\n return {\n mutations: proposal.mutations,\n reasoning: proposal.reasoning,\n };\n}\n\n/**\n * Evaluate the synthesized harness against ALL tasks (full suite, no sampling).\n *\n * @param synthesisHarnessPath - Path to the synthesized harness\n * @param tasks - All task definitions\n * @param workspacePath - Workspace directory for traces\n * @param kairnConfig - Kairn config\n * @returns Evaluation results and aggregate score\n */\nexport async function evaluateSynthesis(\n synthesisHarnessPath: string,\n tasks: Task[],\n workspacePath: string,\n kairnConfig: KairnConfig,\n): Promise<{ results: Record<string, Score>; aggregate: number }> {\n const synthesisIterNum = 999; // Distinguishes synthesis eval from branch evals\n return evaluateAll(\n tasks,\n synthesisHarnessPath,\n workspacePath,\n synthesisIterNum,\n kairnConfig,\n undefined,\n 1, // single run per task for synthesis\n 2, // moderate parallelism\n );\n}\n\n/**\n * Run the full synthesis pipeline: build prompt, call LLM, apply mutations,\n * evaluate, and compare against the best branch.\n *\n * @param context - All branch results\n * @param kairnConfig - Kairn config\n * @param evolveConfig - Evolution config\n * @param workspacePath - Root workspace for synthesis output\n * @returns Synthesis evaluation result, or null if synthesis failed\n */\nexport async function runSynthesis(\n context: SynthesisContext,\n kairnConfig: KairnConfig,\n evolveConfig: EvolveConfig,\n workspacePath: string,\n): Promise<{ result: { results: Record<string, Score>; aggregate: number }; mutations: Mutation[]; reasoning: string } | null> {\n try {\n // 1. Call Meta-Principal\n const { mutations, reasoning } = await synthesizeBranches(context, kairnConfig, evolveConfig);\n\n if (mutations.length === 0) {\n return null;\n }\n\n // 2. Apply mutations to baseline\n const synthesisDir = path.join(workspacePath, 'synthesis');\n const { newHarnessPath } = await applyMutations(\n context.baselineHarnessPath,\n synthesisDir,\n mutations,\n );\n\n // 3. Evaluate against all tasks\n const evalResult = await evaluateSynthesis(\n newHarnessPath,\n context.tasks,\n workspacePath,\n kairnConfig,\n );\n\n return { result: evalResult, mutations, reasoning };\n } catch {\n return null;\n }\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport { evolve } from './loop.js';\nimport { runSynthesis } from './synthesis.js';\nimport type { KairnConfig } from '../types.js';\nimport type {\n Task,\n EvolveConfig,\n EvolveResult,\n LoopProgressEvent,\n} from './types.js';\nimport type { TaskBelief } from './sampling.js';\n\n/**\n * Configuration for a single PBT branch.\n */\nexport interface BranchConfig {\n branchId: number;\n seed: number; // RNG seed for Thompson Sampling\n workspacePath: string; // .kairn-evolve/branches/{N}/\n}\n\n/**\n * Result from a single PBT branch.\n */\nexport interface BranchResult {\n branchId: number;\n result: EvolveResult;\n finalHarnessPath: string;\n beliefs: TaskBelief[]; // final Thompson beliefs from this branch\n}\n\n/**\n * Aggregate result from a PBT run (all branches + optional synthesis).\n */\nexport interface PBTResult {\n branches: BranchResult[];\n synthesizedResult?: EvolveResult; // after Meta-Principal (Step 4)\n bestBranch: number;\n bestScore: number;\n}\n\n/**\n * Initialize branch workspaces by copying the baseline harness and config into\n * each branch directory.\n *\n * Creates: .kairn-evolve/branches/{0..N-1}/ with iterations/0/harness/ and tasks.yaml\n *\n * @param workspacePath - Root .kairn-evolve/ directory\n * @param baselinePath - Path to baseline harness (usually .kairn-evolve/baseline/)\n * @param numBranches - Number of parallel branches to create\n * @returns Array of BranchConfig with unique seeds\n */\nexport async function initBranches(\n workspacePath: string,\n baselinePath: string,\n numBranches: number,\n): Promise<BranchConfig[]> {\n const branchesDir = path.join(workspacePath, 'branches');\n await fs.mkdir(branchesDir, { recursive: true });\n\n const configs: BranchConfig[] = [];\n\n for (let i = 0; i < numBranches; i++) {\n const branchPath = path.join(branchesDir, i.toString());\n const harnessPath = path.join(branchPath, 'iterations', '0', 'harness');\n\n // Copy baseline harness into branch's iteration 0\n await copyDir(baselinePath, harnessPath);\n\n // Copy tasks.yaml if it exists in the workspace\n const tasksYaml = path.join(workspacePath, 'tasks.yaml');\n try {\n await fs.access(tasksYaml);\n await fs.copyFile(tasksYaml, path.join(branchPath, 'tasks.yaml'));\n } catch {\n // tasks.yaml doesn't exist in workspace — skip\n }\n\n // Copy config.yaml if it exists\n const configYaml = path.join(workspacePath, 'config.yaml');\n try {\n await fs.access(configYaml);\n await fs.copyFile(configYaml, path.join(branchPath, 'config.yaml'));\n } catch {\n // config.yaml doesn't exist — skip\n }\n\n // Each branch gets a unique seed derived from branch index\n const seed = 42 + i * 1337;\n\n configs.push({\n branchId: i,\n seed,\n workspacePath: branchPath,\n });\n }\n\n return configs;\n}\n\n/**\n * Run N parallel evolution branches, each with its own workspace, seed, and\n * Thompson Sampling beliefs.\n *\n * All branches run concurrently via Promise.all. Each branch operates on\n * an independent copy of the baseline harness, so mutations in one branch\n * never affect another.\n *\n * @param workspacePath - Root .kairn-evolve/ directory\n * @param tasks - Task definitions from tasks.yaml\n * @param kairnConfig - Kairn config with API key and model\n * @param evolveConfig - Evolution config (iterations, proposer, etc.)\n * @param numBranches - Number of parallel branches (default: evolveConfig.pbtBranches)\n * @param onProgress - Optional callback for real-time progress (includes branchId)\n * @returns PBTResult with all branch results and best branch identification\n */\nexport async function runPopulation(\n workspacePath: string,\n tasks: Task[],\n kairnConfig: KairnConfig,\n evolveConfig: EvolveConfig,\n numBranches?: number,\n onProgress?: (event: LoopProgressEvent & { branchId?: number }) => void,\n): Promise<PBTResult> {\n const branches = numBranches ?? evolveConfig.pbtBranches;\n\n // Initialize branch workspaces\n const baselinePath = path.join(workspacePath, 'baseline');\n const branchConfigs = await initBranches(workspacePath, baselinePath, branches);\n\n // Run all branches concurrently\n const branchPromises = branchConfigs.map(async (branchConfig) => {\n // Each branch gets its own evolve config with unique seed behavior\n // The seed is embedded in the workspace path (Thompson Sampling reads/writes\n // beliefs per-workspace, so each branch naturally gets independent beliefs)\n const branchEvolveConfig: EvolveConfig = {\n ...evolveConfig,\n // Disable principal for individual branches — synthesis replaces it\n usePrincipal: false,\n // Each branch gets its own RNG seed for Thompson Sampling diversity\n rngSeed: branchConfig.seed,\n };\n\n const branchProgress = onProgress\n ? (event: LoopProgressEvent) => {\n onProgress({ ...event, branchId: branchConfig.branchId });\n }\n : undefined;\n\n const result = await evolve(\n branchConfig.workspacePath,\n tasks,\n kairnConfig,\n branchEvolveConfig,\n branchProgress,\n );\n\n // Find the best iteration's harness path\n const finalHarnessPath = path.join(\n branchConfig.workspacePath,\n 'iterations',\n result.bestIteration.toString(),\n 'harness',\n );\n\n // Load final beliefs\n let beliefs: TaskBelief[] = [];\n try {\n const beliefsPath = path.join(branchConfig.workspacePath, 'task-beliefs.json');\n const beliefsContent = await fs.readFile(beliefsPath, 'utf-8');\n beliefs = JSON.parse(beliefsContent) as TaskBelief[];\n } catch {\n // No beliefs saved — branch may have used uniform sampling\n }\n\n return {\n branchId: branchConfig.branchId,\n result,\n finalHarnessPath,\n beliefs,\n } satisfies BranchResult;\n });\n\n const branchResults = await Promise.all(branchPromises);\n\n // Identify best branch\n let bestBranch = 0;\n let bestScore = -1;\n for (const br of branchResults) {\n if (br.result.bestScore > bestScore) {\n bestScore = br.result.bestScore;\n bestBranch = br.branchId;\n }\n }\n\n // Meta-Principal synthesis: combine best mutations from all branches\n let synthesizedResult: EvolveResult | undefined;\n try {\n const baselinePath = path.join(workspacePath, 'baseline');\n const synthesisResult = await runSynthesis(\n { branches: branchResults, tasks, baselineHarnessPath: baselinePath },\n kairnConfig,\n evolveConfig,\n workspacePath,\n );\n\n if (synthesisResult) {\n const synthScore = synthesisResult.result.aggregate;\n synthesizedResult = {\n iterations: [{\n iteration: 0,\n score: synthScore,\n taskResults: synthesisResult.result.results,\n proposal: {\n reasoning: synthesisResult.reasoning,\n mutations: synthesisResult.mutations,\n expectedImpact: {},\n },\n diffPatch: null,\n timestamp: new Date().toISOString(),\n }],\n bestIteration: 0,\n bestScore: synthScore,\n baselineScore: bestScore,\n };\n\n onProgress?.({\n type: 'iteration-scored',\n iteration: 0,\n score: synthScore,\n message: `Meta-Principal synthesis: ${synthScore.toFixed(1)}%`,\n });\n\n // If synthesis beats all branches, it becomes the best\n if (synthScore > bestScore) {\n bestScore = synthScore;\n bestBranch = -1; // -1 indicates synthesis won\n }\n }\n } catch {\n // Synthesis failed — use best branch result\n }\n\n return {\n branches: branchResults,\n synthesizedResult,\n bestBranch,\n bestScore,\n };\n}\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { createRequire } from \"module\";\nimport { initCommand } from \"./commands/init.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\") as { version: string };\nimport { describeCommand } from \"./commands/describe.js\";\nimport { listCommand } from \"./commands/list.js\";\nimport { activateCommand } from \"./commands/activate.js\";\nimport { updateRegistryCommand } from \"./commands/update-registry.js\";\nimport { optimizeCommand } from \"./commands/optimize.js\";\nimport { doctorCommand } from \"./commands/doctor.js\";\nimport { registryCommand } from \"./commands/registry.js\";\nimport { templatesCommand } from \"./commands/templates.js\";\nimport { keysCommand } from \"./commands/keys.js\";\nimport { evolveCommand } from \"./commands/evolve.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"kairn\")\n .description(\n \"Compile natural language intent into optimized Claude Code environments\"\n )\n .version(pkg.version)\n .option(\"--no-color\", \"Disable colored output\");\n\nprogram.addCommand(initCommand);\nprogram.addCommand(describeCommand);\nprogram.addCommand(optimizeCommand);\nprogram.addCommand(listCommand);\nprogram.addCommand(activateCommand);\nprogram.addCommand(updateRegistryCommand);\nprogram.addCommand(doctorCommand);\nprogram.addCommand(registryCommand);\nprogram.addCommand(templatesCommand);\nprogram.addCommand(keysCommand);\nprogram.addCommand(evolveCommand);\n\n// Check for --no-color before parsing (Commander handles it but chalk needs manual disable)\nif (process.argv.includes(\"--no-color\") || process.env.NO_COLOR) {\n chalk.level = 0;\n}\n\nprogram.parse();\n","import { Command } from \"commander\";\nimport { confirm, input, password, select } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport OpenAI from \"openai\";\nimport { execFileSync } from \"child_process\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { loadConfig, saveConfig, getConfigPath, getTemplatesDir } from \"../config.js\";\nimport type { KairnConfig, LLMProvider, AuthType } from \"../types.js\";\nimport { getAccessToken } from \"../auth/keychain.js\";\nimport { PROVIDER_CONFIGS, PROVIDER_MODELS, PROVIDER_CHOICES, getProviderName, getBaseURL, getVerifyModel } from \"../providers.js\";\nimport { ui } from \"../ui.js\";\nimport { printFullBanner } from \"../logo.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nasync function installSeedTemplates(): Promise<void> {\n const templatesDir = getTemplatesDir();\n await fs.mkdir(templatesDir, { recursive: true });\n\n const candidates = [\n path.resolve(__dirname, \"../registry/templates\"),\n path.resolve(__dirname, \"../src/registry/templates\"),\n path.resolve(__dirname, \"../../src/registry/templates\"),\n ];\n\n let seedDir: string | null = null;\n for (const candidate of candidates) {\n try {\n await fs.access(candidate);\n seedDir = candidate;\n break;\n } catch {\n continue;\n }\n }\n\n if (!seedDir) return;\n\n const files = (await fs.readdir(seedDir)).filter((f) => f.endsWith(\".json\"));\n let installed = 0;\n\n for (const file of files) {\n const dest = path.join(templatesDir, file);\n try {\n await fs.access(dest);\n // File already exists — don't overwrite user modifications\n } catch {\n await fs.copyFile(path.join(seedDir, file), dest);\n installed++;\n }\n }\n\n if (installed > 0) {\n console.log(ui.success(`${installed} template${installed === 1 ? \"\" : \"s\"} installed`));\n }\n}\n\nasync function verifyKey(\n provider: LLMProvider,\n apiKey: string,\n baseURL?: string,\n model?: string,\n): Promise<boolean> {\n try {\n if (provider === \"anthropic\") {\n const client = new Anthropic({ apiKey });\n await client.messages.create({\n model: getVerifyModel(provider, model || \"claude-haiku-4-5-20251001\"),\n max_tokens: 10,\n messages: [{ role: \"user\", content: \"ping\" }],\n });\n return true;\n }\n\n // All other providers use OpenAI-compatible API\n const verifyModel = provider === \"other\"\n ? (model || \"test\")\n : getVerifyModel(provider, model || \"\");\n const resolvedBaseURL = getBaseURL(provider, baseURL);\n\n const clientOptions: { apiKey: string; baseURL?: string } = { apiKey };\n if (resolvedBaseURL) clientOptions.baseURL = resolvedBaseURL;\n\n const client = new OpenAI(clientOptions);\n await client.chat.completions.create({\n model: verifyModel,\n max_tokens: 10,\n messages: [{ role: \"user\", content: \"ping\" }],\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction detectClaudeCode(): boolean {\n try {\n execFileSync(\"which\", [\"claude\"], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\nexport const initCommand = new Command(\"init\")\n .description(\"Set up Kairn with your API key\")\n .action(async () => {\n printFullBanner(\"Setup\");\n\n const existing = await loadConfig();\n if (existing) {\n console.log(ui.warn(`Config already exists at ${chalk.dim(getConfigPath())}`));\n console.log(ui.warn(\"Running setup will overwrite it.\\n\"));\n }\n\n const provider = await select<LLMProvider>({\n message: \"LLM provider\",\n choices: PROVIDER_CHOICES,\n });\n\n let model: string;\n let baseURL: string | undefined;\n let providerDisplayName: string;\n\n if (provider === \"other\") {\n // Custom OpenAI-compatible endpoint\n providerDisplayName = \"Custom endpoint\";\n baseURL = await input({ message: \"Base URL\" });\n model = await input({ message: \"Model name\" });\n } else {\n providerDisplayName = getProviderName(provider);\n model = await select({\n message: \"Compilation model\",\n choices: PROVIDER_MODELS[provider],\n });\n }\n\n // For Anthropic: offer Claude Code subscription auth as an alternative\n let apiKey = \"\";\n let authType: AuthType = \"api-key\";\n\n if (provider === \"anthropic\") {\n const oauthToken = await getAccessToken();\n if (oauthToken) {\n const useOAuth = await confirm({\n message: \"Claude Code subscription detected. Use it instead of an API key? (experimental — may break)\",\n default: true,\n });\n if (useOAuth) {\n authType = \"claude-code-oauth\";\n console.log(ui.warn(\"Using Claude Code OAuth token. This is undocumented and may break at any time.\"));\n console.log(ui.success(\"OAuth token validated\"));\n }\n }\n }\n\n if (authType === \"api-key\") {\n apiKey = await password({\n message: `${providerDisplayName} API key${provider === \"other\" ? \" (Enter to skip)\" : \"\"}`,\n mask: \"*\",\n });\n\n if (!apiKey && provider !== \"other\") {\n console.log(ui.error(\"No API key provided. Aborting.\"));\n process.exit(1);\n }\n\n if (apiKey) {\n console.log(chalk.dim(\"\\n Verifying API key...\"));\n const valid = await verifyKey(provider, apiKey, baseURL, model);\n\n if (!valid) {\n console.log(ui.error(\"Invalid API key. Check your key and try again.\"));\n process.exit(1);\n }\n\n console.log(ui.success(\"API key verified\"));\n } else {\n console.log(ui.warn(\"No API key — skipping verification\"));\n }\n }\n\n const config: KairnConfig = {\n provider,\n api_key: apiKey,\n model,\n ...(baseURL ? { base_url: baseURL } : {}),\n ...(authType !== \"api-key\" ? { auth_type: authType } : {}),\n default_runtime: \"claude-code\",\n created_at: new Date().toISOString(),\n };\n\n await saveConfig(config);\n console.log(ui.success(`Config saved to ${chalk.dim(getConfigPath())}`));\n console.log(ui.kv(\"Provider\", providerDisplayName));\n console.log(ui.kv(\"Model\", model));\n\n await installSeedTemplates();\n\n const hasClaude = detectClaudeCode();\n if (hasClaude) {\n console.log(ui.success(\"Claude Code detected\"));\n } else {\n console.log(\n ui.warn(\"Claude Code not found. Install it: npm install -g @anthropic-ai/claude-code\")\n );\n }\n\n console.log(\n \"\\n\" + ui.success(`Ready! Run ${chalk.bold(\"kairn describe\")} to create your first environment.`) + \"\\n\"\n );\n });\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport os from \"os\";\nimport type { KairnConfig } from \"./types.js\";\n\nconst KAIRN_DIR = path.join(os.homedir(), \".kairn\");\nconst CONFIG_PATH = path.join(KAIRN_DIR, \"config.json\");\nconst ENVS_DIR = path.join(KAIRN_DIR, \"envs\");\nconst TEMPLATES_DIR = path.join(KAIRN_DIR, \"templates\");\nconst USER_REGISTRY_PATH = path.join(KAIRN_DIR, \"user-registry.json\");\n\nexport function getKairnDir(): string {\n return KAIRN_DIR;\n}\n\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n\nexport function getEnvsDir(): string {\n return ENVS_DIR;\n}\n\nexport function getTemplatesDir(): string {\n return TEMPLATES_DIR;\n}\n\nexport function getUserRegistryPath(): string {\n return USER_REGISTRY_PATH;\n}\n\nexport async function ensureDirs(): Promise<void> {\n await fs.mkdir(KAIRN_DIR, { recursive: true });\n await fs.mkdir(ENVS_DIR, { recursive: true });\n await fs.mkdir(TEMPLATES_DIR, { recursive: true });\n}\n\nexport async function loadConfig(): Promise<KairnConfig | null> {\n try {\n const data = await fs.readFile(CONFIG_PATH, \"utf-8\");\n const raw = JSON.parse(data) as Record<string, unknown>;\n\n // Handle old config format (v1.0.0: anthropic_api_key)\n if (raw.anthropic_api_key && !raw.provider) {\n return {\n provider: \"anthropic\",\n api_key: raw.anthropic_api_key as string,\n model: \"claude-sonnet-4-6\",\n default_runtime: \"claude-code\",\n created_at: (raw.created_at as string) || new Date().toISOString(),\n };\n }\n\n return raw as unknown as KairnConfig;\n } catch {\n return null;\n }\n}\n\nexport async function saveConfig(config: KairnConfig): Promise<void> {\n await ensureDirs();\n await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2), \"utf-8\");\n}\n","import chalk from \"chalk\";\nimport type { CompileProgress } from \"./types.js\";\n\nconst maroon = chalk.rgb(139, 0, 0);\nconst darkMaroon = chalk.rgb(100, 0, 0);\nconst warmStone = chalk.rgb(212, 165, 116);\nconst lightStone = chalk.rgb(220, 190, 160);\nconst dimStone = chalk.rgb(140, 100, 70);\n\nexport const ui = {\n // Brand colors\n brand: (text: string) => maroon.bold(text),\n accent: (text: string) => warmStone(text),\n\n // Logos and banners\n fullBanner: (subtitle?: string) => {\n const KAIRN_WORDMARK = [\n maroon(\"██╗ ██╗\") + \" \" + maroon(\"█████╗ \") + \" \" + maroon(\"██╗\") + \" \" + maroon(\"██████╗ \") + \" \" + maroon(\"███╗ ██╗\"),\n maroon(\"██║ ██╔╝\") + \" \" + maroon(\"██╔══██╗\") + \" \" + maroon(\"██║\") + \" \" + maroon(\"██╔══██╗\") + \" \" + maroon(\"████╗ ██║\"),\n warmStone(\"█████╔╝ \") + \" \" + warmStone(\"███████║\") + \" \" + warmStone(\"██║\") + \" \" + warmStone(\"██████╔╝\") + \" \" + warmStone(\"██╔██╗ ██║\"),\n warmStone(\"██╔═██╗ \") + \" \" + warmStone(\"██╔══██║\") + \" \" + warmStone(\"██║\") + \" \" + warmStone(\"██╔══██╗\") + \" \" + warmStone(\"██║╚██╗██║\"),\n lightStone(\"██║ ██╗\") + \" \" + lightStone(\"██║ ██║\") + \" \" + lightStone(\"██║\") + \" \" + lightStone(\"██║ ██║\") + \" \" + lightStone(\"██║ ╚████║\"),\n lightStone(\"╚═╝ ╚═╝\") + \" \" + lightStone(\"╚═╝ ╚═╝\") + \" \" + lightStone(\"╚═╝\") + \" \" + lightStone(\"╚═╝ ╚═╝\") + \" \" + lightStone(\"╚═╝ ╚═══╝\"),\n ];\n console.log(\"\");\n for (const line of KAIRN_WORDMARK) {\n console.log(\" \" + line);\n }\n if (subtitle) {\n console.log(dimStone(` ${subtitle}`));\n }\n console.log(\"\");\n },\n compactBanner: (subtitle?: string) => {\n const line = maroon(\"━\").repeat(52);\n console.log(` ${line}`);\n console.log(` ${maroon(\" ◆\")} ${chalk.bold.rgb(139, 0, 0)(\"KAIRN\")}` + (subtitle ? ` ${dimStone(\"— \" + subtitle)}` : \"\"));\n console.log(` ${line}`);\n },\n\n // Section headers\n section: (title: string) => {\n const len = chalk.dim(title).length;\n const line = \"━\".repeat(Math.max(0, 48 - len));\n return `\\n ${warmStone(\"━━\")} ${chalk.bold(title)} ${chalk.dim(warmStone(line))}`;\n },\n\n // Status messages\n success: (text: string) => chalk.green(` ✓ ${text}`),\n warn: (text: string) => chalk.yellow(` ⚠ ${text}`),\n error: (text: string) => chalk.red(` ✗ ${text}`),\n info: (text: string) => chalk.cyan(` ℹ ${text}`),\n\n // Key-value pairs\n kv: (key: string, value: string) => ` ${chalk.cyan(key.padEnd(14))} ${value}`,\n\n // File list\n file: (path: string) => chalk.dim(` ${path}`),\n\n // Tool display\n tool: (name: string, reason: string) => ` ${warmStone(\"●\")} ${chalk.bold(name)}\\n ${chalk.dim(reason)}`,\n\n // Divider\n divider: () => chalk.dim(` ${\"─\".repeat(50)}`),\n\n // Command suggestion\n cmd: (command: string) => ` ${chalk.bold.white(\"$ \" + command)}`,\n\n // Env var setup with signupUrl\n envVarPrompt: (name: string, desc: string, url?: string) => {\n let out = ` ${chalk.bold(name)}${chalk.dim(` (${desc})`)}`;\n if (url) out += `\\n ${chalk.dim(\"Get one at:\")} ${warmStone(url)}`;\n return out;\n },\n\n // Clarification question\n question: (q: string, suggestion?: string) => {\n let msg = ` ${warmStone(\"?\")} ${chalk.bold(q)}`;\n if (suggestion) {\n msg += `\\n ${chalk.dim(`(suggested: ${suggestion})`)}`;\n }\n return msg;\n },\n\n // Error box for compile failures\n errorBox: (title: string, message: string) => {\n const line = \"─\".repeat(50);\n return chalk.red(`\\n ┌${line}┐\\n │ ${title.padEnd(49)}│\\n │ ${message.padEnd(49)}│\\n └${line}┘\\n`);\n },\n};\n\nfunction formatTime(seconds: number): string {\n if (seconds < 60) return `${seconds}s`;\n const min = Math.floor(seconds / 60);\n const sec = seconds % 60;\n return sec > 0 ? `${min}m ${sec}s` : `${min} min`;\n}\n\nexport function estimateTime(model: string, intent: string): string {\n const wordCount = intent.split(/\\s+/).length;\n const isComplex = wordCount > 40;\n\n const perPass: Record<string, number> = {\n 'haiku': 5,\n 'sonnet': 20,\n 'opus': 60,\n 'gpt-4.1-mini': 10,\n 'gpt-4.1': 25,\n 'gpt-5': 15,\n 'o4-mini': 12,\n 'gemini-2.5-flash': 8,\n 'gemini-3-flash': 8,\n 'gemini-2.5-pro': 30,\n 'gemini-3.1-pro': 30,\n 'grok-4.1-fast': 10,\n 'grok-4.20': 25,\n 'deepseek': 15,\n 'mistral-large': 20,\n 'codestral': 15,\n 'mistral-small': 10,\n 'llama': 10,\n 'qwen': 10,\n };\n\n // Find closest match or default to 20s per pass\n const basePerPass = Object.entries(perPass).find(([k]) => model.toLowerCase().includes(k))?.[1] ?? 20;\n const totalBase = basePerPass * 2; // 2 LLM passes\n\n if (isComplex) {\n const low = Math.floor(totalBase * 1.5);\n const high = Math.floor(totalBase * 4);\n return `~${formatTime(low)}-${formatTime(high)} (complex workflow)`;\n }\n return `~${formatTime(totalBase)}`;\n}\n\nexport function createProgressRenderer(): {\n update: (progress: CompileProgress) => void;\n finish: () => void;\n fail: (err: unknown) => void;\n} {\n const lines: string[] = [];\n let intervalId: NodeJS.Timeout | null = null;\n let currentPhase = '';\n let phaseStart = Date.now();\n let lineCount = 0; // tracks how many lines have been written to stdout\n\n function render(): void {\n // Move cursor up to overwrite previous output\n if (lineCount > 0) {\n process.stdout.write(`\\x1B[${lineCount}A`);\n }\n for (const line of lines) {\n process.stdout.write('\\x1B[2K' + line + '\\n');\n }\n lineCount = lines.length;\n }\n\n function updateElapsed(): void {\n if (!currentPhase) return;\n const elapsed = Math.floor((Date.now() - phaseStart) / 1000);\n const lastIdx = lines.length - 1;\n if (lastIdx >= 0) {\n lines[lastIdx] = lines[lastIdx].replace(/\\[\\d+s\\]/, `[${elapsed}s]`);\n render();\n }\n }\n\n return {\n update(progress: CompileProgress): void {\n if (progress.status === 'running') {\n currentPhase = progress.phase;\n phaseStart = Date.now();\n lines.push(` ${warmStone(\"◐\")} ${progress.message} ${chalk.dim(\"[0s]\")}`);\n if (!intervalId) {\n intervalId = setInterval(updateElapsed, 1000);\n }\n } else if (progress.status === 'success') {\n const lastIdx = lines.length - 1;\n const elapsed = progress.elapsed != null ? ` ${chalk.dim(\"—\")} ${chalk.dim(Math.floor(progress.elapsed) + \"s\")}` : '';\n const detail = progress.detail ? ` ${chalk.dim(\"(\" + progress.detail + \")\")}` : '';\n if (lastIdx >= 0) {\n lines[lastIdx] = ` ${chalk.green(\"✔\")} ${progress.message}${detail}${elapsed}`;\n }\n currentPhase = '';\n } else if (progress.status === 'warning') {\n const lastIdx = lines.length - 1;\n if (lastIdx >= 0) {\n lines[lastIdx] = ` ${chalk.yellow(\"⚠\")} ${progress.message}`;\n }\n // Add new running line for the retry\n currentPhase = progress.phase;\n phaseStart = Date.now();\n lines.push(` ${warmStone(\"◐\")} Retrying in concise mode... ${chalk.dim(\"[0s]\")}`);\n }\n render();\n },\n finish(): void {\n if (intervalId) clearInterval(intervalId);\n currentPhase = '';\n render();\n },\n fail(err: unknown): void {\n if (intervalId) clearInterval(intervalId);\n currentPhase = '';\n const lastIdx = lines.length - 1;\n if (lastIdx >= 0) {\n lines[lastIdx] = ` ${chalk.red(\"✖\")} Compilation failed`;\n }\n render();\n },\n };\n}\n","import chalk from \"chalk\";\n\n// Kairn brand colors\nconst maroon = chalk.rgb(139, 0, 0);\nconst darkMaroon = chalk.rgb(100, 0, 0);\nconst warmStone = chalk.rgb(180, 120, 80);\nconst lightStone = chalk.rgb(212, 165, 116);\nconst dimStone = chalk.rgb(140, 100, 70);\n\n// Block-character wordmark (matches Hermes quality level)\nconst KAIRN_WORDMARK = [\n maroon(\"██╗ ██╗\") + darkMaroon(\" \") + maroon(\"█████╗ \") + darkMaroon(\" \") + maroon(\"██╗\") + darkMaroon(\" \") + maroon(\"██████╗ \") + darkMaroon(\" \") + maroon(\"███╗ ██╗\"),\n maroon(\"██║ ██╔╝\") + darkMaroon(\" \") + maroon(\"██╔══██╗\") + darkMaroon(\" \") + maroon(\"██║\") + darkMaroon(\" \") + maroon(\"██╔══██╗\") + darkMaroon(\" \") + maroon(\"████╗ ██║\"),\n warmStone(\"█████╔╝ \") + dimStone(\" \") + warmStone(\"███████║\") + dimStone(\" \") + warmStone(\"██║\") + dimStone(\" \") + warmStone(\"██████╔╝\") + dimStone(\" \") + warmStone(\"██╔██╗ ██║\"),\n warmStone(\"██╔═██╗ \") + dimStone(\" \") + warmStone(\"██╔══██║\") + dimStone(\" \") + warmStone(\"██║\") + dimStone(\" \") + warmStone(\"██╔══██╗\") + dimStone(\" \") + warmStone(\"██║╚██╗██║\"),\n lightStone(\"██║ ██╗\") + dimStone(\" \") + lightStone(\"██║ ██║\") + dimStone(\" \") + lightStone(\"██║\") + dimStone(\" \") + lightStone(\"██║ ██║\") + dimStone(\" \") + lightStone(\"██║ ╚████║\"),\n lightStone(\"╚═╝ ╚═╝\") + dimStone(\" \") + lightStone(\"╚═╝ ╚═╝\") + dimStone(\" \") + lightStone(\"╚═╝\") + dimStone(\" \") + lightStone(\"╚═╝ ╚═╝\") + dimStone(\" \") + lightStone(\"╚═╝ ╚═══╝\"),\n];\n\n// Braille-art cairn (stacked stones)\nconst CAIRN_ART = [\n dimStone(\" ⣀⣀⣀ \"),\n warmStone(\" ⣴⣿⣿⣿⣦ \"),\n warmStone(\" ⠙⠿⠿⠋ \"),\n dimStone(\" ⣀⣤⣤⣤⣤⣀ \"),\n lightStone(\" ⣴⣿⣿⣿⣿⣿⣿⣦ \"),\n lightStone(\" ⠙⠻⠿⠿⠿⠟⠋ \"),\n dimStone(\" ⣀⣤⣤⣶⣶⣶⣶⣤⣤⣀ \"),\n warmStone(\" ⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦ \"),\n warmStone(\" ⠙⠻⠿⠿⠿⠿⠿⠿⠟⠋ \"),\n dimStone(\" ⣀⣤⣶⣶⣿⣿⣿⣿⣿⣿⣶⣶⣤⣀ \"),\n lightStone(\" ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ \"),\n dimStone(\" ⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉ \"),\n];\n\nexport function printLogo(): void {\n console.log(\"\");\n for (const line of KAIRN_WORDMARK) {\n console.log(\" \" + line);\n }\n console.log(\"\");\n}\n\nexport function printCairn(): void {\n console.log(\"\");\n for (const line of CAIRN_ART) {\n console.log(\" \" + line);\n }\n console.log(\"\");\n}\n\nexport function printFullBanner(subtitle?: string): void {\n console.log(\"\");\n for (const line of KAIRN_WORDMARK) {\n console.log(\" \" + line);\n }\n if (subtitle) {\n console.log(dimStone(` ${subtitle}`));\n }\n console.log(\"\");\n}\n\n// Compact one-liner for smaller outputs\nexport function printCompactBanner(): void {\n const line = maroon(\"━\").repeat(50);\n console.log(`\\n ${line}`);\n console.log(` ${maroon(\" ◆\")} ${chalk.bold.rgb(139, 0, 0)(\"KAIRN\")} ${dimStone(\"— Agent Environment Compiler\")}`);\n console.log(` ${line}\\n`);\n}\n","import { Command } from \"commander\";\nimport { input, confirm, select } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { loadConfig } from \"../config.js\";\nimport { generateClarifications, compile } from \"../compiler/compile.js\";\nimport { writeEnvironment, summarizeSpec } from \"../adapter/claude-code.js\";\nimport { writeHermesEnvironment } from \"../adapter/hermes-agent.js\";\nimport { loadRegistry } from \"../registry/loader.js\";\nimport { ui, createProgressRenderer, estimateTime } from \"../ui.js\";\nimport { printFullBanner } from \"../logo.js\";\nimport { collectAndWriteKeys, writeEmptyEnvFile } from \"../secrets.js\";\nimport { autonomyLabel } from \"../autonomy.js\";\nimport type { RuntimeTarget, Clarification, AutonomyLevel } from \"../types.js\";\n\nexport const describeCommand = new Command(\"describe\")\n .description(\"Describe your workflow and generate a Claude Code environment\")\n .argument(\"[intent]\", \"What you want your agent to do\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .option(\"-q, --quick\", \"Skip clarification questions\")\n .option(\"--runtime <runtime>\", \"Target runtime (claude-code or hermes)\", \"claude-code\")\n .action(async (\n intentArg: string | undefined,\n options: { yes?: boolean; quick?: boolean; runtime?: string }\n ) => {\n // 1. Banner\n printFullBanner(\"The Agent Environment Compiler\");\n\n // 2. Check config\n const config = await loadConfig();\n if (!config) {\n console.log(\n ui.errorBox(\n \"No configuration found\",\n `Run ${chalk.bold(\"kairn init\")} to set up your API key.`\n )\n );\n process.exit(1);\n }\n\n // 3. Get intent\n const intentRaw =\n intentArg ||\n (await input({\n message: \"What do you want your agent to do?\",\n }));\n\n if (!intentRaw.trim()) {\n console.log(chalk.red(\"\\n No description provided. Aborting.\\n\"));\n process.exit(1);\n }\n\n // 4. Clarification flow\n let finalIntent = intentRaw;\n\n if (!options.quick) {\n console.log(ui.section(\"Clarification\"));\n console.log(chalk.dim(\" Let me understand your project better.\"));\n console.log(chalk.dim(\" Press Enter to accept the suggestion, or type your own answer.\\n\"));\n\n let clarifications: Clarification[] = [];\n try {\n clarifications = await generateClarifications(intentRaw);\n } catch {\n // Non-fatal: proceed without clarifications\n }\n\n if (clarifications.length > 0) {\n const answers: Array<{ question: string; answer: string }> = [];\n\n for (const c of clarifications) {\n const answer = await input({\n message: c.question,\n default: c.suggestion,\n });\n answers.push({ question: c.question, answer });\n }\n\n const clarificationLines = answers\n .map((a) => `- ${a.question}: ${a.answer}`)\n .join(\"\\n\");\n\n finalIntent =\n `User intent: \"${intentRaw}\"\\n\\nClarifications:\\n${clarificationLines}`;\n }\n }\n\n // 5. Autonomy level\n let autonomyLevel: AutonomyLevel = 1;\n\n if (!options.quick) {\n console.log(ui.section(\"Autonomy\"));\n autonomyLevel = await select({\n message: \"Autonomy level\",\n choices: [\n { name: \"1. Guided — orientation + commands, you drive\", value: 1 as AutonomyLevel },\n { name: \"2. Assisted — workflow loop, you approve phases\", value: 2 as AutonomyLevel },\n { name: \"3. Autonomous — PM plans, loop executes, you review PRs\", value: 3 as AutonomyLevel },\n { name: \"4. Full Auto — continuous execution (⚠ advanced)\", value: 4 as AutonomyLevel },\n ],\n default: 1,\n });\n\n finalIntent += `\\n\\nAutonomy level: ${autonomyLevel} (${autonomyLabel(autonomyLevel)})`;\n }\n\n // 6. Compilation\n console.log(ui.section(\"Compilation\"));\n const estimate = estimateTime(config.model, finalIntent);\n console.log(chalk.dim(` Estimated time: ${estimate} (${config.model})`));\n console.log(\"\");\n\n const renderer = createProgressRenderer();\n\n let spec;\n try {\n spec = await compile(finalIntent, (progress) => {\n renderer.update(progress);\n });\n spec.autonomy_level = autonomyLevel;\n renderer.finish();\n } catch (err) {\n renderer.fail(err);\n const msg = err instanceof Error ? err.message : String(err);\n console.log(chalk.red(`\\n ${msg}\\n`));\n process.exit(1);\n }\n\n // 7. Results display\n const registry = await loadRegistry();\n const summary = summarizeSpec(spec, registry);\n\n console.log(\"\");\n console.log(ui.kv(\"Name:\", spec.name));\n console.log(ui.kv(\"Description:\", spec.description));\n console.log(ui.kv(\"Autonomy:\", `Level ${spec.autonomy_level} (${autonomyLabel(spec.autonomy_level)})`));\n console.log(ui.kv(\"Tools:\", String(summary.toolCount)));\n console.log(ui.kv(\"Commands:\", String(summary.commandCount)));\n console.log(ui.kv(\"Rules:\", String(summary.ruleCount)));\n console.log(ui.kv(\"Skills:\", String(summary.skillCount)));\n console.log(ui.kv(\"Agents:\", String(summary.agentCount)));\n\n if (spec.tools.length > 0) {\n console.log(ui.section(\"Selected Tools\"));\n console.log(\"\");\n for (const tool of spec.tools) {\n const regTool = registry.find((t) => t.id === tool.tool_id);\n const name = regTool?.name || tool.tool_id;\n console.log(ui.tool(name, tool.reason));\n console.log(\"\");\n }\n }\n\n // 7. Confirm\n const proceed =\n options.yes ||\n (await confirm({\n message: \"Generate environment in current directory?\",\n default: true,\n }));\n\n if (!proceed) {\n console.log(chalk.dim(\"\\n Aborted. Environment saved to ~/.kairn/envs/\\n\"));\n return;\n }\n\n // 8. Write\n const targetDir = process.cwd();\n const runtime = (options.runtime ?? \"claude-code\") as RuntimeTarget;\n\n if (runtime === \"hermes\") {\n await writeHermesEnvironment(spec, registry);\n console.log(\"\\n\" + ui.success(\"Environment written for Hermes\"));\n console.log(\n chalk.cyan(\"\\n Ready! Run \") + chalk.bold(\"hermes\") + chalk.cyan(\" to start.\\n\")\n );\n } else {\n const hasEnvVars = summary.envSetup.length > 0;\n const written = await writeEnvironment(spec, targetDir, { hasEnvVars });\n\n console.log(ui.section(\"Files Written\"));\n console.log(\"\");\n for (const file of written) {\n console.log(ui.file(file));\n }\n // Handle .env file generation and key collection\n if (hasEnvVars) {\n if (options.quick) {\n await writeEmptyEnvFile(summary.envSetup, targetDir);\n console.log(ui.success(\"Empty .env written (gitignored) — fill in keys later: kairn keys\"));\n } else {\n await collectAndWriteKeys(summary.envSetup, targetDir);\n }\n console.log(\"\");\n }\n\n if (summary.pluginCommands.length > 0) {\n console.log(ui.section(\"Plugins\"));\n console.log(\"\");\n for (const cmd of summary.pluginCommands) {\n console.log(ui.cmd(cmd));\n }\n console.log(\"\");\n }\n\n console.log(ui.divider());\n console.log(ui.success(\"Ready! Run: $ claude\"));\n console.log(\"\");\n }\n });\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport crypto from \"crypto\";\nimport { loadConfig, getEnvsDir, ensureDirs } from \"../config.js\";\nimport { SYSTEM_PROMPT, SKELETON_PROMPT, HARNESS_PROMPT, CLARIFICATION_PROMPT } from \"./prompt.js\";\nimport { loadRegistry } from \"../registry/loader.js\";\nimport { getCheapModel } from \"../providers.js\";\nimport { callLLM } from \"../llm.js\";\nimport type { EnvironmentSpec, RegistryTool, Clarification, SkeletonSpec, HarnessContent, CompileProgress } from \"../types.js\";\nimport { generateIntentPatterns } from \"../intent/patterns.js\";\nimport { compileIntentPrompt } from \"../intent/prompt-template.js\";\nimport { renderIntentRouter } from \"../intent/router-template.js\";\nimport { renderIntentLearner } from \"../intent/learner-template.js\";\n\nfunction buildUserMessage(intent: string, registry: RegistryTool[]): string {\n const registrySummary = registry\n .map(\n (t) =>\n `- ${t.id} (${t.type}, tier ${t.tier}, auth: ${t.auth}): ${t.description} [best_for: ${t.best_for.join(\", \")}]`\n )\n .join(\"\\n\");\n\n return `## User Intent\\n\\n${intent}\\n\\n## Available Tool Registry\\n\\n${registrySummary}\\n\\nGenerate the EnvironmentSpec JSON now.`;\n}\n\nfunction buildSkeletonMessage(intent: string, registry: RegistryTool[]): string {\n const registrySummary = registry\n .map(\n (t) =>\n `- ${t.id} (${t.type}, tier ${t.tier}, auth: ${t.auth}): ${t.description} [best_for: ${t.best_for.join(\", \")}]`\n )\n .join(\"\\n\");\n\n return `## User Intent\\n\\n${intent}\\n\\n## Available Tool Registry\\n\\n${registrySummary}\\n\\nGenerate the skeleton JSON now.`;\n}\n\nfunction buildHarnessMessage(intent: string, skeleton: SkeletonSpec, concise?: boolean): string {\n const skeletonJson = JSON.stringify(skeleton, null, 2);\n const conciseNote = concise\n ? \"\\n\\nIMPORTANT: Be concise. Maximum 80 lines for claude_md. Maximum 5 commands. Keep all content brief.\"\n : \"\";\n return `## User Intent\\n\\n${intent}\\n\\n## Project Skeleton\\n\\n${skeletonJson}\\n\\nGenerate the harness content JSON now.${conciseNote}`;\n}\n\nfunction parseSpecResponse(text: string): Omit<EnvironmentSpec, \"id\" | \"intent\" | \"created_at\"> {\n let cleaned = text.trim();\n // Strip markdown code fences\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n // Try to extract JSON if there's surrounding text\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n throw new Error(\n \"LLM response did not contain valid JSON. Try again or use a different model.\"\n );\n }\n try {\n return JSON.parse(jsonMatch[0]);\n } catch (err) {\n throw new Error(\n `Failed to parse LLM response as JSON: ${err instanceof Error ? err.message : String(err)}\\n` +\n `Response started with: ${cleaned.slice(0, 200)}...`\n );\n }\n}\n\nfunction parseSkeletonResponse(text: string): SkeletonSpec {\n let cleaned = text.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n throw new Error(\"Pass 1 (skeleton) did not return valid JSON.\");\n }\n try {\n const parsed = JSON.parse(jsonMatch[0]);\n // Validate required fields\n if (!parsed.name || !parsed.tools || !Array.isArray(parsed.tools)) {\n throw new Error(\"Skeleton missing required fields: name, tools\");\n }\n return parsed as SkeletonSpec;\n } catch (err) {\n throw new Error(\n `Failed to parse skeleton JSON: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\nfunction parseHarnessResponse(text: string): HarnessContent {\n let cleaned = text.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n throw new Error(\"Pass 2 (harness) did not return valid JSON.\");\n }\n try {\n const parsed = JSON.parse(jsonMatch[0]);\n if (!parsed.claude_md || !parsed.commands) {\n throw new Error(\"Harness missing required fields: claude_md, commands\");\n }\n return parsed as HarnessContent;\n } catch (err) {\n throw new Error(\n `Failed to parse harness JSON: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\nfunction buildSettings(skeleton: SkeletonSpec, registry: RegistryTool[]): Record<string, unknown> {\n const selectedTools = skeleton.tools\n .map((t) => registry.find((r) => r.id === t.tool_id))\n .filter(Boolean);\n\n // Build permissions based on workflow type\n const allow = [\"Read\", \"Write\", \"Edit\", \"Bash(npm run *)\", \"Bash(npx *)\"];\n const deny = [\n \"Bash(rm -rf *)\",\n \"Bash(curl * | sh)\",\n \"Bash(wget * | sh)\",\n \"Read(./.env)\",\n \"Read(./secrets/**)\",\n ];\n\n // Build hooks\n const hooks: Record<string, unknown[]> = {\n PreToolUse: [\n {\n matcher: \"Bash\",\n hooks: [\n {\n type: \"command\",\n command:\n \"CMD=$(cat | jq -r '.tool_input.command // empty') && echo \\\"$CMD\\\" | grep -qiE 'rm\\\\s+-rf\\\\s+/|DROP\\\\s+TABLE|curl.*\\\\|\\\\s*sh' && echo 'Blocked destructive command' >&2 && exit 2 || true\",\n },\n ],\n },\n ],\n PostCompact: [\n {\n matcher: \"\",\n hooks: [\n {\n type: \"prompt\",\n prompt:\n \"Re-read CLAUDE.md and docs/SPRINT.md (if it exists) to restore project context after compaction.\",\n },\n ],\n },\n ],\n };\n\n // Add formatter hook if project uses common formatters\n const techStack = skeleton.outline.tech_stack.map((t) => t.toLowerCase());\n if (\n techStack.some((t) => t.includes(\"typescript\") || t.includes(\"javascript\") || t.includes(\"react\") || t.includes(\"next\"))\n ) {\n hooks.PostToolUse = [\n {\n matcher: \"Edit|Write\",\n hooks: [\n {\n type: \"command\",\n command:\n 'FILE=$(cat | jq -r \\'.tool_input.file_path // empty\\') && [ -n \"$FILE\" ] && npx prettier --write \"$FILE\" 2>/dev/null || true',\n },\n ],\n },\n ];\n }\n\n return { permissions: { allow, deny }, hooks };\n}\n\nfunction buildMcpConfig(skeleton: SkeletonSpec, registry: RegistryTool[]): Record<string, unknown> {\n const config: Record<string, unknown> = {};\n for (const tool of skeleton.tools) {\n const reg = registry.find((r) => r.id === tool.tool_id);\n if (reg?.install.mcp_config) {\n config[tool.tool_id] = reg.install.mcp_config;\n }\n }\n return config;\n}\n\nfunction validateSpec(spec: EnvironmentSpec): string[] {\n const warnings: string[] = [];\n\n if (spec.tools.length > 8) {\n warnings.push(`${spec.tools.length} MCP servers selected (recommended: ≤6)`);\n }\n\n if (spec.harness.claude_md) {\n const lines = spec.harness.claude_md.split('\\n').length;\n if (lines > 150) {\n warnings.push(`CLAUDE.md is ${lines} lines (recommended: ≤150)`);\n }\n }\n\n if (spec.harness.skills && Object.keys(spec.harness.skills).length > 5) {\n warnings.push(`${Object.keys(spec.harness.skills).length} skills (recommended: ≤3)`);\n }\n\n return warnings;\n}\n\nexport async function compile(\n intent: string,\n onProgress?: (progress: CompileProgress) => void\n): Promise<EnvironmentSpec> {\n const startTime = Date.now();\n const config = await loadConfig();\n if (!config) {\n throw new Error(\"No config found. Run `kairn init` first.\");\n }\n\n // Registry\n onProgress?.({ phase: 'registry', status: 'running', message: 'Loading tool registry...' });\n const registry = await loadRegistry();\n onProgress?.({ phase: 'registry', status: 'success', message: 'Tool registry loaded', detail: `${registry.length} tools` });\n\n // Pass 1: Skeleton (tool selection + project outline)\n onProgress?.({ phase: 'pass1', status: 'running', message: 'Pass 1: Analyzing workflow & selecting tools...' });\n const skeletonMsg = buildSkeletonMessage(intent, registry);\n const skeletonText = await callLLM(config, skeletonMsg, {\n maxTokens: 2048,\n systemPrompt: SKELETON_PROMPT,\n });\n const skeleton = parseSkeletonResponse(skeletonText);\n const toolNames = skeleton.tools.map(t => t.tool_id).join(', ');\n onProgress?.({\n phase: 'pass1', status: 'success',\n message: `Pass 1: Selected ${skeleton.tools.length} tools`,\n detail: toolNames,\n elapsed: (Date.now() - startTime) / 1000,\n });\n\n // Pass 2: Harness content (CLAUDE.md + commands + rules + agents)\n onProgress?.({ phase: 'pass2', status: 'running', message: 'Pass 2: Generating CLAUDE.md, commands, agents...' });\n const harnessMsg = buildHarnessMessage(intent, skeleton);\n let harness: HarnessContent;\n try {\n const harnessText = await callLLM(config, harnessMsg, {\n maxTokens: 8192,\n systemPrompt: HARNESS_PROMPT,\n });\n harness = parseHarnessResponse(harnessText);\n } catch {\n // Retry with concise mode if Pass 2 fails (likely JSON truncation)\n onProgress?.({ phase: 'pass2-retry', status: 'warning', message: 'Pass 2: Response too large, retrying in concise mode...' });\n const retryMsg = buildHarnessMessage(intent, skeleton, true);\n const retryText = await callLLM(config, retryMsg, {\n maxTokens: 8192,\n systemPrompt: HARNESS_PROMPT,\n });\n harness = parseHarnessResponse(retryText);\n }\n const cmdCount = Object.keys(harness.commands).length;\n const agentCount = Object.keys(harness.agents ?? {}).length;\n const ruleCount = Object.keys(harness.rules).length;\n onProgress?.({\n phase: 'pass2', status: 'success',\n message: `Pass 2: Generated ${cmdCount} commands, ${agentCount} agents, ${ruleCount} rules`,\n elapsed: (Date.now() - startTime) / 1000,\n });\n\n // Pass 3: Settings + MCP config (deterministic, no LLM)\n onProgress?.({ phase: 'pass3', status: 'running', message: 'Pass 3: Configuring MCP servers & settings...' });\n const settings = buildSettings(skeleton, registry);\n const mcpConfig = buildMcpConfig(skeleton, registry);\n\n // Intent routing: generate patterns, prompt template, and hook scripts\n const projectProfile = {\n language: skeleton.outline.tech_stack[0] ?? 'unknown',\n framework: skeleton.outline.tech_stack[1] ?? 'none',\n scripts: {} as Record<string, string>, // scripts come from project scanning, not compilation\n };\n const intentPatterns = generateIntentPatterns(\n harness.commands,\n harness.agents ?? {},\n projectProfile,\n );\n const intentPromptTemplate = compileIntentPrompt(\n harness.commands,\n harness.agents ?? {},\n );\n const generationTimestamp = new Date().toISOString();\n const intentHooks: Record<string, string> = {};\n if (intentPatterns.length > 0) {\n intentHooks['intent-router'] = renderIntentRouter(intentPatterns, generationTimestamp);\n intentHooks['intent-learner'] = renderIntentLearner();\n }\n\n onProgress?.({ phase: 'pass3', status: 'success', message: 'Pass 3: Configured MCP servers & settings' });\n\n // Assemble final EnvironmentSpec\n const spec: EnvironmentSpec = {\n id: `env_${crypto.randomUUID()}`,\n intent,\n created_at: new Date().toISOString(),\n name: skeleton.name,\n description: skeleton.description,\n autonomy_level: 1,\n tools: skeleton.tools,\n harness: {\n claude_md: harness.claude_md,\n settings,\n mcp_config: mcpConfig,\n commands: harness.commands,\n rules: harness.rules,\n skills: harness.skills ?? {},\n agents: harness.agents ?? {},\n docs: harness.docs,\n hooks: intentHooks,\n intent_patterns: intentPatterns,\n intent_prompt_template: intentPromptTemplate,\n },\n };\n\n const warnings = validateSpec(spec);\n for (const w of warnings) {\n onProgress?.({ phase: 'done', status: 'warning', message: `⚠ ${w}` });\n }\n\n const totalElapsed = ((Date.now() - startTime) / 1000).toFixed(0);\n onProgress?.({ phase: 'done', status: 'success', message: `Environment compiled in ${totalElapsed}s`, elapsed: (Date.now() - startTime) / 1000 });\n\n // Save to ~/.kairn/envs/\n await ensureDirs();\n const envPath = path.join(getEnvsDir(), `${spec.id}.json`);\n await fs.writeFile(envPath, JSON.stringify(spec, null, 2), \"utf-8\");\n\n return spec;\n}\n\nexport async function generateClarifications(\n intent: string,\n onProgress?: (msg: string) => void\n): Promise<Clarification[]> {\n const config = await loadConfig();\n if (!config) {\n throw new Error(\"No config found. Run `kairn init` first.\");\n }\n\n onProgress?.(\"Analyzing your request...\");\n\n // Use the cheapest model for clarifications regardless of selected compilation model\n const clarificationConfig = { ...config };\n clarificationConfig.model = getCheapModel(config.provider, config.model);\n\n const response = await callLLM(clarificationConfig, CLARIFICATION_PROMPT + \"\\n\\nUser description: \" + intent, {\n systemPrompt: SYSTEM_PROMPT,\n });\n\n try {\n let cleaned = response.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n const jsonMatch = cleaned.match(/\\[[\\s\\S]*\\]/);\n if (!jsonMatch) return [];\n return JSON.parse(jsonMatch[0]) as Clarification[];\n } catch {\n return [];\n }\n}\n","export const SKELETON_PROMPT = `You are the Kairn skeleton compiler. Your job is to select tools and outline the project structure from a user's natural language description.\n\nYou will receive:\n1. The user's intent (what they want to build/do)\n2. A tool registry (available MCP servers, plugins, and hooks)\n\nYou must output a JSON object matching the SkeletonSpec schema.\n\n## Core Principles\n\n- **Minimalism over completeness.** Fewer, well-chosen tools beat many generic ones. Each MCP server costs 500-2000 context tokens.\n- **Workflow-specific, not generic.** Select tools that directly support the user's actual workflow.\n- **Security by default.** Essential for all projects.\n\n## Tool Selection Rules\n\n- Only select tools directly relevant to the described workflow\n- Prefer free tools (auth: \"none\") when quality is comparable\n- Tier 1 tools (Context7, Sequential Thinking, security-guidance) should be included in most environments\n- For tools requiring API keys (auth: \"api_key\"), use \\${ENV_VAR} syntax — never hardcode keys\n- Maximum 6-8 MCP servers to avoid context bloat\n- Include a \\`reason\\` for each selected tool explaining why it fits this workflow\n\n## Context Budget (STRICT)\n\n- MCP servers: maximum 6. Prefer fewer.\n- Skills: maximum 3. Only include directly relevant ones.\n- Agents: maximum 5. Orchestration pipeline (/develop) agents.\n- Hooks: maximum 4 (auto-format, block-destructive, PostCompact, plus one contextual).\n\nIf the workflow doesn't clearly need a tool, DO NOT include it.\nEach MCP server costs 500-2000 tokens of context window.\n\n## Output Schema\n\nReturn ONLY valid JSON matching this structure:\n\n\\`\\`\\`json\n{\n \"name\": \"short-kebab-case-name\",\n \"description\": \"One-line description\",\n \"tools\": [\n { \"tool_id\": \"id-from-registry\", \"reason\": \"why this tool fits\" }\n ],\n \"outline\": {\n \"tech_stack\": [\"Python\", \"pandas\"],\n \"workflow_type\": \"data-analysis\",\n \"key_commands\": [\"ingest\", \"analyze\", \"report\"],\n \"custom_rules\": [\"data-integrity\"],\n \"custom_agents\": [\"data-reviewer\"],\n \"custom_skills\": [\"ms-data-analysis\"]\n }\n}\n\\`\\`\\`\n\nReturn ONLY valid JSON. No markdown fences. No text outside the JSON.`;\n\nexport const HARNESS_PROMPT = `You are the Kairn harness compiler. Your job is to generate the full environment content from a project skeleton.\n\nYou will receive:\n1. The skeleton (tool selections + project outline)\n2. The user's original intent\n\nYou must generate all harness content: CLAUDE.md, commands, rules, agents, skills, and docs.\n\n## Core Principles\n\n- **Workflow-specific, not generic.** Every instruction, command, and rule must relate to the user's actual workflow.\n- **Concise CLAUDE.md.** Under 150 lines. No generic text like \"be helpful.\" Include build/test commands, reference docs/ and skills/.\n- **Security by default.** Always include deny rules for destructive commands and secret file access.\n\n## CLAUDE.md Template (mandatory structure)\n\nThe \\`claude_md\\` field MUST follow this exact structure (max 150 lines):\n\n\\`\\`\\`\n# {Project Name}\n\n## Purpose\n{one-line description}\n\n## Tech Stack\n{bullet list of frameworks/languages}\n\n## Commands\n{concrete build/test/lint/dev commands}\n\n## Architecture\n{brief folder structure, max 10 lines}\n\n## Conventions\n{3-5 specific coding rules}\n\n## Key Commands\n{list /project: commands with descriptions}\n\n## Output\n{where results go, key files}\n\n## Verification\nAfter implementing any change, verify it works:\n- {build command} — must pass with no errors\n- {test command} — all tests must pass\n- {lint command} — no warnings or errors\n- {type check command} — no type errors\n\nIf any verification step fails, fix the issue before moving on.\nDo NOT skip verification steps.\n\n## Known Gotchas\n<!-- After any correction, add it here: \"Update CLAUDE.md so you don't make that mistake again.\" -->\n<!-- Prune this section when it exceeds 10 items — keep only the recurring ones. -->\n- (none yet — this section grows as you work)\n\n## Debugging\nWhen debugging, paste raw error output. Don't summarize — Claude works better with raw data.\nUse subagents for deep investigation to keep main context clean.\n\n## Git Workflow\n- Prefer small, focused commits (one feature or fix per commit)\n- Use conventional commits: feat:, fix:, docs:, refactor:, test:\n- Target < 200 lines per PR when possible\n\n## Engineering Standards\n- Lead with answers over reasoning. Be concise.\n- Use absolute file paths in all references.\n- No filler, no inner monologue, no time estimates.\n- Produce load-bearing code — every line of output should be actionable.\n\n## Tool Usage Policy\n- Prefer Edit tool over sed/awk for file modifications\n- Prefer Grep tool over rg for searching\n- Prefer Read tool over cat for file reading\n- Reserve Bash for: builds, installs, git, network, processes\n- Read and understand existing code before modifying\n- Delete unused code completely — no compatibility shims\n\n## Code Philosophy\n- Do not create abstractions for one-time operations\n- Complete the task fully — don't gold-plate, but don't leave it half-done\n- Prefer editing existing files over creating new ones\n\n## First Turn Protocol\n\nAt the start of every session, before doing ANY work:\n1. Run \\`pwd && ls -la && git status --short\\` to orient yourself\n2. Check relevant runtimes (e.g. \\`node --version\\`, \\`python3 --version\\` — pick what fits this project)\n3. Read any task-tracking files (docs/SPRINT.md, docs/DECISIONS.md)\n4. Summarize what you see in 2-3 lines, then proceed\n\nThis saves 2-5 exploratory turns. Never ask \"what files are here?\" — look first.\n\n## Sprint Contract\n\nBefore implementing, confirm acceptance criteria exist in docs/SPRINT.md.\nEach criterion must be numbered, testable, and independently verifiable.\nAfter implementing, verify EACH criterion individually. Do not mark done until all pass.\n\n## Completion Standards\n\nNever mark a task \"done\" without running the Completion Verification checklist.\nTests passing is necessary but not sufficient — also verify requirements coverage,\nstate cleanliness, and review changes from the perspective of a test engineer,\ncode reviewer, and the requesting user.\n\\`\\`\\`\n\nDo not add generic filler. Every line must be specific to the user's workflow.\n\n## What You Must Always Include\n\n1. A concise, workflow-specific \\`claude_md\\` (the CLAUDE.md content)\n2. A \\`/project:help\\` command that explains the environment\n3. A \\`docs/DECISIONS.md\\` file for architectural decisions\n4. A \\`docs/LEARNINGS.md\\` file for non-obvious discoveries\n5. A \\`rules/continuity.md\\` rule encouraging updates to DECISIONS.md and LEARNINGS.md\n6. A \\`rules/security.md\\` rule with essential security instructions\n7. settings.json with deny rules for \\`rm -rf\\`, \\`curl|sh\\`, reading \\`.env\\` and \\`secrets/\\`\n8. A \\`/project:status\\` command for code projects (uses ! for live git/SPRINT.md output)\n9. A \\`/project:fix\\` command for code projects (uses $ARGUMENTS for issue number)\n10. A \\`docs/SPRINT.md\\` file as the living spec/plan (replaces TODO.md — acceptance criteria, verification steps)\n11. A \"Verification\" section in CLAUDE.md with concrete verify commands for the project\n12. A \"Known Gotchas\" section in CLAUDE.md (starts empty, grows with corrections)\n13. A \"Debugging\" section in CLAUDE.md (2 lines: paste raw errors, use subagents)\n14. A \"Git Workflow\" section in CLAUDE.md (3 rules: small commits, conventional format, <200 lines PR)\n15. \"Engineering Standards\", \"Tool Usage Policy\", and \"Code Philosophy\" sections in CLAUDE.md\n16. A \"First Turn Protocol\" section in CLAUDE.md (orient before working: pwd, ls, git status, check relevant runtimes, read task files)\n17. A \"Completion Standards\" section in CLAUDE.md (never mark done without verifying: requirements met, tests passing, no debug artifacts, reviewed from 3 perspectives)\n18. A \"Sprint Contract\" section in CLAUDE.md (confirm acceptance criteria exist before implementing, verify each criterion after)\n\n## Shell-Integrated Commands\n\nCommands that reference live project state should use Claude Code's \\`!\\` prefix for shell output:\n\n\\`\\`\\`markdown\n# Example: .claude/commands/review.md\nReview the staged changes for quality and security:\n\n!git diff --staged\n\nRun tests and check for failures:\n\n!npm test 2>&1 | tail -20\n\nFocus on: security, error handling, test coverage.\n\\`\\`\\`\n\nUse \\`!\\` when a command needs: git status, test results, build output, or file listings.\n\n## Path-Scoped Rules\n\nFor code projects with multiple domains (API, frontend, tests), generate path-scoped rules using YAML frontmatter:\n\n\\`\\`\\`markdown\n# Example: rules/api.md\n---\npaths:\n - \"src/api/**\"\n - \"src/routes/**\"\n---\n- All handlers return { data, error } shape\n- Use Zod for request validation\n- Log errors with request ID context\n\\`\\`\\`\n\n\\`\\`\\`markdown\n# Example: rules/testing.md\n---\npaths:\n - \"tests/**\"\n - \"**/*.test.*\"\n - \"**/*.spec.*\"\n---\n- Use AAA pattern: Arrange-Act-Assert\n- One assertion per test when possible\n- Mock external dependencies, never real APIs\n\\`\\`\\`\n\nKeep \\`security.md\\` and \\`continuity.md\\` as unconditional (no paths frontmatter).\nOnly generate scoped rules when the workflow involves multiple code domains.\n\n## Hooks\n\nGenerate hooks in settings.json based on project type:\n\n**All code projects** — block destructive commands, credential leaks, injection, and network exfiltration:\n\\`\\`\\`json\n{\n \"hooks\": {\n \"PreToolUse\": [\n {\n \"matcher\": \"Bash\",\n \"hooks\": [{\n \"type\": \"command\",\n \"command\": \"CMD=$(cat | jq -r '.tool_input.command // empty') && echo \\\\\"$CMD\\\\\" | grep -qiE 'rm\\\\\\\\s+-rf\\\\\\\\s+/|DROP\\\\\\\\s+(TABLE|DATABASE)|curl.*\\\\\\\\|\\\\\\\\s*sh|:(){ :|:& };:|git\\\\\\\\s+push.*--force(?!-with-lease)|ch(mod|own).*-R\\\\\\\\s+/|npm\\\\\\\\s+publish(?!.*--dry-run)|(api[_-]?key|secret|token|password)\\\\\\\\s*[:=]|AKIA[0-9A-Z]{16}|BEGIN.*PRIVATE\\\\\\\\s+KEY|;\\\\\\\\s*(DROP|DELETE|ALTER|TRUNCATE)\\\\\\\\s+|\\\\\\\\.\\\\\\\\./\\\\\\\\.\\\\\\\\./\\\\\\\\.\\\\\\\\.\\/|nc\\\\\\\\s+.*-e|/dev/tcp/|bash\\\\\\\\s+-i|curl.*-d.*@|wget.*--post-file' && echo 'Blocked dangerous command' >&2 && exit 2 || true\"\n }]\n }\n ]\n }\n}\n\\`\\`\\`\n\n**Projects with Prettier/ESLint/Black** — auto-format on write:\n\\`\\`\\`json\n{\n \"hooks\": {\n \"PostToolUse\": [{\n \"matcher\": \"Edit|Write\",\n \"hooks\": [{\n \"type\": \"command\",\n \"command\": \"FILE=$(cat | jq -r '.tool_input.file_path // empty') && [ -n \\\\\"$FILE\\\\\" ] && npx prettier --write \\\\\"$FILE\\\\\" 2>/dev/null || true\"\n }]\n }]\n }\n}\n\\`\\`\\`\n\nMerge hooks into the \\`settings\\` object alongside permissions. Choose the formatter hook based on detected dependencies (Prettier → prettier, ESLint → eslint, Black → black).\n\n## PostCompact Hook\n\nAll projects should include a PostCompact hook to restore context after compaction:\n\n\\`\\`\\`json\n{\n \"hooks\": {\n \"PostCompact\": [{\n \"matcher\": \"\",\n \"hooks\": [{\n \"type\": \"prompt\",\n \"prompt\": \"Re-read CLAUDE.md and docs/SPRINT.md (if it exists) to restore project context after compaction.\"\n }]\n }]\n }\n}\n\\`\\`\\`\n\nMerge this into the settings hooks alongside the PreToolUse and PostToolUse hooks.\n\nFor long-running sessions (>2 hours or >3 compactions), prefer \"Full Reset\" over re-inject:\nreplace the prompt-type PostCompact hook with a command-type hook that pipes CLAUDE.md + SPRINT.md + DECISIONS.md content directly into additionalContext.\n\n## Memory Persistence Hooks\n\nFor projects with multi-session workflows, include SessionStart/End hooks that persist context to \\`.claude/memory.json\\`:\n- **SessionEnd:** Save recent decisions, sprint status, and known gotchas to \\`.claude/memory.json\\`\n- **SessionStart:** Load \\`.claude/memory.json\\` and inject as additionalContext\n\nThis ensures accumulated project knowledge survives session boundaries.\n\n## For Code Projects, Additionally Include\n\n- \\`/project:plan\\` command (plan before coding)\n- \\`/project:review\\` command (review changes)\n- \\`/project:test\\` command (run and fix tests)\n- \\`/project:commit\\` command (conventional commits)\n- \\`/project:status\\` command (live git status, recent commits, SPRINT.md overview using ! prefix)\n- \\`/project:fix\\` command (takes $ARGUMENTS as issue number, plans fix, implements, tests, commits)\n- \\`/project:sprint\\` command (define acceptance criteria before coding, writes to docs/SPRINT.md)\n- \\`/project:develop\\` command (full development pipeline — orchestrates @architect → @planner → @implementer → @verifier → @fixer → @grill → @doc-updater through spec, plan, TDD implement, review, and doc update phases). Phase 4 (Verify) MUST validate EACH acceptance criterion from docs/SPRINT.md individually, reporting PASS/FAIL per item as a contract scorecard. MUST include a Phase 7 \"Completion Gate\" that runs a Completion Verification checklist before marking the feature done: re-read original requirements, confirm each is met with evidence, run test suite + lint/typecheck, review git diff for unexpected changes or debug artifacts, answer 3 perspective questions (test engineer, code reviewer, requesting user). If ANY check fails, loop back to fix before completing.\n- A TDD skill using the 3-phase isolation pattern (RED → GREEN → REFACTOR):\n - RED: Write failing test only. Verify it FAILS.\n - GREEN: Write MINIMUM code to pass. Nothing extra.\n - REFACTOR: Improve while keeping tests green.\n Rules: never write tests and implementation in same step, AAA pattern, one assertion per test.\n- A multi-agent QA pipeline:\n - \\`@qa-orchestrator\\` (sonnet) — delegates to linter and e2e-tester, compiles QA report\n - \\`@linter\\` (haiku) — runs formatters, linters, security scanners\n - \\`@e2e-tester\\` (sonnet, only when Playwright is in tools) — browser-based QA via Playwright\n- A \"Model Selection\" section in generated agents:\n \\`\\`\\`\n ## Model Selection (all agents)\n - Haiku: simple file edits, linting, formatting, doc updates (<50 lines changed)\n - Sonnet: implementation, testing, debugging, code review (50-500 lines)\n - Opus: architecture decisions, spec writing, complex refactors (>500 lines or cross-cutting)\n Default: Sonnet. Only escalate to Opus when the task involves multi-file architecture or ambiguous requirements.\n \\`\\`\\`\n- Development pipeline agents (used by /project:develop). Each agent should include a modelRouting field in its YAML frontmatter:\n - \\`@architect\\` (default: opus) — conducts spec interview with user, writes confirmed spec to docs/SPRINT.md with numbered acceptance criteria. Your spec is a CONTRACT — the verifier will check every criterion. Vague criteria = guaranteed rework.\n - \\`@planner\\` (default: sonnet, escalate to opus for cross-cutting changes) — reads spec and codebase, creates step-by-step implementation plan in docs/PLAN.md\n - \\`@implementer\\` (default: sonnet, escalate to opus for cross-cutting changes) — TDD-focused implementation, writes failing tests then minimum code to pass\n - \\`@fixer\\` (default: sonnet, use haiku for single-file fixes) — targeted bug fixing from verifier/review feedback\n - \\`@doc-updater\\` (default: haiku) — extracts decisions and learnings from completed work, updates docs/DECISIONS.md and docs/LEARNINGS.md\n- \\`/project:spec\\` command (interview-based spec creation — asks 5-8 questions one at a time, writes structured spec to docs/SPRINT.md with ## Acceptance Criteria containing 3-8 numbered, testable conditions. Each criterion must be independently verifiable. Does NOT start coding until confirmed)\n- \\`/project:prove\\` command (runs tests, shows git diff vs main, rates confidence HIGH/MEDIUM/LOW with evidence)\n- \\`/project:grill\\` command (adversarial code review — challenges each change with \"why this approach?\", \"what if X input?\", rates BLOCKER/SHOULD-FIX/NITPICK, blocks until BLOCKERs resolved)\n- \\`/project:reset\\` command (reads DECISIONS.md and LEARNINGS.md, proposes clean restart, stashes current work, implements elegant solution)\n\n## For Research Projects, Additionally Include\n\n- \\`/project:research\\` command (deep research on a topic)\n- \\`/project:summarize\\` command (summarize findings)\n- A research-synthesis skill\n- A researcher agent\n- Note: the Verification section in CLAUDE.md should adapt for research — e.g. \"Verify all sources are cited\" instead of build/test commands\n\n## For Content/Writing Projects, Additionally Include\n\n- \\`/project:draft\\` command (write first draft)\n- \\`/project:edit\\` command (review and improve writing)\n- A writing-workflow skill\n\n## Hermes Runtime\n\nWhen generating for Hermes runtime, the same EnvironmentSpec JSON is produced. The adapter layer handles conversion:\n- MCP config entries → Hermes config.yaml mcp_servers\n- Commands and skills → ~/.hermes/skills/ markdown files\n- Rules → ~/.hermes/skills/rule-*.md files\n\nThe LLM output format does not change. Adapter-level conversion happens post-compilation.\n\n## Autonomy Levels\n\nThe user may specify an autonomy level (1-4). This affects CLAUDE.md content:\n\n- **Level 1 (Guided):** Add a \"Workflow\" section showing recommended command flow (e.g., spec → sprint → plan → code → prove → grill → commit) and a \"When to Use What\" reference table.\n- **Level 2 (Assisted):** Level 1 content + mention /project:loop in the workflow section and @pm in the agents section of CLAUDE.md.\n- **Level 3 (Autonomous):** Level 2 content + mention /project:auto and worktree-based PR delivery workflow.\n- **Level 4 (Full Auto):** Level 3 content + add a prominent warning section about autonomous operation.\n\nThe autonomy-specific commands, agents, and hooks are injected post-compilation. Focus on tailoring the CLAUDE.md content and workflow guidance for the selected level.\n\nIf no autonomy level is specified, assume Level 1 (Guided).\n\n## Output Schema\n\nReturn ONLY valid JSON matching this structure:\n\n\\`\\`\\`json\n{\n \"claude_md\": \"Full CLAUDE.md content (under 150 lines)\",\n \"commands\": { \"help\": \"...\", \"develop\": \"...\", \"status\": \"...\", \"fix\": \"...\", \"sprint\": \"...\", \"spec\": \"...\", \"prove\": \"...\", \"grill\": \"...\", \"reset\": \"...\" },\n \"rules\": { \"continuity\": \"...\", \"security\": \"...\" },\n \"agents\": { \"architect\": \"...\", \"planner\": \"...\", \"implementer\": \"...\", \"fixer\": \"...\", \"doc-updater\": \"...\", \"qa-orchestrator\": \"...\", \"linter\": \"...\", \"e2e-tester\": \"...\" },\n \"skills\": { \"skill-name/SKILL\": \"...\" },\n \"docs\": { \"DECISIONS\": \"...\", \"LEARNINGS\": \"...\", \"SPRINT\": \"...\" }\n}\n\\`\\`\\`\n\nReturn ONLY valid JSON. No markdown fences. No text outside the JSON.`;\n\nexport const SYSTEM_PROMPT = `You are the Kairn environment compiler. Your job is to generate a minimal, optimal Claude Code agent environment from a user's natural language description of what they want their agent to do.\n\nYou will receive:\n1. The user's intent (what they want to build/do)\n2. A tool registry (available MCP servers, plugins, and hooks)\n\nYou must output a JSON object matching the EnvironmentSpec schema.\n\n## Core Principles\n\n- **Minimalism over completeness.** Fewer, well-chosen tools beat many generic ones. Each MCP server costs 500-2000 context tokens.\n- **Workflow-specific, not generic.** Every instruction, command, and rule must relate to the user's actual workflow.\n- **Concise CLAUDE.md.** Under 150 lines. No generic text like \"be helpful.\" Include build/test commands, reference docs/ and skills/.\n- **Security by default.** Always include deny rules for destructive commands and secret file access.\n\n## CLAUDE.md Template (mandatory structure)\n\nThe \\`claude_md\\` field MUST follow this exact structure (max 150 lines):\n\n\\`\\`\\`\n# {Project Name}\n\n## Purpose\n{one-line description}\n\n## Tech Stack\n{bullet list of frameworks/languages}\n\n## Commands\n{concrete build/test/lint/dev commands}\n\n## Architecture\n{brief folder structure, max 10 lines}\n\n## Conventions\n{3-5 specific coding rules}\n\n## Key Commands\n{list /project: commands with descriptions}\n\n## Output\n{where results go, key files}\n\n## Verification\nAfter implementing any change, verify it works:\n- {build command} — must pass with no errors\n- {test command} — all tests must pass\n- {lint command} — no warnings or errors\n- {type check command} — no type errors\n\nIf any verification step fails, fix the issue before moving on.\nDo NOT skip verification steps.\n\n## Known Gotchas\n<!-- After any correction, add it here: \"Update CLAUDE.md so you don't make that mistake again.\" -->\n<!-- Prune this section when it exceeds 10 items — keep only the recurring ones. -->\n- (none yet — this section grows as you work)\n\n## Debugging\nWhen debugging, paste raw error output. Don't summarize — Claude works better with raw data.\nUse subagents for deep investigation to keep main context clean.\n\n## Git Workflow\n- Prefer small, focused commits (one feature or fix per commit)\n- Use conventional commits: feat:, fix:, docs:, refactor:, test:\n- Target < 200 lines per PR when possible\n\n## Engineering Standards\n- Lead with answers over reasoning. Be concise.\n- Use absolute file paths in all references.\n- No filler, no inner monologue, no time estimates.\n- Produce load-bearing code — every line of output should be actionable.\n\n## Tool Usage Policy\n- Prefer Edit tool over sed/awk for file modifications\n- Prefer Grep tool over rg for searching\n- Prefer Read tool over cat for file reading\n- Reserve Bash for: builds, installs, git, network, processes\n- Read and understand existing code before modifying\n- Delete unused code completely — no compatibility shims\n\n## Code Philosophy\n- Do not create abstractions for one-time operations\n- Complete the task fully — don't gold-plate, but don't leave it half-done\n- Prefer editing existing files over creating new ones\n\n## First Turn Protocol\n\nAt the start of every session, before doing ANY work:\n1. Run \\`pwd && ls -la && git status --short\\` to orient yourself\n2. Check relevant runtimes (e.g. \\`node --version\\`, \\`python3 --version\\` — pick what fits this project)\n3. Read any task-tracking files (docs/SPRINT.md, docs/DECISIONS.md)\n4. Summarize what you see in 2-3 lines, then proceed\n\nThis saves 2-5 exploratory turns. Never ask \"what files are here?\" — look first.\n\n## Sprint Contract\n\nBefore implementing, confirm acceptance criteria exist in docs/SPRINT.md.\nEach criterion must be numbered, testable, and independently verifiable.\nAfter implementing, verify EACH criterion individually. Do not mark done until all pass.\n\n## Completion Standards\n\nNever mark a task \"done\" without running the Completion Verification checklist.\nTests passing is necessary but not sufficient — also verify requirements coverage,\nstate cleanliness, and review changes from the perspective of a test engineer,\ncode reviewer, and the requesting user.\n\\`\\`\\`\n\nDo not add generic filler. Every line must be specific to the user's workflow.\n\n## What You Must Always Include\n\n1. A concise, workflow-specific \\`claude_md\\` (the CLAUDE.md content)\n2. A \\`/project:help\\` command that explains the environment\n3. A \\`docs/DECISIONS.md\\` file for architectural decisions\n4. A \\`docs/LEARNINGS.md\\` file for non-obvious discoveries\n5. A \\`rules/continuity.md\\` rule encouraging updates to DECISIONS.md and LEARNINGS.md\n6. A \\`rules/security.md\\` rule with essential security instructions\n7. settings.json with deny rules for \\`rm -rf\\`, \\`curl|sh\\`, reading \\`.env\\` and \\`secrets/\\`\n8. A \\`/project:status\\` command for code projects (uses ! for live git/SPRINT.md output)\n9. A \\`/project:fix\\` command for code projects (uses $ARGUMENTS for issue number)\n10. A \\`docs/SPRINT.md\\` file as the living spec/plan (replaces TODO.md — acceptance criteria, verification steps)\n11. A \"Verification\" section in CLAUDE.md with concrete verify commands for the project\n12. A \"Known Gotchas\" section in CLAUDE.md (starts empty, grows with corrections)\n13. A \"Debugging\" section in CLAUDE.md (2 lines: paste raw errors, use subagents)\n14. A \"Git Workflow\" section in CLAUDE.md (3 rules: small commits, conventional format, <200 lines PR)\n15. \"Engineering Standards\", \"Tool Usage Policy\", and \"Code Philosophy\" sections in CLAUDE.md\n16. A \"First Turn Protocol\" section in CLAUDE.md (orient before working: pwd, ls, git status, check relevant runtimes, read task files)\n17. A \"Completion Standards\" section in CLAUDE.md (never mark done without verifying: requirements met, tests passing, no debug artifacts, reviewed from 3 perspectives)\n18. A \"Sprint Contract\" section in CLAUDE.md (confirm acceptance criteria exist before implementing, verify each criterion after)\n\n## Tool Selection Rules\n\n- Only select tools directly relevant to the described workflow\n- Prefer free tools (auth: \"none\") when quality is comparable\n- Tier 1 tools (Context7, Sequential Thinking, security-guidance) should be included in most environments\n- For tools requiring API keys (auth: \"api_key\"), use \\${ENV_VAR} syntax — never hardcode keys\n- Maximum 6-8 MCP servers to avoid context bloat\n- Include a \\`reason\\` for each selected tool explaining why it fits this workflow\n\n## Context Budget (STRICT)\n\n- MCP servers: maximum 6. Prefer fewer.\n- CLAUDE.md: maximum 150 lines.\n- Rules: maximum 5 files, each under 20 lines.\n- Skills: maximum 3. Only include directly relevant ones.\n- Agents: maximum 5. Orchestration pipeline (/develop) agents.\n- Commands: no limit (loaded on demand, zero context cost).\n- Hooks: maximum 4 (auto-format, block-destructive, PostCompact, plus one contextual).\n\nIf the workflow doesn't clearly need a tool, DO NOT include it.\nEach MCP server costs 500-2000 tokens of context window.\n\n## Output Schema\n\nReturn ONLY valid JSON matching this structure:\n\n\\`\\`\\`json\n{\n \"name\": \"short-kebab-case-name\",\n \"description\": \"One-line description of the environment\",\n \"tools\": [\n { \"tool_id\": \"id-from-registry\", \"reason\": \"why this tool fits\" }\n ],\n \"harness\": {\n \"claude_md\": \"The full CLAUDE.md content (under 150 lines)\",\n \"settings\": {\n \"permissions\": {\n \"allow\": [\"Bash(npm run *)\", \"Read\", \"Write\", \"Edit\"],\n \"deny\": [\"Bash(rm -rf *)\", \"Bash(curl * | sh)\", \"Read(./.env)\", \"Read(./secrets/**)\"]\n }\n },\n \"mcp_config\": {\n \"server-name\": { \"command\": \"npx\", \"args\": [\"...\"], \"env\": {} }\n },\n \"commands\": {\n \"help\": \"markdown content for /project:help\",\n \"develop\": \"markdown content for /project:develop\"\n },\n \"rules\": {\n \"continuity\": \"markdown content for continuity rule\",\n \"security\": \"markdown content for security rule\"\n },\n \"skills\": {\n \"skill-name/SKILL\": \"markdown content with YAML frontmatter\"\n },\n \"agents\": {\n \"architect\": \"agent markdown with YAML frontmatter\",\n \"planner\": \"agent markdown with YAML frontmatter\",\n \"implementer\": \"agent markdown with YAML frontmatter\",\n \"fixer\": \"agent markdown with YAML frontmatter\",\n \"doc-updater\": \"agent markdown with YAML frontmatter\"\n },\n \"docs\": {\n \"DECISIONS\": \"# Decisions\\\\n\\\\nArchitectural decisions.\",\n \"LEARNINGS\": \"# Learnings\\\\n\\\\nNon-obvious discoveries.\",\n \"SPRINT\": \"# Sprint\\\\n\\\\nLiving spec and plan.\"\n }\n }\n}\n\\`\\`\\`\n\nDo not include any text outside the JSON object. Do not wrap in markdown code fences.`;\n\nexport const CLARIFICATION_PROMPT = `You are helping a user define their project for environment compilation.\n\nGiven their initial description, generate 3-5 clarifying questions to understand:\n1. Language and framework\n2. What the project specifically does (be precise)\n3. Primary workflow (build, research, write, analyze?)\n4. Key dependencies or integrations\n5. Target audience\n\nFor each question, provide a reasonable suggestion based on the description.\n\nOutput ONLY a JSON array:\n[\n { \"question\": \"Language/framework?\", \"suggestion\": \"TypeScript + Node.js\" },\n ...\n]\n\nRules:\n- Suggestions should be reasonable guesses, clearly marked as suggestions\n- Keep questions short (under 10 words)\n- Maximum 5 questions\n- If the description is already very detailed, ask fewer questions`;\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { getUserRegistryPath } from \"../config.js\";\nimport type { RegistryTool } from \"../types.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport async function loadBundledRegistry(): Promise<RegistryTool[]> {\n const candidates = [\n path.resolve(__dirname, \"../registry/tools.json\"),\n path.resolve(__dirname, \"../src/registry/tools.json\"),\n path.resolve(__dirname, \"../../src/registry/tools.json\"),\n ];\n for (const candidate of candidates) {\n try {\n const data = await fs.readFile(candidate, \"utf-8\");\n return JSON.parse(data) as RegistryTool[];\n } catch {\n continue;\n }\n }\n throw new Error(\"Could not find tools.json registry\");\n}\n\nexport async function loadUserRegistry(): Promise<RegistryTool[]> {\n try {\n const data = await fs.readFile(getUserRegistryPath(), \"utf-8\");\n return JSON.parse(data) as RegistryTool[];\n } catch {\n return [];\n }\n}\n\nexport async function saveUserRegistry(tools: RegistryTool[]): Promise<void> {\n await fs.writeFile(getUserRegistryPath(), JSON.stringify(tools, null, 2), \"utf-8\");\n}\n\nexport async function loadRegistry(): Promise<RegistryTool[]> {\n const bundled = await loadBundledRegistry();\n const user = await loadUserRegistry();\n\n if (user.length === 0) return bundled;\n\n // User tools take precedence by ID\n const merged = new Map<string, RegistryTool>();\n for (const tool of bundled) {\n merged.set(tool.id, tool);\n }\n for (const tool of user) {\n merged.set(tool.id, tool);\n }\n return Array.from(merged.values());\n}\n","import type { IntentPattern } from './types.js';\n\n/** Static synonym map: verb → alternative phrases users might say */\nconst SYNONYM_MAP: Record<string, string[]> = {\n deploy: ['ship', 'push\\\\s+to\\\\s+prod', 'release', 'publish'],\n test: ['run\\\\s+tests', 'check', 'verify', 'run\\\\s+test\\\\s+suite'],\n lint: ['format', 'style\\\\s+check', 'linting'],\n build: ['compile', 'bundle', 'make'],\n dev: ['develop', 'start\\\\s+dev', 'run\\\\s+dev'],\n start: ['run', 'launch', 'serve'],\n migrate: ['migration', 'schema\\\\s+change', 'db\\\\s+update'],\n seed: ['populate', 'seed\\\\s+data', 'load\\\\s+fixtures'],\n clean: ['purge', 'clear', 'reset\\\\s+cache'],\n docs: ['document', 'documentation', 'write\\\\s+docs'],\n review: ['code\\\\s+review', 'pr\\\\s+review', 'check\\\\s+code'],\n commit: ['save\\\\s+changes', 'check\\\\s+in', 'git\\\\s+commit'],\n fix: ['repair', 'patch', 'debug', 'resolve'],\n refactor: ['restructure', 'reorganize', 'clean\\\\s+up'],\n plan: ['design', 'architect', 'outline'],\n status: ['progress', 'overview', 'summary'],\n};\n\n/**\n * Extract the first description line from command markdown content.\n * Skips the heading line (starts with #) and returns the next non-empty line.\n */\nfunction extractDescription(content: string): string {\n const lines = content.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n return trimmed;\n }\n }\n return '';\n}\n\n/**\n * Extract the primary verb from a command name.\n * Handles hyphenated names like \"db-migrate\" → \"migrate\".\n */\nfunction extractVerb(commandName: string): string {\n const parts = commandName.split('-');\n // For multi-part names, the verb is usually the last part\n // \"db-migrate\" → \"migrate\", \"test\" → \"test\"\n if (parts.length > 1) {\n return parts[parts.length - 1];\n }\n return parts[0];\n}\n\n/**\n * Build a regex alternation from a command name and its synonyms.\n */\nfunction buildPatternAlternation(commandName: string): string {\n const verb = extractVerb(commandName);\n const alternatives = [verb];\n\n // Add synonyms if available\n const synonyms = SYNONYM_MAP[verb];\n if (synonyms) {\n alternatives.push(...synonyms);\n }\n\n // Add the full command name if it differs from the verb\n if (commandName !== verb && !alternatives.includes(commandName)) {\n alternatives.push(commandName.replace(/-/g, '[\\\\s-]'));\n }\n\n return `\\\\b(${alternatives.join('|')})\\\\b`;\n}\n\n/**\n * Generate intent patterns from npm scripts that aren't covered by commands.\n */\nfunction generateScriptPatterns(\n scripts: Record<string, string>,\n existingCommands: Set<string>,\n): IntentPattern[] {\n const patterns: IntentPattern[] = [];\n\n for (const scriptName of Object.keys(scripts)) {\n // Skip if a command already covers this script\n const verb = extractVerb(scriptName);\n if (existingCommands.has(verb) || existingCommands.has(scriptName)) {\n continue;\n }\n\n // Handle composite script names like \"test:e2e\"\n const parts = scriptName.split(':');\n if (parts.length > 1) {\n const suffix = parts[parts.length - 1];\n const alternatives = [suffix];\n\n // Add common expansions\n if (suffix === 'e2e') {\n alternatives.push('end[\\\\s.-]to[\\\\s.-]end');\n }\n\n patterns.push({\n pattern: `\\\\b(${alternatives.join('|')})\\\\b`,\n command: `/project:${scriptName}`,\n description: `Run npm script: ${scriptName}`,\n source: 'generated',\n });\n }\n }\n\n return patterns;\n}\n\n/**\n * Generate intent patterns from generated commands and project context.\n *\n * For each command, produces regex patterns from the command name,\n * synonyms from a static map, and framework-specific verbs.\n * Patterns are sorted by specificity (longer patterns first).\n */\nexport function generateIntentPatterns(\n commands: Record<string, string>,\n agents: Record<string, string>,\n projectProfile: { language: string; framework: string; scripts: Record<string, string> },\n): IntentPattern[] {\n const patterns: IntentPattern[] = [];\n const commandNames = new Set(Object.keys(commands));\n\n // Generate patterns for each command\n for (const [name, content] of Object.entries(commands)) {\n const description = extractDescription(content);\n const patternStr = buildPatternAlternation(name);\n\n patterns.push({\n pattern: patternStr,\n command: `/project:${name}`,\n description: description || `Run ${name} workflow`,\n source: 'generated',\n });\n }\n\n // Add patterns from npm scripts not already covered\n const scriptPatterns = generateScriptPatterns(\n projectProfile.scripts,\n commandNames,\n );\n patterns.push(...scriptPatterns);\n\n // Sort by specificity: longer patterns first (more specific = higher priority)\n patterns.sort((a, b) => b.pattern.length - a.pattern.length);\n\n return patterns;\n}\n","/**\n * Extract the first description line from command/agent markdown content.\n * Skips heading lines (starting with #) and returns the first non-empty line.\n */\nfunction extractFirstLine(content: string): string {\n const lines = content.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n return trimmed;\n }\n }\n return '';\n}\n\n/**\n * Compile the Tier 2 intent classification prompt.\n *\n * Builds a project-specific prompt by extracting first-line descriptions\n * from each command and agent, then embedding them into a classification\n * template. The resulting prompt is baked into settings.json at generation\n * time — no runtime template interpolation needed.\n */\nexport function compileIntentPrompt(\n commands: Record<string, string>,\n agents: Record<string, string>,\n): string {\n // Build workflow manifest\n const workflowLines: string[] = [];\n for (const [name, content] of Object.entries(commands)) {\n const desc = extractFirstLine(content);\n workflowLines.push(`- /project:${name} — ${desc}`);\n }\n const workflowManifest = workflowLines.length > 0\n ? workflowLines.join('\\n')\n : '(no workflows defined)';\n\n // Build agent manifest\n const agentLines: string[] = [];\n for (const [name, content] of Object.entries(agents)) {\n const desc = extractFirstLine(content);\n agentLines.push(`- @${name} — ${desc}`);\n }\n const agentManifest = agentLines.length > 0\n ? agentLines.join('\\n')\n : '(no agents defined)';\n\n return `You are an intent classifier for a software project. The user said something that didn't match any known command keyword.\n\nAvailable workflows:\n${workflowManifest}\n\nAvailable agents:\n${agentManifest}\n\nUser input: $PROMPT\n\nIf this maps to one or more workflows, return JSON:\n{\"additionalContext\": \"[INTENT ROUTED] Based on your request, use: /project:<command> — <description>\"}\n\nIf the user is asking a question or making a statement that doesn't need a workflow, return:\n{\"ok\": true}\n\nDo not activate workflows for questions like 'what does deploy do?' or 'how do I test?'. Only activate for action requests.`;\n}\n","import type { IntentPattern } from './types.js';\n\n/**\n * Render a pattern entry as a JavaScript object literal for embedding\n * in the generated intent-router.mjs script.\n */\nfunction renderPatternEntry(p: IntentPattern): string {\n // Escape backslashes for embedding in a JS regex literal\n const escapedPattern = p.pattern.replace(/\\\\/g, '\\\\\\\\');\n const escapedDesc = p.description.replace(/'/g, \"\\\\'\");\n const escapedCmd = p.command.replace(/'/g, \"\\\\'\");\n return ` { pattern: /${p.pattern}/i,\\n command: '${escapedCmd}',\\n description: '${escapedDesc}' }`;\n}\n\n/**\n * Render the full intent-router.mjs script.\n *\n * This generates a Node.js ESM script that:\n * 1. Reads the user prompt from stdin (Claude Code hooks API)\n * 2. Sanitizes it (strips code blocks, URLs, file paths)\n * 3. Filters out informational questions\n * 4. Matches against project-specific regex patterns\n * 5. Returns additionalContext on match, or falls through to Tier 2\n */\nexport function renderIntentRouter(\n patterns: IntentPattern[],\n generationTimestamp: string,\n): string {\n const patternEntries = patterns\n .map(p => renderPatternEntry(p))\n .join(',\\n');\n\n return `#!/usr/bin/env node\n/**\n * Kairn Intent Router — Tier 1 (Regex)\n * Generated by kairn describe. Project-specific keyword patterns.\n *\n * If a keyword matches, injects a system-reminder pointing Claude\n * to the right command/workflow. If no match, falls through to\n * the Tier 2 prompt hook.\n *\n * Last updated: ${generationTimestamp}\n */\n\nimport { readFileSync } from 'fs';\n\n// Read prompt from stdin (Claude Code hooks API)\nconst input = readFileSync('/dev/stdin', 'utf-8');\nlet prompt = '';\ntry {\n const data = JSON.parse(input);\n prompt = data.prompt || '';\n} catch { process.exit(0); }\n\nif (!prompt.trim()) {\n console.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n process.exit(0);\n}\n\n// Sanitize: strip code blocks, URLs, file paths\nconst clean = prompt\n .replace(/\\`\\`\\`[\\\\s\\\\S]*?\\`\\`\\`/g, '')\n .replace(/\\`[^\\`]+\\`/g, '')\n .replace(/https?:\\\\/\\\\/\\\\S+/g, '')\n .replace(/(\\\\/[\\\\w.-]+){2,}/g, '')\n .toLowerCase();\n\n// Question filter: don't trigger on informational queries\nconst QUESTION_PATTERNS = [\n /\\\\b(?:what(?:'s|\\\\s+is)|how\\\\s+(?:to|do\\\\s+i)\\\\s+use|explain|describe|tell\\\\s+me\\\\s+about)\\\\b/i,\n];\nfunction isQuestion(text, position, length) {\n const start = Math.max(0, position - 80);\n const end = Math.min(text.length, position + length + 80);\n const ctx = text.slice(start, end);\n return QUESTION_PATTERNS.some(p => p.test(ctx));\n}\n\n// ═══════════════════════════════════════════════\n// PROJECT-SPECIFIC KEYWORD PATTERNS\n// Generated from: kairn describe analysis\n// Last updated: ${generationTimestamp}\n// ═══════════════════════════════════════════════\n\nconst PATTERNS = [\n${patternEntries}\n];\n\n// Match against patterns\nfor (const { pattern, command, description } of PATTERNS) {\n const match = clean.match(pattern);\n if (match && !isQuestion(clean, match.index, match[0].length)) {\n const output = {\n \"continue\": true,\n hookSpecificOutput: {\n hookEventName: 'UserPromptSubmit',\n additionalContext: \\`[INTENT ROUTED] Based on your request, use: \\${command} — \\${description}\\\\n\\\\nUser's original request: \\${prompt}\\\\n\\\\nExecute the command above to fulfill the user's intent.\\`\n }\n };\n console.log(JSON.stringify(output));\n process.exit(0);\n }\n}\n\n// No match — fall through to Tier 2 (prompt hook)\nconsole.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n`;\n}\n","/**\n * Render the intent-learner.mjs script.\n *\n * This generates a static Node.js ESM script (not project-specific) that:\n * 1. Reads .claude/hooks/intent-log.jsonl\n * 2. Groups entries by routed_to command\n * 3. For commands with 3+ entries: extracts common words, builds regex\n * 4. Appends new patterns to intent-router.mjs PATTERNS array\n * 5. Writes audit log to intent-promotions.jsonl\n * 6. Truncates processed entries from log\n */\nexport function renderIntentLearner(): string {\n return `#!/usr/bin/env node\n/**\n * Kairn Intent Learner — Pattern Promotion (Tier 2 → Tier 1)\n * Runs on SessionStart to promote recurring Tier 2 patterns to Tier 1 regexes.\n * Generated by kairn describe.\n */\n\nimport { readFileSync, writeFileSync, appendFileSync, existsSync } from 'fs';\nimport { join, dirname } from 'path';\n\nconst hooksDir = join(dirname(new URL(import.meta.url).pathname));\nconst logPath = join(hooksDir, 'intent-log.jsonl');\nconst routerPath = join(hooksDir, 'intent-router.mjs');\nconst promotionsPath = join(hooksDir, 'intent-promotions.jsonl');\n\n// Read log entries\nlet entries = [];\ntry {\n const raw = readFileSync(logPath, 'utf-8').trim();\n if (!raw) {\n console.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n process.exit(0);\n }\n entries = raw.split('\\\\n').map(line => {\n try { return JSON.parse(line); }\n catch { return null; }\n }).filter(Boolean);\n} catch {\n // Log file doesn't exist or is unreadable — nothing to promote\n console.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n process.exit(0);\n}\n\nif (entries.length === 0) {\n console.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n process.exit(0);\n}\n\n// Group by routed_to command\nconst groups = {};\nconst remaining = [];\nfor (const entry of entries) {\n if (!entry.routed_to) { remaining.push(entry); continue; }\n if (!groups[entry.routed_to]) groups[entry.routed_to] = [];\n groups[entry.routed_to].push(entry);\n}\n\n// For each command with 3+ entries, extract common words and build regex\nconst promoted = [];\nfor (const [command, cmdEntries] of Object.entries(groups)) {\n if (cmdEntries.length < 3) {\n remaining.push(...cmdEntries);\n continue;\n }\n\n // Extract unique words from all prompts\n const wordFreq = {};\n for (const entry of cmdEntries) {\n const words = (entry.prompt || '').toLowerCase()\n .replace(/[^a-z\\\\s]/g, '')\n .split(/\\\\s+/)\n .filter(w => w.length > 2);\n const unique = [...new Set(words)];\n for (const word of unique) {\n wordFreq[word] = (wordFreq[word] || 0) + 1;\n }\n }\n\n // Find words that appear in at least half the entries\n const threshold = Math.ceil(cmdEntries.length / 2);\n const commonWords = Object.entries(wordFreq)\n .filter(([, count]) => count >= threshold)\n .map(([word]) => word)\n .filter(w => !['the', 'and', 'for', 'this', 'that', 'can', 'you', 'please'].includes(w));\n\n if (commonWords.length === 0) {\n remaining.push(...cmdEntries);\n continue;\n }\n\n // Build regex pattern from common words\n const patternStr = '\\\\\\\\b(' + commonWords.join('|') + ')\\\\\\\\b';\n\n // Read current router and check if pattern already exists\n try {\n const routerContent = readFileSync(routerPath, 'utf-8');\n if (commonWords.some(w => routerContent.includes(w + '|') || routerContent.includes('|' + w))) {\n remaining.push(...cmdEntries);\n continue;\n }\n\n // Append new pattern to PATTERNS array\n const newEntry = \\` { pattern: /\\\\\\\\b(\\${commonWords.join('|')})/i,\\\\n command: '\\${command}',\\\\n description: 'Learned from usage patterns' },\\`;\n const insertPoint = routerContent.lastIndexOf('];');\n if (insertPoint === -1) {\n remaining.push(...cmdEntries);\n continue;\n }\n\n const updatedRouter = routerContent.slice(0, insertPoint) +\n newEntry + '\\\\n' +\n routerContent.slice(insertPoint);\n writeFileSync(routerPath, updatedRouter, 'utf-8');\n\n // Record promotion\n const promotion = {\n timestamp: new Date().toISOString(),\n command,\n pattern: patternStr,\n sourcePrompts: cmdEntries.map(e => e.prompt),\n commonWords,\n };\n promoted.push(promotion);\n appendFileSync(promotionsPath, JSON.stringify(promotion) + '\\\\n');\n\n } catch {\n remaining.push(...cmdEntries);\n continue;\n }\n}\n\n// Write back remaining (unprocessed) entries\nwriteFileSync(logPath, remaining.map(e => JSON.stringify(e)).join('\\\\n') + (remaining.length ? '\\\\n' : ''), 'utf-8');\n\nconsole.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n`;\n}\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport type { EnvironmentSpec, RegistryTool } from \"../types.js\";\nimport { applyAutonomyLevel } from \"../autonomy.js\";\n\nconst STATUS_LINE = {\n command:\n \"printf '%s | %s tasks' \\\"$(git branch --show-current 2>/dev/null || echo 'no-git')\\\" \\\"$(grep -c '\\\\- \\\\[ \\\\]' docs/SPRINT.md 2>/dev/null || echo 0)\\\"\",\n};\n\nfunction isCodeProject(spec: EnvironmentSpec): boolean {\n const commands = spec.harness.commands ?? {};\n return \"status\" in commands || \"test\" in commands;\n}\n\nconst ENV_LOADER_HOOK = {\n matcher: \"\",\n hooks: [{\n type: \"command\",\n command: 'if [ -f .env ] && [ -n \"$CLAUDE_ENV_FILE\" ]; then grep -v \"^#\" .env | grep -v \"^$\" | grep \"=\" >> \"$CLAUDE_ENV_FILE\"; fi',\n }],\n};\n\nfunction resolveSettings(\n spec: EnvironmentSpec,\n options?: { hasEnvVars?: boolean }\n): Record<string, unknown> | null {\n const settings = spec.harness.settings;\n const base: Record<string, unknown> = settings && Object.keys(settings).length > 0\n ? { ...(settings as Record<string, unknown>) }\n : {};\n\n // Add statusLine for code projects\n if (!(\"statusLine\" in base) && isCodeProject(spec)) {\n base.statusLine = STATUS_LINE;\n }\n\n // Add SessionStart hook for .env loading\n if (options?.hasEnvVars) {\n const hooks = (base.hooks ?? {}) as Record<string, unknown[]>;\n const sessionStart = (hooks.SessionStart ?? []) as unknown[];\n sessionStart.push(ENV_LOADER_HOOK);\n hooks.SessionStart = sessionStart;\n base.hooks = hooks;\n }\n\n // Add intent routing hooks if patterns exist\n const hasIntentHooks = spec.harness.hooks &&\n Object.keys(spec.harness.hooks).length > 0;\n\n if (hasIntentHooks) {\n const hooks = (base.hooks ?? {}) as Record<string, unknown[]>;\n\n // Tier 1 (regex) + Tier 2 (prompt) on UserPromptSubmit\n const userPromptSubmit = (hooks.UserPromptSubmit ?? []) as unknown[];\n const intentHookEntry: Record<string, unknown> = {\n matcher: '*',\n hooks: [\n {\n type: 'command',\n command: 'node \"$CLAUDE_PROJECT_DIR/.claude/hooks/intent-router.mjs\"',\n timeout: 5,\n },\n ],\n };\n // Add Tier 2 prompt hook if template exists\n if (spec.harness.intent_prompt_template) {\n (intentHookEntry.hooks as unknown[]).push({\n type: 'prompt',\n prompt: spec.harness.intent_prompt_template,\n timeout: 15,\n });\n }\n userPromptSubmit.push(intentHookEntry);\n hooks.UserPromptSubmit = userPromptSubmit;\n\n // Intent learner on SessionStart\n const sessionStart = (hooks.SessionStart ?? []) as unknown[];\n sessionStart.push({\n matcher: '*',\n hooks: [{\n type: 'command',\n command: 'node \"$CLAUDE_PROJECT_DIR/.claude/hooks/intent-learner.mjs\"',\n timeout: 10,\n }],\n });\n hooks.SessionStart = sessionStart;\n\n base.hooks = hooks;\n }\n\n if (Object.keys(base).length === 0) return null;\n return base;\n}\n\nasync function writeFile(filePath: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf-8\");\n}\n\nexport function buildFileMap(\n spec: EnvironmentSpec,\n options?: { hasEnvVars?: boolean }\n): Map<string, string> {\n // Apply autonomy-level content before building file map\n applyAutonomyLevel(spec);\n\n const files = new Map<string, string>();\n\n if (spec.harness.claude_md) {\n files.set(\".claude/CLAUDE.md\", spec.harness.claude_md);\n }\n const resolvedSettings = resolveSettings(spec, options);\n if (resolvedSettings) {\n files.set(\".claude/settings.json\", JSON.stringify(resolvedSettings, null, 2));\n }\n if (\n spec.harness.mcp_config &&\n Object.keys(spec.harness.mcp_config).length > 0\n ) {\n files.set(\n \".mcp.json\",\n JSON.stringify({ mcpServers: spec.harness.mcp_config }, null, 2)\n );\n }\n if (spec.harness.commands) {\n for (const [name, content] of Object.entries(spec.harness.commands)) {\n files.set(`.claude/commands/${name}.md`, content);\n }\n }\n if (spec.harness.rules) {\n for (const [name, content] of Object.entries(spec.harness.rules)) {\n files.set(`.claude/rules/${name}.md`, content);\n }\n }\n if (spec.harness.skills) {\n for (const [skillPath, content] of Object.entries(spec.harness.skills)) {\n files.set(`.claude/skills/${skillPath}.md`, content);\n }\n }\n if (spec.harness.agents) {\n for (const [name, content] of Object.entries(spec.harness.agents)) {\n files.set(`.claude/agents/${name}.md`, content);\n }\n }\n if (spec.harness.docs) {\n for (const [name, content] of Object.entries(spec.harness.docs)) {\n files.set(`.claude/docs/${name}.md`, content);\n }\n }\n\n // Hooks (intent-router.mjs, intent-learner.mjs)\n if (spec.harness.hooks) {\n for (const [name, content] of Object.entries(spec.harness.hooks)) {\n files.set(`.claude/hooks/${name}.mjs`, content);\n }\n // Create empty intent-log.jsonl for Tier 2 logging\n if (Object.keys(spec.harness.hooks).length > 0) {\n files.set('.claude/hooks/intent-log.jsonl', '');\n }\n }\n\n return files;\n}\n\nexport async function writeEnvironment(\n spec: EnvironmentSpec,\n targetDir: string,\n options?: { hasEnvVars?: boolean }\n): Promise<string[]> {\n // Apply autonomy-level content before writing\n applyAutonomyLevel(spec);\n\n const claudeDir = path.join(targetDir, \".claude\");\n const written: string[] = [];\n\n // 1. CLAUDE.md\n if (spec.harness.claude_md) {\n const p = path.join(claudeDir, \"CLAUDE.md\");\n await writeFile(p, spec.harness.claude_md);\n written.push(\".claude/CLAUDE.md\");\n }\n\n // 2. settings.json\n const resolvedSettings = resolveSettings(spec, options);\n if (resolvedSettings) {\n const p = path.join(claudeDir, \"settings.json\");\n await writeFile(p, JSON.stringify(resolvedSettings, null, 2));\n written.push(\".claude/settings.json\");\n }\n\n // 3. .mcp.json (project-scoped, goes in project root)\n if (\n spec.harness.mcp_config &&\n Object.keys(spec.harness.mcp_config).length > 0\n ) {\n const p = path.join(targetDir, \".mcp.json\");\n const mcpContent = { mcpServers: spec.harness.mcp_config };\n await writeFile(p, JSON.stringify(mcpContent, null, 2));\n written.push(\".mcp.json\");\n }\n\n // 4. Commands\n if (spec.harness.commands) {\n for (const [name, content] of Object.entries(spec.harness.commands)) {\n const p = path.join(claudeDir, \"commands\", `${name}.md`);\n await writeFile(p, content);\n written.push(`.claude/commands/${name}.md`);\n }\n }\n\n // 5. Rules\n if (spec.harness.rules) {\n for (const [name, content] of Object.entries(spec.harness.rules)) {\n const p = path.join(claudeDir, \"rules\", `${name}.md`);\n await writeFile(p, content);\n written.push(`.claude/rules/${name}.md`);\n }\n }\n\n // 6. Skills\n if (spec.harness.skills) {\n for (const [skillPath, content] of Object.entries(spec.harness.skills)) {\n const p = path.join(claudeDir, \"skills\", `${skillPath}.md`);\n await writeFile(p, content);\n written.push(`.claude/skills/${skillPath}.md`);\n }\n }\n\n // 7. Agents\n if (spec.harness.agents) {\n for (const [name, content] of Object.entries(spec.harness.agents)) {\n const p = path.join(claudeDir, \"agents\", `${name}.md`);\n await writeFile(p, content);\n written.push(`.claude/agents/${name}.md`);\n }\n }\n\n // 8. Docs\n if (spec.harness.docs) {\n for (const [name, content] of Object.entries(spec.harness.docs)) {\n const p = path.join(claudeDir, \"docs\", `${name}.md`);\n await writeFile(p, content);\n written.push(`.claude/docs/${name}.md`);\n }\n }\n\n // 9. Hooks (intent-router.mjs, intent-learner.mjs)\n if (spec.harness.hooks) {\n for (const [name, content] of Object.entries(spec.harness.hooks)) {\n const p = path.join(claudeDir, \"hooks\", `${name}.mjs`);\n await writeFile(p, content);\n written.push(`.claude/hooks/${name}.mjs`);\n }\n // Create empty intent-log.jsonl for Tier 2 logging\n if (Object.keys(spec.harness.hooks).length > 0) {\n const logPath = path.join(claudeDir, \"hooks\", \"intent-log.jsonl\");\n await writeFile(logPath, '');\n written.push('.claude/hooks/intent-log.jsonl');\n }\n }\n\n return written;\n}\n\nexport interface EnvSetupInfo {\n toolName: string;\n envVar: string;\n description: string;\n signupUrl?: string;\n}\n\nexport function summarizeSpec(\n spec: EnvironmentSpec,\n registry: RegistryTool[]\n): {\n toolCount: number;\n commandCount: number;\n ruleCount: number;\n skillCount: number;\n agentCount: number;\n pluginCommands: string[];\n envSetup: EnvSetupInfo[];\n} {\n const pluginCommands: string[] = [];\n const envSetup: EnvSetupInfo[] = [];\n\n for (const selected of spec.tools) {\n const tool = registry.find((t) => t.id === selected.tool_id);\n if (!tool) continue;\n\n if (tool.install.plugin_command) {\n pluginCommands.push(tool.install.plugin_command);\n }\n\n if (tool.env_vars) {\n for (const ev of tool.env_vars) {\n envSetup.push({\n toolName: tool.name,\n envVar: ev.name,\n description: ev.description,\n signupUrl: tool.signup_url,\n });\n }\n }\n }\n\n return {\n toolCount: spec.tools.length,\n commandCount: Object.keys(spec.harness.commands || {}).length,\n ruleCount: Object.keys(spec.harness.rules || {}).length,\n skillCount: Object.keys(spec.harness.skills || {}).length,\n agentCount: Object.keys(spec.harness.agents || {}).length,\n pluginCommands,\n envSetup,\n };\n}\n","import type { EnvironmentSpec, AutonomyLevel } from \"./types.js\";\n\nconst AUTONOMY_LABELS: Record<AutonomyLevel, string> = {\n 1: \"Guided\",\n 2: \"Assisted\",\n 3: \"Autonomous\",\n 4: \"Full Auto\",\n};\n\n/** Welcome hook — shows orientation on first session */\nconst WELCOME_HOOK = {\n matcher: \"\",\n hooks: [{\n type: \"command\" as const,\n command: \"if [ ! -f .claude/.toured ]; then echo '\\\\n Welcome to your Kairn environment!\\\\n Type /project:tour for a walkthrough, or /project:help for a quick reference.\\\\n'; fi\",\n }],\n};\n\n// ── Level 1: Guided ─────────────────────────────────────────────\n\nconst TOUR_COMMAND = `# Environment Tour\n\nWelcome! Let me show you around this Kairn environment.\n\n## Your Commands\nRead .claude/commands/ and list each one with a one-line description.\nGroup them by workflow phase:\n\n PLAN: /project:spec, /project:sprint, /project:plan\n BUILD: /project:develop (full pipeline), or just start coding\n VERIFY: /project:prove, /project:grill, /project:test\n SHIP: /project:commit, /project:review\n MANAGE: /project:status, /project:reset\n\n## Your Agents\nRead .claude/agents/ and explain each one with how to invoke it.\n\n## Your MCP Tools\n!claude mcp list 2>/dev/null || echo \"Run /mcp in Claude Code to see active tools\"\n\n## Workflow\nFor this project, the recommended flow is:\n spec → sprint → plan → code → prove → grill → commit\n\n## Tips\n- Type / to see all commands\n- Type @ to invoke an agent\n- Paste raw errors — don't summarize them\n- Use subagents for deep investigation\n- Say \"update CLAUDE.md\" after any correction\n\nAfter showing the tour, create .claude/.toured to suppress the welcome message:\n!touch .claude/.toured\n\nReady to start? Try /project:spec to define your first feature.`;\n\nfunction buildQuickstart(spec: EnvironmentSpec): string {\n const commands = Object.keys(spec.harness.commands || {});\n const agents = Object.keys(spec.harness.agents || {});\n\n const commandList = commands\n .map((c) => `- \\`/project:${c}\\``)\n .join(\"\\n\");\n\n const agentList = agents.length > 0\n ? agents.map((a) => `- \\`@${a}\\``).join(\"\\n\")\n : \"- (none configured)\";\n\n return `# Quick Start Guide\n\nThis environment was generated by Kairn. Here's how to use it.\n\n## First Time\n1. Open terminal in this directory\n2. Run \\`claude\\`\n3. Type \\`/project:tour\\` for a guided walkthrough\n\n## Daily Workflow\n1. \\`/project:status\\` — see where things stand\n2. \\`/project:spec\\` — define what to build (Claude will interview you)\n3. Start coding — Claude follows CLAUDE.md automatically\n4. \\`/project:prove\\` — verify your work\n5. \\`/project:commit\\` — ship it\n\n## Commands\n${commandList}\n\n## Agents\n${agentList}\n\n## Need Help?\nType \\`/project:help\\` in Claude Code for a quick reference.\n`;\n}\n\n// ── Bootstrap (Level 2+: command, Level 3+: SessionStart hook) ─\n\nconst BOOTSTRAP_COMMAND = `# Environment Snapshot\n\nRun this command at the start of any session to gather runtime context.\nThis saves 2-5 exploratory turns.\n\n1. Run the following compound command and read the output:\n \\`\\`\\`bash\n echo '=== WORKING DIRECTORY ===' && pwd && \\\\\n echo '=== PROJECT FILES ===' && ls -la && \\\\\n echo '=== GIT STATUS ===' && (git status --short 2>/dev/null || echo 'not a git repo') && \\\\\n echo '=== LANGUAGES ===' && \\\\\n (node --version 2>&1 || true) && \\\\\n (python3 --version 2>&1 || true) && \\\\\n (go version 2>&1 || true) && \\\\\n (rustc --version 2>&1 || true) && \\\\\n echo '=== PACKAGE MANAGERS ===' && \\\\\n (npm --version 2>&1 && echo \"npm $(npm --version 2>&1)\" || true) && \\\\\n (pip3 --version 2>&1 || true) && \\\\\n (cargo --version 2>&1 || true) && \\\\\n echo '=== ENVIRONMENT ===' && \\\\\n (cat .env 2>/dev/null | sed 's/=.*/=***/' || echo 'no .env file')\n \\`\\`\\`\n\n2. Summarize the environment in 3-4 lines:\n - Runtime: [languages + versions found]\n - Project: [framework, key deps, file count]\n - State: [git branch, clean/dirty, .env present]\n\n3. Keep this summary in context for the rest of the session.`;\n\nfunction buildBootstrapHookCommand(spec: EnvironmentSpec): string {\n const checks: string[] = [\n \"echo '--- Environment Snapshot ---'\",\n \"pwd\",\n \"ls -la --color=never | head -20\",\n \"echo '---'\",\n \"git status --short 2>/dev/null || true\",\n \"echo '---'\",\n ];\n\n // Infer project type from claude_md content (Tech Stack section)\n const md = (spec.harness.claude_md ?? \"\").toLowerCase();\n if (md.includes(\"node\") || md.includes(\"typescript\") || md.includes(\"javascript\") || md.includes(\"react\") || md.includes(\"next\")) {\n checks.push(\"node --version 2>&1 || true\");\n checks.push(\"cat package.json 2>/dev/null | head -5 || true\");\n }\n if (md.includes(\"python\") || md.includes(\"django\") || md.includes(\"flask\") || md.includes(\"fastapi\")) {\n checks.push(\"python3 --version 2>&1 || true\");\n }\n if (md.includes(\"rust\") || md.includes(\"cargo\")) {\n checks.push(\"rustc --version 2>&1 || true\");\n }\n if (md.includes(\"go \") || md.includes(\"golang\")) {\n checks.push(\"go version 2>&1 || true\");\n }\n\n // .env key masking — show KEY=***, never values\n checks.push(\"cat .env 2>/dev/null | sed 's/=.*/=***/' || true\");\n\n return checks.join(\" && \");\n}\n\n// ── Level 2: Assisted ───────────────────────────────────────────\n\nconst LOOP_COMMAND_CODE = `# Development Loop\n\nRun an assisted development cycle for the next feature.\n\n## Phase 1: SPEC\nReview docs/SPRINT.md.\nIf no sprint is defined, run /project:spec to interview the user.\nWait for user approval of the spec.\n\n## Phase 2: PLAN\nRead the approved spec in docs/SPRINT.md.\nPlan the implementation: files to change, tests to write, approach.\nWrite plan to docs/DECISIONS.md.\nWait for user approval of the plan.\n\n## Phase 3: IMPLEMENT\nFollow the plan. Implement the feature.\nRun tests after each change.\nCommit each logical unit: \"feat: description\"\n\n## Phase 4: VERIFY\nRun /project:prove to verify the implementation.\nIf confidence is LOW or MEDIUM, fix issues and re-verify.\n\n## Phase 5: REVIEW\nRun /project:grill for adversarial review.\nFix any BLOCKERs.\n\n## Phase 6: COMPLETION GATE\n\nBefore shipping, run the Completion Verification checklist:\n\n### Requirements Check\n- [ ] Re-read the ORIGINAL task description (not your interpretation)\n- [ ] Each explicit requirement is met with evidence (test output, diff)\n- [ ] Each implicit requirement (error handling, types, tests) is addressed\n\n### State Check\n- [ ] Test suite passes\n- [ ] Lint/typecheck passes\n- [ ] \\`git diff --stat\\` — every changed file is intentional\n- [ ] No debug artifacts (console.log, TODO, commented-out code, temp files)\n\n### Perspective Check (1 sentence each)\n- **Test engineer:** Most likely production failure mode?\n- **Code reviewer:** What would I flag in review?\n- **Requesting user:** Does this solve my actual problem?\n\nALL pass → proceed to ship. ANY fail → fix first, then re-verify.\n\n## Phase 7: SHIP\nRun /project:commit.\nReport what was built and what's next from docs/SPRINT.md.\n\nThen ask: \"Continue to next feature?\"\nIf yes, return to Phase 1.`;\n\nconst LOOP_COMMAND_RESEARCH = `# Research Loop\n\nRun an assisted research cycle.\n\n## Phase 1: QUESTION\nReview docs/SPRINT.md for the next research question.\nIf none, ask the user what to investigate.\n\n## Phase 2: RESEARCH\nSearch, extract, and analyze sources.\nLog findings to docs/SOURCES.md and docs/LEARNINGS.md.\n\n## Phase 3: SYNTHESIZE\nReview all findings. Write structured summary to docs/SUMMARY.md.\nCite all sources.\n\n## Phase 4: REVIEW\nPresent the summary. Ask the user for feedback.\nRevise based on feedback.\n\n## Phase 5: NEXT\nUpdate docs/SPRINT.md — mark question as done, identify follow-ups.\nAsk: \"Continue to next question?\"`;\n\nconst PM_AGENT = `---\nname: pm\ndescription: Project manager agent. Maintains roadmap, specs features, prioritizes work.\nmodel: opus\n---\n\nYou are a project manager for this codebase.\n\nYour responsibilities:\n1. Maintain docs/SPRINT.md — keep it prioritized and current\n2. Write specs to docs/SPRINT.md when asked\n3. Review completed work and suggest what's next\n4. Track decisions in docs/DECISIONS.md\n5. Track learnings in docs/LEARNINGS.md\n\nWhen invoked:\n- Read all docs/ files to understand current state\n- Read recent git log for what changed\n- Suggest the highest-priority next task\n- If asked to spec something, interview the user (5-8 questions)\n\nYou do NOT write code. You plan, spec, and prioritize.`;\n\n// ── Level 3: Autonomous ─────────────────────────────────────────\n\nconst AUTO_COMMAND = `# Autonomous Development\n\nPM-driven development loop with PR delivery.\n\n## Phase 1: PLAN (@pm)\nUse @pm to:\n- Read docs/SPRINT.md\n- Select the highest-priority unfinished task\n- Write a spec to docs/SPRINT.md\n- Present the spec for approval\n\nWait for user approval. If approved, proceed.\n\n## Phase 2: BRANCH\nCreate an isolated worktree:\n git worktree add ../project-feat-{name} -b feat/{name}\nAll implementation happens in the worktree.\n\n## Phase 3: IMPLEMENT\nIn the worktree directory:\n- Follow the spec in docs/SPRINT.md\n- Build, test, commit after each change\n\n## Phase 4: VERIFY\nRun verification:\n- Static analysis (linting, type checks)\n- Run functional tests\n- If NEEDS FIXES: fix and re-verify\n\n## Phase 5: COMPLETION GATE\n\nBefore creating a PR, run the Completion Verification checklist:\n- [ ] Re-read the ORIGINAL spec from docs/SPRINT.md\n- [ ] Each requirement is met with evidence (test output, diff)\n- [ ] Test suite + lint/typecheck pass\n- [ ] \\`git diff --stat\\` — every changed file is intentional, no debug artifacts\n- **Test engineer:** Most likely production failure mode?\n- **Code reviewer:** What would I flag in review?\n- **Requesting user:** Does this solve my actual problem?\n\nALL pass → proceed to PR. ANY fail → fix first, then re-verify.\n\nInclude the checklist results in the PR description.\n\n## Phase 6: PR\nCreate a pull request:\n gh pr create --title \"feat: {name}\" --body \"{spec + QA report + verification checklist}\"\n\n## Phase 7: NEXT\nReport:\n \"PR #{N} ready for review: {link}\n Next priority from SPRINT.md: {next task}\n Continue? (y/n)\"\n\nIf yes, return to Phase 1 with next task.`;\n\n// ── Level 4: Full Auto ──────────────────────────────────────────\n\nconst AUTOPILOT_COMMAND = `# Autopilot Mode\n\nContinuous autonomous development. The PM plans, the loop executes,\nPRs are opened automatically. You review when ready.\n\n## Configuration\n- Max features per session: 5 (prevent runaway)\n- Stop on: test failure, build error, or blocked dependency\n- All work in isolated worktrees\n- Every feature = one PR\n\n## The Loop\nRepeat until max features reached or stopped:\n1. @pm selects next priority from docs/SPRINT.md\n2. Create worktree + branch\n3. Implement the feature\n4. Run verification (build, test, lint)\n5. Run Completion Verification checklist:\n - Requirements met with evidence\n - Tests + lint/typecheck pass\n - No debug artifacts or unexpected file changes\n - 3-perspective check (test engineer, reviewer, user)\n6. Open PR via gh (include verification results in PR body)\n7. Report status\n8. Move to next feature\n\n## Stop Conditions\n- Max 5 features per autopilot session\n- Any BLOCKER from verification\n- Completion Verification checklist fails after 2 fix attempts\n- Build failure that can't be resolved in 3 attempts\n- User presses Escape`;\n\nconst AUTOPILOT_WARNING = `\n## Autopilot Mode Active\nThis environment is configured for autonomous operation.\nThe @pm agent plans features and /project:autopilot executes them.\nAll changes are delivered as PRs — review before merging.\nStop conditions: max 5 features, test failure, or Escape.`;\n\n// ── Main export ─────────────────────────────────────────────────\n\nfunction isResearchProject(spec: EnvironmentSpec): boolean {\n const commands = spec.harness.commands ?? {};\n return \"research\" in commands || \"summarize\" in commands;\n}\n\n/**\n * Apply autonomy-level-specific content to an EnvironmentSpec.\n * Mutates spec.harness by injecting commands, agents, hooks, and docs\n * appropriate for the selected autonomy level.\n */\nexport function applyAutonomyLevel(spec: EnvironmentSpec): void {\n const level = spec.autonomy_level ?? 1;\n const commands = spec.harness.commands ?? {};\n const agents = spec.harness.agents ?? {};\n const docs = spec.harness.docs ?? {};\n const settings = (spec.harness.settings ?? {}) as Record<string, unknown>;\n\n // Level 1+: Tour, QUICKSTART, welcome hook\n if (level >= 1) {\n if (!(\"tour\" in commands)) {\n commands.tour = TOUR_COMMAND;\n }\n docs.QUICKSTART = buildQuickstart(spec);\n\n // Add SessionStart welcome hook\n const hooks = (settings.hooks ?? {}) as Record<string, unknown[]>;\n const sessionStart = (hooks.SessionStart ?? []) as unknown[];\n sessionStart.push(WELCOME_HOOK);\n hooks.SessionStart = sessionStart;\n settings.hooks = hooks;\n }\n\n // Level 2+: Bootstrap command, Loop, PM agent\n if (level >= 2) {\n if (!(\"bootstrap\" in commands)) {\n commands.bootstrap = BOOTSTRAP_COMMAND;\n }\n if (!(\"loop\" in commands)) {\n commands.loop = isResearchProject(spec)\n ? LOOP_COMMAND_RESEARCH\n : LOOP_COMMAND_CODE;\n }\n if (!(\"pm\" in agents)) {\n agents.pm = PM_AGENT;\n }\n }\n\n // Level 3+: Auto command + SessionStart bootstrap hook\n if (level >= 3) {\n if (!(\"auto\" in commands)) {\n commands.auto = AUTO_COMMAND;\n }\n\n // Add SessionStart bootstrap hook (automatic environment snapshot)\n const hooks = (settings.hooks ?? {}) as Record<string, unknown[]>;\n const sessionStart = (hooks.SessionStart ?? []) as unknown[];\n const bootstrapHook = {\n matcher: \"\",\n hooks: [{\n type: \"command\" as const,\n command: buildBootstrapHookCommand(spec),\n }],\n };\n sessionStart.push(bootstrapHook);\n hooks.SessionStart = sessionStart;\n settings.hooks = hooks;\n }\n\n // Level 4: Autopilot command + warning\n if (level >= 4) {\n if (!(\"autopilot\" in commands)) {\n commands.autopilot = AUTOPILOT_COMMAND;\n }\n // Append warning to CLAUDE.md\n if (spec.harness.claude_md && !spec.harness.claude_md.includes(\"Autopilot Mode\")) {\n spec.harness.claude_md += \"\\n\" + AUTOPILOT_WARNING;\n }\n }\n\n // Write back\n spec.harness.commands = commands;\n spec.harness.agents = agents;\n spec.harness.docs = docs;\n spec.harness.settings = settings;\n}\n\n/** Human-readable label for an autonomy level. */\nexport function autonomyLabel(level: AutonomyLevel): string {\n return AUTONOMY_LABELS[level];\n}\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport os from \"os\";\nimport type { EnvironmentSpec, RegistryTool } from \"../types.js\";\n\nasync function writeFile(filePath: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf-8\");\n}\n\nfunction toYaml(obj: unknown, indent: number = 0): string {\n const pad = \" \".repeat(indent);\n\n if (obj === null || obj === undefined) {\n return \"~\";\n }\n\n if (typeof obj === \"boolean\") {\n return obj ? \"true\" : \"false\";\n }\n\n if (typeof obj === \"number\") {\n return String(obj);\n }\n\n if (typeof obj === \"string\") {\n // Quote strings that contain special characters or look like other types\n const needsQuotes =\n obj === \"\" ||\n /[:#\\[\\]{}&*!|>'\"%@`,]/.test(obj) ||\n /^(true|false|null|~|\\d)/.test(obj) ||\n obj.includes(\"\\n\");\n return needsQuotes ? `\"${obj.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"` : obj;\n }\n\n if (Array.isArray(obj)) {\n if (obj.length === 0) {\n return \"[]\";\n }\n return obj\n .map((item) => `${pad}- ${toYaml(item, indent + 1).trimStart()}`)\n .join(\"\\n\");\n }\n\n if (typeof obj === \"object\") {\n const entries = Object.entries(obj as Record<string, unknown>);\n if (entries.length === 0) {\n return \"{}\";\n }\n return entries\n .map(([key, value]) => {\n const valueStr = toYaml(value, indent + 1);\n const isScalar =\n typeof value !== \"object\" || value === null || Array.isArray(value);\n if (isScalar && !Array.isArray(value)) {\n return `${pad}${key}: ${valueStr}`;\n }\n if (Array.isArray(value)) {\n if ((value as unknown[]).length === 0) {\n return `${pad}${key}: []`;\n }\n return `${pad}${key}:\\n${valueStr}`;\n }\n return `${pad}${key}:\\n${valueStr}`;\n })\n .join(\"\\n\");\n }\n\n return String(obj);\n}\n\nfunction buildMcpServersYaml(\n spec: EnvironmentSpec,\n registry: RegistryTool[]\n): string {\n const servers: Record<string, unknown> = {};\n\n // For each selected tool, check for hermes-specific mcp_server config first\n for (const selected of spec.tools) {\n const tool = registry.find((t) => t.id === selected.tool_id);\n if (!tool) continue;\n\n if (tool.install.hermes?.mcp_server) {\n const serverName = tool.id.replace(/_/g, \"-\");\n servers[serverName] = tool.install.hermes.mcp_server;\n } else if (tool.install.mcp_config) {\n // Fall back to converting the Claude Code mcp_config format\n for (const [serverName, serverConfig] of Object.entries(\n tool.install.mcp_config\n )) {\n servers[serverName] = serverConfig;\n }\n }\n }\n\n // Also include any mcp_config entries from the harness that weren't covered by tools\n for (const [serverName, serverConfig] of Object.entries(\n spec.harness.mcp_config || {}\n )) {\n if (!(serverName in servers)) {\n servers[serverName] = serverConfig;\n }\n }\n\n if (Object.keys(servers).length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n lines.push(`# Generated by Kairn v1.5.0`);\n lines.push(`# Environment: ${spec.name}`);\n lines.push(``);\n lines.push(`mcp_servers:`);\n\n for (const [serverName, serverConfig] of Object.entries(servers)) {\n lines.push(` ${serverName}:`);\n lines.push(toYaml(serverConfig, 2));\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport async function writeHermesEnvironment(\n spec: EnvironmentSpec,\n registry: RegistryTool[]\n): Promise<string[]> {\n const hermesDir = path.join(os.homedir(), \".hermes\");\n const written: string[] = [];\n\n // 1. config.yaml\n const configYaml = buildMcpServersYaml(spec, registry);\n if (configYaml) {\n const configPath = path.join(hermesDir, \"config.yaml\");\n await writeFile(configPath, configYaml);\n written.push(\".hermes/config.yaml\");\n }\n\n // 2. Skills from commands\n if (spec.harness.commands) {\n for (const [name, content] of Object.entries(spec.harness.commands)) {\n const skillPath = path.join(hermesDir, \"skills\", `${name}.md`);\n await writeFile(skillPath, content);\n written.push(`.hermes/skills/${name}.md`);\n }\n }\n\n // 3. Skills from skills\n if (spec.harness.skills) {\n for (const [name, content] of Object.entries(spec.harness.skills)) {\n const skillPath = path.join(hermesDir, \"skills\", `${name}.md`);\n await writeFile(skillPath, content);\n written.push(`.hermes/skills/${name}.md`);\n }\n }\n\n // 4. Skills from rules (prefixed with \"rule-\")\n if (spec.harness.rules) {\n for (const [name, content] of Object.entries(spec.harness.rules)) {\n const skillPath = path.join(hermesDir, \"skills\", `rule-${name}.md`);\n await writeFile(skillPath, content);\n written.push(`.hermes/skills/rule-${name}.md`);\n }\n }\n\n return written;\n}\n","import { password } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { ui } from \"./ui.js\";\nimport type { EnvSetupInfo } from \"./adapter/claude-code.js\";\n\nexport interface KeyCollectionResult {\n keysEntered: number;\n keysSkipped: number;\n envPath: string;\n}\n\n/**\n * Interactively prompt the user for API keys and write a .env file.\n * Skipped keys get empty placeholders. Also updates .gitignore.\n */\nexport async function collectAndWriteKeys(\n envSetup: EnvSetupInfo[],\n targetDir: string\n): Promise<KeyCollectionResult> {\n console.log(ui.section(\"API Keys\"));\n console.log(\n chalk.dim(\" Some tools need API keys. Enter them now or press Enter to skip.\\n\")\n );\n\n const envEntries: string[] = [\n \"# Generated by Kairn — API keys for MCP servers\",\n \"# Do NOT commit this file to git\",\n \"\",\n ];\n\n let keysEntered = 0;\n let keysSkipped = 0;\n const seen = new Set<string>();\n\n for (const env of envSetup) {\n if (seen.has(env.envVar)) continue;\n seen.add(env.envVar);\n\n console.log(chalk.bold(` ${env.envVar}`) + chalk.dim(` (${env.toolName})`));\n if (env.signupUrl) {\n console.log(chalk.dim(` Get one at: ${env.signupUrl}`));\n }\n\n const value = await password({\n message: env.envVar,\n mask: \"•\",\n });\n\n if (value && value.trim()) {\n envEntries.push(`${env.envVar}=${value.trim()}`);\n console.log(chalk.green(\" ✓ saved\\n\"));\n keysEntered++;\n } else {\n envEntries.push(`${env.envVar}=`);\n console.log(chalk.dim(\" (skipped)\\n\"));\n keysSkipped++;\n }\n }\n\n // Write .env file\n const envPath = path.join(targetDir, \".env\");\n await fs.writeFile(envPath, envEntries.join(\"\\n\") + \"\\n\", \"utf-8\");\n\n // Update .gitignore\n await ensureGitignoreEntry(targetDir, \".env\");\n\n console.log(chalk.green(` ✓ ${keysEntered} key(s) saved to .env (gitignored)`));\n if (keysSkipped > 0) {\n console.log(chalk.dim(\" Skipped keys can be added later: kairn keys\"));\n }\n\n return { keysEntered, keysSkipped, envPath };\n}\n\n/**\n * Write a .env file with empty placeholders for all keys (no prompts).\n * Used with --quick flag.\n */\nexport async function writeEmptyEnvFile(\n envSetup: EnvSetupInfo[],\n targetDir: string\n): Promise<void> {\n const envEntries: string[] = [\n \"# Generated by Kairn — API keys for MCP servers\",\n \"# Do NOT commit this file to git\",\n \"\",\n ];\n\n const seen = new Set<string>();\n for (const env of envSetup) {\n if (seen.has(env.envVar)) continue;\n seen.add(env.envVar);\n envEntries.push(`${env.envVar}=`);\n }\n\n const envPath = path.join(targetDir, \".env\");\n await fs.writeFile(envPath, envEntries.join(\"\\n\") + \"\\n\", \"utf-8\");\n await ensureGitignoreEntry(targetDir, \".env\");\n}\n\n/**\n * Ensure a line exists in .gitignore. Creates the file if needed.\n */\nasync function ensureGitignoreEntry(\n targetDir: string,\n entry: string\n): Promise<void> {\n const gitignorePath = path.join(targetDir, \".gitignore\");\n let gitignore = \"\";\n try {\n gitignore = await fs.readFile(gitignorePath, \"utf-8\");\n } catch {\n // File doesn't exist yet\n }\n if (!gitignore.split(\"\\n\").some((line) => line.trim() === entry)) {\n const separator = gitignore.length > 0 && !gitignore.endsWith(\"\\n\") ? \"\\n\" : \"\";\n await fs.writeFile(gitignorePath, gitignore + separator + entry + \"\\n\", \"utf-8\");\n }\n}\n\n/**\n * Parse an existing .env file and return key-value pairs.\n */\nexport async function readEnvFile(\n targetDir: string\n): Promise<Map<string, string>> {\n const envPath = path.join(targetDir, \".env\");\n const entries = new Map<string, string>();\n try {\n const content = await fs.readFile(envPath, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) continue;\n const key = trimmed.slice(0, eqIndex);\n const value = trimmed.slice(eqIndex + 1);\n entries.set(key, value);\n }\n } catch {\n // File doesn't exist\n }\n return entries;\n}\n\n/**\n * Parse .mcp.json to find which env vars are needed.\n */\nexport async function detectRequiredEnvVars(\n targetDir: string\n): Promise<string[]> {\n const mcpPath = path.join(targetDir, \".mcp.json\");\n const envVars = new Set<string>();\n try {\n const content = await fs.readFile(mcpPath, \"utf-8\");\n // Match ${ENV_VAR} patterns in the MCP config\n const matches = content.matchAll(/\\$\\{([A-Z_][A-Z0-9_]*)\\}/g);\n for (const match of matches) {\n envVars.add(match[1]);\n }\n } catch {\n // No .mcp.json\n }\n return [...envVars];\n}\n\n/**\n * Get unique env setup entries (deduplicated by envVar).\n */\nexport function dedupeEnvSetup(envSetup: EnvSetupInfo[]): EnvSetupInfo[] {\n const seen = new Set<string>();\n return envSetup.filter((e) => {\n if (seen.has(e.envVar)) return false;\n seen.add(e.envVar);\n return true;\n });\n}\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { getEnvsDir } from \"../config.js\";\nimport type { EnvironmentSpec } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nexport const listCommand = new Command(\"list\")\n .description(\"Show saved environments\")\n .action(async () => {\n printCompactBanner();\n\n const envsDir = getEnvsDir();\n\n let files: string[];\n try {\n files = await fs.readdir(envsDir);\n } catch {\n console.log(chalk.dim(\" No environments yet. Run \") +\n chalk.bold(\"kairn describe\") +\n chalk.dim(\" to create one.\\n\"));\n return;\n }\n\n const jsonFiles = files.filter((f) => f.endsWith(\".json\"));\n\n if (jsonFiles.length === 0) {\n console.log(chalk.dim(\" No environments yet. Run \") +\n chalk.bold(\"kairn describe\") +\n chalk.dim(\" to create one.\\n\"));\n return;\n }\n\n let first = true;\n for (const file of jsonFiles) {\n try {\n const data = await fs.readFile(path.join(envsDir, file), \"utf-8\");\n const spec = JSON.parse(data) as EnvironmentSpec;\n const date = new Date(spec.created_at).toLocaleDateString();\n const toolCount = spec.tools?.length ?? 0;\n\n if (!first) {\n console.log(ui.divider());\n }\n first = false;\n\n console.log(ui.kv(\"Name\", chalk.bold(spec.name)));\n console.log(ui.kv(\"Description\", spec.description));\n console.log(ui.kv(\"Date\", `${date} · ${toolCount} tools`));\n console.log(ui.kv(\"ID\", chalk.dim(spec.id)));\n console.log(\"\");\n } catch {\n // Skip malformed files\n }\n }\n });\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { getEnvsDir, getTemplatesDir } from \"../config.js\";\nimport { writeEnvironment } from \"../adapter/claude-code.js\";\nimport type { EnvironmentSpec } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nexport const activateCommand = new Command(\"activate\")\n .description(\"Re-deploy a saved environment to the current directory\")\n .argument(\"<env_id>\", \"Environment ID (from kairn list)\")\n .action(async (envId: string) => {\n printCompactBanner();\n\n const envsDir = getEnvsDir();\n const templatesDir = getTemplatesDir();\n\n // Find the env file — accept full ID or partial match\n let sourceDir: string;\n let match: string | undefined;\n let fromTemplate = false;\n\n // 1. Search envs dir\n let envFiles: string[] = [];\n try {\n envFiles = await fs.readdir(envsDir);\n } catch {\n // envs dir may not exist yet; continue to templates search\n }\n\n match = envFiles.find(\n (f) => f === `${envId}.json` || f.startsWith(envId)\n );\n\n if (match) {\n sourceDir = envsDir;\n } else {\n // 2. Fall back to templates dir\n let templateFiles: string[] = [];\n try {\n templateFiles = await fs.readdir(templatesDir);\n } catch {\n // templates dir may not exist\n }\n\n match = templateFiles.find(\n (f) => f === `${envId}.json` || f.startsWith(envId)\n );\n\n if (match) {\n sourceDir = templatesDir;\n fromTemplate = true;\n } else {\n console.log(ui.error(`Environment \"${envId}\" not found.`));\n console.log(chalk.dim(\" Run kairn list to see saved environments.\"));\n console.log(chalk.dim(\" Run kairn templates to see available templates.\\n\"));\n process.exit(1);\n }\n }\n\n const data = await fs.readFile(path.join(sourceDir, match), \"utf-8\");\n const spec = JSON.parse(data) as EnvironmentSpec;\n\n const label = fromTemplate ? chalk.dim(\" (template)\") : \"\";\n console.log(chalk.cyan(` Activating: ${spec.name}`) + label);\n console.log(chalk.dim(` ${spec.description}\\n`));\n\n const targetDir = process.cwd();\n const written = await writeEnvironment(spec, targetDir);\n\n console.log(ui.success(\"Environment written\\n\"));\n for (const file of written) {\n console.log(ui.file(file));\n }\n\n console.log(\"\\n\" + ui.success(`Ready! Run: $ claude`) + \"\\n\");\n });\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nconst REGISTRY_URL =\n \"https://raw.githubusercontent.com/ashtonperlroth/kairn/main/src/registry/tools.json\";\n\nasync function getLocalRegistryPath(): Promise<string> {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n const candidates = [\n path.resolve(__dirname, \"../registry/tools.json\"),\n path.resolve(__dirname, \"../src/registry/tools.json\"),\n path.resolve(__dirname, \"../../src/registry/tools.json\"),\n ];\n for (const candidate of candidates) {\n try {\n await fs.access(candidate);\n return candidate;\n } catch {\n continue;\n }\n }\n throw new Error(\"Could not find local tools.json registry\");\n}\n\nexport const updateRegistryCommand = new Command(\"update-registry\")\n .description(\"Fetch the latest tool registry from GitHub\")\n .option(\"--url <url>\", \"Custom registry URL\")\n .action(async (options: { url?: string }) => {\n printCompactBanner();\n\n const url = options.url || REGISTRY_URL;\n\n console.log(chalk.dim(` Fetching registry from ${url}...`));\n\n try {\n const response = await fetch(url);\n\n if (!response.ok) {\n console.log(\n ui.error(`Failed to fetch registry: ${response.status} ${response.statusText}`)\n );\n console.log(chalk.dim(\" The remote registry may not be available yet.\"));\n console.log(chalk.dim(\" Your local registry is still active.\\n\"));\n return;\n }\n\n const text = await response.text();\n\n // Validate it's valid JSON and has the expected structure\n let tools: unknown[];\n try {\n tools = JSON.parse(text);\n if (!Array.isArray(tools)) throw new Error(\"Not an array\");\n if (tools.length === 0) throw new Error(\"Empty registry\");\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(`Invalid registry format: ${msg}\\n`));\n return;\n }\n\n const registryPath = await getLocalRegistryPath();\n\n // Back up existing registry\n const backupPath = registryPath + \".bak\";\n try {\n await fs.copyFile(registryPath, backupPath);\n } catch {\n // No existing file to back up\n }\n\n await fs.writeFile(registryPath, JSON.stringify(tools, null, 2), \"utf-8\");\n\n console.log(ui.success(`Registry updated: ${tools.length} tools`));\n console.log(chalk.dim(` Saved to: ${registryPath}`));\n console.log(chalk.dim(` Backup: ${backupPath}\\n`));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(`Network error: ${msg}`));\n console.log(chalk.dim(\" Your local registry is still active.\\n\"));\n }\n });\n","import { Command } from \"commander\";\nimport { confirm } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { loadConfig } from \"../config.js\";\nimport { compile } from \"../compiler/compile.js\";\nimport {\n writeEnvironment,\n summarizeSpec,\n buildFileMap,\n} from \"../adapter/claude-code.js\";\nimport { writeHermesEnvironment } from \"../adapter/hermes-agent.js\";\nimport { loadRegistry } from \"../registry/loader.js\";\nimport { collectAndWriteKeys } from \"../secrets.js\";\nimport type { RuntimeTarget } from \"../types.js\";\nimport { scanProject } from \"../scanner/scan.js\";\nimport type { ProjectProfile } from \"../scanner/scan.js\";\nimport type { EnvironmentSpec } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\ninterface FileDiff {\n path: string;\n status: \"new\" | \"modified\" | \"unchanged\";\n diff: string;\n}\n\nfunction simpleDiff(oldContent: string, newContent: string): string[] {\n const oldLines = oldContent.split(\"\\n\");\n const newLines = newContent.split(\"\\n\");\n const output: string[] = [];\n\n const maxLines = Math.max(oldLines.length, newLines.length);\n for (let i = 0; i < maxLines; i++) {\n const oldLine = oldLines[i];\n const newLine = newLines[i];\n\n if (oldLine === undefined) {\n output.push(chalk.green(`+ ${newLine}`));\n } else if (newLine === undefined) {\n output.push(chalk.red(`- ${oldLine}`));\n } else if (oldLine !== newLine) {\n output.push(chalk.red(`- ${oldLine}`));\n output.push(chalk.green(`+ ${newLine}`));\n }\n }\n\n return output;\n}\n\nasync function generateDiff(\n spec: EnvironmentSpec,\n targetDir: string,\n options?: { hasEnvVars?: boolean }\n): Promise<FileDiff[]> {\n const fileMap = buildFileMap(spec, options);\n const results: FileDiff[] = [];\n\n for (const [relativePath, newContent] of fileMap) {\n const absolutePath = path.join(targetDir, relativePath);\n let oldContent: string | null = null;\n try {\n oldContent = await fs.readFile(absolutePath, \"utf-8\");\n } catch {\n // File does not exist yet\n }\n\n if (oldContent === null) {\n results.push({\n path: relativePath,\n status: \"new\",\n diff: chalk.green(\"+ NEW FILE\"),\n });\n } else if (oldContent === newContent) {\n results.push({\n path: relativePath,\n status: \"unchanged\",\n diff: \"\",\n });\n } else {\n const diffLines = simpleDiff(oldContent, newContent);\n results.push({\n path: relativePath,\n status: \"modified\",\n diff: diffLines.join(\"\\n\"),\n });\n }\n }\n\n return results;\n}\n\nfunction buildProfileSummary(profile: ProjectProfile): string {\n const lines: string[] = [];\n lines.push(`Project: ${profile.name}`);\n if (profile.description) lines.push(`Description: ${profile.description}`);\n if (profile.language) lines.push(`Language: ${profile.language}`);\n if (profile.framework) lines.push(`Framework: ${profile.framework}`);\n if (profile.dependencies.length > 0) {\n lines.push(`Dependencies: ${profile.dependencies.join(\", \")}`);\n }\n if (profile.testCommand) lines.push(`Test command: ${profile.testCommand}`);\n if (profile.buildCommand) lines.push(`Build command: ${profile.buildCommand}`);\n if (profile.lintCommand) lines.push(`Lint command: ${profile.lintCommand}`);\n if (profile.hasDocker) lines.push(\"Has Docker configuration\");\n if (profile.hasCi) lines.push(\"Has CI/CD (GitHub Actions)\");\n if (profile.envKeys.length > 0) {\n lines.push(`Env keys needed: ${profile.envKeys.join(\", \")}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction buildAuditSummary(profile: ProjectProfile): string {\n const lines: string[] = [];\n lines.push(`\\nExisting .claude/ harness found:`);\n lines.push(` CLAUDE.md: ${profile.claudeMdLineCount} lines${profile.claudeMdLineCount > 200 ? \" (⚠ over 200 — may degrade adherence)\" : \"\"}`);\n lines.push(` MCP servers: ${profile.mcpServerCount}`);\n lines.push(` Commands: ${profile.existingCommands.length > 0 ? profile.existingCommands.map(c => `/project:${c}`).join(\", \") : \"none\"}`);\n lines.push(` Rules: ${profile.existingRules.length > 0 ? profile.existingRules.join(\", \") : \"none\"}`);\n lines.push(` Skills: ${profile.existingSkills.length > 0 ? profile.existingSkills.join(\", \") : \"none\"}`);\n lines.push(` Agents: ${profile.existingAgents.length > 0 ? profile.existingAgents.join(\", \") : \"none\"}`);\n return lines.join(\"\\n\");\n}\n\nfunction buildOptimizeIntent(profile: ProjectProfile): string {\n const parts: string[] = [];\n\n parts.push(\"## Project Profile (scanned from actual codebase)\\n\");\n parts.push(buildProfileSummary(profile));\n\n if (profile.hasClaudeDir) {\n parts.push(buildAuditSummary(profile));\n\n if (profile.existingClaudeMd) {\n parts.push(`\\n## Existing CLAUDE.md Content\\n\\n${profile.existingClaudeMd}`);\n }\n\n parts.push(`\\n## Task\\n`);\n parts.push(\"Analyze this existing Claude Code environment and generate an OPTIMIZED version.\");\n parts.push(\"Preserve what works. Fix what's wrong. Add what's missing. Remove what's bloat.\");\n parts.push(\"Key optimizations to consider:\");\n parts.push(\"- Is CLAUDE.md under 100 lines? If not, move detail to rules/ or docs/\");\n parts.push(\"- Are the right MCP servers selected for these dependencies?\");\n parts.push(\"- Are there missing slash commands (help, tasks, plan, test, commit)?\");\n parts.push(\"- Are security rules present?\");\n parts.push(\"- Is there a continuity rule for session memory?\");\n parts.push(\"- Are there unnecessary MCP servers adding context bloat?\");\n parts.push(\"- Are hooks configured in settings.json for destructive command blocking?\");\n parts.push(\"- Are there path-scoped rules for different code domains (api, testing, frontend)?\");\n parts.push(\"- Does the project have a /project:status command with live git output?\");\n parts.push(\"- Is there a /project:fix command for issue-driven development?\");\n if (profile.claudeMdLineCount > 200) {\n parts.push(`- CLAUDE.md is ${profile.claudeMdLineCount} lines — needs aggressive trimming`);\n }\n if (!profile.existingCommands.includes(\"help\")) {\n parts.push(\"- Missing /project:help command\");\n }\n if (!profile.existingRules.includes(\"security\")) {\n parts.push(\"- Missing security rules\");\n }\n } else {\n parts.push(`\\n## Task\\n`);\n parts.push(\"Generate an optimal Claude Code environment for this existing project.\");\n parts.push(\"Use the scanned project profile — this is a real codebase, not a description.\");\n parts.push(\"The environment should match the actual tech stack, dependencies, and workflows.\");\n }\n\n return parts.join(\"\\n\");\n}\n\nexport const optimizeCommand = new Command(\"optimize\")\n .description(\"Scan an existing project and generate or optimize its Claude Code environment\")\n .option(\"-y, --yes\", \"Skip confirmation prompts\")\n .option(\"--audit-only\", \"Only audit the existing harness, don't generate changes\")\n .option(\"--diff\", \"Preview changes as a diff without writing\")\n .option(\"--runtime <runtime>\", \"Target runtime (claude-code or hermes)\", \"claude-code\")\n .action(async (options: { yes?: boolean; auditOnly?: boolean; diff?: boolean; runtime?: string }) => {\n printCompactBanner();\n\n const config = await loadConfig();\n if (!config) {\n console.log(ui.errorBox(\"KAIRN — Error\", \"No config found. Run kairn init first.\"));\n process.exit(1);\n }\n\n const targetDir = process.cwd();\n\n // 1. Scan\n console.log(ui.section(\"Project Scan\"));\n const scanSpinner = ora({ text: \"Scanning project...\", indent: 2 }).start();\n const profile = await scanProject(targetDir);\n scanSpinner.stop();\n\n // 2. Show profile\n if (profile.language) console.log(ui.kv(\"Language:\", profile.language));\n if (profile.framework) console.log(ui.kv(\"Framework:\", profile.framework));\n console.log(ui.kv(\"Dependencies:\", String(profile.dependencies.length)));\n if (profile.testCommand) console.log(ui.kv(\"Tests:\", profile.testCommand));\n if (profile.buildCommand) console.log(ui.kv(\"Build:\", profile.buildCommand));\n if (profile.hasDocker) console.log(ui.kv(\"Docker:\", \"yes\"));\n if (profile.hasCi) console.log(ui.kv(\"CI/CD:\", \"yes\"));\n if (profile.envKeys.length > 0) console.log(ui.kv(\"Env keys:\", profile.envKeys.join(\", \")));\n\n // 3. Audit existing harness\n if (profile.hasClaudeDir) {\n console.log(ui.section(\"Harness Audit\"));\n console.log(ui.kv(\"CLAUDE.md:\", `${profile.claudeMdLineCount} lines${profile.claudeMdLineCount > 200 ? \" ⚠ bloated\" : \" ✓\"}`));\n console.log(ui.kv(\"MCP servers:\", String(profile.mcpServerCount)));\n console.log(ui.kv(\"Commands:\", profile.existingCommands.length > 0 ? profile.existingCommands.join(\", \") : \"none\"));\n console.log(ui.kv(\"Rules:\", profile.existingRules.length > 0 ? profile.existingRules.join(\", \") : \"none\"));\n console.log(ui.kv(\"Skills:\", profile.existingSkills.length > 0 ? profile.existingSkills.join(\", \") : \"none\"));\n console.log(ui.kv(\"Agents:\", profile.existingAgents.length > 0 ? profile.existingAgents.join(\", \") : \"none\"));\n\n // Quick audit checks\n const issues: string[] = [];\n if (profile.claudeMdLineCount > 200) issues.push(\"CLAUDE.md over 200 lines — move detail to rules/ or docs/\");\n if (!profile.existingCommands.includes(\"help\")) issues.push(\"Missing /project:help command\");\n if (!profile.existingRules.includes(\"security\")) issues.push(\"Missing security rules\");\n if (!profile.existingRules.includes(\"continuity\")) issues.push(\"Missing continuity rule for session memory\");\n if (profile.mcpServerCount > 8) issues.push(`${profile.mcpServerCount} MCP servers — may cause context bloat`);\n if (profile.mcpServerCount === 0 && profile.dependencies.length > 0) issues.push(\"No MCP servers configured\");\n if (profile.hasTests && !profile.existingCommands.includes(\"test\")) issues.push(\"Has tests but no /project:test command\");\n if (!profile.existingCommands.includes(\"tasks\")) issues.push(\"Missing /project:tasks command\");\n if (!profile.existingSettings?.hooks) issues.push(\"No hooks configured — missing destructive command blocking\");\n const scopedRules = profile.existingRules.filter(r => r !== \"security\" && r !== \"continuity\");\n if (profile.hasSrc && scopedRules.length === 0) issues.push(\"No path-scoped rules — consider adding api.md, testing.md, or frontend.md rules\");\n\n if (issues.length > 0) {\n console.log(\"\");\n for (const issue of issues) {\n console.log(ui.warn(issue));\n }\n } else {\n console.log(ui.success(\"No obvious issues found\"));\n }\n\n if (options.auditOnly) {\n console.log(chalk.dim(\"\\n Audit complete. Run without --audit-only to generate optimized environment.\\n\"));\n return;\n }\n\n // Ask before overwriting\n if (!options.yes) {\n console.log(\"\");\n const proceed = await confirm({\n message: \"Generate optimized environment? This will overwrite existing .claude/ files.\",\n default: false,\n });\n if (!proceed) {\n console.log(chalk.dim(\"\\n Aborted.\\n\"));\n return;\n }\n }\n } else {\n console.log(chalk.dim(\"\\n No existing .claude/ directory found — generating from scratch.\\n\"));\n\n if (!options.yes) {\n const proceed = await confirm({\n message: \"Generate Claude Code environment for this project?\",\n default: true,\n });\n if (!proceed) {\n console.log(chalk.dim(\"\\n Aborted.\\n\"));\n return;\n }\n }\n }\n\n // 4. Compile with scanned profile\n const intent = buildOptimizeIntent(profile);\n let spec;\n const spinner = ora({ text: \"Compiling optimized environment...\", indent: 2 }).start();\n try {\n spec = await compile(intent, (progress) => {\n spinner.text = progress.message;\n });\n spinner.succeed(\"Environment compiled\");\n } catch (err) {\n spinner.fail(\"Compilation failed\");\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.errorBox(\"KAIRN — Error\", `Optimization failed: ${msg}`));\n process.exit(1);\n }\n\n // 5. Show results\n const registry = await loadRegistry();\n const summary = summarizeSpec(spec, registry);\n\n console.log(\"\");\n console.log(ui.kv(\"Name:\", spec.name));\n console.log(ui.kv(\"Tools:\", String(summary.toolCount)));\n console.log(ui.kv(\"Commands:\", String(summary.commandCount)));\n console.log(ui.kv(\"Rules:\", String(summary.ruleCount)));\n console.log(ui.kv(\"Skills:\", String(summary.skillCount)));\n console.log(ui.kv(\"Agents:\", String(summary.agentCount)));\n\n if (spec.tools.length > 0) {\n console.log(ui.section(\"Selected Tools\"));\n for (const tool of spec.tools) {\n const regTool = registry.find((t) => t.id === tool.tool_id);\n const name = regTool?.name || tool.tool_id;\n console.log(ui.tool(name, tool.reason));\n }\n }\n\n // 6. Diff preview or direct write\n const hasEnvVars = summary.envSetup.length > 0;\n\n if (options.diff) {\n const diffs = await generateDiff(spec, targetDir, { hasEnvVars });\n const changedDiffs = diffs.filter((d) => d.status !== \"unchanged\");\n\n if (changedDiffs.length === 0) {\n console.log(ui.success(\"No changes needed — environment is already up to date.\"));\n console.log(\"\");\n return;\n }\n\n console.log(ui.section(\"Changes Preview\"));\n for (const d of changedDiffs) {\n console.log(chalk.cyan(`\\n --- ${d.path}`));\n if (d.status === \"new\") {\n console.log(` ${d.diff}`);\n } else {\n for (const line of d.diff.split(\"\\n\")) {\n console.log(` ${line}`);\n }\n }\n }\n console.log(\"\");\n\n const apply = await confirm({\n message: \"Apply these changes?\",\n default: true,\n });\n if (!apply) {\n console.log(chalk.dim(\"\\n Aborted.\\n\"));\n return;\n }\n }\n\n const runtime = (options.runtime ?? \"claude-code\") as RuntimeTarget;\n\n if (runtime === \"hermes\") {\n await writeHermesEnvironment(spec, registry);\n console.log(ui.divider());\n console.log(ui.success(`Ready! Run: $ hermes`));\n console.log(\"\");\n } else {\n const written = await writeEnvironment(spec, targetDir, { hasEnvVars });\n\n console.log(ui.section(\"Files Written\"));\n for (const file of written) {\n console.log(ui.file(file));\n }\n\n // Interactive key collection after optimize\n if (hasEnvVars) {\n await collectAndWriteKeys(summary.envSetup, targetDir);\n console.log(\"\");\n }\n\n if (summary.pluginCommands.length > 0) {\n console.log(ui.section(\"Plugins\"));\n for (const cmd of summary.pluginCommands) {\n console.log(ui.cmd(cmd));\n }\n console.log(\"\");\n }\n\n console.log(ui.divider());\n console.log(ui.success(\"Ready! Run: $ claude\"));\n console.log(\"\");\n }\n });\n","import fs from \"fs/promises\";\nimport path from \"path\";\n\nexport interface ProjectProfile {\n // Core identity\n name: string;\n description: string;\n directory: string;\n\n // Language & framework\n language: string | null;\n framework: string | null;\n typescript: boolean;\n\n // Dependencies\n dependencies: string[];\n devDependencies: string[];\n\n // Scripts & commands\n scripts: Record<string, string>;\n hasTests: boolean;\n testCommand: string | null;\n buildCommand: string | null;\n lintCommand: string | null;\n\n // Project structure\n hasSrc: boolean;\n hasDocker: boolean;\n hasCi: boolean;\n hasEnvFile: boolean;\n envKeys: string[]; // from .env.example only — never read .env values\n\n // Existing harness\n hasClaudeDir: boolean;\n existingClaudeMd: string | null;\n existingSettings: Record<string, unknown> | null;\n existingMcpConfig: Record<string, unknown> | null;\n existingCommands: string[];\n existingRules: string[];\n existingSkills: string[];\n existingAgents: string[];\n mcpServerCount: number;\n claudeMdLineCount: number;\n\n // Key files found\n keyFiles: string[];\n}\n\nasync function fileExists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readJsonSafe(p: string): Promise<Record<string, unknown> | null> {\n try {\n const data = await fs.readFile(p, \"utf-8\");\n return JSON.parse(data);\n } catch {\n return null;\n }\n}\n\nasync function readFileSafe(p: string): Promise<string | null> {\n try {\n return await fs.readFile(p, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function listDirSafe(p: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(p);\n return entries.filter((e) => !e.startsWith(\".\"));\n } catch {\n return [];\n }\n}\n\nfunction detectFramework(deps: string[]): string | null {\n const frameworks: [string[], string][] = [\n [[\"next\"], \"Next.js\"],\n [[\"nuxt\"], \"Nuxt\"],\n [[\"@remix-run/node\", \"@remix-run/react\"], \"Remix\"],\n [[\"svelte\", \"@sveltejs/kit\"], \"SvelteKit\"],\n [[\"express\"], \"Express\"],\n [[\"fastify\"], \"Fastify\"],\n [[\"hono\"], \"Hono\"],\n [[\"react\", \"react-dom\"], \"React\"],\n [[\"vue\"], \"Vue\"],\n [[\"angular\"], \"Angular\"],\n [[\"django\"], \"Django\"],\n [[\"flask\"], \"Flask\"],\n [[\"fastapi\"], \"FastAPI\"],\n [[\"@supabase/supabase-js\"], \"Supabase\"],\n [[\"prisma\", \"@prisma/client\"], \"Prisma\"],\n [[\"drizzle-orm\"], \"Drizzle\"],\n [[\"tailwindcss\"], \"Tailwind CSS\"],\n ];\n\n const detected: string[] = [];\n for (const [packages, name] of frameworks) {\n if (packages.some((pkg) => deps.includes(pkg))) {\n detected.push(name);\n }\n }\n return detected.length > 0 ? detected.join(\" + \") : null;\n}\n\nfunction detectLanguage(dir: string, keyFiles: string[]): string | null {\n if (keyFiles.some((f) => f === \"tsconfig.json\")) return \"TypeScript\";\n if (keyFiles.some((f) => f === \"package.json\")) return \"JavaScript\";\n if (keyFiles.some((f) => f === \"pyproject.toml\" || f === \"setup.py\" || f === \"requirements.txt\")) return \"Python\";\n if (keyFiles.some((f) => f === \"Cargo.toml\")) return \"Rust\";\n if (keyFiles.some((f) => f === \"go.mod\")) return \"Go\";\n if (keyFiles.some((f) => f === \"Gemfile\")) return \"Ruby\";\n return null;\n}\n\nfunction extractEnvKeys(content: string): string[] {\n const keys: string[] = [];\n for (const line of content.split(\"\\n\")) {\n const match = line.match(/^([A-Z][A-Z0-9_]*)=/);\n if (match) keys.push(match[1]);\n }\n return keys;\n}\n\nexport async function scanProject(dir: string): Promise<ProjectProfile> {\n // Read package.json\n const pkg = await readJsonSafe(path.join(dir, \"package.json\")) as Record<string, unknown> | null;\n const deps = pkg?.dependencies ? Object.keys(pkg.dependencies as Record<string, string>) : [];\n const devDeps = pkg?.devDependencies ? Object.keys(pkg.devDependencies as Record<string, string>) : [];\n const allDeps = [...deps, ...devDeps];\n const scripts = (pkg?.scripts || {}) as Record<string, string>;\n\n // Detect key files\n const rootFiles = await listDirSafe(dir);\n const keyFiles = rootFiles.filter((f) =>\n [\n \"package.json\", \"tsconfig.json\", \"pyproject.toml\", \"setup.py\",\n \"requirements.txt\", \"Cargo.toml\", \"go.mod\", \"Gemfile\",\n \"docker-compose.yml\", \"Dockerfile\", \".env.example\", \".env\",\n \"README.md\", \"CLAUDE.md\",\n ].includes(f)\n );\n\n // Detect language & framework\n const language = detectLanguage(dir, keyFiles);\n const framework = detectFramework(allDeps);\n const typescript = keyFiles.includes(\"tsconfig.json\") || allDeps.includes(\"typescript\");\n\n // Test detection\n const testCommand = scripts.test && scripts.test !== 'echo \"Error: no test specified\" && exit 1'\n ? scripts.test : null;\n const hasTests = testCommand !== null ||\n await fileExists(path.join(dir, \"tests\")) ||\n await fileExists(path.join(dir, \"__tests__\")) ||\n await fileExists(path.join(dir, \"test\"));\n\n // Build & lint\n const buildCommand = scripts.build || null;\n const lintCommand = scripts.lint || null;\n\n // Structure\n const hasSrc = await fileExists(path.join(dir, \"src\"));\n const hasDocker = await fileExists(path.join(dir, \"docker-compose.yml\")) ||\n await fileExists(path.join(dir, \"Dockerfile\"));\n const hasCi = await fileExists(path.join(dir, \".github/workflows\"));\n\n // Env keys (from .env.example only — never read actual .env values)\n const hasEnvFile = await fileExists(path.join(dir, \".env\")) ||\n await fileExists(path.join(dir, \".env.example\"));\n let envKeys: string[] = [];\n const envExample = await readFileSafe(path.join(dir, \".env.example\"));\n if (envExample) {\n envKeys = extractEnvKeys(envExample);\n }\n\n // Existing .claude/ harness\n const claudeDir = path.join(dir, \".claude\");\n const hasClaudeDir = await fileExists(claudeDir);\n let existingClaudeMd: string | null = null;\n let existingSettings: Record<string, unknown> | null = null;\n let existingMcpConfig: Record<string, unknown> | null = null;\n let existingCommands: string[] = [];\n let existingRules: string[] = [];\n let existingSkills: string[] = [];\n let existingAgents: string[] = [];\n let mcpServerCount = 0;\n let claudeMdLineCount = 0;\n\n if (hasClaudeDir) {\n existingClaudeMd = await readFileSafe(path.join(claudeDir, \"CLAUDE.md\"));\n if (existingClaudeMd) {\n claudeMdLineCount = existingClaudeMd.split(\"\\n\").length;\n }\n\n existingSettings = await readJsonSafe(path.join(claudeDir, \"settings.json\"));\n existingMcpConfig = await readJsonSafe(path.join(dir, \".mcp.json\"));\n if (existingMcpConfig?.mcpServers) {\n mcpServerCount = Object.keys(existingMcpConfig.mcpServers as Record<string, unknown>).length;\n }\n\n existingCommands = (await listDirSafe(path.join(claudeDir, \"commands\")))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => f.replace(\".md\", \"\"));\n existingRules = (await listDirSafe(path.join(claudeDir, \"rules\")))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => f.replace(\".md\", \"\"));\n existingSkills = await listDirSafe(path.join(claudeDir, \"skills\"));\n existingAgents = (await listDirSafe(path.join(claudeDir, \"agents\")))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => f.replace(\".md\", \"\"));\n }\n\n // Project name & description\n const name = (pkg?.name as string) || path.basename(dir);\n const description = (pkg?.description as string) || \"\";\n\n return {\n name,\n description,\n directory: dir,\n language,\n framework,\n typescript,\n dependencies: deps,\n devDependencies: devDeps,\n scripts,\n hasTests,\n testCommand,\n buildCommand,\n lintCommand,\n hasSrc,\n hasDocker,\n hasCi,\n hasEnvFile,\n envKeys,\n hasClaudeDir,\n existingClaudeMd,\n existingSettings,\n existingMcpConfig,\n existingCommands,\n existingRules,\n existingSkills,\n existingAgents,\n mcpServerCount,\n claudeMdLineCount,\n keyFiles,\n };\n}\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { scanProject } from \"../scanner/scan.js\";\nimport type { ProjectProfile } from \"../scanner/scan.js\";\nimport { ui } from \"../ui.js\";\nimport { printFullBanner } from \"../logo.js\";\n\ninterface Check {\n name: string;\n weight: number; // 1-3\n status: \"pass\" | \"warn\" | \"fail\";\n message: string;\n}\n\nfunction runChecks(profile: ProjectProfile): Check[] {\n const checks: Check[] = [];\n\n // CLAUDE.md existence and size\n if (!profile.existingClaudeMd) {\n checks.push({\n name: \"CLAUDE.md\",\n weight: 3,\n status: \"fail\",\n message: \"Missing CLAUDE.md\",\n });\n } else if (profile.claudeMdLineCount > 200) {\n checks.push({\n name: \"CLAUDE.md\",\n weight: 2,\n status: \"warn\",\n message: `${profile.claudeMdLineCount} lines (recommended: ≤100)`,\n });\n } else {\n checks.push({\n name: \"CLAUDE.md\",\n weight: 3,\n status: \"pass\",\n message: `${profile.claudeMdLineCount} lines`,\n });\n }\n\n // Settings.json with deny rules\n if (!profile.existingSettings) {\n checks.push({\n name: \"settings.json\",\n weight: 2,\n status: \"fail\",\n message: \"Missing settings.json\",\n });\n } else {\n const perms = profile.existingSettings.permissions as\n | Record<string, unknown>\n | undefined;\n const hasDeny =\n perms?.deny &&\n Array.isArray(perms.deny) &&\n (perms.deny as string[]).length > 0;\n checks.push({\n name: \"Deny rules\",\n weight: 2,\n status: hasDeny ? \"pass\" : \"warn\",\n message: hasDeny\n ? \"Deny rules configured\"\n : \"No deny rules in settings.json\",\n });\n }\n\n // MCP server count\n if (profile.mcpServerCount > 8) {\n checks.push({\n name: \"MCP servers\",\n weight: 1,\n status: \"warn\",\n message: `${profile.mcpServerCount} servers (recommended: ≤8)`,\n });\n } else if (profile.mcpServerCount > 0) {\n checks.push({\n name: \"MCP servers\",\n weight: 1,\n status: \"pass\",\n message: `${profile.mcpServerCount} servers`,\n });\n } else {\n checks.push({\n name: \"MCP servers\",\n weight: 1,\n status: \"warn\",\n message: \"No MCP servers configured\",\n });\n }\n\n // /project:help command\n checks.push({\n name: \"/project:help\",\n weight: 2,\n status: profile.existingCommands.includes(\"help\") ? \"pass\" : \"fail\",\n message: profile.existingCommands.includes(\"help\")\n ? \"Help command present\"\n : \"Missing /project:help command\",\n });\n\n // /project:tasks command\n checks.push({\n name: \"/project:tasks\",\n weight: 1,\n status: profile.existingCommands.includes(\"tasks\") ? \"pass\" : \"warn\",\n message: profile.existingCommands.includes(\"tasks\")\n ? \"Tasks command present\"\n : \"Missing /project:tasks command\",\n });\n\n // Security rule\n checks.push({\n name: \"Security rule\",\n weight: 3,\n status: profile.existingRules.includes(\"security\") ? \"pass\" : \"fail\",\n message: profile.existingRules.includes(\"security\")\n ? \"Security rule present\"\n : \"Missing rules/security.md\",\n });\n\n // Continuity rule\n checks.push({\n name: \"Continuity rule\",\n weight: 2,\n status: profile.existingRules.includes(\"continuity\") ? \"pass\" : \"warn\",\n message: profile.existingRules.includes(\"continuity\")\n ? \"Continuity rule present\"\n : \"Missing rules/continuity.md\",\n });\n\n // Hooks\n const hasHooks = profile.existingSettings?.hooks;\n checks.push({\n name: \"Hooks\",\n weight: 1,\n status: hasHooks ? \"pass\" : \"warn\",\n message: hasHooks ? \"Hooks configured\" : \"No hooks in settings.json\",\n });\n\n // .env protection\n const perms = profile.existingSettings?.permissions as\n | Record<string, unknown>\n | undefined;\n const denyList = (perms?.deny as string[] | undefined) || [];\n const envProtected = denyList.some((d: string) => d.includes(\".env\"));\n checks.push({\n name: \".env protection\",\n weight: 2,\n status: envProtected ? \"pass\" : \"warn\",\n message: envProtected ? \".env in deny list\" : \".env not in deny list\",\n });\n\n // CLAUDE.md sections check (if exists)\n if (profile.existingClaudeMd) {\n const requiredSections = [\"## Purpose\", \"## Commands\", \"## Tech Stack\"];\n const missingSections = requiredSections.filter(\n (s) => !profile.existingClaudeMd!.includes(s)\n );\n if (missingSections.length > 0) {\n checks.push({\n name: \"CLAUDE.md sections\",\n weight: 1,\n status: \"warn\",\n message: `Missing: ${missingSections.join(\", \")}`,\n });\n } else {\n checks.push({\n name: \"CLAUDE.md sections\",\n weight: 1,\n status: \"pass\",\n message: \"Required sections present\",\n });\n }\n }\n\n return checks;\n}\n\nexport const doctorCommand = new Command(\"doctor\")\n .description(\n \"Validate the current Claude Code environment against best practices\"\n )\n .action(async () => {\n printFullBanner(\"Doctor\");\n\n const targetDir = process.cwd();\n\n console.log(chalk.dim(\" Checking .claude/ environment...\\n\"));\n\n const profile = await scanProject(targetDir);\n\n if (!profile.hasClaudeDir) {\n console.log(ui.error(\"No .claude/ directory found.\\n\"));\n console.log(\n chalk.dim(\" Run \") +\n chalk.bold(\"kairn describe\") +\n chalk.dim(\" or \") +\n chalk.bold(\"kairn optimize\") +\n chalk.dim(\" to generate one.\\n\")\n );\n process.exit(1);\n }\n\n const checks = runChecks(profile);\n\n console.log(ui.section(\"Health Check\"));\n console.log(\"\");\n\n // Display results\n for (const check of checks) {\n if (check.status === \"pass\") {\n console.log(ui.success(`${check.name}: ${check.message}`));\n } else if (check.status === \"warn\") {\n console.log(ui.warn(`${check.name}: ${check.message}`));\n } else {\n console.log(ui.error(`${check.name}: ${check.message}`));\n }\n }\n\n // Calculate score\n const maxScore = checks.reduce((sum, c) => sum + c.weight, 0);\n const score = checks.reduce((sum, c) => {\n if (c.status === \"pass\") return sum + c.weight;\n if (c.status === \"warn\") return sum + Math.floor(c.weight / 2);\n return sum;\n }, 0);\n\n const percentage = Math.round((score / maxScore) * 100);\n const scoreColor =\n percentage >= 80\n ? chalk.green\n : percentage >= 50\n ? chalk.yellow\n : chalk.red;\n\n console.log(\n `\\n Score: ${scoreColor(`${score}/${maxScore}`)} (${scoreColor(`${percentage}%`)})\\n`\n );\n\n if (percentage < 80) {\n console.log(\n chalk.dim(\" Run \") +\n chalk.bold(\"kairn optimize\") +\n chalk.dim(\" to fix issues.\\n\")\n );\n }\n });\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { input, select } from \"@inquirer/prompts\";\nimport { loadRegistry, loadUserRegistry, saveUserRegistry } from \"../registry/loader.js\";\nimport type { RegistryTool } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nconst listCommand = new Command(\"list\")\n .description(\"List tools in the registry\")\n .option(\"--category <cat>\", \"Filter by category\")\n .option(\"--user-only\", \"Show only user-defined tools\")\n .action(async (options: { category?: string; userOnly?: boolean }) => {\n printCompactBanner();\n\n let all: RegistryTool[];\n let userTools: RegistryTool[];\n\n try {\n [all, userTools] = await Promise.all([loadRegistry(), loadUserRegistry()]);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(`Failed to load registry: ${msg}\\n`));\n process.exit(1);\n }\n\n const userIds = new Set(userTools.map((t) => t.id));\n\n let tools = all;\n\n if (options.userOnly) {\n tools = tools.filter((t) => userIds.has(t.id));\n }\n\n if (options.category) {\n tools = tools.filter(\n (t) => t.category.toLowerCase() === options.category!.toLowerCase()\n );\n }\n\n if (tools.length === 0) {\n console.log(chalk.dim(\"\\n No tools found.\\n\"));\n return;\n }\n\n const bundledCount = all.filter((t) => !userIds.has(t.id)).length;\n const userCount = userIds.size;\n\n console.log(ui.section(\"Registry Tools\"));\n console.log(\"\");\n\n for (const tool of tools) {\n const isUser = userIds.has(tool.id);\n const meta = [\n tool.category,\n `tier ${tool.tier}`,\n tool.auth,\n ].join(\", \");\n\n console.log(` ${ui.accent(tool.id)}` + chalk.dim(` (${meta})`));\n console.log(chalk.dim(` ${tool.description}`));\n\n if (tool.best_for.length > 0) {\n console.log(chalk.dim(` Best for: ${tool.best_for.join(\", \")}`));\n }\n\n if (isUser) {\n console.log(chalk.yellow(\" [USER-DEFINED]\"));\n }\n\n console.log(\"\");\n }\n\n const totalShown = tools.length;\n const shownUser = tools.filter((t) => userIds.has(t.id)).length;\n const shownBundled = totalShown - shownUser;\n\n console.log(\n chalk.dim(\n ` ${totalShown} tool${totalShown !== 1 ? \"s\" : \"\"} (${shownBundled} bundled, ${shownUser} user-defined)`\n ) + \"\\n\"\n );\n });\n\nconst addCommand = new Command(\"add\")\n .description(\"Add a tool to the user registry\")\n .action(async () => {\n let id: string;\n try {\n id = await input({\n message: \"Tool ID (kebab-case)\",\n validate: (v) => {\n if (!v) return \"ID is required\";\n if (!/^[a-z][a-z0-9-]*$/.test(v)) return \"ID must be kebab-case (e.g. my-tool)\";\n return true;\n },\n });\n\n const name = await input({ message: \"Display name\" });\n const description = await input({ message: \"Description\" });\n\n const category = await select({\n message: \"Category\",\n choices: [\n { value: \"universal\" },\n { value: \"code\" },\n { value: \"search\" },\n { value: \"data\" },\n { value: \"communication\" },\n { value: \"design\" },\n { value: \"monitoring\" },\n { value: \"infrastructure\" },\n { value: \"sandbox\" },\n ],\n });\n\n const tier = await select<number>({\n message: \"Tier\",\n choices: [\n { name: \"1 — Universal\", value: 1 },\n { name: \"2 — Common\", value: 2 },\n { name: \"3 — Specialized\", value: 3 },\n ],\n });\n\n const type = await select<\"mcp_server\" | \"plugin\" | \"hook\">({\n message: \"Type\",\n choices: [\n { value: \"mcp_server\" },\n { value: \"plugin\" },\n { value: \"hook\" },\n ],\n });\n\n const auth = await select<\"none\" | \"api_key\" | \"oauth\" | \"connection_string\">({\n message: \"Auth\",\n choices: [\n { value: \"none\" },\n { value: \"api_key\" },\n { value: \"oauth\" },\n { value: \"connection_string\" },\n ],\n });\n\n const env_vars: { name: string; description: string }[] = [];\n if (auth === \"api_key\" || auth === \"connection_string\") {\n let addMore = true;\n while (addMore) {\n const varName = await input({ message: \"Env var name\" });\n const varDesc = await input({ message: \"Env var description\" });\n env_vars.push({ name: varName, description: varDesc });\n const another = await select<boolean>({\n message: \"Add another env var?\",\n choices: [\n { name: \"No\", value: false },\n { name: \"Yes\", value: true },\n ],\n });\n addMore = another;\n }\n }\n\n const signup_url_raw = await input({ message: \"Signup URL (optional, press enter to skip)\" });\n const signup_url = signup_url_raw.trim() || undefined;\n\n const best_for_raw = await input({ message: \"Best-for tags, comma-separated\" });\n const best_for = best_for_raw\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n const install: RegistryTool[\"install\"] = {};\n if (type === \"mcp_server\") {\n const command = await input({ message: \"MCP command\" });\n const args_raw = await input({ message: \"MCP args, comma-separated (leave blank for none)\" });\n const args = args_raw\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n install.mcp_config = { command, args };\n }\n\n const tool: RegistryTool = {\n id,\n name,\n description,\n category,\n tier,\n type,\n auth,\n best_for,\n install,\n ...(env_vars.length > 0 ? { env_vars } : {}),\n ...(signup_url ? { signup_url } : {}),\n };\n\n let userToolsList: RegistryTool[];\n try {\n userToolsList = await loadUserRegistry();\n } catch {\n userToolsList = [];\n }\n\n const existingIdx = userToolsList.findIndex((t) => t.id === id);\n if (existingIdx >= 0) {\n userToolsList[existingIdx] = tool;\n } else {\n userToolsList.push(tool);\n }\n\n await saveUserRegistry(userToolsList);\n\n console.log(ui.success(`Tool ${id} added to user registry\\n`));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(`Failed to add tool: ${msg}\\n`));\n process.exit(1);\n }\n });\n\nexport const registryCommand = new Command(\"registry\")\n .description(\"Manage the tool registry\")\n .addCommand(listCommand)\n .addCommand(addCommand);\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { getTemplatesDir } from \"../config.js\";\nimport type { EnvironmentSpec } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nexport const templatesCommand = new Command(\"templates\")\n .description(\"Browse available templates\")\n .option(\"--category <cat>\", \"filter templates by category keyword\")\n .option(\"--json\", \"output raw JSON array\")\n .action(async (options: { category?: string; json?: boolean }) => {\n printCompactBanner();\n\n const templatesDir = getTemplatesDir();\n\n let files: string[];\n try {\n files = await fs.readdir(templatesDir);\n } catch {\n console.log(\n chalk.dim(\n \" No templates found. Templates will be installed with \"\n ) +\n chalk.bold(\"kairn init\") +\n chalk.dim(\n \" or you can add .json files to ~/.kairn/templates/\\n\"\n )\n );\n return;\n }\n\n const jsonFiles = files.filter((f) => f.endsWith(\".json\"));\n\n if (jsonFiles.length === 0) {\n console.log(\n chalk.dim(\n \" No templates found. Templates will be installed with \"\n ) +\n chalk.bold(\"kairn init\") +\n chalk.dim(\n \" or you can add .json files to ~/.kairn/templates/\\n\"\n )\n );\n return;\n }\n\n const templates: EnvironmentSpec[] = [];\n\n for (const file of jsonFiles) {\n try {\n const data = await fs.readFile(\n path.join(templatesDir, file),\n \"utf-8\"\n );\n const spec = JSON.parse(data) as EnvironmentSpec;\n templates.push(spec);\n } catch {\n // Skip malformed files\n }\n }\n\n const filtered = options.category\n ? templates.filter((t) => {\n const keyword = options.category!.toLowerCase();\n return (\n t.intent?.toLowerCase().includes(keyword) ||\n t.description?.toLowerCase().includes(keyword)\n );\n })\n : templates;\n\n if (options.json) {\n console.log(JSON.stringify(filtered, null, 2));\n return;\n }\n\n if (filtered.length === 0) {\n console.log(\n chalk.dim(` No templates matched category \"${options.category}\".\\n`)\n );\n return;\n }\n\n console.log(ui.section(\"Templates\"));\n console.log(\"\");\n\n for (const spec of filtered) {\n const toolCount = spec.tools?.length ?? 0;\n const commandCount = Object.keys(spec.harness?.commands ?? {}).length;\n const ruleCount = Object.keys(spec.harness?.rules ?? {}).length;\n\n console.log(ui.kv(\"Name\", chalk.bold(spec.name)));\n console.log(ui.kv(\"ID\", chalk.dim(spec.id)));\n console.log(ui.kv(\"Description\", spec.description));\n console.log(\n ui.kv(\"Contents\", `${toolCount} tools · ${commandCount} commands · ${ruleCount} rules`)\n );\n console.log(\"\");\n }\n\n console.log(\n chalk.dim(` ${filtered.length} template${filtered.length === 1 ? \"\" : \"s\"} available\\n`)\n );\n });\n","import { Command } from \"commander\";\nimport { password } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\nimport {\n detectRequiredEnvVars,\n readEnvFile,\n collectAndWriteKeys,\n} from \"../secrets.js\";\nimport { loadRegistry } from \"../registry/loader.js\";\nimport type { EnvSetupInfo } from \"../adapter/claude-code.js\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\n\nexport const keysCommand = new Command(\"keys\")\n .description(\"Add or update API keys for the current environment\")\n .option(\"--show\", \"Show which keys are set vs missing\")\n .action(async (options: { show?: boolean }) => {\n printCompactBanner();\n\n const targetDir = process.cwd();\n\n // 1. Detect required env vars from .mcp.json\n const requiredVars = await detectRequiredEnvVars(targetDir);\n\n if (requiredVars.length === 0) {\n console.log(\n ui.info(\"No MCP servers found in .mcp.json — no API keys needed.\")\n );\n console.log(\"\");\n return;\n }\n\n // 2. Read existing .env\n const existing = await readEnvFile(targetDir);\n\n // 3. Build env setup info from registry for richer display\n const registry = await loadRegistry();\n const envSetupMap = new Map<string, EnvSetupInfo>();\n for (const tool of registry) {\n if (!tool.env_vars) continue;\n for (const ev of tool.env_vars) {\n if (requiredVars.includes(ev.name)) {\n envSetupMap.set(ev.name, {\n toolName: tool.name,\n envVar: ev.name,\n description: ev.description,\n signupUrl: tool.signup_url,\n });\n }\n }\n }\n\n // Fill in any vars not found in registry\n for (const varName of requiredVars) {\n if (!envSetupMap.has(varName)) {\n envSetupMap.set(varName, {\n toolName: \"unknown\",\n envVar: varName,\n description: \"Required by MCP server\",\n });\n }\n }\n\n // 4. --show mode: display status and exit\n if (options.show) {\n console.log(ui.section(\"API Key Status\"));\n console.log(\"\");\n\n for (const varName of requiredVars) {\n const value = existing.get(varName);\n const info = envSetupMap.get(varName);\n const toolLabel = info?.toolName !== \"unknown\" ? chalk.dim(` (${info?.toolName})`) : \"\";\n\n if (value && value.length > 0) {\n const masked = value.slice(0, 4) + \"•\".repeat(Math.max(0, value.length - 4));\n console.log(chalk.green(` ✓ ${varName}`) + toolLabel + chalk.dim(` = ${masked}`));\n } else {\n console.log(chalk.yellow(` ✗ ${varName}`) + toolLabel + chalk.dim(\" = (not set)\"));\n if (info?.signupUrl) {\n console.log(chalk.dim(` Get one at: ${info.signupUrl}`));\n }\n }\n }\n\n const setCount = requiredVars.filter((v) => {\n const val = existing.get(v);\n return val && val.length > 0;\n }).length;\n const missingCount = requiredVars.length - setCount;\n\n console.log(\"\");\n if (missingCount === 0) {\n console.log(ui.success(`All ${setCount} key(s) configured`));\n } else {\n console.log(\n ui.warn(`${missingCount} key(s) missing — run ${chalk.bold(\"kairn keys\")} to add them`)\n );\n }\n console.log(\"\");\n return;\n }\n\n // 5. Interactive mode: prompt for missing or empty keys\n const missing = requiredVars.filter((v) => {\n const val = existing.get(v);\n return !val || val.length === 0;\n });\n\n if (missing.length === 0) {\n console.log(ui.success(\"All API keys are already configured.\"));\n console.log(chalk.dim(\" Use --show to see current keys.\\n\"));\n return;\n }\n\n console.log(ui.section(\"API Keys\"));\n console.log(chalk.dim(` ${missing.length} key(s) need to be set. Press Enter to skip.\\n`));\n\n const envEntries = new Map(existing);\n let keysEntered = 0;\n\n for (const varName of missing) {\n const info = envSetupMap.get(varName);\n\n console.log(\n chalk.bold(` ${varName}`) +\n (info?.toolName !== \"unknown\" ? chalk.dim(` (${info?.toolName})`) : \"\")\n );\n if (info?.signupUrl) {\n console.log(chalk.dim(` Get one at: ${info.signupUrl}`));\n }\n\n const value = await password({\n message: varName,\n mask: \"•\",\n });\n\n if (value && value.trim()) {\n envEntries.set(varName, value.trim());\n console.log(chalk.green(\" ✓ saved\\n\"));\n keysEntered++;\n } else {\n console.log(chalk.dim(\" (skipped)\\n\"));\n }\n }\n\n // 6. Write updated .env\n const envLines: string[] = [\n \"# Generated by Kairn — API keys for MCP servers\",\n \"# Do NOT commit this file to git\",\n \"\",\n ];\n for (const [key, value] of envEntries) {\n envLines.push(`${key}=${value}`);\n }\n\n const envPath = path.join(targetDir, \".env\");\n await fs.writeFile(envPath, envLines.join(\"\\n\") + \"\\n\", \"utf-8\");\n\n console.log(chalk.green(` ✓ ${keysEntered} key(s) saved to .env`));\n console.log(\"\");\n });\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport { parse as yamlParse } from 'yaml';\nimport { confirm, input, select } from '@inquirer/prompts';\nimport { ui } from '../ui.js';\nimport { autoGenerateTasks, createEvolveWorkspace, writeTasksFile, buildProjectProfile } from '../evolve/init.js';\nimport { generateTasksFromTemplates, EVAL_TEMPLATES, selectTemplatesForWorkflow } from '../evolve/templates.js';\nimport { snapshotBaseline } from '../evolve/baseline.js';\nimport { runTask } from '../evolve/runner.js';\nimport { scoreTask } from '../evolve/scorers.js';\nimport { writeScore, loadIterationLog } from '../evolve/trace.js';\nimport { evolve } from '../evolve/loop.js';\nimport { generateMarkdownReport, generateJsonReport } from '../evolve/report.js';\nimport { generateDiff } from '../evolve/mutator.js';\nimport { applyEvolution } from '../evolve/apply.js';\nimport { loadConfig } from '../config.js';\nimport type { EvolveConfig, Task, TasksFile, TaskResult, LoopProgressEvent } from '../evolve/types.js';\n\nconst DEFAULT_CONFIG: EvolveConfig = {\n model: 'claude-sonnet-4-6',\n proposerModel: 'claude-sonnet-4-6',\n scorer: 'pass-fail',\n maxIterations: 5,\n parallelTasks: 1,\n runsPerTask: 1,\n maxMutationsPerIteration: 3,\n pruneThreshold: 95,\n maxTaskDrop: 20,\n usePrincipal: false,\n evalSampleSize: 0,\n samplingStrategy: 'thompson',\n klLambda: 0.1,\n pbtBranches: 3,\n};\n\n/**\n * Load EvolveConfig from a workspace's config.yaml.\n * Falls back to DEFAULT_CONFIG for any missing fields.\n */\nexport async function loadEvolveConfigFromWorkspace(workspacePath: string): Promise<EvolveConfig> {\n try {\n const configStr = await fs.readFile(path.join(workspacePath, 'config.yaml'), 'utf-8');\n const parsed = yamlParse(configStr) as Record<string, unknown>;\n return {\n model: (parsed.model as string) ?? DEFAULT_CONFIG.model,\n proposerModel: (parsed.proposer_model as string) ?? DEFAULT_CONFIG.proposerModel,\n scorer: (parsed.scorer as EvolveConfig['scorer']) ?? DEFAULT_CONFIG.scorer,\n maxIterations: (parsed.max_iterations as number) ?? DEFAULT_CONFIG.maxIterations,\n parallelTasks: (parsed.parallel_tasks as number) ?? DEFAULT_CONFIG.parallelTasks,\n runsPerTask: (parsed.runs_per_task as number) ?? DEFAULT_CONFIG.runsPerTask,\n maxMutationsPerIteration: (parsed.max_mutations_per_iteration as number) ?? DEFAULT_CONFIG.maxMutationsPerIteration,\n pruneThreshold: (parsed.prune_threshold as number) ?? DEFAULT_CONFIG.pruneThreshold,\n maxTaskDrop: (parsed.max_task_drop as number) ?? DEFAULT_CONFIG.maxTaskDrop,\n usePrincipal: (parsed.use_principal as boolean) ?? DEFAULT_CONFIG.usePrincipal,\n evalSampleSize: (parsed.eval_sample_size as number) ?? DEFAULT_CONFIG.evalSampleSize,\n samplingStrategy: (parsed.sampling_strategy as EvolveConfig['samplingStrategy']) ?? DEFAULT_CONFIG.samplingStrategy,\n klLambda: (parsed.kl_lambda as number) ?? DEFAULT_CONFIG.klLambda,\n pbtBranches: (parsed.pbt_branches as number) ?? DEFAULT_CONFIG.pbtBranches,\n };\n } catch {\n return { ...DEFAULT_CONFIG };\n }\n}\n\nexport const evolveCommand = new Command('evolve')\n .description('Evolve your agent environment through automated optimization');\n\n// --- kairn evolve init ---\nevolveCommand\n .command('init')\n .description('Initialize an evolution workspace with auto-generated tasks')\n .option('--workflow <type>', 'Workflow type for template selection', 'feature-development')\n .action(async (options: { workflow: string }) => {\n try {\n const projectRoot = process.cwd();\n\n console.log(ui.section('Evolve Init'));\n\n // Check for .claude/ directory\n const claudeDir = path.join(projectRoot, '.claude');\n try {\n await fs.access(claudeDir);\n } catch {\n console.log(ui.error('No .claude/ directory found. Run kairn describe first.'));\n process.exit(1);\n }\n\n // Create workspace\n const workspace = await createEvolveWorkspace(projectRoot, DEFAULT_CONFIG);\n console.log(ui.success('Created .kairn-evolve/ workspace'));\n\n // Auto-generate tasks via LLM\n const spinner = ora('Generating project-specific eval tasks...').start();\n let tasks: Task[];\n try {\n tasks = await autoGenerateTasks(projectRoot, options.workflow);\n spinner.succeed(`Generated ${tasks.length} eval tasks`);\n } catch {\n spinner.fail('LLM task generation failed');\n // Fallback to template-based placeholder tasks\n const templateIds = selectTemplatesForWorkflow(options.workflow);\n tasks = templateIds.map((templateId, index) => ({\n id: `${templateId}-${index + 1}`,\n template: templateId,\n description: `${EVAL_TEMPLATES[templateId].description} (project-specific task — edit in tasks.yaml)`,\n setup: 'npm install',\n expected_outcome: 'Task completed successfully',\n scoring: 'pass-fail' as const,\n timeout: 300,\n }));\n console.log(ui.info(`Fell back to ${tasks.length} template placeholders`));\n }\n\n // Display generated tasks\n for (const task of tasks) {\n console.log(chalk.cyan(` ${task.id}`) + chalk.dim(` (${task.template}) — ${task.description.slice(0, 80)}`));\n }\n\n // Interactive \"add another eval?\" loop\n let addMore = true;\n while (addMore) {\n try {\n addMore = await confirm({ message: 'Add another eval task?', default: false });\n } catch {\n addMore = false; // Handle non-interactive (piped) mode\n }\n if (addMore) {\n const templateId = await select({\n message: 'Select eval template:',\n choices: Object.values(EVAL_TEMPLATES).map(t => ({\n name: `${t.name} — ${t.description}`,\n value: t.id,\n })),\n });\n\n const addSpinner = ora('Generating task...').start();\n try {\n const config = await loadConfig();\n if (config) {\n let claudeMd = '';\n try { claudeMd = await fs.readFile(path.join(claudeDir, 'CLAUDE.md'), 'utf-8'); } catch { /* optional */ }\n const profile = await buildProjectProfile(projectRoot);\n const newTasks = await generateTasksFromTemplates(claudeMd, profile, [templateId], config);\n tasks.push(...newTasks);\n addSpinner.succeed(`Added ${newTasks.length} task(s)`);\n } else {\n addSpinner.fail('No config found');\n }\n } catch {\n addSpinner.fail('Failed to generate task');\n }\n }\n }\n\n // Write tasks file\n await writeTasksFile(workspace, tasks);\n console.log(ui.success(`Wrote ${tasks.length} tasks to tasks.yaml`));\n\n console.log('');\n console.log(chalk.dim(' Next steps:'));\n console.log(chalk.dim(' 1. Review .kairn-evolve/tasks.yaml'));\n console.log(chalk.dim(' 2. Run: kairn evolve baseline'));\n console.log(chalk.dim(' 3. Run: kairn evolve run'));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve baseline ---\nevolveCommand\n .command('baseline')\n .description('Snapshot current .claude/ directory as baseline')\n .action(async () => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n console.log(ui.section('Evolve Baseline'));\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n // Snapshot baseline\n await snapshotBaseline(projectRoot, workspace);\n\n // Count files copied\n const baselineDir = path.join(workspace, 'baseline');\n const fileCount = await countFiles(baselineDir);\n console.log(ui.success(`Baseline snapshot created (${fileCount} files)`));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve run ---\nevolveCommand\n .command('run')\n .description('Run tasks against the current harness')\n .option('--task <id>', 'Run a specific task by ID')\n .option('--iterations <n>', 'Number of evolution iterations', '5')\n .option('--runs <n>', 'Run each task N times for variance measurement', '1')\n .option('--parallel <n>', 'Run up to N tasks concurrently', '1')\n .option('--max-mutations <n>', 'Max mutations per iteration', '3')\n .option('--prune-threshold <n>', 'Skip tasks scoring above this on middle iterations', '95')\n .option('--max-task-drop <n>', 'Roll back if any task drops more than N points', '20')\n .option('--principal', 'Run Principal Proposer as final iteration')\n .option('--eval-sample <n>', 'Sample N tasks per middle iteration (0 = all)', '0')\n .option('--sampling <strategy>', 'Task sampling strategy: thompson or uniform', 'thompson')\n .option('--kl-lambda <n>', 'KL regularization strength (0 = disabled)', '0.1')\n .option('-i, --interactive', 'Configure evolution settings interactively')\n .action(async (options: { task?: string; iterations?: string; runs?: string; parallel?: string; maxMutations?: string; pruneThreshold?: string; maxTaskDrop?: string; principal?: boolean; evalSample?: string; sampling?: string; klLambda?: string; interactive?: boolean }) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n console.log(ui.section('Evolve Run'));\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n const tasksPath = path.join(workspace, 'tasks.yaml');\n let tasksContent: string;\n try {\n tasksContent = await fs.readFile(tasksPath, 'utf-8');\n } catch {\n console.log(ui.error('No tasks.yaml found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n const parsed = yamlParse(tasksContent) as TasksFile;\n if (!parsed?.tasks || parsed.tasks.length === 0) {\n console.log(ui.error('No tasks found in tasks.yaml'));\n process.exit(1);\n }\n\n if (options.task) {\n const tasksToRun = parsed.tasks.filter(t => t.id === options.task);\n\n if (tasksToRun.length === 0) {\n console.log(ui.error(`Task \"${options.task}\" not found in tasks.yaml`));\n process.exit(1);\n }\n\n console.log(ui.info(`Running ${tasksToRun.length} task(s)...`));\n console.log('');\n\n const config = await loadConfig();\n const harnessPath = path.join(projectRoot, '.claude');\n const results: TaskResult[] = [];\n\n for (const task of tasksToRun) {\n const traceDir = path.join(workspace, 'traces', '0', task.id);\n const spinner = ora(`Running: ${task.id}`).start();\n\n const result = await runTask(task, harnessPath, traceDir, 0);\n\n // Score the result\n if (config) {\n const stdout = await fs.readFile(path.join(traceDir, 'stdout.log'), 'utf-8').catch(() => '');\n const stderr = await fs.readFile(path.join(traceDir, 'stderr.log'), 'utf-8').catch(() => '');\n const score = await scoreTask(task, traceDir, stdout, stderr, config);\n result.score = score;\n await writeScore(traceDir, score);\n }\n\n results.push(result);\n\n const status = result.score.pass ? chalk.green('PASS') : chalk.red('FAIL');\n const scoreStr = result.score.score !== undefined ? chalk.dim(` (${result.score.score}%)`) : '';\n spinner.stop();\n console.log(` ${status} ${task.id}${scoreStr}${result.score.details ? chalk.dim(` — ${result.score.details}`) : ''}`);\n }\n\n // Summary\n const passed = results.filter(r => r.score.pass).length;\n console.log('');\n console.log(ui.info(`Results: ${passed}/${results.length} passed`));\n console.log(ui.info('Traces written to .kairn-evolve/traces/0/'));\n } else {\n const kairnConfig = await loadConfig();\n if (!kairnConfig) {\n console.log(ui.error('No config found. Run kairn init first.'));\n process.exit(1);\n }\n\n const evolveConfig = await loadEvolveConfigFromWorkspace(workspace);\n\n // Show interactive menu by default unless flags were explicitly passed\n const hasExplicitFlags = options.iterations !== '5' || options.runs !== '1' ||\n options.parallel !== '1' || options.maxMutations !== '3' ||\n options.pruneThreshold !== '95' || options.maxTaskDrop !== '20' ||\n options.principal || options.evalSample !== '0' ||\n options.sampling !== 'thompson' || options.klLambda !== '0.1';\n\n if (!hasExplicitFlags) {\n // Interactive configuration menu\n console.log(chalk.dim(' Configure evolution settings:\\n'));\n\n const preset = await select({\n message: 'Evolution preset',\n choices: [\n { name: 'Quick (3 iterations, 1 run, no extras)', value: 'quick' },\n { name: 'Standard (5 iterations, 1 run, parallel)', value: 'standard' },\n { name: 'Rigorous (5 iterations, 3 runs, parallel, principal)', value: 'rigorous' },\n { name: 'Custom (configure each setting)', value: 'custom' },\n ],\n });\n\n if (preset === 'quick') {\n evolveConfig.maxIterations = 3;\n evolveConfig.runsPerTask = 1;\n evolveConfig.parallelTasks = 3;\n } else if (preset === 'standard') {\n evolveConfig.maxIterations = 5;\n evolveConfig.runsPerTask = 1;\n evolveConfig.parallelTasks = 5;\n } else if (preset === 'rigorous') {\n evolveConfig.maxIterations = 5;\n evolveConfig.runsPerTask = 3;\n evolveConfig.parallelTasks = 5;\n evolveConfig.usePrincipal = true;\n } else {\n evolveConfig.maxIterations = parseInt(\n await input({ message: 'Iterations', default: '5' }), 10) || 5;\n evolveConfig.runsPerTask = parseInt(\n await input({ message: 'Runs per task (variance)', default: '1' }), 10) || 1;\n evolveConfig.parallelTasks = parseInt(\n await input({ message: 'Parallel tasks', default: '3' }), 10) || 3;\n evolveConfig.maxMutationsPerIteration = parseInt(\n await input({ message: 'Max mutations per iteration', default: '3' }), 10) || 3;\n evolveConfig.pruneThreshold = parseInt(\n await input({ message: 'Prune threshold (%)', default: '95' }), 10) || 95;\n evolveConfig.maxTaskDrop = parseInt(\n await input({ message: 'Max task drop (rollback guard)', default: '20' }), 10) || 20;\n evolveConfig.usePrincipal = await confirm({\n message: 'Run Principal Proposer at end?', default: false,\n });\n evolveConfig.evalSampleSize = parseInt(\n await input({ message: 'Eval sample size (0 = all)', default: '0' }), 10) || 0;\n }\n\n console.log('');\n console.log(chalk.dim(` Iterations: ${evolveConfig.maxIterations}, Runs: ${evolveConfig.runsPerTask}, Parallel: ${evolveConfig.parallelTasks}`));\n console.log(chalk.dim(` Mutations: ${evolveConfig.maxMutationsPerIteration}, Prune: ${evolveConfig.pruneThreshold}%, Guard: ${evolveConfig.maxTaskDrop}pt`));\n if (evolveConfig.usePrincipal) console.log(chalk.dim(' Principal Proposer: enabled'));\n if (evolveConfig.evalSampleSize > 0) console.log(chalk.dim(` Eval sampling: ${evolveConfig.evalSampleSize} tasks/iter (${evolveConfig.samplingStrategy})`));\n if (evolveConfig.klLambda > 0) console.log(chalk.dim(` KL regularization: λ=${evolveConfig.klLambda}`));\n console.log('');\n } else {\n // Flag-based configuration\n const iterations = parseInt(options.iterations ?? '5', 10);\n if (isNaN(iterations) || iterations < 1) {\n console.log(ui.error('--iterations must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.maxIterations = iterations;\n\n const runs = parseInt(options.runs ?? '1', 10);\n if (isNaN(runs) || runs < 1) {\n console.log(ui.error('--runs must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.runsPerTask = runs;\n\n const parallel = parseInt(options.parallel ?? '1', 10);\n if (isNaN(parallel) || parallel < 1) {\n console.log(ui.error('--parallel must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.parallelTasks = parallel;\n\n const maxMutations = parseInt(options.maxMutations ?? '3', 10);\n if (isNaN(maxMutations) || maxMutations < 1) {\n console.log(ui.error('--max-mutations must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.maxMutationsPerIteration = maxMutations;\n\n const pruneThreshold = parseInt(options.pruneThreshold ?? '95', 10);\n if (isNaN(pruneThreshold) || pruneThreshold < 0 || pruneThreshold > 100) {\n console.log(ui.error('--prune-threshold must be 0-100'));\n process.exit(1);\n }\n evolveConfig.pruneThreshold = pruneThreshold;\n\n const maxTaskDrop = parseInt(options.maxTaskDrop ?? '20', 10);\n if (isNaN(maxTaskDrop) || maxTaskDrop < 1) {\n console.log(ui.error('--max-task-drop must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.maxTaskDrop = maxTaskDrop;\n\n if (options.principal) {\n evolveConfig.usePrincipal = true;\n }\n\n const evalSample = parseInt(options.evalSample ?? '0', 10);\n if (isNaN(evalSample) || evalSample < 0) {\n console.log(ui.error('--eval-sample must be a non-negative integer'));\n process.exit(1);\n }\n evolveConfig.evalSampleSize = evalSample;\n\n const sampling = options.sampling ?? 'thompson';\n if (sampling !== 'thompson' && sampling !== 'uniform') {\n console.log(ui.error('--sampling must be \"thompson\" or \"uniform\"'));\n process.exit(1);\n }\n evolveConfig.samplingStrategy = sampling;\n\n const klLambda = parseFloat(options.klLambda ?? '0.1');\n if (isNaN(klLambda) || klLambda < 0) {\n console.log(ui.error('--kl-lambda must be a non-negative number'));\n process.exit(1);\n }\n evolveConfig.klLambda = klLambda;\n }\n\n // Verify baseline exists\n try {\n await fs.access(path.join(workspace, 'iterations', '0', 'harness'));\n } catch {\n console.log(ui.error('No baseline harness found. Run kairn evolve baseline first.'));\n process.exit(1);\n }\n\n const result = await evolve(workspace, parsed.tasks, kairnConfig, evolveConfig, (event: LoopProgressEvent) => {\n switch (event.type) {\n case 'iteration-start':\n console.log(ui.section(`Iteration ${event.iteration}`));\n break;\n case 'iteration-scored': {\n const scoreColor = event.score !== undefined && event.score >= 100\n ? chalk.green\n : event.score !== undefined && event.score >= 60\n ? chalk.yellow\n : chalk.red;\n console.log(` Score: ${scoreColor((event.score?.toFixed(1) ?? '0') + '%')}`);\n break;\n }\n case 'rollback':\n console.log(chalk.yellow(` Warning: ${event.message ?? 'Regression detected'}`));\n break;\n case 'proposing':\n console.log(chalk.dim(' Proposer analyzing traces...'));\n break;\n case 'mutations-applied':\n console.log(chalk.dim(` Applied ${event.mutationCount ?? 0} mutation(s)`));\n break;\n case 'perfect-score':\n console.log(chalk.green(' Perfect score. Stopping.'));\n break;\n case 'proposer-error':\n console.log(chalk.yellow(` Warning: ${event.message ?? 'Proposer failed'}`));\n break;\n case 'task-start':\n console.log(chalk.dim(` Running: ${event.taskId ?? 'unknown'}...`));\n break;\n case 'task-run':\n console.log(chalk.dim(` ${event.message ?? ''}`));\n break;\n case 'task-skipped':\n console.log(chalk.dim(` SKIP ${event.taskId ?? 'unknown'} (above prune threshold last iteration)`));\n break;\n case 'task-regression':\n console.log(chalk.yellow(` DROP ${event.taskId ?? 'unknown'} ${event.message ?? ''}`));\n break;\n case 'task-scored': {\n const taskScore = event.score ?? 0;\n const taskStatus = taskScore >= 100 ? chalk.green('PASS') : taskScore >= 60 ? chalk.yellow('PARTIAL') : chalk.red('FAIL');\n console.log(` ${taskStatus} ${event.taskId ?? 'unknown'} ${chalk.dim(`(${taskScore.toFixed(0)}%)`)}`);\n break;\n }\n case 'complete':\n break; // Summary printed below\n }\n });\n\n // Print summary\n console.log(ui.section('Evolution Summary'));\n console.log(` Iterations: ${result.iterations.length}`);\n console.log(` Baseline: ${result.baselineScore.toFixed(1)}%`);\n console.log(` Best: ${chalk.green(result.bestScore.toFixed(1) + '%')} (iteration ${result.bestIteration})`);\n const improvement = result.bestScore - result.baselineScore;\n if (improvement > 0) {\n console.log(` Improvement: ${chalk.green('+' + improvement.toFixed(1) + ' points')}`);\n } else {\n console.log(` Improvement: ${improvement.toFixed(1)} points`);\n }\n console.log('');\n\n // Iteration table\n const showVariance = evolveConfig.runsPerTask > 1;\n console.log(showVariance\n ? ' Iter Score Mutations Status'\n : ' Iter Score Mutations Status');\n for (const iter of result.iterations) {\n // Compute average stddev across tasks for this iteration\n let scoreDisplay: string;\n if (showVariance) {\n const taskScores = Object.values(iter.taskResults);\n const stddevs = taskScores\n .map(s => s.variance?.stddev)\n .filter((v): v is number => v !== undefined);\n const avgStddev = stddevs.length > 0\n ? stddevs.reduce((a, b) => a + b, 0) / stddevs.length\n : 0;\n scoreDisplay = `${iter.score.toFixed(1).padStart(6)}% ±${avgStddev.toFixed(1)}`;\n } else {\n scoreDisplay = iter.score.toFixed(1).padStart(6) + '%';\n }\n const mutations = iter.proposal?.mutations.length ?? 0;\n const mutStr = mutations > 0 ? mutations.toString() : '-';\n let status = 'evaluated';\n if (iter.iteration === 0) status = 'baseline';\n else if (!iter.proposal && !iter.diffPatch) status = 'rollback';\n else if (iter.score >= 100) status = 'perfect';\n else if (iter.iteration === result.bestIteration) status = 'best';\n console.log(` ${iter.iteration.toString().padStart(4)} ${scoreDisplay} ${mutStr.padStart(9)} ${status}`);\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve pbt ---\nevolveCommand\n .command('pbt')\n .description('Run Population-Based Training with parallel evolution branches')\n .option('--branches <n>', 'Number of parallel branches', '3')\n .option('--iterations <n>', 'Iterations per branch', '5')\n .option('--parallel <n>', 'Tasks per branch concurrently', '2')\n .option('--sampling <strategy>', 'Task sampling strategy: thompson or uniform', 'thompson')\n .option('--kl-lambda <n>', 'KL regularization strength (0 = disabled)', '0.1')\n .option('--eval-sample <n>', 'Sample N tasks per middle iteration (0 = all)', '5')\n .action(async (options: { branches?: string; iterations?: string; parallel?: string; sampling?: string; klLambda?: string; evalSample?: string }) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n console.log(ui.section('Evolve PBT'));\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n // Verify baseline exists\n try {\n await fs.access(path.join(workspace, 'iterations', '0', 'harness'));\n } catch {\n console.log(ui.error('No baseline harness found. Run kairn evolve baseline first.'));\n process.exit(1);\n }\n\n const kairnConfig = await loadConfig();\n if (!kairnConfig) {\n console.log(ui.error('No config found. Run kairn init first.'));\n process.exit(1);\n }\n\n const evolveConfig = await loadEvolveConfigFromWorkspace(workspace);\n\n // Parse options\n const numBranches = parseInt(options.branches ?? '3', 10);\n evolveConfig.maxIterations = parseInt(options.iterations ?? '5', 10);\n evolveConfig.parallelTasks = parseInt(options.parallel ?? '2', 10);\n evolveConfig.evalSampleSize = parseInt(options.evalSample ?? '5', 10);\n evolveConfig.klLambda = parseFloat(options.klLambda ?? '0.1');\n const sampling = options.sampling ?? 'thompson';\n if (sampling === 'thompson' || sampling === 'uniform') {\n evolveConfig.samplingStrategy = sampling;\n }\n\n // Load tasks\n const tasksPath = path.join(workspace, 'tasks.yaml');\n const tasksContent = await fs.readFile(tasksPath, 'utf-8');\n const parsed = yamlParse(tasksContent) as TasksFile;\n if (!parsed?.tasks || parsed.tasks.length === 0) {\n console.log(ui.error('No tasks found in tasks.yaml'));\n process.exit(1);\n }\n\n console.log(chalk.dim(` Branches: ${numBranches}, Iterations: ${evolveConfig.maxIterations}, Parallel: ${evolveConfig.parallelTasks}`));\n console.log(chalk.dim(` Sampling: ${evolveConfig.samplingStrategy}, KL Lambda: ${evolveConfig.klLambda}`));\n console.log('');\n\n const { runPopulation } = await import('../evolve/population.js');\n\n const result = await runPopulation(\n workspace,\n parsed.tasks,\n kairnConfig,\n evolveConfig,\n numBranches,\n (event) => {\n const branchPrefix = event.branchId !== undefined ? chalk.dim(`[branch ${event.branchId}] `) : '';\n switch (event.type) {\n case 'iteration-start':\n console.log(`${branchPrefix}${ui.section(`Iteration ${event.iteration}`)}`);\n break;\n case 'iteration-scored': {\n const scoreColor = event.score !== undefined && event.score >= 100\n ? chalk.green\n : event.score !== undefined && event.score >= 60\n ? chalk.yellow\n : chalk.red;\n console.log(`${branchPrefix} Score: ${scoreColor((event.score?.toFixed(1) ?? '0') + '%')}`);\n break;\n }\n case 'complete':\n break;\n default:\n if (event.message) {\n console.log(`${branchPrefix} ${chalk.dim(event.message)}`);\n }\n break;\n }\n },\n );\n\n // Print PBT summary\n console.log(ui.section('PBT Results'));\n for (const branch of result.branches) {\n const marker = branch.branchId === result.bestBranch ? chalk.green(' <- BEST') : '';\n console.log(` Branch ${branch.branchId}: ${branch.result.bestScore.toFixed(1)}% (${branch.result.iterations.length} iterations)${marker}`);\n }\n if (result.synthesizedResult) {\n const synthMarker = result.synthesizedResult.bestScore > result.bestScore ? chalk.green(' <- BEST') : '';\n console.log(` ${'─'.repeat(40)}`);\n console.log(` Meta-Principal: ${result.synthesizedResult.bestScore.toFixed(1)}%${synthMarker}`);\n }\n console.log('');\n console.log(ui.success(`Best: Branch ${result.bestBranch} with ${result.bestScore.toFixed(1)}%`));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve apply ---\nevolveCommand\n .command('apply')\n .description('Apply the best evolved harness to your project')\n .option('--iter <n>', 'Apply a specific iteration instead of the best')\n .option('--pbt', 'Apply best PBT result (branch winner or synthesis)')\n .option('--force', 'Apply even if git working tree is dirty')\n .option('--no-commit', 'Skip automatic git commit after applying')\n .action(async (options: { iter?: string; pbt?: boolean; force?: boolean; commit?: boolean }) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n console.log(ui.section('Evolve Apply'));\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n // Parse --iter option\n let targetIteration: number | undefined;\n if (options.iter) {\n targetIteration = parseInt(options.iter, 10);\n if (isNaN(targetIteration)) {\n console.log(ui.error('--iter must be a number'));\n process.exit(1);\n }\n }\n\n const result = await applyEvolution(workspace, projectRoot, targetIteration, options.pbt);\n\n // Show diff preview\n if (result.diffPreview) {\n console.log(ui.section('Changes'));\n for (const line of result.diffPreview.split('\\n')) {\n if (line.startsWith('---') || line.startsWith('+++')) {\n console.log(chalk.bold(line));\n } else if (line.startsWith('+')) {\n console.log(chalk.green(line));\n } else if (line.startsWith('-')) {\n console.log(chalk.red(line));\n } else {\n console.log(line);\n }\n }\n }\n\n console.log('');\n console.log(ui.success(\n `Applied iteration ${result.iteration} harness (${result.filesChanged.length} files)`,\n ));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve report ---\nevolveCommand\n .command('report')\n .description('Generate a summary report of the evolution run')\n .option('--json', 'Output machine-readable JSON instead of Markdown')\n .action(async (options: { json?: boolean }) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n if (options.json) {\n const report = await generateJsonReport(workspace);\n console.log(JSON.stringify(report, null, 2));\n } else {\n const markdown = await generateMarkdownReport(workspace);\n console.log(markdown);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve diff ---\nevolveCommand\n .command('diff <iter1> <iter2>')\n .description('Show harness changes between two iterations')\n .action(async (iter1Str: string, iter2Str: string) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n const iter1 = parseInt(iter1Str, 10);\n const iter2 = parseInt(iter2Str, 10);\n\n if (isNaN(iter1) || isNaN(iter2)) {\n console.log(ui.error('Both arguments must be integers (iteration numbers)'));\n process.exit(1);\n }\n\n // Verify both iteration harness directories exist\n const harness1 = path.join(workspace, 'iterations', iter1.toString(), 'harness');\n const harness2 = path.join(workspace, 'iterations', iter2.toString(), 'harness');\n\n try {\n await fs.access(harness1);\n } catch {\n console.log(ui.error(`Iteration ${iter1} harness not found at ${harness1}`));\n process.exit(1);\n }\n try {\n await fs.access(harness2);\n } catch {\n console.log(ui.error(`Iteration ${iter2} harness not found at ${harness2}`));\n process.exit(1);\n }\n\n console.log(ui.section(`Diff: Iteration ${iter1} → ${iter2}`));\n\n // Generate and display colored diff\n const diffPatch = await generateDiff(harness1, harness2);\n\n if (!diffPatch) {\n console.log(chalk.dim(' No harness changes between these iterations.'));\n } else {\n for (const line of diffPatch.split('\\n')) {\n if (line.startsWith('---') || line.startsWith('+++')) {\n console.log(chalk.bold(line));\n } else if (line.startsWith('+')) {\n console.log(chalk.green(line));\n } else if (line.startsWith('-')) {\n console.log(chalk.red(line));\n } else {\n console.log(line);\n }\n }\n }\n\n // Per-task score comparison\n const [log1, log2] = await Promise.all([\n loadIterationLog(workspace, iter1),\n loadIterationLog(workspace, iter2),\n ]);\n\n if (log1 && log2) {\n console.log('');\n console.log(ui.section('Score Comparison'));\n console.log('');\n console.log(' Task Iter ' + iter1 + ' Iter ' + iter2 + ' Delta');\n\n const allTaskIds = new Set([\n ...Object.keys(log1.taskResults),\n ...Object.keys(log2.taskResults),\n ]);\n\n for (const taskId of [...allTaskIds].sort()) {\n const s1 = log1.taskResults[taskId];\n const s2 = log2.taskResults[taskId];\n const score1 = s1 ? (s1.score ?? (s1.pass ? 100 : 0)) : 0;\n const score2 = s2 ? (s2.score ?? (s2.pass ? 100 : 0)) : 0;\n const delta = score2 - score1;\n const deltaStr = delta > 0\n ? chalk.green(`+${delta.toFixed(0)}`)\n : delta < 0\n ? chalk.red(delta.toFixed(0).toString())\n : chalk.dim('0');\n const name = taskId.padEnd(30);\n console.log(` ${name} ${score1.toFixed(0).padStart(5)}% ${score2.toFixed(0).padStart(5)}% ${deltaStr}`);\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n/**\n * Count files recursively in a directory.\n */\nasync function countFiles(dir: string): Promise<number> {\n let count = 0;\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory()) {\n count += await countFiles(path.join(dir, entry.name));\n } else {\n count++;\n }\n }\n } catch {\n // Directory doesn't exist\n }\n return count;\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { stringify as yamlStringify } from 'yaml';\nimport { loadConfig } from '../config.js';\nimport { selectTemplatesForWorkflow, generateTasksFromTemplates } from './templates.js';\nimport type { EvolveConfig, Task, ProjectProfileSummary } from './types.js';\n\n/**\n * Creates the .kairn-evolve/ directory structure and writes config.yaml.\n * Returns the path to the workspace.\n */\nexport async function createEvolveWorkspace(\n projectRoot: string,\n config: EvolveConfig,\n): Promise<string> {\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n // Create directories\n await fs.mkdir(path.join(workspace, 'baseline'), { recursive: true });\n await fs.mkdir(path.join(workspace, 'traces'), { recursive: true });\n await fs.mkdir(path.join(workspace, 'iterations'), { recursive: true });\n\n // Write config.yaml using proper YAML serialization\n const configObj = {\n model: config.model,\n proposer_model: config.proposerModel,\n scorer: config.scorer,\n max_iterations: config.maxIterations,\n parallel_tasks: config.parallelTasks,\n };\n await fs.writeFile(\n path.join(workspace, 'config.yaml'),\n yamlStringify(configObj),\n 'utf-8',\n );\n\n return workspace;\n}\n\n/**\n * Writes tasks.yaml to the workspace using proper YAML serialization.\n *\n * Each task is serialized with all required fields. The rubric key\n * is only included when the task has rubric criteria defined.\n */\nexport async function writeTasksFile(\n workspacePath: string,\n tasks: Task[],\n): Promise<void> {\n const doc = {\n tasks: tasks.map((t) => ({\n id: t.id,\n template: t.template,\n description: t.description,\n setup: t.setup,\n expected_outcome: t.expected_outcome,\n scoring: t.scoring,\n ...(t.rubric ? { rubric: t.rubric } : {}),\n timeout: t.timeout,\n })),\n };\n\n const header =\n '# .kairn-evolve/tasks.yaml\\n# Auto-generated by kairn evolve init — edit freely\\n';\n await fs.writeFile(\n path.join(workspacePath, 'tasks.yaml'),\n header + yamlStringify(doc),\n 'utf-8',\n );\n}\n\n/**\n * Build a lightweight project profile by scanning key files in the project root.\n *\n * Reads package.json for Node.js projects, checks for pyproject.toml or\n * requirements.txt for Python projects, and scans for common configuration files.\n */\nexport async function buildProjectProfile(\n projectRoot: string,\n): Promise<ProjectProfileSummary> {\n const profile: ProjectProfileSummary = {\n language: null,\n framework: null,\n scripts: {},\n keyFiles: [],\n };\n\n // Try to read package.json for Node.js projects\n try {\n const pkgStr = await fs.readFile(\n path.join(projectRoot, 'package.json'),\n 'utf-8',\n );\n const pkg = JSON.parse(pkgStr) as Record<string, unknown>;\n profile.language = 'typescript';\n\n if (pkg.scripts && typeof pkg.scripts === 'object') {\n profile.scripts = pkg.scripts as Record<string, string>;\n }\n\n // Detect framework from dependencies\n const deps: Record<string, string> = {\n ...((pkg.dependencies as Record<string, string>) ?? {}),\n ...((pkg.devDependencies as Record<string, string>) ?? {}),\n };\n\n if (deps.next) {\n profile.framework = 'Next.js';\n } else if (deps.express) {\n profile.framework = 'Express';\n } else if (deps.react) {\n profile.framework = 'React';\n } else if (deps.vue) {\n profile.framework = 'Vue';\n } else if (deps.commander) {\n profile.framework = 'CLI (Commander.js)';\n }\n } catch {\n // Not a Node.js project\n }\n\n // Try pyproject.toml / requirements.txt for Python\n if (!profile.language) {\n try {\n await fs.access(path.join(projectRoot, 'pyproject.toml'));\n profile.language = 'python';\n } catch {\n try {\n await fs.access(path.join(projectRoot, 'requirements.txt'));\n profile.language = 'python';\n } catch {\n // Not Python either\n }\n }\n }\n\n // Scan for key files\n try {\n const entries = await fs.readdir(projectRoot);\n const keyPatterns = [\n 'README.md',\n 'package.json',\n 'tsconfig.json',\n 'pyproject.toml',\n 'Cargo.toml',\n 'go.mod',\n 'Makefile',\n 'Dockerfile',\n ];\n profile.keyFiles = entries.filter((e) => keyPatterns.includes(e));\n } catch {\n // Ignore\n }\n\n return profile;\n}\n\n/**\n * Auto-generate project-specific eval tasks using the LLM.\n *\n * Reads the project's CLAUDE.md (if present), builds a project profile\n * by scanning key files, selects eval templates for the given workflow\n * type, then calls the LLM to generate concrete tasks.\n *\n * @param projectRoot - Path to the project root directory\n * @param workflowType - The type of workflow (e.g., \"feature-development\", \"maintenance\")\n * @returns Array of generated Task objects\n */\nexport async function autoGenerateTasks(\n projectRoot: string,\n workflowType: string,\n): Promise<Task[]> {\n const config = await loadConfig();\n if (!config) {\n throw new Error('No config found. Run `kairn init` first.');\n }\n\n // Read CLAUDE.md\n let claudeMd = '';\n try {\n claudeMd = await fs.readFile(\n path.join(projectRoot, '.claude', 'CLAUDE.md'),\n 'utf-8',\n );\n } catch {\n // CLAUDE.md is optional but recommended\n }\n\n // Build project profile by scanning key files\n const profile = await buildProjectProfile(projectRoot);\n\n // Select templates for workflow type\n const templates = selectTemplatesForWorkflow(workflowType);\n\n // Generate tasks via LLM\n return generateTasksFromTemplates(claudeMd, profile, templates, config);\n}\n","import { callLLM } from '../llm.js';\nimport type { KairnConfig } from '../types.js';\nimport type { EvalTemplate, ProjectProfileSummary, Task } from './types.js';\n\ninterface TemplateMetadata {\n id: EvalTemplate;\n name: string;\n description: string;\n bestFor: string[];\n}\n\nexport const EVAL_TEMPLATES: Record<EvalTemplate, TemplateMetadata> = {\n 'add-feature': {\n id: 'add-feature',\n name: 'Add Feature',\n description: 'Can the agent add a new capability?',\n bestFor: ['feature-development', 'api-building', 'full-stack'],\n },\n 'fix-bug': {\n id: 'fix-bug',\n name: 'Fix Bug',\n description: 'Can the agent diagnose and fix a problem?',\n bestFor: ['maintenance', 'debugging', 'qa'],\n },\n 'refactor': {\n id: 'refactor',\n name: 'Refactor',\n description: 'Can the agent restructure code?',\n bestFor: ['maintenance', 'architecture', 'backend'],\n },\n 'test-writing': {\n id: 'test-writing',\n name: 'Test Writing',\n description: 'Can the agent write tests?',\n bestFor: ['tdd', 'qa', 'backend'],\n },\n 'config-change': {\n id: 'config-change',\n name: 'Config Change',\n description: 'Can the agent update configuration?',\n bestFor: ['devops', 'infrastructure', 'backend'],\n },\n 'documentation': {\n id: 'documentation',\n name: 'Documentation',\n description: 'Can the agent write and update docs?',\n bestFor: ['content', 'api-building', 'full-stack'],\n },\n 'convention-adherence': {\n id: 'convention-adherence',\n name: 'Convention Adherence',\n description: 'Does the agent follow all project conventions defined in CLAUDE.md?',\n bestFor: ['feature-development', 'full-stack', 'backend', 'maintenance'],\n },\n 'workflow-compliance': {\n id: 'workflow-compliance',\n name: 'Workflow Compliance',\n description: 'Does the agent use the project workflow commands and skills?',\n bestFor: ['feature-development', 'full-stack', 'tdd', 'qa'],\n },\n 'rule-compliance': {\n id: 'rule-compliance',\n name: 'Rule Compliance',\n description: 'Does the agent follow all project rules without violations?',\n bestFor: ['feature-development', 'backend', 'maintenance', 'architecture'],\n },\n 'intent-routing': {\n id: 'intent-routing',\n name: 'Intent Routing',\n description: 'Test that natural language prompts route to the correct workflow command via intent hooks',\n bestFor: ['feature-development', 'full-stack', 'api-building'],\n },\n};\n\n/**\n * Select eval templates appropriate for a given workflow type.\n *\n * Returns a curated subset of eval templates that best match the\n * project's workflow. Falls back to a general-purpose set if the\n * workflow type is not recognized.\n */\nexport function selectTemplatesForWorkflow(workflowType: string): EvalTemplate[] {\n const mapping: Record<string, EvalTemplate[]> = {\n 'feature-development': ['add-feature', 'test-writing', 'convention-adherence', 'workflow-compliance', 'intent-routing'],\n 'api-building': ['add-feature', 'fix-bug', 'test-writing', 'convention-adherence'],\n 'full-stack': ['add-feature', 'fix-bug', 'test-writing', 'convention-adherence'],\n 'maintenance': ['fix-bug', 'refactor', 'test-writing', 'rule-compliance'],\n 'debugging': ['fix-bug', 'test-writing', 'rule-compliance'],\n 'qa': ['fix-bug', 'test-writing', 'add-feature', 'workflow-compliance'],\n 'architecture': ['refactor', 'test-writing', 'config-change', 'convention-adherence'],\n 'backend': ['fix-bug', 'refactor', 'config-change', 'rule-compliance'],\n 'devops': ['config-change', 'fix-bug', 'rule-compliance'],\n 'infrastructure': ['config-change', 'refactor', 'convention-adherence'],\n 'tdd': ['test-writing', 'add-feature', 'fix-bug', 'workflow-compliance'],\n 'content': ['documentation', 'add-feature', 'convention-adherence'],\n 'research': ['documentation', 'add-feature', 'convention-adherence'],\n };\n return mapping[workflowType] || ['add-feature', 'fix-bug', 'test-writing', 'convention-adherence'];\n}\n\n/**\n * System prompt instructing the LLM to generate project-specific eval tasks\n * from eval templates and project context.\n */\nexport const TASK_GENERATION_PROMPT = `You are an eval task generator for Claude Code agent environments. Given a project's CLAUDE.md, project structure, and selected eval templates, generate concrete, project-specific tasks.\n\nEach task must be realistic and testable against the actual project. Avoid generic placeholders.\n\nIMPORTANT: For harness-aware templates (convention-adherence, workflow-compliance, rule-compliance), generate tasks where success DEPENDS on the agent reading and following the .claude/ harness content:\n- convention-adherence: Task must require following specific conventions from CLAUDE.md (naming, file structure, patterns). Judge by whether output matches the conventions.\n- workflow-compliance: Task must require using project slash commands or workflow steps defined in .claude/commands/. Judge by whether the agent followed the defined workflow.\n- rule-compliance: Task must create a scenario where .claude/rules/ content is relevant. Judge by whether the agent respected all rules.\n\nThese harness-aware tasks are critical — they test whether the .claude/ environment actually improves agent behavior.\n\nReturn a JSON object with a \"tasks\" array. Each task has:\n- id: kebab-case identifier (e.g., \"add-health-endpoint\")\n- template: which eval template this instantiates\n- description: concrete task description the agent will receive\n- setup: shell commands to prepare the workspace (e.g., \"npm install\")\n- expected_outcome: multi-line string describing what success looks like\n- scoring: \"pass-fail\", \"llm-judge\", or \"rubric\"\n- timeout: seconds (300 for features/bugs, 600 for refactors, 180 for config/docs/tests)\n\nReturn ONLY valid JSON, no markdown fences.`;\n\n/**\n * Parse a raw LLM response string into a JSON object.\n *\n * Strips markdown code fences if present, then extracts the first\n * top-level JSON object (`{...}`) or array (`[...]`) from the text.\n */\nfunction parseJsonResponse(raw: string): unknown {\n let cleaned = raw.trim();\n\n // Strip markdown code fences\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n\n // Extract first JSON object or array\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/) ?? cleaned.match(/\\[[\\s\\S]*\\]/);\n if (!jsonMatch) {\n throw new Error(\n \"LLM response did not contain valid JSON. Try again or use a different model.\",\n );\n }\n\n try {\n return JSON.parse(jsonMatch[0]);\n } catch (err) {\n throw new Error(\n `Failed to parse LLM response as JSON: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nconst REQUIRED_TASK_FIELDS: ReadonlyArray<keyof Task> = [\n \"id\",\n \"template\",\n \"description\",\n \"setup\",\n \"expected_outcome\",\n \"scoring\",\n \"timeout\",\n];\n\n/**\n * Validate that a parsed object has all required Task fields.\n */\nfunction validateTask(obj: unknown, index: number): Task {\n if (typeof obj !== \"object\" || obj === null) {\n throw new Error(`Task at index ${index} is not an object`);\n }\n const record = obj as Record<string, unknown>;\n\n for (const field of REQUIRED_TASK_FIELDS) {\n if (!(field in record) || record[field] === undefined || record[field] === null) {\n throw new Error(`Task at index ${index} is missing required field: ${field}`);\n }\n }\n\n return record as unknown as Task;\n}\n\n/**\n * Build the user message for LLM task generation.\n */\nfunction buildTaskGenerationMessage(\n claudeMd: string,\n projectProfile: ProjectProfileSummary,\n templates: EvalTemplate[],\n): string {\n const profileLines = [\n `Language: ${projectProfile.language ?? \"unknown\"}`,\n `Framework: ${projectProfile.framework ?? \"none\"}`,\n `Scripts: ${Object.entries(projectProfile.scripts).map(([k, v]) => `${k}=${v}`).join(\", \") || \"none\"}`,\n `Key files: ${projectProfile.keyFiles.join(\", \") || \"none\"}`,\n ];\n\n const templateDescriptions = templates\n .map((t) => {\n const meta = EVAL_TEMPLATES[t];\n return `- ${t}: ${meta.description}`;\n })\n .join(\"\\n\");\n\n return [\n \"## CLAUDE.md\",\n \"\",\n claudeMd,\n \"\",\n \"## Project Profile\",\n \"\",\n ...profileLines,\n \"\",\n \"## Selected Eval Templates\",\n \"\",\n templateDescriptions,\n \"\",\n \"Generate concrete, project-specific tasks for each template above.\",\n ].join(\"\\n\");\n}\n\n/**\n * Use the LLM to generate project-specific eval tasks from eval templates.\n *\n * Sends the project's CLAUDE.md, profile summary, and selected templates\n * to the LLM, then parses and validates the returned task definitions.\n *\n * @param claudeMd - Contents of the project's CLAUDE.md\n * @param projectProfile - Lightweight project info (language, framework, etc.)\n * @param templates - Which eval templates to instantiate\n * @param config - Kairn configuration with provider, API key, and model\n * @returns Validated array of Task objects\n */\nexport async function generateTasksFromTemplates(\n claudeMd: string,\n projectProfile: ProjectProfileSummary,\n templates: EvalTemplate[],\n config: KairnConfig,\n): Promise<Task[]> {\n const userMessage = buildTaskGenerationMessage(claudeMd, projectProfile, templates);\n\n const rawResponse = await callLLM(config, userMessage, {\n systemPrompt: TASK_GENERATION_PROMPT,\n maxTokens: 4096,\n });\n\n const parsed = parseJsonResponse(rawResponse);\n\n // Extract tasks array from response\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new Error(\"LLM response is not a JSON object\");\n }\n\n const tasksObj = parsed as Record<string, unknown>;\n if (!Array.isArray(tasksObj.tasks)) {\n throw new Error(\"LLM response does not contain a 'tasks' array\");\n }\n\n // Validate each task\n const tasks: Task[] = [];\n for (let i = 0; i < tasksObj.tasks.length; i++) {\n tasks.push(validateTask(tasksObj.tasks[i], i));\n }\n\n return tasks;\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { loadIterationLog } from './trace.js';\nimport { diagnoseCounterfactuals } from './diagnosis.js';\nimport type {\n IterationLog,\n Task,\n TasksFile,\n Score,\n EvolutionReport,\n} from './types.js';\nimport { parse as yamlParse } from 'yaml';\n\n/**\n * Compute the numeric score from a Score object.\n */\nfunction numericScore(s: Score): number {\n return s.score ?? (s.pass ? 100 : 0);\n}\n\n/**\n * Load all iteration logs from a workspace by scanning iteration directories.\n */\nasync function loadAllIterations(workspacePath: string): Promise<IterationLog[]> {\n const iterDir = path.join(workspacePath, 'iterations');\n let entries: string[];\n try {\n entries = await fs.readdir(iterDir);\n } catch {\n return [];\n }\n\n const iterations: IterationLog[] = [];\n const iterNums = entries\n .map(e => parseInt(e, 10))\n .filter(n => !isNaN(n))\n .sort((a, b) => a - b);\n\n for (const n of iterNums) {\n const log = await loadIterationLog(workspacePath, n);\n if (log) iterations.push(log);\n }\n\n return iterations;\n}\n\n/**\n * Load tasks from tasks.yaml in the workspace.\n */\nasync function loadTasks(workspacePath: string): Promise<Task[]> {\n try {\n const content = await fs.readFile(path.join(workspacePath, 'tasks.yaml'), 'utf-8');\n const parsed = yamlParse(content) as TasksFile;\n return parsed?.tasks ?? [];\n } catch {\n return [];\n }\n}\n\n/**\n * Build a leaderboard: per-task scores across all iterations.\n */\nfunction buildLeaderboard(\n iterations: IterationLog[],\n tasks: Task[],\n): EvolutionReport['leaderboard'] {\n const taskIds = tasks.map(t => t.id);\n return taskIds.map(taskId => {\n const scores: Record<number, number> = {};\n const variance: Record<number, { mean: number; stddev: number; runs: number }> = {};\n let bestScore = -1;\n let bestIteration = 0;\n\n for (const iter of iterations) {\n const s = iter.taskResults[taskId];\n if (s) {\n const score = numericScore(s);\n scores[iter.iteration] = score;\n if (s.variance) {\n variance[iter.iteration] = {\n mean: s.variance.mean,\n stddev: s.variance.stddev,\n runs: s.variance.runs,\n };\n }\n if (score > bestScore) {\n bestScore = score;\n bestIteration = iter.iteration;\n }\n }\n }\n\n const hasVariance = Object.keys(variance).length > 0;\n return { taskId, scores, bestIteration, bestScore, ...(hasVariance ? { variance } : {}) };\n });\n}\n\n/**\n * Determine iteration status label.\n */\nfunction iterationStatus(iter: IterationLog, bestIteration: number): string {\n if (iter.iteration === 0) return 'baseline';\n if (!iter.proposal && !iter.diffPatch) return 'rollback';\n if (iter.score >= 100) return 'perfect';\n if (iter.iteration === bestIteration) return 'best';\n return 'evaluated';\n}\n\n/**\n * Generate a human-readable Markdown report of an evolution run.\n */\nexport async function generateMarkdownReport(workspacePath: string): Promise<string> {\n const iterations = await loadAllIterations(workspacePath);\n const tasks = await loadTasks(workspacePath);\n\n if (iterations.length === 0) {\n return '# Evolution Report\\n\\nNo iterations found. Run `kairn evolve run` first.\\n';\n }\n\n const baselineScore = iterations[0].score;\n const bestIter = iterations.reduce((best, curr) =>\n curr.score > best.score ? curr : best, iterations[0]);\n const improvement = bestIter.score - baselineScore;\n\n const counterfactuals = diagnoseCounterfactuals(iterations, tasks);\n const leaderboard = buildLeaderboard(iterations, tasks);\n\n const lines: string[] = [];\n\n // Title\n lines.push('# Evolution Report');\n lines.push('');\n\n // Overview\n lines.push('## Overview');\n lines.push('');\n lines.push(`| Metric | Value |`);\n lines.push(`|--------|-------|`);\n lines.push(`| Total iterations | ${iterations.length} |`);\n lines.push(`| Baseline score | ${baselineScore.toFixed(1)}% |`);\n lines.push(`| Best score | ${bestIter.score.toFixed(1)}% |`);\n lines.push(`| Best iteration | ${bestIter.iteration} |`);\n lines.push(`| Improvement | ${improvement >= 0 ? '+' : ''}${improvement.toFixed(1)} points |`);\n lines.push('');\n\n // Iteration summary table\n lines.push('## Iterations');\n lines.push('');\n // Check if any iteration has variance data\n const hasVariance = iterations.some(iter =>\n Object.values(iter.taskResults).some(s => s.variance),\n );\n\n if (hasVariance) {\n lines.push('| Iter | Score | Mutations | Status |');\n lines.push('|------|-------|-----------|--------|');\n } else {\n lines.push('| Iter | Score | Mutations | Status |');\n lines.push('|------|-------|-----------|--------|');\n }\n for (const iter of iterations) {\n const mutations = iter.proposal?.mutations.length ?? 0;\n const mutStr = mutations > 0 ? mutations.toString() : '-';\n const status = iterationStatus(iter, bestIter.iteration);\n let scoreStr = `${iter.score.toFixed(1)}%`;\n if (hasVariance) {\n const stddevs = Object.values(iter.taskResults)\n .map(s => s.variance?.stddev)\n .filter((v): v is number => v !== undefined);\n if (stddevs.length > 0) {\n const avgStddev = stddevs.reduce((a, b) => a + b, 0) / stddevs.length;\n scoreStr = `${iter.score.toFixed(1)}% ±${avgStddev.toFixed(1)}`;\n }\n }\n lines.push(`| ${iter.iteration} | ${scoreStr} | ${mutStr} | ${status} |`);\n }\n lines.push('');\n\n // Leaderboard\n if (leaderboard.length > 0) {\n lines.push('## Leaderboard');\n lines.push('');\n\n // Header: Task | Iter 0 | Iter 1 | ... | Best\n const iterNums = iterations.map(i => i.iteration);\n const headerCols = ['Task', ...iterNums.map(n => `Iter ${n}`), 'Best'];\n lines.push(`| ${headerCols.join(' | ')} |`);\n lines.push(`| ${headerCols.map(() => '---').join(' | ')} |`);\n\n for (const entry of leaderboard) {\n const scoreCols = iterNums.map(n => {\n const s = entry.scores[n];\n if (s === undefined) return '-';\n const v = entry.variance?.[n];\n if (v && v.runs > 1) return `${s.toFixed(0)}% ±${v.stddev.toFixed(1)}`;\n return `${s.toFixed(0)}%`;\n });\n lines.push(`| ${entry.taskId} | ${scoreCols.join(' | ')} | ${entry.bestScore.toFixed(0)}% (iter ${entry.bestIteration}) |`);\n }\n lines.push('');\n }\n\n // Counterfactual diagnosis\n if (counterfactuals.entries.length > 0) {\n lines.push('## Counterfactual Diagnosis');\n lines.push('');\n\n for (const entry of counterfactuals.entries) {\n const sign = entry.netScoreDelta >= 0 ? '+' : '';\n lines.push(`### Iteration ${entry.iteration} (net ${sign}${entry.netScoreDelta.toFixed(1)} points)`);\n lines.push('');\n lines.push(`**Mutations:** ${entry.mutationSummary}`);\n lines.push('');\n\n if (entry.helpedTasks.length > 0) {\n lines.push('**Helped:**');\n for (const t of entry.helpedTasks) {\n lines.push(`- ${t.taskId}: +${t.delta.toFixed(1)}`);\n }\n lines.push('');\n }\n\n if (entry.hurtTasks.length > 0) {\n lines.push('**Hurt:**');\n for (const t of entry.hurtTasks) {\n lines.push(`- ${t.taskId}: ${t.delta.toFixed(1)}`);\n }\n lines.push('');\n }\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Generate a machine-readable JSON report of an evolution run.\n */\nexport async function generateJsonReport(workspacePath: string): Promise<EvolutionReport> {\n const iterations = await loadAllIterations(workspacePath);\n const tasks = await loadTasks(workspacePath);\n\n const baselineScore = iterations.length > 0 ? iterations[0].score : 0;\n const bestIter = iterations.length > 0\n ? iterations.reduce((best, curr) => curr.score > best.score ? curr : best, iterations[0])\n : { score: 0, iteration: 0 };\n const improvement = bestIter.score - baselineScore;\n\n const counterfactuals = diagnoseCounterfactuals(iterations, tasks);\n const leaderboard = buildLeaderboard(iterations, tasks);\n\n return {\n overview: {\n title: 'Evolution Report',\n totalIterations: iterations.length,\n baselineScore,\n bestScore: bestIter.score,\n bestIteration: bestIter.iteration,\n improvement,\n },\n iterations: iterations.map(iter => {\n const stddevs = Object.values(iter.taskResults)\n .map(s => s.variance?.stddev)\n .filter((v): v is number => v !== undefined);\n const avgStddev = stddevs.length > 0\n ? stddevs.reduce((a, b) => a + b, 0) / stddevs.length\n : undefined;\n return {\n iteration: iter.iteration,\n score: iter.score,\n ...(avgStddev !== undefined ? { stddev: avgStddev } : {}),\n mutationCount: iter.proposal?.mutations.length ?? 0,\n status: iterationStatus(iter, bestIter.iteration),\n };\n }),\n leaderboard,\n counterfactuals,\n };\n}\n","import type {\n Trace,\n TraceDiff,\n IterationLog,\n Task,\n CounterfactualReport,\n CounterfactualEntry,\n Score,\n} from './types.js';\n\n/**\n * Compute the numeric score from a Score object.\n * Uses the explicit score field if present, otherwise 100 for pass / 0 for fail.\n */\nfunction numericScore(s: Score): number {\n return s.score ?? (s.pass ? 100 : 0);\n}\n\n/**\n * Produce a concise summary of stdout differences between two traces.\n * Shows line counts and the first few differing lines rather than a full diff.\n */\nfunction summarizeStdoutDiff(stdoutA: string, stdoutB: string): string {\n if (stdoutA === stdoutB) return '(identical)';\n\n const linesA = stdoutA.split('\\n');\n const linesB = stdoutB.split('\\n');\n\n const parts: string[] = [];\n parts.push(`Line count: ${linesA.length} → ${linesB.length}`);\n\n // Find first divergence point\n const minLen = Math.min(linesA.length, linesB.length);\n let firstDiff = -1;\n for (let i = 0; i < minLen; i++) {\n if (linesA[i] !== linesB[i]) {\n firstDiff = i;\n break;\n }\n }\n if (firstDiff === -1 && linesA.length !== linesB.length) {\n firstDiff = minLen;\n }\n if (firstDiff >= 0) {\n parts.push(`First difference at line ${firstDiff + 1}`);\n }\n\n return parts.join('; ');\n}\n\n/**\n * Diff two traces for the same task across different iterations.\n *\n * Compares scores, pass/fail status, stdout content, and file changes\n * to produce a structured TraceDiff showing what changed.\n */\nexport function diffTaskTraces(traceA: Trace, traceB: Trace): TraceDiff {\n const scoreA = numericScore(traceA.score);\n const scoreB = numericScore(traceB.score);\n\n const filesA = new Set(Object.keys(traceA.filesChanged));\n const filesB = new Set(Object.keys(traceB.filesChanged));\n\n const added: string[] = [];\n const removed: string[] = [];\n const changed: string[] = [];\n\n for (const f of filesB) {\n if (!filesA.has(f)) {\n added.push(f);\n } else if (traceA.filesChanged[f] !== traceB.filesChanged[f]) {\n changed.push(f);\n }\n }\n for (const f of filesA) {\n if (!filesB.has(f)) {\n removed.push(f);\n }\n }\n\n return {\n taskId: traceA.taskId,\n iterA: traceA.iteration,\n iterB: traceB.iteration,\n scoreDelta: scoreB - scoreA,\n passChanged: traceA.score.pass !== traceB.score.pass,\n stdoutDiff: summarizeStdoutDiff(traceA.stdout, traceB.stdout),\n filesChangedDiff: { added, removed, changed },\n };\n}\n\n/**\n * Analyze an evolution run to identify which mutations helped or hurt specific tasks.\n *\n * For each iteration that has a proposal (mutations), compares per-task scores\n * between consecutive iterations to attribute score changes to the mutations applied.\n */\nexport function diagnoseCounterfactuals(\n iterations: IterationLog[],\n _tasks: Task[],\n): CounterfactualReport {\n const entries: CounterfactualEntry[] = [];\n\n for (let i = 1; i < iterations.length; i++) {\n const prev = iterations[i - 1];\n const curr = iterations[i];\n\n // Skip iterations without proposals (rollbacks, baseline)\n if (!curr.proposal && !prev.proposal) continue;\n\n // The proposal that caused this iteration's harness was from the previous iteration\n const proposal = prev.proposal;\n if (!proposal || proposal.mutations.length === 0) continue;\n\n const mutationSummary = proposal.mutations\n .map(m => `${m.action} in ${m.file}: ${m.rationale}`)\n .join('; ');\n\n const helpedTasks: Array<{ taskId: string; delta: number }> = [];\n const hurtTasks: Array<{ taskId: string; delta: number }> = [];\n\n // Compare per-task scores\n const allTaskIds = new Set([\n ...Object.keys(prev.taskResults),\n ...Object.keys(curr.taskResults),\n ]);\n\n let netDelta = 0;\n for (const taskId of allTaskIds) {\n const prevScore = prev.taskResults[taskId]\n ? numericScore(prev.taskResults[taskId])\n : 0;\n const currScore = curr.taskResults[taskId]\n ? numericScore(curr.taskResults[taskId])\n : 0;\n const delta = currScore - prevScore;\n\n if (delta > 0) {\n helpedTasks.push({ taskId, delta });\n } else if (delta < 0) {\n hurtTasks.push({ taskId, delta });\n }\n netDelta += delta;\n }\n\n entries.push({\n iteration: i,\n mutationSummary,\n helpedTasks,\n hurtTasks,\n netScoreDelta: netDelta,\n });\n }\n\n return { entries };\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport { generateDiff } from './mutator.js';\nimport { loadIterationLog } from './trace.js';\n\nexport interface ApplyResult {\n iteration: number;\n filesChanged: string[];\n diffPreview: string;\n}\n\n/**\n * Find all iteration directories in the workspace and return their numbers.\n */\nasync function listIterations(workspacePath: string): Promise<number[]> {\n const iterationsDir = path.join(workspacePath, 'iterations');\n let entries: string[];\n try {\n entries = await fs.readdir(iterationsDir);\n } catch {\n return [];\n }\n\n const nums: number[] = [];\n for (const entry of entries) {\n const n = parseInt(entry, 10);\n if (!isNaN(n)) {\n try {\n await fs.access(path.join(iterationsDir, entry, 'harness'));\n nums.push(n);\n } catch {\n // skip entries without a harness directory\n }\n }\n }\n return nums.sort((a, b) => a - b);\n}\n\n/**\n * Find the best iteration by score across all iteration logs.\n */\nasync function findBestIteration(\n workspacePath: string,\n iterations: number[],\n): Promise<number> {\n let bestIter = iterations[0];\n let bestScore = -Infinity;\n\n for (const iter of iterations) {\n const log = await loadIterationLog(workspacePath, iter);\n const score = log?.score ?? 0;\n if (score > bestScore) {\n bestScore = score;\n bestIter = iter;\n }\n }\n\n return bestIter;\n}\n\n/**\n * List all files in a directory recursively, returning relative paths.\n */\nasync function listFilesRecursive(dir: string): Promise<string[]> {\n const results: string[] = [];\n\n async function walk(current: string): Promise<void> {\n let entries: import('fs').Dirent[];\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const fullPath = path.join(current, entry.name);\n if (entry.isDirectory()) {\n await walk(fullPath);\n } else {\n results.push(path.relative(dir, fullPath));\n }\n }\n }\n\n await walk(dir);\n return results;\n}\n\n/**\n * Apply an evolved harness to the project's .claude/ directory.\n *\n * 1. Determines target iteration (best by score, or user-specified)\n * 2. Generates a unified diff between current .claude/ and target harness\n * 3. Replaces .claude/ with the target harness\n *\n * @param workspacePath - Path to .kairn-evolve/ directory\n * @param projectRoot - Path to the project root (parent of .claude/)\n * @param targetIteration - Specific iteration to apply (undefined = best)\n * @returns ApplyResult with iteration number, changed files, and diff preview\n */\n/**\n * Find the best PBT result: check branch winners and synthesis output.\n * Returns the path to the best harness and a label describing its source.\n */\nasync function findBestPBTHarness(\n workspacePath: string,\n): Promise<{ harnessPath: string; label: string } | null> {\n const branchesDir = path.join(workspacePath, 'branches');\n let branchEntries: string[];\n try {\n branchEntries = await fs.readdir(branchesDir);\n } catch {\n return null; // No PBT branches exist\n }\n\n let bestScore = -Infinity;\n let bestPath = '';\n let bestLabel = '';\n\n // Check each branch's best iteration\n for (const branchId of branchEntries) {\n const branchPath = path.join(branchesDir, branchId);\n const branchIterations = await listIterations(branchPath);\n if (branchIterations.length === 0) continue;\n\n const bestIter = await findBestIteration(branchPath, branchIterations);\n const log = await loadIterationLog(branchPath, bestIter);\n const score = log?.score ?? 0;\n\n if (score > bestScore) {\n bestScore = score;\n bestPath = path.join(branchPath, 'iterations', bestIter.toString(), 'harness');\n bestLabel = `branch ${branchId}, iteration ${bestIter} (${score.toFixed(1)}%)`;\n }\n }\n\n // Check synthesis output\n const synthesisHarness = path.join(workspacePath, 'synthesis', 'harness');\n try {\n await fs.access(synthesisHarness);\n // Synthesis doesn't have iteration logs — check for a score file\n const synthesisLog = await loadIterationLog(workspacePath, 999);\n const synthScore = synthesisLog?.score ?? 0;\n if (synthScore > bestScore) {\n bestScore = synthScore;\n bestPath = synthesisHarness;\n bestLabel = `Meta-Principal synthesis (${synthScore.toFixed(1)}%)`;\n }\n } catch {\n // No synthesis output\n }\n\n if (!bestPath) return null;\n return { harnessPath: bestPath, label: bestLabel };\n}\n\nexport async function applyEvolution(\n workspacePath: string,\n projectRoot: string,\n targetIteration?: number,\n pbt?: boolean,\n): Promise<ApplyResult> {\n // PBT mode: find best across branches and synthesis\n if (pbt) {\n const pbtResult = await findBestPBTHarness(workspacePath);\n if (!pbtResult) {\n throw new Error('No PBT results found. Run `kairn evolve pbt` first.');\n }\n\n const claudeDir = path.join(projectRoot, '.claude');\n const diffPreview = await generateDiff(claudeDir, pbtResult.harnessPath);\n\n const currentFiles = await listFilesRecursive(claudeDir);\n const targetFiles = await listFilesRecursive(pbtResult.harnessPath);\n const allPaths = new Set([...currentFiles, ...targetFiles]);\n const filesChanged: string[] = [];\n for (const filePath of allPaths) {\n const currentContent = await fs.readFile(path.join(claudeDir, filePath), 'utf-8').catch(() => null);\n const targetContent = await fs.readFile(path.join(pbtResult.harnessPath, filePath), 'utf-8').catch(() => null);\n if (currentContent !== targetContent) {\n filesChanged.push(filePath);\n }\n }\n\n await fs.rm(claudeDir, { recursive: true, force: true });\n await copyDir(pbtResult.harnessPath, claudeDir);\n\n // Copy .mcp.json if present\n const harnessMcpJson = path.join(pbtResult.harnessPath, '.mcp.json');\n const projectMcpJson = path.join(projectRoot, '.mcp.json');\n try {\n await fs.access(harnessMcpJson);\n await fs.copyFile(harnessMcpJson, projectMcpJson);\n if (!filesChanged.includes('.mcp.json')) filesChanged.push('.mcp.json');\n } catch {\n // No .mcp.json in harness\n }\n\n return {\n iteration: -1, // signals PBT source\n filesChanged,\n diffPreview,\n };\n }\n\n // Standard mode: find best among top-level iterations\n const iterations = await listIterations(workspacePath);\n\n if (iterations.length === 0) {\n throw new Error('No iterations found in workspace. Run `kairn evolve run` first.');\n }\n\n let iter: number;\n if (targetIteration !== undefined) {\n if (!iterations.includes(targetIteration)) {\n throw new Error(\n `Iteration ${targetIteration} not found. Available: ${iterations.join(', ')}`,\n );\n }\n iter = targetIteration;\n } else {\n iter = await findBestIteration(workspacePath, iterations);\n }\n\n const harnessPath = path.join(\n workspacePath,\n 'iterations',\n iter.toString(),\n 'harness',\n );\n const claudeDir = path.join(projectRoot, '.claude');\n\n const diffPreview = await generateDiff(claudeDir, harnessPath);\n\n const currentFiles = await listFilesRecursive(claudeDir);\n const targetFiles = await listFilesRecursive(harnessPath);\n const allPaths = new Set([...currentFiles, ...targetFiles]);\n const filesChanged: string[] = [];\n for (const filePath of allPaths) {\n const currentContent = await fs.readFile(path.join(claudeDir, filePath), 'utf-8').catch(() => null);\n const targetContent = await fs.readFile(path.join(harnessPath, filePath), 'utf-8').catch(() => null);\n if (currentContent !== targetContent) {\n filesChanged.push(filePath);\n }\n }\n\n await fs.rm(claudeDir, { recursive: true, force: true });\n await copyDir(harnessPath, claudeDir);\n\n // Copy .mcp.json from harness if it exists (harness scope includes MCP config)\n const harnessMcpJson = path.join(harnessPath, '.mcp.json');\n const projectMcpJson = path.join(projectRoot, '.mcp.json');\n try {\n await fs.access(harnessMcpJson);\n const currentMcp = await fs.readFile(projectMcpJson, 'utf-8').catch(() => null);\n const targetMcp = await fs.readFile(harnessMcpJson, 'utf-8').catch(() => null);\n if (currentMcp !== targetMcp) {\n filesChanged.push('.mcp.json');\n }\n await fs.copyFile(harnessMcpJson, projectMcpJson);\n } catch {\n // No .mcp.json in harness — leave project's .mcp.json untouched\n }\n\n return {\n iteration: iter,\n filesChanged,\n diffPreview,\n };\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAkBnB,SAAS,yBAAyB,KAAsC;AAC7E,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG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AAClC,QAAQ,WAAW,qBAAqB;AACxC,QAAQ,WAAW,aAAa;AAChC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,gBAAgB;AACnC,QAAQ,WAAW,WAAW;AAC9B,QAAQ,WAAW,aAAa;AAGhC,IAAI,QAAQ,KAAK,SAAS,YAAY,KAAK,QAAQ,IAAI,UAAU;AAC/D,EAAAC,QAAM,QAAQ;AAChB;AAEA,QAAQ,MAAM;","names":["Anthropic","OpenAI","client","fs","path","fs","path","exec","promisify","execAsync","passed","exec","promisify","fs","os","path","execAsync","tmpDir","fs","path","fs","path","loadProposerMemory","formatMemoryForProposer","fs","path","readFileSafe","path","fs","path","generateDiff","legacyDiff","fs","path","fs","path","fs","path","nextIterDir","buildRunSummary","saveRunSummary","path","fs","path","baselinePath","Command","chalk","chalk","fs","path","KAIRN_WORDMARK","path","chalk","maroon","darkMaroon","warmStone","lightStone","dimStone","dimStone","maroon","chalk","path","fs","client","chalk","Command","input","confirm","select","chalk","fs","path","fs","path","fileURLToPath","__filename","fileURLToPath","__dirname","path","fs","path","fs","fs","path","fs","path","fs","path","os","writeFile","password","chalk","fs","path","chalk","password","path","fs","Command","chalk","input","select","confirm","Command","chalk","fs","path","Command","fs","chalk","path","Command","chalk","fs","path","Command","fs","chalk","path","Command","chalk","fs","path","fileURLToPath","__filename","fileURLToPath","__dirname","path","fs","Command","chalk","Command","confirm","chalk","fs","path","fs","path","pkg","chalk","path","fs","Command","confirm","Command","chalk","perms","Command","chalk","Command","chalk","input","select","listCommand","Command","chalk","input","select","Command","chalk","fs","path","Command","fs","chalk","path","Command","password","chalk","fs","path","Command","chalk","password","Command","chalk","ora","fs","path","yamlParse","confirm","input","select","fs","path","path","fs","pkg","fs","path","numericScore","path","fs","fs","path","claudeDir","diffPreview","generateDiff","currentFiles","targetFiles","allPaths","filesChanged","harnessMcpJson","projectMcpJson","fs","path","yamlParse","Command","ora","chalk","confirm","select","input","runPopulation","generateDiff","require","Command","chalk"]}
|
|
1
|
+
{"version":3,"sources":["../src/auth/keychain.ts","../src/providers.ts","../src/llm.ts","../src/evolve/baseline.ts","../src/evolve/trace.ts","../src/evolve/exec.ts","../src/evolve/scorers.ts","../src/evolve/runner.ts","../src/evolve/memory.ts","../src/evolve/proposer.ts","../src/ir/types.ts","../src/ir/parser.ts","../src/ir/translate.ts","../src/ir/mutations.ts","../src/ir/renderer.ts","../src/ir/diff.ts","../src/evolve/mutator.ts","../src/evolve/sampling.ts","../src/evolve/regularization.ts","../src/evolve/targeting.ts","../src/evolve/loop.ts","../src/evolve/synthesis.ts","../src/evolve/population.ts","../src/cli.ts","../src/commands/init.ts","../src/config.ts","../src/ui.ts","../src/logo.ts","../src/commands/describe.ts","../src/compiler/compile.ts","../src/compiler/prompt.ts","../src/registry/loader.ts","../src/intent/patterns.ts","../src/intent/prompt-template.ts","../src/intent/router-template.ts","../src/intent/learner-template.ts","../src/adapter/claude-code.ts","../src/autonomy.ts","../src/adapter/hermes-agent.ts","../src/secrets.ts","../src/commands/list.ts","../src/commands/activate.ts","../src/commands/update-registry.ts","../src/commands/optimize.ts","../src/scanner/scan.ts","../src/commands/doctor.ts","../src/commands/registry.ts","../src/commands/templates.ts","../src/commands/keys.ts","../src/commands/evolve.ts","../src/evolve/init.ts","../src/evolve/templates.ts","../src/evolve/report.ts","../src/evolve/diagnosis.ts","../src/evolve/apply.ts"],"sourcesContent":["import { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nconst KEYCHAIN_SERVICE = 'Claude Code-credentials';\nconst TOKEN_EXPIRY_BUFFER_MS = 60_000; // Treat tokens as expired 60s early\n\nexport interface OAuthCredentials {\n accessToken: string;\n refreshToken: string;\n expiresAt: number;\n subscriptionType: string;\n}\n\n/**\n * Parse raw keychain JSON into OAuthCredentials.\n * Returns null if the JSON is invalid or missing required fields.\n */\nexport function parseKeychainCredentials(raw: string): OAuthCredentials | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n\n if (typeof parsed !== 'object' || parsed === null) return null;\n\n const obj = parsed as Record<string, unknown>;\n const oauth = obj['claudeAiOauth'];\n if (typeof oauth !== 'object' || oauth === null) return null;\n\n const oauthObj = oauth as Record<string, unknown>;\n const accessToken = oauthObj['accessToken'];\n const refreshToken = oauthObj['refreshToken'];\n const expiresAt = oauthObj['expiresAt'];\n const subscriptionType = oauthObj['subscriptionType'];\n\n if (typeof accessToken !== 'string' || !accessToken) return null;\n if (typeof refreshToken !== 'string') return null;\n if (typeof expiresAt !== 'number') return null;\n\n return {\n accessToken,\n refreshToken,\n expiresAt,\n subscriptionType: typeof subscriptionType === 'string' ? subscriptionType : 'unknown',\n };\n}\n\n/**\n * Check if an OAuth token is expired (or within the expiry buffer).\n */\nexport function isTokenExpired(credentials: OAuthCredentials): boolean {\n return Date.now() + TOKEN_EXPIRY_BUFFER_MS >= credentials.expiresAt;\n}\n\n/**\n * Read Claude Code OAuth credentials from macOS Keychain.\n * Returns null if not on macOS, keychain entry doesn't exist, or parsing fails.\n */\nexport async function readClaudeCodeCredentials(\n account?: string,\n): Promise<OAuthCredentials | null> {\n if (process.platform !== 'darwin') return null;\n\n try {\n const acct = account ?? '';\n const cmd = acct\n ? `security find-generic-password -s \"${KEYCHAIN_SERVICE}\" -a \"${acct}\" -w`\n : `security find-generic-password -s \"${KEYCHAIN_SERVICE}\" -w`;\n\n const { stdout } = await execAsync(cmd, { timeout: 5000 });\n return parseKeychainCredentials(stdout.trim());\n } catch {\n return null;\n }\n}\n\n/**\n * Get a valid access token, reading from keychain.\n * Returns the token string or null if unavailable/expired.\n *\n * Note: Token refresh is not implemented — when the token expires,\n * Claude Code itself will refresh it on next launch. The user can\n * re-run `kairn init` if the token is stale.\n */\nexport async function getAccessToken(\n account?: string,\n): Promise<string | null> {\n const creds = await readClaudeCodeCredentials(account);\n if (!creds) return null;\n if (isTokenExpired(creds)) return null;\n return creds.accessToken;\n}\n","import type { LLMProvider } from \"./types.js\";\n\nexport interface ProviderConfig {\n name: string;\n baseURL?: string;\n verifyModel: string;\n cheapModel: string;\n}\n\nexport const PROVIDER_CONFIGS: Record<Exclude<LLMProvider, \"other\">, ProviderConfig> = {\n anthropic: {\n name: \"Anthropic\",\n verifyModel: \"claude-haiku-4-5-20251001\",\n cheapModel: \"claude-haiku-4-5-20251001\",\n },\n openai: {\n name: \"OpenAI\",\n verifyModel: \"gpt-4.1-nano\",\n cheapModel: \"gpt-4.1-nano\",\n },\n google: {\n name: \"Google Gemini\",\n baseURL: \"https://generativelanguage.googleapis.com/v1beta/openai/\",\n verifyModel: \"gemini-2.5-flash\",\n cheapModel: \"gemini-2.5-flash\",\n },\n xai: {\n name: \"xAI (Grok)\",\n baseURL: \"https://api.x.ai/v1\",\n verifyModel: \"grok-4-1-fast-non-reasoning\",\n cheapModel: \"grok-4-1-fast-non-reasoning\",\n },\n deepseek: {\n name: \"DeepSeek\",\n baseURL: \"https://api.deepseek.com\",\n verifyModel: \"deepseek-chat\",\n cheapModel: \"deepseek-chat\",\n },\n mistral: {\n name: \"Mistral\",\n baseURL: \"https://api.mistral.ai/v1\",\n verifyModel: \"mistral-small-latest\",\n cheapModel: \"mistral-small-latest\",\n },\n groq: {\n name: \"Groq (open-source models)\",\n baseURL: \"https://api.groq.com/openai/v1\",\n verifyModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n cheapModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n },\n};\n\nexport const PROVIDER_MODELS: Record<Exclude<LLMProvider, \"other\">, { name: string; value: string }[]> = {\n anthropic: [\n { name: \"Claude Sonnet 4.6 (recommended)\", value: \"claude-sonnet-4-6\" },\n { name: \"Claude Opus 4.6 (highest quality)\", value: \"claude-opus-4-6\" },\n { name: \"Claude Haiku 4.5 (fastest, cheapest)\", value: \"claude-haiku-4-5-20251001\" },\n ],\n openai: [\n { name: \"GPT-4.1 (recommended — smartest non-reasoning)\", value: \"gpt-4.1\" },\n { name: \"GPT-4.1 mini (faster, cheaper)\", value: \"gpt-4.1-mini\" },\n { name: \"o4-mini (reasoning, cost-efficient)\", value: \"o4-mini\" },\n { name: \"GPT-5 mini (frontier)\", value: \"gpt-5-mini\" },\n ],\n google: [\n { name: \"Gemini 2.5 Flash (recommended — best value)\", value: \"gemini-2.5-flash\" },\n { name: \"Gemini 3 Flash (newest frontier)\", value: \"gemini-3-flash\" },\n { name: \"Gemini 2.5 Pro (highest quality)\", value: \"gemini-2.5-pro\" },\n { name: \"Gemini 3.1 Pro Preview (most advanced)\", value: \"gemini-3.1-pro-preview\" },\n ],\n xai: [\n { name: \"Grok 4.1 Fast (recommended — $0.20/M, very fast)\", value: \"grok-4-1-fast-non-reasoning\" },\n { name: \"Grok 4.20 (frontier quality, 2M context)\", value: \"grok-4.20-0309-non-reasoning\" },\n ],\n deepseek: [\n { name: \"DeepSeek V3.2 Chat (recommended — cheapest good model)\", value: \"deepseek-chat\" },\n { name: \"DeepSeek V3.2 Reasoner (with chain-of-thought)\", value: \"deepseek-reasoner\" },\n ],\n mistral: [\n { name: \"Mistral Large 3 (recommended — open-weight flagship)\", value: \"mistral-large-latest\" },\n { name: \"Codestral (code-optimized, 256K context)\", value: \"codestral-latest\" },\n { name: \"Mistral Small 4 (cheapest)\", value: \"mistral-small-latest\" },\n ],\n groq: [\n { name: \"Llama 4 Maverick (recommended — free, fast)\", value: \"meta-llama/llama-4-maverick-17b-128e-instruct\" },\n { name: \"Llama 4 Scout (free, fast)\", value: \"meta-llama/llama-4-scout-17b-16e-instruct\" },\n { name: \"DeepSeek R1 70B (free reasoning)\", value: \"deepseek-r1-distill-llama-70b\" },\n { name: \"Qwen 3 32B (free, multilingual)\", value: \"qwen/qwen3-32b\" },\n ],\n};\n\nexport const PROVIDER_CHOICES: { name: string; value: LLMProvider }[] = [\n { name: \"Anthropic (Claude) — recommended\", value: \"anthropic\" },\n { name: \"OpenAI (GPT)\", value: \"openai\" },\n { name: \"Google (Gemini)\", value: \"google\" },\n { name: \"xAI (Grok)\", value: \"xai\" },\n { name: \"DeepSeek — cheapest\", value: \"deepseek\" },\n { name: \"Mistral — open-weight\", value: \"mistral\" },\n { name: \"Groq — free tier, open-source models\", value: \"groq\" },\n { name: \"Other (OpenAI-compatible endpoint)\", value: \"other\" },\n];\n\nexport function getProviderName(provider: LLMProvider): string {\n if (provider === \"other\") return \"Custom endpoint\";\n return PROVIDER_CONFIGS[provider].name;\n}\n\nexport function getBaseURL(provider: LLMProvider, customBaseURL?: string): string | undefined {\n if (provider === \"other\") return customBaseURL;\n return PROVIDER_CONFIGS[provider]?.baseURL;\n}\n\nexport function getCheapModel(provider: LLMProvider, fallbackModel: string): string {\n if (provider === \"other\") return fallbackModel;\n return PROVIDER_CONFIGS[provider].cheapModel;\n}\n\nexport function getVerifyModel(provider: LLMProvider, fallbackModel: string): string {\n if (provider === \"other\") return fallbackModel;\n return PROVIDER_CONFIGS[provider].verifyModel;\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport OpenAI from \"openai\";\nimport { getProviderName, getBaseURL } from \"./providers.js\";\nimport { getAccessToken } from \"./auth/keychain.js\";\nimport type { KairnConfig } from \"./types.js\";\n\n/**\n * Classify an API error into a user-friendly, actionable message.\n *\n * Inspects the error's `status`, `code`, and message text to produce\n * guidance specific to the provider (e.g. \"Run `kairn init` to reconfigure\").\n */\nexport function classifyError(err: unknown, provider: string): string {\n const msg = err instanceof Error ? err.message : String(err);\n const status = (err as { status?: number })?.status;\n const code = (err as { code?: string })?.code;\n\n // Network errors\n if (code === \"ECONNREFUSED\" || code === \"ENOTFOUND\" || code === \"ETIMEDOUT\") {\n return `Network error: could not reach ${provider} API. Check your internet connection.`;\n }\n\n // Auth errors\n if (status === 401 || (msg.includes(\"invalid\") && msg.includes(\"key\"))) {\n return `Invalid API key for ${provider}. Run \\`kairn init\\` to reconfigure.`;\n }\n if (status === 403) {\n return `Access denied by ${provider}. Your API key may lack permissions for this model.`;\n }\n\n // Rate limiting\n if (status === 429 || msg.includes(\"rate limit\") || msg.includes(\"quota\")) {\n return `Rate limited by ${provider}. Wait a moment and try again, or switch to a cheaper model with \\`kairn init\\`.`;\n }\n\n // Model errors\n if (status === 404 || msg.includes(\"not found\") || msg.includes(\"does not exist\")) {\n return `Model not found on ${provider}. Run \\`kairn init\\` to select a valid model.`;\n }\n\n // Overloaded\n if (status === 529 || status === 503 || msg.includes(\"overloaded\")) {\n return `${provider} is temporarily overloaded. Try again in a few seconds.`;\n }\n\n // Token/context limit\n if (msg.includes(\"token\") && (msg.includes(\"limit\") || msg.includes(\"exceed\"))) {\n return `Request too large for the selected model. Try a shorter workflow description.`;\n }\n\n // Billing\n if (msg.includes(\"billing\") || msg.includes(\"payment\") || msg.includes(\"insufficient\")) {\n return `Billing issue with your ${provider} account. Check your account dashboard.`;\n }\n\n // Fallback\n return `${provider} API error: ${msg}`;\n}\n\n/**\n * Call an LLM provider with a user message and system prompt.\n *\n * Routes to the Anthropic SDK for `anthropic` provider, and to the\n * OpenAI-compatible SDK for all other providers.\n *\n * @param config - Kairn configuration with provider, API key, and model\n * @param userMessage - The user message to send\n * @param options - Must include `systemPrompt`; `maxTokens` defaults to 8192\n * @returns The text response from the LLM\n */\nexport async function callLLM(\n config: KairnConfig,\n userMessage: string,\n options: { maxTokens?: number; systemPrompt: string; jsonMode?: boolean; cacheControl?: boolean }\n): Promise<string> {\n const maxTokens = options.maxTokens ?? 8192;\n const { systemPrompt } = options;\n const jsonMode = options.jsonMode ?? false;\n const cacheControl = options.cacheControl ?? false;\n const providerName = getProviderName(config.provider);\n\n // Resolve API key — use OAuth token from keychain if configured\n let apiKey = config.api_key;\n if (config.auth_type === 'claude-code-oauth') {\n const oauthToken = await getAccessToken();\n if (!oauthToken) {\n throw new Error(\n 'Claude Code OAuth token unavailable or expired. Run `kairn init` to reconfigure, or launch Claude Code to refresh the token.'\n );\n }\n apiKey = oauthToken;\n }\n\n if (config.provider === \"anthropic\") {\n const client = new Anthropic({ apiKey });\n\n const messages: Array<{ role: \"user\" | \"assistant\"; content: string }> = [\n { role: \"user\", content: userMessage },\n ];\n\n try {\n const response = await client.messages.create({\n model: config.model,\n max_tokens: maxTokens,\n system: cacheControl\n ? [{ type: \"text\" as const, text: systemPrompt, cache_control: { type: \"ephemeral\" as const } }]\n : systemPrompt,\n messages,\n });\n const textBlock = response.content.find((block) => block.type === \"text\");\n if (!textBlock || textBlock.type !== \"text\") {\n throw new Error(\"No text response from compiler LLM\");\n }\n return textBlock.text;\n } catch (err) {\n throw new Error(classifyError(err, providerName));\n }\n }\n\n // All other providers use OpenAI-compatible API\n const resolvedBaseURL = getBaseURL(config.provider, config.base_url);\n const clientOptions: { apiKey: string; baseURL?: string } = { apiKey };\n if (resolvedBaseURL) clientOptions.baseURL = resolvedBaseURL;\n\n const client = new OpenAI(clientOptions);\n try {\n const response = await client.chat.completions.create({\n model: config.model,\n max_tokens: maxTokens,\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userMessage },\n ],\n ...(jsonMode ? { response_format: { type: \"json_object\" as const } } : {}),\n });\n const text = response.choices[0]?.message?.content;\n if (!text) {\n throw new Error(\"No text response from compiler LLM\");\n }\n return text;\n } catch (err) {\n throw new Error(classifyError(err, providerName));\n }\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { HarnessSnapshot } from './types.js';\n\n/**\n * Creates a baseline snapshot of the .claude/ directory.\n * Copies to both baseline/ and iterations/0/harness/ in the workspace.\n */\nexport async function snapshotBaseline(\n projectRoot: string,\n workspacePath: string,\n): Promise<void> {\n const claudeDir = path.join(projectRoot, '.claude');\n const baselineDir = path.join(workspacePath, 'baseline');\n const iter0Dir = path.join(workspacePath, 'iterations', '0', 'harness');\n\n try {\n await fs.access(claudeDir);\n } catch {\n throw new Error(`.claude/ directory not found in ${projectRoot}`);\n }\n\n await copyDir(claudeDir, baselineDir);\n await copyDir(claudeDir, iter0Dir);\n\n // Include .mcp.json in harness scope if it exists\n const mcpJsonPath = path.join(projectRoot, '.mcp.json');\n try {\n await fs.access(mcpJsonPath);\n await fs.copyFile(mcpJsonPath, path.join(baselineDir, '.mcp.json'));\n await fs.copyFile(mcpJsonPath, path.join(iter0Dir, '.mcp.json'));\n } catch {\n // .mcp.json doesn't exist — skip\n }\n}\n\n/**\n * Recursively copies a directory from src to dest.\n * Creates dest (and any missing parent directories) if it does not exist.\n */\nexport async function copyDir(src: string, dest: string): Promise<void> {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Loads a HarnessSnapshot from a harness directory path.\n * Verifies the directory exists before returning.\n */\nexport async function loadHarnessSnapshot(\n harnessDir: string,\n iteration: number,\n): Promise<HarnessSnapshot> {\n try {\n await fs.access(harnessDir);\n } catch {\n throw new Error(`Harness directory not found: ${harnessDir}`);\n }\n\n return { path: harnessDir, iteration };\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { Trace, Score, IterationLog, Proposal } from './types.js';\n\n/**\n * Load a trace from filesystem.\n * Parses tool_calls.jsonl (one JSON object per line) and extracts\n * the iteration number from the parent directory name.\n */\nexport async function loadTrace(traceDir: string): Promise<Trace> {\n const stdout = await fs.readFile(path.join(traceDir, 'stdout.log'), 'utf-8').catch(() => '');\n const stderr = await fs.readFile(path.join(traceDir, 'stderr.log'), 'utf-8').catch(() => '');\n const filesChangedStr = await fs.readFile(\n path.join(traceDir, 'files_changed.json'),\n 'utf-8',\n ).catch(() => '{}');\n const timingStr = await fs.readFile(\n path.join(traceDir, 'timing.json'),\n 'utf-8',\n ).catch(() => '{}');\n const scoreStr = await fs.readFile(\n path.join(traceDir, 'score.json'),\n 'utf-8',\n ).catch(() => '{\"pass\": false}');\n\n // Parse tool_calls.jsonl — one JSON object per line\n const toolCallsStr = await fs.readFile(\n path.join(traceDir, 'tool_calls.jsonl'),\n 'utf-8',\n ).catch(() => '');\n const toolCalls = toolCallsStr\n .split('\\n')\n .filter(line => line.trim())\n .map(line => JSON.parse(line) as unknown);\n\n // Extract iteration from parent directory name (traces/{iteration}/{taskId})\n const parentDir = path.basename(path.dirname(traceDir));\n const iteration = parseInt(parentDir, 10) || 0;\n\n return {\n taskId: path.basename(traceDir),\n iteration,\n stdout,\n stderr,\n toolCalls,\n filesChanged: JSON.parse(filesChangedStr) as Record<string, 'created' | 'modified' | 'deleted'>,\n score: JSON.parse(scoreStr) as Trace['score'],\n timing: JSON.parse(timingStr) as Trace['timing'],\n };\n}\n\n/**\n * Load all traces for an iteration.\n */\nexport async function loadIterationTraces(\n workspacePath: string,\n iteration: number,\n): Promise<Trace[]> {\n const tracesDir = path.join(workspacePath, 'traces', iteration.toString());\n const traces: Trace[] = [];\n\n try {\n const taskDirs = await fs.readdir(tracesDir);\n for (const taskId of taskDirs) {\n const trace = await loadTrace(path.join(tracesDir, taskId));\n traces.push(trace);\n }\n } catch {\n // Directory doesn't exist yet\n }\n\n return traces;\n}\n\n/**\n * Write all trace files to the given directory.\n * Writes stdout.log, stderr.log, tool_calls.jsonl, files_changed.json,\n * timing.json, and score.json.\n */\nexport async function writeTrace(traceDir: string, trace: Trace): Promise<void> {\n await fs.mkdir(traceDir, { recursive: true });\n await fs.writeFile(path.join(traceDir, 'stdout.log'), trace.stdout, 'utf-8');\n await fs.writeFile(path.join(traceDir, 'stderr.log'), trace.stderr, 'utf-8');\n\n // Write tool_calls.jsonl — one JSON object per line\n const toolCallsLines = trace.toolCalls\n .map(tc => JSON.stringify(tc))\n .join('\\n');\n await fs.writeFile(path.join(traceDir, 'tool_calls.jsonl'), toolCallsLines, 'utf-8');\n\n await fs.writeFile(\n path.join(traceDir, 'files_changed.json'),\n JSON.stringify(trace.filesChanged, null, 2),\n 'utf-8',\n );\n await fs.writeFile(\n path.join(traceDir, 'timing.json'),\n JSON.stringify(trace.timing, null, 2),\n 'utf-8',\n );\n await fs.writeFile(\n path.join(traceDir, 'score.json'),\n JSON.stringify(trace.score, null, 2),\n 'utf-8',\n );\n}\n\n/**\n * Write or overwrite only the score.json file in an existing trace directory.\n * Used to update the score after scoring runs separately from trace capture.\n */\nexport async function writeScore(traceDir: string, score: Score): Promise<void> {\n await fs.writeFile(\n path.join(traceDir, 'score.json'),\n JSON.stringify(score, null, 2),\n 'utf-8',\n );\n}\n\n/**\n * Check whether a trace directory has been populated.\n * Returns true if stdout.log exists inside traceDir.\n */\nexport async function traceExists(traceDir: string): Promise<boolean> {\n try {\n await fs.access(path.join(traceDir, 'stdout.log'));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Write iteration log files to .kairn-evolve/iterations/{N}/.\n * Creates: scores.json, proposer_reasoning.md, mutation_diff.patch\n */\nexport async function writeIterationLog(\n workspacePath: string,\n log: IterationLog,\n): Promise<void> {\n const iterDir = path.join(workspacePath, 'iterations', log.iteration.toString());\n await fs.mkdir(iterDir, { recursive: true });\n\n // Write scores\n await fs.writeFile(\n path.join(iterDir, 'scores.json'),\n JSON.stringify({ score: log.score, taskResults: log.taskResults }, null, 2),\n 'utf-8',\n );\n\n // Write proposer reasoning\n await fs.writeFile(\n path.join(iterDir, 'proposer_reasoning.md'),\n log.proposal?.reasoning ?? 'Baseline evaluation (no proposal)',\n 'utf-8',\n );\n\n // Write mutation diff\n await fs.writeFile(\n path.join(iterDir, 'mutation_diff.patch'),\n log.diffPatch ?? '',\n 'utf-8',\n );\n}\n\n/**\n * Load an iteration log from .kairn-evolve/iterations/{N}/.\n * Returns null if the iteration directory doesn't exist.\n */\nexport async function loadIterationLog(\n workspacePath: string,\n iteration: number,\n): Promise<IterationLog | null> {\n const iterDir = path.join(workspacePath, 'iterations', iteration.toString());\n\n try {\n await fs.access(iterDir);\n } catch {\n return null;\n }\n\n const scoresStr = await fs.readFile(path.join(iterDir, 'scores.json'), 'utf-8').catch(() => '{}');\n const reasoning = await fs.readFile(path.join(iterDir, 'proposer_reasoning.md'), 'utf-8').catch(() => '');\n const diffPatch = await fs.readFile(path.join(iterDir, 'mutation_diff.patch'), 'utf-8').catch(() => '');\n\n const scoresData = JSON.parse(scoresStr) as { score?: number; taskResults?: Record<string, Score> };\n\n const proposal: Proposal | null = reasoning\n ? { reasoning, mutations: [], expectedImpact: {} }\n : null;\n\n return {\n iteration,\n score: scoresData.score ?? 0,\n taskResults: scoresData.taskResults ?? {},\n proposal,\n diffPatch: diffPatch || null,\n timestamp: '',\n };\n}\n","import { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\n/**\n * Execute a shell command in a given directory with a timeout.\n * Returns `{ stdout, stderr }` on success; throws on non-zero exit.\n */\nexport async function execCommand(\n cmd: string,\n cwd: string,\n timeoutMs: number = 30_000,\n): Promise<{ stdout: string; stderr: string }> {\n return execAsync(cmd, { cwd, timeout: timeoutMs });\n}\n","import { execCommand } from './exec.js';\nimport { callLLM } from '../llm.js';\nimport type { KairnConfig } from '../types.js';\nimport type { Task, Score } from './types.js';\n\n/** Pattern to identify lines that look like shell commands. */\nconst COMMAND_PATTERN =\n /^(npm |npx |node |python |make |cargo |go |git |test |ls |cat |grep |curl )/;\n\n/** Shell metacharacters that could enable command injection. */\nconst SHELL_METACHAR_PATTERN = /[;|&`$()<>]/;\n\n/** System prompt for LLM-as-judge scoring. */\nexport const JUDGE_SYSTEM_PROMPT = `You are an eval judge for Claude Code agent tasks. Given a task description, expected outcome, and actual execution results, determine if the task was completed successfully.\n\nReturn ONLY valid JSON with this structure:\n{\n \"pass\": true/false,\n \"score\": 0-100,\n \"reasoning\": \"Brief explanation of your judgment\"\n}`;\n\n/** System prompt for rubric criterion scoring. */\nexport const RUBRIC_SYSTEM_PROMPT = `You are an eval judge scoring a specific criterion. Given the task, the criterion to evaluate, and the execution results, score the criterion.\n\nReturn ONLY valid JSON:\n{\n \"score\": 0.0-1.0,\n \"reasoning\": \"Brief explanation\"\n}`;\n\n// ── Deterministic criterion scoring heuristics ──\n\n/** Evidence keywords for \"Ran {command}\" pattern, keyed by command keyword. */\nconst RAN_COMMAND_EVIDENCE: Array<{ keywords: string[]; evidence: string[] }> = [\n { keywords: ['npm run build', 'build', 'tsup'], evidence: ['build success', 'tsup', 'built in', 'build completed'] },\n { keywords: ['tsc', 'typecheck'], evidence: ['tsc', 'typecheck'] },\n { keywords: ['npm run lint', 'eslint', 'lint'], evidence: ['lint', 'eslint'] },\n { keywords: ['npm test', 'vitest', 'test'], evidence: ['vitest', 'test files', 'tests passed', 'passed (', 'tests '] },\n];\n\n/** Patterns for \"Zero/No {pattern}\" — items to search for absence. */\nconst ABSENCE_PATTERNS: Array<{ keywords: string[]; search: string[] }> = [\n { keywords: ['.then()', '.catch()'], search: ['.then(', '.catch('] },\n { keywords: ['readfilesync', 'writefilesync'], search: ['readfilesync', 'writefilesync'] },\n { keywords: ['sync'], search: ['sync'] },\n];\n\n/** Patterns for \"Uses {pattern}\" — keyword in criterion text mapped to output search terms. */\nconst PRESENCE_PATTERNS: Array<{ keyword: string; search: string[] }> = [\n { keyword: 'chalk.green', search: ['chalk.green'] },\n { keyword: 'chalk.yellow', search: ['chalk.yellow'] },\n { keyword: 'chalk.red', search: ['chalk.red'] },\n { keyword: 'chalk.cyan', search: ['chalk.cyan'] },\n { keyword: 'fs.promises', search: ['fs.promises', 'fs/promises'] },\n { keyword: 'fs/promises', search: ['fs.promises', 'fs/promises'] },\n { keyword: 'async/await', search: ['async ', 'await '] },\n { keyword: '@inquirer/prompts', search: ['@inquirer/prompts'] },\n];\n\n/** Patterns for \"Calls {function}\" — items to search for presence. */\nconst CALL_PATTERNS: string[] = [\n 'process.exit(1)',\n 'process.exit',\n];\n\n/**\n * Attempt to score a rubric criterion deterministically using stdout/stderr\n * pattern matching. Returns null if the criterion cannot be scored this way\n * (falls back to LLM).\n */\nexport function scoreCriterionDeterministic(\n criterionText: string,\n stdout: string,\n stderr: string,\n): { score: number; reasoning: string } | null {\n const combined = `${stdout}\\n${stderr}`.toLowerCase();\n const criterionLower = criterionText.toLowerCase().trim();\n\n // Pattern 1: \"Ran {command}\" — check if command was executed\n if (/^ran\\b/i.test(criterionText.trim())) {\n for (const entry of RAN_COMMAND_EVIDENCE) {\n // Check if the criterion text mentions any of this entry's command keywords\n const matchesKeyword = entry.keywords.some((kw) =>\n criterionLower.includes(kw.toLowerCase()),\n );\n if (matchesKeyword) {\n const found = entry.evidence.some((ev) => combined.includes(ev.toLowerCase()));\n if (found) {\n const matchedEvidence = entry.evidence.find((ev) =>\n combined.includes(ev.toLowerCase()),\n );\n return {\n score: 1.0,\n reasoning: `Deterministic: found evidence of '${matchedEvidence}' in output`,\n };\n }\n return {\n score: 0.0,\n reasoning: `Deterministic: no evidence of '${entry.keywords[0]}' found`,\n };\n }\n }\n // \"Ran\" prefix matched but no known command pattern — fall through to null\n return null;\n }\n\n // Pattern 2: \"Zero/No {pattern}\" — check absence\n if (/^(zero|no)\\b/i.test(criterionText.trim())) {\n for (const entry of ABSENCE_PATTERNS) {\n const matchesKeyword = entry.keywords.some((kw) =>\n criterionLower.includes(kw.toLowerCase()),\n );\n if (matchesKeyword) {\n const found = entry.search.some((pat) => combined.includes(pat.toLowerCase()));\n if (found) {\n const matchedPattern = entry.search.find((pat) =>\n combined.includes(pat.toLowerCase()),\n );\n return {\n score: 0.0,\n reasoning: `Deterministic: found '${matchedPattern}' which should be absent`,\n };\n }\n return {\n score: 1.0,\n reasoning: `Deterministic: no prohibited pattern found in output`,\n };\n }\n }\n // \"Zero/No\" prefix matched but no known pattern — fall through to null\n return null;\n }\n\n // Pattern 3: \"Uses {specific pattern}\" — check presence\n if (/^uses?\\b/i.test(criterionText.trim())) {\n for (const entry of PRESENCE_PATTERNS) {\n if (criterionLower.includes(entry.keyword.toLowerCase())) {\n const found = entry.search.some((s) => combined.includes(s.toLowerCase()));\n if (found) {\n return {\n score: 1.0,\n reasoning: `Deterministic: found '${entry.keyword}' in output`,\n };\n }\n return {\n score: 0.0,\n reasoning: `Deterministic: '${entry.keyword}' not found in output`,\n };\n }\n }\n // \"Uses\" prefix matched but no known pattern — fall through to null\n return null;\n }\n\n // Pattern 4: \"Calls {function}\" — check presence\n if (/^calls?\\b/i.test(criterionText.trim())) {\n for (const pattern of CALL_PATTERNS) {\n if (criterionLower.includes(pattern.toLowerCase())) {\n const found = combined.includes(pattern.toLowerCase());\n if (found) {\n return {\n score: 1.0,\n reasoning: `Deterministic: found '${pattern}' in output`,\n };\n }\n return {\n score: 0.0,\n reasoning: `Deterministic: '${pattern}' not found in output`,\n };\n }\n }\n // \"Calls\" prefix matched but no known pattern — fall through to null\n return null;\n }\n\n // No pattern matched — fall back to LLM\n return null;\n}\n\n/**\n * Pass/fail scorer: execute verification commands from expected_outcome,\n * falling back to stderr analysis when no commands are found.\n */\nexport async function passFailScorer(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n): Promise<Score> {\n const outcomes = Array.isArray(task.expected_outcome)\n ? task.expected_outcome\n : task.expected_outcome.split('\\n');\n\n // Look for lines that look like shell commands\n const commands = outcomes\n .map((line) => line.replace(/^-\\s*/, '').trim())\n .filter((line) => COMMAND_PATTERN.test(line));\n\n if (commands.length > 0) {\n // Execute verification commands — reject commands with shell metacharacters\n // to prevent injection from LLM-generated expected_outcome strings\n const failures: string[] = [];\n for (const cmd of commands) {\n if (SHELL_METACHAR_PATTERN.test(cmd)) {\n failures.push(`Rejected unsafe command (shell metacharacters): ${cmd}`);\n continue;\n }\n try {\n await execCommand(cmd, workspacePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n failures.push(`Command failed: ${cmd}\\n${msg}`);\n }\n }\n\n const passed = failures.length === 0;\n return {\n pass: passed,\n score: passed ? 100 : 0,\n details: passed\n ? `All ${commands.length} verification commands passed`\n : failures.join('\\n'),\n };\n }\n\n // Fallback: check stderr for error indicators\n // Strip lines from setup (prefixed with [setup]) — these are not Claude's errors\n const filteredStderr = stderr\n .split('\\n')\n .filter(line => !line.startsWith('[setup]'))\n .join('\\n');\n const hasErrors =\n filteredStderr.toLowerCase().includes('error') ||\n filteredStderr.toLowerCase().includes('failed') ||\n filteredStderr.toLowerCase().includes('exception');\n const passed = !hasErrors;\n\n return {\n pass: passed,\n score: passed ? 100 : 0,\n details: passed ? 'No errors detected in output' : 'Errors found in stderr',\n };\n}\n\n/**\n * LLM-as-judge scorer: ask an LLM to evaluate whether the task outcome\n * matches the expected result.\n */\nexport async function llmJudgeScorer(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n config: KairnConfig,\n): Promise<Score> {\n const expectedOutcome = Array.isArray(task.expected_outcome)\n ? task.expected_outcome.join('\\n')\n : task.expected_outcome;\n\n const userMessage = [\n '## Task',\n task.description,\n '',\n '## Expected Outcome',\n expectedOutcome,\n '',\n '## Actual stdout (last 2000 chars)',\n stdout.slice(-2000),\n '',\n '## Actual stderr (last 1000 chars)',\n stderr.slice(-1000),\n ].join('\\n');\n\n try {\n const response = await callLLM(config, userMessage, {\n systemPrompt: JUDGE_SYSTEM_PROMPT,\n maxTokens: 1024,\n cacheControl: true,\n });\n\n // Parse JSON response, stripping markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```')) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '');\n }\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n return { pass: false, score: 0, reasoning: 'Judge returned invalid JSON' };\n }\n const result = JSON.parse(jsonMatch[0]) as {\n pass: boolean;\n score: number;\n reasoning: string;\n };\n return {\n pass: result.pass,\n score: result.score,\n reasoning: result.reasoning,\n };\n } catch (err) {\n return {\n pass: false,\n score: 0,\n reasoning: `LLM judge error: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n\n/**\n * Rubric scorer: evaluate multiple weighted criteria via LLM,\n * producing a weighted aggregate score.\n *\n * Falls back to passFailScorer when no rubric criteria are defined.\n */\nexport async function rubricScorer(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n config: KairnConfig,\n): Promise<Score> {\n if (!task.rubric || task.rubric.length === 0) {\n return passFailScorer(task, workspacePath, stdout, stderr);\n }\n\n const breakdown: Array<{ criterion: string; score: number; weight: number }> =\n [];\n let weightedSum = 0;\n\n for (const criterion of task.rubric) {\n // Try deterministic scoring first to avoid unnecessary LLM calls\n const deterministicResult = scoreCriterionDeterministic(\n criterion.criterion,\n stdout,\n stderr,\n );\n\n if (deterministicResult !== null) {\n breakdown.push({\n criterion: criterion.criterion,\n score: deterministicResult.score,\n weight: criterion.weight,\n });\n weightedSum += deterministicResult.score * criterion.weight;\n continue; // Skip LLM call\n }\n\n // Fall through to LLM scoring\n const userMessage = [\n '## Task',\n task.description,\n '',\n '## Criterion to Evaluate',\n `\"${criterion.criterion}\" (weight: ${criterion.weight})`,\n '',\n '## Actual stdout (last 2000 chars)',\n stdout.slice(-2000),\n '',\n '## Actual stderr (last 500 chars)',\n stderr.slice(-500),\n ].join('\\n');\n\n try {\n const response = await callLLM(config, userMessage, {\n systemPrompt: RUBRIC_SYSTEM_PROMPT,\n maxTokens: 512,\n cacheControl: true,\n });\n\n let cleaned = response.trim();\n if (cleaned.startsWith('```')) {\n cleaned = cleaned\n .replace(/^```(?:json)?\\n?/, '')\n .replace(/\\n?```$/, '');\n }\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n const result = JSON.parse(jsonMatch[0]) as {\n score: number;\n reasoning: string;\n };\n const clampedScore = Math.max(0, Math.min(1, result.score));\n breakdown.push({\n criterion: criterion.criterion,\n score: clampedScore,\n weight: criterion.weight,\n });\n weightedSum += clampedScore * criterion.weight;\n } else {\n breakdown.push({\n criterion: criterion.criterion,\n score: 0,\n weight: criterion.weight,\n });\n }\n } catch {\n breakdown.push({\n criterion: criterion.criterion,\n score: 0,\n weight: criterion.weight,\n });\n }\n }\n\n const totalWeight = task.rubric.reduce((sum, c) => sum + c.weight, 0);\n const totalScore = totalWeight > 0 ? Math.round((weightedSum / totalWeight) * 100) : 0;\n return {\n pass: totalScore >= 60,\n score: totalScore,\n reasoning: `Rubric score: ${totalScore}%`,\n breakdown,\n };\n}\n\n/**\n * Classify why a task failed based on trace data.\n * Only called for non-passing scores.\n */\nexport function classifyFailure(\n score: Score,\n stdout: string,\n stderr: string,\n): Score {\n if (score.pass) return score;\n\n const combined = `${stdout}\\n${stderr}`.toLowerCase();\n const scoreValue = score.score ?? 0;\n\n let failureCategory: Score['failureCategory'] = 'unknown';\n let failureReason = '';\n\n // Setup/task errors: task definition is broken or ambiguous\n if (\n stderr.includes('[setup]') && stderr.includes('Error') ||\n combined.includes('command not found') ||\n combined.includes('no such file or directory')\n ) {\n failureCategory = 'task';\n failureReason = 'Task setup failed or references missing resources';\n }\n // Model errors: API failures, token limits, context overflow\n else if (\n combined.includes('token limit') ||\n combined.includes('context length') ||\n combined.includes('rate limit') ||\n combined.includes('api error') ||\n combined.includes('429') ||\n combined.includes('overloaded')\n ) {\n failureCategory = 'model';\n failureReason = 'Model API error, token limit, or rate limit';\n }\n // Repo errors: pre-existing build failures, dirty state\n else if (\n combined.includes('build failed') && combined.includes('before') ||\n combined.includes('merge conflict') ||\n combined.includes('git dirty') ||\n combined.includes('uncommitted changes')\n ) {\n failureCategory = 'repo';\n failureReason = 'Pre-existing repo issues (build failure, dirty state)';\n }\n // Harness errors: agent tried but got it wrong (partial score)\n else if (scoreValue >= 20 && scoreValue < 80) {\n failureCategory = 'harness';\n failureReason = 'Agent attempted the task but did not follow harness conventions';\n }\n\n return { ...score, failureCategory, failureReason };\n}\n\nexport async function scoreTask(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n config?: KairnConfig,\n): Promise<Score> {\n let score: Score;\n if (task.scoring === 'pass-fail') {\n score = await passFailScorer(task, workspacePath, stdout, stderr);\n } else if (task.scoring === 'llm-judge' && config) {\n score = await llmJudgeScorer(task, workspacePath, stdout, stderr, config);\n } else if (task.scoring === 'rubric' && config) {\n score = await rubricScorer(task, workspacePath, stdout, stderr, config);\n } else {\n score = await passFailScorer(task, workspacePath, stdout, stderr);\n }\n\n if (!score.pass) {\n score = classifyFailure(score, stdout, stderr);\n }\n\n return score;\n}\n","import { exec, spawn } from 'child_process';\nimport { promisify } from 'util';\nimport fs from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport { writeTrace, writeScore } from './trace.js';\nimport { scoreTask } from './scorers.js';\nimport type { KairnConfig } from '../types.js';\nimport type { Task, TaskResult, Trace, Score, LoopProgressEvent } from './types.js';\n\nconst execAsync = promisify(exec);\n\n/** Directories to skip when copying the project directory as fallback. */\nconst COPY_SKIP_DIRS = new Set(['.git', 'node_modules', '.kairn-evolve', '.claude']);\n\n/**\n * Copy .mcp.json from the harness into the workspace root if present.\n */\nasync function deployMcpJson(harnessPath: string, workDir: string): Promise<void> {\n const src = path.join(harnessPath, '.mcp.json');\n await fs.copyFile(src, path.join(workDir, '.mcp.json')).catch(() => {});\n}\n\n/**\n * Create an isolated workspace with project files and a swapped harness.\n * Tries git worktree first for speed and proper isolation.\n * Falls back to copying the project directory if not in a git repo.\n */\nasync function createIsolatedWorkspace(\n projectRoot: string,\n harnessPath: string,\n): Promise<{ workDir: string; isWorktree: boolean }> {\n const suffix = `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n\n // Try git worktree first\n try {\n await execAsync('git rev-parse --is-inside-work-tree', {\n cwd: projectRoot,\n timeout: 5000,\n });\n const tmpDir = path.join(os.tmpdir(), `kairn-evolve-wt-${suffix}`);\n await execAsync(`git worktree add --detach \"${tmpDir}\" HEAD`, {\n cwd: projectRoot,\n timeout: 30_000,\n });\n // Replace .claude with iteration harness\n await fs.rm(path.join(tmpDir, '.claude'), { recursive: true, force: true });\n await copyDir(harnessPath, path.join(tmpDir, '.claude'));\n await deployMcpJson(harnessPath, tmpDir);\n return { workDir: tmpDir, isWorktree: true };\n } catch {\n // Not a git repo or worktree creation failed — fall back to copy\n }\n\n // Fallback: copy project directory (skip large/irrelevant dirs)\n const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), `kairn-evolve-cp-`));\n await copyProjectDir(projectRoot, tmpDir);\n await fs.rm(path.join(tmpDir, '.claude'), { recursive: true, force: true });\n await copyDir(harnessPath, path.join(tmpDir, '.claude'));\n await deployMcpJson(harnessPath, tmpDir);\n return { workDir: tmpDir, isWorktree: false };\n}\n\n/**\n * Copy project directory to dest, skipping .git, node_modules, .kairn-evolve, .claude.\n */\nasync function copyProjectDir(src: string, dest: string): Promise<void> {\n await fs.mkdir(dest, { recursive: true });\n let entries;\n try {\n entries = await fs.readdir(src, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (COPY_SKIP_DIRS.has(entry.name)) continue;\n\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Clean up an isolated workspace.\n */\nasync function cleanupIsolatedWorkspace(\n workDir: string,\n isWorktree: boolean,\n projectRoot: string,\n): Promise<void> {\n if (isWorktree) {\n try {\n await execAsync(`git worktree remove \"${workDir}\" --force`, {\n cwd: projectRoot,\n timeout: 10_000,\n });\n } catch {\n await fs.rm(workDir, { recursive: true, force: true }).catch(() => {});\n await execAsync('git worktree prune', {\n cwd: projectRoot,\n timeout: 5000,\n }).catch(() => {});\n }\n } else {\n await fs.rm(workDir, { recursive: true, force: true }).catch(() => {});\n }\n}\n\n/**\n * Run a single task against a harness in an isolated workspace.\n *\n * 1. Creates isolated workspace (git worktree or project copy)\n * 2. Swaps .claude/ with the iteration's harness\n * 3. Runs task.setup commands\n * 4. Spawns `claude` CLI with --print flag\n * 5. Captures stdout, stderr, files changed\n * 6. Writes all trace files\n * 7. Cleans up workspace\n *\n * @param projectRoot - Root directory of the project (contains package.json, src/, etc.)\n */\nexport async function runTask(\n task: Task,\n harnessPath: string,\n traceDir: string,\n iteration: number,\n projectRoot?: string,\n): Promise<TaskResult> {\n await fs.mkdir(traceDir, { recursive: true });\n const startedAt = new Date().toISOString();\n const startMs = Date.now();\n\n const root = projectRoot ?? process.cwd();\n const { workDir, isWorktree } = await createIsolatedWorkspace(root, harnessPath);\n\n try {\n // Run setup commands if any\n // Trust boundary: setup commands come from tasks.yaml which is user-reviewed\n // before execution. The user is the trust anchor for these commands.\n let setupStderr = '';\n if (task.setup.trim()) {\n try {\n await execAsync(task.setup, { cwd: workDir, timeout: 60_000 });\n } catch (err) {\n setupStderr =\n err instanceof Error ? err.message : String(err);\n }\n }\n\n // Snapshot file list before execution for diffing\n const filesBefore = await snapshotFileList(workDir);\n\n // Spawn claude CLI\n const spawnResult = await spawnClaude(task.description, workDir, task.timeout);\n\n // Diff files to detect changes\n const filesAfter = await snapshotFileList(workDir);\n const filesChanged = diffFileLists(filesBefore, filesAfter);\n\n // Parse tool calls from JSON output (if available)\n const toolCalls = parseToolCalls(spawnResult.stdout);\n\n const completedAt = new Date().toISOString();\n const durationMs = Date.now() - startMs;\n\n // Build trace\n const combinedStderr = setupStderr\n ? `[setup] ${setupStderr}\\n${spawnResult.stderr}`\n : spawnResult.stderr;\n\n const trace: Trace = {\n taskId: task.id,\n iteration,\n stdout: spawnResult.stdout,\n stderr: combinedStderr,\n toolCalls,\n filesChanged,\n score: { pass: false, details: 'Pending scoring' },\n timing: { startedAt, completedAt, durationMs },\n };\n\n // Write trace files\n await writeTrace(traceDir, trace);\n\n // Return result (scoring is done by the caller / CLI command)\n return {\n taskId: task.id,\n score: trace.score,\n traceDir,\n };\n } finally {\n await cleanupIsolatedWorkspace(workDir, isWorktree, root);\n }\n}\n\n/**\n * Spawn the claude CLI with --print flag and capture output.\n */\nexport async function spawnClaude(\n instruction: string,\n cwd: string,\n timeoutSec: number,\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n return new Promise((resolve) => {\n const args = ['--print', '--output-format', 'text', '--max-turns', '50', '--dangerously-skip-permissions'];\n const child = spawn('claude', args, {\n cwd,\n stdio: ['pipe', 'pipe', 'pipe'],\n timeout: timeoutSec * 1000,\n env: { ...process.env },\n });\n\n let stdout = '';\n let stderr = '';\n\n child.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n // Send the instruction via stdin\n child.stdin.write(instruction);\n child.stdin.end();\n\n child.on('close', (code) => {\n resolve({ stdout, stderr, exitCode: code ?? 1 });\n });\n\n child.on('error', (err) => {\n resolve({\n stdout,\n stderr: stderr + `\\nSpawn error: ${err.message}`,\n exitCode: 1,\n });\n });\n });\n}\n\n/**\n * Snapshot all file paths + mtimes in a directory recursively.\n * Used for before/after diffing to detect file changes.\n */\nexport async function snapshotFileList(\n dir: string,\n): Promise<Record<string, number>> {\n const result: Record<string, number> = {};\n\n async function walk(current: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = path.join(current, entry.name);\n const relativePath = path.relative(dir, fullPath);\n\n // Skip .claude directory (that's the harness, not task output)\n if (relativePath.startsWith('.claude')) continue;\n // Skip node_modules\n if (relativePath.startsWith('node_modules')) continue;\n // Skip .git\n if (relativePath.startsWith('.git')) continue;\n\n if (entry.isDirectory()) {\n await walk(fullPath);\n } else {\n try {\n const stat = await fs.stat(fullPath);\n result[relativePath] = stat.mtimeMs;\n } catch {\n // File might have been deleted between readdir and stat\n }\n }\n }\n }\n\n await walk(dir);\n return result;\n}\n\n/**\n * Compare before/after file snapshots to determine what changed.\n */\nexport function diffFileLists(\n before: Record<string, number>,\n after: Record<string, number>,\n): Record<string, 'created' | 'modified' | 'deleted'> {\n const changes: Record<string, 'created' | 'modified' | 'deleted'> = {};\n\n // Check for new and modified files\n for (const [file, mtime] of Object.entries(after)) {\n if (!(file in before)) {\n changes[file] = 'created';\n } else if (before[file] !== mtime) {\n changes[file] = 'modified';\n }\n }\n\n // Check for deleted files\n for (const file of Object.keys(before)) {\n if (!(file in after)) {\n changes[file] = 'deleted';\n }\n }\n\n return changes;\n}\n\n/**\n * Try to parse tool calls from claude output.\n * Looks for JSON lines containing tool_use type or tool_name field.\n * Falls back to empty array if output is plain text.\n */\nexport function parseToolCalls(stdout: string): unknown[] {\n try {\n const lines = stdout.split('\\n').filter((l) => l.trim());\n const toolCalls: unknown[] = [];\n for (const line of lines) {\n try {\n const obj = JSON.parse(line) as Record<string, unknown>;\n if (obj.type === 'tool_use' || obj.tool_name) {\n toolCalls.push(obj);\n }\n } catch {\n // Not JSON, skip\n }\n }\n return toolCalls;\n } catch {\n return [];\n }\n}\n\n/**\n * Run async tasks with a concurrency limit.\n * Returns results in the same order as the input tasks array.\n */\nexport async function runWithConcurrency<T>(\n tasks: (() => Promise<T>)[],\n limit: number,\n): Promise<T[]> {\n const results: T[] = new Array(tasks.length);\n const executing = new Set<Promise<void>>();\n const errors: unknown[] = [];\n const effectiveLimit = Math.max(1, limit);\n\n for (let i = 0; i < tasks.length; i++) {\n const p = tasks[i]().then(\n (result) => { results[i] = result; },\n (err) => { errors.push(err); },\n );\n const tracked = p.then(() => { executing.delete(tracked); });\n executing.add(tracked);\n if (executing.size >= effectiveLimit) {\n await Promise.race(executing);\n }\n }\n\n await Promise.all(executing);\n\n if (errors.length > 0) {\n throw errors[0];\n }\n\n return results;\n}\n\n/**\n * Compute population standard deviation for a list of numbers.\n *\n * Uses population stddev (divide by N) rather than sample stddev (divide by N-1).\n * For typical run counts (3-5), this slightly underestimates variance compared\n * to sample stddev, but is consistent with reporting the observed spread of\n * the actual runs performed rather than estimating the population parameter.\n */\nfunction computeStddev(values: number[], mean: number): number {\n if (values.length <= 1) return 0;\n const sumSqDiffs = values.reduce((sum, v) => sum + (v - mean) ** 2, 0);\n return Math.sqrt(sumSqDiffs / values.length);\n}\n\n/**\n * Run all tasks against a harness and return aggregated results.\n *\n * Each task is run sequentially via `runTask`, scored (optionally via\n * `scoreTask` when a `KairnConfig` is provided), and its score written\n * to the trace directory.\n *\n * The aggregate score is the arithmetic mean of all task scores.\n * For scores that have a numeric `score` field, that value is used directly.\n * For pass/fail scores without a numeric value, `pass=true` counts as 100\n * and `pass=false` counts as 0.\n */\nexport async function evaluateAll(\n tasks: Task[],\n harnessPath: string,\n workspacePath: string,\n iteration: number,\n config: KairnConfig | null,\n onProgress?: (event: LoopProgressEvent) => void,\n runsPerTask: number = 1,\n parallelTasks: number = 1,\n): Promise<{ results: Record<string, Score>; aggregate: number }> {\n const results: Record<string, Score> = {};\n const projectRoot = path.resolve(workspacePath, '..');\n const effectiveRuns = Math.max(1, runsPerTask);\n const concurrency = Math.max(1, parallelTasks);\n\n const evaluateTask = async (task: Task): Promise<{ id: string; score: Score }> => {\n onProgress?.({ type: 'task-start', iteration, taskId: task.id });\n\n let finalScore: Score;\n\n if (effectiveRuns > 1 && config) {\n const runScores: number[] = [];\n let passCount = 0;\n\n for (let run = 0; run < effectiveRuns; run++) {\n const traceDir = path.join(\n workspacePath,\n 'traces',\n iteration.toString(),\n `${task.id}_run${run}`,\n );\n\n onProgress?.({\n type: 'task-run',\n iteration,\n taskId: task.id,\n message: `Run ${run + 1}/${effectiveRuns} of ${task.id}`,\n });\n\n await runTask(task, harnessPath, traceDir, iteration, projectRoot);\n\n const stdout = await fs\n .readFile(path.join(traceDir, 'stdout.log'), 'utf-8')\n .catch(() => '');\n const stderr = await fs\n .readFile(path.join(traceDir, 'stderr.log'), 'utf-8')\n .catch(() => '');\n const score = await scoreTask(task, traceDir, stdout, stderr, config);\n await writeScore(traceDir, score);\n\n runScores.push(score.score ?? (score.pass ? 100 : 0));\n if (score.pass) passCount++;\n }\n\n const mean = runScores.reduce((a, b) => a + b, 0) / runScores.length;\n const stddev = computeStddev(runScores, mean);\n\n finalScore = {\n pass: passCount > effectiveRuns / 2,\n score: mean,\n details: `Mean of ${effectiveRuns} runs`,\n variance: {\n runs: effectiveRuns,\n scores: runScores,\n mean,\n stddev,\n },\n };\n } else {\n const traceDir = path.join(\n workspacePath,\n 'traces',\n iteration.toString(),\n task.id,\n );\n\n const taskResult = await runTask(task, harnessPath, traceDir, iteration, projectRoot);\n\n finalScore = taskResult.score;\n if (config) {\n const stdout = await fs\n .readFile(path.join(traceDir, 'stdout.log'), 'utf-8')\n .catch(() => '');\n const stderr = await fs\n .readFile(path.join(traceDir, 'stderr.log'), 'utf-8')\n .catch(() => '');\n finalScore = await scoreTask(task, traceDir, stdout, stderr, config);\n await writeScore(traceDir, finalScore);\n }\n }\n\n onProgress?.({\n type: 'task-scored',\n iteration,\n taskId: task.id,\n score: finalScore.score ?? (finalScore.pass ? 100 : 0),\n });\n\n return { id: task.id, score: finalScore };\n };\n\n const taskResults = await runWithConcurrency(\n tasks.map((task) => () => evaluateTask(task)),\n concurrency,\n );\n\n for (const { id, score } of taskResults) {\n results[id] = score;\n }\n\n const scores = Object.values(results);\n const total = scores.reduce(\n (sum, s) => sum + (s.score ?? (s.pass ? 100 : 0)),\n 0,\n );\n const aggregate = scores.length > 0 ? total / scores.length : 0;\n\n return { results, aggregate };\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { IterationLog } from './types.js';\n\nconst MEMORY_FILE = 'proposer-memory.json';\nconst MAX_ENTRIES = 10;\n\nexport interface RunSummary {\n timestamp: string;\n baselineScore: number;\n bestScore: number;\n improvement: number;\n effectiveMutations: string[];\n regressiveMutations: string[];\n insights: string;\n}\n\n/**\n * Load proposer memory from the workspace.\n * Returns empty array if no memory file exists.\n */\nexport async function loadProposerMemory(workspacePath: string): Promise<RunSummary[]> {\n const memoryPath = path.join(workspacePath, MEMORY_FILE);\n try {\n const raw = await fs.readFile(memoryPath, 'utf-8');\n const parsed = JSON.parse(raw) as unknown;\n if (Array.isArray(parsed)) return parsed as RunSummary[];\n return [];\n } catch {\n return [];\n }\n}\n\n/**\n * Build a run summary from iteration history.\n */\nexport function buildRunSummary(history: IterationLog[], baselineScore: number, bestScore: number): RunSummary {\n const effectiveMutations: string[] = [];\n const regressiveMutations: string[] = [];\n\n for (let i = 1; i < history.length; i++) {\n const prev = history[i - 1];\n const curr = history[i];\n if (!curr.proposal?.mutations.length) continue;\n\n const delta = curr.score - prev.score;\n const summary = curr.proposal.mutations\n .map(m => `${m.action} ${m.file}: ${m.rationale}`)\n .join('; ');\n\n if (delta > 0) {\n effectiveMutations.push(`+${delta.toFixed(1)}: ${summary}`);\n } else if (delta < -5) {\n regressiveMutations.push(`${delta.toFixed(1)}: ${summary}`);\n }\n }\n\n const improvement = bestScore - baselineScore;\n const insights = improvement > 0\n ? `Improved ${improvement.toFixed(1)} points. ${effectiveMutations.length} helpful mutations, ${regressiveMutations.length} regressions.`\n : `No improvement. ${regressiveMutations.length} regressions observed.`;\n\n return {\n timestamp: new Date().toISOString(),\n baselineScore,\n bestScore,\n improvement,\n effectiveMutations,\n regressiveMutations,\n insights,\n };\n}\n\n/**\n * Save a run summary to the workspace. Keeps last MAX_ENTRIES entries.\n */\nexport async function saveRunSummary(workspacePath: string, summary: RunSummary): Promise<void> {\n const existing = await loadProposerMemory(workspacePath);\n existing.push(summary);\n const trimmed = existing.slice(-MAX_ENTRIES);\n const memoryPath = path.join(workspacePath, MEMORY_FILE);\n await fs.writeFile(memoryPath, JSON.stringify(trimmed, null, 2), 'utf-8');\n}\n\n/**\n * Format proposer memory for inclusion in the proposer context.\n */\nexport function formatMemoryForProposer(memory: RunSummary[]): string {\n if (memory.length === 0) return '';\n\n const lines: string[] = ['## Prior Run History\\n'];\n for (const entry of memory) {\n lines.push(`### Run at ${entry.timestamp}`);\n lines.push(`- Baseline: ${entry.baselineScore.toFixed(1)}%, Best: ${entry.bestScore.toFixed(1)}%, Improvement: ${entry.improvement >= 0 ? '+' : ''}${entry.improvement.toFixed(1)}`);\n if (entry.effectiveMutations.length > 0) {\n lines.push('- Effective mutations:');\n for (const m of entry.effectiveMutations.slice(0, 3)) {\n lines.push(` - ${m}`);\n }\n }\n if (entry.regressiveMutations.length > 0) {\n lines.push('- Regressive mutations (AVOID these):');\n for (const m of entry.regressiveMutations.slice(0, 3)) {\n lines.push(` - ${m}`);\n }\n }\n lines.push('');\n }\n return lines.join('\\n');\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { callLLM } from '../llm.js';\nimport { loadIterationTraces } from './trace.js';\nimport type { Task, Trace, Proposal, Mutation, IterationLog } from './types.js';\nimport type { KairnConfig } from '../types.js';\n\nexport const PROPOSER_SYSTEM_PROMPT = `You are an expert agent environment optimizer. Your job is to improve a Claude Code\nagent environment (.claude/ directory) based on execution traces from real tasks.\n\n## What You Have Access To\n1. Current harness: The .claude/ directory files (CLAUDE.md, commands/, rules/, agents/)\n2. Execution traces: Full stdout/stderr, tool call sequences, file changes, and scores\n3. History: Previous iterations' proposals, diffs, and resulting score changes\n\n## Your Task\nAnalyze the traces to identify WHY tasks fail or underperform. Then propose specific,\nminimal changes to the harness files that will fix those failures.\n\n## Diagnosis Process\n1. For each failed/low-scoring task:\n a. Read the full trace (stdout, tool calls, file changes)\n b. Identify the ROOT CAUSE: bad instruction? Missing tool? Wrong rule?\n c. Trace the failure back to a specific harness decision\n d. Propose a fix\n\n2. For each successful task:\n a. Note what worked well\n b. Ensure proposed changes don't break what's working\n\n3. Check history for counterfactual evidence\n\n## Available Mutation Actions\n1. **replace** — Replace old_text with new_text in a file: { \"file\": \"...\", \"action\": \"replace\", \"old_text\": \"...\", \"new_text\": \"...\", \"rationale\": \"...\" }\n2. **add_section** — Append new content to a file (or create it): { \"file\": \"...\", \"action\": \"add_section\", \"new_text\": \"...\", \"rationale\": \"...\" }\n3. **create_file** — Create a new file: { \"file\": \"...\", \"action\": \"create_file\", \"new_text\": \"...\", \"rationale\": \"...\" }\n4. **delete_section** — Remove specific text from a file: { \"file\": \"...\", \"action\": \"delete_section\", \"old_text\": \"...\", \"rationale\": \"...\" }\n5. **delete_file** — Delete an entire file: { \"file\": \"...\", \"action\": \"delete_file\", \"rationale\": \"...\" }\n\n## Output Format\nReturn a JSON object:\n{\n \"reasoning\": \"Your full causal analysis...\",\n \"mutations\": [\n { \"file\": \"CLAUDE.md\", \"action\": \"replace\", \"old_text\": \"...\", \"new_text\": \"...\", \"rationale\": \"...\" },\n { \"file\": \"commands/develop.md\", \"action\": \"add_section\", \"new_text\": \"...\", \"rationale\": \"...\" },\n { \"file\": \"rules/obsolete.md\", \"action\": \"delete_file\", \"rationale\": \"...\" }\n ],\n \"expected_impact\": { \"task-id\": \"+15% — explanation\" }\n}\n\n## MCP Configuration\nYou can also mutate .mcp.json to add, remove, or reconfigure MCP servers.\nTreat .mcp.json like any other harness file — propose changes when traces show\nthe agent lacks a tool it needs, or has tools that add noise without benefit.\n\n## Rules\n- Propose AT MOST 3 mutations per iteration. Fewer, targeted mutations are more stable than many broad ones.\n- Each mutation must have a clear rationale tied to a specific trace observation.\n- Never remove something that's working for another task.\n- If a previous iteration's change caused a regression, REVERT it.\n- Consider both additions AND removals. Remove sections that add noise without improving task performance.\n- Bloated harnesses hurt performance — trim what isn't earning its keep.\n\n## Anti-Gaming (CRITICAL)\n- Mutations must improve GENERAL-PURPOSE development quality, not target specific eval criteria.\n- You do NOT have access to scoring rubrics or expected outcomes. Diagnose problems from traces only.\n- Do NOT add over-specified rules that restate existing conventions with stronger emphasis (e.g., changing \"use chalk.green for success\" to \"MUST use chalk.green, no exceptions\"). If a convention already exists, trust it.\n- Do NOT add rules that only apply to a narrow eval scenario (e.g., write permissions for a specific directory just because one task needed it).\n- Ask: \"Would this mutation help a developer working on ANY task in this project?\" If not, don't propose it.\n\nReturn ONLY valid JSON.`;\n\n/** Maximum characters of stdout to include per trace in the prompt. */\nconst STDOUT_TRUNCATION_LIMIT = 1000;\n\n/** Maximum total characters for the proposer user message. */\nconst MAX_CONTEXT_CHARS = 100_000;\n\n/**\n * Recursively read all files in a harness directory.\n *\n * Returns a record mapping relative file paths (e.g. \"commands/develop.md\")\n * to their string contents. Missing or unreadable directories return an\n * empty record.\n */\nexport async function readHarnessFiles(\n harnessPath: string,\n): Promise<Record<string, string>> {\n const result: Record<string, string> = {};\n\n async function walk(dir: string, prefix: string): Promise<void> {\n let entries: import('fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const relativePath = prefix ? path.join(prefix, entry.name) : entry.name;\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await walk(fullPath, relativePath);\n } else if (entry.isFile()) {\n try {\n result[relativePath] = await fs.readFile(fullPath, 'utf-8');\n } catch {\n // Skip unreadable files\n }\n }\n }\n }\n\n await walk(harnessPath, '');\n return result;\n}\n\nfunction truncateStdout(stdout: string, limit: number): string {\n if (stdout.length <= limit) {\n return stdout;\n }\n return `[...truncated, showing last ${limit} chars...]\\n${stdout.slice(-limit)}`;\n}\n\n/**\n * Build the user-facing prompt for the proposer LLM call.\n *\n * Assembles current harness file contents, trace summaries (with truncated\n * stdout), task definitions, and iteration history into a single string.\n */\nexport function buildProposerUserMessage(\n harnessFiles: Record<string, string>,\n traces: Trace[],\n tasks: Task[],\n history: IterationLog[],\n memorySection?: string,\n): string {\n // Priority-based context assembly: harness + tasks are never truncated,\n // traces and history are progressively reduced to fit within budget.\n\n // Section 1: Current harness files (highest priority — never truncated)\n const harnessSection: string[] = ['## Current Harness Files\\n'];\n const fileEntries = Object.entries(harnessFiles);\n if (fileEntries.length === 0) {\n harnessSection.push('(No harness files found)\\n');\n } else {\n for (const [filePath, content] of fileEntries) {\n harnessSection.push(`### ${filePath}\\n\\`\\`\\`\\n${content}\\n\\`\\`\\`\\n`);\n }\n }\n\n // Section 2: Task definitions (description only — rubrics and expected_outcome\n // are intentionally excluded to prevent the proposer from gaming eval criteria)\n const taskSection: string[] = ['## Task Definitions\\n'];\n if (tasks.length === 0) {\n taskSection.push('(No tasks defined)\\n');\n } else {\n for (const task of tasks) {\n taskSection.push(\n `### Task: ${task.id}\\n` +\n `- Template: ${task.template}\\n` +\n `- Description: ${task.description}\\n`,\n );\n }\n }\n\n const fixedContent = harnessSection.join('\\n') + '\\n' + taskSection.join('\\n');\n const remainingBudget = MAX_CONTEXT_CHARS - fixedContent.length;\n\n if (remainingBudget <= 0) {\n return fixedContent + '\\n\\n[...traces and history omitted — harness + tasks fill context budget...]';\n }\n\n // Section 3: Execution traces (medium priority — stdout truncated progressively)\n // Allocate 70% of remaining budget to traces, 30% to history\n const traceBudget = Math.floor(remainingBudget * 0.7);\n const historyBudget = remainingBudget - traceBudget;\n\n const traceSection = buildTraceSection(traces, traceBudget);\n const historySection = buildHistorySection(history, historyBudget);\n\n const memoryPart = memorySection ? '\\n' + memorySection : '';\n return fixedContent + '\\n' + traceSection + '\\n' + historySection + memoryPart;\n}\n\n/**\n * Build the trace section, fitting within the given character budget.\n * Progressively reduces per-trace stdout limit if the section exceeds budget.\n */\nfunction buildTraceSection(traces: Trace[], budget: number): string {\n if (traces.length === 0) return '## Execution Traces\\n\\n(No traces available)\\n';\n\n // Sort traces by score ascending (worst-first) so the proposer focuses on what's broken\n const sortedTraces = [...traces].sort((a, b) => {\n const scoreA = a.score.score ?? (a.score.pass ? 100 : 0);\n const scoreB = b.score.score ?? (b.score.pass ? 100 : 0);\n return scoreA - scoreB;\n });\n\n // Try with default limit, halve stdout limit until it fits\n let stdoutLimit = STDOUT_TRUNCATION_LIMIT;\n for (let attempt = 0; attempt < 4; attempt++) {\n const parts: string[] = ['## Execution Traces (sorted worst-first)\\n'];\n for (const trace of sortedTraces) {\n const scoreNum = trace.score.score !== undefined ? trace.score.score : (trace.score.pass ? 100 : 0);\n const truncatedStdout = truncateStdout(trace.stdout, stdoutLimit);\n const filesChangedList = Object.entries(trace.filesChanged)\n .map(([f, action]) => ` - ${f}: ${action}`)\n .join('\\n');\n\n parts.push(\n `### Trace: ${trace.taskId}\\n` +\n `- Pass: ${trace.score.pass}\\n` +\n `- Score: ${scoreNum}\\n` +\n (trace.score.details ? `- Details: ${trace.score.details}\\n` : '') +\n `- Duration: ${trace.timing.durationMs}ms\\n` +\n `- Files changed:\\n${filesChangedList || ' (none)'}\\n` +\n `- Stdout (last ${stdoutLimit} chars):\\n\\`\\`\\`\\n${truncatedStdout}\\n\\`\\`\\`\\n`,\n );\n }\n const result = parts.join('\\n');\n if (result.length <= budget) return result;\n stdoutLimit = Math.floor(stdoutLimit / 2);\n }\n\n // Final fallback: scores-only summary\n const summary = ['## Execution Traces (summary — stdout omitted to fit budget)\\n'];\n for (const trace of traces) {\n const scoreNum = trace.score.score !== undefined ? trace.score.score : (trace.score.pass ? 100 : 0);\n summary.push(`- ${trace.taskId}: ${scoreNum} (pass=${trace.score.pass})\\n`);\n }\n return summary.join('\\n');\n}\n\n/**\n * Build the history section, fitting within the given character budget.\n * Drops oldest iterations first if it exceeds budget.\n */\nfunction buildHistorySection(history: IterationLog[], budget: number): string {\n if (history.length === 0) return '## Iteration History\\n\\n(No previous iterations)\\n';\n\n // Try with full history, then drop oldest entries until it fits\n let entries = [...history];\n while (entries.length > 0) {\n const parts: string[] = ['## Iteration History\\n'];\n if (entries.length < history.length) {\n parts.push(`(Showing ${entries.length}/${history.length} most recent iterations)\\n`);\n }\n for (const log of entries) {\n const taskScores = Object.entries(log.taskResults)\n .map(([id, s]) => ` - ${id}: ${s.score !== undefined ? s.score : (s.pass ? 100 : 0)} (pass=${s.pass})`)\n .join('\\n');\n\n parts.push(\n `### Iteration ${log.iteration} — Score: ${log.score}\\n` +\n `- Task results:\\n${taskScores}\\n`,\n );\n\n if (log.proposal) {\n parts.push(\n `- Proposal reasoning: ${log.proposal.reasoning}\\n` +\n `- Mutations: ${log.proposal.mutations.length} change(s)\\n`,\n );\n }\n }\n const result = parts.join('\\n');\n if (result.length <= budget) return result;\n entries = entries.slice(1); // drop oldest\n }\n\n return '## Iteration History\\n\\n(History omitted to fit context budget)\\n';\n}\n\n/**\n * Parse a raw LLM response string into a validated Proposal.\n *\n * Strips markdown code fences, extracts JSON, maps snake_case keys\n * (old_text, new_text, expected_impact) to camelCase, and filters out\n * any mutations with path traversal in the file field.\n *\n * @throws Error if the response is not valid JSON or lacks required fields.\n */\nexport function parseProposerResponse(raw: string): Proposal {\n let cleaned = raw.trim();\n\n // Strip markdown code fences (```json ... ``` or ``` ... ```)\n const fenceMatch = cleaned.match(/^```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```$/);\n if (fenceMatch) {\n cleaned = fenceMatch[1].trim();\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(cleaned);\n } catch {\n // Fallback: extract JSON object from prose-wrapped text (first '{' to last '}')\n const firstBrace = cleaned.indexOf('{');\n const lastBrace = cleaned.lastIndexOf('}');\n if (firstBrace !== -1 && lastBrace > firstBrace) {\n const extracted = cleaned.slice(firstBrace, lastBrace + 1);\n try {\n parsed = JSON.parse(extracted);\n } catch {\n throw new Error(`Proposer returned invalid JSON: ${cleaned.slice(0, 200)}`);\n }\n } else {\n throw new Error(`Proposer returned invalid JSON: ${cleaned.slice(0, 200)}`);\n }\n }\n\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('Proposer response is not a JSON object');\n }\n\n const obj = parsed as Record<string, unknown>;\n\n if (typeof obj['reasoning'] !== 'string') {\n throw new Error('Proposer response missing required \"reasoning\" string field');\n }\n\n if (!Array.isArray(obj['mutations'])) {\n throw new Error('Proposer response missing required \"mutations\" array field');\n }\n\n const mutations: Mutation[] = [];\n for (const entry of obj['mutations'] as unknown[]) {\n if (typeof entry !== 'object' || entry === null) {\n continue;\n }\n const m = entry as Record<string, unknown>;\n\n const file = typeof m['file'] === 'string' ? m['file'] : '';\n const action = typeof m['action'] === 'string' ? m['action'] : '';\n const newText = typeof m['new_text'] === 'string'\n ? m['new_text']\n : (typeof m['newText'] === 'string' ? m['newText'] : '');\n const oldText = typeof m['old_text'] === 'string'\n ? m['old_text']\n : (typeof m['oldText'] === 'string' ? m['oldText'] : undefined);\n const rationale = typeof m['rationale'] === 'string' ? m['rationale'] : '';\n\n // Security: reject path traversal\n if (file.includes('..')) {\n continue;\n }\n\n const validActions = new Set(['replace', 'add_section', 'create_file', 'delete_section', 'delete_file']);\n if (!validActions.has(action)) {\n continue;\n }\n\n // For replace and delete_section actions, oldText is required\n if ((action === 'replace' || action === 'delete_section') && !oldText) {\n continue;\n }\n\n const mutation: Mutation = {\n file,\n action: action as Mutation['action'],\n newText,\n rationale,\n };\n\n if (oldText !== undefined) {\n mutation.oldText = oldText;\n }\n\n mutations.push(mutation);\n }\n\n // Parse expectedImpact (accept both snake_case and camelCase)\n const rawImpact = obj['expected_impact'] ?? obj['expectedImpact'] ?? {};\n const expectedImpact: Record<string, string> = {};\n if (typeof rawImpact === 'object' && rawImpact !== null) {\n for (const [key, value] of Object.entries(rawImpact as Record<string, unknown>)) {\n expectedImpact[key] = typeof value === 'string' ? value : String(value);\n }\n }\n\n return {\n reasoning: obj['reasoning'] as string,\n mutations,\n expectedImpact,\n };\n}\n\n/**\n * Run the proposer agent: read harness, load traces, call LLM, return a Proposal.\n *\n * The proposer analyzes execution traces from the current iteration, diagnoses\n * root causes of failures, and proposes minimal mutations to the harness files.\n *\n * @param iteration - Current iteration number\n * @param workspacePath - Path to the .kairn-evolve workspace\n * @param harnessPath - Path to the current harness (.claude/) directory\n * @param history - Logs from previous iterations\n * @param tasks - Task definitions being evaluated\n * @param config - Kairn configuration (for LLM access)\n * @param proposerModel - Model ID to use for the proposer call\n * @returns A validated Proposal with reasoning, mutations, and expected impact\n */\nexport async function propose(\n iteration: number,\n workspacePath: string,\n harnessPath: string,\n history: IterationLog[],\n tasks: Task[],\n config: KairnConfig,\n proposerModel: string,\n): Promise<Proposal> {\n const harnessFiles = await readHarnessFiles(harnessPath);\n const traces = await loadIterationTraces(workspacePath, iteration);\n const { loadProposerMemory, formatMemoryForProposer } = await import('./memory.js');\n const memory = await loadProposerMemory(workspacePath);\n const memorySection = formatMemoryForProposer(memory);\n const userMessage = buildProposerUserMessage(harnessFiles, traces, tasks, history, memorySection);\n\n // Override model with proposer-specific model\n const proposerConfig: KairnConfig = { ...config, model: proposerModel };\n const response = await callLLM(proposerConfig, userMessage, {\n systemPrompt: PROPOSER_SYSTEM_PROMPT,\n maxTokens: 8192,\n jsonMode: true,\n cacheControl: true,\n });\n\n return parseProposerResponse(response);\n}\n","/**\n * Harness IR — Structured intermediate representation for .claude/ directories.\n *\n * This module defines every node type that the parser emits and the emitter consumes.\n * Types are intentionally simple value objects with no behaviour.\n */\n\n// ---------------------------------------------------------------------------\n// Meta\n// ---------------------------------------------------------------------------\n\n/** Top-level metadata extracted from the CLAUDE.md preamble and tech-stack section. */\nexport interface HarnessMeta {\n name: string;\n purpose: string;\n techStack: {\n language: string;\n framework?: string;\n buildTool?: string;\n testRunner?: string;\n packageManager?: string;\n };\n autonomyLevel: 1 | 2 | 3 | 4;\n}\n\n// ---------------------------------------------------------------------------\n// Content nodes\n// ---------------------------------------------------------------------------\n\n/** A heading-delimited section inside CLAUDE.md. */\nexport interface Section {\n id: string;\n heading: string;\n content: string;\n order: number;\n}\n\n/** A file under `.claude/commands/`. */\nexport interface CommandNode {\n name: string;\n description: string;\n content: string;\n}\n\n/** A file under `.claude/rules/` — may carry YAML frontmatter with `paths`. */\nexport interface RuleNode {\n name: string;\n paths?: string[];\n content: string;\n}\n\n/** A file under `.claude/agents/` — may carry YAML frontmatter with `model` / `disallowedTools`. */\nexport interface AgentNode {\n name: string;\n model?: string;\n disallowedTools?: string[];\n modelRouting?: {\n default: 'haiku' | 'sonnet' | 'opus';\n escalateTo?: 'sonnet' | 'opus';\n escalateWhen?: string;\n };\n extraFrontmatter?: Record<string, unknown>; // preserve all other YAML frontmatter fields\n content: string;\n}\n\n/** A file under `.claude/skills/`. */\nexport interface SkillNode {\n name: string;\n content: string;\n}\n\n/** A file under `.claude/docs/`. */\nexport interface DocNode {\n name: string;\n content: string;\n}\n\n/** A file under `.claude/hooks/` (ESM `.mjs`). */\nexport interface HookNode {\n name: string;\n content: string;\n type: \"command\" | \"prompt\";\n}\n\n// ---------------------------------------------------------------------------\n// Settings\n// ---------------------------------------------------------------------------\n\n/** A single hook entry inside `settings.json` hooks map. */\nexport interface HookEntry {\n matcher: string;\n hooks: Array<{\n type: \"command\" | \"prompt\";\n command?: string;\n prompt?: string;\n timeout?: number;\n }>;\n}\n\n/** Parsed representation of `settings.json`. */\nexport interface SettingsIR {\n statusLine?: { command: string };\n hooks: {\n PreToolUse?: HookEntry[];\n PostToolUse?: HookEntry[];\n UserPromptSubmit?: HookEntry[];\n SessionStart?: HookEntry[];\n PostCompact?: HookEntry[];\n };\n denyPatterns?: string[];\n raw: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// MCP\n// ---------------------------------------------------------------------------\n\n/** An MCP server declaration from `.mcp.json`. */\nexport interface McpServerNode {\n id: string;\n command: string;\n args: string[];\n env?: Record<string, string>;\n}\n\n// ---------------------------------------------------------------------------\n// Intent\n// ---------------------------------------------------------------------------\n\n/** Maps natural-language patterns to slash-commands for intent routing. */\nexport interface IntentNode {\n commandName: string;\n patterns: string[];\n priority: number;\n}\n\n// ---------------------------------------------------------------------------\n// Root IR\n// ---------------------------------------------------------------------------\n\n/** The complete intermediate representation of a `.claude/` harness directory. */\nexport interface HarnessIR {\n meta: HarnessMeta;\n sections: Section[];\n commands: CommandNode[];\n rules: RuleNode[];\n agents: AgentNode[];\n skills: SkillNode[];\n docs: DocNode[];\n hooks: HookNode[];\n settings: SettingsIR;\n mcpServers: McpServerNode[];\n intents: IntentNode[];\n}\n\n// ---------------------------------------------------------------------------\n// Factory helpers\n// ---------------------------------------------------------------------------\n\n/** Create a HarnessIR with all fields set to safe defaults. */\nexport function createEmptyIR(): HarnessIR {\n return {\n meta: {\n name: \"\",\n purpose: \"\",\n techStack: { language: \"\" },\n autonomyLevel: 2,\n },\n sections: [],\n commands: [],\n rules: [],\n agents: [],\n skills: [],\n docs: [],\n hooks: [],\n settings: createEmptySettings(),\n mcpServers: [],\n intents: [],\n };\n}\n\n/** Create a SettingsIR with all fields set to safe defaults. */\nexport function createEmptySettings(): SettingsIR {\n return { hooks: {}, raw: {} };\n}\n\n/** Convenience factory for Section nodes. */\nexport function createSection(\n id: string,\n heading: string,\n content: string,\n order: number,\n): Section {\n return { id, heading, content, order };\n}\n\n/** Convenience factory for CommandNode with an optional description (defaults to empty string). */\nexport function createCommandNode(\n name: string,\n content: string,\n description?: string,\n): CommandNode {\n return { name, description: description ?? \"\", content };\n}\n\n/** Convenience factory for RuleNode with optional path scoping. */\nexport function createRuleNode(\n name: string,\n content: string,\n paths?: string[],\n): RuleNode {\n const node: RuleNode = { name, content };\n if (paths !== undefined) {\n node.paths = paths;\n }\n return node;\n}\n\n/** Convenience factory for AgentNode with optional model hint. */\nexport function createAgentNode(\n name: string,\n content: string,\n model?: string,\n): AgentNode {\n const node: AgentNode = { name, content };\n if (model !== undefined) {\n node.model = model;\n }\n return node;\n}\n\n// ---------------------------------------------------------------------------\n// Mutation types\n// ---------------------------------------------------------------------------\n\n/** Discriminated union of all possible IR mutations. */\nexport type IRMutation =\n | { type: \"update_section\"; sectionId: string; content: string; rationale: string }\n | { type: \"add_section\"; section: Section; rationale: string }\n | { type: \"remove_section\"; sectionId: string; rationale: string }\n | { type: \"reorder_section\"; sectionId: string; newOrder: number; rationale: string }\n | { type: \"add_command\"; command: CommandNode; rationale: string }\n | { type: \"update_command\"; name: string; content: string; rationale: string }\n | { type: \"remove_command\"; name: string; rationale: string }\n | { type: \"add_rule\"; rule: RuleNode; rationale: string }\n | { type: \"update_rule\"; name: string; content: string; rationale: string }\n | { type: \"remove_rule\"; name: string; rationale: string }\n | { type: \"add_agent\"; agent: AgentNode; rationale: string }\n | { type: \"update_agent\"; name: string; changes: Partial<AgentNode>; rationale: string }\n | { type: \"remove_agent\"; name: string; rationale: string }\n | { type: \"add_mcp_server\"; server: McpServerNode; rationale: string }\n | { type: \"remove_mcp_server\"; id: string; rationale: string }\n | { type: \"update_settings\"; path: string; value: unknown; rationale: string }\n | {\n type: \"raw_text\";\n file: string;\n action: \"replace\" | \"add_section\" | \"create_file\" | \"delete_section\" | \"delete_file\";\n oldText?: string;\n newText: string;\n rationale: string;\n };\n\n// ---------------------------------------------------------------------------\n// Diff types\n// ---------------------------------------------------------------------------\n\n/** Structural diff between two HarnessIR snapshots. */\nexport interface IRDiff {\n sections: {\n added: Section[];\n removed: Section[];\n modified: Array<{ id: string; before: string; after: string }>;\n reordered: Array<{ id: string; oldOrder: number; newOrder: number }>;\n };\n commands: {\n added: CommandNode[];\n removed: string[];\n modified: Array<{ name: string; before: string; after: string }>;\n };\n rules: {\n added: RuleNode[];\n removed: string[];\n modified: Array<{ name: string; before: string; after: string }>;\n };\n agents: {\n added: AgentNode[];\n removed: string[];\n modified: Array<{ name: string; changes: string }>;\n };\n mcpServers: {\n added: McpServerNode[];\n removed: string[];\n };\n settings: {\n changes: Array<{ path: string; before: unknown; after: unknown }>;\n };\n}\n\n/** Create an empty IRDiff with all collections empty. */\nexport function createEmptyDiff(): IRDiff {\n return {\n sections: {\n added: [],\n removed: [],\n modified: [],\n reordered: [],\n },\n commands: {\n added: [],\n removed: [],\n modified: [],\n },\n rules: {\n added: [],\n removed: [],\n modified: [],\n },\n agents: {\n added: [],\n removed: [],\n modified: [],\n },\n mcpServers: {\n added: [],\n removed: [],\n },\n settings: {\n changes: [],\n },\n };\n}\n","/**\n * Harness Parser — reads a `.claude/` directory and produces a HarnessIR.\n *\n * All file I/O uses `fs.promises`. Missing directories/files are handled\n * gracefully (empty arrays, empty strings) rather than throwing.\n */\n\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type {\n HarnessIR,\n HarnessMeta,\n Section,\n CommandNode,\n RuleNode,\n AgentNode,\n SkillNode,\n DocNode,\n HookNode,\n McpServerNode,\n SettingsIR,\n HookEntry,\n} from \"./types.js\";\nimport { createEmptyIR, createEmptySettings } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Section ID mapping\n// ---------------------------------------------------------------------------\n\n/** Maps heading keywords to well-known section IDs. */\nconst SECTION_ID_MAP: Array<{ pattern: RegExp; id: string }> = [\n { pattern: /^(purpose|about|what)\\b/i, id: \"purpose\" },\n { pattern: /^(tech\\s*stack|technology|stack)\\b/i, id: \"tech-stack\" },\n { pattern: /^(commands|key\\s*commands)\\b/i, id: \"commands\" },\n { pattern: /^architecture\\b/i, id: \"architecture\" },\n { pattern: /^conventions?\\b/i, id: \"conventions\" },\n { pattern: /^verification\\b/i, id: \"verification\" },\n { pattern: /^(known\\s*gotchas|gotchas)\\b/i, id: \"gotchas\" },\n { pattern: /^output\\b/i, id: \"output\" },\n { pattern: /^debugging\\b/i, id: \"debugging\" },\n { pattern: /^git\\b/i, id: \"git\" },\n];\n\n/**\n * Slugify a heading into a CSS-style ID: lowercase, spaces to hyphens,\n * strip anything that isn't alphanumeric or hyphen.\n */\nfunction slugify(heading: string): string {\n return heading\n .toLowerCase()\n .trim()\n .replace(/\\s+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n/** Resolve a heading string to a well-known section ID or a custom-* slug. */\nexport function resolveSectionId(heading: string): string {\n const trimmed = heading.trim();\n for (const entry of SECTION_ID_MAP) {\n if (entry.pattern.test(trimmed)) {\n return entry.id;\n }\n }\n return `custom-${slugify(trimmed)}`;\n}\n\n// ---------------------------------------------------------------------------\n// parseYamlFrontmatter\n// ---------------------------------------------------------------------------\n\n/**\n * Extract simple YAML frontmatter delimited by `---` lines.\n *\n * Handles:\n * - `key: value` pairs (string values)\n * - `key:` followed by indented ` - item` list items (arrays)\n * - Quoted values have their quotes stripped\n *\n * Does **not** depend on an external YAML library.\n */\nexport function parseYamlFrontmatter(content: string): {\n frontmatter: Record<string, unknown>;\n body: string;\n} {\n if (!content.startsWith(\"---\\n\") && !content.startsWith(\"---\\r\\n\")) {\n return { frontmatter: {}, body: content };\n }\n\n // Find the closing ---\n const secondDash = content.indexOf(\"\\n---\", 3);\n if (secondDash === -1) {\n return { frontmatter: {}, body: content };\n }\n\n const yamlBlock = content.slice(4, secondDash); // skip opening \"---\\n\"\n const afterClose = secondDash + 4; // skip \"\\n---\"\n const body = content.slice(afterClose).replace(/^\\r?\\n/, \"\");\n\n const frontmatter: Record<string, unknown> = {};\n const lines = yamlBlock.split(\"\\n\");\n\n let currentKey: string | null = null;\n let currentList: string[] | null = null;\n\n for (const line of lines) {\n const trimmed = line.trimEnd();\n\n // List item under the current key\n if (currentKey !== null && /^\\s+-\\s+/.test(trimmed)) {\n if (currentList === null) {\n currentList = [];\n }\n let value = trimmed.replace(/^\\s+-\\s+/, \"\").trim();\n // Strip surrounding quotes\n value = stripQuotes(value);\n currentList.push(value);\n continue;\n }\n\n // Flush any pending list\n if (currentKey !== null && currentList !== null) {\n frontmatter[currentKey] = currentList;\n currentKey = null;\n currentList = null;\n }\n\n // key: value pair\n const colonIdx = trimmed.indexOf(\":\");\n if (colonIdx > 0) {\n const key = trimmed.slice(0, colonIdx).trim();\n const rawValue = trimmed.slice(colonIdx + 1).trim();\n\n if (rawValue === \"\") {\n // Could be the start of a list\n currentKey = key;\n currentList = null;\n } else {\n frontmatter[key] = stripQuotes(rawValue);\n currentKey = null;\n currentList = null;\n }\n }\n }\n\n // Flush final pending list\n if (currentKey !== null && currentList !== null) {\n frontmatter[currentKey] = currentList;\n }\n\n return { frontmatter, body };\n}\n\n/** Remove surrounding single or double quotes from a string value. */\nfunction stripQuotes(value: string): string {\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n return value.slice(1, -1);\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// parseClaudeMd\n// ---------------------------------------------------------------------------\n\n/**\n * Parse the content of a CLAUDE.md file into partial metadata and sections.\n *\n * Splits on `## ` boundaries. The chunk before the first `## ` becomes the\n * preamble section. Each subsequent chunk is assigned a well-known or custom\n * section ID based on its heading text.\n */\nexport function parseClaudeMd(content: string): {\n meta: Partial<HarnessMeta>;\n sections: Section[];\n} {\n const meta: Partial<HarnessMeta> = {\n techStack: { language: \"\" },\n autonomyLevel: 2,\n };\n const sections: Section[] = [];\n\n // Split on ## boundaries (keeping the delimiter for all but the first chunk)\n const chunks = content.split(/^## /gm);\n\n // First chunk is the preamble (everything before the first ## )\n const preamble = chunks[0];\n\n // Extract name from `# Title` line\n const titleMatch = preamble.match(/^# (.+)$/m);\n if (titleMatch) {\n meta.name = titleMatch[1].trim();\n } else {\n meta.name = \"\";\n }\n\n // Build preamble section\n const preambleHeading = meta.name ? `# ${meta.name}` : \"\";\n // Content is everything after the title line (if any)\n const preambleContent = titleMatch\n ? preamble.slice(preamble.indexOf(titleMatch[0]) + titleMatch[0].length).trim()\n : preamble.trim();\n\n sections.push({\n id: \"preamble\",\n heading: preambleHeading,\n content: preambleContent,\n order: 0,\n });\n\n // Process each ## section\n for (let i = 1; i < chunks.length; i++) {\n const chunk = chunks[i];\n const newlineIdx = chunk.indexOf(\"\\n\");\n const heading =\n newlineIdx >= 0 ? chunk.slice(0, newlineIdx).trim() : chunk.trim();\n const sectionContent =\n newlineIdx >= 0 ? chunk.slice(newlineIdx + 1).trim() : \"\";\n\n const sectionId = resolveSectionId(heading);\n\n sections.push({\n id: sectionId,\n heading: `## ${heading}`,\n content: sectionContent,\n order: i,\n });\n\n // Extract purpose from purpose section (first paragraph only)\n if (sectionId === \"purpose\") {\n const firstParagraph = sectionContent.split(/\\n\\n/)[0].trim();\n meta.purpose = firstParagraph;\n }\n\n // Extract tech stack from tech-stack section\n if (sectionId === \"tech-stack\") {\n meta.techStack = extractTechStack(sectionContent);\n }\n }\n\n return { meta, sections };\n}\n\n/**\n * Extract technology details from bullet-point content in a Tech Stack section.\n */\nfunction extractTechStack(content: string): HarnessMeta[\"techStack\"] {\n const stack: HarnessMeta[\"techStack\"] = { language: \"\" };\n const lines = content.split(\"\\n\");\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"-\")) continue;\n const bullet = trimmed.slice(1).trim().toLowerCase();\n\n // Language detection\n if (\n !stack.language &&\n (bullet.includes(\"typescript\") || bullet.includes(\"javascript\"))\n ) {\n stack.language = bullet.includes(\"typescript\")\n ? \"TypeScript\"\n : \"JavaScript\";\n } else if (!stack.language && bullet.includes(\"python\")) {\n stack.language = \"Python\";\n } else if (!stack.language && bullet.includes(\"rust\")) {\n stack.language = \"Rust\";\n } else if (!stack.language && bullet.includes(\"go \") || !stack.language && bullet.startsWith(\"go,\")) {\n stack.language = \"Go\";\n }\n\n // Build tool detection\n if (!stack.buildTool) {\n const buildTools = [\n \"tsup\", \"webpack\", \"vite\", \"esbuild\", \"rollup\", \"parcel\",\n \"turbopack\", \"swc\", \"cargo\", \"make\", \"cmake\",\n ];\n for (const tool of buildTools) {\n if (bullet.includes(tool)) {\n stack.buildTool = tool;\n break;\n }\n }\n }\n\n // Test runner detection\n if (!stack.testRunner) {\n const testRunners = [\n \"vitest\", \"jest\", \"mocha\", \"ava\", \"tap\", \"pytest\", \"cargo test\",\n ];\n for (const runner of testRunners) {\n if (bullet.includes(runner)) {\n stack.testRunner = runner;\n break;\n }\n }\n }\n\n // Framework detection\n if (!stack.framework) {\n const frameworks = [\n \"commander.js\", \"commander\", \"express\", \"fastify\", \"next.js\",\n \"nextjs\", \"react\", \"vue\", \"angular\", \"svelte\", \"django\", \"flask\",\n \"actix\", \"axum\",\n ];\n for (const fw of frameworks) {\n if (bullet.includes(fw)) {\n // Normalize: \"commander.js\" → \"Commander.js\"\n stack.framework =\n fw.charAt(0).toUpperCase() + fw.slice(1);\n break;\n }\n }\n }\n\n // Package manager detection\n if (!stack.packageManager) {\n const pkgManagers = [\"pnpm\", \"yarn\", \"bun\", \"npm\", \"cargo\", \"pip\"];\n for (const pm of pkgManagers) {\n if (bullet.includes(`${pm} `)) {\n stack.packageManager = pm;\n break;\n }\n }\n }\n }\n\n return stack;\n}\n\n// ---------------------------------------------------------------------------\n// parseSettings\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a `settings.json` string into a SettingsIR.\n *\n * Extracts:\n * - `permissions.deny` → `denyPatterns`\n * - `hooks.*` → typed hook entries\n * - `statusLine` → status line config\n * - Everything else → `raw`\n */\nexport function parseSettings(content: string): SettingsIR {\n const parsed = JSON.parse(content) as Record<string, unknown>;\n const settings = createEmptySettings();\n\n // Extract deny patterns\n const permissions = parsed[\"permissions\"] as\n | Record<string, unknown>\n | undefined;\n if (permissions) {\n const deny = permissions[\"deny\"];\n if (Array.isArray(deny) && deny.length > 0) {\n settings.denyPatterns = deny as string[];\n }\n }\n\n // Extract status line\n const statusLine = parsed[\"statusLine\"] as\n | { command: string }\n | undefined;\n if (statusLine && typeof statusLine.command === \"string\") {\n settings.statusLine = { command: statusLine.command };\n }\n\n // Extract hooks\n const hooksRaw = parsed[\"hooks\"] as Record<string, unknown> | undefined;\n if (hooksRaw && typeof hooksRaw === \"object\") {\n const knownEvents = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"UserPromptSubmit\",\n \"SessionStart\",\n \"PostCompact\",\n ] as const;\n\n for (const event of knownEvents) {\n const entries = hooksRaw[event];\n if (Array.isArray(entries) && entries.length > 0) {\n settings.hooks[event] = entries as HookEntry[];\n }\n }\n }\n\n // Put everything into raw (excluding already-extracted top-level keys)\n const extractedKeys = new Set([\"permissions\", \"hooks\", \"statusLine\"]);\n for (const [key, value] of Object.entries(parsed)) {\n if (!extractedKeys.has(key)) {\n settings.raw[key] = value;\n }\n }\n\n return settings;\n}\n\n// ---------------------------------------------------------------------------\n// parseMcpConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a `.mcp.json` string into an array of McpServerNode.\n *\n * Each key in the `mcpServers` object becomes a node with `id` = key.\n */\nexport function parseMcpConfig(content: string): McpServerNode[] {\n const parsed = JSON.parse(content) as Record<string, unknown>;\n const servers = parsed[\"mcpServers\"] as\n | Record<string, Record<string, unknown>>\n | undefined;\n\n if (!servers || typeof servers !== \"object\") {\n return [];\n }\n\n const nodes: McpServerNode[] = [];\n\n for (const [id, config] of Object.entries(servers)) {\n const command = config[\"command\"] as string;\n const args = (config[\"args\"] as string[]) ?? [];\n const env = config[\"env\"] as Record<string, string> | undefined;\n\n const node: McpServerNode = { id, command, args };\n\n // Only include env if it's a non-empty object\n if (env && typeof env === \"object\" && Object.keys(env).length > 0) {\n node.env = env;\n }\n\n nodes.push(node);\n }\n\n return nodes;\n}\n\n// ---------------------------------------------------------------------------\n// Directory reading helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Safely read a directory, returning an empty array if it doesn't exist.\n */\nasync function readDirSafe(dirPath: string): Promise<string[]> {\n try {\n return await fs.readdir(dirPath);\n } catch {\n return [];\n }\n}\n\n/**\n * Safely read a file, returning null if it doesn't exist.\n */\nasync function readFileSafe(filePath: string): Promise<string | null> {\n try {\n return await fs.readFile(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\n/**\n * Safely check whether a path is a directory.\n */\nasync function isDirectory(filePath: string): Promise<boolean> {\n try {\n const stat = await fs.stat(filePath);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Sub-parsers for harness subdirectories\n// ---------------------------------------------------------------------------\n\n/** Read `commands/*.md` files into CommandNode[]. */\nasync function parseCommands(harnessPath: string): Promise<CommandNode[]> {\n const dirPath = path.join(harnessPath, \"commands\");\n const entries = await readDirSafe(dirPath);\n const nodes: CommandNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const content = await readFileSafe(filePath);\n if (content === null) continue;\n\n const name = entry.replace(/\\.md$/, \"\");\n const firstLine = content.split(\"\\n\")[0].trim();\n // Use first line as description if it's not a heading or code block\n const description =\n firstLine && !firstLine.startsWith(\"#\") && !firstLine.startsWith(\"```\")\n ? firstLine\n : \"\";\n\n nodes.push({ name, description, content });\n }\n\n return nodes;\n}\n\n/** Read `rules/*.md` files into RuleNode[], parsing YAML frontmatter for `paths`. */\nasync function parseRules(harnessPath: string): Promise<RuleNode[]> {\n const dirPath = path.join(harnessPath, \"rules\");\n const entries = await readDirSafe(dirPath);\n const nodes: RuleNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const rawContent = await readFileSafe(filePath);\n if (rawContent === null) continue;\n\n const name = entry.replace(/\\.md$/, \"\");\n const { frontmatter, body } = parseYamlFrontmatter(rawContent);\n\n const node: RuleNode = { name, content: body };\n\n const paths = frontmatter[\"paths\"];\n if (Array.isArray(paths) && paths.length > 0) {\n node.paths = paths as string[];\n }\n\n nodes.push(node);\n }\n\n return nodes;\n}\n\n/** Read `agents/*.md` files into AgentNode[], parsing YAML frontmatter for `model` and `disallowedTools`. */\nasync function parseAgents(harnessPath: string): Promise<AgentNode[]> {\n const dirPath = path.join(harnessPath, \"agents\");\n const entries = await readDirSafe(dirPath);\n const nodes: AgentNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const rawContent = await readFileSafe(filePath);\n if (rawContent === null) continue;\n\n const fileBaseName = entry.replace(/\\.md$/, \"\");\n const { frontmatter, body } = parseYamlFrontmatter(rawContent);\n\n // Use frontmatter name if present, otherwise file name\n const name =\n typeof frontmatter[\"name\"] === \"string\"\n ? frontmatter[\"name\"]\n : fileBaseName;\n\n const node: AgentNode = { name, content: body };\n\n if (typeof frontmatter[\"model\"] === \"string\") {\n node.model = frontmatter[\"model\"];\n }\n\n const disallowedTools = frontmatter[\"disallowedTools\"];\n if (Array.isArray(disallowedTools)) {\n node.disallowedTools = disallowedTools as string[];\n }\n\n // Parse modelRouting if present\n const modelRouting = frontmatter[\"modelRouting\"];\n if (typeof modelRouting === \"object\" && modelRouting !== null) {\n const mr = modelRouting as Record<string, unknown>;\n if (typeof mr[\"default\"] === \"string\") {\n node.modelRouting = {\n default: mr[\"default\"] as 'haiku' | 'sonnet' | 'opus',\n };\n if (typeof mr[\"escalateTo\"] === \"string\") {\n node.modelRouting.escalateTo = mr[\"escalateTo\"] as 'sonnet' | 'opus';\n }\n if (typeof mr[\"escalateWhen\"] === \"string\") {\n node.modelRouting.escalateWhen = mr[\"escalateWhen\"];\n }\n }\n }\n\n // Preserve all other frontmatter fields not already handled\n const knownKeys = new Set([\"name\", \"model\", \"disallowedTools\", \"modelRouting\"]);\n const extra: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(frontmatter)) {\n if (!knownKeys.has(key)) {\n extra[key] = value;\n }\n }\n if (Object.keys(extra).length > 0) {\n node.extraFrontmatter = extra;\n }\n\n nodes.push(node);\n }\n\n return nodes;\n}\n\n/**\n * Read `skills/` directory into SkillNode[].\n *\n * Skills can be either:\n * - A direct `.md` file: `skills/tdd.md`\n * - A directory with a `skill.md` inside: `skills/tdd/skill.md`\n */\nasync function parseSkills(harnessPath: string): Promise<SkillNode[]> {\n const dirPath = path.join(harnessPath, \"skills\");\n const entries = await readDirSafe(dirPath);\n const nodes: SkillNode[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry);\n\n if (entry.endsWith(\".md\")) {\n // Direct file\n const content = await readFileSafe(entryPath);\n if (content === null) continue;\n const name = entry.replace(/\\.md$/, \"\");\n nodes.push({ name, content });\n } else if (await isDirectory(entryPath)) {\n // Directory — look for skill.md or SKILL.md inside (case-insensitive)\n let content = await readFileSafe(path.join(entryPath, \"skill.md\"));\n if (content === null) {\n content = await readFileSafe(path.join(entryPath, \"SKILL.md\"));\n }\n if (content === null) continue;\n nodes.push({ name: entry, content });\n }\n }\n\n return nodes;\n}\n\n/** Read `docs/*.md` files into DocNode[]. */\nasync function parseDocs(harnessPath: string): Promise<DocNode[]> {\n const dirPath = path.join(harnessPath, \"docs\");\n const entries = await readDirSafe(dirPath);\n const nodes: DocNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const content = await readFileSafe(filePath);\n if (content === null) continue;\n\n const name = entry.replace(/\\.md$/, \"\");\n nodes.push({ name, content });\n }\n\n return nodes;\n}\n\n/** Read `hooks/*.mjs` files into HookNode[]. */\nasync function parseHooks(harnessPath: string): Promise<HookNode[]> {\n const dirPath = path.join(harnessPath, \"hooks\");\n const entries = await readDirSafe(dirPath);\n const nodes: HookNode[] = [];\n\n for (const entry of entries) {\n if (!entry.endsWith(\".mjs\")) continue;\n\n const filePath = path.join(dirPath, entry);\n const content = await readFileSafe(filePath);\n if (content === null) continue;\n\n const name = entry.replace(/\\.mjs$/, \"\");\n nodes.push({ name, content, type: \"command\" });\n }\n\n return nodes;\n}\n\n// ---------------------------------------------------------------------------\n// parseHarness — main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Read an entire `.claude/` directory (or compatible harness directory) and\n * produce a complete HarnessIR.\n *\n * Missing files/directories are handled gracefully — the resulting IR simply\n * has empty arrays/strings for the missing parts.\n *\n * @param harnessPath - Absolute path to the `.claude/` directory.\n */\nexport async function parseHarness(harnessPath: string): Promise<HarnessIR> {\n const ir = createEmptyIR();\n\n // 1. Parse CLAUDE.md\n const claudeMdContent = await readFileSafe(\n path.join(harnessPath, \"CLAUDE.md\"),\n );\n if (claudeMdContent !== null) {\n const { meta, sections } = parseClaudeMd(claudeMdContent);\n ir.meta = {\n ...ir.meta,\n ...meta,\n techStack: { ...ir.meta.techStack, ...meta.techStack },\n };\n ir.sections = sections;\n }\n\n // 2. Parse settings.json\n const settingsContent = await readFileSafe(\n path.join(harnessPath, \"settings.json\"),\n );\n if (settingsContent !== null) {\n ir.settings = parseSettings(settingsContent);\n }\n\n // 3. Parse subdirectories in parallel\n const [commands, rules, agents, skills, docs, hooks] = await Promise.all([\n parseCommands(harnessPath),\n parseRules(harnessPath),\n parseAgents(harnessPath),\n parseSkills(harnessPath),\n parseDocs(harnessPath),\n parseHooks(harnessPath),\n ]);\n\n ir.commands = commands;\n ir.rules = rules;\n ir.agents = agents;\n ir.skills = skills;\n ir.docs = docs;\n ir.hooks = hooks;\n\n // 4. Parse .mcp.json — check both parent directory and harness directory itself\n const mcpServers: McpServerNode[] = [];\n const seenIds = new Set<string>();\n\n // Check parent directory (standard location: project root has .mcp.json, .claude/ is the harness)\n const parentMcpPath = path.join(path.dirname(harnessPath), \".mcp.json\");\n const parentMcpContent = await readFileSafe(parentMcpPath);\n if (parentMcpContent !== null) {\n for (const node of parseMcpConfig(parentMcpContent)) {\n if (!seenIds.has(node.id)) {\n seenIds.add(node.id);\n mcpServers.push(node);\n }\n }\n }\n\n // Check inside the harness directory itself (evolution may copy it here)\n const innerMcpPath = path.join(harnessPath, \".mcp.json\");\n const innerMcpContent = await readFileSafe(innerMcpPath);\n if (innerMcpContent !== null) {\n for (const node of parseMcpConfig(innerMcpContent)) {\n if (!seenIds.has(node.id)) {\n seenIds.add(node.id);\n mcpServers.push(node);\n }\n }\n }\n\n ir.mcpServers = mcpServers;\n\n return ir;\n}\n","/**\n * Legacy Mutation Translator — converts evolve-era `Mutation` objects into\n * structured `IRMutation` values that the IR mutation engine can apply.\n *\n * This bridge allows the existing proposer (which emits file-level text mutations)\n * to target the structured IR without rewriting the proposer prompt.\n */\n\nimport type { HarnessIR, IRMutation } from \"./types.js\";\nimport type { Mutation } from \"../evolve/types.js\";\nimport {\n createSection,\n createCommandNode,\n createRuleNode,\n createAgentNode,\n} from \"./types.js\";\nimport { resolveSectionId } from \"./parser.js\";\n\n// ---------------------------------------------------------------------------\n// Path matching helpers\n// ---------------------------------------------------------------------------\n\n/** Regex for paths targeting command files: `commands/X.md` or `commands/X`. */\nconst COMMANDS_PATH_RE = /^commands\\/([^/]+?)(?:\\.md)?$/;\n\n/** Regex for paths targeting rule files: `rules/X.md` or `rules/X`. */\nconst RULES_PATH_RE = /^rules\\/([^/]+?)(?:\\.md)?$/;\n\n/** Regex for paths targeting agent files: `agents/X.md` or `agents/X`. */\nconst AGENTS_PATH_RE = /^agents\\/([^/]+?)(?:\\.md)?$/;\n\n/**\n * Extract a name from a file path using the given regex.\n * Returns the first capture group (the bare file name) or `null` if no match.\n */\nfunction extractName(filePath: string, pattern: RegExp): string | null {\n const match = filePath.match(pattern);\n return match ? match[1] : null;\n}\n\n// ---------------------------------------------------------------------------\n// Section search helper\n// ---------------------------------------------------------------------------\n\n/**\n * Find the first section whose `content` includes the given text.\n * Returns the section or `undefined` if not found.\n */\nfunction findSectionContaining(\n ir: HarnessIR,\n text: string,\n): HarnessIR[\"sections\"][number] | undefined {\n return ir.sections.find((s) => s.content.includes(text));\n}\n\n// ---------------------------------------------------------------------------\n// CLAUDE.md translation\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a mutation targeting `CLAUDE.md` into a structured IR mutation.\n */\nfunction translateClaudeMdMutation(\n mutation: Mutation,\n ir: HarnessIR,\n): IRMutation {\n switch (mutation.action) {\n case \"replace\": {\n if (mutation.oldText === undefined) {\n return buildRawText(mutation);\n }\n const section = findSectionContaining(ir, mutation.oldText);\n if (!section) {\n return buildRawText(mutation);\n }\n return {\n type: \"update_section\",\n sectionId: section.id,\n content: section.content.replace(mutation.oldText, mutation.newText),\n rationale: mutation.rationale,\n };\n }\n\n case \"add_section\": {\n const headingMatch = mutation.newText.match(/^## (.+)/);\n if (!headingMatch) {\n return buildRawText(mutation);\n }\n const headingText = headingMatch[1].trim();\n const sectionId = resolveSectionId(headingText);\n const heading = `## ${headingText}`;\n\n // Content is everything after the heading line\n const newlineIdx = mutation.newText.indexOf(\"\\n\");\n const content =\n newlineIdx >= 0 ? mutation.newText.slice(newlineIdx + 1).trim() : \"\";\n\n const nextOrder = ir.sections.length;\n\n return {\n type: \"add_section\",\n section: createSection(sectionId, heading, content, nextOrder),\n rationale: mutation.rationale,\n };\n }\n\n case \"delete_section\": {\n if (mutation.oldText === undefined) {\n return buildRawText(mutation);\n }\n const section = findSectionContaining(ir, mutation.oldText);\n if (!section) {\n return buildRawText(mutation);\n }\n return {\n type: \"remove_section\",\n sectionId: section.id,\n rationale: mutation.rationale,\n };\n }\n\n default:\n return buildRawText(mutation);\n }\n}\n\n// ---------------------------------------------------------------------------\n// commands/ translation\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a mutation targeting a `commands/*.md` file into a structured IR mutation.\n */\nfunction translateCommandMutation(\n mutation: Mutation,\n name: string,\n): IRMutation {\n switch (mutation.action) {\n case \"create_file\":\n return {\n type: \"add_command\",\n command: createCommandNode(name, mutation.newText),\n rationale: mutation.rationale,\n };\n\n case \"delete_file\":\n return {\n type: \"remove_command\",\n name,\n rationale: mutation.rationale,\n };\n\n case \"replace\":\n return {\n type: \"update_command\",\n name,\n content: mutation.newText,\n rationale: mutation.rationale,\n };\n\n default:\n return buildRawText(mutation);\n }\n}\n\n// ---------------------------------------------------------------------------\n// rules/ translation\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a mutation targeting a `rules/*.md` file into a structured IR mutation.\n */\nfunction translateRuleMutation(\n mutation: Mutation,\n name: string,\n): IRMutation {\n switch (mutation.action) {\n case \"create_file\":\n return {\n type: \"add_rule\",\n rule: createRuleNode(name, mutation.newText),\n rationale: mutation.rationale,\n };\n\n case \"delete_file\":\n return {\n type: \"remove_rule\",\n name,\n rationale: mutation.rationale,\n };\n\n case \"replace\":\n return {\n type: \"update_rule\",\n name,\n content: mutation.newText,\n rationale: mutation.rationale,\n };\n\n default:\n return buildRawText(mutation);\n }\n}\n\n// ---------------------------------------------------------------------------\n// agents/ translation\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a mutation targeting an `agents/*.md` file into a structured IR mutation.\n */\nfunction translateAgentMutation(\n mutation: Mutation,\n name: string,\n): IRMutation {\n switch (mutation.action) {\n case \"create_file\":\n return {\n type: \"add_agent\",\n agent: createAgentNode(name, mutation.newText),\n rationale: mutation.rationale,\n };\n\n case \"delete_file\":\n return {\n type: \"remove_agent\",\n name,\n rationale: mutation.rationale,\n };\n\n case \"replace\":\n return {\n type: \"update_agent\",\n name,\n changes: { content: mutation.newText },\n rationale: mutation.rationale,\n };\n\n default:\n return buildRawText(mutation);\n }\n}\n\n// ---------------------------------------------------------------------------\n// raw_text fallback builder\n// ---------------------------------------------------------------------------\n\n/** Build a `raw_text` IRMutation from a legacy Mutation (passthrough). */\nfunction buildRawText(mutation: Mutation): IRMutation {\n return {\n type: \"raw_text\",\n file: mutation.file,\n action: mutation.action,\n oldText: mutation.oldText,\n newText: mutation.newText,\n rationale: mutation.rationale,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Translate a single legacy `Mutation` (file-level text operation) into a\n * structured `IRMutation` by inspecting the file path and action.\n *\n * The IR is used to look up which section contains text being replaced.\n *\n * @param mutation - A legacy evolve-era Mutation.\n * @param ir - The current HarnessIR state (used for section lookups).\n * @returns The equivalent structured IRMutation.\n */\nexport function translateMutation(mutation: Mutation, ir: HarnessIR): IRMutation {\n // CLAUDE.md mutations\n if (mutation.file === \"CLAUDE.md\") {\n return translateClaudeMdMutation(mutation, ir);\n }\n\n // commands/*.md mutations\n const commandName = extractName(mutation.file, COMMANDS_PATH_RE);\n if (commandName !== null) {\n return translateCommandMutation(mutation, commandName);\n }\n\n // rules/*.md mutations\n const ruleName = extractName(mutation.file, RULES_PATH_RE);\n if (ruleName !== null) {\n return translateRuleMutation(mutation, ruleName);\n }\n\n // agents/*.md mutations\n const agentName = extractName(mutation.file, AGENTS_PATH_RE);\n if (agentName !== null) {\n return translateAgentMutation(mutation, agentName);\n }\n\n // Fallback: anything else becomes a raw_text passthrough\n return buildRawText(mutation);\n}\n\n/**\n * Translate an array of legacy `Mutation` values into structured `IRMutation` values.\n *\n * @param mutations - Array of legacy Mutations.\n * @param ir - The current HarnessIR state.\n * @returns Array of equivalent IRMutations, in the same order.\n */\nexport function translateMutations(mutations: Mutation[], ir: HarnessIR): IRMutation[] {\n return mutations.map((m) => translateMutation(m, ir));\n}\n","/**\n * IR Mutation Engine — Immutable transformations on HarnessIR.\n *\n * Every `applyIRMutation` call returns a **new** HarnessIR; the input is never mutated.\n * `validateIRMutation` checks pre-conditions without side-effects.\n */\n\nimport type {\n HarnessIR,\n IRMutation,\n SettingsIR,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Validation result\n// ---------------------------------------------------------------------------\n\n/** Result of a pre-condition check on a mutation. */\nexport interface ValidationResult {\n valid: boolean;\n reason?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Internal lookup helpers\n// ---------------------------------------------------------------------------\n\nfunction sectionExists(ir: HarnessIR, id: string): boolean {\n return ir.sections.some((s) => s.id === id);\n}\n\nfunction commandExists(ir: HarnessIR, name: string): boolean {\n return ir.commands.some((c) => c.name === name);\n}\n\nfunction ruleExists(ir: HarnessIR, name: string): boolean {\n return ir.rules.some((r) => r.name === name);\n}\n\nfunction agentExists(ir: HarnessIR, name: string): boolean {\n return ir.agents.some((a) => a.name === name);\n}\n\nfunction mcpServerExists(ir: HarnessIR, id: string): boolean {\n return ir.mcpServers.some((s) => s.id === id);\n}\n\n// ---------------------------------------------------------------------------\n// Deep-set helper for settings paths\n// ---------------------------------------------------------------------------\n\n/** Known top-level keys in SettingsIR that map to structured fields. */\nconst STRUCTURED_SETTINGS_KEYS = new Set([\"statusLine\", \"hooks\", \"denyPatterns\"]);\n\n/**\n * Immutably deep-set a dotted path on an object, returning a new object tree.\n *\n * Example: `deepSet({}, \"a.b.c\", 42)` => `{ a: { b: { c: 42 } } }`\n */\nfunction deepSet(\n obj: Record<string, unknown>,\n segments: string[],\n value: unknown,\n): Record<string, unknown> {\n if (segments.length === 0) return obj;\n\n const [head, ...rest] = segments;\n\n if (rest.length === 0) {\n return { ...obj, [head]: value };\n }\n\n const existing = obj[head];\n const child =\n existing !== null && typeof existing === \"object\" && !Array.isArray(existing)\n ? (existing as Record<string, unknown>)\n : {};\n\n return { ...obj, [head]: deepSet(child, rest, value) };\n}\n\n/**\n * Apply a dotted-path setting update to SettingsIR immutably.\n *\n * If the top-level key maps to a structured field (statusLine, hooks, denyPatterns),\n * we set it directly on the SettingsIR. Otherwise, we store it in `settings.raw`.\n */\nfunction applySettingsUpdate(\n settings: SettingsIR,\n path: string,\n value: unknown,\n): SettingsIR {\n const segments = path.split(\".\");\n const topKey = segments[0];\n\n if (STRUCTURED_SETTINGS_KEYS.has(topKey)) {\n // Deep-set into the structured settings object\n const settingsRecord = { ...settings } as unknown as Record<string, unknown>;\n const updated = deepSet(settingsRecord, segments, value);\n return {\n ...settings,\n ...updated,\n // Preserve raw as-is (deepSet may have overwritten it if path happened to be \"raw\")\n raw: settings.raw,\n } as SettingsIR;\n }\n\n // Unrecognized key — store in raw\n const updatedRaw = deepSet({ ...settings.raw }, segments, value);\n return {\n ...settings,\n raw: updatedRaw,\n };\n}\n\n// ---------------------------------------------------------------------------\n// applyIRMutation\n// ---------------------------------------------------------------------------\n\n/**\n * Apply a single mutation to a HarnessIR, returning a new immutable IR.\n *\n * Throws if a pre-condition is violated (e.g., updating a section that doesn't exist).\n */\nexport function applyIRMutation(ir: HarnessIR, mutation: IRMutation): HarnessIR {\n switch (mutation.type) {\n // -- Sections ----------------------------------------------------------\n\n case \"update_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n throw new Error(`Section '${mutation.sectionId}' not found`);\n }\n return {\n ...ir,\n sections: ir.sections.map((s) =>\n s.id === mutation.sectionId ? { ...s, content: mutation.content } : s,\n ),\n };\n }\n\n case \"add_section\": {\n if (sectionExists(ir, mutation.section.id)) {\n throw new Error(`Section '${mutation.section.id}' already exists`);\n }\n return {\n ...ir,\n sections: [...ir.sections, { ...mutation.section }],\n };\n }\n\n case \"remove_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n throw new Error(`Section '${mutation.sectionId}' not found`);\n }\n return {\n ...ir,\n sections: ir.sections.filter((s) => s.id !== mutation.sectionId),\n };\n }\n\n case \"reorder_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n throw new Error(`Section '${mutation.sectionId}' not found`);\n }\n return {\n ...ir,\n sections: ir.sections.map((s) =>\n s.id === mutation.sectionId ? { ...s, order: mutation.newOrder } : s,\n ),\n };\n }\n\n // -- Commands ----------------------------------------------------------\n\n case \"add_command\": {\n if (commandExists(ir, mutation.command.name)) {\n throw new Error(`Command '${mutation.command.name}' already exists`);\n }\n return {\n ...ir,\n commands: [...ir.commands, { ...mutation.command }],\n };\n }\n\n case \"update_command\": {\n if (!commandExists(ir, mutation.name)) {\n throw new Error(`Command '${mutation.name}' not found`);\n }\n return {\n ...ir,\n commands: ir.commands.map((c) =>\n c.name === mutation.name ? { ...c, content: mutation.content } : c,\n ),\n };\n }\n\n case \"remove_command\": {\n if (!commandExists(ir, mutation.name)) {\n throw new Error(`Command '${mutation.name}' not found`);\n }\n return {\n ...ir,\n commands: ir.commands.filter((c) => c.name !== mutation.name),\n };\n }\n\n // -- Rules -------------------------------------------------------------\n\n case \"add_rule\": {\n if (ruleExists(ir, mutation.rule.name)) {\n throw new Error(`Rule '${mutation.rule.name}' already exists`);\n }\n return {\n ...ir,\n rules: [...ir.rules, { ...mutation.rule }],\n };\n }\n\n case \"update_rule\": {\n if (!ruleExists(ir, mutation.name)) {\n throw new Error(`Rule '${mutation.name}' not found`);\n }\n return {\n ...ir,\n rules: ir.rules.map((r) =>\n r.name === mutation.name ? { ...r, content: mutation.content } : r,\n ),\n };\n }\n\n case \"remove_rule\": {\n if (!ruleExists(ir, mutation.name)) {\n throw new Error(`Rule '${mutation.name}' not found`);\n }\n return {\n ...ir,\n rules: ir.rules.filter((r) => r.name !== mutation.name),\n };\n }\n\n // -- Agents ------------------------------------------------------------\n\n case \"add_agent\": {\n if (agentExists(ir, mutation.agent.name)) {\n throw new Error(`Agent '${mutation.agent.name}' already exists`);\n }\n return {\n ...ir,\n agents: [...ir.agents, { ...mutation.agent }],\n };\n }\n\n case \"update_agent\": {\n if (!agentExists(ir, mutation.name)) {\n throw new Error(`Agent '${mutation.name}' not found`);\n }\n return {\n ...ir,\n agents: ir.agents.map((a) =>\n a.name === mutation.name ? { ...a, ...mutation.changes } : a,\n ),\n };\n }\n\n case \"remove_agent\": {\n if (!agentExists(ir, mutation.name)) {\n throw new Error(`Agent '${mutation.name}' not found`);\n }\n return {\n ...ir,\n agents: ir.agents.filter((a) => a.name !== mutation.name),\n };\n }\n\n // -- MCP Servers -------------------------------------------------------\n\n case \"add_mcp_server\": {\n if (mcpServerExists(ir, mutation.server.id)) {\n throw new Error(`MCP server '${mutation.server.id}' already exists`);\n }\n return {\n ...ir,\n mcpServers: [...ir.mcpServers, { ...mutation.server }],\n };\n }\n\n case \"remove_mcp_server\": {\n if (!mcpServerExists(ir, mutation.id)) {\n throw new Error(`MCP server '${mutation.id}' not found`);\n }\n return {\n ...ir,\n mcpServers: ir.mcpServers.filter((s) => s.id !== mutation.id),\n };\n }\n\n // -- Settings ----------------------------------------------------------\n\n case \"update_settings\": {\n return {\n ...ir,\n settings: applySettingsUpdate(ir.settings, mutation.path, mutation.value),\n };\n }\n\n // -- Raw text (legacy fallback) ----------------------------------------\n\n case \"raw_text\": {\n console.warn(\n \"raw_text mutation is a legacy fallback — the text operation will be applied during rendering\",\n );\n return { ...ir };\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// applyIRMutations\n// ---------------------------------------------------------------------------\n\n/**\n * Apply a sequence of mutations to a HarnessIR, returning the final IR.\n *\n * Mutations are applied in order. If any mutation fails, the error propagates immediately.\n */\nexport function applyIRMutations(ir: HarnessIR, mutations: IRMutation[]): HarnessIR {\n return mutations.reduce<HarnessIR>(\n (acc, mut) => applyIRMutation(acc, mut),\n ir,\n );\n}\n\n// ---------------------------------------------------------------------------\n// validateIRMutation\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether a mutation's pre-conditions are satisfied without applying it.\n *\n * Returns `{ valid: true }` if the mutation can be applied, or\n * `{ valid: false, reason: \"...\" }` describing why it cannot.\n */\nexport function validateIRMutation(\n ir: HarnessIR,\n mutation: IRMutation,\n): ValidationResult {\n switch (mutation.type) {\n // -- Sections ----------------------------------------------------------\n\n case \"update_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n return { valid: false, reason: `Section '${mutation.sectionId}' not found` };\n }\n return { valid: true };\n }\n\n case \"add_section\": {\n if (sectionExists(ir, mutation.section.id)) {\n return { valid: false, reason: `Section '${mutation.section.id}' already exists` };\n }\n return { valid: true };\n }\n\n case \"remove_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n return { valid: false, reason: `Section '${mutation.sectionId}' not found` };\n }\n return { valid: true };\n }\n\n case \"reorder_section\": {\n if (!sectionExists(ir, mutation.sectionId)) {\n return { valid: false, reason: `Section '${mutation.sectionId}' not found` };\n }\n return { valid: true };\n }\n\n // -- Commands ----------------------------------------------------------\n\n case \"add_command\": {\n if (commandExists(ir, mutation.command.name)) {\n return { valid: false, reason: `Command '${mutation.command.name}' already exists` };\n }\n return { valid: true };\n }\n\n case \"update_command\": {\n if (!commandExists(ir, mutation.name)) {\n return { valid: false, reason: `Command '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n case \"remove_command\": {\n if (!commandExists(ir, mutation.name)) {\n return { valid: false, reason: `Command '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n // -- Rules -------------------------------------------------------------\n\n case \"add_rule\": {\n if (ruleExists(ir, mutation.rule.name)) {\n return { valid: false, reason: `Rule '${mutation.rule.name}' already exists` };\n }\n return { valid: true };\n }\n\n case \"update_rule\": {\n if (!ruleExists(ir, mutation.name)) {\n return { valid: false, reason: `Rule '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n case \"remove_rule\": {\n if (!ruleExists(ir, mutation.name)) {\n return { valid: false, reason: `Rule '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n // -- Agents ------------------------------------------------------------\n\n case \"add_agent\": {\n if (agentExists(ir, mutation.agent.name)) {\n return { valid: false, reason: `Agent '${mutation.agent.name}' already exists` };\n }\n return { valid: true };\n }\n\n case \"update_agent\": {\n if (!agentExists(ir, mutation.name)) {\n return { valid: false, reason: `Agent '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n case \"remove_agent\": {\n if (!agentExists(ir, mutation.name)) {\n return { valid: false, reason: `Agent '${mutation.name}' not found` };\n }\n return { valid: true };\n }\n\n // -- MCP Servers -------------------------------------------------------\n\n case \"add_mcp_server\": {\n if (mcpServerExists(ir, mutation.server.id)) {\n return { valid: false, reason: `MCP server '${mutation.server.id}' already exists` };\n }\n return { valid: true };\n }\n\n case \"remove_mcp_server\": {\n if (!mcpServerExists(ir, mutation.id)) {\n return { valid: false, reason: `MCP server '${mutation.id}' not found` };\n }\n return { valid: true };\n }\n\n // -- Settings & raw_text always valid at pre-condition level ------------\n\n case \"update_settings\": {\n return { valid: true };\n }\n\n case \"raw_text\": {\n return { valid: true };\n }\n }\n}\n","/**\n * Harness Renderer — produces a `.claude/` directory structure from a HarnessIR.\n *\n * This is the inverse of the parser: given a HarnessIR, it emits the file\n * contents that `parseHarness` would read back into the same IR.\n *\n * All file I/O uses `fs.promises`. Directories are created on demand.\n */\n\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type {\n HarnessIR,\n HarnessMeta,\n Section,\n SettingsIR,\n McpServerNode,\n RuleNode,\n AgentNode,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// renderClaudeMd\n// ---------------------------------------------------------------------------\n\n/**\n * Render the CLAUDE.md file content from metadata and sections.\n *\n * Sections are sorted by `order`. Each section is output as\n * `{heading}\\n\\n{content}` — the heading already includes its `## ` prefix\n * (or `# ` for the preamble). Sections are joined with double newlines.\n *\n * @param _meta - Harness metadata (name used only if no preamble section provides a title)\n * @param sections - The ordered sections to render\n * @returns The full CLAUDE.md content string with trailing newline\n */\nexport function renderClaudeMd(_meta: HarnessMeta, sections: Section[]): string {\n const sorted = [...sections].sort((a, b) => a.order - b.order);\n\n const blocks: string[] = [];\n\n for (const section of sorted) {\n if (section.heading && section.content) {\n blocks.push(`${section.heading}\\n\\n${section.content}`);\n } else if (section.heading) {\n blocks.push(section.heading);\n } else if (section.content) {\n blocks.push(section.content);\n }\n // Skip sections with neither heading nor content\n }\n\n if (blocks.length === 0) {\n return \"\\n\";\n }\n\n return blocks.join(\"\\n\\n\") + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// renderSettings\n// ---------------------------------------------------------------------------\n\n/**\n * Render a `settings.json` string from a SettingsIR.\n *\n * Reconstructs the JSON structure that `parseSettings` would parse:\n * - `raw` fields are spread as the base\n * - `denyPatterns` → `permissions.deny`\n * - `statusLine` → `statusLine`\n * - Non-empty hook arrays → `hooks.{EventType}`\n *\n * @param settings - The settings IR to render\n * @returns JSON string with 2-space indent and trailing newline\n */\nexport function renderSettings(settings: SettingsIR): string {\n // Deep-clone raw as the base\n const result: Record<string, unknown> = JSON.parse(\n JSON.stringify(settings.raw),\n );\n\n // Add deny patterns\n if (settings.denyPatterns && settings.denyPatterns.length > 0) {\n const permissions =\n (result[\"permissions\"] as Record<string, unknown>) ?? {};\n permissions[\"deny\"] = settings.denyPatterns;\n result[\"permissions\"] = permissions;\n }\n\n // Add status line\n if (settings.statusLine) {\n result[\"statusLine\"] = settings.statusLine;\n }\n\n // Add hooks\n const hookEvents = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"UserPromptSubmit\",\n \"SessionStart\",\n \"PostCompact\",\n ] as const;\n\n const hooksObj: Record<string, unknown> = {};\n let hasHooks = false;\n\n for (const event of hookEvents) {\n const entries = settings.hooks[event];\n if (entries && entries.length > 0) {\n hooksObj[event] = entries;\n hasHooks = true;\n }\n }\n\n if (hasHooks) {\n result[\"hooks\"] = hooksObj;\n }\n\n return JSON.stringify(result, null, 2) + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// renderMcpConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Render a `.mcp.json` string from an array of MCP server nodes.\n *\n * Builds the `{ mcpServers: { id: { command, args, env? } } }` structure.\n * Returns an empty string if the servers array is empty (no file needed).\n *\n * @param servers - Array of MCP server declarations\n * @returns JSON string with 2-space indent and trailing newline, or empty string\n */\nexport function renderMcpConfig(servers: McpServerNode[]): string {\n if (servers.length === 0) {\n return \"\";\n }\n\n const mcpServers: Record<string, Record<string, unknown>> = {};\n\n for (const server of servers) {\n const entry: Record<string, unknown> = {\n command: server.command,\n args: server.args,\n };\n\n if (server.env && Object.keys(server.env).length > 0) {\n entry[\"env\"] = server.env;\n }\n\n mcpServers[server.id] = entry;\n }\n\n return JSON.stringify({ mcpServers }, null, 2) + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// renderRuleWithFrontmatter\n// ---------------------------------------------------------------------------\n\n/**\n * Render a rule's content, prepending YAML frontmatter if the rule has paths.\n *\n * The frontmatter format matches what `parseYamlFrontmatter` expects:\n * ```\n * ---\n * paths:\n * - path1\n * - path2\n * ---\n *\n * {content}\n * ```\n *\n * @param rule - The rule node to render\n * @returns The rendered string (with or without frontmatter)\n */\nexport function renderRuleWithFrontmatter(rule: RuleNode): string {\n if (!rule.paths || rule.paths.length === 0) {\n return rule.content;\n }\n\n const yamlLines = [\"---\", \"paths:\"];\n for (const p of rule.paths) {\n yamlLines.push(` - ${p}`);\n }\n yamlLines.push(\"---\");\n\n return yamlLines.join(\"\\n\") + \"\\n\\n\" + rule.content;\n}\n\n// ---------------------------------------------------------------------------\n// renderAgentWithFrontmatter\n// ---------------------------------------------------------------------------\n\n/**\n * Render an agent's content, prepending YAML frontmatter if the agent has\n * `model` or `disallowedTools`.\n *\n * The frontmatter format matches what `parseYamlFrontmatter` expects:\n * ```\n * ---\n * model: opus\n * disallowedTools:\n * - Tool1\n * ---\n *\n * {content}\n * ```\n *\n * @param agent - The agent node to render\n * @returns The rendered string (with or without frontmatter)\n */\nexport function renderAgentWithFrontmatter(agent: AgentNode): string {\n const hasModel = agent.model !== undefined;\n const hasDisallowed =\n agent.disallowedTools !== undefined && agent.disallowedTools.length > 0;\n const hasRouting = agent.modelRouting !== undefined;\n const hasExtra =\n agent.extraFrontmatter !== undefined &&\n Object.keys(agent.extraFrontmatter).length > 0;\n\n if (!hasModel && !hasDisallowed && !hasRouting && !hasExtra) {\n return agent.content;\n }\n\n const yamlLines = [\"---\"];\n\n if (hasModel) {\n yamlLines.push(`model: ${agent.model}`);\n }\n\n if (hasDisallowed) {\n yamlLines.push(\"disallowedTools:\");\n for (const tool of agent.disallowedTools!) {\n yamlLines.push(` - ${tool}`);\n }\n }\n\n // Emit modelRouting as nested YAML\n if (hasRouting) {\n yamlLines.push(\"modelRouting:\");\n yamlLines.push(` default: ${agent.modelRouting!.default}`);\n if (agent.modelRouting!.escalateTo) {\n yamlLines.push(` escalateTo: ${agent.modelRouting!.escalateTo}`);\n }\n if (agent.modelRouting!.escalateWhen) {\n yamlLines.push(` escalateWhen: ${agent.modelRouting!.escalateWhen}`);\n }\n }\n\n // Re-emit all extra frontmatter fields preserved from the original file\n if (hasExtra) {\n for (const [key, value] of Object.entries(agent.extraFrontmatter!)) {\n if (Array.isArray(value)) {\n yamlLines.push(`${key}:`);\n for (const item of value) {\n yamlLines.push(` - ${String(item)}`);\n }\n } else if (typeof value === 'object' && value !== null) {\n // Nested objects — render as indented YAML\n yamlLines.push(`${key}:`);\n for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {\n yamlLines.push(` ${subKey}: ${String(subVal)}`);\n }\n } else {\n yamlLines.push(`${key}: ${String(value)}`);\n }\n }\n }\n\n yamlLines.push(\"---\");\n\n return yamlLines.join(\"\\n\") + \"\\n\\n\" + agent.content;\n}\n\n// ---------------------------------------------------------------------------\n// settingsHasContent\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether a SettingsIR has any meaningful content beyond empty defaults.\n *\n * Returns false for `{ hooks: {}, raw: {} }` (the output of `createEmptySettings`).\n */\nfunction settingsHasContent(settings: SettingsIR): boolean {\n if (settings.statusLine) return true;\n if (settings.denyPatterns && settings.denyPatterns.length > 0) return true;\n if (Object.keys(settings.raw).length > 0) return true;\n\n // Check if any hook event has entries\n const hookEvents = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"UserPromptSubmit\",\n \"SessionStart\",\n \"PostCompact\",\n ] as const;\n\n for (const event of hookEvents) {\n const entries = settings.hooks[event];\n if (entries && entries.length > 0) return true;\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// renderHarness\n// ---------------------------------------------------------------------------\n\n/**\n * Render a complete HarnessIR into a file map.\n *\n * Returns a `Map<string, string>` where keys are relative file paths\n * (e.g., `CLAUDE.md`, `commands/build.md`) and values are file contents.\n *\n * Only files with actual content are included in the map.\n *\n * @param ir - The complete harness IR to render\n * @returns Map of relative file path to file content\n */\nexport function renderHarness(ir: HarnessIR): Map<string, string> {\n const files = new Map<string, string>();\n\n // CLAUDE.md — only if sections exist or meta.name is set\n if (ir.sections.length > 0 || ir.meta.name) {\n files.set(\"CLAUDE.md\", renderClaudeMd(ir.meta, ir.sections));\n }\n\n // settings.json — only if settings has content beyond empty defaults\n if (settingsHasContent(ir.settings)) {\n files.set(\"settings.json\", renderSettings(ir.settings));\n }\n\n // Commands\n for (const cmd of ir.commands) {\n files.set(`commands/${cmd.name}.md`, cmd.content);\n }\n\n // Rules\n for (const rule of ir.rules) {\n files.set(`rules/${rule.name}.md`, renderRuleWithFrontmatter(rule));\n }\n\n // Agents\n for (const agent of ir.agents) {\n files.set(`agents/${agent.name}.md`, renderAgentWithFrontmatter(agent));\n }\n\n // Skills\n for (const skill of ir.skills) {\n files.set(`skills/${skill.name}.md`, skill.content);\n }\n\n // Docs\n for (const doc of ir.docs) {\n files.set(`docs/${doc.name}.md`, doc.content);\n }\n\n // Hooks\n for (const hook of ir.hooks) {\n files.set(`hooks/${hook.name}.mjs`, hook.content);\n }\n\n // .mcp.json — only if servers exist\n const mcpContent = renderMcpConfig(ir.mcpServers);\n if (mcpContent) {\n files.set(\".mcp.json\", mcpContent);\n }\n\n return files;\n}\n\n// ---------------------------------------------------------------------------\n// renderHarnessToDir\n// ---------------------------------------------------------------------------\n\n/**\n * Render a HarnessIR to a target directory on disk.\n *\n * Calls `renderHarness` to produce the file map, then writes each file\n * to `path.join(targetDir, relativePath)`, creating directories as needed.\n *\n * @param ir - The complete harness IR to render\n * @param targetDir - Absolute path to write files into\n * @returns Array of relative file paths that were written\n */\nexport async function renderHarnessToDir(\n ir: HarnessIR,\n targetDir: string,\n): Promise<string[]> {\n const fileMap = renderHarness(ir);\n const writtenPaths: string[] = [];\n\n for (const [relativePath, content] of fileMap) {\n const fullPath = path.join(targetDir, relativePath);\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n await fs.writeFile(fullPath, content, \"utf-8\");\n writtenPaths.push(relativePath);\n }\n\n return writtenPaths;\n}\n","/**\n * Structural diff engine for HarnessIR snapshots.\n *\n * Compares two HarnessIR trees and produces an IRDiff describing\n * every addition, removal, modification, and reordering across\n * sections, commands, rules, agents, MCP servers, and settings.\n */\n\nimport type {\n HarnessIR,\n IRDiff,\n Section,\n CommandNode,\n RuleNode,\n AgentNode,\n McpServerNode,\n SettingsIR,\n} from \"./types.js\";\nimport { createEmptyDiff } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Compute a structural diff between two HarnessIR snapshots.\n *\n * Every category is compared by its natural key (id for sections/servers,\n * name for commands/rules/agents). Settings are deep-compared field by field.\n */\nexport function diffIR(before: HarnessIR, after: HarnessIR): IRDiff {\n const diff = createEmptyDiff();\n\n diffSections(before.sections, after.sections, diff);\n diffByName(before.commands, after.commands, diff.commands);\n diffByName(before.rules, after.rules, diff.rules);\n diffAgents(before.agents, after.agents, diff);\n diffMcpServers(before.mcpServers, after.mcpServers, diff);\n diffSettings(before.settings, after.settings, diff);\n\n return diff;\n}\n\n/**\n * Format an IRDiff into a human-readable, plain-text summary.\n *\n * Categories with no changes are omitted. If the entire diff is empty\n * the string \"No changes.\" is returned.\n */\nexport function formatIRDiff(diff: IRDiff): string {\n const blocks: string[] = [];\n\n // Sections\n const sectionLines = formatSectionBlock(diff);\n if (sectionLines.length > 0) {\n blocks.push([\"Sections:\", ...sectionLines].join(\"\\n\"));\n }\n\n // Commands\n const commandLines = formatNamedBlock(diff.commands, \"commands\");\n if (commandLines.length > 0) {\n blocks.push([\"Commands:\", ...commandLines].join(\"\\n\"));\n }\n\n // Rules\n const ruleLines = formatNamedBlock(diff.rules, \"rules\");\n if (ruleLines.length > 0) {\n blocks.push([\"Rules:\", ...ruleLines].join(\"\\n\"));\n }\n\n // Agents\n const agentLines = formatAgentBlock(diff);\n if (agentLines.length > 0) {\n blocks.push([\"Agents:\", ...agentLines].join(\"\\n\"));\n }\n\n // MCP Servers\n const mcpLines = formatMcpBlock(diff);\n if (mcpLines.length > 0) {\n blocks.push([\"MCP Servers:\", ...mcpLines].join(\"\\n\"));\n }\n\n // Settings\n const settingsLines = formatSettingsBlock(diff);\n if (settingsLines.length > 0) {\n blocks.push([\"Settings:\", ...settingsLines].join(\"\\n\"));\n }\n\n if (blocks.length === 0) {\n return \"No changes.\";\n }\n\n return blocks.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Diff internals\n// ---------------------------------------------------------------------------\n\n/** Compare sections by `id`, detecting adds, removes, modifications, and reorderings. */\nfunction diffSections(\n beforeList: Section[],\n afterList: Section[],\n diff: IRDiff,\n): void {\n const beforeMap = new Map<string, Section>();\n for (const s of beforeList) {\n beforeMap.set(s.id, s);\n }\n\n const afterMap = new Map<string, Section>();\n for (const s of afterList) {\n afterMap.set(s.id, s);\n }\n\n // Added: in after but not in before\n for (const s of afterList) {\n if (!beforeMap.has(s.id)) {\n diff.sections.added.push(s);\n }\n }\n\n // Removed: in before but not in after\n for (const s of beforeList) {\n if (!afterMap.has(s.id)) {\n diff.sections.removed.push(s);\n }\n }\n\n // Modified & reordered: present in both\n for (const [id, afterSection] of afterMap) {\n const beforeSection = beforeMap.get(id);\n if (beforeSection === undefined) continue;\n\n if (beforeSection.content !== afterSection.content) {\n diff.sections.modified.push({\n id,\n before: beforeSection.content,\n after: afterSection.content,\n });\n }\n\n if (beforeSection.order !== afterSection.order) {\n diff.sections.reordered.push({\n id,\n oldOrder: beforeSection.order,\n newOrder: afterSection.order,\n });\n }\n }\n}\n\n/**\n * Generic diff for node lists keyed by `name` (commands and rules share this shape).\n * Populates `added`, `removed`, and `modified` arrays on the target bucket.\n */\nfunction diffByName<T extends { name: string; content: string }>(\n beforeList: T[],\n afterList: T[],\n target: {\n added: T[];\n removed: string[];\n modified: Array<{ name: string; before: string; after: string }>;\n },\n): void {\n const beforeMap = new Map<string, T>();\n for (const n of beforeList) {\n beforeMap.set(n.name, n);\n }\n\n const afterMap = new Map<string, T>();\n for (const n of afterList) {\n afterMap.set(n.name, n);\n }\n\n // Added\n for (const n of afterList) {\n if (!beforeMap.has(n.name)) {\n target.added.push(n);\n }\n }\n\n // Removed\n for (const n of beforeList) {\n if (!afterMap.has(n.name)) {\n target.removed.push(n.name);\n }\n }\n\n // Modified\n for (const [name, afterNode] of afterMap) {\n const beforeNode = beforeMap.get(name);\n if (beforeNode === undefined) continue;\n\n if (beforeNode.content !== afterNode.content) {\n target.modified.push({\n name,\n before: beforeNode.content,\n after: afterNode.content,\n });\n }\n }\n}\n\n/** Compare agents by `name`, building a human-readable `changes` description. */\nfunction diffAgents(\n beforeList: AgentNode[],\n afterList: AgentNode[],\n diff: IRDiff,\n): void {\n const beforeMap = new Map<string, AgentNode>();\n for (const a of beforeList) {\n beforeMap.set(a.name, a);\n }\n\n const afterMap = new Map<string, AgentNode>();\n for (const a of afterList) {\n afterMap.set(a.name, a);\n }\n\n // Added\n for (const a of afterList) {\n if (!beforeMap.has(a.name)) {\n diff.agents.added.push(a);\n }\n }\n\n // Removed\n for (const a of beforeList) {\n if (!afterMap.has(a.name)) {\n diff.agents.removed.push(a.name);\n }\n }\n\n // Modified\n for (const [name, afterAgent] of afterMap) {\n const beforeAgent = beforeMap.get(name);\n if (beforeAgent === undefined) continue;\n\n const changeParts: string[] = [];\n\n if (beforeAgent.model !== afterAgent.model) {\n const from = beforeAgent.model ?? \"none\";\n const to = afterAgent.model ?? \"none\";\n changeParts.push(`model changed from ${from} to ${to}`);\n }\n\n if (beforeAgent.content !== afterAgent.content) {\n changeParts.push(\"content updated\");\n }\n\n const beforeTools = JSON.stringify(beforeAgent.disallowedTools ?? []);\n const afterTools = JSON.stringify(afterAgent.disallowedTools ?? []);\n if (beforeTools !== afterTools) {\n changeParts.push(\"disallowedTools changed\");\n }\n\n if (changeParts.length > 0) {\n diff.agents.modified.push({\n name,\n changes: changeParts.join(\"; \"),\n });\n }\n }\n}\n\n/** Compare MCP servers by `id`. */\nfunction diffMcpServers(\n beforeList: McpServerNode[],\n afterList: McpServerNode[],\n diff: IRDiff,\n): void {\n const beforeIds = new Set(beforeList.map((s) => s.id));\n const afterIds = new Set(afterList.map((s) => s.id));\n\n for (const s of afterList) {\n if (!beforeIds.has(s.id)) {\n diff.mcpServers.added.push(s);\n }\n }\n\n for (const s of beforeList) {\n if (!afterIds.has(s.id)) {\n diff.mcpServers.removed.push(s.id);\n }\n }\n}\n\n/** Deep-compare settings fields: statusLine, denyPatterns, and hooks. */\nfunction diffSettings(\n before: SettingsIR,\n after: SettingsIR,\n diff: IRDiff,\n): void {\n // statusLine\n if (!deepEqual(before.statusLine, after.statusLine)) {\n diff.settings.changes.push({\n path: \"statusLine\",\n before: before.statusLine,\n after: after.statusLine,\n });\n }\n\n // denyPatterns\n if (!deepEqual(before.denyPatterns, after.denyPatterns)) {\n diff.settings.changes.push({\n path: \"denyPatterns\",\n before: before.denyPatterns,\n after: after.denyPatterns,\n });\n }\n\n // hooks\n if (!deepEqual(before.hooks, after.hooks)) {\n diff.settings.changes.push({\n path: \"hooks\",\n before: before.hooks,\n after: after.hooks,\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Format internals\n// ---------------------------------------------------------------------------\n\n/** Format the Sections block lines. */\nfunction formatSectionBlock(diff: IRDiff): string[] {\n const lines: string[] = [];\n\n for (const s of diff.sections.added) {\n lines.push(` + Added: ${s.heading}`);\n }\n for (const s of diff.sections.removed) {\n lines.push(` - Removed: ${s.heading}`);\n }\n for (const m of diff.sections.modified) {\n lines.push(` ~ Modified: ${m.id} (content changed)`);\n }\n for (const r of diff.sections.reordered) {\n lines.push(\n ` \\u2195 Reordered: ${r.id} (${r.oldOrder} \\u2192 ${r.newOrder})`,\n );\n }\n\n return lines;\n}\n\n/**\n * Format a generic named block (commands or rules).\n * The `_category` parameter is unused but kept for clarity at the call site.\n */\nfunction formatNamedBlock(\n bucket: {\n added: Array<{ name: string }>;\n removed: string[];\n modified: Array<{ name: string }>;\n },\n _category: string,\n): string[] {\n const lines: string[] = [];\n\n for (const n of bucket.added) {\n lines.push(` + Added: ${n.name}`);\n }\n for (const name of bucket.removed) {\n lines.push(` - Removed: ${name}`);\n }\n for (const m of bucket.modified) {\n lines.push(` ~ Modified: ${m.name} (content changed)`);\n }\n\n return lines;\n}\n\n/** Format the Agents block. */\nfunction formatAgentBlock(diff: IRDiff): string[] {\n const lines: string[] = [];\n\n for (const a of diff.agents.added) {\n lines.push(` + Added: ${a.name}`);\n }\n for (const name of diff.agents.removed) {\n lines.push(` - Removed: ${name}`);\n }\n for (const m of diff.agents.modified) {\n lines.push(` ~ Modified: ${m.name} (${m.changes})`);\n }\n\n return lines;\n}\n\n/** Format the MCP Servers block. */\nfunction formatMcpBlock(diff: IRDiff): string[] {\n const lines: string[] = [];\n\n for (const s of diff.mcpServers.added) {\n lines.push(` + Added: ${s.id}`);\n }\n for (const id of diff.mcpServers.removed) {\n lines.push(` - Removed: ${id}`);\n }\n\n return lines;\n}\n\n/** Format the Settings block. */\nfunction formatSettingsBlock(diff: IRDiff): string[] {\n const lines: string[] = [];\n\n for (const c of diff.settings.changes) {\n lines.push(` ~ ${c.path} changed`);\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Utility\n// ---------------------------------------------------------------------------\n\n/** Simple deep-equality check using JSON serialisation. */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport type { Mutation } from './types.js';\nimport { parseHarness } from '../ir/parser.js';\nimport { translateMutations } from '../ir/translate.js';\nimport { applyIRMutation } from '../ir/mutations.js';\nimport { renderHarness } from '../ir/renderer.js';\nimport { diffIR, formatIRDiff } from '../ir/diff.js';\nimport type { HarnessIR } from '../ir/types.js';\n\n/**\n * Apply mutations to a copy of the current harness using the IR pipeline.\n *\n * Pipeline:\n * 1. Parse the current harness into an IR\n * 2. Translate legacy Mutations into IRMutations\n * 3. Apply each IRMutation immutably (skip failures silently)\n * 4. Render the new IR to disk\n * 5. Apply any raw_text mutations via file-based string surgery (backward compat)\n * 6. Generate a structural diff between baseline and new IR\n *\n * Falls back to the legacy file-copy + string-surgery approach if IR parsing fails.\n *\n * @returns Path to new harness and diff patch string\n */\nexport async function applyMutations(\n currentHarnessPath: string,\n nextIterationDir: string,\n mutations: Mutation[],\n): Promise<{ newHarnessPath: string; diffPatch: string }> {\n const newHarnessPath = path.join(nextIterationDir, 'harness');\n\n // Try the IR pipeline first\n let baselineIR: HarnessIR | null = null;\n try {\n baselineIR = await parseHarness(currentHarnessPath);\n } catch {\n // IR parsing failed — fall back to legacy approach\n }\n\n if (baselineIR !== null) {\n return applyMutationsViaIR(\n currentHarnessPath,\n newHarnessPath,\n mutations,\n baselineIR,\n );\n }\n\n // Legacy fallback: file-copy + string surgery\n return applyMutationsLegacy(currentHarnessPath, newHarnessPath, mutations);\n}\n\n/**\n * IR-based mutation pipeline.\n *\n * Strategy: copy the original harness first (preserving exact byte content),\n * then apply mutations through the IR engine. Only files affected by IR\n * mutations get re-rendered, so untouched files remain byte-identical.\n *\n * raw_text mutations are applied via legacy file-based string surgery after\n * the IR mutations, preserving backward compatibility for non-IR-translatable\n * mutations.\n */\nasync function applyMutationsViaIR(\n currentHarnessPath: string,\n newHarnessPath: string,\n mutations: Mutation[],\n baselineIR: HarnessIR,\n): Promise<{ newHarnessPath: string; diffPatch: string }> {\n // 1. Copy the original harness to preserve exact byte content\n await copyDir(currentHarnessPath, newHarnessPath);\n\n // 2. Translate legacy mutations to IR mutations\n const irMutations = translateMutations(mutations, baselineIR);\n\n // 3. Apply IR mutations one by one, skipping failures silently.\n // Track which IR node categories were touched so we only re-render those files.\n let currentIR = baselineIR;\n const rawTextMutations: Mutation[] = [];\n const touchedCategories = new Set<string>();\n\n for (let i = 0; i < irMutations.length; i++) {\n const irMut = irMutations[i];\n\n if (irMut.type === 'raw_text') {\n // Collect raw_text mutations for file-based application later\n rawTextMutations.push(mutations[i]);\n continue;\n }\n\n try {\n currentIR = applyIRMutation(currentIR, irMut);\n // Track which file category this mutation touched\n touchedCategories.add(getMutationCategory(irMut.type));\n } catch {\n // Skip failed mutations silently — matches old behavior where\n // a replace with missing oldText was simply skipped\n continue;\n }\n }\n\n // 4. Selectively re-render only files affected by IR mutations.\n // This preserves byte-identical content for untouched files while\n // applying structural changes through the IR engine.\n if (touchedCategories.size > 0) {\n await renderAffectedFiles(currentIR, newHarnessPath, touchedCategories);\n }\n\n // 5. Apply raw_text mutations via file-based string surgery\n for (const mutation of rawTextMutations) {\n await applyLegacyMutation(newHarnessPath, mutation);\n }\n\n // 6. Generate structural diff\n const irDiff = diffIR(baselineIR, currentIR);\n let diffPatch = formatIRDiff(irDiff);\n\n // If the IR diff says \"No changes.\" but raw_text mutations were applied,\n // fall back to a file-based diff to capture those changes\n if (diffPatch === 'No changes.' && rawTextMutations.length > 0) {\n diffPatch = await generateDiffLegacy(currentHarnessPath, newHarnessPath);\n }\n\n // Normalize \"No changes.\" to empty string for backward compatibility\n if (diffPatch === 'No changes.') {\n diffPatch = '';\n }\n\n return { newHarnessPath, diffPatch };\n}\n\n/**\n * Map an IR mutation type to the file category it affects.\n * Used to determine which files need re-rendering after IR mutations.\n */\nfunction getMutationCategory(mutationType: string): string {\n if (mutationType.includes('section') || mutationType.includes('reorder')) {\n return 'claude_md';\n }\n if (mutationType.includes('command')) {\n return 'commands';\n }\n if (mutationType.includes('rule')) {\n return 'rules';\n }\n if (mutationType.includes('agent')) {\n return 'agents';\n }\n if (mutationType.includes('mcp')) {\n return 'mcp';\n }\n if (mutationType.includes('settings')) {\n return 'settings';\n }\n return 'unknown';\n}\n\n/**\n * Re-render only the files affected by IR mutations.\n *\n * Instead of re-rendering the entire harness (which can alter whitespace\n * in untouched files), this function renders the full file map from IR\n * and then selectively writes only files belonging to touched categories.\n *\n * For \"remove\" mutations (remove_rule, remove_command, etc.), the affected\n * file is deleted from disk since it won't appear in the rendered map.\n */\nasync function renderAffectedFiles(\n ir: HarnessIR,\n targetDir: string,\n touchedCategories: Set<string>,\n): Promise<void> {\n const fileMap = renderHarness(ir);\n\n // Determine which rendered file paths belong to touched categories\n for (const [relativePath, content] of fileMap) {\n const category = getFileCategory(relativePath);\n if (touchedCategories.has(category)) {\n const fullPath = path.join(targetDir, relativePath);\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n await fs.writeFile(fullPath, content, 'utf-8');\n }\n }\n\n // Handle deletions: for removed commands/rules/agents, delete files that\n // existed in the copy but are absent from the rendered map.\n if (touchedCategories.has('commands')) {\n await deleteOrphanedFiles(targetDir, 'commands', fileMap);\n }\n if (touchedCategories.has('rules')) {\n await deleteOrphanedFiles(targetDir, 'rules', fileMap);\n }\n if (touchedCategories.has('agents')) {\n await deleteOrphanedFiles(targetDir, 'agents', fileMap);\n }\n\n // Handle singleton file deletions: when a category is touched but\n // the rendered map has no entry for its file, delete the stale file.\n if (touchedCategories.has('mcp') && !fileMap.has('.mcp.json')) {\n await fs.unlink(path.join(targetDir, '.mcp.json')).catch(() => {});\n }\n if (touchedCategories.has('settings') && !fileMap.has('settings.json')) {\n await fs.unlink(path.join(targetDir, 'settings.json')).catch(() => {});\n }\n}\n\n/**\n * Map a relative file path to its category for selective rendering.\n */\nfunction getFileCategory(relativePath: string): string {\n if (relativePath === 'CLAUDE.md') return 'claude_md';\n if (relativePath.startsWith('commands/')) return 'commands';\n if (relativePath.startsWith('rules/')) return 'rules';\n if (relativePath.startsWith('agents/')) return 'agents';\n if (relativePath.startsWith('skills/')) return 'skills';\n if (relativePath.startsWith('docs/')) return 'docs';\n if (relativePath.startsWith('hooks/')) return 'hooks';\n if (relativePath === 'settings.json') return 'settings';\n if (relativePath === '.mcp.json') return 'mcp';\n return 'unknown';\n}\n\n/**\n * Delete files in a subdirectory that are present on disk but absent from\n * the rendered file map. This handles \"remove\" IR mutations (e.g., remove_rule).\n */\nasync function deleteOrphanedFiles(\n targetDir: string,\n subdir: string,\n renderedMap: Map<string, string>,\n): Promise<void> {\n const subdirPath = path.join(targetDir, subdir);\n let entries;\n try {\n entries = await fs.readdir(subdirPath);\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const relativePath = `${subdir}/${entry}`;\n if (!renderedMap.has(relativePath)) {\n await fs.unlink(path.join(subdirPath, entry)).catch(() => {});\n }\n }\n}\n\n/**\n * Legacy file-copy + string surgery approach (fallback when IR parsing fails).\n * Preserves the original v2.5.2 behavior exactly.\n */\nasync function applyMutationsLegacy(\n currentHarnessPath: string,\n newHarnessPath: string,\n mutations: Mutation[],\n): Promise<{ newHarnessPath: string; diffPatch: string }> {\n // 1. Copy current harness to new iteration\n await copyDir(currentHarnessPath, newHarnessPath);\n\n // 2. Apply each mutation\n for (const mutation of mutations) {\n await applyLegacyMutation(newHarnessPath, mutation);\n }\n\n // 3. Generate diff\n const diffPatch = await generateDiffLegacy(currentHarnessPath, newHarnessPath);\n\n return { newHarnessPath, diffPatch };\n}\n\n/**\n * Apply a single legacy mutation to a file in the harness directory.\n * This is the original string-surgery approach used in v2.5.2.\n */\nasync function applyLegacyMutation(\n harnessPath: string,\n mutation: Mutation,\n): Promise<void> {\n // Security: reject path traversal\n if (mutation.file.includes('..')) {\n return;\n }\n\n const filePath = path.join(harnessPath, mutation.file);\n\n if (mutation.action === 'replace') {\n if (!mutation.oldText) {\n return;\n }\n let content: string;\n try {\n content = await fs.readFile(filePath, 'utf-8');\n } catch {\n return;\n }\n if (!content.includes(mutation.oldText)) {\n return;\n }\n // Replace first occurrence only — intentional for surgical mutations\n await fs.writeFile(\n filePath,\n content.replace(mutation.oldText, mutation.newText),\n 'utf-8',\n );\n } else if (mutation.action === 'add_section') {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n await fs.writeFile(\n filePath,\n content + '\\n\\n' + mutation.newText,\n 'utf-8',\n );\n } catch {\n // File doesn't exist — create it\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, mutation.newText, 'utf-8');\n }\n } else if (mutation.action === 'create_file') {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, mutation.newText, 'utf-8');\n } else if (mutation.action === 'delete_section') {\n if (!mutation.oldText) {\n return;\n }\n let sectionContent: string;\n try {\n sectionContent = await fs.readFile(filePath, 'utf-8');\n } catch {\n return;\n }\n if (!sectionContent.includes(mutation.oldText)) {\n return;\n }\n await fs.writeFile(filePath, sectionContent.replace(mutation.oldText, ''), 'utf-8');\n } else if (mutation.action === 'delete_file') {\n await fs.unlink(filePath).catch(() => {});\n }\n}\n\n/**\n * Generate a simple unified-diff-style patch between two directories.\n * Compares files in both directories and outputs differences.\n *\n * Attempts to use the IR-based structural diff first. Falls back to the\n * legacy character-diff approach if IR parsing fails for either directory\n * or if the directories don't contain recognizable harness content.\n */\nexport async function generateDiff(\n oldDir: string,\n newDir: string,\n): Promise<string> {\n // Try IR-based diff first — only if both directories have harness content\n try {\n const oldIR = await parseHarness(oldDir);\n const newIR = await parseHarness(newDir);\n\n // Only use IR diff if at least one directory has meaningful harness content\n // (sections, commands, rules, etc.). Otherwise fall through to legacy.\n const oldHasContent = oldIR.sections.length > 0 || oldIR.commands.length > 0 ||\n oldIR.rules.length > 0 || oldIR.agents.length > 0;\n const newHasContent = newIR.sections.length > 0 || newIR.commands.length > 0 ||\n newIR.rules.length > 0 || newIR.agents.length > 0;\n\n if (oldHasContent || newHasContent) {\n const irDiff = diffIR(oldIR, newIR);\n const formatted = formatIRDiff(irDiff);\n\n // \"No changes.\" means identical — normalize to empty string for backward compat\n if (formatted === 'No changes.') {\n // Double-check with legacy diff in case there are non-IR file changes\n const legacyDiff = await generateDiffLegacy(oldDir, newDir);\n return legacyDiff;\n }\n\n // IR diff found structural changes — but also check for non-IR file changes\n const legacyDiff = await generateDiffLegacy(oldDir, newDir);\n if (legacyDiff && !formatted.includes(legacyDiff)) {\n return formatted + '\\n\\n' + legacyDiff;\n }\n return formatted;\n }\n } catch {\n // IR parsing failed — fall back to legacy diff\n }\n\n return generateDiffLegacy(oldDir, newDir);\n}\n\n/**\n * Legacy diff implementation: character-by-character comparison of all files.\n */\nasync function generateDiffLegacy(\n oldDir: string,\n newDir: string,\n): Promise<string> {\n const oldFiles = await readAllFiles(oldDir);\n const newFiles = await readAllFiles(newDir);\n\n const allPaths = new Set([\n ...Object.keys(oldFiles),\n ...Object.keys(newFiles),\n ]);\n const patches: string[] = [];\n\n for (const filePath of [...allPaths].sort()) {\n const oldContent = oldFiles[filePath] ?? '';\n const newContent = newFiles[filePath] ?? '';\n\n if (oldContent === newContent) continue;\n\n patches.push(`--- a/${filePath}`);\n patches.push(`+++ b/${filePath}`);\n\n if (!oldContent) {\n // New file\n for (const line of newContent.split('\\n')) {\n patches.push(`+${line}`);\n }\n } else if (!newContent) {\n // Deleted file\n for (const line of oldContent.split('\\n')) {\n patches.push(`-${line}`);\n }\n } else {\n // Modified — show old lines as removed, new lines as added\n const oldLines = oldContent.split('\\n');\n const newLines = newContent.split('\\n');\n for (const line of oldLines) {\n patches.push(`-${line}`);\n }\n for (const line of newLines) {\n patches.push(`+${line}`);\n }\n }\n patches.push('');\n }\n\n return patches.join('\\n');\n}\n\n/**\n * Recursively read all files in a directory into a map of relative path -> content.\n */\nasync function readAllFiles(dir: string): Promise<Record<string, string>> {\n const result: Record<string, string> = {};\n\n async function walk(current: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const fullPath = path.join(current, entry.name);\n const relativePath = path.relative(dir, fullPath);\n if (entry.isDirectory()) {\n await walk(fullPath);\n } else {\n result[relativePath] = await fs.readFile(fullPath, 'utf-8');\n }\n }\n }\n\n await walk(dir);\n return result;\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { Task } from './types.js';\n\n/**\n * Represents a Beta distribution belief about a task's success rate.\n * Used by Thompson Sampling to select tasks with high uncertainty.\n */\nexport interface TaskBelief {\n taskId: string;\n alpha: number; // successes + 1 (Beta distribution parameter)\n beta: number; // failures + 1 (Beta distribution parameter)\n}\n\n/**\n * Initialize uniform prior beliefs for all tasks.\n * Each task starts with alpha=1, beta=1 (uniform distribution).\n */\nexport function initBeliefs(tasks: Task[]): TaskBelief[] {\n return tasks.map(task => ({\n taskId: task.id,\n alpha: 1,\n beta: 1,\n }));\n}\n\n/**\n * Sample from a Beta distribution using the Joehnk algorithm.\n * Returns a value in [0, 1].\n */\nfunction sampleBeta(alpha: number, beta: number, rng: () => number): number {\n // For alpha=1, beta=1 (uniform), just return rng directly\n if (alpha === 1 && beta === 1) return rng();\n\n // Joehnk's algorithm for general Beta(a, b)\n // Uses rejection sampling via Gamma variates approximation\n // For small alpha/beta, use the inverse CDF method via Gamma ratio\n const gammaA = sampleGamma(alpha, rng);\n const gammaB = sampleGamma(beta, rng);\n return gammaA / (gammaA + gammaB);\n}\n\n/**\n * Sample from Gamma(alpha, 1) using Marsaglia and Tsang's method.\n */\nfunction sampleGamma(alpha: number, rng: () => number): number {\n if (alpha < 1) {\n // Boost: Gamma(alpha) = Gamma(alpha+1) * U^(1/alpha)\n return sampleGamma(alpha + 1, rng) * Math.pow(rng(), 1 / alpha);\n }\n\n const d = alpha - 1 / 3;\n const c = 1 / Math.sqrt(9 * d);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let x: number;\n let v: number;\n do {\n x = sampleNormal(rng);\n v = 1 + c * x;\n } while (v <= 0);\n\n v = v * v * v;\n const u = rng();\n if (u < 1 - 0.0331 * (x * x) * (x * x)) return d * v;\n if (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v))) return d * v;\n }\n}\n\n/**\n * Sample from standard normal using Box-Muller transform.\n */\nfunction sampleNormal(rng: () => number): number {\n const u1 = rng();\n const u2 = rng();\n return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n}\n\n/**\n * Select tasks using Thompson Sampling.\n *\n * For each task, sample from its Beta(alpha, beta) distribution.\n * Select the top-K tasks by sampled value. Tasks with high uncertainty\n * (wide distributions) are more likely to produce extreme samples and\n * thus more likely to be selected.\n *\n * @param beliefs - Current beliefs about each task\n * @param sampleSize - Number of tasks to select\n * @param rng - Random number generator (0-1)\n * @returns Array of selected task IDs (length = sampleSize)\n */\nexport function sampleThompson(\n beliefs: TaskBelief[],\n sampleSize: number,\n rng: () => number,\n): string[] {\n if (sampleSize >= beliefs.length) {\n return beliefs.map(b => b.taskId);\n }\n\n // Sample from each task's Beta distribution\n const samples = beliefs.map(belief => ({\n taskId: belief.taskId,\n sample: sampleBeta(belief.alpha, belief.beta, rng),\n }));\n\n // Sort by sampled value descending, take top-K\n samples.sort((a, b) => b.sample - a.sample);\n return samples.slice(0, sampleSize).map(s => s.taskId);\n}\n\n/**\n * Update beliefs after observing task results.\n *\n * If score >= 70%, increment alpha (success).\n * If score < 70%, increment beta (failure).\n *\n * @param beliefs - Current beliefs\n * @param results - Task scores from this iteration (taskId -> score value 0-100)\n * @returns Updated beliefs (new array, does not mutate input)\n */\nexport function updateBeliefs(\n beliefs: TaskBelief[],\n results: Record<string, number>,\n): TaskBelief[] {\n return beliefs.map(belief => {\n const score = results[belief.taskId];\n if (score === undefined) return belief; // task wasn't evaluated this round\n\n if (score >= 70) {\n return { ...belief, alpha: belief.alpha + 1 };\n } else {\n return { ...belief, beta: belief.beta + 1 };\n }\n });\n}\n\n/**\n * Load persisted beliefs from disk.\n * Returns null if no beliefs file exists.\n */\nexport async function loadBeliefs(workspacePath: string): Promise<TaskBelief[] | null> {\n const beliefsPath = path.join(workspacePath, 'task-beliefs.json');\n try {\n const content = await fs.readFile(beliefsPath, 'utf-8');\n const parsed = JSON.parse(content) as unknown;\n if (!Array.isArray(parsed)) return null;\n // Validate structure\n for (const entry of parsed) {\n if (\n typeof entry !== 'object' || entry === null ||\n typeof (entry as Record<string, unknown>).taskId !== 'string' ||\n typeof (entry as Record<string, unknown>).alpha !== 'number' ||\n typeof (entry as Record<string, unknown>).beta !== 'number'\n ) {\n return null;\n }\n }\n return parsed as TaskBelief[];\n } catch {\n return null;\n }\n}\n\n/**\n * Persist beliefs to disk.\n */\nexport async function saveBeliefs(workspacePath: string, beliefs: TaskBelief[]): Promise<void> {\n const beliefsPath = path.join(workspacePath, 'task-beliefs.json');\n await fs.mkdir(path.dirname(beliefsPath), { recursive: true });\n await fs.writeFile(beliefsPath, JSON.stringify(beliefs, null, 2), 'utf-8');\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport type { HarnessIR } from '../ir/types.js';\n\n/**\n * Metrics capturing the complexity of a harness directory.\n */\nexport interface ComplexityMetrics {\n totalLines: number; // total lines across all harness files\n totalFiles: number; // number of files in harness\n totalSections: number; // number of ## sections in CLAUDE.md\n totalRules: number; // number of files in rules/\n totalCommands: number; // number of files in commands/\n diffFromBaseline: number; // character-level diff ratio (normalized 0-1)\n}\n\n/**\n * Measure the complexity of a harness directory.\n *\n * Counts total lines, files, CLAUDE.md sections, rules/ files, and commands/ files.\n * The diffFromBaseline field is set to 0 here — use computeComplexityCost for comparison.\n */\nexport async function measureComplexity(harnessPath: string): Promise<ComplexityMetrics> {\n let totalLines = 0;\n let totalFiles = 0;\n let totalSections = 0;\n let totalRules = 0;\n let totalCommands = 0;\n\n const allContent = await readAllFilesRecursive(harnessPath);\n\n for (const [relativePath, content] of Object.entries(allContent)) {\n totalFiles++;\n totalLines += content.split('\\n').length;\n\n // Count ## sections in CLAUDE.md\n if (relativePath === 'CLAUDE.md') {\n const sectionMatches = content.match(/^##\\s/gm);\n totalSections = sectionMatches ? sectionMatches.length : 0;\n }\n\n // Count rules/ and commands/ files\n if (relativePath.startsWith('rules/') || relativePath.startsWith('rules\\\\')) {\n totalRules++;\n }\n if (relativePath.startsWith('commands/') || relativePath.startsWith('commands\\\\')) {\n totalCommands++;\n }\n }\n\n return {\n totalLines,\n totalFiles,\n totalSections,\n totalRules,\n totalCommands,\n diffFromBaseline: 0,\n };\n}\n\n/**\n * Measure the complexity of a harness from its in-memory IR representation.\n *\n * This is the IR-native counterpart to `measureComplexity(harnessPath)`.\n * It avoids disk I/O by computing metrics directly from the HarnessIR tree.\n *\n * Counts:\n * - `totalSections`: number of sections in the IR\n * - `totalRules`: number of rule nodes\n * - `totalCommands`: number of command nodes\n * - `totalFiles`: total count of all renderable nodes (sections count as 1 for\n * CLAUDE.md, plus commands, rules, agents, skills, docs, hooks, settings if\n * non-empty, mcp if servers exist)\n * - `totalLines`: sum of content line counts across all content-bearing nodes\n * - `diffFromBaseline`: always 0 (set externally if needed)\n */\nexport function measureComplexityFromIR(ir: HarnessIR): ComplexityMetrics {\n const totalSections = ir.sections.length;\n const totalRules = ir.rules.length;\n const totalCommands = ir.commands.length;\n\n // Count total files: each node type contributes its count\n let totalFiles = 0;\n\n // CLAUDE.md counts as 1 file if there are sections or a name\n if (ir.sections.length > 0 || ir.meta.name) {\n totalFiles += 1;\n }\n\n totalFiles += ir.commands.length;\n totalFiles += ir.rules.length;\n totalFiles += ir.agents.length;\n totalFiles += ir.skills.length;\n totalFiles += ir.docs.length;\n totalFiles += ir.hooks.length;\n\n // settings.json counts as 1 file if it has meaningful content\n const hasSettings =\n ir.settings.statusLine !== undefined ||\n (ir.settings.denyPatterns !== undefined && ir.settings.denyPatterns.length > 0) ||\n Object.keys(ir.settings.raw).length > 0 ||\n Object.values(ir.settings.hooks).some(\n (entries) => entries !== undefined && entries.length > 0,\n );\n if (hasSettings) {\n totalFiles += 1;\n }\n\n // .mcp.json counts as 1 file if servers exist\n if (ir.mcpServers.length > 0) {\n totalFiles += 1;\n }\n\n // Count total lines across all content-bearing nodes\n let totalLines = 0;\n for (const section of ir.sections) {\n totalLines += countLines(section.content);\n }\n for (const cmd of ir.commands) {\n totalLines += countLines(cmd.content);\n }\n for (const rule of ir.rules) {\n totalLines += countLines(rule.content);\n }\n for (const agent of ir.agents) {\n totalLines += countLines(agent.content);\n }\n for (const skill of ir.skills) {\n totalLines += countLines(skill.content);\n }\n for (const doc of ir.docs) {\n totalLines += countLines(doc.content);\n }\n for (const hook of ir.hooks) {\n totalLines += countLines(hook.content);\n }\n\n return {\n totalLines,\n totalFiles,\n totalSections,\n totalRules,\n totalCommands,\n diffFromBaseline: 0,\n };\n}\n\n/**\n * Count the number of lines in a content string.\n * An empty string has 0 lines. A non-empty string has at least 1.\n */\nfunction countLines(content: string): number {\n if (!content) return 0;\n return content.split('\\n').length;\n}\n\n/**\n * Compute a weighted complexity cost between current and baseline harness metrics.\n *\n * Cost components:\n * - Lines added beyond baseline: +0.3 per line (normalized by baseline)\n * - Files added beyond baseline: +5.0 per file (normalized by baseline)\n * - Net character diff ratio (0 = identical, 1 = completely rewritten)\n *\n * Returns a non-negative number. A return of 0 means identical to baseline.\n * Can return negative values when the current harness is simpler (complexity bonus).\n */\nexport function computeComplexityCost(\n current: ComplexityMetrics,\n baseline: ComplexityMetrics,\n): number {\n // Line cost: normalized by baseline size (capped at a minimum of 1 to avoid division by zero)\n const baselineLines = Math.max(baseline.totalLines, 1);\n const lineDelta = (current.totalLines - baseline.totalLines) / baselineLines;\n const lineCost = lineDelta * 0.3;\n\n // File cost: each added file is expensive\n const baselineFiles = Math.max(baseline.totalFiles, 1);\n const fileDelta = (current.totalFiles - baseline.totalFiles) / baselineFiles;\n const fileCost = fileDelta * 5.0;\n\n // Diff ratio is stored in current.diffFromBaseline if pre-computed\n const diffCost = current.diffFromBaseline;\n\n return lineCost + fileCost + diffCost;\n}\n\n/**\n * Apply KL penalty to a raw score.\n *\n * effective_score = rawScore - lambda * complexityCost * 100\n *\n * When lambda = 0, returns rawScore unchanged (regularization disabled).\n *\n * @param rawScore - The raw aggregate score (0-100)\n * @param complexityCost - Complexity cost from computeComplexityCost\n * @param lambda - Regularization strength (default 0.1)\n * @returns Penalized score\n */\nexport function applyKLPenalty(\n rawScore: number,\n complexityCost: number,\n lambda: number,\n): number {\n if (lambda === 0) return rawScore;\n return rawScore - lambda * complexityCost * 100;\n}\n\n/**\n * Compute a character-level diff ratio between two harness directories.\n * Returns a value in [0, 1] where 0 means identical content and 1 means completely different.\n */\nexport async function computeDiffRatio(\n currentPath: string,\n baselinePath: string,\n): Promise<number> {\n const currentFiles = await readAllFilesRecursive(currentPath);\n const baselineFiles = await readAllFilesRecursive(baselinePath);\n\n const allPaths = new Set([\n ...Object.keys(currentFiles),\n ...Object.keys(baselineFiles),\n ]);\n\n if (allPaths.size === 0) return 0;\n\n let totalChars = 0;\n let diffChars = 0;\n\n for (const filePath of allPaths) {\n const currentContent = currentFiles[filePath] ?? '';\n const baselineContent = baselineFiles[filePath] ?? '';\n\n const maxLen = Math.max(currentContent.length, baselineContent.length);\n totalChars += maxLen;\n\n if (currentContent !== baselineContent) {\n // Simple character-level diff: count differing characters\n const minLen = Math.min(currentContent.length, baselineContent.length);\n let charDiffs = Math.abs(currentContent.length - baselineContent.length);\n for (let i = 0; i < minLen; i++) {\n if (currentContent[i] !== baselineContent[i]) charDiffs++;\n }\n diffChars += charDiffs;\n }\n }\n\n return totalChars > 0 ? diffChars / totalChars : 0;\n}\n\n/**\n * Recursively read all files in a directory into a map of relative path -> content.\n */\nasync function readAllFilesRecursive(dir: string): Promise<Record<string, string>> {\n const result: Record<string, string> = {};\n\n async function walk(current: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const fullPath = path.join(current, entry.name);\n const relativePath = path.relative(dir, fullPath);\n if (entry.isDirectory()) {\n await walk(fullPath);\n } else {\n try {\n result[relativePath] = await fs.readFile(fullPath, 'utf-8');\n } catch {\n // Skip unreadable files\n }\n }\n }\n }\n\n await walk(dir);\n return result;\n}\n","/**\n * IR-Aware Targeted Re-evaluation — maps IR mutations to harness aspects\n * and tasks to aspects, enabling the loop to skip tasks unaffected by\n * the current iteration's mutations.\n */\n\nimport type { IRMutation } from '../ir/types.js';\nimport type { Task, EvalTemplate } from './types.js';\n\n/** Semantic aspects of a harness that mutations can affect. */\nexport type HarnessAspect =\n | 'conventions'\n | 'commands'\n | 'rules'\n | 'agents'\n | 'settings'\n | 'mcp'\n | 'architecture'\n | 'verification'\n | 'general';\n\n/** Map a single IR mutation to the harness aspect it affects. */\nfunction mutationToAspect(mutation: IRMutation): HarnessAspect {\n switch (mutation.type) {\n case 'update_section': {\n const id = mutation.sectionId;\n if (id === 'conventions' || id === 'gotchas' || id === 'debugging' || id === 'git') return 'conventions';\n if (id === 'commands' || id === 'custom-key-commands') return 'commands';\n if (id === 'verification') return 'verification';\n if (id === 'architecture') return 'architecture';\n return 'general';\n }\n case 'add_section': {\n const id = mutation.section.id;\n if (id === 'conventions' || id === 'gotchas' || id === 'debugging' || id === 'git') return 'conventions';\n if (id === 'commands' || id === 'custom-key-commands') return 'commands';\n if (id === 'verification') return 'verification';\n if (id === 'architecture') return 'architecture';\n return 'general';\n }\n case 'remove_section':\n case 'reorder_section':\n return 'general';\n case 'add_command':\n case 'update_command':\n case 'remove_command':\n return 'commands';\n case 'add_rule':\n case 'update_rule':\n case 'remove_rule':\n return 'rules';\n case 'add_agent':\n case 'update_agent':\n case 'remove_agent':\n return 'agents';\n case 'add_mcp_server':\n case 'remove_mcp_server':\n return 'mcp';\n case 'update_settings':\n return 'settings';\n case 'raw_text':\n return 'general';\n }\n}\n\n/** Map which eval templates depend on which harness aspects. */\nconst TEMPLATE_ASPECTS: Record<EvalTemplate, HarnessAspect[]> = {\n 'convention-adherence': ['conventions', 'rules'],\n 'workflow-compliance': ['commands', 'verification'],\n 'rule-compliance': ['rules'],\n 'intent-routing': ['settings'],\n 'add-feature': ['general'],\n 'fix-bug': ['general'],\n 'refactor': ['architecture', 'conventions'],\n 'test-writing': ['verification', 'commands'],\n 'config-change': ['settings', 'mcp'],\n 'documentation': ['general'],\n 'persistence-completion': ['commands', 'verification'],\n};\n\n/**\n * Map IR mutations to the harness aspects they affect.\n */\nexport function mutationsToAspects(mutations: IRMutation[]): Set<HarnessAspect> {\n const aspects = new Set<HarnessAspect>();\n for (const m of mutations) {\n aspects.add(mutationToAspect(m));\n }\n return aspects;\n}\n\n/**\n * Determine which harness aspects a task depends on based on its template.\n */\nexport function taskDependsOnAspects(task: Task): Set<HarnessAspect> {\n const aspects = TEMPLATE_ASPECTS[task.template];\n return new Set(aspects ?? ['general']);\n}\n\n/**\n * Determine if a task should be re-evaluated given the changed aspects.\n */\nexport function shouldReEvaluate(task: Task, changedAspects: Set<HarnessAspect>): boolean {\n if (changedAspects.has('general')) return true;\n if (changedAspects.size === 0) return false;\n\n const taskAspects = taskDependsOnAspects(task);\n if (taskAspects.has('general')) return true;\n\n for (const aspect of taskAspects) {\n if (changedAspects.has(aspect)) return true;\n }\n return false;\n}\n\n/**\n * Filter a task list to only tasks that need re-evaluation.\n */\nexport function filterTasksByAspects(tasks: Task[], changedAspects: Set<HarnessAspect>): Task[] {\n return tasks.filter(t => shouldReEvaluate(t, changedAspects));\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { evaluateAll } from './runner.js';\nimport { propose } from './proposer.js';\nimport { applyMutations } from './mutator.js';\nimport { writeIterationLog } from './trace.js';\nimport { copyDir } from './baseline.js';\nimport { initBeliefs, sampleThompson, updateBeliefs, loadBeliefs, saveBeliefs } from './sampling.js';\nimport { measureComplexity, measureComplexityFromIR, computeComplexityCost, applyKLPenalty, computeDiffRatio } from './regularization.js';\nimport { parseHarness } from '../ir/parser.js';\nimport { translateMutations } from '../ir/translate.js';\nimport { filterTasksByAspects, mutationsToAspects } from './targeting.js';\nimport type { HarnessAspect } from './targeting.js';\nimport type { HarnessIR } from '../ir/types.js';\nimport type { TaskBelief } from './sampling.js';\nimport type { ComplexityMetrics } from './regularization.js';\nimport type { KairnConfig } from '../types.js';\nimport type {\n Task,\n Score,\n EvolveConfig,\n IterationLog,\n EvolveResult,\n LoopProgressEvent,\n} from './types.js';\n\n/**\n * Compute dynamic mutation cap based on iteration progress.\n * First 40% of iterations: full cap (exploration).\n * Last 60%: linearly decays to 1 (exploitation).\n */\nexport function computeMutationCap(iter: number, maxIterations: number, maxMutations: number): number {\n if (maxIterations <= 1) return maxMutations;\n const progress = iter / (maxIterations - 1); // 0.0 to 1.0\n if (progress <= 0.4) return maxMutations;\n // Linear decay from maxMutations at 40% to 1 at 100%\n const decayProgress = (progress - 0.4) / 0.6; // 0.0 to 1.0 within decay phase\n return Math.max(1, Math.round(maxMutations * (1 - decayProgress * (1 - 1 / maxMutations))));\n}\n\n/**\n * Run the evolution loop: evaluate -> diagnose -> mutate -> re-evaluate.\n *\n * Each iteration follows these steps:\n * 1. Evaluate all tasks against the current harness\n * 2. Check for regression — if score dropped below best, rollback\n * 3. Check for perfect score — exit early if 100%\n * 4. Propose mutations via the proposer LLM agent\n * 5. Apply mutations to create the next iteration's harness\n * 6. Log iteration results\n * 7. Advance to the next iteration\n *\n * @param workspacePath - Path to .kairn-evolve/ directory\n * @param tasks - Task definitions from tasks.yaml\n * @param kairnConfig - Kairn config with API key and model\n * @param evolveConfig - Evolution config with iterations, proposer model, etc.\n * @param onProgress - Optional callback for real-time progress updates\n * @returns Final evolution result with iteration history and best score\n */\nexport async function evolve(\n workspacePath: string,\n tasks: Task[],\n kairnConfig: KairnConfig,\n evolveConfig: EvolveConfig,\n onProgress?: (event: LoopProgressEvent) => void,\n): Promise<EvolveResult> {\n const history: IterationLog[] = [];\n let bestScore = -1;\n let bestIteration = 0;\n let baselineScore = 0;\n\n // Thompson Sampling: initialize or load beliefs\n const useThompson = evolveConfig.samplingStrategy === 'thompson' && evolveConfig.evalSampleSize > 0;\n let beliefs: TaskBelief[] = useThompson\n ? (await loadBeliefs(workspacePath) ?? initBeliefs(tasks))\n : [];\n\n // KL Regularization: measure baseline complexity\n const useKL = evolveConfig.klLambda > 0;\n let baselineComplexity: ComplexityMetrics | null = null;\n let baselineIR: HarnessIR | null = null;\n if (useKL) {\n const baselineHarness = path.join(workspacePath, 'iterations', '0', 'harness');\n try {\n baselineIR = await parseHarness(baselineHarness);\n baselineComplexity = measureComplexityFromIR(baselineIR);\n } catch {\n // IR parsing failed — fall back to file-based measurement\n try {\n baselineComplexity = await measureComplexity(baselineHarness);\n } catch {\n // Baseline not available yet — will be measured after iteration 0\n }\n }\n }\n\n // Targeted re-evaluation: track which harness aspects changed last iteration\n let lastChangedAspects: Set<HarnessAspect> | null = null;\n\n // Seeded RNG for Thompson Sampling (deterministic per-run, per-branch via rngSeed)\n let rngState = evolveConfig.rngSeed ?? 42;\n const rng = (): number => {\n rngState = (rngState * 1664525 + 1013904223) & 0xffffffff;\n return (rngState >>> 0) / 0x100000000;\n };\n\n for (let iter = 0; iter < evolveConfig.maxIterations; iter++) {\n const harnessPath = path.join(\n workspacePath,\n 'iterations',\n iter.toString(),\n 'harness',\n );\n\n // Verify harness exists for this iteration\n try {\n await fs.access(harnessPath);\n } catch {\n if (iter === 0) {\n throw new Error(\n 'No baseline harness found. Run `kairn evolve baseline` first.',\n );\n }\n break; // No more iterations to run\n }\n\n // 1. EVALUATE (with adaptive pruning on middle iterations)\n onProgress?.({ type: 'iteration-start', iteration: iter });\n\n const isFirstIter = iter === 0;\n const isLastIter = iter === evolveConfig.maxIterations - 1;\n const prevLog = history.length > 0 ? history[history.length - 1] : null;\n\n let tasksToRun = tasks;\n const carriedScores: Record<string, Score> = {};\n const threshold = evolveConfig.pruneThreshold;\n\n if (!isFirstIter && !isLastIter && prevLog) {\n tasksToRun = [];\n for (const task of tasks) {\n const prevScore = prevLog.taskResults[task.id];\n const prevValue = prevScore ? (prevScore.score ?? (prevScore.pass ? 100 : 0)) : 0;\n if (prevValue >= threshold) {\n carriedScores[task.id] = { pass: true, score: prevValue };\n onProgress?.({\n type: 'task-skipped',\n iteration: iter,\n taskId: task.id,\n message: `Skipped ${task.id} (scored ${prevValue.toFixed(0)}% >= ${threshold}% threshold)`,\n });\n } else {\n tasksToRun.push(task);\n }\n }\n\n // Targeted re-evaluation: skip tasks unaffected by last mutation\n if (lastChangedAspects !== null) {\n const targetedTasks = filterTasksByAspects(tasksToRun, lastChangedAspects);\n const skippedByTargeting = tasksToRun.filter(t => !targetedTasks.includes(t));\n for (const task of skippedByTargeting) {\n const prev = prevLog.taskResults[task.id];\n const prevVal = prev ? (prev.score ?? (prev.pass ? 100 : 0)) : 0;\n carriedScores[task.id] = { pass: prevVal >= 50, score: prevVal };\n onProgress?.({\n type: 'task-skipped',\n iteration: iter,\n taskId: task.id,\n message: `Skipped ${task.id} (unaffected by mutations)`,\n });\n }\n tasksToRun = targetedTasks;\n }\n\n // Mini-batch sampling: Thompson or uniform\n const sampleSize = evolveConfig.evalSampleSize;\n if (sampleSize > 0 && sampleSize < tasksToRun.length) {\n let sampled: Set<string>;\n\n if (useThompson) {\n // Thompson Sampling: select tasks proportional to uncertainty\n const relevantBeliefs = beliefs.filter(b => tasksToRun.some(t => t.id === b.taskId));\n const selectedIds = sampleThompson(relevantBeliefs, sampleSize, rng);\n sampled = new Set(selectedIds);\n } else {\n // Uniform: seeded shuffle (v2.5.2 behavior)\n const shuffled = [...tasksToRun].sort((a, b) => {\n const hashA = (iter * 31 + a.id.charCodeAt(0)) % 1000;\n const hashB = (iter * 31 + b.id.charCodeAt(0)) % 1000;\n return hashA - hashB;\n });\n sampled = new Set(shuffled.slice(0, sampleSize).map(t => t.id));\n }\n\n // Carry forward unsampled tasks\n for (const task of tasksToRun) {\n if (!sampled.has(task.id)) {\n const prev = prevLog.taskResults[task.id];\n const prevVal = prev ? (prev.score ?? (prev.pass ? 100 : 0)) : 0;\n carriedScores[task.id] = { pass: prevVal >= 50, score: prevVal };\n onProgress?.({\n type: 'task-skipped',\n iteration: iter,\n taskId: task.id,\n message: `Sampled out ${task.id} (${useThompson ? 'thompson' : 'uniform'} ${sampleSize}/${tasksToRun.length})`,\n });\n }\n }\n tasksToRun = tasksToRun.filter(t => sampled.has(t.id));\n }\n }\n\n const { results: evalResults, aggregate: evalAggregate } = await evaluateAll(\n tasksToRun,\n harnessPath,\n workspacePath,\n iter,\n kairnConfig,\n onProgress,\n evolveConfig.runsPerTask,\n evolveConfig.parallelTasks,\n );\n\n // Merge carried-forward scores with evaluated results\n const results = { ...carriedScores, ...evalResults };\n const allScores = Object.values(results);\n const total = allScores.reduce(\n (sum, s) => sum + (s.score ?? (s.pass ? 100 : 0)),\n 0,\n );\n const rawAggregate = allScores.length > 0 ? total / allScores.length : 0;\n\n // KL Regularization: penalize complexity drift\n let aggregate = rawAggregate;\n let iterComplexityCost: number | undefined;\n if (useKL && baselineComplexity) {\n let currentComplexity: ComplexityMetrics;\n try {\n const iterIR = await parseHarness(harnessPath);\n currentComplexity = measureComplexityFromIR(iterIR);\n } catch {\n currentComplexity = await measureComplexity(harnessPath);\n }\n const diffRatio = await computeDiffRatio(\n harnessPath,\n path.join(workspacePath, 'iterations', '0', 'harness'),\n );\n currentComplexity.diffFromBaseline = diffRatio;\n iterComplexityCost = computeComplexityCost(currentComplexity, baselineComplexity);\n aggregate = applyKLPenalty(rawAggregate, iterComplexityCost, evolveConfig.klLambda);\n }\n\n // Thompson Sampling: update beliefs with EVALUATED results only\n // Carried-forward scores are stale — treating them as fresh observations\n // makes the sampler artificially overconfident and freezes beliefs.\n if (useThompson) {\n const scoreMap: Record<string, number> = {};\n for (const [taskId, score] of Object.entries(evalResults)) {\n scoreMap[taskId] = score.score ?? (score.pass ? 100 : 0);\n }\n beliefs = updateBeliefs(beliefs, scoreMap);\n await saveBeliefs(workspacePath, beliefs);\n }\n\n onProgress?.({ type: 'iteration-scored', iteration: iter, score: aggregate });\n\n if (iter === 0) {\n baselineScore = aggregate;\n // Measure baseline complexity if not yet available\n if (useKL && !baselineComplexity) {\n try {\n baselineIR = await parseHarness(harnessPath);\n baselineComplexity = measureComplexityFromIR(baselineIR);\n } catch {\n baselineComplexity = await measureComplexity(harnessPath);\n }\n }\n }\n\n // 2. ROLLBACK CHECK (aggregate regression OR per-task drop exceeding maxTaskDrop)\n let shouldRollback = iter > 0 && aggregate < bestScore;\n let rollbackMessage = shouldRollback\n ? `Regression: ${aggregate.toFixed(1)}% < ${bestScore.toFixed(1)}%. Rolling back.`\n : '';\n\n // Compare per-task scores against the best iteration (not previous — previous may be a rejected rollback)\n const bestLog = history.find(h => h.iteration === bestIteration);\n if (iter > 0 && !shouldRollback && bestLog) {\n for (const [taskId, score] of Object.entries(results)) {\n const currValue = score.score ?? (score.pass ? 100 : 0);\n const bestTaskScore = bestLog.taskResults[taskId];\n const bestValue = bestTaskScore ? (bestTaskScore.score ?? (bestTaskScore.pass ? 100 : 0)) : currValue;\n const drop = bestValue - currValue;\n if (drop > evolveConfig.maxTaskDrop) {\n shouldRollback = true;\n rollbackMessage = `Task ${taskId} dropped ${drop.toFixed(0)} points (${bestValue.toFixed(0)}% → ${currValue.toFixed(0)}%). Rolling back.`;\n onProgress?.({\n type: 'task-regression',\n iteration: iter,\n taskId,\n score: currValue,\n message: `dropped ${drop.toFixed(0)} points (limit: ${evolveConfig.maxTaskDrop})`,\n });\n break;\n }\n }\n }\n\n if (shouldRollback) {\n onProgress?.({\n type: 'rollback',\n iteration: iter,\n score: aggregate,\n message: rollbackMessage,\n });\n\n // Log the regression\n const rollbackLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal: null,\n diffPatch: null,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, rollbackLog);\n history.push(rollbackLog);\n\n // Instead of just copying the best harness unchanged, propose NEW mutations\n // on the best harness so the next iteration has something different to evaluate.\n const bestHarnessPath = path.join(\n workspacePath,\n 'iterations',\n bestIteration.toString(),\n 'harness',\n );\n\n if (iter + 1 < evolveConfig.maxIterations) {\n onProgress?.({ type: 'proposing', iteration: iter, message: 'Proposing new mutations after rollback' });\n try {\n let rollbackProposal = await propose(\n iter,\n workspacePath,\n bestHarnessPath,\n history,\n tasks,\n kairnConfig,\n evolveConfig.proposerModel,\n );\n const rollbackCap = computeMutationCap(iter, evolveConfig.maxIterations, evolveConfig.maxMutationsPerIteration);\n if (rollbackProposal.mutations.length > rollbackCap) {\n rollbackProposal = {\n ...rollbackProposal,\n mutations: rollbackProposal.mutations.slice(0, rollbackCap),\n };\n }\n const nextIterDir = path.join(workspacePath, 'iterations', (iter + 1).toString());\n await applyMutations(bestHarnessPath, nextIterDir, rollbackProposal.mutations);\n // Compute changed aspects for targeted re-evaluation\n try {\n const rollbackIR = await parseHarness(bestHarnessPath);\n const irMuts = translateMutations(rollbackProposal.mutations, rollbackIR);\n lastChangedAspects = mutationsToAspects(irMuts);\n } catch {\n lastChangedAspects = null;\n }\n onProgress?.({\n type: 'mutations-applied',\n iteration: iter,\n mutationCount: rollbackProposal.mutations.length,\n });\n } catch {\n // Proposer or mutation failed — fall back to copying best harness unchanged\n const nextIterDir = path.join(workspacePath, 'iterations', (iter + 1).toString());\n await copyDir(bestHarnessPath, path.join(nextIterDir, 'harness'));\n }\n }\n continue;\n }\n\n // 3. UPDATE BEST\n bestScore = aggregate;\n bestIteration = iter;\n\n // 4. PERFECT SCORE CHECK\n if (aggregate >= 100) {\n onProgress?.({ type: 'perfect-score', iteration: iter, score: aggregate });\n const perfectLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal: null,\n diffPatch: null,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, perfectLog);\n history.push(perfectLog);\n break;\n }\n\n // 5. PROPOSE (skip on last iteration — no point mutating if we won't eval)\n if (iter === evolveConfig.maxIterations - 1) {\n const finalLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal: null,\n diffPatch: null,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, finalLog);\n history.push(finalLog);\n break;\n }\n\n onProgress?.({ type: 'proposing', iteration: iter });\n let proposal;\n try {\n proposal = await propose(\n iter,\n workspacePath,\n harnessPath,\n history,\n tasks,\n kairnConfig,\n evolveConfig.proposerModel,\n );\n // Enforce mutation cap\n const iterCap = computeMutationCap(iter, evolveConfig.maxIterations, evolveConfig.maxMutationsPerIteration);\n if (proposal.mutations.length > iterCap) {\n proposal = {\n ...proposal,\n mutations: proposal.mutations.slice(0, iterCap),\n };\n }\n } catch (err) {\n // Proposer failed — log the error and copy current harness forward unchanged\n const errMsg = err instanceof Error ? err.message : String(err);\n onProgress?.({\n type: 'proposer-error',\n iteration: iter,\n message: `Proposer failed: ${errMsg}`,\n });\n const nextIterDir = path.join(\n workspacePath,\n 'iterations',\n (iter + 1).toString(),\n );\n await copyDir(harnessPath, path.join(nextIterDir, 'harness'));\n const skipLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal: null,\n diffPatch: null,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, skipLog);\n history.push(skipLog);\n continue;\n }\n\n // 6. APPLY MUTATIONS\n const nextIterDir = path.join(\n workspacePath,\n 'iterations',\n (iter + 1).toString(),\n );\n let diffPatch = '';\n try {\n const mutationResult = await applyMutations(\n harnessPath,\n nextIterDir,\n proposal.mutations,\n );\n diffPatch = mutationResult.diffPatch;\n // Compute changed aspects for targeted re-evaluation\n try {\n const currentIR = await parseHarness(harnessPath);\n const irMuts = translateMutations(proposal.mutations, currentIR);\n lastChangedAspects = mutationsToAspects(irMuts);\n } catch {\n lastChangedAspects = null;\n }\n } catch {\n // Mutation failed — copy current harness forward unchanged\n await copyDir(harnessPath, path.join(nextIterDir, 'harness'));\n lastChangedAspects = null;\n }\n\n onProgress?.({\n type: 'mutations-applied',\n iteration: iter,\n mutationCount: proposal.mutations.length,\n });\n\n // 7. LOG\n const iterLog: IterationLog = {\n iteration: iter,\n score: aggregate,\n taskResults: results,\n proposal,\n diffPatch,\n timestamp: new Date().toISOString(),\n rawScore: useKL ? rawAggregate : undefined,\n complexityCost: iterComplexityCost,\n };\n await writeIterationLog(workspacePath, iterLog);\n history.push(iterLog);\n }\n\n // PRINCIPAL PROPOSER: after normal loop, synthesize the best harness from all learnings\n if (evolveConfig.usePrincipal && history.length >= 2) {\n onProgress?.({ type: 'proposing', iteration: history.length, message: 'Principal Proposer synthesizing final harness' });\n\n const baselineHarnessPath = path.join(workspacePath, 'iterations', '0', 'harness');\n try {\n const principalProposal = await propose(\n history.length,\n workspacePath,\n baselineHarnessPath,\n history,\n tasks,\n kairnConfig,\n evolveConfig.proposerModel,\n );\n\n if (principalProposal.mutations.length > evolveConfig.maxMutationsPerIteration) {\n principalProposal.mutations = principalProposal.mutations.slice(0, evolveConfig.maxMutationsPerIteration);\n }\n\n const principalIterNum = history.length;\n const principalIterDir = path.join(workspacePath, 'iterations', principalIterNum.toString());\n const mutResult = await applyMutations(baselineHarnessPath, principalIterDir, principalProposal.mutations);\n\n onProgress?.({ type: 'iteration-start', iteration: principalIterNum });\n const { results: principalResults, aggregate: principalAggregate } = await evaluateAll(\n tasks,\n mutResult.newHarnessPath,\n workspacePath,\n principalIterNum,\n kairnConfig,\n onProgress,\n evolveConfig.runsPerTask,\n evolveConfig.parallelTasks,\n );\n onProgress?.({ type: 'iteration-scored', iteration: principalIterNum, score: principalAggregate });\n\n const principalLog: IterationLog = {\n iteration: principalIterNum,\n score: principalAggregate,\n taskResults: principalResults,\n proposal: principalProposal,\n diffPatch: mutResult.diffPatch,\n timestamp: new Date().toISOString(),\n };\n await writeIterationLog(workspacePath, principalLog);\n history.push(principalLog);\n\n if (principalAggregate > bestScore) {\n bestScore = principalAggregate;\n bestIteration = principalIterNum;\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n onProgress?.({ type: 'proposer-error', iteration: history.length, message: `Principal failed: ${errMsg}` });\n }\n }\n\n // Save run summary to proposer memory for cross-run learning\n try {\n const { buildRunSummary, saveRunSummary } = await import('./memory.js');\n const summary = buildRunSummary(history, baselineScore, bestScore);\n await saveRunSummary(workspacePath, summary);\n } catch {\n // Memory save is non-critical — don't fail the run\n }\n\n onProgress?.({\n type: 'complete',\n iteration: history.length > 0 ? history.length - 1 : 0,\n score: bestScore,\n });\n\n return {\n iterations: history,\n bestIteration,\n bestScore,\n baselineScore,\n };\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { callLLM } from '../llm.js';\nimport { readHarnessFiles } from './proposer.js';\nimport { parseProposerResponse } from './proposer.js';\nimport { applyMutations } from './mutator.js';\nimport { evaluateAll } from './runner.js';\nimport { copyDir } from './baseline.js';\nimport type { KairnConfig } from '../types.js';\nimport type {\n Task,\n Score,\n EvolveConfig,\n Mutation,\n IterationLog,\n} from './types.js';\nimport type { BranchResult } from './population.js';\nimport type { TaskBelief } from './sampling.js';\n\n/**\n * Context passed to the Meta-Principal for cross-branch synthesis.\n */\nexport interface SynthesisContext {\n branches: BranchResult[];\n tasks: Task[];\n baselineHarnessPath: string;\n}\n\n/**\n * Build the system prompt for the Meta-Principal.\n */\nfunction buildMetaPrincipalSystemPrompt(numBranches: number): string {\n return `You are reviewing the COMPLETE results of ${numBranches} independent evolution runs.\nEach branch explored different mutations and saw different task subsets.\n\nYour job is SYNTHESIS, not iteration:\n1. Identify mutations that helped across multiple branches (high-confidence wins)\n2. Identify mutations that helped in one branch but weren't tested in others (potential wins)\n3. Identify mutations that consistently hurt scores (high-confidence losses)\n4. Resolve conflicts: if Branch 0 says \"add verbose error rules\" but Branch 2 says \"remove verbose rules\", use the per-task evidence to decide\n\nApply your selected mutations to the BASELINE harness (not any branch's final harness).\nThis ensures a clean synthesis — no accumulated branch-specific artifacts.\n\n## Output Format\nReturn a JSON object:\n{\n \"reasoning\": \"Your synthesis analysis — which mutations from which branches, why...\",\n \"mutations\": [\n { \"file\": \"CLAUDE.md\", \"action\": \"replace\", \"old_text\": \"...\", \"new_text\": \"...\", \"rationale\": \"...\" }\n ],\n \"expected_impact\": { \"task-id\": \"+N% — explanation\" }\n}\n\n## Rules\n- Apply mutations to the BASELINE, not any branch's final harness\n- Prefer mutations with cross-branch evidence over single-branch evidence\n- If two mutations conflict, choose the one with stronger per-task evidence\n- Keep it concise: harness bloat defeats the purpose\n\nReturn ONLY valid JSON.`;\n}\n\n/**\n * Build the user message for the Meta-Principal with all branch evidence.\n *\n * Includes: iteration logs, per-task score matrices, Thompson beliefs,\n * complexity metrics, and the baseline harness.\n */\nexport function buildSynthesisPrompt(context: SynthesisContext): string {\n const parts: string[] = [];\n\n // Section 1: Baseline harness summary\n parts.push('## Baseline Harness\\n');\n parts.push(`Path: ${context.baselineHarnessPath}\\n`);\n\n // Section 2: Per-branch results\n for (const branch of context.branches) {\n parts.push(`\\n## Branch ${branch.branchId}\\n`);\n parts.push(`Best Score: ${branch.result.bestScore.toFixed(1)}% (iteration ${branch.result.bestIteration})\\n`);\n parts.push(`Baseline Score: ${branch.result.baselineScore.toFixed(1)}%\\n`);\n\n // Iteration logs with proposals\n for (const log of branch.result.iterations) {\n parts.push(`\\n### Branch ${branch.branchId} — Iteration ${log.iteration} (score: ${log.score.toFixed(1)}%)\\n`);\n\n // Raw vs penalized score\n if (log.rawScore !== undefined) {\n parts.push(`Raw score: ${log.rawScore.toFixed(1)}%, Complexity cost: ${log.complexityCost?.toFixed(3) ?? 'N/A'}\\n`);\n }\n\n // Task results\n const taskLines = Object.entries(log.taskResults)\n .map(([id, s]) => ` - ${id}: ${s.score !== undefined ? s.score : (s.pass ? 100 : 0)}%`)\n .join('\\n');\n parts.push(`Task results:\\n${taskLines}\\n`);\n\n // Proposal\n if (log.proposal) {\n parts.push(`Proposal reasoning: ${log.proposal.reasoning}\\n`);\n parts.push(`Mutations (${log.proposal.mutations.length}):\\n`);\n for (const m of log.proposal.mutations) {\n parts.push(` - ${m.action} ${m.file}: ${m.rationale}\\n`);\n }\n } else {\n parts.push('(No proposal — baseline or rollback)\\n');\n }\n }\n\n // Thompson beliefs\n if (branch.beliefs.length > 0) {\n parts.push(`\\nThompson Beliefs (Branch ${branch.branchId}):\\n`);\n for (const belief of branch.beliefs) {\n const mean = belief.alpha / (belief.alpha + belief.beta);\n const uncertainty = 1 / (belief.alpha + belief.beta);\n parts.push(` - ${belief.taskId}: mean=${mean.toFixed(2)}, uncertainty=${uncertainty.toFixed(3)} (α=${belief.alpha}, β=${belief.beta})\\n`);\n }\n }\n }\n\n // Section 3: Cross-branch score matrix\n parts.push('\\n## Cross-Branch Score Matrix\\n');\n parts.push('Task | ' + context.branches.map(b => `Branch ${b.branchId}`).join(' | ') + '\\n');\n\n const allTaskIds = new Set<string>();\n for (const branch of context.branches) {\n const lastIter = branch.result.iterations[branch.result.iterations.length - 1];\n if (lastIter) {\n for (const taskId of Object.keys(lastIter.taskResults)) {\n allTaskIds.add(taskId);\n }\n }\n }\n\n for (const taskId of [...allTaskIds].sort()) {\n const scores = context.branches.map(b => {\n const bestIter = b.result.iterations.find(i => i.iteration === b.result.bestIteration);\n const score = bestIter?.taskResults[taskId];\n return score ? (score.score ?? (score.pass ? 100 : 0)).toFixed(0) + '%' : 'N/A';\n });\n parts.push(`${taskId} | ${scores.join(' | ')}\\n`);\n }\n\n // Section 4: Task definitions (description only — no rubrics)\n parts.push('\\n## Task Definitions\\n');\n for (const task of context.tasks) {\n parts.push(`- ${task.id} (${task.template}): ${task.description}\\n`);\n }\n\n return parts.join('');\n}\n\n/**\n * Call the Meta-Principal LLM to synthesize the best harness from all branches.\n *\n * @param context - All branch results, tasks, and baseline path\n * @param kairnConfig - Kairn config (API key, model)\n * @param evolveConfig - Evolution config (proposer model)\n * @returns Synthesized mutations and reasoning\n */\nexport async function synthesizeBranches(\n context: SynthesisContext,\n kairnConfig: KairnConfig,\n evolveConfig: EvolveConfig,\n): Promise<{ mutations: Mutation[]; reasoning: string }> {\n const userMessage = buildSynthesisPrompt(context);\n const systemPrompt = buildMetaPrincipalSystemPrompt(context.branches.length);\n\n // Read baseline harness to include in context\n const harnessFiles = await readHarnessFiles(context.baselineHarnessPath);\n const harnessSection = Object.entries(harnessFiles)\n .map(([file, content]) => `### ${file}\\n\\`\\`\\`\\n${content}\\n\\`\\`\\``)\n .join('\\n\\n');\n\n const fullMessage = `## Current Baseline Harness Files\\n\\n${harnessSection}\\n\\n${userMessage}`;\n\n const proposerConfig: KairnConfig = { ...kairnConfig, model: evolveConfig.proposerModel };\n const response = await callLLM(proposerConfig, fullMessage, {\n systemPrompt,\n maxTokens: 8192,\n jsonMode: true,\n cacheControl: true,\n });\n\n const proposal = parseProposerResponse(response);\n return {\n mutations: proposal.mutations,\n reasoning: proposal.reasoning,\n };\n}\n\n/**\n * Evaluate the synthesized harness against ALL tasks (full suite, no sampling).\n *\n * @param synthesisHarnessPath - Path to the synthesized harness\n * @param tasks - All task definitions\n * @param workspacePath - Workspace directory for traces\n * @param kairnConfig - Kairn config\n * @returns Evaluation results and aggregate score\n */\nexport async function evaluateSynthesis(\n synthesisHarnessPath: string,\n tasks: Task[],\n workspacePath: string,\n kairnConfig: KairnConfig,\n): Promise<{ results: Record<string, Score>; aggregate: number }> {\n const synthesisIterNum = 999; // Distinguishes synthesis eval from branch evals\n return evaluateAll(\n tasks,\n synthesisHarnessPath,\n workspacePath,\n synthesisIterNum,\n kairnConfig,\n undefined,\n 1, // single run per task for synthesis\n 2, // moderate parallelism\n );\n}\n\n/**\n * Run the full synthesis pipeline: build prompt, call LLM, apply mutations,\n * evaluate, and compare against the best branch.\n *\n * @param context - All branch results\n * @param kairnConfig - Kairn config\n * @param evolveConfig - Evolution config\n * @param workspacePath - Root workspace for synthesis output\n * @returns Synthesis evaluation result, or null if synthesis failed\n */\nexport async function runSynthesis(\n context: SynthesisContext,\n kairnConfig: KairnConfig,\n evolveConfig: EvolveConfig,\n workspacePath: string,\n): Promise<{ result: { results: Record<string, Score>; aggregate: number }; mutations: Mutation[]; reasoning: string } | null> {\n try {\n // 1. Call Meta-Principal\n const { mutations, reasoning } = await synthesizeBranches(context, kairnConfig, evolveConfig);\n\n if (mutations.length === 0) {\n return null;\n }\n\n // 2. Apply mutations to baseline\n const synthesisDir = path.join(workspacePath, 'synthesis');\n const { newHarnessPath } = await applyMutations(\n context.baselineHarnessPath,\n synthesisDir,\n mutations,\n );\n\n // 3. Evaluate against all tasks\n const evalResult = await evaluateSynthesis(\n newHarnessPath,\n context.tasks,\n workspacePath,\n kairnConfig,\n );\n\n return { result: evalResult, mutations, reasoning };\n } catch {\n return null;\n }\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport { evolve } from './loop.js';\nimport { runSynthesis } from './synthesis.js';\nimport type { KairnConfig } from '../types.js';\nimport type {\n Task,\n EvolveConfig,\n EvolveResult,\n LoopProgressEvent,\n} from './types.js';\nimport type { TaskBelief } from './sampling.js';\n\n/**\n * Configuration for a single PBT branch.\n */\nexport interface BranchConfig {\n branchId: number;\n seed: number; // RNG seed for Thompson Sampling\n workspacePath: string; // .kairn-evolve/branches/{N}/\n}\n\n/**\n * Result from a single PBT branch.\n */\nexport interface BranchResult {\n branchId: number;\n result: EvolveResult;\n finalHarnessPath: string;\n beliefs: TaskBelief[]; // final Thompson beliefs from this branch\n}\n\n/**\n * Aggregate result from a PBT run (all branches + optional synthesis).\n */\nexport interface PBTResult {\n branches: BranchResult[];\n synthesizedResult?: EvolveResult; // after Meta-Principal (Step 4)\n bestBranch: number;\n bestScore: number;\n}\n\n/**\n * Initialize branch workspaces by copying the baseline harness and config into\n * each branch directory.\n *\n * Creates: .kairn-evolve/branches/{0..N-1}/ with iterations/0/harness/ and tasks.yaml\n *\n * @param workspacePath - Root .kairn-evolve/ directory\n * @param baselinePath - Path to baseline harness (usually .kairn-evolve/baseline/)\n * @param numBranches - Number of parallel branches to create\n * @returns Array of BranchConfig with unique seeds\n */\nexport async function initBranches(\n workspacePath: string,\n baselinePath: string,\n numBranches: number,\n): Promise<BranchConfig[]> {\n const branchesDir = path.join(workspacePath, 'branches');\n await fs.mkdir(branchesDir, { recursive: true });\n\n const configs: BranchConfig[] = [];\n\n for (let i = 0; i < numBranches; i++) {\n const branchPath = path.join(branchesDir, i.toString());\n const harnessPath = path.join(branchPath, 'iterations', '0', 'harness');\n\n // Copy baseline harness into branch's iteration 0\n await copyDir(baselinePath, harnessPath);\n\n // Copy tasks.yaml if it exists in the workspace\n const tasksYaml = path.join(workspacePath, 'tasks.yaml');\n try {\n await fs.access(tasksYaml);\n await fs.copyFile(tasksYaml, path.join(branchPath, 'tasks.yaml'));\n } catch {\n // tasks.yaml doesn't exist in workspace — skip\n }\n\n // Copy config.yaml if it exists\n const configYaml = path.join(workspacePath, 'config.yaml');\n try {\n await fs.access(configYaml);\n await fs.copyFile(configYaml, path.join(branchPath, 'config.yaml'));\n } catch {\n // config.yaml doesn't exist — skip\n }\n\n // Each branch gets a unique seed derived from branch index\n const seed = 42 + i * 1337;\n\n configs.push({\n branchId: i,\n seed,\n workspacePath: branchPath,\n });\n }\n\n return configs;\n}\n\n/**\n * Run N parallel evolution branches, each with its own workspace, seed, and\n * Thompson Sampling beliefs.\n *\n * All branches run concurrently via Promise.all. Each branch operates on\n * an independent copy of the baseline harness, so mutations in one branch\n * never affect another.\n *\n * @param workspacePath - Root .kairn-evolve/ directory\n * @param tasks - Task definitions from tasks.yaml\n * @param kairnConfig - Kairn config with API key and model\n * @param evolveConfig - Evolution config (iterations, proposer, etc.)\n * @param numBranches - Number of parallel branches (default: evolveConfig.pbtBranches)\n * @param onProgress - Optional callback for real-time progress (includes branchId)\n * @returns PBTResult with all branch results and best branch identification\n */\nexport async function runPopulation(\n workspacePath: string,\n tasks: Task[],\n kairnConfig: KairnConfig,\n evolveConfig: EvolveConfig,\n numBranches?: number,\n onProgress?: (event: LoopProgressEvent & { branchId?: number }) => void,\n): Promise<PBTResult> {\n const branches = numBranches ?? evolveConfig.pbtBranches;\n\n // Initialize branch workspaces\n const baselinePath = path.join(workspacePath, 'baseline');\n const branchConfigs = await initBranches(workspacePath, baselinePath, branches);\n\n // Run all branches concurrently\n const branchPromises = branchConfigs.map(async (branchConfig) => {\n // Each branch gets its own evolve config with unique seed behavior\n // The seed is embedded in the workspace path (Thompson Sampling reads/writes\n // beliefs per-workspace, so each branch naturally gets independent beliefs)\n const branchEvolveConfig: EvolveConfig = {\n ...evolveConfig,\n // Disable principal for individual branches — synthesis replaces it\n usePrincipal: false,\n // Each branch gets its own RNG seed for Thompson Sampling diversity\n rngSeed: branchConfig.seed,\n };\n\n const branchProgress = onProgress\n ? (event: LoopProgressEvent) => {\n onProgress({ ...event, branchId: branchConfig.branchId });\n }\n : undefined;\n\n const result = await evolve(\n branchConfig.workspacePath,\n tasks,\n kairnConfig,\n branchEvolveConfig,\n branchProgress,\n );\n\n // Find the best iteration's harness path\n const finalHarnessPath = path.join(\n branchConfig.workspacePath,\n 'iterations',\n result.bestIteration.toString(),\n 'harness',\n );\n\n // Load final beliefs\n let beliefs: TaskBelief[] = [];\n try {\n const beliefsPath = path.join(branchConfig.workspacePath, 'task-beliefs.json');\n const beliefsContent = await fs.readFile(beliefsPath, 'utf-8');\n beliefs = JSON.parse(beliefsContent) as TaskBelief[];\n } catch {\n // No beliefs saved — branch may have used uniform sampling\n }\n\n return {\n branchId: branchConfig.branchId,\n result,\n finalHarnessPath,\n beliefs,\n } satisfies BranchResult;\n });\n\n const branchResults = await Promise.all(branchPromises);\n\n // Identify best branch\n let bestBranch = 0;\n let bestScore = -1;\n for (const br of branchResults) {\n if (br.result.bestScore > bestScore) {\n bestScore = br.result.bestScore;\n bestBranch = br.branchId;\n }\n }\n\n // Meta-Principal synthesis: combine best mutations from all branches\n let synthesizedResult: EvolveResult | undefined;\n try {\n const baselinePath = path.join(workspacePath, 'baseline');\n const synthesisResult = await runSynthesis(\n { branches: branchResults, tasks, baselineHarnessPath: baselinePath },\n kairnConfig,\n evolveConfig,\n workspacePath,\n );\n\n if (synthesisResult) {\n const synthScore = synthesisResult.result.aggregate;\n synthesizedResult = {\n iterations: [{\n iteration: 0,\n score: synthScore,\n taskResults: synthesisResult.result.results,\n proposal: {\n reasoning: synthesisResult.reasoning,\n mutations: synthesisResult.mutations,\n expectedImpact: {},\n },\n diffPatch: null,\n timestamp: new Date().toISOString(),\n }],\n bestIteration: 0,\n bestScore: synthScore,\n baselineScore: bestScore,\n };\n\n onProgress?.({\n type: 'iteration-scored',\n iteration: 0,\n score: synthScore,\n message: `Meta-Principal synthesis: ${synthScore.toFixed(1)}%`,\n });\n\n // If synthesis beats all branches, it becomes the best\n if (synthScore > bestScore) {\n bestScore = synthScore;\n bestBranch = -1; // -1 indicates synthesis won\n }\n }\n } catch {\n // Synthesis failed — use best branch result\n }\n\n return {\n branches: branchResults,\n synthesizedResult,\n bestBranch,\n bestScore,\n };\n}\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { createRequire } from \"module\";\nimport { initCommand } from \"./commands/init.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\") as { version: string };\nimport { describeCommand } from \"./commands/describe.js\";\nimport { listCommand } from \"./commands/list.js\";\nimport { activateCommand } from \"./commands/activate.js\";\nimport { updateRegistryCommand } from \"./commands/update-registry.js\";\nimport { optimizeCommand } from \"./commands/optimize.js\";\nimport { doctorCommand } from \"./commands/doctor.js\";\nimport { registryCommand } from \"./commands/registry.js\";\nimport { templatesCommand } from \"./commands/templates.js\";\nimport { keysCommand } from \"./commands/keys.js\";\nimport { evolveCommand } from \"./commands/evolve.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"kairn\")\n .description(\n \"Compile natural language intent into optimized Claude Code environments\"\n )\n .version(pkg.version)\n .option(\"--no-color\", \"Disable colored output\");\n\nprogram.addCommand(initCommand);\nprogram.addCommand(describeCommand);\nprogram.addCommand(optimizeCommand);\nprogram.addCommand(listCommand);\nprogram.addCommand(activateCommand);\nprogram.addCommand(updateRegistryCommand);\nprogram.addCommand(doctorCommand);\nprogram.addCommand(registryCommand);\nprogram.addCommand(templatesCommand);\nprogram.addCommand(keysCommand);\nprogram.addCommand(evolveCommand);\n\n// Check for --no-color before parsing (Commander handles it but chalk needs manual disable)\nif (process.argv.includes(\"--no-color\") || process.env.NO_COLOR) {\n chalk.level = 0;\n}\n\nprogram.parse();\n","import { Command } from \"commander\";\nimport { confirm, input, password, select } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport OpenAI from \"openai\";\nimport { execFileSync } from \"child_process\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { loadConfig, saveConfig, getConfigPath, getTemplatesDir } from \"../config.js\";\nimport type { KairnConfig, LLMProvider, AuthType } from \"../types.js\";\nimport { getAccessToken } from \"../auth/keychain.js\";\nimport { PROVIDER_CONFIGS, PROVIDER_MODELS, PROVIDER_CHOICES, getProviderName, getBaseURL, getVerifyModel } from \"../providers.js\";\nimport { ui } from \"../ui.js\";\nimport { printFullBanner } from \"../logo.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nasync function installSeedTemplates(): Promise<void> {\n const templatesDir = getTemplatesDir();\n await fs.mkdir(templatesDir, { recursive: true });\n\n const candidates = [\n path.resolve(__dirname, \"../registry/templates\"),\n path.resolve(__dirname, \"../src/registry/templates\"),\n path.resolve(__dirname, \"../../src/registry/templates\"),\n ];\n\n let seedDir: string | null = null;\n for (const candidate of candidates) {\n try {\n await fs.access(candidate);\n seedDir = candidate;\n break;\n } catch {\n continue;\n }\n }\n\n if (!seedDir) return;\n\n const files = (await fs.readdir(seedDir)).filter((f) => f.endsWith(\".json\"));\n let installed = 0;\n\n for (const file of files) {\n const dest = path.join(templatesDir, file);\n try {\n await fs.access(dest);\n // File already exists — don't overwrite user modifications\n } catch {\n await fs.copyFile(path.join(seedDir, file), dest);\n installed++;\n }\n }\n\n if (installed > 0) {\n console.log(ui.success(`${installed} template${installed === 1 ? \"\" : \"s\"} installed`));\n }\n}\n\nasync function verifyKey(\n provider: LLMProvider,\n apiKey: string,\n baseURL?: string,\n model?: string,\n): Promise<boolean> {\n try {\n if (provider === \"anthropic\") {\n const client = new Anthropic({ apiKey });\n await client.messages.create({\n model: getVerifyModel(provider, model || \"claude-haiku-4-5-20251001\"),\n max_tokens: 10,\n messages: [{ role: \"user\", content: \"ping\" }],\n });\n return true;\n }\n\n // All other providers use OpenAI-compatible API\n const verifyModel = provider === \"other\"\n ? (model || \"test\")\n : getVerifyModel(provider, model || \"\");\n const resolvedBaseURL = getBaseURL(provider, baseURL);\n\n const clientOptions: { apiKey: string; baseURL?: string } = { apiKey };\n if (resolvedBaseURL) clientOptions.baseURL = resolvedBaseURL;\n\n const client = new OpenAI(clientOptions);\n await client.chat.completions.create({\n model: verifyModel,\n max_tokens: 10,\n messages: [{ role: \"user\", content: \"ping\" }],\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction detectClaudeCode(): boolean {\n try {\n execFileSync(\"which\", [\"claude\"], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\nexport const initCommand = new Command(\"init\")\n .description(\"Set up Kairn with your API key\")\n .action(async () => {\n printFullBanner(\"Setup\");\n\n const existing = await loadConfig();\n if (existing) {\n console.log(ui.warn(`Config already exists at ${chalk.dim(getConfigPath())}`));\n console.log(ui.warn(\"Running setup will overwrite it.\\n\"));\n }\n\n const provider = await select<LLMProvider>({\n message: \"LLM provider\",\n choices: PROVIDER_CHOICES,\n });\n\n let model: string;\n let baseURL: string | undefined;\n let providerDisplayName: string;\n\n if (provider === \"other\") {\n // Custom OpenAI-compatible endpoint\n providerDisplayName = \"Custom endpoint\";\n baseURL = await input({ message: \"Base URL\" });\n model = await input({ message: \"Model name\" });\n } else {\n providerDisplayName = getProviderName(provider);\n model = await select({\n message: \"Compilation model\",\n choices: PROVIDER_MODELS[provider],\n });\n }\n\n // For Anthropic: offer Claude Code subscription auth as an alternative\n let apiKey = \"\";\n let authType: AuthType = \"api-key\";\n\n if (provider === \"anthropic\") {\n const oauthToken = await getAccessToken();\n if (oauthToken) {\n const useOAuth = await confirm({\n message: \"Claude Code subscription detected. Use it instead of an API key? (experimental — may break)\",\n default: true,\n });\n if (useOAuth) {\n authType = \"claude-code-oauth\";\n console.log(ui.warn(\"Using Claude Code OAuth token. This is undocumented and may break at any time.\"));\n console.log(ui.success(\"OAuth token validated\"));\n }\n }\n }\n\n if (authType === \"api-key\") {\n apiKey = await password({\n message: `${providerDisplayName} API key${provider === \"other\" ? \" (Enter to skip)\" : \"\"}`,\n mask: \"*\",\n });\n\n if (!apiKey && provider !== \"other\") {\n console.log(ui.error(\"No API key provided. Aborting.\"));\n process.exit(1);\n }\n\n if (apiKey) {\n console.log(chalk.dim(\"\\n Verifying API key...\"));\n const valid = await verifyKey(provider, apiKey, baseURL, model);\n\n if (!valid) {\n console.log(ui.error(\"Invalid API key. Check your key and try again.\"));\n process.exit(1);\n }\n\n console.log(ui.success(\"API key verified\"));\n } else {\n console.log(ui.warn(\"No API key — skipping verification\"));\n }\n }\n\n const config: KairnConfig = {\n provider,\n api_key: apiKey,\n model,\n ...(baseURL ? { base_url: baseURL } : {}),\n ...(authType !== \"api-key\" ? { auth_type: authType } : {}),\n default_runtime: \"claude-code\",\n created_at: new Date().toISOString(),\n };\n\n await saveConfig(config);\n console.log(ui.success(`Config saved to ${chalk.dim(getConfigPath())}`));\n console.log(ui.kv(\"Provider\", providerDisplayName));\n console.log(ui.kv(\"Model\", model));\n\n await installSeedTemplates();\n\n const hasClaude = detectClaudeCode();\n if (hasClaude) {\n console.log(ui.success(\"Claude Code detected\"));\n } else {\n console.log(\n ui.warn(\"Claude Code not found. Install it: npm install -g @anthropic-ai/claude-code\")\n );\n }\n\n console.log(\n \"\\n\" + ui.success(`Ready! Run ${chalk.bold(\"kairn describe\")} to create your first environment.`) + \"\\n\"\n );\n });\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport os from \"os\";\nimport type { KairnConfig } from \"./types.js\";\n\nconst KAIRN_DIR = path.join(os.homedir(), \".kairn\");\nconst CONFIG_PATH = path.join(KAIRN_DIR, \"config.json\");\nconst ENVS_DIR = path.join(KAIRN_DIR, \"envs\");\nconst TEMPLATES_DIR = path.join(KAIRN_DIR, \"templates\");\nconst USER_REGISTRY_PATH = path.join(KAIRN_DIR, \"user-registry.json\");\n\nexport function getKairnDir(): string {\n return KAIRN_DIR;\n}\n\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n\nexport function getEnvsDir(): string {\n return ENVS_DIR;\n}\n\nexport function getTemplatesDir(): string {\n return TEMPLATES_DIR;\n}\n\nexport function getUserRegistryPath(): string {\n return USER_REGISTRY_PATH;\n}\n\nexport async function ensureDirs(): Promise<void> {\n await fs.mkdir(KAIRN_DIR, { recursive: true });\n await fs.mkdir(ENVS_DIR, { recursive: true });\n await fs.mkdir(TEMPLATES_DIR, { recursive: true });\n}\n\nexport async function loadConfig(): Promise<KairnConfig | null> {\n try {\n const data = await fs.readFile(CONFIG_PATH, \"utf-8\");\n const raw = JSON.parse(data) as Record<string, unknown>;\n\n // Handle old config format (v1.0.0: anthropic_api_key)\n if (raw.anthropic_api_key && !raw.provider) {\n return {\n provider: \"anthropic\",\n api_key: raw.anthropic_api_key as string,\n model: \"claude-sonnet-4-6\",\n default_runtime: \"claude-code\",\n created_at: (raw.created_at as string) || new Date().toISOString(),\n };\n }\n\n return raw as unknown as KairnConfig;\n } catch {\n return null;\n }\n}\n\nexport async function saveConfig(config: KairnConfig): Promise<void> {\n await ensureDirs();\n await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2), \"utf-8\");\n}\n","import chalk from \"chalk\";\nimport type { CompileProgress } from \"./types.js\";\n\nconst maroon = chalk.rgb(139, 0, 0);\nconst darkMaroon = chalk.rgb(100, 0, 0);\nconst warmStone = chalk.rgb(212, 165, 116);\nconst lightStone = chalk.rgb(220, 190, 160);\nconst dimStone = chalk.rgb(140, 100, 70);\n\nexport const ui = {\n // Brand colors\n brand: (text: string) => maroon.bold(text),\n accent: (text: string) => warmStone(text),\n\n // Logos and banners\n fullBanner: (subtitle?: string) => {\n const KAIRN_WORDMARK = [\n maroon(\"██╗ ██╗\") + \" \" + maroon(\"█████╗ \") + \" \" + maroon(\"██╗\") + \" \" + maroon(\"██████╗ \") + \" \" + maroon(\"███╗ ██╗\"),\n maroon(\"██║ ██╔╝\") + \" \" + maroon(\"██╔══██╗\") + \" \" + maroon(\"██║\") + \" \" + maroon(\"██╔══██╗\") + \" \" + maroon(\"████╗ ██║\"),\n warmStone(\"█████╔╝ \") + \" \" + warmStone(\"███████║\") + \" \" + warmStone(\"██║\") + \" \" + warmStone(\"██████╔╝\") + \" \" + warmStone(\"██╔██╗ ██║\"),\n warmStone(\"██╔═██╗ \") + \" \" + warmStone(\"██╔══██║\") + \" \" + warmStone(\"██║\") + \" \" + warmStone(\"██╔══██╗\") + \" \" + warmStone(\"██║╚██╗██║\"),\n lightStone(\"██║ ██╗\") + \" \" + lightStone(\"██║ ██║\") + \" \" + lightStone(\"██║\") + \" \" + lightStone(\"██║ ██║\") + \" \" + lightStone(\"██║ ╚████║\"),\n lightStone(\"╚═╝ ╚═╝\") + \" \" + lightStone(\"╚═╝ ╚═╝\") + \" \" + lightStone(\"╚═╝\") + \" \" + lightStone(\"╚═╝ ╚═╝\") + \" \" + lightStone(\"╚═╝ ╚═══╝\"),\n ];\n console.log(\"\");\n for (const line of KAIRN_WORDMARK) {\n console.log(\" \" + line);\n }\n if (subtitle) {\n console.log(dimStone(` ${subtitle}`));\n }\n console.log(\"\");\n },\n compactBanner: (subtitle?: string) => {\n const line = maroon(\"━\").repeat(52);\n console.log(` ${line}`);\n console.log(` ${maroon(\" ◆\")} ${chalk.bold.rgb(139, 0, 0)(\"KAIRN\")}` + (subtitle ? ` ${dimStone(\"— \" + subtitle)}` : \"\"));\n console.log(` ${line}`);\n },\n\n // Section headers\n section: (title: string) => {\n const len = chalk.dim(title).length;\n const line = \"━\".repeat(Math.max(0, 48 - len));\n return `\\n ${warmStone(\"━━\")} ${chalk.bold(title)} ${chalk.dim(warmStone(line))}`;\n },\n\n // Status messages\n success: (text: string) => chalk.green(` ✓ ${text}`),\n warn: (text: string) => chalk.yellow(` ⚠ ${text}`),\n error: (text: string) => chalk.red(` ✗ ${text}`),\n info: (text: string) => chalk.cyan(` ℹ ${text}`),\n\n // Key-value pairs\n kv: (key: string, value: string) => ` ${chalk.cyan(key.padEnd(14))} ${value}`,\n\n // File list\n file: (path: string) => chalk.dim(` ${path}`),\n\n // Tool display\n tool: (name: string, reason: string) => ` ${warmStone(\"●\")} ${chalk.bold(name)}\\n ${chalk.dim(reason)}`,\n\n // Divider\n divider: () => chalk.dim(` ${\"─\".repeat(50)}`),\n\n // Command suggestion\n cmd: (command: string) => ` ${chalk.bold.white(\"$ \" + command)}`,\n\n // Env var setup with signupUrl\n envVarPrompt: (name: string, desc: string, url?: string) => {\n let out = ` ${chalk.bold(name)}${chalk.dim(` (${desc})`)}`;\n if (url) out += `\\n ${chalk.dim(\"Get one at:\")} ${warmStone(url)}`;\n return out;\n },\n\n // Clarification question\n question: (q: string, suggestion?: string) => {\n let msg = ` ${warmStone(\"?\")} ${chalk.bold(q)}`;\n if (suggestion) {\n msg += `\\n ${chalk.dim(`(suggested: ${suggestion})`)}`;\n }\n return msg;\n },\n\n // Error box for compile failures\n errorBox: (title: string, message: string) => {\n const line = \"─\".repeat(50);\n return chalk.red(`\\n ┌${line}┐\\n │ ${title.padEnd(49)}│\\n │ ${message.padEnd(49)}│\\n └${line}┘\\n`);\n },\n};\n\nfunction formatTime(seconds: number): string {\n if (seconds < 60) return `${seconds}s`;\n const min = Math.floor(seconds / 60);\n const sec = seconds % 60;\n return sec > 0 ? `${min}m ${sec}s` : `${min} min`;\n}\n\nexport function estimateTime(model: string, intent: string): string {\n const wordCount = intent.split(/\\s+/).length;\n const isComplex = wordCount > 40;\n\n const perPass: Record<string, number> = {\n 'haiku': 5,\n 'sonnet': 20,\n 'opus': 60,\n 'gpt-4.1-mini': 10,\n 'gpt-4.1': 25,\n 'gpt-5': 15,\n 'o4-mini': 12,\n 'gemini-2.5-flash': 8,\n 'gemini-3-flash': 8,\n 'gemini-2.5-pro': 30,\n 'gemini-3.1-pro': 30,\n 'grok-4.1-fast': 10,\n 'grok-4.20': 25,\n 'deepseek': 15,\n 'mistral-large': 20,\n 'codestral': 15,\n 'mistral-small': 10,\n 'llama': 10,\n 'qwen': 10,\n };\n\n // Find closest match or default to 20s per pass\n const basePerPass = Object.entries(perPass).find(([k]) => model.toLowerCase().includes(k))?.[1] ?? 20;\n const totalBase = basePerPass * 2; // 2 LLM passes\n\n if (isComplex) {\n const low = Math.floor(totalBase * 1.5);\n const high = Math.floor(totalBase * 4);\n return `~${formatTime(low)}-${formatTime(high)} (complex workflow)`;\n }\n return `~${formatTime(totalBase)}`;\n}\n\nexport function createProgressRenderer(): {\n update: (progress: CompileProgress) => void;\n finish: () => void;\n fail: (err: unknown) => void;\n} {\n const lines: string[] = [];\n let intervalId: NodeJS.Timeout | null = null;\n let currentPhase = '';\n let phaseStart = Date.now();\n let lineCount = 0; // tracks how many lines have been written to stdout\n\n function render(): void {\n // Move cursor up to overwrite previous output\n if (lineCount > 0) {\n process.stdout.write(`\\x1B[${lineCount}A`);\n }\n for (const line of lines) {\n process.stdout.write('\\x1B[2K' + line + '\\n');\n }\n lineCount = lines.length;\n }\n\n function updateElapsed(): void {\n if (!currentPhase) return;\n const elapsed = Math.floor((Date.now() - phaseStart) / 1000);\n const lastIdx = lines.length - 1;\n if (lastIdx >= 0) {\n lines[lastIdx] = lines[lastIdx].replace(/\\[\\d+s\\]/, `[${elapsed}s]`);\n render();\n }\n }\n\n return {\n update(progress: CompileProgress): void {\n if (progress.status === 'running') {\n currentPhase = progress.phase;\n phaseStart = Date.now();\n lines.push(` ${warmStone(\"◐\")} ${progress.message} ${chalk.dim(\"[0s]\")}`);\n if (!intervalId) {\n intervalId = setInterval(updateElapsed, 1000);\n }\n } else if (progress.status === 'success') {\n const lastIdx = lines.length - 1;\n const elapsed = progress.elapsed != null ? ` ${chalk.dim(\"—\")} ${chalk.dim(Math.floor(progress.elapsed) + \"s\")}` : '';\n const detail = progress.detail ? ` ${chalk.dim(\"(\" + progress.detail + \")\")}` : '';\n if (lastIdx >= 0) {\n lines[lastIdx] = ` ${chalk.green(\"✔\")} ${progress.message}${detail}${elapsed}`;\n }\n currentPhase = '';\n } else if (progress.status === 'warning') {\n const lastIdx = lines.length - 1;\n if (lastIdx >= 0) {\n lines[lastIdx] = ` ${chalk.yellow(\"⚠\")} ${progress.message}`;\n }\n // Add new running line for the retry\n currentPhase = progress.phase;\n phaseStart = Date.now();\n lines.push(` ${warmStone(\"◐\")} Retrying in concise mode... ${chalk.dim(\"[0s]\")}`);\n }\n render();\n },\n finish(): void {\n if (intervalId) clearInterval(intervalId);\n currentPhase = '';\n render();\n },\n fail(err: unknown): void {\n if (intervalId) clearInterval(intervalId);\n currentPhase = '';\n const lastIdx = lines.length - 1;\n if (lastIdx >= 0) {\n lines[lastIdx] = ` ${chalk.red(\"✖\")} Compilation failed`;\n }\n render();\n },\n };\n}\n","import chalk from \"chalk\";\n\n// Kairn brand colors\nconst maroon = chalk.rgb(139, 0, 0);\nconst darkMaroon = chalk.rgb(100, 0, 0);\nconst warmStone = chalk.rgb(180, 120, 80);\nconst lightStone = chalk.rgb(212, 165, 116);\nconst dimStone = chalk.rgb(140, 100, 70);\n\n// Block-character wordmark (matches Hermes quality level)\nconst KAIRN_WORDMARK = [\n maroon(\"██╗ ██╗\") + darkMaroon(\" \") + maroon(\"█████╗ \") + darkMaroon(\" \") + maroon(\"██╗\") + darkMaroon(\" \") + maroon(\"██████╗ \") + darkMaroon(\" \") + maroon(\"███╗ ██╗\"),\n maroon(\"██║ ██╔╝\") + darkMaroon(\" \") + maroon(\"██╔══██╗\") + darkMaroon(\" \") + maroon(\"██║\") + darkMaroon(\" \") + maroon(\"██╔══██╗\") + darkMaroon(\" \") + maroon(\"████╗ ██║\"),\n warmStone(\"█████╔╝ \") + dimStone(\" \") + warmStone(\"███████║\") + dimStone(\" \") + warmStone(\"██║\") + dimStone(\" \") + warmStone(\"██████╔╝\") + dimStone(\" \") + warmStone(\"██╔██╗ ██║\"),\n warmStone(\"██╔═██╗ \") + dimStone(\" \") + warmStone(\"██╔══██║\") + dimStone(\" \") + warmStone(\"██║\") + dimStone(\" \") + warmStone(\"██╔══██╗\") + dimStone(\" \") + warmStone(\"██║╚██╗██║\"),\n lightStone(\"██║ ██╗\") + dimStone(\" \") + lightStone(\"██║ ██║\") + dimStone(\" \") + lightStone(\"██║\") + dimStone(\" \") + lightStone(\"██║ ██║\") + dimStone(\" \") + lightStone(\"██║ ╚████║\"),\n lightStone(\"╚═╝ ╚═╝\") + dimStone(\" \") + lightStone(\"╚═╝ ╚═╝\") + dimStone(\" \") + lightStone(\"╚═╝\") + dimStone(\" \") + lightStone(\"╚═╝ ╚═╝\") + dimStone(\" \") + lightStone(\"╚═╝ ╚═══╝\"),\n];\n\n// Braille-art cairn (stacked stones)\nconst CAIRN_ART = [\n dimStone(\" ⣀⣀⣀ \"),\n warmStone(\" ⣴⣿⣿⣿⣦ \"),\n warmStone(\" ⠙⠿⠿⠋ \"),\n dimStone(\" ⣀⣤⣤⣤⣤⣀ \"),\n lightStone(\" ⣴⣿⣿⣿⣿⣿⣿⣦ \"),\n lightStone(\" ⠙⠻⠿⠿⠿⠟⠋ \"),\n dimStone(\" ⣀⣤⣤⣶⣶⣶⣶⣤⣤⣀ \"),\n warmStone(\" ⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦ \"),\n warmStone(\" ⠙⠻⠿⠿⠿⠿⠿⠿⠟⠋ \"),\n dimStone(\" ⣀⣤⣶⣶⣿⣿⣿⣿⣿⣿⣶⣶⣤⣀ \"),\n lightStone(\" ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ \"),\n dimStone(\" ⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉ \"),\n];\n\nexport function printLogo(): void {\n console.log(\"\");\n for (const line of KAIRN_WORDMARK) {\n console.log(\" \" + line);\n }\n console.log(\"\");\n}\n\nexport function printCairn(): void {\n console.log(\"\");\n for (const line of CAIRN_ART) {\n console.log(\" \" + line);\n }\n console.log(\"\");\n}\n\nexport function printFullBanner(subtitle?: string): void {\n console.log(\"\");\n for (const line of KAIRN_WORDMARK) {\n console.log(\" \" + line);\n }\n if (subtitle) {\n console.log(dimStone(` ${subtitle}`));\n }\n console.log(\"\");\n}\n\n// Compact one-liner for smaller outputs\nexport function printCompactBanner(): void {\n const line = maroon(\"━\").repeat(50);\n console.log(`\\n ${line}`);\n console.log(` ${maroon(\" ◆\")} ${chalk.bold.rgb(139, 0, 0)(\"KAIRN\")} ${dimStone(\"— Agent Environment Compiler\")}`);\n console.log(` ${line}\\n`);\n}\n","import { Command } from \"commander\";\nimport { input, confirm, select } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { loadConfig } from \"../config.js\";\nimport { generateClarifications, compile } from \"../compiler/compile.js\";\nimport { writeEnvironment, summarizeSpec } from \"../adapter/claude-code.js\";\nimport { writeHermesEnvironment } from \"../adapter/hermes-agent.js\";\nimport { loadRegistry } from \"../registry/loader.js\";\nimport { ui, createProgressRenderer, estimateTime } from \"../ui.js\";\nimport { printFullBanner } from \"../logo.js\";\nimport { collectAndWriteKeys, writeEmptyEnvFile } from \"../secrets.js\";\nimport { autonomyLabel } from \"../autonomy.js\";\nimport type { RuntimeTarget, Clarification, AutonomyLevel } from \"../types.js\";\n\nexport const describeCommand = new Command(\"describe\")\n .description(\"Describe your workflow and generate a Claude Code environment\")\n .argument(\"[intent]\", \"What you want your agent to do\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .option(\"-q, --quick\", \"Skip clarification questions\")\n .option(\"--runtime <runtime>\", \"Target runtime (claude-code or hermes)\", \"claude-code\")\n .action(async (\n intentArg: string | undefined,\n options: { yes?: boolean; quick?: boolean; runtime?: string }\n ) => {\n // 1. Banner\n printFullBanner(\"The Agent Environment Compiler\");\n\n // 2. Check config\n const config = await loadConfig();\n if (!config) {\n console.log(\n ui.errorBox(\n \"No configuration found\",\n `Run ${chalk.bold(\"kairn init\")} to set up your API key.`\n )\n );\n process.exit(1);\n }\n\n // 3. Get intent\n const intentRaw =\n intentArg ||\n (await input({\n message: \"What do you want your agent to do?\",\n }));\n\n if (!intentRaw.trim()) {\n console.log(chalk.red(\"\\n No description provided. Aborting.\\n\"));\n process.exit(1);\n }\n\n // 4. Clarification flow\n let finalIntent = intentRaw;\n\n if (!options.quick) {\n console.log(ui.section(\"Clarification\"));\n console.log(chalk.dim(\" Let me understand your project better.\"));\n console.log(chalk.dim(\" Press Enter to accept the suggestion, or type your own answer.\\n\"));\n\n let clarifications: Clarification[] = [];\n try {\n clarifications = await generateClarifications(intentRaw);\n } catch {\n // Non-fatal: proceed without clarifications\n }\n\n if (clarifications.length > 0) {\n const answers: Array<{ question: string; answer: string }> = [];\n\n for (const c of clarifications) {\n const answer = await input({\n message: c.question,\n default: c.suggestion,\n });\n answers.push({ question: c.question, answer });\n }\n\n const clarificationLines = answers\n .map((a) => `- ${a.question}: ${a.answer}`)\n .join(\"\\n\");\n\n finalIntent =\n `User intent: \"${intentRaw}\"\\n\\nClarifications:\\n${clarificationLines}`;\n }\n }\n\n // 5. Autonomy level\n let autonomyLevel: AutonomyLevel = 1;\n\n if (!options.quick) {\n console.log(ui.section(\"Autonomy\"));\n autonomyLevel = await select({\n message: \"Autonomy level\",\n choices: [\n { name: \"1. Guided — orientation + commands, you drive\", value: 1 as AutonomyLevel },\n { name: \"2. Assisted — workflow loop, you approve phases\", value: 2 as AutonomyLevel },\n { name: \"3. Autonomous — PM plans, loop executes, you review PRs\", value: 3 as AutonomyLevel },\n { name: \"4. Full Auto — continuous execution (⚠ advanced)\", value: 4 as AutonomyLevel },\n ],\n default: 1,\n });\n\n finalIntent += `\\n\\nAutonomy level: ${autonomyLevel} (${autonomyLabel(autonomyLevel)})`;\n }\n\n // 6. Compilation\n console.log(ui.section(\"Compilation\"));\n const estimate = estimateTime(config.model, finalIntent);\n console.log(chalk.dim(` Estimated time: ${estimate} (${config.model})`));\n console.log(\"\");\n\n const renderer = createProgressRenderer();\n\n let spec;\n try {\n spec = await compile(finalIntent, (progress) => {\n renderer.update(progress);\n });\n spec.autonomy_level = autonomyLevel;\n renderer.finish();\n } catch (err) {\n renderer.fail(err);\n const msg = err instanceof Error ? err.message : String(err);\n console.log(chalk.red(`\\n ${msg}\\n`));\n process.exit(1);\n }\n\n // 7. Results display\n const registry = await loadRegistry();\n const summary = summarizeSpec(spec, registry);\n\n console.log(\"\");\n console.log(ui.kv(\"Name:\", spec.name));\n console.log(ui.kv(\"Description:\", spec.description));\n console.log(ui.kv(\"Autonomy:\", `Level ${spec.autonomy_level} (${autonomyLabel(spec.autonomy_level)})`));\n console.log(ui.kv(\"Tools:\", String(summary.toolCount)));\n console.log(ui.kv(\"Commands:\", String(summary.commandCount)));\n console.log(ui.kv(\"Rules:\", String(summary.ruleCount)));\n console.log(ui.kv(\"Skills:\", String(summary.skillCount)));\n console.log(ui.kv(\"Agents:\", String(summary.agentCount)));\n\n if (spec.tools.length > 0) {\n console.log(ui.section(\"Selected Tools\"));\n console.log(\"\");\n for (const tool of spec.tools) {\n const regTool = registry.find((t) => t.id === tool.tool_id);\n const name = regTool?.name || tool.tool_id;\n console.log(ui.tool(name, tool.reason));\n console.log(\"\");\n }\n }\n\n // 7. Confirm\n const proceed =\n options.yes ||\n (await confirm({\n message: \"Generate environment in current directory?\",\n default: true,\n }));\n\n if (!proceed) {\n console.log(chalk.dim(\"\\n Aborted. Environment saved to ~/.kairn/envs/\\n\"));\n return;\n }\n\n // 8. Write\n const targetDir = process.cwd();\n const runtime = (options.runtime ?? \"claude-code\") as RuntimeTarget;\n\n if (runtime === \"hermes\") {\n await writeHermesEnvironment(spec, registry);\n console.log(\"\\n\" + ui.success(\"Environment written for Hermes\"));\n console.log(\n chalk.cyan(\"\\n Ready! Run \") + chalk.bold(\"hermes\") + chalk.cyan(\" to start.\\n\")\n );\n } else {\n const hasEnvVars = summary.envSetup.length > 0;\n const written = await writeEnvironment(spec, targetDir, { hasEnvVars });\n\n console.log(ui.section(\"Files Written\"));\n console.log(\"\");\n for (const file of written) {\n console.log(ui.file(file));\n }\n // Handle .env file generation and key collection\n if (hasEnvVars) {\n if (options.quick) {\n await writeEmptyEnvFile(summary.envSetup, targetDir);\n console.log(ui.success(\"Empty .env written (gitignored) — fill in keys later: kairn keys\"));\n } else {\n await collectAndWriteKeys(summary.envSetup, targetDir);\n }\n console.log(\"\");\n }\n\n if (summary.pluginCommands.length > 0) {\n console.log(ui.section(\"Plugins\"));\n console.log(\"\");\n for (const cmd of summary.pluginCommands) {\n console.log(ui.cmd(cmd));\n }\n console.log(\"\");\n }\n\n console.log(ui.divider());\n console.log(ui.success(\"Ready! Run: $ claude\"));\n console.log(\"\");\n }\n });\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport crypto from \"crypto\";\nimport { loadConfig, getEnvsDir, ensureDirs } from \"../config.js\";\nimport { SYSTEM_PROMPT, SKELETON_PROMPT, HARNESS_PROMPT, CLARIFICATION_PROMPT } from \"./prompt.js\";\nimport { loadRegistry } from \"../registry/loader.js\";\nimport { getCheapModel } from \"../providers.js\";\nimport { callLLM } from \"../llm.js\";\nimport type { EnvironmentSpec, RegistryTool, Clarification, SkeletonSpec, HarnessContent, CompileProgress } from \"../types.js\";\nimport { generateIntentPatterns } from \"../intent/patterns.js\";\nimport { compileIntentPrompt } from \"../intent/prompt-template.js\";\nimport { renderIntentRouter } from \"../intent/router-template.js\";\nimport { renderIntentLearner } from \"../intent/learner-template.js\";\n\nfunction buildUserMessage(intent: string, registry: RegistryTool[]): string {\n const registrySummary = registry\n .map(\n (t) =>\n `- ${t.id} (${t.type}, tier ${t.tier}, auth: ${t.auth}): ${t.description} [best_for: ${t.best_for.join(\", \")}]`\n )\n .join(\"\\n\");\n\n return `## User Intent\\n\\n${intent}\\n\\n## Available Tool Registry\\n\\n${registrySummary}\\n\\nGenerate the EnvironmentSpec JSON now.`;\n}\n\nfunction buildSkeletonMessage(intent: string, registry: RegistryTool[]): string {\n const registrySummary = registry\n .map(\n (t) =>\n `- ${t.id} (${t.type}, tier ${t.tier}, auth: ${t.auth}): ${t.description} [best_for: ${t.best_for.join(\", \")}]`\n )\n .join(\"\\n\");\n\n return `## User Intent\\n\\n${intent}\\n\\n## Available Tool Registry\\n\\n${registrySummary}\\n\\nGenerate the skeleton JSON now.`;\n}\n\nfunction buildHarnessMessage(intent: string, skeleton: SkeletonSpec, concise?: boolean): string {\n const skeletonJson = JSON.stringify(skeleton, null, 2);\n const conciseNote = concise\n ? \"\\n\\nIMPORTANT: Be concise. Maximum 80 lines for claude_md. Maximum 5 commands. Keep all content brief.\"\n : \"\";\n return `## User Intent\\n\\n${intent}\\n\\n## Project Skeleton\\n\\n${skeletonJson}\\n\\nGenerate the harness content JSON now.${conciseNote}`;\n}\n\nfunction parseSpecResponse(text: string): Omit<EnvironmentSpec, \"id\" | \"intent\" | \"created_at\"> {\n let cleaned = text.trim();\n // Strip markdown code fences\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n // Try to extract JSON if there's surrounding text\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n throw new Error(\n \"LLM response did not contain valid JSON. Try again or use a different model.\"\n );\n }\n try {\n return JSON.parse(jsonMatch[0]);\n } catch (err) {\n throw new Error(\n `Failed to parse LLM response as JSON: ${err instanceof Error ? err.message : String(err)}\\n` +\n `Response started with: ${cleaned.slice(0, 200)}...`\n );\n }\n}\n\nfunction parseSkeletonResponse(text: string): SkeletonSpec {\n let cleaned = text.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n throw new Error(\"Pass 1 (skeleton) did not return valid JSON.\");\n }\n try {\n const parsed = JSON.parse(jsonMatch[0]);\n // Validate required fields\n if (!parsed.name || !parsed.tools || !Array.isArray(parsed.tools)) {\n throw new Error(\"Skeleton missing required fields: name, tools\");\n }\n return parsed as SkeletonSpec;\n } catch (err) {\n throw new Error(\n `Failed to parse skeleton JSON: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\nfunction parseHarnessResponse(text: string): HarnessContent {\n let cleaned = text.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n throw new Error(\"Pass 2 (harness) did not return valid JSON.\");\n }\n try {\n const parsed = JSON.parse(jsonMatch[0]);\n if (!parsed.claude_md || !parsed.commands) {\n throw new Error(\"Harness missing required fields: claude_md, commands\");\n }\n return parsed as HarnessContent;\n } catch (err) {\n throw new Error(\n `Failed to parse harness JSON: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\nfunction buildSettings(skeleton: SkeletonSpec, registry: RegistryTool[]): Record<string, unknown> {\n const selectedTools = skeleton.tools\n .map((t) => registry.find((r) => r.id === t.tool_id))\n .filter(Boolean);\n\n // Build permissions based on workflow type\n const allow = [\"Read\", \"Write\", \"Edit\", \"Bash(npm run *)\", \"Bash(npx *)\"];\n const deny = [\n \"Bash(rm -rf *)\",\n \"Bash(curl * | sh)\",\n \"Bash(wget * | sh)\",\n \"Read(./.env)\",\n \"Read(./secrets/**)\",\n ];\n\n // Build hooks\n const hooks: Record<string, unknown[]> = {\n PreToolUse: [\n {\n matcher: \"Bash\",\n hooks: [\n {\n type: \"command\",\n command:\n \"CMD=$(cat | jq -r '.tool_input.command // empty') && echo \\\"$CMD\\\" | grep -qiE 'rm\\\\s+-rf\\\\s+/|DROP\\\\s+TABLE|curl.*\\\\|\\\\s*sh' && echo 'Blocked destructive command' >&2 && exit 2 || true\",\n },\n ],\n },\n ],\n PostCompact: [\n {\n matcher: \"\",\n hooks: [\n {\n type: \"prompt\",\n prompt:\n \"Re-read CLAUDE.md and docs/SPRINT.md (if it exists) to restore project context after compaction.\",\n },\n ],\n },\n ],\n };\n\n // Add formatter hook if project uses common formatters\n const techStack = skeleton.outline.tech_stack.map((t) => t.toLowerCase());\n if (\n techStack.some((t) => t.includes(\"typescript\") || t.includes(\"javascript\") || t.includes(\"react\") || t.includes(\"next\"))\n ) {\n hooks.PostToolUse = [\n {\n matcher: \"Edit|Write\",\n hooks: [\n {\n type: \"command\",\n command:\n 'FILE=$(cat | jq -r \\'.tool_input.file_path // empty\\') && [ -n \"$FILE\" ] && npx prettier --write \"$FILE\" 2>/dev/null || true',\n },\n ],\n },\n ];\n }\n\n return { permissions: { allow, deny }, hooks };\n}\n\nfunction buildMcpConfig(skeleton: SkeletonSpec, registry: RegistryTool[]): Record<string, unknown> {\n const config: Record<string, unknown> = {};\n for (const tool of skeleton.tools) {\n const reg = registry.find((r) => r.id === tool.tool_id);\n if (reg?.install.mcp_config) {\n config[tool.tool_id] = reg.install.mcp_config;\n }\n }\n return config;\n}\n\nfunction validateSpec(spec: EnvironmentSpec): string[] {\n const warnings: string[] = [];\n\n if (spec.tools.length > 8) {\n warnings.push(`${spec.tools.length} MCP servers selected (recommended: ≤6)`);\n }\n\n if (spec.harness.claude_md) {\n const lines = spec.harness.claude_md.split('\\n').length;\n if (lines > 150) {\n warnings.push(`CLAUDE.md is ${lines} lines (recommended: ≤150)`);\n }\n }\n\n if (spec.harness.skills && Object.keys(spec.harness.skills).length > 5) {\n warnings.push(`${Object.keys(spec.harness.skills).length} skills (recommended: ≤3)`);\n }\n\n return warnings;\n}\n\nexport async function compile(\n intent: string,\n onProgress?: (progress: CompileProgress) => void\n): Promise<EnvironmentSpec> {\n const startTime = Date.now();\n const config = await loadConfig();\n if (!config) {\n throw new Error(\"No config found. Run `kairn init` first.\");\n }\n\n // Registry\n onProgress?.({ phase: 'registry', status: 'running', message: 'Loading tool registry...' });\n const registry = await loadRegistry();\n onProgress?.({ phase: 'registry', status: 'success', message: 'Tool registry loaded', detail: `${registry.length} tools` });\n\n // Pass 1: Skeleton (tool selection + project outline)\n onProgress?.({ phase: 'pass1', status: 'running', message: 'Pass 1: Analyzing workflow & selecting tools...' });\n const skeletonMsg = buildSkeletonMessage(intent, registry);\n const skeletonText = await callLLM(config, skeletonMsg, {\n maxTokens: 2048,\n systemPrompt: SKELETON_PROMPT,\n });\n const skeleton = parseSkeletonResponse(skeletonText);\n const toolNames = skeleton.tools.map(t => t.tool_id).join(', ');\n onProgress?.({\n phase: 'pass1', status: 'success',\n message: `Pass 1: Selected ${skeleton.tools.length} tools`,\n detail: toolNames,\n elapsed: (Date.now() - startTime) / 1000,\n });\n\n // Pass 2: Harness content (CLAUDE.md + commands + rules + agents)\n onProgress?.({ phase: 'pass2', status: 'running', message: 'Pass 2: Generating CLAUDE.md, commands, agents...' });\n const harnessMsg = buildHarnessMessage(intent, skeleton);\n let harness: HarnessContent;\n try {\n const harnessText = await callLLM(config, harnessMsg, {\n maxTokens: 8192,\n systemPrompt: HARNESS_PROMPT,\n });\n harness = parseHarnessResponse(harnessText);\n } catch {\n // Retry with concise mode if Pass 2 fails (likely JSON truncation)\n onProgress?.({ phase: 'pass2-retry', status: 'warning', message: 'Pass 2: Response too large, retrying in concise mode...' });\n const retryMsg = buildHarnessMessage(intent, skeleton, true);\n const retryText = await callLLM(config, retryMsg, {\n maxTokens: 8192,\n systemPrompt: HARNESS_PROMPT,\n });\n harness = parseHarnessResponse(retryText);\n }\n const cmdCount = Object.keys(harness.commands).length;\n const agentCount = Object.keys(harness.agents ?? {}).length;\n const ruleCount = Object.keys(harness.rules).length;\n onProgress?.({\n phase: 'pass2', status: 'success',\n message: `Pass 2: Generated ${cmdCount} commands, ${agentCount} agents, ${ruleCount} rules`,\n elapsed: (Date.now() - startTime) / 1000,\n });\n\n // Pass 3: Settings + MCP config (deterministic, no LLM)\n onProgress?.({ phase: 'pass3', status: 'running', message: 'Pass 3: Configuring MCP servers & settings...' });\n const settings = buildSettings(skeleton, registry);\n const mcpConfig = buildMcpConfig(skeleton, registry);\n\n // Intent routing: generate patterns, prompt template, and hook scripts\n const projectProfile = {\n language: skeleton.outline.tech_stack[0] ?? 'unknown',\n framework: skeleton.outline.tech_stack[1] ?? 'none',\n scripts: {} as Record<string, string>, // scripts come from project scanning, not compilation\n };\n const intentPatterns = generateIntentPatterns(\n harness.commands,\n harness.agents ?? {},\n projectProfile,\n );\n const intentPromptTemplate = compileIntentPrompt(\n harness.commands,\n harness.agents ?? {},\n );\n const generationTimestamp = new Date().toISOString();\n const intentHooks: Record<string, string> = {};\n if (intentPatterns.length > 0) {\n intentHooks['intent-router'] = renderIntentRouter(intentPatterns, generationTimestamp);\n intentHooks['intent-learner'] = renderIntentLearner();\n }\n\n onProgress?.({ phase: 'pass3', status: 'success', message: 'Pass 3: Configured MCP servers & settings' });\n\n // Assemble final EnvironmentSpec\n const spec: EnvironmentSpec = {\n id: `env_${crypto.randomUUID()}`,\n intent,\n created_at: new Date().toISOString(),\n name: skeleton.name,\n description: skeleton.description,\n autonomy_level: 1,\n tools: skeleton.tools,\n harness: {\n claude_md: harness.claude_md,\n settings,\n mcp_config: mcpConfig,\n commands: harness.commands,\n rules: harness.rules,\n skills: harness.skills ?? {},\n agents: harness.agents ?? {},\n docs: harness.docs,\n hooks: intentHooks,\n intent_patterns: intentPatterns,\n intent_prompt_template: intentPromptTemplate,\n },\n };\n\n const warnings = validateSpec(spec);\n for (const w of warnings) {\n onProgress?.({ phase: 'done', status: 'warning', message: `⚠ ${w}` });\n }\n\n const totalElapsed = ((Date.now() - startTime) / 1000).toFixed(0);\n onProgress?.({ phase: 'done', status: 'success', message: `Environment compiled in ${totalElapsed}s`, elapsed: (Date.now() - startTime) / 1000 });\n\n // Save to ~/.kairn/envs/\n await ensureDirs();\n const envPath = path.join(getEnvsDir(), `${spec.id}.json`);\n await fs.writeFile(envPath, JSON.stringify(spec, null, 2), \"utf-8\");\n\n return spec;\n}\n\nexport async function generateClarifications(\n intent: string,\n onProgress?: (msg: string) => void\n): Promise<Clarification[]> {\n const config = await loadConfig();\n if (!config) {\n throw new Error(\"No config found. Run `kairn init` first.\");\n }\n\n onProgress?.(\"Analyzing your request...\");\n\n // Use the cheapest model for clarifications regardless of selected compilation model\n const clarificationConfig = { ...config };\n clarificationConfig.model = getCheapModel(config.provider, config.model);\n\n const response = await callLLM(clarificationConfig, CLARIFICATION_PROMPT + \"\\n\\nUser description: \" + intent, {\n systemPrompt: SYSTEM_PROMPT,\n });\n\n try {\n let cleaned = response.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n const jsonMatch = cleaned.match(/\\[[\\s\\S]*\\]/);\n if (!jsonMatch) return [];\n return JSON.parse(jsonMatch[0]) as Clarification[];\n } catch {\n return [];\n }\n}\n","export const SKELETON_PROMPT = `You are the Kairn skeleton compiler. Your job is to select tools and outline the project structure from a user's natural language description.\n\nYou will receive:\n1. The user's intent (what they want to build/do)\n2. A tool registry (available MCP servers, plugins, and hooks)\n\nYou must output a JSON object matching the SkeletonSpec schema.\n\n## Core Principles\n\n- **Minimalism over completeness.** Fewer, well-chosen tools beat many generic ones. Each MCP server costs 500-2000 context tokens.\n- **Workflow-specific, not generic.** Select tools that directly support the user's actual workflow.\n- **Security by default.** Essential for all projects.\n\n## Tool Selection Rules\n\n- Only select tools directly relevant to the described workflow\n- Prefer free tools (auth: \"none\") when quality is comparable\n- Tier 1 tools (Context7, Sequential Thinking, security-guidance) should be included in most environments\n- For tools requiring API keys (auth: \"api_key\"), use \\${ENV_VAR} syntax — never hardcode keys\n- Maximum 6-8 MCP servers to avoid context bloat\n- Include a \\`reason\\` for each selected tool explaining why it fits this workflow\n\n## Context Budget (STRICT)\n\n- MCP servers: maximum 6. Prefer fewer.\n- Skills: maximum 3. Only include directly relevant ones.\n- Agents: maximum 5. Orchestration pipeline (/develop) agents.\n- Hooks: maximum 5 (auto-format, block-destructive, PostCompact, memory-persistence, plus one contextual).\n\nIf the workflow doesn't clearly need a tool, DO NOT include it.\nEach MCP server costs 500-2000 tokens of context window.\n\n## Output Schema\n\nReturn ONLY valid JSON matching this structure:\n\n\\`\\`\\`json\n{\n \"name\": \"short-kebab-case-name\",\n \"description\": \"One-line description\",\n \"tools\": [\n { \"tool_id\": \"id-from-registry\", \"reason\": \"why this tool fits\" }\n ],\n \"outline\": {\n \"tech_stack\": [\"Python\", \"pandas\"],\n \"workflow_type\": \"data-analysis\",\n \"key_commands\": [\"ingest\", \"analyze\", \"report\"],\n \"custom_rules\": [\"data-integrity\"],\n \"custom_agents\": [\"data-reviewer\"],\n \"custom_skills\": [\"ms-data-analysis\"]\n }\n}\n\\`\\`\\`\n\nReturn ONLY valid JSON. No markdown fences. No text outside the JSON.`;\n\nexport const HARNESS_PROMPT = `You are the Kairn harness compiler. Your job is to generate the full environment content from a project skeleton.\n\nYou will receive:\n1. The skeleton (tool selections + project outline)\n2. The user's original intent\n\nYou must generate all harness content: CLAUDE.md, commands, rules, agents, skills, and docs.\n\n## Core Principles\n\n- **Workflow-specific, not generic.** Every instruction, command, and rule must relate to the user's actual workflow.\n- **Concise CLAUDE.md.** Under 150 lines. No generic text like \"be helpful.\" Include build/test commands, reference docs/ and skills/.\n- **Security by default.** Always include deny rules for destructive commands and secret file access.\n\n## CLAUDE.md Template (mandatory structure)\n\nThe \\`claude_md\\` field MUST follow this exact structure (max 150 lines):\n\n\\`\\`\\`\n# {Project Name}\n\n## Purpose\n{one-line description}\n\n## Tech Stack\n{bullet list of frameworks/languages}\n\n## Commands\n{concrete build/test/lint/dev commands}\n\n## Architecture\n{brief folder structure, max 10 lines}\n\n## Conventions\n{3-5 specific coding rules}\n\n## Key Commands\n{list /project: commands with descriptions}\n\n## Output\n{where results go, key files}\n\n## Verification\nAfter implementing any change, verify it works:\n- {build command} — must pass with no errors\n- {test command} — all tests must pass\n- {lint command} — no warnings or errors\n- {type check command} — no type errors\n\nIf any verification step fails, fix the issue before moving on.\nDo NOT skip verification steps.\n\n## Known Gotchas\n<!-- After any correction, add it here: \"Update CLAUDE.md so you don't make that mistake again.\" -->\n<!-- Prune this section when it exceeds 10 items — keep only the recurring ones. -->\n- (none yet — this section grows as you work)\n\n## Debugging\nWhen debugging, paste raw error output. Don't summarize — Claude works better with raw data.\nUse subagents for deep investigation to keep main context clean.\n\n## Git Workflow\n- Prefer small, focused commits (one feature or fix per commit)\n- Use conventional commits: feat:, fix:, docs:, refactor:, test:\n- Target < 200 lines per PR when possible\n\n## Engineering Standards\n- Lead with answers over reasoning. Be concise.\n- Use absolute file paths in all references.\n- No filler, no inner monologue, no time estimates.\n- Produce load-bearing code — every line of output should be actionable.\n\n## Tool Usage Policy\n- Prefer Edit tool over sed/awk for file modifications\n- Prefer Grep tool over rg for searching\n- Prefer Read tool over cat for file reading\n- Reserve Bash for: builds, installs, git, network, processes\n- Read and understand existing code before modifying\n- Delete unused code completely — no compatibility shims\n\n## Code Philosophy\n- Do not create abstractions for one-time operations\n- Complete the task fully — don't gold-plate, but don't leave it half-done\n- Prefer editing existing files over creating new ones\n\n## First Turn Protocol\n\nAt the start of every session, before doing ANY work:\n1. Run \\`pwd && ls -la && git status --short\\` to orient yourself\n2. Check relevant runtimes (e.g. \\`node --version\\`, \\`python3 --version\\` — pick what fits this project)\n3. Read any task-tracking files (docs/SPRINT.md, docs/DECISIONS.md)\n4. Summarize what you see in 2-3 lines, then proceed\n\nThis saves 2-5 exploratory turns. Never ask \"what files are here?\" — look first.\n\n## Sprint Contract\n\nBefore implementing, confirm acceptance criteria exist in docs/SPRINT.md.\nEach criterion must be numbered, testable, and independently verifiable.\nAfter implementing, verify EACH criterion individually. Do not mark done until all pass.\n\n## Completion Standards\n\nNever mark a task \"done\" without running the Completion Verification checklist.\nTests passing is necessary but not sufficient — also verify requirements coverage,\nstate cleanliness, and review changes from the perspective of a test engineer,\ncode reviewer, and the requesting user.\n\\`\\`\\`\n\nDo not add generic filler. Every line must be specific to the user's workflow.\n\n## What You Must Always Include\n\n1. A concise, workflow-specific \\`claude_md\\` (the CLAUDE.md content)\n2. A \\`/project:help\\` command that explains the environment\n3. A \\`docs/DECISIONS.md\\` file for architectural decisions\n4. A \\`docs/LEARNINGS.md\\` file for non-obvious discoveries\n5. A \\`rules/continuity.md\\` rule encouraging updates to DECISIONS.md and LEARNINGS.md\n6. A \\`rules/security.md\\` rule with essential security instructions\n7. settings.json with deny rules for \\`rm -rf\\`, \\`curl|sh\\`, reading \\`.env\\` and \\`secrets/\\`\n8. A \\`/project:status\\` command for code projects (uses ! for live git/SPRINT.md output)\n9. A \\`/project:fix\\` command for code projects (uses $ARGUMENTS for issue number)\n10. A \\`docs/SPRINT.md\\` file as the living spec/plan (replaces TODO.md — acceptance criteria, verification steps)\n11. A \"Verification\" section in CLAUDE.md with concrete verify commands for the project\n12. A \"Known Gotchas\" section in CLAUDE.md (starts empty, grows with corrections)\n13. A \"Debugging\" section in CLAUDE.md (2 lines: paste raw errors, use subagents)\n14. A \"Git Workflow\" section in CLAUDE.md (3 rules: small commits, conventional format, <200 lines PR)\n15. \"Engineering Standards\", \"Tool Usage Policy\", and \"Code Philosophy\" sections in CLAUDE.md\n16. A \"First Turn Protocol\" section in CLAUDE.md (orient before working: pwd, ls, git status, check relevant runtimes, read task files)\n17. A \"Completion Standards\" section in CLAUDE.md (never mark done without verifying: requirements met, tests passing, no debug artifacts, reviewed from 3 perspectives)\n18. A \"Sprint Contract\" section in CLAUDE.md (confirm acceptance criteria exist before implementing, verify each criterion after)\n\n## Shell-Integrated Commands\n\nCommands that reference live project state should use Claude Code's \\`!\\` prefix for shell output:\n\n\\`\\`\\`markdown\n# Example: .claude/commands/review.md\nReview the staged changes for quality and security:\n\n!git diff --staged\n\nRun tests and check for failures:\n\n!npm test 2>&1 | tail -20\n\nFocus on: security, error handling, test coverage.\n\\`\\`\\`\n\nUse \\`!\\` when a command needs: git status, test results, build output, or file listings.\n\n## Path-Scoped Rules\n\nFor code projects with multiple domains (API, frontend, tests), generate path-scoped rules using YAML frontmatter:\n\n\\`\\`\\`markdown\n# Example: rules/api.md\n---\npaths:\n - \"src/api/**\"\n - \"src/routes/**\"\n---\n- All handlers return { data, error } shape\n- Use Zod for request validation\n- Log errors with request ID context\n\\`\\`\\`\n\n\\`\\`\\`markdown\n# Example: rules/testing.md\n---\npaths:\n - \"tests/**\"\n - \"**/*.test.*\"\n - \"**/*.spec.*\"\n---\n- Use AAA pattern: Arrange-Act-Assert\n- One assertion per test when possible\n- Mock external dependencies, never real APIs\n\\`\\`\\`\n\nKeep \\`security.md\\` and \\`continuity.md\\` as unconditional (no paths frontmatter).\nOnly generate scoped rules when the workflow involves multiple code domains.\n\n## Hooks\n\nGenerate hooks in settings.json based on project type:\n\n**All code projects** — block destructive commands, credential leaks, injection, and network exfiltration:\n\\`\\`\\`json\n{\n \"hooks\": {\n \"PreToolUse\": [\n {\n \"matcher\": \"Bash\",\n \"hooks\": [{\n \"type\": \"command\",\n \"command\": \"CMD=$(cat | jq -r '.tool_input.command // empty') && echo \\\\\"$CMD\\\\\" | grep -qiE 'rm\\\\\\\\s+-rf\\\\\\\\s+/|DROP\\\\\\\\s+(TABLE|DATABASE)|curl.*\\\\\\\\|\\\\\\\\s*sh|:(){ :|:& };:|git\\\\\\\\s+push.*--force(?!-with-lease)|ch(mod|own).*-R\\\\\\\\s+/|npm\\\\\\\\s+publish(?!.*--dry-run)|(api[_-]?key|secret|token|password)\\\\\\\\s*[:=]|AKIA[0-9A-Z]{16}|BEGIN.*PRIVATE\\\\\\\\s+KEY|;\\\\\\\\s*(DROP|DELETE|ALTER|TRUNCATE)\\\\\\\\s+|\\\\\\\\.\\\\\\\\./\\\\\\\\.\\\\\\\\./\\\\\\\\.\\\\\\\\.\\/|nc\\\\\\\\s+.*-e|/dev/tcp/|bash\\\\\\\\s+-i|curl.*-d.*@|wget.*--post-file' && echo 'Blocked dangerous command' >&2 && exit 2 || true\"\n }]\n }\n ]\n }\n}\n\\`\\`\\`\n\n**Projects with Prettier/ESLint/Black** — auto-format on write:\n\\`\\`\\`json\n{\n \"hooks\": {\n \"PostToolUse\": [{\n \"matcher\": \"Edit|Write\",\n \"hooks\": [{\n \"type\": \"command\",\n \"command\": \"FILE=$(cat | jq -r '.tool_input.file_path // empty') && [ -n \\\\\"$FILE\\\\\" ] && npx prettier --write \\\\\"$FILE\\\\\" 2>/dev/null || true\"\n }]\n }]\n }\n}\n\\`\\`\\`\n\nMerge hooks into the \\`settings\\` object alongside permissions. Choose the formatter hook based on detected dependencies (Prettier → prettier, ESLint → eslint, Black → black).\n\n## PostCompact Hook\n\nAll projects should include a PostCompact hook to restore context after compaction:\n\n\\`\\`\\`json\n{\n \"hooks\": {\n \"PostCompact\": [{\n \"matcher\": \"\",\n \"hooks\": [{\n \"type\": \"prompt\",\n \"prompt\": \"Re-read CLAUDE.md and docs/SPRINT.md (if it exists) to restore project context after compaction.\"\n }]\n }]\n }\n}\n\\`\\`\\`\n\nMerge this into the settings hooks alongside the PreToolUse and PostToolUse hooks.\n\nFor long-running sessions (>2 hours or >3 compactions), prefer \"Full Reset\" over re-inject:\nreplace the prompt-type PostCompact hook with a command-type hook that pipes CLAUDE.md + SPRINT.md + DECISIONS.md content directly into additionalContext.\n\n## Memory Persistence Hooks\n\nFor projects with multi-session workflows, include SessionStart/End hooks that persist context to \\`.claude/memory.json\\`:\n- **SessionEnd:** Save recent decisions, sprint status, and known gotchas to \\`.claude/memory.json\\`\n- **SessionStart:** Load \\`.claude/memory.json\\` and inject as additionalContext\n\nThis ensures accumulated project knowledge survives session boundaries.\n\n## Persistence Routing Hook\n\nFor code projects with autonomy level 3+, include a \\`UserPromptSubmit\\` hook that routes complex tasks through \\`/project:persist\\`.\nGenerate \\`.claude/hooks/persist-router.mjs\\` (the routing logic) and add a \\`UserPromptSubmit\\` hook entry in settings.json that invokes it.\nAlso add \\`\"persistence_routing\": \"auto\"\\` (level 3-4) or \\`\"persistence_routing\": \"manual\"\\` (level 1-2) to settings.json.\n\n## For Code Projects, Additionally Include\n\n- \\`/project:plan\\` command (plan before coding)\n- \\`/project:review\\` command (review changes)\n- \\`/project:test\\` command (run and fix tests)\n- \\`/project:commit\\` command (conventional commits)\n- \\`/project:status\\` command (live git status, recent commits, SPRINT.md overview using ! prefix)\n- \\`/project:fix\\` command (takes $ARGUMENTS as issue number, plans fix, implements, tests, commits)\n- \\`/project:sprint\\` command (define acceptance criteria before coding, writes to docs/SPRINT.md)\n- \\`/project:develop\\` command (full development pipeline — orchestrates @architect → @planner → @implementer → @verifier → @fixer → @grill → @doc-updater through spec, plan, TDD implement, review, and doc update phases). Phase 4 (Verify) MUST validate EACH acceptance criterion from docs/SPRINT.md individually, reporting PASS/FAIL per item as a contract scorecard. MUST include a Phase 7 \"Completion Gate\" that runs a Completion Verification checklist before marking the feature done: re-read original requirements, confirm each is met with evidence, run test suite + lint/typecheck, review git diff for unexpected changes or debug artifacts, answer 3 perspective questions (test engineer, code reviewer, requesting user). If ANY check fails, loop back to fix before completing.\n- A TDD skill using the 3-phase isolation pattern (RED → GREEN → REFACTOR):\n - RED: Write failing test only. Verify it FAILS.\n - GREEN: Write MINIMUM code to pass. Nothing extra.\n - REFACTOR: Improve while keeping tests green.\n Rules: never write tests and implementation in same step, AAA pattern, one assertion per test.\n- A multi-agent QA pipeline:\n - \\`@qa-orchestrator\\` (sonnet) — delegates to linter and e2e-tester, compiles QA report\n - \\`@linter\\` (haiku) — runs formatters, linters, security scanners\n - \\`@e2e-tester\\` (sonnet, only when Playwright is in tools) — browser-based QA via Playwright\n- A \"Model Selection\" section in generated agents:\n \\`\\`\\`\n ## Model Selection (all agents)\n - Haiku: simple file edits, linting, formatting, doc updates (<50 lines changed)\n - Sonnet: implementation, testing, debugging, code review (50-500 lines)\n - Opus: architecture decisions, spec writing, complex refactors (>500 lines or cross-cutting)\n Default: Sonnet. Only escalate to Opus when the task involves multi-file architecture or ambiguous requirements.\n \\`\\`\\`\n- Development pipeline agents (used by /project:develop). Each agent should include a modelRouting field in its YAML frontmatter:\n - \\`@architect\\` (default: opus) — conducts spec interview with user, writes confirmed spec to docs/SPRINT.md with numbered acceptance criteria. Your spec is a CONTRACT — the verifier will check every criterion. Vague criteria = guaranteed rework.\n - \\`@planner\\` (default: sonnet, escalate to opus for cross-cutting changes) — reads spec and codebase, creates step-by-step implementation plan in docs/PLAN.md\n - \\`@implementer\\` (default: sonnet, escalate to opus for cross-cutting changes) — TDD-focused implementation, writes failing tests then minimum code to pass\n - \\`@fixer\\` (default: sonnet, use haiku for single-file fixes) — targeted bug fixing from verifier/review feedback\n - \\`@doc-updater\\` (default: haiku) — extracts decisions and learnings from completed work, updates docs/DECISIONS.md and docs/LEARNINGS.md\n- \\`/project:spec\\` command (interview-based spec creation — asks 5-8 questions one at a time, writes structured spec to docs/SPRINT.md with ## Acceptance Criteria containing 3-8 numbered, testable conditions. Each criterion must be independently verifiable. Does NOT start coding until confirmed)\n- \\`/project:prove\\` command (runs tests, shows git diff vs main, rates confidence HIGH/MEDIUM/LOW with evidence)\n- \\`/project:grill\\` command (adversarial code review — challenges each change with \"why this approach?\", \"what if X input?\", rates BLOCKER/SHOULD-FIX/NITPICK, blocks until BLOCKERs resolved)\n- \\`/project:reset\\` command (reads DECISIONS.md and LEARNINGS.md, proposes clean restart, stashes current work, implements elegant solution)\n- \\`/project:persist\\` command (persistent execution loop — reads acceptance criteria from docs/SPRINT.md, works criterion-by-criterion with structured progress tracking in .claude/progress.json, auto-retries on verification failure up to 3 times per criterion, delegates to @grill for review gate before completion, resumes from progress.json if session was interrupted). The command protocol:\n 1. Load or initialize .claude/progress.json from docs/SPRINT.md numbered acceptance criteria\n 2. For each incomplete criterion: implement, run verification (build/test/typecheck/lint), mark PASSED or retry (max 3 attempts per criterion, mark BLOCKED after 3 failures)\n 3. After all criteria attempted: if any BLOCKED report which and why; if all PASSED proceed to review gate\n 4. Review gate: delegate to @grill for adversarial review; fix blockers if found (max 1 fix cycle)\n 5. Persist state: write final progress.json; include progress summary in memory.json for session resume\n Resume protocol: when progress.json exists, skip PASSED criteria, resume from first non-PASSED criterion, carry forward failure notes from prior attempts.\n\n## For Research Projects, Additionally Include\n\n- \\`/project:research\\` command (deep research on a topic)\n- \\`/project:summarize\\` command (summarize findings)\n- A research-synthesis skill\n- A researcher agent\n- Note: the Verification section in CLAUDE.md should adapt for research — e.g. \"Verify all sources are cited\" instead of build/test commands\n\n## For Content/Writing Projects, Additionally Include\n\n- \\`/project:draft\\` command (write first draft)\n- \\`/project:edit\\` command (review and improve writing)\n- A writing-workflow skill\n\n## Hermes Runtime\n\nWhen generating for Hermes runtime, the same EnvironmentSpec JSON is produced. The adapter layer handles conversion:\n- MCP config entries → Hermes config.yaml mcp_servers\n- Commands and skills → ~/.hermes/skills/ markdown files\n- Rules → ~/.hermes/skills/rule-*.md files\n\nThe LLM output format does not change. Adapter-level conversion happens post-compilation.\n\n## Autonomy Levels\n\nThe user may specify an autonomy level (1-4). This affects CLAUDE.md content:\n\n- **Level 1 (Guided):** Add a \"Workflow\" section showing recommended command flow (e.g., spec → sprint → plan → code → prove → grill → commit) and a \"When to Use What\" reference table.\n- **Level 2 (Assisted):** Level 1 content + mention /project:loop in the workflow section and @pm in the agents section of CLAUDE.md.\n- **Level 3 (Autonomous):** Level 2 content + mention /project:auto and worktree-based PR delivery workflow.\n- **Level 4 (Full Auto):** Level 3 content + add a prominent warning section about autonomous operation.\n\nThe autonomy-specific commands, agents, and hooks are injected post-compilation. Focus on tailoring the CLAUDE.md content and workflow guidance for the selected level.\n\nIf no autonomy level is specified, assume Level 1 (Guided).\n\n## Output Schema\n\nReturn ONLY valid JSON matching this structure:\n\n\\`\\`\\`json\n{\n \"claude_md\": \"Full CLAUDE.md content (under 150 lines)\",\n \"commands\": { \"help\": \"...\", \"develop\": \"...\", \"status\": \"...\", \"fix\": \"...\", \"sprint\": \"...\", \"spec\": \"...\", \"prove\": \"...\", \"grill\": \"...\", \"reset\": \"...\", \"persist\": \"...\" },\n \"rules\": { \"continuity\": \"...\", \"security\": \"...\" },\n \"agents\": { \"architect\": \"...\", \"planner\": \"...\", \"implementer\": \"...\", \"fixer\": \"...\", \"doc-updater\": \"...\", \"qa-orchestrator\": \"...\", \"linter\": \"...\", \"e2e-tester\": \"...\" },\n \"skills\": { \"skill-name/SKILL\": \"...\" },\n \"docs\": { \"DECISIONS\": \"...\", \"LEARNINGS\": \"...\", \"SPRINT\": \"...\" }\n}\n\\`\\`\\`\n\nReturn ONLY valid JSON. No markdown fences. No text outside the JSON.`;\n\nexport const SYSTEM_PROMPT = `You are the Kairn environment compiler. Your job is to generate a minimal, optimal Claude Code agent environment from a user's natural language description of what they want their agent to do.\n\nYou will receive:\n1. The user's intent (what they want to build/do)\n2. A tool registry (available MCP servers, plugins, and hooks)\n\nYou must output a JSON object matching the EnvironmentSpec schema.\n\n## Core Principles\n\n- **Minimalism over completeness.** Fewer, well-chosen tools beat many generic ones. Each MCP server costs 500-2000 context tokens.\n- **Workflow-specific, not generic.** Every instruction, command, and rule must relate to the user's actual workflow.\n- **Concise CLAUDE.md.** Under 150 lines. No generic text like \"be helpful.\" Include build/test commands, reference docs/ and skills/.\n- **Security by default.** Always include deny rules for destructive commands and secret file access.\n\n## CLAUDE.md Template (mandatory structure)\n\nThe \\`claude_md\\` field MUST follow this exact structure (max 150 lines):\n\n\\`\\`\\`\n# {Project Name}\n\n## Purpose\n{one-line description}\n\n## Tech Stack\n{bullet list of frameworks/languages}\n\n## Commands\n{concrete build/test/lint/dev commands}\n\n## Architecture\n{brief folder structure, max 10 lines}\n\n## Conventions\n{3-5 specific coding rules}\n\n## Key Commands\n{list /project: commands with descriptions}\n\n## Output\n{where results go, key files}\n\n## Verification\nAfter implementing any change, verify it works:\n- {build command} — must pass with no errors\n- {test command} — all tests must pass\n- {lint command} — no warnings or errors\n- {type check command} — no type errors\n\nIf any verification step fails, fix the issue before moving on.\nDo NOT skip verification steps.\n\n## Known Gotchas\n<!-- After any correction, add it here: \"Update CLAUDE.md so you don't make that mistake again.\" -->\n<!-- Prune this section when it exceeds 10 items — keep only the recurring ones. -->\n- (none yet — this section grows as you work)\n\n## Debugging\nWhen debugging, paste raw error output. Don't summarize — Claude works better with raw data.\nUse subagents for deep investigation to keep main context clean.\n\n## Git Workflow\n- Prefer small, focused commits (one feature or fix per commit)\n- Use conventional commits: feat:, fix:, docs:, refactor:, test:\n- Target < 200 lines per PR when possible\n\n## Engineering Standards\n- Lead with answers over reasoning. Be concise.\n- Use absolute file paths in all references.\n- No filler, no inner monologue, no time estimates.\n- Produce load-bearing code — every line of output should be actionable.\n\n## Tool Usage Policy\n- Prefer Edit tool over sed/awk for file modifications\n- Prefer Grep tool over rg for searching\n- Prefer Read tool over cat for file reading\n- Reserve Bash for: builds, installs, git, network, processes\n- Read and understand existing code before modifying\n- Delete unused code completely — no compatibility shims\n\n## Code Philosophy\n- Do not create abstractions for one-time operations\n- Complete the task fully — don't gold-plate, but don't leave it half-done\n- Prefer editing existing files over creating new ones\n\n## First Turn Protocol\n\nAt the start of every session, before doing ANY work:\n1. Run \\`pwd && ls -la && git status --short\\` to orient yourself\n2. Check relevant runtimes (e.g. \\`node --version\\`, \\`python3 --version\\` — pick what fits this project)\n3. Read any task-tracking files (docs/SPRINT.md, docs/DECISIONS.md)\n4. Summarize what you see in 2-3 lines, then proceed\n\nThis saves 2-5 exploratory turns. Never ask \"what files are here?\" — look first.\n\n## Sprint Contract\n\nBefore implementing, confirm acceptance criteria exist in docs/SPRINT.md.\nEach criterion must be numbered, testable, and independently verifiable.\nAfter implementing, verify EACH criterion individually. Do not mark done until all pass.\n\n## Completion Standards\n\nNever mark a task \"done\" without running the Completion Verification checklist.\nTests passing is necessary but not sufficient — also verify requirements coverage,\nstate cleanliness, and review changes from the perspective of a test engineer,\ncode reviewer, and the requesting user.\n\\`\\`\\`\n\nDo not add generic filler. Every line must be specific to the user's workflow.\n\n## What You Must Always Include\n\n1. A concise, workflow-specific \\`claude_md\\` (the CLAUDE.md content)\n2. A \\`/project:help\\` command that explains the environment\n3. A \\`docs/DECISIONS.md\\` file for architectural decisions\n4. A \\`docs/LEARNINGS.md\\` file for non-obvious discoveries\n5. A \\`rules/continuity.md\\` rule encouraging updates to DECISIONS.md and LEARNINGS.md\n6. A \\`rules/security.md\\` rule with essential security instructions\n7. settings.json with deny rules for \\`rm -rf\\`, \\`curl|sh\\`, reading \\`.env\\` and \\`secrets/\\`\n8. A \\`/project:status\\` command for code projects (uses ! for live git/SPRINT.md output)\n9. A \\`/project:fix\\` command for code projects (uses $ARGUMENTS for issue number)\n10. A \\`docs/SPRINT.md\\` file as the living spec/plan (replaces TODO.md — acceptance criteria, verification steps)\n11. A \"Verification\" section in CLAUDE.md with concrete verify commands for the project\n12. A \"Known Gotchas\" section in CLAUDE.md (starts empty, grows with corrections)\n13. A \"Debugging\" section in CLAUDE.md (2 lines: paste raw errors, use subagents)\n14. A \"Git Workflow\" section in CLAUDE.md (3 rules: small commits, conventional format, <200 lines PR)\n15. \"Engineering Standards\", \"Tool Usage Policy\", and \"Code Philosophy\" sections in CLAUDE.md\n16. A \"First Turn Protocol\" section in CLAUDE.md (orient before working: pwd, ls, git status, check relevant runtimes, read task files)\n17. A \"Completion Standards\" section in CLAUDE.md (never mark done without verifying: requirements met, tests passing, no debug artifacts, reviewed from 3 perspectives)\n18. A \"Sprint Contract\" section in CLAUDE.md (confirm acceptance criteria exist before implementing, verify each criterion after)\n\n## Tool Selection Rules\n\n- Only select tools directly relevant to the described workflow\n- Prefer free tools (auth: \"none\") when quality is comparable\n- Tier 1 tools (Context7, Sequential Thinking, security-guidance) should be included in most environments\n- For tools requiring API keys (auth: \"api_key\"), use \\${ENV_VAR} syntax — never hardcode keys\n- Maximum 6-8 MCP servers to avoid context bloat\n- Include a \\`reason\\` for each selected tool explaining why it fits this workflow\n\n## Context Budget (STRICT)\n\n- MCP servers: maximum 6. Prefer fewer.\n- CLAUDE.md: maximum 150 lines.\n- Rules: maximum 5 files, each under 20 lines.\n- Skills: maximum 3. Only include directly relevant ones.\n- Agents: maximum 5. Orchestration pipeline (/develop) agents.\n- Commands: no limit (loaded on demand, zero context cost).\n- Hooks: maximum 5 (auto-format, block-destructive, PostCompact, memory-persistence, plus one contextual).\n\nIf the workflow doesn't clearly need a tool, DO NOT include it.\nEach MCP server costs 500-2000 tokens of context window.\n\n## Output Schema\n\nReturn ONLY valid JSON matching this structure:\n\n\\`\\`\\`json\n{\n \"name\": \"short-kebab-case-name\",\n \"description\": \"One-line description of the environment\",\n \"tools\": [\n { \"tool_id\": \"id-from-registry\", \"reason\": \"why this tool fits\" }\n ],\n \"harness\": {\n \"claude_md\": \"The full CLAUDE.md content (under 150 lines)\",\n \"settings\": {\n \"permissions\": {\n \"allow\": [\"Bash(npm run *)\", \"Read\", \"Write\", \"Edit\"],\n \"deny\": [\"Bash(rm -rf *)\", \"Bash(curl * | sh)\", \"Read(./.env)\", \"Read(./secrets/**)\"]\n }\n },\n \"mcp_config\": {\n \"server-name\": { \"command\": \"npx\", \"args\": [\"...\"], \"env\": {} }\n },\n \"commands\": {\n \"help\": \"markdown content for /project:help\",\n \"develop\": \"markdown content for /project:develop\",\n \"persist\": \"markdown content for /project:persist\"\n },\n \"rules\": {\n \"continuity\": \"markdown content for continuity rule\",\n \"security\": \"markdown content for security rule\"\n },\n \"skills\": {\n \"skill-name/SKILL\": \"markdown content with YAML frontmatter\"\n },\n \"agents\": {\n \"architect\": \"agent markdown with YAML frontmatter\",\n \"planner\": \"agent markdown with YAML frontmatter\",\n \"implementer\": \"agent markdown with YAML frontmatter\",\n \"fixer\": \"agent markdown with YAML frontmatter\",\n \"doc-updater\": \"agent markdown with YAML frontmatter\"\n },\n \"docs\": {\n \"DECISIONS\": \"# Decisions\\\\n\\\\nArchitectural decisions.\",\n \"LEARNINGS\": \"# Learnings\\\\n\\\\nNon-obvious discoveries.\",\n \"SPRINT\": \"# Sprint\\\\n\\\\nLiving spec and plan.\"\n }\n }\n}\n\\`\\`\\`\n\nDo not include any text outside the JSON object. Do not wrap in markdown code fences.`;\n\nexport const CLARIFICATION_PROMPT = `You are helping a user define their project for environment compilation.\n\nGiven their initial description, generate 3-5 clarifying questions to understand:\n1. Language and framework\n2. What the project specifically does (be precise)\n3. Primary workflow (build, research, write, analyze?)\n4. Key dependencies or integrations\n5. Target audience\n\nFor each question, provide a reasonable suggestion based on the description.\n\nOutput ONLY a JSON array:\n[\n { \"question\": \"Language/framework?\", \"suggestion\": \"TypeScript + Node.js\" },\n ...\n]\n\nRules:\n- Suggestions should be reasonable guesses, clearly marked as suggestions\n- Keep questions short (under 10 words)\n- Maximum 5 questions\n- If the description is already very detailed, ask fewer questions`;\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { getUserRegistryPath } from \"../config.js\";\nimport type { RegistryTool } from \"../types.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport async function loadBundledRegistry(): Promise<RegistryTool[]> {\n const candidates = [\n path.resolve(__dirname, \"../registry/tools.json\"),\n path.resolve(__dirname, \"../src/registry/tools.json\"),\n path.resolve(__dirname, \"../../src/registry/tools.json\"),\n ];\n for (const candidate of candidates) {\n try {\n const data = await fs.readFile(candidate, \"utf-8\");\n return JSON.parse(data) as RegistryTool[];\n } catch {\n continue;\n }\n }\n throw new Error(\"Could not find tools.json registry\");\n}\n\nexport async function loadUserRegistry(): Promise<RegistryTool[]> {\n try {\n const data = await fs.readFile(getUserRegistryPath(), \"utf-8\");\n return JSON.parse(data) as RegistryTool[];\n } catch {\n return [];\n }\n}\n\nexport async function saveUserRegistry(tools: RegistryTool[]): Promise<void> {\n await fs.writeFile(getUserRegistryPath(), JSON.stringify(tools, null, 2), \"utf-8\");\n}\n\nexport async function loadRegistry(): Promise<RegistryTool[]> {\n const bundled = await loadBundledRegistry();\n const user = await loadUserRegistry();\n\n if (user.length === 0) return bundled;\n\n // User tools take precedence by ID\n const merged = new Map<string, RegistryTool>();\n for (const tool of bundled) {\n merged.set(tool.id, tool);\n }\n for (const tool of user) {\n merged.set(tool.id, tool);\n }\n return Array.from(merged.values());\n}\n","import type { IntentPattern } from './types.js';\n\n/** Static synonym map: verb → alternative phrases users might say */\nconst SYNONYM_MAP: Record<string, string[]> = {\n deploy: ['ship', 'push\\\\s+to\\\\s+prod', 'release', 'publish'],\n test: ['run\\\\s+tests', 'check', 'verify', 'run\\\\s+test\\\\s+suite'],\n lint: ['format', 'style\\\\s+check', 'linting'],\n build: ['compile', 'bundle', 'make'],\n dev: ['develop', 'start\\\\s+dev', 'run\\\\s+dev'],\n start: ['run', 'launch', 'serve'],\n migrate: ['migration', 'schema\\\\s+change', 'db\\\\s+update'],\n seed: ['populate', 'seed\\\\s+data', 'load\\\\s+fixtures'],\n clean: ['purge', 'clear', 'reset\\\\s+cache'],\n docs: ['document', 'documentation', 'write\\\\s+docs'],\n review: ['code\\\\s+review', 'pr\\\\s+review', 'check\\\\s+code'],\n commit: ['save\\\\s+changes', 'check\\\\s+in', 'git\\\\s+commit'],\n fix: ['repair', 'patch', 'debug', 'resolve'],\n refactor: ['restructure', 'reorganize', 'clean\\\\s+up'],\n plan: ['design', 'architect', 'outline'],\n status: ['progress', 'overview', 'summary'],\n};\n\n/**\n * Extract the first description line from command markdown content.\n * Skips the heading line (starts with #) and returns the next non-empty line.\n */\nfunction extractDescription(content: string): string {\n const lines = content.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n return trimmed;\n }\n }\n return '';\n}\n\n/**\n * Extract the primary verb from a command name.\n * Handles hyphenated names like \"db-migrate\" → \"migrate\".\n */\nfunction extractVerb(commandName: string): string {\n const parts = commandName.split('-');\n // For multi-part names, the verb is usually the last part\n // \"db-migrate\" → \"migrate\", \"test\" → \"test\"\n if (parts.length > 1) {\n return parts[parts.length - 1];\n }\n return parts[0];\n}\n\n/**\n * Build a regex alternation from a command name and its synonyms.\n */\nfunction buildPatternAlternation(commandName: string): string {\n const verb = extractVerb(commandName);\n const alternatives = [verb];\n\n // Add synonyms if available\n const synonyms = SYNONYM_MAP[verb];\n if (synonyms) {\n alternatives.push(...synonyms);\n }\n\n // Add the full command name if it differs from the verb\n if (commandName !== verb && !alternatives.includes(commandName)) {\n alternatives.push(commandName.replace(/-/g, '[\\\\s-]'));\n }\n\n return `\\\\b(${alternatives.join('|')})\\\\b`;\n}\n\n/**\n * Generate intent patterns from npm scripts that aren't covered by commands.\n */\nfunction generateScriptPatterns(\n scripts: Record<string, string>,\n existingCommands: Set<string>,\n): IntentPattern[] {\n const patterns: IntentPattern[] = [];\n\n for (const scriptName of Object.keys(scripts)) {\n // Skip if a command already covers this script\n const verb = extractVerb(scriptName);\n if (existingCommands.has(verb) || existingCommands.has(scriptName)) {\n continue;\n }\n\n // Handle composite script names like \"test:e2e\"\n const parts = scriptName.split(':');\n if (parts.length > 1) {\n const suffix = parts[parts.length - 1];\n const alternatives = [suffix];\n\n // Add common expansions\n if (suffix === 'e2e') {\n alternatives.push('end[\\\\s.-]to[\\\\s.-]end');\n }\n\n patterns.push({\n pattern: `\\\\b(${alternatives.join('|')})\\\\b`,\n command: `/project:${scriptName}`,\n description: `Run npm script: ${scriptName}`,\n source: 'generated',\n });\n }\n }\n\n return patterns;\n}\n\n/**\n * Generate intent patterns from generated commands and project context.\n *\n * For each command, produces regex patterns from the command name,\n * synonyms from a static map, and framework-specific verbs.\n * Patterns are sorted by specificity (longer patterns first).\n */\nexport function generateIntentPatterns(\n commands: Record<string, string>,\n agents: Record<string, string>,\n projectProfile: { language: string; framework: string; scripts: Record<string, string> },\n): IntentPattern[] {\n const patterns: IntentPattern[] = [];\n const commandNames = new Set(Object.keys(commands));\n\n // Generate patterns for each command\n for (const [name, content] of Object.entries(commands)) {\n const description = extractDescription(content);\n const patternStr = buildPatternAlternation(name);\n\n patterns.push({\n pattern: patternStr,\n command: `/project:${name}`,\n description: description || `Run ${name} workflow`,\n source: 'generated',\n });\n }\n\n // Add patterns from npm scripts not already covered\n const scriptPatterns = generateScriptPatterns(\n projectProfile.scripts,\n commandNames,\n );\n patterns.push(...scriptPatterns);\n\n // Sort by specificity: longer patterns first (more specific = higher priority)\n patterns.sort((a, b) => b.pattern.length - a.pattern.length);\n\n return patterns;\n}\n","/**\n * Extract the first description line from command/agent markdown content.\n * Skips heading lines (starting with #) and returns the first non-empty line.\n */\nfunction extractFirstLine(content: string): string {\n const lines = content.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n return trimmed;\n }\n }\n return '';\n}\n\n/**\n * Compile the Tier 2 intent classification prompt.\n *\n * Builds a project-specific prompt by extracting first-line descriptions\n * from each command and agent, then embedding them into a classification\n * template. The resulting prompt is baked into settings.json at generation\n * time — no runtime template interpolation needed.\n */\nexport function compileIntentPrompt(\n commands: Record<string, string>,\n agents: Record<string, string>,\n): string {\n // Build workflow manifest\n const workflowLines: string[] = [];\n for (const [name, content] of Object.entries(commands)) {\n const desc = extractFirstLine(content);\n workflowLines.push(`- /project:${name} — ${desc}`);\n }\n const workflowManifest = workflowLines.length > 0\n ? workflowLines.join('\\n')\n : '(no workflows defined)';\n\n // Build agent manifest\n const agentLines: string[] = [];\n for (const [name, content] of Object.entries(agents)) {\n const desc = extractFirstLine(content);\n agentLines.push(`- @${name} — ${desc}`);\n }\n const agentManifest = agentLines.length > 0\n ? agentLines.join('\\n')\n : '(no agents defined)';\n\n return `You are an intent classifier for a software project. The user said something that didn't match any known command keyword.\n\nAvailable workflows:\n${workflowManifest}\n\nAvailable agents:\n${agentManifest}\n\nUser input: $PROMPT\n\nIf this maps to one or more workflows, return JSON:\n{\"additionalContext\": \"[INTENT ROUTED] Based on your request, use: /project:<command> — <description>\"}\n\nIf the user is asking a question or making a statement that doesn't need a workflow, return:\n{\"ok\": true}\n\nDo not activate workflows for questions like 'what does deploy do?' or 'how do I test?'. Only activate for action requests.`;\n}\n","import type { IntentPattern } from './types.js';\n\n/**\n * Render a pattern entry as a JavaScript object literal for embedding\n * in the generated intent-router.mjs script.\n */\nfunction renderPatternEntry(p: IntentPattern): string {\n // Escape backslashes for embedding in a JS regex literal\n const escapedPattern = p.pattern.replace(/\\\\/g, '\\\\\\\\');\n const escapedDesc = p.description.replace(/'/g, \"\\\\'\");\n const escapedCmd = p.command.replace(/'/g, \"\\\\'\");\n return ` { pattern: /${p.pattern}/i,\\n command: '${escapedCmd}',\\n description: '${escapedDesc}' }`;\n}\n\n/**\n * Render the full intent-router.mjs script.\n *\n * This generates a Node.js ESM script that:\n * 1. Reads the user prompt from stdin (Claude Code hooks API)\n * 2. Sanitizes it (strips code blocks, URLs, file paths)\n * 3. Filters out informational questions\n * 4. Matches against project-specific regex patterns\n * 5. Returns additionalContext on match, or falls through to Tier 2\n */\nexport function renderIntentRouter(\n patterns: IntentPattern[],\n generationTimestamp: string,\n): string {\n const patternEntries = patterns\n .map(p => renderPatternEntry(p))\n .join(',\\n');\n\n return `#!/usr/bin/env node\n/**\n * Kairn Intent Router — Tier 1 (Regex)\n * Generated by kairn describe. Project-specific keyword patterns.\n *\n * If a keyword matches, injects a system-reminder pointing Claude\n * to the right command/workflow. If no match, falls through to\n * the Tier 2 prompt hook.\n *\n * Last updated: ${generationTimestamp}\n */\n\nimport { readFileSync } from 'fs';\n\n// Read prompt from stdin (Claude Code hooks API)\nconst input = readFileSync('/dev/stdin', 'utf-8');\nlet prompt = '';\ntry {\n const data = JSON.parse(input);\n prompt = data.prompt || '';\n} catch { process.exit(0); }\n\nif (!prompt.trim()) {\n console.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n process.exit(0);\n}\n\n// Sanitize: strip code blocks, URLs, file paths\nconst clean = prompt\n .replace(/\\`\\`\\`[\\\\s\\\\S]*?\\`\\`\\`/g, '')\n .replace(/\\`[^\\`]+\\`/g, '')\n .replace(/https?:\\\\/\\\\/\\\\S+/g, '')\n .replace(/(\\\\/[\\\\w.-]+){2,}/g, '')\n .toLowerCase();\n\n// Question filter: don't trigger on informational queries\nconst QUESTION_PATTERNS = [\n /\\\\b(?:what(?:'s|\\\\s+is)|how\\\\s+(?:to|do\\\\s+i)\\\\s+use|explain|describe|tell\\\\s+me\\\\s+about)\\\\b/i,\n];\nfunction isQuestion(text, position, length) {\n const start = Math.max(0, position - 80);\n const end = Math.min(text.length, position + length + 80);\n const ctx = text.slice(start, end);\n return QUESTION_PATTERNS.some(p => p.test(ctx));\n}\n\n// ═══════════════════════════════════════════════\n// PROJECT-SPECIFIC KEYWORD PATTERNS\n// Generated from: kairn describe analysis\n// Last updated: ${generationTimestamp}\n// ═══════════════════════════════════════════════\n\nconst PATTERNS = [\n${patternEntries}\n];\n\n// Match against patterns\nfor (const { pattern, command, description } of PATTERNS) {\n const match = clean.match(pattern);\n if (match && !isQuestion(clean, match.index, match[0].length)) {\n const output = {\n \"continue\": true,\n hookSpecificOutput: {\n hookEventName: 'UserPromptSubmit',\n additionalContext: \\`[INTENT ROUTED] Based on your request, use: \\${command} — \\${description}\\\\n\\\\nUser's original request: \\${prompt}\\\\n\\\\nExecute the command above to fulfill the user's intent.\\`\n }\n };\n console.log(JSON.stringify(output));\n process.exit(0);\n }\n}\n\n// No match — fall through to Tier 2 (prompt hook)\nconsole.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n`;\n}\n","/**\n * Render the intent-learner.mjs script.\n *\n * This generates a static Node.js ESM script (not project-specific) that:\n * 1. Reads .claude/hooks/intent-log.jsonl\n * 2. Groups entries by routed_to command\n * 3. For commands with 3+ entries: extracts common words, builds regex\n * 4. Appends new patterns to intent-router.mjs PATTERNS array\n * 5. Writes audit log to intent-promotions.jsonl\n * 6. Truncates processed entries from log\n */\nexport function renderIntentLearner(): string {\n return `#!/usr/bin/env node\n/**\n * Kairn Intent Learner — Pattern Promotion (Tier 2 → Tier 1)\n * Runs on SessionStart to promote recurring Tier 2 patterns to Tier 1 regexes.\n * Generated by kairn describe.\n */\n\nimport { readFileSync, writeFileSync, appendFileSync, existsSync } from 'fs';\nimport { join, dirname } from 'path';\n\nconst hooksDir = join(dirname(new URL(import.meta.url).pathname));\nconst logPath = join(hooksDir, 'intent-log.jsonl');\nconst routerPath = join(hooksDir, 'intent-router.mjs');\nconst promotionsPath = join(hooksDir, 'intent-promotions.jsonl');\n\n// Read log entries\nlet entries = [];\ntry {\n const raw = readFileSync(logPath, 'utf-8').trim();\n if (!raw) {\n console.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n process.exit(0);\n }\n entries = raw.split('\\\\n').map(line => {\n try { return JSON.parse(line); }\n catch { return null; }\n }).filter(Boolean);\n} catch {\n // Log file doesn't exist or is unreadable — nothing to promote\n console.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n process.exit(0);\n}\n\nif (entries.length === 0) {\n console.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n process.exit(0);\n}\n\n// Group by routed_to command\nconst groups = {};\nconst remaining = [];\nfor (const entry of entries) {\n if (!entry.routed_to) { remaining.push(entry); continue; }\n if (!groups[entry.routed_to]) groups[entry.routed_to] = [];\n groups[entry.routed_to].push(entry);\n}\n\n// For each command with 3+ entries, extract common words and build regex\nconst promoted = [];\nfor (const [command, cmdEntries] of Object.entries(groups)) {\n if (cmdEntries.length < 3) {\n remaining.push(...cmdEntries);\n continue;\n }\n\n // Extract unique words from all prompts\n const wordFreq = {};\n for (const entry of cmdEntries) {\n const words = (entry.prompt || '').toLowerCase()\n .replace(/[^a-z\\\\s]/g, '')\n .split(/\\\\s+/)\n .filter(w => w.length > 2);\n const unique = [...new Set(words)];\n for (const word of unique) {\n wordFreq[word] = (wordFreq[word] || 0) + 1;\n }\n }\n\n // Find words that appear in at least half the entries\n const threshold = Math.ceil(cmdEntries.length / 2);\n const commonWords = Object.entries(wordFreq)\n .filter(([, count]) => count >= threshold)\n .map(([word]) => word)\n .filter(w => !['the', 'and', 'for', 'this', 'that', 'can', 'you', 'please'].includes(w));\n\n if (commonWords.length === 0) {\n remaining.push(...cmdEntries);\n continue;\n }\n\n // Build regex pattern from common words\n const patternStr = '\\\\\\\\b(' + commonWords.join('|') + ')\\\\\\\\b';\n\n // Read current router and check if pattern already exists\n try {\n const routerContent = readFileSync(routerPath, 'utf-8');\n if (commonWords.some(w => routerContent.includes(w + '|') || routerContent.includes('|' + w))) {\n remaining.push(...cmdEntries);\n continue;\n }\n\n // Append new pattern to PATTERNS array\n const newEntry = \\` { pattern: /\\\\\\\\b(\\${commonWords.join('|')})/i,\\\\n command: '\\${command}',\\\\n description: 'Learned from usage patterns' },\\`;\n const insertPoint = routerContent.lastIndexOf('];');\n if (insertPoint === -1) {\n remaining.push(...cmdEntries);\n continue;\n }\n\n const updatedRouter = routerContent.slice(0, insertPoint) +\n newEntry + '\\\\n' +\n routerContent.slice(insertPoint);\n writeFileSync(routerPath, updatedRouter, 'utf-8');\n\n // Record promotion\n const promotion = {\n timestamp: new Date().toISOString(),\n command,\n pattern: patternStr,\n sourcePrompts: cmdEntries.map(e => e.prompt),\n commonWords,\n };\n promoted.push(promotion);\n appendFileSync(promotionsPath, JSON.stringify(promotion) + '\\\\n');\n\n } catch {\n remaining.push(...cmdEntries);\n continue;\n }\n}\n\n// Write back remaining (unprocessed) entries\nwriteFileSync(logPath, remaining.map(e => JSON.stringify(e)).join('\\\\n') + (remaining.length ? '\\\\n' : ''), 'utf-8');\n\nconsole.log(JSON.stringify({ \"continue\": true, suppressOutput: true }));\n`;\n}\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport type { EnvironmentSpec, RegistryTool } from \"../types.js\";\nimport { applyAutonomyLevel } from \"../autonomy.js\";\n\nconst STATUS_LINE = {\n command:\n \"printf '%s | %s tasks' \\\"$(git branch --show-current 2>/dev/null || echo 'no-git')\\\" \\\"$(grep -c '\\\\- \\\\[ \\\\]' docs/SPRINT.md 2>/dev/null || echo 0)\\\"\",\n};\n\nfunction isCodeProject(spec: EnvironmentSpec): boolean {\n const commands = spec.harness.commands ?? {};\n return \"status\" in commands || \"test\" in commands;\n}\n\nconst ENV_LOADER_HOOK = {\n matcher: \"\",\n hooks: [{\n type: \"command\",\n command: 'if [ -f .env ] && [ -n \"$CLAUDE_ENV_FILE\" ]; then grep -v \"^#\" .env | grep -v \"^$\" | grep \"=\" >> \"$CLAUDE_ENV_FILE\"; fi',\n }],\n};\n\nconst PERSIST_ROUTER_TEMPLATE = `import { readFileSync } from 'fs';\n\nconst input = JSON.parse(readFileSync('/dev/stdin', 'utf8'));\nconst prompt = (input.prompt ?? '').trim();\n\n// Pass-through patterns (fast exit)\nconst PASSTHROUGH = /^(what|how|why|where|when|can you|does|is |show me|find |search |list |\\\\/project:)/i;\nconst SINGLE_FILE = /^(edit|fix the typo|update the comment|change the|rename) .{3,60}$/i;\n\nif (PASSTHROUGH.test(prompt) || SINGLE_FILE.test(prompt) || prompt.length < 20) {\n process.stdout.write(JSON.stringify({ continue: true }));\n process.exit(0);\n}\n\n// Check config for routing mode\nlet routingMode = 'auto';\ntry {\n const settings = JSON.parse(readFileSync('.claude/settings.json', 'utf8'));\n routingMode = settings.persistence_routing ?? 'auto';\n} catch { /* default to auto */ }\n\nif (routingMode === 'off') {\n process.stdout.write(JSON.stringify({ continue: true }));\n process.exit(0);\n}\n\n// Complexity signals\nconst signals = [];\n\nif (/\\\\b(then|after that|and also|next|finally|step \\\\d|first .* then)\\\\b/i.test(prompt)) {\n signals.push('multi-step');\n}\nif (/\\\\b(add|implement|build|create|integrate|set up)\\\\b.*\\\\b(feature|auth|api|endpoint|page|component|module|service|database|migration)\\\\b/i.test(prompt)) {\n signals.push('feature-scope');\n}\nif (/\\\\b(migrate|convert|replace|upgrade|refactor|rewrite|restructure)\\\\b/i.test(prompt)) {\n signals.push('refactor-scope');\n}\nif (/\\\\b(when .* happens|steps to reproduce|broken|crash|regression|fails when)\\\\b/i.test(prompt)) {\n signals.push('bug-with-repro');\n}\nif (/\\\\b(persist|keep working|don't stop|until done|until .* pass)\\\\b/i.test(prompt)) {\n signals.push('explicit');\n}\nif (prompt.split(/\\\\s+/).length > 50) {\n signals.push('long-prompt');\n}\n\nconst shouldRoute = routingMode === 'manual'\n ? signals.includes('explicit')\n : signals.length >= 2 || signals.includes('explicit');\n\nif (shouldRoute) {\n process.stdout.write(JSON.stringify({\n continue: true,\n hookSpecificOutput: {\n hookEventName: 'UserPromptSubmit',\n additionalContext: [\n 'PERSISTENCE ROUTING: This task has complexity signals (' + signals.join(', ') + ').',\n 'Execute this using the /project:persist workflow:',\n '1. Ensure acceptance criteria exist in docs/SPRINT.md (create from this prompt if needed)',\n '2. Initialize .claude/progress.json',\n '3. Work criterion-by-criterion until all pass',\n '4. Run review gate before marking complete',\n ].join('\\\\n'),\n },\n }));\n} else {\n process.stdout.write(JSON.stringify({ continue: true }));\n}\n`;\n\nconst PERSIST_ROUTER_HOOK = {\n matcher: '',\n hooks: [{\n type: 'command',\n command: 'node \"$CLAUDE_PROJECT_DIR/.claude/hooks/persist-router.mjs\"',\n timeout: 5,\n }],\n};\n\nfunction resolveSettings(\n spec: EnvironmentSpec,\n options?: { hasEnvVars?: boolean }\n): Record<string, unknown> | null {\n const settings = spec.harness.settings;\n const base: Record<string, unknown> = settings && Object.keys(settings).length > 0\n ? { ...(settings as Record<string, unknown>) }\n : {};\n\n // Add statusLine for code projects\n if (!(\"statusLine\" in base) && isCodeProject(spec)) {\n base.statusLine = STATUS_LINE;\n }\n\n // Add SessionStart hook for .env loading\n if (options?.hasEnvVars) {\n const hooks = (base.hooks ?? {}) as Record<string, unknown[]>;\n const sessionStart = (hooks.SessionStart ?? []) as unknown[];\n sessionStart.push(ENV_LOADER_HOOK);\n hooks.SessionStart = sessionStart;\n base.hooks = hooks;\n }\n\n // Add persist-router hook for L3+ code projects\n // (persistence_routing is set by applyAutonomyLevel for all levels)\n if (isCodeProject(spec) && (spec.autonomy_level ?? 1) >= 3) {\n const hooks = (base.hooks ?? {}) as Record<string, unknown[]>;\n const userPromptSubmit = (hooks.UserPromptSubmit ?? []) as unknown[];\n userPromptSubmit.push(PERSIST_ROUTER_HOOK);\n hooks.UserPromptSubmit = userPromptSubmit;\n base.hooks = hooks;\n }\n\n // Add intent routing hooks if patterns exist\n const hasIntentHooks = spec.harness.hooks &&\n Object.keys(spec.harness.hooks).length > 0;\n\n if (hasIntentHooks) {\n const hooks = (base.hooks ?? {}) as Record<string, unknown[]>;\n\n // Tier 1 (regex) + Tier 2 (prompt) on UserPromptSubmit\n const userPromptSubmit = (hooks.UserPromptSubmit ?? []) as unknown[];\n const intentHookEntry: Record<string, unknown> = {\n matcher: '*',\n hooks: [\n {\n type: 'command',\n command: 'node \"$CLAUDE_PROJECT_DIR/.claude/hooks/intent-router.mjs\"',\n timeout: 5,\n },\n ],\n };\n // Add Tier 2 prompt hook if template exists\n if (spec.harness.intent_prompt_template) {\n (intentHookEntry.hooks as unknown[]).push({\n type: 'prompt',\n prompt: spec.harness.intent_prompt_template,\n timeout: 15,\n });\n }\n userPromptSubmit.push(intentHookEntry);\n hooks.UserPromptSubmit = userPromptSubmit;\n\n // Intent learner on SessionStart\n const sessionStart = (hooks.SessionStart ?? []) as unknown[];\n sessionStart.push({\n matcher: '*',\n hooks: [{\n type: 'command',\n command: 'node \"$CLAUDE_PROJECT_DIR/.claude/hooks/intent-learner.mjs\"',\n timeout: 10,\n }],\n });\n hooks.SessionStart = sessionStart;\n\n base.hooks = hooks;\n }\n\n if (Object.keys(base).length === 0) return null;\n return base;\n}\n\nasync function writeFile(filePath: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf-8\");\n}\n\nexport function buildFileMap(\n spec: EnvironmentSpec,\n options?: { hasEnvVars?: boolean }\n): Map<string, string> {\n // Apply autonomy-level content before building file map\n applyAutonomyLevel(spec);\n\n const files = new Map<string, string>();\n\n if (spec.harness.claude_md) {\n files.set(\".claude/CLAUDE.md\", spec.harness.claude_md);\n }\n const resolvedSettings = resolveSettings(spec, options);\n if (resolvedSettings) {\n files.set(\".claude/settings.json\", JSON.stringify(resolvedSettings, null, 2));\n }\n if (\n spec.harness.mcp_config &&\n Object.keys(spec.harness.mcp_config).length > 0\n ) {\n files.set(\n \".mcp.json\",\n JSON.stringify({ mcpServers: spec.harness.mcp_config }, null, 2)\n );\n }\n if (spec.harness.commands) {\n for (const [name, content] of Object.entries(spec.harness.commands)) {\n files.set(`.claude/commands/${name}.md`, content);\n }\n }\n if (spec.harness.rules) {\n for (const [name, content] of Object.entries(spec.harness.rules)) {\n files.set(`.claude/rules/${name}.md`, content);\n }\n }\n if (spec.harness.skills) {\n for (const [skillPath, content] of Object.entries(spec.harness.skills)) {\n files.set(`.claude/skills/${skillPath}.md`, content);\n }\n }\n if (spec.harness.agents) {\n for (const [name, content] of Object.entries(spec.harness.agents)) {\n files.set(`.claude/agents/${name}.md`, content);\n }\n }\n if (spec.harness.docs) {\n for (const [name, content] of Object.entries(spec.harness.docs)) {\n files.set(`.claude/docs/${name}.md`, content);\n }\n }\n\n // Hooks (intent-router.mjs, intent-learner.mjs)\n if (spec.harness.hooks) {\n for (const [name, content] of Object.entries(spec.harness.hooks)) {\n files.set(`.claude/hooks/${name}.mjs`, content);\n }\n // Create empty intent-log.jsonl for Tier 2 logging\n if (Object.keys(spec.harness.hooks).length > 0) {\n files.set('.claude/hooks/intent-log.jsonl', '');\n }\n }\n\n // Persist-router hook for L3+ code projects\n if (isCodeProject(spec) && (spec.autonomy_level ?? 1) >= 3) {\n files.set('.claude/hooks/persist-router.mjs', PERSIST_ROUTER_TEMPLATE);\n }\n\n return files;\n}\n\nexport async function writeEnvironment(\n spec: EnvironmentSpec,\n targetDir: string,\n options?: { hasEnvVars?: boolean }\n): Promise<string[]> {\n // Apply autonomy-level content before writing\n applyAutonomyLevel(spec);\n\n const claudeDir = path.join(targetDir, \".claude\");\n const written: string[] = [];\n\n // 1. CLAUDE.md\n if (spec.harness.claude_md) {\n const p = path.join(claudeDir, \"CLAUDE.md\");\n await writeFile(p, spec.harness.claude_md);\n written.push(\".claude/CLAUDE.md\");\n }\n\n // 2. settings.json\n const resolvedSettings = resolveSettings(spec, options);\n if (resolvedSettings) {\n const p = path.join(claudeDir, \"settings.json\");\n await writeFile(p, JSON.stringify(resolvedSettings, null, 2));\n written.push(\".claude/settings.json\");\n }\n\n // 3. .mcp.json (project-scoped, goes in project root)\n if (\n spec.harness.mcp_config &&\n Object.keys(spec.harness.mcp_config).length > 0\n ) {\n const p = path.join(targetDir, \".mcp.json\");\n const mcpContent = { mcpServers: spec.harness.mcp_config };\n await writeFile(p, JSON.stringify(mcpContent, null, 2));\n written.push(\".mcp.json\");\n }\n\n // 4. Commands\n if (spec.harness.commands) {\n for (const [name, content] of Object.entries(spec.harness.commands)) {\n const p = path.join(claudeDir, \"commands\", `${name}.md`);\n await writeFile(p, content);\n written.push(`.claude/commands/${name}.md`);\n }\n }\n\n // 5. Rules\n if (spec.harness.rules) {\n for (const [name, content] of Object.entries(spec.harness.rules)) {\n const p = path.join(claudeDir, \"rules\", `${name}.md`);\n await writeFile(p, content);\n written.push(`.claude/rules/${name}.md`);\n }\n }\n\n // 6. Skills\n if (spec.harness.skills) {\n for (const [skillPath, content] of Object.entries(spec.harness.skills)) {\n const p = path.join(claudeDir, \"skills\", `${skillPath}.md`);\n await writeFile(p, content);\n written.push(`.claude/skills/${skillPath}.md`);\n }\n }\n\n // 7. Agents\n if (spec.harness.agents) {\n for (const [name, content] of Object.entries(spec.harness.agents)) {\n const p = path.join(claudeDir, \"agents\", `${name}.md`);\n await writeFile(p, content);\n written.push(`.claude/agents/${name}.md`);\n }\n }\n\n // 8. Docs\n if (spec.harness.docs) {\n for (const [name, content] of Object.entries(spec.harness.docs)) {\n const p = path.join(claudeDir, \"docs\", `${name}.md`);\n await writeFile(p, content);\n written.push(`.claude/docs/${name}.md`);\n }\n }\n\n // 9. Hooks (intent-router.mjs, intent-learner.mjs)\n if (spec.harness.hooks) {\n for (const [name, content] of Object.entries(spec.harness.hooks)) {\n const p = path.join(claudeDir, \"hooks\", `${name}.mjs`);\n await writeFile(p, content);\n written.push(`.claude/hooks/${name}.mjs`);\n }\n // Create empty intent-log.jsonl for Tier 2 logging\n if (Object.keys(spec.harness.hooks).length > 0) {\n const logPath = path.join(claudeDir, \"hooks\", \"intent-log.jsonl\");\n await writeFile(logPath, '');\n written.push('.claude/hooks/intent-log.jsonl');\n }\n }\n\n // 10. Persist-router hook for L3+ code projects\n if (isCodeProject(spec) && (spec.autonomy_level ?? 1) >= 3) {\n const p = path.join(claudeDir, \"hooks\", \"persist-router.mjs\");\n await writeFile(p, PERSIST_ROUTER_TEMPLATE);\n written.push('.claude/hooks/persist-router.mjs');\n }\n\n return written;\n}\n\nexport interface EnvSetupInfo {\n toolName: string;\n envVar: string;\n description: string;\n signupUrl?: string;\n}\n\nexport function summarizeSpec(\n spec: EnvironmentSpec,\n registry: RegistryTool[]\n): {\n toolCount: number;\n commandCount: number;\n ruleCount: number;\n skillCount: number;\n agentCount: number;\n pluginCommands: string[];\n envSetup: EnvSetupInfo[];\n} {\n const pluginCommands: string[] = [];\n const envSetup: EnvSetupInfo[] = [];\n\n for (const selected of spec.tools) {\n const tool = registry.find((t) => t.id === selected.tool_id);\n if (!tool) continue;\n\n if (tool.install.plugin_command) {\n pluginCommands.push(tool.install.plugin_command);\n }\n\n if (tool.env_vars) {\n for (const ev of tool.env_vars) {\n envSetup.push({\n toolName: tool.name,\n envVar: ev.name,\n description: ev.description,\n signupUrl: tool.signup_url,\n });\n }\n }\n }\n\n return {\n toolCount: spec.tools.length,\n commandCount: Object.keys(spec.harness.commands || {}).length,\n ruleCount: Object.keys(spec.harness.rules || {}).length,\n skillCount: Object.keys(spec.harness.skills || {}).length,\n agentCount: Object.keys(spec.harness.agents || {}).length,\n pluginCommands,\n envSetup,\n };\n}\n","import type { EnvironmentSpec, AutonomyLevel } from \"./types.js\";\n\nconst AUTONOMY_LABELS: Record<AutonomyLevel, string> = {\n 1: \"Guided\",\n 2: \"Assisted\",\n 3: \"Autonomous\",\n 4: \"Full Auto\",\n};\n\n/** Welcome hook — shows orientation on first session */\nconst WELCOME_HOOK = {\n matcher: \"\",\n hooks: [{\n type: \"command\" as const,\n command: \"if [ ! -f .claude/.toured ]; then echo '\\\\n Welcome to your Kairn environment!\\\\n Type /project:tour for a walkthrough, or /project:help for a quick reference.\\\\n'; fi\",\n }],\n};\n\n// ── Level 1: Guided ─────────────────────────────────────────────\n\nconst TOUR_COMMAND = `# Environment Tour\n\nWelcome! Let me show you around this Kairn environment.\n\n## Your Commands\nRead .claude/commands/ and list each one with a one-line description.\nGroup them by workflow phase:\n\n PLAN: /project:spec, /project:sprint, /project:plan\n BUILD: /project:develop (full pipeline), or just start coding\n VERIFY: /project:prove, /project:grill, /project:test\n SHIP: /project:commit, /project:review\n MANAGE: /project:status, /project:reset\n\n## Your Agents\nRead .claude/agents/ and explain each one with how to invoke it.\n\n## Your MCP Tools\n!claude mcp list 2>/dev/null || echo \"Run /mcp in Claude Code to see active tools\"\n\n## Workflow\nFor this project, the recommended flow is:\n spec → sprint → plan → code → prove → grill → commit\n\n## Tips\n- Type / to see all commands\n- Type @ to invoke an agent\n- Paste raw errors — don't summarize them\n- Use subagents for deep investigation\n- Say \"update CLAUDE.md\" after any correction\n\nAfter showing the tour, create .claude/.toured to suppress the welcome message:\n!touch .claude/.toured\n\nReady to start? Try /project:spec to define your first feature.`;\n\nfunction buildQuickstart(spec: EnvironmentSpec): string {\n const commands = Object.keys(spec.harness.commands || {});\n const agents = Object.keys(spec.harness.agents || {});\n\n const commandList = commands\n .map((c) => `- \\`/project:${c}\\``)\n .join(\"\\n\");\n\n const agentList = agents.length > 0\n ? agents.map((a) => `- \\`@${a}\\``).join(\"\\n\")\n : \"- (none configured)\";\n\n return `# Quick Start Guide\n\nThis environment was generated by Kairn. Here's how to use it.\n\n## First Time\n1. Open terminal in this directory\n2. Run \\`claude\\`\n3. Type \\`/project:tour\\` for a guided walkthrough\n\n## Daily Workflow\n1. \\`/project:status\\` — see where things stand\n2. \\`/project:spec\\` — define what to build (Claude will interview you)\n3. Start coding — Claude follows CLAUDE.md automatically\n4. \\`/project:prove\\` — verify your work\n5. \\`/project:commit\\` — ship it\n\n## Commands\n${commandList}\n\n## Agents\n${agentList}\n\n## Need Help?\nType \\`/project:help\\` in Claude Code for a quick reference.\n`;\n}\n\n// ── Bootstrap (Level 2+: command, Level 3+: SessionStart hook) ─\n\nconst BOOTSTRAP_COMMAND = `# Environment Snapshot\n\nRun this command at the start of any session to gather runtime context.\nThis saves 2-5 exploratory turns.\n\n1. Run the following compound command and read the output:\n \\`\\`\\`bash\n echo '=== WORKING DIRECTORY ===' && pwd && \\\\\n echo '=== PROJECT FILES ===' && ls -la && \\\\\n echo '=== GIT STATUS ===' && (git status --short 2>/dev/null || echo 'not a git repo') && \\\\\n echo '=== LANGUAGES ===' && \\\\\n (node --version 2>&1 || true) && \\\\\n (python3 --version 2>&1 || true) && \\\\\n (go version 2>&1 || true) && \\\\\n (rustc --version 2>&1 || true) && \\\\\n echo '=== PACKAGE MANAGERS ===' && \\\\\n (npm --version 2>&1 && echo \"npm $(npm --version 2>&1)\" || true) && \\\\\n (pip3 --version 2>&1 || true) && \\\\\n (cargo --version 2>&1 || true) && \\\\\n echo '=== ENVIRONMENT ===' && \\\\\n (cat .env 2>/dev/null | sed 's/=.*/=***/' || echo 'no .env file')\n \\`\\`\\`\n\n2. Summarize the environment in 3-4 lines:\n - Runtime: [languages + versions found]\n - Project: [framework, key deps, file count]\n - State: [git branch, clean/dirty, .env present]\n\n3. Keep this summary in context for the rest of the session.`;\n\nfunction buildBootstrapHookCommand(spec: EnvironmentSpec): string {\n const checks: string[] = [\n \"echo '--- Environment Snapshot ---'\",\n \"pwd\",\n \"ls -la --color=never | head -20\",\n \"echo '---'\",\n \"git status --short 2>/dev/null || true\",\n \"echo '---'\",\n ];\n\n // Infer project type from claude_md content (Tech Stack section)\n const md = (spec.harness.claude_md ?? \"\").toLowerCase();\n if (md.includes(\"node\") || md.includes(\"typescript\") || md.includes(\"javascript\") || md.includes(\"react\") || md.includes(\"next\")) {\n checks.push(\"node --version 2>&1 || true\");\n checks.push(\"cat package.json 2>/dev/null | head -5 || true\");\n }\n if (md.includes(\"python\") || md.includes(\"django\") || md.includes(\"flask\") || md.includes(\"fastapi\")) {\n checks.push(\"python3 --version 2>&1 || true\");\n }\n if (md.includes(\"rust\") || md.includes(\"cargo\")) {\n checks.push(\"rustc --version 2>&1 || true\");\n }\n if (md.includes(\"go \") || md.includes(\"golang\")) {\n checks.push(\"go version 2>&1 || true\");\n }\n\n // .env key masking — show KEY=***, never values\n checks.push(\"cat .env 2>/dev/null | sed 's/=.*/=***/' || true\");\n\n return checks.join(\" && \");\n}\n\n// ── Level 2: Assisted ───────────────────────────────────────────\n\nconst LOOP_COMMAND_CODE = `# Development Loop\n\nRun an assisted development cycle for the next feature.\n\n## Phase 1: SPEC\nReview docs/SPRINT.md.\nIf no sprint is defined, run /project:spec to interview the user.\nWait for user approval of the spec.\n\n## Phase 2: PLAN\nRead the approved spec in docs/SPRINT.md.\nPlan the implementation: files to change, tests to write, approach.\nWrite plan to docs/DECISIONS.md.\nWait for user approval of the plan.\n\n## Phase 3: IMPLEMENT\nFollow the plan. Implement the feature.\nRun tests after each change.\nCommit each logical unit: \"feat: description\"\n\n## Phase 4: VERIFY\nRun /project:prove to verify the implementation.\nIf confidence is LOW or MEDIUM, fix issues and re-verify.\n\n## Phase 5: REVIEW\nRun /project:grill for adversarial review.\nFix any BLOCKERs.\n\n## Phase 6: COMPLETION GATE\n\nBefore shipping, run the Completion Verification checklist:\n\n### Requirements Check\n- [ ] Re-read the ORIGINAL task description (not your interpretation)\n- [ ] Each explicit requirement is met with evidence (test output, diff)\n- [ ] Each implicit requirement (error handling, types, tests) is addressed\n\n### State Check\n- [ ] Test suite passes\n- [ ] Lint/typecheck passes\n- [ ] \\`git diff --stat\\` — every changed file is intentional\n- [ ] No debug artifacts (console.log, TODO, commented-out code, temp files)\n\n### Perspective Check (1 sentence each)\n- **Test engineer:** Most likely production failure mode?\n- **Code reviewer:** What would I flag in review?\n- **Requesting user:** Does this solve my actual problem?\n\nALL pass → proceed to ship. ANY fail → fix first, then re-verify.\n\n## Phase 7: SHIP\nRun /project:commit.\nReport what was built and what's next from docs/SPRINT.md.\n\nThen ask: \"Continue to next feature?\"\nIf yes, return to Phase 1.`;\n\nconst LOOP_COMMAND_RESEARCH = `# Research Loop\n\nRun an assisted research cycle.\n\n## Phase 1: QUESTION\nReview docs/SPRINT.md for the next research question.\nIf none, ask the user what to investigate.\n\n## Phase 2: RESEARCH\nSearch, extract, and analyze sources.\nLog findings to docs/SOURCES.md and docs/LEARNINGS.md.\n\n## Phase 3: SYNTHESIZE\nReview all findings. Write structured summary to docs/SUMMARY.md.\nCite all sources.\n\n## Phase 4: REVIEW\nPresent the summary. Ask the user for feedback.\nRevise based on feedback.\n\n## Phase 5: NEXT\nUpdate docs/SPRINT.md — mark question as done, identify follow-ups.\nAsk: \"Continue to next question?\"`;\n\nconst PM_AGENT = `---\nname: pm\ndescription: Project manager agent. Maintains roadmap, specs features, prioritizes work.\nmodel: opus\n---\n\nYou are a project manager for this codebase.\n\nYour responsibilities:\n1. Maintain docs/SPRINT.md — keep it prioritized and current\n2. Write specs to docs/SPRINT.md when asked\n3. Review completed work and suggest what's next\n4. Track decisions in docs/DECISIONS.md\n5. Track learnings in docs/LEARNINGS.md\n\nWhen invoked:\n- Read all docs/ files to understand current state\n- Read recent git log for what changed\n- Suggest the highest-priority next task\n- If asked to spec something, interview the user (5-8 questions)\n\nYou do NOT write code. You plan, spec, and prioritize.`;\n\n// ── Level 3: Autonomous ─────────────────────────────────────────\n\nconst AUTO_COMMAND = `# Autonomous Development\n\nPM-driven development loop with PR delivery.\n\n## Phase 1: PLAN (@pm)\nUse @pm to:\n- Read docs/SPRINT.md\n- Select the highest-priority unfinished task\n- Write a spec to docs/SPRINT.md\n- Present the spec for approval\n\nWait for user approval. If approved, proceed.\n\n## Phase 2: BRANCH\nCreate an isolated worktree:\n git worktree add ../project-feat-{name} -b feat/{name}\nAll implementation happens in the worktree.\n\n## Phase 3: IMPLEMENT\nIn the worktree directory:\n- Follow the spec in docs/SPRINT.md\n- Build, test, commit after each change\n\n## Phase 4: VERIFY\nRun verification:\n- Static analysis (linting, type checks)\n- Run functional tests\n- If NEEDS FIXES: fix and re-verify\n\n## Phase 5: COMPLETION GATE\n\nBefore creating a PR, run the Completion Verification checklist:\n- [ ] Re-read the ORIGINAL spec from docs/SPRINT.md\n- [ ] Each requirement is met with evidence (test output, diff)\n- [ ] Test suite + lint/typecheck pass\n- [ ] \\`git diff --stat\\` — every changed file is intentional, no debug artifacts\n- **Test engineer:** Most likely production failure mode?\n- **Code reviewer:** What would I flag in review?\n- **Requesting user:** Does this solve my actual problem?\n\nALL pass → proceed to PR. ANY fail → fix first, then re-verify.\n\nInclude the checklist results in the PR description.\n\n## Phase 6: PR\nCreate a pull request:\n gh pr create --title \"feat: {name}\" --body \"{spec + QA report + verification checklist}\"\n\n## Phase 7: NEXT\nReport:\n \"PR #{N} ready for review: {link}\n Next priority from SPRINT.md: {next task}\n Continue? (y/n)\"\n\nIf yes, return to Phase 1 with next task.`;\n\n// ── Level 4: Full Auto ──────────────────────────────────────────\n\nconst AUTOPILOT_COMMAND = `# Autopilot Mode\n\nContinuous autonomous development. The PM plans, the loop executes,\nPRs are opened automatically. You review when ready.\n\n## Configuration\n- Max features per session: 5 (prevent runaway)\n- Stop on: test failure, build error, or blocked dependency\n- All work in isolated worktrees\n- Every feature = one PR\n\n## The Loop\nRepeat until max features reached or stopped:\n1. @pm selects next priority from docs/SPRINT.md\n2. Create worktree + branch\n3. Implement the feature\n4. Run verification (build, test, lint)\n5. Run Completion Verification checklist:\n - Requirements met with evidence\n - Tests + lint/typecheck pass\n - No debug artifacts or unexpected file changes\n - 3-perspective check (test engineer, reviewer, user)\n6. Open PR via gh (include verification results in PR body)\n7. Report status\n8. Move to next feature\n\n## Stop Conditions\n- Max 5 features per autopilot session\n- Any BLOCKER from verification\n- Completion Verification checklist fails after 2 fix attempts\n- Build failure that can't be resolved in 3 attempts\n- User presses Escape`;\n\nconst AUTOPILOT_WARNING = `\n## Autopilot Mode Active\nThis environment is configured for autonomous operation.\nThe @pm agent plans features and /project:autopilot executes them.\nAll changes are delivered as PRs — review before merging.\nStop conditions: max 5 features, test failure, or Escape.`;\n\n// ── Main export ─────────────────────────────────────────────────\n\nfunction isResearchProject(spec: EnvironmentSpec): boolean {\n const commands = spec.harness.commands ?? {};\n return \"research\" in commands || \"summarize\" in commands;\n}\n\n/**\n * Apply autonomy-level-specific content to an EnvironmentSpec.\n * Mutates spec.harness by injecting commands, agents, hooks, and docs\n * appropriate for the selected autonomy level.\n */\nexport function applyAutonomyLevel(spec: EnvironmentSpec): void {\n const level = spec.autonomy_level ?? 1;\n const commands = spec.harness.commands ?? {};\n const agents = spec.harness.agents ?? {};\n const docs = spec.harness.docs ?? {};\n const settings = (spec.harness.settings ?? {}) as Record<string, unknown>;\n\n // All levels: persistence_routing setting\n if (!(\"persistence_routing\" in settings)) {\n settings.persistence_routing = level >= 3 ? \"auto\" : \"manual\";\n }\n\n // Level 1+: Tour, QUICKSTART, welcome hook\n if (level >= 1) {\n if (!(\"tour\" in commands)) {\n commands.tour = TOUR_COMMAND;\n }\n docs.QUICKSTART = buildQuickstart(spec);\n\n // Add SessionStart welcome hook\n const hooks = (settings.hooks ?? {}) as Record<string, unknown[]>;\n const sessionStart = (hooks.SessionStart ?? []) as unknown[];\n sessionStart.push(WELCOME_HOOK);\n hooks.SessionStart = sessionStart;\n settings.hooks = hooks;\n }\n\n // Level 2+: Bootstrap command, Loop, PM agent\n if (level >= 2) {\n if (!(\"bootstrap\" in commands)) {\n commands.bootstrap = BOOTSTRAP_COMMAND;\n }\n if (!(\"loop\" in commands)) {\n commands.loop = isResearchProject(spec)\n ? LOOP_COMMAND_RESEARCH\n : LOOP_COMMAND_CODE;\n }\n if (!(\"pm\" in agents)) {\n agents.pm = PM_AGENT;\n }\n }\n\n // Level 3+: Auto command + SessionStart bootstrap hook\n if (level >= 3) {\n if (!(\"auto\" in commands)) {\n commands.auto = AUTO_COMMAND;\n }\n\n // Add SessionStart bootstrap hook (automatic environment snapshot)\n const hooks = (settings.hooks ?? {}) as Record<string, unknown[]>;\n const sessionStart = (hooks.SessionStart ?? []) as unknown[];\n const bootstrapHook = {\n matcher: \"\",\n hooks: [{\n type: \"command\" as const,\n command: buildBootstrapHookCommand(spec),\n }],\n };\n sessionStart.push(bootstrapHook);\n hooks.SessionStart = sessionStart;\n settings.hooks = hooks;\n }\n\n // Level 4: Autopilot command + warning\n if (level >= 4) {\n if (!(\"autopilot\" in commands)) {\n commands.autopilot = AUTOPILOT_COMMAND;\n }\n // Append warning to CLAUDE.md\n if (spec.harness.claude_md && !spec.harness.claude_md.includes(\"Autopilot Mode\")) {\n spec.harness.claude_md += \"\\n\" + AUTOPILOT_WARNING;\n }\n }\n\n // Write back\n spec.harness.commands = commands;\n spec.harness.agents = agents;\n spec.harness.docs = docs;\n spec.harness.settings = settings;\n}\n\n/** Human-readable label for an autonomy level. */\nexport function autonomyLabel(level: AutonomyLevel): string {\n return AUTONOMY_LABELS[level];\n}\n","import fs from \"fs/promises\";\nimport path from \"path\";\nimport os from \"os\";\nimport type { EnvironmentSpec, RegistryTool } from \"../types.js\";\n\nasync function writeFile(filePath: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf-8\");\n}\n\nfunction toYaml(obj: unknown, indent: number = 0): string {\n const pad = \" \".repeat(indent);\n\n if (obj === null || obj === undefined) {\n return \"~\";\n }\n\n if (typeof obj === \"boolean\") {\n return obj ? \"true\" : \"false\";\n }\n\n if (typeof obj === \"number\") {\n return String(obj);\n }\n\n if (typeof obj === \"string\") {\n // Quote strings that contain special characters or look like other types\n const needsQuotes =\n obj === \"\" ||\n /[:#\\[\\]{}&*!|>'\"%@`,]/.test(obj) ||\n /^(true|false|null|~|\\d)/.test(obj) ||\n obj.includes(\"\\n\");\n return needsQuotes ? `\"${obj.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"` : obj;\n }\n\n if (Array.isArray(obj)) {\n if (obj.length === 0) {\n return \"[]\";\n }\n return obj\n .map((item) => `${pad}- ${toYaml(item, indent + 1).trimStart()}`)\n .join(\"\\n\");\n }\n\n if (typeof obj === \"object\") {\n const entries = Object.entries(obj as Record<string, unknown>);\n if (entries.length === 0) {\n return \"{}\";\n }\n return entries\n .map(([key, value]) => {\n const valueStr = toYaml(value, indent + 1);\n const isScalar =\n typeof value !== \"object\" || value === null || Array.isArray(value);\n if (isScalar && !Array.isArray(value)) {\n return `${pad}${key}: ${valueStr}`;\n }\n if (Array.isArray(value)) {\n if ((value as unknown[]).length === 0) {\n return `${pad}${key}: []`;\n }\n return `${pad}${key}:\\n${valueStr}`;\n }\n return `${pad}${key}:\\n${valueStr}`;\n })\n .join(\"\\n\");\n }\n\n return String(obj);\n}\n\nfunction buildMcpServersYaml(\n spec: EnvironmentSpec,\n registry: RegistryTool[]\n): string {\n const servers: Record<string, unknown> = {};\n\n // For each selected tool, check for hermes-specific mcp_server config first\n for (const selected of spec.tools) {\n const tool = registry.find((t) => t.id === selected.tool_id);\n if (!tool) continue;\n\n if (tool.install.hermes?.mcp_server) {\n const serverName = tool.id.replace(/_/g, \"-\");\n servers[serverName] = tool.install.hermes.mcp_server;\n } else if (tool.install.mcp_config) {\n // Fall back to converting the Claude Code mcp_config format\n for (const [serverName, serverConfig] of Object.entries(\n tool.install.mcp_config\n )) {\n servers[serverName] = serverConfig;\n }\n }\n }\n\n // Also include any mcp_config entries from the harness that weren't covered by tools\n for (const [serverName, serverConfig] of Object.entries(\n spec.harness.mcp_config || {}\n )) {\n if (!(serverName in servers)) {\n servers[serverName] = serverConfig;\n }\n }\n\n if (Object.keys(servers).length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n lines.push(`# Generated by Kairn v1.5.0`);\n lines.push(`# Environment: ${spec.name}`);\n lines.push(``);\n lines.push(`mcp_servers:`);\n\n for (const [serverName, serverConfig] of Object.entries(servers)) {\n lines.push(` ${serverName}:`);\n lines.push(toYaml(serverConfig, 2));\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport async function writeHermesEnvironment(\n spec: EnvironmentSpec,\n registry: RegistryTool[]\n): Promise<string[]> {\n const hermesDir = path.join(os.homedir(), \".hermes\");\n const written: string[] = [];\n\n // 1. config.yaml\n const configYaml = buildMcpServersYaml(spec, registry);\n if (configYaml) {\n const configPath = path.join(hermesDir, \"config.yaml\");\n await writeFile(configPath, configYaml);\n written.push(\".hermes/config.yaml\");\n }\n\n // 2. Skills from commands\n if (spec.harness.commands) {\n for (const [name, content] of Object.entries(spec.harness.commands)) {\n const skillPath = path.join(hermesDir, \"skills\", `${name}.md`);\n await writeFile(skillPath, content);\n written.push(`.hermes/skills/${name}.md`);\n }\n }\n\n // 3. Skills from skills\n if (spec.harness.skills) {\n for (const [name, content] of Object.entries(spec.harness.skills)) {\n const skillPath = path.join(hermesDir, \"skills\", `${name}.md`);\n await writeFile(skillPath, content);\n written.push(`.hermes/skills/${name}.md`);\n }\n }\n\n // 4. Skills from rules (prefixed with \"rule-\")\n if (spec.harness.rules) {\n for (const [name, content] of Object.entries(spec.harness.rules)) {\n const skillPath = path.join(hermesDir, \"skills\", `rule-${name}.md`);\n await writeFile(skillPath, content);\n written.push(`.hermes/skills/rule-${name}.md`);\n }\n }\n\n return written;\n}\n","import { password } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { ui } from \"./ui.js\";\nimport type { EnvSetupInfo } from \"./adapter/claude-code.js\";\n\nexport interface KeyCollectionResult {\n keysEntered: number;\n keysSkipped: number;\n envPath: string;\n}\n\n/**\n * Interactively prompt the user for API keys and write a .env file.\n * Skipped keys get empty placeholders. Also updates .gitignore.\n */\nexport async function collectAndWriteKeys(\n envSetup: EnvSetupInfo[],\n targetDir: string\n): Promise<KeyCollectionResult> {\n console.log(ui.section(\"API Keys\"));\n console.log(\n chalk.dim(\" Some tools need API keys. Enter them now or press Enter to skip.\\n\")\n );\n\n const envEntries: string[] = [\n \"# Generated by Kairn — API keys for MCP servers\",\n \"# Do NOT commit this file to git\",\n \"\",\n ];\n\n let keysEntered = 0;\n let keysSkipped = 0;\n const seen = new Set<string>();\n\n for (const env of envSetup) {\n if (seen.has(env.envVar)) continue;\n seen.add(env.envVar);\n\n console.log(chalk.bold(` ${env.envVar}`) + chalk.dim(` (${env.toolName})`));\n if (env.signupUrl) {\n console.log(chalk.dim(` Get one at: ${env.signupUrl}`));\n }\n\n const value = await password({\n message: env.envVar,\n mask: \"•\",\n });\n\n if (value && value.trim()) {\n envEntries.push(`${env.envVar}=${value.trim()}`);\n console.log(chalk.green(\" ✓ saved\\n\"));\n keysEntered++;\n } else {\n envEntries.push(`${env.envVar}=`);\n console.log(chalk.dim(\" (skipped)\\n\"));\n keysSkipped++;\n }\n }\n\n // Write .env file\n const envPath = path.join(targetDir, \".env\");\n await fs.writeFile(envPath, envEntries.join(\"\\n\") + \"\\n\", \"utf-8\");\n\n // Update .gitignore\n await ensureGitignoreEntry(targetDir, \".env\");\n\n console.log(chalk.green(` ✓ ${keysEntered} key(s) saved to .env (gitignored)`));\n if (keysSkipped > 0) {\n console.log(chalk.dim(\" Skipped keys can be added later: kairn keys\"));\n }\n\n return { keysEntered, keysSkipped, envPath };\n}\n\n/**\n * Write a .env file with empty placeholders for all keys (no prompts).\n * Used with --quick flag.\n */\nexport async function writeEmptyEnvFile(\n envSetup: EnvSetupInfo[],\n targetDir: string\n): Promise<void> {\n const envEntries: string[] = [\n \"# Generated by Kairn — API keys for MCP servers\",\n \"# Do NOT commit this file to git\",\n \"\",\n ];\n\n const seen = new Set<string>();\n for (const env of envSetup) {\n if (seen.has(env.envVar)) continue;\n seen.add(env.envVar);\n envEntries.push(`${env.envVar}=`);\n }\n\n const envPath = path.join(targetDir, \".env\");\n await fs.writeFile(envPath, envEntries.join(\"\\n\") + \"\\n\", \"utf-8\");\n await ensureGitignoreEntry(targetDir, \".env\");\n}\n\n/**\n * Ensure a line exists in .gitignore. Creates the file if needed.\n */\nasync function ensureGitignoreEntry(\n targetDir: string,\n entry: string\n): Promise<void> {\n const gitignorePath = path.join(targetDir, \".gitignore\");\n let gitignore = \"\";\n try {\n gitignore = await fs.readFile(gitignorePath, \"utf-8\");\n } catch {\n // File doesn't exist yet\n }\n if (!gitignore.split(\"\\n\").some((line) => line.trim() === entry)) {\n const separator = gitignore.length > 0 && !gitignore.endsWith(\"\\n\") ? \"\\n\" : \"\";\n await fs.writeFile(gitignorePath, gitignore + separator + entry + \"\\n\", \"utf-8\");\n }\n}\n\n/**\n * Parse an existing .env file and return key-value pairs.\n */\nexport async function readEnvFile(\n targetDir: string\n): Promise<Map<string, string>> {\n const envPath = path.join(targetDir, \".env\");\n const entries = new Map<string, string>();\n try {\n const content = await fs.readFile(envPath, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) continue;\n const key = trimmed.slice(0, eqIndex);\n const value = trimmed.slice(eqIndex + 1);\n entries.set(key, value);\n }\n } catch {\n // File doesn't exist\n }\n return entries;\n}\n\n/**\n * Parse .mcp.json to find which env vars are needed.\n */\nexport async function detectRequiredEnvVars(\n targetDir: string\n): Promise<string[]> {\n const mcpPath = path.join(targetDir, \".mcp.json\");\n const envVars = new Set<string>();\n try {\n const content = await fs.readFile(mcpPath, \"utf-8\");\n // Match ${ENV_VAR} patterns in the MCP config\n const matches = content.matchAll(/\\$\\{([A-Z_][A-Z0-9_]*)\\}/g);\n for (const match of matches) {\n envVars.add(match[1]);\n }\n } catch {\n // No .mcp.json\n }\n return [...envVars];\n}\n\n/**\n * Get unique env setup entries (deduplicated by envVar).\n */\nexport function dedupeEnvSetup(envSetup: EnvSetupInfo[]): EnvSetupInfo[] {\n const seen = new Set<string>();\n return envSetup.filter((e) => {\n if (seen.has(e.envVar)) return false;\n seen.add(e.envVar);\n return true;\n });\n}\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { getEnvsDir } from \"../config.js\";\nimport type { EnvironmentSpec } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nexport const listCommand = new Command(\"list\")\n .description(\"Show saved environments\")\n .action(async () => {\n printCompactBanner();\n\n const envsDir = getEnvsDir();\n\n let files: string[];\n try {\n files = await fs.readdir(envsDir);\n } catch {\n console.log(chalk.dim(\" No environments yet. Run \") +\n chalk.bold(\"kairn describe\") +\n chalk.dim(\" to create one.\\n\"));\n return;\n }\n\n const jsonFiles = files.filter((f) => f.endsWith(\".json\"));\n\n if (jsonFiles.length === 0) {\n console.log(chalk.dim(\" No environments yet. Run \") +\n chalk.bold(\"kairn describe\") +\n chalk.dim(\" to create one.\\n\"));\n return;\n }\n\n let first = true;\n for (const file of jsonFiles) {\n try {\n const data = await fs.readFile(path.join(envsDir, file), \"utf-8\");\n const spec = JSON.parse(data) as EnvironmentSpec;\n const date = new Date(spec.created_at).toLocaleDateString();\n const toolCount = spec.tools?.length ?? 0;\n\n if (!first) {\n console.log(ui.divider());\n }\n first = false;\n\n console.log(ui.kv(\"Name\", chalk.bold(spec.name)));\n console.log(ui.kv(\"Description\", spec.description));\n console.log(ui.kv(\"Date\", `${date} · ${toolCount} tools`));\n console.log(ui.kv(\"ID\", chalk.dim(spec.id)));\n console.log(\"\");\n } catch {\n // Skip malformed files\n }\n }\n });\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { getEnvsDir, getTemplatesDir } from \"../config.js\";\nimport { writeEnvironment } from \"../adapter/claude-code.js\";\nimport type { EnvironmentSpec } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nexport const activateCommand = new Command(\"activate\")\n .description(\"Re-deploy a saved environment to the current directory\")\n .argument(\"<env_id>\", \"Environment ID (from kairn list)\")\n .action(async (envId: string) => {\n printCompactBanner();\n\n const envsDir = getEnvsDir();\n const templatesDir = getTemplatesDir();\n\n // Find the env file — accept full ID or partial match\n let sourceDir: string;\n let match: string | undefined;\n let fromTemplate = false;\n\n // 1. Search envs dir\n let envFiles: string[] = [];\n try {\n envFiles = await fs.readdir(envsDir);\n } catch {\n // envs dir may not exist yet; continue to templates search\n }\n\n match = envFiles.find(\n (f) => f === `${envId}.json` || f.startsWith(envId)\n );\n\n if (match) {\n sourceDir = envsDir;\n } else {\n // 2. Fall back to templates dir\n let templateFiles: string[] = [];\n try {\n templateFiles = await fs.readdir(templatesDir);\n } catch {\n // templates dir may not exist\n }\n\n match = templateFiles.find(\n (f) => f === `${envId}.json` || f.startsWith(envId)\n );\n\n if (match) {\n sourceDir = templatesDir;\n fromTemplate = true;\n } else {\n console.log(ui.error(`Environment \"${envId}\" not found.`));\n console.log(chalk.dim(\" Run kairn list to see saved environments.\"));\n console.log(chalk.dim(\" Run kairn templates to see available templates.\\n\"));\n process.exit(1);\n }\n }\n\n const data = await fs.readFile(path.join(sourceDir, match), \"utf-8\");\n const spec = JSON.parse(data) as EnvironmentSpec;\n\n const label = fromTemplate ? chalk.dim(\" (template)\") : \"\";\n console.log(chalk.cyan(` Activating: ${spec.name}`) + label);\n console.log(chalk.dim(` ${spec.description}\\n`));\n\n const targetDir = process.cwd();\n const written = await writeEnvironment(spec, targetDir);\n\n console.log(ui.success(\"Environment written\\n\"));\n for (const file of written) {\n console.log(ui.file(file));\n }\n\n console.log(\"\\n\" + ui.success(`Ready! Run: $ claude`) + \"\\n\");\n });\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nconst REGISTRY_URL =\n \"https://raw.githubusercontent.com/ashtonperlroth/kairn/main/src/registry/tools.json\";\n\nasync function getLocalRegistryPath(): Promise<string> {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n const candidates = [\n path.resolve(__dirname, \"../registry/tools.json\"),\n path.resolve(__dirname, \"../src/registry/tools.json\"),\n path.resolve(__dirname, \"../../src/registry/tools.json\"),\n ];\n for (const candidate of candidates) {\n try {\n await fs.access(candidate);\n return candidate;\n } catch {\n continue;\n }\n }\n throw new Error(\"Could not find local tools.json registry\");\n}\n\nexport const updateRegistryCommand = new Command(\"update-registry\")\n .description(\"Fetch the latest tool registry from GitHub\")\n .option(\"--url <url>\", \"Custom registry URL\")\n .action(async (options: { url?: string }) => {\n printCompactBanner();\n\n const url = options.url || REGISTRY_URL;\n\n console.log(chalk.dim(` Fetching registry from ${url}...`));\n\n try {\n const response = await fetch(url);\n\n if (!response.ok) {\n console.log(\n ui.error(`Failed to fetch registry: ${response.status} ${response.statusText}`)\n );\n console.log(chalk.dim(\" The remote registry may not be available yet.\"));\n console.log(chalk.dim(\" Your local registry is still active.\\n\"));\n return;\n }\n\n const text = await response.text();\n\n // Validate it's valid JSON and has the expected structure\n let tools: unknown[];\n try {\n tools = JSON.parse(text);\n if (!Array.isArray(tools)) throw new Error(\"Not an array\");\n if (tools.length === 0) throw new Error(\"Empty registry\");\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(`Invalid registry format: ${msg}\\n`));\n return;\n }\n\n const registryPath = await getLocalRegistryPath();\n\n // Back up existing registry\n const backupPath = registryPath + \".bak\";\n try {\n await fs.copyFile(registryPath, backupPath);\n } catch {\n // No existing file to back up\n }\n\n await fs.writeFile(registryPath, JSON.stringify(tools, null, 2), \"utf-8\");\n\n console.log(ui.success(`Registry updated: ${tools.length} tools`));\n console.log(chalk.dim(` Saved to: ${registryPath}`));\n console.log(chalk.dim(` Backup: ${backupPath}\\n`));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(`Network error: ${msg}`));\n console.log(chalk.dim(\" Your local registry is still active.\\n\"));\n }\n });\n","import { Command } from \"commander\";\nimport { confirm } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { loadConfig } from \"../config.js\";\nimport { compile } from \"../compiler/compile.js\";\nimport {\n writeEnvironment,\n summarizeSpec,\n buildFileMap,\n} from \"../adapter/claude-code.js\";\nimport { writeHermesEnvironment } from \"../adapter/hermes-agent.js\";\nimport { loadRegistry } from \"../registry/loader.js\";\nimport { collectAndWriteKeys } from \"../secrets.js\";\nimport type { RuntimeTarget } from \"../types.js\";\nimport { scanProject } from \"../scanner/scan.js\";\nimport type { ProjectProfile } from \"../scanner/scan.js\";\nimport type { EnvironmentSpec } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\ninterface FileDiff {\n path: string;\n status: \"new\" | \"modified\" | \"unchanged\";\n diff: string;\n}\n\nfunction simpleDiff(oldContent: string, newContent: string): string[] {\n const oldLines = oldContent.split(\"\\n\");\n const newLines = newContent.split(\"\\n\");\n const output: string[] = [];\n\n const maxLines = Math.max(oldLines.length, newLines.length);\n for (let i = 0; i < maxLines; i++) {\n const oldLine = oldLines[i];\n const newLine = newLines[i];\n\n if (oldLine === undefined) {\n output.push(chalk.green(`+ ${newLine}`));\n } else if (newLine === undefined) {\n output.push(chalk.red(`- ${oldLine}`));\n } else if (oldLine !== newLine) {\n output.push(chalk.red(`- ${oldLine}`));\n output.push(chalk.green(`+ ${newLine}`));\n }\n }\n\n return output;\n}\n\nasync function generateDiff(\n spec: EnvironmentSpec,\n targetDir: string,\n options?: { hasEnvVars?: boolean }\n): Promise<FileDiff[]> {\n const fileMap = buildFileMap(spec, options);\n const results: FileDiff[] = [];\n\n for (const [relativePath, newContent] of fileMap) {\n const absolutePath = path.join(targetDir, relativePath);\n let oldContent: string | null = null;\n try {\n oldContent = await fs.readFile(absolutePath, \"utf-8\");\n } catch {\n // File does not exist yet\n }\n\n if (oldContent === null) {\n results.push({\n path: relativePath,\n status: \"new\",\n diff: chalk.green(\"+ NEW FILE\"),\n });\n } else if (oldContent === newContent) {\n results.push({\n path: relativePath,\n status: \"unchanged\",\n diff: \"\",\n });\n } else {\n const diffLines = simpleDiff(oldContent, newContent);\n results.push({\n path: relativePath,\n status: \"modified\",\n diff: diffLines.join(\"\\n\"),\n });\n }\n }\n\n return results;\n}\n\nfunction buildProfileSummary(profile: ProjectProfile): string {\n const lines: string[] = [];\n lines.push(`Project: ${profile.name}`);\n if (profile.description) lines.push(`Description: ${profile.description}`);\n if (profile.language) lines.push(`Language: ${profile.language}`);\n if (profile.framework) lines.push(`Framework: ${profile.framework}`);\n if (profile.dependencies.length > 0) {\n lines.push(`Dependencies: ${profile.dependencies.join(\", \")}`);\n }\n if (profile.testCommand) lines.push(`Test command: ${profile.testCommand}`);\n if (profile.buildCommand) lines.push(`Build command: ${profile.buildCommand}`);\n if (profile.lintCommand) lines.push(`Lint command: ${profile.lintCommand}`);\n if (profile.hasDocker) lines.push(\"Has Docker configuration\");\n if (profile.hasCi) lines.push(\"Has CI/CD (GitHub Actions)\");\n if (profile.envKeys.length > 0) {\n lines.push(`Env keys needed: ${profile.envKeys.join(\", \")}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction buildAuditSummary(profile: ProjectProfile): string {\n const lines: string[] = [];\n lines.push(`\\nExisting .claude/ harness found:`);\n lines.push(` CLAUDE.md: ${profile.claudeMdLineCount} lines${profile.claudeMdLineCount > 200 ? \" (⚠ over 200 — may degrade adherence)\" : \"\"}`);\n lines.push(` MCP servers: ${profile.mcpServerCount}`);\n lines.push(` Commands: ${profile.existingCommands.length > 0 ? profile.existingCommands.map(c => `/project:${c}`).join(\", \") : \"none\"}`);\n lines.push(` Rules: ${profile.existingRules.length > 0 ? profile.existingRules.join(\", \") : \"none\"}`);\n lines.push(` Skills: ${profile.existingSkills.length > 0 ? profile.existingSkills.join(\", \") : \"none\"}`);\n lines.push(` Agents: ${profile.existingAgents.length > 0 ? profile.existingAgents.join(\", \") : \"none\"}`);\n return lines.join(\"\\n\");\n}\n\nfunction buildOptimizeIntent(profile: ProjectProfile): string {\n const parts: string[] = [];\n\n parts.push(\"## Project Profile (scanned from actual codebase)\\n\");\n parts.push(buildProfileSummary(profile));\n\n if (profile.hasClaudeDir) {\n parts.push(buildAuditSummary(profile));\n\n if (profile.existingClaudeMd) {\n parts.push(`\\n## Existing CLAUDE.md Content\\n\\n${profile.existingClaudeMd}`);\n }\n\n parts.push(`\\n## Task\\n`);\n parts.push(\"Analyze this existing Claude Code environment and generate an OPTIMIZED version.\");\n parts.push(\"Preserve what works. Fix what's wrong. Add what's missing. Remove what's bloat.\");\n parts.push(\"Key optimizations to consider:\");\n parts.push(\"- Is CLAUDE.md under 100 lines? If not, move detail to rules/ or docs/\");\n parts.push(\"- Are the right MCP servers selected for these dependencies?\");\n parts.push(\"- Are there missing slash commands (help, tasks, plan, test, commit)?\");\n parts.push(\"- Are security rules present?\");\n parts.push(\"- Is there a continuity rule for session memory?\");\n parts.push(\"- Are there unnecessary MCP servers adding context bloat?\");\n parts.push(\"- Are hooks configured in settings.json for destructive command blocking?\");\n parts.push(\"- Are there path-scoped rules for different code domains (api, testing, frontend)?\");\n parts.push(\"- Does the project have a /project:status command with live git output?\");\n parts.push(\"- Is there a /project:fix command for issue-driven development?\");\n if (profile.claudeMdLineCount > 200) {\n parts.push(`- CLAUDE.md is ${profile.claudeMdLineCount} lines — needs aggressive trimming`);\n }\n if (!profile.existingCommands.includes(\"help\")) {\n parts.push(\"- Missing /project:help command\");\n }\n if (!profile.existingRules.includes(\"security\")) {\n parts.push(\"- Missing security rules\");\n }\n } else {\n parts.push(`\\n## Task\\n`);\n parts.push(\"Generate an optimal Claude Code environment for this existing project.\");\n parts.push(\"Use the scanned project profile — this is a real codebase, not a description.\");\n parts.push(\"The environment should match the actual tech stack, dependencies, and workflows.\");\n }\n\n return parts.join(\"\\n\");\n}\n\nexport const optimizeCommand = new Command(\"optimize\")\n .description(\"Scan an existing project and generate or optimize its Claude Code environment\")\n .option(\"-y, --yes\", \"Skip confirmation prompts\")\n .option(\"--audit-only\", \"Only audit the existing harness, don't generate changes\")\n .option(\"--diff\", \"Preview changes as a diff without writing\")\n .option(\"--runtime <runtime>\", \"Target runtime (claude-code or hermes)\", \"claude-code\")\n .action(async (options: { yes?: boolean; auditOnly?: boolean; diff?: boolean; runtime?: string }) => {\n printCompactBanner();\n\n const config = await loadConfig();\n if (!config) {\n console.log(ui.errorBox(\"KAIRN — Error\", \"No config found. Run kairn init first.\"));\n process.exit(1);\n }\n\n const targetDir = process.cwd();\n\n // 1. Scan\n console.log(ui.section(\"Project Scan\"));\n const scanSpinner = ora({ text: \"Scanning project...\", indent: 2 }).start();\n const profile = await scanProject(targetDir);\n scanSpinner.stop();\n\n // 2. Show profile\n if (profile.language) console.log(ui.kv(\"Language:\", profile.language));\n if (profile.framework) console.log(ui.kv(\"Framework:\", profile.framework));\n console.log(ui.kv(\"Dependencies:\", String(profile.dependencies.length)));\n if (profile.testCommand) console.log(ui.kv(\"Tests:\", profile.testCommand));\n if (profile.buildCommand) console.log(ui.kv(\"Build:\", profile.buildCommand));\n if (profile.hasDocker) console.log(ui.kv(\"Docker:\", \"yes\"));\n if (profile.hasCi) console.log(ui.kv(\"CI/CD:\", \"yes\"));\n if (profile.envKeys.length > 0) console.log(ui.kv(\"Env keys:\", profile.envKeys.join(\", \")));\n\n // 3. Audit existing harness\n if (profile.hasClaudeDir) {\n console.log(ui.section(\"Harness Audit\"));\n console.log(ui.kv(\"CLAUDE.md:\", `${profile.claudeMdLineCount} lines${profile.claudeMdLineCount > 200 ? \" ⚠ bloated\" : \" ✓\"}`));\n console.log(ui.kv(\"MCP servers:\", String(profile.mcpServerCount)));\n console.log(ui.kv(\"Commands:\", profile.existingCommands.length > 0 ? profile.existingCommands.join(\", \") : \"none\"));\n console.log(ui.kv(\"Rules:\", profile.existingRules.length > 0 ? profile.existingRules.join(\", \") : \"none\"));\n console.log(ui.kv(\"Skills:\", profile.existingSkills.length > 0 ? profile.existingSkills.join(\", \") : \"none\"));\n console.log(ui.kv(\"Agents:\", profile.existingAgents.length > 0 ? profile.existingAgents.join(\", \") : \"none\"));\n\n // Quick audit checks\n const issues: string[] = [];\n if (profile.claudeMdLineCount > 200) issues.push(\"CLAUDE.md over 200 lines — move detail to rules/ or docs/\");\n if (!profile.existingCommands.includes(\"help\")) issues.push(\"Missing /project:help command\");\n if (!profile.existingRules.includes(\"security\")) issues.push(\"Missing security rules\");\n if (!profile.existingRules.includes(\"continuity\")) issues.push(\"Missing continuity rule for session memory\");\n if (profile.mcpServerCount > 8) issues.push(`${profile.mcpServerCount} MCP servers — may cause context bloat`);\n if (profile.mcpServerCount === 0 && profile.dependencies.length > 0) issues.push(\"No MCP servers configured\");\n if (profile.hasTests && !profile.existingCommands.includes(\"test\")) issues.push(\"Has tests but no /project:test command\");\n if (!profile.existingCommands.includes(\"tasks\")) issues.push(\"Missing /project:tasks command\");\n if (!profile.existingSettings?.hooks) issues.push(\"No hooks configured — missing destructive command blocking\");\n const scopedRules = profile.existingRules.filter(r => r !== \"security\" && r !== \"continuity\");\n if (profile.hasSrc && scopedRules.length === 0) issues.push(\"No path-scoped rules — consider adding api.md, testing.md, or frontend.md rules\");\n\n if (issues.length > 0) {\n console.log(\"\");\n for (const issue of issues) {\n console.log(ui.warn(issue));\n }\n } else {\n console.log(ui.success(\"No obvious issues found\"));\n }\n\n if (options.auditOnly) {\n console.log(chalk.dim(\"\\n Audit complete. Run without --audit-only to generate optimized environment.\\n\"));\n return;\n }\n\n // Ask before overwriting\n if (!options.yes) {\n console.log(\"\");\n const proceed = await confirm({\n message: \"Generate optimized environment? This will overwrite existing .claude/ files.\",\n default: false,\n });\n if (!proceed) {\n console.log(chalk.dim(\"\\n Aborted.\\n\"));\n return;\n }\n }\n } else {\n console.log(chalk.dim(\"\\n No existing .claude/ directory found — generating from scratch.\\n\"));\n\n if (!options.yes) {\n const proceed = await confirm({\n message: \"Generate Claude Code environment for this project?\",\n default: true,\n });\n if (!proceed) {\n console.log(chalk.dim(\"\\n Aborted.\\n\"));\n return;\n }\n }\n }\n\n // 4. Compile with scanned profile\n const intent = buildOptimizeIntent(profile);\n let spec;\n const spinner = ora({ text: \"Compiling optimized environment...\", indent: 2 }).start();\n try {\n spec = await compile(intent, (progress) => {\n spinner.text = progress.message;\n });\n spinner.succeed(\"Environment compiled\");\n } catch (err) {\n spinner.fail(\"Compilation failed\");\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.errorBox(\"KAIRN — Error\", `Optimization failed: ${msg}`));\n process.exit(1);\n }\n\n // 5. Show results\n const registry = await loadRegistry();\n const summary = summarizeSpec(spec, registry);\n\n console.log(\"\");\n console.log(ui.kv(\"Name:\", spec.name));\n console.log(ui.kv(\"Tools:\", String(summary.toolCount)));\n console.log(ui.kv(\"Commands:\", String(summary.commandCount)));\n console.log(ui.kv(\"Rules:\", String(summary.ruleCount)));\n console.log(ui.kv(\"Skills:\", String(summary.skillCount)));\n console.log(ui.kv(\"Agents:\", String(summary.agentCount)));\n\n if (spec.tools.length > 0) {\n console.log(ui.section(\"Selected Tools\"));\n for (const tool of spec.tools) {\n const regTool = registry.find((t) => t.id === tool.tool_id);\n const name = regTool?.name || tool.tool_id;\n console.log(ui.tool(name, tool.reason));\n }\n }\n\n // 6. Diff preview or direct write\n const hasEnvVars = summary.envSetup.length > 0;\n\n if (options.diff) {\n const diffs = await generateDiff(spec, targetDir, { hasEnvVars });\n const changedDiffs = diffs.filter((d) => d.status !== \"unchanged\");\n\n if (changedDiffs.length === 0) {\n console.log(ui.success(\"No changes needed — environment is already up to date.\"));\n console.log(\"\");\n return;\n }\n\n console.log(ui.section(\"Changes Preview\"));\n for (const d of changedDiffs) {\n console.log(chalk.cyan(`\\n --- ${d.path}`));\n if (d.status === \"new\") {\n console.log(` ${d.diff}`);\n } else {\n for (const line of d.diff.split(\"\\n\")) {\n console.log(` ${line}`);\n }\n }\n }\n console.log(\"\");\n\n const apply = await confirm({\n message: \"Apply these changes?\",\n default: true,\n });\n if (!apply) {\n console.log(chalk.dim(\"\\n Aborted.\\n\"));\n return;\n }\n }\n\n const runtime = (options.runtime ?? \"claude-code\") as RuntimeTarget;\n\n if (runtime === \"hermes\") {\n await writeHermesEnvironment(spec, registry);\n console.log(ui.divider());\n console.log(ui.success(`Ready! Run: $ hermes`));\n console.log(\"\");\n } else {\n const written = await writeEnvironment(spec, targetDir, { hasEnvVars });\n\n console.log(ui.section(\"Files Written\"));\n for (const file of written) {\n console.log(ui.file(file));\n }\n\n // Interactive key collection after optimize\n if (hasEnvVars) {\n await collectAndWriteKeys(summary.envSetup, targetDir);\n console.log(\"\");\n }\n\n if (summary.pluginCommands.length > 0) {\n console.log(ui.section(\"Plugins\"));\n for (const cmd of summary.pluginCommands) {\n console.log(ui.cmd(cmd));\n }\n console.log(\"\");\n }\n\n console.log(ui.divider());\n console.log(ui.success(\"Ready! Run: $ claude\"));\n console.log(\"\");\n }\n });\n","import fs from \"fs/promises\";\nimport path from \"path\";\n\nexport interface ProjectProfile {\n // Core identity\n name: string;\n description: string;\n directory: string;\n\n // Language & framework\n language: string | null;\n framework: string | null;\n typescript: boolean;\n\n // Dependencies\n dependencies: string[];\n devDependencies: string[];\n\n // Scripts & commands\n scripts: Record<string, string>;\n hasTests: boolean;\n testCommand: string | null;\n buildCommand: string | null;\n lintCommand: string | null;\n\n // Project structure\n hasSrc: boolean;\n hasDocker: boolean;\n hasCi: boolean;\n hasEnvFile: boolean;\n envKeys: string[]; // from .env.example only — never read .env values\n\n // Existing harness\n hasClaudeDir: boolean;\n existingClaudeMd: string | null;\n existingSettings: Record<string, unknown> | null;\n existingMcpConfig: Record<string, unknown> | null;\n existingCommands: string[];\n existingRules: string[];\n existingSkills: string[];\n existingAgents: string[];\n mcpServerCount: number;\n claudeMdLineCount: number;\n\n // Key files found\n keyFiles: string[];\n}\n\nasync function fileExists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readJsonSafe(p: string): Promise<Record<string, unknown> | null> {\n try {\n const data = await fs.readFile(p, \"utf-8\");\n return JSON.parse(data);\n } catch {\n return null;\n }\n}\n\nasync function readFileSafe(p: string): Promise<string | null> {\n try {\n return await fs.readFile(p, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function listDirSafe(p: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(p);\n return entries.filter((e) => !e.startsWith(\".\"));\n } catch {\n return [];\n }\n}\n\nfunction detectFramework(deps: string[]): string | null {\n const frameworks: [string[], string][] = [\n [[\"next\"], \"Next.js\"],\n [[\"nuxt\"], \"Nuxt\"],\n [[\"@remix-run/node\", \"@remix-run/react\"], \"Remix\"],\n [[\"svelte\", \"@sveltejs/kit\"], \"SvelteKit\"],\n [[\"express\"], \"Express\"],\n [[\"fastify\"], \"Fastify\"],\n [[\"hono\"], \"Hono\"],\n [[\"react\", \"react-dom\"], \"React\"],\n [[\"vue\"], \"Vue\"],\n [[\"angular\"], \"Angular\"],\n [[\"django\"], \"Django\"],\n [[\"flask\"], \"Flask\"],\n [[\"fastapi\"], \"FastAPI\"],\n [[\"@supabase/supabase-js\"], \"Supabase\"],\n [[\"prisma\", \"@prisma/client\"], \"Prisma\"],\n [[\"drizzle-orm\"], \"Drizzle\"],\n [[\"tailwindcss\"], \"Tailwind CSS\"],\n ];\n\n const detected: string[] = [];\n for (const [packages, name] of frameworks) {\n if (packages.some((pkg) => deps.includes(pkg))) {\n detected.push(name);\n }\n }\n return detected.length > 0 ? detected.join(\" + \") : null;\n}\n\nfunction detectLanguage(dir: string, keyFiles: string[]): string | null {\n if (keyFiles.some((f) => f === \"tsconfig.json\")) return \"TypeScript\";\n if (keyFiles.some((f) => f === \"package.json\")) return \"JavaScript\";\n if (keyFiles.some((f) => f === \"pyproject.toml\" || f === \"setup.py\" || f === \"requirements.txt\")) return \"Python\";\n if (keyFiles.some((f) => f === \"Cargo.toml\")) return \"Rust\";\n if (keyFiles.some((f) => f === \"go.mod\")) return \"Go\";\n if (keyFiles.some((f) => f === \"Gemfile\")) return \"Ruby\";\n return null;\n}\n\nfunction extractEnvKeys(content: string): string[] {\n const keys: string[] = [];\n for (const line of content.split(\"\\n\")) {\n const match = line.match(/^([A-Z][A-Z0-9_]*)=/);\n if (match) keys.push(match[1]);\n }\n return keys;\n}\n\nexport async function scanProject(dir: string): Promise<ProjectProfile> {\n // Read package.json\n const pkg = await readJsonSafe(path.join(dir, \"package.json\")) as Record<string, unknown> | null;\n const deps = pkg?.dependencies ? Object.keys(pkg.dependencies as Record<string, string>) : [];\n const devDeps = pkg?.devDependencies ? Object.keys(pkg.devDependencies as Record<string, string>) : [];\n const allDeps = [...deps, ...devDeps];\n const scripts = (pkg?.scripts || {}) as Record<string, string>;\n\n // Detect key files\n const rootFiles = await listDirSafe(dir);\n const keyFiles = rootFiles.filter((f) =>\n [\n \"package.json\", \"tsconfig.json\", \"pyproject.toml\", \"setup.py\",\n \"requirements.txt\", \"Cargo.toml\", \"go.mod\", \"Gemfile\",\n \"docker-compose.yml\", \"Dockerfile\", \".env.example\", \".env\",\n \"README.md\", \"CLAUDE.md\",\n ].includes(f)\n );\n\n // Detect language & framework\n const language = detectLanguage(dir, keyFiles);\n const framework = detectFramework(allDeps);\n const typescript = keyFiles.includes(\"tsconfig.json\") || allDeps.includes(\"typescript\");\n\n // Test detection\n const testCommand = scripts.test && scripts.test !== 'echo \"Error: no test specified\" && exit 1'\n ? scripts.test : null;\n const hasTests = testCommand !== null ||\n await fileExists(path.join(dir, \"tests\")) ||\n await fileExists(path.join(dir, \"__tests__\")) ||\n await fileExists(path.join(dir, \"test\"));\n\n // Build & lint\n const buildCommand = scripts.build || null;\n const lintCommand = scripts.lint || null;\n\n // Structure\n const hasSrc = await fileExists(path.join(dir, \"src\"));\n const hasDocker = await fileExists(path.join(dir, \"docker-compose.yml\")) ||\n await fileExists(path.join(dir, \"Dockerfile\"));\n const hasCi = await fileExists(path.join(dir, \".github/workflows\"));\n\n // Env keys (from .env.example only — never read actual .env values)\n const hasEnvFile = await fileExists(path.join(dir, \".env\")) ||\n await fileExists(path.join(dir, \".env.example\"));\n let envKeys: string[] = [];\n const envExample = await readFileSafe(path.join(dir, \".env.example\"));\n if (envExample) {\n envKeys = extractEnvKeys(envExample);\n }\n\n // Existing .claude/ harness\n const claudeDir = path.join(dir, \".claude\");\n const hasClaudeDir = await fileExists(claudeDir);\n let existingClaudeMd: string | null = null;\n let existingSettings: Record<string, unknown> | null = null;\n let existingMcpConfig: Record<string, unknown> | null = null;\n let existingCommands: string[] = [];\n let existingRules: string[] = [];\n let existingSkills: string[] = [];\n let existingAgents: string[] = [];\n let mcpServerCount = 0;\n let claudeMdLineCount = 0;\n\n if (hasClaudeDir) {\n existingClaudeMd = await readFileSafe(path.join(claudeDir, \"CLAUDE.md\"));\n if (existingClaudeMd) {\n claudeMdLineCount = existingClaudeMd.split(\"\\n\").length;\n }\n\n existingSettings = await readJsonSafe(path.join(claudeDir, \"settings.json\"));\n existingMcpConfig = await readJsonSafe(path.join(dir, \".mcp.json\"));\n if (existingMcpConfig?.mcpServers) {\n mcpServerCount = Object.keys(existingMcpConfig.mcpServers as Record<string, unknown>).length;\n }\n\n existingCommands = (await listDirSafe(path.join(claudeDir, \"commands\")))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => f.replace(\".md\", \"\"));\n existingRules = (await listDirSafe(path.join(claudeDir, \"rules\")))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => f.replace(\".md\", \"\"));\n existingSkills = await listDirSafe(path.join(claudeDir, \"skills\"));\n existingAgents = (await listDirSafe(path.join(claudeDir, \"agents\")))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => f.replace(\".md\", \"\"));\n }\n\n // Project name & description\n const name = (pkg?.name as string) || path.basename(dir);\n const description = (pkg?.description as string) || \"\";\n\n return {\n name,\n description,\n directory: dir,\n language,\n framework,\n typescript,\n dependencies: deps,\n devDependencies: devDeps,\n scripts,\n hasTests,\n testCommand,\n buildCommand,\n lintCommand,\n hasSrc,\n hasDocker,\n hasCi,\n hasEnvFile,\n envKeys,\n hasClaudeDir,\n existingClaudeMd,\n existingSettings,\n existingMcpConfig,\n existingCommands,\n existingRules,\n existingSkills,\n existingAgents,\n mcpServerCount,\n claudeMdLineCount,\n keyFiles,\n };\n}\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { scanProject } from \"../scanner/scan.js\";\nimport type { ProjectProfile } from \"../scanner/scan.js\";\nimport { ui } from \"../ui.js\";\nimport { printFullBanner } from \"../logo.js\";\n\ninterface Check {\n name: string;\n weight: number; // 1-3\n status: \"pass\" | \"warn\" | \"fail\";\n message: string;\n}\n\nfunction runChecks(profile: ProjectProfile): Check[] {\n const checks: Check[] = [];\n\n // CLAUDE.md existence and size\n if (!profile.existingClaudeMd) {\n checks.push({\n name: \"CLAUDE.md\",\n weight: 3,\n status: \"fail\",\n message: \"Missing CLAUDE.md\",\n });\n } else if (profile.claudeMdLineCount > 200) {\n checks.push({\n name: \"CLAUDE.md\",\n weight: 2,\n status: \"warn\",\n message: `${profile.claudeMdLineCount} lines (recommended: ≤100)`,\n });\n } else {\n checks.push({\n name: \"CLAUDE.md\",\n weight: 3,\n status: \"pass\",\n message: `${profile.claudeMdLineCount} lines`,\n });\n }\n\n // Settings.json with deny rules\n if (!profile.existingSettings) {\n checks.push({\n name: \"settings.json\",\n weight: 2,\n status: \"fail\",\n message: \"Missing settings.json\",\n });\n } else {\n const perms = profile.existingSettings.permissions as\n | Record<string, unknown>\n | undefined;\n const hasDeny =\n perms?.deny &&\n Array.isArray(perms.deny) &&\n (perms.deny as string[]).length > 0;\n checks.push({\n name: \"Deny rules\",\n weight: 2,\n status: hasDeny ? \"pass\" : \"warn\",\n message: hasDeny\n ? \"Deny rules configured\"\n : \"No deny rules in settings.json\",\n });\n }\n\n // MCP server count\n if (profile.mcpServerCount > 8) {\n checks.push({\n name: \"MCP servers\",\n weight: 1,\n status: \"warn\",\n message: `${profile.mcpServerCount} servers (recommended: ≤8)`,\n });\n } else if (profile.mcpServerCount > 0) {\n checks.push({\n name: \"MCP servers\",\n weight: 1,\n status: \"pass\",\n message: `${profile.mcpServerCount} servers`,\n });\n } else {\n checks.push({\n name: \"MCP servers\",\n weight: 1,\n status: \"warn\",\n message: \"No MCP servers configured\",\n });\n }\n\n // /project:help command\n checks.push({\n name: \"/project:help\",\n weight: 2,\n status: profile.existingCommands.includes(\"help\") ? \"pass\" : \"fail\",\n message: profile.existingCommands.includes(\"help\")\n ? \"Help command present\"\n : \"Missing /project:help command\",\n });\n\n // /project:tasks command\n checks.push({\n name: \"/project:tasks\",\n weight: 1,\n status: profile.existingCommands.includes(\"tasks\") ? \"pass\" : \"warn\",\n message: profile.existingCommands.includes(\"tasks\")\n ? \"Tasks command present\"\n : \"Missing /project:tasks command\",\n });\n\n // Security rule\n checks.push({\n name: \"Security rule\",\n weight: 3,\n status: profile.existingRules.includes(\"security\") ? \"pass\" : \"fail\",\n message: profile.existingRules.includes(\"security\")\n ? \"Security rule present\"\n : \"Missing rules/security.md\",\n });\n\n // Continuity rule\n checks.push({\n name: \"Continuity rule\",\n weight: 2,\n status: profile.existingRules.includes(\"continuity\") ? \"pass\" : \"warn\",\n message: profile.existingRules.includes(\"continuity\")\n ? \"Continuity rule present\"\n : \"Missing rules/continuity.md\",\n });\n\n // Hooks\n const hasHooks = profile.existingSettings?.hooks;\n checks.push({\n name: \"Hooks\",\n weight: 1,\n status: hasHooks ? \"pass\" : \"warn\",\n message: hasHooks ? \"Hooks configured\" : \"No hooks in settings.json\",\n });\n\n // .env protection\n const perms = profile.existingSettings?.permissions as\n | Record<string, unknown>\n | undefined;\n const denyList = (perms?.deny as string[] | undefined) || [];\n const envProtected = denyList.some((d: string) => d.includes(\".env\"));\n checks.push({\n name: \".env protection\",\n weight: 2,\n status: envProtected ? \"pass\" : \"warn\",\n message: envProtected ? \".env in deny list\" : \".env not in deny list\",\n });\n\n // CLAUDE.md sections check (if exists)\n if (profile.existingClaudeMd) {\n const requiredSections = [\"## Purpose\", \"## Commands\", \"## Tech Stack\"];\n const missingSections = requiredSections.filter(\n (s) => !profile.existingClaudeMd!.includes(s)\n );\n if (missingSections.length > 0) {\n checks.push({\n name: \"CLAUDE.md sections\",\n weight: 1,\n status: \"warn\",\n message: `Missing: ${missingSections.join(\", \")}`,\n });\n } else {\n checks.push({\n name: \"CLAUDE.md sections\",\n weight: 1,\n status: \"pass\",\n message: \"Required sections present\",\n });\n }\n }\n\n return checks;\n}\n\nexport const doctorCommand = new Command(\"doctor\")\n .description(\n \"Validate the current Claude Code environment against best practices\"\n )\n .action(async () => {\n printFullBanner(\"Doctor\");\n\n const targetDir = process.cwd();\n\n console.log(chalk.dim(\" Checking .claude/ environment...\\n\"));\n\n const profile = await scanProject(targetDir);\n\n if (!profile.hasClaudeDir) {\n console.log(ui.error(\"No .claude/ directory found.\\n\"));\n console.log(\n chalk.dim(\" Run \") +\n chalk.bold(\"kairn describe\") +\n chalk.dim(\" or \") +\n chalk.bold(\"kairn optimize\") +\n chalk.dim(\" to generate one.\\n\")\n );\n process.exit(1);\n }\n\n const checks = runChecks(profile);\n\n console.log(ui.section(\"Health Check\"));\n console.log(\"\");\n\n // Display results\n for (const check of checks) {\n if (check.status === \"pass\") {\n console.log(ui.success(`${check.name}: ${check.message}`));\n } else if (check.status === \"warn\") {\n console.log(ui.warn(`${check.name}: ${check.message}`));\n } else {\n console.log(ui.error(`${check.name}: ${check.message}`));\n }\n }\n\n // Calculate score\n const maxScore = checks.reduce((sum, c) => sum + c.weight, 0);\n const score = checks.reduce((sum, c) => {\n if (c.status === \"pass\") return sum + c.weight;\n if (c.status === \"warn\") return sum + Math.floor(c.weight / 2);\n return sum;\n }, 0);\n\n const percentage = Math.round((score / maxScore) * 100);\n const scoreColor =\n percentage >= 80\n ? chalk.green\n : percentage >= 50\n ? chalk.yellow\n : chalk.red;\n\n console.log(\n `\\n Score: ${scoreColor(`${score}/${maxScore}`)} (${scoreColor(`${percentage}%`)})\\n`\n );\n\n if (percentage < 80) {\n console.log(\n chalk.dim(\" Run \") +\n chalk.bold(\"kairn optimize\") +\n chalk.dim(\" to fix issues.\\n\")\n );\n }\n });\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { input, select } from \"@inquirer/prompts\";\nimport { loadRegistry, loadUserRegistry, saveUserRegistry } from \"../registry/loader.js\";\nimport type { RegistryTool } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nconst listCommand = new Command(\"list\")\n .description(\"List tools in the registry\")\n .option(\"--category <cat>\", \"Filter by category\")\n .option(\"--user-only\", \"Show only user-defined tools\")\n .action(async (options: { category?: string; userOnly?: boolean }) => {\n printCompactBanner();\n\n let all: RegistryTool[];\n let userTools: RegistryTool[];\n\n try {\n [all, userTools] = await Promise.all([loadRegistry(), loadUserRegistry()]);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(`Failed to load registry: ${msg}\\n`));\n process.exit(1);\n }\n\n const userIds = new Set(userTools.map((t) => t.id));\n\n let tools = all;\n\n if (options.userOnly) {\n tools = tools.filter((t) => userIds.has(t.id));\n }\n\n if (options.category) {\n tools = tools.filter(\n (t) => t.category.toLowerCase() === options.category!.toLowerCase()\n );\n }\n\n if (tools.length === 0) {\n console.log(chalk.dim(\"\\n No tools found.\\n\"));\n return;\n }\n\n const bundledCount = all.filter((t) => !userIds.has(t.id)).length;\n const userCount = userIds.size;\n\n console.log(ui.section(\"Registry Tools\"));\n console.log(\"\");\n\n for (const tool of tools) {\n const isUser = userIds.has(tool.id);\n const meta = [\n tool.category,\n `tier ${tool.tier}`,\n tool.auth,\n ].join(\", \");\n\n console.log(` ${ui.accent(tool.id)}` + chalk.dim(` (${meta})`));\n console.log(chalk.dim(` ${tool.description}`));\n\n if (tool.best_for.length > 0) {\n console.log(chalk.dim(` Best for: ${tool.best_for.join(\", \")}`));\n }\n\n if (isUser) {\n console.log(chalk.yellow(\" [USER-DEFINED]\"));\n }\n\n console.log(\"\");\n }\n\n const totalShown = tools.length;\n const shownUser = tools.filter((t) => userIds.has(t.id)).length;\n const shownBundled = totalShown - shownUser;\n\n console.log(\n chalk.dim(\n ` ${totalShown} tool${totalShown !== 1 ? \"s\" : \"\"} (${shownBundled} bundled, ${shownUser} user-defined)`\n ) + \"\\n\"\n );\n });\n\nconst addCommand = new Command(\"add\")\n .description(\"Add a tool to the user registry\")\n .action(async () => {\n let id: string;\n try {\n id = await input({\n message: \"Tool ID (kebab-case)\",\n validate: (v) => {\n if (!v) return \"ID is required\";\n if (!/^[a-z][a-z0-9-]*$/.test(v)) return \"ID must be kebab-case (e.g. my-tool)\";\n return true;\n },\n });\n\n const name = await input({ message: \"Display name\" });\n const description = await input({ message: \"Description\" });\n\n const category = await select({\n message: \"Category\",\n choices: [\n { value: \"universal\" },\n { value: \"code\" },\n { value: \"search\" },\n { value: \"data\" },\n { value: \"communication\" },\n { value: \"design\" },\n { value: \"monitoring\" },\n { value: \"infrastructure\" },\n { value: \"sandbox\" },\n ],\n });\n\n const tier = await select<number>({\n message: \"Tier\",\n choices: [\n { name: \"1 — Universal\", value: 1 },\n { name: \"2 — Common\", value: 2 },\n { name: \"3 — Specialized\", value: 3 },\n ],\n });\n\n const type = await select<\"mcp_server\" | \"plugin\" | \"hook\">({\n message: \"Type\",\n choices: [\n { value: \"mcp_server\" },\n { value: \"plugin\" },\n { value: \"hook\" },\n ],\n });\n\n const auth = await select<\"none\" | \"api_key\" | \"oauth\" | \"connection_string\">({\n message: \"Auth\",\n choices: [\n { value: \"none\" },\n { value: \"api_key\" },\n { value: \"oauth\" },\n { value: \"connection_string\" },\n ],\n });\n\n const env_vars: { name: string; description: string }[] = [];\n if (auth === \"api_key\" || auth === \"connection_string\") {\n let addMore = true;\n while (addMore) {\n const varName = await input({ message: \"Env var name\" });\n const varDesc = await input({ message: \"Env var description\" });\n env_vars.push({ name: varName, description: varDesc });\n const another = await select<boolean>({\n message: \"Add another env var?\",\n choices: [\n { name: \"No\", value: false },\n { name: \"Yes\", value: true },\n ],\n });\n addMore = another;\n }\n }\n\n const signup_url_raw = await input({ message: \"Signup URL (optional, press enter to skip)\" });\n const signup_url = signup_url_raw.trim() || undefined;\n\n const best_for_raw = await input({ message: \"Best-for tags, comma-separated\" });\n const best_for = best_for_raw\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n const install: RegistryTool[\"install\"] = {};\n if (type === \"mcp_server\") {\n const command = await input({ message: \"MCP command\" });\n const args_raw = await input({ message: \"MCP args, comma-separated (leave blank for none)\" });\n const args = args_raw\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n install.mcp_config = { command, args };\n }\n\n const tool: RegistryTool = {\n id,\n name,\n description,\n category,\n tier,\n type,\n auth,\n best_for,\n install,\n ...(env_vars.length > 0 ? { env_vars } : {}),\n ...(signup_url ? { signup_url } : {}),\n };\n\n let userToolsList: RegistryTool[];\n try {\n userToolsList = await loadUserRegistry();\n } catch {\n userToolsList = [];\n }\n\n const existingIdx = userToolsList.findIndex((t) => t.id === id);\n if (existingIdx >= 0) {\n userToolsList[existingIdx] = tool;\n } else {\n userToolsList.push(tool);\n }\n\n await saveUserRegistry(userToolsList);\n\n console.log(ui.success(`Tool ${id} added to user registry\\n`));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(`Failed to add tool: ${msg}\\n`));\n process.exit(1);\n }\n });\n\nexport const registryCommand = new Command(\"registry\")\n .description(\"Manage the tool registry\")\n .addCommand(listCommand)\n .addCommand(addCommand);\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport { getTemplatesDir } from \"../config.js\";\nimport type { EnvironmentSpec } from \"../types.js\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\n\nexport const templatesCommand = new Command(\"templates\")\n .description(\"Browse available templates\")\n .option(\"--category <cat>\", \"filter templates by category keyword\")\n .option(\"--json\", \"output raw JSON array\")\n .action(async (options: { category?: string; json?: boolean }) => {\n printCompactBanner();\n\n const templatesDir = getTemplatesDir();\n\n let files: string[];\n try {\n files = await fs.readdir(templatesDir);\n } catch {\n console.log(\n chalk.dim(\n \" No templates found. Templates will be installed with \"\n ) +\n chalk.bold(\"kairn init\") +\n chalk.dim(\n \" or you can add .json files to ~/.kairn/templates/\\n\"\n )\n );\n return;\n }\n\n const jsonFiles = files.filter((f) => f.endsWith(\".json\"));\n\n if (jsonFiles.length === 0) {\n console.log(\n chalk.dim(\n \" No templates found. Templates will be installed with \"\n ) +\n chalk.bold(\"kairn init\") +\n chalk.dim(\n \" or you can add .json files to ~/.kairn/templates/\\n\"\n )\n );\n return;\n }\n\n const templates: EnvironmentSpec[] = [];\n\n for (const file of jsonFiles) {\n try {\n const data = await fs.readFile(\n path.join(templatesDir, file),\n \"utf-8\"\n );\n const spec = JSON.parse(data) as EnvironmentSpec;\n templates.push(spec);\n } catch {\n // Skip malformed files\n }\n }\n\n const filtered = options.category\n ? templates.filter((t) => {\n const keyword = options.category!.toLowerCase();\n return (\n t.intent?.toLowerCase().includes(keyword) ||\n t.description?.toLowerCase().includes(keyword)\n );\n })\n : templates;\n\n if (options.json) {\n console.log(JSON.stringify(filtered, null, 2));\n return;\n }\n\n if (filtered.length === 0) {\n console.log(\n chalk.dim(` No templates matched category \"${options.category}\".\\n`)\n );\n return;\n }\n\n console.log(ui.section(\"Templates\"));\n console.log(\"\");\n\n for (const spec of filtered) {\n const toolCount = spec.tools?.length ?? 0;\n const commandCount = Object.keys(spec.harness?.commands ?? {}).length;\n const ruleCount = Object.keys(spec.harness?.rules ?? {}).length;\n\n console.log(ui.kv(\"Name\", chalk.bold(spec.name)));\n console.log(ui.kv(\"ID\", chalk.dim(spec.id)));\n console.log(ui.kv(\"Description\", spec.description));\n console.log(\n ui.kv(\"Contents\", `${toolCount} tools · ${commandCount} commands · ${ruleCount} rules`)\n );\n console.log(\"\");\n }\n\n console.log(\n chalk.dim(` ${filtered.length} template${filtered.length === 1 ? \"\" : \"s\"} available\\n`)\n );\n });\n","import { Command } from \"commander\";\nimport { password } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport { ui } from \"../ui.js\";\nimport { printCompactBanner } from \"../logo.js\";\nimport {\n detectRequiredEnvVars,\n readEnvFile,\n collectAndWriteKeys,\n} from \"../secrets.js\";\nimport { loadRegistry } from \"../registry/loader.js\";\nimport type { EnvSetupInfo } from \"../adapter/claude-code.js\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\n\nexport const keysCommand = new Command(\"keys\")\n .description(\"Add or update API keys for the current environment\")\n .option(\"--show\", \"Show which keys are set vs missing\")\n .action(async (options: { show?: boolean }) => {\n printCompactBanner();\n\n const targetDir = process.cwd();\n\n // 1. Detect required env vars from .mcp.json\n const requiredVars = await detectRequiredEnvVars(targetDir);\n\n if (requiredVars.length === 0) {\n console.log(\n ui.info(\"No MCP servers found in .mcp.json — no API keys needed.\")\n );\n console.log(\"\");\n return;\n }\n\n // 2. Read existing .env\n const existing = await readEnvFile(targetDir);\n\n // 3. Build env setup info from registry for richer display\n const registry = await loadRegistry();\n const envSetupMap = new Map<string, EnvSetupInfo>();\n for (const tool of registry) {\n if (!tool.env_vars) continue;\n for (const ev of tool.env_vars) {\n if (requiredVars.includes(ev.name)) {\n envSetupMap.set(ev.name, {\n toolName: tool.name,\n envVar: ev.name,\n description: ev.description,\n signupUrl: tool.signup_url,\n });\n }\n }\n }\n\n // Fill in any vars not found in registry\n for (const varName of requiredVars) {\n if (!envSetupMap.has(varName)) {\n envSetupMap.set(varName, {\n toolName: \"unknown\",\n envVar: varName,\n description: \"Required by MCP server\",\n });\n }\n }\n\n // 4. --show mode: display status and exit\n if (options.show) {\n console.log(ui.section(\"API Key Status\"));\n console.log(\"\");\n\n for (const varName of requiredVars) {\n const value = existing.get(varName);\n const info = envSetupMap.get(varName);\n const toolLabel = info?.toolName !== \"unknown\" ? chalk.dim(` (${info?.toolName})`) : \"\";\n\n if (value && value.length > 0) {\n const masked = value.slice(0, 4) + \"•\".repeat(Math.max(0, value.length - 4));\n console.log(chalk.green(` ✓ ${varName}`) + toolLabel + chalk.dim(` = ${masked}`));\n } else {\n console.log(chalk.yellow(` ✗ ${varName}`) + toolLabel + chalk.dim(\" = (not set)\"));\n if (info?.signupUrl) {\n console.log(chalk.dim(` Get one at: ${info.signupUrl}`));\n }\n }\n }\n\n const setCount = requiredVars.filter((v) => {\n const val = existing.get(v);\n return val && val.length > 0;\n }).length;\n const missingCount = requiredVars.length - setCount;\n\n console.log(\"\");\n if (missingCount === 0) {\n console.log(ui.success(`All ${setCount} key(s) configured`));\n } else {\n console.log(\n ui.warn(`${missingCount} key(s) missing — run ${chalk.bold(\"kairn keys\")} to add them`)\n );\n }\n console.log(\"\");\n return;\n }\n\n // 5. Interactive mode: prompt for missing or empty keys\n const missing = requiredVars.filter((v) => {\n const val = existing.get(v);\n return !val || val.length === 0;\n });\n\n if (missing.length === 0) {\n console.log(ui.success(\"All API keys are already configured.\"));\n console.log(chalk.dim(\" Use --show to see current keys.\\n\"));\n return;\n }\n\n console.log(ui.section(\"API Keys\"));\n console.log(chalk.dim(` ${missing.length} key(s) need to be set. Press Enter to skip.\\n`));\n\n const envEntries = new Map(existing);\n let keysEntered = 0;\n\n for (const varName of missing) {\n const info = envSetupMap.get(varName);\n\n console.log(\n chalk.bold(` ${varName}`) +\n (info?.toolName !== \"unknown\" ? chalk.dim(` (${info?.toolName})`) : \"\")\n );\n if (info?.signupUrl) {\n console.log(chalk.dim(` Get one at: ${info.signupUrl}`));\n }\n\n const value = await password({\n message: varName,\n mask: \"•\",\n });\n\n if (value && value.trim()) {\n envEntries.set(varName, value.trim());\n console.log(chalk.green(\" ✓ saved\\n\"));\n keysEntered++;\n } else {\n console.log(chalk.dim(\" (skipped)\\n\"));\n }\n }\n\n // 6. Write updated .env\n const envLines: string[] = [\n \"# Generated by Kairn — API keys for MCP servers\",\n \"# Do NOT commit this file to git\",\n \"\",\n ];\n for (const [key, value] of envEntries) {\n envLines.push(`${key}=${value}`);\n }\n\n const envPath = path.join(targetDir, \".env\");\n await fs.writeFile(envPath, envLines.join(\"\\n\") + \"\\n\", \"utf-8\");\n\n console.log(chalk.green(` ✓ ${keysEntered} key(s) saved to .env`));\n console.log(\"\");\n });\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport { parse as yamlParse } from 'yaml';\nimport { confirm, input, select } from '@inquirer/prompts';\nimport { ui } from '../ui.js';\nimport { autoGenerateTasks, createEvolveWorkspace, writeTasksFile, buildProjectProfile } from '../evolve/init.js';\nimport { generateTasksFromTemplates, EVAL_TEMPLATES, selectTemplatesForWorkflow } from '../evolve/templates.js';\nimport { snapshotBaseline } from '../evolve/baseline.js';\nimport { runTask } from '../evolve/runner.js';\nimport { scoreTask } from '../evolve/scorers.js';\nimport { writeScore, loadIterationLog } from '../evolve/trace.js';\nimport { evolve } from '../evolve/loop.js';\nimport { generateMarkdownReport, generateJsonReport } from '../evolve/report.js';\nimport { generateDiff } from '../evolve/mutator.js';\nimport { applyEvolution } from '../evolve/apply.js';\nimport { loadConfig } from '../config.js';\nimport type { EvolveConfig, Task, TasksFile, TaskResult, LoopProgressEvent } from '../evolve/types.js';\n\nconst DEFAULT_CONFIG: EvolveConfig = {\n model: 'claude-sonnet-4-6',\n proposerModel: 'claude-sonnet-4-6',\n scorer: 'pass-fail',\n maxIterations: 5,\n parallelTasks: 1,\n runsPerTask: 1,\n maxMutationsPerIteration: 3,\n pruneThreshold: 95,\n maxTaskDrop: 20,\n usePrincipal: false,\n evalSampleSize: 0,\n samplingStrategy: 'thompson',\n klLambda: 0.1,\n pbtBranches: 3,\n};\n\n/**\n * Load EvolveConfig from a workspace's config.yaml.\n * Falls back to DEFAULT_CONFIG for any missing fields.\n */\nexport async function loadEvolveConfigFromWorkspace(workspacePath: string): Promise<EvolveConfig> {\n try {\n const configStr = await fs.readFile(path.join(workspacePath, 'config.yaml'), 'utf-8');\n const parsed = yamlParse(configStr) as Record<string, unknown>;\n return {\n model: (parsed.model as string) ?? DEFAULT_CONFIG.model,\n proposerModel: (parsed.proposer_model as string) ?? DEFAULT_CONFIG.proposerModel,\n scorer: (parsed.scorer as EvolveConfig['scorer']) ?? DEFAULT_CONFIG.scorer,\n maxIterations: (parsed.max_iterations as number) ?? DEFAULT_CONFIG.maxIterations,\n parallelTasks: (parsed.parallel_tasks as number) ?? DEFAULT_CONFIG.parallelTasks,\n runsPerTask: (parsed.runs_per_task as number) ?? DEFAULT_CONFIG.runsPerTask,\n maxMutationsPerIteration: (parsed.max_mutations_per_iteration as number) ?? DEFAULT_CONFIG.maxMutationsPerIteration,\n pruneThreshold: (parsed.prune_threshold as number) ?? DEFAULT_CONFIG.pruneThreshold,\n maxTaskDrop: (parsed.max_task_drop as number) ?? DEFAULT_CONFIG.maxTaskDrop,\n usePrincipal: (parsed.use_principal as boolean) ?? DEFAULT_CONFIG.usePrincipal,\n evalSampleSize: (parsed.eval_sample_size as number) ?? DEFAULT_CONFIG.evalSampleSize,\n samplingStrategy: (parsed.sampling_strategy as EvolveConfig['samplingStrategy']) ?? DEFAULT_CONFIG.samplingStrategy,\n klLambda: (parsed.kl_lambda as number) ?? DEFAULT_CONFIG.klLambda,\n pbtBranches: (parsed.pbt_branches as number) ?? DEFAULT_CONFIG.pbtBranches,\n };\n } catch {\n return { ...DEFAULT_CONFIG };\n }\n}\n\nexport const evolveCommand = new Command('evolve')\n .description('Evolve your agent environment through automated optimization');\n\n// --- kairn evolve init ---\nevolveCommand\n .command('init')\n .description('Initialize an evolution workspace with auto-generated tasks')\n .option('--workflow <type>', 'Workflow type for template selection', 'feature-development')\n .action(async (options: { workflow: string }) => {\n try {\n const projectRoot = process.cwd();\n\n console.log(ui.section('Evolve Init'));\n\n // Check for .claude/ directory\n const claudeDir = path.join(projectRoot, '.claude');\n try {\n await fs.access(claudeDir);\n } catch {\n console.log(ui.error('No .claude/ directory found. Run kairn describe first.'));\n process.exit(1);\n }\n\n // Create workspace\n const workspace = await createEvolveWorkspace(projectRoot, DEFAULT_CONFIG);\n console.log(ui.success('Created .kairn-evolve/ workspace'));\n\n // Auto-generate tasks via LLM\n const spinner = ora('Generating project-specific eval tasks...').start();\n let tasks: Task[];\n try {\n tasks = await autoGenerateTasks(projectRoot, options.workflow);\n spinner.succeed(`Generated ${tasks.length} eval tasks`);\n } catch {\n spinner.fail('LLM task generation failed');\n // Fallback to template-based placeholder tasks\n const templateIds = selectTemplatesForWorkflow(options.workflow);\n tasks = templateIds.map((templateId, index) => ({\n id: `${templateId}-${index + 1}`,\n template: templateId,\n description: `${EVAL_TEMPLATES[templateId].description} (project-specific task — edit in tasks.yaml)`,\n setup: 'npm install',\n expected_outcome: 'Task completed successfully',\n scoring: 'pass-fail' as const,\n timeout: 300,\n }));\n console.log(ui.info(`Fell back to ${tasks.length} template placeholders`));\n }\n\n // Display generated tasks\n for (const task of tasks) {\n console.log(chalk.cyan(` ${task.id}`) + chalk.dim(` (${task.template}) — ${task.description.slice(0, 80)}`));\n }\n\n // Interactive \"add another eval?\" loop\n let addMore = true;\n while (addMore) {\n try {\n addMore = await confirm({ message: 'Add another eval task?', default: false });\n } catch {\n addMore = false; // Handle non-interactive (piped) mode\n }\n if (addMore) {\n const templateId = await select({\n message: 'Select eval template:',\n choices: Object.values(EVAL_TEMPLATES).map(t => ({\n name: `${t.name} — ${t.description}`,\n value: t.id,\n })),\n });\n\n const addSpinner = ora('Generating task...').start();\n try {\n const config = await loadConfig();\n if (config) {\n let claudeMd = '';\n try { claudeMd = await fs.readFile(path.join(claudeDir, 'CLAUDE.md'), 'utf-8'); } catch { /* optional */ }\n const profile = await buildProjectProfile(projectRoot);\n const newTasks = await generateTasksFromTemplates(claudeMd, profile, [templateId], config);\n tasks.push(...newTasks);\n addSpinner.succeed(`Added ${newTasks.length} task(s)`);\n } else {\n addSpinner.fail('No config found');\n }\n } catch {\n addSpinner.fail('Failed to generate task');\n }\n }\n }\n\n // Write tasks file\n await writeTasksFile(workspace, tasks);\n console.log(ui.success(`Wrote ${tasks.length} tasks to tasks.yaml`));\n\n console.log('');\n console.log(chalk.dim(' Next steps:'));\n console.log(chalk.dim(' 1. Review .kairn-evolve/tasks.yaml'));\n console.log(chalk.dim(' 2. Run: kairn evolve baseline'));\n console.log(chalk.dim(' 3. Run: kairn evolve run'));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve baseline ---\nevolveCommand\n .command('baseline')\n .description('Snapshot current .claude/ directory as baseline')\n .action(async () => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n console.log(ui.section('Evolve Baseline'));\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n // Snapshot baseline\n await snapshotBaseline(projectRoot, workspace);\n\n // Count files copied\n const baselineDir = path.join(workspace, 'baseline');\n const fileCount = await countFiles(baselineDir);\n console.log(ui.success(`Baseline snapshot created (${fileCount} files)`));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve run ---\nevolveCommand\n .command('run')\n .description('Run tasks against the current harness')\n .option('--task <id>', 'Run a specific task by ID')\n .option('--iterations <n>', 'Number of evolution iterations', '5')\n .option('--runs <n>', 'Run each task N times for variance measurement', '1')\n .option('--parallel <n>', 'Run up to N tasks concurrently', '1')\n .option('--max-mutations <n>', 'Max mutations per iteration', '3')\n .option('--prune-threshold <n>', 'Skip tasks scoring above this on middle iterations', '95')\n .option('--max-task-drop <n>', 'Roll back if any task drops more than N points', '20')\n .option('--principal', 'Run Principal Proposer as final iteration')\n .option('--eval-sample <n>', 'Sample N tasks per middle iteration (0 = all)', '0')\n .option('--sampling <strategy>', 'Task sampling strategy: thompson or uniform', 'thompson')\n .option('--kl-lambda <n>', 'KL regularization strength (0 = disabled)', '0.1')\n .option('-i, --interactive', 'Configure evolution settings interactively')\n .action(async (options: { task?: string; iterations?: string; runs?: string; parallel?: string; maxMutations?: string; pruneThreshold?: string; maxTaskDrop?: string; principal?: boolean; evalSample?: string; sampling?: string; klLambda?: string; interactive?: boolean }) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n console.log(ui.section('Evolve Run'));\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n const tasksPath = path.join(workspace, 'tasks.yaml');\n let tasksContent: string;\n try {\n tasksContent = await fs.readFile(tasksPath, 'utf-8');\n } catch {\n console.log(ui.error('No tasks.yaml found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n const parsed = yamlParse(tasksContent) as TasksFile;\n if (!parsed?.tasks || parsed.tasks.length === 0) {\n console.log(ui.error('No tasks found in tasks.yaml'));\n process.exit(1);\n }\n\n if (options.task) {\n const tasksToRun = parsed.tasks.filter(t => t.id === options.task);\n\n if (tasksToRun.length === 0) {\n console.log(ui.error(`Task \"${options.task}\" not found in tasks.yaml`));\n process.exit(1);\n }\n\n console.log(ui.info(`Running ${tasksToRun.length} task(s)...`));\n console.log('');\n\n const config = await loadConfig();\n const harnessPath = path.join(projectRoot, '.claude');\n const results: TaskResult[] = [];\n\n for (const task of tasksToRun) {\n const traceDir = path.join(workspace, 'traces', '0', task.id);\n const spinner = ora(`Running: ${task.id}`).start();\n\n const result = await runTask(task, harnessPath, traceDir, 0);\n\n // Score the result\n if (config) {\n const stdout = await fs.readFile(path.join(traceDir, 'stdout.log'), 'utf-8').catch(() => '');\n const stderr = await fs.readFile(path.join(traceDir, 'stderr.log'), 'utf-8').catch(() => '');\n const score = await scoreTask(task, traceDir, stdout, stderr, config);\n result.score = score;\n await writeScore(traceDir, score);\n }\n\n results.push(result);\n\n const status = result.score.pass ? chalk.green('PASS') : chalk.red('FAIL');\n const scoreStr = result.score.score !== undefined ? chalk.dim(` (${result.score.score}%)`) : '';\n spinner.stop();\n console.log(` ${status} ${task.id}${scoreStr}${result.score.details ? chalk.dim(` — ${result.score.details}`) : ''}`);\n }\n\n // Summary\n const passed = results.filter(r => r.score.pass).length;\n console.log('');\n console.log(ui.info(`Results: ${passed}/${results.length} passed`));\n console.log(ui.info('Traces written to .kairn-evolve/traces/0/'));\n } else {\n const kairnConfig = await loadConfig();\n if (!kairnConfig) {\n console.log(ui.error('No config found. Run kairn init first.'));\n process.exit(1);\n }\n\n const evolveConfig = await loadEvolveConfigFromWorkspace(workspace);\n\n // Show interactive menu by default unless flags were explicitly passed\n const hasExplicitFlags = options.iterations !== '5' || options.runs !== '1' ||\n options.parallel !== '1' || options.maxMutations !== '3' ||\n options.pruneThreshold !== '95' || options.maxTaskDrop !== '20' ||\n options.principal || options.evalSample !== '0' ||\n options.sampling !== 'thompson' || options.klLambda !== '0.1';\n\n if (!hasExplicitFlags) {\n // Interactive configuration menu\n console.log(chalk.dim(' Configure evolution settings:\\n'));\n\n const preset = await select({\n message: 'Evolution preset',\n choices: [\n { name: 'Quick (3 iterations, 1 run, no extras)', value: 'quick' },\n { name: 'Standard (5 iterations, 1 run, parallel)', value: 'standard' },\n { name: 'Rigorous (5 iterations, 3 runs, parallel, principal)', value: 'rigorous' },\n { name: 'Custom (configure each setting)', value: 'custom' },\n ],\n });\n\n if (preset === 'quick') {\n evolveConfig.maxIterations = 3;\n evolveConfig.runsPerTask = 1;\n evolveConfig.parallelTasks = 3;\n } else if (preset === 'standard') {\n evolveConfig.maxIterations = 5;\n evolveConfig.runsPerTask = 1;\n evolveConfig.parallelTasks = 5;\n } else if (preset === 'rigorous') {\n evolveConfig.maxIterations = 5;\n evolveConfig.runsPerTask = 3;\n evolveConfig.parallelTasks = 5;\n evolveConfig.usePrincipal = true;\n } else {\n evolveConfig.maxIterations = parseInt(\n await input({ message: 'Iterations', default: '5' }), 10) || 5;\n evolveConfig.runsPerTask = parseInt(\n await input({ message: 'Runs per task (variance)', default: '1' }), 10) || 1;\n evolveConfig.parallelTasks = parseInt(\n await input({ message: 'Parallel tasks', default: '3' }), 10) || 3;\n evolveConfig.maxMutationsPerIteration = parseInt(\n await input({ message: 'Max mutations per iteration', default: '3' }), 10) || 3;\n evolveConfig.pruneThreshold = parseInt(\n await input({ message: 'Prune threshold (%)', default: '95' }), 10) || 95;\n evolveConfig.maxTaskDrop = parseInt(\n await input({ message: 'Max task drop (rollback guard)', default: '20' }), 10) || 20;\n evolveConfig.usePrincipal = await confirm({\n message: 'Run Principal Proposer at end?', default: false,\n });\n evolveConfig.evalSampleSize = parseInt(\n await input({ message: 'Eval sample size (0 = all)', default: '0' }), 10) || 0;\n }\n\n console.log('');\n console.log(chalk.dim(` Iterations: ${evolveConfig.maxIterations}, Runs: ${evolveConfig.runsPerTask}, Parallel: ${evolveConfig.parallelTasks}`));\n console.log(chalk.dim(` Mutations: ${evolveConfig.maxMutationsPerIteration}, Prune: ${evolveConfig.pruneThreshold}%, Guard: ${evolveConfig.maxTaskDrop}pt`));\n if (evolveConfig.usePrincipal) console.log(chalk.dim(' Principal Proposer: enabled'));\n if (evolveConfig.evalSampleSize > 0) console.log(chalk.dim(` Eval sampling: ${evolveConfig.evalSampleSize} tasks/iter (${evolveConfig.samplingStrategy})`));\n if (evolveConfig.klLambda > 0) console.log(chalk.dim(` KL regularization: λ=${evolveConfig.klLambda}`));\n console.log('');\n } else {\n // Flag-based configuration\n const iterations = parseInt(options.iterations ?? '5', 10);\n if (isNaN(iterations) || iterations < 1) {\n console.log(ui.error('--iterations must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.maxIterations = iterations;\n\n const runs = parseInt(options.runs ?? '1', 10);\n if (isNaN(runs) || runs < 1) {\n console.log(ui.error('--runs must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.runsPerTask = runs;\n\n const parallel = parseInt(options.parallel ?? '1', 10);\n if (isNaN(parallel) || parallel < 1) {\n console.log(ui.error('--parallel must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.parallelTasks = parallel;\n\n const maxMutations = parseInt(options.maxMutations ?? '3', 10);\n if (isNaN(maxMutations) || maxMutations < 1) {\n console.log(ui.error('--max-mutations must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.maxMutationsPerIteration = maxMutations;\n\n const pruneThreshold = parseInt(options.pruneThreshold ?? '95', 10);\n if (isNaN(pruneThreshold) || pruneThreshold < 0 || pruneThreshold > 100) {\n console.log(ui.error('--prune-threshold must be 0-100'));\n process.exit(1);\n }\n evolveConfig.pruneThreshold = pruneThreshold;\n\n const maxTaskDrop = parseInt(options.maxTaskDrop ?? '20', 10);\n if (isNaN(maxTaskDrop) || maxTaskDrop < 1) {\n console.log(ui.error('--max-task-drop must be a positive integer'));\n process.exit(1);\n }\n evolveConfig.maxTaskDrop = maxTaskDrop;\n\n if (options.principal) {\n evolveConfig.usePrincipal = true;\n }\n\n const evalSample = parseInt(options.evalSample ?? '0', 10);\n if (isNaN(evalSample) || evalSample < 0) {\n console.log(ui.error('--eval-sample must be a non-negative integer'));\n process.exit(1);\n }\n evolveConfig.evalSampleSize = evalSample;\n\n const sampling = options.sampling ?? 'thompson';\n if (sampling !== 'thompson' && sampling !== 'uniform') {\n console.log(ui.error('--sampling must be \"thompson\" or \"uniform\"'));\n process.exit(1);\n }\n evolveConfig.samplingStrategy = sampling;\n\n const klLambda = parseFloat(options.klLambda ?? '0.1');\n if (isNaN(klLambda) || klLambda < 0) {\n console.log(ui.error('--kl-lambda must be a non-negative number'));\n process.exit(1);\n }\n evolveConfig.klLambda = klLambda;\n }\n\n // Verify baseline exists\n try {\n await fs.access(path.join(workspace, 'iterations', '0', 'harness'));\n } catch {\n console.log(ui.error('No baseline harness found. Run kairn evolve baseline first.'));\n process.exit(1);\n }\n\n const result = await evolve(workspace, parsed.tasks, kairnConfig, evolveConfig, (event: LoopProgressEvent) => {\n switch (event.type) {\n case 'iteration-start':\n console.log(ui.section(`Iteration ${event.iteration}`));\n break;\n case 'iteration-scored': {\n const scoreColor = event.score !== undefined && event.score >= 100\n ? chalk.green\n : event.score !== undefined && event.score >= 60\n ? chalk.yellow\n : chalk.red;\n console.log(` Score: ${scoreColor((event.score?.toFixed(1) ?? '0') + '%')}`);\n break;\n }\n case 'rollback':\n console.log(chalk.yellow(` Warning: ${event.message ?? 'Regression detected'}`));\n break;\n case 'proposing':\n console.log(chalk.dim(' Proposer analyzing traces...'));\n break;\n case 'mutations-applied':\n console.log(chalk.dim(` Applied ${event.mutationCount ?? 0} mutation(s)`));\n break;\n case 'perfect-score':\n console.log(chalk.green(' Perfect score. Stopping.'));\n break;\n case 'proposer-error':\n console.log(chalk.yellow(` Warning: ${event.message ?? 'Proposer failed'}`));\n break;\n case 'task-start':\n console.log(chalk.dim(` Running: ${event.taskId ?? 'unknown'}...`));\n break;\n case 'task-run':\n console.log(chalk.dim(` ${event.message ?? ''}`));\n break;\n case 'task-skipped':\n console.log(chalk.dim(` SKIP ${event.taskId ?? 'unknown'} (above prune threshold last iteration)`));\n break;\n case 'task-regression':\n console.log(chalk.yellow(` DROP ${event.taskId ?? 'unknown'} ${event.message ?? ''}`));\n break;\n case 'task-scored': {\n const taskScore = event.score ?? 0;\n const taskStatus = taskScore >= 100 ? chalk.green('PASS') : taskScore >= 60 ? chalk.yellow('PARTIAL') : chalk.red('FAIL');\n console.log(` ${taskStatus} ${event.taskId ?? 'unknown'} ${chalk.dim(`(${taskScore.toFixed(0)}%)`)}`);\n break;\n }\n case 'complete':\n break; // Summary printed below\n }\n });\n\n // Print summary\n console.log(ui.section('Evolution Summary'));\n console.log(` Iterations: ${result.iterations.length}`);\n console.log(` Baseline: ${result.baselineScore.toFixed(1)}%`);\n console.log(` Best: ${chalk.green(result.bestScore.toFixed(1) + '%')} (iteration ${result.bestIteration})`);\n const improvement = result.bestScore - result.baselineScore;\n if (improvement > 0) {\n console.log(` Improvement: ${chalk.green('+' + improvement.toFixed(1) + ' points')}`);\n } else {\n console.log(` Improvement: ${improvement.toFixed(1)} points`);\n }\n console.log('');\n\n // Iteration table\n const showVariance = evolveConfig.runsPerTask > 1;\n console.log(showVariance\n ? ' Iter Score Mutations Status'\n : ' Iter Score Mutations Status');\n for (const iter of result.iterations) {\n // Compute average stddev across tasks for this iteration\n let scoreDisplay: string;\n if (showVariance) {\n const taskScores = Object.values(iter.taskResults);\n const stddevs = taskScores\n .map(s => s.variance?.stddev)\n .filter((v): v is number => v !== undefined);\n const avgStddev = stddevs.length > 0\n ? stddevs.reduce((a, b) => a + b, 0) / stddevs.length\n : 0;\n scoreDisplay = `${iter.score.toFixed(1).padStart(6)}% ±${avgStddev.toFixed(1)}`;\n } else {\n scoreDisplay = iter.score.toFixed(1).padStart(6) + '%';\n }\n const mutations = iter.proposal?.mutations.length ?? 0;\n const mutStr = mutations > 0 ? mutations.toString() : '-';\n let status = 'evaluated';\n if (iter.iteration === 0) status = 'baseline';\n else if (!iter.proposal && !iter.diffPatch) status = 'rollback';\n else if (iter.score >= 100) status = 'perfect';\n else if (iter.iteration === result.bestIteration) status = 'best';\n console.log(` ${iter.iteration.toString().padStart(4)} ${scoreDisplay} ${mutStr.padStart(9)} ${status}`);\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve pbt ---\nevolveCommand\n .command('pbt')\n .description('Run Population-Based Training with parallel evolution branches')\n .option('--branches <n>', 'Number of parallel branches', '3')\n .option('--iterations <n>', 'Iterations per branch', '5')\n .option('--parallel <n>', 'Tasks per branch concurrently', '2')\n .option('--sampling <strategy>', 'Task sampling strategy: thompson or uniform', 'thompson')\n .option('--kl-lambda <n>', 'KL regularization strength (0 = disabled)', '0.1')\n .option('--eval-sample <n>', 'Sample N tasks per middle iteration (0 = all)', '5')\n .action(async (options: { branches?: string; iterations?: string; parallel?: string; sampling?: string; klLambda?: string; evalSample?: string }) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n console.log(ui.section('Evolve PBT'));\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n // Verify baseline exists\n try {\n await fs.access(path.join(workspace, 'iterations', '0', 'harness'));\n } catch {\n console.log(ui.error('No baseline harness found. Run kairn evolve baseline first.'));\n process.exit(1);\n }\n\n const kairnConfig = await loadConfig();\n if (!kairnConfig) {\n console.log(ui.error('No config found. Run kairn init first.'));\n process.exit(1);\n }\n\n const evolveConfig = await loadEvolveConfigFromWorkspace(workspace);\n\n // Parse options\n const numBranches = parseInt(options.branches ?? '3', 10);\n evolveConfig.maxIterations = parseInt(options.iterations ?? '5', 10);\n evolveConfig.parallelTasks = parseInt(options.parallel ?? '2', 10);\n evolveConfig.evalSampleSize = parseInt(options.evalSample ?? '5', 10);\n evolveConfig.klLambda = parseFloat(options.klLambda ?? '0.1');\n const sampling = options.sampling ?? 'thompson';\n if (sampling === 'thompson' || sampling === 'uniform') {\n evolveConfig.samplingStrategy = sampling;\n }\n\n // Load tasks\n const tasksPath = path.join(workspace, 'tasks.yaml');\n const tasksContent = await fs.readFile(tasksPath, 'utf-8');\n const parsed = yamlParse(tasksContent) as TasksFile;\n if (!parsed?.tasks || parsed.tasks.length === 0) {\n console.log(ui.error('No tasks found in tasks.yaml'));\n process.exit(1);\n }\n\n console.log(chalk.dim(` Branches: ${numBranches}, Iterations: ${evolveConfig.maxIterations}, Parallel: ${evolveConfig.parallelTasks}`));\n console.log(chalk.dim(` Sampling: ${evolveConfig.samplingStrategy}, KL Lambda: ${evolveConfig.klLambda}`));\n console.log('');\n\n const { runPopulation } = await import('../evolve/population.js');\n\n const result = await runPopulation(\n workspace,\n parsed.tasks,\n kairnConfig,\n evolveConfig,\n numBranches,\n (event) => {\n const branchPrefix = event.branchId !== undefined ? chalk.dim(`[branch ${event.branchId}] `) : '';\n switch (event.type) {\n case 'iteration-start':\n console.log(`${branchPrefix}${ui.section(`Iteration ${event.iteration}`)}`);\n break;\n case 'iteration-scored': {\n const scoreColor = event.score !== undefined && event.score >= 100\n ? chalk.green\n : event.score !== undefined && event.score >= 60\n ? chalk.yellow\n : chalk.red;\n console.log(`${branchPrefix} Score: ${scoreColor((event.score?.toFixed(1) ?? '0') + '%')}`);\n break;\n }\n case 'complete':\n break;\n default:\n if (event.message) {\n console.log(`${branchPrefix} ${chalk.dim(event.message)}`);\n }\n break;\n }\n },\n );\n\n // Print PBT summary\n console.log(ui.section('PBT Results'));\n for (const branch of result.branches) {\n const marker = branch.branchId === result.bestBranch ? chalk.green(' <- BEST') : '';\n console.log(` Branch ${branch.branchId}: ${branch.result.bestScore.toFixed(1)}% (${branch.result.iterations.length} iterations)${marker}`);\n }\n if (result.synthesizedResult) {\n const synthMarker = result.synthesizedResult.bestScore > result.bestScore ? chalk.green(' <- BEST') : '';\n console.log(` ${'─'.repeat(40)}`);\n console.log(` Meta-Principal: ${result.synthesizedResult.bestScore.toFixed(1)}%${synthMarker}`);\n }\n console.log('');\n console.log(ui.success(`Best: Branch ${result.bestBranch} with ${result.bestScore.toFixed(1)}%`));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve apply ---\nevolveCommand\n .command('apply')\n .description('Apply the best evolved harness to your project')\n .option('--iter <n>', 'Apply a specific iteration instead of the best')\n .option('--pbt', 'Apply best PBT result (branch winner or synthesis)')\n .option('--force', 'Apply even if git working tree is dirty')\n .option('--no-commit', 'Skip automatic git commit after applying')\n .action(async (options: { iter?: string; pbt?: boolean; force?: boolean; commit?: boolean }) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n console.log(ui.section('Evolve Apply'));\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n // Parse --iter option\n let targetIteration: number | undefined;\n if (options.iter) {\n targetIteration = parseInt(options.iter, 10);\n if (isNaN(targetIteration)) {\n console.log(ui.error('--iter must be a number'));\n process.exit(1);\n }\n }\n\n const result = await applyEvolution(workspace, projectRoot, targetIteration, options.pbt);\n\n // Show diff preview\n if (result.diffPreview) {\n console.log(ui.section('Changes'));\n for (const line of result.diffPreview.split('\\n')) {\n if (line.startsWith('---') || line.startsWith('+++')) {\n console.log(chalk.bold(line));\n } else if (line.startsWith('+')) {\n console.log(chalk.green(line));\n } else if (line.startsWith('-')) {\n console.log(chalk.red(line));\n } else {\n console.log(line);\n }\n }\n }\n\n console.log('');\n console.log(ui.success(\n `Applied iteration ${result.iteration} harness (${result.filesChanged.length} files)`,\n ));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve report ---\nevolveCommand\n .command('report')\n .description('Generate a summary report of the evolution run')\n .option('--json', 'Output machine-readable JSON instead of Markdown')\n .action(async (options: { json?: boolean }) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n // Verify workspace exists\n try {\n await fs.access(workspace);\n } catch {\n console.log(ui.error('No .kairn-evolve/ directory found. Run kairn evolve init first.'));\n process.exit(1);\n }\n\n if (options.json) {\n const report = await generateJsonReport(workspace);\n console.log(JSON.stringify(report, null, 2));\n } else {\n const markdown = await generateMarkdownReport(workspace);\n console.log(markdown);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n// --- kairn evolve diff ---\nevolveCommand\n .command('diff <iter1> <iter2>')\n .description('Show harness changes between two iterations')\n .action(async (iter1Str: string, iter2Str: string) => {\n try {\n const projectRoot = process.cwd();\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n const iter1 = parseInt(iter1Str, 10);\n const iter2 = parseInt(iter2Str, 10);\n\n if (isNaN(iter1) || isNaN(iter2)) {\n console.log(ui.error('Both arguments must be integers (iteration numbers)'));\n process.exit(1);\n }\n\n // Verify both iteration harness directories exist\n const harness1 = path.join(workspace, 'iterations', iter1.toString(), 'harness');\n const harness2 = path.join(workspace, 'iterations', iter2.toString(), 'harness');\n\n try {\n await fs.access(harness1);\n } catch {\n console.log(ui.error(`Iteration ${iter1} harness not found at ${harness1}`));\n process.exit(1);\n }\n try {\n await fs.access(harness2);\n } catch {\n console.log(ui.error(`Iteration ${iter2} harness not found at ${harness2}`));\n process.exit(1);\n }\n\n console.log(ui.section(`Diff: Iteration ${iter1} → ${iter2}`));\n\n // Generate and display colored diff\n const diffPatch = await generateDiff(harness1, harness2);\n\n if (!diffPatch) {\n console.log(chalk.dim(' No harness changes between these iterations.'));\n } else {\n for (const line of diffPatch.split('\\n')) {\n if (line.startsWith('---') || line.startsWith('+++')) {\n console.log(chalk.bold(line));\n } else if (line.startsWith('+')) {\n console.log(chalk.green(line));\n } else if (line.startsWith('-')) {\n console.log(chalk.red(line));\n } else {\n console.log(line);\n }\n }\n }\n\n // Per-task score comparison\n const [log1, log2] = await Promise.all([\n loadIterationLog(workspace, iter1),\n loadIterationLog(workspace, iter2),\n ]);\n\n if (log1 && log2) {\n console.log('');\n console.log(ui.section('Score Comparison'));\n console.log('');\n console.log(' Task Iter ' + iter1 + ' Iter ' + iter2 + ' Delta');\n\n const allTaskIds = new Set([\n ...Object.keys(log1.taskResults),\n ...Object.keys(log2.taskResults),\n ]);\n\n for (const taskId of [...allTaskIds].sort()) {\n const s1 = log1.taskResults[taskId];\n const s2 = log2.taskResults[taskId];\n const score1 = s1 ? (s1.score ?? (s1.pass ? 100 : 0)) : 0;\n const score2 = s2 ? (s2.score ?? (s2.pass ? 100 : 0)) : 0;\n const delta = score2 - score1;\n const deltaStr = delta > 0\n ? chalk.green(`+${delta.toFixed(0)}`)\n : delta < 0\n ? chalk.red(delta.toFixed(0).toString())\n : chalk.dim('0');\n const name = taskId.padEnd(30);\n console.log(` ${name} ${score1.toFixed(0).padStart(5)}% ${score2.toFixed(0).padStart(5)}% ${deltaStr}`);\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(ui.error(msg));\n process.exit(1);\n }\n });\n\n/**\n * Count files recursively in a directory.\n */\nasync function countFiles(dir: string): Promise<number> {\n let count = 0;\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory()) {\n count += await countFiles(path.join(dir, entry.name));\n } else {\n count++;\n }\n }\n } catch {\n // Directory doesn't exist\n }\n return count;\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { stringify as yamlStringify } from 'yaml';\nimport { loadConfig } from '../config.js';\nimport { selectTemplatesForWorkflow, generateTasksFromTemplates } from './templates.js';\nimport type { EvolveConfig, Task, ProjectProfileSummary } from './types.js';\n\n/**\n * Creates the .kairn-evolve/ directory structure and writes config.yaml.\n * Returns the path to the workspace.\n */\nexport async function createEvolveWorkspace(\n projectRoot: string,\n config: EvolveConfig,\n): Promise<string> {\n const workspace = path.join(projectRoot, '.kairn-evolve');\n\n // Create directories\n await fs.mkdir(path.join(workspace, 'baseline'), { recursive: true });\n await fs.mkdir(path.join(workspace, 'traces'), { recursive: true });\n await fs.mkdir(path.join(workspace, 'iterations'), { recursive: true });\n\n // Write config.yaml using proper YAML serialization\n const configObj = {\n model: config.model,\n proposer_model: config.proposerModel,\n scorer: config.scorer,\n max_iterations: config.maxIterations,\n parallel_tasks: config.parallelTasks,\n };\n await fs.writeFile(\n path.join(workspace, 'config.yaml'),\n yamlStringify(configObj),\n 'utf-8',\n );\n\n return workspace;\n}\n\n/**\n * Writes tasks.yaml to the workspace using proper YAML serialization.\n *\n * Each task is serialized with all required fields. The rubric key\n * is only included when the task has rubric criteria defined.\n */\nexport async function writeTasksFile(\n workspacePath: string,\n tasks: Task[],\n): Promise<void> {\n const doc = {\n tasks: tasks.map((t) => ({\n id: t.id,\n template: t.template,\n description: t.description,\n setup: t.setup,\n expected_outcome: t.expected_outcome,\n scoring: t.scoring,\n ...(t.rubric ? { rubric: t.rubric } : {}),\n timeout: t.timeout,\n })),\n };\n\n const header =\n '# .kairn-evolve/tasks.yaml\\n# Auto-generated by kairn evolve init — edit freely\\n';\n await fs.writeFile(\n path.join(workspacePath, 'tasks.yaml'),\n header + yamlStringify(doc),\n 'utf-8',\n );\n}\n\n/**\n * Build a lightweight project profile by scanning key files in the project root.\n *\n * Reads package.json for Node.js projects, checks for pyproject.toml or\n * requirements.txt for Python projects, and scans for common configuration files.\n */\nexport async function buildProjectProfile(\n projectRoot: string,\n): Promise<ProjectProfileSummary> {\n const profile: ProjectProfileSummary = {\n language: null,\n framework: null,\n scripts: {},\n keyFiles: [],\n };\n\n // Try to read package.json for Node.js projects\n try {\n const pkgStr = await fs.readFile(\n path.join(projectRoot, 'package.json'),\n 'utf-8',\n );\n const pkg = JSON.parse(pkgStr) as Record<string, unknown>;\n profile.language = 'typescript';\n\n if (pkg.scripts && typeof pkg.scripts === 'object') {\n profile.scripts = pkg.scripts as Record<string, string>;\n }\n\n // Detect framework from dependencies\n const deps: Record<string, string> = {\n ...((pkg.dependencies as Record<string, string>) ?? {}),\n ...((pkg.devDependencies as Record<string, string>) ?? {}),\n };\n\n if (deps.next) {\n profile.framework = 'Next.js';\n } else if (deps.express) {\n profile.framework = 'Express';\n } else if (deps.react) {\n profile.framework = 'React';\n } else if (deps.vue) {\n profile.framework = 'Vue';\n } else if (deps.commander) {\n profile.framework = 'CLI (Commander.js)';\n }\n } catch {\n // Not a Node.js project\n }\n\n // Try pyproject.toml / requirements.txt for Python\n if (!profile.language) {\n try {\n await fs.access(path.join(projectRoot, 'pyproject.toml'));\n profile.language = 'python';\n } catch {\n try {\n await fs.access(path.join(projectRoot, 'requirements.txt'));\n profile.language = 'python';\n } catch {\n // Not Python either\n }\n }\n }\n\n // Scan for key files\n try {\n const entries = await fs.readdir(projectRoot);\n const keyPatterns = [\n 'README.md',\n 'package.json',\n 'tsconfig.json',\n 'pyproject.toml',\n 'Cargo.toml',\n 'go.mod',\n 'Makefile',\n 'Dockerfile',\n ];\n profile.keyFiles = entries.filter((e) => keyPatterns.includes(e));\n } catch {\n // Ignore\n }\n\n return profile;\n}\n\n/**\n * Auto-generate project-specific eval tasks using the LLM.\n *\n * Reads the project's CLAUDE.md (if present), builds a project profile\n * by scanning key files, selects eval templates for the given workflow\n * type, then calls the LLM to generate concrete tasks.\n *\n * @param projectRoot - Path to the project root directory\n * @param workflowType - The type of workflow (e.g., \"feature-development\", \"maintenance\")\n * @returns Array of generated Task objects\n */\nexport async function autoGenerateTasks(\n projectRoot: string,\n workflowType: string,\n): Promise<Task[]> {\n const config = await loadConfig();\n if (!config) {\n throw new Error('No config found. Run `kairn init` first.');\n }\n\n // Read CLAUDE.md\n let claudeMd = '';\n try {\n claudeMd = await fs.readFile(\n path.join(projectRoot, '.claude', 'CLAUDE.md'),\n 'utf-8',\n );\n } catch {\n // CLAUDE.md is optional but recommended\n }\n\n // Build project profile by scanning key files\n const profile = await buildProjectProfile(projectRoot);\n\n // Select templates for workflow type\n const templates = selectTemplatesForWorkflow(workflowType);\n\n // Generate tasks via LLM\n return generateTasksFromTemplates(claudeMd, profile, templates, config);\n}\n","import { callLLM } from '../llm.js';\nimport type { KairnConfig } from '../types.js';\nimport type { EvalTemplate, ProjectProfileSummary, Task } from './types.js';\n\ninterface TemplateMetadata {\n id: EvalTemplate;\n name: string;\n description: string;\n bestFor: string[];\n}\n\nexport const EVAL_TEMPLATES: Record<EvalTemplate, TemplateMetadata> = {\n 'add-feature': {\n id: 'add-feature',\n name: 'Add Feature',\n description: 'Can the agent add a new capability?',\n bestFor: ['feature-development', 'api-building', 'full-stack'],\n },\n 'fix-bug': {\n id: 'fix-bug',\n name: 'Fix Bug',\n description: 'Can the agent diagnose and fix a problem?',\n bestFor: ['maintenance', 'debugging', 'qa'],\n },\n 'refactor': {\n id: 'refactor',\n name: 'Refactor',\n description: 'Can the agent restructure code?',\n bestFor: ['maintenance', 'architecture', 'backend'],\n },\n 'test-writing': {\n id: 'test-writing',\n name: 'Test Writing',\n description: 'Can the agent write tests?',\n bestFor: ['tdd', 'qa', 'backend'],\n },\n 'config-change': {\n id: 'config-change',\n name: 'Config Change',\n description: 'Can the agent update configuration?',\n bestFor: ['devops', 'infrastructure', 'backend'],\n },\n 'documentation': {\n id: 'documentation',\n name: 'Documentation',\n description: 'Can the agent write and update docs?',\n bestFor: ['content', 'api-building', 'full-stack'],\n },\n 'convention-adherence': {\n id: 'convention-adherence',\n name: 'Convention Adherence',\n description: 'Does the agent follow all project conventions defined in CLAUDE.md?',\n bestFor: ['feature-development', 'full-stack', 'backend', 'maintenance'],\n },\n 'workflow-compliance': {\n id: 'workflow-compliance',\n name: 'Workflow Compliance',\n description: 'Does the agent use the project workflow commands and skills?',\n bestFor: ['feature-development', 'full-stack', 'tdd', 'qa'],\n },\n 'rule-compliance': {\n id: 'rule-compliance',\n name: 'Rule Compliance',\n description: 'Does the agent follow all project rules without violations?',\n bestFor: ['feature-development', 'backend', 'maintenance', 'architecture'],\n },\n 'intent-routing': {\n id: 'intent-routing',\n name: 'Intent Routing',\n description: 'Test that natural language prompts route to the correct workflow command via intent hooks',\n bestFor: ['feature-development', 'full-stack', 'api-building'],\n },\n 'persistence-completion': {\n id: 'persistence-completion',\n name: 'Persistence Completion',\n description: 'Can the agent complete a multi-criterion task using the persistence loop?',\n bestFor: ['feature-development', 'full-stack', 'api-building', 'maintenance'],\n },\n};\n\n/**\n * Select eval templates appropriate for a given workflow type.\n *\n * Returns a curated subset of eval templates that best match the\n * project's workflow. Falls back to a general-purpose set if the\n * workflow type is not recognized.\n */\nexport function selectTemplatesForWorkflow(workflowType: string): EvalTemplate[] {\n const mapping: Record<string, EvalTemplate[]> = {\n 'feature-development': ['add-feature', 'test-writing', 'convention-adherence', 'workflow-compliance', 'intent-routing', 'persistence-completion'],\n 'api-building': ['add-feature', 'fix-bug', 'test-writing', 'convention-adherence', 'persistence-completion'],\n 'full-stack': ['add-feature', 'fix-bug', 'test-writing', 'convention-adherence', 'persistence-completion'],\n 'maintenance': ['fix-bug', 'refactor', 'test-writing', 'rule-compliance', 'persistence-completion'],\n 'debugging': ['fix-bug', 'test-writing', 'rule-compliance'],\n 'qa': ['fix-bug', 'test-writing', 'add-feature', 'workflow-compliance'],\n 'architecture': ['refactor', 'test-writing', 'config-change', 'convention-adherence'],\n 'backend': ['fix-bug', 'refactor', 'config-change', 'rule-compliance'],\n 'devops': ['config-change', 'fix-bug', 'rule-compliance'],\n 'infrastructure': ['config-change', 'refactor', 'convention-adherence'],\n 'tdd': ['test-writing', 'add-feature', 'fix-bug', 'workflow-compliance'],\n 'content': ['documentation', 'add-feature', 'convention-adherence'],\n 'research': ['documentation', 'add-feature', 'convention-adherence'],\n };\n return mapping[workflowType] || ['add-feature', 'fix-bug', 'test-writing', 'convention-adherence'];\n}\n\n/**\n * System prompt instructing the LLM to generate project-specific eval tasks\n * from eval templates and project context.\n */\nexport const TASK_GENERATION_PROMPT = `You are an eval task generator for Claude Code agent environments. Given a project's CLAUDE.md, project structure, and selected eval templates, generate concrete, project-specific tasks.\n\nEach task must be realistic and testable against the actual project. Avoid generic placeholders.\n\nIMPORTANT: For harness-aware templates (convention-adherence, workflow-compliance, rule-compliance), generate tasks where success DEPENDS on the agent reading and following the .claude/ harness content:\n- convention-adherence: Task must require following specific conventions from CLAUDE.md (naming, file structure, patterns). Judge by whether output matches the conventions.\n- workflow-compliance: Task must require using project slash commands or workflow steps defined in .claude/commands/. Judge by whether the agent followed the defined workflow.\n- rule-compliance: Task must create a scenario where .claude/rules/ content is relevant. Judge by whether the agent respected all rules.\n- persistence-completion: Task MUST have 3+ acceptance criteria that require sequential implementation. The task description should be a realistic feature request — the agent must parse it into criteria. Judge by: (a) all criteria met (progress.json status: complete), (b) structured tracking used (progress.json exists with 3+ criteria), (c) tests pass, (d) review gate executed (progress.json review field present).\n\nThese harness-aware tasks are critical — they test whether the .claude/ environment actually improves agent behavior.\n\nReturn a JSON object with a \"tasks\" array. Each task has:\n- id: kebab-case identifier (e.g., \"add-health-endpoint\")\n- template: which eval template this instantiates\n- description: concrete task description the agent will receive\n- setup: shell commands to prepare the workspace (e.g., \"npm install\")\n- expected_outcome: multi-line string describing what success looks like\n- scoring: \"pass-fail\", \"llm-judge\", or \"rubric\"\n- timeout: seconds (300 for features/bugs, 600 for refactors, 180 for config/docs/tests)\n\nReturn ONLY valid JSON, no markdown fences.`;\n\n/**\n * Parse a raw LLM response string into a JSON object.\n *\n * Strips markdown code fences if present, then extracts the first\n * top-level JSON object (`{...}`) or array (`[...]`) from the text.\n */\nfunction parseJsonResponse(raw: string): unknown {\n let cleaned = raw.trim();\n\n // Strip markdown code fences\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n\n // Extract first JSON object or array\n const jsonMatch = cleaned.match(/\\{[\\s\\S]*\\}/) ?? cleaned.match(/\\[[\\s\\S]*\\]/);\n if (!jsonMatch) {\n throw new Error(\n \"LLM response did not contain valid JSON. Try again or use a different model.\",\n );\n }\n\n try {\n return JSON.parse(jsonMatch[0]);\n } catch (err) {\n throw new Error(\n `Failed to parse LLM response as JSON: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nconst REQUIRED_TASK_FIELDS: ReadonlyArray<keyof Task> = [\n \"id\",\n \"template\",\n \"description\",\n \"setup\",\n \"expected_outcome\",\n \"scoring\",\n \"timeout\",\n];\n\n/**\n * Validate that a parsed object has all required Task fields.\n */\nfunction validateTask(obj: unknown, index: number): Task {\n if (typeof obj !== \"object\" || obj === null) {\n throw new Error(`Task at index ${index} is not an object`);\n }\n const record = obj as Record<string, unknown>;\n\n for (const field of REQUIRED_TASK_FIELDS) {\n if (!(field in record) || record[field] === undefined || record[field] === null) {\n throw new Error(`Task at index ${index} is missing required field: ${field}`);\n }\n }\n\n return record as unknown as Task;\n}\n\n/**\n * Build the user message for LLM task generation.\n */\nfunction buildTaskGenerationMessage(\n claudeMd: string,\n projectProfile: ProjectProfileSummary,\n templates: EvalTemplate[],\n): string {\n const profileLines = [\n `Language: ${projectProfile.language ?? \"unknown\"}`,\n `Framework: ${projectProfile.framework ?? \"none\"}`,\n `Scripts: ${Object.entries(projectProfile.scripts).map(([k, v]) => `${k}=${v}`).join(\", \") || \"none\"}`,\n `Key files: ${projectProfile.keyFiles.join(\", \") || \"none\"}`,\n ];\n\n const templateDescriptions = templates\n .map((t) => {\n const meta = EVAL_TEMPLATES[t];\n return `- ${t}: ${meta.description}`;\n })\n .join(\"\\n\");\n\n return [\n \"## CLAUDE.md\",\n \"\",\n claudeMd,\n \"\",\n \"## Project Profile\",\n \"\",\n ...profileLines,\n \"\",\n \"## Selected Eval Templates\",\n \"\",\n templateDescriptions,\n \"\",\n \"Generate concrete, project-specific tasks for each template above.\",\n ].join(\"\\n\");\n}\n\n/**\n * Use the LLM to generate project-specific eval tasks from eval templates.\n *\n * Sends the project's CLAUDE.md, profile summary, and selected templates\n * to the LLM, then parses and validates the returned task definitions.\n *\n * @param claudeMd - Contents of the project's CLAUDE.md\n * @param projectProfile - Lightweight project info (language, framework, etc.)\n * @param templates - Which eval templates to instantiate\n * @param config - Kairn configuration with provider, API key, and model\n * @returns Validated array of Task objects\n */\nexport async function generateTasksFromTemplates(\n claudeMd: string,\n projectProfile: ProjectProfileSummary,\n templates: EvalTemplate[],\n config: KairnConfig,\n): Promise<Task[]> {\n const userMessage = buildTaskGenerationMessage(claudeMd, projectProfile, templates);\n\n const rawResponse = await callLLM(config, userMessage, {\n systemPrompt: TASK_GENERATION_PROMPT,\n maxTokens: 4096,\n });\n\n const parsed = parseJsonResponse(rawResponse);\n\n // Extract tasks array from response\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new Error(\"LLM response is not a JSON object\");\n }\n\n const tasksObj = parsed as Record<string, unknown>;\n if (!Array.isArray(tasksObj.tasks)) {\n throw new Error(\"LLM response does not contain a 'tasks' array\");\n }\n\n // Validate each task\n const tasks: Task[] = [];\n for (let i = 0; i < tasksObj.tasks.length; i++) {\n tasks.push(validateTask(tasksObj.tasks[i], i));\n }\n\n return tasks;\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { loadIterationLog } from './trace.js';\nimport { diagnoseCounterfactuals } from './diagnosis.js';\nimport type {\n IterationLog,\n Task,\n TasksFile,\n Score,\n EvolutionReport,\n} from './types.js';\nimport { parse as yamlParse } from 'yaml';\n\n/**\n * Compute the numeric score from a Score object.\n */\nfunction numericScore(s: Score): number {\n return s.score ?? (s.pass ? 100 : 0);\n}\n\n/**\n * Load all iteration logs from a workspace by scanning iteration directories.\n */\nasync function loadAllIterations(workspacePath: string): Promise<IterationLog[]> {\n const iterDir = path.join(workspacePath, 'iterations');\n let entries: string[];\n try {\n entries = await fs.readdir(iterDir);\n } catch {\n return [];\n }\n\n const iterations: IterationLog[] = [];\n const iterNums = entries\n .map(e => parseInt(e, 10))\n .filter(n => !isNaN(n))\n .sort((a, b) => a - b);\n\n for (const n of iterNums) {\n const log = await loadIterationLog(workspacePath, n);\n if (log) iterations.push(log);\n }\n\n return iterations;\n}\n\n/**\n * Load tasks from tasks.yaml in the workspace.\n */\nasync function loadTasks(workspacePath: string): Promise<Task[]> {\n try {\n const content = await fs.readFile(path.join(workspacePath, 'tasks.yaml'), 'utf-8');\n const parsed = yamlParse(content) as TasksFile;\n return parsed?.tasks ?? [];\n } catch {\n return [];\n }\n}\n\n/**\n * Build a leaderboard: per-task scores across all iterations.\n */\nfunction buildLeaderboard(\n iterations: IterationLog[],\n tasks: Task[],\n): EvolutionReport['leaderboard'] {\n const taskIds = tasks.map(t => t.id);\n return taskIds.map(taskId => {\n const scores: Record<number, number> = {};\n const variance: Record<number, { mean: number; stddev: number; runs: number }> = {};\n let bestScore = -1;\n let bestIteration = 0;\n\n for (const iter of iterations) {\n const s = iter.taskResults[taskId];\n if (s) {\n const score = numericScore(s);\n scores[iter.iteration] = score;\n if (s.variance) {\n variance[iter.iteration] = {\n mean: s.variance.mean,\n stddev: s.variance.stddev,\n runs: s.variance.runs,\n };\n }\n if (score > bestScore) {\n bestScore = score;\n bestIteration = iter.iteration;\n }\n }\n }\n\n const hasVariance = Object.keys(variance).length > 0;\n return { taskId, scores, bestIteration, bestScore, ...(hasVariance ? { variance } : {}) };\n });\n}\n\n/**\n * Determine iteration status label.\n */\nfunction iterationStatus(iter: IterationLog, bestIteration: number): string {\n if (iter.iteration === 0) return 'baseline';\n if (!iter.proposal && !iter.diffPatch) return 'rollback';\n if (iter.score >= 100) return 'perfect';\n if (iter.iteration === bestIteration) return 'best';\n return 'evaluated';\n}\n\n/**\n * Generate a human-readable Markdown report of an evolution run.\n */\nexport async function generateMarkdownReport(workspacePath: string): Promise<string> {\n const iterations = await loadAllIterations(workspacePath);\n const tasks = await loadTasks(workspacePath);\n\n if (iterations.length === 0) {\n return '# Evolution Report\\n\\nNo iterations found. Run `kairn evolve run` first.\\n';\n }\n\n const baselineScore = iterations[0].score;\n const bestIter = iterations.reduce((best, curr) =>\n curr.score > best.score ? curr : best, iterations[0]);\n const improvement = bestIter.score - baselineScore;\n\n const counterfactuals = diagnoseCounterfactuals(iterations, tasks);\n const leaderboard = buildLeaderboard(iterations, tasks);\n\n const lines: string[] = [];\n\n // Title\n lines.push('# Evolution Report');\n lines.push('');\n\n // Overview\n lines.push('## Overview');\n lines.push('');\n lines.push(`| Metric | Value |`);\n lines.push(`|--------|-------|`);\n lines.push(`| Total iterations | ${iterations.length} |`);\n lines.push(`| Baseline score | ${baselineScore.toFixed(1)}% |`);\n lines.push(`| Best score | ${bestIter.score.toFixed(1)}% |`);\n lines.push(`| Best iteration | ${bestIter.iteration} |`);\n lines.push(`| Improvement | ${improvement >= 0 ? '+' : ''}${improvement.toFixed(1)} points |`);\n lines.push('');\n\n // Iteration summary table\n lines.push('## Iterations');\n lines.push('');\n // Check if any iteration has variance data\n const hasVariance = iterations.some(iter =>\n Object.values(iter.taskResults).some(s => s.variance),\n );\n\n if (hasVariance) {\n lines.push('| Iter | Score | Mutations | Status |');\n lines.push('|------|-------|-----------|--------|');\n } else {\n lines.push('| Iter | Score | Mutations | Status |');\n lines.push('|------|-------|-----------|--------|');\n }\n for (const iter of iterations) {\n const mutations = iter.proposal?.mutations.length ?? 0;\n const mutStr = mutations > 0 ? mutations.toString() : '-';\n const status = iterationStatus(iter, bestIter.iteration);\n let scoreStr = `${iter.score.toFixed(1)}%`;\n if (hasVariance) {\n const stddevs = Object.values(iter.taskResults)\n .map(s => s.variance?.stddev)\n .filter((v): v is number => v !== undefined);\n if (stddevs.length > 0) {\n const avgStddev = stddevs.reduce((a, b) => a + b, 0) / stddevs.length;\n scoreStr = `${iter.score.toFixed(1)}% ±${avgStddev.toFixed(1)}`;\n }\n }\n lines.push(`| ${iter.iteration} | ${scoreStr} | ${mutStr} | ${status} |`);\n }\n lines.push('');\n\n // Leaderboard\n if (leaderboard.length > 0) {\n lines.push('## Leaderboard');\n lines.push('');\n\n // Header: Task | Iter 0 | Iter 1 | ... | Best\n const iterNums = iterations.map(i => i.iteration);\n const headerCols = ['Task', ...iterNums.map(n => `Iter ${n}`), 'Best'];\n lines.push(`| ${headerCols.join(' | ')} |`);\n lines.push(`| ${headerCols.map(() => '---').join(' | ')} |`);\n\n for (const entry of leaderboard) {\n const scoreCols = iterNums.map(n => {\n const s = entry.scores[n];\n if (s === undefined) return '-';\n const v = entry.variance?.[n];\n if (v && v.runs > 1) return `${s.toFixed(0)}% ±${v.stddev.toFixed(1)}`;\n return `${s.toFixed(0)}%`;\n });\n lines.push(`| ${entry.taskId} | ${scoreCols.join(' | ')} | ${entry.bestScore.toFixed(0)}% (iter ${entry.bestIteration}) |`);\n }\n lines.push('');\n }\n\n // Counterfactual diagnosis\n if (counterfactuals.entries.length > 0) {\n lines.push('## Counterfactual Diagnosis');\n lines.push('');\n\n for (const entry of counterfactuals.entries) {\n const sign = entry.netScoreDelta >= 0 ? '+' : '';\n lines.push(`### Iteration ${entry.iteration} (net ${sign}${entry.netScoreDelta.toFixed(1)} points)`);\n lines.push('');\n lines.push(`**Mutations:** ${entry.mutationSummary}`);\n lines.push('');\n\n if (entry.helpedTasks.length > 0) {\n lines.push('**Helped:**');\n for (const t of entry.helpedTasks) {\n lines.push(`- ${t.taskId}: +${t.delta.toFixed(1)}`);\n }\n lines.push('');\n }\n\n if (entry.hurtTasks.length > 0) {\n lines.push('**Hurt:**');\n for (const t of entry.hurtTasks) {\n lines.push(`- ${t.taskId}: ${t.delta.toFixed(1)}`);\n }\n lines.push('');\n }\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Generate a machine-readable JSON report of an evolution run.\n */\nexport async function generateJsonReport(workspacePath: string): Promise<EvolutionReport> {\n const iterations = await loadAllIterations(workspacePath);\n const tasks = await loadTasks(workspacePath);\n\n const baselineScore = iterations.length > 0 ? iterations[0].score : 0;\n const bestIter = iterations.length > 0\n ? iterations.reduce((best, curr) => curr.score > best.score ? curr : best, iterations[0])\n : { score: 0, iteration: 0 };\n const improvement = bestIter.score - baselineScore;\n\n const counterfactuals = diagnoseCounterfactuals(iterations, tasks);\n const leaderboard = buildLeaderboard(iterations, tasks);\n\n return {\n overview: {\n title: 'Evolution Report',\n totalIterations: iterations.length,\n baselineScore,\n bestScore: bestIter.score,\n bestIteration: bestIter.iteration,\n improvement,\n },\n iterations: iterations.map(iter => {\n const stddevs = Object.values(iter.taskResults)\n .map(s => s.variance?.stddev)\n .filter((v): v is number => v !== undefined);\n const avgStddev = stddevs.length > 0\n ? stddevs.reduce((a, b) => a + b, 0) / stddevs.length\n : undefined;\n return {\n iteration: iter.iteration,\n score: iter.score,\n ...(avgStddev !== undefined ? { stddev: avgStddev } : {}),\n mutationCount: iter.proposal?.mutations.length ?? 0,\n status: iterationStatus(iter, bestIter.iteration),\n };\n }),\n leaderboard,\n counterfactuals,\n };\n}\n","import type {\n Trace,\n TraceDiff,\n IterationLog,\n Task,\n CounterfactualReport,\n CounterfactualEntry,\n Score,\n} from './types.js';\n\n/**\n * Compute the numeric score from a Score object.\n * Uses the explicit score field if present, otherwise 100 for pass / 0 for fail.\n */\nfunction numericScore(s: Score): number {\n return s.score ?? (s.pass ? 100 : 0);\n}\n\n/**\n * Produce a concise summary of stdout differences between two traces.\n * Shows line counts and the first few differing lines rather than a full diff.\n */\nfunction summarizeStdoutDiff(stdoutA: string, stdoutB: string): string {\n if (stdoutA === stdoutB) return '(identical)';\n\n const linesA = stdoutA.split('\\n');\n const linesB = stdoutB.split('\\n');\n\n const parts: string[] = [];\n parts.push(`Line count: ${linesA.length} → ${linesB.length}`);\n\n // Find first divergence point\n const minLen = Math.min(linesA.length, linesB.length);\n let firstDiff = -1;\n for (let i = 0; i < minLen; i++) {\n if (linesA[i] !== linesB[i]) {\n firstDiff = i;\n break;\n }\n }\n if (firstDiff === -1 && linesA.length !== linesB.length) {\n firstDiff = minLen;\n }\n if (firstDiff >= 0) {\n parts.push(`First difference at line ${firstDiff + 1}`);\n }\n\n return parts.join('; ');\n}\n\n/**\n * Diff two traces for the same task across different iterations.\n *\n * Compares scores, pass/fail status, stdout content, and file changes\n * to produce a structured TraceDiff showing what changed.\n */\nexport function diffTaskTraces(traceA: Trace, traceB: Trace): TraceDiff {\n const scoreA = numericScore(traceA.score);\n const scoreB = numericScore(traceB.score);\n\n const filesA = new Set(Object.keys(traceA.filesChanged));\n const filesB = new Set(Object.keys(traceB.filesChanged));\n\n const added: string[] = [];\n const removed: string[] = [];\n const changed: string[] = [];\n\n for (const f of filesB) {\n if (!filesA.has(f)) {\n added.push(f);\n } else if (traceA.filesChanged[f] !== traceB.filesChanged[f]) {\n changed.push(f);\n }\n }\n for (const f of filesA) {\n if (!filesB.has(f)) {\n removed.push(f);\n }\n }\n\n return {\n taskId: traceA.taskId,\n iterA: traceA.iteration,\n iterB: traceB.iteration,\n scoreDelta: scoreB - scoreA,\n passChanged: traceA.score.pass !== traceB.score.pass,\n stdoutDiff: summarizeStdoutDiff(traceA.stdout, traceB.stdout),\n filesChangedDiff: { added, removed, changed },\n };\n}\n\n/**\n * Analyze an evolution run to identify which mutations helped or hurt specific tasks.\n *\n * For each iteration that has a proposal (mutations), compares per-task scores\n * between consecutive iterations to attribute score changes to the mutations applied.\n */\nexport function diagnoseCounterfactuals(\n iterations: IterationLog[],\n _tasks: Task[],\n): CounterfactualReport {\n const entries: CounterfactualEntry[] = [];\n\n for (let i = 1; i < iterations.length; i++) {\n const prev = iterations[i - 1];\n const curr = iterations[i];\n\n // Skip iterations without proposals (rollbacks, baseline)\n if (!curr.proposal && !prev.proposal) continue;\n\n // The proposal that caused this iteration's harness was from the previous iteration\n const proposal = prev.proposal;\n if (!proposal || proposal.mutations.length === 0) continue;\n\n const mutationSummary = proposal.mutations\n .map(m => `${m.action} in ${m.file}: ${m.rationale}`)\n .join('; ');\n\n const helpedTasks: Array<{ taskId: string; delta: number }> = [];\n const hurtTasks: Array<{ taskId: string; delta: number }> = [];\n\n // Compare per-task scores\n const allTaskIds = new Set([\n ...Object.keys(prev.taskResults),\n ...Object.keys(curr.taskResults),\n ]);\n\n let netDelta = 0;\n for (const taskId of allTaskIds) {\n const prevScore = prev.taskResults[taskId]\n ? numericScore(prev.taskResults[taskId])\n : 0;\n const currScore = curr.taskResults[taskId]\n ? numericScore(curr.taskResults[taskId])\n : 0;\n const delta = currScore - prevScore;\n\n if (delta > 0) {\n helpedTasks.push({ taskId, delta });\n } else if (delta < 0) {\n hurtTasks.push({ taskId, delta });\n }\n netDelta += delta;\n }\n\n entries.push({\n iteration: i,\n mutationSummary,\n helpedTasks,\n hurtTasks,\n netScoreDelta: netDelta,\n });\n }\n\n return { entries };\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport { generateDiff } from './mutator.js';\nimport { loadIterationLog } from './trace.js';\n\nexport interface ApplyResult {\n iteration: number;\n filesChanged: string[];\n diffPreview: string;\n}\n\n/**\n * Find all iteration directories in the workspace and return their numbers.\n */\nasync function listIterations(workspacePath: string): Promise<number[]> {\n const iterationsDir = path.join(workspacePath, 'iterations');\n let entries: string[];\n try {\n entries = await fs.readdir(iterationsDir);\n } catch {\n return [];\n }\n\n const nums: number[] = [];\n for (const entry of entries) {\n const n = parseInt(entry, 10);\n if (!isNaN(n)) {\n try {\n await fs.access(path.join(iterationsDir, entry, 'harness'));\n nums.push(n);\n } catch {\n // skip entries without a harness directory\n }\n }\n }\n return nums.sort((a, b) => a - b);\n}\n\n/**\n * Find the best iteration by score across all iteration logs.\n */\nasync function findBestIteration(\n workspacePath: string,\n iterations: number[],\n): Promise<number> {\n let bestIter = iterations[0];\n let bestScore = -Infinity;\n\n for (const iter of iterations) {\n const log = await loadIterationLog(workspacePath, iter);\n const score = log?.score ?? 0;\n if (score > bestScore) {\n bestScore = score;\n bestIter = iter;\n }\n }\n\n return bestIter;\n}\n\n/**\n * List all files in a directory recursively, returning relative paths.\n */\nasync function listFilesRecursive(dir: string): Promise<string[]> {\n const results: string[] = [];\n\n async function walk(current: string): Promise<void> {\n let entries: import('fs').Dirent[];\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const fullPath = path.join(current, entry.name);\n if (entry.isDirectory()) {\n await walk(fullPath);\n } else {\n results.push(path.relative(dir, fullPath));\n }\n }\n }\n\n await walk(dir);\n return results;\n}\n\n/**\n * Apply an evolved harness to the project's .claude/ directory.\n *\n * 1. Determines target iteration (best by score, or user-specified)\n * 2. Generates a unified diff between current .claude/ and target harness\n * 3. Replaces .claude/ with the target harness\n *\n * @param workspacePath - Path to .kairn-evolve/ directory\n * @param projectRoot - Path to the project root (parent of .claude/)\n * @param targetIteration - Specific iteration to apply (undefined = best)\n * @returns ApplyResult with iteration number, changed files, and diff preview\n */\n/**\n * Find the best PBT result: check branch winners and synthesis output.\n * Returns the path to the best harness and a label describing its source.\n */\nasync function findBestPBTHarness(\n workspacePath: string,\n): Promise<{ harnessPath: string; label: string } | null> {\n const branchesDir = path.join(workspacePath, 'branches');\n let branchEntries: string[];\n try {\n branchEntries = await fs.readdir(branchesDir);\n } catch {\n return null; // No PBT branches exist\n }\n\n let bestScore = -Infinity;\n let bestPath = '';\n let bestLabel = '';\n\n // Check each branch's best iteration\n for (const branchId of branchEntries) {\n const branchPath = path.join(branchesDir, branchId);\n const branchIterations = await listIterations(branchPath);\n if (branchIterations.length === 0) continue;\n\n const bestIter = await findBestIteration(branchPath, branchIterations);\n const log = await loadIterationLog(branchPath, bestIter);\n const score = log?.score ?? 0;\n\n if (score > bestScore) {\n bestScore = score;\n bestPath = path.join(branchPath, 'iterations', bestIter.toString(), 'harness');\n bestLabel = `branch ${branchId}, iteration ${bestIter} (${score.toFixed(1)}%)`;\n }\n }\n\n // Check synthesis output\n const synthesisHarness = path.join(workspacePath, 'synthesis', 'harness');\n try {\n await fs.access(synthesisHarness);\n // Synthesis doesn't have iteration logs — check for a score file\n const synthesisLog = await loadIterationLog(workspacePath, 999);\n const synthScore = synthesisLog?.score ?? 0;\n if (synthScore > bestScore) {\n bestScore = synthScore;\n bestPath = synthesisHarness;\n bestLabel = `Meta-Principal synthesis (${synthScore.toFixed(1)}%)`;\n }\n } catch {\n // No synthesis output\n }\n\n if (!bestPath) return null;\n return { harnessPath: bestPath, label: bestLabel };\n}\n\nexport async function applyEvolution(\n workspacePath: string,\n projectRoot: string,\n targetIteration?: number,\n pbt?: boolean,\n): Promise<ApplyResult> {\n // PBT mode: find best across branches and synthesis\n if (pbt) {\n const pbtResult = await findBestPBTHarness(workspacePath);\n if (!pbtResult) {\n throw new Error('No PBT results found. Run `kairn evolve pbt` first.');\n }\n\n const claudeDir = path.join(projectRoot, '.claude');\n const diffPreview = await generateDiff(claudeDir, pbtResult.harnessPath);\n\n const currentFiles = await listFilesRecursive(claudeDir);\n const targetFiles = await listFilesRecursive(pbtResult.harnessPath);\n const allPaths = new Set([...currentFiles, ...targetFiles]);\n const filesChanged: string[] = [];\n for (const filePath of allPaths) {\n const currentContent = await fs.readFile(path.join(claudeDir, filePath), 'utf-8').catch(() => null);\n const targetContent = await fs.readFile(path.join(pbtResult.harnessPath, filePath), 'utf-8').catch(() => null);\n if (currentContent !== targetContent) {\n filesChanged.push(filePath);\n }\n }\n\n await fs.rm(claudeDir, { recursive: true, force: true });\n await copyDir(pbtResult.harnessPath, claudeDir);\n\n // Copy .mcp.json if present\n const harnessMcpJson = path.join(pbtResult.harnessPath, '.mcp.json');\n const projectMcpJson = path.join(projectRoot, '.mcp.json');\n try {\n await fs.access(harnessMcpJson);\n await fs.copyFile(harnessMcpJson, projectMcpJson);\n if (!filesChanged.includes('.mcp.json')) filesChanged.push('.mcp.json');\n } catch {\n // No .mcp.json in harness\n }\n\n return {\n iteration: -1, // signals PBT source\n filesChanged,\n diffPreview,\n };\n }\n\n // Standard mode: find best among top-level iterations\n const iterations = await listIterations(workspacePath);\n\n if (iterations.length === 0) {\n throw new Error('No iterations found in workspace. Run `kairn evolve run` first.');\n }\n\n let iter: number;\n if (targetIteration !== undefined) {\n if (!iterations.includes(targetIteration)) {\n throw new Error(\n `Iteration ${targetIteration} not found. Available: ${iterations.join(', ')}`,\n );\n }\n iter = targetIteration;\n } else {\n iter = await findBestIteration(workspacePath, iterations);\n }\n\n const harnessPath = path.join(\n workspacePath,\n 'iterations',\n iter.toString(),\n 'harness',\n );\n const claudeDir = path.join(projectRoot, '.claude');\n\n const diffPreview = await generateDiff(claudeDir, harnessPath);\n\n const currentFiles = await listFilesRecursive(claudeDir);\n const targetFiles = await listFilesRecursive(harnessPath);\n const allPaths = new Set([...currentFiles, ...targetFiles]);\n const filesChanged: string[] = [];\n for (const filePath of allPaths) {\n const currentContent = await fs.readFile(path.join(claudeDir, filePath), 'utf-8').catch(() => null);\n const targetContent = await fs.readFile(path.join(harnessPath, filePath), 'utf-8').catch(() => null);\n if (currentContent !== targetContent) {\n filesChanged.push(filePath);\n }\n }\n\n await fs.rm(claudeDir, { recursive: true, force: true });\n await copyDir(harnessPath, claudeDir);\n\n // Copy .mcp.json from harness if it exists (harness scope includes MCP config)\n const harnessMcpJson = path.join(harnessPath, '.mcp.json');\n const projectMcpJson = path.join(projectRoot, '.mcp.json');\n try {\n await fs.access(harnessMcpJson);\n const currentMcp = await fs.readFile(projectMcpJson, 'utf-8').catch(() => null);\n const targetMcp = await fs.readFile(harnessMcpJson, 'utf-8').catch(() => null);\n if (currentMcp !== targetMcp) {\n filesChanged.push('.mcp.json');\n }\n await fs.copyFile(harnessMcpJson, projectMcpJson);\n } catch {\n // No .mcp.json in harness — leave project's .mcp.json untouched\n }\n\n return {\n iteration: iter,\n filesChanged,\n diffPreview,\n };\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAkBnB,SAAS,yBAAyB,KAAsC;AAC7E,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;AAE1D,QAAM,MAAM;AACZ,QAAM,QAAQ,IAAI,eAAe;AACjC,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AAExD,QAAM,WAAW;AACjB,QAAM,cAAc,SAAS,aAAa;AAC1C,QAAM,eAAe,SAAS,cAAc;AAC5C,QAAM,YAAY,SAAS,WAAW;AACtC,QAAM,mBAAmB,SAAS,kBAAkB;AAEpD,MAAI,OAAO,gBAAgB,YAAY,CAAC,YAAa,QAAO;AAC5D,MAAI,OAAO,iBAAiB,SAAU,QAAO;AAC7C,MAA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,QAAQ,IAAI,UAAU;AAC/D,EAAAC,QAAM,QAAQ;AAChB;AAEA,QAAQ,MAAM;","names":["Anthropic","OpenAI","client","fs","path","fs","path","exec","promisify","execAsync","passed","exec","promisify","fs","os","path","execAsync","tmpDir","fs","path","fs","path","loadProposerMemory","formatMemoryForProposer","fs","path","readFileSafe","path","fs","path","generateDiff","legacyDiff","fs","path","fs","path","fs","path","nextIterDir","buildRunSummary","saveRunSummary","path","fs","path","baselinePath","Command","chalk","chalk","fs","path","KAIRN_WORDMARK","path","chalk","maroon","darkMaroon","warmStone","lightStone","dimStone","dimStone","maroon","chalk","path","fs","client","chalk","Command","input","confirm","select","chalk","fs","path","fs","path","fileURLToPath","__filename","fileURLToPath","__dirname","path","fs","path","fs","fs","path","fs","path","fs","path","os","writeFile","password","chalk","fs","path","chalk","password","path","fs","Command","chalk","input","select","confirm","Command","chalk","fs","path","Command","fs","chalk","path","Command","chalk","fs","path","Command","fs","chalk","path","Command","chalk","fs","path","fileURLToPath","__filename","fileURLToPath","__dirname","path","fs","Command","chalk","Command","confirm","chalk","fs","path","fs","path","pkg","chalk","path","fs","Command","confirm","Command","chalk","perms","Command","chalk","Command","chalk","input","select","listCommand","Command","chalk","input","select","Command","chalk","fs","path","Command","fs","chalk","path","Command","password","chalk","fs","path","Command","chalk","password","Command","chalk","ora","fs","path","yamlParse","confirm","input","select","fs","path","path","fs","pkg","fs","path","numericScore","path","fs","fs","path","claudeDir","diffPreview","generateDiff","currentFiles","targetFiles","allPaths","filesChanged","harnessMcpJson","projectMcpJson","fs","path","yamlParse","Command","ora","chalk","confirm","select","input","runPopulation","generateDiff","require","Command","chalk"]}
|