@agntk/agent-harness 0.1.1 → 0.1.3
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/index.js +5 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/index.js +77 -1
- package/dist/index.js.map +1 -1
- package/dist/{universal-installer-QGS4SJGX.js → universal-installer-EVBDGOWM.js} +79 -2
- package/dist/universal-installer-EVBDGOWM.js.map +1 -0
- package/package.json +1 -1
- package/dist/universal-installer-QGS4SJGX.js.map +0 -1
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/index.ts"],"sourcesContent":["// Suppress Node 18 ExperimentalWarning for the Fetch API. Must run BEFORE any\n// import that triggers fetch (most of the Vercel AI SDK chain). Node 20+ users\n// won't see this warning at all; Node 18 users get clean output.\n// We listen on the 'warning' event and re-emit everything except the fetch one.\nconst __defaultWarningHandlers = process.listeners('warning');\nprocess.removeAllListeners('warning');\nprocess.on('warning', (warning: NodeJS.ErrnoException) => {\n if (warning.name === 'ExperimentalWarning' && /fetch/i.test(warning.message)) {\n return;\n }\n // Restore default behavior: print the warning to stderr.\n for (const handler of __defaultWarningHandlers) {\n (handler as (w: NodeJS.ErrnoException) => void)(warning);\n }\n});\n\nimport { Command } from 'commander';\nimport { resolve, join, basename } from 'path';\nimport { existsSync } from 'fs';\nimport { config as loadDotenv } from 'dotenv';\nimport { setGlobalLogLevel, type LogLevel } from '../core/logger.js';\n\n// Load .env from current directory and common locations.\n// `quiet: true` suppresses dotenv 17.x's \"injected env (N) from .env\" banners\n// and the rotating \"tip:\" marketing text. Users who want the banners back can\n// run with HARNESS_VERBOSE=1 or unset DOTENV_CONFIG_QUIET in their shell.\nconst __dotenvQuiet = process.env.HARNESS_VERBOSE !== '1';\nloadDotenv({ quiet: __dotenvQuiet });\nloadDotenv({ path: resolve('.env.local'), quiet: __dotenvQuiet });\n\nconst program = new Command();\n\n// Model aliases for convenience\nconst MODEL_ALIASES: Record<string, string> = {\n 'gemma': 'google/gemma-4-26b-a4b-it',\n 'gemma-31b': 'google/gemma-4-31b-it',\n 'qwen': 'qwen/qwen3.5-35b-a3b',\n 'glm': 'z-ai/glm-4.7-flash',\n 'claude': 'anthropic/claude-sonnet-4',\n 'gpt4o': 'openai/gpt-4o',\n 'gpt4o-mini': 'openai/gpt-4o-mini',\n};\n\nfunction resolveModel(model?: string): string | undefined {\n if (!model) return undefined;\n return MODEL_ALIASES[model] || model;\n}\n\nfunction loadEnvFromDir(dir: string) {\n const envPath = join(dir, '.env');\n if (existsSync(envPath)) {\n loadDotenv({ path: envPath });\n }\n}\n\nfunction formatError(err: unknown): string {\n if (!err) return 'Unknown error';\n if (typeof err === 'string') return err;\n const e = err as Record<string, unknown>;\n\n // OpenRouter API errors\n if (e.data && typeof e.data === 'object') {\n const data = e.data as Record<string, unknown>;\n if (data.error && typeof data.error === 'object') {\n const apiErr = data.error as Record<string, unknown>;\n if (typeof apiErr.message === 'string') return apiErr.message;\n }\n }\n\n const message = e.message;\n if (typeof message !== 'string') return String(err);\n\n // API key errors\n if (message.includes('API key') || message.includes('OPENROUTER_API_KEY'))\n return message;\n\n // Model errors\n if (message.includes('not a valid model') || message.includes('model not found'))\n return `Invalid model: ${message}`;\n\n // Network errors\n if (message.includes('ECONNREFUSED') || message.includes('ENOTFOUND'))\n return `Network error: Could not reach API. Check your internet connection.`;\n if (message.includes('ETIMEDOUT'))\n return `Request timed out. The API may be overloaded — try again.`;\n\n // Rate limiting\n if (message.includes('429') || message.includes('rate limit'))\n return `Rate limited by API. Wait a moment and try again.`;\n\n // Config errors\n if (message.includes('Invalid config'))\n return message;\n\n // Zod validation errors\n if (message.includes('Expected') && message.includes('received'))\n return `Validation error: ${message}`;\n\n // File system errors\n if (message.includes('ENOENT'))\n return `File not found: ${message.replace(/.*ENOENT[^']*'([^']+)'.*/, '$1')}`;\n if (message.includes('EACCES'))\n return `Permission denied: ${message.replace(/.*EACCES[^']*'([^']+)'.*/, '$1')}`;\n\n return message;\n}\n\nfunction requireHarness(dir: string): void {\n if (!existsSync(join(dir, 'CORE.md')) && !existsSync(join(dir, 'config.yaml'))) {\n console.error(`Error: No harness found in ${dir}`);\n console.error(`Run \"harness init <name>\" to create one.`);\n process.exit(1);\n }\n}\n\nprogram\n .name('harness')\n .description('Agent Harness — build AI agents by editing files, not writing code.')\n .version('0.1.0')\n .option('-q, --quiet', 'Suppress non-error output')\n .option('-v, --verbose', 'Enable debug output')\n .option('--log-level <level>', 'Set log level (debug, info, warn, error, silent)')\n .hook('preAction', () => {\n const opts = program.opts();\n if (opts.quiet) setGlobalLogLevel('error');\n else if (opts.verbose) setGlobalLogLevel('debug');\n else if (opts.logLevel) setGlobalLogLevel(opts.logLevel as LogLevel);\n });\n\n// --- INIT ---\n\n/** Ask a question via readline and return the answer */\nfunction askQuestion(rl: ReturnType<typeof import('readline').createInterface>, question: string, defaultValue?: string): Promise<string> {\n const suffix = defaultValue ? ` [${defaultValue}]` : '';\n return new Promise((resolve) => {\n rl.question(`${question}${suffix}: `, (answer) => {\n resolve(answer.trim() || defaultValue || '');\n });\n });\n}\n\nprogram\n .command('init [name]')\n .description('Scaffold a new agent harness directory (interactive if no name given)')\n .option('-d, --dir <path>', 'Parent directory', '.')\n .option('-t, --template <name>', 'Config template (base, claude-opus, gpt4, local)', 'base')\n .option('-p, --purpose <description>', 'Agent purpose description')\n .option('-i, --interactive', 'Force interactive mode', false)\n .option('--generate', 'Generate CORE.md using LLM (requires API key)', false)\n .option('--no-discover-mcp', 'Skip MCP server auto-discovery')\n .option('--no-discover-env', 'Skip environment variable scanning')\n .option('--no-discover-project', 'Skip project context detection')\n .option('-y, --yes', 'Accept defaults for all prompts (skip MCP confirmation)', false)\n .action(async (name: string | undefined, opts: { dir: string; template: string; purpose?: string; interactive: boolean; generate: boolean; discoverMcp: boolean; discoverEnv: boolean; discoverProject: boolean; yes: boolean }) => {\n const { scaffoldHarness, generateCoreMd, listTemplates } = await import('./scaffold.js');\n\n // Interactive mode: no name provided or --interactive flag\n const isInteractive = !name || opts.interactive;\n let agentName = name ?? '';\n let purpose = opts.purpose ?? '';\n let template = opts.template;\n let shouldGenerate = opts.generate;\n\n if (isInteractive && process.stdin.isTTY) {\n const readline = await import('readline');\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n\n try {\n console.log('\\n Agent Harness Setup\\n');\n\n if (!agentName) {\n agentName = await askQuestion(rl, ' Agent name', 'my-agent');\n }\n\n if (!purpose) {\n purpose = await askQuestion(rl, ' What does this agent do? (purpose)');\n }\n\n const templates = listTemplates();\n if (templates.length > 1) {\n console.log(` Available templates: ${templates.join(', ')}`);\n template = await askQuestion(rl, ' Template', template);\n }\n\n if (purpose && !shouldGenerate) {\n // Check if an API key is available for LLM generation\n const hasKey = !!(process.env.OPENROUTER_API_KEY || process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY);\n if (hasKey) {\n const gen = await askQuestion(rl, ' Generate CORE.md using AI? (y/n)', 'y');\n shouldGenerate = gen.toLowerCase() === 'y' || gen.toLowerCase() === 'yes';\n }\n }\n\n console.log();\n } finally {\n rl.close();\n }\n }\n\n if (!agentName) {\n console.error('Error: agent name is required. Usage: harness init <name>');\n process.exit(1);\n }\n\n // If the user passed a path (e.g. /tmp/my-agent or ./projects/foo), use the\n // basename as the agent name and resolve the parent dir from the path.\n // Otherwise treat agentName as a bare name relative to opts.dir as before.\n const looksLikePath = agentName.includes('/') || agentName.startsWith('.');\n const targetDir = looksLikePath ? resolve(agentName) : resolve(opts.dir, agentName);\n const parentDir = looksLikePath ? resolve(targetDir, '..') : resolve(opts.dir);\n if (looksLikePath) {\n agentName = basename(targetDir);\n }\n\n try {\n // Generate CORE.md via LLM if requested\n let coreContent: string | undefined;\n if (shouldGenerate && purpose) {\n console.log('Generating CORE.md...');\n try {\n coreContent = await generateCoreMd(agentName, purpose, {});\n console.log('✓ CORE.md generated via LLM');\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n console.log(` LLM generation failed: ${message}`);\n console.log(' Using template instead');\n }\n }\n\n scaffoldHarness(targetDir, agentName, { template, purpose: purpose || undefined, coreContent });\n console.log(`\\n✓ Agent harness created: ${targetDir}`);\n\n // Auto-discover MCP servers from other tools\n if (opts.discoverMcp !== false) {\n const { discoverMcpServers, discoveredServersToYaml, filterUnsafeServers } = await import('../runtime/mcp-discovery.js');\n const discovery = discoverMcpServers();\n const safeServers = filterUnsafeServers(discovery.servers);\n\n if (safeServers.length > 0) {\n console.log(`\\n✓ Discovered ${safeServers.length} MCP server(s) from existing tools:`);\n const safeNames = new Set(safeServers.map((s) => s.name));\n for (const source of discovery.sources) {\n const kept = source.servers.filter((s) => safeNames.has(s.name));\n if (kept.length > 0) {\n console.log(` ${source.tool}: ${kept.map((s) => s.name).join(', ')}`);\n }\n }\n\n // Prompt for confirmation unless --yes or stdin is not a TTY\n let shouldAdd = true;\n if (!opts.yes && process.stdin.isTTY) {\n const readline = await import('readline');\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await new Promise<string>((res) => {\n rl.question(`\\nAdd these ${safeServers.length} server(s) to config.yaml? [Y/n] `, (a) => res(a.trim()));\n });\n shouldAdd = answer === '' || answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes';\n } finally {\n rl.close();\n }\n }\n\n if (shouldAdd) {\n const { appendFileSync } = await import('fs');\n const configPath = resolve(targetDir, 'config.yaml');\n const yaml = discoveredServersToYaml(safeServers);\n appendFileSync(configPath, '\\n' + yaml + '\\n');\n console.log(` → Added to config.yaml`);\n console.log(` → Run 'harness mcp test' to verify connections`);\n } else {\n console.log(` → Skipped MCP discovery. Add servers manually with 'harness mcp install <name>'.`);\n }\n }\n }\n\n // Auto-discover environment variables\n if (opts.discoverEnv !== false) {\n const { discoverEnvKeys } = await import('../runtime/env-discovery.js');\n const envResult = discoverEnvKeys({ dir: parentDir, extraDirs: [targetDir] });\n\n if (envResult.suggestions.length > 0) {\n console.log(`\\n✓ Detected ${envResult.keys.length} API key(s) in environment:`);\n for (const suggestion of envResult.suggestions) {\n console.log(` ${suggestion.triggeredBy} → ${suggestion.message}`);\n console.log(` Install: harness mcp install \"${suggestion.serverQuery}\" -d ${name}`);\n }\n }\n }\n\n // Auto-discover project context\n if (opts.discoverProject !== false) {\n const { discoverProjectContext } = await import('../runtime/project-discovery.js');\n const projectResult = discoverProjectContext({ dir: parentDir });\n\n if (projectResult.signals.length > 0) {\n const stack = projectResult.signals.map((s) => s.name).join(', ');\n console.log(`\\n✓ Detected project stack: ${stack}`);\n\n if (projectResult.suggestions.length > 0) {\n console.log(` Suggestions:`);\n for (const suggestion of projectResult.suggestions) {\n if (suggestion.type === 'mcp-server') {\n console.log(` Install MCP: harness mcp install \"${suggestion.target}\" -d ${name}`);\n } else {\n console.log(` Create ${suggestion.type}: ${suggestion.target}`);\n }\n }\n }\n }\n }\n\n console.log(`\\nNext steps — try these in order:`);\n console.log(` cd ${targetDir}`);\n console.log(` harness run \"What can you do?\" # see what's loaded`);\n console.log(` harness run \"Help me decide between two options: A or B\"`);\n console.log(` harness run \"Plan a weekend project for me\" # see it qualify`);\n console.log(` harness journal # see what it learned`);\n console.log(` harness learn --install # teach it to remember`);\n console.log(`\\nThe agent gets better the more you use it. See README.md inside`);\n console.log(`the harness directory for the full walkthrough.`);\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- RUN ---\nprogram\n .command('run <prompt>')\n .description('Run a prompt through the agent')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-s, --stream', 'Stream output', false)\n .option('-m, --model <model>', 'Model override (or alias: gemma, qwen, glm, claude)')\n .option('-p, --provider <provider>', 'Provider override (openrouter, anthropic, openai)')\n .option('-k, --api-key <key>', 'API key override (default: from environment)')\n .action(async (prompt: string, opts: { dir: string; stream: boolean; model?: string; provider?: string; apiKey?: string }) => {\n const { createHarness } = await import('../core/harness.js');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n\n requireHarness(dir);\n\n const modelId = resolveModel(opts.model);\n try {\n const agent = createHarness({\n dir,\n model: modelId,\n provider: opts.provider,\n apiKey: opts.apiKey,\n });\n\n if (opts.stream) {\n const streamResult = agent.stream(prompt);\n process.stdout.write('\\n');\n for await (const chunk of streamResult.textStream) {\n process.stdout.write(chunk);\n }\n process.stdout.write('\\n\\n');\n const result = await streamResult.result;\n const toolInfo = result.toolCalls.length > 0\n ? ` | ${result.toolCalls.length} tool call(s)`\n : '';\n const stepInfo = result.steps > 1 ? ` | ${result.steps} steps` : '';\n console.error(\n `[${result.usage.totalTokens} tokens${stepInfo}${toolInfo} | session: ${result.session_id}]`\n );\n } else {\n const result = await agent.run(prompt);\n console.log('\\n' + result.text + '\\n');\n const toolInfo = result.toolCalls.length > 0\n ? ` | ${result.toolCalls.length} tool call(s)`\n : '';\n const stepInfo = result.steps > 1 ? ` | ${result.steps} steps` : '';\n console.error(\n `[${result.usage.totalTokens} tokens${stepInfo}${toolInfo} | session: ${result.session_id}]`\n );\n }\n\n await agent.shutdown();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- CHAT (interactive REPL with conversation memory) ---\nprogram\n .command('chat')\n .description('Start an interactive chat session with conversation memory')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-m, --model <model>', 'Model override')\n .option('-p, --provider <provider>', 'Provider override (openrouter, anthropic, openai)')\n .option('-k, --api-key <key>', 'API key override (default: from environment)')\n .option('--fresh', 'Start fresh (clear conversation history)', false)\n .action(async (opts: { dir: string; model?: string; provider?: string; apiKey?: string; fresh: boolean }) => {\n const { Conversation } = await import('../runtime/conversation.js');\n const { loadConfig } = await import('../core/config.js');\n const { buildToolSet } = await import('../runtime/tool-executor.js');\n const { createMcpManager } = await import('../runtime/mcp.js');\n const readline = await import('readline');\n const dir = resolve(opts.dir);\n\n requireHarness(dir);\n\n const config = loadConfig(dir);\n\n // Load tools (markdown + programmatic + MCP)\n let mcpTools: Record<string, unknown> = {};\n const mcpManager = createMcpManager(config);\n if (mcpManager.hasServers()) {\n try {\n await mcpManager.connect();\n mcpTools = mcpManager.getTools();\n } catch (err: unknown) {\n console.error(`Warning: MCP connection failed: ${formatError(err)}`);\n }\n }\n const toolSet = buildToolSet(dir, undefined, mcpTools as Record<string, never>);\n const toolCount = Object.keys(toolSet).length;\n\n const conv = new Conversation(dir, opts.apiKey, { tools: toolSet });\n const modelId = resolveModel(opts.model);\n if (modelId) conv.setModelOverride(modelId);\n if (opts.provider) conv.setProviderOverride(opts.provider);\n if (opts.fresh) conv.clear();\n await conv.init();\n\n const history = conv.getHistory();\n console.log(`\\n${config.agent.name} is ready. ${history.length > 0 ? `(${history.length} messages in history)` : ''}${toolCount > 0 ? ` | ${toolCount} tools` : ''}`);\n console.log(`Type your message, \"clear\" to reset, or \"exit\" to quit.\\n`);\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n let closed = false;\n let sending = false; // Track in-flight LLM requests\n let pendingClose = false; // Deferred close requested while sending\n\n const cleanup = async () => {\n if (mcpManager.hasServers()) {\n await mcpManager.close();\n }\n };\n\n const doClose = async () => {\n if (closed) return;\n closed = true;\n await cleanup();\n };\n\n rl.on('close', async () => {\n if (sending) {\n // Defer cleanup until the in-flight request finishes\n pendingClose = true;\n return;\n }\n await doClose();\n });\n\n const ask = () => {\n if (closed) return;\n rl.question('> ', async (input) => {\n if (closed) return;\n const trimmed = input.trim();\n if (!trimmed || trimmed === 'exit' || trimmed === 'quit') {\n await doClose();\n rl.close();\n return;\n }\n if (trimmed === 'clear') {\n conv.clear();\n console.log('[conversation cleared]\\n');\n ask();\n return;\n }\n\n sending = true;\n try {\n const streamResult = conv.sendStream(trimmed);\n process.stdout.write('\\n');\n for await (const chunk of streamResult.textStream) {\n process.stdout.write(chunk);\n }\n process.stdout.write('\\n');\n const meta = await streamResult.result;\n if (meta.usage.totalTokens > 0) {\n const toolInfo = meta.toolCalls.length > 0\n ? ` | ${meta.toolCalls.length} tool call(s)`\n : '';\n const stepInfo = meta.steps > 1 ? ` | ${meta.steps} steps` : '';\n console.error(`[${meta.usage.totalTokens} tokens${stepInfo}${toolInfo}]`);\n }\n process.stdout.write('\\n');\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n } finally {\n sending = false;\n // If readline closed while we were sending, clean up now\n if (pendingClose) {\n await doClose();\n return;\n }\n }\n\n ask();\n });\n };\n\n ask();\n });\n\n// --- INFO ---\nprogram\n .command('info')\n .description('Show harness info and loaded context')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; json: boolean }) => {\n const { loadConfig } = await import('../core/config.js');\n const { buildSystemPrompt } = await import('../runtime/context-loader.js');\n const { loadState } = await import('../runtime/state.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n const config = loadConfig(dir);\n const ctx = buildSystemPrompt(dir, config);\n const state = loadState(dir);\n\n // MCP servers\n const mcpServers = config.mcp?.servers ?? {};\n const mcpEntries = Object.entries(mcpServers);\n\n if (opts.json) {\n const info = {\n agent: { name: config.agent.name, version: config.agent.version },\n model: config.model.id,\n provider: config.model.provider,\n state: { mode: state.mode, last_interaction: state.last_interaction },\n context: {\n max_tokens: ctx.budget.max_tokens,\n used_tokens: ctx.budget.used_tokens,\n remaining: ctx.budget.remaining,\n loaded_files: ctx.budget.loaded_files,\n },\n mcp: mcpEntries.map(([name, s]) => ({\n name,\n transport: s.transport,\n enabled: s.enabled !== false,\n })),\n };\n console.log(JSON.stringify(info, null, 2));\n return;\n }\n\n console.log(`\\nAgent: ${config.agent.name} v${config.agent.version}`);\n console.log(`Model: ${config.model.id}`);\n console.log(`State: ${state.mode}`);\n console.log(`Last interaction: ${state.last_interaction}`);\n console.log(`\\nContext budget:`);\n console.log(` Max tokens: ${ctx.budget.max_tokens}`);\n console.log(` Used: ~${ctx.budget.used_tokens}`);\n console.log(` Remaining: ~${ctx.budget.remaining}`);\n console.log(` Files loaded: ${ctx.budget.loaded_files.length}`);\n ctx.budget.loaded_files.forEach(f => console.log(` - ${f}`));\n\n if (mcpEntries.length > 0) {\n const enabledCount = mcpEntries.filter(([, s]) => s.enabled !== false).length;\n console.log(`\\nMCP servers: ${mcpEntries.length} configured (${enabledCount} enabled)`);\n for (const [name, s] of mcpEntries) {\n const enabled = s.enabled !== false;\n console.log(` ${enabled ? '+' : '-'} ${name} (${s.transport})`);\n }\n }\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- PROMPT (show the assembled system prompt) ---\nprogram\n .command('prompt')\n .description('Show the full assembled system prompt')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output metadata as JSON (includes prompt, budget, warnings)')\n .action(async (opts: { dir: string; json: boolean }) => {\n const { loadConfig } = await import('../core/config.js');\n const { buildSystemPrompt } = await import('../runtime/context-loader.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n const config = loadConfig(dir);\n const ctx = buildSystemPrompt(dir, config);\n\n if (opts.json) {\n console.log(JSON.stringify({\n systemPrompt: ctx.systemPrompt,\n budget: ctx.budget,\n warnings: ctx.warnings,\n parseErrors: ctx.parseErrors,\n }, null, 2));\n return;\n }\n\n console.log(ctx.systemPrompt);\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- DEV (watch mode + scheduler) ---\nprogram\n .command('dev')\n .description('Start dev mode — watches for file changes, rebuilds indexes, runs scheduled workflows, serves dashboard')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-k, --api-key <key>', 'API key override (default: from environment)')\n .option('--no-schedule', 'Disable workflow scheduler')\n .option('--no-auto-process', 'Disable auto-processing of primitives on save')\n .option('--no-web', 'Disable web dashboard server')\n .option('-p, --port <number>', 'Web dashboard port', '3000')\n .action(async (opts: { dir: string; apiKey?: string; schedule: boolean; autoProcess: boolean; web: boolean; port: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const { rebuildAllIndexes } = await import('../runtime/indexer.js');\n const { createWatcher } = await import('../runtime/watcher.js');\n const { Scheduler } = await import('../runtime/scheduler.js');\n const { autoProcessAll } = await import('../runtime/auto-processor.js');\n const { generateSystemMd } = await import('../cli/scaffold.js');\n const { writeFileSync } = await import('fs');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const doAutoProcess = opts.autoProcess && (config.runtime?.auto_process !== false);\n console.log(`\\n[dev] Watching \"${config.agent.name}\" harness at ${dir}`);\n\n // Auto-process all primitives on startup (fills missing frontmatter, L0/L1)\n if (doAutoProcess) {\n const processed = autoProcessAll(dir);\n if (processed.length > 0) {\n console.log(`[dev] Auto-processed ${processed.length} file(s) on startup`);\n for (const r of processed) {\n const rel = r.path.replace(dir + '/', '');\n console.log(` ${rel}: ${r.fixes.join(', ')}`);\n }\n }\n }\n\n // Regenerate SYSTEM.md from current directory structure\n const systemPath = join(dir, 'SYSTEM.md');\n const newSystem = generateSystemMd(dir, config.agent.name);\n writeFileSync(systemPath, newSystem, 'utf-8');\n console.log(`[dev] SYSTEM.md regenerated from directory structure`);\n\n // Initial index build\n const extDirs = config.extensions?.directories ?? [];\n rebuildAllIndexes(dir, extDirs);\n console.log(`[dev] Indexes rebuilt${extDirs.length ? ` (+ ${extDirs.length} extension dir(s))` : ''}`);\n\n // Start scheduler if there are workflows\n let scheduler: InstanceType<typeof Scheduler> | null = null;\n if (opts.schedule) {\n scheduler = new Scheduler({\n harnessDir: dir,\n apiKey: opts.apiKey,\n autoJournal: config.intelligence?.auto_journal ?? false,\n autoLearn: config.intelligence?.auto_learn ?? false,\n onRun: (id, result) => {\n console.log(`[scheduler] ✓ ${id}: ${result.slice(0, 100)}`);\n },\n onError: (id, error) => {\n console.error(`[scheduler] ✗ ${id}: ${error.message}`);\n },\n onSchedule: (id, cronExpr) => {\n console.log(`[scheduler] Scheduled: ${id} (${cronExpr})`);\n },\n onArchival: (sessions, journals) => {\n if (sessions + journals > 0) {\n console.log(`[scheduler] Archived ${sessions} session(s), ${journals} journal(s)`);\n }\n },\n onJournal: (date, sessionsCount) => {\n console.log(`[scheduler] Auto-journal: synthesized ${sessionsCount} session(s) for ${date}`);\n },\n onLearn: (installed, skipped) => {\n console.log(`[scheduler] Auto-learn: ${installed} instinct(s) installed, ${skipped} skipped`);\n },\n });\n scheduler.start();\n\n const scheduled = scheduler.listScheduled();\n const features: string[] = [];\n if (scheduled.length > 0) features.push(`${scheduled.length} workflow(s)`);\n if (config.intelligence?.auto_journal) features.push('auto-journal');\n if (config.intelligence?.auto_learn) features.push('auto-learn');\n if (features.length > 0) {\n console.log(`[dev] Scheduler started: ${features.join(', ')}`);\n } else {\n console.log(`[dev] Scheduler running (no workflows or intelligence features configured)`);\n }\n }\n\n // Start web dashboard server\n let webServer: { server: unknown; broadcaster: { broadcast: (e: { type: string; data: unknown; timestamp: string }) => void } } | null = null;\n if (opts.web) {\n const { startWebServer } = await import('../runtime/web-server.js');\n const port = parseInt(opts.port, 10) || 3000;\n webServer = await startWebServer({\n harnessDir: dir,\n port,\n apiKey: opts.apiKey,\n onStart: (p) => console.log(`[dev] Dashboard: http://localhost:${p}`),\n });\n }\n\n const sseBroadcast = (type: string, data: unknown): void => {\n webServer?.broadcaster.broadcast({ type, data, timestamp: new Date().toISOString() });\n };\n\n // Start watching (including extension directories and config.yaml)\n createWatcher({\n harnessDir: dir,\n extraDirs: extDirs,\n watchConfig: true,\n autoProcess: doAutoProcess,\n onChange: (path, event) => {\n const rel = path.replace(dir + '/', '');\n console.log(`[dev] ${event}: ${rel}`);\n sseBroadcast('file_change', { path: rel, event });\n },\n onIndexRebuild: (directory) => {\n console.log(`[dev] Index rebuilt: ${directory}/_index.md`);\n sseBroadcast('index_rebuild', { directory });\n },\n onAutoProcess: (result) => {\n if (result.modified) {\n const rel = result.path.replace(dir + '/', '');\n console.log(`[dev] Auto-processed: ${rel} (${result.fixes.join(', ')})`);\n sseBroadcast('auto_process', { path: rel, fixes: result.fixes });\n }\n },\n onConfigChange: () => {\n try {\n const newConfig = loadConfig(dir);\n console.log(`[dev] Config reloaded: model=${newConfig.model.id}`);\n sseBroadcast('config_change', { model: newConfig.model.id });\n } catch (err: unknown) {\n console.error(`[dev] Config reload failed: ${formatError(err)}`);\n }\n },\n onError: (err) => {\n console.error(`[dev] Watcher error: ${err.message}`);\n },\n });\n\n console.log(`[dev] Watching for changes... (Ctrl+C to stop)\\n`);\n\n // Graceful shutdown\n const cleanup = () => {\n console.log(`\\n[dev] Shutting down...`);\n if (scheduler) scheduler.stop();\n if (webServer?.server && typeof (webServer.server as { close?: () => void }).close === 'function') {\n (webServer.server as { close: () => void }).close();\n }\n process.exit(0);\n };\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n });\n\n// --- INDEX (rebuild all indexes) ---\nprogram\n .command('index')\n .description('Rebuild all index files')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { rebuildAllIndexes } = await import('../runtime/indexer.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n\n let extDirs: string[] = [];\n try {\n const config = loadConfig(dir);\n extDirs = config.extensions?.directories ?? [];\n } catch (err) {\n if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n rebuildAllIndexes(dir, extDirs);\n console.log(`✓ All indexes rebuilt in ${dir}`);\n });\n\n// --- PROCESS (auto-process all primitives) ---\nprogram\n .command('process')\n .description('Auto-process all primitives: fill missing frontmatter and generate L0/L1 summaries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--no-frontmatter', 'Skip frontmatter generation')\n .option('--no-summaries', 'Skip L0/L1 summary generation')\n .action(async (opts: { dir: string; frontmatter: boolean; summaries: boolean }) => {\n const { autoProcessAll } = await import('../runtime/auto-processor.js');\n const dir = resolve(opts.dir);\n\n requireHarness(dir);\n\n const results = autoProcessAll(dir, {\n generateFrontmatter: opts.frontmatter,\n generateSummaries: opts.summaries,\n });\n\n if (results.length === 0) {\n console.log('All primitives are up to date.');\n } else {\n for (const r of results) {\n const rel = r.path.replace(dir + '/', '');\n if (r.modified) {\n console.log(`✓ ${rel}: ${r.fixes.join(', ')}`);\n }\n for (const err of r.errors) {\n console.error(`✗ ${rel}: ${err}`);\n }\n }\n const modified = results.filter((r) => r.modified).length;\n const errors = results.filter((r) => r.errors.length > 0).length;\n console.log(`\\nProcessed ${modified} file(s)${errors > 0 ? `, ${errors} error(s)` : ''}`);\n }\n });\n\n// --- SYSTEM (regenerate SYSTEM.md from directory structure) ---\nprogram\n .command('system')\n .description('Regenerate SYSTEM.md from current directory structure')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const { generateSystemMd } = await import('../cli/scaffold.js');\n const { writeFileSync } = await import('fs');\n const dir = resolve(opts.dir);\n\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const systemPath = join(dir, 'SYSTEM.md');\n const content = generateSystemMd(dir, config.agent.name);\n writeFileSync(systemPath, content, 'utf-8');\n console.log(`✓ SYSTEM.md regenerated at ${systemPath}`);\n });\n\n// --- JOURNAL (synthesize sessions into journal) ---\nprogram\n .command('journal')\n .description('Synthesize sessions into journal entries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--date <date>', 'Date to synthesize (YYYY-MM-DD)')\n .option('--from <date>', 'Start of date range (YYYY-MM-DD)')\n .option('--to <date>', 'End of date range (YYYY-MM-DD, default: today)')\n .option('--all', 'Synthesize all dates with sessions', false)\n .option('--force', 'Re-synthesize even if journal exists', false)\n .option('--pending', 'Show dates with sessions but no journal', false)\n .option('--auto-harvest', 'Auto-install instinct candidates from synthesized journals', false)\n .action(async (opts: { dir: string; date?: string; from?: string; to?: string; all: boolean; force: boolean; pending: boolean; autoHarvest: boolean }) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n\n requireHarness(dir);\n\n // Show pending (unjournaled) dates\n if (opts.pending) {\n const { listUnjournaled } = await import('../runtime/journal.js');\n const dates = listUnjournaled(dir);\n if (dates.length === 0) {\n console.log('All sessions have been journaled.');\n } else {\n console.log(`\\n${dates.length} date(s) with unjournaled sessions:\\n`);\n dates.forEach((d) => console.log(` ${d}`));\n console.log(`\\nRun \"harness journal --all\" to synthesize them.\\n`);\n }\n return;\n }\n\n // Range mode (--from/--to or --all)\n if (opts.from || opts.all) {\n const { synthesizeJournalRange } = await import('../runtime/journal.js');\n\n try {\n const label = opts.all ? 'all dates' : `${opts.from}${opts.to ? ` to ${opts.to}` : ' to today'}`;\n console.log(`Synthesizing journals for ${label}${opts.force ? ' (force)' : ''}...`);\n\n const entries = await synthesizeJournalRange(dir, {\n from: opts.from,\n to: opts.to,\n all: opts.all,\n force: opts.force,\n });\n\n if (entries.length === 0) {\n console.log('No sessions to synthesize (or all dates already journaled).');\n return;\n }\n\n console.log(`\\n✓ ${entries.length} journal(s) synthesized:\\n`);\n for (const entry of entries) {\n const sessionCount = entry.sessions.length;\n const instinctCount = entry.instinct_candidates.length;\n console.log(` ${entry.date}: ${sessionCount} session(s), ${entry.tokens_used} tokens${instinctCount > 0 ? `, ${instinctCount} instinct candidate(s)` : ''}`);\n }\n console.log();\n\n // Auto-harvest: install instinct candidates from synthesized journals\n if (opts.autoHarvest) {\n const { harvestInstincts } = await import('../runtime/instinct-learner.js');\n const dates = entries.map((e) => e.date).sort();\n const harvest = harvestInstincts(dir, {\n from: dates[0],\n to: dates[dates.length - 1],\n install: true,\n });\n if (harvest.installed.length > 0) {\n console.log(`Auto-harvested ${harvest.installed.length} instinct(s):`);\n harvest.installed.forEach((id) => console.log(` ✓ ${id}`));\n console.log();\n }\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n return;\n }\n\n // Single date mode (default)\n const { synthesizeJournal } = await import('../runtime/journal.js');\n\n try {\n console.log(`Synthesizing journal...`);\n const entry = await synthesizeJournal(dir, opts.date);\n console.log(`\\n✓ Journal for ${entry.date}`);\n console.log(` Sessions: ${entry.sessions.length}`);\n console.log(` Tokens: ${entry.tokens_used}`);\n if (entry.instinct_candidates.length > 0) {\n console.log(` Instinct candidates:`);\n entry.instinct_candidates.forEach(c => console.log(` - ${c}`));\n\n // Auto-harvest: install instinct candidates from this journal\n if (opts.autoHarvest) {\n const { harvestInstincts } = await import('../runtime/instinct-learner.js');\n const harvest = harvestInstincts(dir, {\n from: entry.date,\n to: entry.date,\n install: true,\n });\n if (harvest.installed.length > 0) {\n console.log(` Auto-harvested:`);\n harvest.installed.forEach((id) => console.log(` ✓ ${id}`));\n }\n }\n }\n console.log(`\\n${entry.synthesis}`);\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- COMPRESS (weekly journal roll-ups) ---\nprogram\n .command('compress')\n .description('Compress daily journals into weekly roll-up summaries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--force', 'Overwrite existing weekly summaries', false)\n .action(async (opts: { dir: string; force: boolean }) => {\n const { compressJournals } = await import('../runtime/journal.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const results = compressJournals(dir, { force: opts.force });\n\n if (results.length === 0) {\n console.log('\\nNo complete past weeks to compress (or all already compressed).\\n');\n return;\n }\n\n console.log(`\\n✓ ${results.length} weekly summary(ies) created:\\n`);\n for (const week of results) {\n const insights = week.allInsights.length;\n const instincts = week.allInstinctCandidates.length;\n console.log(` ${week.weekStart} to ${week.weekEnd} (${week.journalDates.length} days)`);\n console.log(` ${insights} insight(s), ${instincts} instinct candidate(s)`);\n }\n console.log();\n });\n\n// --- LEARN (propose and install instincts) ---\nprogram\n .command('learn')\n .description('Analyze sessions and propose new instincts')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--install', 'Auto-install proposed instincts', false)\n .action(async (opts: { dir: string; install: boolean }) => {\n const { learnFromSessions } = await import('../runtime/instinct-learner.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n console.log(`Analyzing sessions for instinct candidates...`);\n const result = await learnFromSessions(dir, opts.install);\n\n if (result.candidates.length === 0) {\n console.log(`No instinct candidates found.`);\n return;\n }\n\n console.log(`\\n${result.candidates.length} instinct candidate(s):\\n`);\n for (const c of result.candidates) {\n const status = result.installed.includes(c.id)\n ? '✓ installed'\n : result.skipped.includes(c.id)\n ? '⊘ skipped (exists)'\n : '○ proposed';\n console.log(` [${status}] ${c.id} (${c.confidence})`);\n console.log(` ${c.behavior}`);\n console.log(` Provenance: ${c.provenance}\\n`);\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- HARVEST (extract instinct candidates from journals) ---\nprogram\n .command('harvest')\n .description('Extract instinct candidates from journal entries and optionally install them')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--install', 'Auto-install candidates as draft instincts', false)\n .action(async (opts: { dir: string; from?: string; to?: string; install: boolean }) => {\n const { harvestInstincts } = await import('../runtime/instinct-learner.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const result = harvestInstincts(dir, {\n from: opts.from,\n to: opts.to,\n install: opts.install,\n });\n\n console.log(`\\nScanned ${result.journalsScanned} journal(s)`);\n\n if (result.candidates.length === 0) {\n console.log(`No new instinct candidates found.\\n`);\n return;\n }\n\n console.log(`Found ${result.candidates.length} candidate(s):\\n`);\n for (const c of result.candidates) {\n const status = result.installed.includes(c.id)\n ? '✓ installed'\n : result.skipped.includes(c.id)\n ? '⊘ skipped (exists)'\n : '○ proposed';\n console.log(` [${status}] ${c.id}`);\n console.log(` ${c.behavior}`);\n console.log(` Source: ${c.provenance}\\n`);\n }\n\n if (!opts.install && result.candidates.length > 0) {\n console.log(`Run with --install to create instinct files.\\n`);\n }\n });\n\n// NOTE: \"install\" command moved to universal installer below (Phase 9)\n\n// --- INTAKE (process all files in intake/) ---\nprogram\n .command('intake')\n .description('Process all pending files in the intake/ directory')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { processIntake } = await import('../runtime/intake.js');\n const dir = resolve(opts.dir);\n\n const results = processIntake(dir);\n\n if (results.length === 0) {\n console.log(`No files in intake/`);\n return;\n }\n\n for (const { file, result } of results) {\n if (result.installed) {\n console.log(`✓ ${file} → ${result.evalResult.type}`);\n } else {\n console.log(`✗ ${file}: ${result.evalResult.errors.join(', ')}`);\n }\n }\n });\n\n// --- VALIDATE (check harness integrity) ---\nprogram\n .command('validate')\n .description('Validate harness structure and configuration')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; json: boolean }) => {\n const { validateHarness } = await import('../runtime/validator.js');\n const dir = resolve(opts.dir);\n\n const result = validateHarness(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n if (result.errors.length > 0) process.exit(1);\n return;\n }\n\n // Output results\n console.log(`\\nHarness validation: ${dir}\\n`);\n\n if (result.ok.length > 0) {\n for (const msg of result.ok) {\n console.log(` ✓ ${msg}`);\n }\n }\n\n if (result.warnings.length > 0) {\n console.log();\n for (const msg of result.warnings) {\n console.log(` ⚠ ${msg}`);\n }\n }\n\n if (result.errors.length > 0) {\n console.log();\n for (const msg of result.errors) {\n console.log(` ✗ ${msg}`);\n }\n }\n\n console.log(`\\nSummary: ${result.ok.length} passed, ${result.warnings.length} warnings, ${result.errors.length} errors`);\n console.log(`Primitives: ${result.totalPrimitives} loaded${result.parseErrors.length > 0 ? `, ${result.parseErrors.length} parse error(s)` : ''}\\n`);\n\n if (result.errors.length > 0) {\n process.exit(1);\n }\n });\n\n// --- DOCTOR (validate + batch auto-fix) ---\nprogram\n .command('doctor')\n .description('Validate harness and auto-fix all fixable issues in one pass')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { doctorHarness } = await import('../runtime/validator.js');\n const dir = resolve(opts.dir);\n\n console.log(`\\nRunning doctor on: ${dir}\\n`);\n const result = doctorHarness(dir);\n\n // Show fixes first\n if (result.fixes.length > 0) {\n console.log(` Auto-fixed ${result.fixes.length} issue(s):`);\n for (const fix of result.fixes) {\n console.log(` ✓ ${fix}`);\n }\n console.log();\n }\n\n // Show remaining checks\n if (result.ok.length > 0) {\n for (const msg of result.ok) {\n console.log(` ✓ ${msg}`);\n }\n }\n\n if (result.warnings.length > 0) {\n console.log();\n for (const msg of result.warnings) {\n console.log(` ⚠ ${msg}`);\n }\n }\n\n if (result.errors.length > 0) {\n console.log();\n for (const msg of result.errors) {\n console.log(` ✗ ${msg}`);\n }\n }\n\n const fixLabel = result.fixes.length > 0 ? `, ${result.fixes.length} fixed` : '';\n console.log(`\\nSummary: ${result.ok.length} ok, ${result.warnings.length} warnings, ${result.errors.length} errors${fixLabel}`);\n console.log(`Primitives: ${result.totalPrimitives}\\n`);\n\n if (result.errors.length > 0) {\n process.exit(1);\n }\n });\n\n// --- FIX (auto-fix common issues in a capability file) ---\nprogram\n .command('fix <file>')\n .description('Auto-fix common issues in a capability markdown file (missing id, status, L0/L1)')\n .action(async (file: string) => {\n const { fixCapability } = await import('../runtime/intake.js');\n const filePath = resolve(file);\n\n const result = fixCapability(filePath);\n\n if (result.fixes_applied.length > 0) {\n console.log(`Fixed ${result.fixes_applied.length} issue(s) in ${filePath}:`);\n for (const fix of result.fixes_applied) {\n console.log(` ✓ ${fix}`);\n }\n } else {\n console.log('No auto-fixable issues found.');\n }\n\n if (result.warnings.length > 0) {\n for (const w of result.warnings) {\n console.log(` ⚠ ${w}`);\n }\n }\n\n if (result.errors.length > 0) {\n console.error(`\\nRemaining errors (manual fix required):`);\n for (const e of result.errors) {\n console.error(` ✗ ${e}`);\n }\n process.exit(1);\n }\n });\n\n// --- CLEANUP (archive or remove old sessions/journals per retention policy) ---\nprogram\n .command('cleanup')\n .description('Archive sessions and journals older than retention period')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--dry-run', 'Show what would be archived without acting', false)\n .option('--delete', 'Permanently delete instead of archiving', false)\n .action(async (opts: { dir: string; dryRun: boolean; delete: boolean }) => {\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const sessionDays = config.memory.session_retention_days;\n const journalDays = config.memory.journal_retention_days;\n\n if (opts.dryRun) {\n const { listExpiredFiles } = await import('../runtime/sessions.js');\n const expired = listExpiredFiles(dir, sessionDays, journalDays);\n const action = opts.delete ? 'delete' : 'archive';\n console.log(`\\nDry run — retention policy (sessions: ${sessionDays}d, journals: ${journalDays}d)\\n`);\n console.log(`Would ${action} ${expired.sessionFiles.length} session(s):`);\n expired.sessionFiles.forEach((f) => console.log(` - ${f}`));\n console.log(`Would ${action} ${expired.journalFiles.length} journal(s):`);\n expired.journalFiles.forEach((f) => console.log(` - ${f}`));\n return;\n }\n\n if (opts.delete) {\n const { cleanupOldFiles } = await import('../runtime/sessions.js');\n const result = cleanupOldFiles(dir, sessionDays, journalDays);\n console.log(`\\nDeleted ${result.sessionsRemoved} session(s), ${result.journalsRemoved} journal(s)`);\n if (result.sessionFiles.length > 0) {\n result.sessionFiles.forEach((f) => console.log(` - ${f}`));\n }\n if (result.journalFiles.length > 0) {\n result.journalFiles.forEach((f) => console.log(` - ${f}`));\n }\n } else {\n const { archiveOldFiles } = await import('../runtime/sessions.js');\n const result = archiveOldFiles(dir, sessionDays, journalDays);\n console.log(`\\nArchived ${result.sessionsArchived} session(s), ${result.journalsArchived} journal(s)`);\n if (result.sessionFiles.length > 0) {\n console.log(` Sessions → memory/sessions/archive/`);\n result.sessionFiles.forEach((f) => console.log(` - ${f}`));\n }\n if (result.journalFiles.length > 0) {\n console.log(` Journals → memory/journal/archive/`);\n result.journalFiles.forEach((f) => console.log(` - ${f}`));\n }\n }\n console.log();\n });\n\n// --- STATUS (rich harness overview) ---\nprogram\n .command('status')\n .description('Show harness status: primitives, sessions, config, state')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { existsSync, readdirSync } = await import('fs');\n const { validateHarness } = await import('../runtime/validator.js');\n const { loadConfig } = await import('../core/config.js');\n const { loadState } = await import('../runtime/state.js');\n const { listSessions } = await import('../runtime/sessions.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const state = loadState(dir);\n const validation = validateHarness(dir);\n const sessions = listSessions(dir);\n\n // Header\n console.log(`\\n ${config.agent.name} v${config.agent.version}`);\n console.log(` Model: ${config.model.provider}/${config.model.id}`);\n console.log(` Mode: ${state.mode}`);\n\n // Primitives\n console.log(`\\n Primitives (${validation.totalPrimitives} total):`);\n for (const [dir, count] of validation.primitiveCounts) {\n if (count > 0) console.log(` ${dir}: ${count}`);\n }\n const emptyDirs = Array.from(validation.primitiveCounts.entries())\n .filter(([, c]) => c === 0)\n .map(([d]) => d);\n if (emptyDirs.length > 0) {\n console.log(` (empty: ${emptyDirs.join(', ')})`);\n }\n\n // Sessions\n console.log(`\\n Sessions: ${sessions.length} total`);\n if (sessions.length > 0) {\n const recent = sessions.slice(0, 3);\n for (const s of recent) {\n console.log(` ${s.id}`);\n }\n if (sessions.length > 3) console.log(` ... and ${sessions.length - 3} more`);\n }\n\n // Journals\n const journalDir = join(dir, 'memory', 'journal');\n let journalCount = 0;\n if (existsSync(journalDir)) {\n journalCount = readdirSync(journalDir).filter(\n (f) => f.endsWith('.md') && !f.startsWith('.') && !f.startsWith('_'),\n ).length;\n }\n console.log(` Journals: ${journalCount}`);\n\n // MCP Servers\n const mcpServers = config.mcp?.servers ?? {};\n const mcpEntries = Object.entries(mcpServers);\n if (mcpEntries.length > 0) {\n const enabledCount = mcpEntries.filter(([, s]) => s.enabled !== false).length;\n console.log(`\\n MCP Servers: ${mcpEntries.length} configured (${enabledCount} enabled)`);\n for (const [name, serverConfig] of mcpEntries) {\n const enabled = serverConfig.enabled !== false;\n const icon = enabled ? '+' : '-';\n const detail = serverConfig.transport === 'stdio'\n ? serverConfig.command ?? ''\n : serverConfig.url ?? '';\n console.log(` [${icon}] ${name} (${serverConfig.transport}) ${detail}`);\n }\n }\n\n // State\n if (state.goals.length > 0) {\n console.log(`\\n Goals:`);\n for (const g of state.goals) {\n console.log(` - ${g}`);\n }\n }\n if (state.active_workflows.length > 0) {\n console.log(`\\n Active workflows:`);\n for (const w of state.active_workflows) {\n console.log(` - ${w}`);\n }\n }\n if (state.unfinished_business.length > 0) {\n console.log(`\\n Unfinished business:`);\n for (const u of state.unfinished_business) {\n console.log(` - ${u}`);\n }\n }\n\n // Health\n const healthIssues = validation.errors.length + validation.warnings.length;\n if (healthIssues > 0) {\n console.log(`\\n Health: ${validation.errors.length} error(s), ${validation.warnings.length} warning(s)`);\n if (validation.errors.length > 0) {\n console.log(` Run 'harness validate' for details`);\n }\n } else {\n console.log(`\\n Health: OK`);\n }\n\n console.log(` Last interaction: ${state.last_interaction}\\n`);\n });\n\n// --- SCRATCH (write to working memory) ---\nprogram\n .command('scratch')\n .description('Write a note to scratch.md (working memory)')\n .argument('<note...>', 'Note to write')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--clear', 'Clear scratch before writing', false)\n .option('--show', 'Show current scratch contents', false)\n .action(async (note: string[], opts: { dir: string; clear: boolean; show: boolean }) => {\n const { readFileSync, writeFileSync, existsSync, mkdirSync } = await import('fs');\n const scratchPath = join(resolve(opts.dir), 'memory', 'scratch.md');\n const memoryDir = join(resolve(opts.dir), 'memory');\n\n if (!existsSync(memoryDir)) {\n mkdirSync(memoryDir, { recursive: true });\n }\n\n if (opts.show) {\n if (existsSync(scratchPath)) {\n const content = readFileSync(scratchPath, 'utf-8');\n console.log(content || '(empty)');\n } else {\n console.log('(no scratch.md)');\n }\n return;\n }\n\n const noteText = note.join(' ');\n\n if (opts.clear) {\n writeFileSync(scratchPath, noteText + '\\n', 'utf-8');\n console.log('✓ Scratch cleared and updated');\n } else {\n const existing = existsSync(scratchPath) ? readFileSync(scratchPath, 'utf-8') : '';\n const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 19);\n const entry = `[${timestamp}] ${noteText}\\n`;\n writeFileSync(scratchPath, existing + entry, 'utf-8');\n console.log('✓ Note added to scratch');\n }\n });\n\n// --- WORKFLOW (list and run workflows) ---\nconst workflowCmd = program\n .command('workflow')\n .description('Manage workflows');\n\nworkflowCmd\n .command('list')\n .description('List all workflows and their schedules')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { loadDirectory } = await import('../primitives/loader.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const workflowDir = join(dir, 'workflows');\n if (!existsSync(workflowDir)) {\n console.log('\\nNo workflows/ directory. Create workflow files to enable scheduling.\\n');\n return;\n }\n\n const docs = loadDirectory(workflowDir);\n if (docs.length === 0) {\n console.log('\\nNo workflows defined.\\n');\n return;\n }\n\n console.log(`\\n${docs.length} workflow(s):\\n`);\n for (const doc of docs) {\n const schedule = doc.frontmatter.schedule || '(no schedule)';\n const status = doc.frontmatter.status === 'active' ? '' : ` [${doc.frontmatter.status}]`;\n const withAgent = doc.frontmatter.with ? ` → ${doc.frontmatter.with}` : '';\n console.log(` ${doc.frontmatter.id}${status}`);\n console.log(` Schedule: ${schedule}${withAgent}`);\n if (doc.l0) console.log(` ${doc.l0}`);\n }\n console.log();\n });\n\nworkflowCmd\n .command('run <id>')\n .description('Execute a workflow by ID (bypasses quiet hours)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (workflowId: string, opts: { dir: string }) => {\n const { Scheduler } = await import('../runtime/scheduler.js');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n requireHarness(dir);\n\n console.log(`\\nExecuting workflow: ${workflowId}...`);\n const scheduler = new Scheduler({\n harnessDir: dir,\n autoArchival: false,\n });\n\n try {\n const result = await scheduler.runOnce(workflowId);\n console.log(`\\n✓ Workflow \"${workflowId}\" complete.\\n`);\n if (result) {\n console.log(result.slice(0, 500));\n if (result.length > 500) console.log(`\\n... (${result.length} chars total)`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`\\n✗ Workflow failed: ${msg}\\n`);\n process.exit(1);\n }\n });\n\n// --- SEARCH (find primitives by query/filters) ---\nprogram\n .command('search [query]')\n .description('Search primitives by text query and/or filters')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-t, --tag <tag>', 'Filter by tag')\n .option('--type <type>', 'Filter by primitive type (e.g., rules, skills)')\n .option('--status <status>', 'Filter by status (active, draft, archived, deprecated)')\n .option('--author <author>', 'Filter by author (human, agent, infrastructure)')\n .option('--json', 'Output as JSON')\n .action(async (query: string | undefined, opts: { dir: string; tag?: string; type?: string; status?: string; author?: string; json: boolean }) => {\n const { searchPrimitives } = await import('../runtime/search.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try {\n config = loadConfig(dir);\n } catch (err) {\n if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const results = searchPrimitives(dir, query, {\n tag: opts.tag,\n type: opts.type,\n status: opts.status,\n author: opts.author,\n }, config);\n\n if (opts.json) {\n console.log(JSON.stringify(results.map((r) => ({\n id: r.doc.frontmatter.id,\n directory: r.directory,\n status: r.doc.frontmatter.status,\n tags: r.doc.frontmatter.tags,\n l0: r.doc.l0,\n matchReason: r.matchReason,\n })), null, 2));\n return;\n }\n\n if (results.length === 0) {\n const filters = [query, opts.tag && `tag:${opts.tag}`, opts.type && `type:${opts.type}`, opts.status && `status:${opts.status}`, opts.author && `author:${opts.author}`].filter(Boolean).join(', ');\n console.log(`\\nNo results for: ${filters || '(no filters)'}\\n`);\n return;\n }\n\n console.log(`\\n${results.length} result(s):\\n`);\n for (const r of results) {\n const tags = r.doc.frontmatter.tags.length > 0 ? ` [${r.doc.frontmatter.tags.join(', ')}]` : '';\n const status = r.doc.frontmatter.status !== 'active' ? ` (${r.doc.frontmatter.status})` : '';\n console.log(` ${r.directory}/${r.doc.frontmatter.id}${status}${tags}`);\n console.log(` ${r.matchReason}`);\n if (r.doc.l0) console.log(` ${r.doc.l0}`);\n }\n console.log();\n });\n\n// --- CONFIG (show/get configuration) ---\nconst configCmd = program\n .command('config')\n .description('Show or inspect configuration');\n\nconfigCmd\n .command('show')\n .description('Show full resolved configuration (merged defaults + file + env)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const YAML = await import('yaml');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n const config = loadConfig(dir);\n console.log(`\\n# Resolved config for: ${dir}\\n`);\n console.log(YAML.stringify(config).trimEnd());\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nconfigCmd\n .command('get <key>')\n .description('Get a specific config value (dot-notation, e.g. model.id)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (key: string, opts: { dir: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n const config = loadConfig(dir);\n const parts = key.split('.');\n let value: unknown = config;\n for (const part of parts) {\n if (value === null || value === undefined || typeof value !== 'object') {\n console.error(`Error: Key \"${key}\" not found (stopped at \"${part}\")`);\n process.exit(1);\n }\n value = (value as Record<string, unknown>)[part];\n }\n\n if (value === undefined) {\n console.error(`Error: Key \"${key}\" not found`);\n process.exit(1);\n }\n\n if (typeof value === 'object' && value !== null) {\n const YAML = await import('yaml');\n console.log(YAML.stringify(value).trimEnd());\n } else {\n console.log(String(value));\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nconfigCmd\n .command('set <key> <value>')\n .description('Set a config value (writes to config.yaml)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (key: string, value: string, opts: { dir: string }) => {\n const { readFileSync, writeFileSync, existsSync } = await import('fs');\n const YAML = await import('yaml');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const configPath = join(dir, 'config.yaml');\n if (!existsSync(configPath)) {\n console.error(`Error: No config.yaml found in ${dir}`);\n process.exit(1);\n }\n\n try {\n const content = readFileSync(configPath, 'utf-8');\n const doc = YAML.parseDocument(content);\n\n // Parse the value — attempt number/boolean coercion\n let parsed: unknown = value;\n if (value === 'true') parsed = true;\n else if (value === 'false') parsed = false;\n else if (/^\\d+$/.test(value)) parsed = parseInt(value, 10);\n else if (/^\\d+\\.\\d+$/.test(value)) parsed = parseFloat(value);\n\n // Set using dot-notation path\n const parts = key.split('.');\n doc.setIn(parts, parsed);\n\n writeFileSync(configPath, doc.toString(), 'utf-8');\n\n // Validate the resulting config\n const { loadConfig } = await import('../core/config.js');\n try {\n loadConfig(dir);\n console.log(`✓ ${key} = ${String(parsed)}`);\n } catch (err: unknown) {\n console.error(`Warning: Config saved but validation failed: ${formatError(err)}`);\n console.error(`You may want to revert: harness config set ${key} <previous-value>`);\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- METRICS (workflow execution stats) ---\nconst metricsCmd = program\n .command('metrics')\n .description('View workflow execution metrics and stats');\n\nmetricsCmd\n .command('show')\n .description('Show stats for all workflows (default)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--workflow <id>', 'Show stats for a specific workflow')\n .action(async (opts: { dir: string; workflow?: string }) => {\n const { getAllWorkflowStats, getWorkflowStats } = await import('../runtime/metrics.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n if (opts.workflow) {\n const stats = getWorkflowStats(dir, opts.workflow);\n if (!stats) {\n console.log(`\\nNo metrics recorded for workflow \"${opts.workflow}\".\\n`);\n return;\n }\n console.log(`\\nWorkflow: ${stats.workflow_id}\\n`);\n console.log(` Runs: ${stats.total_runs}`);\n console.log(` Successes: ${stats.successes}`);\n console.log(` Failures: ${stats.failures}`);\n console.log(` Success rate: ${(stats.success_rate * 100).toFixed(1)}%`);\n console.log(` Avg duration: ${formatDuration(stats.avg_duration_ms)}`);\n console.log(` Total tokens: ${stats.total_tokens}`);\n console.log(` Last run: ${stats.last_run}`);\n if (stats.last_success) console.log(` Last success: ${stats.last_success}`);\n if (stats.last_failure) console.log(` Last failure: ${stats.last_failure}`);\n console.log();\n return;\n }\n\n const allStats = getAllWorkflowStats(dir);\n if (allStats.length === 0) {\n console.log('\\nNo workflow metrics recorded yet.\\n');\n console.log('Metrics are automatically recorded when workflows run via scheduler or `harness workflow run`.\\n');\n return;\n }\n\n console.log(`\\n${allStats.length} workflow(s) with metrics:\\n`);\n for (const stats of allStats) {\n const rate = (stats.success_rate * 100).toFixed(0);\n console.log(` ${stats.workflow_id}`);\n console.log(` ${stats.total_runs} runs (${rate}% success) | avg ${formatDuration(stats.avg_duration_ms)} | ${stats.total_tokens} tokens`);\n console.log(` Last: ${stats.last_run}`);\n }\n console.log();\n });\n\nmetricsCmd\n .command('clear')\n .description('Clear metrics for a specific workflow or all workflows')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--workflow <id>', 'Clear only this workflow (clears all if omitted)')\n .action(async (opts: { dir: string; workflow?: string }) => {\n const { clearMetrics } = await import('../runtime/metrics.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const removed = clearMetrics(dir, opts.workflow);\n if (opts.workflow) {\n console.log(`Cleared ${removed} metric(s) for workflow \"${opts.workflow}\".`);\n } else {\n console.log(`Cleared ${removed} total metric(s).`);\n }\n });\n\nmetricsCmd\n .command('history')\n .description('Show recent workflow run history')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--workflow <id>', 'Filter by workflow ID')\n .option('-n, --limit <count>', 'Number of recent runs to show', '10')\n .action(async (opts: { dir: string; workflow?: string; limit: string }) => {\n const { loadMetrics } = await import('../runtime/metrics.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const store = loadMetrics(dir);\n let runs = store.runs;\n\n if (opts.workflow) {\n runs = runs.filter((r) => r.workflow_id === opts.workflow);\n }\n\n const limit = parseInt(opts.limit, 10) || 10;\n const recent = runs.slice(-limit).reverse();\n\n if (recent.length === 0) {\n console.log('\\nNo workflow runs recorded.\\n');\n return;\n }\n\n console.log(`\\n${recent.length} recent run(s)${opts.workflow ? ` for \"${opts.workflow}\"` : ''}:\\n`);\n for (const run of recent) {\n const status = run.success ? 'OK' : 'FAIL';\n const tokens = run.tokens_used ? ` | ${run.tokens_used} tokens` : '';\n const retries = run.attempt > 1 ? ` (attempt ${run.attempt}/${run.max_retries + 1})` : '';\n const error = run.error ? `\\n Error: ${run.error.slice(0, 100)}` : '';\n console.log(` [${status}] ${run.workflow_id} — ${formatDuration(run.duration_ms)}${tokens}${retries}`);\n console.log(` ${run.started}${error}`);\n }\n console.log();\n });\n\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${ms}ms`;\n if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;\n const minutes = Math.floor(ms / 60000);\n const seconds = Math.round((ms % 60000) / 1000);\n return `${minutes}m${seconds}s`;\n}\n\n// --- TOOLS (list and inspect tool definitions) ---\nconst toolsCmd = program\n .command('tools')\n .description('List and inspect tool definitions');\n\ntoolsCmd\n .command('list')\n .description('List all defined tools with auth status')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { listToolSummaries } = await import('../runtime/tools.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const tools = listToolSummaries(dir);\n if (tools.length === 0) {\n console.log('\\nNo tools defined. Create tool files in tools/ to register external services.\\n');\n return;\n }\n\n console.log(`\\n${tools.length} tool(s):\\n`);\n for (const tool of tools) {\n const auth = tool.authReady ? 'ready' : 'missing auth';\n const status = tool.status !== 'active' ? ` [${tool.status}]` : '';\n console.log(` ${tool.id}${status} (${auth})`);\n if (tool.l0) console.log(` ${tool.l0}`);\n console.log(` ${tool.operationCount} operation(s) | tags: ${tool.tags.join(', ') || 'none'}`);\n }\n console.log();\n });\n\ntoolsCmd\n .command('show <id>')\n .description('Show detailed info for a specific tool')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (toolId: string, opts: { dir: string }) => {\n const { getToolById } = await import('../runtime/tools.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const tool = getToolById(dir, toolId);\n if (!tool) {\n console.error(`Tool not found: ${toolId}`);\n process.exit(1);\n }\n\n console.log(`\\nTool: ${tool.id}`);\n console.log(` Status: ${tool.status}`);\n console.log(` Tags: ${tool.tags.join(', ') || 'none'}`);\n\n if (tool.auth.length > 0) {\n console.log(`\\n Authentication:`);\n for (const a of tool.auth) {\n const status = a.present ? 'set' : 'MISSING';\n console.log(` ${a.envVar}: ${status}`);\n }\n }\n\n if (tool.operations.length > 0) {\n console.log(`\\n Operations (${tool.operations.length}):`);\n for (const op of tool.operations) {\n console.log(` ${op.method} ${op.endpoint}`);\n }\n }\n\n if (tool.rateLimits.length > 0) {\n console.log(`\\n Rate Limits:`);\n for (const rl of tool.rateLimits) {\n console.log(` - ${rl}`);\n }\n }\n\n if (tool.gotchas.length > 0) {\n console.log(`\\n Gotchas:`);\n for (const g of tool.gotchas) {\n console.log(` - ${g}`);\n }\n }\n console.log();\n });\n\ntoolsCmd\n .command('auth')\n .description('Check auth status for all tools')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { checkToolAuth } = await import('../runtime/tools.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const results = checkToolAuth(dir);\n if (results.length === 0) {\n console.log('\\nNo tools defined.\\n');\n return;\n }\n\n console.log('\\nTool auth status:\\n');\n for (const { tool, auth } of results) {\n if (auth.length === 0) {\n console.log(` ${tool}: no auth required`);\n continue;\n }\n const allPresent = auth.every((a) => a.present);\n console.log(` ${tool}: ${allPresent ? 'ready' : 'INCOMPLETE'}`);\n for (const a of auth) {\n const icon = a.present ? 'set' : 'MISSING';\n console.log(` ${a.envVar}: ${icon}`);\n }\n }\n console.log();\n });\n\n// --- EXPORT (data portability) ---\nprogram\n .command('export [output]')\n .description('Export harness to a portable JSON bundle')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--no-sessions', 'Exclude session files')\n .option('--no-journals', 'Exclude journal files')\n .option('--no-metrics', 'Exclude metrics')\n .option('--no-state', 'Exclude state and scratch')\n .action(async (output: string | undefined, opts: { dir: string; sessions: boolean; journals: boolean; metrics: boolean; state: boolean }) => {\n const { exportHarness, writeBundle } = await import('../runtime/export.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const bundle = exportHarness(dir, {\n sessions: opts.sessions,\n journals: opts.journals,\n metrics: opts.metrics,\n state: opts.state,\n });\n\n const outputPath = output ? resolve(output) : resolve(`${bundle.agent_name}-export.json`);\n writeBundle(bundle, outputPath);\n\n const { metadata } = bundle;\n console.log(`\\nExported \"${bundle.agent_name}\" to ${outputPath}`);\n console.log(` ${bundle.entries.length} files (${metadata.primitives} primitives, ${metadata.sessions} sessions, ${metadata.journals} journals)\\n`);\n });\n\n// --- IMPORT (data portability) ---\nprogram\n .command('import <bundle>')\n .description('Import a harness bundle into current directory')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--overwrite', 'Overwrite existing files', false)\n .action(async (bundlePath: string, opts: { dir: string; overwrite: boolean }) => {\n const { readBundle, importBundle } = await import('../runtime/export.js');\n const dir = resolve(opts.dir);\n\n try {\n const bundle = readBundle(resolve(bundlePath));\n console.log(`\\nImporting bundle: \"${bundle.agent_name}\" (exported ${bundle.exported_at})`);\n console.log(` ${bundle.entries.length} files in bundle\\n`);\n\n const result = importBundle(dir, bundle, { overwrite: opts.overwrite });\n\n console.log(` Imported: ${result.imported}`);\n console.log(` Skipped (exists): ${result.skipped}`);\n if (result.errors.length > 0) {\n console.log(` Errors: ${result.errors.length}`);\n for (const err of result.errors) {\n console.log(` - ${err}`);\n }\n }\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- BUNDLE (pack primitives into shareable bundle) ---\nprogram\n .command('bundle <output>')\n .description('Pack primitives into a shareable bundle with manifest.yaml')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-n, --name <name>', 'Bundle name')\n .option('--description <text>', 'Bundle description', '')\n .option('--author <name>', 'Author name')\n .option('--version <ver>', 'Bundle version', '1.0.0')\n .option('-t, --types <types...>', 'Primitive types to include (e.g., rules instincts)')\n .option('-f, --files <files...>', 'Specific files to include (relative paths)')\n .option('--tags <tags...>', 'Tags for search/discovery')\n .option('--license <id>', 'License identifier (e.g., MIT)')\n .option('--json', 'Output as JSON', false)\n .action(async (output: string, opts: { dir: string; name?: string; description: string; author?: string; version: string; types?: string[]; files?: string[]; tags?: string[]; license?: string; json: boolean }) => {\n const { packBundle, writeBundleDir } = await import('../runtime/primitive-registry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const bundleName = opts.name ?? basename(dir);\n const bundle = packBundle(dir, {\n name: bundleName,\n description: opts.description,\n author: opts.author,\n version: opts.version,\n types: opts.types,\n files: opts.files,\n tags: opts.tags,\n license: opts.license,\n });\n\n const outputPath = resolve(output);\n writeBundleDir(bundle, outputPath);\n\n if (opts.json) {\n console.log(JSON.stringify(bundle.manifest, null, 2));\n } else {\n console.log(`\\nBundled \"${bundleName}\" v${opts.version}`);\n console.log(` ${bundle.files.length} files in ${bundle.manifest.types.join(', ')}`);\n console.log(` Output: ${outputPath}/`);\n console.log(` Manifest: ${outputPath}/manifest.yaml\\n`);\n }\n });\n\n// --- BUNDLE INSTALL (install from bundle directory or URL) ---\nprogram\n .command('bundle-install <source>')\n .description('Install primitives from a bundle directory, JSON file, or URL')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--overwrite', 'Overwrite existing files', false)\n .option('--force', 'Skip dependency checks', false)\n .option('--json', 'Output as JSON', false)\n .action(async (source: string, opts: { dir: string; overwrite: boolean; force: boolean; json: boolean }) => {\n const { readBundleDir, installBundle, fetchRemoteBundle } = await import('../runtime/primitive-registry.js');\n const { readBundle } = await import('../runtime/export.js');\n const dir = resolve(opts.dir);\n\n try {\n let bundle;\n\n if (source.startsWith('https://') || source.startsWith('http://')) {\n console.log(`Downloading bundle from ${source}...`);\n bundle = await fetchRemoteBundle(source);\n } else {\n const sourcePath = resolve(source);\n // Check if it's a directory with manifest.yaml\n if (existsSync(join(sourcePath, 'manifest.yaml'))) {\n bundle = readBundleDir(sourcePath);\n } else if (source.endsWith('.json')) {\n // Legacy JSON bundle — convert\n const jsonBundle = readBundle(sourcePath);\n const { CORE_PRIMITIVE_DIRS } = await import('../core/types.js');\n const files = jsonBundle.entries;\n const types = new Set<string>();\n for (const entry of files) {\n const entryDir = entry.path.split('/')[0];\n if ((CORE_PRIMITIVE_DIRS as readonly string[]).includes(entryDir)) types.add(entryDir);\n }\n bundle = {\n manifest: {\n version: '1.0',\n name: jsonBundle.agent_name ?? 'imported',\n description: 'Imported from JSON bundle',\n author: 'unknown',\n bundle_version: '1.0.0',\n created: jsonBundle.exported_at ?? new Date().toISOString(),\n types: [...types],\n tags: [],\n files: files.map((f) => ({ path: f.path, type: f.path.split('/')[0], id: basename(f.path, '.md'), l0: '' })),\n },\n files,\n };\n } else {\n console.error(`Error: ${sourcePath} is not a bundle directory (no manifest.yaml) or JSON file`);\n process.exit(1);\n }\n }\n\n const result = installBundle(dir, bundle, { overwrite: opts.overwrite, force: opts.force });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.installed) {\n console.log(`\\nInstalled \"${result.name}\"`);\n console.log(` Files: ${result.files.length} installed, ${result.skipped.length} skipped`);\n if (result.files.length > 0) {\n for (const f of result.files) console.log(` + ${f}`);\n }\n if (result.skipped.length > 0) {\n for (const f of result.skipped) console.log(` = ${f} (exists)`);\n }\n } else {\n console.error(`\\nInstallation failed:`);\n for (const err of result.errors) console.error(` - ${err}`);\n }\n console.log();\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- UNINSTALL (soft-delete primitives) ---\nprogram\n .command('uninstall <bundle-name>')\n .description('Uninstall a previously installed bundle (moves files to archive/)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--hard', 'Permanently delete files instead of archiving', false)\n .option('--json', 'Output as JSON', false)\n .action(async (bundleName: string, opts: { dir: string; hard: boolean; json: boolean }) => {\n const { uninstallBundle } = await import('../runtime/primitive-registry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const result = uninstallBundle(dir, bundleName, { hard: opts.hard });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.uninstalled) {\n console.log(`\\nUninstalled \"${bundleName}\"`);\n console.log(` ${result.archived.length} files ${opts.hard ? 'deleted' : 'archived'}`);\n for (const f of result.archived) console.log(` - ${f}`);\n } else {\n console.error(`\\nUninstall failed:`);\n for (const err of result.errors) console.error(` - ${err}`);\n if (result.dependents.length > 0) {\n console.error(` Dependents: ${result.dependents.join(', ')}`);\n }\n }\n console.log();\n }\n });\n\n// --- UPDATE (update installed bundle) ---\nprogram\n .command('update <source>')\n .description('Update an installed bundle from a new version')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--remove-deleted', 'Archive files removed in new version', false)\n .option('--json', 'Output as JSON', false)\n .action(async (source: string, opts: { dir: string; removeDeleted: boolean; json: boolean }) => {\n const { readBundleDir, diffBundle, updateBundle, fetchRemoteBundle } = await import('../runtime/primitive-registry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n let bundle;\n\n if (source.startsWith('https://') || source.startsWith('http://')) {\n console.log(`Downloading bundle from ${source}...`);\n bundle = await fetchRemoteBundle(source);\n } else {\n const sourcePath = resolve(source);\n if (!existsSync(join(sourcePath, 'manifest.yaml'))) {\n console.error(`Error: ${sourcePath} is not a bundle directory (no manifest.yaml)`);\n process.exit(1);\n }\n bundle = readBundleDir(sourcePath);\n }\n\n // Show diff first\n const diff = diffBundle(dir, bundle);\n if (diff.added.length === 0 && diff.modified.length === 0 && diff.removed.length === 0) {\n console.log(`\\n\"${bundle.manifest.name}\" is already up to date.\\n`);\n return;\n }\n\n if (!opts.json) {\n console.log(`\\nUpdate \"${bundle.manifest.name}\" to v${bundle.manifest.bundle_version}:`);\n if (diff.added.length > 0) {\n console.log(` Added (${diff.added.length}):`);\n for (const f of diff.added) console.log(` + ${f}`);\n }\n if (diff.modified.length > 0) {\n console.log(` Modified (${diff.modified.length}):`);\n for (const f of diff.modified) console.log(` ~ ${f}`);\n }\n if (diff.removed.length > 0) {\n console.log(` Removed (${diff.removed.length}):`);\n for (const f of diff.removed) console.log(` - ${f}`);\n }\n console.log();\n }\n\n const result = updateBundle(dir, bundle, { removeDeleted: opts.removeDeleted });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.updated) {\n console.log(`Updated \"${result.name}\" ${result.oldVersion ?? '?'} → ${result.newVersion ?? '?'}`);\n console.log(` ${result.added.length} added, ${result.modified.length} modified, ${result.removed.length} removed`);\n } else {\n console.error(`Update failed:`);\n for (const err of result.errors) console.error(` - ${err}`);\n }\n console.log();\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- INSTALLED (list installed bundles) ---\nprogram\n .command('installed')\n .description('List installed bundles')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { listInstalledBundles } = await import('../runtime/primitive-registry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const bundles = listInstalledBundles(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(bundles, null, 2));\n } else {\n if (bundles.length === 0) {\n console.log('\\nNo bundles installed.\\n');\n } else {\n console.log(`\\n${bundles.length} bundle(s) installed:\\n`);\n for (const b of bundles) {\n console.log(` ${b.name} v${b.version} — ${b.description}`);\n console.log(` ${b.fileCount} files, types: ${b.types.join(', ')}`);\n }\n console.log();\n }\n }\n });\n\n// --- REGISTRY (search/install from configured registries) ---\nconst registryCmd = program.command('registry').description('Search and install bundles from configured registries');\n\nregistryCmd\n .command('search <query>')\n .description('Search all configured registries for bundles')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--limit <n>', 'Max results', '20')\n .option('--json', 'Output as JSON', false)\n .action(async (query: string, opts: { dir: string; limit: string; json: boolean }) => {\n const { searchConfiguredRegistries } = await import('../runtime/primitive-registry.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const registries = config.registries ?? [];\n if (registries.length === 0) {\n console.error('No registries configured. Add registries: to config.yaml');\n process.exit(1);\n }\n\n try {\n const result = await searchConfiguredRegistries(registries, query, { limit: parseInt(opts.limit, 10) });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nSearched ${result.registriesSearched} registry(ies) for \"${query}\"\\n`);\n\n if (result.errors.length > 0) {\n for (const err of result.errors) {\n console.log(` [warn] ${err.registry}: ${err.error}`);\n }\n console.log();\n }\n\n if (result.results.length === 0) {\n console.log('No bundles found.\\n');\n return;\n }\n\n for (const r of result.results) {\n console.log(` ${r.name} v${r.version} — ${r.description}`);\n console.log(` types: ${r.types.join(', ')} | tags: ${r.tags.join(', ') || 'none'} | from: ${r.registryName}`);\n }\n console.log(`\\n ${result.total} result(s) total\\n`);\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nregistryCmd\n .command('install <bundle-name>')\n .description('Install a bundle from configured registries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--version <ver>', 'Specific version to install')\n .option('--overwrite', 'Overwrite existing files', false)\n .option('--force', 'Skip dependency checks', false)\n .option('--json', 'Output as JSON', false)\n .action(async (bundleName: string, opts: { dir: string; version?: string; overwrite: boolean; force: boolean; json: boolean }) => {\n const { installFromRegistry } = await import('../runtime/primitive-registry.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const registries = config.registries ?? [];\n if (registries.length === 0) {\n console.error('No registries configured. Add registries: to config.yaml');\n process.exit(1);\n }\n\n try {\n console.log(`\\nSearching registries for \"${bundleName}\"...`);\n const result = await installFromRegistry(dir, registries, bundleName, {\n version: opts.version,\n overwrite: opts.overwrite,\n force: opts.force,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (result.installed) {\n console.log(`Installed \"${result.name}\" from ${result.registryUrl ?? 'registry'}`);\n console.log(` Files: ${result.files.length} installed, ${result.skipped.length} skipped`);\n if (result.files.length > 0) {\n for (const f of result.files) console.log(` + ${f}`);\n }\n if (result.skipped.length > 0) {\n for (const f of result.skipped) console.log(` = ${f} (exists)`);\n }\n } else {\n console.error(`\\nInstallation failed:`);\n for (const err of result.errors) console.error(` - ${err}`);\n }\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nregistryCmd\n .command('list')\n .description('List configured registries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const registries = config.registries ?? [];\n\n if (opts.json) {\n console.log(JSON.stringify(registries, null, 2));\n return;\n }\n\n if (registries.length === 0) {\n console.log('\\nNo registries configured.');\n console.log('Add to config.yaml:\\n');\n console.log(' registries:');\n console.log(' - url: https://registry.example.com');\n console.log(' name: My Registry\\n');\n return;\n }\n\n console.log(`\\n${registries.length} registry(ies) configured:\\n`);\n for (const reg of registries) {\n const name = reg.name ?? reg.url;\n const auth = reg.token ? ' (authenticated)' : '';\n console.log(` ${name}${auth}`);\n console.log(` ${reg.url}`);\n }\n console.log();\n });\n\n// --- GRAPH (dependency analysis) ---\nprogram\n .command('graph')\n .description('Analyze primitive dependency graph (related:/with: fields)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; json: boolean }) => {\n const { buildDependencyGraph, getGraphStats } = await import('../runtime/graph.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const graph = buildDependencyGraph(dir, config);\n const stats = getGraphStats(dir, config);\n\n if (opts.json) {\n console.log(JSON.stringify({ graph, stats }, null, 2));\n return;\n }\n\n console.log(`\\nDependency Graph\\n`);\n console.log(` Nodes: ${stats.totalNodes}`);\n console.log(` Edges: ${stats.totalEdges}`);\n console.log(` Clusters: ${stats.clusterCount}`);\n console.log(` Orphans: ${stats.orphanCount}`);\n\n if (stats.mostConnected.length > 0) {\n console.log(`\\n Most connected:`);\n for (const mc of stats.mostConnected) {\n console.log(` ${mc.id}: ${mc.connections} connection(s)`);\n }\n }\n\n if (graph.orphans.length > 0) {\n console.log(`\\n Orphaned primitives (no relationships):`);\n for (const id of graph.orphans) {\n const node = graph.nodes.find((n) => n.id === id);\n console.log(` ${id} (${node?.directory || 'unknown'})`);\n }\n }\n\n if (stats.brokenRefs.length > 0) {\n console.log(`\\n Broken references:`);\n for (const br of stats.brokenRefs) {\n console.log(` ${br.from} -> \"${br.ref}\" (not found)`);\n }\n }\n\n if (graph.clusters.length > 0) {\n console.log(`\\n Clusters:`);\n for (let i = 0; i < graph.clusters.length; i++) {\n const cluster = graph.clusters[i];\n console.log(` [${i + 1}] ${cluster.join(', ')}`);\n }\n }\n\n console.log();\n });\n\n// --- ANALYTICS (session statistics) ---\nprogram\n .command('analytics')\n .description('Show session analytics and usage patterns')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; from?: string; to?: string; json: boolean }) => {\n const { getSessionAnalytics, getSessionsInRange } = await import('../runtime/analytics.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n if (opts.from || opts.to) {\n const sessions = getSessionsInRange(dir, opts.from, opts.to);\n const label = opts.from && opts.to ? `${opts.from} to ${opts.to}` : opts.from ? `from ${opts.from}` : `to ${opts.to}`;\n\n if (opts.json) {\n console.log(JSON.stringify({ range: label, sessions }, null, 2));\n return;\n }\n\n if (sessions.length === 0) {\n console.log(`\\nNo sessions found for ${label}.\\n`);\n return;\n }\n\n const totalTokens = sessions.reduce((sum, s) => sum + s.tokens, 0);\n console.log(`\\n${sessions.length} session(s) ${label}:\\n`);\n for (const s of sessions) {\n const model = s.model ? ` [${s.model}]` : '';\n const delegate = s.delegatedTo ? ` -> ${s.delegatedTo}` : '';\n console.log(` ${s.id}: ${s.tokens} tokens, ${s.durationMinutes}min${model}${delegate}`);\n }\n console.log(`\\n Total: ${totalTokens} tokens\\n`);\n return;\n }\n\n const analytics = getSessionAnalytics(dir);\n\n if (opts.json) {\n // Convert Map to plain object for JSON serialization\n const serializable = {\n ...analytics,\n modelUsage: Object.fromEntries(analytics.modelUsage),\n };\n console.log(JSON.stringify(serializable, null, 2));\n return;\n }\n\n if (analytics.totalSessions === 0) {\n console.log('\\nNo sessions recorded yet.\\n');\n return;\n }\n\n console.log(`\\nSession Analytics\\n`);\n console.log(` Total sessions: ${analytics.totalSessions}`);\n console.log(` Total tokens: ${analytics.totalTokens.toLocaleString()}`);\n console.log(` Avg tokens: ${analytics.avgTokensPerSession.toLocaleString()}/session`);\n console.log(` Avg duration: ${analytics.avgDurationMinutes}min/session`);\n console.log(` Delegations: ${analytics.delegationCount}`);\n\n if (analytics.dateRange) {\n console.log(` Date range: ${analytics.dateRange.earliest} to ${analytics.dateRange.latest}`);\n }\n\n if (analytics.modelUsage.size > 0) {\n console.log(`\\n Model usage:`);\n const sorted = Array.from(analytics.modelUsage.entries()).sort((a, b) => b[1] - a[1]);\n for (const [model, count] of sorted) {\n console.log(` ${model}: ${count} session(s)`);\n }\n }\n\n if (analytics.topDays.length > 0) {\n console.log(`\\n Busiest days:`);\n for (const day of analytics.topDays) {\n console.log(` ${day.date}: ${day.sessions} session(s), ${day.tokens.toLocaleString()} tokens`);\n }\n }\n\n console.log();\n });\n\n// --- INTELLIGENCE (auto-promote, dead detection, contradictions, enrichment) ---\n\nprogram\n .command('auto-promote')\n .description('Find instinct patterns appearing 3+ times across journals and optionally install them')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--threshold <n>', 'Minimum occurrences across different dates', '3')\n .option('--install', 'Auto-install promoted instincts', false)\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; threshold: string; install: boolean; json: boolean }) => {\n const { autoPromoteInstincts } = await import('../runtime/intelligence.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const result = autoPromoteInstincts(dir, {\n threshold: parseInt(opts.threshold, 10),\n install: opts.install,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nScanned ${result.journalsScanned} journal(s)\\n`);\n\n if (result.patterns.length === 0) {\n console.log('No patterns found meeting the threshold.\\n');\n return;\n }\n\n console.log(`${result.patterns.length} pattern(s) found:\\n`);\n for (const p of result.patterns) {\n const status = result.promoted.includes(behaviorToCliId(p.behavior))\n ? '✓ promoted'\n : result.skipped.includes(behaviorToCliId(p.behavior))\n ? '⊘ exists'\n : '○ candidate';\n console.log(` [${status}] ${p.behavior}`);\n console.log(` ${p.count}x across: ${p.journalDates.join(', ')}\\n`);\n }\n\n if (!opts.install && result.patterns.length > 0) {\n console.log('Run with --install to create instinct files.\\n');\n }\n });\n\nfunction behaviorToCliId(behavior: string): string {\n return behavior.toLowerCase().replace(/[^a-z0-9\\s-]/g, '').replace(/\\s+/g, '-').slice(0, 50).replace(/-+$/, '');\n}\n\nprogram\n .command('dead-primitives')\n .description('Detect orphaned primitives not modified in 30+ days')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--days <n>', 'Threshold days since last modification', '30')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; days: string; json: boolean }) => {\n const { detectDeadPrimitives } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = detectDeadPrimitives(dir, config, {\n thresholdDays: parseInt(opts.days, 10),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nScanned ${result.totalScanned} primitive(s) (threshold: ${result.thresholdDays} days)\\n`);\n\n if (result.dead.length === 0) {\n console.log('No dead primitives found.\\n');\n return;\n }\n\n console.log(`${result.dead.length} dead primitive(s):\\n`);\n for (const d of result.dead) {\n console.log(` ${d.id} (${d.directory})`);\n console.log(` ${d.path} — last modified ${d.lastModified} (${d.daysSinceModified}d ago)\\n`);\n }\n });\n\nprogram\n .command('contradictions')\n .description('Detect contradictions between rules and instincts')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { detectContradictions } = await import('../runtime/intelligence.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const result = detectContradictions(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nChecked ${result.rulesChecked} rule(s) and ${result.instinctsChecked} instinct(s)\\n`);\n\n if (result.contradictions.length === 0) {\n console.log('No contradictions detected.\\n');\n return;\n }\n\n console.log(`${result.contradictions.length} contradiction(s) found:\\n`);\n for (const c of result.contradictions) {\n console.log(` [${c.severity}] ${c.reason}`);\n console.log(` ${c.primitiveA.type}/${c.primitiveA.id}: \"${c.primitiveA.text}\"`);\n console.log(` ${c.primitiveB.type}/${c.primitiveB.id}: \"${c.primitiveB.text}\"\\n`);\n }\n });\n\nprogram\n .command('enrich')\n .description('Enrich sessions with extracted topics, tools, and primitive references')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; from?: string; to?: string; json: boolean }) => {\n const { enrichSessions } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = enrichSessions(dir, config, { from: opts.from, to: opts.to });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nEnriched ${result.sessionsScanned} session(s)\\n`);\n\n if (result.enriched.length === 0) {\n console.log('No sessions to enrich.\\n');\n return;\n }\n\n for (const s of result.enriched) {\n console.log(` ${s.sessionId}`);\n if (s.topics.length > 0) console.log(` topics: ${s.topics.join(', ')}`);\n if (s.toolsUsed.length > 0) console.log(` tools: ${s.toolsUsed.join(', ')}`);\n if (s.primitivesReferenced.length > 0) console.log(` refs: ${s.primitivesReferenced.join(', ')}`);\n console.log(` ${s.tokenCount} tokens, ${s.stepCount} steps, ${s.model}\\n`);\n }\n });\n\nprogram\n .command('suggest')\n .description('Suggest capabilities (skills/playbooks) for frequent uncovered session topics')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--min-frequency <n>', 'Minimum topic frequency', '3')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; minFrequency: string; json: boolean }) => {\n const { suggestCapabilities } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = suggestCapabilities(dir, config, {\n minFrequency: parseInt(opts.minFrequency, 10),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nAnalyzed ${result.topicsAnalyzed} topic(s) from ${result.sessionsScanned} session(s)\\n`);\n\n if (result.suggestions.length === 0) {\n console.log('No capability gaps found.\\n');\n return;\n }\n\n console.log(`${result.suggestions.length} suggestion(s):\\n`);\n for (const s of result.suggestions) {\n console.log(` \"${s.topic}\" — ${s.frequency}x in sessions`);\n console.log(` Suggest: create a ${s.suggestedType}\\n`);\n }\n });\n\n// --- AGENTS (list available sub-agents) ---\nprogram\n .command('agents')\n .description('List available sub-agents')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { listAgents } = await import('../runtime/delegate.js');\n const dir = resolve(opts.dir);\n\n const agents = listAgents(dir);\n\n if (agents.length === 0) {\n console.log('\\nNo agents defined.');\n console.log('Create agent files in agents/ to enable delegation.\\n');\n return;\n }\n\n console.log(`\\n${agents.length} agent(s) available:\\n`);\n for (const agent of agents) {\n const status = agent.status === 'active' ? '' : ` [${agent.status}]`;\n console.log(` ${agent.id}${status}`);\n if (agent.l0) console.log(` ${agent.l0}`);\n if (agent.tags.length > 0) console.log(` tags: ${agent.tags.join(', ')}`);\n console.log();\n }\n });\n\n// --- DELEGATE (invoke a sub-agent) ---\nprogram\n .command('delegate <agent-id> <prompt>')\n .description('Delegate a prompt to a sub-agent')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-m, --model <model>', 'Model override (or alias: gemma, qwen, glm, claude)')\n .option('-s, --stream', 'Stream output', false)\n .action(async (agentId: string, prompt: string, opts: { dir: string; model?: string; stream: boolean }) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n requireHarness(dir);\n\n const modelId = resolveModel(opts.model);\n const delegateOpts = {\n harnessDir: dir,\n agentId,\n prompt,\n modelOverride: modelId,\n };\n\n try {\n console.error(`[delegate] Invoking agent \"${agentId}\"${opts.stream ? ' (streaming)' : ''}...`);\n\n if (opts.stream) {\n const { delegateStream } = await import('../runtime/delegate.js');\n const result = delegateStream(delegateOpts);\n process.stdout.write('\\n');\n for await (const chunk of result.textStream) {\n process.stdout.write(chunk);\n }\n process.stdout.write('\\n\\n');\n console.error(\n `[delegate] Agent: ${result.agentId} | session: ${result.sessionId}`\n );\n } else {\n const { delegateTo } = await import('../runtime/delegate.js');\n const result = await delegateTo(delegateOpts);\n console.log('\\n' + result.text + '\\n');\n console.error(\n `[delegate] Agent: ${result.agentId} | ` +\n `${result.usage.totalTokens} tokens | ` +\n `session: ${result.sessionId}`\n );\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- COSTS (spending tracker) ---\nconst costsCmd = program\n .command('costs')\n .description('View and manage API spending');\n\ncostsCmd\n .command('show')\n .description('Show spending summary (default: today)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; from?: string; to?: string; json: boolean }) => {\n const { getSpending } = await import('../runtime/cost-tracker.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const summary = getSpending(dir, opts.from, opts.to);\n const label = opts.from || opts.to\n ? `${opts.from ?? 'start'} to ${opts.to ?? 'now'}`\n : 'today';\n\n if (opts.json) {\n console.log(JSON.stringify({ period: label, ...summary }, null, 2));\n return;\n }\n\n if (summary.entries === 0) {\n console.log(`\\nNo spending recorded for ${label}.\\n`);\n return;\n }\n\n console.log(`\\nSpending — ${label}\\n`);\n console.log(` Total: $${summary.total_cost_usd.toFixed(6)}`);\n console.log(` Entries: ${summary.entries}`);\n console.log(` Tokens: ${summary.total_input_tokens.toLocaleString()} in / ${summary.total_output_tokens.toLocaleString()} out`);\n\n const models = Object.entries(summary.by_model);\n if (models.length > 0) {\n console.log(`\\n By model:`);\n for (const [model, data] of models.sort((a, b) => b[1].cost_usd - a[1].cost_usd)) {\n console.log(` ${model}: $${data.cost_usd.toFixed(6)} (${data.count} calls)`);\n }\n }\n\n const providers = Object.entries(summary.by_provider);\n if (providers.length > 0) {\n console.log(`\\n By provider:`);\n for (const [provider, data] of providers.sort((a, b) => b[1].cost_usd - a[1].cost_usd)) {\n console.log(` ${provider}: $${data.cost_usd.toFixed(6)} (${data.count} calls)`);\n }\n }\n console.log();\n });\n\ncostsCmd\n .command('budget')\n .description('Check spending against budget limits')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--daily <usd>', 'Daily budget limit in USD')\n .option('--monthly <usd>', 'Monthly budget limit in USD')\n .action(async (opts: { dir: string; daily?: string; monthly?: string }) => {\n const { checkBudget } = await import('../runtime/cost-tracker.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const dailyLimit = opts.daily ? parseFloat(opts.daily) : undefined;\n const monthlyLimit = opts.monthly ? parseFloat(opts.monthly) : undefined;\n\n if (dailyLimit === undefined && monthlyLimit === undefined) {\n console.error('Error: Specify at least --daily or --monthly budget limit.');\n process.exit(1);\n }\n\n const status = checkBudget(dir, {\n daily_limit_usd: dailyLimit,\n monthly_limit_usd: monthlyLimit,\n });\n\n console.log('\\nBudget Status\\n');\n\n if (status.daily_limit_usd !== null) {\n const pct = status.daily_pct !== null ? ` (${status.daily_pct.toFixed(1)}%)` : '';\n console.log(` Daily: $${status.daily_spent_usd.toFixed(6)} / $${status.daily_limit_usd.toFixed(2)}${pct}`);\n if (status.daily_remaining_usd !== null) {\n console.log(` Remaining: $${status.daily_remaining_usd.toFixed(6)}`);\n }\n }\n\n if (status.monthly_limit_usd !== null) {\n const pct = status.monthly_pct !== null ? ` (${status.monthly_pct.toFixed(1)}%)` : '';\n console.log(` Monthly: $${status.monthly_spent_usd.toFixed(6)} / $${status.monthly_limit_usd.toFixed(2)}${pct}`);\n if (status.monthly_remaining_usd !== null) {\n console.log(` Remaining: $${status.monthly_remaining_usd.toFixed(6)}`);\n }\n }\n\n if (status.alerts.length > 0) {\n console.log('\\n Alerts:');\n for (const alert of status.alerts) {\n console.log(` ⚠ ${alert}`);\n }\n }\n console.log();\n\n // Exit 1 if any budget exceeded\n if (status.alerts.some((a) => a.includes('exceeded'))) {\n process.exit(1);\n }\n });\n\ncostsCmd\n .command('clear')\n .description('Clear all cost records')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--model <id>', 'Clear only entries for this model')\n .action(async (opts: { dir: string; model?: string }) => {\n const { clearCosts } = await import('../runtime/cost-tracker.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const removed = clearCosts(dir, opts.model);\n if (opts.model) {\n console.log(`Cleared ${removed} cost entry(ies) for model \"${opts.model}\".`);\n } else {\n console.log(`Cleared ${removed} total cost entry(ies).`);\n }\n });\n\n// --- HEALTH (system health status) ---\nprogram\n .command('health')\n .description('Show system health status and metrics')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--reset', 'Reset health metrics', false)\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; reset: boolean; json: boolean }) => {\n const { getHealthStatus, resetHealth } = await import('../runtime/health.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n if (opts.reset) {\n resetHealth(dir);\n console.log('Health metrics reset.');\n return;\n }\n\n const health = getHealthStatus(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(health, null, 2));\n return;\n }\n\n const statusIcon = health.status === 'healthy' ? 'OK' : health.status === 'degraded' ? 'WARN' : 'FAIL';\n console.log(`\\nHealth: ${statusIcon} (${health.status})\\n`);\n\n for (const check of health.checks) {\n const icon = check.status === 'pass' ? 'pass' : check.status === 'warn' ? 'WARN' : 'FAIL';\n console.log(` [${icon}] ${check.name}: ${check.message}`);\n }\n\n console.log(`\\n Metrics:`);\n console.log(` Total runs: ${health.metrics.totalRuns}`);\n console.log(` Successes: ${health.metrics.totalSuccesses}`);\n console.log(` Failures: ${health.metrics.totalFailures}`);\n console.log(` Consecutive: ${health.metrics.consecutiveFailures} failure(s)`);\n\n if (health.metrics.bootedAt) {\n console.log(` Booted at: ${health.metrics.bootedAt}`);\n }\n if (health.metrics.lastSuccessfulRun) {\n console.log(` Last success: ${health.metrics.lastSuccessfulRun}`);\n }\n if (health.metrics.lastFailedRun) {\n console.log(` Last failure: ${health.metrics.lastFailedRun}`);\n }\n if (health.metrics.lastError) {\n console.log(` Last error: ${health.metrics.lastError.slice(0, 120)}`);\n }\n\n if (health.costToday > 0 || health.costThisMonth > 0) {\n console.log(`\\n Spending:`);\n console.log(` Today: $${health.costToday.toFixed(6)}`);\n console.log(` Month: $${health.costThisMonth.toFixed(6)}`);\n }\n\n console.log();\n });\n\n// --- RATELIMIT (rate limit management) ---\nconst rateLimitCmd = program\n .command('ratelimit')\n .description('View and manage rate limit state');\n\nrateLimitCmd\n .command('status')\n .description('Show current rate limit usage for a key')\n .argument('<key>', 'Rate limit key (e.g., tool:github, model:claude)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--window <ms>', 'Window size in ms', '3600000')\n .action(async (key: string, opts: { dir: string; window: string }) => {\n const { getUsage } = await import('../runtime/rate-limiter.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const windowMs = parseInt(opts.window, 10) || 3600000;\n const usage = getUsage(dir, key, windowMs);\n\n const windowLabel = windowMs >= 3600000\n ? `${windowMs / 3600000}h`\n : windowMs >= 60000\n ? `${windowMs / 60000}m`\n : `${windowMs}ms`;\n\n console.log(`\\nRate limit: ${key} (${windowLabel} window)\\n`);\n console.log(` Requests: ${usage.count}`);\n if (usage.oldest !== null) {\n console.log(` Oldest: ${new Date(usage.oldest).toISOString()}`);\n }\n if (usage.newest !== null) {\n console.log(` Newest: ${new Date(usage.newest).toISOString()}`);\n }\n console.log();\n });\n\nrateLimitCmd\n .command('clear')\n .description('Clear rate limit events')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--key <key>', 'Clear only this key (clears all if omitted)')\n .action(async (opts: { dir: string; key?: string }) => {\n const { clearRateLimits } = await import('../runtime/rate-limiter.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const removed = clearRateLimits(dir, opts.key);\n if (opts.key) {\n console.log(`Cleared ${removed} event(s) for key \"${opts.key}\".`);\n } else {\n console.log(`Cleared ${removed} total event(s).`);\n }\n });\n\n// --- MCP (Model Context Protocol server management) ---\nconst mcpCmd = program\n .command('mcp')\n .description('Manage MCP (Model Context Protocol) server connections');\n\nmcpCmd\n .command('list')\n .description('List configured MCP servers and their status')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const { validateMcpConfig } = await import('../runtime/mcp.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const servers = config.mcp?.servers ?? {};\n const entries = Object.entries(servers);\n\n if (entries.length === 0) {\n console.log('\\nNo MCP servers configured.');\n console.log('Add servers to config.yaml under mcp.servers:\\n');\n console.log(' mcp:');\n console.log(' servers:');\n console.log(' my-server:');\n console.log(' transport: stdio');\n console.log(' command: npx');\n console.log(' args: [\"-y\", \"@my/mcp-server\"]');\n console.log();\n return;\n }\n\n const validationErrors = validateMcpConfig(config);\n const errorMap = new Map(validationErrors.map((e) => [e.server, e.error]));\n\n console.log(`\\n${entries.length} MCP server(s) configured:\\n`);\n for (const [name, serverConfig] of entries) {\n const enabled = serverConfig.enabled !== false;\n const status = !enabled ? 'disabled' : errorMap.has(name) ? 'invalid' : 'configured';\n const icon = status === 'configured' ? '+' : status === 'disabled' ? '-' : '!';\n\n console.log(` [${icon}] ${name} (${serverConfig.transport})`);\n\n if (serverConfig.transport === 'stdio' && serverConfig.command) {\n const args = serverConfig.args?.join(' ') ?? '';\n console.log(` Command: ${serverConfig.command} ${args}`.trimEnd());\n } else if (serverConfig.url) {\n console.log(` URL: ${serverConfig.url}`);\n }\n\n if (errorMap.has(name)) {\n console.log(` Error: ${errorMap.get(name)}`);\n }\n }\n console.log();\n });\n\nmcpCmd\n .command('test')\n .description('Test MCP server connections and list available tools')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-s, --server <name>', 'Test only a specific server')\n .action(async (opts: { dir: string; server?: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const { createMcpManager } = await import('../runtime/mcp.js');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const servers = config.mcp?.servers ?? {};\n\n if (Object.keys(servers).length === 0) {\n console.log('\\nNo MCP servers configured. Run `harness mcp list` for setup instructions.\\n');\n return;\n }\n\n // If testing a specific server, filter config\n let testConfig = config;\n if (opts.server) {\n if (!servers[opts.server]) {\n console.error(`Error: MCP server \"${opts.server}\" not found in config.`);\n console.error(`Available: ${Object.keys(servers).join(', ')}`);\n process.exit(1);\n }\n testConfig = {\n ...config,\n mcp: { servers: { [opts.server]: servers[opts.server] } },\n };\n }\n\n console.log(`\\nTesting MCP server connections...\\n`);\n\n const manager = createMcpManager(testConfig);\n try {\n await manager.connect();\n const summaries = manager.getSummaries();\n\n for (const summary of summaries) {\n if (!summary.enabled) {\n console.log(` [-] ${summary.name}: disabled`);\n continue;\n }\n\n if (summary.connected) {\n console.log(` [OK] ${summary.name}: connected, ${summary.toolCount} tool(s)`);\n if (summary.toolNames.length > 0) {\n for (const toolName of summary.toolNames) {\n console.log(` - ${toolName}`);\n }\n }\n } else {\n console.log(` [FAIL] ${summary.name}: ${summary.error ?? 'unknown error'}`);\n }\n }\n\n const totalTools = summaries.reduce((sum, s) => sum + s.toolCount, 0);\n const connectedCount = summaries.filter((s) => s.connected).length;\n console.log(`\\n ${connectedCount}/${summaries.length} server(s) connected, ${totalTools} total tool(s)\\n`);\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n } finally {\n await manager.close();\n }\n });\n\nmcpCmd\n .command('discover')\n .description('Scan for MCP servers from other tools (Claude Desktop, Cursor, VS Code, etc.)')\n .option('--json', 'Output raw JSON', false)\n .action(async (opts: { json: boolean }) => {\n const { discoverMcpServers, discoveredServersToYaml, getScannedTools } = await import('../runtime/mcp-discovery.js');\n const discovery = discoverMcpServers();\n\n if (opts.json) {\n console.log(JSON.stringify(discovery, null, 2));\n return;\n }\n\n const tools = getScannedTools();\n console.log(`\\nScanned ${tools.length} tools: ${tools.join(', ')}\\n`);\n\n if (discovery.sourcesFound === 0) {\n console.log('No tool configs found on this machine.\\n');\n return;\n }\n\n console.log(`Found config files from ${discovery.sourcesFound} tool(s):\\n`);\n for (const source of discovery.sources) {\n if (!source.found) continue;\n const status = source.error\n ? `error: ${source.error}`\n : `${source.servers.length} server(s)`;\n console.log(` ${source.tool}: ${status}`);\n for (const server of source.servers) {\n console.log(` - ${server.name} (${server.transport}${server.command ? `: ${server.command}` : ''}${server.url ? `: ${server.url}` : ''})`);\n }\n }\n\n if (discovery.totalServers > 0) {\n console.log(`\\n${discovery.totalServers} unique server(s) after dedup:\\n`);\n console.log(discoveredServersToYaml(discovery.servers));\n console.log('\\nAdd the above to your config.yaml to use these servers.\\n');\n } else {\n console.log('\\nNo MCP servers found in any tool configs.\\n');\n }\n });\n\nmcpCmd\n .command('search <query>')\n .description('Search the MCP registry for available servers')\n .option('-n, --limit <number>', 'Max results', '10')\n .option('--json', 'Output raw JSON', false)\n .action(async (query: string, opts: { limit: string; json: boolean }) => {\n const { searchRegistry, formatRegistryServer } = await import('../runtime/mcp-installer.js');\n\n try {\n const result = await searchRegistry(query, { limit: parseInt(opts.limit, 10) });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (result.servers.length === 0) {\n console.log(`\\nNo servers found for \"${query}\".\\n`);\n return;\n }\n\n console.log(`\\n${result.servers.length} server(s) found for \"${query}\":\\n`);\n for (const entry of result.servers) {\n console.log(formatRegistryServer(entry));\n console.log();\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nmcpCmd\n .command('install <query>')\n .description('Install an MCP server from the registry into config.yaml')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-n, --name <name>', 'Custom name for the server in config')\n .option('--force', 'Overwrite if server already exists', false)\n .option('--skip-test', 'Skip connection testing', false)\n .option('--skip-docs', 'Skip tool doc generation', false)\n .option('--json', 'Output raw JSON', false)\n .action(async (query: string, opts: { dir: string; name?: string; force: boolean; skipTest: boolean; skipDocs: boolean; json: boolean }) => {\n const { installMcpServer } = await import('../runtime/mcp-installer.js');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n requireHarness(dir);\n\n try {\n console.log(`\\nSearching for \"${query}\" in MCP registry...`);\n const result = await installMcpServer(query, {\n dir,\n name: opts.name,\n force: opts.force,\n skipTest: opts.skipTest,\n skipDocs: opts.skipDocs,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (!result.installed) {\n console.error(`\\nFailed: ${result.error}`);\n process.exit(1);\n }\n\n console.log(`\\nInstalled MCP server: ${result.name}`);\n if (result.server?.registryName) {\n console.log(` registry: ${result.server.registryName}`);\n }\n if (result.server?.description) {\n const desc = result.server.description.length > 80\n ? result.server.description.slice(0, 77) + '...'\n : result.server.description;\n console.log(` description: ${desc}`);\n }\n console.log(` transport: ${result.server?.config.transport ?? 'unknown'}`);\n console.log(` -> Added to config.yaml`);\n\n // Show required env vars\n if (result.pendingEnvVars.length > 0) {\n console.log(`\\n Required environment variables:`);\n for (const ev of result.pendingEnvVars) {\n const desc = ev.description ? ` — ${ev.description}` : '';\n console.log(` ${ev.name}${desc}`);\n }\n console.log(` -> Set these in .env or config.yaml env section`);\n }\n\n // Show connection test results\n if (result.connectionTest) {\n if (result.connectionTest.connected) {\n console.log(`\\n [OK] Connected: ${result.connectionTest.toolCount} tool(s)`);\n for (const toolName of result.connectionTest.toolNames) {\n console.log(` - ${toolName}`);\n }\n } else {\n console.log(`\\n [WARN] Connection test failed: ${result.connectionTest.error}`);\n if (result.pendingEnvVars.length > 0) {\n console.log(` (This is expected if required env vars are not yet set)`);\n }\n }\n }\n\n // Show generated docs\n if (result.generatedDocs.length > 0) {\n console.log(`\\n Generated tool docs:`);\n for (const doc of result.generatedDocs) {\n console.log(` ${doc}`);\n }\n }\n\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- DISCOVER (environment and project context) ---\nconst discoverCmd = program\n .command('discover')\n .description('Discover environment variables, project context, and MCP servers');\n\ndiscoverCmd\n .command('env')\n .description('Scan .env files for API keys and suggest MCP servers')\n .option('-d, --dir <path>', 'Directory to scan', '.')\n .option('--json', 'Output raw JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { discoverEnvKeys } = await import('../runtime/env-discovery.js');\n const dir = resolve(opts.dir);\n const result = discoverEnvKeys({ dir });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nScanned ${result.filesScanned.length} file(s)\\n`);\n\n if (result.keys.length === 0) {\n console.log('No API keys detected in .env files.\\n');\n return;\n }\n\n console.log(`${result.keys.length} API key(s) detected:\\n`);\n for (const key of result.keys) {\n const status = key.hasValue ? '[set]' : '[empty]';\n const sug = key.suggestion ? ` → ${key.suggestion}` : '';\n console.log(` ${status} ${key.name} (${key.source})${sug}`);\n }\n\n if (result.suggestions.length > 0) {\n console.log(`\\nSuggested MCP servers:\\n`);\n for (const sug of result.suggestions) {\n console.log(` ${sug.message}`);\n console.log(` Install: harness mcp install \"${sug.serverQuery}\"`);\n }\n }\n console.log();\n });\n\ndiscoverCmd\n .command('project')\n .description('Scan project files to detect tech stack and suggest rules/skills')\n .option('-d, --dir <path>', 'Project directory to scan', '.')\n .option('--json', 'Output raw JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { discoverProjectContext } = await import('../runtime/project-discovery.js');\n const dir = resolve(opts.dir);\n const result = discoverProjectContext({ dir });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (result.signals.length === 0) {\n console.log('\\nNo project signals detected.\\n');\n return;\n }\n\n console.log(`\\nDetected ${result.signals.length} signal(s):\\n`);\n const byCategory = new Map<string, ProjectSignalDisplay[]>();\n for (const signal of result.signals) {\n const list = byCategory.get(signal.category) ?? [];\n list.push(signal);\n byCategory.set(signal.category, list);\n }\n for (const [category, signals] of byCategory) {\n console.log(` ${category}: ${signals.map((s) => s.name).join(', ')}`);\n }\n\n if (result.suggestions.length > 0) {\n console.log(`\\nSuggestions:\\n`);\n for (const sug of result.suggestions) {\n if (sug.type === 'mcp-server') {\n console.log(` [mcp] ${sug.message}`);\n console.log(` Install: harness mcp install \"${sug.target}\"`);\n } else {\n console.log(` [${sug.type}] ${sug.message}`);\n console.log(` Create: ${sug.target}`);\n }\n }\n }\n console.log();\n });\n\n// Type alias for CLI display (avoids importing the full type)\ntype ProjectSignalDisplay = { name: string; category: string };\n\n// --- GENERATE (auto-generate files) ---\nconst generateCmd = program\n .command('generate')\n .description('Auto-generate harness files');\n\ngenerateCmd\n .command('system')\n .description('Regenerate SYSTEM.md from actual directory structure')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { generateSystemMd } = await import('./scaffold.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const { loadConfig } = await import('../core/config.js');\n const config = loadConfig(dir);\n const content = generateSystemMd(dir, config.agent.name);\n\n const { writeFileSync } = await import('fs');\n writeFileSync(join(dir, 'SYSTEM.md'), content, 'utf-8');\n console.log(`\\n✓ SYSTEM.md regenerated from directory structure\\n`);\n });\n\n// --- DASHBOARD (unified telemetry view) ---\nprogram\n .command('dashboard')\n .description('Show a unified dashboard of health, costs, sessions, workflows, and storage')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output raw JSON snapshot', false)\n .option('--watch', 'Refresh every N seconds', false)\n .option('--interval <seconds>', 'Watch refresh interval in seconds', '5')\n .action(async (opts: { dir: string; json: boolean; watch: boolean; interval: string }) => {\n const { collectSnapshot, formatDashboard } = await import('../runtime/telemetry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n if (opts.json) {\n const snapshot = collectSnapshot(dir);\n console.log(JSON.stringify(snapshot, null, 2));\n return;\n }\n\n const showDashboard = () => {\n const snapshot = collectSnapshot(dir);\n const output = formatDashboard(snapshot);\n if (opts.watch) {\n // Clear screen for watch mode\n process.stdout.write('\\x1B[2J\\x1B[H');\n console.log(`\\n Agent Harness Dashboard (refreshing every ${opts.interval}s — Ctrl+C to stop)\\n`);\n console.log(` ${snapshot.timestamp}\\n`);\n } else {\n console.log(`\\n Agent Harness Dashboard\\n`);\n }\n console.log(output);\n };\n\n showDashboard();\n\n if (opts.watch) {\n const intervalMs = (parseInt(opts.interval, 10) || 5) * 1000;\n const timer = setInterval(showDashboard, intervalMs);\n\n const cleanup = () => {\n clearInterval(timer);\n process.exit(0);\n };\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n }\n });\n\n// --- Intelligence Commands ---\n\nconst intelligenceCmd = program.command('intelligence').description('Intelligence and learning analysis tools');\n\nintelligenceCmd\n .command('promote')\n .description('Auto-promote instinct candidates that appear 3+ times across journals')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--threshold <n>', 'Minimum occurrences to promote', '3')\n .option('--install', 'Install promoted instincts as .md files')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { autoPromoteInstincts } = await import('../runtime/intelligence.js');\n const result = autoPromoteInstincts(dir, {\n threshold: parseInt(opts.threshold, 10),\n install: opts.install ?? false,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Scanned ${result.journalsScanned} journals`);\n if (result.patterns.length === 0) {\n console.log('No patterns meeting threshold found.');\n } else {\n console.log(`\\nPatterns (${result.patterns.length}):`);\n for (const p of result.patterns) {\n console.log(` [${p.count}x] ${p.behavior}`);\n console.log(` Dates: ${p.journalDates.join(', ')}`);\n }\n }\n if (result.promoted.length > 0) {\n console.log(`\\nPromoted: ${result.promoted.join(', ')}`);\n }\n if (result.skipped.length > 0) {\n console.log(`Skipped (already exists): ${result.skipped.join(', ')}`);\n }\n }\n });\n\nintelligenceCmd\n .command('dead')\n .description('Detect dead primitives (unreferenced and old)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--threshold <days>', 'Days since modification to consider dead', '30')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { detectDeadPrimitives } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = detectDeadPrimitives(dir, config, {\n thresholdDays: parseInt(opts.threshold, 10),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Scanned ${result.totalScanned} primitives (threshold: ${result.thresholdDays} days)`);\n if (result.dead.length === 0) {\n console.log('No dead primitives found.');\n } else {\n console.log(`\\nDead primitives (${result.dead.length}):`);\n for (const d of result.dead) {\n console.log(` ${d.id} (${d.directory}) — ${d.daysSinceModified}d since modified`);\n console.log(` ${d.reason}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('contradictions')\n .description('Detect contradictions between rules and instincts')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { detectContradictions } = await import('../runtime/intelligence.js');\n const result = detectContradictions(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Checked ${result.rulesChecked} rules, ${result.instinctsChecked} instincts`);\n if (result.contradictions.length === 0) {\n console.log('No contradictions detected.');\n } else {\n console.log(`\\nContradictions (${result.contradictions.length}):`);\n for (const c of result.contradictions) {\n console.log(` [${c.severity}] ${c.primitiveA.id} (${c.primitiveA.type}) vs ${c.primitiveB.id} (${c.primitiveB.type})`);\n console.log(` ${c.reason}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('enrich')\n .description('Enrich sessions with topics, token counts, and related primitives')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { enrichSessions } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = enrichSessions(dir, config, {\n from: opts.from,\n to: opts.to,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Scanned ${result.sessionsScanned} sessions, enriched ${result.enriched.length}`);\n for (const s of result.enriched) {\n console.log(` ${s.sessionId}: ${s.topics.join(', ') || '(no topics)'} — ${s.tokenCount} tokens, ${s.toolsUsed.length} tools`);\n if (s.primitivesReferenced.length > 0) {\n console.log(` Referenced: ${s.primitivesReferenced.join(', ')}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('suggest')\n .description('Suggest new skills/playbooks for frequent uncovered topics')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--min-frequency <n>', 'Minimum topic frequency', '3')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { suggestCapabilities } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = suggestCapabilities(dir, config, {\n minFrequency: parseInt(opts.minFrequency, 10),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Analyzed ${result.topicsAnalyzed} topics from ${result.sessionsScanned} sessions`);\n if (result.suggestions.length === 0) {\n console.log('No capability suggestions at this time.');\n } else {\n console.log(`\\nSuggestions (${result.suggestions.length}):`);\n for (const s of result.suggestions) {\n console.log(` [${s.suggestedType}] \"${s.topic}\" — ${s.frequency} occurrences`);\n console.log(` ${s.suggestion}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('failures')\n .description('Analyze recent failure patterns and suggest recovery strategies')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--days <n>', 'Days to look back', '7')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { analyzeFailures } = await import('../runtime/intelligence.js');\n const result = analyzeFailures(dir, { days: parseInt(opts.days, 10) });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Health: ${result.healthImplication}`);\n console.log(`Recent failures: ${result.recentFailures.length}`);\n if (result.mostCommonMode) {\n console.log(`Most common failure: ${result.mostCommonMode}`);\n }\n if (Object.keys(result.modeFrequency).length > 0) {\n console.log('\\nFailure frequency:');\n for (const [mode, count] of Object.entries(result.modeFrequency)) {\n console.log(` ${mode}: ${count}`);\n }\n }\n if (result.suggestedRecovery.length > 0) {\n console.log('\\nSuggested recovery:');\n for (const s of result.suggestedRecovery) {\n console.log(` - ${s}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('classify <error>')\n .description('Classify an error message into a failure mode')\n .action(async (errorMsg) => {\n const { classifyFailure, getRecoveryStrategies, FAILURE_TAXONOMY } = await import('../runtime/intelligence.js');\n const mode = classifyFailure(errorMsg);\n const info = FAILURE_TAXONOMY.modes[mode];\n const strategies = getRecoveryStrategies(mode);\n\n console.log(`Mode: ${mode}`);\n console.log(`Severity: ${info.severity}`);\n console.log(`Description: ${info.description}`);\n console.log(`Auto-recoverable: ${info.autoRecoverable}`);\n console.log('\\nRecovery strategies:');\n for (const s of strategies) {\n console.log(` - ${s}`);\n }\n });\n\n// --- Verification Gate Commands ---\n\nconst gateCmd = program.command('gate').description('Run verification gates');\n\ngateCmd\n .command('run [name]')\n .description('Run a verification gate (or all gates if no name)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (name, opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { runGate, runAllGates } = await import('../runtime/intelligence.js');\n\n if (name) {\n const result = runGate(name, dir);\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Gate: ${result.gateName} — ${result.passed ? 'PASSED' : 'FAILED'}`);\n console.log(result.summary);\n for (const c of result.checks) {\n const icon = c.status === 'pass' ? '[OK]' : c.status === 'fail' ? '[FAIL]' : c.status === 'warn' ? '[WARN]' : '[SKIP]';\n console.log(` ${icon} ${c.name}: ${c.message}`);\n }\n }\n } else {\n const results = runAllGates(dir);\n if (opts.json) {\n console.log(JSON.stringify(results, null, 2));\n } else {\n for (const result of results) {\n const icon = result.passed ? '[OK]' : '[FAIL]';\n console.log(`${icon} ${result.summary}`);\n for (const c of result.checks) {\n const cIcon = c.status === 'pass' ? '[OK]' : c.status === 'fail' ? '[FAIL]' : c.status === 'warn' ? '[WARN]' : '[SKIP]';\n console.log(` ${cIcon} ${c.name}: ${c.message}`);\n }\n }\n }\n }\n });\n\ngateCmd\n .command('list')\n .description('List available verification gates')\n .action(async () => {\n const { listGates } = await import('../runtime/intelligence.js');\n const gates = listGates();\n for (const g of gates) {\n console.log(` ${g.name}: ${g.description}`);\n }\n });\n\n// ── Rule Engine ──────────────────────────────────────────────────────────────\n\nprogram\n .command('check-rules')\n .description('Check an action against loaded rules')\n .argument('<action>', 'Action to check (e.g., \"deploy\", \"run\", \"tool_call\")')\n .option('-d, --dir <path>', 'Harness directory', process.cwd())\n .option('--description <text>', 'Description of the action')\n .option('--tags <tags>', 'Comma-separated tags')\n .option('--tool <name>', 'Tool name (for tool_call actions)')\n .option('--json', 'Output as JSON')\n .action(async (action: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { enforceRules } = await import('../runtime/rule-engine.js');\n\n const tags = opts.tags ? (opts.tags as string).split(',').map((t: string) => t.trim()) : undefined;\n const result = enforceRules(dir, {\n action,\n description: opts.description as string | undefined,\n tags,\n toolName: opts.tool as string | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(result.allowed ? '[OK] ' + result.summary : '[BLOCKED] ' + result.summary);\n for (const v of result.violations) {\n console.log(` [${v.severity.toUpperCase()}] ${v.directive} (rule: ${v.ruleId})`);\n }\n for (const w of result.warnings) {\n console.log(` [WARN] ${w.directive} (rule: ${w.ruleId})`);\n }\n }\n });\n\nprogram\n .command('list-rules')\n .description('List all parsed rules from the harness')\n .option('-d, --dir <path>', 'Harness directory', process.cwd())\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadRules } = await import('../runtime/rule-engine.js');\n\n const rules = loadRules(dir);\n if (opts.json) {\n console.log(JSON.stringify(rules, null, 2));\n } else {\n if (rules.length === 0) {\n console.log('No enforceable rules found.');\n } else {\n console.log(`${rules.length} rule(s) loaded:\\n`);\n for (const rule of rules) {\n const icon = rule.action === 'deny' ? '[DENY]' : rule.action === 'warn' ? '[WARN]' : rule.action === 'require_approval' ? '[APPROVAL]' : '[ALLOW]';\n console.log(` ${icon} ${rule.directive} (from: ${rule.ruleId})`);\n }\n }\n }\n });\n\n// ── Playbook Gates ───────────────────────────────────────────────────────────\n\nprogram\n .command('playbook-gates')\n .description('Extract and check verification gates from playbooks/workflows')\n .argument('[playbook-id]', 'Specific playbook/workflow ID')\n .option('-d, --dir <path>', 'Harness directory', process.cwd())\n .option('--json', 'Output as JSON')\n .action(async (playbookId: string | undefined, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadGates, getGatesForPlaybook } = await import('../runtime/verification-gate.js');\n\n if (playbookId) {\n const gates = getGatesForPlaybook(dir, playbookId);\n if (opts.json) {\n console.log(JSON.stringify(gates, null, 2));\n } else if (gates.length === 0) {\n console.log(`No verification gates found for \"${playbookId}\".`);\n } else {\n console.log(`${gates.length} gate(s) for \"${playbookId}\":\\n`);\n for (const gate of gates) {\n console.log(` Gate: ${gate.stage} (${gate.id})`);\n for (const c of gate.criteria) {\n const icon = c.manual ? '[MANUAL]' : '[AUTO]';\n console.log(` ${icon} ${c.description}`);\n }\n }\n }\n } else {\n const { gates, sources } = loadGates(dir);\n if (opts.json) {\n console.log(JSON.stringify({ gates, sources }, null, 2));\n } else if (gates.length === 0) {\n console.log('No verification gates found in playbooks or workflows.');\n } else {\n console.log(`${gates.length} gate(s) from ${sources.length} source(s):\\n`);\n for (const gate of gates) {\n console.log(` [${gate.sourceId}] ${gate.stage} — ${gate.criteria.length} criterion(s)`);\n }\n }\n }\n });\n\n// ── State Merge ──────────────────────────────────────────────────────────────\n\nconst stateCmd = program.command('state-merge').description('Mixed-ownership state merging');\n\nstateCmd\n .command('apply')\n .description('Apply a state change with ownership tracking')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--author <owner>', 'Change author: human, agent, infrastructure', 'human')\n .option('--mode <mode>', 'Set agent mode')\n .option('--goals <goals>', 'Set goals (comma-separated)')\n .option('--strategy <strategy>', 'Merge strategy: human-wins, agent-wins, latest-wins, union', 'human-wins')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { mergeState } = await import('../runtime/state-merge.js');\n const changes: Record<string, unknown> = {};\n if (opts.mode) changes.mode = opts.mode;\n if (opts.goals) changes.goals = (opts.goals as string).split(',').map((g: string) => g.trim());\n\n if (Object.keys(changes).length === 0) {\n console.log('No changes specified. Use --mode or --goals.');\n return;\n }\n\n const result = mergeState(dir, {\n author: opts.author as 'human' | 'agent' | 'infrastructure',\n changes,\n }, opts.strategy as 'human-wins' | 'agent-wins' | 'latest-wins' | 'union');\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`State merged (strategy: ${opts.strategy}).`);\n if (result.hadConflicts) {\n console.log(` ${result.conflicts.length} conflict(s) resolved:`);\n for (const c of result.conflicts) {\n console.log(` ${c.field}: resolved to ${c.resolvedTo}`);\n }\n } else {\n console.log(' No conflicts.');\n }\n console.log(` Mode: ${result.state.mode}`);\n console.log(` Goals: ${result.state.goals.join(', ') || '(none)'}`);\n }\n });\n\nstateCmd\n .command('ownership')\n .description('Show current state ownership')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadOwnership } = await import('../runtime/state-merge.js');\n const ownership = loadOwnership(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(ownership, null, 2));\n } else {\n console.log('State field ownership:');\n for (const [field, owner] of Object.entries(ownership)) {\n console.log(` ${field}: ${owner}`);\n }\n }\n });\n\n// ── Emotional State ──────────────────────────────────────────────────────────\n\nconst emoCmd = program.command('emotional').description('Operational disposition tracking');\n\nemoCmd\n .command('status')\n .description('Show current emotional/disposition state')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadEmotionalState, summarizeEmotionalState } = await import('../runtime/emotional-state.js');\n const state = loadEmotionalState(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(state, null, 2));\n } else {\n console.log('Operational Disposition:');\n console.log(` Confidence: ${state.confidence}/100`);\n console.log(` Engagement: ${state.engagement}/100`);\n console.log(` Frustration: ${state.frustration}/100`);\n console.log(` Curiosity: ${state.curiosity}/100`);\n console.log(` Urgency: ${state.urgency}/100`);\n console.log(` Updated: ${state.updatedAt}`);\n console.log(`\\n${summarizeEmotionalState(state)}`);\n }\n });\n\nemoCmd\n .command('signal')\n .description('Apply an emotional signal')\n .argument('<dimension>', 'Dimension: confidence, engagement, frustration, curiosity, urgency')\n .argument('<delta>', 'Delta value (positive or negative integer)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-r, --reason <reason>', 'Reason for the signal')\n .option('--json', 'Output as JSON')\n .action(async (dimension: string, delta: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { applySignals } = await import('../runtime/emotional-state.js');\n const state = applySignals(dir, [{\n dimension: dimension as 'confidence' | 'engagement' | 'frustration' | 'curiosity' | 'urgency',\n delta: parseInt(delta, 10),\n reason: opts.reason as string | undefined,\n }]);\n\n if (opts.json) {\n console.log(JSON.stringify(state, null, 2));\n } else {\n console.log(`Applied signal: ${dimension} ${parseInt(delta, 10) >= 0 ? '+' : ''}${delta}`);\n console.log(` New ${dimension}: ${state[dimension as keyof typeof state]}/100`);\n }\n });\n\nemoCmd\n .command('trends')\n .description('Show emotional dimension trends')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--days <days>', 'Days to analyze', '7')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { getEmotionalTrends } = await import('../runtime/emotional-state.js');\n const trends = getEmotionalTrends(dir, { days: parseInt(opts.days as string, 10) });\n\n if (opts.json) {\n console.log(JSON.stringify(trends, null, 2));\n } else {\n console.log(`Emotional trends (last ${opts.days} days):\\n`);\n for (const t of trends) {\n const arrow = t.trend === 'rising' ? '↑' : t.trend === 'falling' ? '↓' : '→';\n console.log(` ${t.dimension}: avg ${t.average.toFixed(0)}/100 ${arrow} (${t.values.length} data points)`);\n }\n }\n });\n\nemoCmd\n .command('reset')\n .description('Reset emotional state to defaults')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { resetEmotionalState } = await import('../runtime/emotional-state.js');\n resetEmotionalState(dir);\n console.log('Emotional state reset to defaults.');\n });\n\n// ── Check Action ─────────────────────────────────────────────────────────────\n\nprogram\n .command('check-action')\n .description('Check if an action is allowed by harness rules (agent-framework guardrails)')\n .argument('<action>', 'Action description to check')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--tags <tags>', 'Filter by rule tags (comma-separated)')\n .option('--json', 'Output as JSON')\n .action(async (action: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { checkAction } = await import('../runtime/agent-framework.js');\n const tags = opts.tags ? (opts.tags as string).split(',').map((t: string) => t.trim()) : undefined;\n const result = checkAction(dir, action, { ruleTags: tags });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else if (result.allowed) {\n console.log('[OK] Action allowed.');\n } else {\n console.log(`[BLOCKED] ${result.reason}`);\n }\n });\n\n// ── Serve ────────────────────────────────────────────────────────────────────\n\nprogram\n .command('serve')\n .description('Start the harness HTTP API server for webhooks and integrations')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-p, --port <port>', 'Port to listen on', '8080')\n .option('--api-key <key>', 'API key for LLM provider')\n .option('--webhook-secret <secret>', 'Secret for authenticating webhook management API')\n .option('--no-cors', 'Disable CORS')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { startServe } = await import('../runtime/serve.js');\n\n const port = parseInt(opts.port as string, 10);\n const result = startServe({\n harnessDir: dir,\n port,\n apiKey: opts.apiKey as string | undefined,\n webhookSecret: opts.webhookSecret as string | undefined,\n corsEnabled: opts.cors !== false,\n });\n\n console.log(`Harness API server listening on http://localhost:${result.port}`);\n console.log('Endpoints:');\n console.log(' GET /api/health — health check');\n console.log(' GET /api/info — agent info');\n console.log(' POST /api/run — execute a prompt');\n console.log(' GET /api/webhooks — list registered webhooks');\n console.log(' POST /api/webhooks — register a webhook');\n console.log(' DEL /api/webhooks/:id — delete a webhook');\n console.log(' PATCH /api/webhooks/:id — toggle webhook active/inactive');\n console.log(' POST /api/webhooks/:id/test — test a webhook');\n console.log(' + all dashboard endpoints from harness dev');\n console.log('\\nPress Ctrl+C to stop.');\n\n // Keep process alive\n process.on('SIGINT', () => {\n console.log('\\nShutting down...');\n result.stop();\n process.exit(0);\n });\n process.on('SIGTERM', () => {\n result.stop();\n process.exit(0);\n });\n\n // Wait indefinitely\n await new Promise<void>(() => { /* keep alive */ });\n });\n\n// ── Sources ──────────────────────────────────────────────────────────────────\n\nconst sourcesCmd = program.command('sources').description('Manage content sources (skills, agents, rules, MCP servers)');\n\nsourcesCmd\n .command('list')\n .description('List all configured content sources')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--type <type>', 'Filter by content type (skills, agents, rules, hooks, mcp, etc.)')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadAllSources, getSourcesForType } = await import('../runtime/sources.js');\n\n const sources = opts.type\n ? getSourcesForType(dir, opts.type as 'skills' | 'agents' | 'rules' | 'hooks' | 'mcp')\n : loadAllSources(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(sources, null, 2));\n } else if (sources.length === 0) {\n console.log('No sources configured.');\n } else {\n console.log(`${sources.length} source(s):\\n`);\n for (const s of sources) {\n const types = s.content.join(', ');\n const stats = s.stats ? ` (${Object.entries(s.stats).map(([k, v]) => `${v} ${k}`).join(', ')})` : '';\n console.log(` [${s.type}] ${s.name}${stats}`);\n console.log(` ${s.url}`);\n console.log(` Content: ${types}`);\n if (s.description) console.log(` ${s.description}`);\n console.log();\n }\n }\n });\n\nsourcesCmd\n .command('add')\n .description('Add a new content source')\n .argument('<url>', 'Source URL (GitHub repo, registry API, or endpoint)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-n, --name <name>', 'Source display name')\n .option('-t, --type <type>', 'Source type: github, registry, api', 'github')\n .option('-c, --content <types>', 'Content types (comma-separated: skills,agents,rules,hooks,mcp)')\n .option('--description <desc>', 'Source description')\n .option('--json', 'Output as JSON')\n .action(async (url: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { addSource } = await import('../runtime/sources.js');\n\n // Derive name from URL if not provided\n const name = (opts.name as string) ?? url.replace(/https?:\\/\\//, '').replace(/github\\.com\\//, '').replace(/\\/$/, '');\n const content = opts.content\n ? (opts.content as string).split(',').map((c: string) => c.trim())\n : ['skills'];\n\n const result = addSource(dir, {\n name,\n url,\n type: (opts.type as 'github' | 'registry' | 'api'),\n content: content as Array<'skills' | 'agents' | 'rules' | 'hooks' | 'mcp'>,\n description: opts.description as string | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else if (result) {\n console.log(`Added source: ${result.name} (${result.url})`);\n } else {\n console.log('Source with that name already exists.');\n }\n });\n\nsourcesCmd\n .command('remove')\n .description('Remove a content source')\n .argument('<name>', 'Source name to remove')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .action(async (name: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { removeSource } = await import('../runtime/sources.js');\n\n const removed = removeSource(dir, name);\n if (removed) {\n console.log(`Removed source: ${name}`);\n } else {\n console.log(`Source not found: ${name}`);\n }\n });\n\nsourcesCmd\n .command('summary')\n .description('Show content available by type across all sources')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { getSourcesSummary } = await import('../runtime/sources.js');\n\n const summary = getSourcesSummary(dir);\n\n if (opts.json) {\n const json: Record<string, number> = {};\n for (const [type, sources] of Object.entries(summary)) {\n json[type] = sources.length;\n }\n console.log(JSON.stringify(json, null, 2));\n } else {\n console.log('Content sources by type:\\n');\n for (const [type, sources] of Object.entries(summary)) {\n if (sources.length > 0) {\n console.log(` ${type}: ${sources.length} source(s)`);\n for (const s of sources) {\n console.log(` - ${s.name}`);\n }\n }\n }\n }\n });\n\n// ── Discover Search (sub-command of existing discoverCmd) ────────────────────\n\ndiscoverCmd\n .command('search')\n .description('Search all content sources for skills, agents, rules, hooks, MCP servers')\n .argument('<query>', 'Search query')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-t, --type <type>', 'Filter by content type (skills, agents, rules, hooks, mcp, etc.)')\n .option('-n, --max <n>', 'Maximum results', '20')\n .option('--remote', 'Also search remote sources (GitHub API, registries)')\n .option('--json', 'Output as JSON')\n .action(async (query: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n\n const maxResults = parseInt(opts.max as string, 10);\n const type = opts.type as string | undefined;\n\n if (opts.remote) {\n const { discoverRemote } = await import('../runtime/sources.js');\n const results = await discoverRemote(dir, query, {\n type: type as 'skills' | 'agents' | undefined,\n maxResults,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(results, null, 2));\n } else if (results.length === 0) {\n console.log('No results found.');\n } else {\n console.log(`${results.length} result(s):\\n`);\n for (const r of results) {\n console.log(` [${r.type}] ${r.name} (score: ${r.score.toFixed(2)})`);\n console.log(` Source: ${r.source.name}`);\n console.log(` ${r.url}`);\n if (r.description) console.log(` ${r.description}`);\n console.log();\n }\n }\n } else {\n const { discoverSources } = await import('../runtime/sources.js');\n const results = discoverSources(dir, query, {\n type: type as 'skills' | 'agents' | undefined,\n maxResults,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(results, null, 2));\n } else if (results.length === 0) {\n console.log('No results found. Try --remote to search GitHub and registries.');\n } else {\n console.log(`${results.length} result(s):\\n`);\n for (const r of results) {\n console.log(` [${r.type}] ${r.name} (score: ${r.score.toFixed(2)})`);\n console.log(` Source: ${r.source.name}`);\n console.log(` ${r.url}`);\n if (r.description) console.log(` ${r.description}`);\n console.log();\n }\n }\n }\n });\n\n// ── Browse ──────────────────────────────────────────────────────────────────\n\nprogram\n .command('browse')\n .description('Browse available community content — starter packs, sources, and installed primitives')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--type <type>', 'Filter by content type (packs, sources, installed)')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { listStarterPacks } = await import('../runtime/starter-packs.js');\n const { loadAllSources, getSourcesSummary } = await import('../runtime/sources.js');\n const { listInstalledBundles } = await import('../runtime/primitive-registry.js');\n\n const filter = opts.type as string | undefined;\n const sections: Array<{ title: string; type: string; items: unknown[] }> = [];\n\n // Starter Packs\n if (!filter || filter === 'packs') {\n const packs = listStarterPacks();\n sections.push({\n title: 'Starter Packs',\n type: 'packs',\n items: packs.map(p => ({\n name: p.name,\n description: p.description,\n files: p.fileCount,\n tags: p.tags,\n install: `harness install pack:${p.name}`,\n })),\n });\n }\n\n // Community Sources\n if (!filter || filter === 'sources') {\n const sources = loadAllSources(dir);\n const summary = getSourcesSummary(dir);\n const typeEntries = Object.entries(summary)\n .filter(([, s]) => s.length > 0)\n .map(([type, s]) => `${type}: ${s.length}`);\n sections.push({\n title: 'Community Sources',\n type: 'sources',\n items: sources.map(s => ({\n name: s.name,\n url: s.url,\n type: s.type,\n content: s.content,\n stats: s.stats,\n })),\n ...(typeEntries.length > 0 ? { summary: typeEntries } : {}),\n });\n }\n\n // Installed Bundles\n if (!filter || filter === 'installed') {\n const installed = listInstalledBundles(dir);\n sections.push({\n title: 'Installed Bundles',\n type: 'installed',\n items: installed.map(b => ({\n name: b.name,\n description: b.description,\n version: b.version,\n types: b.types,\n files: b.fileCount,\n })),\n });\n }\n\n if (opts.json) {\n const output: Record<string, unknown> = {};\n for (const section of sections) {\n output[section.type] = section.items;\n }\n console.log(JSON.stringify(output, null, 2));\n return;\n }\n\n // Text output\n console.log('=== Agent Harness Content Browser ===\\n');\n\n for (const section of sections) {\n console.log(`── ${section.title} ──\\n`);\n if (section.items.length === 0) {\n console.log(' (none)\\n');\n continue;\n }\n\n for (const item of section.items as Array<Record<string, unknown>>) {\n if (section.type === 'packs') {\n console.log(` pack:${item.name as string}`);\n console.log(` ${item.description as string}`);\n console.log(` Files: ${item.files as number} | Tags: ${(item.tags as string[]).join(', ')}`);\n console.log(` Install: ${item.install as string}`);\n console.log();\n } else if (section.type === 'sources') {\n const stats = item.stats as Record<string, number> | undefined;\n const statsStr = stats ? ` (${Object.entries(stats).map(([k, v]) => `${v} ${k}`).join(', ')})` : '';\n console.log(` [${item.type as string}] ${item.name as string}${statsStr}`);\n console.log(` ${item.url as string}`);\n console.log(` Content: ${(item.content as string[]).join(', ')}`);\n console.log();\n } else if (section.type === 'installed') {\n console.log(` ${item.name as string} v${item.version as string}`);\n if (item.description) console.log(` ${item.description as string}`);\n console.log(` Types: ${(item.types as string[]).join(', ')} | Files: ${item.files as number}`);\n console.log();\n }\n }\n }\n\n // Quick tips\n console.log('── Quick Start ──\\n');\n console.log(' Install a pack: harness install pack:<name> -d <dir>');\n console.log(' Search sources: harness discover search <query> -d <dir>');\n console.log(' Install anything: harness install <url-or-name> -d <dir>');\n console.log(' Add a source: harness sources add <url> -d <dir>');\n console.log();\n });\n\n// ── Semantic Search ──────────────────────────────────────────────────────────\n\nconst semanticCmd = program.command('semantic').description('Semantic search over indexed primitives');\n\nsemanticCmd\n .command('index')\n .description('Index all primitives for semantic search (requires an embed function at runtime — shows stats only from CLI)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { getEmbeddingStats } = await import('../runtime/semantic-search.js');\n const stats = getEmbeddingStats(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(stats, null, 2));\n } else {\n console.log('Embedding index stats:');\n console.log(` Indexed: ${stats.indexed} primitives`);\n console.log(` Model: ${stats.modelId ?? '(none)'}`);\n console.log(` Dimensions: ${stats.dimensions}`);\n console.log(` Last indexed: ${stats.lastIndexedAt ?? '(never)'}`);\n console.log(` Store size: ${(stats.storeSize / 1024).toFixed(1)} KB`);\n }\n });\n\nsemanticCmd\n .command('stats')\n .description('Show embedding store statistics')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { getEmbeddingStats, detectStalePrimitives, loadEmbeddingStore } = await import('../runtime/semantic-search.js');\n const stats = getEmbeddingStats(dir);\n const store = loadEmbeddingStore(dir);\n const stale = detectStalePrimitives(dir, store, stats.modelId ?? '');\n\n if (opts.json) {\n console.log(JSON.stringify({ ...stats, stale: stale.length }, null, 2));\n } else {\n console.log('Semantic search stats:');\n console.log(` Indexed: ${stats.indexed} primitives`);\n console.log(` Stale: ${stale.length} primitive(s) need re-indexing`);\n console.log(` Model: ${stats.modelId ?? '(none)'}`);\n console.log(` Dimensions: ${stats.dimensions}`);\n console.log(` Last indexed: ${stats.lastIndexedAt ?? '(never)'}`);\n console.log(` Store size: ${(stats.storeSize / 1024).toFixed(1)} KB`);\n }\n });\n\n// ── Universal Installer ──────────────────────────────────────────────────────\n\nprogram\n .command('install')\n .description('Install a primitive from any source (file, URL, or name)')\n .argument('<source>', 'File path, HTTPS URL, or source name to install')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-t, --type <type>', 'Override detected type (skill, rule, agent, playbook, workflow, tool)')\n .option('--id <id>', 'Override generated ID')\n .option('--force', 'Force install despite validation warnings')\n .option('--skip-fix', 'Skip auto-fix (no frontmatter/L0/L1 generation)')\n .option('--tags <tags...>', 'Additional tags to add')\n .option('--json', 'Output as JSON')\n .action(async (source: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n\n // Handle pack: prefix — install builtin starter packs\n const { isPackReference, parsePackName, getStarterPack, listStarterPacks } = await import('../runtime/starter-packs.js');\n if (isPackReference(source)) {\n const packName = parsePackName(source);\n\n // Special case: pack:list shows available packs\n if (packName === 'list') {\n const packs = listStarterPacks();\n console.log('\\nAvailable starter packs:\\n');\n for (const p of packs) {\n console.log(` pack:${p.name}`);\n console.log(` ${p.description}`);\n console.log(` Files: ${p.fileCount} | Tags: ${p.tags.join(', ')}\\n`);\n }\n console.log(`Install with: harness install pack:<name> -d <harness-dir>`);\n return;\n }\n\n const bundle = getStarterPack(packName);\n if (!bundle) {\n const available = listStarterPacks().map(p => `pack:${p.name}`).join(', ');\n console.error(`Unknown starter pack: \"${packName}\"\\nAvailable packs: ${available}`);\n process.exitCode = 1;\n return;\n }\n\n const { installBundle } = await import('../runtime/primitive-registry.js');\n const bundleResult = installBundle(dir, bundle, {\n overwrite: opts.force as boolean | undefined,\n force: opts.force as boolean | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(bundleResult, null, 2));\n } else if (bundleResult.installed) {\n console.log(`\\nInstalled pack: ${packName}`);\n console.log(` Files: ${bundleResult.files.length}`);\n for (const f of bundleResult.files) {\n console.log(` + ${f}`);\n }\n if (bundleResult.skipped.length > 0) {\n console.log(` Skipped (already exist): ${bundleResult.skipped.length}`);\n for (const f of bundleResult.skipped) {\n console.log(` ~ ${f}`);\n }\n console.log(` Use --force to overwrite existing files.`);\n }\n console.log(`\\nCustomize the workflows in your workflows/ directory.`);\n } else {\n console.error(`Failed to install pack: ${packName}`);\n for (const err of bundleResult.errors) {\n console.error(` ${err}`);\n }\n process.exitCode = 1;\n }\n return;\n }\n\n const { universalInstall } = await import('../runtime/universal-installer.js');\n\n const result = await universalInstall(dir, source, {\n type: opts.type as string | undefined,\n id: opts.id as string | undefined,\n force: opts.force as boolean | undefined,\n skipFix: opts.skipFix as boolean | undefined,\n tags: opts.tags as string[] | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.installed) {\n console.log(`Installed: ${result.destination}`);\n console.log(` Format: ${result.format.format} (${(result.format.confidence * 100).toFixed(0)}% confidence)`);\n if (result.format.primitiveType) {\n console.log(` Type: ${result.format.primitiveType}`);\n }\n if (result.fixes.length > 0) {\n console.log(` Fixes:`);\n for (const fix of result.fixes) {\n console.log(` - ${fix}`);\n }\n }\n if (result.suggestedDependencies.length > 0) {\n console.log(` Dependencies to consider:`);\n for (const dep of result.suggestedDependencies) {\n console.log(` - ${dep}`);\n }\n }\n } else {\n console.error(`Failed to install: ${source}`);\n for (const err of result.errors) {\n console.error(` ${err}`);\n }\n if (result.fixes.length > 0) {\n console.log(` Attempted fixes:`);\n for (const fix of result.fixes) {\n console.log(` - ${fix}`);\n }\n }\n process.exitCode = 1;\n }\n }\n });\n\n// ── Versioning ───────────────────────────────────────────────────────────────\n\nconst versionCmd = program.command('version').description('Git-backed primitive versioning');\n\nversionCmd\n .command('init')\n .description('Initialize git versioning for the harness')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { initVersioning, isGitRepo } = await import('../runtime/versioning.js');\n if (isGitRepo(dir)) {\n console.log('Versioning already initialized.');\n } else {\n const ok = initVersioning(dir);\n console.log(ok ? 'Versioning initialized.' : 'Failed to initialize versioning.');\n }\n });\n\nversionCmd\n .command('snapshot')\n .description('Take a versioned snapshot of the current harness state')\n .argument('<message>', 'Commit message')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-t, --tag <tag>', 'Tag this version')\n .option('--json', 'Output as JSON')\n .action(async (message: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { snapshot } = await import('../runtime/versioning.js');\n const result = snapshot(dir, message, { tag: opts.tag as string | undefined });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else if (result.success && result.files.length > 0) {\n console.log(`Snapshot ${result.hash.slice(0, 7)}: ${result.files.length} file(s) committed.`);\n for (const f of result.files) { console.log(` ${f}`); }\n if (opts.tag) { console.log(` Tagged: ${opts.tag}`); }\n } else if (result.error) {\n console.log(result.error);\n }\n });\n\nversionCmd\n .command('log')\n .description('Show version history')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-n, --limit <n>', 'Max entries', '20')\n .option('-f, --file <path>', 'Filter by file path')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { getVersionLog } = await import('../runtime/versioning.js');\n const log = getVersionLog(dir, {\n limit: parseInt(opts.limit as string, 10),\n file: opts.file as string | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(log, null, 2));\n } else if (log.entries.length === 0) {\n console.log('No version history. Run `harness version init` first.');\n } else {\n console.log(`Version history (${log.entries.length} entries):\\n`);\n for (const entry of log.entries) {\n const tag = entry.tag ? ` [${entry.tag}]` : '';\n console.log(` ${entry.hash} ${entry.message}${tag}`);\n console.log(` ${entry.timestamp} — ${entry.filesChanged.length} file(s)`);\n }\n }\n });\n\nversionCmd\n .command('diff')\n .description('Show changes between versions')\n .argument('<from>', 'Source commit hash or tag')\n .argument('[to]', 'Target commit hash or tag (default: HEAD)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (from: string, to: string | undefined, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { getVersionDiff } = await import('../runtime/versioning.js');\n const diff = getVersionDiff(dir, from, to);\n\n if (opts.json) {\n console.log(JSON.stringify(diff, null, 2));\n } else {\n console.log(`${diff.summary}\\n`);\n for (const entry of diff.entries) {\n const icon = entry.status === 'added' ? '+' : entry.status === 'deleted' ? '-' : 'M';\n const stats = entry.additions !== undefined ? ` (+${entry.additions}/-${entry.deletions})` : '';\n console.log(` [${icon}] ${entry.file}${stats}`);\n }\n }\n });\n\nversionCmd\n .command('rollback')\n .description('Roll back to a previous version (creates new commit preserving history)')\n .argument('<target>', 'Commit hash or tag to roll back to')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (target: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { rollback } = await import('../runtime/versioning.js');\n const result = rollback(dir, target);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else if (result.success) {\n console.log(`Rolled back to ${result.targetHash.slice(0, 7)}.`);\n console.log(` ${result.restoredFiles.length} file(s) restored.`);\n } else {\n console.log(`Rollback failed: ${result.error}`);\n }\n });\n\nversionCmd\n .command('tag')\n .description('Tag the current version')\n .argument('<name>', 'Tag name (e.g., v1.0.0)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-m, --message <msg>', 'Tag message')\n .action(async (name: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { tagVersion } = await import('../runtime/versioning.js');\n const ok = tagVersion(dir, name, opts.message as string | undefined);\n console.log(ok ? `Tagged: ${name}` : 'Failed to create tag.');\n });\n\nversionCmd\n .command('tags')\n .description('List all version tags')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { listTags } = await import('../runtime/versioning.js');\n const tags = listTags(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(tags, null, 2));\n } else if (tags.length === 0) {\n console.log('No tags.');\n } else {\n for (const t of tags) {\n console.log(` ${t.tag} → ${t.hash} (${t.message})`);\n }\n }\n });\n\nversionCmd\n .command('pending')\n .description('Show uncommitted changes')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { getPendingChanges } = await import('../runtime/versioning.js');\n const changes = getPendingChanges(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(changes, null, 2));\n } else if (changes.length === 0) {\n console.log('No pending changes.');\n } else {\n console.log(`${changes.length} pending change(s):\\n`);\n for (const c of changes) {\n const icon = c.status === 'added' ? '+' : c.status === 'deleted' ? '-' : 'M';\n console.log(` [${icon}] ${c.file}`);\n }\n }\n });\n\nversionCmd\n .command('show')\n .description('Show file content at a specific version')\n .argument('<file>', 'File path relative to harness')\n .argument('<hash>', 'Commit hash or tag')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .action(async (file: string, hash: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { getFileAtVersion } = await import('../runtime/versioning.js');\n const content = getFileAtVersion(dir, file, hash);\n if (content === null) {\n console.log(`File not found at version ${hash}.`);\n } else {\n console.log(content);\n }\n });\n\nprogram.parse();\n"],"mappings":";;;;;;;;AAgBA,SAAS,eAAe;AACxB,SAAS,SAAS,MAAM,gBAAgB;AACxC,SAAS,kBAAkB;AAC3B,SAAS,UAAU,kBAAkB;AAfrC,IAAM,2BAA2B,QAAQ,UAAU,SAAS;AAC5D,QAAQ,mBAAmB,SAAS;AACpC,QAAQ,GAAG,WAAW,CAAC,YAAmC;AACxD,MAAI,QAAQ,SAAS,yBAAyB,SAAS,KAAK,QAAQ,OAAO,GAAG;AAC5E;AAAA,EACF;AAEA,aAAW,WAAW,0BAA0B;AAC9C,IAAC,QAA+C,OAAO;AAAA,EACzD;AACF,CAAC;AAYD,IAAM,gBAAgB,QAAQ,IAAI,oBAAoB;AACtD,WAAW,EAAE,OAAO,cAAc,CAAC;AACnC,WAAW,EAAE,MAAM,QAAQ,YAAY,GAAG,OAAO,cAAc,CAAC;AAEhE,IAAM,UAAU,IAAI,QAAQ;AAG5B,IAAM,gBAAwC;AAAA,EAC5C,SAAS;AAAA,EACT,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,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"version":3,"sources":["../../src/cli/index.ts"],"sourcesContent":["// Suppress Node 18 ExperimentalWarning for the Fetch API. Must run BEFORE any\n// import that triggers fetch (most of the Vercel AI SDK chain). Node 20+ users\n// won't see this warning at all; Node 18 users get clean output.\n// We listen on the 'warning' event and re-emit everything except the fetch one.\nconst __defaultWarningHandlers = process.listeners('warning');\nprocess.removeAllListeners('warning');\nprocess.on('warning', (warning: NodeJS.ErrnoException) => {\n if (warning.name === 'ExperimentalWarning' && /fetch/i.test(warning.message)) {\n return;\n }\n // Restore default behavior: print the warning to stderr.\n for (const handler of __defaultWarningHandlers) {\n (handler as (w: NodeJS.ErrnoException) => void)(warning);\n }\n});\n\nimport { Command } from 'commander';\nimport { createRequire } from 'module';\nimport { resolve, join, basename } from 'path';\nimport { existsSync } from 'fs';\nimport { config as loadDotenv } from 'dotenv';\nimport { setGlobalLogLevel, type LogLevel } from '../core/logger.js';\n\n// Load .env from current directory and common locations.\n// `quiet: true` suppresses dotenv 17.x's \"injected env (N) from .env\" banners\n// and the rotating \"tip:\" marketing text. Users who want the banners back can\n// run with HARNESS_VERBOSE=1 or unset DOTENV_CONFIG_QUIET in their shell.\nconst __dotenvQuiet = process.env.HARNESS_VERBOSE !== '1';\nloadDotenv({ quiet: __dotenvQuiet });\nloadDotenv({ path: resolve('.env.local'), quiet: __dotenvQuiet });\n\nconst program = new Command();\n\n// Model aliases for convenience\nconst MODEL_ALIASES: Record<string, string> = {\n 'gemma': 'google/gemma-4-26b-a4b-it',\n 'gemma-31b': 'google/gemma-4-31b-it',\n 'qwen': 'qwen/qwen3.5-35b-a3b',\n 'glm': 'z-ai/glm-4.7-flash',\n 'claude': 'anthropic/claude-sonnet-4',\n 'gpt4o': 'openai/gpt-4o',\n 'gpt4o-mini': 'openai/gpt-4o-mini',\n};\n\nfunction resolveModel(model?: string): string | undefined {\n if (!model) return undefined;\n return MODEL_ALIASES[model] || model;\n}\n\nfunction loadEnvFromDir(dir: string) {\n const envPath = join(dir, '.env');\n if (existsSync(envPath)) {\n loadDotenv({ path: envPath });\n }\n}\n\nfunction formatError(err: unknown): string {\n if (!err) return 'Unknown error';\n if (typeof err === 'string') return err;\n const e = err as Record<string, unknown>;\n\n // OpenRouter API errors\n if (e.data && typeof e.data === 'object') {\n const data = e.data as Record<string, unknown>;\n if (data.error && typeof data.error === 'object') {\n const apiErr = data.error as Record<string, unknown>;\n if (typeof apiErr.message === 'string') return apiErr.message;\n }\n }\n\n const message = e.message;\n if (typeof message !== 'string') return String(err);\n\n // API key errors\n if (message.includes('API key') || message.includes('OPENROUTER_API_KEY'))\n return message;\n\n // Model errors\n if (message.includes('not a valid model') || message.includes('model not found'))\n return `Invalid model: ${message}`;\n\n // Network errors\n if (message.includes('ECONNREFUSED') || message.includes('ENOTFOUND'))\n return `Network error: Could not reach API. Check your internet connection.`;\n if (message.includes('ETIMEDOUT'))\n return `Request timed out. The API may be overloaded — try again.`;\n\n // Rate limiting\n if (message.includes('429') || message.includes('rate limit'))\n return `Rate limited by API. Wait a moment and try again.`;\n\n // Config errors\n if (message.includes('Invalid config'))\n return message;\n\n // Zod validation errors\n if (message.includes('Expected') && message.includes('received'))\n return `Validation error: ${message}`;\n\n // File system errors\n if (message.includes('ENOENT'))\n return `File not found: ${message.replace(/.*ENOENT[^']*'([^']+)'.*/, '$1')}`;\n if (message.includes('EACCES'))\n return `Permission denied: ${message.replace(/.*EACCES[^']*'([^']+)'.*/, '$1')}`;\n\n return message;\n}\n\nfunction requireHarness(dir: string): void {\n if (!existsSync(join(dir, 'CORE.md')) && !existsSync(join(dir, 'config.yaml'))) {\n console.error(`Error: No harness found in ${dir}`);\n console.error(`Run \"harness init <name>\" to create one.`);\n process.exit(1);\n }\n}\n\n// Read version from package.json at runtime so `harness --version` always\n// matches the installed package. Hardcoding the version string caused 0.1.1\n// to print \"0.1.0\" when shipped (caught in post-ship verification).\n// package.json is always in the tarball (npm includes it automatically),\n// and dist/cli/index.js lives at <pkg>/dist/cli/index.js, so the relative\n// path to package.json is ../../package.json from the built file.\nconst __pkgRequire = createRequire(import.meta.url);\nconst __pkg = __pkgRequire('../../package.json') as { version: string };\n\nprogram\n .name('harness')\n .description('Agent Harness — build AI agents by editing files, not writing code.')\n .version(__pkg.version)\n .option('-q, --quiet', 'Suppress non-error output')\n .option('-v, --verbose', 'Enable debug output')\n .option('--log-level <level>', 'Set log level (debug, info, warn, error, silent)')\n .hook('preAction', () => {\n const opts = program.opts();\n if (opts.quiet) setGlobalLogLevel('error');\n else if (opts.verbose) setGlobalLogLevel('debug');\n else if (opts.logLevel) setGlobalLogLevel(opts.logLevel as LogLevel);\n });\n\n// --- INIT ---\n\n/** Ask a question via readline and return the answer */\nfunction askQuestion(rl: ReturnType<typeof import('readline').createInterface>, question: string, defaultValue?: string): Promise<string> {\n const suffix = defaultValue ? ` [${defaultValue}]` : '';\n return new Promise((resolve) => {\n rl.question(`${question}${suffix}: `, (answer) => {\n resolve(answer.trim() || defaultValue || '');\n });\n });\n}\n\nprogram\n .command('init [name]')\n .description('Scaffold a new agent harness directory (interactive if no name given)')\n .option('-d, --dir <path>', 'Parent directory', '.')\n .option('-t, --template <name>', 'Config template (base, claude-opus, gpt4, local)', 'base')\n .option('-p, --purpose <description>', 'Agent purpose description')\n .option('-i, --interactive', 'Force interactive mode', false)\n .option('--generate', 'Generate CORE.md using LLM (requires API key)', false)\n .option('--no-discover-mcp', 'Skip MCP server auto-discovery')\n .option('--no-discover-env', 'Skip environment variable scanning')\n .option('--no-discover-project', 'Skip project context detection')\n .option('-y, --yes', 'Accept defaults for all prompts (skip MCP confirmation)', false)\n .action(async (name: string | undefined, opts: { dir: string; template: string; purpose?: string; interactive: boolean; generate: boolean; discoverMcp: boolean; discoverEnv: boolean; discoverProject: boolean; yes: boolean }) => {\n const { scaffoldHarness, generateCoreMd, listTemplates } = await import('./scaffold.js');\n\n // Interactive mode: no name provided or --interactive flag\n const isInteractive = !name || opts.interactive;\n let agentName = name ?? '';\n let purpose = opts.purpose ?? '';\n let template = opts.template;\n let shouldGenerate = opts.generate;\n\n if (isInteractive && process.stdin.isTTY) {\n const readline = await import('readline');\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n\n try {\n console.log('\\n Agent Harness Setup\\n');\n\n if (!agentName) {\n agentName = await askQuestion(rl, ' Agent name', 'my-agent');\n }\n\n if (!purpose) {\n purpose = await askQuestion(rl, ' What does this agent do? (purpose)');\n }\n\n const templates = listTemplates();\n if (templates.length > 1) {\n console.log(` Available templates: ${templates.join(', ')}`);\n template = await askQuestion(rl, ' Template', template);\n }\n\n if (purpose && !shouldGenerate) {\n // Check if an API key is available for LLM generation\n const hasKey = !!(process.env.OPENROUTER_API_KEY || process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY);\n if (hasKey) {\n const gen = await askQuestion(rl, ' Generate CORE.md using AI? (y/n)', 'y');\n shouldGenerate = gen.toLowerCase() === 'y' || gen.toLowerCase() === 'yes';\n }\n }\n\n console.log();\n } finally {\n rl.close();\n }\n }\n\n if (!agentName) {\n console.error('Error: agent name is required. Usage: harness init <name>');\n process.exit(1);\n }\n\n // If the user passed a path (e.g. /tmp/my-agent or ./projects/foo), use the\n // basename as the agent name and resolve the parent dir from the path.\n // Otherwise treat agentName as a bare name relative to opts.dir as before.\n const looksLikePath = agentName.includes('/') || agentName.startsWith('.');\n const targetDir = looksLikePath ? resolve(agentName) : resolve(opts.dir, agentName);\n const parentDir = looksLikePath ? resolve(targetDir, '..') : resolve(opts.dir);\n if (looksLikePath) {\n agentName = basename(targetDir);\n }\n\n try {\n // Generate CORE.md via LLM if requested\n let coreContent: string | undefined;\n if (shouldGenerate && purpose) {\n console.log('Generating CORE.md...');\n try {\n coreContent = await generateCoreMd(agentName, purpose, {});\n console.log('✓ CORE.md generated via LLM');\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n console.log(` LLM generation failed: ${message}`);\n console.log(' Using template instead');\n }\n }\n\n scaffoldHarness(targetDir, agentName, { template, purpose: purpose || undefined, coreContent });\n console.log(`\\n✓ Agent harness created: ${targetDir}`);\n\n // Auto-discover MCP servers from other tools\n if (opts.discoverMcp !== false) {\n const { discoverMcpServers, discoveredServersToYaml, filterUnsafeServers } = await import('../runtime/mcp-discovery.js');\n const discovery = discoverMcpServers();\n const safeServers = filterUnsafeServers(discovery.servers);\n\n if (safeServers.length > 0) {\n console.log(`\\n✓ Discovered ${safeServers.length} MCP server(s) from existing tools:`);\n const safeNames = new Set(safeServers.map((s) => s.name));\n for (const source of discovery.sources) {\n const kept = source.servers.filter((s) => safeNames.has(s.name));\n if (kept.length > 0) {\n console.log(` ${source.tool}: ${kept.map((s) => s.name).join(', ')}`);\n }\n }\n\n // Prompt for confirmation unless --yes or stdin is not a TTY\n let shouldAdd = true;\n if (!opts.yes && process.stdin.isTTY) {\n const readline = await import('readline');\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await new Promise<string>((res) => {\n rl.question(`\\nAdd these ${safeServers.length} server(s) to config.yaml? [Y/n] `, (a) => res(a.trim()));\n });\n shouldAdd = answer === '' || answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes';\n } finally {\n rl.close();\n }\n }\n\n if (shouldAdd) {\n const { appendFileSync } = await import('fs');\n const configPath = resolve(targetDir, 'config.yaml');\n const yaml = discoveredServersToYaml(safeServers);\n appendFileSync(configPath, '\\n' + yaml + '\\n');\n console.log(` → Added to config.yaml`);\n console.log(` → Run 'harness mcp test' to verify connections`);\n } else {\n console.log(` → Skipped MCP discovery. Add servers manually with 'harness mcp install <name>'.`);\n }\n }\n }\n\n // Auto-discover environment variables\n if (opts.discoverEnv !== false) {\n const { discoverEnvKeys } = await import('../runtime/env-discovery.js');\n const envResult = discoverEnvKeys({ dir: parentDir, extraDirs: [targetDir] });\n\n if (envResult.suggestions.length > 0) {\n console.log(`\\n✓ Detected ${envResult.keys.length} API key(s) in environment:`);\n for (const suggestion of envResult.suggestions) {\n console.log(` ${suggestion.triggeredBy} → ${suggestion.message}`);\n console.log(` Install: harness mcp install \"${suggestion.serverQuery}\" -d ${name}`);\n }\n }\n }\n\n // Auto-discover project context\n if (opts.discoverProject !== false) {\n const { discoverProjectContext } = await import('../runtime/project-discovery.js');\n const projectResult = discoverProjectContext({ dir: parentDir });\n\n if (projectResult.signals.length > 0) {\n const stack = projectResult.signals.map((s) => s.name).join(', ');\n console.log(`\\n✓ Detected project stack: ${stack}`);\n\n if (projectResult.suggestions.length > 0) {\n console.log(` Suggestions:`);\n for (const suggestion of projectResult.suggestions) {\n if (suggestion.type === 'mcp-server') {\n console.log(` Install MCP: harness mcp install \"${suggestion.target}\" -d ${name}`);\n } else {\n console.log(` Create ${suggestion.type}: ${suggestion.target}`);\n }\n }\n }\n }\n }\n\n console.log(`\\nNext steps — try these in order:`);\n console.log(` cd ${targetDir}`);\n console.log(` harness run \"What can you do?\" # see what's loaded`);\n console.log(` harness run \"Help me decide between two options: A or B\"`);\n console.log(` harness run \"Plan a weekend project for me\" # see it qualify`);\n console.log(` harness journal # see what it learned`);\n console.log(` harness learn --install # teach it to remember`);\n console.log(`\\nThe agent gets better the more you use it. See README.md inside`);\n console.log(`the harness directory for the full walkthrough.`);\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- RUN ---\nprogram\n .command('run <prompt>')\n .description('Run a prompt through the agent')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-s, --stream', 'Stream output', false)\n .option('-m, --model <model>', 'Model override (or alias: gemma, qwen, glm, claude)')\n .option('-p, --provider <provider>', 'Provider override (openrouter, anthropic, openai)')\n .option('-k, --api-key <key>', 'API key override (default: from environment)')\n .action(async (prompt: string, opts: { dir: string; stream: boolean; model?: string; provider?: string; apiKey?: string }) => {\n const { createHarness } = await import('../core/harness.js');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n\n requireHarness(dir);\n\n const modelId = resolveModel(opts.model);\n try {\n const agent = createHarness({\n dir,\n model: modelId,\n provider: opts.provider,\n apiKey: opts.apiKey,\n });\n\n if (opts.stream) {\n const streamResult = agent.stream(prompt);\n process.stdout.write('\\n');\n for await (const chunk of streamResult.textStream) {\n process.stdout.write(chunk);\n }\n process.stdout.write('\\n\\n');\n const result = await streamResult.result;\n const toolInfo = result.toolCalls.length > 0\n ? ` | ${result.toolCalls.length} tool call(s)`\n : '';\n const stepInfo = result.steps > 1 ? ` | ${result.steps} steps` : '';\n console.error(\n `[${result.usage.totalTokens} tokens${stepInfo}${toolInfo} | session: ${result.session_id}]`\n );\n } else {\n const result = await agent.run(prompt);\n console.log('\\n' + result.text + '\\n');\n const toolInfo = result.toolCalls.length > 0\n ? ` | ${result.toolCalls.length} tool call(s)`\n : '';\n const stepInfo = result.steps > 1 ? ` | ${result.steps} steps` : '';\n console.error(\n `[${result.usage.totalTokens} tokens${stepInfo}${toolInfo} | session: ${result.session_id}]`\n );\n }\n\n await agent.shutdown();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- CHAT (interactive REPL with conversation memory) ---\nprogram\n .command('chat')\n .description('Start an interactive chat session with conversation memory')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-m, --model <model>', 'Model override')\n .option('-p, --provider <provider>', 'Provider override (openrouter, anthropic, openai)')\n .option('-k, --api-key <key>', 'API key override (default: from environment)')\n .option('--fresh', 'Start fresh (clear conversation history)', false)\n .action(async (opts: { dir: string; model?: string; provider?: string; apiKey?: string; fresh: boolean }) => {\n const { Conversation } = await import('../runtime/conversation.js');\n const { loadConfig } = await import('../core/config.js');\n const { buildToolSet } = await import('../runtime/tool-executor.js');\n const { createMcpManager } = await import('../runtime/mcp.js');\n const readline = await import('readline');\n const dir = resolve(opts.dir);\n\n requireHarness(dir);\n\n const config = loadConfig(dir);\n\n // Load tools (markdown + programmatic + MCP)\n let mcpTools: Record<string, unknown> = {};\n const mcpManager = createMcpManager(config);\n if (mcpManager.hasServers()) {\n try {\n await mcpManager.connect();\n mcpTools = mcpManager.getTools();\n } catch (err: unknown) {\n console.error(`Warning: MCP connection failed: ${formatError(err)}`);\n }\n }\n const toolSet = buildToolSet(dir, undefined, mcpTools as Record<string, never>);\n const toolCount = Object.keys(toolSet).length;\n\n const conv = new Conversation(dir, opts.apiKey, { tools: toolSet });\n const modelId = resolveModel(opts.model);\n if (modelId) conv.setModelOverride(modelId);\n if (opts.provider) conv.setProviderOverride(opts.provider);\n if (opts.fresh) conv.clear();\n await conv.init();\n\n const history = conv.getHistory();\n console.log(`\\n${config.agent.name} is ready. ${history.length > 0 ? `(${history.length} messages in history)` : ''}${toolCount > 0 ? ` | ${toolCount} tools` : ''}`);\n console.log(`Type your message, \"clear\" to reset, or \"exit\" to quit.\\n`);\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n let closed = false;\n let sending = false; // Track in-flight LLM requests\n let pendingClose = false; // Deferred close requested while sending\n\n const cleanup = async () => {\n if (mcpManager.hasServers()) {\n await mcpManager.close();\n }\n };\n\n const doClose = async () => {\n if (closed) return;\n closed = true;\n await cleanup();\n };\n\n rl.on('close', async () => {\n if (sending) {\n // Defer cleanup until the in-flight request finishes\n pendingClose = true;\n return;\n }\n await doClose();\n });\n\n const ask = () => {\n if (closed) return;\n rl.question('> ', async (input) => {\n if (closed) return;\n const trimmed = input.trim();\n if (!trimmed || trimmed === 'exit' || trimmed === 'quit') {\n await doClose();\n rl.close();\n return;\n }\n if (trimmed === 'clear') {\n conv.clear();\n console.log('[conversation cleared]\\n');\n ask();\n return;\n }\n\n sending = true;\n try {\n const streamResult = conv.sendStream(trimmed);\n process.stdout.write('\\n');\n for await (const chunk of streamResult.textStream) {\n process.stdout.write(chunk);\n }\n process.stdout.write('\\n');\n const meta = await streamResult.result;\n if (meta.usage.totalTokens > 0) {\n const toolInfo = meta.toolCalls.length > 0\n ? ` | ${meta.toolCalls.length} tool call(s)`\n : '';\n const stepInfo = meta.steps > 1 ? ` | ${meta.steps} steps` : '';\n console.error(`[${meta.usage.totalTokens} tokens${stepInfo}${toolInfo}]`);\n }\n process.stdout.write('\\n');\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n } finally {\n sending = false;\n // If readline closed while we were sending, clean up now\n if (pendingClose) {\n await doClose();\n return;\n }\n }\n\n ask();\n });\n };\n\n ask();\n });\n\n// --- INFO ---\nprogram\n .command('info')\n .description('Show harness info and loaded context')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; json: boolean }) => {\n const { loadConfig } = await import('../core/config.js');\n const { buildSystemPrompt } = await import('../runtime/context-loader.js');\n const { loadState } = await import('../runtime/state.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n const config = loadConfig(dir);\n const ctx = buildSystemPrompt(dir, config);\n const state = loadState(dir);\n\n // MCP servers\n const mcpServers = config.mcp?.servers ?? {};\n const mcpEntries = Object.entries(mcpServers);\n\n if (opts.json) {\n const info = {\n agent: { name: config.agent.name, version: config.agent.version },\n model: config.model.id,\n provider: config.model.provider,\n state: { mode: state.mode, last_interaction: state.last_interaction },\n context: {\n max_tokens: ctx.budget.max_tokens,\n used_tokens: ctx.budget.used_tokens,\n remaining: ctx.budget.remaining,\n loaded_files: ctx.budget.loaded_files,\n },\n mcp: mcpEntries.map(([name, s]) => ({\n name,\n transport: s.transport,\n enabled: s.enabled !== false,\n })),\n };\n console.log(JSON.stringify(info, null, 2));\n return;\n }\n\n console.log(`\\nAgent: ${config.agent.name} v${config.agent.version}`);\n console.log(`Model: ${config.model.id}`);\n console.log(`State: ${state.mode}`);\n console.log(`Last interaction: ${state.last_interaction}`);\n console.log(`\\nContext budget:`);\n console.log(` Max tokens: ${ctx.budget.max_tokens}`);\n console.log(` Used: ~${ctx.budget.used_tokens}`);\n console.log(` Remaining: ~${ctx.budget.remaining}`);\n console.log(` Files loaded: ${ctx.budget.loaded_files.length}`);\n ctx.budget.loaded_files.forEach(f => console.log(` - ${f}`));\n\n if (mcpEntries.length > 0) {\n const enabledCount = mcpEntries.filter(([, s]) => s.enabled !== false).length;\n console.log(`\\nMCP servers: ${mcpEntries.length} configured (${enabledCount} enabled)`);\n for (const [name, s] of mcpEntries) {\n const enabled = s.enabled !== false;\n console.log(` ${enabled ? '+' : '-'} ${name} (${s.transport})`);\n }\n }\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- PROMPT (show the assembled system prompt) ---\nprogram\n .command('prompt')\n .description('Show the full assembled system prompt')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output metadata as JSON (includes prompt, budget, warnings)')\n .action(async (opts: { dir: string; json: boolean }) => {\n const { loadConfig } = await import('../core/config.js');\n const { buildSystemPrompt } = await import('../runtime/context-loader.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n const config = loadConfig(dir);\n const ctx = buildSystemPrompt(dir, config);\n\n if (opts.json) {\n console.log(JSON.stringify({\n systemPrompt: ctx.systemPrompt,\n budget: ctx.budget,\n warnings: ctx.warnings,\n parseErrors: ctx.parseErrors,\n }, null, 2));\n return;\n }\n\n console.log(ctx.systemPrompt);\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- DEV (watch mode + scheduler) ---\nprogram\n .command('dev')\n .description('Start dev mode — watches for file changes, rebuilds indexes, runs scheduled workflows, serves dashboard')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-k, --api-key <key>', 'API key override (default: from environment)')\n .option('--no-schedule', 'Disable workflow scheduler')\n .option('--no-auto-process', 'Disable auto-processing of primitives on save')\n .option('--no-web', 'Disable web dashboard server')\n .option('-p, --port <number>', 'Web dashboard port', '3000')\n .action(async (opts: { dir: string; apiKey?: string; schedule: boolean; autoProcess: boolean; web: boolean; port: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const { rebuildAllIndexes } = await import('../runtime/indexer.js');\n const { createWatcher } = await import('../runtime/watcher.js');\n const { Scheduler } = await import('../runtime/scheduler.js');\n const { autoProcessAll } = await import('../runtime/auto-processor.js');\n const { generateSystemMd } = await import('../cli/scaffold.js');\n const { writeFileSync } = await import('fs');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const doAutoProcess = opts.autoProcess && (config.runtime?.auto_process !== false);\n console.log(`\\n[dev] Watching \"${config.agent.name}\" harness at ${dir}`);\n\n // Auto-process all primitives on startup (fills missing frontmatter, L0/L1)\n if (doAutoProcess) {\n const processed = autoProcessAll(dir);\n if (processed.length > 0) {\n console.log(`[dev] Auto-processed ${processed.length} file(s) on startup`);\n for (const r of processed) {\n const rel = r.path.replace(dir + '/', '');\n console.log(` ${rel}: ${r.fixes.join(', ')}`);\n }\n }\n }\n\n // Regenerate SYSTEM.md from current directory structure\n const systemPath = join(dir, 'SYSTEM.md');\n const newSystem = generateSystemMd(dir, config.agent.name);\n writeFileSync(systemPath, newSystem, 'utf-8');\n console.log(`[dev] SYSTEM.md regenerated from directory structure`);\n\n // Initial index build\n const extDirs = config.extensions?.directories ?? [];\n rebuildAllIndexes(dir, extDirs);\n console.log(`[dev] Indexes rebuilt${extDirs.length ? ` (+ ${extDirs.length} extension dir(s))` : ''}`);\n\n // Start scheduler if there are workflows\n let scheduler: InstanceType<typeof Scheduler> | null = null;\n if (opts.schedule) {\n scheduler = new Scheduler({\n harnessDir: dir,\n apiKey: opts.apiKey,\n autoJournal: config.intelligence?.auto_journal ?? false,\n autoLearn: config.intelligence?.auto_learn ?? false,\n onRun: (id, result) => {\n console.log(`[scheduler] ✓ ${id}: ${result.slice(0, 100)}`);\n },\n onError: (id, error) => {\n console.error(`[scheduler] ✗ ${id}: ${error.message}`);\n },\n onSchedule: (id, cronExpr) => {\n console.log(`[scheduler] Scheduled: ${id} (${cronExpr})`);\n },\n onArchival: (sessions, journals) => {\n if (sessions + journals > 0) {\n console.log(`[scheduler] Archived ${sessions} session(s), ${journals} journal(s)`);\n }\n },\n onJournal: (date, sessionsCount) => {\n console.log(`[scheduler] Auto-journal: synthesized ${sessionsCount} session(s) for ${date}`);\n },\n onLearn: (installed, skipped) => {\n console.log(`[scheduler] Auto-learn: ${installed} instinct(s) installed, ${skipped} skipped`);\n },\n });\n scheduler.start();\n\n const scheduled = scheduler.listScheduled();\n const features: string[] = [];\n if (scheduled.length > 0) features.push(`${scheduled.length} workflow(s)`);\n if (config.intelligence?.auto_journal) features.push('auto-journal');\n if (config.intelligence?.auto_learn) features.push('auto-learn');\n if (features.length > 0) {\n console.log(`[dev] Scheduler started: ${features.join(', ')}`);\n } else {\n console.log(`[dev] Scheduler running (no workflows or intelligence features configured)`);\n }\n }\n\n // Start web dashboard server\n let webServer: { server: unknown; broadcaster: { broadcast: (e: { type: string; data: unknown; timestamp: string }) => void } } | null = null;\n if (opts.web) {\n const { startWebServer } = await import('../runtime/web-server.js');\n const port = parseInt(opts.port, 10) || 3000;\n webServer = await startWebServer({\n harnessDir: dir,\n port,\n apiKey: opts.apiKey,\n onStart: (p) => console.log(`[dev] Dashboard: http://localhost:${p}`),\n });\n }\n\n const sseBroadcast = (type: string, data: unknown): void => {\n webServer?.broadcaster.broadcast({ type, data, timestamp: new Date().toISOString() });\n };\n\n // Start watching (including extension directories and config.yaml)\n createWatcher({\n harnessDir: dir,\n extraDirs: extDirs,\n watchConfig: true,\n autoProcess: doAutoProcess,\n onChange: (path, event) => {\n const rel = path.replace(dir + '/', '');\n console.log(`[dev] ${event}: ${rel}`);\n sseBroadcast('file_change', { path: rel, event });\n },\n onIndexRebuild: (directory) => {\n console.log(`[dev] Index rebuilt: ${directory}/_index.md`);\n sseBroadcast('index_rebuild', { directory });\n },\n onAutoProcess: (result) => {\n if (result.modified) {\n const rel = result.path.replace(dir + '/', '');\n console.log(`[dev] Auto-processed: ${rel} (${result.fixes.join(', ')})`);\n sseBroadcast('auto_process', { path: rel, fixes: result.fixes });\n }\n },\n onConfigChange: () => {\n try {\n const newConfig = loadConfig(dir);\n console.log(`[dev] Config reloaded: model=${newConfig.model.id}`);\n sseBroadcast('config_change', { model: newConfig.model.id });\n } catch (err: unknown) {\n console.error(`[dev] Config reload failed: ${formatError(err)}`);\n }\n },\n onError: (err) => {\n console.error(`[dev] Watcher error: ${err.message}`);\n },\n });\n\n console.log(`[dev] Watching for changes... (Ctrl+C to stop)\\n`);\n\n // Graceful shutdown\n const cleanup = () => {\n console.log(`\\n[dev] Shutting down...`);\n if (scheduler) scheduler.stop();\n if (webServer?.server && typeof (webServer.server as { close?: () => void }).close === 'function') {\n (webServer.server as { close: () => void }).close();\n }\n process.exit(0);\n };\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n });\n\n// --- INDEX (rebuild all indexes) ---\nprogram\n .command('index')\n .description('Rebuild all index files')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { rebuildAllIndexes } = await import('../runtime/indexer.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n\n let extDirs: string[] = [];\n try {\n const config = loadConfig(dir);\n extDirs = config.extensions?.directories ?? [];\n } catch (err) {\n if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n rebuildAllIndexes(dir, extDirs);\n console.log(`✓ All indexes rebuilt in ${dir}`);\n });\n\n// --- PROCESS (auto-process all primitives) ---\nprogram\n .command('process')\n .description('Auto-process all primitives: fill missing frontmatter and generate L0/L1 summaries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--no-frontmatter', 'Skip frontmatter generation')\n .option('--no-summaries', 'Skip L0/L1 summary generation')\n .action(async (opts: { dir: string; frontmatter: boolean; summaries: boolean }) => {\n const { autoProcessAll } = await import('../runtime/auto-processor.js');\n const dir = resolve(opts.dir);\n\n requireHarness(dir);\n\n const results = autoProcessAll(dir, {\n generateFrontmatter: opts.frontmatter,\n generateSummaries: opts.summaries,\n });\n\n if (results.length === 0) {\n console.log('All primitives are up to date.');\n } else {\n for (const r of results) {\n const rel = r.path.replace(dir + '/', '');\n if (r.modified) {\n console.log(`✓ ${rel}: ${r.fixes.join(', ')}`);\n }\n for (const err of r.errors) {\n console.error(`✗ ${rel}: ${err}`);\n }\n }\n const modified = results.filter((r) => r.modified).length;\n const errors = results.filter((r) => r.errors.length > 0).length;\n console.log(`\\nProcessed ${modified} file(s)${errors > 0 ? `, ${errors} error(s)` : ''}`);\n }\n });\n\n// --- SYSTEM (regenerate SYSTEM.md from directory structure) ---\nprogram\n .command('system')\n .description('Regenerate SYSTEM.md from current directory structure')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const { generateSystemMd } = await import('../cli/scaffold.js');\n const { writeFileSync } = await import('fs');\n const dir = resolve(opts.dir);\n\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const systemPath = join(dir, 'SYSTEM.md');\n const content = generateSystemMd(dir, config.agent.name);\n writeFileSync(systemPath, content, 'utf-8');\n console.log(`✓ SYSTEM.md regenerated at ${systemPath}`);\n });\n\n// --- JOURNAL (synthesize sessions into journal) ---\nprogram\n .command('journal')\n .description('Synthesize sessions into journal entries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--date <date>', 'Date to synthesize (YYYY-MM-DD)')\n .option('--from <date>', 'Start of date range (YYYY-MM-DD)')\n .option('--to <date>', 'End of date range (YYYY-MM-DD, default: today)')\n .option('--all', 'Synthesize all dates with sessions', false)\n .option('--force', 'Re-synthesize even if journal exists', false)\n .option('--pending', 'Show dates with sessions but no journal', false)\n .option('--auto-harvest', 'Auto-install instinct candidates from synthesized journals', false)\n .action(async (opts: { dir: string; date?: string; from?: string; to?: string; all: boolean; force: boolean; pending: boolean; autoHarvest: boolean }) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n\n requireHarness(dir);\n\n // Show pending (unjournaled) dates\n if (opts.pending) {\n const { listUnjournaled } = await import('../runtime/journal.js');\n const dates = listUnjournaled(dir);\n if (dates.length === 0) {\n console.log('All sessions have been journaled.');\n } else {\n console.log(`\\n${dates.length} date(s) with unjournaled sessions:\\n`);\n dates.forEach((d) => console.log(` ${d}`));\n console.log(`\\nRun \"harness journal --all\" to synthesize them.\\n`);\n }\n return;\n }\n\n // Range mode (--from/--to or --all)\n if (opts.from || opts.all) {\n const { synthesizeJournalRange } = await import('../runtime/journal.js');\n\n try {\n const label = opts.all ? 'all dates' : `${opts.from}${opts.to ? ` to ${opts.to}` : ' to today'}`;\n console.log(`Synthesizing journals for ${label}${opts.force ? ' (force)' : ''}...`);\n\n const entries = await synthesizeJournalRange(dir, {\n from: opts.from,\n to: opts.to,\n all: opts.all,\n force: opts.force,\n });\n\n if (entries.length === 0) {\n console.log('No sessions to synthesize (or all dates already journaled).');\n return;\n }\n\n console.log(`\\n✓ ${entries.length} journal(s) synthesized:\\n`);\n for (const entry of entries) {\n const sessionCount = entry.sessions.length;\n const instinctCount = entry.instinct_candidates.length;\n console.log(` ${entry.date}: ${sessionCount} session(s), ${entry.tokens_used} tokens${instinctCount > 0 ? `, ${instinctCount} instinct candidate(s)` : ''}`);\n }\n console.log();\n\n // Auto-harvest: install instinct candidates from synthesized journals\n if (opts.autoHarvest) {\n const { harvestInstincts } = await import('../runtime/instinct-learner.js');\n const dates = entries.map((e) => e.date).sort();\n const harvest = harvestInstincts(dir, {\n from: dates[0],\n to: dates[dates.length - 1],\n install: true,\n });\n if (harvest.installed.length > 0) {\n console.log(`Auto-harvested ${harvest.installed.length} instinct(s):`);\n harvest.installed.forEach((id) => console.log(` ✓ ${id}`));\n console.log();\n }\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n return;\n }\n\n // Single date mode (default)\n const { synthesizeJournal } = await import('../runtime/journal.js');\n\n try {\n console.log(`Synthesizing journal...`);\n const entry = await synthesizeJournal(dir, opts.date);\n console.log(`\\n✓ Journal for ${entry.date}`);\n console.log(` Sessions: ${entry.sessions.length}`);\n console.log(` Tokens: ${entry.tokens_used}`);\n if (entry.instinct_candidates.length > 0) {\n console.log(` Instinct candidates:`);\n entry.instinct_candidates.forEach(c => console.log(` - ${c}`));\n\n // Auto-harvest: install instinct candidates from this journal\n if (opts.autoHarvest) {\n const { harvestInstincts } = await import('../runtime/instinct-learner.js');\n const harvest = harvestInstincts(dir, {\n from: entry.date,\n to: entry.date,\n install: true,\n });\n if (harvest.installed.length > 0) {\n console.log(` Auto-harvested:`);\n harvest.installed.forEach((id) => console.log(` ✓ ${id}`));\n }\n }\n }\n console.log(`\\n${entry.synthesis}`);\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- COMPRESS (weekly journal roll-ups) ---\nprogram\n .command('compress')\n .description('Compress daily journals into weekly roll-up summaries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--force', 'Overwrite existing weekly summaries', false)\n .action(async (opts: { dir: string; force: boolean }) => {\n const { compressJournals } = await import('../runtime/journal.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const results = compressJournals(dir, { force: opts.force });\n\n if (results.length === 0) {\n console.log('\\nNo complete past weeks to compress (or all already compressed).\\n');\n return;\n }\n\n console.log(`\\n✓ ${results.length} weekly summary(ies) created:\\n`);\n for (const week of results) {\n const insights = week.allInsights.length;\n const instincts = week.allInstinctCandidates.length;\n console.log(` ${week.weekStart} to ${week.weekEnd} (${week.journalDates.length} days)`);\n console.log(` ${insights} insight(s), ${instincts} instinct candidate(s)`);\n }\n console.log();\n });\n\n// --- LEARN (propose and install instincts) ---\nprogram\n .command('learn')\n .description('Analyze sessions and propose new instincts')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--install', 'Auto-install proposed instincts', false)\n .action(async (opts: { dir: string; install: boolean }) => {\n const { learnFromSessions } = await import('../runtime/instinct-learner.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n console.log(`Analyzing sessions for instinct candidates...`);\n const result = await learnFromSessions(dir, opts.install);\n\n if (result.candidates.length === 0) {\n console.log(`No instinct candidates found.`);\n return;\n }\n\n console.log(`\\n${result.candidates.length} instinct candidate(s):\\n`);\n for (const c of result.candidates) {\n const status = result.installed.includes(c.id)\n ? '✓ installed'\n : result.skipped.includes(c.id)\n ? '⊘ skipped (exists)'\n : '○ proposed';\n console.log(` [${status}] ${c.id} (${c.confidence})`);\n console.log(` ${c.behavior}`);\n console.log(` Provenance: ${c.provenance}\\n`);\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- HARVEST (extract instinct candidates from journals) ---\nprogram\n .command('harvest')\n .description('Extract instinct candidates from journal entries and optionally install them')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--install', 'Auto-install candidates as draft instincts', false)\n .action(async (opts: { dir: string; from?: string; to?: string; install: boolean }) => {\n const { harvestInstincts } = await import('../runtime/instinct-learner.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const result = harvestInstincts(dir, {\n from: opts.from,\n to: opts.to,\n install: opts.install,\n });\n\n console.log(`\\nScanned ${result.journalsScanned} journal(s)`);\n\n if (result.candidates.length === 0) {\n console.log(`No new instinct candidates found.\\n`);\n return;\n }\n\n console.log(`Found ${result.candidates.length} candidate(s):\\n`);\n for (const c of result.candidates) {\n const status = result.installed.includes(c.id)\n ? '✓ installed'\n : result.skipped.includes(c.id)\n ? '⊘ skipped (exists)'\n : '○ proposed';\n console.log(` [${status}] ${c.id}`);\n console.log(` ${c.behavior}`);\n console.log(` Source: ${c.provenance}\\n`);\n }\n\n if (!opts.install && result.candidates.length > 0) {\n console.log(`Run with --install to create instinct files.\\n`);\n }\n });\n\n// NOTE: \"install\" command moved to universal installer below (Phase 9)\n\n// --- INTAKE (process all files in intake/) ---\nprogram\n .command('intake')\n .description('Process all pending files in the intake/ directory')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { processIntake } = await import('../runtime/intake.js');\n const dir = resolve(opts.dir);\n\n const results = processIntake(dir);\n\n if (results.length === 0) {\n console.log(`No files in intake/`);\n return;\n }\n\n for (const { file, result } of results) {\n if (result.installed) {\n console.log(`✓ ${file} → ${result.evalResult.type}`);\n } else {\n console.log(`✗ ${file}: ${result.evalResult.errors.join(', ')}`);\n }\n }\n });\n\n// --- VALIDATE (check harness integrity) ---\nprogram\n .command('validate')\n .description('Validate harness structure and configuration')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; json: boolean }) => {\n const { validateHarness } = await import('../runtime/validator.js');\n const dir = resolve(opts.dir);\n\n const result = validateHarness(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n if (result.errors.length > 0) process.exit(1);\n return;\n }\n\n // Output results\n console.log(`\\nHarness validation: ${dir}\\n`);\n\n if (result.ok.length > 0) {\n for (const msg of result.ok) {\n console.log(` ✓ ${msg}`);\n }\n }\n\n if (result.warnings.length > 0) {\n console.log();\n for (const msg of result.warnings) {\n console.log(` ⚠ ${msg}`);\n }\n }\n\n if (result.errors.length > 0) {\n console.log();\n for (const msg of result.errors) {\n console.log(` ✗ ${msg}`);\n }\n }\n\n console.log(`\\nSummary: ${result.ok.length} passed, ${result.warnings.length} warnings, ${result.errors.length} errors`);\n console.log(`Primitives: ${result.totalPrimitives} loaded${result.parseErrors.length > 0 ? `, ${result.parseErrors.length} parse error(s)` : ''}\\n`);\n\n if (result.errors.length > 0) {\n process.exit(1);\n }\n });\n\n// --- DOCTOR (validate + batch auto-fix) ---\nprogram\n .command('doctor')\n .description('Validate harness and auto-fix all fixable issues in one pass')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { doctorHarness } = await import('../runtime/validator.js');\n const dir = resolve(opts.dir);\n\n console.log(`\\nRunning doctor on: ${dir}\\n`);\n const result = doctorHarness(dir);\n\n // Show fixes first\n if (result.fixes.length > 0) {\n console.log(` Auto-fixed ${result.fixes.length} issue(s):`);\n for (const fix of result.fixes) {\n console.log(` ✓ ${fix}`);\n }\n console.log();\n }\n\n // Show remaining checks\n if (result.ok.length > 0) {\n for (const msg of result.ok) {\n console.log(` ✓ ${msg}`);\n }\n }\n\n if (result.warnings.length > 0) {\n console.log();\n for (const msg of result.warnings) {\n console.log(` ⚠ ${msg}`);\n }\n }\n\n if (result.errors.length > 0) {\n console.log();\n for (const msg of result.errors) {\n console.log(` ✗ ${msg}`);\n }\n }\n\n const fixLabel = result.fixes.length > 0 ? `, ${result.fixes.length} fixed` : '';\n console.log(`\\nSummary: ${result.ok.length} ok, ${result.warnings.length} warnings, ${result.errors.length} errors${fixLabel}`);\n console.log(`Primitives: ${result.totalPrimitives}\\n`);\n\n if (result.errors.length > 0) {\n process.exit(1);\n }\n });\n\n// --- FIX (auto-fix common issues in a capability file) ---\nprogram\n .command('fix <file>')\n .description('Auto-fix common issues in a capability markdown file (missing id, status, L0/L1)')\n .action(async (file: string) => {\n const { fixCapability } = await import('../runtime/intake.js');\n const filePath = resolve(file);\n\n const result = fixCapability(filePath);\n\n if (result.fixes_applied.length > 0) {\n console.log(`Fixed ${result.fixes_applied.length} issue(s) in ${filePath}:`);\n for (const fix of result.fixes_applied) {\n console.log(` ✓ ${fix}`);\n }\n } else {\n console.log('No auto-fixable issues found.');\n }\n\n if (result.warnings.length > 0) {\n for (const w of result.warnings) {\n console.log(` ⚠ ${w}`);\n }\n }\n\n if (result.errors.length > 0) {\n console.error(`\\nRemaining errors (manual fix required):`);\n for (const e of result.errors) {\n console.error(` ✗ ${e}`);\n }\n process.exit(1);\n }\n });\n\n// --- CLEANUP (archive or remove old sessions/journals per retention policy) ---\nprogram\n .command('cleanup')\n .description('Archive sessions and journals older than retention period')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--dry-run', 'Show what would be archived without acting', false)\n .option('--delete', 'Permanently delete instead of archiving', false)\n .action(async (opts: { dir: string; dryRun: boolean; delete: boolean }) => {\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const sessionDays = config.memory.session_retention_days;\n const journalDays = config.memory.journal_retention_days;\n\n if (opts.dryRun) {\n const { listExpiredFiles } = await import('../runtime/sessions.js');\n const expired = listExpiredFiles(dir, sessionDays, journalDays);\n const action = opts.delete ? 'delete' : 'archive';\n console.log(`\\nDry run — retention policy (sessions: ${sessionDays}d, journals: ${journalDays}d)\\n`);\n console.log(`Would ${action} ${expired.sessionFiles.length} session(s):`);\n expired.sessionFiles.forEach((f) => console.log(` - ${f}`));\n console.log(`Would ${action} ${expired.journalFiles.length} journal(s):`);\n expired.journalFiles.forEach((f) => console.log(` - ${f}`));\n return;\n }\n\n if (opts.delete) {\n const { cleanupOldFiles } = await import('../runtime/sessions.js');\n const result = cleanupOldFiles(dir, sessionDays, journalDays);\n console.log(`\\nDeleted ${result.sessionsRemoved} session(s), ${result.journalsRemoved} journal(s)`);\n if (result.sessionFiles.length > 0) {\n result.sessionFiles.forEach((f) => console.log(` - ${f}`));\n }\n if (result.journalFiles.length > 0) {\n result.journalFiles.forEach((f) => console.log(` - ${f}`));\n }\n } else {\n const { archiveOldFiles } = await import('../runtime/sessions.js');\n const result = archiveOldFiles(dir, sessionDays, journalDays);\n console.log(`\\nArchived ${result.sessionsArchived} session(s), ${result.journalsArchived} journal(s)`);\n if (result.sessionFiles.length > 0) {\n console.log(` Sessions → memory/sessions/archive/`);\n result.sessionFiles.forEach((f) => console.log(` - ${f}`));\n }\n if (result.journalFiles.length > 0) {\n console.log(` Journals → memory/journal/archive/`);\n result.journalFiles.forEach((f) => console.log(` - ${f}`));\n }\n }\n console.log();\n });\n\n// --- STATUS (rich harness overview) ---\nprogram\n .command('status')\n .description('Show harness status: primitives, sessions, config, state')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { existsSync, readdirSync } = await import('fs');\n const { validateHarness } = await import('../runtime/validator.js');\n const { loadConfig } = await import('../core/config.js');\n const { loadState } = await import('../runtime/state.js');\n const { listSessions } = await import('../runtime/sessions.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const state = loadState(dir);\n const validation = validateHarness(dir);\n const sessions = listSessions(dir);\n\n // Header\n console.log(`\\n ${config.agent.name} v${config.agent.version}`);\n console.log(` Model: ${config.model.provider}/${config.model.id}`);\n console.log(` Mode: ${state.mode}`);\n\n // Primitives\n console.log(`\\n Primitives (${validation.totalPrimitives} total):`);\n for (const [dir, count] of validation.primitiveCounts) {\n if (count > 0) console.log(` ${dir}: ${count}`);\n }\n const emptyDirs = Array.from(validation.primitiveCounts.entries())\n .filter(([, c]) => c === 0)\n .map(([d]) => d);\n if (emptyDirs.length > 0) {\n console.log(` (empty: ${emptyDirs.join(', ')})`);\n }\n\n // Sessions\n console.log(`\\n Sessions: ${sessions.length} total`);\n if (sessions.length > 0) {\n const recent = sessions.slice(0, 3);\n for (const s of recent) {\n console.log(` ${s.id}`);\n }\n if (sessions.length > 3) console.log(` ... and ${sessions.length - 3} more`);\n }\n\n // Journals\n const journalDir = join(dir, 'memory', 'journal');\n let journalCount = 0;\n if (existsSync(journalDir)) {\n journalCount = readdirSync(journalDir).filter(\n (f) => f.endsWith('.md') && !f.startsWith('.') && !f.startsWith('_'),\n ).length;\n }\n console.log(` Journals: ${journalCount}`);\n\n // MCP Servers\n const mcpServers = config.mcp?.servers ?? {};\n const mcpEntries = Object.entries(mcpServers);\n if (mcpEntries.length > 0) {\n const enabledCount = mcpEntries.filter(([, s]) => s.enabled !== false).length;\n console.log(`\\n MCP Servers: ${mcpEntries.length} configured (${enabledCount} enabled)`);\n for (const [name, serverConfig] of mcpEntries) {\n const enabled = serverConfig.enabled !== false;\n const icon = enabled ? '+' : '-';\n const detail = serverConfig.transport === 'stdio'\n ? serverConfig.command ?? ''\n : serverConfig.url ?? '';\n console.log(` [${icon}] ${name} (${serverConfig.transport}) ${detail}`);\n }\n }\n\n // State\n if (state.goals.length > 0) {\n console.log(`\\n Goals:`);\n for (const g of state.goals) {\n console.log(` - ${g}`);\n }\n }\n if (state.active_workflows.length > 0) {\n console.log(`\\n Active workflows:`);\n for (const w of state.active_workflows) {\n console.log(` - ${w}`);\n }\n }\n if (state.unfinished_business.length > 0) {\n console.log(`\\n Unfinished business:`);\n for (const u of state.unfinished_business) {\n console.log(` - ${u}`);\n }\n }\n\n // Health\n const healthIssues = validation.errors.length + validation.warnings.length;\n if (healthIssues > 0) {\n console.log(`\\n Health: ${validation.errors.length} error(s), ${validation.warnings.length} warning(s)`);\n if (validation.errors.length > 0) {\n console.log(` Run 'harness validate' for details`);\n }\n } else {\n console.log(`\\n Health: OK`);\n }\n\n console.log(` Last interaction: ${state.last_interaction}\\n`);\n });\n\n// --- SCRATCH (write to working memory) ---\nprogram\n .command('scratch')\n .description('Write a note to scratch.md (working memory)')\n .argument('<note...>', 'Note to write')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--clear', 'Clear scratch before writing', false)\n .option('--show', 'Show current scratch contents', false)\n .action(async (note: string[], opts: { dir: string; clear: boolean; show: boolean }) => {\n const { readFileSync, writeFileSync, existsSync, mkdirSync } = await import('fs');\n const scratchPath = join(resolve(opts.dir), 'memory', 'scratch.md');\n const memoryDir = join(resolve(opts.dir), 'memory');\n\n if (!existsSync(memoryDir)) {\n mkdirSync(memoryDir, { recursive: true });\n }\n\n if (opts.show) {\n if (existsSync(scratchPath)) {\n const content = readFileSync(scratchPath, 'utf-8');\n console.log(content || '(empty)');\n } else {\n console.log('(no scratch.md)');\n }\n return;\n }\n\n const noteText = note.join(' ');\n\n if (opts.clear) {\n writeFileSync(scratchPath, noteText + '\\n', 'utf-8');\n console.log('✓ Scratch cleared and updated');\n } else {\n const existing = existsSync(scratchPath) ? readFileSync(scratchPath, 'utf-8') : '';\n const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 19);\n const entry = `[${timestamp}] ${noteText}\\n`;\n writeFileSync(scratchPath, existing + entry, 'utf-8');\n console.log('✓ Note added to scratch');\n }\n });\n\n// --- WORKFLOW (list and run workflows) ---\nconst workflowCmd = program\n .command('workflow')\n .description('Manage workflows');\n\nworkflowCmd\n .command('list')\n .description('List all workflows and their schedules')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { loadDirectory } = await import('../primitives/loader.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const workflowDir = join(dir, 'workflows');\n if (!existsSync(workflowDir)) {\n console.log('\\nNo workflows/ directory. Create workflow files to enable scheduling.\\n');\n return;\n }\n\n const docs = loadDirectory(workflowDir);\n if (docs.length === 0) {\n console.log('\\nNo workflows defined.\\n');\n return;\n }\n\n console.log(`\\n${docs.length} workflow(s):\\n`);\n for (const doc of docs) {\n const schedule = doc.frontmatter.schedule || '(no schedule)';\n const status = doc.frontmatter.status === 'active' ? '' : ` [${doc.frontmatter.status}]`;\n const withAgent = doc.frontmatter.with ? ` → ${doc.frontmatter.with}` : '';\n console.log(` ${doc.frontmatter.id}${status}`);\n console.log(` Schedule: ${schedule}${withAgent}`);\n if (doc.l0) console.log(` ${doc.l0}`);\n }\n console.log();\n });\n\nworkflowCmd\n .command('run <id>')\n .description('Execute a workflow by ID (bypasses quiet hours)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (workflowId: string, opts: { dir: string }) => {\n const { Scheduler } = await import('../runtime/scheduler.js');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n requireHarness(dir);\n\n console.log(`\\nExecuting workflow: ${workflowId}...`);\n const scheduler = new Scheduler({\n harnessDir: dir,\n autoArchival: false,\n });\n\n try {\n const result = await scheduler.runOnce(workflowId);\n console.log(`\\n✓ Workflow \"${workflowId}\" complete.\\n`);\n if (result) {\n console.log(result.slice(0, 500));\n if (result.length > 500) console.log(`\\n... (${result.length} chars total)`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`\\n✗ Workflow failed: ${msg}\\n`);\n process.exit(1);\n }\n });\n\n// --- SEARCH (find primitives by query/filters) ---\nprogram\n .command('search [query]')\n .description('Search primitives by text query and/or filters')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-t, --tag <tag>', 'Filter by tag')\n .option('--type <type>', 'Filter by primitive type (e.g., rules, skills)')\n .option('--status <status>', 'Filter by status (active, draft, archived, deprecated)')\n .option('--author <author>', 'Filter by author (human, agent, infrastructure)')\n .option('--json', 'Output as JSON')\n .action(async (query: string | undefined, opts: { dir: string; tag?: string; type?: string; status?: string; author?: string; json: boolean }) => {\n const { searchPrimitives } = await import('../runtime/search.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try {\n config = loadConfig(dir);\n } catch (err) {\n if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const results = searchPrimitives(dir, query, {\n tag: opts.tag,\n type: opts.type,\n status: opts.status,\n author: opts.author,\n }, config);\n\n if (opts.json) {\n console.log(JSON.stringify(results.map((r) => ({\n id: r.doc.frontmatter.id,\n directory: r.directory,\n status: r.doc.frontmatter.status,\n tags: r.doc.frontmatter.tags,\n l0: r.doc.l0,\n matchReason: r.matchReason,\n })), null, 2));\n return;\n }\n\n if (results.length === 0) {\n const filters = [query, opts.tag && `tag:${opts.tag}`, opts.type && `type:${opts.type}`, opts.status && `status:${opts.status}`, opts.author && `author:${opts.author}`].filter(Boolean).join(', ');\n console.log(`\\nNo results for: ${filters || '(no filters)'}\\n`);\n return;\n }\n\n console.log(`\\n${results.length} result(s):\\n`);\n for (const r of results) {\n const tags = r.doc.frontmatter.tags.length > 0 ? ` [${r.doc.frontmatter.tags.join(', ')}]` : '';\n const status = r.doc.frontmatter.status !== 'active' ? ` (${r.doc.frontmatter.status})` : '';\n console.log(` ${r.directory}/${r.doc.frontmatter.id}${status}${tags}`);\n console.log(` ${r.matchReason}`);\n if (r.doc.l0) console.log(` ${r.doc.l0}`);\n }\n console.log();\n });\n\n// --- CONFIG (show/get configuration) ---\nconst configCmd = program\n .command('config')\n .description('Show or inspect configuration');\n\nconfigCmd\n .command('show')\n .description('Show full resolved configuration (merged defaults + file + env)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const YAML = await import('yaml');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n const config = loadConfig(dir);\n console.log(`\\n# Resolved config for: ${dir}\\n`);\n console.log(YAML.stringify(config).trimEnd());\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nconfigCmd\n .command('get <key>')\n .description('Get a specific config value (dot-notation, e.g. model.id)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (key: string, opts: { dir: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n const config = loadConfig(dir);\n const parts = key.split('.');\n let value: unknown = config;\n for (const part of parts) {\n if (value === null || value === undefined || typeof value !== 'object') {\n console.error(`Error: Key \"${key}\" not found (stopped at \"${part}\")`);\n process.exit(1);\n }\n value = (value as Record<string, unknown>)[part];\n }\n\n if (value === undefined) {\n console.error(`Error: Key \"${key}\" not found`);\n process.exit(1);\n }\n\n if (typeof value === 'object' && value !== null) {\n const YAML = await import('yaml');\n console.log(YAML.stringify(value).trimEnd());\n } else {\n console.log(String(value));\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nconfigCmd\n .command('set <key> <value>')\n .description('Set a config value (writes to config.yaml)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (key: string, value: string, opts: { dir: string }) => {\n const { readFileSync, writeFileSync, existsSync } = await import('fs');\n const YAML = await import('yaml');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const configPath = join(dir, 'config.yaml');\n if (!existsSync(configPath)) {\n console.error(`Error: No config.yaml found in ${dir}`);\n process.exit(1);\n }\n\n try {\n const content = readFileSync(configPath, 'utf-8');\n const doc = YAML.parseDocument(content);\n\n // Parse the value — attempt number/boolean coercion\n let parsed: unknown = value;\n if (value === 'true') parsed = true;\n else if (value === 'false') parsed = false;\n else if (/^\\d+$/.test(value)) parsed = parseInt(value, 10);\n else if (/^\\d+\\.\\d+$/.test(value)) parsed = parseFloat(value);\n\n // Set using dot-notation path\n const parts = key.split('.');\n doc.setIn(parts, parsed);\n\n writeFileSync(configPath, doc.toString(), 'utf-8');\n\n // Validate the resulting config\n const { loadConfig } = await import('../core/config.js');\n try {\n loadConfig(dir);\n console.log(`✓ ${key} = ${String(parsed)}`);\n } catch (err: unknown) {\n console.error(`Warning: Config saved but validation failed: ${formatError(err)}`);\n console.error(`You may want to revert: harness config set ${key} <previous-value>`);\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- METRICS (workflow execution stats) ---\nconst metricsCmd = program\n .command('metrics')\n .description('View workflow execution metrics and stats');\n\nmetricsCmd\n .command('show')\n .description('Show stats for all workflows (default)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--workflow <id>', 'Show stats for a specific workflow')\n .action(async (opts: { dir: string; workflow?: string }) => {\n const { getAllWorkflowStats, getWorkflowStats } = await import('../runtime/metrics.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n if (opts.workflow) {\n const stats = getWorkflowStats(dir, opts.workflow);\n if (!stats) {\n console.log(`\\nNo metrics recorded for workflow \"${opts.workflow}\".\\n`);\n return;\n }\n console.log(`\\nWorkflow: ${stats.workflow_id}\\n`);\n console.log(` Runs: ${stats.total_runs}`);\n console.log(` Successes: ${stats.successes}`);\n console.log(` Failures: ${stats.failures}`);\n console.log(` Success rate: ${(stats.success_rate * 100).toFixed(1)}%`);\n console.log(` Avg duration: ${formatDuration(stats.avg_duration_ms)}`);\n console.log(` Total tokens: ${stats.total_tokens}`);\n console.log(` Last run: ${stats.last_run}`);\n if (stats.last_success) console.log(` Last success: ${stats.last_success}`);\n if (stats.last_failure) console.log(` Last failure: ${stats.last_failure}`);\n console.log();\n return;\n }\n\n const allStats = getAllWorkflowStats(dir);\n if (allStats.length === 0) {\n console.log('\\nNo workflow metrics recorded yet.\\n');\n console.log('Metrics are automatically recorded when workflows run via scheduler or `harness workflow run`.\\n');\n return;\n }\n\n console.log(`\\n${allStats.length} workflow(s) with metrics:\\n`);\n for (const stats of allStats) {\n const rate = (stats.success_rate * 100).toFixed(0);\n console.log(` ${stats.workflow_id}`);\n console.log(` ${stats.total_runs} runs (${rate}% success) | avg ${formatDuration(stats.avg_duration_ms)} | ${stats.total_tokens} tokens`);\n console.log(` Last: ${stats.last_run}`);\n }\n console.log();\n });\n\nmetricsCmd\n .command('clear')\n .description('Clear metrics for a specific workflow or all workflows')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--workflow <id>', 'Clear only this workflow (clears all if omitted)')\n .action(async (opts: { dir: string; workflow?: string }) => {\n const { clearMetrics } = await import('../runtime/metrics.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const removed = clearMetrics(dir, opts.workflow);\n if (opts.workflow) {\n console.log(`Cleared ${removed} metric(s) for workflow \"${opts.workflow}\".`);\n } else {\n console.log(`Cleared ${removed} total metric(s).`);\n }\n });\n\nmetricsCmd\n .command('history')\n .description('Show recent workflow run history')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--workflow <id>', 'Filter by workflow ID')\n .option('-n, --limit <count>', 'Number of recent runs to show', '10')\n .action(async (opts: { dir: string; workflow?: string; limit: string }) => {\n const { loadMetrics } = await import('../runtime/metrics.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const store = loadMetrics(dir);\n let runs = store.runs;\n\n if (opts.workflow) {\n runs = runs.filter((r) => r.workflow_id === opts.workflow);\n }\n\n const limit = parseInt(opts.limit, 10) || 10;\n const recent = runs.slice(-limit).reverse();\n\n if (recent.length === 0) {\n console.log('\\nNo workflow runs recorded.\\n');\n return;\n }\n\n console.log(`\\n${recent.length} recent run(s)${opts.workflow ? ` for \"${opts.workflow}\"` : ''}:\\n`);\n for (const run of recent) {\n const status = run.success ? 'OK' : 'FAIL';\n const tokens = run.tokens_used ? ` | ${run.tokens_used} tokens` : '';\n const retries = run.attempt > 1 ? ` (attempt ${run.attempt}/${run.max_retries + 1})` : '';\n const error = run.error ? `\\n Error: ${run.error.slice(0, 100)}` : '';\n console.log(` [${status}] ${run.workflow_id} — ${formatDuration(run.duration_ms)}${tokens}${retries}`);\n console.log(` ${run.started}${error}`);\n }\n console.log();\n });\n\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${ms}ms`;\n if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;\n const minutes = Math.floor(ms / 60000);\n const seconds = Math.round((ms % 60000) / 1000);\n return `${minutes}m${seconds}s`;\n}\n\n// --- TOOLS (list and inspect tool definitions) ---\nconst toolsCmd = program\n .command('tools')\n .description('List and inspect tool definitions');\n\ntoolsCmd\n .command('list')\n .description('List all defined tools with auth status')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { listToolSummaries } = await import('../runtime/tools.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const tools = listToolSummaries(dir);\n if (tools.length === 0) {\n console.log('\\nNo tools defined. Create tool files in tools/ to register external services.\\n');\n return;\n }\n\n console.log(`\\n${tools.length} tool(s):\\n`);\n for (const tool of tools) {\n const auth = tool.authReady ? 'ready' : 'missing auth';\n const status = tool.status !== 'active' ? ` [${tool.status}]` : '';\n console.log(` ${tool.id}${status} (${auth})`);\n if (tool.l0) console.log(` ${tool.l0}`);\n console.log(` ${tool.operationCount} operation(s) | tags: ${tool.tags.join(', ') || 'none'}`);\n }\n console.log();\n });\n\ntoolsCmd\n .command('show <id>')\n .description('Show detailed info for a specific tool')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (toolId: string, opts: { dir: string }) => {\n const { getToolById } = await import('../runtime/tools.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const tool = getToolById(dir, toolId);\n if (!tool) {\n console.error(`Tool not found: ${toolId}`);\n process.exit(1);\n }\n\n console.log(`\\nTool: ${tool.id}`);\n console.log(` Status: ${tool.status}`);\n console.log(` Tags: ${tool.tags.join(', ') || 'none'}`);\n\n if (tool.auth.length > 0) {\n console.log(`\\n Authentication:`);\n for (const a of tool.auth) {\n const status = a.present ? 'set' : 'MISSING';\n console.log(` ${a.envVar}: ${status}`);\n }\n }\n\n if (tool.operations.length > 0) {\n console.log(`\\n Operations (${tool.operations.length}):`);\n for (const op of tool.operations) {\n console.log(` ${op.method} ${op.endpoint}`);\n }\n }\n\n if (tool.rateLimits.length > 0) {\n console.log(`\\n Rate Limits:`);\n for (const rl of tool.rateLimits) {\n console.log(` - ${rl}`);\n }\n }\n\n if (tool.gotchas.length > 0) {\n console.log(`\\n Gotchas:`);\n for (const g of tool.gotchas) {\n console.log(` - ${g}`);\n }\n }\n console.log();\n });\n\ntoolsCmd\n .command('auth')\n .description('Check auth status for all tools')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { checkToolAuth } = await import('../runtime/tools.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const results = checkToolAuth(dir);\n if (results.length === 0) {\n console.log('\\nNo tools defined.\\n');\n return;\n }\n\n console.log('\\nTool auth status:\\n');\n for (const { tool, auth } of results) {\n if (auth.length === 0) {\n console.log(` ${tool}: no auth required`);\n continue;\n }\n const allPresent = auth.every((a) => a.present);\n console.log(` ${tool}: ${allPresent ? 'ready' : 'INCOMPLETE'}`);\n for (const a of auth) {\n const icon = a.present ? 'set' : 'MISSING';\n console.log(` ${a.envVar}: ${icon}`);\n }\n }\n console.log();\n });\n\n// --- EXPORT (data portability) ---\nprogram\n .command('export [output]')\n .description('Export harness to a portable JSON bundle')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--no-sessions', 'Exclude session files')\n .option('--no-journals', 'Exclude journal files')\n .option('--no-metrics', 'Exclude metrics')\n .option('--no-state', 'Exclude state and scratch')\n .action(async (output: string | undefined, opts: { dir: string; sessions: boolean; journals: boolean; metrics: boolean; state: boolean }) => {\n const { exportHarness, writeBundle } = await import('../runtime/export.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const bundle = exportHarness(dir, {\n sessions: opts.sessions,\n journals: opts.journals,\n metrics: opts.metrics,\n state: opts.state,\n });\n\n const outputPath = output ? resolve(output) : resolve(`${bundle.agent_name}-export.json`);\n writeBundle(bundle, outputPath);\n\n const { metadata } = bundle;\n console.log(`\\nExported \"${bundle.agent_name}\" to ${outputPath}`);\n console.log(` ${bundle.entries.length} files (${metadata.primitives} primitives, ${metadata.sessions} sessions, ${metadata.journals} journals)\\n`);\n });\n\n// --- IMPORT (data portability) ---\nprogram\n .command('import <bundle>')\n .description('Import a harness bundle into current directory')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--overwrite', 'Overwrite existing files', false)\n .action(async (bundlePath: string, opts: { dir: string; overwrite: boolean }) => {\n const { readBundle, importBundle } = await import('../runtime/export.js');\n const dir = resolve(opts.dir);\n\n try {\n const bundle = readBundle(resolve(bundlePath));\n console.log(`\\nImporting bundle: \"${bundle.agent_name}\" (exported ${bundle.exported_at})`);\n console.log(` ${bundle.entries.length} files in bundle\\n`);\n\n const result = importBundle(dir, bundle, { overwrite: opts.overwrite });\n\n console.log(` Imported: ${result.imported}`);\n console.log(` Skipped (exists): ${result.skipped}`);\n if (result.errors.length > 0) {\n console.log(` Errors: ${result.errors.length}`);\n for (const err of result.errors) {\n console.log(` - ${err}`);\n }\n }\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- BUNDLE (pack primitives into shareable bundle) ---\nprogram\n .command('bundle <output>')\n .description('Pack primitives into a shareable bundle with manifest.yaml')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-n, --name <name>', 'Bundle name')\n .option('--description <text>', 'Bundle description', '')\n .option('--author <name>', 'Author name')\n .option('--version <ver>', 'Bundle version', '1.0.0')\n .option('-t, --types <types...>', 'Primitive types to include (e.g., rules instincts)')\n .option('-f, --files <files...>', 'Specific files to include (relative paths)')\n .option('--tags <tags...>', 'Tags for search/discovery')\n .option('--license <id>', 'License identifier (e.g., MIT)')\n .option('--json', 'Output as JSON', false)\n .action(async (output: string, opts: { dir: string; name?: string; description: string; author?: string; version: string; types?: string[]; files?: string[]; tags?: string[]; license?: string; json: boolean }) => {\n const { packBundle, writeBundleDir } = await import('../runtime/primitive-registry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const bundleName = opts.name ?? basename(dir);\n const bundle = packBundle(dir, {\n name: bundleName,\n description: opts.description,\n author: opts.author,\n version: opts.version,\n types: opts.types,\n files: opts.files,\n tags: opts.tags,\n license: opts.license,\n });\n\n const outputPath = resolve(output);\n writeBundleDir(bundle, outputPath);\n\n if (opts.json) {\n console.log(JSON.stringify(bundle.manifest, null, 2));\n } else {\n console.log(`\\nBundled \"${bundleName}\" v${opts.version}`);\n console.log(` ${bundle.files.length} files in ${bundle.manifest.types.join(', ')}`);\n console.log(` Output: ${outputPath}/`);\n console.log(` Manifest: ${outputPath}/manifest.yaml\\n`);\n }\n });\n\n// --- BUNDLE INSTALL (install from bundle directory or URL) ---\nprogram\n .command('bundle-install <source>')\n .description('Install primitives from a bundle directory, JSON file, or URL')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--overwrite', 'Overwrite existing files', false)\n .option('--force', 'Skip dependency checks', false)\n .option('--json', 'Output as JSON', false)\n .action(async (source: string, opts: { dir: string; overwrite: boolean; force: boolean; json: boolean }) => {\n const { readBundleDir, installBundle, fetchRemoteBundle } = await import('../runtime/primitive-registry.js');\n const { readBundle } = await import('../runtime/export.js');\n const dir = resolve(opts.dir);\n\n try {\n let bundle;\n\n if (source.startsWith('https://') || source.startsWith('http://')) {\n console.log(`Downloading bundle from ${source}...`);\n bundle = await fetchRemoteBundle(source);\n } else {\n const sourcePath = resolve(source);\n // Check if it's a directory with manifest.yaml\n if (existsSync(join(sourcePath, 'manifest.yaml'))) {\n bundle = readBundleDir(sourcePath);\n } else if (source.endsWith('.json')) {\n // Legacy JSON bundle — convert\n const jsonBundle = readBundle(sourcePath);\n const { CORE_PRIMITIVE_DIRS } = await import('../core/types.js');\n const files = jsonBundle.entries;\n const types = new Set<string>();\n for (const entry of files) {\n const entryDir = entry.path.split('/')[0];\n if ((CORE_PRIMITIVE_DIRS as readonly string[]).includes(entryDir)) types.add(entryDir);\n }\n bundle = {\n manifest: {\n version: '1.0',\n name: jsonBundle.agent_name ?? 'imported',\n description: 'Imported from JSON bundle',\n author: 'unknown',\n bundle_version: '1.0.0',\n created: jsonBundle.exported_at ?? new Date().toISOString(),\n types: [...types],\n tags: [],\n files: files.map((f) => ({ path: f.path, type: f.path.split('/')[0], id: basename(f.path, '.md'), l0: '' })),\n },\n files,\n };\n } else {\n console.error(`Error: ${sourcePath} is not a bundle directory (no manifest.yaml) or JSON file`);\n process.exit(1);\n }\n }\n\n const result = installBundle(dir, bundle, { overwrite: opts.overwrite, force: opts.force });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.installed) {\n console.log(`\\nInstalled \"${result.name}\"`);\n console.log(` Files: ${result.files.length} installed, ${result.skipped.length} skipped`);\n if (result.files.length > 0) {\n for (const f of result.files) console.log(` + ${f}`);\n }\n if (result.skipped.length > 0) {\n for (const f of result.skipped) console.log(` = ${f} (exists)`);\n }\n } else {\n console.error(`\\nInstallation failed:`);\n for (const err of result.errors) console.error(` - ${err}`);\n }\n console.log();\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- UNINSTALL (soft-delete primitives) ---\nprogram\n .command('uninstall <bundle-name>')\n .description('Uninstall a previously installed bundle (moves files to archive/)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--hard', 'Permanently delete files instead of archiving', false)\n .option('--json', 'Output as JSON', false)\n .action(async (bundleName: string, opts: { dir: string; hard: boolean; json: boolean }) => {\n const { uninstallBundle } = await import('../runtime/primitive-registry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const result = uninstallBundle(dir, bundleName, { hard: opts.hard });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.uninstalled) {\n console.log(`\\nUninstalled \"${bundleName}\"`);\n console.log(` ${result.archived.length} files ${opts.hard ? 'deleted' : 'archived'}`);\n for (const f of result.archived) console.log(` - ${f}`);\n } else {\n console.error(`\\nUninstall failed:`);\n for (const err of result.errors) console.error(` - ${err}`);\n if (result.dependents.length > 0) {\n console.error(` Dependents: ${result.dependents.join(', ')}`);\n }\n }\n console.log();\n }\n });\n\n// --- UPDATE (update installed bundle) ---\nprogram\n .command('update <source>')\n .description('Update an installed bundle from a new version')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--remove-deleted', 'Archive files removed in new version', false)\n .option('--json', 'Output as JSON', false)\n .action(async (source: string, opts: { dir: string; removeDeleted: boolean; json: boolean }) => {\n const { readBundleDir, diffBundle, updateBundle, fetchRemoteBundle } = await import('../runtime/primitive-registry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n try {\n let bundle;\n\n if (source.startsWith('https://') || source.startsWith('http://')) {\n console.log(`Downloading bundle from ${source}...`);\n bundle = await fetchRemoteBundle(source);\n } else {\n const sourcePath = resolve(source);\n if (!existsSync(join(sourcePath, 'manifest.yaml'))) {\n console.error(`Error: ${sourcePath} is not a bundle directory (no manifest.yaml)`);\n process.exit(1);\n }\n bundle = readBundleDir(sourcePath);\n }\n\n // Show diff first\n const diff = diffBundle(dir, bundle);\n if (diff.added.length === 0 && diff.modified.length === 0 && diff.removed.length === 0) {\n console.log(`\\n\"${bundle.manifest.name}\" is already up to date.\\n`);\n return;\n }\n\n if (!opts.json) {\n console.log(`\\nUpdate \"${bundle.manifest.name}\" to v${bundle.manifest.bundle_version}:`);\n if (diff.added.length > 0) {\n console.log(` Added (${diff.added.length}):`);\n for (const f of diff.added) console.log(` + ${f}`);\n }\n if (diff.modified.length > 0) {\n console.log(` Modified (${diff.modified.length}):`);\n for (const f of diff.modified) console.log(` ~ ${f}`);\n }\n if (diff.removed.length > 0) {\n console.log(` Removed (${diff.removed.length}):`);\n for (const f of diff.removed) console.log(` - ${f}`);\n }\n console.log();\n }\n\n const result = updateBundle(dir, bundle, { removeDeleted: opts.removeDeleted });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.updated) {\n console.log(`Updated \"${result.name}\" ${result.oldVersion ?? '?'} → ${result.newVersion ?? '?'}`);\n console.log(` ${result.added.length} added, ${result.modified.length} modified, ${result.removed.length} removed`);\n } else {\n console.error(`Update failed:`);\n for (const err of result.errors) console.error(` - ${err}`);\n }\n console.log();\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- INSTALLED (list installed bundles) ---\nprogram\n .command('installed')\n .description('List installed bundles')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { listInstalledBundles } = await import('../runtime/primitive-registry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const bundles = listInstalledBundles(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(bundles, null, 2));\n } else {\n if (bundles.length === 0) {\n console.log('\\nNo bundles installed.\\n');\n } else {\n console.log(`\\n${bundles.length} bundle(s) installed:\\n`);\n for (const b of bundles) {\n console.log(` ${b.name} v${b.version} — ${b.description}`);\n console.log(` ${b.fileCount} files, types: ${b.types.join(', ')}`);\n }\n console.log();\n }\n }\n });\n\n// --- REGISTRY (search/install from configured registries) ---\nconst registryCmd = program.command('registry').description('Search and install bundles from configured registries');\n\nregistryCmd\n .command('search <query>')\n .description('Search all configured registries for bundles')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--limit <n>', 'Max results', '20')\n .option('--json', 'Output as JSON', false)\n .action(async (query: string, opts: { dir: string; limit: string; json: boolean }) => {\n const { searchConfiguredRegistries } = await import('../runtime/primitive-registry.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const registries = config.registries ?? [];\n if (registries.length === 0) {\n console.error('No registries configured. Add registries: to config.yaml');\n process.exit(1);\n }\n\n try {\n const result = await searchConfiguredRegistries(registries, query, { limit: parseInt(opts.limit, 10) });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nSearched ${result.registriesSearched} registry(ies) for \"${query}\"\\n`);\n\n if (result.errors.length > 0) {\n for (const err of result.errors) {\n console.log(` [warn] ${err.registry}: ${err.error}`);\n }\n console.log();\n }\n\n if (result.results.length === 0) {\n console.log('No bundles found.\\n');\n return;\n }\n\n for (const r of result.results) {\n console.log(` ${r.name} v${r.version} — ${r.description}`);\n console.log(` types: ${r.types.join(', ')} | tags: ${r.tags.join(', ') || 'none'} | from: ${r.registryName}`);\n }\n console.log(`\\n ${result.total} result(s) total\\n`);\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nregistryCmd\n .command('install <bundle-name>')\n .description('Install a bundle from configured registries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--version <ver>', 'Specific version to install')\n .option('--overwrite', 'Overwrite existing files', false)\n .option('--force', 'Skip dependency checks', false)\n .option('--json', 'Output as JSON', false)\n .action(async (bundleName: string, opts: { dir: string; version?: string; overwrite: boolean; force: boolean; json: boolean }) => {\n const { installFromRegistry } = await import('../runtime/primitive-registry.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const registries = config.registries ?? [];\n if (registries.length === 0) {\n console.error('No registries configured. Add registries: to config.yaml');\n process.exit(1);\n }\n\n try {\n console.log(`\\nSearching registries for \"${bundleName}\"...`);\n const result = await installFromRegistry(dir, registries, bundleName, {\n version: opts.version,\n overwrite: opts.overwrite,\n force: opts.force,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (result.installed) {\n console.log(`Installed \"${result.name}\" from ${result.registryUrl ?? 'registry'}`);\n console.log(` Files: ${result.files.length} installed, ${result.skipped.length} skipped`);\n if (result.files.length > 0) {\n for (const f of result.files) console.log(` + ${f}`);\n }\n if (result.skipped.length > 0) {\n for (const f of result.skipped) console.log(` = ${f} (exists)`);\n }\n } else {\n console.error(`\\nInstallation failed:`);\n for (const err of result.errors) console.error(` - ${err}`);\n }\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nregistryCmd\n .command('list')\n .description('List configured registries')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const registries = config.registries ?? [];\n\n if (opts.json) {\n console.log(JSON.stringify(registries, null, 2));\n return;\n }\n\n if (registries.length === 0) {\n console.log('\\nNo registries configured.');\n console.log('Add to config.yaml:\\n');\n console.log(' registries:');\n console.log(' - url: https://registry.example.com');\n console.log(' name: My Registry\\n');\n return;\n }\n\n console.log(`\\n${registries.length} registry(ies) configured:\\n`);\n for (const reg of registries) {\n const name = reg.name ?? reg.url;\n const auth = reg.token ? ' (authenticated)' : '';\n console.log(` ${name}${auth}`);\n console.log(` ${reg.url}`);\n }\n console.log();\n });\n\n// --- GRAPH (dependency analysis) ---\nprogram\n .command('graph')\n .description('Analyze primitive dependency graph (related:/with: fields)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; json: boolean }) => {\n const { buildDependencyGraph, getGraphStats } = await import('../runtime/graph.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const graph = buildDependencyGraph(dir, config);\n const stats = getGraphStats(dir, config);\n\n if (opts.json) {\n console.log(JSON.stringify({ graph, stats }, null, 2));\n return;\n }\n\n console.log(`\\nDependency Graph\\n`);\n console.log(` Nodes: ${stats.totalNodes}`);\n console.log(` Edges: ${stats.totalEdges}`);\n console.log(` Clusters: ${stats.clusterCount}`);\n console.log(` Orphans: ${stats.orphanCount}`);\n\n if (stats.mostConnected.length > 0) {\n console.log(`\\n Most connected:`);\n for (const mc of stats.mostConnected) {\n console.log(` ${mc.id}: ${mc.connections} connection(s)`);\n }\n }\n\n if (graph.orphans.length > 0) {\n console.log(`\\n Orphaned primitives (no relationships):`);\n for (const id of graph.orphans) {\n const node = graph.nodes.find((n) => n.id === id);\n console.log(` ${id} (${node?.directory || 'unknown'})`);\n }\n }\n\n if (stats.brokenRefs.length > 0) {\n console.log(`\\n Broken references:`);\n for (const br of stats.brokenRefs) {\n console.log(` ${br.from} -> \"${br.ref}\" (not found)`);\n }\n }\n\n if (graph.clusters.length > 0) {\n console.log(`\\n Clusters:`);\n for (let i = 0; i < graph.clusters.length; i++) {\n const cluster = graph.clusters[i];\n console.log(` [${i + 1}] ${cluster.join(', ')}`);\n }\n }\n\n console.log();\n });\n\n// --- ANALYTICS (session statistics) ---\nprogram\n .command('analytics')\n .description('Show session analytics and usage patterns')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; from?: string; to?: string; json: boolean }) => {\n const { getSessionAnalytics, getSessionsInRange } = await import('../runtime/analytics.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n if (opts.from || opts.to) {\n const sessions = getSessionsInRange(dir, opts.from, opts.to);\n const label = opts.from && opts.to ? `${opts.from} to ${opts.to}` : opts.from ? `from ${opts.from}` : `to ${opts.to}`;\n\n if (opts.json) {\n console.log(JSON.stringify({ range: label, sessions }, null, 2));\n return;\n }\n\n if (sessions.length === 0) {\n console.log(`\\nNo sessions found for ${label}.\\n`);\n return;\n }\n\n const totalTokens = sessions.reduce((sum, s) => sum + s.tokens, 0);\n console.log(`\\n${sessions.length} session(s) ${label}:\\n`);\n for (const s of sessions) {\n const model = s.model ? ` [${s.model}]` : '';\n const delegate = s.delegatedTo ? ` -> ${s.delegatedTo}` : '';\n console.log(` ${s.id}: ${s.tokens} tokens, ${s.durationMinutes}min${model}${delegate}`);\n }\n console.log(`\\n Total: ${totalTokens} tokens\\n`);\n return;\n }\n\n const analytics = getSessionAnalytics(dir);\n\n if (opts.json) {\n // Convert Map to plain object for JSON serialization\n const serializable = {\n ...analytics,\n modelUsage: Object.fromEntries(analytics.modelUsage),\n };\n console.log(JSON.stringify(serializable, null, 2));\n return;\n }\n\n if (analytics.totalSessions === 0) {\n console.log('\\nNo sessions recorded yet.\\n');\n return;\n }\n\n console.log(`\\nSession Analytics\\n`);\n console.log(` Total sessions: ${analytics.totalSessions}`);\n console.log(` Total tokens: ${analytics.totalTokens.toLocaleString()}`);\n console.log(` Avg tokens: ${analytics.avgTokensPerSession.toLocaleString()}/session`);\n console.log(` Avg duration: ${analytics.avgDurationMinutes}min/session`);\n console.log(` Delegations: ${analytics.delegationCount}`);\n\n if (analytics.dateRange) {\n console.log(` Date range: ${analytics.dateRange.earliest} to ${analytics.dateRange.latest}`);\n }\n\n if (analytics.modelUsage.size > 0) {\n console.log(`\\n Model usage:`);\n const sorted = Array.from(analytics.modelUsage.entries()).sort((a, b) => b[1] - a[1]);\n for (const [model, count] of sorted) {\n console.log(` ${model}: ${count} session(s)`);\n }\n }\n\n if (analytics.topDays.length > 0) {\n console.log(`\\n Busiest days:`);\n for (const day of analytics.topDays) {\n console.log(` ${day.date}: ${day.sessions} session(s), ${day.tokens.toLocaleString()} tokens`);\n }\n }\n\n console.log();\n });\n\n// --- INTELLIGENCE (auto-promote, dead detection, contradictions, enrichment) ---\n\nprogram\n .command('auto-promote')\n .description('Find instinct patterns appearing 3+ times across journals and optionally install them')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--threshold <n>', 'Minimum occurrences across different dates', '3')\n .option('--install', 'Auto-install promoted instincts', false)\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; threshold: string; install: boolean; json: boolean }) => {\n const { autoPromoteInstincts } = await import('../runtime/intelligence.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const result = autoPromoteInstincts(dir, {\n threshold: parseInt(opts.threshold, 10),\n install: opts.install,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nScanned ${result.journalsScanned} journal(s)\\n`);\n\n if (result.patterns.length === 0) {\n console.log('No patterns found meeting the threshold.\\n');\n return;\n }\n\n console.log(`${result.patterns.length} pattern(s) found:\\n`);\n for (const p of result.patterns) {\n const status = result.promoted.includes(behaviorToCliId(p.behavior))\n ? '✓ promoted'\n : result.skipped.includes(behaviorToCliId(p.behavior))\n ? '⊘ exists'\n : '○ candidate';\n console.log(` [${status}] ${p.behavior}`);\n console.log(` ${p.count}x across: ${p.journalDates.join(', ')}\\n`);\n }\n\n if (!opts.install && result.patterns.length > 0) {\n console.log('Run with --install to create instinct files.\\n');\n }\n });\n\nfunction behaviorToCliId(behavior: string): string {\n return behavior.toLowerCase().replace(/[^a-z0-9\\s-]/g, '').replace(/\\s+/g, '-').slice(0, 50).replace(/-+$/, '');\n}\n\nprogram\n .command('dead-primitives')\n .description('Detect orphaned primitives not modified in 30+ days')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--days <n>', 'Threshold days since last modification', '30')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; days: string; json: boolean }) => {\n const { detectDeadPrimitives } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = detectDeadPrimitives(dir, config, {\n thresholdDays: parseInt(opts.days, 10),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nScanned ${result.totalScanned} primitive(s) (threshold: ${result.thresholdDays} days)\\n`);\n\n if (result.dead.length === 0) {\n console.log('No dead primitives found.\\n');\n return;\n }\n\n console.log(`${result.dead.length} dead primitive(s):\\n`);\n for (const d of result.dead) {\n console.log(` ${d.id} (${d.directory})`);\n console.log(` ${d.path} — last modified ${d.lastModified} (${d.daysSinceModified}d ago)\\n`);\n }\n });\n\nprogram\n .command('contradictions')\n .description('Detect contradictions between rules and instincts')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { detectContradictions } = await import('../runtime/intelligence.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const result = detectContradictions(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nChecked ${result.rulesChecked} rule(s) and ${result.instinctsChecked} instinct(s)\\n`);\n\n if (result.contradictions.length === 0) {\n console.log('No contradictions detected.\\n');\n return;\n }\n\n console.log(`${result.contradictions.length} contradiction(s) found:\\n`);\n for (const c of result.contradictions) {\n console.log(` [${c.severity}] ${c.reason}`);\n console.log(` ${c.primitiveA.type}/${c.primitiveA.id}: \"${c.primitiveA.text}\"`);\n console.log(` ${c.primitiveB.type}/${c.primitiveB.id}: \"${c.primitiveB.text}\"\\n`);\n }\n });\n\nprogram\n .command('enrich')\n .description('Enrich sessions with extracted topics, tools, and primitive references')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; from?: string; to?: string; json: boolean }) => {\n const { enrichSessions } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = enrichSessions(dir, config, { from: opts.from, to: opts.to });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nEnriched ${result.sessionsScanned} session(s)\\n`);\n\n if (result.enriched.length === 0) {\n console.log('No sessions to enrich.\\n');\n return;\n }\n\n for (const s of result.enriched) {\n console.log(` ${s.sessionId}`);\n if (s.topics.length > 0) console.log(` topics: ${s.topics.join(', ')}`);\n if (s.toolsUsed.length > 0) console.log(` tools: ${s.toolsUsed.join(', ')}`);\n if (s.primitivesReferenced.length > 0) console.log(` refs: ${s.primitivesReferenced.join(', ')}`);\n console.log(` ${s.tokenCount} tokens, ${s.stepCount} steps, ${s.model}\\n`);\n }\n });\n\nprogram\n .command('suggest')\n .description('Suggest capabilities (skills/playbooks) for frequent uncovered session topics')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--min-frequency <n>', 'Minimum topic frequency', '3')\n .option('--json', 'Output as JSON', false)\n .action(async (opts: { dir: string; minFrequency: string; json: boolean }) => {\n const { suggestCapabilities } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = suggestCapabilities(dir, config, {\n minFrequency: parseInt(opts.minFrequency, 10),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nAnalyzed ${result.topicsAnalyzed} topic(s) from ${result.sessionsScanned} session(s)\\n`);\n\n if (result.suggestions.length === 0) {\n console.log('No capability gaps found.\\n');\n return;\n }\n\n console.log(`${result.suggestions.length} suggestion(s):\\n`);\n for (const s of result.suggestions) {\n console.log(` \"${s.topic}\" — ${s.frequency}x in sessions`);\n console.log(` Suggest: create a ${s.suggestedType}\\n`);\n }\n });\n\n// --- AGENTS (list available sub-agents) ---\nprogram\n .command('agents')\n .description('List available sub-agents')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { listAgents } = await import('../runtime/delegate.js');\n const dir = resolve(opts.dir);\n\n const agents = listAgents(dir);\n\n if (agents.length === 0) {\n console.log('\\nNo agents defined.');\n console.log('Create agent files in agents/ to enable delegation.\\n');\n return;\n }\n\n console.log(`\\n${agents.length} agent(s) available:\\n`);\n for (const agent of agents) {\n const status = agent.status === 'active' ? '' : ` [${agent.status}]`;\n console.log(` ${agent.id}${status}`);\n if (agent.l0) console.log(` ${agent.l0}`);\n if (agent.tags.length > 0) console.log(` tags: ${agent.tags.join(', ')}`);\n console.log();\n }\n });\n\n// --- DELEGATE (invoke a sub-agent) ---\nprogram\n .command('delegate <agent-id> <prompt>')\n .description('Delegate a prompt to a sub-agent')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-m, --model <model>', 'Model override (or alias: gemma, qwen, glm, claude)')\n .option('-s, --stream', 'Stream output', false)\n .action(async (agentId: string, prompt: string, opts: { dir: string; model?: string; stream: boolean }) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n requireHarness(dir);\n\n const modelId = resolveModel(opts.model);\n const delegateOpts = {\n harnessDir: dir,\n agentId,\n prompt,\n modelOverride: modelId,\n };\n\n try {\n console.error(`[delegate] Invoking agent \"${agentId}\"${opts.stream ? ' (streaming)' : ''}...`);\n\n if (opts.stream) {\n const { delegateStream } = await import('../runtime/delegate.js');\n const result = delegateStream(delegateOpts);\n process.stdout.write('\\n');\n for await (const chunk of result.textStream) {\n process.stdout.write(chunk);\n }\n process.stdout.write('\\n\\n');\n console.error(\n `[delegate] Agent: ${result.agentId} | session: ${result.sessionId}`\n );\n } else {\n const { delegateTo } = await import('../runtime/delegate.js');\n const result = await delegateTo(delegateOpts);\n console.log('\\n' + result.text + '\\n');\n console.error(\n `[delegate] Agent: ${result.agentId} | ` +\n `${result.usage.totalTokens} tokens | ` +\n `session: ${result.sessionId}`\n );\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- COSTS (spending tracker) ---\nconst costsCmd = program\n .command('costs')\n .description('View and manage API spending');\n\ncostsCmd\n .command('show')\n .description('Show spending summary (default: today)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; from?: string; to?: string; json: boolean }) => {\n const { getSpending } = await import('../runtime/cost-tracker.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const summary = getSpending(dir, opts.from, opts.to);\n const label = opts.from || opts.to\n ? `${opts.from ?? 'start'} to ${opts.to ?? 'now'}`\n : 'today';\n\n if (opts.json) {\n console.log(JSON.stringify({ period: label, ...summary }, null, 2));\n return;\n }\n\n if (summary.entries === 0) {\n console.log(`\\nNo spending recorded for ${label}.\\n`);\n return;\n }\n\n console.log(`\\nSpending — ${label}\\n`);\n console.log(` Total: $${summary.total_cost_usd.toFixed(6)}`);\n console.log(` Entries: ${summary.entries}`);\n console.log(` Tokens: ${summary.total_input_tokens.toLocaleString()} in / ${summary.total_output_tokens.toLocaleString()} out`);\n\n const models = Object.entries(summary.by_model);\n if (models.length > 0) {\n console.log(`\\n By model:`);\n for (const [model, data] of models.sort((a, b) => b[1].cost_usd - a[1].cost_usd)) {\n console.log(` ${model}: $${data.cost_usd.toFixed(6)} (${data.count} calls)`);\n }\n }\n\n const providers = Object.entries(summary.by_provider);\n if (providers.length > 0) {\n console.log(`\\n By provider:`);\n for (const [provider, data] of providers.sort((a, b) => b[1].cost_usd - a[1].cost_usd)) {\n console.log(` ${provider}: $${data.cost_usd.toFixed(6)} (${data.count} calls)`);\n }\n }\n console.log();\n });\n\ncostsCmd\n .command('budget')\n .description('Check spending against budget limits')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--daily <usd>', 'Daily budget limit in USD')\n .option('--monthly <usd>', 'Monthly budget limit in USD')\n .action(async (opts: { dir: string; daily?: string; monthly?: string }) => {\n const { checkBudget } = await import('../runtime/cost-tracker.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const dailyLimit = opts.daily ? parseFloat(opts.daily) : undefined;\n const monthlyLimit = opts.monthly ? parseFloat(opts.monthly) : undefined;\n\n if (dailyLimit === undefined && monthlyLimit === undefined) {\n console.error('Error: Specify at least --daily or --monthly budget limit.');\n process.exit(1);\n }\n\n const status = checkBudget(dir, {\n daily_limit_usd: dailyLimit,\n monthly_limit_usd: monthlyLimit,\n });\n\n console.log('\\nBudget Status\\n');\n\n if (status.daily_limit_usd !== null) {\n const pct = status.daily_pct !== null ? ` (${status.daily_pct.toFixed(1)}%)` : '';\n console.log(` Daily: $${status.daily_spent_usd.toFixed(6)} / $${status.daily_limit_usd.toFixed(2)}${pct}`);\n if (status.daily_remaining_usd !== null) {\n console.log(` Remaining: $${status.daily_remaining_usd.toFixed(6)}`);\n }\n }\n\n if (status.monthly_limit_usd !== null) {\n const pct = status.monthly_pct !== null ? ` (${status.monthly_pct.toFixed(1)}%)` : '';\n console.log(` Monthly: $${status.monthly_spent_usd.toFixed(6)} / $${status.monthly_limit_usd.toFixed(2)}${pct}`);\n if (status.monthly_remaining_usd !== null) {\n console.log(` Remaining: $${status.monthly_remaining_usd.toFixed(6)}`);\n }\n }\n\n if (status.alerts.length > 0) {\n console.log('\\n Alerts:');\n for (const alert of status.alerts) {\n console.log(` ⚠ ${alert}`);\n }\n }\n console.log();\n\n // Exit 1 if any budget exceeded\n if (status.alerts.some((a) => a.includes('exceeded'))) {\n process.exit(1);\n }\n });\n\ncostsCmd\n .command('clear')\n .description('Clear all cost records')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--model <id>', 'Clear only entries for this model')\n .action(async (opts: { dir: string; model?: string }) => {\n const { clearCosts } = await import('../runtime/cost-tracker.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const removed = clearCosts(dir, opts.model);\n if (opts.model) {\n console.log(`Cleared ${removed} cost entry(ies) for model \"${opts.model}\".`);\n } else {\n console.log(`Cleared ${removed} total cost entry(ies).`);\n }\n });\n\n// --- HEALTH (system health status) ---\nprogram\n .command('health')\n .description('Show system health status and metrics')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--reset', 'Reset health metrics', false)\n .option('--json', 'Output as JSON')\n .action(async (opts: { dir: string; reset: boolean; json: boolean }) => {\n const { getHealthStatus, resetHealth } = await import('../runtime/health.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n if (opts.reset) {\n resetHealth(dir);\n console.log('Health metrics reset.');\n return;\n }\n\n const health = getHealthStatus(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(health, null, 2));\n return;\n }\n\n const statusIcon = health.status === 'healthy' ? 'OK' : health.status === 'degraded' ? 'WARN' : 'FAIL';\n console.log(`\\nHealth: ${statusIcon} (${health.status})\\n`);\n\n for (const check of health.checks) {\n const icon = check.status === 'pass' ? 'pass' : check.status === 'warn' ? 'WARN' : 'FAIL';\n console.log(` [${icon}] ${check.name}: ${check.message}`);\n }\n\n console.log(`\\n Metrics:`);\n console.log(` Total runs: ${health.metrics.totalRuns}`);\n console.log(` Successes: ${health.metrics.totalSuccesses}`);\n console.log(` Failures: ${health.metrics.totalFailures}`);\n console.log(` Consecutive: ${health.metrics.consecutiveFailures} failure(s)`);\n\n if (health.metrics.bootedAt) {\n console.log(` Booted at: ${health.metrics.bootedAt}`);\n }\n if (health.metrics.lastSuccessfulRun) {\n console.log(` Last success: ${health.metrics.lastSuccessfulRun}`);\n }\n if (health.metrics.lastFailedRun) {\n console.log(` Last failure: ${health.metrics.lastFailedRun}`);\n }\n if (health.metrics.lastError) {\n console.log(` Last error: ${health.metrics.lastError.slice(0, 120)}`);\n }\n\n if (health.costToday > 0 || health.costThisMonth > 0) {\n console.log(`\\n Spending:`);\n console.log(` Today: $${health.costToday.toFixed(6)}`);\n console.log(` Month: $${health.costThisMonth.toFixed(6)}`);\n }\n\n console.log();\n });\n\n// --- RATELIMIT (rate limit management) ---\nconst rateLimitCmd = program\n .command('ratelimit')\n .description('View and manage rate limit state');\n\nrateLimitCmd\n .command('status')\n .description('Show current rate limit usage for a key')\n .argument('<key>', 'Rate limit key (e.g., tool:github, model:claude)')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--window <ms>', 'Window size in ms', '3600000')\n .action(async (key: string, opts: { dir: string; window: string }) => {\n const { getUsage } = await import('../runtime/rate-limiter.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const windowMs = parseInt(opts.window, 10) || 3600000;\n const usage = getUsage(dir, key, windowMs);\n\n const windowLabel = windowMs >= 3600000\n ? `${windowMs / 3600000}h`\n : windowMs >= 60000\n ? `${windowMs / 60000}m`\n : `${windowMs}ms`;\n\n console.log(`\\nRate limit: ${key} (${windowLabel} window)\\n`);\n console.log(` Requests: ${usage.count}`);\n if (usage.oldest !== null) {\n console.log(` Oldest: ${new Date(usage.oldest).toISOString()}`);\n }\n if (usage.newest !== null) {\n console.log(` Newest: ${new Date(usage.newest).toISOString()}`);\n }\n console.log();\n });\n\nrateLimitCmd\n .command('clear')\n .description('Clear rate limit events')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--key <key>', 'Clear only this key (clears all if omitted)')\n .action(async (opts: { dir: string; key?: string }) => {\n const { clearRateLimits } = await import('../runtime/rate-limiter.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const removed = clearRateLimits(dir, opts.key);\n if (opts.key) {\n console.log(`Cleared ${removed} event(s) for key \"${opts.key}\".`);\n } else {\n console.log(`Cleared ${removed} total event(s).`);\n }\n });\n\n// --- MCP (Model Context Protocol server management) ---\nconst mcpCmd = program\n .command('mcp')\n .description('Manage MCP (Model Context Protocol) server connections');\n\nmcpCmd\n .command('list')\n .description('List configured MCP servers and their status')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const { validateMcpConfig } = await import('../runtime/mcp.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const servers = config.mcp?.servers ?? {};\n const entries = Object.entries(servers);\n\n if (entries.length === 0) {\n console.log('\\nNo MCP servers configured.');\n console.log('Add servers to config.yaml under mcp.servers:\\n');\n console.log(' mcp:');\n console.log(' servers:');\n console.log(' my-server:');\n console.log(' transport: stdio');\n console.log(' command: npx');\n console.log(' args: [\"-y\", \"@my/mcp-server\"]');\n console.log();\n return;\n }\n\n const validationErrors = validateMcpConfig(config);\n const errorMap = new Map(validationErrors.map((e) => [e.server, e.error]));\n\n console.log(`\\n${entries.length} MCP server(s) configured:\\n`);\n for (const [name, serverConfig] of entries) {\n const enabled = serverConfig.enabled !== false;\n const status = !enabled ? 'disabled' : errorMap.has(name) ? 'invalid' : 'configured';\n const icon = status === 'configured' ? '+' : status === 'disabled' ? '-' : '!';\n\n console.log(` [${icon}] ${name} (${serverConfig.transport})`);\n\n if (serverConfig.transport === 'stdio' && serverConfig.command) {\n const args = serverConfig.args?.join(' ') ?? '';\n console.log(` Command: ${serverConfig.command} ${args}`.trimEnd());\n } else if (serverConfig.url) {\n console.log(` URL: ${serverConfig.url}`);\n }\n\n if (errorMap.has(name)) {\n console.log(` Error: ${errorMap.get(name)}`);\n }\n }\n console.log();\n });\n\nmcpCmd\n .command('test')\n .description('Test MCP server connections and list available tools')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-s, --server <name>', 'Test only a specific server')\n .action(async (opts: { dir: string; server?: string }) => {\n const { loadConfig } = await import('../core/config.js');\n const { createMcpManager } = await import('../runtime/mcp.js');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n requireHarness(dir);\n\n const config = loadConfig(dir);\n const servers = config.mcp?.servers ?? {};\n\n if (Object.keys(servers).length === 0) {\n console.log('\\nNo MCP servers configured. Run `harness mcp list` for setup instructions.\\n');\n return;\n }\n\n // If testing a specific server, filter config\n let testConfig = config;\n if (opts.server) {\n if (!servers[opts.server]) {\n console.error(`Error: MCP server \"${opts.server}\" not found in config.`);\n console.error(`Available: ${Object.keys(servers).join(', ')}`);\n process.exit(1);\n }\n testConfig = {\n ...config,\n mcp: { servers: { [opts.server]: servers[opts.server] } },\n };\n }\n\n console.log(`\\nTesting MCP server connections...\\n`);\n\n const manager = createMcpManager(testConfig);\n try {\n await manager.connect();\n const summaries = manager.getSummaries();\n\n for (const summary of summaries) {\n if (!summary.enabled) {\n console.log(` [-] ${summary.name}: disabled`);\n continue;\n }\n\n if (summary.connected) {\n console.log(` [OK] ${summary.name}: connected, ${summary.toolCount} tool(s)`);\n if (summary.toolNames.length > 0) {\n for (const toolName of summary.toolNames) {\n console.log(` - ${toolName}`);\n }\n }\n } else {\n console.log(` [FAIL] ${summary.name}: ${summary.error ?? 'unknown error'}`);\n }\n }\n\n const totalTools = summaries.reduce((sum, s) => sum + s.toolCount, 0);\n const connectedCount = summaries.filter((s) => s.connected).length;\n console.log(`\\n ${connectedCount}/${summaries.length} server(s) connected, ${totalTools} total tool(s)\\n`);\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n } finally {\n await manager.close();\n }\n });\n\nmcpCmd\n .command('discover')\n .description('Scan for MCP servers from other tools (Claude Desktop, Cursor, VS Code, etc.)')\n .option('--json', 'Output raw JSON', false)\n .action(async (opts: { json: boolean }) => {\n const { discoverMcpServers, discoveredServersToYaml, getScannedTools } = await import('../runtime/mcp-discovery.js');\n const discovery = discoverMcpServers();\n\n if (opts.json) {\n console.log(JSON.stringify(discovery, null, 2));\n return;\n }\n\n const tools = getScannedTools();\n console.log(`\\nScanned ${tools.length} tools: ${tools.join(', ')}\\n`);\n\n if (discovery.sourcesFound === 0) {\n console.log('No tool configs found on this machine.\\n');\n return;\n }\n\n console.log(`Found config files from ${discovery.sourcesFound} tool(s):\\n`);\n for (const source of discovery.sources) {\n if (!source.found) continue;\n const status = source.error\n ? `error: ${source.error}`\n : `${source.servers.length} server(s)`;\n console.log(` ${source.tool}: ${status}`);\n for (const server of source.servers) {\n console.log(` - ${server.name} (${server.transport}${server.command ? `: ${server.command}` : ''}${server.url ? `: ${server.url}` : ''})`);\n }\n }\n\n if (discovery.totalServers > 0) {\n console.log(`\\n${discovery.totalServers} unique server(s) after dedup:\\n`);\n console.log(discoveredServersToYaml(discovery.servers));\n console.log('\\nAdd the above to your config.yaml to use these servers.\\n');\n } else {\n console.log('\\nNo MCP servers found in any tool configs.\\n');\n }\n });\n\nmcpCmd\n .command('search <query>')\n .description('Search the MCP registry for available servers')\n .option('-n, --limit <number>', 'Max results', '10')\n .option('--json', 'Output raw JSON', false)\n .action(async (query: string, opts: { limit: string; json: boolean }) => {\n const { searchRegistry, formatRegistryServer } = await import('../runtime/mcp-installer.js');\n\n try {\n const result = await searchRegistry(query, { limit: parseInt(opts.limit, 10) });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (result.servers.length === 0) {\n console.log(`\\nNo servers found for \"${query}\".\\n`);\n return;\n }\n\n console.log(`\\n${result.servers.length} server(s) found for \"${query}\":\\n`);\n for (const entry of result.servers) {\n console.log(formatRegistryServer(entry));\n console.log();\n }\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\nmcpCmd\n .command('install <query>')\n .description('Install an MCP server from the registry into config.yaml')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('-n, --name <name>', 'Custom name for the server in config')\n .option('--force', 'Overwrite if server already exists', false)\n .option('--skip-test', 'Skip connection testing', false)\n .option('--skip-docs', 'Skip tool doc generation', false)\n .option('--json', 'Output raw JSON', false)\n .action(async (query: string, opts: { dir: string; name?: string; force: boolean; skipTest: boolean; skipDocs: boolean; json: boolean }) => {\n const { installMcpServer } = await import('../runtime/mcp-installer.js');\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n requireHarness(dir);\n\n try {\n console.log(`\\nSearching for \"${query}\" in MCP registry...`);\n const result = await installMcpServer(query, {\n dir,\n name: opts.name,\n force: opts.force,\n skipTest: opts.skipTest,\n skipDocs: opts.skipDocs,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (!result.installed) {\n console.error(`\\nFailed: ${result.error}`);\n process.exit(1);\n }\n\n console.log(`\\nInstalled MCP server: ${result.name}`);\n if (result.server?.registryName) {\n console.log(` registry: ${result.server.registryName}`);\n }\n if (result.server?.description) {\n const desc = result.server.description.length > 80\n ? result.server.description.slice(0, 77) + '...'\n : result.server.description;\n console.log(` description: ${desc}`);\n }\n console.log(` transport: ${result.server?.config.transport ?? 'unknown'}`);\n console.log(` -> Added to config.yaml`);\n\n // Show required env vars\n if (result.pendingEnvVars.length > 0) {\n console.log(`\\n Required environment variables:`);\n for (const ev of result.pendingEnvVars) {\n const desc = ev.description ? ` — ${ev.description}` : '';\n console.log(` ${ev.name}${desc}`);\n }\n console.log(` -> Set these in .env or config.yaml env section`);\n }\n\n // Show connection test results\n if (result.connectionTest) {\n if (result.connectionTest.connected) {\n console.log(`\\n [OK] Connected: ${result.connectionTest.toolCount} tool(s)`);\n for (const toolName of result.connectionTest.toolNames) {\n console.log(` - ${toolName}`);\n }\n } else {\n console.log(`\\n [WARN] Connection test failed: ${result.connectionTest.error}`);\n if (result.pendingEnvVars.length > 0) {\n console.log(` (This is expected if required env vars are not yet set)`);\n }\n }\n }\n\n // Show generated docs\n if (result.generatedDocs.length > 0) {\n console.log(`\\n Generated tool docs:`);\n for (const doc of result.generatedDocs) {\n console.log(` ${doc}`);\n }\n }\n\n console.log();\n } catch (err: unknown) {\n console.error(`Error: ${formatError(err)}`);\n process.exit(1);\n }\n });\n\n// --- DISCOVER (environment and project context) ---\nconst discoverCmd = program\n .command('discover')\n .description('Discover environment variables, project context, and MCP servers');\n\ndiscoverCmd\n .command('env')\n .description('Scan .env files for API keys and suggest MCP servers')\n .option('-d, --dir <path>', 'Directory to scan', '.')\n .option('--json', 'Output raw JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { discoverEnvKeys } = await import('../runtime/env-discovery.js');\n const dir = resolve(opts.dir);\n const result = discoverEnvKeys({ dir });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(`\\nScanned ${result.filesScanned.length} file(s)\\n`);\n\n if (result.keys.length === 0) {\n console.log('No API keys detected in .env files.\\n');\n return;\n }\n\n console.log(`${result.keys.length} API key(s) detected:\\n`);\n for (const key of result.keys) {\n const status = key.hasValue ? '[set]' : '[empty]';\n const sug = key.suggestion ? ` → ${key.suggestion}` : '';\n console.log(` ${status} ${key.name} (${key.source})${sug}`);\n }\n\n if (result.suggestions.length > 0) {\n console.log(`\\nSuggested MCP servers:\\n`);\n for (const sug of result.suggestions) {\n console.log(` ${sug.message}`);\n console.log(` Install: harness mcp install \"${sug.serverQuery}\"`);\n }\n }\n console.log();\n });\n\ndiscoverCmd\n .command('project')\n .description('Scan project files to detect tech stack and suggest rules/skills')\n .option('-d, --dir <path>', 'Project directory to scan', '.')\n .option('--json', 'Output raw JSON', false)\n .action(async (opts: { dir: string; json: boolean }) => {\n const { discoverProjectContext } = await import('../runtime/project-discovery.js');\n const dir = resolve(opts.dir);\n const result = discoverProjectContext({ dir });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (result.signals.length === 0) {\n console.log('\\nNo project signals detected.\\n');\n return;\n }\n\n console.log(`\\nDetected ${result.signals.length} signal(s):\\n`);\n const byCategory = new Map<string, ProjectSignalDisplay[]>();\n for (const signal of result.signals) {\n const list = byCategory.get(signal.category) ?? [];\n list.push(signal);\n byCategory.set(signal.category, list);\n }\n for (const [category, signals] of byCategory) {\n console.log(` ${category}: ${signals.map((s) => s.name).join(', ')}`);\n }\n\n if (result.suggestions.length > 0) {\n console.log(`\\nSuggestions:\\n`);\n for (const sug of result.suggestions) {\n if (sug.type === 'mcp-server') {\n console.log(` [mcp] ${sug.message}`);\n console.log(` Install: harness mcp install \"${sug.target}\"`);\n } else {\n console.log(` [${sug.type}] ${sug.message}`);\n console.log(` Create: ${sug.target}`);\n }\n }\n }\n console.log();\n });\n\n// Type alias for CLI display (avoids importing the full type)\ntype ProjectSignalDisplay = { name: string; category: string };\n\n// --- GENERATE (auto-generate files) ---\nconst generateCmd = program\n .command('generate')\n .description('Auto-generate harness files');\n\ngenerateCmd\n .command('system')\n .description('Regenerate SYSTEM.md from actual directory structure')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .action(async (opts: { dir: string }) => {\n const { generateSystemMd } = await import('./scaffold.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n const { loadConfig } = await import('../core/config.js');\n const config = loadConfig(dir);\n const content = generateSystemMd(dir, config.agent.name);\n\n const { writeFileSync } = await import('fs');\n writeFileSync(join(dir, 'SYSTEM.md'), content, 'utf-8');\n console.log(`\\n✓ SYSTEM.md regenerated from directory structure\\n`);\n });\n\n// --- DASHBOARD (unified telemetry view) ---\nprogram\n .command('dashboard')\n .description('Show a unified dashboard of health, costs, sessions, workflows, and storage')\n .option('-d, --dir <path>', 'Harness directory', '.')\n .option('--json', 'Output raw JSON snapshot', false)\n .option('--watch', 'Refresh every N seconds', false)\n .option('--interval <seconds>', 'Watch refresh interval in seconds', '5')\n .action(async (opts: { dir: string; json: boolean; watch: boolean; interval: string }) => {\n const { collectSnapshot, formatDashboard } = await import('../runtime/telemetry.js');\n const dir = resolve(opts.dir);\n requireHarness(dir);\n\n if (opts.json) {\n const snapshot = collectSnapshot(dir);\n console.log(JSON.stringify(snapshot, null, 2));\n return;\n }\n\n const showDashboard = () => {\n const snapshot = collectSnapshot(dir);\n const output = formatDashboard(snapshot);\n if (opts.watch) {\n // Clear screen for watch mode\n process.stdout.write('\\x1B[2J\\x1B[H');\n console.log(`\\n Agent Harness Dashboard (refreshing every ${opts.interval}s — Ctrl+C to stop)\\n`);\n console.log(` ${snapshot.timestamp}\\n`);\n } else {\n console.log(`\\n Agent Harness Dashboard\\n`);\n }\n console.log(output);\n };\n\n showDashboard();\n\n if (opts.watch) {\n const intervalMs = (parseInt(opts.interval, 10) || 5) * 1000;\n const timer = setInterval(showDashboard, intervalMs);\n\n const cleanup = () => {\n clearInterval(timer);\n process.exit(0);\n };\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n }\n });\n\n// --- Intelligence Commands ---\n\nconst intelligenceCmd = program.command('intelligence').description('Intelligence and learning analysis tools');\n\nintelligenceCmd\n .command('promote')\n .description('Auto-promote instinct candidates that appear 3+ times across journals')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--threshold <n>', 'Minimum occurrences to promote', '3')\n .option('--install', 'Install promoted instincts as .md files')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { autoPromoteInstincts } = await import('../runtime/intelligence.js');\n const result = autoPromoteInstincts(dir, {\n threshold: parseInt(opts.threshold, 10),\n install: opts.install ?? false,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Scanned ${result.journalsScanned} journals`);\n if (result.patterns.length === 0) {\n console.log('No patterns meeting threshold found.');\n } else {\n console.log(`\\nPatterns (${result.patterns.length}):`);\n for (const p of result.patterns) {\n console.log(` [${p.count}x] ${p.behavior}`);\n console.log(` Dates: ${p.journalDates.join(', ')}`);\n }\n }\n if (result.promoted.length > 0) {\n console.log(`\\nPromoted: ${result.promoted.join(', ')}`);\n }\n if (result.skipped.length > 0) {\n console.log(`Skipped (already exists): ${result.skipped.join(', ')}`);\n }\n }\n });\n\nintelligenceCmd\n .command('dead')\n .description('Detect dead primitives (unreferenced and old)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--threshold <days>', 'Days since modification to consider dead', '30')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { detectDeadPrimitives } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = detectDeadPrimitives(dir, config, {\n thresholdDays: parseInt(opts.threshold, 10),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Scanned ${result.totalScanned} primitives (threshold: ${result.thresholdDays} days)`);\n if (result.dead.length === 0) {\n console.log('No dead primitives found.');\n } else {\n console.log(`\\nDead primitives (${result.dead.length}):`);\n for (const d of result.dead) {\n console.log(` ${d.id} (${d.directory}) — ${d.daysSinceModified}d since modified`);\n console.log(` ${d.reason}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('contradictions')\n .description('Detect contradictions between rules and instincts')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { detectContradictions } = await import('../runtime/intelligence.js');\n const result = detectContradictions(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Checked ${result.rulesChecked} rules, ${result.instinctsChecked} instincts`);\n if (result.contradictions.length === 0) {\n console.log('No contradictions detected.');\n } else {\n console.log(`\\nContradictions (${result.contradictions.length}):`);\n for (const c of result.contradictions) {\n console.log(` [${c.severity}] ${c.primitiveA.id} (${c.primitiveA.type}) vs ${c.primitiveB.id} (${c.primitiveB.type})`);\n console.log(` ${c.reason}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('enrich')\n .description('Enrich sessions with topics, token counts, and related primitives')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--from <date>', 'Start date (YYYY-MM-DD)')\n .option('--to <date>', 'End date (YYYY-MM-DD)')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { enrichSessions } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = enrichSessions(dir, config, {\n from: opts.from,\n to: opts.to,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Scanned ${result.sessionsScanned} sessions, enriched ${result.enriched.length}`);\n for (const s of result.enriched) {\n console.log(` ${s.sessionId}: ${s.topics.join(', ') || '(no topics)'} — ${s.tokenCount} tokens, ${s.toolsUsed.length} tools`);\n if (s.primitivesReferenced.length > 0) {\n console.log(` Referenced: ${s.primitivesReferenced.join(', ')}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('suggest')\n .description('Suggest new skills/playbooks for frequent uncovered topics')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--min-frequency <n>', 'Minimum topic frequency', '3')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { suggestCapabilities } = await import('../runtime/intelligence.js');\n const { loadConfig } = await import('../core/config.js');\n\n let config;\n try { config = loadConfig(dir); } catch (err) { if (process.env.DEBUG) console.error(`Config load skipped: ${err instanceof Error ? err.message : String(err)}`); }\n\n const result = suggestCapabilities(dir, config, {\n minFrequency: parseInt(opts.minFrequency, 10),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Analyzed ${result.topicsAnalyzed} topics from ${result.sessionsScanned} sessions`);\n if (result.suggestions.length === 0) {\n console.log('No capability suggestions at this time.');\n } else {\n console.log(`\\nSuggestions (${result.suggestions.length}):`);\n for (const s of result.suggestions) {\n console.log(` [${s.suggestedType}] \"${s.topic}\" — ${s.frequency} occurrences`);\n console.log(` ${s.suggestion}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('failures')\n .description('Analyze recent failure patterns and suggest recovery strategies')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--days <n>', 'Days to look back', '7')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { analyzeFailures } = await import('../runtime/intelligence.js');\n const result = analyzeFailures(dir, { days: parseInt(opts.days, 10) });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Health: ${result.healthImplication}`);\n console.log(`Recent failures: ${result.recentFailures.length}`);\n if (result.mostCommonMode) {\n console.log(`Most common failure: ${result.mostCommonMode}`);\n }\n if (Object.keys(result.modeFrequency).length > 0) {\n console.log('\\nFailure frequency:');\n for (const [mode, count] of Object.entries(result.modeFrequency)) {\n console.log(` ${mode}: ${count}`);\n }\n }\n if (result.suggestedRecovery.length > 0) {\n console.log('\\nSuggested recovery:');\n for (const s of result.suggestedRecovery) {\n console.log(` - ${s}`);\n }\n }\n }\n });\n\nintelligenceCmd\n .command('classify <error>')\n .description('Classify an error message into a failure mode')\n .action(async (errorMsg) => {\n const { classifyFailure, getRecoveryStrategies, FAILURE_TAXONOMY } = await import('../runtime/intelligence.js');\n const mode = classifyFailure(errorMsg);\n const info = FAILURE_TAXONOMY.modes[mode];\n const strategies = getRecoveryStrategies(mode);\n\n console.log(`Mode: ${mode}`);\n console.log(`Severity: ${info.severity}`);\n console.log(`Description: ${info.description}`);\n console.log(`Auto-recoverable: ${info.autoRecoverable}`);\n console.log('\\nRecovery strategies:');\n for (const s of strategies) {\n console.log(` - ${s}`);\n }\n });\n\n// --- Verification Gate Commands ---\n\nconst gateCmd = program.command('gate').description('Run verification gates');\n\ngateCmd\n .command('run [name]')\n .description('Run a verification gate (or all gates if no name)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (name, opts) => {\n const dir = resolve(opts.dir);\n loadEnvFromDir(dir);\n const { runGate, runAllGates } = await import('../runtime/intelligence.js');\n\n if (name) {\n const result = runGate(name, dir);\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`Gate: ${result.gateName} — ${result.passed ? 'PASSED' : 'FAILED'}`);\n console.log(result.summary);\n for (const c of result.checks) {\n const icon = c.status === 'pass' ? '[OK]' : c.status === 'fail' ? '[FAIL]' : c.status === 'warn' ? '[WARN]' : '[SKIP]';\n console.log(` ${icon} ${c.name}: ${c.message}`);\n }\n }\n } else {\n const results = runAllGates(dir);\n if (opts.json) {\n console.log(JSON.stringify(results, null, 2));\n } else {\n for (const result of results) {\n const icon = result.passed ? '[OK]' : '[FAIL]';\n console.log(`${icon} ${result.summary}`);\n for (const c of result.checks) {\n const cIcon = c.status === 'pass' ? '[OK]' : c.status === 'fail' ? '[FAIL]' : c.status === 'warn' ? '[WARN]' : '[SKIP]';\n console.log(` ${cIcon} ${c.name}: ${c.message}`);\n }\n }\n }\n }\n });\n\ngateCmd\n .command('list')\n .description('List available verification gates')\n .action(async () => {\n const { listGates } = await import('../runtime/intelligence.js');\n const gates = listGates();\n for (const g of gates) {\n console.log(` ${g.name}: ${g.description}`);\n }\n });\n\n// ── Rule Engine ──────────────────────────────────────────────────────────────\n\nprogram\n .command('check-rules')\n .description('Check an action against loaded rules')\n .argument('<action>', 'Action to check (e.g., \"deploy\", \"run\", \"tool_call\")')\n .option('-d, --dir <path>', 'Harness directory', process.cwd())\n .option('--description <text>', 'Description of the action')\n .option('--tags <tags>', 'Comma-separated tags')\n .option('--tool <name>', 'Tool name (for tool_call actions)')\n .option('--json', 'Output as JSON')\n .action(async (action: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { enforceRules } = await import('../runtime/rule-engine.js');\n\n const tags = opts.tags ? (opts.tags as string).split(',').map((t: string) => t.trim()) : undefined;\n const result = enforceRules(dir, {\n action,\n description: opts.description as string | undefined,\n tags,\n toolName: opts.tool as string | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(result.allowed ? '[OK] ' + result.summary : '[BLOCKED] ' + result.summary);\n for (const v of result.violations) {\n console.log(` [${v.severity.toUpperCase()}] ${v.directive} (rule: ${v.ruleId})`);\n }\n for (const w of result.warnings) {\n console.log(` [WARN] ${w.directive} (rule: ${w.ruleId})`);\n }\n }\n });\n\nprogram\n .command('list-rules')\n .description('List all parsed rules from the harness')\n .option('-d, --dir <path>', 'Harness directory', process.cwd())\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadRules } = await import('../runtime/rule-engine.js');\n\n const rules = loadRules(dir);\n if (opts.json) {\n console.log(JSON.stringify(rules, null, 2));\n } else {\n if (rules.length === 0) {\n console.log('No enforceable rules found.');\n } else {\n console.log(`${rules.length} rule(s) loaded:\\n`);\n for (const rule of rules) {\n const icon = rule.action === 'deny' ? '[DENY]' : rule.action === 'warn' ? '[WARN]' : rule.action === 'require_approval' ? '[APPROVAL]' : '[ALLOW]';\n console.log(` ${icon} ${rule.directive} (from: ${rule.ruleId})`);\n }\n }\n }\n });\n\n// ── Playbook Gates ───────────────────────────────────────────────────────────\n\nprogram\n .command('playbook-gates')\n .description('Extract and check verification gates from playbooks/workflows')\n .argument('[playbook-id]', 'Specific playbook/workflow ID')\n .option('-d, --dir <path>', 'Harness directory', process.cwd())\n .option('--json', 'Output as JSON')\n .action(async (playbookId: string | undefined, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadGates, getGatesForPlaybook } = await import('../runtime/verification-gate.js');\n\n if (playbookId) {\n const gates = getGatesForPlaybook(dir, playbookId);\n if (opts.json) {\n console.log(JSON.stringify(gates, null, 2));\n } else if (gates.length === 0) {\n console.log(`No verification gates found for \"${playbookId}\".`);\n } else {\n console.log(`${gates.length} gate(s) for \"${playbookId}\":\\n`);\n for (const gate of gates) {\n console.log(` Gate: ${gate.stage} (${gate.id})`);\n for (const c of gate.criteria) {\n const icon = c.manual ? '[MANUAL]' : '[AUTO]';\n console.log(` ${icon} ${c.description}`);\n }\n }\n }\n } else {\n const { gates, sources } = loadGates(dir);\n if (opts.json) {\n console.log(JSON.stringify({ gates, sources }, null, 2));\n } else if (gates.length === 0) {\n console.log('No verification gates found in playbooks or workflows.');\n } else {\n console.log(`${gates.length} gate(s) from ${sources.length} source(s):\\n`);\n for (const gate of gates) {\n console.log(` [${gate.sourceId}] ${gate.stage} — ${gate.criteria.length} criterion(s)`);\n }\n }\n }\n });\n\n// ── State Merge ──────────────────────────────────────────────────────────────\n\nconst stateCmd = program.command('state-merge').description('Mixed-ownership state merging');\n\nstateCmd\n .command('apply')\n .description('Apply a state change with ownership tracking')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--author <owner>', 'Change author: human, agent, infrastructure', 'human')\n .option('--mode <mode>', 'Set agent mode')\n .option('--goals <goals>', 'Set goals (comma-separated)')\n .option('--strategy <strategy>', 'Merge strategy: human-wins, agent-wins, latest-wins, union', 'human-wins')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { mergeState } = await import('../runtime/state-merge.js');\n const changes: Record<string, unknown> = {};\n if (opts.mode) changes.mode = opts.mode;\n if (opts.goals) changes.goals = (opts.goals as string).split(',').map((g: string) => g.trim());\n\n if (Object.keys(changes).length === 0) {\n console.log('No changes specified. Use --mode or --goals.');\n return;\n }\n\n const result = mergeState(dir, {\n author: opts.author as 'human' | 'agent' | 'infrastructure',\n changes,\n }, opts.strategy as 'human-wins' | 'agent-wins' | 'latest-wins' | 'union');\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`State merged (strategy: ${opts.strategy}).`);\n if (result.hadConflicts) {\n console.log(` ${result.conflicts.length} conflict(s) resolved:`);\n for (const c of result.conflicts) {\n console.log(` ${c.field}: resolved to ${c.resolvedTo}`);\n }\n } else {\n console.log(' No conflicts.');\n }\n console.log(` Mode: ${result.state.mode}`);\n console.log(` Goals: ${result.state.goals.join(', ') || '(none)'}`);\n }\n });\n\nstateCmd\n .command('ownership')\n .description('Show current state ownership')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadOwnership } = await import('../runtime/state-merge.js');\n const ownership = loadOwnership(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(ownership, null, 2));\n } else {\n console.log('State field ownership:');\n for (const [field, owner] of Object.entries(ownership)) {\n console.log(` ${field}: ${owner}`);\n }\n }\n });\n\n// ── Emotional State ──────────────────────────────────────────────────────────\n\nconst emoCmd = program.command('emotional').description('Operational disposition tracking');\n\nemoCmd\n .command('status')\n .description('Show current emotional/disposition state')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadEmotionalState, summarizeEmotionalState } = await import('../runtime/emotional-state.js');\n const state = loadEmotionalState(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(state, null, 2));\n } else {\n console.log('Operational Disposition:');\n console.log(` Confidence: ${state.confidence}/100`);\n console.log(` Engagement: ${state.engagement}/100`);\n console.log(` Frustration: ${state.frustration}/100`);\n console.log(` Curiosity: ${state.curiosity}/100`);\n console.log(` Urgency: ${state.urgency}/100`);\n console.log(` Updated: ${state.updatedAt}`);\n console.log(`\\n${summarizeEmotionalState(state)}`);\n }\n });\n\nemoCmd\n .command('signal')\n .description('Apply an emotional signal')\n .argument('<dimension>', 'Dimension: confidence, engagement, frustration, curiosity, urgency')\n .argument('<delta>', 'Delta value (positive or negative integer)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-r, --reason <reason>', 'Reason for the signal')\n .option('--json', 'Output as JSON')\n .action(async (dimension: string, delta: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { applySignals } = await import('../runtime/emotional-state.js');\n const state = applySignals(dir, [{\n dimension: dimension as 'confidence' | 'engagement' | 'frustration' | 'curiosity' | 'urgency',\n delta: parseInt(delta, 10),\n reason: opts.reason as string | undefined,\n }]);\n\n if (opts.json) {\n console.log(JSON.stringify(state, null, 2));\n } else {\n console.log(`Applied signal: ${dimension} ${parseInt(delta, 10) >= 0 ? '+' : ''}${delta}`);\n console.log(` New ${dimension}: ${state[dimension as keyof typeof state]}/100`);\n }\n });\n\nemoCmd\n .command('trends')\n .description('Show emotional dimension trends')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--days <days>', 'Days to analyze', '7')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { getEmotionalTrends } = await import('../runtime/emotional-state.js');\n const trends = getEmotionalTrends(dir, { days: parseInt(opts.days as string, 10) });\n\n if (opts.json) {\n console.log(JSON.stringify(trends, null, 2));\n } else {\n console.log(`Emotional trends (last ${opts.days} days):\\n`);\n for (const t of trends) {\n const arrow = t.trend === 'rising' ? '↑' : t.trend === 'falling' ? '↓' : '→';\n console.log(` ${t.dimension}: avg ${t.average.toFixed(0)}/100 ${arrow} (${t.values.length} data points)`);\n }\n }\n });\n\nemoCmd\n .command('reset')\n .description('Reset emotional state to defaults')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { resetEmotionalState } = await import('../runtime/emotional-state.js');\n resetEmotionalState(dir);\n console.log('Emotional state reset to defaults.');\n });\n\n// ── Check Action ─────────────────────────────────────────────────────────────\n\nprogram\n .command('check-action')\n .description('Check if an action is allowed by harness rules (agent-framework guardrails)')\n .argument('<action>', 'Action description to check')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--tags <tags>', 'Filter by rule tags (comma-separated)')\n .option('--json', 'Output as JSON')\n .action(async (action: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { checkAction } = await import('../runtime/agent-framework.js');\n const tags = opts.tags ? (opts.tags as string).split(',').map((t: string) => t.trim()) : undefined;\n const result = checkAction(dir, action, { ruleTags: tags });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else if (result.allowed) {\n console.log('[OK] Action allowed.');\n } else {\n console.log(`[BLOCKED] ${result.reason}`);\n }\n });\n\n// ── Serve ────────────────────────────────────────────────────────────────────\n\nprogram\n .command('serve')\n .description('Start the harness HTTP API server for webhooks and integrations')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-p, --port <port>', 'Port to listen on', '8080')\n .option('--api-key <key>', 'API key for LLM provider')\n .option('--webhook-secret <secret>', 'Secret for authenticating webhook management API')\n .option('--no-cors', 'Disable CORS')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { startServe } = await import('../runtime/serve.js');\n\n const port = parseInt(opts.port as string, 10);\n const result = startServe({\n harnessDir: dir,\n port,\n apiKey: opts.apiKey as string | undefined,\n webhookSecret: opts.webhookSecret as string | undefined,\n corsEnabled: opts.cors !== false,\n });\n\n console.log(`Harness API server listening on http://localhost:${result.port}`);\n console.log('Endpoints:');\n console.log(' GET /api/health — health check');\n console.log(' GET /api/info — agent info');\n console.log(' POST /api/run — execute a prompt');\n console.log(' GET /api/webhooks — list registered webhooks');\n console.log(' POST /api/webhooks — register a webhook');\n console.log(' DEL /api/webhooks/:id — delete a webhook');\n console.log(' PATCH /api/webhooks/:id — toggle webhook active/inactive');\n console.log(' POST /api/webhooks/:id/test — test a webhook');\n console.log(' + all dashboard endpoints from harness dev');\n console.log('\\nPress Ctrl+C to stop.');\n\n // Keep process alive\n process.on('SIGINT', () => {\n console.log('\\nShutting down...');\n result.stop();\n process.exit(0);\n });\n process.on('SIGTERM', () => {\n result.stop();\n process.exit(0);\n });\n\n // Wait indefinitely\n await new Promise<void>(() => { /* keep alive */ });\n });\n\n// ── Sources ──────────────────────────────────────────────────────────────────\n\nconst sourcesCmd = program.command('sources').description('Manage content sources (skills, agents, rules, MCP servers)');\n\nsourcesCmd\n .command('list')\n .description('List all configured content sources')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--type <type>', 'Filter by content type (skills, agents, rules, hooks, mcp, etc.)')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { loadAllSources, getSourcesForType } = await import('../runtime/sources.js');\n\n const sources = opts.type\n ? getSourcesForType(dir, opts.type as 'skills' | 'agents' | 'rules' | 'hooks' | 'mcp')\n : loadAllSources(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(sources, null, 2));\n } else if (sources.length === 0) {\n console.log('No sources configured.');\n } else {\n console.log(`${sources.length} source(s):\\n`);\n for (const s of sources) {\n const types = s.content.join(', ');\n const stats = s.stats ? ` (${Object.entries(s.stats).map(([k, v]) => `${v} ${k}`).join(', ')})` : '';\n console.log(` [${s.type}] ${s.name}${stats}`);\n console.log(` ${s.url}`);\n console.log(` Content: ${types}`);\n if (s.description) console.log(` ${s.description}`);\n console.log();\n }\n }\n });\n\nsourcesCmd\n .command('add')\n .description('Add a new content source')\n .argument('<url>', 'Source URL (GitHub repo, registry API, or endpoint)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-n, --name <name>', 'Source display name')\n .option('-t, --type <type>', 'Source type: github, registry, api', 'github')\n .option('-c, --content <types>', 'Content types (comma-separated: skills,agents,rules,hooks,mcp)')\n .option('--description <desc>', 'Source description')\n .option('--json', 'Output as JSON')\n .action(async (url: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { addSource } = await import('../runtime/sources.js');\n\n // Derive name from URL if not provided\n const name = (opts.name as string) ?? url.replace(/https?:\\/\\//, '').replace(/github\\.com\\//, '').replace(/\\/$/, '');\n const content = opts.content\n ? (opts.content as string).split(',').map((c: string) => c.trim())\n : ['skills'];\n\n const result = addSource(dir, {\n name,\n url,\n type: (opts.type as 'github' | 'registry' | 'api'),\n content: content as Array<'skills' | 'agents' | 'rules' | 'hooks' | 'mcp'>,\n description: opts.description as string | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else if (result) {\n console.log(`Added source: ${result.name} (${result.url})`);\n } else {\n console.log('Source with that name already exists.');\n }\n });\n\nsourcesCmd\n .command('remove')\n .description('Remove a content source')\n .argument('<name>', 'Source name to remove')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .action(async (name: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { removeSource } = await import('../runtime/sources.js');\n\n const removed = removeSource(dir, name);\n if (removed) {\n console.log(`Removed source: ${name}`);\n } else {\n console.log(`Source not found: ${name}`);\n }\n });\n\nsourcesCmd\n .command('summary')\n .description('Show content available by type across all sources')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { getSourcesSummary } = await import('../runtime/sources.js');\n\n const summary = getSourcesSummary(dir);\n\n if (opts.json) {\n const json: Record<string, number> = {};\n for (const [type, sources] of Object.entries(summary)) {\n json[type] = sources.length;\n }\n console.log(JSON.stringify(json, null, 2));\n } else {\n console.log('Content sources by type:\\n');\n for (const [type, sources] of Object.entries(summary)) {\n if (sources.length > 0) {\n console.log(` ${type}: ${sources.length} source(s)`);\n for (const s of sources) {\n console.log(` - ${s.name}`);\n }\n }\n }\n }\n });\n\n// ── Discover Search (sub-command of existing discoverCmd) ────────────────────\n\ndiscoverCmd\n .command('search')\n .description('Search all content sources for skills, agents, rules, hooks, MCP servers')\n .argument('<query>', 'Search query')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-t, --type <type>', 'Filter by content type (skills, agents, rules, hooks, mcp, etc.)')\n .option('-n, --max <n>', 'Maximum results', '20')\n .option('--remote', 'Also search remote sources (GitHub API, registries)')\n .option('--json', 'Output as JSON')\n .action(async (query: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n\n const maxResults = parseInt(opts.max as string, 10);\n const type = opts.type as string | undefined;\n\n if (opts.remote) {\n const { discoverRemote } = await import('../runtime/sources.js');\n const results = await discoverRemote(dir, query, {\n type: type as 'skills' | 'agents' | undefined,\n maxResults,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(results, null, 2));\n } else if (results.length === 0) {\n console.log('No results found.');\n } else {\n console.log(`${results.length} result(s):\\n`);\n for (const r of results) {\n console.log(` [${r.type}] ${r.name} (score: ${r.score.toFixed(2)})`);\n console.log(` Source: ${r.source.name}`);\n console.log(` ${r.url}`);\n if (r.description) console.log(` ${r.description}`);\n console.log();\n }\n }\n } else {\n const { discoverSources } = await import('../runtime/sources.js');\n const results = discoverSources(dir, query, {\n type: type as 'skills' | 'agents' | undefined,\n maxResults,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(results, null, 2));\n } else if (results.length === 0) {\n console.log('No results found. Try --remote to search GitHub and registries.');\n } else {\n console.log(`${results.length} result(s):\\n`);\n for (const r of results) {\n console.log(` [${r.type}] ${r.name} (score: ${r.score.toFixed(2)})`);\n console.log(` Source: ${r.source.name}`);\n console.log(` ${r.url}`);\n if (r.description) console.log(` ${r.description}`);\n console.log();\n }\n }\n }\n });\n\n// ── Browse ──────────────────────────────────────────────────────────────────\n\nprogram\n .command('browse')\n .description('Browse available community content — starter packs, sources, and installed primitives')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--type <type>', 'Filter by content type (packs, sources, installed)')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { listStarterPacks } = await import('../runtime/starter-packs.js');\n const { loadAllSources, getSourcesSummary } = await import('../runtime/sources.js');\n const { listInstalledBundles } = await import('../runtime/primitive-registry.js');\n\n const filter = opts.type as string | undefined;\n const sections: Array<{ title: string; type: string; items: unknown[] }> = [];\n\n // Starter Packs\n if (!filter || filter === 'packs') {\n const packs = listStarterPacks();\n sections.push({\n title: 'Starter Packs',\n type: 'packs',\n items: packs.map(p => ({\n name: p.name,\n description: p.description,\n files: p.fileCount,\n tags: p.tags,\n install: `harness install pack:${p.name}`,\n })),\n });\n }\n\n // Community Sources\n if (!filter || filter === 'sources') {\n const sources = loadAllSources(dir);\n const summary = getSourcesSummary(dir);\n const typeEntries = Object.entries(summary)\n .filter(([, s]) => s.length > 0)\n .map(([type, s]) => `${type}: ${s.length}`);\n sections.push({\n title: 'Community Sources',\n type: 'sources',\n items: sources.map(s => ({\n name: s.name,\n url: s.url,\n type: s.type,\n content: s.content,\n stats: s.stats,\n })),\n ...(typeEntries.length > 0 ? { summary: typeEntries } : {}),\n });\n }\n\n // Installed Bundles\n if (!filter || filter === 'installed') {\n const installed = listInstalledBundles(dir);\n sections.push({\n title: 'Installed Bundles',\n type: 'installed',\n items: installed.map(b => ({\n name: b.name,\n description: b.description,\n version: b.version,\n types: b.types,\n files: b.fileCount,\n })),\n });\n }\n\n if (opts.json) {\n const output: Record<string, unknown> = {};\n for (const section of sections) {\n output[section.type] = section.items;\n }\n console.log(JSON.stringify(output, null, 2));\n return;\n }\n\n // Text output\n console.log('=== Agent Harness Content Browser ===\\n');\n\n for (const section of sections) {\n console.log(`── ${section.title} ──\\n`);\n if (section.items.length === 0) {\n console.log(' (none)\\n');\n continue;\n }\n\n for (const item of section.items as Array<Record<string, unknown>>) {\n if (section.type === 'packs') {\n console.log(` pack:${item.name as string}`);\n console.log(` ${item.description as string}`);\n console.log(` Files: ${item.files as number} | Tags: ${(item.tags as string[]).join(', ')}`);\n console.log(` Install: ${item.install as string}`);\n console.log();\n } else if (section.type === 'sources') {\n const stats = item.stats as Record<string, number> | undefined;\n const statsStr = stats ? ` (${Object.entries(stats).map(([k, v]) => `${v} ${k}`).join(', ')})` : '';\n console.log(` [${item.type as string}] ${item.name as string}${statsStr}`);\n console.log(` ${item.url as string}`);\n console.log(` Content: ${(item.content as string[]).join(', ')}`);\n console.log();\n } else if (section.type === 'installed') {\n console.log(` ${item.name as string} v${item.version as string}`);\n if (item.description) console.log(` ${item.description as string}`);\n console.log(` Types: ${(item.types as string[]).join(', ')} | Files: ${item.files as number}`);\n console.log();\n }\n }\n }\n\n // Quick tips\n console.log('── Quick Start ──\\n');\n console.log(' Install a pack: harness install pack:<name> -d <dir>');\n console.log(' Search sources: harness discover search <query> -d <dir>');\n console.log(' Install anything: harness install <url-or-name> -d <dir>');\n console.log(' Add a source: harness sources add <url> -d <dir>');\n console.log();\n });\n\n// ── Semantic Search ──────────────────────────────────────────────────────────\n\nconst semanticCmd = program.command('semantic').description('Semantic search over indexed primitives');\n\nsemanticCmd\n .command('index')\n .description('Index all primitives for semantic search (requires an embed function at runtime — shows stats only from CLI)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { getEmbeddingStats } = await import('../runtime/semantic-search.js');\n const stats = getEmbeddingStats(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(stats, null, 2));\n } else {\n console.log('Embedding index stats:');\n console.log(` Indexed: ${stats.indexed} primitives`);\n console.log(` Model: ${stats.modelId ?? '(none)'}`);\n console.log(` Dimensions: ${stats.dimensions}`);\n console.log(` Last indexed: ${stats.lastIndexedAt ?? '(never)'}`);\n console.log(` Store size: ${(stats.storeSize / 1024).toFixed(1)} KB`);\n }\n });\n\nsemanticCmd\n .command('stats')\n .description('Show embedding store statistics')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n const { getEmbeddingStats, detectStalePrimitives, loadEmbeddingStore } = await import('../runtime/semantic-search.js');\n const stats = getEmbeddingStats(dir);\n const store = loadEmbeddingStore(dir);\n const stale = detectStalePrimitives(dir, store, stats.modelId ?? '');\n\n if (opts.json) {\n console.log(JSON.stringify({ ...stats, stale: stale.length }, null, 2));\n } else {\n console.log('Semantic search stats:');\n console.log(` Indexed: ${stats.indexed} primitives`);\n console.log(` Stale: ${stale.length} primitive(s) need re-indexing`);\n console.log(` Model: ${stats.modelId ?? '(none)'}`);\n console.log(` Dimensions: ${stats.dimensions}`);\n console.log(` Last indexed: ${stats.lastIndexedAt ?? '(never)'}`);\n console.log(` Store size: ${(stats.storeSize / 1024).toFixed(1)} KB`);\n }\n });\n\n// ── Universal Installer ──────────────────────────────────────────────────────\n\nprogram\n .command('install')\n .description('Install a primitive from any source (file, URL, or name)')\n .argument('<source>', 'File path, HTTPS URL, or source name to install')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-t, --type <type>', 'Override detected type (skill, rule, agent, playbook, workflow, tool)')\n .option('--id <id>', 'Override generated ID')\n .option('--force', 'Force install despite validation warnings')\n .option('--skip-fix', 'Skip auto-fix (no frontmatter/L0/L1 generation)')\n .option('--tags <tags...>', 'Additional tags to add')\n .option('--json', 'Output as JSON')\n .action(async (source: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n loadEnvFromDir(dir);\n\n // Handle pack: prefix — install builtin starter packs\n const { isPackReference, parsePackName, getStarterPack, listStarterPacks } = await import('../runtime/starter-packs.js');\n if (isPackReference(source)) {\n const packName = parsePackName(source);\n\n // Special case: pack:list shows available packs\n if (packName === 'list') {\n const packs = listStarterPacks();\n console.log('\\nAvailable starter packs:\\n');\n for (const p of packs) {\n console.log(` pack:${p.name}`);\n console.log(` ${p.description}`);\n console.log(` Files: ${p.fileCount} | Tags: ${p.tags.join(', ')}\\n`);\n }\n console.log(`Install with: harness install pack:<name> -d <harness-dir>`);\n return;\n }\n\n const bundle = getStarterPack(packName);\n if (!bundle) {\n const available = listStarterPacks().map(p => `pack:${p.name}`).join(', ');\n console.error(`Unknown starter pack: \"${packName}\"\\nAvailable packs: ${available}`);\n process.exitCode = 1;\n return;\n }\n\n const { installBundle } = await import('../runtime/primitive-registry.js');\n const bundleResult = installBundle(dir, bundle, {\n overwrite: opts.force as boolean | undefined,\n force: opts.force as boolean | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(bundleResult, null, 2));\n } else if (bundleResult.installed) {\n console.log(`\\nInstalled pack: ${packName}`);\n console.log(` Files: ${bundleResult.files.length}`);\n for (const f of bundleResult.files) {\n console.log(` + ${f}`);\n }\n if (bundleResult.skipped.length > 0) {\n console.log(` Skipped (already exist): ${bundleResult.skipped.length}`);\n for (const f of bundleResult.skipped) {\n console.log(` ~ ${f}`);\n }\n console.log(` Use --force to overwrite existing files.`);\n }\n console.log(`\\nCustomize the workflows in your workflows/ directory.`);\n } else {\n console.error(`Failed to install pack: ${packName}`);\n for (const err of bundleResult.errors) {\n console.error(` ${err}`);\n }\n process.exitCode = 1;\n }\n return;\n }\n\n const { universalInstall } = await import('../runtime/universal-installer.js');\n\n const result = await universalInstall(dir, source, {\n type: opts.type as string | undefined,\n id: opts.id as string | undefined,\n force: opts.force as boolean | undefined,\n skipFix: opts.skipFix as boolean | undefined,\n tags: opts.tags as string[] | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.installed) {\n console.log(`Installed: ${result.destination}`);\n console.log(` Format: ${result.format.format} (${(result.format.confidence * 100).toFixed(0)}% confidence)`);\n if (result.format.primitiveType) {\n console.log(` Type: ${result.format.primitiveType}`);\n }\n if (result.fixes.length > 0) {\n console.log(` Fixes:`);\n for (const fix of result.fixes) {\n console.log(` - ${fix}`);\n }\n }\n if (result.suggestedDependencies.length > 0) {\n console.log(` Dependencies to consider:`);\n for (const dep of result.suggestedDependencies) {\n console.log(` - ${dep}`);\n }\n }\n } else {\n console.error(`Failed to install: ${source}`);\n for (const err of result.errors) {\n console.error(` ${err}`);\n }\n if (result.fixes.length > 0) {\n console.log(` Attempted fixes:`);\n for (const fix of result.fixes) {\n console.log(` - ${fix}`);\n }\n }\n process.exitCode = 1;\n }\n }\n });\n\n// ── Versioning ───────────────────────────────────────────────────────────────\n\nconst versionCmd = program.command('version').description('Git-backed primitive versioning');\n\nversionCmd\n .command('init')\n .description('Initialize git versioning for the harness')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { initVersioning, isGitRepo } = await import('../runtime/versioning.js');\n if (isGitRepo(dir)) {\n console.log('Versioning already initialized.');\n } else {\n const ok = initVersioning(dir);\n console.log(ok ? 'Versioning initialized.' : 'Failed to initialize versioning.');\n }\n });\n\nversionCmd\n .command('snapshot')\n .description('Take a versioned snapshot of the current harness state')\n .argument('<message>', 'Commit message')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-t, --tag <tag>', 'Tag this version')\n .option('--json', 'Output as JSON')\n .action(async (message: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { snapshot } = await import('../runtime/versioning.js');\n const result = snapshot(dir, message, { tag: opts.tag as string | undefined });\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else if (result.success && result.files.length > 0) {\n console.log(`Snapshot ${result.hash.slice(0, 7)}: ${result.files.length} file(s) committed.`);\n for (const f of result.files) { console.log(` ${f}`); }\n if (opts.tag) { console.log(` Tagged: ${opts.tag}`); }\n } else if (result.error) {\n console.log(result.error);\n }\n });\n\nversionCmd\n .command('log')\n .description('Show version history')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-n, --limit <n>', 'Max entries', '20')\n .option('-f, --file <path>', 'Filter by file path')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { getVersionLog } = await import('../runtime/versioning.js');\n const log = getVersionLog(dir, {\n limit: parseInt(opts.limit as string, 10),\n file: opts.file as string | undefined,\n });\n\n if (opts.json) {\n console.log(JSON.stringify(log, null, 2));\n } else if (log.entries.length === 0) {\n console.log('No version history. Run `harness version init` first.');\n } else {\n console.log(`Version history (${log.entries.length} entries):\\n`);\n for (const entry of log.entries) {\n const tag = entry.tag ? ` [${entry.tag}]` : '';\n console.log(` ${entry.hash} ${entry.message}${tag}`);\n console.log(` ${entry.timestamp} — ${entry.filesChanged.length} file(s)`);\n }\n }\n });\n\nversionCmd\n .command('diff')\n .description('Show changes between versions')\n .argument('<from>', 'Source commit hash or tag')\n .argument('[to]', 'Target commit hash or tag (default: HEAD)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (from: string, to: string | undefined, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { getVersionDiff } = await import('../runtime/versioning.js');\n const diff = getVersionDiff(dir, from, to);\n\n if (opts.json) {\n console.log(JSON.stringify(diff, null, 2));\n } else {\n console.log(`${diff.summary}\\n`);\n for (const entry of diff.entries) {\n const icon = entry.status === 'added' ? '+' : entry.status === 'deleted' ? '-' : 'M';\n const stats = entry.additions !== undefined ? ` (+${entry.additions}/-${entry.deletions})` : '';\n console.log(` [${icon}] ${entry.file}${stats}`);\n }\n }\n });\n\nversionCmd\n .command('rollback')\n .description('Roll back to a previous version (creates new commit preserving history)')\n .argument('<target>', 'Commit hash or tag to roll back to')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (target: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { rollback } = await import('../runtime/versioning.js');\n const result = rollback(dir, target);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else if (result.success) {\n console.log(`Rolled back to ${result.targetHash.slice(0, 7)}.`);\n console.log(` ${result.restoredFiles.length} file(s) restored.`);\n } else {\n console.log(`Rollback failed: ${result.error}`);\n }\n });\n\nversionCmd\n .command('tag')\n .description('Tag the current version')\n .argument('<name>', 'Tag name (e.g., v1.0.0)')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('-m, --message <msg>', 'Tag message')\n .action(async (name: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { tagVersion } = await import('../runtime/versioning.js');\n const ok = tagVersion(dir, name, opts.message as string | undefined);\n console.log(ok ? `Tagged: ${name}` : 'Failed to create tag.');\n });\n\nversionCmd\n .command('tags')\n .description('List all version tags')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { listTags } = await import('../runtime/versioning.js');\n const tags = listTags(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(tags, null, 2));\n } else if (tags.length === 0) {\n console.log('No tags.');\n } else {\n for (const t of tags) {\n console.log(` ${t.tag} → ${t.hash} (${t.message})`);\n }\n }\n });\n\nversionCmd\n .command('pending')\n .description('Show uncommitted changes')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .option('--json', 'Output as JSON')\n .action(async (opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { getPendingChanges } = await import('../runtime/versioning.js');\n const changes = getPendingChanges(dir);\n\n if (opts.json) {\n console.log(JSON.stringify(changes, null, 2));\n } else if (changes.length === 0) {\n console.log('No pending changes.');\n } else {\n console.log(`${changes.length} pending change(s):\\n`);\n for (const c of changes) {\n const icon = c.status === 'added' ? '+' : c.status === 'deleted' ? '-' : 'M';\n console.log(` [${icon}] ${c.file}`);\n }\n }\n });\n\nversionCmd\n .command('show')\n .description('Show file content at a specific version')\n .argument('<file>', 'File path relative to harness')\n .argument('<hash>', 'Commit hash or tag')\n .option('-d, --dir <dir>', 'Harness directory', '.')\n .action(async (file: string, hash: string, opts: Record<string, unknown>) => {\n const dir = resolve(opts.dir as string);\n const { getFileAtVersion } = await import('../runtime/versioning.js');\n const content = getFileAtVersion(dir, file, hash);\n if (content === null) {\n console.log(`File not found at version ${hash}.`);\n } else {\n console.log(content);\n }\n });\n\nprogram.parse();\n"],"mappings":";;;;;;;;AAgBA,SAAS,eAAe;AACxB,SAAS,qBAAqB;AAC9B,SAAS,SAAS,MAAM,gBAAgB;AACxC,SAAS,kBAAkB;AAC3B,SAAS,UAAU,kBAAkB;AAhBrC,IAAM,2BAA2B,QAAQ,UAAU,SAAS;AAC5D,QAAQ,mBAAmB,SAAS;AACpC,QAAQ,GAAG,WAAW,CAAC,YAAmC;AACxD,MAAI,QAAQ,SAAS,yBAAyB,SAAS,KAAK,QAAQ,OAAO,GAAG;AAC5E;AAAA,EACF;AAEA,aAAW,WAAW,0BAA0B;AAC9C,IAAC,QAA+C,OAAO;AAAA,EACzD;AACF,CAAC;AAaD,IAAM,gBAAgB,QAAQ,IAAI,oBAAoB;AACtD,WAAW,EAAE,OAAO,cAAc,CAAC;AACnC,WAAW,EAAE,MAAM,QAAQ,YAAY,GAAG,OAAO,cAAc,CAAC;AAEhE,IAAM,UAAU,IAAI,QAAQ;AAG5B,IAAM,gBAAwC;AAAA,EAC5C,SAAS;AAAA,EACT,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,UAAU;AAAA,EACV,SAAS;AAAA,EACT,cAAc;AAChB;AAEA,SAAS,aAAa,OAAoC;AACxD,MAAI,CAAC,MAAO,QAAO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