kairn-cli 2.0.0 → 2.1.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/commands/init.ts","../src/config.ts","../src/providers.ts","../src/ui.ts","../src/logo.ts","../src/commands/describe.ts","../src/compiler/compile.ts","../src/compiler/prompt.ts","../src/registry/loader.ts","../src/llm.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/baseline.ts","../src/evolve/runner.ts","../src/evolve/trace.ts","../src/evolve/exec.ts","../src/evolve/scorers.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { initCommand } from \"./commands/init.js\";\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(\"1.9.0\")\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 { 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 } from \"../types.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 const 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 const config: KairnConfig = {\n provider,\n api_key: apiKey || \"\",\n model,\n ...(baseURL ? { base_url: baseURL } : {}),\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 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 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\";\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 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 },\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## 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)\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:\n\\`\\`\\`json\n{\n \"hooks\": {\n \"PreToolUse\": [{\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|curl.*\\\\\\\\|\\\\\\\\s*sh' && echo 'Blocked destructive command' >&2 && exit 2 || true\"\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\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). 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- Development pipeline agents (used by /project:develop):\n - \\`@architect\\` (opus) — conducts spec interview with user, writes confirmed spec to docs/SPRINT.md\n - \\`@planner\\` (opus) — reads spec and codebase, creates step-by-step implementation plan in docs/PLAN.md\n - \\`@implementer\\` (sonnet) — TDD-focused implementation, writes failing tests then minimum code to pass\n - \\`@fixer\\` (sonnet) — targeted bug fixing from verifier/review feedback\n - \\`@doc-updater\\` (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, 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## 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)\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 Anthropic from \"@anthropic-ai/sdk\";\nimport OpenAI from \"openai\";\nimport { getProviderName, getBaseURL } from \"./providers.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 }\n): Promise<string> {\n const maxTokens = options.maxTokens ?? 8192;\n const systemPrompt = options.systemPrompt;\n const providerName = getProviderName(config.provider);\n\n if (config.provider === \"anthropic\") {\n const client = new Anthropic({ apiKey: config.api_key });\n try {\n const response = await client.messages.create({\n model: config.model,\n max_tokens: maxTokens,\n system: systemPrompt,\n messages: [{ role: \"user\", content: userMessage }],\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: config.api_key };\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 });\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 { 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 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 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 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, 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 } from '../evolve/trace.js';\nimport { loadConfig } from '../config.js';\nimport type { EvolveConfig, Task, TasksFile, TaskResult } from '../evolve/types.js';\n\nconst DEFAULT_CONFIG: EvolveConfig = {\n model: 'claude-sonnet-4-6',\n proposerModel: 'claude-opus-4-6',\n scorer: 'pass-fail',\n maxIterations: 5,\n parallelTasks: 1,\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 .action(async (options: { task?: string }) => {\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 // Parse tasks.yaml with yaml package\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 // Filter tasks\n const tasksToRun = options.task\n ? parsed.tasks.filter(t => t.id === options.task)\n : parsed.tasks;\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 } 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};\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', 'documentation'],\n 'api-building': ['add-feature', 'fix-bug', 'test-writing'],\n 'full-stack': ['add-feature', 'fix-bug', 'test-writing'],\n 'maintenance': ['fix-bug', 'refactor', 'test-writing'],\n 'debugging': ['fix-bug', 'test-writing'],\n 'qa': ['fix-bug', 'test-writing', 'add-feature'],\n 'architecture': ['refactor', 'test-writing', 'config-change'],\n 'backend': ['fix-bug', 'refactor', 'config-change', 'test-writing'],\n 'devops': ['config-change', 'fix-bug'],\n 'infrastructure': ['config-change', 'refactor'],\n 'tdd': ['test-writing', 'add-feature', 'fix-bug'],\n 'content': ['documentation', 'add-feature'],\n 'research': ['documentation', 'add-feature'],\n };\n return mapping[workflowType] || ['add-feature', 'fix-bug', 'test-writing'];\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\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 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\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 { 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 } from './trace.js';\nimport type { Task, TaskResult, Trace } from './types.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * Run a single task against a harness in an isolated workspace.\n *\n * 1. Creates temp directory\n * 2. Copies harness (.claude/) into it\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 temp directory\n */\nexport async function runTask(\n task: Task,\n harnessPath: string,\n traceDir: string,\n iteration: number,\n): Promise<TaskResult> {\n await fs.mkdir(traceDir, { recursive: true });\n const startedAt = new Date().toISOString();\n const startMs = Date.now();\n\n // 1. Create isolated workspace\n const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'kairn-evolve-'));\n\n try {\n // 2. Copy harness into workspace\n await copyDir(harnessPath, path.join(tmpDir, '.claude'));\n\n // 3. 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: tmpDir, timeout: 60_000 });\n } catch (err) {\n // Setup failure -- record it but continue to capture the trace\n setupStderr =\n err instanceof Error ? err.message : String(err);\n }\n }\n\n // 4. Snapshot file list before execution for diffing\n const filesBefore = await snapshotFileList(tmpDir);\n\n // 5. Spawn claude CLI\n const spawnResult = await spawnClaude(task.description, tmpDir, task.timeout);\n\n // 6. Diff files to detect changes\n const filesAfter = await snapshotFileList(tmpDir);\n const filesChanged = diffFileLists(filesBefore, filesAfter);\n\n // 7. 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 // 8. 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 // 9. Write trace files\n await writeTrace(traceDir, trace);\n\n // 10. 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 // 11. Clean up temp directory\n await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});\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'];\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","import fs from 'fs/promises';\nimport path from 'path';\nimport type { Trace, Score } 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","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/**\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 const hasErrors =\n stderr.toLowerCase().includes('error') ||\n stderr.toLowerCase().includes('failed') ||\n stderr.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 });\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 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 });\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 * Select and run the appropriate scorer based on task config.\n *\n * LLM-based scorers (llm-judge, rubric) require a KairnConfig.\n * When config is not provided, they fall back to passFailScorer.\n */\nexport async function scoreTask(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n config?: KairnConfig,\n): Promise<Score> {\n if (task.scoring === 'pass-fail') {\n return passFailScorer(task, workspacePath, stdout, stderr);\n }\n if (task.scoring === 'llm-judge' && config) {\n return llmJudgeScorer(task, workspacePath, stdout, stderr, config);\n }\n if (task.scoring === 'rubric' && config) {\n return rubricScorer(task, workspacePath, stdout, stderr, config);\n }\n // Fallback to pass-fail if no config provided for LLM-based scorers\n return passFailScorer(task, workspacePath, stdout, stderr);\n}\n"],"mappings":";AAAA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,aAAW;;;ACDlB,SAAS,eAAe;AACxB,SAAS,OAAO,UAAU,cAAc;AACxC,OAAOC,YAAW;AAClB,OAAO,eAAe;AACtB,OAAO,YAAY;AACnB,SAAS,oBAAoB;AAC7B,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,qBAAqB;;;ACR9B,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,QAAQ;AAGf,IAAM,YAAY,KAAK,KAAK,GAAG,QAAQ,GAAG,QAAQ;AAClD,IAAM,cAAc,KAAK,KAAK,WAAW,aAAa;AACtD,IAAM,WAAW,KAAK,KAAK,WAAW,MAAM;AAC5C,IAAM,gBAAgB,KAAK,KAAK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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":["Command","chalk","chalk","fs","path","KAIRN_WORDMARK","path","chalk","maroon","darkMaroon","warmStone","lightStone","dimStone","dimStone","maroon","chalk","path","fs","client","chalk","Command","input","select","chalk","fs","path","fs","path","fileURLToPath","__filename","fileURLToPath","__dirname","path","fs","Anthropic","OpenAI","client","Anthropic","OpenAI","path","fs","fs","path","fs","path","fs","path","os","writeFile","password","chalk","fs","path","chalk","password","path","fs","Command","chalk","input","select","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","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","confirm","select","fs","path","path","fs","fs","path","fs","os","path","fs","path","fs","path","fs","path","os","exec","promisify","execAsync","passed","Command","path","fs","ora","chalk","confirm","select","Command","chalk"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/commands/init.ts","../src/config.ts","../src/providers.ts","../src/ui.ts","../src/logo.ts","../src/commands/describe.ts","../src/compiler/compile.ts","../src/compiler/prompt.ts","../src/registry/loader.ts","../src/llm.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/baseline.ts","../src/evolve/runner.ts","../src/evolve/trace.ts","../src/evolve/exec.ts","../src/evolve/scorers.ts","../src/evolve/loop.ts","../src/evolve/proposer.ts","../src/evolve/mutator.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { initCommand } from \"./commands/init.js\";\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(\"1.9.0\")\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 { 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 } from \"../types.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 const 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 const config: KairnConfig = {\n provider,\n api_key: apiKey || \"\",\n model,\n ...(baseURL ? { base_url: baseURL } : {}),\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 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 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\";\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 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 },\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## 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)\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:\n\\`\\`\\`json\n{\n \"hooks\": {\n \"PreToolUse\": [{\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|curl.*\\\\\\\\|\\\\\\\\s*sh' && echo 'Blocked destructive command' >&2 && exit 2 || true\"\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\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). 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- Development pipeline agents (used by /project:develop):\n - \\`@architect\\` (opus) — conducts spec interview with user, writes confirmed spec to docs/SPRINT.md\n - \\`@planner\\` (opus) — reads spec and codebase, creates step-by-step implementation plan in docs/PLAN.md\n - \\`@implementer\\` (sonnet) — TDD-focused implementation, writes failing tests then minimum code to pass\n - \\`@fixer\\` (sonnet) — targeted bug fixing from verifier/review feedback\n - \\`@doc-updater\\` (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, 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## 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)\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 Anthropic from \"@anthropic-ai/sdk\";\nimport OpenAI from \"openai\";\nimport { getProviderName, getBaseURL } from \"./providers.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 }\n): Promise<string> {\n const maxTokens = options.maxTokens ?? 8192;\n const systemPrompt = options.systemPrompt;\n const providerName = getProviderName(config.provider);\n\n if (config.provider === \"anthropic\") {\n const client = new Anthropic({ apiKey: config.api_key });\n try {\n const response = await client.messages.create({\n model: config.model,\n max_tokens: maxTokens,\n system: systemPrompt,\n messages: [{ role: \"user\", content: userMessage }],\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: config.api_key };\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 });\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 { 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 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 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 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, 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 } from '../evolve/trace.js';\nimport { evolve } from '../evolve/loop.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-opus-4-6',\n scorer: 'pass-fail',\n maxIterations: 5,\n parallelTasks: 1,\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 };\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 .action(async (options: { task?: string; iterations?: string }) => {\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 // Parse tasks.yaml with yaml package\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 // Decision: --task means single-task mode, otherwise full evolution loop\n if (options.task) {\n // --- Single task mode (existing behavior) ---\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 // --- Full evolution loop mode ---\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 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 // 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 // Run evolution with progress callback\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 '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 console.log(' Iter Score Mutations Status');\n for (const iter of result.iterations) {\n const scoreStr = iter.score.toFixed(1).padStart(6) + '%';\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)} ${scoreStr} ${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/**\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};\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', 'documentation'],\n 'api-building': ['add-feature', 'fix-bug', 'test-writing'],\n 'full-stack': ['add-feature', 'fix-bug', 'test-writing'],\n 'maintenance': ['fix-bug', 'refactor', 'test-writing'],\n 'debugging': ['fix-bug', 'test-writing'],\n 'qa': ['fix-bug', 'test-writing', 'add-feature'],\n 'architecture': ['refactor', 'test-writing', 'config-change'],\n 'backend': ['fix-bug', 'refactor', 'config-change', 'test-writing'],\n 'devops': ['config-change', 'fix-bug'],\n 'infrastructure': ['config-change', 'refactor'],\n 'tdd': ['test-writing', 'add-feature', 'fix-bug'],\n 'content': ['documentation', 'add-feature'],\n 'research': ['documentation', 'add-feature'],\n };\n return mapping[workflowType] || ['add-feature', 'fix-bug', 'test-writing'];\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\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 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\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 { 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 } from './types.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * Run a single task against a harness in an isolated workspace.\n *\n * 1. Creates temp directory\n * 2. Copies harness (.claude/) into it\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 temp directory\n */\nexport async function runTask(\n task: Task,\n harnessPath: string,\n traceDir: string,\n iteration: number,\n): Promise<TaskResult> {\n await fs.mkdir(traceDir, { recursive: true });\n const startedAt = new Date().toISOString();\n const startMs = Date.now();\n\n // 1. Create isolated workspace\n const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'kairn-evolve-'));\n\n try {\n // 2. Copy harness into workspace\n await copyDir(harnessPath, path.join(tmpDir, '.claude'));\n\n // 3. 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: tmpDir, timeout: 60_000 });\n } catch (err) {\n // Setup failure -- record it but continue to capture the trace\n setupStderr =\n err instanceof Error ? err.message : String(err);\n }\n }\n\n // 4. Snapshot file list before execution for diffing\n const filesBefore = await snapshotFileList(tmpDir);\n\n // 5. Spawn claude CLI\n const spawnResult = await spawnClaude(task.description, tmpDir, task.timeout);\n\n // 6. Diff files to detect changes\n const filesAfter = await snapshotFileList(tmpDir);\n const filesChanged = diffFileLists(filesBefore, filesAfter);\n\n // 7. 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 // 8. 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 // 9. Write trace files\n await writeTrace(traceDir, trace);\n\n // 10. 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 // 11. Clean up temp directory\n await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});\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'];\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 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): Promise<{ results: Record<string, Score>; aggregate: number }> {\n const results: Record<string, Score> = {};\n\n for (const task of tasks) {\n const traceDir = path.join(\n workspacePath,\n 'traces',\n iteration.toString(),\n task.id,\n );\n const taskResult = await runTask(task, harnessPath, traceDir, iteration);\n\n let score = 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 score = await scoreTask(task, traceDir, stdout, stderr, config);\n await writeScore(traceDir, score);\n }\n\n results[task.id] = score;\n }\n\n // Aggregate: average of all scores (pass-fail counted as 0 or 100)\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 { 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/**\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 const hasErrors =\n stderr.toLowerCase().includes('error') ||\n stderr.toLowerCase().includes('failed') ||\n stderr.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 });\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 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 });\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 * Select and run the appropriate scorer based on task config.\n *\n * LLM-based scorers (llm-judge, rubric) require a KairnConfig.\n * When config is not provided, they fall back to passFailScorer.\n */\nexport async function scoreTask(\n task: Task,\n workspacePath: string,\n stdout: string,\n stderr: string,\n config?: KairnConfig,\n): Promise<Score> {\n if (task.scoring === 'pass-fail') {\n return passFailScorer(task, workspacePath, stdout, stderr);\n }\n if (task.scoring === 'llm-judge' && config) {\n return llmJudgeScorer(task, workspacePath, stdout, stderr, config);\n }\n if (task.scoring === 'rubric' && config) {\n return rubricScorer(task, workspacePath, stdout, stderr, config);\n }\n // Fallback to pass-fail if no config provided for LLM-based scorers\n return passFailScorer(task, workspacePath, stdout, stderr);\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 type { KairnConfig } from '../types.js';\nimport type {\n Task,\n EvolveConfig,\n IterationLog,\n EvolveResult,\n LoopProgressEvent,\n} from './types.js';\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 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\n onProgress?.({ type: 'iteration-start', iteration: iter });\n const { results, aggregate } = await evaluateAll(\n tasks,\n harnessPath,\n workspacePath,\n iter,\n kairnConfig,\n );\n onProgress?.({ type: 'iteration-scored', iteration: iter, score: aggregate });\n\n if (iter === 0) baselineScore = aggregate;\n\n // 2. ROLLBACK CHECK\n if (iter > 0 && aggregate < bestScore) {\n onProgress?.({\n type: 'rollback',\n iteration: iter,\n score: aggregate,\n message: `Regression: ${aggregate.toFixed(1)}% < ${bestScore.toFixed(1)}%. Rolling back.`,\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 };\n await writeIterationLog(workspacePath, rollbackLog);\n history.push(rollbackLog);\n\n // Copy best harness to next iteration (if not last)\n if (iter + 1 < evolveConfig.maxIterations) {\n const nextIterDir = path.join(\n workspacePath,\n 'iterations',\n (iter + 1).toString(),\n );\n const bestHarnessPath = path.join(\n workspacePath,\n 'iterations',\n bestIteration.toString(),\n 'harness',\n );\n await copyDir(bestHarnessPath, path.join(nextIterDir, 'harness'));\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 };\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 };\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 } catch {\n // Proposer failed — copy current harness forward unchanged\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 };\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 } catch {\n // Mutation failed — copy current harness forward unchanged\n await copyDir(harnessPath, path.join(nextIterDir, 'harness'));\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 };\n await writeIterationLog(workspacePath, iterLog);\n history.push(iterLog);\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 { loadIterationTraces } from './trace.js';\nimport type { Task, Trace, Proposal, Mutation, IterationLog } from './types.js';\nimport type { KairnConfig } from '../types.js';\n\n/**\n * System prompt for the proposer agent.\n *\n * Instructs the LLM to analyze execution traces, diagnose root causes\n * of task failures, and propose minimal, targeted harness mutations.\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## 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 ],\n \"expected_impact\": { \"task-id\": \"+15% — explanation\" }\n}\n\n## Rules\n- MINIMAL changes only. Don't rewrite the entire CLAUDE.md.\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- Prefer ADDITIVE changes over replacements when possible.\n\nReturn ONLY valid JSON.`;\n\n/** Maximum characters of stdout to include per trace in the prompt. */\nconst STDOUT_TRUNCATION_LIMIT = 2000;\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\n/**\n * Truncate a string to the last `limit` characters.\n * Prepends a truncation notice if the string was shortened.\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): string {\n const sections: string[] = [];\n\n // Section 1: Current harness files\n sections.push('## Current Harness Files\\n');\n const fileEntries = Object.entries(harnessFiles);\n if (fileEntries.length === 0) {\n sections.push('(No harness files found)\\n');\n } else {\n for (const [filePath, content] of fileEntries) {\n sections.push(`### ${filePath}\\n\\`\\`\\`\\n${content}\\n\\`\\`\\`\\n`);\n }\n }\n\n // Section 2: Task definitions\n sections.push('## Task Definitions\\n');\n if (tasks.length === 0) {\n sections.push('(No tasks defined)\\n');\n } else {\n for (const task of tasks) {\n sections.push(\n `### Task: ${task.id}\\n` +\n `- Template: ${task.template}\\n` +\n `- Description: ${task.description}\\n` +\n `- Expected outcome: ${Array.isArray(task.expected_outcome) ? task.expected_outcome.join('; ') : task.expected_outcome}\\n` +\n `- Scoring: ${task.scoring}\\n`,\n );\n }\n }\n\n // Section 3: Execution traces\n sections.push('## Execution Traces\\n');\n if (traces.length === 0) {\n sections.push('(No traces available)\\n');\n } else {\n for (const trace of traces) {\n const scoreNum = trace.score.score !== undefined ? trace.score.score : (trace.score.pass ? 100 : 0);\n const truncatedStdout = truncateStdout(trace.stdout, STDOUT_TRUNCATION_LIMIT);\n const filesChangedList = Object.entries(trace.filesChanged)\n .map(([f, action]) => ` - ${f}: ${action}`)\n .join('\\n');\n\n sections.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 ${STDOUT_TRUNCATION_LIMIT} chars):\\n\\`\\`\\`\\n${truncatedStdout}\\n\\`\\`\\`\\n`,\n );\n }\n }\n\n // Section 4: Iteration history\n sections.push('## Iteration History\\n');\n if (history.length === 0) {\n sections.push('(No previous iterations)\\n');\n } else {\n for (const log of history) {\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 sections.push(\n `### Iteration ${log.iteration} — Score: ${log.score}\\n` +\n `- Task results:\\n${taskScores}\\n`,\n );\n\n if (log.proposal) {\n sections.push(\n `- Proposal reasoning: ${log.proposal.reasoning}\\n` +\n `- Mutations: ${log.proposal.mutations.length} change(s)\\n`,\n );\n }\n }\n }\n\n return sections.join('\\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 // Strip leading/trailing whitespace\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 // Parse JSON\n let parsed: unknown;\n try {\n parsed = JSON.parse(cleaned);\n } catch {\n throw new Error(`Proposer returned invalid JSON: ${cleaned.slice(0, 200)}`);\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 // Validate reasoning\n if (typeof obj['reasoning'] !== 'string') {\n throw new Error('Proposer response missing required \"reasoning\" string field');\n }\n\n // Validate mutations\n if (!Array.isArray(obj['mutations'])) {\n throw new Error('Proposer response missing required \"mutations\" array field');\n }\n\n // Parse and validate each mutation\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'] as string : '');\n const oldText = typeof m['old_text'] === 'string'\n ? m['old_text']\n : (typeof m['oldText'] === 'string' ? m['oldText'] as string : 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 // Validate action type\n if (action !== 'replace' && action !== 'add_section' && action !== 'create_file') {\n continue;\n }\n\n // For replace action, oldText is required\n if (action === 'replace' && !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 // 1. Read harness files\n const harnessFiles = await readHarnessFiles(harnessPath);\n\n // 2. Load traces for this iteration\n const traces = await loadIterationTraces(workspacePath, iteration);\n\n // 3. Build user message\n const userMessage = buildProposerUserMessage(harnessFiles, traces, tasks, history);\n\n // 4. Call LLM with proposer model override\n const proposerConfig: KairnConfig = { ...config, model: proposerModel };\n const response = await callLLM(proposerConfig, userMessage, {\n systemPrompt: PROPOSER_SYSTEM_PROMPT,\n maxTokens: 8192,\n });\n\n // 5. Parse response\n return parseProposerResponse(response);\n}\n","import fs from 'fs/promises';\nimport path from 'path';\nimport { copyDir } from './baseline.js';\nimport type { Mutation } from './types.js';\n\n/**\n * Apply mutations to a copy of the current harness.\n *\n * 1. Copies currentHarnessPath to {nextIterationDir}/harness/\n * 2. Applies each mutation in order\n * 3. Generates a unified diff between old and new harness\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 // 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 // Security: reject path traversal\n if (mutation.file.includes('..')) {\n continue;\n }\n\n const filePath = path.join(newHarnessPath, mutation.file);\n\n if (mutation.action === 'replace') {\n if (!mutation.oldText) {\n continue;\n }\n const content = await fs.readFile(filePath, 'utf-8');\n if (!content.includes(mutation.oldText)) {\n continue;\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 }\n }\n\n // 3. Generate diff\n const diffPatch = await generateDiff(currentHarnessPath, newHarnessPath);\n\n return { newHarnessPath, diffPatch };\n}\n\n/**\n * Generate a simple unified-diff-style patch between two directories.\n * Compares files in both directories and outputs differences.\n */\nexport async function generateDiff(\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"],"mappings":";AAAA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,aAAW;;;ACDlB,SAAS,eAAe;AACxB,SAAS,OAAO,UAAU,cAAc;AACxC,OAAOC,YAAW;AAClB,OAAO,eAAe;AACtB,OAAO,YAAY;AACnB,SAAS,oBAAoB;AAC7B,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,qBAAqB;;;ACR9B,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,QAAQ;AAGf,IAAM,YAAY,KAAK,KAAK,GAAG,QAAQ,GAAG,QAAQ;AAClD,IAAM,cAAc,KAAK,KAAK,WAAW,aAAa;AACtD,IAAM,WAAW,KAAK,KAAK,WAAW,MAAM;AAC5C,IAAM,gBAAgB,KAAK,KAAK,WAAW,WAAW;AACtD,IAAM,qBAAqB,KAAK,KAAK,WAAW,oBAAoB;AAM7D,SAAS,gBAAwB;AACtC,SAAO;AACT;AAEO,SAAS,aAAqB;AACnC,SAAO;AACT;AAEO,SAAS,kBAA0B;AACxC,SAAO;AACT;AAEO,SAAS,sBAA8B;AAC5C,SAAO;AACT;AAEA,eAAsB,aAA4B;AAChD,QAAM,GAAG,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAC7C,QAAM,GAAG,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;AAC5C,QAAM,GAAG,MAAM,eAAe,EAAE,WAAW,KAAK,CAAC;AACnD;AAEA,eAAsB,aAA0C;AAC9D,MAAI;AACF,UAAM,OAAO,MAAM,GAAG,SAAS,aAAa,OAAO;AACnD,UAAM,MAAM,KAAK,MAAM,IAAI;AAG3B,QAAI,IAAI,qBAAqB,CAAC,IAAI,UAAU;AAC1C,aAAO;AAAA,QAC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AAC/D,EAAAC,QAAM,QAAQ;AAChB;AAEA,QAAQ,MAAM;","names":["Command","chalk","chalk","fs","path","KAIRN_WORDMARK","path","chalk","maroon","darkMaroon","warmStone","lightStone","dimStone","dimStone","maroon","chalk","path","fs","client","chalk","Command","input","select","chalk","fs","path","fs","path","fileURLToPath","__filename","fileURLToPath","__dirname","path","fs","Anthropic","OpenAI","client","Anthropic","OpenAI","path","fs","fs","path","fs","path","fs","path","os","writeFile","password","chalk","fs","path","chalk","password","path","fs","Command","chalk","input","select","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","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","confirm","select","fs","path","path","fs","fs","path","exec","promisify","fs","os","path","fs","path","path","fs","passed","execAsync","promisify","exec","fs","path","os","fs","path","fs","path","fs","path","fs","path","path","fs","generateDiff","path","fs","nextIterDir","fs","path","Command","ora","chalk","confirm","select","Command","chalk"]}