{
  "version": 3,
  "sources": ["../src/utils/logger.ts", "../src/mapping/index.ts", "../src/pty/index.ts", "../src/lsp/index.ts", "../src/sandbox/index.ts", "../src/strategies/index.ts", "../src/executor/stream-helpers.ts", "../src/auth/oauth-keychain.ts", "../src/auth/openai-oauth.ts", "../src/auth/gemini-oauth.ts", "../src/auth/cch.ts", "../src/executor/local.ts", "../src/executor/profiles.ts", "../src/hooks/index.ts", "../src/tools/worktree.ts", "../src/tools/gemini/definitions/base-declarations.ts", "../src/tools/docker-sandbox.ts", "../src/tools/gemini/crew-adapter.ts", "../src/engine/run-state.ts", "../src/executor/tool-result-clearing.ts", "../src/executor/tool-batching.ts", "../src/execution/agentic-guidance.ts", "../src/execution/action-ranking.ts", "../src/engine/run-engine.ts", "../src/learning/corrections.ts", "../src/context/token-compaction.ts", "../src/execution/transcript.ts", "../src/engine/patch-critic.ts", "../src/engine/structured-history.ts", "../src/engine/tool-filter.ts", "../src/engine/top-of-mind.ts", "../src/executor/scratchpad.ts", "../src/collections/index.ts", "../src/executor/agentic-executor.ts", "../src/prompts/registry.ts", "../src/utils/structured-json.ts", "../src/prompts/dual-l2.ts", "../src/pipeline/context-pack.ts", "../src/pipeline/agent-memory.ts", "../src/utils/json-schemas.ts", "../src/metrics/json-parse.ts", "../src/pipeline/run-state.ts", "../src/capabilities/index.ts", "../src/pipeline/task-envelope.ts", "../src/execution/qa-gate.ts", "../src/context/project-context.ts", "../src/executor/reviewer.ts", "../src/engine/delegation.ts", "../src/cli/file-commands.ts", "../src/context/codebase-rag.ts", "../src/pipeline/unified.ts", "../src/orchestrator/worker-pool.ts", "../src/orchestrator/index.ts", "../src/memory/agentkeeper.ts", "../src/ci/index.ts", "../src/blast-radius/index.ts", "../src/status/dashboard.ts", "../src/repl/model-info.ts", "../src/engine/chat-recall.ts", "../src/engine/summon.ts", "../src/shell/index.ts", "../src/cli/index.ts", "../src/agent/router.js", "../src/context/git.ts", "../src/agent/prompt.ts", "../src/tools/manager.js", "../src/config/manager.js", "../src/session/manager.ts", "../src/auth/token-finder.ts", "../src/planner/index.ts", "../src/cache/token-cache.ts", "../src/diagnostics/doctor.ts", "../src/mcp/index.ts", "../src/cost/predictor.ts", "../src/engines/index.ts", "../src/engines/session-layer.ts", "../src/session/conversation-transcript.ts", "../src/engines/native-session.ts", "../src/engines/tool-audit.ts", "../src/watch/index.ts", "../src/studio/broadcaster.ts", "../src/hello/index.ts", "../src/multirepo/index.ts", "../src/browser/index.ts", "../src/team/index.ts", "../src/voice/listener.ts", "../src/context/augment.ts", "../src/review/index.ts", "../src/headless/index.ts", "../src/runtime/execution-policy.ts", "../src/interface/server.ts", "../src/interface/mcp-handler.ts", "../src/metrics/pipeline.ts", "../src/sourcegraph/index.ts", "../src/repl/index.ts", "../src/memory/broker.ts", "../src/checkpoint/store.ts", "../src/risk/score.ts", "../src/tui/index.ts", "../src/xai/search.ts", "../src/config/repo-config.ts", "../src/github/nl.ts", "../src/config/model-policy.ts", "../src/autofix/store.ts", "../src/autofix/runner.ts"],
  "sourcesContent": ["const useColor = Boolean(process.stdout?.isTTY) && !process.env.NO_COLOR;\n\nfunction ansi(code: string, text: string): string {\n  if (!useColor) return text;\n  return `\\u001b[${code}m${text}\\u001b[0m`;\n}\n\nconst color = {\n  gray: (text: string) => ansi('90', text),\n  red: (text: string) => ansi('31', text),\n  yellow: (text: string) => ansi('33', text),\n  green: (text: string) => ansi('32', text),\n  blue: (text: string) => ansi('34', text),\n  cyan: (text: string) => ansi('36', text),\n  bold: (text: string) => ansi('1', text),\n};\n\nexport class Logger {\n  level: string;\n  prefix: string;\n\n  constructor(options: { level?: string; prefix?: string } = {}) {\n    this.level = options.level || 'info';\n    this.prefix = options.prefix || '[crewswarm]';\n  }\n\n  formatMessage(level: string, message: string, ...args: unknown[]) {\n    const timestamp = new Date().toISOString();\n    const prefix = `${color.gray(timestamp)} ${this.prefix}`;\n    \n    let colorFn;\n    switch (level) {\n      case 'error': colorFn = color.red; break;\n      case 'warn': colorFn = color.yellow; break;\n      case 'success': colorFn = color.green; break;\n      case 'debug': colorFn = color.gray; break;\n      default: colorFn = color.blue;\n    }\n\n    return `${prefix} ${colorFn(`[${level.toUpperCase()}]`)} ${message}`;\n  }\n\n  info(message: string, ...args: unknown[]) {\n    console.log(this.formatMessage('info', message), ...args);\n  }\n\n  error(message: string, ...args: unknown[]) {\n    console.error(this.formatMessage('error', message), ...args);\n  }\n\n  warn(message: string, ...args: unknown[]) {\n    console.warn(this.formatMessage('warn', message), ...args);\n  }\n\n  success(message: string, ...args: unknown[]) {\n    console.log(this.formatMessage('success', message), ...args);\n  }\n\n  debug(message: string, ...args: unknown[]) {\n    if (this.level === 'debug') {\n      console.log(this.formatMessage('debug', message), ...args);\n    }\n  }\n\n  highlightCodeBlocks(text: string) {\n    if (!text.includes('```')) return text;\n\n    const parts = text.split(/(```[\\s\\S]*?```)/g);\n    return parts\n      .map(part => {\n        if (!part.startsWith('```')) return part;\n        return color.cyan(part);\n      })\n      .join('');\n  }\n\n  printWithHighlight(text: string) {\n    // Rich markdown rendering for terminal\n    let output = this.highlightCodeBlocks(text);\n\n    // Process line-by-line for headers, bullets, etc.\n    output = output.split('\\n').map(line => {\n      // Headers: # ## ###\n      if (/^#{1,3}\\s/.test(line)) {\n        return color.bold(color.cyan(line));\n      }\n      // Bullet points\n      if (/^\\s*[-*]\\s/.test(line)) {\n        return line.replace(/^(\\s*)([-*])(\\s)/, `$1${color.cyan('$2')}$3`);\n      }\n      // Numbered lists\n      if (/^\\s*\\d+\\.\\s/.test(line)) {\n        return line.replace(/^(\\s*)(\\d+\\.)(\\s)/, `$1${color.cyan('$2')}$3`);\n      }\n      return line;\n    }).join('\\n');\n\n    // Inline formatting (skip inside code blocks)\n    // Bold: **text**\n    output = output.replace(/\\*\\*([^*]+)\\*\\*/g, (_, t) => color.bold(t));\n    // Inline code: `text`\n    output = output.replace(/`([^`]+)`/g, (_, t) => color.cyan(t));\n\n    console.log(output);\n  }\n\n  highlightDiff(diff: string) {\n    return diff\n      .split('\\n')\n      .map(line => {\n        if (line.startsWith('+') && !line.startsWith('+++')) return color.green(line);\n        if (line.startsWith('-') && !line.startsWith('---')) return color.red(line);\n        if (line.startsWith('@@')) return color.cyan(line);\n        if (line.startsWith('diff') || line.startsWith('index') || line.startsWith('---') || line.startsWith('+++')) {\n          return color.bold(line);\n        }\n        return line;\n      })\n      .join('\\n');\n  }\n\n  progress(current: number, total: number, label = 'Progress') {\n    const safeTotal = Math.max(1, total);\n    const clamped = Math.min(Math.max(current, 0), safeTotal);\n    const width = 24;\n    const filled = Math.round((clamped / safeTotal) * width);\n    const bar = `${'='.repeat(filled)}${'-'.repeat(width - filled)}`;\n    const pct = Math.round((clamped / safeTotal) * 100);\n    console.log(`${color.blue(label)} [${bar}] ${pct}% (${clamped}/${safeTotal})`);\n  }\n}\n\n/** Shared singleton logger instance for modules that need lightweight logging without injection. */\nexport const logger = new Logger({ level: process.env.CREW_LOG_LEVEL || 'info' });\n", "import { readdir, readFile, stat } from 'node:fs/promises';\nimport { dirname, extname, join, relative, resolve } from 'node:path';\nimport ignore from 'ignore';\n\nexport interface RepositoryGraphNode {\n  path: string;\n  imports: string[];\n  importedBy: string[];\n}\n\nexport interface RepositoryGraph {\n  root: string;\n  nodeCount: number;\n  edgeCount: number;\n  nodes: RepositoryGraphNode[];\n}\n\nfunction toHtmlEscaped(value: string): string {\n  return value\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;');\n}\n\nconst SOURCE_EXTENSIONS = new Set([\n  '.ts',\n  '.tsx',\n  '.js',\n  '.jsx',\n  '.mjs',\n  '.cjs'\n]);\n\nfunction createIgnoreMatcher(rootDir: string) {\n  const ig = ignore();\n  ig.add(['.git', 'node_modules', 'dist', 'build', '.crew', '.next', '.turbo', 'coverage']);\n  return readFile(join(rootDir, '.gitignore'), 'utf8')\n    .then(content => {\n      ig.add(content);\n      return ig;\n    })\n    .catch(() => ig);\n}\n\nasync function walkIncludedEntries(rootDir: string): Promise<Array<{ fullPath: string; relPath: string; isDir: boolean }>> {\n  console.log(`[walkIncludedEntries] Starting walk for root: ${rootDir}`);\n  const ig = await createIgnoreMatcher(rootDir);\n  console.log(`[walkIncludedEntries] Ignore matcher created`);\n  const out: Array<{ fullPath: string; relPath: string; isDir: boolean }> = [];\n\n  async function walk(currentPath: string): Promise<void> {\n    const relCurrentPath = relative(rootDir, currentPath);\n    console.log(`[walk] Entering directory: ${relCurrentPath || '(root)'}`);\n    \n    let entries: string[];\n    try {\n      entries = await readdir(currentPath);\n      console.log(`[walk] Directory ${relCurrentPath || '(root)'} contains ${entries.length} entries`);\n    } catch (err) {\n      console.log(`[walk] Failed to read directory ${relCurrentPath || '(root)'}: ${err}`);\n      return;\n    }\n\n    for (const entry of entries) {\n      const fullPath = join(currentPath, entry);\n      const relPath = relative(rootDir, fullPath);\n      console.log(`[walk] Processing entry: ${relPath}`);\n      \n      let entryStat;\n      try {\n        entryStat = await stat(fullPath);\n        console.log(`[walk] Successfully stat'd: ${relPath}`);\n      } catch (err) {\n        console.log(`[walk] Failed to stat ${relPath}: ${err}`);\n        continue;\n      }\n\n      const isDir = entryStat.isDirectory();\n      console.log(`[walk] Entry ${relPath} is ${isDir ? 'directory' : 'file'}`);\n      \n      const checkPath = isDir ? `${relPath}/` : relPath;\n      const shouldIgnore = ig.ignores(checkPath);\n      console.log(`[walk] Ignore check for ${checkPath}: ${shouldIgnore ? 'IGNORED' : 'INCLUDED'}`);\n      \n      if (shouldIgnore) {\n        console.log(`[walk] Skipping ignored path: ${checkPath}`);\n        continue;\n      }\n\n      console.log(`[walk] Adding to output: ${relPath} (${isDir ? 'dir' : 'file'})`);\n      out.push({ fullPath, relPath, isDir });\n      \n      if (isDir) {\n        console.log(`[walk] Recursing into directory: ${relPath}`);\n        await walk(fullPath);\n        console.log(`[walk] Returned from directory: ${relPath}`);\n      }\n    }\n    \n    console.log(`[walk] Exiting directory: ${relCurrentPath || '(root)'}`);\n  }\n\n  await walk(rootDir);\n  console.log(`[walkIncludedEntries] Walk complete. Found ${out.length} entries (${out.filter(e => e.isDir).length} dirs, ${out.filter(e => !e.isDir).length} files)`);\n  return out;\n}\n\nfunction parseImports(content: string): string[] {\n  const specs = new Set<string>();\n  const patterns = [\n    /import\\s+[^'\"]*?from\\s+['\"]([^'\"]+)['\"]/g,\n    /import\\s*?\\(\\s*?['\"]([^'\"]+)['\"]\\s*?\\)/g,\n    /export\\s+[^'\"]*?from\\s+['\"]([^'\"]+)['\"]/g,\n    /require\\s*?\\(\\s*?['\"]([^'\"]+)['\"]\\s*?\\)/g\n  ];\n\n  for (const rx of patterns) {\n    for (const match of content.matchAll(rx)) {\n      if (match[1]) specs.add(match[1]);\n    }\n  }\n  return Array.from(specs);\n}\n\nfunction resolveImport(fromFile: string, specifier: string, knownFiles: Set<string>): string | null {\n  if (!specifier.startsWith('.')) return null;\n  const fromDir = dirname(fromFile);\n  const absBase = resolve(fromDir, specifier);\n  const candidates = [\n    absBase,\n    `${absBase}.ts`,\n    `${absBase}.tsx`,\n    `${absBase}.js`,\n    `${absBase}.jsx`,\n    `${absBase}.mjs`,\n    `${absBase}.cjs`,\n    join(absBase, 'index.ts'),\n    join(absBase, 'index.tsx'),\n    join(absBase, 'index.js'),\n    join(absBase, 'index.jsx'),\n    join(absBase, 'index.mjs'),\n    join(absBase, 'index.cjs')\n  ];\n\n  for (const candidate of candidates) {\n    if (knownFiles.has(candidate)) return candidate;\n  }\n  return null;\n}\n\nexport async function buildRepositoryGraph(dirPath: string): Promise<RepositoryGraph> {\n  const root = resolve(dirPath);\n  const entries = await walkIncludedEntries(root);\n  const sourceFiles = entries\n    .filter(entry => !entry.isDir && SOURCE_EXTENSIONS.has(extname(entry.fullPath).toLowerCase()))\n    .map(entry => entry.fullPath);\n\n  const knownFileSet = new Set(sourceFiles);\n  const importsByFile = new Map<string, Set<string>>();\n  const importedByFile = new Map<string, Set<string>>();\n\n  for (const file of sourceFiles) {\n    importsByFile.set(file, new Set());\n    importedByFile.set(file, new Set());\n  }\n\n  for (const file of sourceFiles) {\n    let content = '';\n    try {\n      content = await readFile(file, 'utf8');\n    } catch {\n      continue;\n    }\n    const imports = parseImports(content);\n    for (const specifier of imports) {\n      const resolved = resolveImport(file, specifier, knownFileSet);\n      if (!resolved) continue;\n      importsByFile.get(file)?.add(resolved);\n      importedByFile.get(resolved)?.add(file);\n    }\n  }\n\n  const nodes: RepositoryGraphNode[] = sourceFiles.map(file => ({\n    path: relative(root, file),\n    imports: Array.from(importsByFile.get(file) || []).map(x => relative(root, x)).sort(),\n    importedBy: Array.from(importedByFile.get(file) || []).map(x => relative(root, x)).sort()\n  })).sort((a, b) => a.path.localeCompare(b.path));\n\n  const edgeCount = nodes.reduce((sum, node) => sum + node.imports.length, 0);\n  return {\n    root,\n    nodeCount: nodes.length,\n    edgeCount,\n    nodes\n  };\n}\n\nexport async function buildRepositoryMap(dirPath: string): Promise<string> {\n  const root = resolve(dirPath);\n  const entries = await walkIncludedEntries(root);\n  const lines: string[] = [];\n  const rootName = root.split('/').pop() || '.';\n  lines.push(`${rootName}/`);\n\n  const byParent = new Map<string, Array<{ fullPath: string; relPath: string; isDir: boolean }>>();\n  for (const entry of entries) {\n    const parentRel = relative(root, dirname(entry.fullPath));\n    const key = parentRel === '' ? '.' : parentRel;\n    if (!byParent.has(key)) byParent.set(key, []);\n    byParent.get(key)?.push(entry);\n  }\n\n  function render(relDir: string, prefix: string) {\n    const bucket = (byParent.get(relDir) || []).slice().sort((a, b) => {\n      if (a.isDir && !b.isDir) return -1;\n      if (!a.isDir && b.isDir) return 1;\n      return a.relPath.localeCompare(b.relPath);\n    });\n\n    for (let i = 0; i < bucket.length; i += 1) {\n      const item = bucket[i];\n      const isLast = i === bucket.length - 1;\n      const marker = isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 ';\n      lines.push(`${prefix}${marker}${item.relPath.split('/').pop() || item.relPath}${item.isDir ? '/' : ''}`);\n      if (item.isDir) {\n        render(item.relPath, `${prefix}${isLast ? '    ' : '\u2502   '}`);\n      }\n    }\n  }\n\n  render('.', '');\n  return `${lines.join('\\n')}\\n`;\n}\n\nexport function renderGraphHtml(graph: RepositoryGraph): string {\n  const data = JSON.stringify(graph);\n  return `<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\" />\n  <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n  <title>Repository Graph</title>\n  <style>\n    :root { --bg:#0f172a; --card:#111827; --text:#e5e7eb; --muted:#94a3b8; --link:#38bdf8; --edge:#334155; }\n    body { margin:0; background:linear-gradient(120deg,#0b1220,#111827); color:var(--text); font:14px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace; }\n    .wrap { max-width:1200px; margin:0 auto; padding:24px; }\n    h1 { margin:0 0 4px; font-size:20px; }\n    .meta { color:var(--muted); margin-bottom:16px; }\n    .search { width:100%; padding:10px 12px; border:1px solid #374151; border-radius:8px; background:#0b1020; color:var(--text); margin-bottom:14px; }\n    .grid { display:grid; gap:10px; grid-template-columns:repeat(auto-fill,minmax(320px,1fr)); }\n    .node { background:rgba(17,24,39,.8); border:1px solid #1f2937; border-radius:10px; padding:12px; }\n    .path { color:var(--link); font-weight:600; margin-bottom:8px; word-break:break-all; }\n    .label { color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:.04em; }\n    .list { margin:6px 0 0; padding-left:16px; max-height:120px; overflow:auto; }\n    .empty { color:var(--muted); font-style:italic; }\n  </style>\n</head>\n<body>\n  <div class=\"wrap\">\n    <h1>Repository Dependency Graph</h1>\n    <div class=\"meta\" id=\"meta\"></div>\n    <input id=\"search\" class=\"search\" placeholder=\"Filter nodes by path...\" />\n    <div id=\"grid\" class=\"grid\"></div>\n  </div>\n  <script>\n    const graph = ${data};\n    const grid = document.getElementById('grid');\n    const meta = document.getElementById('meta');\n    const search = document.getElementById('search');\n    const esc = s => String(s).replace(/[&<>\\\\\"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'}[c] || c));\n    meta.textContent = \\`\\${graph.root} | nodes: \\${graph.nodeCount} | edges: \\${graph.edgeCount}\\`;\n    function render(filter = '') {\n      const q = filter.trim().toLowerCase();\n      const nodes = graph.nodes.filter(n => !q || n.path.toLowerCase().includes(q));\n      grid.innerHTML = nodes.map(n => \\`\n        <article class=\"node\">\n          <div class=\"path\">\\${esc(n.path)}</div>\n          <div class=\"label\">imports</div>\n          \\${n.imports.length ? '<ul class=\"list\">' + n.imports.map(i => '<li>' + esc(i) + '</li>').join('') + '</ul>' : '<div class=\"empty\">(none)</div>'}\n          <div class=\"label\" style=\"margin-top:8px\">imported by</div>\n          \\${n.importedBy.length ? '<ul class=\"list\">' + n.importedBy.map(i => '<li>' + esc(i) + '</li>').join('') + '</ul>' : '<div class=\"empty\">(none)</div>'}\n        </article>\n      \\`).join('');\n    }\n    render();\n    search.addEventListener('input', () => render(search.value));\n  </script>\n</body>\n</html>\n`;\n}\n\nexport function buildRepositoryGraphDot(graph: RepositoryGraph): string {\n  const lines: string[] = [];\n  lines.push('digraph RepositoryGraph {');\n  lines.push('  rankdir=LR;');\n  lines.push('  node [shape=box, style=rounded, fontsize=10];');\n\n  for (const node of graph.nodes) {\n    lines.push(`  \"${node.path}\";`);\n  }\n  for (const node of graph.nodes) {\n    for (const target of node.imports) {\n      lines.push(`  \"${node.path}\" -> \"${target}\";`);\n    }\n  }\n  lines.push('}');\n  return `${lines.join('\\n')}\\n`;\n}\n\nfunction escapeHtml(value: string): string {\n  return String(value)\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#39;');\n}\n\nexport function buildRepositoryGraphHtml(graph: RepositoryGraph): string {\n  const payload = JSON.stringify(graph);\n  return `<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\" />\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n  <title>Repository Graph</title>\n  <style>\n    :root { --bg:#0b1220; --panel:#111a2d; --text:#dbe7ff; --muted:#8fa7d1; --accent:#63d3ff; --line:#21314f; }\n    * { box-sizing:border-box; }\n    body { margin:0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; background:linear-gradient(160deg,#0a1324,#101a31); color:var(--text); }\n    .wrap { display:grid; grid-template-columns: 360px 1fr; min-height:100vh; }\n    .left { border-right:1px solid var(--line); padding:16px; background:rgba(8,13,24,.6); }\n    .right { padding:16px; }\n    input { width:100%; padding:10px; border:1px solid var(--line); border-radius:10px; background:#0f1728; color:var(--text); }\n    h1 { margin:0 0 8px; font-size:16px; color:var(--accent); }\n    .meta { color:var(--muted); font-size:12px; margin-bottom:12px; }\n    .list { margin-top:10px; max-height:calc(100vh - 130px); overflow:auto; border:1px solid var(--line); border-radius:10px; }\n    .item { padding:10px 12px; border-bottom:1px solid var(--line); cursor:pointer; font-size:12px; }\n    .item:hover, .item.active { background:#17223b; }\n    .item:last-child { border-bottom:none; }\n    .panel { border:1px solid var(--line); border-radius:12px; padding:14px; background:rgba(12,18,32,.75); }\n    .k { color:var(--muted); font-size:12px; margin-top:10px; }\n    .v { white-space:pre-wrap; font-size:12px; line-height:1.45; }\n    @media (max-width: 900px) { .wrap { grid-template-columns: 1fr; } .left { border-right:none; border-bottom:1px solid var(--line); } }\n  </style>\n</head>\n<body>\n  <div class=\"wrap\">\n    <aside class=\"left\">\n      <h1>Repository Graph</h1>\n      <div class=\"meta\">${escapeHtml(graph.root)}<br/>${graph.nodeCount} nodes \u2022 ${graph.edgeCount} edges</div>\n      <input id=\"q\" placeholder=\"Filter files...\" />\n      <div id=\"list\" class=\"list\"></div>\n    </aside>\n    <main class=\"right\">\n      <div class=\"panel\">\n        <h1 id=\"title\">Select a node</h1>\n        <div class=\"k\">Imports</div>\n        <div id=\"imports\" class=\"v\">(none)</div>\n        <div class=\"k\">Imported By</div>\n        <div id=\"importedBy\" class=\"v\">(none)</div>\n      </div>\n    </main>\n  </div>\n  <script>\n    const graph = ${payload};\n    const list = document.getElementById('list');\n    const q = document.getElementById('q');\n    const title = document.getElementById('title');\n    const importsEl = document.getElementById('imports');\n    const importedByEl = document.getElementById('importedBy');\n    let activePath = '';\n    function render(items) {\n      list.innerHTML = '';\n      for (const node of items) {\n        const row = document.createElement('div');\n        row.className = 'item' + (node.path === activePath ? ' active' : '');\n        row.textContent = node.path;\n        row.onclick = () => select(node.path);\n        list.appendChild(row);\n      }\n    }\n    function select(path) {\n      activePath = path;\n      const node = graph.nodes.find(n => n.path === path);\n      if (!node) return;\n      title.textContent = node.path;\n      importsEl.textContent = node.imports.length ? node.imports.join('\\\\n') : '(none)';\n      importedByEl.textContent = node.importedBy.length ? node.importedBy.join('\\\\n') : '(none)';\n      render(filterNodes(q.value));\n    }\n    function filterNodes(text) {\n      const t = String(text || '').toLowerCase().trim();\n      if (!t) return graph.nodes;\n      return graph.nodes.filter(n => n.path.toLowerCase().includes(t));\n    }\n    q.addEventListener('input', () => render(filterNodes(q.value)));\n    render(graph.nodes);\n    if (graph.nodes[0]) select(graph.nodes[0].path);\n  </script>\n</body>\n</html>\n`;\n}\n", "import { spawn as spawnChild } from 'node:child_process';\n\nexport interface PtyRunOptions {\n  cwd?: string;\n  shell?: string;\n  cols?: number;\n  rows?: number;\n  timeoutMs?: number;\n}\n\nexport interface PtyRunResult {\n  success: boolean;\n  exitCode: number;\n  signal: string | null;\n  output: string;\n}\n\ninterface PtyProcessLike {\n  onData(cb: (data: string) => void): void;\n  onExit(cb: (info: { exitCode: number; signal: number }) => void): void;\n  resize(cols: number, rows: number): void;\n  kill(): void;\n}\n\ninterface PtyPackageLike {\n  spawn(\n    file: string,\n    args: string | string[],\n    options: {\n      name: string;\n      cwd: string;\n      cols: number;\n      rows: number;\n      env: NodeJS.ProcessEnv;\n    }\n  ): PtyProcessLike;\n}\n\nexport async function runPtyCommand(command: string, options: PtyRunOptions = {}): Promise<PtyRunResult> {\n  if (!command || !String(command).trim()) {\n    throw new Error('PTY command is required');\n  }\n\n  let ptyPackage: PtyPackageLike | null = null;\n  try {\n    const mod = await import('node-pty') as { spawn?: PtyPackageLike['spawn']; default?: PtyPackageLike };\n    ptyPackage = mod.default || (mod.spawn ? { spawn: mod.spawn } : null);\n  } catch {\n    ptyPackage = null;\n  }\n\n  if (ptyPackage?.spawn) {\n    try {\n      return await runWithNodePty(command, options, ptyPackage);\n    } catch {\n      return runWithInherit(command, options);\n    }\n  }\n  return runWithInherit(command, options);\n}\n\nasync function runWithNodePty(command: string, options: PtyRunOptions, ptyPackage: PtyPackageLike): Promise<PtyRunResult> {\n  return new Promise(resolve => {\n    const shell = options.shell || process.env.SHELL || '/bin/bash';\n    const pty = ptyPackage.spawn(shell, ['-lc', command], {\n      name: 'xterm-color',\n      cwd: options.cwd || process.cwd(),\n      cols: options.cols || process.stdout.columns || 120,\n      rows: options.rows || process.stdout.rows || 30,\n      env: process.env\n    });\n\n    let output = '';\n    let done = false;\n\n    const timeoutMs = options.timeoutMs || 0;\n    const timer = timeoutMs > 0\n      ? setTimeout(() => {\n          if (done) return;\n          done = true;\n          pty.kill();\n          resolve({ success: false, exitCode: -1, signal: 'SIGTERM', output });\n        }, timeoutMs)\n      : null;\n\n    const onData = (data: string) => {\n      output += data;\n      process.stdout.write(data);\n    };\n    pty.onData(onData);\n\n    const onResize = () => {\n      const cols = process.stdout.columns || 120;\n      const rows = process.stdout.rows || 30;\n      try {\n        pty.resize(cols, rows);\n      } catch {\n        // Ignore resize failures.\n      }\n    };\n    process.stdout.on('resize', onResize);\n\n    pty.onExit(({ exitCode, signal }: { exitCode: number; signal: number }) => {\n      if (done) return;\n      done = true;\n      if (timer) clearTimeout(timer);\n      process.stdout.off('resize', onResize);\n      resolve({\n        success: exitCode === 0,\n        exitCode,\n        signal: signal ? String(signal) : null,\n        output\n      });\n    });\n  });\n}\n\nasync function runWithInherit(command: string, options: PtyRunOptions): Promise<PtyRunResult> {\n  return new Promise(resolve => {\n    const shell = options.shell || process.env.SHELL || '/bin/bash';\n    const child = spawnChild(shell, ['-lc', command], {\n      cwd: options.cwd || process.cwd(),\n      stdio: 'inherit'\n    });\n\n    const timeoutMs = options.timeoutMs || 0;\n    const timer = timeoutMs > 0\n      ? setTimeout(() => {\n          child.kill('SIGTERM');\n        }, timeoutMs)\n      : null;\n\n    child.on('close', (code, signal) => {\n      if (timer) clearTimeout(timer);\n      resolve({\n        success: (code ?? -1) === 0,\n        exitCode: code ?? -1,\n        signal: signal ?? null,\n        output: ''\n      });\n    });\n  });\n}\n", "import { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\n\ninterface TsSystem {\n  fileExists(path: string): boolean;\n  readFile(path: string): string | undefined;\n  readDirectory(...args: unknown[]): string[];\n  directoryExists(path: string): boolean;\n  getDirectories(path: string): string[];\n}\n\ninterface TsScriptSnapshot {\n  fromString(text: string): unknown;\n}\n\ninterface TsSourceFile {\n  fileName: string;\n  getLineAndCharacterOfPosition(pos: number): { line: number; character: number };\n}\n\ninterface TsProgram {\n  getSourceFile(fileName: string): TsSourceFile | undefined;\n}\n\ninterface TsLanguageService {\n  dispose(): void;\n  getCompletionsAtPosition(fileName: string, position: number, options: Record<string, unknown>): { entries?: Array<Record<string, unknown>> } | undefined;\n  getDefinitionAtPosition(fileName: string, position: number): Array<Record<string, unknown> & { fileName: string; textSpan: { start: number } }> | undefined;\n  getReferencesAtPosition(fileName: string, position: number): Array<Record<string, unknown> & { fileName: string; textSpan: { start: number } }> | undefined;\n  getNavigationTree(fileName: string): Record<string, unknown>;\n  getProgram(): TsProgram | undefined;\n}\n\ninterface TsApi {\n  sys: TsSystem;\n  ScriptSnapshot: TsScriptSnapshot;\n  findConfigFile(root: string, exists: (path: string) => boolean, configName: string): string | undefined;\n  readConfigFile(configPath: string, readFile: (path: string) => string | undefined): { error?: { messageText: unknown }; config: Record<string, unknown> };\n  flattenDiagnosticMessageText(messageText: unknown, newline: string): string;\n  parseJsonConfigFileContent(config: Record<string, unknown>, sys: TsSystem, basePath: string): {\n    errors: Array<{ messageText: unknown }>;\n    options: unknown;\n    fileNames: string[];\n  };\n  createCompilerHost(options: unknown, setParentNodes: boolean): unknown;\n  createProgram(fileNames: string[], options: unknown, host: unknown): unknown;\n  getPreEmitDiagnostics(program: unknown): Array<{\n    file?: TsSourceFile;\n    start?: number;\n    code: number;\n    category: number;\n    messageText: unknown;\n  }>;\n  getDefaultLibFilePath(options: unknown): string;\n  createLanguageService(serviceHost: Record<string, unknown>): TsLanguageService;\n}\n\n// Lazy-load typescript to avoid blocking ESM module init on Node 24+\n// (Node 24 ESM resolver can't resolve `import ts from 'typescript'` at top level)\nlet _ts: TsApi | undefined;\nasync function ensureTs(): Promise<TsApi> {\n  if (!_ts) {\n    _ts = await import('typescript').then((m: { default?: unknown }) => (m.default ?? m) as TsApi);\n  }\n  return _ts as TsApi;\n}\n\nexport interface LspDiagnostic {\n  file: string;\n  line: number;\n  column: number;\n  code: number;\n  category: 'error' | 'warning' | 'suggestion' | 'message';\n  message: string;\n}\n\nexport interface LspCompletion {\n  name: string;\n  kind: string;\n  sortText?: string;\n}\n\nexport interface LspLocation {\n  file: string;\n  line: number;\n  column: number;\n}\n\nexport interface LspSymbol {\n  name: string;\n  kind: string;\n  line: number;\n  column: number;\n}\n\ninterface LoadedProject {\n  root: string;\n  // CompilerOptions from the TypeScript API \u2014 typed as unknown because TypeScript is a dynamic import\n  options: unknown;\n  fileNames: string[];\n}\n\nfunction categoryToText(cat: number): LspDiagnostic['category'] {\n  // ts.DiagnosticCategory.Error = 1, Warning = 0, Suggestion = 2, Message = 3\n  if (cat === 1) return 'error';\n  if (cat === 0) return 'warning';\n  if (cat === 2) return 'suggestion';\n  return 'message';\n}\n\nfunction loadProject(projectDir: string, ts: TsApi): LoadedProject {\n  const root = resolve(projectDir);\n  const configPath = ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.json');\n  if (!configPath) {\n    throw new Error(`No tsconfig.json found at or above ${root}`);\n  }\n\n  const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n  if (configFile.error) {\n    throw new Error(ts.flattenDiagnosticMessageText(configFile.error.messageText, '\\n'));\n  }\n\n  const parsed = ts.parseJsonConfigFileContent(\n    configFile.config,\n    ts.sys,\n    dirname(configPath)\n  );\n  if (parsed.errors.length > 0) {\n    const first = parsed.errors[0];\n    throw new Error(ts.flattenDiagnosticMessageText(first.messageText, '\\n'));\n  }\n\n  return {\n    root,\n    options: parsed.options,\n    fileNames: parsed.fileNames\n  };\n}\n\nexport async function typeCheckProject(projectDir: string, includeFiles: string[] = []): Promise<LspDiagnostic[]> {\n  const ts = await ensureTs();\n  const project = loadProject(projectDir, ts);\n  const includeAbs = new Set(includeFiles.map(x => resolve(project.root, x)));\n  const shouldFilter = includeAbs.size > 0;\n  const host = ts.createCompilerHost(project.options, true);\n  const program = ts.createProgram(project.fileNames, project.options, host);\n\n  const diagnostics = ts.getPreEmitDiagnostics(program);\n  const out: LspDiagnostic[] = [];\n  for (const diagnostic of diagnostics) {\n    const sourceFile = diagnostic.file;\n    if (!sourceFile) continue;\n    const absFile = resolve(sourceFile.fileName);\n    if (shouldFilter && !includeAbs.has(absFile)) continue;\n    const { line, character } = sourceFile.getLineAndCharacterOfPosition(diagnostic.start ?? 0);\n    out.push({\n      file: absFile,\n      line: line + 1,\n      column: character + 1,\n      code: diagnostic.code,\n      category: categoryToText(diagnostic.category),\n      message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n')\n    });\n  }\n  return out;\n}\n\nfunction kindToText(kind: unknown): string {\n  return String(kind || 'unknown');\n}\n\nfunction createLanguageService(projectDir: string, ts: TsApi) {\n  const project = loadProject(projectDir, ts);\n  const sourceTexts = new Map<string, { version: number; text: string }>();\n  for (const file of project.fileNames) {\n    const text = ts.sys.readFile(file) || '';\n    sourceTexts.set(resolve(file), { version: 1, text });\n  }\n\n  const serviceHost = {\n    getCompilationSettings: () => project.options,\n    getScriptFileNames: () => Array.from(sourceTexts.keys()),\n    getScriptVersion: (fileName: string) => String(sourceTexts.get(resolve(fileName))?.version || 1),\n    getScriptSnapshot: (fileName: string) => {\n      const resolved = resolve(fileName);\n      const entry = sourceTexts.get(resolved);\n      if (!entry) return undefined;\n      return ts.ScriptSnapshot.fromString(entry.text);\n    },\n    getCurrentDirectory: () => project.root,\n    getDefaultLibFileName: (options: unknown) => (ts as { getDefaultLibFilePath(o: unknown): string }).getDefaultLibFilePath(options),\n    fileExists: ts.sys.fileExists,\n    readFile: ts.sys.readFile,\n    readDirectory: ts.sys.readDirectory,\n    directoryExists: ts.sys.directoryExists,\n    getDirectories: ts.sys.getDirectories\n  };\n\n  const service = ts.createLanguageService(serviceHost);\n  return { service, project, sourceTexts };\n}\n\nfunction lineColToPosition(text: string, line: number, column: number): number {\n  const lines = text.split('\\n');\n  const lineIndex = Math.max(0, line - 1);\n  const offset = lines.slice(0, lineIndex).reduce((sum: number, x: string) => sum + x.length + 1, 0) + Math.max(0, column - 1);\n  return Math.min(offset, text.length);\n}\n\nexport async function getCompletions(\n  projectDir: string,\n  filePath: string,\n  line: number,\n  column: number,\n  limit = 50,\n  prefix = ''\n): Promise<LspCompletion[]> {\n  const ts = await ensureTs();\n  const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n  try {\n    const absFile = resolve(project.root, filePath);\n    if (!existsSync(absFile)) {\n      throw new Error(`File not found: ${absFile}`);\n    }\n\n    if (!sourceTexts.has(absFile)) {\n      sourceTexts.set(absFile, { version: 1, text: ts.sys.readFile(absFile) || '' });\n    }\n\n    const fileText = sourceTexts.get(absFile)?.text || '';\n    const lines = fileText.split('\\n');\n    const lineIndex = Math.max(0, line - 1);\n    const safeLine = lines[lineIndex] || '';\n    const offset = lines.slice(0, lineIndex).reduce((sum: number, x: string) => sum + x.length + 1, 0) + Math.max(0, column - 1);\n    const position = Math.min(offset, fileText.length);\n\n    const completions = service.getCompletionsAtPosition(absFile, position, {\n      includeCompletionsWithInsertText: true,\n      includeCompletionsForModuleExports: true\n    });\n\n    const items = (completions?.entries || []).filter((entry: Record<string, unknown>) => {\n      if (!prefix) return true;\n      return String(entry.name || '').toLowerCase().startsWith(prefix.toLowerCase());\n    });\n\n    return items.slice(0, Math.max(1, limit)).map((entry: Record<string, unknown>) => ({\n      name: String(entry.name || ''),\n      kind: kindToText(entry.kind),\n      sortText: entry.sortText as string | undefined\n    }));\n  } finally {\n    service.dispose();\n  }\n}\n\nexport async function getDefinitions(projectDir: string, filePath: string, line: number, column: number): Promise<LspLocation[]> {\n  const ts = await ensureTs();\n  const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n  try {\n    const absFile = resolve(project.root, filePath);\n    const fileText = sourceTexts.get(absFile)?.text || ts.sys.readFile(absFile) || '';\n    const position = lineColToPosition(fileText, line, column);\n    const defs = service.getDefinitionAtPosition(absFile, position) || [];\n    return defs.map((def: Record<string, unknown> & { fileName: string; textSpan: { start: number } }) => {\n      const sf = service.getProgram()?.getSourceFile(def.fileName);\n      const lc = sf?.getLineAndCharacterOfPosition(def.textSpan.start) || { line: 0, character: 0 };\n      return {\n        file: resolve(def.fileName),\n        line: lc.line + 1,\n        column: lc.character + 1\n      };\n    });\n  } finally {\n    service.dispose();\n  }\n}\n\nexport async function getReferences(projectDir: string, filePath: string, line: number, column: number): Promise<LspLocation[]> {\n  const ts = await ensureTs();\n  const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n  try {\n    const absFile = resolve(project.root, filePath);\n    const fileText = sourceTexts.get(absFile)?.text || ts.sys.readFile(absFile) || '';\n    const position = lineColToPosition(fileText, line, column);\n    const refs = service.getReferencesAtPosition(absFile, position) || [];\n    return refs.map((ref: Record<string, unknown> & { fileName: string; textSpan: { start: number } }) => {\n      const sf = service.getProgram()?.getSourceFile(ref.fileName);\n      const lc = sf?.getLineAndCharacterOfPosition(ref.textSpan.start) || { line: 0, character: 0 };\n      return {\n        file: resolve(ref.fileName),\n        line: lc.line + 1,\n        column: lc.character + 1\n      };\n    });\n  } finally {\n    service.dispose();\n  }\n}\n\nexport async function getDocumentSymbols(projectDir: string, filePath: string): Promise<LspSymbol[]> {\n  const ts = await ensureTs();\n  const { service, project } = createLanguageService(projectDir, ts);\n  try {\n    const absFile = resolve(project.root, filePath);\n    const nav = service.getNavigationTree(absFile);\n    const out: LspSymbol[] = [];\n    const walk = (node: Record<string, unknown> & { spans?: Array<{ start: number }>; text?: string; kind?: unknown; childItems?: unknown[] }) => {\n      for (const span of node.spans || []) {\n        const sf = service.getProgram()?.getSourceFile(absFile);\n        const lc = sf?.getLineAndCharacterOfPosition(span.start) || { line: 0, character: 0 };\n        if (node.text && node.text !== '<global>') {\n          out.push({\n            name: node.text,\n            kind: String(node.kind || 'unknown'),\n            line: lc.line + 1,\n            column: lc.character + 1\n          });\n        }\n      }\n      for (const child of node.childItems || []) {\n        walk(child as Record<string, unknown> & { spans?: Array<{ start: number }>; text?: string; kind?: unknown; childItems?: unknown[] });\n      }\n    };\n    walk(nav);\n    return out;\n  } finally {\n    service.dispose();\n  }\n}\n", "import { createTwoFilesPatch } from 'diff';\nimport { readFile, writeFile, mkdir, access } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nexport interface SandboxChange {\n  path: string;\n  original: string;\n  modified: string;\n  timestamp: string;\n}\n\nexport interface SandboxState {\n  updatedAt: string;\n  activeBranch: string;\n  branches: Record<string, Record<string, SandboxChange>>;\n}\n\nexport class Sandbox {\n  protected state: SandboxState = {\n    updatedAt: new Date().toISOString(),\n    activeBranch: 'main',\n    branches: { main: {} }\n  };\n  protected baseDir: string;  // Changed from private to protected\n  private stateFilePath: string;\n\n  constructor(baseDir = process.cwd()) {\n    this.baseDir = baseDir;\n    this.stateFilePath = join(baseDir, '.crew', 'sandbox.json');\n  }\n\n  private async exists(path: string): Promise<boolean> {\n    try {\n      await access(path, constants.F_OK);\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  async load(): Promise<void> {\n    if (await this.exists(this.stateFilePath)) {\n      try {\n        const data = await readFile(this.stateFilePath, 'utf8');\n        const parsed = JSON.parse(data) as SandboxState;\n        this.state = {\n          ...this.state,\n          ...parsed,\n          branches: parsed.branches || { main: {} },\n          activeBranch: parsed.activeBranch || 'main'\n        };\n      } catch (err) {\n        console.error(`Failed to load sandbox state: ${(err as Error).message}`);\n      }\n    }\n  }\n\n  async persist(): Promise<void> {\n    this.state.updatedAt = new Date().toISOString();\n    const dir = dirname(this.stateFilePath);\n    if (!(await this.exists(dir))) {\n      await mkdir(dir, { recursive: true });\n    }\n    await writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2), 'utf8');\n  }\n\n  /** Alias for persist() to match external API expectations */\n  async save(): Promise<void> {\n    await this.persist();\n  }\n\n  async addChange(filePath: string, modifiedContent: string): Promise<void> {\n    const fullPath = join(this.baseDir, filePath);\n    let original = '';\n\n    // Ensure branch exists and is an object (not array)\n    if (!this.state.branches[this.state.activeBranch] || Array.isArray(this.state.branches[this.state.activeBranch])) {\n      // Fix malformed branch data silently\n      this.state.branches[this.state.activeBranch] = {};\n    }\n\n    const activeChanges = this.state.branches[this.state.activeBranch];\n\n    if (activeChanges[filePath]) {\n      original = activeChanges[filePath].original;\n    } else if (await this.exists(fullPath)) {\n      original = await readFile(fullPath, 'utf8');\n    }\n\n    activeChanges[filePath] = {\n      path: filePath,\n      original,\n      modified: modifiedContent,\n      timestamp: new Date().toISOString()\n    };\n    \n\n    await this.persist();\n  }\n\n  preview(branchName = this.state.activeBranch): string {\n    const branch = this.state.branches[branchName];\n    if (!branch) return `Branch \"${branchName}\" not found.`;\n\n    let diff = '';\n    for (const [path, change] of Object.entries(branch)) {\n      diff += createTwoFilesPatch(\n        `a/${path}`,\n        `b/${path}`,\n        change.original,\n        change.modified,\n        undefined,\n        undefined,\n        { context: 3 }\n      );\n    }\n    return diff || 'No pending changes.';\n  }\n\n  async apply(branchName = this.state.activeBranch): Promise<void> {\n    const branch = this.state.branches[branchName];\n    if (!branch) throw new Error(`Branch \"${branchName}\" not found.`);\n\n    for (const [path, change] of Object.entries(branch)) {\n      const fullPath = join(this.baseDir, path);\n      const dir = dirname(fullPath);\n      if (!(await this.exists(dir))) {\n        await mkdir(dir, { recursive: true });\n      }\n      await writeFile(fullPath, change.modified, 'utf8');\n    }\n    await this.rollback(branchName);\n  }\n\n  async rollback(branchName = this.state.activeBranch): Promise<void> {\n    if (this.state.branches[branchName]) {\n      this.state.branches[branchName] = {};\n      await this.persist();\n    }\n  }\n\n  async createBranch(name: string, fromBranch = this.state.activeBranch): Promise<void> {\n    if (this.state.branches[name]) {\n      throw new Error(`Branch \"${name}\" already exists.`);\n    }\n    // Deep copy current changes from fromBranch\n    const sourceBranch = this.state.branches[fromBranch] || {};\n    this.state.branches[name] = JSON.parse(JSON.stringify(sourceBranch));\n    this.state.activeBranch = name;\n    await this.persist();\n  }\n\n  async switchBranch(name: string): Promise<void> {\n    if (!this.state.branches[name]) {\n      throw new Error(`Branch \"${name}\" does not exist.`);\n    }\n    this.state.activeBranch = name;\n    await this.persist();\n  }\n\n  async deleteBranch(name: string): Promise<void> {\n    if (name === 'main') throw new Error('Cannot delete main branch.');\n    if (this.state.activeBranch === name) {\n      this.state.activeBranch = 'main';\n    }\n    delete this.state.branches[name];\n    await this.persist();\n  }\n\n  async mergeBranch(source: string, target = this.state.activeBranch): Promise<void> {\n    if (!this.state.branches[source]) throw new Error(`Source branch \"${source}\" not found.`);\n    if (!this.state.branches[target]) throw new Error(`Target branch \"${target}\" not found.`);\n\n    const sourceChanges = this.state.branches[source];\n    const targetChanges = this.state.branches[target];\n\n    for (const [path, change] of Object.entries(sourceChanges)) {\n      targetChanges[path] = JSON.parse(JSON.stringify(change));\n    }\n\n    await this.persist();\n  }\n\n  /** Expose state for read-only access by VirtualFS and similar utilities. */\n  getState(): SandboxState {\n    return this.state;\n  }\n\n  getBaseDir(): string {\n    return this.baseDir;\n  }\n\n  getActiveBranch(): string {\n    return this.state.activeBranch;\n  }\n\n  getBranches(): string[] {\n    return Object.keys(this.state.branches);\n  }\n\n  getPendingPaths(branchName = this.state.activeBranch): string[] {\n    return Object.keys(this.state.branches[branchName] || {});\n  }\n\n  hasChanges(branchName = this.state.activeBranch): boolean {\n    return Object.keys(this.state.branches[branchName] || {}).length > 0;\n  }\n\n  /**\n   * Get staged content for a file path (returns undefined if not staged).\n   * Used by tool adapter so agentic workers can read their own staged files.\n   */\n  getStagedContent(filePath: string, branchName = this.state.activeBranch): string | undefined {\n    const branch = this.state.branches[branchName];\n    if (!branch) return undefined;\n    // Try both the raw path and normalized path\n    const change = branch[filePath];\n    if (change) return change.modified;\n    return undefined;\n  }\n}\n", "import { applyPatch } from 'diff';\n\nexport interface EditStrategy {\n  name: string;\n  apply(original: string, change: string): string;\n}\n\nexport class WholeFileStrategy implements EditStrategy {\n  name = 'whole-file';\n  apply(original: string, change: string): string {\n    return change;\n  }\n}\n\n/**\n * Aider-style Search/Replace Blocks\n */\nexport class SearchReplaceStrategy implements EditStrategy {\n  name = 'search-replace';\n  \n  apply(originalContent: string, changePayload: string): string {\n    const lines = changePayload.split('\\n');\n    let currentContent = originalContent;\n    \n    let i = 0;\n    while (i < lines.length) {\n      if (lines[i].trim() === '<<<<<< SEARCH') {\n        const searchStart = i + 1;\n        let searchEnd = -1;\n        let replaceEnd = -1;\n        \n        for (let j = i + 1; j < lines.length; j++) {\n          if (lines[j].trim() === '======') {\n            searchEnd = j;\n          } else if (lines[j].trim() === '>>>>>> REPLACE') {\n            replaceEnd = j;\n            break;\n          }\n        }\n        \n        if (searchEnd !== -1 && replaceEnd !== -1) {\n          const searchBlock = lines.slice(searchStart, searchEnd).join('\\n');\n          const replaceBlock = lines.slice(searchEnd + 1, replaceEnd).join('\\n');\n          \n          if (searchBlock.trim() === '') {\n            // Append if search is empty (or handle at start)\n            currentContent += replaceBlock;\n          } else if (currentContent.includes(searchBlock)) {\n            currentContent = currentContent.replace(searchBlock, replaceBlock);\n          } else {\n            // Fallback: try fuzzy or just ignore?\n            // For now, throw to signal failure\n            throw new Error('Search block not found in content.');\n          }\n          i = replaceEnd + 1;\n        } else {\n          i++;\n        }\n      } else {\n        i++;\n      }\n    }\n    \n    return currentContent;\n  }\n}\n\n/**\n * Unified Diff format using 'diff' library\n */\nexport class UnifiedDiffStrategy implements EditStrategy {\n  name = 'unified-diff';\n  apply(original: string, diff: string): string {\n    const result = applyPatch(original, diff);\n    if (result === false) {\n      throw new Error('Failed to apply unified diff patch.');\n    }\n    return result;\n  }\n}\n\nexport function getStrategy(name: string): EditStrategy {\n  switch (name) {\n    case 'whole-file': return new WholeFileStrategy();\n    case 'search-replace': return new SearchReplaceStrategy();\n    case 'editblock': return new SearchReplaceStrategy(); // Alias\n    case 'unified-diff': return new UnifiedDiffStrategy();\n    default: return new WholeFileStrategy();\n  }\n}\n", "/**\n * Shared SSE streaming helpers for all LLM providers.\n * Extracts the common pattern from agentic-executor.ts so local.ts\n * and multi-turn-drivers.ts can stream without duplicating logic.\n */\n\nimport type { OpenAIUsage, AnthropicUsage, GeminiUsage } from '../types/common.js';\n\n/** Parse an SSE stream from an OpenAI-compatible API (OpenAI, Grok, DeepSeek, Groq, Mistral, Cerebras) */\nexport async function streamOpenAIResponse(\n  response: Response,\n  onText?: (chunk: string) => void\n): Promise<{ text: string; toolCalls: Array<{ name: string; arguments: string }>; usage?: OpenAIUsage | null; finishReason?: string }> {\n  if (!response.body) throw new Error('No response body for streaming');\n\n  const reader = response.body.getReader();\n  const decoder = new TextDecoder();\n  let buffer = '';\n  let fullText = '';\n  const toolCallAccumulator = new Map<number, { name: string; args: string }>();\n  let usage: OpenAIUsage | null = null;\n  let finishReason: string | undefined;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (!line.startsWith('data: ')) continue;\n        const jsonStr = line.slice(6).trim();\n        if (!jsonStr || jsonStr === '[DONE]') continue;\n\n        try {\n          const chunk = JSON.parse(jsonStr);\n          const choice = chunk?.choices?.[0];\n          const delta = choice?.delta;\n\n          // Capture finish_reason when present\n          if (choice?.finish_reason) finishReason = choice.finish_reason;\n\n          if (!delta) {\n            // Capture usage from final chunk\n            if (chunk?.usage) usage = chunk.usage;\n            continue;\n          }\n\n          if (delta.content) {\n            onText?.(delta.content);\n            fullText += delta.content;\n          }\n\n          if (delta.tool_calls) {\n            for (const tc of delta.tool_calls) {\n              const idx = tc.index ?? 0;\n              if (!toolCallAccumulator.has(idx)) {\n                toolCallAccumulator.set(idx, { name: '', args: '' });\n              }\n              const acc = toolCallAccumulator.get(idx)!;\n              if (tc.function?.name) acc.name = tc.function.name;\n              if (tc.function?.arguments) acc.args += tc.function.arguments;\n            }\n          }\n        } catch { /* skip malformed SSE lines */ }\n      }\n    }\n  } finally {\n    reader.releaseLock();\n  }\n\n  const toolCalls = [...toolCallAccumulator.values()]\n    .filter(tc => tc.name)\n    .map(tc => ({ name: tc.name, arguments: tc.args }));\n\n  return { text: fullText, toolCalls, usage, finishReason };\n}\n\n/** Parse an SSE stream from Anthropic's Messages API */\nexport async function streamAnthropicResponse(\n  response: Response,\n  onText?: (chunk: string) => void\n): Promise<{ text: string; toolCalls: Array<{ name: string; input: Record<string, unknown> }>; usage?: AnthropicUsage | null; stopReason?: string }> {\n  if (!response.body) throw new Error('No response body for streaming');\n\n  const reader = response.body.getReader();\n  const decoder = new TextDecoder();\n  let buffer = '';\n  let fullText = '';\n  const toolBlocks = new Map<number, { name: string; inputJson: string }>();\n  let usage: AnthropicUsage | null = null;\n  let stopReason: string | undefined;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (!line.startsWith('data: ')) continue;\n        const jsonStr = line.slice(6).trim();\n        if (!jsonStr) continue;\n\n        try {\n          const event = JSON.parse(jsonStr);\n\n          if (event.type === 'content_block_start' && event.content_block?.type === 'tool_use') {\n            toolBlocks.set(event.index, { name: event.content_block.name || '', inputJson: '' });\n          }\n\n          if (event.type === 'content_block_delta') {\n            if (event.delta?.type === 'text_delta' && event.delta.text) {\n              onText?.(event.delta.text);\n              fullText += event.delta.text;\n            }\n            if (event.delta?.type === 'input_json_delta' && event.delta.partial_json) {\n              const block = toolBlocks.get(event.index);\n              if (block) block.inputJson += event.delta.partial_json;\n            }\n          }\n\n          if (event.type === 'message_delta') {\n            if (event.usage) usage = event.usage;\n            // Capture stop_reason from message_delta (Anthropic streaming)\n            if (event.delta?.stop_reason) stopReason = event.delta.stop_reason;\n          }\n          if (event.type === 'message_start' && event.message?.usage) {\n            usage = { ...event.message.usage, ...(usage || {}) };\n          }\n        } catch { /* skip malformed events */ }\n      }\n    }\n  } finally {\n    reader.releaseLock();\n  }\n\n  const toolCalls = [...toolBlocks.values()]\n    .filter(b => b.name)\n    .map(b => {\n      let input = {};\n      try { input = JSON.parse(b.inputJson); } catch { /* partial JSON */ }\n      return { name: b.name, input };\n    });\n\n  return { text: fullText, toolCalls, usage, stopReason };\n}\n\n/** Parse an SSE stream from Gemini's streamGenerateContent endpoint */\nexport async function streamGeminiResponse(\n  response: Response,\n  onText?: (chunk: string) => void\n): Promise<{ text: string; toolCalls: Array<{ name: string; args: Record<string, unknown> }>; usage?: GeminiUsage | null }> {\n  if (!response.body) throw new Error('No response body for streaming');\n\n  const reader = response.body.getReader();\n  const decoder = new TextDecoder();\n  let buffer = '';\n  let fullText = '';\n  const toolCalls: Array<{ name: string; args: Record<string, unknown> }> = [];\n  let usage: GeminiUsage | null = null;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (!line.startsWith('data: ')) continue;\n        const jsonStr = line.slice(6).trim();\n        if (!jsonStr) continue;\n\n        try {\n          const chunk = JSON.parse(jsonStr);\n          const parts = chunk?.candidates?.[0]?.content?.parts ?? [];\n          for (const part of parts) {\n            if (part.text) {\n              onText?.(part.text);\n              fullText += part.text;\n            }\n            if (part.functionCall) {\n              toolCalls.push({ name: part.functionCall.name || '', args: part.functionCall.args || {} });\n            }\n          }\n          if (chunk?.usageMetadata) usage = chunk.usageMetadata;\n        } catch { /* skip malformed events */ }\n      }\n    }\n  } finally {\n    reader.releaseLock();\n  }\n\n  return { text: fullText, toolCalls, usage };\n}\n\n/** Default text handler: write to stdout */\nexport const writeToStdout = (chunk: string) => process.stdout.write(chunk);\n\n/** Check if streaming is disabled via env */\nexport function isStreamingDisabled(): boolean {\n  return String(process.env.CREW_NO_STREAM || '').toLowerCase() === 'true';\n}\n", "/**\n * OAuth Keychain Provider \u2014 reads Claude Max OAuth tokens from macOS Keychain.\n *\n * Claude Code stores OAuth credentials in macOS Keychain at service \"Claude Code-credentials\".\n * This module reads them and provides Bearer auth for the Anthropic API,\n * giving crew-cli free Claude Opus 4.6 on Max subscriptions.\n *\n * Token refresh is handled automatically when the token is within 5 min of expiry.\n */\n\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { userInfo } from 'node:os';\n\nconst execFileAsync = promisify(execFile);\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface OAuthTokens {\n  accessToken: string;\n  refreshToken: string | null;\n  expiresAt: number | null;\n  scopes: string[];\n  subscriptionType: string | null;   // \"max\", \"pro\", \"enterprise\", \"team\"\n  rateLimitTier: string | null;\n}\n\ninterface KeychainData {\n  claudeAiOauth?: OAuthTokens;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst KEYCHAIN_SERVICE = 'Claude Code-credentials';\nconst TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000; // Refresh 5 min before expiry\nconst CACHE_TTL_MS = 30_000; // Cache keychain reads for 30s\n\n// OAuth refresh endpoint (from Claude Code reference \u2014 constants/oauth.ts)\nconst TOKEN_URL = 'https://platform.claude.com/v1/oauth/token';\nconst CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e'; // Claude Code production client ID\n\n// ---------------------------------------------------------------------------\n// Cache\n// ---------------------------------------------------------------------------\n\nlet _cachedTokens: OAuthTokens | null = null;\nlet _cacheTimestamp = 0;\nlet _refreshInFlight: Promise<OAuthTokens | null> | null = null;\n\n// ---------------------------------------------------------------------------\n// Read from Keychain\n// ---------------------------------------------------------------------------\n\nasync function readFromKeychain(): Promise<OAuthTokens | null> {\n  // Only works on macOS\n  if (process.platform !== 'darwin') return null;\n\n  try {\n    // Try with actual username first, then \"unknown\" (Claude Code uses either)\n    let stdout = '';\n    const username = userInfo().username;\n    for (const acct of [username, 'unknown']) {\n      try {\n        const result = await execFileAsync('security', [\n          'find-generic-password',\n          '-a', acct,\n          '-s', KEYCHAIN_SERVICE,\n          '-w'\n        ], { timeout: 5000 });\n        const parsed = JSON.parse(result.stdout.trim() || '{}');\n        if (parsed.claudeAiOauth?.accessToken) {\n          stdout = result.stdout;\n          break;\n        }\n      } catch { /* try next account */ }\n    }\n    if (!stdout) {\n      // Last resort: no account filter\n      const result = await execFileAsync('security', [\n        'find-generic-password',\n        '-s', KEYCHAIN_SERVICE,\n        '-w'\n      ], { timeout: 5000 });\n      stdout = result.stdout;\n    }\n\n    const raw = stdout.trim();\n    if (!raw) return null;\n\n    // Keychain value might be hex-encoded or raw JSON\n    let jsonStr: string;\n    if (raw.startsWith('{')) {\n      jsonStr = raw;\n    } else {\n      // Try hex decode\n      jsonStr = Buffer.from(raw, 'hex').toString('utf8');\n    }\n\n    const data: KeychainData = JSON.parse(jsonStr);\n    const oauth = data.claudeAiOauth;\n    if (!oauth?.accessToken) return null;\n\n    return oauth;\n  } catch {\n    // Keychain not available, locked, or entry missing\n    return null;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Token Refresh\n// ---------------------------------------------------------------------------\n\nasync function refreshToken(currentTokens: OAuthTokens): Promise<OAuthTokens | null> {\n  if (!currentTokens.refreshToken) return null;\n\n  try {\n    const response = await fetch(TOKEN_URL, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify({\n        grant_type: 'refresh_token',\n        refresh_token: currentTokens.refreshToken,\n        client_id: CLIENT_ID\n      }),\n      signal: AbortSignal.timeout(10000)\n    });\n\n    if (!response.ok) {\n      const errText = await response.text().catch(() => '');\n      console.error(`[OAuth] Token refresh failed: ${response.status} ${errText.slice(0, 200)}`);\n      return null;\n    }\n\n    const data = await response.json() as { access_token?: string; refresh_token?: string; expires_in?: number; scope?: string };\n    if (!data.access_token) return null;\n\n    const refreshed: OAuthTokens = {\n      accessToken: data.access_token,\n      refreshToken: data.refresh_token || currentTokens.refreshToken,\n      expiresAt: data.expires_in ? Date.now() + data.expires_in * 1000 : null,\n      scopes: data.scope ? data.scope.split(' ') : currentTokens.scopes,\n      subscriptionType: currentTokens.subscriptionType,\n      rateLimitTier: currentTokens.rateLimitTier\n    };\n\n    // Do NOT write back to keychain \u2014 let Claude Code manage its own tokens.\n    // Writing back could corrupt the keychain entry (missing mcpOAuth, etc.).\n\n    return refreshed;\n  } catch (err) {\n    console.error(`[OAuth] Token refresh error: ${(err as Error).message}`);\n    return null;\n  }\n}\n\nasync function writeToKeychain(tokens: OAuthTokens): Promise<void> {\n  if (process.platform !== 'darwin') return;\n\n  try {\n    const username = userInfo().username;\n    const data: KeychainData = { claudeAiOauth: tokens };\n    const jsonStr = JSON.stringify(data);\n\n    // Delete old entry first (security doesn't support update-in-place)\n    await execFileAsync('security', [\n      'delete-generic-password',\n      '-a', username,\n      '-s', KEYCHAIN_SERVICE\n    ]).catch(() => {}); // Ignore if doesn't exist\n\n    await execFileAsync('security', [\n      'add-generic-password',\n      '-a', username,\n      '-s', KEYCHAIN_SERVICE,\n      '-w', jsonStr,\n      '-U' // Update if exists\n    ], { timeout: 5000 });\n  } catch {\n    // Best-effort \u2014 don't break if keychain write fails\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nfunction isTokenExpired(tokens: OAuthTokens): boolean {\n  if (!tokens.expiresAt) return false; // No expiry info = assume valid\n  return Date.now() >= tokens.expiresAt - TOKEN_EXPIRY_BUFFER_MS;\n}\n\n/**\n * Get a valid OAuth access token from macOS Keychain.\n * Returns null if unavailable, expired and unrefreshable, or not on macOS.\n *\n * Caches reads for 30s and deduplicates concurrent refresh attempts.\n */\nexport async function getOAuthToken(): Promise<OAuthTokens | null> {\n  // Check cache first\n  if (_cachedTokens && Date.now() - _cacheTimestamp < CACHE_TTL_MS) {\n    if (!isTokenExpired(_cachedTokens)) return _cachedTokens;\n  }\n\n  // Read from keychain\n  let tokens = await readFromKeychain();\n  if (!tokens) return null;\n\n  // Check if refresh needed\n  if (isTokenExpired(tokens)) {\n    // Deduplicate concurrent refresh attempts\n    if (!_refreshInFlight) {\n      _refreshInFlight = refreshToken(tokens).finally(() => { _refreshInFlight = null; });\n    }\n    const refreshed = await _refreshInFlight;\n    if (refreshed) {\n      tokens = refreshed;\n    } else {\n      // Refresh failed \u2014 use existing token anyway (might still work)\n    }\n  }\n\n  // Cache\n  _cachedTokens = tokens;\n  _cacheTimestamp = Date.now();\n  return tokens;\n}\n\n/**\n * Force re-read from keychain (ignoring cache).\n * Useful after a 401 to check if another process refreshed the token.\n */\nexport async function forceRefreshOAuthToken(): Promise<OAuthTokens | null> {\n  _cachedTokens = null;\n  _cacheTimestamp = 0;\n\n  const tokens = await readFromKeychain();\n  if (!tokens) return null;\n\n  // Force refresh even if not expired\n  if (tokens.refreshToken) {\n    if (!_refreshInFlight) {\n      _refreshInFlight = refreshToken(tokens).finally(() => { _refreshInFlight = null; });\n    }\n    const refreshed = await _refreshInFlight;\n    if (refreshed) {\n      _cachedTokens = refreshed;\n      _cacheTimestamp = Date.now();\n      return refreshed;\n    }\n  }\n\n  _cachedTokens = tokens;\n  _cacheTimestamp = Date.now();\n  return tokens;\n}\n\n/**\n * Check if OAuth keychain tokens are available (quick check, no refresh).\n */\nexport async function hasOAuthTokens(): Promise<boolean> {\n  const tokens = await getOAuthToken();\n  return tokens !== null;\n}\n", "/**\n * OpenAI OAuth Provider \u2014 reads Codex CLI OAuth tokens for ChatGPT Plus/Pro/Max.\n *\n * OpenAI Codex CLI stores OAuth credentials in ~/.codex/auth.json or\n * ~/.local/share/opencode/auth.json. This module reads them and provides\n * Bearer auth for the Codex backend API (chatgpt.com/backend-api/codex/responses),\n * giving crew-cli free GPT-5.x access on ChatGPT subscriptions.\n *\n * Token refresh is handled automatically when the token is within 5 min of expiry.\n */\n\nimport { readFile, access } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface OpenAIOAuthTokens {\n  accessToken: string;\n  refreshToken: string | null;\n  expiresAt: number | null;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000; // Refresh 5 min before expiry\nconst CACHE_TTL_MS = 30_000; // Cache reads for 30s\n\n// OpenAI Codex public client ID (same as Codex CLI)\nconst CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';\nconst TOKEN_URL = 'https://auth.openai.com/oauth/token';\n\n// The Codex backend API \u2014 uses ChatGPT subscription billing, not API credits\nexport const OPENAI_CODEX_API_URL = 'https://chatgpt.com/backend-api/codex/responses';\n\n// Possible token file locations (Codex CLI, OpenCode, openai-oauth)\nconst TOKEN_PATHS = [\n  join(homedir(), '.codex', 'auth.json'),\n  join(homedir(), '.local', 'share', 'opencode', 'auth.json'),\n  join(homedir(), '.codex-auth', 'auth.json'),\n];\n\n// ---------------------------------------------------------------------------\n// Cache\n// ---------------------------------------------------------------------------\n\nlet _cachedTokens: OpenAIOAuthTokens | null = null;\nlet _cacheTimestamp = 0;\nlet _refreshInFlight: Promise<OpenAIOAuthTokens | null> | null = null;\n\n// ---------------------------------------------------------------------------\n// Read from disk\n// ---------------------------------------------------------------------------\n\nasync function fileExists(path: string): Promise<boolean> {\n  try {\n    await access(path, constants.F_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nasync function readTokenFile(): Promise<OpenAIOAuthTokens | null> {\n  for (const tokenPath of TOKEN_PATHS) {\n    if (!(await fileExists(tokenPath))) continue;\n\n    try {\n      const raw = await readFile(tokenPath, 'utf8');\n      const data = JSON.parse(raw);\n\n      // Format 1: { \"openai-codex\": { type: \"oauth\", access, refresh, expires } }\n      const codexEntry = data['openai-codex'] || data['codex'] || data['openai'];\n      if (codexEntry?.access) {\n        return {\n          accessToken: codexEntry.access,\n          refreshToken: codexEntry.refresh || null,\n          expiresAt: codexEntry.expires || null,\n        };\n      }\n\n      // Format 1b: nested auth object used by some Codex/OpenCode builds\n      const nestedAuth = data.auth || data.oauth || data.credentials;\n      if (nestedAuth?.accessToken || nestedAuth?.access_token || nestedAuth?.access) {\n        return {\n          accessToken: nestedAuth.accessToken || nestedAuth.access_token || nestedAuth.access,\n          refreshToken: nestedAuth.refreshToken || nestedAuth.refresh_token || nestedAuth.refresh || null,\n          expiresAt: nestedAuth.expiresAt || nestedAuth.expires_at || nestedAuth.expires || null,\n        };\n      }\n\n      // Format 2: flat { access_token, refresh_token, expires_at }\n      if (data.access_token) {\n        return {\n          accessToken: data.access_token,\n          refreshToken: data.refresh_token || null,\n          expiresAt: data.expires_at || data.expires || null,\n        };\n      }\n\n      // Format 3: { token: \"...\" } (simple bearer token)\n      if (data.token) {\n        return {\n          accessToken: data.token,\n          refreshToken: data.refresh_token || null,\n          expiresAt: data.expires_at || null,\n        };\n      }\n\n      // Format 4: Codex CLI chatgpt mode \u2014 { auth_mode: \"chatgpt\", tokens: { access_token, refresh_token, ... } }\n      if (data.tokens?.access_token) {\n        return {\n          accessToken: data.tokens.access_token,\n          refreshToken: data.tokens.refresh_token || null,\n          expiresAt: data.tokens.expires_at || data.last_refresh ? (data.last_refresh + 3600 * 1000) : null,\n        };\n      }\n    } catch {\n      // Parse error \u2014 try next path\n      continue;\n    }\n  }\n\n  return null;\n}\n\n// ---------------------------------------------------------------------------\n// Token Refresh\n// ---------------------------------------------------------------------------\n\nasync function refreshToken(current: OpenAIOAuthTokens): Promise<OpenAIOAuthTokens | null> {\n  if (!current.refreshToken) return null;\n\n  try {\n    const response = await fetch(TOKEN_URL, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n      body: new URLSearchParams({\n        grant_type: 'refresh_token',\n        refresh_token: current.refreshToken,\n        client_id: CLIENT_ID,\n      }).toString(),\n      signal: AbortSignal.timeout(10000),\n    });\n\n    if (!response.ok) {\n      const errText = await response.text().catch(() => '');\n      console.error(`[OpenAI OAuth] Token refresh failed: ${response.status} ${errText.slice(0, 200)}`);\n      return null;\n    }\n\n    const data = await response.json() as { access_token?: string; refresh_token?: string; expires_in?: number };\n    if (!data.access_token) return null;\n\n    return {\n      accessToken: data.access_token,\n      refreshToken: data.refresh_token || current.refreshToken,\n      expiresAt: data.expires_in ? Date.now() + data.expires_in * 1000 : null,\n    };\n  } catch (err) {\n    console.error(`[OpenAI OAuth] Token refresh error: ${(err as Error).message}`);\n    return null;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nfunction isTokenExpired(tokens: OpenAIOAuthTokens): boolean {\n  if (!tokens.expiresAt) return false;\n  return Date.now() >= tokens.expiresAt - TOKEN_EXPIRY_BUFFER_MS;\n}\n\n/**\n * Get a valid OpenAI OAuth access token from Codex CLI auth files.\n * Returns null if unavailable or expired and unrefreshable.\n *\n * Caches reads for 30s and deduplicates concurrent refresh attempts.\n */\nexport async function getOpenAIOAuthToken(): Promise<OpenAIOAuthTokens | null> {\n  // Check cache first\n  if (_cachedTokens && Date.now() - _cacheTimestamp < CACHE_TTL_MS) {\n    if (!isTokenExpired(_cachedTokens)) return _cachedTokens;\n  }\n\n  let tokens = await readTokenFile();\n  if (!tokens) return null;\n\n  // Check if refresh needed\n  if (isTokenExpired(tokens)) {\n    if (!_refreshInFlight) {\n      _refreshInFlight = refreshToken(tokens).finally(() => { _refreshInFlight = null; });\n    }\n    const refreshed = await _refreshInFlight;\n    if (refreshed) {\n      tokens = refreshed;\n    }\n    // If refresh failed, use existing token \u2014 might still work\n  }\n\n  _cachedTokens = tokens;\n  _cacheTimestamp = Date.now();\n  return tokens;\n}\n\n/**\n * Force re-read and refresh (ignoring cache).\n * Useful after a 401 to check if another process refreshed the token.\n */\nexport async function forceRefreshOpenAIOAuth(): Promise<OpenAIOAuthTokens | null> {\n  _cachedTokens = null;\n  _cacheTimestamp = 0;\n\n  const tokens = await readTokenFile();\n  if (!tokens) return null;\n\n  if (tokens.refreshToken) {\n    if (!_refreshInFlight) {\n      _refreshInFlight = refreshToken(tokens).finally(() => { _refreshInFlight = null; });\n    }\n    const refreshed = await _refreshInFlight;\n    if (refreshed) {\n      _cachedTokens = refreshed;\n      _cacheTimestamp = Date.now();\n      return refreshed;\n    }\n  }\n\n  _cachedTokens = tokens;\n  _cacheTimestamp = Date.now();\n  return tokens;\n}\n\n/**\n * Quick check for OpenAI OAuth availability.\n */\nexport async function hasOpenAIOAuthTokens(): Promise<boolean> {\n  const tokens = await getOpenAIOAuthToken();\n  return tokens !== null;\n}\n", "/**\n * Gemini OAuth Provider \u2014 reads Google ADC or Gemini CLI OAuth tokens.\n *\n * Supports two token sources:\n * 1. Google ADC (~/.config/gcloud/application_default_credentials.json)\n *    \u2014 from `gcloud auth application-default login`\n * 2. Gemini CLI OAuth (~/.gemini/oauth_creds.json)\n *    \u2014 from Gemini CLI browser login\n *\n * Uses Bearer auth with generativelanguage.googleapis.com instead of ?key= param.\n * Token refresh is handled automatically when within 5 min of expiry.\n */\n\nimport { readFile, access } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface GeminiOAuthTokens {\n  accessToken: string;\n  refreshToken: string | null;\n  expiresAt: number | null;\n  clientId: string | null;\n  clientSecret: string | null;\n  projectId: string | null;\n  source: 'adc' | 'gemini-cli';\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;\nconst CACHE_TTL_MS = 30_000;\n\n// Google OAuth token endpoint\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token';\n\n// Gemini CLI's OAuth client credentials (public, safe to embed per Google docs)\nconst GEMINI_CLI_CLIENT_ID = '681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com';\nconst GEMINI_CLI_CLIENT_SECRET = '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';\n\n// Token file locations\nconst ADC_PATH = join(homedir(), '.config', 'gcloud', 'application_default_credentials.json');\nconst GEMINI_CLI_PATH = join(homedir(), '.gemini', 'oauth_creds.json');\n\n// ---------------------------------------------------------------------------\n// Cache\n// ---------------------------------------------------------------------------\n\nlet _cachedTokens: GeminiOAuthTokens | null = null;\nlet _cacheTimestamp = 0;\nlet _refreshInFlight: Promise<GeminiOAuthTokens | null> | null = null;\n\n// ---------------------------------------------------------------------------\n// Read from disk\n// ---------------------------------------------------------------------------\n\nasync function fileExists(path: string): Promise<boolean> {\n  try {\n    await access(path, constants.F_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nasync function resolveGoogleProjectId(): Promise<string | null> {\n  const envProject = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT || process.env.ANTHROPIC_VERTEX_PROJECT_ID;\n  if (envProject) return envProject;\n\n  if (await fileExists(ADC_PATH)) {\n    try {\n      const raw = await readFile(ADC_PATH, 'utf8');\n      const data = JSON.parse(raw);\n      return data.quota_project_id || data.project_id || null;\n    } catch {\n      // Ignore malformed ADC files and fall back to null.\n    }\n  }\n\n  return null;\n}\n\nasync function readTokenFiles(): Promise<GeminiOAuthTokens | null> {\n  const projectId = await resolveGoogleProjectId();\n  const preference = String(process.env.CREW_GEMINI_OAUTH_SOURCE || 'auto').trim().toLowerCase();\n  const orderedSources =\n    preference === 'gemini-cli'\n      ? ['gemini-cli', 'adc']\n    : preference === 'adc'\n        ? ['adc', 'gemini-cli']\n        : ['gemini-cli', 'adc'];\n\n  for (const source of orderedSources) {\n    if (source === 'adc' && await fileExists(ADC_PATH)) {\n      try {\n        const raw = await readFile(ADC_PATH, 'utf8');\n        const data = JSON.parse(raw);\n\n        // ADC files contain client_id, client_secret, refresh_token (no access_token)\n        if (data.refresh_token && data.client_id) {\n          const refreshed = await exchangeRefreshToken(\n            data.refresh_token,\n            data.client_id,\n            data.client_secret\n          );\n          if (refreshed) {\n            return {\n              ...refreshed,\n              clientId: data.client_id,\n              clientSecret: data.client_secret,\n              projectId: data.quota_project_id || data.project_id || projectId,\n              source: 'adc',\n            };\n          }\n        }\n\n        if (data.access_token) {\n          return {\n            accessToken: data.access_token,\n            refreshToken: data.refresh_token || null,\n            expiresAt: null,\n            clientId: data.client_id || null,\n            clientSecret: data.client_secret || null,\n            projectId: data.quota_project_id || data.project_id || projectId,\n            source: 'adc',\n          };\n        }\n      } catch {\n        // Parse error \u2014 try next source\n      }\n    }\n\n    if (source === 'gemini-cli' && await fileExists(GEMINI_CLI_PATH)) {\n      try {\n        const raw = await readFile(GEMINI_CLI_PATH, 'utf8');\n        const data = JSON.parse(raw);\n        if (data.refresh_token) {\n          const refreshed = await exchangeRefreshToken(\n            data.refresh_token,\n            GEMINI_CLI_CLIENT_ID,\n            GEMINI_CLI_CLIENT_SECRET\n          );\n          if (refreshed) {\n            return {\n              ...refreshed,\n              clientId: GEMINI_CLI_CLIENT_ID,\n              clientSecret: GEMINI_CLI_CLIENT_SECRET,\n              projectId,\n              source: 'gemini-cli',\n            };\n          }\n        }\n        if (data.access_token) {\n          return {\n            accessToken: data.access_token,\n            refreshToken: data.refresh_token || null,\n            expiresAt: data.expiry_date || null,\n            clientId: GEMINI_CLI_CLIENT_ID,\n            clientSecret: GEMINI_CLI_CLIENT_SECRET,\n            projectId,\n            source: 'gemini-cli',\n          };\n        }\n      } catch {\n        // Parse error \u2014 try next source\n      }\n    }\n  }\n\n  return null;\n}\n\n// ---------------------------------------------------------------------------\n// Token Refresh\n// ---------------------------------------------------------------------------\n\nasync function exchangeRefreshToken(\n  refreshToken: string,\n  clientId: string,\n  clientSecret: string\n): Promise<{ accessToken: string; refreshToken: string | null; expiresAt: number | null } | null> {\n  try {\n    const response = await fetch(TOKEN_URL, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n      body: new URLSearchParams({\n        grant_type: 'refresh_token',\n        refresh_token: refreshToken,\n        client_id: clientId,\n        client_secret: clientSecret,\n      }).toString(),\n      signal: AbortSignal.timeout(10000),\n    });\n\n    if (!response.ok) {\n      const errText = await response.text().catch(() => '');\n      console.error(`[Gemini OAuth] Token refresh failed: ${response.status} ${errText.slice(0, 200)}`);\n      return null;\n    }\n\n    const data = await response.json() as { access_token?: string; refresh_token?: string; expires_in?: number };\n    if (!data.access_token) return null;\n\n    return {\n      accessToken: data.access_token,\n      refreshToken: data.refresh_token || refreshToken,\n      expiresAt: data.expires_in ? Date.now() + data.expires_in * 1000 : null,\n    };\n  } catch (err) {\n    console.error(`[Gemini OAuth] Token exchange error: ${(err as Error).message}`);\n    return null;\n  }\n}\n\nasync function refreshTokens(current: GeminiOAuthTokens): Promise<GeminiOAuthTokens | null> {\n  if (!current.refreshToken) return null;\n\n  const clientId = current.clientId || GEMINI_CLI_CLIENT_ID;\n  const clientSecret = current.clientSecret || GEMINI_CLI_CLIENT_SECRET;\n\n  const result = await exchangeRefreshToken(current.refreshToken, clientId, clientSecret);\n  if (!result) return null;\n\n  return {\n    ...result,\n    clientId,\n    clientSecret,\n    projectId: current.projectId || null,\n    source: current.source,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nfunction isTokenExpired(tokens: GeminiOAuthTokens): boolean {\n  if (!tokens.expiresAt) return false;\n  return Date.now() >= tokens.expiresAt - TOKEN_EXPIRY_BUFFER_MS;\n}\n\n/**\n * Get a valid Gemini OAuth access token from ADC or Gemini CLI creds.\n * Returns null if unavailable or expired and unrefreshable.\n *\n * Caches reads for 30s and deduplicates concurrent refresh attempts.\n */\nexport async function getGeminiOAuthToken(): Promise<GeminiOAuthTokens | null> {\n  // Check cache first\n  if (_cachedTokens && Date.now() - _cacheTimestamp < CACHE_TTL_MS) {\n    if (!isTokenExpired(_cachedTokens)) return _cachedTokens;\n  }\n\n  let tokens = await readTokenFiles();\n  if (!tokens) return null;\n\n  // Check if refresh needed\n  if (isTokenExpired(tokens)) {\n    if (!_refreshInFlight) {\n      _refreshInFlight = refreshTokens(tokens).finally(() => { _refreshInFlight = null; });\n    }\n    const refreshed = await _refreshInFlight;\n    if (refreshed) {\n      tokens = refreshed;\n    }\n  }\n\n  _cachedTokens = tokens;\n  _cacheTimestamp = Date.now();\n  return tokens;\n}\n\n/**\n * Force re-read and refresh (ignoring cache).\n * Useful after a 401 to retry with a fresh token.\n */\nexport async function forceRefreshGeminiOAuth(): Promise<GeminiOAuthTokens | null> {\n  _cachedTokens = null;\n  _cacheTimestamp = 0;\n\n  const tokens = await readTokenFiles();\n  if (!tokens) return null;\n\n  if (tokens.refreshToken) {\n    if (!_refreshInFlight) {\n      _refreshInFlight = refreshTokens(tokens).finally(() => { _refreshInFlight = null; });\n    }\n    const refreshed = await _refreshInFlight;\n    if (refreshed) {\n      _cachedTokens = refreshed;\n      _cacheTimestamp = Date.now();\n      return refreshed;\n    }\n  }\n\n  _cachedTokens = tokens;\n  _cacheTimestamp = Date.now();\n  return tokens;\n}\n\n/**\n * Quick check for Gemini OAuth availability.\n */\nexport async function hasGeminiOAuthTokens(): Promise<boolean> {\n  const tokens = await getGeminiOAuthToken();\n  return tokens !== null;\n}\n", "import { createHash } from 'node:crypto';\nimport xxhash from 'xxhash-wasm';\n\nconst CCH_SEED = BigInt('0x6E52736AC806831E');\nconst VERSION = '2.1.87';\nconst SALT = '59cf53e54c78';\n\nlet _h64: ((input: string, seed?: bigint) => bigint) | null = null;\n\nasync function getHasher() {\n  if (!_h64) {\n    const wasm = await xxhash();\n    _h64 = wasm.h64;\n  }\n  return _h64;\n}\n\n/** Compute 3-char version suffix from the first user message content */\nexport function computeVersionSuffix(firstUserMessage: string): string {\n  const msg = firstUserMessage || '';\n  const chars = [4, 7, 20].map(i => (i < msg.length ? msg[i] : '0')).join('');\n  return createHash('sha256')\n    .update(`${SALT}${chars}${VERSION}`)\n    .digest('hex')\n    .slice(0, 3);\n}\n\n/** Compute cch hash over the full body string (which must contain cch=00000 placeholder) */\nexport async function computeCch(bodyWithPlaceholder: string): Promise<string> {\n  const h64 = await getHasher();\n  const hash = h64(bodyWithPlaceholder, CCH_SEED);\n  return Number(hash & BigInt(0xfffff)).toString(16).padStart(5, '0');\n}\n\n/**\n * Build the billing system block that goes as the FIRST element of the system array.\n * cch=00000 is the placeholder \u2014 must be replaced after hashing the full body.\n */\nexport function buildBillingBlock(suffix: string): { type: 'text'; text: string } {\n  return {\n    type: 'text',\n    text: `x-anthropic-billing-header: cc_version=${VERSION}.${suffix}; cc_entrypoint=cli; cch=00000;`,\n  };\n}\n\n/**\n * Given a body object (with cch=00000 placeholder in system[0]),\n * serialize it with system before messages, compute CCH, replace placeholder.\n * Returns the final body string ready to send.\n */\nexport async function signBody(bodyObj: Record<string, unknown>): Promise<string> {\n  // Ensure system is serialized before messages (key order matters for hash)\n  const { system, messages, ...rest } = bodyObj as { system?: unknown; messages?: unknown; [key: string]: unknown };\n  const ordered = { ...rest, ...(system !== undefined ? { system } : {}), ...(messages !== undefined ? { messages } : {}) };\n  const bodyStr = JSON.stringify(ordered, null, 0);\n  const cch = await computeCch(bodyStr);\n  return bodyStr.replace('cch=00000', `cch=${cch}`);\n}\n", "// @ts-nocheck\n/**\n * Local LLM executor - runs tasks without gateway dependency\n * This is the standalone Tier 2 executor that handles tasks directly\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { Logger } from '../utils/logger.js';\nimport { streamOpenAIResponse, streamAnthropicResponse, streamGeminiResponse, writeToStdout, isStreamingDisabled } from './stream-helpers.js';\nimport { getOAuthToken, forceRefreshOAuthToken } from '../auth/oauth-keychain.js';\nimport { getOpenAIOAuthToken, forceRefreshOpenAIOAuth, OPENAI_CODEX_API_URL } from '../auth/openai-oauth.js';\nimport { getGeminiOAuthToken, forceRefreshGeminiOAuth } from '../auth/gemini-oauth.js';\nimport { computeVersionSuffix, buildBillingBlock, signBody } from '../auth/cch.js';\n\nexport interface ExecutorOptions {\n  model?: string;\n  explicitModel?: boolean;\n  temperature?: number;\n  maxTokens?: number;\n  systemPrompt?: string;  // Override default executor prompt with specialized persona\n  jsonMode?: boolean;  // Force JSON response mode (for routing/planning only)\n  sessionId?: string;  // Session ID for cache coherence (Grok, Anthropic)\n}\n\nexport interface ExecutorResult {\n  success: boolean;\n  result: string;\n  model: string;\n  providerId?: string;\n  attemptedProviders?: string[];\n  providerFailures?: string[];\n  promptTokens?: number;\n  completionTokens?: number;\n  cachedTokens?: number;  // Cache hit tokens (Grok, OpenAI, Anthropic)\n  costUsd?: number;\n}\n\ninterface ProviderAuth {\n  token: string;\n  isOAuth: boolean;\n  apiUrl?: string;\n  projectId?: string;\n  oauthSource?: string;\n}\n\ninterface OpenAIChatResponse {\n  choices?: Array<{\n    message?: {\n      content?: string;\n      reasoning_content?: string;\n    };\n  }>;\n  usage?: {\n    prompt_tokens?: number;\n    completion_tokens?: number;\n    prompt_tokens_details?: {\n      cached_tokens?: number;\n    };\n  };\n}\n\ninterface GeminiContentResponse {\n  candidates?: Array<{\n    content?: {\n      parts?: Array<{ text?: string }>;\n    };\n  }>;\n  usageMetadata?: {\n    promptTokenCount?: number;\n    candidatesTokenCount?: number;\n  };\n}\n\ninterface GeminiCodeAssistLoadResponse {\n  cloudaicompanionProject?: string;\n}\n\ninterface GeminiCodeAssistGenerateResponse {\n  response?: {\n    candidates?: Array<{\n      content?: {\n        parts?: Array<Record<string, unknown>>;\n      };\n    }>;\n    usageMetadata?: {\n      promptTokenCount?: number;\n      candidatesTokenCount?: number;\n    };\n  };\n}\n\ninterface AnthropicMessageResponse {\n  content?: Array<{ type?: string; text?: string }>;\n  usage?: {\n    input_tokens?: number;\n    output_tokens?: number;\n    cache_creation_input_tokens?: number;\n    cache_read_input_tokens?: number;\n  };\n}\n\nconst CLAUDE_OAUTH_BETA_HEADER = [\n  'claude-code-20250219',\n  'oauth-2025-04-20',\n  'adaptive-thinking-2026-01-28',\n  'research-preview-2026-02-01',\n  'interleaved-thinking-2025-05-14',\n  'redact-thinking-2026-02-12',\n  'context-management-2025-06-27',\n].join(',');\n\nconst EXECUTOR_SYSTEM_PROMPT = `You are the conversational interface for crewswarm CLI.\n\n## Your Role\n- Handle user interaction, clarifications, and responses\n- Lead with the answer, not the reasoning. Skip preamble and filler.\n- Keep it concise and actionable - under 2000 chars\n- Match crew-lead's personality: sharp, direct, no filler\n\n## Personality\n- Be concise and sharp - no fluff\n- When the user is direct, match their energy\n- Research well, build anything, never make excuses\n\n## Technical Capabilities\nYou can:\n- Answer technical questions clearly\n- Write, edit, and explain code\n- Provide step-by-step guidance\n- Make architectural recommendations\n\n## Principles\n- Read before acting: never claim what a file contains without reading it first.\n- Match the request: do what was asked, don't over-scope or over-engineer.\n- Own mistakes: if wrong, say so briefly and fix it. Don't repeat failing approaches.\n- Never fabricate file contents, command output, or tool results.\n\nBe concise, accurate, and helpful. Format code in markdown blocks.`;\n\n\nexport class LocalExecutor {\n  private logger = new Logger();\n  private readonly timeoutMs = this.getTimeoutMs();\n\n  private hasExplicitModelOverride(options: ExecutorOptions): boolean {\n    return options.explicitModel === true;\n  }\n\n  private async getConfiguredProviderOrder(): Promise<string[]> {\n    const envOrder = String(process.env.CREW_EXECUTION_PROVIDER_ORDER || \"\")\n      .split(\",\")\n      .map((value) => value.trim().toLowerCase())\n      .filter(Boolean);\n    const baseOrder = envOrder.length > 0\n      ? envOrder\n      : [\"openai\", \"anthropic\", \"gemini\", \"deepseek\", \"groq\", \"grok\"];\n\n    const resolved: string[] = [];\n    for (const provider of baseOrder) {\n      if (await this.resolveProviderAuth(provider)) {\n        resolved.push(provider);\n      }\n    }\n    return resolved;\n  }\n\n  private async resolveProviderAuth(provider: string): Promise<ProviderAuth | null> {\n    switch (provider) {\n      case 'openai': {\n        // OAuth first (free via ChatGPT subscription), API key fallback\n        if (process.env.CREW_NO_OAUTH !== 'true') {\n          const oauth = await getOpenAIOAuthToken();\n          if (oauth?.accessToken) {\n            return { token: oauth.accessToken, isOAuth: true, apiUrl: OPENAI_CODEX_API_URL };\n          }\n        }\n        if (process.env.OPENAI_API_KEY) {\n          return { token: process.env.OPENAI_API_KEY, isOAuth: false, apiUrl: 'https://api.openai.com/v1/chat/completions' };\n        }\n        return null;\n      }\n      case 'anthropic': {\n        // OAuth first (free via Claude Max subscription), API key fallback\n        if (process.env.CREW_NO_OAUTH !== 'true') {\n          const oauth = await getOAuthToken();\n          if (oauth?.accessToken) {\n            return { token: oauth.accessToken, isOAuth: true };\n          }\n        }\n        if (process.env.ANTHROPIC_API_KEY) {\n          return { token: process.env.ANTHROPIC_API_KEY, isOAuth: false };\n        }\n        return null;\n      }\n      case 'gemini': {\n        const apiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;\n        if (apiKey) {\n          return { token: apiKey, isOAuth: false };\n        }\n        if (process.env.CREW_NO_OAUTH === 'true') return null;\n        const oauth = await getGeminiOAuthToken();\n        if (oauth?.accessToken) {\n          return {\n            token: oauth.accessToken,\n            isOAuth: true,\n            projectId: oauth.projectId || undefined,\n            oauthSource: oauth.source\n          };\n        }\n        return null;\n      }\n      case 'deepseek':\n        return process.env.DEEPSEEK_API_KEY ? { token: process.env.DEEPSEEK_API_KEY, isOAuth: false } : null;\n      case 'groq':\n        return process.env.GROQ_API_KEY ? { token: process.env.GROQ_API_KEY, isOAuth: false } : null;\n      case 'grok':\n        return process.env.XAI_API_KEY ? { token: process.env.XAI_API_KEY, isOAuth: false } : null;\n      default:\n        return null;\n    }\n  }\n\n  /**\n   * Execute a task using local LLM (no gateway required)\n   */\n  async execute(task: string, options: ExecutorOptions = {}): Promise<ExecutorResult> {\n    const model = options.model || await this.getDefaultModel();\n    const systemPrompt = options.systemPrompt || EXECUTOR_SYSTEM_PROMPT;\n    const explicitModel = this.hasExplicitModelOverride(options);\n    \n    // Determine provider from model name\n    // Explicit model choice stays locked to its provider.\n    // Auto-selected defaults should fall through across configured providers.\n    let providers: string[] = [];\n    \n    if (!explicitModel) {\n      providers = await this.getConfiguredProviderOrder();\n    } else if (model.startsWith('gemini')) {\n      providers = ['gemini'];  // Only Gemini for gemini-* models\n    } else if (model.startsWith('deepseek')) {\n      providers = ['deepseek'];  // Only DeepSeek for deepseek-* models\n    } else if (model.startsWith('grok')) {\n      providers = ['grok'];  // Only Grok for grok-* models\n    } else if (model.startsWith('claude')) {\n      providers = ['anthropic'];  // Only Anthropic for claude-* models\n    } else if (model.startsWith('gpt-')) {\n      providers = ['openai'];  // Only OpenAI for gpt-* models\n    } else if (model.includes('llama') || model.includes('mixtral')) {\n      providers = ['groq', 'grok', 'deepseek'];  // Try multiple for generic models\n    } else {\n      // Generic/unknown model - try all providers\n      providers = ['openai', 'anthropic', 'grok', 'gemini', 'deepseek'];\n    }\n\n    if (!options.model && providers.length === 1) {\n      const fallbackProviders = (await this.getConfiguredProviderOrder()).filter(\n        (provider) => provider !== providers[0]\n      );\n      providers = [...providers, ...fallbackProviders];\n    }\n\n    if (providers.length === 0) {\n      providers = ['openai', 'anthropic', 'grok', 'gemini', 'deepseek'];\n    }\n    \n    const failures: string[] = [];\n    \n    if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[Executor] Model: ${model}, Providers: [${providers.join(', ')}]`);\n    \n    for (const provider of providers) {\n      try {\n        const auth = await this.resolveProviderAuth(provider);\n        const authBadge = auth?.isOAuth ? 'OAuth' : 'API';\n        if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') {\n          console.error(`\\x1b[2m[Executor] ${provider} (${authBadge})\\x1b[0m`);\n        }\n        const result = await this.executeWithProvider(provider, task, model, options, systemPrompt);\n        if (result) {\n          return {\n            ...result,\n            providerId: result.providerId || provider,\n            attemptedProviders: [...providers.slice(0, providers.indexOf(provider) + 1)],\n            providerFailures: [...failures]\n          };\n        }\n        failures.push(`${provider}: no usable response (missing key, timeout, or empty body)`);\n      } catch (err) {\n        const errMsg = (err as Error).message;\n        failures.push(`${provider}: ${errMsg}`);\n        this.logger.warn(`Provider ${provider} failed: ${errMsg}`);\n      }\n    }\n    \n    this.logger.error('All providers failed:', failures.join('; '));\n    this.logger.debug('API keys present:', JSON.stringify({\n      OPENAI: !!process.env.OPENAI_API_KEY,\n      ANTHROPIC: !!process.env.ANTHROPIC_API_KEY,\n      XAI: !!process.env.XAI_API_KEY,\n      GEMINI: !!process.env.GEMINI_API_KEY,\n      DEEPSEEK: !!process.env.DEEPSEEK_API_KEY\n    }));\n    \n    const configured = await this.getConfiguredProviderOrder();\n    const configuredText = configured.length > 0 ? configured.join(', ') : 'none';\n    const triedText = providers.join(', ');\n    const failureText = failures.length > 0 ? ` Failures: ${failures.join(' | ')}` : '';\n    throw new Error(\n      `No LLM providers succeeded. Configured providers: ${configuredText}. Tried: ${triedText}.${failureText} Set at least one working provider key such as OPENAI_API_KEY, ANTHROPIC_API_KEY, XAI_API_KEY, GEMINI_API_KEY, DEEPSEEK_API_KEY, or GROQ_API_KEY.`\n    );\n  }\n\n  private getTimeoutMs(): number {\n    const raw = Number(process.env.CREW_EXECUTOR_TIMEOUT_MS || 90000);\n    if (!Number.isFinite(raw) || raw < 1000) return 90000;\n    return Math.floor(raw);\n  }\n\n  private async getDefaultModel(): Promise<string> {\n    // Check environment variable first\n    const envModel = process.env.CREW_EXECUTION_MODEL || process.env.CREW_CHAT_MODEL || process.env.CREW_REASONING_MODEL;\n    if (envModel) return envModel;\n    \n    // Prefer OAuth-capable providers before raw API keys where possible.\n    if (await this.resolveProviderAuth('openai')) return 'gpt-5.4';\n    if (await this.resolveProviderAuth('anthropic')) return 'claude-sonnet-4-20250514';\n    if (process.env.XAI_API_KEY) return 'grok-beta';\n    if (await this.resolveProviderAuth('gemini')) return 'gemini-2.5-flash';\n    if (await this.resolveProviderAuth('deepseek')) return 'deepseek-chat';\n    return 'grok-beta';\n  }\n\n  private async executeWithProvider(\n    provider: string,\n    task: string,\n    model: string,\n    options: ExecutorOptions,\n    systemPrompt: string\n  ): Promise<ExecutorResult | null> {\n    const providerOptions = this.getProviderOptions(provider, model, options);\n    switch (provider) {\n      case 'openai':\n        return this.executeWithOpenAI(task, providerOptions, systemPrompt, providerOptions.sessionId);\n      case 'groq':\n        return this.executeWithGroq(task, providerOptions, systemPrompt);\n      case 'grok':\n        return this.executeWithGrok(task, providerOptions, systemPrompt, providerOptions.sessionId);\n      case 'gemini':\n        return this.executeWithGemini(task, providerOptions, systemPrompt);\n      case 'deepseek':\n        return this.executeWithDeepSeek(task, providerOptions, systemPrompt);\n      case 'anthropic':\n        return this.executeWithAnthropic(task, providerOptions, systemPrompt, providerOptions.sessionId);\n      default:\n        return null;\n    }\n  }\n\n  private getProviderOptions(provider: string, requestedModel: string, options: ExecutorOptions): ExecutorOptions {\n    if (options.explicitModel === true) {\n      return options;\n    }\n\n    const normalized = String(requestedModel || '').trim().toLowerCase();\n    const matchesProvider =\n      (provider === 'openai' && normalized.startsWith('gpt-')) ||\n      (provider === 'anthropic' && normalized.startsWith('claude')) ||\n      (provider === 'grok' && normalized.startsWith('grok')) ||\n      (provider === 'gemini' && normalized.startsWith('gemini')) ||\n      (provider === 'deepseek' && normalized.startsWith('deepseek')) ||\n      (provider === 'groq' && (normalized.includes('llama') || normalized.includes('mixtral')));\n\n    if (matchesProvider) {\n      return options;\n    }\n\n    return {\n      ...options,\n      model: undefined\n    };\n  }\n\n  private async executeWithGroq(task: string, options: ExecutorOptions, systemPrompt: string): Promise<ExecutorResult | null> {\n    const apiKey = process.env.GROQ_API_KEY;\n    if (!apiKey) return null;\n    const stream = !isStreamingDisabled() && options.jsonMode !== true;\n\n    try {\n      const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          'Authorization': `Bearer ${apiKey}`\n        },\n        signal: AbortSignal.timeout(this.timeoutMs),\n        body: JSON.stringify({\n          model: 'llama-3.3-70b-versatile',\n          messages: [\n            { role: 'system', content: systemPrompt },\n            { role: 'user', content: task }\n          ],\n          temperature: options.temperature || 0.7,\n          max_tokens: options.maxTokens || 2000,\n          ...(stream ? { stream: true, stream_options: { include_usage: true } } : {})\n        })\n      });\n\n      if (!response.ok) {\n        throw new Error(`Groq API error: ${response.statusText}`);\n      }\n\n      if (stream && response.body) {\n        const result = await streamOpenAIResponse(response, writeToStdout);\n        if (result.text) process.stdout.write('\\n');\n        const cost = this.calculateCost('groq-llama', result.usage?.prompt_tokens || 0, result.usage?.completion_tokens || 0);\n        return { success: true, result: result.text, costUsd: cost, model: 'llama-3.3-70b-versatile', providerId: 'groq' };\n      }\n\n      const data = await response.json();\n      const cost = this.calculateCost('groq-llama', data.usage?.prompt_tokens || 0, data.usage?.completion_tokens || 0);\n\n      return {\n        success: true,\n        result: data.choices[0].message.content,\n        costUsd: cost,\n        model: 'llama-3.3-70b-versatile',\n        providerId: 'groq'\n      };\n    } catch (err) {\n      this.logger.error(`Groq execution failed: ${(err as Error).message}`);\n      return null;\n    }\n  }\n\n  private async executeWithGrok(task: string, options: ExecutorOptions, systemPrompt: string, sessionId?: string): Promise<ExecutorResult | null> {\n    const key = process.env.XAI_API_KEY;\n    if (!key) return null;\n\n    // Use model from env or options, fallback to grok-4-1-fast-reasoning\n    const model = options.model || process.env.CREW_EXECUTION_MODEL || 'grok-4-1-fast-reasoning';\n\n    try {\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[Grok] Starting API call (model: ${model})...`);\n      const callStart = Date.now();\n      \n      const headers: Record<string, string> = {\n        'Content-Type': 'application/json',\n        'Authorization': `Bearer ${key}`\n      };\n      \n      // Add x-grok-conv-id for better cache coherence (increases cache hit rate)\n      if (sessionId) {\n        headers['x-grok-conv-id'] = sessionId;\n      }\n      \n      const stream = !isStreamingDisabled() && options.jsonMode !== true && process.env.CREW_GROK_STREAMING !== '0';\n      const requestBody = {\n        model,\n        messages: [\n          { role: 'system', content: systemPrompt },\n          { role: 'user', content: task }\n        ],\n        temperature: options.temperature || 0.7,\n        max_tokens: options.maxTokens || 4000,\n        ...(stream ? { stream: true, stream_options: { include_usage: true } } : {})\n      };\n      const response = await fetch('https://api.x.ai/v1/chat/completions', {\n        method: 'POST',\n        headers,\n        signal: AbortSignal.timeout(this.timeoutMs),\n        body: JSON.stringify(requestBody)\n      });\n\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[Grok] Response received in ${Date.now() - callStart}ms (status: ${response.status})`);\n\n      if (!response.ok) {\n        const errorText = await response.text().catch(() => response.statusText);\n        console.log(`[Grok] API error: ${response.status} - ${errorText}`);\n        return null;\n      }\n\n      if (stream && response.body) {\n        try {\n          const result = await streamOpenAIResponse(response, writeToStdout);\n          if (result.text) process.stdout.write('\\n');\n          const cachedTokens = result.usage?.prompt_tokens_details?.cached_tokens || 0;\n          if (cachedTokens > 0) {\n            const totalPrompt = result.usage?.prompt_tokens || 0;\n            const pct = Math.round((cachedTokens / totalPrompt) * 100);\n            console.log(`[Grok] cache hit: ${cachedTokens}/${totalPrompt} tokens cached (${pct}%) \u2014 50% cost savings`);\n          }\n          return {\n            success: true, result: result.text, model,\n            providerId: 'grok',\n            promptTokens: result.usage?.prompt_tokens,\n            completionTokens: result.usage?.completion_tokens,\n            cachedTokens,\n            costUsd: this.calculateGrokCostWithCache(result.usage)\n          };\n        } catch (streamErr) {\n          this.logger.warn(`Grok streaming failed, retrying without stream: ${(streamErr as Error).message}`);\n          const retryResponse = await fetch('https://api.x.ai/v1/chat/completions', {\n            method: 'POST',\n            headers,\n            signal: AbortSignal.timeout(this.timeoutMs),\n            body: JSON.stringify({\n              ...requestBody,\n              stream: false,\n              stream_options: undefined\n            })\n          });\n          if (!retryResponse.ok) {\n            const retryText = await retryResponse.text().catch(() => retryResponse.statusText);\n            console.log(`[Grok] Retry API error: ${retryResponse.status} - ${retryText}`);\n            return null;\n          }\n          const retryData = await retryResponse.json() as OpenAIChatResponse;\n          const retryContent = retryData?.choices?.[0]?.message?.content;\n          if (!retryContent) return null;\n          const cachedTokens = retryData?.usage?.prompt_tokens_details?.cached_tokens || 0;\n          return {\n            success: true,\n            result: retryContent,\n            model,\n            providerId: 'grok',\n            promptTokens: retryData?.usage?.prompt_tokens,\n            completionTokens: retryData?.usage?.completion_tokens,\n            cachedTokens,\n            costUsd: this.calculateGrokCostWithCache(retryData?.usage)\n          };\n        }\n      }\n\n      const data = await response.json() as OpenAIChatResponse;\n      const content = data?.choices?.[0]?.message?.content;\n      if (!content) return null;\n\n      // Track cache hits from Grok (50% savings on cached tokens)\n      const cachedTokens = data?.usage?.prompt_tokens_details?.cached_tokens || 0;\n      if (cachedTokens > 0) {\n        const totalPrompt = data?.usage?.prompt_tokens || 0;\n        const pct = Math.round((cachedTokens / totalPrompt) * 100);\n        console.log(`[Grok] cache hit: ${cachedTokens}/${totalPrompt} tokens cached (${pct}%) \u2014 50% cost savings`);\n      }\n\n      return {\n        success: true,\n        result: content,\n        model,\n        providerId: 'grok',\n        promptTokens: data?.usage?.prompt_tokens,\n        completionTokens: data?.usage?.completion_tokens,\n        cachedTokens,\n        costUsd: this.calculateGrokCostWithCache(data?.usage)\n      };\n    } catch (err) {\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[Grok] Exception: ${(err as Error).message}`);\n      this.logger.debug(`Grok execution failed: ${(err as Error).message}`);\n      return null;\n    }\n  }\n\n  private calculateGrokCostWithCache(usage: { prompt_tokens?: number; completion_tokens?: number; prompt_tokens_details?: { cached_tokens?: number } }): number {\n    if (!usage) return 0;\n    \n    const totalPrompt = usage.prompt_tokens || 0;\n    const cachedTokens = usage.prompt_tokens_details?.cached_tokens || 0;\n    const regularTokens = totalPrompt - cachedTokens;\n    const completionTokens = usage.completion_tokens || 0;\n    \n    // Grok-4 pricing: $5/1M input, $15/1M output\n    // Cached tokens: 50% discount\n    const regularCost = (regularTokens * 5.00) / 1_000_000;\n    const cachedCost = (cachedTokens * 2.50) / 1_000_000;  // 50% off\n    const outputCost = (completionTokens * 15.00) / 1_000_000;\n    \n    return regularCost + cachedCost + outputCost;\n  }\n\n  private async executeWithGemini(task: string, options: ExecutorOptions, systemPrompt: string): Promise<ExecutorResult | null> {\n    const auth = await this.resolveProviderAuth('gemini');\n    const verbose = process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true';\n    if (!auth) {\n      if (verbose) console.log('[Gemini] No API key found');\n      return null;\n    }\n\n    const model = options.model || await this.getDefaultModel();\n    if (verbose) console.log(`[Gemini] Starting API call (model: ${model})...`);\n\n    // Use explicit jsonMode flag, or detect if task expects JSON output\n    const expectsJson = options.jsonMode === true || (\n      options.jsonMode !== false && (\n        task.toLowerCase().includes('return only valid json') || \n        (task.includes('{\"') && task.includes('\"}'))\n      )\n    );\n    \n    if (expectsJson && verbose) {\n      console.log('[Gemini] JSON mode enabled');\n    }\n\n    try {\n      if (auth.isOAuth) {\n        return this.executeWithGeminiCodeAssist(task, options, systemPrompt, auth);\n      }\n\n      const requestBody: Record<string, unknown> = {\n        contents: [{\n          parts: [{\n            text: `${systemPrompt}\\n\\nUser task: ${task}`\n          }]\n        }],\n        generationConfig: {\n          temperature: options.temperature || 0.7,\n          maxOutputTokens: options.maxTokens || 4000\n        }\n      };\n\n      // Enable JSON mode for structured outputs\n      if (expectsJson) {\n        requestBody.generationConfig.responseMimeType = 'application/json';\n      }\n\n      const usingVertexOAuth = auth.isOAuth && !!auth.projectId;\n      const stream = !isStreamingDisabled() && !expectsJson && !usingVertexOAuth;\n      const vertexRegion = process.env.GEMINI_VERTEX_REGION || process.env.CLOUD_ML_REGION || 'us-central1';\n      const endpoint = usingVertexOAuth\n        ? `https://${vertexRegion}-aiplatform.googleapis.com/v1/projects/${encodeURIComponent(auth.projectId!)}/locations/${encodeURIComponent(vertexRegion)}/publishers/google/models/${model}:generateContent`\n        : (auth.isOAuth\n          ? `https://generativelanguage.googleapis.com/v1beta/models/${model}:${stream ? 'streamGenerateContent?alt=sse' : 'generateContent'}`\n          : (stream\n          ? `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${encodeURIComponent(auth.token)}`\n          : `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${encodeURIComponent(auth.token)}`));\n\n      const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n      if (auth.isOAuth) {\n        headers.Authorization = `Bearer ${auth.token}`;\n        if (usingVertexOAuth) {\n          headers['x-goog-user-project'] = auth.projectId!;\n        }\n      }\n\n      const response = await fetch(endpoint, {\n          method: 'POST',\n          headers,\n          signal: AbortSignal.timeout(this.timeoutMs),\n          body: JSON.stringify(requestBody)\n        }\n      );\n\n      if (verbose) {\n        console.log(`[Gemini] Response received (status: ${response.status})`);\n      }\n\n      if (!response.ok) {\n        if (response.status === 401 && auth.isOAuth) {\n          const refreshed = await forceRefreshGeminiOAuth();\n          if (refreshed?.accessToken && refreshed.accessToken !== auth.token) {\n            return this.executeWithGemini(task, options, systemPrompt);\n          }\n        }\n        const errorText = await response.text();\n        if (verbose) {\n          console.log(`[Gemini] API error: ${response.status} - ${errorText}`);\n        }\n        return null;\n      }\n\n      if (stream && response.body) {\n        const result = await streamGeminiResponse(response, writeToStdout);\n        if (result.text) process.stdout.write('\\n');\n        return {\n          success: true, result: result.text, model,\n          providerId: 'gemini',\n          promptTokens: result.usage?.promptTokenCount,\n          completionTokens: result.usage?.candidatesTokenCount,\n          costUsd: this.calculateCost(model, result.usage?.promptTokenCount || 0, result.usage?.candidatesTokenCount || 0)\n        };\n      }\n\n      const data = await response.json() as GeminiContentResponse;\n      const content = data?.candidates?.[0]?.content?.parts?.[0]?.text;\n      if (!content) return null;\n\n      return {\n        success: true,\n        result: content,\n        model: model,\n        providerId: 'gemini',\n        promptTokens: data?.usageMetadata?.promptTokenCount,\n        completionTokens: data?.usageMetadata?.candidatesTokenCount,\n        costUsd: this.calculateCost(model,\n          data?.usageMetadata?.promptTokenCount || 0,\n          data?.usageMetadata?.candidatesTokenCount || 0)\n      };\n    } catch (err) {\n      this.logger.debug(`Gemini execution failed: ${(err as Error).message}`);\n      return null;\n    }\n  }\n\n  private async executeWithGeminiCodeAssist(\n    task: string,\n    options: ExecutorOptions,\n    systemPrompt: string,\n    auth: ProviderAuth\n  ): Promise<ExecutorResult | null> {\n    const model = options.model || await this.getDefaultModel();\n    const projectId = auth.projectId || process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT_ID || '';\n    const headers: Record<string, string> = {\n      'Content-Type': 'application/json',\n      'Authorization': `Bearer ${auth.token}`,\n      'User-Agent': 'GeminiCLI/crew-cli'\n    };\n    if (auth.oauthSource === 'adc' && projectId) {\n      headers['x-goog-user-project'] = projectId;\n    }\n\n    const metadata = {\n      ideType: 'IDE_UNSPECIFIED',\n      platform: 'PLATFORM_UNSPECIFIED',\n      pluginType: 'GEMINI',\n      duetProject: projectId || undefined\n    };\n\n    const loadResponse = await fetch('https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist', {\n      method: 'POST',\n      headers,\n      signal: AbortSignal.timeout(this.timeoutMs),\n      body: JSON.stringify({\n        cloudaicompanionProject: projectId || undefined,\n        metadata\n      })\n    });\n\n    if (!loadResponse.ok) {\n      const errorText = await loadResponse.text().catch(() => '');\n      throw new Error(`Gemini Code Assist loadCodeAssist ${loadResponse.status}: ${errorText.slice(0, 300)}`);\n    }\n\n    const loadData = await loadResponse.json() as GeminiCodeAssistLoadResponse;\n    const resolvedProjectId = loadData?.cloudaicompanionProject || projectId;\n    const requestBody = {\n      model,\n      project: resolvedProjectId || undefined,\n      user_prompt_id: options.sessionId || `crew-${Date.now()}`,\n      request: {\n        contents: [{\n          role: 'user',\n          parts: [{ text: `${systemPrompt}\\n\\nUser task: ${task}` }]\n        }],\n        systemInstruction: {\n          role: 'user',\n          parts: [{ text: systemPrompt }]\n        },\n        generationConfig: {\n          temperature: options.temperature ?? 0.7,\n          maxOutputTokens: options.maxTokens || 4000\n        },\n        session_id: options.sessionId || ''\n      }\n    };\n\n    const response = await fetch('https://cloudcode-pa.googleapis.com/v1internal:generateContent', {\n      method: 'POST',\n      headers,\n      signal: AbortSignal.timeout(this.timeoutMs),\n      body: JSON.stringify(requestBody)\n    });\n\n    if (!response.ok) {\n      if (response.status === 401) {\n        const refreshed = await forceRefreshGeminiOAuth();\n        if (refreshed?.accessToken && refreshed.accessToken !== auth.token) {\n          return this.executeWithGemini(task, options, systemPrompt);\n        }\n      }\n      const errorText = await response.text().catch(() => '');\n      throw new Error(`Gemini Code Assist generateContent ${response.status}: ${errorText.slice(0, 300)}`);\n    }\n\n    const data = await response.json() as GeminiCodeAssistGenerateResponse;\n    const parts = data?.response?.candidates?.[0]?.content?.parts || [];\n    const content = parts.filter((part: Record<string, unknown>) => typeof part?.text === 'string').map((part: Record<string, unknown>) => part.text).join('\\n').trim();\n    if (!content) return null;\n\n    return {\n      success: true,\n      result: content,\n      model,\n      providerId: `gemini-oauth-${auth.oauthSource || 'unknown'}`,\n      promptTokens: data?.response?.usageMetadata?.promptTokenCount,\n      completionTokens: data?.response?.usageMetadata?.candidatesTokenCount,\n      costUsd: this.calculateCost(\n        model,\n        data?.response?.usageMetadata?.promptTokenCount || 0,\n        data?.response?.usageMetadata?.candidatesTokenCount || 0\n      )\n    };\n  }\n\n  private async executeWithDeepSeek(task: string, options: ExecutorOptions, systemPrompt: string): Promise<ExecutorResult | null> {\n    const key = process.env.DEEPSEEK_API_KEY;\n    if (!key) {\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log('[DeepSeek] No API key found');\n      return null;\n    }\n\n    const model = options.model || 'deepseek-chat';\n    \n    // For deepseek-reasoner on large tasks, allow much longer timeout\n    const timeoutMs = model.includes('reasoner') && (options.maxTokens || 0) > 6000\n      ? 10 * 60 * 1000  // 10 minutes for large reasoning tasks\n      : this.timeoutMs;\n    \n    console.log(`[DeepSeek] Starting API call (model: ${model}, timeout: ${timeoutMs/1000}s)...`);\n\n    try {\n      const stream = !isStreamingDisabled() && !model.includes('reasoner');\n      const response = await fetch('https://api.deepseek.com/v1/chat/completions', {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          Authorization: `Bearer ${key}`\n        },\n        signal: AbortSignal.timeout(timeoutMs),\n        body: JSON.stringify({\n          model: model,\n          messages: [\n            { role: 'system', content: systemPrompt },\n            { role: 'user', content: task }\n          ],\n          temperature: options.temperature || 0.7,\n          max_tokens: options.maxTokens || 4000,\n          ...(stream ? { stream: true, stream_options: { include_usage: true } } : {})\n        })\n      });\n\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[DeepSeek] Response received (status: ${response.status})`);\n\n      if (!response.ok) {\n        const errorText = await response.text();\n        console.log(`[DeepSeek] API error: ${response.status} - ${errorText}`);\n        return null;\n      }\n\n      if (stream && response.body) {\n        const result = await streamOpenAIResponse(response, writeToStdout);\n        if (result.text) process.stdout.write('\\n');\n        if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[DeepSeek] \u2713 Success (${result.usage?.prompt_tokens || 0} in, ${result.usage?.completion_tokens || 0} out)`);\n        return {\n          success: true, result: result.text, model,\n          promptTokens: result.usage?.prompt_tokens,\n          completionTokens: result.usage?.completion_tokens,\n          costUsd: this.calculateCost(model, result.usage?.prompt_tokens || 0, result.usage?.completion_tokens || 0)\n        };\n      }\n\n      const data = await response.json() as OpenAIChatResponse;\n\n      // deepseek-reasoner returns reasoning_content + content\n      // deepseek-chat returns only content\n      const reasoning_content = data?.choices?.[0]?.message?.reasoning_content;\n      let content = data?.choices?.[0]?.message?.content;\n      \n      if (!content && !reasoning_content) {\n        console.log('[DeepSeek] No content or reasoning_content in response');\n        return null;\n      }\n\n      // Log reasoning trace if present (for deepseek-reasoner)\n      if (reasoning_content && process.env.DEBUG_REASONING) {\n        console.log(`[DeepSeek] Reasoning trace (${reasoning_content.length} chars):`, \n          reasoning_content.substring(0, 200) + '...');\n      }\n\n      // Validate content is not just an empty brace or whitespace\n      const trimmedContent = (content || '').trim();\n      if (trimmedContent && trimmedContent !== '{' && trimmedContent !== '{}' && trimmedContent.length > 5) {\n        // Valid content - use it\n      } else if (reasoning_content) {\n        // content is invalid/empty but we have reasoning - try to extract JSON from reasoning\n        console.log('[DeepSeek] content field invalid, checking reasoning_content for JSON...');\n        content = reasoning_content;\n      } else {\n        console.log('[DeepSeek] No valid content available');\n        return null;\n      }\n\n      // Return ONLY the final answer content (content field)\n      // The reasoning_content is internal CoT, not part of structured output\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[DeepSeek] \u2713 Success (${data?.usage?.prompt_tokens || 0} in, ${data?.usage?.completion_tokens || 0} out)`);\n\n      return {\n        success: true,\n        result: content,\n        model: model,\n        promptTokens: data?.usage?.prompt_tokens,\n        completionTokens: data?.usage?.completion_tokens,\n        costUsd: this.calculateCost(model, data?.usage?.prompt_tokens || 0, data?.usage?.completion_tokens || 0)\n      };\n    } catch (err) {\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[DeepSeek] Exception: ${(err as Error).message}`);\n      this.logger.debug(`DeepSeek execution failed: ${(err as Error).message}`);\n      return null;\n    }\n  }\n\n  private calculateCost(model: string, promptTokens: number, completionTokens: number): number {\n    // Rough pricing (per 1M tokens) - March 2026\n    const pricing: Record<string, { prompt: number; completion: number }> = {\n      'grok-beta': { prompt: 5, completion: 15 },\n      'grok-4-1-fast-reasoning': { prompt: 5, completion: 15 },\n      'gemini-2.0-flash-exp': { prompt: 0.075, completion: 0.30 },\n      'gemini-2.5-flash': { prompt: 0.075, completion: 0.30 },\n      'gemini-2.5-pro': { prompt: 1.25, completion: 5.00 },\n      'deepseek-chat': { prompt: 0.27, completion: 1.10 },\n      'deepseek-reasoner': { prompt: 0.55, completion: 2.19 },\n      'claude-3-5-sonnet-20241022': { prompt: 3.00, completion: 15.00 },\n      'claude-opus-4-6': { prompt: 5.00, completion: 25.00 },\n      'claude-haiku-4-5': { prompt: 1.00, completion: 5.00 }\n    };\n\n    const rates = pricing[model] || { prompt: 1, completion: 3 };\n    return (promptTokens * rates.prompt + completionTokens * rates.completion) / 1_000_000;\n  }\n\n  /**\n   * Execute with Anthropic (Claude) - supports explicit prompt caching for 90% savings\n   */\n  private async executeWithAnthropic(\n    task: string, \n    options: ExecutorOptions,\n    systemPrompt: string,\n    sessionId?: string\n  ): Promise<ExecutorResult | null> {\n    const auth = await this.resolveProviderAuth('anthropic');\n    if (!auth) return null;\n\n    const model = options.model || 'claude-3-5-sonnet-20241022';\n    \n    try {\n      if (auth.isOAuth) {\n        const oauthModel = options.model || String(process.env.CREW_OAUTH_CLAUDE_MODEL || 'claude-sonnet-4-6');\n        const firstMsg = typeof task === 'string' ? task : '';\n        const suffix = computeVersionSuffix(firstMsg);\n        const billingBlock = buildBillingBlock(suffix);\n        const systemBlocks = [\n          billingBlock,\n          ...(systemPrompt ? [{ type: 'text' as const, text: systemPrompt, cache_control: { type: 'ephemeral' as const } }] : []),\n        ];\n        const supportsThinking = !oauthModel.includes('haiku');\n        const bodyObj = {\n          model: oauthModel,\n          max_tokens: options.maxTokens || 4000,\n          ...(supportsThinking ? { thinking: { type: 'adaptive' } } : {}),\n          metadata: { user_id: `user_crewswarm_session_${sessionId || randomUUID()}` },\n          system: systemBlocks,\n          messages: [{ role: 'user', content: task }],\n        };\n        const signedBody = await signBody(bodyObj);\n        const response = await fetch('https://api.anthropic.com/v1/messages?beta=true', {\n          method: 'POST',\n          headers: {\n            Authorization: `Bearer ${auth.token}`,\n            'content-type': 'application/json',\n            'anthropic-version': '2023-06-01',\n            'anthropic-beta': CLAUDE_OAUTH_BETA_HEADER,\n            'anthropic-dangerous-direct-browser-access': 'true',\n            'x-app': 'cli',\n            'user-agent': 'claude-cli/2.1.87 (external, cli)',\n            'x-claude-code-session-id': sessionId || randomUUID(),\n          },\n          signal: AbortSignal.timeout(this.timeoutMs),\n          body: signedBody\n        });\n\n        if (!response.ok) {\n          if (response.status === 401) {\n            const refreshed = await forceRefreshOAuthToken();\n            if (refreshed?.accessToken && refreshed.accessToken !== auth.token) {\n              return this.executeWithAnthropic(task, options, systemPrompt, sessionId);\n            }\n          }\n          const errorText = await response.text().catch(() => response.statusText);\n          if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') {\n            console.log(`[Anthropic OAuth] API error: ${response.status} - ${errorText}`);\n          }\n          return null;\n        }\n\n        const data = await response.json() as AnthropicMessageResponse;\n        const content = (data?.content || []).filter((b: Record<string, unknown>) => b.type === 'text').map((b: Record<string, unknown>) => b.text).join('\\n');\n        const usage = data?.usage || {};\n        if (!content) return null;\n        return {\n          success: true,\n          result: content,\n          model: oauthModel,\n          providerId: 'anthropic-oauth',\n          promptTokens: usage.input_tokens,\n          completionTokens: usage.output_tokens,\n          costUsd: this.calculateAnthropicCostWithCache(usage)\n        };\n      }\n\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[Anthropic] Starting API call (model: ${model})...`);\n      const callStart = Date.now();\n\n      // Use explicit cache control for 90% savings on system prompt\n      const stream = !isStreamingDisabled();\n      const response = await fetch('https://api.anthropic.com/v1/messages', {\n        method: 'POST',\n        headers: {\n          'x-api-key': auth.token,\n          'anthropic-version': '2023-06-01',\n          'content-type': 'application/json'\n        },\n        signal: AbortSignal.timeout(this.timeoutMs),\n        body: JSON.stringify({\n          model,\n          max_tokens: options.maxTokens || 4000,\n          ...(stream ? { stream: true } : {}),\n          system: [\n            {\n              type: 'text',\n              text: systemPrompt,\n              cache_control: { type: 'ephemeral' }  // Explicit cache control (90% savings!)\n            }\n          ],\n          messages: [\n            { role: 'user', content: task }\n          ]\n        })\n      });\n\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[Anthropic] Response received in ${Date.now() - callStart}ms (status: ${response.status})`);\n\n      if (!response.ok) {\n        const errorText = await response.text().catch(() => response.statusText);\n        console.log(`[Anthropic] API error: ${response.status} - ${errorText}`);\n        return null;\n      }\n\n      if (stream && response.body) {\n        const result = await streamAnthropicResponse(response, writeToStdout);\n        if (result.text) process.stdout.write('\\n');\n        const usage = result.usage || {};\n        const cacheReadTokens = usage.cache_read_input_tokens || 0;\n        const cacheCreateTokens = usage.cache_creation_input_tokens || 0;\n        const inputTokens = usage.input_tokens || 0;\n        if (cacheReadTokens > 0) {\n          const totalInput = inputTokens + cacheReadTokens;\n          const pct = Math.round((cacheReadTokens / totalInput) * 100);\n          console.log(`[Anthropic] cache hit: ${cacheReadTokens}/${totalInput} tokens cached (${pct}%) \u2014 90% cost savings`);\n        } else if (cacheCreateTokens > 0) {\n          console.log(`[Anthropic] cache write: ${cacheCreateTokens} tokens cached for future requests`);\n        }\n        return {\n          success: true, result: result.text, model,\n          promptTokens: inputTokens,\n          completionTokens: usage.output_tokens,\n          cachedTokens: cacheReadTokens,\n          costUsd: this.calculateAnthropicCostWithCache(usage)\n        };\n      }\n\n      const data = await response.json() as AnthropicMessageResponse;\n      const content = data?.content?.[0]?.text;\n      if (!content) return null;\n\n      // Track cache metrics (Anthropic reports detailed cache usage)\n      const cacheCreateTokens = data?.usage?.cache_creation_input_tokens || 0;\n      const cacheReadTokens = data?.usage?.cache_read_input_tokens || 0;\n      const inputTokens = data?.usage?.input_tokens || 0;\n\n      if (cacheReadTokens > 0) {\n        const totalInput = inputTokens + cacheReadTokens;\n        const pct = Math.round((cacheReadTokens / totalInput) * 100);\n        console.log(`[Anthropic] cache hit: ${cacheReadTokens}/${totalInput} tokens cached (${pct}%) \u2014 90% cost savings`);\n      } else if (cacheCreateTokens > 0) {\n        console.log(`[Anthropic] cache write: ${cacheCreateTokens} tokens cached for future requests`);\n      }\n\n      return {\n        success: true,\n        result: content,\n        model,\n        promptTokens: inputTokens,\n        completionTokens: data?.usage?.output_tokens,\n        cachedTokens: cacheReadTokens,\n        costUsd: this.calculateAnthropicCostWithCache(data?.usage)\n      };\n    } catch (err) {\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[Anthropic] Exception: ${(err as Error).message}`);\n      this.logger.debug(`Anthropic execution failed: ${(err as Error).message}`);\n      return null;\n    }\n  }\n\n  private calculateAnthropicCostWithCache(usage: { input_tokens?: number; output_tokens?: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number }): number {\n    if (!usage) return 0;\n    \n    const inputBase = (usage.input_tokens || 0) * 3.00 / 1_000_000;\n    const cacheWrite = (usage.cache_creation_input_tokens || 0) * 3.75 / 1_000_000;  // 1.25x\n    const cacheRead = (usage.cache_read_input_tokens || 0) * 0.30 / 1_000_000;  // 0.1x (90% off!)\n    const output = (usage.output_tokens || 0) * 15.00 / 1_000_000;\n    \n    return inputBase + cacheWrite + cacheRead + output;\n  }\n\n  /**\n   * Execute with OpenAI (GPT-4, GPT-5)\n   */\n  private async executeWithOpenAI(\n    task: string,\n    options: ExecutorOptions,\n    systemPrompt: string,\n    sessionId?: string\n  ): Promise<ExecutorResult | null> {\n    const auth = await this.resolveProviderAuth('openai');\n    if (!auth) {\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log('[OpenAI] No API key found');\n      return null;\n    }\n\n    const model = options.model || (auth.isOAuth ? String(process.env.CREW_OAUTH_OPENAI_MODEL || 'gpt-5.4') : 'gpt-4o');\n    \n    if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[OpenAI] Starting API call (model: ${model})...`);\n\n    try {\n      // GPT-5+ uses max_completion_tokens, GPT-4 uses max_tokens\n      const maxTokensParam = model.startsWith('gpt-5') || model.startsWith('gpt-6')\n        ? 'max_completion_tokens'\n        : 'max_tokens';\n      // GPT-5/6 only support temperature=1 (default); other values cause 400\n      const temp = (model.startsWith('gpt-5') || model.startsWith('gpt-6'))\n        ? 1\n        : (options.temperature ?? 0.7);\n      const apiUrl = auth.apiUrl || 'https://api.openai.com/v1/chat/completions';\n      const isCodexOAuth = auth.isOAuth && apiUrl === OPENAI_CODEX_API_URL;\n      const stream = !isStreamingDisabled() && !options.jsonMode && !isCodexOAuth;\n\n      const requestBody: Record<string, unknown> = isCodexOAuth\n        ? {\n            model,\n            instructions: systemPrompt,\n            input: [\n              {\n                role: 'user',\n                content: [\n                  { type: 'input_text', text: task }\n                ]\n              }\n            ],\n            store: false,\n            stream: true\n          }\n        : {\n            model,\n            messages: [\n              { role: 'system', content: systemPrompt },\n              { role: 'user', content: task }\n            ],\n            temperature: temp,\n            [maxTokensParam]: options.maxTokens || 4000,\n            ...(stream ? { stream: true, stream_options: { include_usage: true } } : {})\n          };\n\n      if (options.jsonMode && !isCodexOAuth) {\n        requestBody.response_format = { type: 'json_object' };\n      }\n\n      const response = await fetch(apiUrl, {\n        method: 'POST',\n        headers: {\n          'Authorization': `Bearer ${auth.token}`,\n          'Content-Type': 'application/json'\n        },\n        signal: AbortSignal.timeout(this.timeoutMs),\n        body: JSON.stringify(requestBody)\n      });\n\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[OpenAI] Response received (status: ${response.status})`);\n\n      if (!response.ok) {\n        if (response.status === 401 && auth.isOAuth) {\n          const refreshed = await forceRefreshOpenAIOAuth();\n          if (refreshed?.accessToken && refreshed.accessToken !== auth.token) {\n            return this.executeWithOpenAI(task, options, systemPrompt, sessionId);\n          }\n        }\n        const errorText = await response.text();\n        console.log(`[OpenAI] API error: ${response.status} - ${errorText}`);\n        return null;\n      }\n\n      if (isCodexOAuth && response.body) {\n        const result = await this.streamOpenAIResponsesOAuth(response);\n        if (result.text) process.stdout.write('\\n');\n        const usage = result.usage || {};\n        return {\n          success: true,\n          result: result.text,\n          model,\n          promptTokens: usage.prompt_tokens,\n          completionTokens: usage.completion_tokens,\n          cachedTokens: 0,\n          costUsd: this.calculateOpenAICost(model, usage.prompt_tokens || 0, usage.completion_tokens || 0)\n        };\n      }\n\n      if (stream && response.body) {\n        const result = await streamOpenAIResponse(response, writeToStdout);\n        if (result.text) process.stdout.write('\\n');\n        if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[OpenAI] \u2713 Success (${result.usage?.prompt_tokens || 0} in, ${result.usage?.completion_tokens || 0} out)`);\n        return {\n          success: true, result: result.text, model,\n          promptTokens: result.usage?.prompt_tokens,\n          completionTokens: result.usage?.completion_tokens,\n          cachedTokens: 0,\n          costUsd: this.calculateOpenAICost(model, result.usage?.prompt_tokens || 0, result.usage?.completion_tokens || 0)\n        };\n      }\n\n      const data = await response.json() as OpenAIChatResponse;\n      const content = isCodexOAuth\n        ? this.extractOpenAIResponsesText(data)\n        : data?.choices?.[0]?.message?.content;\n\n      if (!content) {\n        console.log('[OpenAI] No content in response');\n        return null;\n      }\n\n      const usage = isCodexOAuth\n        ? {\n            prompt_tokens: data?.usage?.input_tokens,\n            completion_tokens: data?.usage?.output_tokens\n          }\n        : data?.usage;\n\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[OpenAI] \u2713 Success (${usage?.prompt_tokens || 0} in, ${usage?.completion_tokens || 0} out)`);\n\n      return {\n        success: true,\n        result: content,\n        model,\n        promptTokens: usage?.prompt_tokens,\n        completionTokens: usage?.completion_tokens,\n        cachedTokens: 0,\n        costUsd: this.calculateOpenAICost(model, usage?.prompt_tokens || 0, usage?.completion_tokens || 0)\n      };\n    } catch (err) {\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') console.log(`[OpenAI] Exception: ${(err as Error).message}`);\n      this.logger.debug(`OpenAI execution failed: ${(err as Error).message}`);\n      return null;\n    }\n  }\n\n  private extractOpenAIResponsesText(data: unknown): string {\n    if (typeof data?.output_text === 'string' && data.output_text.trim()) {\n      return data.output_text;\n    }\n\n    const outputs = Array.isArray(data?.output) ? data.output : [];\n    const textParts: string[] = [];\n    for (const item of outputs) {\n      const contents = Array.isArray(item?.content) ? item.content : [];\n      for (const content of contents) {\n        if (typeof content?.text === 'string' && content.text) {\n          textParts.push(content.text);\n        }\n      }\n    }\n    return textParts.join('\\n').trim();\n  }\n\n  private async streamOpenAIResponsesOAuth(response: Response): Promise<{ text: string; usage?: { prompt_tokens?: number; completion_tokens?: number } }> {\n    if (!response.body) {\n      return { text: '' };\n    }\n\n    const reader = response.body.getReader();\n    const decoder = new TextDecoder();\n    const functionCalls = new Map<string, { name: string; args: string }>();\n    let buffer = '';\n    let currentEvent = '';\n    let text = '';\n    let usage: { prompt_tokens?: number; completion_tokens?: number } | undefined;\n\n    const flushEvent = (rawData: string) => {\n      if (!rawData.trim()) return;\n      let payload: Record<string, unknown> | undefined;\n      try {\n        payload = JSON.parse(rawData);\n      } catch {\n        return;\n      }\n\n      const eventType = currentEvent || payload?.type || '';\n      const item = payload?.item || payload?.output_item;\n      const itemId = item?.id || payload?.item_id || payload?.call_id || '';\n\n      if (eventType === 'response.output_text.delta' && typeof payload?.delta === 'string') {\n        process.stdout.write(payload.delta);\n        text += payload.delta;\n        return;\n      }\n\n      if (eventType === 'response.function_call_arguments.delta' && itemId) {\n        if (!functionCalls.has(itemId)) {\n          functionCalls.set(itemId, { name: '', args: '' });\n        }\n        const acc = functionCalls.get(itemId)!;\n        acc.args += String(payload?.delta || '');\n        return;\n      }\n\n      if ((eventType === 'response.output_item.added' || eventType === 'response.output_item.done') && item?.type === 'function_call') {\n        if (!functionCalls.has(itemId)) {\n          functionCalls.set(itemId, { name: '', args: '' });\n        }\n        const acc = functionCalls.get(itemId)!;\n        if (item?.name) acc.name = item.name;\n        if (typeof item?.arguments === 'string') acc.args = item.arguments;\n        return;\n      }\n\n      if (eventType === 'response.completed') {\n        usage = {\n          prompt_tokens: payload?.response?.usage?.input_tokens,\n          completion_tokens: payload?.response?.usage?.output_tokens\n        };\n        if (!text) {\n          text = this.extractOpenAIResponsesText(payload?.response);\n        }\n      }\n    };\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n        buffer += decoder.decode(value, { stream: true });\n\n        let boundary = buffer.indexOf('\\n\\n');\n        while (boundary !== -1) {\n          const chunk = buffer.slice(0, boundary);\n          buffer = buffer.slice(boundary + 2);\n\n          const lines = chunk.split('\\n');\n          currentEvent = '';\n          const dataLines: string[] = [];\n          for (const line of lines) {\n            if (line.startsWith('event:')) currentEvent = line.slice(6).trim();\n            if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());\n          }\n          flushEvent(dataLines.join('\\n'));\n          boundary = buffer.indexOf('\\n\\n');\n        }\n      }\n    } finally {\n      reader.releaseLock();\n    }\n\n    return { text: text.trim(), usage };\n  }\n\n  private calculateOpenAICost(model: string, promptTokens: number, completionTokens: number): number {\n    // Pricing per 1M tokens\n    const pricing: Record<string, { prompt: number; completion: number }> = {\n      'gpt-5.2': { prompt: 5, completion: 20 },\n      'gpt-5.2-2025-12-11': { prompt: 5, completion: 20 },\n      'gpt-5.2-codex': { prompt: 5, completion: 20 },\n      'gpt-5.1': { prompt: 4, completion: 16 },\n      'gpt-5.1-chat-latest': { prompt: 4, completion: 16 },\n      'gpt-5.1-codex': { prompt: 4, completion: 16 },\n      'gpt-5-mini': { prompt: 0.5, completion: 2 },\n      'gpt-5-nano': { prompt: 0.1, completion: 0.4 },\n      'gpt-4o': { prompt: 2.5, completion: 10 },\n      'gpt-4o-mini': { prompt: 0.15, completion: 0.6 },\n      'gpt-4-turbo': { prompt: 10, completion: 30 }\n    };\n    \n    const rates = pricing[model] || pricing['gpt-4o'];\n    return (promptTokens * rates.prompt + completionTokens * rates.completion) / 1_000_000;\n  }\n}\n", "/**\n * Runtime profiles - replaces confusing mode system\n */\n\nexport type RuntimeProfile = 'chat' | 'builder' | 'orchestrator';\n\nexport interface ProfileConfig {\n  name: RuntimeProfile;\n  description: string;\n  useLocalExecutor: boolean;\n  useGateway: boolean;\n  autoApply: boolean;\n  showExecutionPath: boolean;\n}\n\nexport const RUNTIME_PROFILES: Record<RuntimeProfile, ProfileConfig> = {\n  chat: {\n    name: 'chat',\n    description: 'Conversational mode - local LLM only, no code execution',\n    useLocalExecutor: true,\n    useGateway: false,\n    autoApply: false,\n    showExecutionPath: false\n  },\n  builder: {\n    name: 'builder',\n    description: 'Build mode - local execution with manual approval',\n    useLocalExecutor: true,\n    useGateway: false,\n    autoApply: false,\n    showExecutionPath: true\n  },\n  orchestrator: {\n    name: 'orchestrator',\n    description: 'Team mode - coordinates specialists via gateway',\n    useLocalExecutor: false,\n    useGateway: true,\n    autoApply: false,\n    showExecutionPath: true\n  }\n};\n\nexport function getProfileConfig(profile: RuntimeProfile): ProfileConfig {\n  return RUNTIME_PROFILES[profile];\n}\n\nexport function formatExecutionPath(parts: string[]): string {\n  return parts.join(' \u2192 ');\n}\n", "/**\n * crewswarm Hook System\n *\n * Hooks allow users to run shell commands before/after tool execution.\n * Configuration lives in .crew/hooks.json or CREW_HOOKS_FILE env var.\n *\n * Hook commands receive tool input as JSON on stdin and can:\n * - PreToolUse: allow/deny/modify tool execution\n * - PostToolUse: log, alert, or transform results\n *\n * Example .crew/hooks.json:\n * {\n *   \"hooks\": {\n *     \"PreToolUse\": [\n *       { \"matcher\": \"shell|run_cmd\", \"command\": \"node .crew/validate-shell.js\", \"timeout\": 5000 }\n *     ],\n *     \"PostToolUse\": [\n *       { \"matcher\": \".*\", \"command\": \"node .crew/log-tool.js\", \"timeout\": 3000 }\n *     ]\n *   }\n * }\n */\n\nimport { spawn } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport type HookEvent = 'PreToolUse' | 'PostToolUse';\n\nexport interface HookDefinition {\n  matcher: string;       // Regex pattern to match tool names\n  command: string;       // Shell command to execute\n  timeout?: number;      // Timeout in ms (default 10000)\n}\n\nexport interface HookConfig {\n  hooks: Partial<Record<HookEvent, HookDefinition[]>>;\n}\n\nexport interface PreToolUseResult {\n  decision: 'allow' | 'deny' | 'ask';\n  reason?: string;\n  updatedInput?: Record<string, unknown>;\n}\n\nexport interface PostToolUseResult {\n  message?: string;\n}\n\ninterface HookOutput {\n  permissionDecision?: 'allow' | 'deny' | 'ask';\n  permissionDecisionReason?: string;\n  updatedInput?: Record<string, unknown>;\n  message?: string;\n}\n\nlet cachedConfig: HookConfig | null = null;\nlet configPath: string | null = null;\n\nfunction getConfigPath(baseDir: string = process.cwd()): string {\n  return process.env.CREW_HOOKS_FILE || join(baseDir, '.crew', 'hooks.json');\n}\n\nexport async function loadHookConfig(baseDir?: string): Promise<HookConfig> {\n  const path = getConfigPath(baseDir);\n  if (cachedConfig && configPath === path) return cachedConfig;\n\n  if (!existsSync(path)) {\n    cachedConfig = { hooks: {} };\n    configPath = path;\n    return cachedConfig;\n  }\n\n  try {\n    const raw = await readFile(path, 'utf8');\n    cachedConfig = JSON.parse(raw) as HookConfig;\n    configPath = path;\n    return cachedConfig;\n  } catch {\n    cachedConfig = { hooks: {} };\n    configPath = path;\n    return cachedConfig;\n  }\n}\n\n/** Clear cached config (for testing or after config changes) */\nexport function clearHookCache(): void {\n  cachedConfig = null;\n  configPath = null;\n}\n\nfunction matchesHook(toolName: string, hook: HookDefinition): boolean {\n  try {\n    return new RegExp(hook.matcher).test(toolName);\n  } catch {\n    return false;\n  }\n}\n\nasync function executeHookCommand(\n  command: string,\n  stdinData: string,\n  timeoutMs: number\n): Promise<HookOutput> {\n  return new Promise((resolve) => {\n    const proc = spawn('sh', ['-c', command], {\n      stdio: ['pipe', 'pipe', 'pipe'],\n      timeout: timeoutMs\n    });\n\n    let stdout = '';\n    let stderr = '';\n\n    proc.stdout.on('data', (d: Buffer) => { stdout += d.toString(); });\n    proc.stderr.on('data', (d: Buffer) => { stderr += d.toString(); });\n\n    proc.on('error', () => {\n      resolve({});\n    });\n\n    proc.on('close', (code) => {\n      if (code !== 0) {\n        // Non-zero exit = deny for PreToolUse\n        resolve({\n          permissionDecision: 'deny',\n          permissionDecisionReason: stderr.trim() || `Hook exited with code ${code}`\n        });\n        return;\n      }\n\n      // Try to parse JSON output from hook\n      try {\n        const parsed = JSON.parse(stdout.trim());\n        resolve(parsed);\n      } catch {\n        // No JSON output = passthrough (allow)\n        resolve({ message: stdout.trim() || undefined });\n      }\n    });\n\n    // Pipe tool input as JSON on stdin\n    proc.stdin.write(stdinData);\n    proc.stdin.end();\n  });\n}\n\n/**\n * Run PreToolUse hooks for a tool call.\n * Returns the decision and optionally modified input.\n */\nexport async function runPreToolUseHooks(\n  toolName: string,\n  toolInput: Record<string, unknown>,\n  baseDir?: string\n): Promise<PreToolUseResult> {\n  const config = await loadHookConfig(baseDir);\n  const hooks = config.hooks.PreToolUse || [];\n\n  for (const hook of hooks) {\n    if (!matchesHook(toolName, hook)) continue;\n\n    const stdinData = JSON.stringify({ tool: toolName, input: toolInput });\n    const result = await executeHookCommand(hook.command, stdinData, hook.timeout || 10000);\n\n    if (result.permissionDecision === 'deny') {\n      return {\n        decision: 'deny',\n        reason: result.permissionDecisionReason || 'Denied by PreToolUse hook'\n      };\n    }\n\n    if (result.permissionDecision === 'ask') {\n      return {\n        decision: 'ask',\n        reason: result.permissionDecisionReason\n      };\n    }\n\n    // Hook can modify input\n    if (result.updatedInput) {\n      return { decision: 'allow', updatedInput: result.updatedInput };\n    }\n  }\n\n  return { decision: 'allow' };\n}\n\n/**\n * Run PostToolUse hooks for a tool call.\n */\nexport async function runPostToolUseHooks(\n  toolName: string,\n  toolInput: Record<string, unknown>,\n  toolOutput: unknown,\n  baseDir?: string\n): Promise<PostToolUseResult> {\n  const config = await loadHookConfig(baseDir);\n  const hooks = config.hooks.PostToolUse || [];\n\n  for (const hook of hooks) {\n    if (!matchesHook(toolName, hook)) continue;\n\n    const stdinData = JSON.stringify({ tool: toolName, input: toolInput, output: toolOutput });\n    const result = await executeHookCommand(hook.command, stdinData, hook.timeout || 10000);\n\n    if (result.message) {\n      return { message: result.message };\n    }\n  }\n\n  return {};\n}\n", "/**\n * Git Worktree Isolation for Parallel Agent Work\n *\n * Creates isolated git worktrees so subagents can work on separate branches\n * without conflicting with each other or the main working directory.\n *\n * Flow:\n * 1. enterWorktree() \u2014 creates a new worktree + branch\n * 2. Agent works in the isolated directory\n * 3. exitWorktree() \u2014 if changes made, returns branch name for merge; if no changes, cleans up\n */\n\nimport { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { rm } from 'node:fs/promises';\n\nexport interface WorktreeInfo {\n  worktreePath: string;\n  branchName: string;\n  baseBranch: string;\n  createdAt: string;\n}\n\n/** Active worktrees tracked in memory */\nconst activeWorktrees = new Map<string, WorktreeInfo>();\n\nfunction git(cmd: string, cwd: string): string {\n  return execSync(`git ${cmd}`, { cwd, encoding: 'utf8', timeout: 30000 }).trim();\n}\n\nfunction isGitRepo(dir: string): boolean {\n  try {\n    git('rev-parse --is-inside-work-tree', dir);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nfunction getCurrentBranch(cwd: string): string {\n  try {\n    return git('rev-parse --abbrev-ref HEAD', cwd);\n  } catch {\n    return 'main';\n  }\n}\n\nfunction hasUncommittedChanges(cwd: string): boolean {\n  try {\n    const status = git('status --porcelain', cwd);\n    return status.length > 0;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Create an isolated git worktree for an agent to work in.\n * Returns the worktree path and branch name.\n */\nexport function enterWorktree(\n  projectDir: string,\n  opts?: { branchPrefix?: string; agentId?: string }\n): WorktreeInfo {\n  const cwd = resolve(projectDir);\n  if (!isGitRepo(cwd)) {\n    throw new Error('Not a git repository \u2014 cannot create worktree');\n  }\n\n  const baseBranch = getCurrentBranch(cwd);\n  const prefix = opts?.branchPrefix || 'crew-agent';\n  const suffix = (opts?.agentId || randomUUID()).slice(0, 8);\n  const branchName = `${prefix}/${suffix}`;\n\n  // Worktrees go in .crew/worktrees/\n  const worktreeBase = join(cwd, '.crew', 'worktrees');\n  const worktreePath = join(worktreeBase, suffix);\n\n  // Create the worktree with a new branch\n  try {\n    execSync(`mkdir -p \"${worktreeBase}\"`, { cwd });\n    git(`worktree add -b \"${branchName}\" \"${worktreePath}\" HEAD`, cwd);\n  } catch (err) {\n    throw new Error(`Failed to create worktree: ${(err as Error).message}`);\n  }\n\n  const info: WorktreeInfo = {\n    worktreePath,\n    branchName,\n    baseBranch,\n    createdAt: new Date().toISOString()\n  };\n\n  activeWorktrees.set(branchName, info);\n  return info;\n}\n\n/**\n * Exit a worktree. If changes were made, keeps the branch for merging.\n * If no changes, cleans up the worktree and branch entirely.\n *\n * Returns: { hasChanges, branchName, commitCount }\n */\nexport async function exitWorktree(\n  projectDir: string,\n  branchName: string\n): Promise<{ hasChanges: boolean; branchName: string; commitCount: number; worktreePath?: string }> {\n  const cwd = resolve(projectDir);\n  const info = activeWorktrees.get(branchName);\n\n  if (!info) {\n    throw new Error(`No active worktree found for branch: ${branchName}`);\n  }\n\n  const wt = info.worktreePath;\n\n  // Check if any commits were made on the branch beyond the base\n  let commitCount = 0;\n  try {\n    const log = git(`log ${info.baseBranch}..${branchName} --oneline`, cwd);\n    commitCount = log ? log.split('\\n').filter(l => l.trim()).length : 0;\n  } catch {\n    commitCount = 0;\n  }\n\n  // Check for uncommitted changes in the worktree\n  const uncommitted = existsSync(wt) && hasUncommittedChanges(wt);\n\n  // If uncommitted changes, auto-commit them\n  if (uncommitted) {\n    try {\n      git('add -A', wt);\n      git('commit -m \"Auto-commit: agent work in progress\"', wt);\n      commitCount++;\n    } catch {\n      // Commit failed (maybe nothing to commit after all)\n    }\n  }\n\n  const hasChanges = commitCount > 0;\n\n  // Remove the worktree\n  try {\n    git(`worktree remove \"${wt}\" --force`, cwd);\n  } catch {\n    // Manual cleanup if git worktree remove fails\n    try {\n      await rm(wt, { recursive: true, force: true });\n      git('worktree prune', cwd);\n    } catch { /* best effort */ }\n  }\n\n  // If no changes, also delete the branch\n  if (!hasChanges) {\n    try {\n      git(`branch -D \"${branchName}\"`, cwd);\n    } catch { /* branch might not exist */ }\n  }\n\n  activeWorktrees.delete(branchName);\n\n  return {\n    hasChanges,\n    branchName,\n    commitCount,\n    worktreePath: hasChanges ? wt : undefined\n  };\n}\n\n/**\n * List all active worktrees.\n */\nexport function listWorktrees(): WorktreeInfo[] {\n  return [...activeWorktrees.values()];\n}\n\n/**\n * Merge a worktree branch back into the base branch.\n */\nexport function mergeWorktree(\n  projectDir: string,\n  branchName: string,\n  strategy: 'merge' | 'squash' = 'squash'\n): { success: boolean; message: string } {\n  const cwd = resolve(projectDir);\n\n  try {\n    if (strategy === 'squash') {\n      git(`merge --squash \"${branchName}\"`, cwd);\n      git(`commit -m \"Merge agent work from ${branchName}\"`, cwd);\n    } else {\n      git(`merge \"${branchName}\" --no-edit`, cwd);\n    }\n\n    // Clean up the branch after merge\n    try {\n      git(`branch -D \"${branchName}\"`, cwd);\n    } catch { /* already deleted */ }\n\n    return { success: true, message: `Merged ${branchName} into current branch` };\n  } catch (err) {\n    return { success: false, message: `Merge failed: ${(err as Error).message}` };\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Identity registry for all core tools.\n * Sits at the bottom of the dependency tree to prevent circular imports.\n */\n\n// ============================================================================\n// SHARED PARAMETER NAMES (used by multiple tools)\n// ============================================================================\n\nexport const PARAM_FILE_PATH = 'file_path';\nexport const PARAM_DIR_PATH = 'dir_path';\nexport const PARAM_PATTERN = 'pattern';\nexport const PARAM_CASE_SENSITIVE = 'case_sensitive';\nexport const PARAM_RESPECT_GIT_IGNORE = 'respect_git_ignore';\nexport const PARAM_RESPECT_GEMINI_IGNORE = 'respect_gemini_ignore';\nexport const PARAM_FILE_FILTERING_OPTIONS = 'file_filtering_options';\nexport const PARAM_DESCRIPTION = 'description';\n\n// ============================================================================\n// TOOL NAMES & TOOL-SPECIFIC PARAMETER NAMES\n// ============================================================================\n\n// -- glob --\nexport const GLOB_TOOL_NAME = 'glob';\n\n// -- grep_search --\nexport const GREP_TOOL_NAME = 'grep_search';\nexport const GREP_PARAM_INCLUDE_PATTERN = 'include_pattern';\nexport const GREP_PARAM_EXCLUDE_PATTERN = 'exclude_pattern';\nexport const GREP_PARAM_NAMES_ONLY = 'names_only';\nexport const GREP_PARAM_MAX_MATCHES_PER_FILE = 'max_matches_per_file';\nexport const GREP_PARAM_TOTAL_MAX_MATCHES = 'total_max_matches';\n// ripgrep only\nexport const GREP_PARAM_FIXED_STRINGS = 'fixed_strings';\nexport const GREP_PARAM_CONTEXT = 'context';\nexport const GREP_PARAM_AFTER = 'after';\nexport const GREP_PARAM_BEFORE = 'before';\nexport const GREP_PARAM_NO_IGNORE = 'no_ignore';\n\n// -- list_directory --\nexport const LS_TOOL_NAME = 'list_directory';\nexport const LS_PARAM_IGNORE = 'ignore';\n\n// -- read_file --\nexport const READ_FILE_TOOL_NAME = 'read_file';\nexport const READ_FILE_PARAM_START_LINE = 'start_line';\nexport const READ_FILE_PARAM_END_LINE = 'end_line';\n\n// -- run_shell_command --\nexport const SHELL_TOOL_NAME = 'run_shell_command';\nexport const SHELL_PARAM_COMMAND = 'command';\nexport const SHELL_PARAM_IS_BACKGROUND = 'is_background';\n\n// -- write_file --\nexport const WRITE_FILE_TOOL_NAME = 'write_file';\nexport const WRITE_FILE_PARAM_CONTENT = 'content';\n\n// -- replace (edit) --\nexport const EDIT_TOOL_NAME = 'replace';\nexport const EDIT_PARAM_INSTRUCTION = 'instruction';\nexport const EDIT_PARAM_OLD_STRING = 'old_string';\nexport const EDIT_PARAM_NEW_STRING = 'new_string';\nexport const EDIT_PARAM_ALLOW_MULTIPLE = 'allow_multiple';\n\n// -- google_web_search --\nexport const WEB_SEARCH_TOOL_NAME = 'google_web_search';\nexport const WEB_SEARCH_PARAM_QUERY = 'query';\n\n// -- write_todos --\nexport const WRITE_TODOS_TOOL_NAME = 'write_todos';\nexport const TODOS_PARAM_TODOS = 'todos';\nexport const TODOS_ITEM_PARAM_DESCRIPTION = 'description';\nexport const TODOS_ITEM_PARAM_STATUS = 'status';\n\n// -- web_fetch --\nexport const WEB_FETCH_TOOL_NAME = 'web_fetch';\nexport const WEB_FETCH_PARAM_PROMPT = 'prompt';\n\n// -- read_many_files --\nexport const READ_MANY_FILES_TOOL_NAME = 'read_many_files';\nexport const READ_MANY_PARAM_INCLUDE = 'include';\nexport const READ_MANY_PARAM_EXCLUDE = 'exclude';\nexport const READ_MANY_PARAM_RECURSIVE = 'recursive';\nexport const READ_MANY_PARAM_USE_DEFAULT_EXCLUDES = 'useDefaultExcludes';\n\n// -- save_memory --\nexport const MEMORY_TOOL_NAME = 'save_memory';\nexport const MEMORY_PARAM_FACT = 'fact';\n\n// -- get_internal_docs --\nexport const GET_INTERNAL_DOCS_TOOL_NAME = 'get_internal_docs';\nexport const DOCS_PARAM_PATH = 'path';\n\n// -- activate_skill --\nexport const ACTIVATE_SKILL_TOOL_NAME = 'activate_skill';\nexport const SKILL_PARAM_NAME = 'name';\n\n// -- ask_user --\nexport const ASK_USER_TOOL_NAME = 'ask_user';\nexport const ASK_USER_PARAM_QUESTIONS = 'questions';\n// ask_user question item params\nexport const ASK_USER_QUESTION_PARAM_QUESTION = 'question';\nexport const ASK_USER_QUESTION_PARAM_HEADER = 'header';\nexport const ASK_USER_QUESTION_PARAM_TYPE = 'type';\nexport const ASK_USER_QUESTION_PARAM_OPTIONS = 'options';\nexport const ASK_USER_QUESTION_PARAM_MULTI_SELECT = 'multiSelect';\nexport const ASK_USER_QUESTION_PARAM_PLACEHOLDER = 'placeholder';\n// ask_user option item params\nexport const ASK_USER_OPTION_PARAM_LABEL = 'label';\nexport const ASK_USER_OPTION_PARAM_DESCRIPTION = 'description';\n\n// -- exit_plan_mode --\nexport const EXIT_PLAN_MODE_TOOL_NAME = 'exit_plan_mode';\nexport const EXIT_PLAN_PARAM_PLAN_PATH = 'plan_path';\n\n// -- enter_plan_mode --\nexport const ENTER_PLAN_MODE_TOOL_NAME = 'enter_plan_mode';\nexport const PLAN_MODE_PARAM_REASON = 'reason';\n\n// -- lsp --\nexport const LSP_TOOL_NAME = 'lsp';\n\n// -- notebook_edit --\nexport const NOTEBOOK_EDIT_TOOL_NAME = 'notebook_edit';\n\n// -- spawn_agent --\nexport const SPAWN_AGENT_TOOL_NAME = 'spawn_agent';\n", "/**\n * Docker-based sandbox for safe command execution\n * Runs commands in isolated Docker containers with staged files\n */\n\nimport { execSync } from 'child_process';\nimport fs from 'fs';\nimport path from 'path';\nimport { randomUUID } from 'crypto';\n\nexport interface DockerSandboxOptions {\n  workDir: string;\n  image?: string;\n  timeout?: number;\n  env?: Record<string, string>;\n}\n\nexport interface DockerSandboxResult {\n  success: boolean;\n  output: string;\n  exitCode: number;\n  duration: number;\n}\n\nexport class DockerSandbox {\n  private readonly defaultImage = 'node:20-slim';\n  private readonly defaultTimeout = 30000; // 30 seconds\n  \n  /**\n   * Check if Docker is available and running\n   */\n  async isDockerAvailable(): Promise<boolean> {\n    try {\n      execSync('docker info', { \n        stdio: 'ignore',\n        timeout: 5000 \n      });\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Copy staged files from sandbox to temp directory\n   */\n  private async prepareTempDir(sandbox: { getPendingPaths(): string[]; state?: { branches?: Record<string, Record<string, { modified?: string }>> }; getActiveBranch(): string }, tempDir: string): Promise<number> {\n    const pendingPaths = sandbox.getPendingPaths();\n    const branch = sandbox.state?.branches?.[sandbox.getActiveBranch()];\n    \n    if (!branch) return 0;\n\n    let fileCount = 0;\n    for (const filePath of pendingPaths) {\n      const fileData = branch[filePath];\n      if (!fileData?.modified) continue;\n\n      const fullPath = path.join(tempDir, filePath);\n      const dir = path.dirname(fullPath);\n      \n      // Create directory structure\n      if (!fs.existsSync(dir)) {\n        fs.mkdirSync(dir, { recursive: true });\n      }\n\n      // Write staged content\n      fs.writeFileSync(fullPath, fileData.modified, 'utf8');\n      fileCount++;\n    }\n\n    return fileCount;\n  }\n\n  /**\n   * Run command in Docker container with staged files\n   */\n  async runCommand(\n    command: string,\n    sandbox: { getPendingPaths(): string[]; state?: { branches?: Record<string, Record<string, { modified?: string }>> }; getActiveBranch(): string },\n    options: Partial<DockerSandboxOptions> = {}\n  ): Promise<DockerSandboxResult> {\n    const startTime = Date.now();\n    const tempDir = path.join('/tmp', `crew-sandbox-${randomUUID()}`);\n    const image = options.image || this.defaultImage;\n    const timeout = options.timeout || this.defaultTimeout;\n    const workDir = options.workDir || process.cwd();\n\n    try {\n      // Create temp directory\n      fs.mkdirSync(tempDir, { recursive: true });\n      console.log(`[Docker] Created temp dir: ${tempDir}`);\n\n      // Copy staged files to temp dir\n      const fileCount = await this.prepareTempDir(sandbox, tempDir);\n      console.log(`[Docker] Copied ${fileCount} staged file(s) to sandbox`);\n\n      // Copy package.json if it exists (for npm commands)\n      const pkgPath = path.join(workDir, 'package.json');\n      if (fs.existsSync(pkgPath)) {\n        fs.copyFileSync(pkgPath, path.join(tempDir, 'package.json'));\n        console.log(`[Docker] Copied package.json`);\n      }\n\n      // Copy node_modules if npm/node command (for dependencies)\n      const needsNodeModules = /\\b(npm|node|npx)\\b/.test(command);\n      if (needsNodeModules) {\n        const nodeModulesPath = path.join(workDir, 'node_modules');\n        if (fs.existsSync(nodeModulesPath)) {\n          console.log(`[Docker] Copying node_modules (this may take a few seconds)...`);\n          execSync(`cp -r \"${nodeModulesPath}\" \"${tempDir}/\"`, {\n            stdio: 'ignore',\n            timeout: 10000\n          });\n        }\n      }\n\n      // Build environment variables\n      const envFlags = options.env \n        ? Object.entries(options.env).map(([k, v]) => `-e ${k}=\"${v}\"`).join(' ')\n        : '';\n\n      // Run command in Docker\n      console.log(`[Docker] Running: ${command}`);\n      const dockerCmd = `docker run --rm -v \"${tempDir}\":/work -w /work ${envFlags} ${image} sh -c \"${command.replace(/\"/g, '\\\\\"')}\"`;\n      \n      const output = execSync(dockerCmd, {\n        encoding: 'utf8',\n        timeout,\n        stdio: ['ignore', 'pipe', 'pipe']\n      });\n\n      const duration = Date.now() - startTime;\n      console.log(`[Docker] \u2713 Command completed in ${duration}ms`);\n\n      return {\n        success: true,\n        output,\n        exitCode: 0,\n        duration\n      };\n\n    } catch (err) {\n      const error = err as { stdout?: string; stderr?: string; message?: string; status?: number };\n      const duration = Date.now() - startTime;\n      console.log(`[Docker] \u2717 Command failed after ${duration}ms`);\n      \n      return {\n        success: false,\n        output: error.stdout || error.stderr || error.message || 'Docker command failed',\n        exitCode: error.status || 1,\n        duration\n      };\n\n    } finally {\n      // Cleanup temp directory\n      try {\n        if (fs.existsSync(tempDir)) {\n          fs.rmSync(tempDir, { recursive: true, force: true });\n          console.log(`[Docker] Cleaned up temp dir`);\n        }\n      } catch (cleanupErr) {\n        console.warn(`[Docker] Failed to cleanup ${tempDir}:`, cleanupErr);\n      }\n    }\n  }\n\n  /**\n   * Pull Docker image if not present (with progress)\n   */\n  async ensureImage(image: string = this.defaultImage): Promise<boolean> {\n    try {\n      // Check if image exists\n      execSync(`docker image inspect ${image}`, { \n        stdio: 'ignore',\n        timeout: 5000 \n      });\n      return true; // Image already exists\n    } catch {\n      // Image doesn't exist, pull it\n      console.log(`[Docker] Pulling image ${image}...`);\n      try {\n        execSync(`docker pull ${image}`, {\n          stdio: 'inherit', // Show progress\n          timeout: 120000 // 2 minutes for image pull\n        });\n        console.log(`[Docker] \u2713 Image pulled successfully`);\n        return true;\n      } catch (pullErr) {\n        console.error(`[Docker] Failed to pull image:`, pullErr);\n        return false;\n      }\n    }\n  }\n}\n", "/**\n * Adapter to use Gemini CLI tools with crew-cli's sandbox\n */\n\nimport { Sandbox } from '../../sandbox/index.js';\nimport { runPreToolUseHooks, runPostToolUseHooks } from '../../hooks/index.js';\nimport { enterWorktree, exitWorktree, mergeWorktree, listWorktrees } from '../worktree.js';\nimport { execSync } from 'node:child_process';\nimport { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport {\n  GLOB_TOOL_NAME,\n  GREP_TOOL_NAME,\n  LS_TOOL_NAME,\n  READ_FILE_TOOL_NAME,\n  SHELL_TOOL_NAME,\n  WRITE_FILE_TOOL_NAME,\n  EDIT_TOOL_NAME,\n  WEB_SEARCH_TOOL_NAME,\n  WRITE_TODOS_TOOL_NAME,\n  WEB_FETCH_TOOL_NAME,\n  READ_MANY_FILES_TOOL_NAME,\n  MEMORY_TOOL_NAME,\n  GET_INTERNAL_DOCS_TOOL_NAME,\n  ACTIVATE_SKILL_TOOL_NAME,\n  ASK_USER_TOOL_NAME,\n  EXIT_PLAN_MODE_TOOL_NAME,\n  ENTER_PLAN_MODE_TOOL_NAME\n} from './definitions/base-declarations.js';\nimport type {\n  ToolDeclarationSchema,\n  TrackerTask,\n  LspDiagnostic,\n  LspSymbol,\n  LspLocation,\n  LspCompletionItem,\n  NotebookCell,\n  Notebook,\n  SearchResponse,\n  SearchHit,\n} from '../../types/common.js';\n\n// ---------------------------------------------------------------------------\n// Human-readable activity descriptions for tool calls\n// ---------------------------------------------------------------------------\nfunction getActivityDescription(tool: string, p: Record<string, unknown>): string | null {\n  const s = (k: string) => String(p[k] || '').replace(/^.*\\//, ''); // basename\n  const f = (k: string) => String(p[k] || '');\n  switch (tool) {\n    case 'read_file':         return `Reading ${f('file_path')}`;\n    case 'read_many_files':   return `Reading ${Array.isArray(p.paths) ? p.paths.length : '?'} files`;\n    case 'write_file':        return `Writing ${f('file_path')}`;\n    case 'append_file':       return `Appending to ${f('file_path')}`;\n    case 'replace': case 'edit': return `Editing ${f('file_path')}`;\n    case 'glob':              return `Globbing ${f('pattern')}`;\n    case 'grep': case 'grep_search': case 'grep_search_ripgrep':\n                              return `Searching for \"${f('pattern')}\"${p.path ? ` in ${f('path')}` : ''}`;\n    case 'list': case 'list_directory': return `Listing ${f('dir_path') || f('path') || '.'}`;\n    case 'mkdir':             return `Creating directory ${f('path')}`;\n    case 'shell': case 'run_cmd': case 'run_shell_command':\n                              return `Running: ${f('command').slice(0, 80)}${f('command').length > 80 ? '\u2026' : ''}`;\n    case 'git':               return `git ${f('command').slice(0, 60)}`;\n    case 'google_web_search': case 'web_search':\n                              return `Searching web: \"${f('query')}\"`;\n    case 'web_fetch':         return `Fetching ${f('url').slice(0, 60)}`;\n    case 'lsp':               return `LSP ${f('action')}${p.file ? ` on ${s('file')}` : ''}`;\n    case 'notebook_edit':     return `Notebook ${f('action')} on ${s('path')}`;\n    case 'save_memory':       return `Saving memory`;\n    case 'write_todos':       return `Writing todos`;\n    case 'get_internal_docs': return `Reading internal docs`;\n    case 'spawn_agent':       return `Spawning sub-agent: ${f('task').slice(0, 60)}`;\n    case 'agent_message':     return `Messaging sub-agent ${s('session_id')}: ${f('message').slice(0, 50)}`;\n    case 'enter_worktree': case 'worktree': return `Worktree ${f('action') || 'enter'}`;\n    case 'exit_worktree':     return `Exiting worktree`;\n    case 'merge_worktree':    return `Merging worktree ${f('branch_name')}`;\n    case 'list_worktrees':    return `Listing worktrees`;\n    case 'sleep':             return `Sleeping ${p.duration_ms}ms${p.reason ? ` \u2014 ${f('reason')}` : ''}`;\n    case 'tool_search':       return `Searching tools: \"${f('query')}\"`;\n    case 'check_background_task': return `Checking background task ${f('task_id')}`;\n    case 'activate_skill':    return `Activating skill ${f('name') || f('skill')}`;\n    case 'enter_plan_mode':   return `Entering plan mode`;\n    case 'exit_plan_mode':    return `Exiting plan mode`;\n    case 'ask_user':          return null; // don't announce \u2014 the question itself is the activity\n    case 'tracker_create_task': return `Creating task: ${f('title').slice(0, 40)}`;\n    case 'tracker_update_task': return `Updating task ${f('id')}`;\n    case 'tracker_get_task':  return `Getting task ${f('id')}`;\n    case 'tracker_list_tasks': return `Listing tasks`;\n    case 'tracker_add_dependency': return `Adding dependency`;\n    case 'tracker_visualize': return `Visualizing task graph`;\n    default:                  return `${tool}`;\n  }\n}\n\n// Minimal adapter types\nexport interface ToolResult {\n  success: boolean;\n  output?: string;\n  error?: string;\n  handled?: boolean;       // false = worker must address this error\n  recovery?: string;       // hint for how to fix (e.g. \"call read_file first\")\n}\n\n// ---------------------------------------------------------------------------\n// Constraint levels \u2014 filter tools by worker trust\n// ---------------------------------------------------------------------------\nexport type ConstraintLevel = 'read-only' | 'edit' | 'full';\n\nconst READ_ONLY_TOOLS = new Set([\n  'read_file', 'read_many_files', 'glob', 'grep_search', 'grep_search_ripgrep',\n  'list_directory', 'list', 'get_internal_docs', 'web_fetch', 'google_web_search',\n  'web_search', 'grep', 'save_memory', 'write_todos',\n  'tracker_get_task', 'tracker_list_tasks', 'tracker_visualize',\n  'check_background_task', 'ask_user', 'enter_plan_mode', 'exit_plan_mode',\n  'lsp', 'git',  // git is read-safe (force-push/--no-verify already blocked)\n  'sleep', 'tool_search'  // sleep and tool_search are safe at any constraint level\n]);\n\nconst EDIT_TOOLS = new Set([\n  ...READ_ONLY_TOOLS,\n  'replace', 'edit', 'append_file',\n  'run_shell_command', 'shell', 'run_cmd',\n  'tracker_create_task', 'tracker_update_task', 'tracker_add_dependency',\n  'mkdir', 'activate_skill',\n  'worktree', 'enter_worktree', 'exit_worktree', 'merge_worktree', 'list_worktrees',\n  'notebook_edit'\n]);\n\nconst FULL_TOOLS = new Set([\n  ...EDIT_TOOLS,\n  'write_file', 'spawn_agent', 'agent_message'\n]);\n\nfunction toolAllowedAtLevel(toolName: string, level: ConstraintLevel): boolean {\n  switch (level) {\n    case 'read-only': return READ_ONLY_TOOLS.has(toolName);\n    case 'edit':      return EDIT_TOOLS.has(toolName);\n    case 'full':      return FULL_TOOLS.has(toolName);\n    default:          return true;\n  }\n}\n\n/** Simple Levenshtein distance (no external deps) */\nfunction levenshteinDistance(a: string, b: string): number {\n  if (a === b) return 0;\n  if (a.length === 0) return b.length;\n  if (b.length === 0) return a.length;\n  // Use two rows for space efficiency\n  let prev = Array.from({ length: b.length + 1 }, (_, i) => i);\n  let curr = new Array(b.length + 1);\n  for (let i = 1; i <= a.length; i++) {\n    curr[0] = i;\n    for (let j = 1; j <= b.length; j++) {\n      const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n      curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);\n    }\n    [prev, curr] = [curr, prev];\n  }\n  return prev[b.length];\n}\n\n/** Map persona names to constraint levels */\nexport function constraintLevelForPersona(persona: string): ConstraintLevel {\n  const lower = persona.toLowerCase();\n  // In standalone crew-cli, all personas run locally and need file access.\n  // Read-only is only for pure analysis personas that should never write.\n  if (lower.includes('planner') || lower.includes('architect')) {\n    return 'read-only';\n  }\n  // All execution personas get full access \u2014 they need to create files,\n  // write tests, edit code, and run commands.\n  return 'full';\n}\n\n// Create config adapter for Gemini tools\nexport class CrewConfig {\n  constructor(private workspaceRoot: string) {}\n  \n  getWorkspaceRoot() {\n    return this.workspaceRoot;\n  }\n  \n  getTargetDir() {\n    return this.workspaceRoot;\n  }\n}\n\n// Create message bus adapter (auto-approve for CLI)\nexport class CrewMessageBus {\n  async requestConfirmation(): Promise<{ status: 'approved' }> {\n    return { status: 'approved' }; // Auto-approve for CLI\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Error helpers\n// ---------------------------------------------------------------------------\n\n/** Extract a message string from an unknown caught error */\nfunction errMsg(err: unknown): string {\n  if (err instanceof Error) return err.message;\n  return String(err);\n}\n\n/** Extract shell command stderr/stdout from Node child_process errors */\nfunction errShell(err: unknown): string {\n  const e = err as Record<string, unknown>;\n  const stdout = typeof e?.stdout === 'string' ? e.stdout : (e?.stdout as Buffer | undefined)?.toString?.() ?? '';\n  const stderr = typeof e?.stderr === 'string' ? e.stderr : (e?.stderr as Buffer | undefined)?.toString?.() ?? '';\n  return `${stdout}\\n${stderr}`.trim();\n}\n\n// Shell timeout: configurable via CREW_SHELL_TIMEOUT env (seconds), default 120s, max 600s\nfunction getShellTimeout(): number {\n  const envVal = parseInt(process.env.CREW_SHELL_TIMEOUT || '', 10);\n  if (envVal > 0) return Math.min(envVal * 1000, 600000); // max 600s\n  return 120000; // default 120s\n}\n\n// Dangerous shell commands that should warn (matches Claude Code behavior)\nconst DANGEROUS_SHELL_PATTERNS = [\n  /\\brm\\s+-rf?\\s/,           // rm -r / rm -rf\n  /\\bgit\\s+push\\s+.*--force/, // force push\n  /\\bgit\\s+reset\\s+--hard/,   // hard reset\n  /\\bgit\\s+clean\\s+-f/,       // clean untracked\n  /\\bdrop\\s+table\\b/i,        // SQL drop\n  /\\bdrop\\s+database\\b/i,     // SQL drop database\n  /\\bkill\\s+-9\\b/,            // kill -9\n  /\\bmkfs\\b/,                 // format filesystem\n  /\\bdd\\s+if=/,               // dd (disk destroyer)\n];\n\n// Background shell processes tracked by ID\nconst _backgroundProcesses = new Map<string, { promise: Promise<ToolResult>; startedAt: number }>();\n\nfunction extractVerificationCommands(task: string): string[] {\n  const commands = new Set<string>();\n  for (const line of String(task || '').split('\\n')) {\n    const trimmed = line.trim();\n    const explicit = trimmed.match(/^(?:[-*]\\s*)?(?:run|execute)\\s+(.+)$/i);\n    if (explicit?.[1] && looksLikeVerificationCommand(explicit[1].trim())) {\n      commands.add(explicit[1].trim());\n    }\n    for (const match of trimmed.matchAll(/`([^`]+)`/g)) {\n      const command = match[1]?.trim();\n      if (command && looksLikeVerificationCommand(command)) commands.add(command);\n    }\n  }\n  return [...commands];\n}\n\nfunction looksLikeVerificationCommand(value: string): boolean {\n  return /^(npm|pnpm|yarn|bun|node|pytest|jest|vitest|cargo|go|make|\\.\\/|bash|sh)\\b/.test(value);\n}\n\n// Main adapter class\nexport class GeminiToolAdapter {\n  private config: CrewConfig;\n  private messageBus: CrewMessageBus;\n  private _filesRead = new Set<string>(); // Track reads for read-before-edit guard\n  private _constraintLevel: ConstraintLevel;\n\n  private _realWorkspaceRoot: string | null = null;\n\n  constructor(private sandbox: Sandbox, constraintLevel: ConstraintLevel = 'full') {\n    const workspaceRoot = sandbox.getBaseDir() || process.cwd();\n    this.config = new CrewConfig(workspaceRoot);\n    this.messageBus = new CrewMessageBus();\n    this._constraintLevel = constraintLevel;\n  }\n\n  /** Resolve workspace root through symlinks (macOS /tmp \u2192 /private/tmp) */\n  private getRealWorkspaceRoot(): string {\n    if (this._realWorkspaceRoot) return this._realWorkspaceRoot;\n    const raw = this.config.getWorkspaceRoot();\n    try {\n      const { realpathSync } = require('node:fs');\n      this._realWorkspaceRoot = realpathSync(raw);\n    } catch {\n      this._realWorkspaceRoot = resolve(raw);\n    }\n    return this._realWorkspaceRoot!;\n  }\n\n  /** Check if a resolved path is within workspace. Handles symlinks. */\n  private isInsideWorkspace(resolvedPath: string): boolean {\n    const root = this.getRealWorkspaceRoot();\n    let realPath: string;\n    try {\n      const { realpathSync } = require('node:fs');\n      realPath = realpathSync(resolvedPath);\n    } catch {\n      realPath = resolvedPath;\n    }\n    return realPath.startsWith(root + '/') || realPath === root;\n  }\n\n  get constraintLevel(): ConstraintLevel {\n    return this._constraintLevel;\n  }\n\n  private buildDynamicDeclarations(): ToolDeclarationSchema[] {\n    // Pull canonical names from Gemini base declarations and hydrate schemas from static declarations.\n    const staticDecls = this.getStaticToolDeclarations();\n    const staticByName = new Map<string, ToolDeclarationSchema>(staticDecls.map((d) => [d.name, d as ToolDeclarationSchema]));\n    const canonicalNames = [\n      READ_FILE_TOOL_NAME,\n      WRITE_FILE_TOOL_NAME,\n      EDIT_TOOL_NAME,\n      GLOB_TOOL_NAME,\n      GREP_TOOL_NAME,\n      LS_TOOL_NAME,\n      SHELL_TOOL_NAME,\n      WEB_SEARCH_TOOL_NAME,\n      WEB_FETCH_TOOL_NAME,\n      READ_MANY_FILES_TOOL_NAME,\n      MEMORY_TOOL_NAME,\n      WRITE_TODOS_TOOL_NAME,\n      GET_INTERNAL_DOCS_TOOL_NAME,\n      ACTIVATE_SKILL_TOOL_NAME,\n      ASK_USER_TOOL_NAME,\n      ENTER_PLAN_MODE_TOOL_NAME,\n      EXIT_PLAN_MODE_TOOL_NAME,\n      'grep_search_ripgrep',\n      'tracker_create_task',\n      'tracker_update_task',\n      'tracker_get_task',\n      'tracker_list_tasks',\n      'tracker_add_dependency',\n      'tracker_visualize',\n      'spawn_agent',\n      'agent_message',\n      'notebook_edit',\n      'check_background_task',\n      'worktree',\n      'sleep',\n      'tool_search'\n    ];\n    const canonical = canonicalNames.map((name) => {\n      const found = staticByName.get(name);\n      if (found) return found;\n      return {\n        name,\n        description: `${name} tool`,\n        parameters: { type: 'object', properties: {} }\n      };\n    });\n\n    const aliases = [\n      { alias: 'read_file', target: 'read_file' },\n      { alias: 'write_file', target: 'write_file' },\n      { alias: 'append_file', target: 'write_file' },\n      { alias: 'edit', target: 'replace' },\n      { alias: 'replace', target: 'replace' },\n      { alias: 'glob', target: 'glob' },\n      { alias: 'grep', target: 'grep_search' },\n      { alias: 'grep_search', target: 'grep_search' },\n      { alias: 'grep_search_ripgrep', target: 'grep_search_ripgrep' },\n      { alias: 'list', target: 'list_directory' },\n      { alias: 'list_directory', target: 'list_directory' },\n      { alias: 'shell', target: 'run_shell_command' },\n      { alias: 'run_cmd', target: 'run_shell_command' },\n      { alias: 'run_shell_command', target: 'run_shell_command' },\n      { alias: 'web_search', target: 'google_web_search' },\n      { alias: 'google_web_search', target: 'google_web_search' },\n      { alias: 'web_fetch', target: 'web_fetch' },\n      { alias: 'save_memory', target: 'save_memory' },\n      { alias: 'write_todos', target: 'write_todos' },\n      { alias: 'get_internal_docs', target: 'get_internal_docs' },\n      { alias: 'ask_user', target: 'ask_user' },\n      { alias: 'enter_plan_mode', target: 'enter_plan_mode' },\n      { alias: 'exit_plan_mode', target: 'exit_plan_mode' },\n      { alias: 'activate_skill', target: 'activate_skill' },\n      { alias: 'tracker_create_task', target: 'tracker_create_task' },\n      { alias: 'tracker_update_task', target: 'tracker_update_task' },\n      { alias: 'tracker_get_task', target: 'tracker_get_task' },\n      { alias: 'tracker_list_tasks', target: 'tracker_list_tasks' },\n      { alias: 'tracker_add_dependency', target: 'tracker_add_dependency' },\n      { alias: 'tracker_visualize', target: 'tracker_visualize' },\n      { alias: 'mkdir', target: 'write_file' },\n      { alias: 'git', target: 'run_shell_command' },\n      // LSP is not yet implemented \u2014 don't alias to read_file (misleads the model)\n      // { alias: 'lsp', target: 'read_file' }\n    ];\n\n    const byName = new Map<string, ToolDeclarationSchema>();\n    for (const decl of canonical) byName.set(decl.name, decl as ToolDeclarationSchema);\n    for (const a of aliases) {\n      const target = byName.get(a.target);\n      if (!target) continue;\n      if (!byName.has(a.alias)) {\n        byName.set(a.alias, { ...target, name: a.alias });\n      }\n    }\n    // Local compatibility schemas for non-Gemini built-ins we support in adapter.\n    byName.set('mkdir', {\n      name: 'mkdir',\n      description: 'Create a directory path (staged via sandbox).',\n      parameters: {\n        type: 'object',\n        properties: {\n          path: { type: 'string', description: 'Directory path to create' },\n          dir_path: { type: 'string', description: 'Alternative directory path field' }\n        }\n      }\n    });\n    byName.set('git', {\n      name: 'git',\n      description: 'Run limited git subcommands (status/diff/log/add/commit/show/branch).',\n      parameters: {\n        type: 'object',\n        properties: {\n          command: { type: 'string', description: 'Git subcommand and args' }\n        },\n        required: ['command']\n      }\n    });\n    byName.set('lsp', {\n      name: 'lsp',\n      description: 'Language Server Protocol code intelligence: diagnostics, go-to-definition, find references, hover type info, completions. Uses TypeScript language service or grep-based fallback.',\n      parameters: {\n        type: 'object',\n        properties: {\n          action: { type: 'string', enum: ['diagnostics', 'definition', 'references', 'hover', 'completions'], description: 'LSP action' },\n          file: { type: 'string', description: 'Source file path' },\n          line: { type: 'number', description: '1-based line number' },\n          column: { type: 'number', description: '1-based column number' },\n          symbol: { type: 'string', description: 'Symbol name for grep-based lookups' }\n        },\n        required: ['action', 'file']\n      }\n    });\n    byName.set('notebook_edit', {\n      name: 'notebook_edit',\n      description: 'Edit Jupyter notebooks (.ipynb files). Actions: read, add_cell, edit_cell, delete_cell, run_cell.',\n      parameters: {\n        type: 'object',\n        properties: {\n          action: { type: 'string', enum: ['add_cell', 'edit_cell', 'delete_cell', 'run_cell', 'read'], description: 'Notebook action' },\n          path: { type: 'string', description: 'Path to .ipynb file' },\n          index: { type: 'number', description: '0-based cell index' },\n          cell_type: { type: 'string', enum: ['code', 'markdown'], description: 'Cell type for add_cell' },\n          content: { type: 'string', description: 'Cell source content for add_cell/edit_cell' }\n        },\n        required: ['action', 'path']\n      }\n    });\n    return Array.from(byName.values());\n  }\n\n  private getStaticToolDeclarations() {\n    return [\n      { name: 'read_file', description: 'Read file', parameters: { type: 'object', properties: { file_path: { type: 'string' } }, required: ['file_path'] } },\n      { name: 'write_file', description: 'Write file', parameters: { type: 'object', properties: { file_path: { type: 'string' }, content: { type: 'string' } }, required: ['file_path', 'content'] } },\n      { name: 'replace', description: 'Replace text in file. old_string must uniquely match one location (use replace_all:true for all occurrences). You MUST read_file before editing.', parameters: { type: 'object', properties: { file_path: { type: 'string' }, old_string: { type: 'string' }, new_string: { type: 'string' }, replace_all: { type: 'boolean', description: 'Replace ALL occurrences (useful for renames). Default: false (unique match required)' } }, required: ['file_path', 'old_string', 'new_string'] } },\n      { name: 'glob', description: 'Glob search', parameters: { type: 'object', properties: { pattern: { type: 'string' } }, required: ['pattern'] } },\n      { name: 'grep_search', description: 'Search for regex/text in files. Supports output modes (content/files/count), context lines, case insensitivity, file type filters.', parameters: { type: 'object', properties: { pattern: { type: 'string' }, path: { type: 'string' }, dir_path: { type: 'string' }, output_mode: { type: 'string', description: 'content (matching lines), files (file paths only), count (match counts)' }, context: { type: 'number', description: 'Lines of context around matches' }, before: { type: 'number' }, after: { type: 'number' }, case_insensitive: { type: 'boolean' }, type: { type: 'string', description: 'File type filter (js, py, ts, go, etc.)' }, max_results: { type: 'number' } }, required: ['pattern'] } },\n      { name: 'grep_search_ripgrep', description: 'Alias for grep_search with same capabilities', parameters: { type: 'object', properties: { pattern: { type: 'string' }, path: { type: 'string' }, dir_path: { type: 'string' }, output_mode: { type: 'string' }, context: { type: 'number' }, case_insensitive: { type: 'boolean' }, type: { type: 'string' }, max_results: { type: 'number' } }, required: ['pattern'] } },\n      { name: 'list_directory', description: 'List directory', parameters: { type: 'object', properties: { dir_path: { type: 'string' }, path: { type: 'string' } } } },\n      { name: 'run_shell_command', description: 'Run shell command (configurable timeout, Docker isolation when staged files exist). Use run_in_background:true for long-running commands.', parameters: { type: 'object', properties: { command: { type: 'string' }, run_in_background: { type: 'boolean', description: 'Run in background and return task ID. Use check_background_task to get result.' }, description: { type: 'string', description: 'Brief description of what the command does' } }, required: ['command'] } },\n      { name: 'google_web_search', description: 'Web search', parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } },\n      { name: 'web_fetch', description: 'Fetch URL', parameters: { type: 'object', properties: { url: { type: 'string' }, prompt: { type: 'string' } } } },\n      { name: 'read_many_files', description: 'Read many files', parameters: { type: 'object', properties: { include: { type: 'string' }, exclude: { type: 'string' }, recursive: { type: 'boolean' } } } },\n      { name: 'save_memory', description: 'Save memory fact', parameters: { type: 'object', properties: { fact: { type: 'string' } }, required: ['fact'] } },\n      { name: 'write_todos', description: 'Write todos', parameters: { type: 'object', properties: { todos: { type: 'array', items: { type: 'object', properties: { text: { type: 'string' }, done: { type: 'boolean' } } } } }, required: ['todos'] } },\n      { name: 'get_internal_docs', description: 'Read internal docs', parameters: { type: 'object', properties: { path: { type: 'string' } } } },\n      { name: 'ask_user', description: 'Ask user placeholder', parameters: { type: 'object', properties: { questions: { type: 'array', items: { type: 'object', properties: { question: { type: 'string' } } } } } } },\n      { name: 'enter_plan_mode', description: 'Enter plan mode', parameters: { type: 'object', properties: { reason: { type: 'string' } } } },\n      { name: 'exit_plan_mode', description: 'Exit plan mode', parameters: { type: 'object', properties: { plan_path: { type: 'string' } } } },\n      { name: 'activate_skill', description: 'Activate skill', parameters: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] } },\n      { name: 'tracker_create_task', description: 'Create tracker task', parameters: { type: 'object', properties: { title: { type: 'string' }, description: { type: 'string' }, type: { type: 'string' }, parentId: { type: 'string' }, dependencies: { type: 'array', items: { type: 'string' } } }, required: ['title', 'description', 'type'] } },\n      { name: 'tracker_update_task', description: 'Update tracker task', parameters: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },\n      { name: 'tracker_get_task', description: 'Get tracker task', parameters: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },\n      { name: 'tracker_list_tasks', description: 'List tracker tasks', parameters: { type: 'object', properties: { status: { type: 'string' }, type: { type: 'string' }, parentId: { type: 'string' } } } },\n      { name: 'tracker_add_dependency', description: 'Add tracker dependency', parameters: { type: 'object', properties: { taskId: { type: 'string' }, dependencyId: { type: 'string' } }, required: ['taskId', 'dependencyId'] } },\n      { name: 'tracker_visualize', description: 'Visualize tracker graph', parameters: { type: 'object', properties: {} } },\n      { name: 'spawn_agent', description: 'Spawn a sub-agent to handle a task autonomously. Returns a session_id you can use with agent_message for follow-up conversations. The sub-agent runs in an isolated sandbox branch with a cheaper model.', parameters: { type: 'object', properties: { task: { type: 'string', description: 'Clear task description for the sub-agent' }, tools: { type: 'array', items: { type: 'string' }, description: 'Optional subset of tool names the sub-agent may use' }, maxTurns: { type: 'number', description: 'Max turns for sub-agent (default: 15, max: 25)' }, model: { type: 'string', description: 'Optional model override (default: cheapest configured model)' } }, required: ['task'] } },\n      { name: 'agent_message', description: 'Send a follow-up message to an existing sub-agent session. The sub-agent resumes with its full prior conversation context and file access. Use this for multi-turn collaboration: spawn an agent, review its work, then send corrections or next steps.', parameters: { type: 'object', properties: { session_id: { type: 'string', description: 'Session ID returned by spawn_agent' }, message: { type: 'string', description: 'Follow-up message or instruction for the sub-agent' }, max_turns: { type: 'number', description: 'Max turns for this follow-up (default: 10, max: 25)' } }, required: ['session_id', 'message'] } },\n      { name: 'notebook_edit', description: 'Edit Jupyter notebooks (.ipynb files). Actions: read (view structure), add_cell, edit_cell, delete_cell, run_cell.', parameters: { type: 'object', properties: { action: { type: 'string', enum: ['add_cell', 'edit_cell', 'delete_cell', 'run_cell', 'read'], description: 'Notebook action' }, path: { type: 'string', description: 'Path to .ipynb file' }, index: { type: 'number', description: '0-based cell index' }, cell_type: { type: 'string', enum: ['code', 'markdown'], description: 'Cell type for add_cell' }, content: { type: 'string', description: 'Cell source content for add_cell/edit_cell' } }, required: ['action', 'path'] } },\n      { name: 'check_background_task', description: 'Check the status/result of a background shell command. Returns result if done, or elapsed time if still running.', parameters: { type: 'object', properties: { task_id: { type: 'string', description: 'Task ID returned by run_shell_command with run_in_background:true' } }, required: ['task_id'] } },\n      { name: 'worktree', description: 'Manage git worktrees to isolate agent work on separate branches. Actions: enter (create), exit (remove), merge (merge branch), list (list active).', parameters: { type: 'object', properties: { action: { type: 'string', enum: ['enter', 'exit', 'merge', 'list'], description: 'Worktree action' }, branch: { type: 'string', description: 'Branch name for enter/exit/merge' }, merge: { type: 'boolean', description: 'Merge on exit (default: true)' }, projectDir: { type: 'string', description: 'Override project directory' } }, required: ['action'] } },\n      { name: 'sleep', description: 'Pause execution for a specified duration (max 60s). Useful for polling, rate limiting, or waiting for external processes.', parameters: { type: 'object', properties: { duration_ms: { type: 'number', description: 'Sleep duration in milliseconds (max 60000)' }, reason: { type: 'string', description: 'Why the agent is sleeping' } }, required: ['duration_ms'] } },\n      { name: 'tool_search', description: 'Search the tool registry to discover available tools by name or capability. Returns tool names, descriptions, and parameter schemas.', parameters: { type: 'object', properties: { query: { type: 'string', description: 'Search term matched against tool name and description' }, max_results: { type: 'number', description: 'Max results to return (default: 10)' } }, required: ['query'] } }\n    ];\n  }\n\n  /**\n   * Execute a tool call from LLM (with PreToolUse/PostToolUse hooks)\n   */\n  async executeTool(toolName: string, params: Record<string, unknown>): Promise<ToolResult> {\n    // Constraint level enforcement \u2014 hard block even if LLM hallucinates a removed tool\n    if (!toolAllowedAtLevel(toolName, this._constraintLevel)) {\n      return {\n        success: false,\n        error: `Tool \"${toolName}\" is not available at constraint level \"${this._constraintLevel}\". Use allowed tools only.`,\n        handled: false,\n        recovery: this._constraintLevel === 'read-only'\n          ? 'This is a read-only worker. Use read_file, grep_search, glob, or list_directory.'\n          : 'This is an edit worker. Use replace/edit for changes, not write_file.'\n      };\n    }\n\n    // Print human-readable activity description\n    const activity = getActivityDescription(toolName, params);\n    if (activity) process.stdout.write(`\\x1b[90m  \u2699 ${activity}\\x1b[0m\\n`);\n\n    // Run PreToolUse hooks\n    const preResult = await runPreToolUseHooks(toolName, params);\n    if (preResult.decision === 'deny') {\n      return { success: false, error: `Blocked by hook: ${preResult.reason || 'denied'}` };\n    }\n    // Allow hooks to modify input\n    const effectiveParams = (preResult.updatedInput || params) as Record<string, unknown>;\n\n    const result = await this._executeTool(toolName, effectiveParams);\n\n    // Run PostToolUse hooks (fire-and-forget, don't block)\n    runPostToolUseHooks(toolName, effectiveParams, result).catch(() => {});\n\n    return result;\n  }\n\n  private async _executeTool(toolName: string, params: Record<string, unknown>): Promise<ToolResult> {\n    const asString = (value: unknown): string => typeof value === 'string' ? value : '';\n    const asOptionalString = (value: unknown): string | undefined => typeof value === 'string' ? value : undefined;\n    const asNumber = (value: unknown): number | undefined => typeof value === 'number' ? value : undefined;\n    const asBoolean = (value: unknown): boolean | undefined => typeof value === 'boolean' ? value : undefined;\n    const asUnknownArray = (value: unknown): unknown[] => Array.isArray(value) ? value : [];\n    try {\n      switch (toolName) {\n        // Canonical Gemini names + local aliases\n        case 'write_file':\n          return await this.writeFile({\n            file_path: asString(params.file_path),\n            content: asString(params.content)\n          });\n        case 'replace':\n          return await this.editFile({\n            file_path: asString(params.file_path),\n            old_string: asString(params.old_string),\n            new_string: asString(params.new_string),\n            replace_all: asBoolean(params.replace_all)\n          });\n        case 'append_file':\n          return await this.appendFile({\n            file_path: asString(params.file_path),\n            content: asString(params.content)\n          });\n        case 'read_file':\n          return await this.readFile({\n            file_path: asString(params.file_path),\n            start_line: asNumber(params.start_line),\n            end_line: asNumber(params.end_line)\n          });\n        case 'edit':\n          return await this.editFile({\n            file_path: asString(params.file_path),\n            old_string: asString(params.old_string),\n            new_string: asString(params.new_string),\n            replace_all: asBoolean(params.replace_all)\n          });\n        case 'read_many_files':\n          return await this.readManyFilesTool(params);\n        case 'save_memory':\n          return await this.saveMemoryTool({ fact: asString(params.fact) });\n        case 'write_todos':\n          return await this.writeTodosTool({ todos: asUnknownArray(params.todos) });\n        case 'get_internal_docs':\n          return await this.getInternalDocsTool(params);\n        case 'ask_user':\n          return await this.askUserTool(params);\n        case 'enter_plan_mode':\n          return await this.enterPlanModeTool(params);\n        case 'exit_plan_mode':\n          return await this.exitPlanModeTool(params);\n        case 'activate_skill':\n          return await this.activateSkillTool(params);\n        case 'mkdir':\n          return await this.mkdirTool(params);\n        case 'list':\n          return await this.listTool(params);\n        case 'list_directory':\n          return await this.listTool({ dir_path: asString(params.dir_path) || asString(params.path) });\n        case 'glob':\n          return await this.globTool({ pattern: asString(params.pattern) });\n        case 'grep':\n          return await this.grepTool({\n            pattern: asString(params.pattern),\n            path: asOptionalString(params.path),\n            output_mode: params.output_mode as 'content' | 'files' | 'count' | undefined,\n            context: asNumber(params.context),\n            before: asNumber(params.before),\n            after: asNumber(params.after),\n            case_insensitive: asBoolean(params.case_insensitive),\n            type: asOptionalString(params.type),\n            max_results: asNumber(params.max_results)\n          });\n        case 'grep_search':\n        case 'grep_search_ripgrep':\n          return await this.grepTool({\n            pattern: asString(params.pattern),\n            path: asOptionalString(params.dir_path) || asOptionalString(params.path),\n            output_mode: params.output_mode as 'content' | 'files' | 'count' | undefined,\n            context: asNumber(params.context),\n            before: asNumber(params.before),\n            after: asNumber(params.after),\n            case_insensitive: asBoolean(params.case_insensitive),\n            type: asOptionalString(params.type),\n            max_results: asNumber(params.max_results)\n          });\n        case 'git':\n          return await this.gitTool({ command: asString(params.command) });\n        case 'shell':\n        case 'run_cmd':\n        case 'run_shell_command':\n          // Flush staged sandbox changes to disk before running shell commands\n          // so the command can see edits made by write_file/replace/edit\n          if (this.sandbox.getPendingPaths().length > 0) {\n            await this.sandbox.apply();\n          }\n          return await this.shellTool({\n            command: asString(params.command),\n            run_in_background: asBoolean(params.run_in_background),\n            description: asOptionalString(params.description)\n          });\n        case 'lsp':\n          return await this.lspTool(params);\n        case 'notebook_edit':\n          return await this.notebookEditTool({\n            action: asString(params.action),\n            path: asString(params.path),\n            index: asNumber(params.index),\n            cell_type: params.cell_type as 'code' | 'markdown' | undefined,\n            content: asOptionalString(params.content)\n          });\n        case 'web_search':\n        case 'google_web_search':\n          return await this.webSearchTool({ query: asString(params.query) });\n        case 'web_fetch':\n          return await this.webFetchTool({ url: asString(params.url) });\n        case 'tracker_create_task':\n          return await this.trackerCreateTaskTool(params);\n        case 'tracker_update_task':\n          return await this.trackerUpdateTaskTool(params);\n        case 'tracker_get_task':\n          return await this.trackerGetTaskTool(params);\n        case 'tracker_list_tasks':\n          return await this.trackerListTasksTool(params);\n        case 'tracker_add_dependency':\n          return await this.trackerAddDependencyTool(params);\n        case 'tracker_visualize':\n          return await this.trackerVisualizeTool();\n        case 'spawn_agent':\n          return await this.spawnAgentTool({\n            task: asString(params.task),\n            model: asOptionalString(params.model),\n            max_turns: asNumber(params.max_turns)\n          });\n        case 'agent_message':\n          return await this.agentMessageTool({\n            session_id: asString(params.session_id),\n            message: asString(params.message),\n            max_turns: asNumber(params.max_turns)\n          });\n        case 'check_background_task':\n          return await this.checkBackgroundTask({ task_id: asString(params.task_id) });\n        case 'enter_worktree':\n          return this.enterWorktreeTool({\n            branch_prefix: asOptionalString(params.branch_prefix),\n            agent_id: asOptionalString(params.agent_id)\n          });\n        case 'exit_worktree':\n          return await this.exitWorktreeTool({ branch_name: asString(params.branch_name) });\n        case 'merge_worktree':\n          return this.mergeWorktreeTool({\n            branch_name: asString(params.branch_name),\n            strategy: params.strategy as 'merge' | 'squash' | undefined\n          });\n        case 'list_worktrees':\n          return this.listWorktreesTool();\n        case 'worktree':\n          return await this.worktreeUnifiedTool({\n            action: (params.action as 'enter' | 'exit' | 'merge' | 'list') || 'list',\n            branch: asOptionalString(params.branch),\n            merge: asBoolean(params.merge),\n            projectDir: asOptionalString(params.projectDir)\n          });\n        case 'sleep':\n          return await this.sleepTool({\n            duration_ms: asNumber(params.duration_ms) || 0,\n            reason: asOptionalString(params.reason)\n          });\n        case 'tool_search':\n          return this.toolSearchTool({\n            query: asString(params.query),\n            max_results: asNumber(params.max_results)\n          });\n        default:\n          return {\n            success: false,\n            error: `Unknown tool: ${toolName}`\n          };\n      }\n    } catch (err: unknown) {\n      return {\n        success: false,\n        error: errMsg(err)\n      };\n    }\n  }\n\n  private async writeFile(params: { file_path: string; content: string }): Promise<ToolResult> {\n    const isAbsolute = params.file_path.startsWith('/');\n    const { existsSync } = await import('node:fs');\n\n    // Guard: reject write_file on existing files \u2014 use replace/append instead\n    const checkPath = isAbsolute ? params.file_path : resolve(this.config.getWorkspaceRoot(), params.file_path);\n    if (existsSync(checkPath)) {\n      const { statSync } = await import('node:fs');\n      const size = statSync(checkPath).size;\n      if (size > 0) {\n        return {\n          success: false,\n          error: `File \"${params.file_path}\" already exists (${size} bytes). Use \"replace\" tool to edit existing files (read_file first, then replace with old_string/new_string). Use \"append_file\" to add content at the end. write_file is only for creating NEW files.`,\n          handled: false,\n          recovery: `Read the file first with read_file, then use replace with old_string/new_string for surgical edits.`\n        };\n      }\n    }\n\n    if (isAbsolute) {\n      try {\n        const { mkdir, writeFile } = await import('node:fs/promises');\n        const { dirname } = await import('node:path');\n        const dir = dirname(params.file_path);\n        await mkdir(dir, { recursive: true });\n        await writeFile(params.file_path, params.content, 'utf8');\n        return {\n          success: true,\n          output: `Wrote ${params.file_path} (${params.content.length} bytes)`\n        };\n      } catch (err: unknown) {\n        return { success: false, error: `Write failed: ${errMsg(err)}` };\n      }\n    }\n\n    // Relative paths: stage in sandbox with path traversal guard\n    const fullPath = resolve(this.getRealWorkspaceRoot(), params.file_path);\n    if (!this.isInsideWorkspace(fullPath)) {\n      return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n    }\n    await this.sandbox.addChange(params.file_path, params.content);\n    return {\n      success: true,\n      output: `Staged ${params.file_path} (${params.content.length} bytes)`\n    };\n  }\n\n  private async appendFile(params: { file_path: string; content: string }): Promise<ToolResult> {\n    const filePath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n\n    // Read-before-edit guard: must read_file before appending to existing files\n    const { existsSync } = await import('node:fs');\n    if (existsSync(filePath) && !this._filesRead.has(params.file_path) && !this._filesRead.has(filePath)) {\n      return {\n        success: false,\n        error: `You must read_file \"${params.file_path}\" before appending to it. Read first to understand the existing content and where your addition should go.`,\n        handled: false,\n        recovery: `Call read_file with file_path=\"${params.file_path}\" first, then retry append_file.`\n      };\n    }\n\n    let existing = '';\n    try {\n      const stagedContent = this.sandbox.getStagedContent?.(params.file_path)\n        || this.sandbox.getStagedContent?.(filePath);\n      existing = stagedContent ?? await readFile(filePath, 'utf8');\n    } catch {\n      existing = '';\n    }\n    const combined = `${existing}${params.content || ''}`;\n    await this.sandbox.addChange(params.file_path, combined);\n    return {\n      success: true,\n      output: `Appended ${params.file_path} (${(params.content || '').length} bytes)`\n    };\n  }\n  \n  private async readFile(params: { file_path: string; start_line?: number; end_line?: number }): Promise<ToolResult> {\n    const filePath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n\n    // Path traversal guard: ensure resolved path is within workspace (handles symlinks)\n    if (!this.isInsideWorkspace(filePath)) {\n      return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n    }\n\n    // Track that this file has been read (for read-before-edit guard)\n    this._filesRead.add(params.file_path);\n    this._filesRead.add(filePath);\n\n    // Check sandbox first for staged (not yet applied) changes\n    const stagedContent = this.sandbox.getStagedContent?.(params.file_path)\n      || this.sandbox.getStagedContent?.(filePath);\n    const content = stagedContent ?? await readFile(filePath, 'utf8');\n    \n    if (params.start_line || params.end_line) {\n      const lines = content.split('\\n');\n      const start = (params.start_line || 1) - 1;\n      const end = params.end_line || lines.length;\n      const slice = lines.slice(start, end).join('\\n');\n      return { success: true, output: slice };\n    }\n    \n    return { success: true, output: content };\n  }\n  \n  private async editFile(params: { file_path: string; old_string: string; new_string: string; replace_all?: boolean }): Promise<ToolResult> {\n    const realRoot = this.getRealWorkspaceRoot();\n    const filePath = resolve(realRoot, params.file_path);\n\n    // Path traversal guard (handles symlinks)\n    if (!this.isInsideWorkspace(filePath)) {\n      return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n    }\n\n    // Normalize to relative path for sandbox operations\n    const { relative } = await import('node:path');\n    const relPath = filePath.startsWith(realRoot) ? relative(realRoot, filePath) : params.file_path;\n\n    // Read-before-edit guard: require the file to have been read first (matches Claude Code)\n    if (!this._filesRead.has(params.file_path) && !this._filesRead.has(filePath) && !this._filesRead.has(relPath)) {\n      return {\n        success: false,\n        error: `You must read_file \"${params.file_path}\" before editing it. Never guess at file contents.`,\n        handled: false,\n        recovery: `Call read_file with file_path=\"${params.file_path}\" first, then retry this edit.`\n      };\n    }\n\n    // Read current content (could be staged) \u2014 use relPath for sandbox lookups\n    const stagedContent = this.sandbox.getStagedContent?.(relPath)\n      || this.sandbox.getStagedContent?.(params.file_path)\n      || this.sandbox.getStagedContent?.(filePath);\n    const content = stagedContent ?? await readFile(filePath, 'utf8');\n\n    // \u2500\u2500 Edit Strategy Chain: exact \u2192 whitespace-flex \u2192 regex-ish token match \u2192 fuzzy \u2500\u2500\n    const { match, strategy, occurrences } = this.findEditMatch(content, params.old_string);\n\n    if (!match) {\n      return {\n        success: false,\n        error: `String not found in ${relPath}. Tried: exact match, flexible whitespace, fuzzy (Levenshtein).`,\n        handled: false,\n        recovery: `Re-read the file with read_file and use the exact text from the file as old_string.`\n      };\n    }\n\n    // replace_all mode: replace every occurrence (useful for renames)\n    if (params.replace_all) {\n      const updated = content.split(match).join(params.new_string);\n      await this.sandbox.addChange(relPath, updated);\n      const diagnostics = await this.shadowValidate(params.file_path);\n      return {\n        success: true,\n        output: `Edited ${params.file_path} (${occurrences} replacements, strategy: ${strategy})${diagnostics}`\n      };\n    }\n\n    // Default: unique match required\n    if (occurrences > 1) {\n      return {\n        success: false,\n        error: `old_string matches ${occurrences} locations in ${params.file_path}. Provide more context to make it unique, or use replace_all:true to replace all occurrences.`\n      };\n    }\n\n    const updated = content.replace(match, params.new_string);\n    await this.sandbox.addChange(relPath, updated);\n\n    // Shadow validation: run diagnostics on the edited file (Cursor-style)\n    const diagnostics = await this.shadowValidate(relPath);\n\n    return {\n      success: true,\n      output: `Edited ${relPath}${strategy !== 'exact' ? ` (matched via ${strategy})` : ''}${diagnostics}`\n    };\n  }\n\n  /**\n   * Edit strategy chain: exact \u2192 flexible whitespace \u2192 regex-ish token match \u2192 fuzzy.\n   * Returns the actual matched string in the content and which strategy succeeded.\n   */\n  private findEditMatch(content: string, oldString: string): { match: string | null; strategy: string; occurrences: number } {\n    // Strategy 1: Exact match\n    if (content.includes(oldString)) {\n      return { match: oldString, strategy: 'exact', occurrences: content.split(oldString).length - 1 };\n    }\n\n    // Strategy 2: Flexible whitespace \u2014 normalize whitespace in both sides\n    const normalizeWS = (s: string) => s.replace(/[ \\t]+/g, ' ').replace(/\\r\\n/g, '\\n');\n    const normOld = normalizeWS(oldString);\n    const normContent = normalizeWS(content);\n    if (normContent.includes(normOld)) {\n      // Find the actual text in original content that matches\n      const lines = content.split('\\n');\n      const normLines = normContent.split('\\n');\n      const normOldLines = normOld.split('\\n');\n      // Find start line\n      const firstNormLine = normOldLines[0];\n      for (let i = 0; i <= lines.length - normOldLines.length; i++) {\n        if (normLines[i].includes(firstNormLine) || normLines[i] === firstNormLine) {\n          // Check if all lines match\n          const candidate = lines.slice(i, i + normOldLines.length).join('\\n');\n          if (normalizeWS(candidate) === normOld) {\n            return { match: candidate, strategy: 'whitespace-flex', occurrences: 1 };\n          }\n        }\n      }\n      // Fallback: just use the normalized match on the normalized content\n      // and find it by position\n      const idx = normContent.indexOf(normOld);\n      if (idx >= 0) {\n        // Map back to original by counting chars (approximate)\n        let origIdx = 0, normIdx = 0;\n        while (normIdx < idx && origIdx < content.length) {\n          if (/[ \\t]/.test(content[origIdx]) && origIdx + 1 < content.length && /[ \\t]/.test(content[origIdx + 1])) {\n            origIdx++;\n            continue;\n          }\n          origIdx++;\n          normIdx++;\n        }\n        // Extract same-length chunk from original\n        const chunk = content.substring(origIdx, origIdx + oldString.length + 50);\n        // Find the actual boundary in original that matches when normalized\n        for (let len = oldString.length - 5; len <= oldString.length + 20; len++) {\n          const tryChunk = content.substring(origIdx, origIdx + len);\n          if (normalizeWS(tryChunk) === normOld) {\n            return { match: tryChunk, strategy: 'whitespace-flex', occurrences: 1 };\n          }\n        }\n      }\n    }\n\n    // Strategy 3: Regex-ish token match that tolerates formatting differences around punctuation.\n    const escaped = oldString\n      .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n      .replace(/\\s+/g, '\\\\s+')\n      .replace(/\\\\([(){}\\[\\]:;,=<>+\\-/*])/g, '\\\\s*$1\\\\s*');\n    if (escaped.length > 0) {\n      try {\n        const regex = new RegExp(escaped, 'm');\n        const matches = content.match(new RegExp(escaped, 'gm'));\n        const regexMatch = content.match(regex);\n        if (regexMatch?.[0]) {\n          return { match: regexMatch[0], strategy: 'regex', occurrences: matches?.length || 1 };\n        }\n      } catch {\n        // Fall through to fuzzy matching.\n      }\n    }\n\n    // Strategy 4: Fuzzy match (Levenshtein) \u2014 find best-matching substring\n    const FUZZY_THRESHOLD = 0.10; // Allow up to 10% weighted difference\n    const lines = content.split('\\n');\n    const oldLines = oldString.split('\\n');\n    const oldLen = oldString.length;\n\n    if (oldLen > 0 && oldLen < 5000) { // Don't fuzzy-match huge strings\n      let bestMatch = '';\n      let bestDist = Infinity;\n\n      // Sliding window over content lines\n      for (let i = 0; i <= lines.length - oldLines.length; i++) {\n        const candidate = lines.slice(i, i + oldLines.length).join('\\n');\n        const dist = levenshteinDistance(candidate, oldString);\n        const maxLen = Math.max(candidate.length, oldLen);\n        const ratio = dist / maxLen;\n\n        if (ratio < FUZZY_THRESHOLD && dist < bestDist) {\n          bestDist = dist;\n          bestMatch = candidate;\n        }\n      }\n\n      if (bestMatch) {\n        return { match: bestMatch, strategy: 'fuzzy', occurrences: 1 };\n      }\n    }\n\n    return { match: null, strategy: 'none', occurrences: 0 };\n  }\n\n  /**\n   * Shadow validation: after an edit, check for type/lint errors using LSP.\n   * Returns empty string if clean, or diagnostic summary if errors found.\n   * Non-fatal \u2014 silently returns empty on any failure.\n   */\n  private async shadowValidate(filePath: string): Promise<string> {\n    // Only validate TypeScript/JavaScript files\n    if (!/\\.(ts|tsx|js|jsx|mjs|mts)$/.test(filePath)) return '';\n\n    try {\n      const lsp = await import('../../lsp/index.js');\n      const diags = await lsp.typeCheckProject(this.config.getWorkspaceRoot(), [filePath]);\n\n      // Filter to only errors in the edited file\n      const fileErrors = diags.filter((d: LspDiagnostic) =>\n        d.category === 'error' && d.file?.endsWith(filePath)\n      );\n\n      if (fileErrors.length === 0) return '';\n\n      const errorLines = fileErrors.slice(0, 5).map((d: LspDiagnostic) =>\n        `  ${d.file}:${d.line} \u2014 ${d.message}`\n      );\n\n      return `\\n\\n\u26A0\uFE0F Shadow validation found ${fileErrors.length} error(s) after edit:\\n${errorLines.join('\\n')}${fileErrors.length > 5 ? `\\n  ... and ${fileErrors.length - 5} more` : ''}\\nFix these before moving on.`;\n    } catch {\n      // LSP not available or failed \u2014 non-fatal\n      return '';\n    }\n  }\n\n  private async mkdirTool(params: { path?: string; dir_path?: string }): Promise<ToolResult> {\n    const dir = (params.path || params.dir_path || '').trim();\n    if (!dir) return { success: false, error: 'mkdir requires path' };\n    const keep = join(dir, '.gitkeep');\n    await this.sandbox.addChange(keep, '');\n    return { success: true, output: `Staged directory ${dir}` };\n  }\n\n  private async listTool(params: { path?: string; dir_path?: string }): Promise<ToolResult> {\n    const target = (params.path || params.dir_path || '.').trim();\n    const abs = resolve(this.sandbox.getBaseDir() || process.cwd(), target);\n    const items = await readdir(abs, { withFileTypes: true });\n    const lines = items.map(i => `${i.isDirectory() ? 'd' : 'f'} ${i.name}`);\n    return { success: true, output: lines.join('\\n') };\n  }\n\n  private async globTool(params: { pattern: string }): Promise<ToolResult> {\n    const pattern = String(params.pattern || '').trim();\n    if (!pattern) return { success: false, error: 'glob requires pattern' };\n    try {\n      const out = execSync(`rg --files -g ${JSON.stringify(pattern)}`, { cwd: this.sandbox.getBaseDir() || process.cwd(), stdio: 'pipe', encoding: 'utf8' });\n      return { success: true, output: out.trim() };\n    } catch (err: unknown) {\n      return { success: false, error: errShell(err) || errMsg(err) || 'glob failed' };\n    }\n  }\n\n  private async grepTool(params: {\n    pattern: string;\n    path?: string;\n    output_mode?: 'content' | 'files' | 'count';\n    context?: number;\n    before?: number;\n    after?: number;\n    case_insensitive?: boolean;\n    type?: string;\n    max_results?: number;\n  }): Promise<ToolResult> {\n    const pattern = String(params.pattern || '').trim();\n    const searchPath = String(params.path || '.').trim();\n    if (!pattern) return { success: false, error: 'grep requires pattern' };\n\n    const args = ['rg'];\n\n    // Output mode (matches Claude Code's Grep tool)\n    const mode = params.output_mode || 'content';\n    if (mode === 'files') {\n      args.push('-l'); // files_with_matches\n    } else if (mode === 'count') {\n      args.push('-c'); // count\n    } else {\n      args.push('-n'); // line numbers for content mode\n    }\n\n    // Context flags\n    if (params.context) args.push(`-C${params.context}`);\n    else {\n      if (params.before) args.push(`-B${params.before}`);\n      if (params.after) args.push(`-A${params.after}`);\n    }\n\n    // Case insensitive\n    if (params.case_insensitive) args.push('-i');\n\n    // File type filter\n    if (params.type) args.push(`--type=${params.type}`);\n\n    // Max results\n    if (params.max_results) args.push(`-m${params.max_results}`);\n\n    args.push(JSON.stringify(pattern), JSON.stringify(searchPath));\n\n    try {\n      const out = execSync(args.join(' '), {\n        cwd: this.sandbox.getBaseDir() || process.cwd(),\n        stdio: 'pipe',\n        encoding: 'utf8'\n      });\n      return { success: true, output: out.trim() };\n    } catch (err: unknown) {\n      const text = errShell(err);\n      // rg returns exit code 1 for no matches \u2014 that's not an error\n      const errStatus = (err as Record<string, unknown>)?.status;\n      if (errStatus === 1 && !text) return { success: true, output: '(no matches)' };\n      return { success: false, error: text || errMsg(err) || 'grep failed' };\n    }\n  }\n\n  private async gitTool(params: { command: string }): Promise<ToolResult> {\n    const command = String(params.command || '').trim();\n    if (!command) return { success: false, error: 'git requires command' };\n\n    // Expanded allowed subcommands (matches Claude Code git safety protocol)\n    const allowed = ['status', 'diff', 'log', 'add', 'commit', 'show', 'branch', 'stash', 'tag', 'blame', 'checkout', 'switch', 'restore', 'rev-parse', 'remote', 'fetch', 'pull', 'push', 'merge', 'rebase', 'reset', 'cherry-pick', 'worktree'];\n    const verb = command.split(/\\s+/)[0];\n    if (!allowed.includes(verb)) {\n      return { success: false, error: `git subcommand not allowed: ${verb}. Allowed: ${allowed.join(', ')}` };\n    }\n\n    // Safety guards (Claude Code pattern: never force push, never skip hooks)\n    if (/--force|--force-with-lease/.test(command) && verb === 'push') {\n      return { success: false, error: 'Force push is not allowed. Use a regular push or create a new branch.' };\n    }\n    if (/--no-verify/.test(command)) {\n      return { success: false, error: 'Skipping hooks (--no-verify) is not allowed. Fix the hook issue instead.' };\n    }\n    if (verb === 'reset' && /--hard/.test(command)) {\n      return { success: false, error: 'git reset --hard is destructive. Use git stash or git checkout <file> instead.' };\n    }\n\n    // Reject shell metacharacters to prevent command injection\n    if (/[;&|`$(){}\\\\!<>]/.test(command)) {\n      return { success: false, error: 'git command contains disallowed shell characters. Use only git arguments.' };\n    }\n\n    try {\n      const args = command.split(/\\s+/).filter(Boolean);\n      const { execFileSync } = await import('node:child_process');\n      const out = execFileSync('git', args, {\n        cwd: this.config.getWorkspaceRoot(),\n        stdio: 'pipe',\n        encoding: 'utf8',\n        timeout: 30000\n      });\n      return { success: true, output: out.trim() };\n    } catch (err: unknown) {\n      const text = errShell(err);\n      return { success: false, error: text || errMsg(err) || 'git failed' };\n    }\n  }\n\n  private async shellTool(params: { command: string; run_in_background?: boolean; description?: string }): Promise<ToolResult> {\n    const command = String(params.command || '').trim();\n    if (!command) return { success: false, error: 'shell requires command' };\n\n    // Dangerous command detection \u2014 block destructive patterns\n    for (const pat of DANGEROUS_SHELL_PATTERNS) {\n      if (pat.test(command)) {\n        return { success: false, error: `Blocked: destructive command detected (${command.slice(0, 60)}). Use a safer alternative.` };\n      }\n    }\n\n    // Background execution: run command asynchronously, return task ID\n    if (params.run_in_background) {\n      const taskId = `bg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;\n      const bgPromise = (async (): Promise<ToolResult> => {\n        try {\n          const { spawn } = await import('node:child_process');\n          return new Promise((resolve) => {\n            const proc = spawn('sh', ['-c', command], {\n              cwd: this.config.getWorkspaceRoot(),\n              stdio: 'pipe'\n            });\n            let stdout = '', stderr = '';\n            proc.stdout?.on('data', (d: Buffer) => { stdout += d.toString(); });\n            proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });\n            const timeout = setTimeout(() => { proc.kill('SIGTERM'); resolve({ success: false, error: 'Background task timed out' }); }, getShellTimeout());\n            proc.on('close', (code: number | null) => {\n              clearTimeout(timeout);\n              resolve(code === 0\n                ? { success: true, output: stdout.trim() }\n                : { success: false, error: (stderr || stdout).trim() || `exit code ${code}` });\n            });\n          });\n        } catch (err: unknown) {\n          return { success: false, error: errMsg(err) };\n        }\n      })();\n      _backgroundProcesses.set(taskId, { promise: bgPromise, startedAt: Date.now() });\n      return { success: true, output: `Background task started: ${taskId}\\nUse check_background_task with this ID to get the result.` };\n    }\n    \n    try {\n      // Check if we have staged files - if so, use Docker sandbox\n      const hasStagedFiles = this.sandbox.getPendingPaths().length > 0;\n      \n      if (hasStagedFiles) {\n        const { DockerSandbox } = await import('../docker-sandbox.js');\n        const docker = new DockerSandbox();\n        const dockerAvailable = await docker.isDockerAvailable();\n        \n        if (dockerAvailable) {\n          console.log(`[GeminiAdapter] Running command in Docker with ${this.sandbox.getPendingPaths().length} staged file(s)`);\n          const result = await docker.runCommand(command, this.sandbox as unknown as {\n            getPendingPaths(): string[];\n            state?: { branches?: Record<string, Record<string, { modified?: string }>> };\n            getActiveBranch(): string;\n          }, {\n            workDir: this.config.getWorkspaceRoot(),\n            timeout: getShellTimeout()\n          });\n          return {\n            success: result.success,\n            output: result.output,\n            error: result.success ? undefined : result.output\n          };\n        } else {\n          console.warn('[GeminiAdapter] Docker unavailable - running natively (staged files not available to command)');\n        }\n      }\n      \n      // Fallback: run natively from workspace root\n      const out = execSync(command, {\n        cwd: this.config.getWorkspaceRoot(),\n        stdio: 'pipe',\n        encoding: 'utf8',\n        timeout: getShellTimeout()\n      });\n      return { success: true, output: out.trim() };\n    } catch (err: unknown) {\n      const text = errShell(err);\n      return { success: false, error: text || errMsg(err) || 'shell failed' };\n    }\n  }\n\n  private async webSearchTool(params: { query: string }): Promise<ToolResult> {\n    const query = String(params.query || '').trim();\n    if (!query) return { success: false, error: 'web_search requires query' };\n    const braveKey = process.env.BRAVE_API_KEY || process.env.BRAVE_SEARCH_API_KEY;\n    if (!braveKey) return { success: false, error: 'web_search unavailable (missing BRAVE_API_KEY)' };\n    try {\n      const res = await fetch(\n        `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=5`,\n        {\n          headers: {\n            'Accept': 'application/json',\n            'X-Subscription-Token': braveKey\n          },\n          signal: AbortSignal.timeout(10000)\n        }\n      );\n      if (!res.ok) return { success: false, error: `web_search failed: HTTP ${res.status}` };\n      const data = await res.json() as SearchResponse;\n      const hits = ((data?.web as { results?: SearchHit[] })?.results || []).slice(0, 5) as SearchHit[];\n      const formatted = hits.map((r: SearchHit, i: number) =>\n        `${i + 1}. ${r.title || '(untitled)'}\\n${r.url || ''}\\n${r.description || ''}`\n      ).join('\\n\\n');\n      return { success: true, output: formatted || 'No results' };\n    } catch (err: unknown) {\n      return { success: false, error: errMsg(err) || 'web_search failed' };\n    }\n  }\n\n  private async webFetchTool(params: { url: string }): Promise<ToolResult> {\n    const url = String(params.url || '').trim();\n    if (!url || !/^https?:\\/\\//i.test(url)) {\n      return { success: false, error: 'web_fetch requires valid http(s) url' };\n    }\n    try {\n      const res = await fetch(url, {\n        headers: { 'User-Agent': 'crewswarm-CLI/1.0' },\n        signal: AbortSignal.timeout(12000)\n      });\n      if (!res.ok) return { success: false, error: `web_fetch failed: HTTP ${res.status}` };\n      const ct = String(res.headers.get('content-type') || '');\n      let text = await res.text();\n      if (ct.includes('html')) {\n        text = text\n          .replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n          .replace(/<style[\\s\\S]*?<\\/style>/gi, '')\n          .replace(/<[^>]+>/g, ' ')\n          .replace(/\\s{2,}/g, ' ')\n          .trim();\n      }\n      return { success: true, output: text.slice(0, 12000) };\n    } catch (err: unknown) {\n      return { success: false, error: errMsg(err) || 'web_fetch failed' };\n    }\n  }\n\n  private async readManyFilesTool(params: {\n    include?: string;\n    exclude?: string | string[];\n    recursive?: boolean;\n  }): Promise<ToolResult> {\n    const include = String(params.include || '**/*').trim();\n    try {\n      const out = execSync(`rg --files -g ${JSON.stringify(include)}`, {\n        cwd: this.config.getWorkspaceRoot(),\n        stdio: 'pipe',\n        encoding: 'utf8'\n      });\n      const files = out.split('\\n').filter(Boolean).slice(0, 20);\n      const chunks: string[] = [];\n      for (const rel of files) {\n        const full = resolve(this.config.getWorkspaceRoot(), rel);\n        try {\n          const content = await readFile(full, 'utf8');\n          chunks.push(`--- ${rel} ---\\n${content.slice(0, 2000)}`);\n        } catch {\n          // Skip unreadable/non-text\n        }\n      }\n      return { success: true, output: chunks.join('\\n\\n') || 'No readable files matched' };\n    } catch (err: unknown) {\n      return { success: false, error: errMsg(err) || 'read_many_files failed' };\n    }\n  }\n\n  private async saveMemoryTool(params: { fact: string }): Promise<ToolResult> {\n    const fact = String(params.fact || '').trim();\n    if (!fact) return { success: false, error: 'save_memory requires fact' };\n    const memDir = resolve(this.config.getWorkspaceRoot(), '.crew');\n    await mkdir(memDir, { recursive: true });\n    const memFile = resolve(memDir, 'memory-facts.log');\n    let prior = '';\n    try { prior = await readFile(memFile, 'utf8'); } catch {}\n    await writeFile(memFile, `${prior}${new Date().toISOString()} ${fact}\\n`, 'utf8');\n    return { success: true, output: 'Memory saved' };\n  }\n\n  private async writeTodosTool(params: { todos: unknown[] }): Promise<ToolResult> {\n    const todos = Array.isArray(params.todos) ? params.todos : [];\n    const memDir = resolve(this.config.getWorkspaceRoot(), '.crew');\n    await mkdir(memDir, { recursive: true });\n    const todoFile = resolve(memDir, 'todos.json');\n    await writeFile(todoFile, JSON.stringify(todos, null, 2), 'utf8');\n    return { success: true, output: `Saved ${todos.length} todos` };\n  }\n\n  private async getInternalDocsTool(params: { path?: string }): Promise<ToolResult> {\n    const target = String(params.path || 'AGENTS.md').trim();\n    const abs = resolve(this.config.getWorkspaceRoot(), target);\n    try {\n      const content = await readFile(abs, 'utf8');\n      return { success: true, output: content.slice(0, 12000) };\n    } catch (err: unknown) {\n      return { success: false, error: `get_internal_docs failed: ${errMsg(err) || target}` };\n    }\n  }\n\n  private async askUserTool(params: { questions?: unknown[] }): Promise<ToolResult> {\n    const qs = Array.isArray(params.questions) ? params.questions : [];\n    if (qs.length === 0) {\n      return { success: false, error: 'ask_user requires at least one question' };\n    }\n    const now = new Date().toISOString();\n    const request = {\n      id: `ask-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,\n      ts: now,\n      status: 'pending',\n      questions: qs\n    };\n    const crewDir = this.crewDirPath();\n    await mkdir(crewDir, { recursive: true });\n    await this.appendJsonLine(this.askUserRequestsPath(), request);\n    await writeFile(this.askUserLatestPath(), JSON.stringify(request, null, 2), 'utf8');\n    const summary = qs.map((q: unknown, i: number) => `${i + 1}. ${(q as Record<string, unknown>)?.question || 'question'}`).join('\\n');\n    return {\n      success: true,\n      output: `User input required (non-interactive runtime).\\nSaved request: ${this.relativeCrewPath(this.askUserLatestPath())}\\nQuestions:\\n${summary}`\n    };\n  }\n\n  private async enterPlanModeTool(params: { reason?: string }): Promise<ToolResult> {\n    const crewDir = this.crewDirPath();\n    await mkdir(crewDir, { recursive: true });\n    const state = {\n      active: true,\n      enteredAt: new Date().toISOString(),\n      exitedAt: null,\n      reason: String(params?.reason || '').trim() || null,\n      planPath: null\n    };\n    await writeFile(this.planModeStatePath(), JSON.stringify(state, null, 2), 'utf8');\n    return {\n      success: true,\n      output: `Plan mode entered${state.reason ? `: ${state.reason}` : ''} (${this.relativeCrewPath(this.planModeStatePath())})`\n    };\n  }\n\n  private async exitPlanModeTool(params: { plan_path?: string }): Promise<ToolResult> {\n    const crewDir = this.crewDirPath();\n    await mkdir(crewDir, { recursive: true });\n    let prior: Record<string, unknown> = {};\n    try {\n      prior = JSON.parse(await readFile(this.planModeStatePath(), 'utf8')) as Record<string, unknown>;\n    } catch {\n      prior = {};\n    }\n    const state = {\n      ...prior,\n      active: false,\n      exitedAt: new Date().toISOString(),\n      planPath: String(params?.plan_path || '').trim() || prior?.planPath || null\n    };\n    await writeFile(this.planModeStatePath(), JSON.stringify(state, null, 2), 'utf8');\n    return {\n      success: true,\n      output: `Plan mode exited${state.planPath ? `: ${state.planPath}` : ''} (${this.relativeCrewPath(this.planModeStatePath())})`\n    };\n  }\n\n  private async activateSkillTool(params: { name?: string }): Promise<ToolResult> {\n    const name = String(params?.name || '').trim();\n    if (!name) return { success: false, error: 'activate_skill requires name' };\n    const crewDir = this.crewDirPath();\n    await mkdir(crewDir, { recursive: true });\n    let state: { active?: unknown[] } = { active: [] };\n    try {\n      state = JSON.parse(await readFile(this.activeSkillsPath(), 'utf8')) as { active?: unknown[] };\n    } catch {\n      state = { active: [] };\n    }\n    const active = new Set(Array.isArray(state?.active) ? state.active : []);\n    active.add(name);\n    const next = {\n      active: Array.from(active).sort(),\n      updatedAt: new Date().toISOString()\n    };\n    await writeFile(this.activeSkillsPath(), JSON.stringify(next, null, 2), 'utf8');\n    return { success: true, output: `Skill activated: ${name} (${this.relativeCrewPath(this.activeSkillsPath())})` };\n  }\n\n  private crewDirPath() {\n    return resolve(this.config.getWorkspaceRoot(), '.crew');\n  }\n\n  private askUserRequestsPath() {\n    return resolve(this.crewDirPath(), 'ask-user-requests.jsonl');\n  }\n\n  private askUserLatestPath() {\n    return resolve(this.crewDirPath(), 'ask-user-latest.json');\n  }\n\n  private planModeStatePath() {\n    return resolve(this.crewDirPath(), 'plan-mode.json');\n  }\n\n  private activeSkillsPath() {\n    return resolve(this.crewDirPath(), 'active-skills.json');\n  }\n\n  private relativeCrewPath(absPath: string) {\n    return absPath.replace(this.config.getWorkspaceRoot(), '.');\n  }\n\n  private async appendJsonLine(filePath: string, data: unknown): Promise<void> {\n    let prior = '';\n    try {\n      prior = await readFile(filePath, 'utf8');\n    } catch {\n      prior = '';\n    }\n    const line = `${JSON.stringify(data)}\\n`;\n    await writeFile(filePath, `${prior}${line}`, 'utf8');\n  }\n\n  private trackerFilePath() {\n    return resolve(this.config.getWorkspaceRoot(), '.crew', 'tracker.json');\n  }\n\n  private async readTracker(): Promise<TrackerTask[]> {\n    try {\n      const raw = await readFile(this.trackerFilePath(), 'utf8');\n      const parsed = JSON.parse(raw);\n      return Array.isArray(parsed) ? parsed : [];\n    } catch {\n      return [];\n    }\n  }\n\n  private async writeTracker(tasks: TrackerTask[]): Promise<void> {\n    const dir = resolve(this.config.getWorkspaceRoot(), '.crew');\n    await mkdir(dir, { recursive: true });\n    await writeFile(this.trackerFilePath(), JSON.stringify(tasks, null, 2), 'utf8');\n  }\n\n  private mkTrackerId() {\n    return Math.random().toString(16).slice(2, 8);\n  }\n\n  private async trackerCreateTaskTool(params: Record<string, unknown>): Promise<ToolResult> {\n    const tasks = await this.readTracker();\n    const task: TrackerTask = {\n      id: this.mkTrackerId(),\n      title: String(params?.title || 'Untitled'),\n      description: String(params?.description || ''),\n      type: String(params?.type || 'task'),\n      status: 'pending',\n      parentId: typeof params?.parentId === 'string' ? params.parentId : undefined,\n      dependencies: Array.isArray(params?.dependencies) ? (params.dependencies as string[]) : []\n    };\n    tasks.push(task);\n    await this.writeTracker(tasks);\n    return { success: true, output: JSON.stringify(task, null, 2) };\n  }\n\n  private async trackerUpdateTaskTool(params: Record<string, unknown>): Promise<ToolResult> {\n    const tasks = await this.readTracker();\n    const id = String(params?.id || '');\n    const idx = tasks.findIndex((t) => t.id === id);\n    if (idx < 0) return { success: false, error: `Task not found: ${id}` };\n    tasks[idx] = { ...tasks[idx], ...params };\n    await this.writeTracker(tasks);\n    return { success: true, output: JSON.stringify(tasks[idx], null, 2) };\n  }\n\n  private async trackerGetTaskTool(params: Record<string, unknown>): Promise<ToolResult> {\n    const tasks = await this.readTracker();\n    const id = String(params?.id || '');\n    const task = tasks.find((t) => t.id === id);\n    if (!task) return { success: false, error: `Task not found: ${id}` };\n    return { success: true, output: JSON.stringify(task, null, 2) };\n  }\n\n  private async trackerListTasksTool(params: Record<string, unknown>): Promise<ToolResult> {\n    const tasks = await this.readTracker();\n    const filtered = tasks.filter((t) => {\n      if (params?.status && t.status !== params.status) return false;\n      if (params?.type && t.type !== params.type) return false;\n      if (params?.parentId && t.parentId !== params.parentId) return false;\n      return true;\n    });\n    return { success: true, output: JSON.stringify(filtered, null, 2) };\n  }\n\n  private async trackerAddDependencyTool(params: Record<string, unknown>): Promise<ToolResult> {\n    const tasks = await this.readTracker();\n    const taskId = String(params?.taskId || '');\n    const depId = String(params?.dependencyId || '');\n    const idx = tasks.findIndex((t) => t.id === taskId);\n    if (idx < 0) return { success: false, error: `Task not found: ${taskId}` };\n    const deps = new Set(Array.isArray(tasks[idx].dependencies) ? tasks[idx].dependencies : []);\n    deps.add(depId);\n    tasks[idx].dependencies = Array.from(deps);\n    await this.writeTracker(tasks);\n    return { success: true, output: JSON.stringify(tasks[idx], null, 2) };\n  }\n\n  private async trackerVisualizeTool(): Promise<ToolResult> {\n    const tasks = await this.readTracker();\n    const lines = tasks.map((t) => {\n      const deps = Array.isArray(t.dependencies) && t.dependencies.length\n        ? ` -> [${t.dependencies.join(', ')}]`\n        : '';\n      return `${t.id} [${t.status}] ${t.title}${deps}`;\n    });\n    return { success: true, output: lines.join('\\n') || '(no tasks)' };\n  }\n\n  private async lspTool(params: { query?: string; action?: string; file?: string; line?: number; column?: number; symbol?: string }): Promise<ToolResult> {\n    // New action-based interface \u2014 inlined to avoid importing tools.ts (which has upstream missing deps)\n    if (params.action && params.file) {\n      return this.lspActionTool(params as { action: string; file: string; line?: number; column?: number; symbol?: string });\n    }\n\n    // Legacy query-based interface for backward compatibility\n    const query = String(params.query || '').trim();\n    if (!query) return { success: false, error: 'lsp requires action+file or legacy query string' };\n    const lower = query.toLowerCase();\n    const lsp = await import('../../lsp/index.js');\n    if (lower.startsWith('symbols')) {\n      const file = query.slice('symbols'.length).trim();\n      if (!file) return { success: false, error: 'lsp symbols requires file path' };\n      const symbols = await lsp.getDocumentSymbols(process.cwd(), file);\n      return { success: true, output: symbols.map((s: LspSymbol) => `${file}:${s.line}:${s.column} ${s.kind} ${s.name}`).join('\\n') };\n    }\n    if (lower.startsWith('refs')) {\n      const target = query.slice('refs'.length).trim();\n      const match = target.match(/^(.+):(\\d+)(?::(\\d+))?$/);\n      if (match) {\n        const refs = await lsp.getReferences(process.cwd(), match[1], Number(match[2]), Number(match[3] || '1'));\n        return { success: true, output: refs.map((r: LspLocation) => `${r.file}:${r.line}:${r.column}`).join('\\n') };\n      }\n      if (target) return this.grepTool({ pattern: `\\\\b${target}\\\\b`, path: '.' });\n      return { success: false, error: 'lsp refs requires symbol or file:line[:col]' };\n    }\n    if (lower.startsWith('goto')) {\n      const target = query.slice('goto'.length).trim();\n      const match = target.match(/^(.+):(\\d+)(?::(\\d+))?$/);\n      if (!match) return { success: false, error: 'lsp goto format: file:line[:col]' };\n      const defs = await lsp.getDefinitions(process.cwd(), match[1], Number(match[2]), Number(match[3] || '1'));\n      return { success: true, output: defs.map((d: LspLocation) => `${d.file}:${d.line}:${d.column}`).join('\\n') };\n    }\n    if (lower.startsWith('diagnostics') || lower === 'check') {\n      const diags = await lsp.typeCheckProject(process.cwd(), []);\n      return { success: true, output: diags.map((d: LspDiagnostic) => `${d.file}:${d.line}:${d.column} [${d.category}] ${d.message}`).join('\\n') };\n    }\n    if (lower.startsWith('complete')) {\n      const target = query.slice('complete'.length).trim();\n      const match = target.match(/^(.+):(\\d+):(\\d+)(?:\\s+(.+))?$/);\n      if (!match) return { success: false, error: 'lsp complete format: file:line:col [prefix]' };\n      const items = await lsp.getCompletions(process.cwd(), match[1], Number(match[2]), Number(match[3]), 50, match[4] || '');\n      return { success: true, output: items.map((i: LspCompletionItem) => `${i.name} (${i.kind})`).join('\\n') };\n    }\n    return { success: false, error: `Unsupported lsp query: ${query}` };\n  }\n\n  /** Inline implementation of LSP action-based interface (avoids importing tools.ts) */\n  private async lspActionTool(params: { action: string; file: string; line?: number; column?: number; symbol?: string }): Promise<ToolResult> {\n    const { action, file, line, column, symbol } = params;\n    const workspaceRoot = this.config.getWorkspaceRoot();\n    const absFile = file.startsWith('/') ? file : resolve(workspaceRoot, file);\n    const lsp = await import('../../lsp/index.js');\n    const ext = absFile.slice(absFile.lastIndexOf('.') + 1).toLowerCase();\n    const isTs = ext === 'ts' || ext === 'tsx';\n    const isJs = ext === 'js' || ext === 'jsx' || ext === 'mjs' || ext === 'cjs';\n\n    try {\n      if (action === 'diagnostics') {\n        if (isTs || isJs) {\n          try {\n            const diags = await lsp.typeCheckProject(workspaceRoot, [absFile]);\n            if (diags.length === 0) return { success: true, output: 'No diagnostics found.' };\n            return { success: true, output: diags.map((d: LspDiagnostic) => `${d.file}:${d.line}:${d.column} [${d.category}] TS${d.code}: ${d.message}`).join('\\n') };\n          } catch {\n            const out = execSync(`npx tsc --noEmit 2>&1 || true`, { cwd: workspaceRoot, encoding: 'utf8', timeout: 30000 });\n            return { success: true, output: out.trim() || 'No diagnostics found.' };\n          }\n        }\n        if (ext === 'py') {\n          const out = execSync(`python -m py_compile ${JSON.stringify(absFile)} 2>&1 || true`, { cwd: workspaceRoot, encoding: 'utf8', timeout: 10000 });\n          return { success: true, output: out.trim() || 'No syntax errors found.' };\n        }\n        return { success: false, error: `Diagnostics not supported for .${ext} files` };\n      }\n\n      if (action === 'definition') {\n        if ((isTs || isJs) && line != null) {\n          try {\n            const defs = await lsp.getDefinitions(workspaceRoot, absFile, line, column ?? 1);\n            if (defs.length === 0) return { success: true, output: 'No definition found.' };\n            return { success: true, output: defs.map((d: LspLocation) => `${d.file}:${d.line}:${d.column}`).join('\\n') };\n          } catch { /* fall through to grep */ }\n        }\n        const sym = symbol || 'unknown';\n        try {\n          const out = execSync(`grep -rn -E \"export (function|class|const|let|var|interface|type|enum) ${sym}|def ${sym}|func ${sym}|function ${sym}\" .`, { cwd: workspaceRoot, encoding: 'utf8', timeout: 15000 });\n          return { success: true, output: out.trim() || 'No definition found.' };\n        } catch (e: unknown) {\n          const es = e as Record<string, unknown>;\n          return { success: true, output: es?.status === 1 ? 'No definition found.' : `grep failed: ${errMsg(e)}` };\n        }\n      }\n\n      if (action === 'references') {\n        if ((isTs || isJs) && line != null) {\n          try {\n            const refs = await lsp.getReferences(workspaceRoot, absFile, line, column ?? 1);\n            if (refs.length === 0) return { success: true, output: 'No references found.' };\n            return { success: true, output: refs.map((r: LspLocation) => `${r.file}:${r.line}:${r.column}`).join('\\n') };\n          } catch { /* fall through to grep */ }\n        }\n        const sym = symbol || 'unknown';\n        try {\n          const out = execSync(`grep -rn \"\\\\b${sym}\\\\b\" --include=\"*.ts\" --include=\"*.js\" --include=\"*.py\" --include=\"*.go\" .`, { cwd: workspaceRoot, encoding: 'utf8', timeout: 15000 });\n          return { success: true, output: out.trim() || 'No references found.' };\n        } catch (e: unknown) {\n          const es = e as Record<string, unknown>;\n          return { success: true, output: es?.status === 1 ? 'No references found.' : `grep failed: ${errMsg(e)}` };\n        }\n      }\n\n      if (action === 'hover') {\n        if (line == null) return { success: false, error: 'hover requires line' };\n        if (isTs || isJs) {\n          try {\n            const symbols = await lsp.getDocumentSymbols(workspaceRoot, absFile);\n            const near = symbols.filter((s: LspSymbol) => Math.abs(s.line - line) <= 1);\n            if (near.length > 0) return { success: true, output: near.map((s: LspSymbol) => `${s.kind} ${s.name} (line ${s.line}:${s.column})`).join('\\n') };\n          } catch { /* fall through */ }\n        }\n        try {\n          const content = await readFile(absFile, 'utf8');\n          const lines = content.split('\\n');\n          return { success: true, output: lines[(line - 1)] || '' };\n        } catch (e: unknown) {\n          return { success: false, error: `Could not read file: ${errMsg(e)}` };\n        }\n      }\n\n      if (action === 'completions') {\n        if (line == null || column == null) return { success: false, error: 'completions requires line and column' };\n        if (isTs || isJs) {\n          try {\n            const items = await lsp.getCompletions(workspaceRoot, absFile, line, column, 30, '');\n            if (items.length === 0) return { success: true, output: 'No completions found.' };\n            return { success: true, output: items.map((i: LspCompletionItem) => `${i.name} (${i.kind})`).join('\\n') };\n          } catch (e: unknown) {\n            return { success: false, error: `completions failed: ${errMsg(e)}` };\n          }\n        }\n        return { success: false, error: `Completions not supported for .${ext} files` };\n      }\n\n      return { success: false, error: `Unknown lsp action: ${action}` };\n    } catch (err: unknown) {\n      return { success: false, error: `LSP error: ${errMsg(err)}` };\n    }\n  }\n\n  /** Inline implementation of notebook-edit actions (avoids importing tools.ts) */\n  private async notebookEditTool(params: { action: string; path: string; index?: number; cell_type?: 'code' | 'markdown'; content?: string }): Promise<ToolResult> {\n    const { action, index, content, cell_type } = params;\n    const nbPath = params.path.startsWith('/') ? params.path : resolve(this.config.getWorkspaceRoot(), params.path);\n\n    // Load notebook\n    async function loadNb() {\n      try {\n        const raw = await readFile(nbPath, 'utf8');\n        return JSON.parse(raw);\n      } catch (e: unknown) {\n        throw new Error(`Cannot read notebook ${params.path}: ${errMsg(e)}`);\n      }\n    }\n\n    async function saveNb(nb: Notebook) {\n      await mkdir(dirname(nbPath), { recursive: true });\n      await writeFile(nbPath, JSON.stringify(nb, null, 1), 'utf8');\n    }\n\n    function toLines(src: string): string[] {\n      if (!src) return [];\n      const parts = src.split('\\n');\n      return parts.map((l, i) => i < parts.length - 1 ? `${l}\\n` : l);\n    }\n\n    try {\n      if (action === 'read') {\n        const nb = await loadNb();\n        const cells = (nb.cells || []).map((c: NotebookCell, i: number) => {\n          const src = (Array.isArray(c.source) ? c.source.join('') : c.source || '').slice(0, 200);\n          const outs = Array.isArray(c.outputs) && c.outputs.length ? ` [${c.outputs.length} output(s)]` : '';\n          return `[${i}] ${c.cell_type}${outs}:\\n${src}`;\n        });\n        const summary = `Notebook: ${params.path}\\nFormat: ${nb.nbformat}.${nb.nbformat_minor}\\nCells: ${nb.cells.length}\\n\\n${cells.join('\\n\\n')}`;\n        return { success: true, output: summary };\n      }\n\n      if (action === 'add_cell') {\n        if (content == null) return { success: false, error: \"add_cell requires 'content'\" };\n        const nb = await loadNb();\n        const newCell: NotebookCell = { cell_type: cell_type ?? 'code', source: toLines(content), metadata: {}, outputs: [], execution_count: null };\n        if (index != null && index >= 0 && index <= nb.cells.length) nb.cells.splice(index, 0, newCell);\n        else nb.cells.push(newCell);\n        await saveNb(nb);\n        return { success: true, output: `Added ${newCell.cell_type} cell at index ${index ?? nb.cells.length - 1}` };\n      }\n\n      if (action === 'edit_cell') {\n        if (index == null) return { success: false, error: \"edit_cell requires 'index'\" };\n        if (content == null) return { success: false, error: \"edit_cell requires 'content'\" };\n        const nb = await loadNb();\n        if (index < 0 || index >= nb.cells.length) return { success: false, output: `Cell index ${index} out of range (notebook has ${nb.cells.length} cells)` };\n        nb.cells[index].source = toLines(content);\n        if (nb.cells[index].cell_type === 'code') { nb.cells[index].outputs = []; nb.cells[index].execution_count = null; }\n        await saveNb(nb);\n        return { success: true, output: `Edited cell ${index}` };\n      }\n\n      if (action === 'delete_cell') {\n        if (index == null) return { success: false, error: \"delete_cell requires 'index'\" };\n        const nb = await loadNb();\n        if (index < 0 || index >= nb.cells.length) return { success: false, output: `Cell index ${index} out of range (notebook has ${nb.cells.length} cells)` };\n        nb.cells.splice(index, 1);\n        await saveNb(nb);\n        return { success: true, output: `Deleted cell ${index} (${nb.cells.length} cells remaining)` };\n      }\n\n      if (action === 'run_cell') {\n        if (index == null) return { success: false, error: \"run_cell requires 'index'\" };\n        const nb = await loadNb();\n        if (index < 0 || index >= nb.cells.length) return { success: false, error: `Cell index ${index} out of range` };\n        const cell = nb.cells[index];\n        if (cell.cell_type !== 'code') return { success: false, error: `Cell ${index} is ${cell.cell_type}, only code cells can be run` };\n        const src = Array.isArray(cell.source) ? cell.source.join('') : cell.source;\n        try {\n          const out = execSync(`python3 -c ${JSON.stringify(src)}`, { cwd: this.config.getWorkspaceRoot(), encoding: 'utf8', timeout: 30000 });\n          return { success: true, output: `Cell ${index} executed:\\n${out.trim() || '(no output)'}` };\n        } catch (pyErr: unknown) {\n          const stderr = errShell(pyErr).trim() || errMsg(pyErr) || 'execution failed';\n          return { success: false, error: `Cell ${index} execution failed:\\n${stderr}` };\n        }\n      }\n\n      return { success: false, error: `Unknown notebook_edit action: ${action}` };\n    } catch (err: unknown) {\n      return { success: false, error: `NotebookEdit error: ${errMsg(err)}` };\n    }\n  }\n\n  private async checkBackgroundTask(params: { task_id: string }): Promise<ToolResult> {\n    const taskId = String(params.task_id || '').trim();\n    if (!taskId) return { success: false, error: 'check_background_task requires task_id' };\n    const bg = _backgroundProcesses.get(taskId);\n    if (!bg) return { success: false, error: `No background task found with ID: ${taskId}` };\n\n    // Check if done (non-blocking with race against a resolved promise)\n    const done = await Promise.race([\n      bg.promise.then(r => ({ done: true as const, result: r })),\n      new Promise<{ done: false }>(resolve => setTimeout(() => resolve({ done: false }), 50))\n    ]);\n\n    if (!done.done) {\n      const elapsed = Math.round((Date.now() - bg.startedAt) / 1000);\n      return { success: true, output: `Task ${taskId} still running (${elapsed}s elapsed). Check again later.` };\n    }\n\n    _backgroundProcesses.delete(taskId);\n    return done.result;\n  }\n\n  // Track sub-agent depth to prevent infinite recursion\n  private static _spawnDepth = 0;\n  private static readonly MAX_SPAWN_DEPTH = 3;\n\n  // \u2500\u2500\u2500 Multi-turn sub-agent sessions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // Each session tracks its conversation history, branch, and model so the\n  // parent agent can send follow-up messages to an existing sub-agent.\n  private static _agentSessions = new Map<string, {\n    history: Array<{ role: string; content: string }>;\n    branch: string;\n    model: string;\n    totalCost: number;\n    totalTurns: number;\n  }>();\n\n  private async spawnAgentTool(params: { task: string; model?: string; max_turns?: number }): Promise<ToolResult> {\n    const task = String(params.task || '').trim();\n    if (!task) return { success: false, error: 'spawn_agent requires task' };\n\n    if (GeminiToolAdapter._spawnDepth >= GeminiToolAdapter.MAX_SPAWN_DEPTH) {\n      return { success: false, error: `Sub-agent depth limit reached (max ${GeminiToolAdapter.MAX_SPAWN_DEPTH}). Complete this task directly instead.` };\n    }\n\n    const maxTurns = Math.min(params.max_turns || 15, 25);\n    const model = params.model || process.env.CREW_WORKER_MODEL || process.env.CREW_EXECUTION_MODEL || '';\n    const sessionId = `agent-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;\n    const branchName = `sub-agent-${sessionId}`;\n\n    try {\n      // Create isolated sandbox branch for sub-agent\n      await this.sandbox.createBranch(branchName);\n\n      GeminiToolAdapter._spawnDepth++;\n\n      const { runAgenticWorker } = await import('../../executor/agentic-executor.js');\n      const result = await runAgenticWorker(task, this.sandbox, {\n        model,\n        maxTurns,\n        stream: false,\n        verbose: Boolean(process.env.CREW_DEBUG),\n        tier: 'fast',\n        constraintLevel: 'edit',\n        projectDir: this.sandbox.getBaseDir?.() || process.cwd(),\n        verificationCommands: extractVerificationCommands(task)\n      });\n\n      GeminiToolAdapter._spawnDepth--;\n\n      // Store session for multi-turn follow-ups (don't merge yet)\n      GeminiToolAdapter._agentSessions.set(sessionId, {\n        history: [\n          { role: 'user', content: task },\n          { role: 'assistant', content: result.output || '' }\n        ],\n        branch: branchName,\n        model,\n        totalCost: result.cost || 0,\n        totalTurns: result.turns || 0,\n      });\n\n      // Merge sub-agent changes back to parent branch\n      const parentBranch = this.sandbox.getActiveBranch();\n      if (parentBranch !== branchName) {\n        await this.sandbox.mergeBranch(branchName, parentBranch);\n      } else {\n        const branches = this.sandbox.getBranches();\n        const parent = branches.find(b => b !== branchName) || 'main';\n        await this.sandbox.switchBranch(parent);\n        await this.sandbox.mergeBranch(branchName, parent);\n      }\n\n      const output = [\n        `Sub-agent completed in ${result.turns || 0} turns (${result.modelUsed || 'unknown'})`,\n        `Session: ${sessionId} (use agent_message to send follow-ups)`,\n        result.cost ? `Cost: $${result.cost.toFixed(4)}` : '',\n        `Status: ${result.success ? 'SUCCESS' : 'FAILED'}`,\n        '',\n        result.output?.slice(0, 3000) || '(no output)'\n      ].filter(Boolean).join('\\n');\n\n      return { success: result.success, output };\n    } catch (err: unknown) {\n      GeminiToolAdapter._spawnDepth = Math.max(0, GeminiToolAdapter._spawnDepth - 1);\n      try { await this.sandbox.switchBranch('main'); } catch { /* ignore */ }\n      try { await this.sandbox.deleteBranch(branchName); } catch { /* ignore */ }\n      return { success: false, error: `Sub-agent failed: ${errMsg(err)}` };\n    }\n  }\n\n  // \u2500\u2500\u2500 agent_message: send follow-up to an existing sub-agent session \u2500\u2500\u2500\u2500\u2500\n  private async agentMessageTool(params: { session_id: string; message: string; max_turns?: number }): Promise<ToolResult> {\n    const sessionId = String(params.session_id || '').trim();\n    const message = String(params.message || '').trim();\n    if (!sessionId) return { success: false, error: 'agent_message requires session_id' };\n    if (!message) return { success: false, error: 'agent_message requires message' };\n\n    const session = GeminiToolAdapter._agentSessions.get(sessionId);\n    if (!session) {\n      const available = [...GeminiToolAdapter._agentSessions.keys()];\n      return {\n        success: false,\n        error: `No active session \"${sessionId}\". Active sessions: ${available.length ? available.join(', ') : '(none)'}`\n      };\n    }\n\n    if (GeminiToolAdapter._spawnDepth >= GeminiToolAdapter.MAX_SPAWN_DEPTH) {\n      return { success: false, error: `Sub-agent depth limit reached (max ${GeminiToolAdapter.MAX_SPAWN_DEPTH}).` };\n    }\n\n    const maxTurns = Math.min(params.max_turns || 10, 25);\n\n    // Build a combined task with conversation history as context\n    const historyContext = session.history\n      .map(h => `[${h.role}]: ${h.content.slice(0, 1500)}`)\n      .join('\\n\\n');\n    const continuationTask = [\n      '## Prior conversation with this sub-agent:',\n      historyContext,\n      '',\n      '## New follow-up message:',\n      message,\n      '',\n      'Continue the work from where you left off. You have the same file access and tools.',\n    ].join('\\n');\n\n    // Switch to the sub-agent's branch\n    try {\n      await this.sandbox.switchBranch(session.branch);\n    } catch {\n      // Branch may have been cleaned up \u2014 work on current branch\n    }\n\n    GeminiToolAdapter._spawnDepth++;\n\n    try {\n      const { runAgenticWorker } = await import('../../executor/agentic-executor.js');\n      const result = await runAgenticWorker(continuationTask, this.sandbox, {\n        model: session.model,\n        maxTurns,\n        stream: false,\n        verbose: Boolean(process.env.CREW_DEBUG),\n        tier: 'fast',\n        constraintLevel: 'edit',\n        projectDir: this.sandbox.getBaseDir?.() || process.cwd(),\n        verificationCommands: extractVerificationCommands(continuationTask)\n      });\n\n      GeminiToolAdapter._spawnDepth--;\n\n      // Update session history\n      session.history.push(\n        { role: 'user', content: message },\n        { role: 'assistant', content: result.output || '' }\n      );\n      session.totalCost += result.cost || 0;\n      session.totalTurns += result.turns || 0;\n\n      // Merge changes back\n      try {\n        const parentBranch = this.sandbox.getActiveBranch();\n        if (parentBranch === session.branch) {\n          const branches = this.sandbox.getBranches();\n          const parent = branches.find(b => b !== session.branch) || 'main';\n          await this.sandbox.switchBranch(parent);\n          await this.sandbox.mergeBranch(session.branch, parent);\n        } else {\n          await this.sandbox.mergeBranch(session.branch, parentBranch);\n        }\n      } catch { /* merge may not be needed */ }\n\n      const output = [\n        `Sub-agent follow-up completed in ${result.turns || 0} turns`,\n        `Session: ${sessionId} (${session.history.length / 2} exchanges, $${session.totalCost.toFixed(4)} total)`,\n        `Status: ${result.success ? 'SUCCESS' : 'FAILED'}`,\n        '',\n        result.output?.slice(0, 3000) || '(no output)'\n      ].filter(Boolean).join('\\n');\n\n      return { success: result.success, output };\n    } catch (err: unknown) {\n      GeminiToolAdapter._spawnDepth = Math.max(0, GeminiToolAdapter._spawnDepth - 1);\n      try { await this.sandbox.switchBranch('main'); } catch { /* ignore */ }\n      return { success: false, error: `Sub-agent follow-up failed: ${errMsg(err)}` };\n    }\n  }\n\n  /**\n   * Get tool declarations for LLM function calling\n   */\n  getToolDeclarations() {\n    const dynamicEnabled = process.env.CREW_GEMINI_DYNAMIC_DECLARATIONS !== 'false';\n    let allDecls: ToolDeclarationSchema[] | undefined;\n    if (dynamicEnabled) {\n      try {\n        const decls = this.buildDynamicDeclarations();\n        allDecls = decls.length > 0 ? decls : undefined;\n      } catch {\n        // Fallback to static declarations below.\n      }\n    }\n    if (!allDecls) {\n      allDecls = [\n      {\n        name: 'read_file',\n        description: 'Read the contents of a file. ALWAYS read files before editing them. Use start_line/end_line for large files.',\n        parameters: {\n          type: 'object',\n          properties: {\n            file_path: { type: 'string', description: 'Relative path from project root' },\n            start_line: { type: 'number', description: 'Start line number (1-based, optional)' },\n            end_line: { type: 'number', description: 'End line number (inclusive, optional)' }\n          },\n          required: ['file_path']\n        }\n      },\n      {\n        name: 'glob',\n        description: 'Find files matching a glob pattern. Use this to discover file structure. Examples: \"**/*.ts\", \"src/**/*.tsx\", \"*.json\"',\n        parameters: {\n          type: 'object',\n          properties: {\n            pattern: { type: 'string', description: 'Glob pattern (e.g. \"src/**/*.ts\")' }\n          },\n          required: ['pattern']\n        }\n      },\n      {\n        name: 'grep',\n        description: 'Search for text/regex patterns in files. Returns matching lines with file paths and line numbers.',\n        parameters: {\n          type: 'object',\n          properties: {\n            pattern: { type: 'string', description: 'Regex or text pattern to search for' },\n            path: { type: 'string', description: 'Directory or file to search in (default: \".\")' }\n          },\n          required: ['pattern']\n        }\n      },\n      {\n        name: 'grep_search',\n        description: 'Canonical alias for grep. Search for regex/text in files.',\n        parameters: {\n          type: 'object',\n          properties: {\n            pattern: { type: 'string', description: 'Regex/text pattern' },\n            dir_path: { type: 'string', description: 'Path to search (default: .)' }\n          },\n          required: ['pattern']\n        }\n      },\n      {\n        name: 'grep_search_ripgrep',\n        description: 'Ripgrep-optimized canonical name. Routed to grep tool in this adapter.',\n        parameters: {\n          type: 'object',\n          properties: {\n            pattern: { type: 'string', description: 'Regex/text pattern' },\n            dir_path: { type: 'string', description: 'Path to search (default: .)' },\n            path: { type: 'string', description: 'Alternative path field' }\n          },\n          required: ['pattern']\n        }\n      },\n      {\n        name: 'write_file',\n        description: 'Write content to a file (creates or overwrites). Changes are staged in sandbox. Use for new files or full rewrites.',\n        parameters: {\n          type: 'object',\n          properties: {\n            file_path: { type: 'string', description: 'Relative path from project root' },\n            content: { type: 'string', description: 'Complete file content' }\n          },\n          required: ['file_path', 'content']\n        }\n      },\n      {\n        name: 'append_file',\n        description: 'Append content to an existing file. Creates file if it does not exist. Changes are staged in sandbox.',\n        parameters: {\n          type: 'object',\n          properties: {\n            file_path: { type: 'string', description: 'Relative path from project root' },\n            content: { type: 'string', description: 'Content to append' }\n          },\n          required: ['file_path', 'content']\n        }\n      },\n      {\n        name: 'edit',\n        description: 'Edit a file by replacing an exact string match. ALWAYS read the file first to get the exact string. Use for targeted changes.',\n        parameters: {\n          type: 'object',\n          properties: {\n            file_path: { type: 'string', description: 'Relative path from project root' },\n            old_string: { type: 'string', description: 'Exact string to find (must match precisely)' },\n            new_string: { type: 'string', description: 'Replacement string' }\n          },\n          required: ['file_path', 'old_string', 'new_string']\n        }\n      },\n      {\n        name: 'replace',\n        description: 'Canonical alias for edit. Replace exact old_string with new_string.',\n        parameters: {\n          type: 'object',\n          properties: {\n            file_path: { type: 'string', description: 'Relative path from project root' },\n            old_string: { type: 'string', description: 'Exact string to replace' },\n            new_string: { type: 'string', description: 'Replacement string' }\n          },\n          required: ['file_path', 'old_string', 'new_string']\n        }\n      },\n      {\n        name: 'shell',\n        description: 'Run a shell command (e.g. npm test, node script.js, cat, ls). Use for build verification, running tests, or commands not covered by other tools.',\n        parameters: {\n          type: 'object',\n          properties: {\n            command: { type: 'string', description: 'Shell command to execute' }\n          },\n          required: ['command']\n        }\n      },\n      {\n        name: 'run_cmd',\n        description: 'Alias for shell. Run a shell command. Prefer this for compatibility with existing prompts.',\n        parameters: {\n          type: 'object',\n          properties: {\n            command: { type: 'string', description: 'Shell command to execute' }\n          },\n          required: ['command']\n        }\n      },\n      {\n        name: 'run_shell_command',\n        description: 'Canonical alias for shell/run_cmd.',\n        parameters: {\n          type: 'object',\n          properties: {\n            command: { type: 'string', description: 'Shell command to execute' }\n          },\n          required: ['command']\n        }\n      },\n      {\n        name: 'mkdir',\n        description: 'Create a directory (staged via .gitkeep in sandbox).',\n        parameters: {\n          type: 'object',\n          properties: {\n            path: { type: 'string', description: 'Directory path to create' },\n            dir_path: { type: 'string', description: 'Alternate directory path field' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'list',\n        description: 'List files and directories for a path.',\n        parameters: {\n          type: 'object',\n          properties: {\n            path: { type: 'string', description: 'Path to list (default: .)' },\n            dir_path: { type: 'string', description: 'Alternate path field' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'list_directory',\n        description: 'Canonical alias for list.',\n        parameters: {\n          type: 'object',\n          properties: {\n            dir_path: { type: 'string', description: 'Directory path to list (default: .)' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'git',\n        description: 'Run git subcommands (status, diff, log, show, branch). Use to understand repo state and recent changes.',\n        parameters: {\n          type: 'object',\n          properties: {\n            command: { type: 'string', description: 'Git subcommand (e.g. \"diff HEAD~3\", \"log --oneline -10\")' }\n          },\n          required: ['command']\n        }\n      },\n      {\n        name: 'lsp',\n        description: 'Code intelligence: \"symbols <file>\" for outline, \"refs <file:line:col>\" for references, \"goto <file:line:col>\" for definition, \"diagnostics\" for type errors.',\n        parameters: {\n          type: 'object',\n          properties: {\n            query: { type: 'string', description: 'LSP query (e.g. \"symbols src/app.ts\", \"goto src/app.ts:42:5\")' }\n          },\n          required: ['query']\n        }\n      },\n      {\n        name: 'web_search',\n        description: 'Search the web via Brave Search API (requires BRAVE_API_KEY).',\n        parameters: {\n          type: 'object',\n          properties: {\n            query: { type: 'string', description: 'Search query' }\n          },\n          required: ['query']\n        }\n      },\n      {\n        name: 'google_web_search',\n        description: 'Canonical alias for web_search.',\n        parameters: {\n          type: 'object',\n          properties: {\n            query: { type: 'string', description: 'Search query' }\n          },\n          required: ['query']\n        }\n      },\n      {\n        name: 'web_fetch',\n        description: 'Fetch content from a URL and return cleaned text for analysis.',\n        parameters: {\n          type: 'object',\n          properties: {\n            url: { type: 'string', description: 'http(s) URL to fetch' }\n          },\n          required: ['url']\n        }\n      },\n      {\n        name: 'read_many_files',\n        description: 'Read multiple files by include glob and return concatenated excerpts.',\n        parameters: {\n          type: 'object',\n          properties: {\n            include: { type: 'string', description: 'Glob include pattern (default: **/*)' },\n            exclude: { type: 'string', description: 'Optional exclude glob' },\n            recursive: { type: 'boolean', description: 'Recursive search (optional)' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'save_memory',\n        description: 'Save a memory fact to local project memory log.',\n        parameters: {\n          type: 'object',\n          properties: {\n            fact: { type: 'string', description: 'Memory fact to persist' }\n          },\n          required: ['fact']\n        }\n      },\n      {\n        name: 'write_todos',\n        description: 'Persist todo items for the current project.',\n        parameters: {\n          type: 'object',\n          properties: {\n            todos: { type: 'array', description: 'Todo items array' }\n          },\n          required: ['todos']\n        }\n      },\n      {\n        name: 'get_internal_docs',\n        description: 'Read internal docs by relative path (default AGENTS.md).',\n        parameters: {\n          type: 'object',\n          properties: {\n            path: { type: 'string', description: 'Relative doc path' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'ask_user',\n        description: 'Non-interactive placeholder for ask-user; returns summarized questions.',\n        parameters: {\n          type: 'object',\n          properties: {\n            questions: { type: 'array', description: 'Question descriptors' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'enter_plan_mode',\n        description: 'Enter plan mode (no-op marker in CLI adapter).',\n        parameters: {\n          type: 'object',\n          properties: {\n            reason: { type: 'string', description: 'Plan mode reason' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'exit_plan_mode',\n        description: 'Exit plan mode (no-op marker in CLI adapter).',\n        parameters: {\n          type: 'object',\n          properties: {\n            plan_path: { type: 'string', description: 'Optional plan file path' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'activate_skill',\n        description: 'Activate a named skill (adapter acknowledgment).',\n        parameters: {\n          type: 'object',\n          properties: {\n            name: { type: 'string', description: 'Skill name' }\n          },\n          required: ['name']\n        }\n      },\n      {\n        name: 'tracker_create_task',\n        description: 'Create tracker task in local .crew/tracker.json.',\n        parameters: {\n          type: 'object',\n          properties: {\n            title: { type: 'string' },\n            description: { type: 'string' },\n            type: { type: 'string' },\n            parentId: { type: 'string' },\n            dependencies: { type: 'array' }\n          },\n          required: ['title', 'description', 'type']\n        }\n      },\n      {\n        name: 'tracker_update_task',\n        description: 'Update tracker task by id.',\n        parameters: {\n          type: 'object',\n          properties: {\n            id: { type: 'string' },\n            title: { type: 'string' },\n            description: { type: 'string' },\n            status: { type: 'string' },\n            dependencies: { type: 'array' }\n          },\n          required: ['id']\n        }\n      },\n      {\n        name: 'tracker_get_task',\n        description: 'Get tracker task by id.',\n        parameters: {\n          type: 'object',\n          properties: {\n            id: { type: 'string' }\n          },\n          required: ['id']\n        }\n      },\n      {\n        name: 'tracker_list_tasks',\n        description: 'List tracker tasks with optional filters.',\n        parameters: {\n          type: 'object',\n          properties: {\n            status: { type: 'string' },\n            type: { type: 'string' },\n            parentId: { type: 'string' }\n          },\n          required: []\n        }\n      },\n      {\n        name: 'tracker_add_dependency',\n        description: 'Add dependency between tracker tasks.',\n        parameters: {\n          type: 'object',\n          properties: {\n            taskId: { type: 'string' },\n            dependencyId: { type: 'string' }\n          },\n          required: ['taskId', 'dependencyId']\n        }\n      },\n      {\n        name: 'tracker_visualize',\n        description: 'Visualize tracker tasks as ASCII list.',\n        parameters: {\n          type: 'object',\n          properties: {},\n          required: []\n        }\n      }\n    ];\n    }\n\n    // Filter by constraint level \u2014 removes tools the worker shouldn't see\n    if (this._constraintLevel !== 'full') {\n      allDecls = allDecls.filter((d) => toolAllowedAtLevel(d.name, this._constraintLevel));\n    }\n    return allDecls;\n  }\n\n  // \u2500\u2500\u2500 Worktree Isolation Tools \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private enterWorktreeTool(params: { branch_prefix?: string; agent_id?: string }): ToolResult {\n    try {\n      const info = enterWorktree(this.sandbox.getBaseDir() || process.cwd(), {\n        branchPrefix: params.branch_prefix,\n        agentId: params.agent_id\n      });\n      return {\n        success: true,\n        output: JSON.stringify({\n          worktreePath: info.worktreePath,\n          branchName: info.branchName,\n          baseBranch: info.baseBranch,\n          message: `Created worktree at ${info.worktreePath} on branch ${info.branchName}`\n        })\n      };\n    } catch (err: unknown) {\n      return { success: false, error: errMsg(err) };\n    }\n  }\n\n  private async exitWorktreeTool(params: { branch_name: string }): Promise<ToolResult> {\n    if (!params.branch_name) return { success: false, error: 'exit_worktree requires branch_name' };\n    try {\n      const result = await exitWorktree(this.sandbox.getBaseDir() || process.cwd(), params.branch_name);\n      return {\n        success: true,\n        output: JSON.stringify({\n          hasChanges: result.hasChanges,\n          branchName: result.branchName,\n          commitCount: result.commitCount,\n          message: result.hasChanges\n            ? `Worktree exited with ${result.commitCount} commits on ${result.branchName}. Use merge_worktree to merge.`\n            : `Worktree cleaned up \u2014 no changes were made.`\n        })\n      };\n    } catch (err: unknown) {\n      return { success: false, error: errMsg(err) };\n    }\n  }\n\n  private mergeWorktreeTool(params: { branch_name: string; strategy?: 'merge' | 'squash' }): ToolResult {\n    if (!params.branch_name) return { success: false, error: 'merge_worktree requires branch_name' };\n    try {\n      const result = mergeWorktree(\n        this.sandbox.getBaseDir() || process.cwd(),\n        params.branch_name,\n        params.strategy || 'squash'\n      );\n      return { success: result.success, output: result.message, error: result.success ? undefined : result.message };\n    } catch (err: unknown) {\n      return { success: false, error: errMsg(err) };\n    }\n  }\n\n  private listWorktreesTool(): ToolResult {\n    const trees = listWorktrees();\n    if (trees.length === 0) {\n      return { success: true, output: 'No active worktrees.' };\n    }\n    return {\n      success: true,\n      output: JSON.stringify(trees.map(t => ({\n        branch: t.branchName,\n        path: t.worktreePath,\n        baseBranch: t.baseBranch,\n        createdAt: t.createdAt\n      })), null, 2)\n    };\n  }\n\n  // \u2500\u2500\u2500 Unified Worktree Tool (dispatches to sub-actions) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private async worktreeUnifiedTool(params: {\n    action: 'enter' | 'exit' | 'merge' | 'list';\n    branch?: string;\n    merge?: boolean;\n    projectDir?: string;\n  }): Promise<ToolResult> {\n    const { action, branch, projectDir } = params;\n    const cwd = projectDir || this.sandbox.getBaseDir() || process.cwd();\n\n    switch (action) {\n      case 'enter':\n        return this.enterWorktreeTool({ branch_prefix: branch, agent_id: undefined });\n      case 'exit':\n        if (!branch) return { success: false, error: 'branch is required for exit action' };\n        return await this.exitWorktreeTool({ branch_name: branch });\n      case 'merge':\n        if (!branch) return { success: false, error: 'branch is required for merge action' };\n        return this.mergeWorktreeTool({ branch_name: branch, strategy: 'merge' });\n      case 'list':\n        return this.listWorktreesTool();\n      default:\n        return { success: false, error: `Unknown worktree action: ${action}` };\n    }\n  }\n\n  // \u2500\u2500\u2500 Sleep Tool \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private async sleepTool(params: { duration_ms: number; reason?: string }): Promise<ToolResult> {\n    const MAX_SLEEP_MS = 60_000;\n    const requested = typeof params.duration_ms === 'number' ? params.duration_ms : 0;\n    const actual = Math.min(Math.max(0, requested), MAX_SLEEP_MS);\n    const reason = params.reason || 'no reason given';\n\n    await new Promise<void>(resolve => setTimeout(resolve, actual));\n\n    const cappedNote = requested > MAX_SLEEP_MS ? ` (requested ${requested}ms, capped at ${MAX_SLEEP_MS}ms)` : '';\n    return {\n      success: true,\n      output: JSON.stringify({ sleptMs: actual, reason, cappedNote: cappedNote || undefined }, null, 2)\n    };\n  }\n\n  // \u2500\u2500\u2500 Tool Search Tool \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private toolSearchTool(params: { query: string; max_results?: number }): ToolResult {\n    const query = (params.query || '').trim().toLowerCase();\n    if (!query) return { success: false, error: 'query is required' };\n    const maxResults = Math.max(1, params.max_results ?? 10);\n\n    // Use static declarations as the source of truth in adapter context\n    const allDecls = this.buildDynamicDeclarations();\n\n    const scored = allDecls\n      .map((decl) => {\n        const name = (decl.name || '').toLowerCase();\n        const desc = (decl.description || '').toLowerCase();\n        let score = 0;\n        if (name === query) score += 100;\n        else if (name.startsWith(query)) score += 60;\n        else if (name.includes(query)) score += 40;\n        if (desc.includes(query)) score += 20;\n        return { decl, score };\n      })\n      .filter(({ score }) => score > 0)\n      .sort((a, b) => b.score - a.score)\n      .slice(0, maxResults);\n\n    if (scored.length === 0) {\n      return { success: true, output: `No tools found matching \"${params.query}\".` };\n    }\n\n    const results = scored.map(({ decl }) => ({\n      name: decl.name,\n      description: decl.description,\n      parameterSchema: decl.parameters || {}\n    }));\n\n    return {\n      success: true,\n      output: JSON.stringify({ query: params.query, count: results.length, results }, null, 2)\n    };\n  }\n}\n", "/**\n * RunState \u2014 Central run ownership for crew-cli execution engine.\n *\n * Every task execution (L1 \u2192 L2 \u2192 L3) is wrapped in a RunState that owns:\n *   - Phase lifecycle (plan \u2192 execute \u2192 review \u2192 qa \u2192 complete/failed)\n *   - Cost tracking per phase and per tool\n *   - Failure memory (what failed, how, don't repeat)\n *   - Verification goals (what proof is needed, what's been proven)\n *   - Context budget and compaction decisions\n *   - Full audit trail\n *\n * This replaces the fragmented state scattered across autonomous-loop,\n * agentic-executor, unified pipeline, and multi-turn-drivers.\n */\n\nimport { randomUUID } from 'node:crypto';\n\n// ---------------------------------------------------------------------------\n// Phase lifecycle\n// ---------------------------------------------------------------------------\n\nexport type RunPhase =\n  | 'init'\n  | 'planning'\n  | 'executing'\n  | 'reviewing'\n  | 'qa'\n  | 'complete'\n  | 'failed'\n  | 'aborted';\n\nexport interface PhaseRecord {\n  phase: RunPhase;\n  startedAt: number;\n  endedAt?: number;\n  costUsd: number;\n  turns: number;\n  notes: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Failure memory\n// ---------------------------------------------------------------------------\n\nexport interface FailureRecord {\n  turn: number;\n  tool: string;\n  params: Record<string, unknown>;\n  error: string;\n  signature: string;        // tool:params hash for dedup\n  count: number;            // how many times this exact failure repeated\n  category: FailureCategory;\n}\n\nexport type FailureCategory =\n  | 'bad-file-selection'    // edited wrong file or nonexistent file\n  | 'bad-tool-choice'       // used wrong tool for the situation\n  | 'bad-retry'             // retried same failing action\n  | 'syntax-error'          // generated code with syntax errors\n  | 'test-failure'          // tests failed after edit\n  | 'scope-violation'       // touched files outside allowed paths\n  | 'context-overflow'      // hit context length limit\n  | 'timeout'               // exceeded time/turn budget\n  | 'unknown';\n\n// ---------------------------------------------------------------------------\n// Verification goals\n// ---------------------------------------------------------------------------\n\nexport interface VerificationGoal {\n  id: string;\n  description: string;      // \"tests pass\", \"file exists\", \"lint clean\"\n  status: 'pending' | 'proven' | 'failed' | 'skipped';\n  provenAt?: number;\n  provenBy?: string;         // tool call that proved it\n  attempts: number;\n}\n\n// ---------------------------------------------------------------------------\n// Cost tracking\n// ---------------------------------------------------------------------------\n\nexport interface CostBreakdown {\n  totalUsd: number;\n  byPhase: Record<string, number>;\n  byTool: Record<string, number>;\n  byModel: Record<string, number>;\n  inputTokens: number;\n  outputTokens: number;\n  cachedTokens: number;\n}\n\n// ---------------------------------------------------------------------------\n// RunState\n// ---------------------------------------------------------------------------\n\nexport interface RunStateSnapshot {\n  id: string;\n  sessionId: string;\n  traceId: string;\n  task: string;\n  phase: RunPhase;\n  phases: PhaseRecord[];\n  failures: FailureRecord[];\n  verificationGoals: VerificationGoal[];\n  cost: CostBreakdown;\n  turns: number;\n  startedAt: number;\n  endedAt?: number;\n  abortReason?: string;\n}\n\nexport class RunState {\n  readonly id: string;\n  readonly sessionId: string;\n  readonly traceId: string;\n  readonly task: string;\n  readonly startedAt: number;\n\n  private _phase: RunPhase = 'init';\n  private _phases: PhaseRecord[] = [];\n  private _currentPhase: PhaseRecord | null = null;\n  private _failures: FailureRecord[] = [];\n  private _failureSignatures = new Map<string, FailureRecord>();\n  private _verificationGoals: VerificationGoal[] = [];\n  private _cost: CostBreakdown = {\n    totalUsd: 0,\n    byPhase: {},\n    byTool: {},\n    byModel: {},\n    inputTokens: 0,\n    outputTokens: 0,\n    cachedTokens: 0\n  };\n  private _turns = 0;\n  private _endedAt?: number;\n  private _abortReason?: string;\n\n  constructor(options: {\n    task: string;\n    sessionId?: string;\n    traceId?: string;\n  }) {\n    this.id = randomUUID();\n    this.sessionId = options.sessionId || randomUUID();\n    this.traceId = options.traceId || randomUUID();\n    this.task = options.task;\n    this.startedAt = Date.now();\n  }\n\n  // \u2500\u2500 Phase lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  get phase(): RunPhase {\n    return this._phase;\n  }\n\n  enterPhase(phase: RunPhase): void {\n    // Close current phase\n    if (this._currentPhase) {\n      this._currentPhase.endedAt = Date.now();\n      this._phases.push(this._currentPhase);\n    }\n\n    this._phase = phase;\n    this._currentPhase = {\n      phase,\n      startedAt: Date.now(),\n      costUsd: 0,\n      turns: 0,\n      notes: []\n    };\n\n    if (phase === 'complete' || phase === 'failed' || phase === 'aborted') {\n      this._currentPhase.endedAt = Date.now();\n      this._phases.push(this._currentPhase);\n      this._currentPhase = null;\n      this._endedAt = Date.now();\n    }\n  }\n\n  addPhaseNote(note: string): void {\n    this._currentPhase?.notes.push(note);\n  }\n\n  // \u2500\u2500 Turn tracking \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  get turns(): number {\n    return this._turns;\n  }\n\n  recordTurn(): void {\n    this._turns += 1;\n    if (this._currentPhase) {\n      this._currentPhase.turns += 1;\n    }\n  }\n\n  // \u2500\u2500 Cost tracking \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  get cost(): Readonly<CostBreakdown> {\n    return this._cost;\n  }\n\n  recordCost(entry: {\n    usd: number;\n    tool?: string;\n    model?: string;\n    inputTokens?: number;\n    outputTokens?: number;\n    cachedTokens?: number;\n  }): void {\n    this._cost.totalUsd += entry.usd;\n    if (this._currentPhase) {\n      this._currentPhase.costUsd += entry.usd;\n      this._cost.byPhase[this._currentPhase.phase] =\n        (this._cost.byPhase[this._currentPhase.phase] || 0) + entry.usd;\n    }\n    if (entry.tool) {\n      this._cost.byTool[entry.tool] = (this._cost.byTool[entry.tool] || 0) + entry.usd;\n    }\n    if (entry.model) {\n      this._cost.byModel[entry.model] = (this._cost.byModel[entry.model] || 0) + entry.usd;\n    }\n    this._cost.inputTokens += entry.inputTokens || 0;\n    this._cost.outputTokens += entry.outputTokens || 0;\n    this._cost.cachedTokens += entry.cachedTokens || 0;\n  }\n\n  // \u2500\u2500 Failure memory \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  get failures(): ReadonlyArray<FailureRecord> {\n    return this._failures;\n  }\n\n  recordFailure(entry: {\n    turn: number;\n    tool: string;\n    params: Record<string, unknown>;\n    error: string;\n    category?: FailureCategory;\n  }): FailureRecord {\n    const signature = `${entry.tool}:${stableHash(entry.params)}`;\n    const existing = this._failureSignatures.get(signature);\n\n    if (existing) {\n      existing.count += 1;\n      existing.error = entry.error; // update with latest error\n      return existing;\n    }\n\n    const record: FailureRecord = {\n      turn: entry.turn,\n      tool: entry.tool,\n      params: entry.params,\n      error: entry.error,\n      signature,\n      count: 1,\n      category: entry.category || classifyFailure(entry.tool, entry.error)\n    };\n\n    this._failures.push(record);\n    this._failureSignatures.set(signature, record);\n    return record;\n  }\n\n  /**\n   * Check if a proposed tool call has already failed.\n   * Returns the failure record if it's a known bad move, null otherwise.\n   */\n  wouldRepeatFailure(tool: string, params: Record<string, unknown>): FailureRecord | null {\n    const signature = `${tool}:${stableHash(params)}`;\n    const record = this._failureSignatures.get(signature);\n    // Block after 1 failure for shell commands (retrying the same failing command is wasteful),\n    // after 2 failures for other tools (might succeed with different context)\n    const threshold = (tool === 'run_shell_command' || tool === 'shell' || tool === 'run_cmd') ? 1 : 2;\n    if (record && record.count >= threshold) return record;\n    return null;\n  }\n\n  /**\n   * Build a failure-avoidance prompt for the LLM.\n   * Tells the model what NOT to do based on observed failures.\n   */\n  buildFailureContext(): string {\n    if (this._failures.length === 0) return '';\n\n    const repeated = this._failures.filter(f => f.count >= 2);\n    const recent = this._failures.slice(-5);\n    const relevant = [...new Set([...repeated, ...recent])];\n\n    if (relevant.length === 0) return '';\n\n    const lines = relevant.map(f => {\n      const paramPreview = JSON.stringify(f.params).slice(0, 100);\n      return `- ${f.tool}(${paramPreview}) failed ${f.count}x: ${f.error.slice(0, 120)}`;\n    });\n\n    return [\n      '## Known failures in this run \u2014 do NOT repeat these:',\n      ...lines,\n      '',\n      'Choose a different approach or different parameters.'\n    ].join('\\n');\n  }\n\n  // \u2500\u2500 Verification goals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  get verificationGoals(): ReadonlyArray<VerificationGoal> {\n    return this._verificationGoals;\n  }\n\n  addVerificationGoal(description: string): VerificationGoal {\n    const goal: VerificationGoal = {\n      id: randomUUID(),\n      description,\n      status: 'pending',\n      attempts: 0\n    };\n    this._verificationGoals.push(goal);\n    return goal;\n  }\n\n  proveGoal(id: string, provenBy: string): void {\n    const goal = this._verificationGoals.find(g => g.id === id);\n    if (goal) {\n      goal.status = 'proven';\n      goal.provenAt = Date.now();\n      goal.provenBy = provenBy;\n    }\n  }\n\n  failGoal(id: string): void {\n    const goal = this._verificationGoals.find(g => g.id === id);\n    if (goal) {\n      goal.status = 'failed';\n      goal.attempts += 1;\n    }\n  }\n\n  /**\n   * Check if all verification goals are satisfied.\n   */\n  allGoalsProven(): boolean {\n    return this._verificationGoals.length > 0 &&\n      this._verificationGoals.every(g => g.status === 'proven' || g.status === 'skipped');\n  }\n\n  /**\n   * Get the next unproven goal (for verification-first loop).\n   */\n  nextUnprovenGoal(): VerificationGoal | null {\n    return this._verificationGoals.find(g => g.status === 'pending') || null;\n  }\n\n  /**\n   * Build a verification prompt for the LLM.\n   */\n  buildVerificationContext(): string {\n    if (this._verificationGoals.length === 0) return '';\n\n    const lines = this._verificationGoals.map(g => {\n      const status = g.status === 'proven' ? '[PROVEN]'\n        : g.status === 'failed' ? `[FAILED x${g.attempts}]`\n        : '[PENDING]';\n      return `${status} ${g.description}`;\n    });\n\n    return [\n      '## Verification goals \u2014 prove each one before declaring done:',\n      ...lines\n    ].join('\\n');\n  }\n\n  // \u2500\u2500 Abort \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  abort(reason: string): void {\n    this._abortReason = reason;\n    this.enterPhase('aborted');\n  }\n\n  get isAborted(): boolean {\n    return this._phase === 'aborted';\n  }\n\n  // \u2500\u2500 Budget checks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  isOverBudget(maxUsd: number): boolean {\n    return this._cost.totalUsd >= maxUsd;\n  }\n\n  isOverTurns(maxTurns: number): boolean {\n    return this._turns >= maxTurns;\n  }\n\n  // \u2500\u2500 Snapshot for persistence/logging \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  snapshot(): RunStateSnapshot {\n    return {\n      id: this.id,\n      sessionId: this.sessionId,\n      traceId: this.traceId,\n      task: this.task,\n      phase: this._phase,\n      phases: [...this._phases],\n      failures: [...this._failures],\n      verificationGoals: [...this._verificationGoals],\n      cost: { ...this._cost },\n      turns: this._turns,\n      startedAt: this.startedAt,\n      endedAt: this._endedAt,\n      abortReason: this._abortReason\n    };\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction stableHash(obj: Record<string, unknown>): string {\n  const keys = Object.keys(obj).sort();\n  const parts = keys.map(k => `${k}:${JSON.stringify(obj[k]) || ''}`);\n  return parts.join('|').slice(0, 200);\n}\n\nfunction classifyFailure(tool: string, error: string): FailureCategory {\n  const e = error.toLowerCase();\n  if (e.includes('no such file') || e.includes('enoent') || e.includes('not found')) {\n    return 'bad-file-selection';\n  }\n  if (e.includes('syntax') || e.includes('parse error') || e.includes('unexpected token')) {\n    return 'syntax-error';\n  }\n  if (e.includes('test') && (e.includes('fail') || e.includes('assert'))) {\n    return 'test-failure';\n  }\n  if (e.includes('context') && (e.includes('length') || e.includes('too long'))) {\n    return 'context-overflow';\n  }\n  if (e.includes('timeout') || e.includes('timed out')) {\n    return 'timeout';\n  }\n  if (e.includes('scope') || e.includes('outside allowed') || e.includes('permission')) {\n    return 'scope-violation';\n  }\n  return 'unknown';\n}\n", "/**\n * Tool Result Clearing\n *\n * When message history grows long, old tool results consume most of the context\n * window.  This module replaces result bodies for older turns with a compact\n * placeholder while preserving the tool name and an approximate size hint.\n *\n * The LLM is instructed (via a system-prompt addendum) to write down any\n * important data it will need later, because old results will be cleared.\n */\n\nimport type { TurnResult } from '../worker/autonomous-loop.js';\n\nexport interface ClearingConfig {\n  /**\n   * Keep this many of the most-recent turns' results fully intact.\n   * Default: 5\n   */\n  keepRecent?: number;\n\n  /**\n   * Truncate individual results that exceed this character length even within\n   * the \"keep recent\" window.  0 = no per-result truncation.\n   * Default: 2000\n   */\n  maxResultLength?: number;\n}\n\nconst DEFAULT_KEEP_RECENT = 5;\nconst DEFAULT_MAX_RESULT_LENGTH = 2000;\n\n/**\n * Returns a new history array where tool results for all but the most-recent\n * `keepRecent` turns are replaced with a compact placeholder string.\n *\n * Results within the recent window are returned as-is, unless their string\n * representation exceeds `maxResultLength` \u2014 in that case they are truncated\n * and a note is appended.\n *\n * The original array is never mutated.\n */\nexport function clearOldToolResults(history: TurnResult[], config?: ClearingConfig): TurnResult[] {\n  const keepRecent = config?.keepRecent ?? DEFAULT_KEEP_RECENT;\n  const maxResultLength = config?.maxResultLength ?? DEFAULT_MAX_RESULT_LENGTH;\n\n  if (history.length === 0) return [];\n\n  // Index of the first turn that is considered \"recent\"\n  const cutoff = Math.max(0, history.length - keepRecent);\n\n  return history.map((entry, idx): TurnResult => {\n    if (idx < cutoff) {\n      // Compute original byte count for the placeholder\n      const resultStr =\n        typeof entry.result === 'string'\n          ? entry.result\n          : JSON.stringify(entry.result ?? '');\n      const bytes = Buffer.byteLength(resultStr, 'utf8');\n\n      return {\n        ...entry,\n        result: `[Result cleared \u2014 ${entry.tool} returned ${bytes} bytes]`,\n      };\n    }\n\n    // Recent turn \u2014 keep intact but optionally truncate\n    if (maxResultLength > 0) {\n      const resultStr =\n        typeof entry.result === 'string'\n          ? entry.result\n          : JSON.stringify(entry.result ?? '');\n      if (resultStr.length > maxResultLength) {\n        const truncated =\n          typeof entry.result === 'string'\n            ? entry.result.slice(0, maxResultLength) +\n              `\\n[...truncated ${resultStr.length - maxResultLength} chars]`\n            : resultStr.slice(0, maxResultLength) +\n              `\\n[...truncated ${resultStr.length - maxResultLength} chars]`;\n        return { ...entry, result: truncated };\n      }\n    }\n\n    return entry;\n  });\n}\n\n/**\n * System-prompt addendum to append when tool-result clearing is active.\n * Encourages the model to write down key data before results are cleared.\n */\nexport const TOOL_RESULT_CLEARING_PROMPT =\n  '\\n\\nWhen working with tool results, write down any important information ' +\n  'you might need later in your response, as the original tool result may be ' +\n  'cleared later to free up context space.';\n", "/**\n * Smart Tool Batching\n *\n * Partitions LLM tool calls into smart batches:\n *   - Read-only tools run concurrently in a batch\n *   - Write tools run one at a time, serially\n *   - Mixed sequences are split into alternating concurrent/serial batches\n *\n * Example: [grep, grep, file_write, file_read]\n *   \u2192 batch1 = concurrent [grep, grep]\n *   \u2192 batch2 = serial     [file_write]\n *   \u2192 batch3 = concurrent [file_read]\n */\n\nimport type { ToolCall } from '../worker/autonomous-loop.js';\n\nexport type { ToolCall };\n\n/**\n * Tool names that are safe to run concurrently \u2014 they only read state,\n * never mutate the filesystem or execute processes.\n */\nconst READ_ONLY_TOOLS = new Set([\n  'file_read',\n  'read_file',\n  'read_many_files',\n  'grep',\n  'grep_search',\n  'glob',\n  'find_files',\n  'search_code',\n  'web_search',\n  'google_web_search',\n  'web_fetch',\n  'find_functions',\n  'find_classes',\n  'list_directory',\n  'ls',\n  'git_log',\n  'git_diff',\n  'git_status',\n  'git_show',\n  'git_blame',\n  'get_internal_docs',\n]);\n\n/**\n * Returns true if this tool name is safe to run concurrently with other\n * read-only tools.  Any tool not in the allow-list is treated as a write.\n */\nexport function isConcurrencySafe(toolName: string): boolean {\n  return READ_ONLY_TOOLS.has(toolName);\n}\n\nexport interface ToolBatch {\n  /** When true, all calls in this batch may run in parallel. */\n  concurrent: boolean;\n  calls: ToolCall[];\n}\n\n/**\n * Partition an ordered list of tool calls into ToolBatches.\n *\n * Consecutive read-only calls collapse into a single concurrent batch.\n * Each write call becomes its own serial batch (so side-effects remain ordered).\n *\n * An empty input returns an empty array.\n */\nexport function partitionToolCalls(calls: ToolCall[]): ToolBatch[] {\n  if (calls.length === 0) return [];\n\n  const batches: ToolBatch[] = [];\n  let current: ToolBatch | null = null;\n\n  for (const call of calls) {\n    const safe = isConcurrencySafe(call.tool);\n\n    if (safe) {\n      // Append to open concurrent batch or start a new one\n      if (current && current.concurrent) {\n        current.calls.push(call);\n      } else {\n        current = { concurrent: true, calls: [call] };\n        batches.push(current);\n      }\n    } else {\n      // Write tool: always gets its own serial batch\n      current = { concurrent: false, calls: [call] };\n      batches.push(current);\n      // Reset so the next read-only starts a fresh concurrent batch\n      current = null;\n    }\n  }\n\n  return batches;\n}\n", "import type { TurnResult } from '../worker/autonomous-loop.js';\n\nexport type TaskMode = 'bugfix' | 'feature' | 'refactor' | 'test_repair' | 'analysis';\n\nconst READ_TOOLS = new Set(['read_file', 'read_many_files', 'glob', 'grep_search', 'list_directory', 'lsp']);\nconst EDIT_TOOLS = new Set(['replace', 'edit', 'append_file', 'write_file', 'notebook_edit']);\nconst VERIFY_TOOLS = new Set(['run_shell_command', 'shell', 'run_cmd', 'check_background_task']);\n\nfunction normalizeText(value: string): string {\n  return value.trim().toLowerCase();\n}\n\nfunction extractTarget(params: Record<string, unknown>): string | undefined {\n  const candidate = params.file_path\n    ?? params.path\n    ?? params.include\n    ?? params.pattern\n    ?? params.command;\n  return typeof candidate === 'string' && candidate.trim() ? candidate.trim() : undefined;\n}\n\nfunction isReadTool(result: TurnResult): boolean {\n  return READ_TOOLS.has(result.tool);\n}\n\nfunction isEditTool(result: TurnResult): boolean {\n  return EDIT_TOOLS.has(result.tool);\n}\n\nfunction isVerificationTool(result: TurnResult): boolean {\n  return VERIFY_TOOLS.has(result.tool);\n}\n\nfunction isSuccessfulVerification(result: TurnResult): boolean {\n  if (!isVerificationTool(result) || result.error) return false;\n  const output = typeof result.result === 'string'\n    ? result.result\n    : JSON.stringify(result.result ?? '');\n  const normalized = normalizeText(output);\n  return !normalized.includes('error') && !normalized.includes('failed');\n}\n\nfunction unreadEditTargets(history: TurnResult[]): string[] {\n  const reads = new Set(\n    history\n      .filter(r => !r.error && isReadTool(r))\n      .map(r => extractTarget(r.params))\n      .filter((value): value is string => Boolean(value))\n  );\n\n  return history\n    .filter(r => !r.error && isEditTool(r))\n    .map(r => extractTarget(r.params))\n    .filter((value): value is string => Boolean(value))\n    .filter(target => !reads.has(target));\n}\n\nfunction repeatedFailure(history: TurnResult[]): string | undefined {\n  const recentFailures = history\n    .slice(-6)\n    .filter(r => Boolean(r.error))\n    .map(r => `${r.tool}:${JSON.stringify(r.params)}`);\n  if (recentFailures.length < 2) return undefined;\n  const counts = new Map<string, number>();\n  for (const signature of recentFailures) {\n    counts.set(signature, (counts.get(signature) || 0) + 1);\n  }\n  const repeated = [...counts.entries()].find(([, count]) => count >= 2);\n  return repeated?.[0];\n}\n\nexport function detectTaskMode(task: string): TaskMode {\n  const normalized = normalizeText(task);\n  if (/(failing tests?|test failure|fix tests?|fix the test|make tests? pass|regression test|unit test|test.*(fail|broken|error))/.test(normalized)) {\n    return 'test_repair';\n  }\n  if (/(fix|bug|broken|error|regression|crash|issue|failure)/.test(normalized)) {\n    return 'bugfix';\n  }\n  if (/(refactor|cleanup|restructure|rename|simplify|extract)/.test(normalized)) {\n    return 'refactor';\n  }\n  if (/(add|implement|create|build|support|introduce)/.test(normalized)) {\n    return 'feature';\n  }\n  return 'analysis';\n}\n\nexport function buildTaskModeGuidance(mode: TaskMode): string {\n  const strategyByMode: Record<TaskMode, string> = {\n    bugfix: 'Task mode: bugfix. Reproduce the failure with the smallest useful signal, make the narrowest fix, then run the most targeted verification command before stopping.',\n    feature: 'Task mode: feature. Read the affected files first, implement the smallest complete change that satisfies the request, then verify the touched path with focused checks.',\n    refactor: 'Task mode: refactor. Preserve behavior, prefer small surgical edits, and run typecheck or the narrowest affected tests before finishing.',\n    test_repair: 'Task mode: test repair. Start from the failing test signal, change only what explains the failure, and rerun the targeted test before broader verification.',\n    analysis: 'Task mode: analysis. Gather only the context needed for the task, avoid speculative edits, and verify any code changes with the smallest useful command.'\n  };\n  return strategyByMode[mode];\n}\n\nexport function buildTurnGuidance(\n  mode: TaskMode,\n  history: TurnResult[],\n  turnResults: TurnResult[]\n): string | undefined {\n  const messages: string[] = [];\n  const editedThisTurn = turnResults.some(r => !r.error && isEditTool(r));\n  const verifiedAtLeastOnce = history.some(isSuccessfulVerification);\n\n  const unreadTargets = unreadEditTargets(history);\n  if (unreadTargets.length > 0) {\n    messages.push(`Read before editing on the next step. Re-open the exact file section for: ${[...new Set(unreadTargets)].slice(0, 3).join(', ')}.`);\n  }\n\n  if (editedThisTurn && !verifiedAtLeastOnce) {\n    const verificationHint = mode === 'test_repair'\n      ? 'Run the failing test or the narrowest related test command before more edits.'\n      : mode === 'refactor'\n        ? 'Run typecheck or the narrowest affected test before declaring the refactor done.'\n        : 'Run the smallest useful verification command before finishing.';\n    messages.push(verificationHint);\n  }\n\n  const repeated = repeatedFailure(history);\n  if (repeated) {\n    messages.push(`Do not repeat the same failing action again: ${repeated.slice(0, 120)}. Switch tactics or inspect a narrower target.`);\n  }\n\n  return messages.length > 0\n    ? `Execution guidance:\\n- ${messages.join('\\n- ')}`\n    : undefined;\n}\n", "/**\n * Action Ranking \u2014 Real-time next-action scorer for the execution loop.\n *\n * Each turn, scores candidate action types based on execution state:\n * what's been read, edited, verified, what failed, and the task mode.\n * Returns ranked suggestions injected into the LLM prompt to steer\n * behavior toward the highest-value next step.\n */\n\nimport type { TurnResult } from '../worker/autonomous-loop.js';\nimport type { TaskMode } from './agentic-guidance.js';\n\n// ---------------------------------------------------------------------------\n// Action types\n// ---------------------------------------------------------------------------\n\nexport type ActionType =\n  | 'read'       // read/inspect a file\n  | 'search'     // grep/glob/find\n  | 'edit'       // write/replace/append\n  | 'test'       // run tests\n  | 'build'      // compile/typecheck/lint\n  | 'verify'     // any verification command\n  | 'delegate';  // sub-agent dispatch\n\nexport interface ActionScore {\n  action: ActionType;\n  score: number;      // 0\u20131, higher = more valuable right now\n  reason: string;     // human-readable explanation for the LLM\n}\n\n// ---------------------------------------------------------------------------\n// Tool classification\n// ---------------------------------------------------------------------------\n\nconst READ_TOOLS = new Set([\n  'read_file', 'read_many_files', 'glob', 'list_directory', 'lsp'\n]);\nconst SEARCH_TOOLS = new Set([\n  'grep_search', 'glob', 'search_files', 'find_definition'\n]);\nconst EDIT_TOOLS = new Set([\n  'replace', 'edit', 'append_file', 'write_file', 'notebook_edit'\n]);\nconst SHELL_TOOLS = new Set([\n  'run_shell_command', 'shell', 'run_cmd', 'check_background_task'\n]);\n\nfunction classifyTool(tool: string): ActionType | null {\n  if (READ_TOOLS.has(tool)) return 'read';\n  if (SEARCH_TOOLS.has(tool)) return 'search';\n  if (EDIT_TOOLS.has(tool)) return 'edit';\n  if (SHELL_TOOLS.has(tool)) return isTestCommand(tool) ? 'test' : 'verify';\n  return null;\n}\n\nfunction isTestCommand(command: string): boolean {\n  const lower = command.toLowerCase();\n  return /\\b(test|spec|jest|vitest|pytest|mocha)\\b/.test(lower);\n}\n\nfunction isBuildCommand(command: string): boolean {\n  const lower = command.toLowerCase();\n  return /\\b(build|tsc|typecheck|lint|eslint)\\b/.test(lower);\n}\n\nfunction extractTarget(params: Record<string, unknown>): string | undefined {\n  const candidate = params.file_path ?? params.path ?? params.include ?? params.pattern ?? params.command;\n  return typeof candidate === 'string' && candidate.trim() ? candidate.trim() : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// State analysis\n// ---------------------------------------------------------------------------\n\ninterface ExecutionSnapshot {\n  filesRead: Set<string>;\n  filesEdited: Set<string>;\n  unverifiedEdits: Set<string>;   // edited but no test/build since\n  hasRunTests: boolean;\n  hasRunBuild: boolean;\n  recentFailureTools: Set<string>;\n  totalTurns: number;\n  editTurns: number;              // turns that contained edits\n  lastActionType: ActionType | null;\n  consecutiveSameAction: number;\n}\n\nfunction analyzeHistory(history: TurnResult[]): ExecutionSnapshot {\n  const filesRead = new Set<string>();\n  const filesEdited = new Set<string>();\n  const unverifiedEdits = new Set<string>();\n  let hasRunTests = false;\n  let hasRunBuild = false;\n  const recentFailureTools = new Set<string>();\n  let editTurns = 0;\n  let lastActionType: ActionType | null = null;\n  let consecutiveSameAction = 0;\n\n  let lastTurnHadEdit = false;\n\n  for (const turn of history) {\n    const actionType = classifyTool(turn.tool);\n\n    // Track consecutive same-action\n    if (actionType === lastActionType) {\n      consecutiveSameAction++;\n    } else {\n      consecutiveSameAction = 1;\n      lastActionType = actionType;\n    }\n\n    // Read tracking\n    if (READ_TOOLS.has(turn.tool) && !turn.error) {\n      const target = extractTarget(turn.params);\n      if (target) filesRead.add(target);\n    }\n\n    // Edit tracking\n    if (EDIT_TOOLS.has(turn.tool) && !turn.error) {\n      const target = extractTarget(turn.params);\n      if (target) {\n        filesEdited.add(target);\n        unverifiedEdits.add(target);\n      }\n      if (!lastTurnHadEdit) {\n        editTurns++;\n        lastTurnHadEdit = true;\n      }\n    } else {\n      lastTurnHadEdit = false;\n    }\n\n    // Shell command analysis\n    if (SHELL_TOOLS.has(turn.tool)) {\n      const cmd = String(turn.params.command || '');\n      if (isTestCommand(cmd) && !turn.error) {\n        hasRunTests = true;\n        unverifiedEdits.clear(); // tests cover all edits\n      }\n      if (isBuildCommand(cmd) && !turn.error) {\n        hasRunBuild = true;\n      }\n    }\n\n    // Recent failures (last 5 turns)\n    if (turn.error) {\n      recentFailureTools.add(turn.tool);\n    }\n  }\n\n  // Only keep recent failures (last 5)\n  const recentHistory = history.slice(-5);\n  recentFailureTools.clear();\n  for (const turn of recentHistory) {\n    if (turn.error) recentFailureTools.add(turn.tool);\n  }\n\n  return {\n    filesRead,\n    filesEdited,\n    unverifiedEdits,\n    hasRunTests,\n    hasRunBuild,\n    recentFailureTools,\n    totalTurns: history.length,\n    editTurns,\n    lastActionType,\n    consecutiveSameAction\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Scoring\n// ---------------------------------------------------------------------------\n\n/** Mode-specific base weights for action types. */\nconst DEFAULT_MODE_WEIGHTS: Record<TaskMode, Record<ActionType, number>> = {\n  bugfix: {\n    read: 0.3, search: 0.3, edit: 0.2, test: 0.8, build: 0.3, verify: 0.7, delegate: 0.1\n  },\n  feature: {\n    read: 0.5, search: 0.3, edit: 0.4, test: 0.6, build: 0.4, verify: 0.5, delegate: 0.2\n  },\n  refactor: {\n    read: 0.4, search: 0.2, edit: 0.3, test: 0.5, build: 0.7, verify: 0.6, delegate: 0.1\n  },\n  test_repair: {\n    read: 0.4, search: 0.2, edit: 0.3, test: 0.9, build: 0.2, verify: 0.4, delegate: 0.1\n  },\n  analysis: {\n    read: 0.7, search: 0.6, edit: 0.1, test: 0.2, build: 0.1, verify: 0.2, delegate: 0.3\n  }\n};\n\n// ---------------------------------------------------------------------------\n// Adaptive weights \u2014 learn from autoharness trajectory scores\n// ---------------------------------------------------------------------------\n\n/** Trajectory feedback from past runs, keyed by task mode */\nexport interface TrajectoryFeedback {\n  mode: TaskMode;\n  score: number;           // 0\u20131 trajectory score\n  toolDistribution: Record<ActionType, number>;  // fraction of actions per type\n  success: boolean;\n}\n\n/**\n * Compute adjusted weights from historical trajectory feedback.\n * High-scoring runs boost the weights of their dominant action types.\n * Low-scoring runs penalize theirs.\n */\nexport function computeAdaptiveWeights(\n  feedback: TrajectoryFeedback[],\n  baseWeights: Record<TaskMode, Record<ActionType, number>> = DEFAULT_MODE_WEIGHTS\n): Record<TaskMode, Record<ActionType, number>> {\n  if (feedback.length === 0) return baseWeights;\n\n  const result: Record<string, Record<string, number>> = {};\n  for (const [mode, weights] of Object.entries(baseWeights)) {\n    result[mode] = { ...weights };\n  }\n\n  // Group feedback by mode\n  const byMode = new Map<string, TrajectoryFeedback[]>();\n  for (const f of feedback) {\n    const arr = byMode.get(f.mode) || [];\n    arr.push(f);\n    byMode.set(f.mode, arr);\n  }\n\n  for (const [mode, runs] of byMode) {\n    if (!result[mode] || runs.length < 3) continue; // need enough signal\n\n    const weights = result[mode];\n    const LEARNING_RATE = 0.1;\n\n    for (const run of runs) {\n      // Score deviation from 0.5 midpoint \u2014 positive means good run, negative means bad\n      const signal = (run.score - 0.5) * (run.success ? 1 : -0.5);\n\n      for (const [action, fraction] of Object.entries(run.toolDistribution)) {\n        if (action in weights && fraction > 0.05) {\n          // Boost weights for actions that dominated high-scoring runs,\n          // penalize weights for actions that dominated low-scoring runs\n          weights[action] = Math.max(0.05, Math.min(0.95,\n            weights[action] + signal * fraction * LEARNING_RATE\n          ));\n        }\n      }\n    }\n  }\n\n  return result as Record<TaskMode, Record<ActionType, number>>;\n}\n\n// Active weights \u2014 starts as defaults, updated by loadAdaptiveWeights()\nlet MODE_WEIGHTS: Record<TaskMode, Record<ActionType, number>> = { ...DEFAULT_MODE_WEIGHTS };\n\n/**\n * Load adaptive weights from autoharness trajectory data.\n * Call once at startup or periodically to refresh.\n */\nexport function loadAdaptiveWeights(feedback: TrajectoryFeedback[]): void {\n  MODE_WEIGHTS = computeAdaptiveWeights(feedback, DEFAULT_MODE_WEIGHTS);\n}\n\n/** Get the current active weights (default or adaptive) */\nexport function getActiveWeights(): Record<TaskMode, Record<ActionType, number>> {\n  return MODE_WEIGHTS;\n}\n\n/**\n * Score all action types for the current turn.\n * Returns sorted (highest first) with reasons.\n */\nexport function rankActions(\n  history: TurnResult[],\n  taskMode: TaskMode\n): ActionScore[] {\n  const snap = analyzeHistory(history);\n  const baseWeights = MODE_WEIGHTS[taskMode];\n  const scores: ActionScore[] = [];\n\n  for (const action of Object.keys(baseWeights) as ActionType[]) {\n    let score = baseWeights[action];\n    let reason = '';\n\n    // \u2500\u2500 Contextual adjustments \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n    // Boost read if we've edited files we haven't read\n    if (action === 'read') {\n      const unreadEdits = [...snap.filesEdited].filter(f => !snap.filesRead.has(f));\n      if (unreadEdits.length > 0) {\n        score += 0.3;\n        reason = `${unreadEdits.length} edited file(s) not yet read \u2014 read before more edits`;\n      } else if (snap.filesRead.size === 0 && snap.totalTurns < 3) {\n        score += 0.2;\n        reason = 'No files read yet \u2014 understand context first';\n      }\n    }\n\n    // Boost search early in the task\n    if (action === 'search') {\n      if (snap.totalTurns < 4 && snap.filesRead.size < 2) {\n        score += 0.15;\n        reason = 'Early in task \u2014 search to locate relevant code';\n      }\n    }\n\n    // Penalize edit if nothing has been read\n    if (action === 'edit') {\n      if (snap.filesRead.size === 0) {\n        score -= 0.3;\n        reason = 'Nothing read yet \u2014 read first before editing';\n      } else if (snap.unverifiedEdits.size > 2) {\n        score -= 0.2;\n        reason = 'Multiple unverified edits \u2014 verify before more changes';\n      }\n    }\n\n    // Boost test/verify if there are unverified edits\n    if (action === 'test' || action === 'verify') {\n      if (snap.unverifiedEdits.size > 0) {\n        score += 0.35;\n        reason = reason || `${snap.unverifiedEdits.size} unverified edit(s) \u2014 run verification`;\n      }\n      if (snap.editTurns > 0 && !snap.hasRunTests && action === 'test') {\n        score += 0.25;\n        reason = reason || 'Edits made but no tests run yet';\n      }\n    }\n\n    // Boost build/typecheck for refactors\n    if (action === 'build' && taskMode === 'refactor') {\n      if (snap.filesEdited.size > 0 && !snap.hasRunBuild) {\n        score += 0.3;\n        reason = 'Refactor edits need typecheck/build verification';\n      }\n    }\n\n    // Penalize consecutive same action (diminishing returns)\n    if (action === snap.lastActionType && snap.consecutiveSameAction >= 2) {\n      const penalty = Math.min(0.4, snap.consecutiveSameAction * 0.1);\n      score -= penalty;\n      reason = reason || `${snap.consecutiveSameAction} consecutive ${action} actions \u2014 switch tactics`;\n    }\n\n    // Penalize recently-failed tool types (strong penalty \u2014 don't retry what just broke)\n    if (snap.recentFailureTools.size > 0) {\n      const failedActionTypes = new Set<ActionType>();\n      for (const tool of snap.recentFailureTools) {\n        const at = classifyTool(tool);\n        if (at) failedActionTypes.add(at);\n      }\n      if (failedActionTypes.has(action)) {\n        score -= 0.35;\n        reason = `DO NOT retry ${action} \u2014 recent failures. Try a completely different approach`;\n      }\n    }\n\n    scores.push({\n      action,\n      score: Math.max(0, Math.min(1, score)),\n      reason\n    });\n  }\n\n  // Sort descending by score\n  scores.sort((a, b) => b.score - a.score);\n  return scores;\n}\n\n/**\n * Build a prompt-injectable action ranking summary.\n * Only includes the top recommendations (score > threshold).\n */\nexport function buildActionRankingPrompt(\n  history: TurnResult[],\n  taskMode: TaskMode,\n  threshold = 0.4\n): string {\n  const ranked = rankActions(history, taskMode);\n  const top = ranked.filter(r => r.score >= threshold).slice(0, 3);\n\n  if (top.length === 0) return '';\n\n  // Also surface any strong warnings (score near 0)\n  const warnings = ranked.filter(r => r.score < 0.15 && r.reason?.startsWith('DO NOT'));\n\n  const lines = top.map((r, i) => {\n    const label = i === 0 ? 'RECOMMENDED' : 'also good';\n    const reasonSuffix = r.reason ? ` \u2014 ${r.reason}` : '';\n    return `- [${label}] ${r.action}${reasonSuffix}`;\n  });\n\n  const warningLines = warnings.map(r => `- [AVOID] ${r.action} \u2014 ${r.reason}`);\n\n  return [\n    '## Next action priority (follow this guidance):',\n    ...lines,\n    ...(warningLines.length > 0 ? ['', '## Actions to AVOID:',  ...warningLines] : [])\n  ].join('\\n');\n}\n", "/**\n * RunEngine \u2014 Central execution engine for crew-cli.\n *\n * Wraps the autonomous loop with RunState, failure memory, and\n * verification-first execution. This is the single owner of a\n * task execution lifecycle.\n *\n * Usage:\n *   const engine = new RunEngine({ task, sessionId });\n *   const result = await engine.execute(executeLLM, executeTool, config);\n *\n * The engine:\n *   1. Injects failure-avoidance context into each LLM turn\n *   2. Records failures and prevents repeated bad moves\n *   3. Extracts and tracks verification goals from the task\n *   4. Runs a verification-first loop after the main execution\n *   5. Provides a complete RunState snapshot for auditing\n */\n\nimport { RunState, type RunPhase, type FailureRecord } from './run-state.js';\nimport type { ToolCall, TurnResult, AutonomousConfig, AutonomousResult } from '../worker/autonomous-loop.js';\nimport { clearOldToolResults } from '../executor/tool-result-clearing.js';\nimport { partitionToolCalls } from '../executor/tool-batching.js';\nimport { buildTurnGuidance, type TaskMode } from '../execution/agentic-guidance.js';\nimport { buildActionRankingPrompt, loadAdaptiveWeights, type TrajectoryFeedback } from '../execution/action-ranking.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface RunEngineConfig {\n  task: string;\n  sessionId?: string;\n  traceId?: string;\n  maxTurns?: number;\n  maxBudgetUsd?: number;\n  abortSignal?: AbortSignal;\n  tools?: unknown[];\n  model?: string;\n  /** Task mode for strategy selection and action ranking */\n  taskMode?: TaskMode;\n  /** Verification commands to run after execution (e.g., ['npm test', 'npm run lint']) */\n  verificationCommands?: string[];\n  /** Max verification retry cycles */\n  maxVerificationCycles?: number;\n  /** Max extra turns allowed for verification-first gate (default: 3) */\n  maxVerificationGateTurns?: number;\n  onProgress?: (turn: number, action: string) => void;\n}\n\nexport interface RunEngineResult {\n  success: boolean;\n  output: string;\n  history: TurnResult[];\n  runState: RunState;\n  verificationPassed: boolean;\n  failureCount: number;\n  turns: number;\n  costUsd: number;\n}\n\ntype ExecuteLLMFn = (\n  prompt: string,\n  tools: unknown[],\n  history: TurnResult[],\n  abortSignal?: AbortSignal\n) => Promise<{\n  toolCalls?: ToolCall[];\n  response: string;\n  status?: string;\n  costUsd?: number;\n  finishReason?: string;\n}>;\n\ntype ExecuteToolFn = (\n  tool: string,\n  params: Record<string, unknown>,\n  abortSignal?: AbortSignal\n) => Promise<unknown>;\n\n// ---------------------------------------------------------------------------\n// RunEngine\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_TURNS = 25;\nconst DEFAULT_REPEAT_THRESHOLD = 10;\nconst DEFAULT_MAX_VERIFICATION_CYCLES = 2;\nconst DEFAULT_MAX_VERIFICATION_GATE_TURNS = 3;\n\nexport class RunEngine {\n  readonly state: RunState;\n  private config: RunEngineConfig;\n\n  /**\n   * Load adaptive weights from autoharness trajectory data.\n   * Call once at startup to close the feedback loop.\n   */\n  static loadTrajectoryFeedback(feedback: TrajectoryFeedback[]): void {\n    loadAdaptiveWeights(feedback);\n  }\n\n  constructor(config: RunEngineConfig) {\n    this.config = config;\n    this.state = new RunState({\n      task: config.task,\n      sessionId: config.sessionId,\n      traceId: config.traceId\n    });\n\n    // Extract verification goals from task and explicit commands\n    this.extractVerificationGoals(config);\n  }\n\n  /**\n   * Execute the task end-to-end: plan \u2192 execute \u2192 verify.\n   */\n  async execute(\n    executeLLM: ExecuteLLMFn,\n    executeTool: ExecuteToolFn\n  ): Promise<RunEngineResult> {\n    const {\n      maxTurns = DEFAULT_MAX_TURNS,\n      maxBudgetUsd,\n      abortSignal,\n      tools = [],\n      onProgress,\n      taskMode = 'analysis' as TaskMode,\n      maxVerificationCycles = DEFAULT_MAX_VERIFICATION_CYCLES,\n      maxVerificationGateTurns = DEFAULT_MAX_VERIFICATION_GATE_TURNS\n    } = this.config;\n\n    const history: TurnResult[] = [];\n    let lastResponseText = '';\n    let staleCount = 0;\n    let pendingContext = '';\n    let finalResponse = '';\n    let verificationGateTurnsUsed = 0;\n\n    // \u2500\u2500 Execute phase \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    this.state.enterPhase('executing');\n\n    for (let turn = 0; turn < maxTurns; turn++) {\n      if (abortSignal?.aborted) {\n        this.state.abort('Aborted by caller');\n        break;\n      }\n\n      if (maxBudgetUsd && this.state.isOverBudget(maxBudgetUsd)) {\n        this.state.addPhaseNote(`Budget exceeded: $${this.state.cost.totalUsd.toFixed(4)} >= $${maxBudgetUsd}`);\n        break;\n      }\n\n      this.state.recordTurn();\n      onProgress?.(turn + 1, 'THINKING');\n\n      // Build context with failure avoidance + verification goals + action ranking\n      const failureCtx = this.state.buildFailureContext();\n      const verifyCtx = this.state.buildVerificationContext();\n      const actionCtx = buildActionRankingPrompt(history, taskMode);\n      const extraContext = [failureCtx, verifyCtx, actionCtx].filter(Boolean).join('\\n\\n');\n      const effectiveTask = [this.config.task, extraContext, pendingContext].filter(Boolean).join('\\n\\n');\n      pendingContext = '';\n\n      // Clear old tool results to save context\n      const clearedHistory = clearOldToolResults(history);\n\n      // Call LLM\n      let response: { toolCalls?: ToolCall[]; response: string; status?: string; costUsd?: number; finishReason?: string };\n      try {\n        response = await executeLLM(effectiveTask, tools, clearedHistory, abortSignal);\n      } catch (err) {\n        const msg = (err as Error).message || String(err);\n        if (isContextLengthError(msg)) {\n          this.state.addPhaseNote('Context exceeded \u2014 compacting history');\n          // Compact and retry once\n          const compacted = compactTurnHistory(clearedHistory);\n          try {\n            response = await executeLLM(effectiveTask, tools, compacted, abortSignal);\n          } catch {\n            this.state.enterPhase('failed');\n            break;\n          }\n        } else {\n          this.state.enterPhase('failed');\n          break;\n        }\n      }\n\n      // Track cost\n      if (response!.costUsd) {\n        this.state.recordCost({\n          usd: response!.costUsd,\n          model: this.config.model\n        });\n      }\n\n      // Stale response detection\n      if (response!.response === lastResponseText) {\n        staleCount++;\n        if (staleCount >= DEFAULT_REPEAT_THRESHOLD) {\n          this.state.addPhaseNote('Stale response detected \u2014 stopping');\n          break;\n        }\n      } else {\n        staleCount = 0;\n      }\n      lastResponseText = response!.response;\n      finalResponse = response!.response;\n\n      // \u2500\u2500 Completion check with verification gate + edit gate \u2500\u2500\u2500\u2500\u2500\n      if (!response!.toolCalls || response!.toolCalls.length === 0) {\n        // Edit gate: for mutation tasks, force the model to actually write files\n        const isMutationMode = taskMode === 'bugfix' || taskMode === 'feature' || taskMode === 'refactor' || taskMode === 'test_repair';\n        const hasEdited = history.some(h => !h.error && (\n          h.tool === 'write_file' || h.tool === 'replace' || h.tool === 'edit' ||\n          h.tool === 'append_file' || h.tool === 'notebook_edit'\n        ));\n        if (isMutationMode && !hasEdited && verificationGateTurnsUsed < maxVerificationGateTurns) {\n          verificationGateTurnsUsed++;\n          this.state.addPhaseNote('Edit gate: model attempted completion without editing any files');\n          pendingContext = [\n            '## STOP \u2014 you have not made any changes yet',\n            'You indicated completion but did not use write_file, replace, or edit to modify any files.',\n            'You MUST use a file-editing tool to make the required changes. Do not just describe the fix \u2014 apply it.',\n            'Use replace or write_file to modify the file, then verify with a test or build command.'\n          ].join('\\n');\n          continue; // force another turn\n        }\n\n        // Verification gate: force proof of work\n        const unprovenGoal = this.state.nextUnprovenGoal();\n        if (unprovenGoal && verificationGateTurnsUsed < maxVerificationGateTurns) {\n          // Hard gate: don't stop \u2014 force verification\n          verificationGateTurnsUsed++;\n          this.state.addPhaseNote(`Verification gate: forcing verification for \"${unprovenGoal.description}\"`);\n          pendingContext = [\n            '## STOP \u2014 verification required before completing',\n            `You indicated completion, but this goal is unproven: \"${unprovenGoal.description}\"`,\n            'Run the verification command or test that proves this goal before finishing.',\n            this.config.verificationCommands?.length\n              ? `Available verification commands: ${this.config.verificationCommands.join(', ')}`\n              : 'Run the most targeted test or check command for the changes you made.'\n          ].join('\\n');\n          continue; // force another turn\n        }\n        break;\n      }\n\n      // Execute tool calls with failure tracking\n      if (response!.toolCalls && response!.toolCalls.length > 0) {\n        const batches = partitionToolCalls(response!.toolCalls);\n\n        for (const batch of batches) {\n          if (abortSignal?.aborted) break;\n\n          for (const call of batch.calls) {\n            // \u2500\u2500 Failure memory: check if this would repeat a known failure\n            // Skip blocking for edit tools \u2014 read-before-edit rejections are\n            // recoverable (model reads file then retries with same params).\n            const isEditTool = ['edit', 'replace', 'edit_file', 'write_file', 'append_file'].includes(call.tool);\n            const wouldRepeat = this.state.wouldRepeatFailure(call.tool, call.params);\n            if (wouldRepeat && !isEditTool) {\n              const skipMsg = `Skipped: already failed ${wouldRepeat.count}x with same params`;\n              history.push({\n                turn: turn + 1,\n                tool: call.tool,\n                params: call.params,\n                result: null,\n                error: skipMsg\n              });\n              this.state.addPhaseNote(`Blocked repeated failure: ${call.tool}`);\n              continue;\n            }\n\n            onProgress?.(turn + 1, `EXECUTING: ${call.tool}`);\n\n            try {\n              const result = await executeTool(call.tool, call.params, abortSignal);\n              history.push({ turn: turn + 1, tool: call.tool, params: call.params, result });\n\n              // Check if this tool call proves a verification goal\n              this.checkVerificationProof(call, result);\n            } catch (error) {\n              const errMsg = (error as Error).message || 'tool execution failed';\n              history.push({ turn: turn + 1, tool: call.tool, params: call.params, result: null, error: errMsg });\n\n              // Record failure for future avoidance\n              this.state.recordFailure({\n                turn: turn + 1,\n                tool: call.tool,\n                params: call.params,\n                error: errMsg\n              });\n            }\n          }\n        }\n      }\n\n      // \u2500\u2500 Per-turn guidance: task-mode coaching + action ranking \u2500\u2500\u2500\u2500\n      const turnResults = history.filter(h => h.turn === turn + 1);\n      const turnGuidance = buildTurnGuidance(taskMode, history, turnResults);\n      if (turnGuidance) {\n        pendingContext = pendingContext\n          ? `${pendingContext}\\n\\n${turnGuidance}`\n          : turnGuidance;\n      }\n    }\n\n    // \u2500\u2500 Verification phase \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    let verificationPassed = false;\n\n    if (this.state.phase !== 'failed' && this.state.phase !== 'aborted') {\n      this.state.enterPhase('qa');\n\n      // Run verification commands if provided\n      if (this.config.verificationCommands && this.config.verificationCommands.length > 0) {\n        for (let cycle = 0; cycle < maxVerificationCycles; cycle++) {\n          const allPassed = await this.runVerificationCycle(\n            executeTool,\n            history,\n            abortSignal\n          );\n\n          if (allPassed) {\n            verificationPassed = true;\n            break;\n          }\n\n          // If verification failed and we have cycles left, let LLM fix\n          if (cycle < maxVerificationCycles - 1) {\n            this.state.addPhaseNote(`Verification cycle ${cycle + 1} failed \u2014 retrying`);\n            const fixPrompt = this.buildVerificationFixPrompt();\n            pendingContext = fixPrompt;\n\n            // One more LLM turn to fix\n            const clearedHistory = clearOldToolResults(history);\n            const fixContext = [this.config.task, fixPrompt, this.state.buildFailureContext()].filter(Boolean).join('\\n\\n');\n            try {\n              const fixResponse = await executeLLM(fixContext, tools, clearedHistory, abortSignal);\n              if (fixResponse.toolCalls) {\n                for (const call of fixResponse.toolCalls) {\n                  try {\n                    const result = await executeTool(call.tool, call.params, abortSignal);\n                    history.push({ turn: this.state.turns + 1, tool: call.tool, params: call.params, result });\n                    this.state.recordTurn();\n                  } catch (error) {\n                    const errMsg = (error as Error).message || 'fix failed';\n                    history.push({ turn: this.state.turns + 1, tool: call.tool, params: call.params, result: null, error: errMsg });\n                    this.state.recordFailure({ turn: this.state.turns + 1, tool: call.tool, params: call.params, error: errMsg });\n                  }\n                }\n              }\n            } catch {\n              // Fix attempt failed, continue to next cycle\n            }\n          }\n        }\n      } else {\n        // No explicit verification commands \u2014 check goal satisfaction\n        verificationPassed = this.state.allGoalsProven() || this.state.verificationGoals.length === 0;\n      }\n\n      this.state.enterPhase(verificationPassed ? 'complete' : 'failed');\n    }\n\n    return {\n      success: this.state.phase === 'complete',\n      output: finalResponse,\n      history,\n      runState: this.state,\n      verificationPassed,\n      failureCount: this.state.failures.length,\n      turns: this.state.turns,\n      costUsd: this.state.cost.totalUsd\n    };\n  }\n\n  // \u2500\u2500 Verification helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private extractVerificationGoals(config: RunEngineConfig): void {\n    // Extract from explicit commands\n    if (config.verificationCommands) {\n      for (const cmd of config.verificationCommands) {\n        this.state.addVerificationGoal(`Command passes: ${cmd}`);\n      }\n    }\n\n    // Extract from task text (heuristic)\n    const task = config.task.toLowerCase();\n    if (task.includes('test') && !task.includes('don\\'t test')) {\n      this.state.addVerificationGoal('Tests pass after changes');\n    }\n    if (task.includes('lint') || task.includes('typecheck') || task.includes('type-check')) {\n      this.state.addVerificationGoal('Lint/typecheck passes');\n    }\n    if (task.includes('build')) {\n      this.state.addVerificationGoal('Build succeeds');\n    }\n  }\n\n  private checkVerificationProof(call: ToolCall, result: unknown): void {\n    const output = String(result || '');\n\n    // Shell commands can prove verification goals\n    if (call.tool === 'run_shell_command' || call.tool === 'shell' || call.tool === 'run_cmd') {\n      const command = String(call.params.command || '');\n      for (const goal of this.state.verificationGoals) {\n        if (goal.status !== 'pending') continue;\n\n        // Match command to goal\n        if (goal.description.includes(command) ||\n            (command.includes('test') && goal.description.includes('test')) ||\n            (command.includes('lint') && goal.description.includes('lint')) ||\n            (command.includes('build') && goal.description.includes('build'))) {\n          // Check if it passed (no error in output)\n          if (!output.includes('FAIL') && !output.includes('error') && !output.includes('Error')) {\n            this.state.proveGoal(goal.id, `${call.tool}: ${command}`);\n          } else {\n            this.state.failGoal(goal.id);\n          }\n        }\n      }\n    }\n  }\n\n  private async runVerificationCycle(\n    executeTool: ExecuteToolFn,\n    history: TurnResult[],\n    abortSignal?: AbortSignal\n  ): Promise<boolean> {\n    if (!this.config.verificationCommands) return true;\n\n    let allPassed = true;\n    for (const cmd of this.config.verificationCommands) {\n      try {\n        const result = await executeTool('run_shell_command', { command: cmd }, abortSignal);\n        const output = String(result || '');\n        history.push({\n          turn: this.state.turns + 1,\n          tool: 'run_shell_command',\n          params: { command: cmd },\n          result\n        });\n\n        // Find matching goal\n        const goal = this.state.verificationGoals.find(\n          g => g.status === 'pending' && g.description.includes(cmd)\n        );\n\n        if (output.includes('FAIL') || output.includes('error')) {\n          allPassed = false;\n          if (goal) this.state.failGoal(goal.id);\n          this.state.recordFailure({\n            turn: this.state.turns,\n            tool: 'run_shell_command',\n            params: { command: cmd },\n            error: `Verification failed: ${output.slice(0, 200)}`\n          });\n        } else {\n          if (goal) this.state.proveGoal(goal.id, `verification: ${cmd}`);\n        }\n      } catch (error) {\n        allPassed = false;\n        const errMsg = (error as Error).message || 'verification command failed';\n        history.push({\n          turn: this.state.turns + 1,\n          tool: 'run_shell_command',\n          params: { command: cmd },\n          result: null,\n          error: errMsg\n        });\n      }\n    }\n    return allPassed;\n  }\n\n  private buildVerificationFixPrompt(): string {\n    const failed = this.state.verificationGoals.filter(g => g.status === 'failed');\n    if (failed.length === 0) return '';\n\n    return [\n      '## Verification failed \u2014 fix these issues:',\n      ...failed.map(g => `- ${g.description} (failed ${g.attempts}x)`),\n      '',\n      'Fix the code so these checks pass, then I will re-verify.'\n    ].join('\\n');\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers (duplicated from autonomous-loop to avoid circular deps)\n// ---------------------------------------------------------------------------\n\nfunction isContextLengthError(msg: string): boolean {\n  const lower = msg.toLowerCase();\n  return (\n    lower.includes('context length') ||\n    lower.includes('too long') ||\n    lower.includes('payload size') ||\n    lower.includes('context_length_exceeded') ||\n    lower.includes('max_tokens') ||\n    lower.includes('token limit') ||\n    lower.includes('prompt is too long')\n  );\n}\n\nfunction compactTurnHistory(history: TurnResult[]): TurnResult[] {\n  if (history.length <= 7) return history;\n  const first = history.slice(0, 1);\n  const tail = history.slice(-5);\n  const middle = history.slice(1, history.length - 5);\n  if (middle.length === 0) return history;\n  const summary: TurnResult = {\n    turn: first[0]?.turn ?? 0,\n    tool: 'context_compaction',\n    params: { compactedTurns: middle.length },\n    result: `[Context compacted: ${middle.length} earlier tool results summarized]`\n  };\n  return [...first, summary, ...tail];\n}\n", "import { access, copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface CorrectionEntry {\n  timestamp: string;\n  prompt: string;\n  original: string;\n  corrected: string;\n  agent?: string;\n  tags?: string[];\n}\n\nfunction nowIso(): string {\n  return new Date().toISOString();\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n  try {\n    await access(path, constants.F_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport class CorrectionStore {\n  baseDir: string;\n  stateDir: string;\n  dataPath: string;\n\n  constructor(baseDir = process.cwd()) {\n    this.baseDir = baseDir;\n    this.stateDir = join(baseDir, '.crew');\n    this.dataPath = join(this.stateDir, 'training-data.jsonl');\n  }\n\n  async ensureReady(): Promise<void> {\n    if (!(await pathExists(this.stateDir))) {\n      await mkdir(this.stateDir, { recursive: true });\n    }\n\n    if (!(await pathExists(this.dataPath))) {\n      await writeFile(this.dataPath, '', 'utf8');\n    }\n  }\n\n  async record(entry: Omit<CorrectionEntry, 'timestamp'>): Promise<CorrectionEntry> {\n    await this.ensureReady();\n\n    const payload: CorrectionEntry = {\n      timestamp: nowIso(),\n      ...entry\n    };\n\n    await writeFile(this.dataPath, `${JSON.stringify(payload)}\\n`, {\n      encoding: 'utf8',\n      flag: 'a'\n    });\n\n    return payload;\n  }\n\n  async loadAll(): Promise<CorrectionEntry[]> {\n    await this.ensureReady();\n    const raw = await readFile(this.dataPath, 'utf8');\n    const lines = raw.split('\\n').map(line => line.trim()).filter(Boolean);\n    return lines.map(line => JSON.parse(line) as CorrectionEntry);\n  }\n\n  async summary(): Promise<{ count: number; latest?: CorrectionEntry }> {\n    const all = await this.loadAll();\n    return {\n      count: all.length,\n      latest: all.length > 0 ? all[all.length - 1] : undefined\n    };\n  }\n\n  async exportTo(path: string): Promise<void> {\n    await this.ensureReady();\n    await copyFile(this.dataPath, path);\n  }\n}\n", "/**\n * Token-Aware Context Compaction\n *\n * Tracks estimated token usage per turn and triggers intelligent\n * compaction when approaching context window limits. Uses char-to-token\n * ratio estimation (no tiktoken dependency) and can optionally use\n * LLM-based summarization for better compression than truncation.\n */\n\n// Average chars per token varies by content type:\n// English prose: ~4 chars/token, code: ~3.5 chars/token, JSON: ~3 chars/token\nconst CHARS_PER_TOKEN = 3.7;\n\n/** Context window sizes by model family */\nconst CONTEXT_WINDOWS: Record<string, number> = {\n  'gemini-2.5-flash': 1_048_576,\n  'gemini-2.5-pro': 1_048_576,\n  'gemini-2.0-flash': 1_048_576,\n  'gpt-4o': 128_000,\n  'gpt-4o-mini': 128_000,\n  'gpt-5': 256_000,\n  'gpt-5.4': 256_000,\n  'gpt-5.3': 256_000,\n  'gpt-5.1': 256_000,\n  'gpt-5.2': 256_000,\n  'claude-3-5-sonnet': 200_000,\n  'claude-opus-4.6': 200_000,\n  'claude-opus-4': 200_000,\n  'claude-sonnet-4': 200_000,\n  'claude-haiku-4': 200_000,\n  'grok-4': 131_072,\n  'grok-beta': 131_072,\n  'deepseek-chat': 128_000,\n  'deepseek-reasoner': 128_000,\n  'llama-3.3': 128_000,\n};\n\nexport interface TokenBudget {\n  contextWindow: number;\n  estimatedUsed: number;\n  remainingTokens: number;\n  remainingPct: number;\n  shouldCompact: boolean;\n}\n\nexport interface CompactedMessage {\n  role: string;\n  content: string;\n  isCompacted?: boolean;\n}\n\n/** Estimate tokens from a string using char ratio */\nexport function estimateTokens(text: string): number {\n  if (!text) return 0;\n  return Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\n/** Get context window size for a model */\nexport function getContextWindow(model: string): number {\n  const m = String(model || '').toLowerCase();\n  // Try exact match first, then prefix match\n  for (const [prefix, size] of Object.entries(CONTEXT_WINDOWS)) {\n    if (m.startsWith(prefix)) return size;\n  }\n  return 128_000; // Conservative default\n}\n\n/**\n * Calculate token budget for current conversation state.\n * compactThreshold: trigger compaction when this % of context is used (default 75%)\n */\nexport function calculateTokenBudget(\n  messages: Array<{ content: string }>,\n  model: string,\n  systemPromptTokens: number = 0,\n  compactThreshold: number = 0.75\n): TokenBudget {\n  const contextWindow = getContextWindow(model);\n  let estimatedUsed = systemPromptTokens;\n\n  for (const msg of messages) {\n    estimatedUsed += estimateTokens(msg.content) + 4; // +4 for message framing tokens\n  }\n\n  const remainingTokens = contextWindow - estimatedUsed;\n  const remainingPct = remainingTokens / contextWindow;\n\n  return {\n    contextWindow,\n    estimatedUsed,\n    remainingTokens,\n    remainingPct,\n    shouldCompact: (estimatedUsed / contextWindow) >= compactThreshold\n  };\n}\n\n/**\n * Compact a conversation by summarizing older messages.\n * Keeps the system prompt, first N and last M messages intact,\n * and summarizes the middle section into a single compressed message.\n *\n * If an LLM summarizer is provided, uses it for semantic summarization.\n * Otherwise falls back to extractive compression (key lines only).\n */\nexport async function compactConversation(\n  messages: CompactedMessage[],\n  opts: {\n    keepFirst?: number;     // Keep first N messages intact (default 2)\n    keepLast?: number;      // Keep last M messages intact (default 6)\n    targetTokens?: number;  // Target token count for summary (default 2000)\n    summarizer?: (text: string, maxTokens: number) => Promise<string>;\n  } = {}\n): Promise<CompactedMessage[]> {\n  const keepFirst = opts.keepFirst ?? 2;\n  const keepLast = opts.keepLast ?? 6;\n  const targetTokens = opts.targetTokens ?? 2000;\n\n  if (messages.length <= keepFirst + keepLast) {\n    return messages; // Nothing to compact\n  }\n\n  const head = messages.slice(0, keepFirst);\n  const middle = messages.slice(keepFirst, messages.length - keepLast);\n  const tail = messages.slice(-keepLast);\n\n  if (middle.length === 0) return messages;\n\n  // Build text representation of middle messages\n  const middleText = middle.map(m => {\n    const role = m.role.toUpperCase();\n    const text = m.content.slice(0, 2000); // Cap each message for summarization input\n    return `[${role}] ${text}`;\n  }).join('\\n\\n');\n\n  let summary: string;\n\n  if (opts.summarizer) {\n    // LLM-based semantic summarization\n    const prompt = `Summarize this conversation segment concisely, preserving key decisions, file changes, errors, and outcomes. Focus on what was done and what state things are in now:\\n\\n${middleText}`;\n    summary = await opts.summarizer(prompt, targetTokens);\n  } else {\n    // Extractive compression: keep key lines\n    summary = extractiveCompress(middle, targetTokens);\n  }\n\n  const summaryMessage: CompactedMessage = {\n    role: 'assistant',\n    content: `[Context Summary \u2014 ${middle.length} earlier messages compressed]\\n${summary}`,\n    isCompacted: true\n  };\n\n  return [...head, summaryMessage, ...tail];\n}\n\n/**\n * Extractive compression: select the most important lines from messages.\n * Prioritizes: errors, file paths, tool results, decisions.\n */\nfunction extractiveCompress(messages: CompactedMessage[], targetTokens: number): string {\n  const maxChars = targetTokens * CHARS_PER_TOKEN;\n  const lines: Array<{ text: string; priority: number }> = [];\n\n  for (const msg of messages) {\n    const role = msg.role === 'assistant' ? 'A' : 'U';\n    const content = msg.content || '';\n\n    // Split into lines and score each\n    for (const line of content.split('\\n')) {\n      const trimmed = line.trim();\n      if (!trimmed || trimmed.length < 5) continue;\n\n      let priority = 1;\n      if (/error|fail|exception/i.test(trimmed)) priority = 5;\n      if (/\\.(ts|js|py|go|rs|tsx|jsx|json)/.test(trimmed)) priority = 3;\n      if (/wrote|created|edited|deleted|fixed/i.test(trimmed)) priority = 4;\n      if (/\u2192|\u2713|\u2717|COMPLETE|OK:|FAIL:/i.test(trimmed)) priority = 3;\n      if (/decision|chose|decided|because/i.test(trimmed)) priority = 4;\n\n      lines.push({ text: `[${role}] ${trimmed}`, priority });\n    }\n  }\n\n  // Sort by priority (high first), then take until we hit token budget\n  lines.sort((a, b) => b.priority - a.priority);\n\n  let result = '';\n  for (const line of lines) {\n    if (result.length + line.text.length > maxChars) break;\n    result += line.text + '\\n';\n  }\n\n  return result || '[No significant content to summarize]';\n}\n\n/**\n * Adaptive compression ratios based on context usage.\n * Returns { firstN, lastN } \u2014 how many turns to keep in full detail.\n */\nexport function adaptiveCompressionRatio(\n  totalTurns: number,\n  contextUsagePct: number\n): { firstN: number; lastN: number } {\n  if (contextUsagePct < 0.5) {\n    // Plenty of room \u2014 keep more detail\n    return { firstN: 5, lastN: 8 };\n  }\n  if (contextUsagePct < 0.75) {\n    // Getting tight \u2014 standard compression\n    return { firstN: 3, lastN: 5 };\n  }\n  // Critical \u2014 aggressive compression\n  return { firstN: 1, lastN: 3 };\n}\n", "/**\n * Execution Transcript \u2014 immutable append-only log of every tool call per task.\n *\n * Workers can't modify entries after completion.\n * QA gate reads the transcript to mechanically verify work quality.\n */\n\nexport interface TranscriptEntry {\n  ts: number;              // Date.now()\n  toolName: string;\n  params: Record<string, unknown>;\n  success: boolean;\n  outputPreview: string;   // first 200 chars of output/error\n  durationMs: number;\n  error?: string;\n  handled?: boolean;\n  recovery?: string;\n}\n\nfunction extractShellWriteTargets(command: string): string[] {\n  const text = String(command || '').trim();\n  if (!text) return [];\n  const targets = new Set<string>();\n  const redirectRe = /(?:^|[|&;]\\s*|\\s)(?:>>?|1>>?|2>>?)\\s*(?:\"([^\"]+)\"|'([^']+)'|([^\\s|&;]+))/g;\n  let match: RegExpExecArray | null;\n  while ((match = redirectRe.exec(text)) !== null) {\n    const target = String(match[1] || match[2] || match[3] || '').trim();\n    if (target) targets.add(target);\n  }\n  const teeRe = /\\btee\\s+(?:-a\\s+)?(?:\"([^\"]+)\"|'([^']+)'|([^\\s|&;]+))/g;\n  while ((match = teeRe.exec(text)) !== null) {\n    const target = String(match[1] || match[2] || match[3] || '').trim();\n    if (target) targets.add(target);\n  }\n  return [...targets];\n}\n\nexport class ExecutionTranscript {\n  private _entries: TranscriptEntry[] = [];\n  private _frozen = false;\n\n  /** Append a tool call entry. Throws if transcript is frozen. */\n  record(entry: TranscriptEntry): void {\n    if (this._frozen) throw new Error('Transcript is frozen \u2014 cannot append after completion');\n    this._entries.push(Object.freeze(entry) as TranscriptEntry);\n  }\n\n  /** Freeze the transcript \u2014 no more entries can be added. */\n  freeze(): void {\n    this._frozen = true;\n  }\n\n  /** Read-only access to all entries. */\n  get entries(): ReadonlyArray<TranscriptEntry> {\n    return this._entries;\n  }\n\n  get length(): number {\n    return this._entries.length;\n  }\n\n  /** All unique tool names used. */\n  get toolsUsed(): string[] {\n    return [...new Set(this._entries.map(e => e.toolName))];\n  }\n\n  /** Count of failed tool calls. */\n  get failedCalls(): number {\n    return this._entries.filter(e => !e.success).length;\n  }\n\n  /** Total duration of all tool calls. */\n  get totalDurationMs(): number {\n    return this._entries.reduce((sum, e) => sum + e.durationMs, 0);\n  }\n\n  /** Files that were read (from read_file/read_many_files calls). */\n  get filesRead(): Set<string> {\n    const files = new Set<string>();\n    for (const e of this._entries) {\n      if (!e.success) continue;\n      if (e.toolName === 'read_file' && typeof e.params.file_path === 'string') {\n        files.add(e.params.file_path);\n      }\n      if (e.toolName === 'read_many_files' && typeof e.params.include === 'string') {\n        files.add(e.params.include);\n      }\n    }\n    return files;\n  }\n\n  /** Files that were edited (replace/edit/append_file). */\n  get filesEdited(): Set<string> {\n    const files = new Set<string>();\n    const editTools = new Set(['replace', 'edit', 'append_file']);\n    for (const e of this._entries) {\n      if (!e.success) continue;\n      if (editTools.has(e.toolName) && typeof e.params.file_path === 'string') {\n        files.add(e.params.file_path);\n      }\n      if ((e.toolName === 'run_shell_command' || e.toolName === 'shell' || e.toolName === 'run_cmd') && typeof e.params.command === 'string') {\n        for (const target of extractShellWriteTargets(e.params.command)) files.add(target);\n      }\n    }\n    return files;\n  }\n\n  /** Files that were written (write_file \u2014 new files only). */\n  get filesWritten(): Set<string> {\n    const files = new Set<string>();\n    for (const e of this._entries) {\n      if (!e.success) continue;\n      if (e.toolName === 'write_file' && typeof e.params.file_path === 'string') {\n        files.add(e.params.file_path);\n      }\n      if ((e.toolName === 'run_shell_command' || e.toolName === 'shell' || e.toolName === 'run_cmd') && typeof e.params.command === 'string') {\n        for (const target of extractShellWriteTargets(e.params.command)) files.add(target);\n      }\n    }\n    return files;\n  }\n\n  /** Files edited without a prior read_file call. */\n  get unreadEdits(): string[] {\n    const readFiles = this.filesRead;\n    const edited = this.filesEdited;\n    return [...edited].filter(f => !readFiles.has(f));\n  }\n\n  /** Shell commands that failed (non-zero exit or error). */\n  get failedShellCommands(): TranscriptEntry[] {\n    return this._entries.filter(e =>\n      (e.toolName === 'run_shell_command' || e.toolName === 'shell' || e.toolName === 'run_cmd')\n      && !e.success\n    );\n  }\n\n  /** Serialize transcript to JSONL string for persistence. */\n  toJSONL(): string {\n    return this._entries.map(e => JSON.stringify(e)).join('\\n');\n  }\n\n  /** Summary stats for logging. */\n  toSummary(): {\n    totalCalls: number;\n    failedCalls: number;\n    toolsUsed: string[];\n    filesRead: number;\n    filesEdited: number;\n    filesWritten: number;\n    unreadEdits: string[];\n    totalDurationMs: number;\n  } {\n    return {\n      totalCalls: this._entries.length,\n      failedCalls: this.failedCalls,\n      toolsUsed: this.toolsUsed,\n      filesRead: this.filesRead.size,\n      filesEdited: this.filesEdited.size,\n      filesWritten: this.filesWritten.size,\n      unreadEdits: this.unreadEdits,\n      totalDurationMs: this.totalDurationMs\n    };\n  }\n}\n", "/**\n * Patch Critic \u2014 Per-turn quality evaluation of code changes.\n *\n * After each edit/write tool call, the patch critic evaluates:\n *   - Surgical precision: was the change minimal and targeted?\n *   - Scope discipline: did the change stay within the task scope?\n *   - Read-before-write: was the file read before modification?\n *   - Churn detection: is the agent rewriting the same file repeatedly?\n *   - Pattern quality: does the change follow observed project conventions?\n *\n * The critic produces guidance injected into the next LLM turn,\n * steering the model toward higher-quality changes without blocking.\n *\n * This is a lightweight, deterministic critic \u2014 no LLM call needed.\n */\n\nimport type { StructuredHistory, FileState } from './structured-history.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type CriticSeverity = 'info' | 'warning' | 'error';\n\nexport interface CriticFinding {\n  severity: CriticSeverity;\n  category: CriticCategory;\n  message: string;\n  file?: string;\n  suggestion?: string;\n}\n\nexport type CriticCategory =\n  | 'unread-edit'           // Edited file without reading first\n  | 'excessive-churn'       // Same file edited 3+ times\n  | 'scope-creep'           // File outside declared scope edited\n  | 'large-write'           // Wrote a very large file (possible overwrite)\n  | 'missing-verification'  // Made edits but no verification command run\n  | 'repeated-pattern'      // Same edit pattern applied multiple times\n  | 'overwrite-risk'        // Used write_file on a file that was previously edited\n  | 'no-progress'           // Multiple turns with no file changes\n  | 'good-practice';        // Positive signal (read-before-write, verification after edit)\n\nexport interface CriticReport {\n  turn: number;\n  findings: CriticFinding[];\n  score: number;              // 0-100, higher is better\n  guidance: string;           // Formatted text to inject into next LLM turn\n}\n\n// ---------------------------------------------------------------------------\n// Configuration\n// ---------------------------------------------------------------------------\n\nexport interface PatchCriticConfig {\n  /** Max edits to same file before warning (default: 3) */\n  churnThreshold?: number;\n  /** Max lines for a single write_file before warning (default: 500) */\n  largeWriteThreshold?: number;\n  /** Allowed file paths/patterns for scope checking */\n  allowedPaths?: string[];\n  /** Turns without file changes before warning (default: 3) */\n  noProgressThreshold?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Patch Critic\n// ---------------------------------------------------------------------------\n\nexport class PatchCritic {\n  private config: Required<PatchCriticConfig>;\n  private lastEditTurn = 0;\n  private turnsWithoutEdits = 0;\n  private editCountByFile = new Map<string, number>();\n  private verificationSeen = false;\n\n  constructor(config: PatchCriticConfig = {}) {\n    this.config = {\n      churnThreshold: config.churnThreshold ?? 3,\n      largeWriteThreshold: config.largeWriteThreshold ?? 500,\n      allowedPaths: config.allowedPaths ?? [],\n      noProgressThreshold: config.noProgressThreshold ?? 3\n    };\n  }\n\n  /**\n   * Evaluate a tool execution and produce findings.\n   * Call this after each tool call completes.\n   */\n  evaluate(\n    turn: number,\n    tool: string,\n    params: Record<string, unknown>,\n    result: unknown,\n    error: string | undefined,\n    history: StructuredHistory\n  ): CriticReport {\n    const findings: CriticFinding[] = [];\n    const filePath = String(params.file_path || params.path || '');\n\n    // \u2500\u2500 Check: unread edit \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (isWriteTool(tool) && filePath) {\n      const fileState = history.getFileState(filePath);\n      if (!fileState || !fileState.readBeforeWrite) {\n        findings.push({\n          severity: 'warning',\n          category: 'unread-edit',\n          message: `Edited ${filePath} without reading it first`,\n          file: filePath,\n          suggestion: `Read ${filePath} before editing to understand existing content`\n        });\n      } else {\n        // Positive signal\n        findings.push({\n          severity: 'info',\n          category: 'good-practice',\n          message: `Good: read ${filePath} before editing`\n        });\n      }\n    }\n\n    // \u2500\u2500 Check: excessive churn \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (isWriteTool(tool) && filePath) {\n      const count = (this.editCountByFile.get(filePath) || 0) + 1;\n      this.editCountByFile.set(filePath, count);\n      this.lastEditTurn = turn;\n      this.turnsWithoutEdits = 0;\n\n      if (count >= this.config.churnThreshold) {\n        findings.push({\n          severity: 'warning',\n          category: 'excessive-churn',\n          message: `${filePath} has been edited ${count} times \u2014 consider a single comprehensive edit`,\n          file: filePath,\n          suggestion: 'Read the full file, plan all changes, then apply once'\n        });\n      }\n    }\n\n    // \u2500\u2500 Check: overwrite risk \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (tool === 'write_file' && filePath) {\n      const fileState = history.getFileState(filePath);\n      if (fileState && fileState.editCount > 0) {\n        findings.push({\n          severity: 'warning',\n          category: 'overwrite-risk',\n          message: `write_file on ${filePath} which was previously edited \u2014 may overwrite partial changes`,\n          file: filePath,\n          suggestion: 'Use edit_file for incremental changes to existing files'\n        });\n      }\n    }\n\n    // \u2500\u2500 Check: large write \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (tool === 'write_file' && params.content) {\n      const lines = String(params.content).split('\\n').length;\n      if (lines > this.config.largeWriteThreshold) {\n        findings.push({\n          severity: 'info',\n          category: 'large-write',\n          message: `Large file write: ${filePath} (${lines} lines)`,\n          file: filePath\n        });\n      }\n    }\n\n    // \u2500\u2500 Check: scope creep \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\uFFFD\uFFFD\uFFFD\u2500\u2500\u2500\u2500\n    if (isWriteTool(tool) && filePath && this.config.allowedPaths.length > 0) {\n      const inScope = this.config.allowedPaths.some(\n        allowed => filePath === allowed || filePath.startsWith(allowed) || filePath.startsWith(`${allowed}/`)\n      );\n      if (!inScope) {\n        findings.push({\n          severity: 'error',\n          category: 'scope-creep',\n          message: `${filePath} is outside the allowed scope`,\n          file: filePath,\n          suggestion: `Stay within: ${this.config.allowedPaths.join(', ')}`\n        });\n      }\n    }\n\n    // \u2500\u2500 Check: verification after edits \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (isVerificationTool(tool)) {\n      this.verificationSeen = true;\n      if (!error) {\n        findings.push({\n          severity: 'info',\n          category: 'good-practice',\n          message: 'Good: ran verification after changes'\n        });\n      }\n    }\n\n    // \u2500\u2500 Check: missing verification \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (!isWriteTool(tool) && !isVerificationTool(tool) && !isReadTool(tool)) {\n      // Non-edit, non-verify turn\n    }\n    const totalEdits = [...this.editCountByFile.values()].reduce((a, b) => a + b, 0);\n    if (totalEdits >= 3 && !this.verificationSeen) {\n      findings.push({\n        severity: 'warning',\n        category: 'missing-verification',\n        message: `${totalEdits} edits made with no verification \u2014 run tests or checks`,\n        suggestion: 'Run tests, lint, or build to verify your changes are correct'\n      });\n    }\n\n    // \u2500\u2500 Check: no progress \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (!isWriteTool(tool) && !isReadTool(tool)) {\n      this.turnsWithoutEdits++;\n    }\n    if (this.turnsWithoutEdits >= this.config.noProgressThreshold && totalEdits === 0) {\n      findings.push({\n        severity: 'warning',\n        category: 'no-progress',\n        message: `${this.turnsWithoutEdits} turns without any file changes`,\n        suggestion: 'Make concrete progress: read a file, plan an edit, execute it'\n      });\n    }\n\n    // Score\n    const score = computeScore(findings);\n\n    // Build guidance\n    const guidance = buildGuidance(findings);\n\n    return { turn, findings, score, guidance };\n  }\n\n  /**\n   * Reset state (for new task or after review cycle).\n   */\n  reset(): void {\n    this.editCountByFile.clear();\n    this.verificationSeen = false;\n    this.turnsWithoutEdits = 0;\n    this.lastEditTurn = 0;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isWriteTool(tool: string): boolean {\n  return ['write_file', 'edit_file', 'replace', 'append_file'].includes(tool);\n}\n\nfunction isReadTool(tool: string): boolean {\n  return ['read_file', 'read_many_files', 'grep_search', 'glob', 'list_directory'].includes(tool);\n}\n\nfunction isVerificationTool(tool: string): boolean {\n  return ['run_shell_command', 'shell', 'run_cmd', 'check_background_task'].includes(tool);\n}\n\nfunction computeScore(findings: CriticFinding[]): number {\n  let score = 100;\n  for (const f of findings) {\n    if (f.severity === 'error') score -= 25;\n    else if (f.severity === 'warning') score -= 10;\n    else if (f.category === 'good-practice') score += 5;\n  }\n  return Math.max(0, Math.min(100, score));\n}\n\nfunction buildGuidance(findings: CriticFinding[]): string {\n  const actionable = findings.filter(f => f.severity !== 'info' && f.suggestion);\n  if (actionable.length === 0) return '';\n\n  const lines = actionable.map(f =>\n    `- [${f.severity.toUpperCase()}] ${f.message}${f.suggestion ? `\\n  \u2192 ${f.suggestion}` : ''}`\n  );\n\n  return `## Patch quality feedback:\\n${lines.join('\\n')}`;\n}\n", "/**\n * Structured History Preservation\n *\n * Instead of flattening tool history into text between layers, this module\n * preserves rich structured data across the execution lifecycle.\n *\n * Key problems solved:\n *   - Provider turn state lost when multi-turn-drivers return only text+toolCalls\n *   - Intermediate worker outputs lost during review/fix cycles\n *   - Sandbox filesystem state not captured per-turn\n *   - Compaction decisions opaque to callers\n *\n * Usage:\n *   const history = new StructuredHistory();\n *   history.recordLLMTurn({ ... });\n *   history.recordToolExecution({ ... });\n *   history.recordCompaction({ ... });\n *   const context = history.buildProviderContext('anthropic', tokenBudget);\n */\n\n// ---------------------------------------------------------------------------\n// Turn types \u2014 preserve what each layer produces\n// ---------------------------------------------------------------------------\n\nexport interface LLMTurnRecord {\n  type: 'llm';\n  turn: number;\n  ts: number;\n  model: string;\n  provider: string;\n  response: string;\n  toolCalls: Array<{ tool: string; params: Record<string, unknown> }>;\n  finishReason?: string;\n  costUsd: number;\n  inputTokens: number;\n  outputTokens: number;\n  cachedTokens: number;\n  /** Whether this turn was a retry after compaction */\n  wasRetry: boolean;\n  /** Whether extended thinking was present (o1, o3 models) */\n  hadThinking: boolean;\n}\n\nexport interface ToolExecutionRecord {\n  type: 'tool';\n  turn: number;\n  ts: number;\n  tool: string;\n  params: Record<string, unknown>;\n  result: unknown;\n  error?: string;\n  durationMs: number;\n  /** Files read/written/edited by this tool call */\n  filesAffected: string[];\n  /** Whether this was a read-only operation */\n  readOnly: boolean;\n}\n\nexport interface CompactionRecord {\n  type: 'compaction';\n  ts: number;\n  reason: 'proactive' | 'reactive' | 'budget';\n  turnsBefore: number;\n  turnsAfter: number;\n  tokensBefore: number;\n  tokensAfter: number;\n  /** What was preserved vs dropped */\n  preservedTurns: number[];\n  droppedTurns: number[];\n}\n\nexport interface ReviewRecord {\n  type: 'review';\n  ts: number;\n  cycle: number;\n  approved: boolean;\n  issues: Array<{ severity: string; problem: string }>;\n  fixAttempted: boolean;\n}\n\nexport type HistoryRecord = LLMTurnRecord | ToolExecutionRecord | CompactionRecord | ReviewRecord;\n\n// ---------------------------------------------------------------------------\n// File state tracking\n// ---------------------------------------------------------------------------\n\nexport interface FileState {\n  path: string;\n  lastReadAt?: number;\n  lastWrittenAt?: number;\n  lastEditedAt?: number;\n  readCount: number;\n  writeCount: number;\n  editCount: number;\n  /** Was the file read before first edit/write? */\n  readBeforeWrite: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// StructuredHistory\n// ---------------------------------------------------------------------------\n\nexport class StructuredHistory {\n  private _records: HistoryRecord[] = [];\n  private _fileStates = new Map<string, FileState>();\n  private _activeGoals: string[] = [];\n  private _resolvedGoals: string[] = [];\n\n  // \u2500\u2500 Recording \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  recordLLMTurn(entry: Omit<LLMTurnRecord, 'type' | 'ts'>): void {\n    this._records.push({ ...entry, type: 'llm', ts: Date.now() });\n  }\n\n  recordToolExecution(entry: Omit<ToolExecutionRecord, 'type' | 'ts'>): void {\n    const record: ToolExecutionRecord = { ...entry, type: 'tool', ts: Date.now() };\n    this._records.push(record);\n\n    // Track file state\n    for (const file of entry.filesAffected) {\n      this.trackFileAccess(file, entry.tool, entry.readOnly);\n    }\n  }\n\n  recordCompaction(entry: Omit<CompactionRecord, 'type' | 'ts'>): void {\n    this._records.push({ ...entry, type: 'compaction', ts: Date.now() });\n  }\n\n  recordReview(entry: Omit<ReviewRecord, 'type' | 'ts'>): void {\n    this._records.push({ ...entry, type: 'review', ts: Date.now() });\n  }\n\n  // \u2500\u2500 File state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private trackFileAccess(path: string, tool: string, readOnly: boolean): void {\n    let state = this._fileStates.get(path);\n    if (!state) {\n      state = {\n        path,\n        readCount: 0,\n        writeCount: 0,\n        editCount: 0,\n        readBeforeWrite: false\n      };\n      this._fileStates.set(path, state);\n    }\n\n    const isRead = readOnly || tool === 'read_file' || tool === 'read_many_files' || tool === 'grep_search' || tool === 'glob';\n    const isWrite = tool === 'write_file';\n    const isEdit = tool === 'edit_file' || tool === 'replace' || tool === 'append_file';\n\n    if (isRead) {\n      state.readCount += 1;\n      state.lastReadAt = Date.now();\n      // If this is the first access and it's a read, mark read-before-write\n      if (state.writeCount === 0 && state.editCount === 0) {\n        state.readBeforeWrite = true;\n      }\n    }\n    if (isWrite) {\n      state.writeCount += 1;\n      state.lastWrittenAt = Date.now();\n    }\n    if (isEdit) {\n      state.editCount += 1;\n      state.lastEditedAt = Date.now();\n    }\n  }\n\n  getFileState(path: string): FileState | undefined {\n    return this._fileStates.get(path);\n  }\n\n  get fileStates(): ReadonlyMap<string, FileState> {\n    return this._fileStates;\n  }\n\n  /** Files that were written/edited without being read first */\n  get unreadWrites(): string[] {\n    return [...this._fileStates.values()]\n      .filter(s => (s.writeCount > 0 || s.editCount > 0) && !s.readBeforeWrite)\n      .map(s => s.path);\n  }\n\n  // \u2500\u2500 Goal tracking \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  addGoal(goal: string): void {\n    this._activeGoals.push(goal);\n  }\n\n  resolveGoal(goal: string): void {\n    const idx = this._activeGoals.indexOf(goal);\n    if (idx >= 0) {\n      this._activeGoals.splice(idx, 1);\n      this._resolvedGoals.push(goal);\n    }\n  }\n\n  get activeGoals(): ReadonlyArray<string> {\n    return this._activeGoals;\n  }\n\n  get resolvedGoals(): ReadonlyArray<string> {\n    return this._resolvedGoals;\n  }\n\n  // \u2500\u2500 Queries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  get records(): ReadonlyArray<HistoryRecord> {\n    return this._records;\n  }\n\n  get length(): number {\n    return this._records.length;\n  }\n\n  get llmTurns(): LLMTurnRecord[] {\n    return this._records.filter((r): r is LLMTurnRecord => r.type === 'llm');\n  }\n\n  get toolExecutions(): ToolExecutionRecord[] {\n    return this._records.filter((r): r is ToolExecutionRecord => r.type === 'tool');\n  }\n\n  get failedTools(): ToolExecutionRecord[] {\n    return this.toolExecutions.filter(t => t.error);\n  }\n\n  get compactions(): CompactionRecord[] {\n    return this._records.filter((r): r is CompactionRecord => r.type === 'compaction');\n  }\n\n  /** Total cost across all LLM turns */\n  get totalCostUsd(): number {\n    return this.llmTurns.reduce((sum, t) => sum + t.costUsd, 0);\n  }\n\n  /** Total tokens used */\n  get totalTokens(): { input: number; output: number; cached: number } {\n    return this.llmTurns.reduce(\n      (acc, t) => ({\n        input: acc.input + t.inputTokens,\n        output: acc.output + t.outputTokens,\n        cached: acc.cached + t.cachedTokens\n      }),\n      { input: 0, output: 0, cached: 0 }\n    );\n  }\n\n  // \u2500\u2500 Context building \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  /**\n   * Build a summary of execution state for injection into LLM context.\n   * Preserves critical state that naive compaction would lose:\n   *   - Active/unresolved goals\n   *   - Files currently being worked on\n   *   - Recent failures and what was learned\n   *   - Verification status\n   */\n  buildExecutionSummary(): string {\n    const sections: string[] = [];\n\n    // Active goals\n    if (this._activeGoals.length > 0) {\n      sections.push(`Active goals: ${this._activeGoals.join('; ')}`);\n    }\n    if (this._resolvedGoals.length > 0) {\n      sections.push(`Completed: ${this._resolvedGoals.join('; ')}`);\n    }\n\n    // Files in progress\n    const activeFiles = [...this._fileStates.values()]\n      .filter(s => s.editCount > 0 || s.writeCount > 0)\n      .map(s => s.path);\n    if (activeFiles.length > 0) {\n      sections.push(`Files modified: ${activeFiles.join(', ')}`);\n    }\n\n    // Unread writes (problems)\n    const unread = this.unreadWrites;\n    if (unread.length > 0) {\n      sections.push(`WARNING \u2014 edited without reading first: ${unread.join(', ')}`);\n    }\n\n    // Recent failures\n    const recentFails = this.failedTools.slice(-3);\n    if (recentFails.length > 0) {\n      const lines = recentFails.map(f => `  ${f.tool}: ${(f.error || '').slice(0, 80)}`);\n      sections.push(`Recent failures:\\n${lines.join('\\n')}`);\n    }\n\n    // Compaction history\n    if (this.compactions.length > 0) {\n      const last = this.compactions[this.compactions.length - 1];\n      sections.push(`Context was compacted (${last.reason}): ${last.turnsBefore}\u2192${last.turnsAfter} turns`);\n    }\n\n    return sections.length > 0\n      ? `## Execution state\\n${sections.join('\\n')}`\n      : '';\n  }\n\n  /**\n   * Export a JSON-serializable snapshot for persistence.\n   */\n  toJSON(): {\n    records: HistoryRecord[];\n    fileStates: Array<[string, FileState]>;\n    activeGoals: string[];\n    resolvedGoals: string[];\n  } {\n    return {\n      records: [...this._records],\n      fileStates: [...this._fileStates.entries()],\n      activeGoals: [...this._activeGoals],\n      resolvedGoals: [...this._resolvedGoals]\n    };\n  }\n}\n", "/**\n * Tool Auto-Filtering \u2014 reduce tool count based on task type.\n *\n * Instead of sending all 41 tools to every LLM call, filter to the\n * relevant subset based on task analysis. This:\n *   - Reduces context/token usage\n *   - Improves model accuracy (fewer irrelevant options)\n *   - Fixes GPT-5.4 Responses API degradation with 20+ tools\n *\n * Tools are grouped by capability domain. The task description\n * determines which domains are active.\n */\n\nexport interface ToolDeclarationLike {\n  name: string;\n  description?: string;\n  parameters?: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Tool domain groups\n// ---------------------------------------------------------------------------\n\nconst CORE_TOOLS = new Set([\n  'read_file', 'write_file', 'replace', 'edit', 'glob', 'grep_search',\n  'list_directory', 'run_shell_command', 'shell'\n]);\n\nconst GIT_TOOLS = new Set([\n  'git', 'worktree', 'enter_worktree', 'exit_worktree', 'merge_worktree', 'list_worktrees'\n]);\n\nconst WEB_TOOLS = new Set([\n  'google_web_search', 'web_search', 'web_fetch'\n]);\n\nconst MEMORY_TOOLS = new Set([\n  'save_memory', 'write_todos', 'get_internal_docs'\n]);\n\nconst AGENT_TOOLS = new Set([\n  'spawn_agent', 'agent_message', 'activate_skill', 'tool_search'\n]);\n\nconst CODE_INTEL_TOOLS = new Set([\n  'lsp', 'notebook_edit'\n]);\n\nconst PLANNING_TOOLS = new Set([\n  'enter_plan_mode', 'exit_plan_mode', 'ask_user'\n]);\n\nconst TRACKER_TOOLS = new Set([\n  'tracker_create_task', 'tracker_update_task', 'tracker_get_task',\n  'tracker_list_tasks', 'tracker_add_dependency', 'tracker_visualize'\n]);\n\nconst EXTRA_TOOLS = new Set([\n  'read_many_files', 'append_file', 'mkdir', 'grep_search_ripgrep',\n  'list', 'run_cmd', 'grep', 'check_background_task', 'sleep'\n]);\n\n// ---------------------------------------------------------------------------\n// Task \u2192 domain mapping\n// ---------------------------------------------------------------------------\n\nexport type TaskDomain =\n  | 'coding'        // file read/write/edit + shell\n  | 'research'      // web search + docs\n  | 'git'           // version control\n  | 'planning'      // plan mode + tracker\n  | 'testing'       // shell + code intel\n  | 'docs'          // file write + memory\n  | 'full';         // everything\n\nexport function detectTaskDomains(task: string): Set<TaskDomain> {\n  const lower = task.toLowerCase();\n  const domains = new Set<TaskDomain>();\n\n  // Always include coding (core tools)\n  domains.add('coding');\n\n  if (/\\b(search|find.*online|web|url|http|fetch.*page|research|google)\\b/.test(lower)) {\n    domains.add('research');\n  }\n  if (/\\b(git|commit|branch|merge|push|pull|diff|blame|worktree|rebase)\\b/.test(lower)) {\n    domains.add('git');\n  }\n  if (/\\b(plan|roadmap|break.*down|decompose|architect|design.*system)\\b/.test(lower)) {\n    domains.add('planning');\n  }\n  if (/\\b(tests?|spec|assert|coverage|jest|mocha|vitest|verify|validate)\\b/.test(lower)) {\n    domains.add('testing');\n  }\n  if (/\\b(doc|readme|guide|tutorial|comment|explain|write.*about)\\b/.test(lower)) {\n    domains.add('docs');\n  }\n  // Complex tasks get everything\n  if (lower.length > 500 || /\\b(entire|whole|project|refactor.*across|migration)\\b/.test(lower)) {\n    domains.add('full');\n  }\n\n  return domains;\n}\n\n/**\n * Filter tools to only those relevant for the detected task domains.\n * Always includes core tools. Returns the filtered list.\n */\nexport function filterToolsForTask<T extends ToolDeclarationLike>(\n  tools: T[],\n  task: string,\n  options: {\n    /** Maximum tools to return (0 = no limit) */\n    maxTools?: number;\n    /** Force include these tool names regardless of domain */\n    alwaysInclude?: string[];\n  } = {}\n): T[] {\n  const domains = detectTaskDomains(task);\n\n  // Full domain = return everything\n  if (domains.has('full')) {\n    return options.maxTools ? tools.slice(0, options.maxTools) : tools;\n  }\n\n  const allowed = new Set<string>(CORE_TOOLS);\n\n  // Add domain-specific tools\n  if (domains.has('git')) for (const t of GIT_TOOLS) allowed.add(t);\n  if (domains.has('research')) for (const t of WEB_TOOLS) allowed.add(t);\n  if (domains.has('planning')) {\n    for (const t of PLANNING_TOOLS) allowed.add(t);\n    for (const t of TRACKER_TOOLS) allowed.add(t);\n  }\n  if (domains.has('testing')) for (const t of CODE_INTEL_TOOLS) allowed.add(t);\n  if (domains.has('docs')) for (const t of MEMORY_TOOLS) allowed.add(t);\n\n  // Always include extra common tools\n  for (const t of EXTRA_TOOLS) allowed.add(t);\n\n  // Force-include specific tools\n  if (options.alwaysInclude) {\n    for (const t of options.alwaysInclude) allowed.add(t);\n  }\n\n  const filtered = tools.filter(t => allowed.has(t.name));\n\n  if (options.maxTools && filtered.length > options.maxTools) {\n    return filtered.slice(0, options.maxTools);\n  }\n\n  return filtered;\n}\n\n/**\n * Get a human-readable summary of which domains were detected.\n */\nexport function describeFiltering(task: string, totalTools: number, filteredCount: number): string {\n  const domains = detectTaskDomains(task);\n  return `[ToolFilter] ${filteredCount}/${totalTools} tools (domains: ${[...domains].join(', ')})`;\n}\n", "/**\n * Top of Mind \u2014 persistent instructions injected into every LLM turn.\n *\n * Users create .crew/instructions.md (project-level) or\n * ~/.crewswarm/instructions.md (global) with persistent context\n * that should always be available to the agent:\n *   - Code style preferences\n *   - Project conventions\n *   - \"Always use TypeScript strict mode\"\n *   - \"Never modify package-lock.json\"\n *   - Team-specific patterns\n *\n * Instructions are injected into the system prompt before every\n * LLM call, after the base system prompt but before task context.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nlet _cachedInstructions: string | null = null;\nlet _cachedProjectDir: string | null = null;\n\n/**\n * Load top-of-mind instructions from project and global config.\n * Cached per project directory for the duration of the process.\n */\nexport async function loadTopOfMind(projectDir: string = process.cwd()): Promise<string> {\n  if (_cachedInstructions !== null && _cachedProjectDir === projectDir) {\n    return _cachedInstructions;\n  }\n\n  const sections: string[] = [];\n\n  // Global instructions (~/.crewswarm/instructions.md)\n  const globalPath = join(homedir(), '.crewswarm', 'instructions.md');\n  if (existsSync(globalPath)) {\n    try {\n      const content = await readFile(globalPath, 'utf8');\n      if (content.trim()) {\n        sections.push(`## Global Instructions\\n${content.trim()}`);\n      }\n    } catch {}\n  }\n\n  // Project instructions (.crew/instructions.md)\n  const projectPath = join(projectDir, '.crew', 'instructions.md');\n  if (existsSync(projectPath)) {\n    try {\n      const content = await readFile(projectPath, 'utf8');\n      if (content.trim()) {\n        sections.push(`## Project Instructions\\n${content.trim()}`);\n      }\n    } catch {}\n  }\n\n  // Also check CLAUDE.md style files\n  const claudeMdPath = join(projectDir, 'CLAUDE.md');\n  if (existsSync(claudeMdPath)) {\n    try {\n      const content = await readFile(claudeMdPath, 'utf8');\n      if (content.trim()) {\n        sections.push(`## Project Guidelines (CLAUDE.md)\\n${content.trim()}`);\n      }\n    } catch {}\n  }\n\n  _cachedInstructions = sections.length > 0\n    ? `\\n\\n## Top of Mind \u2014 Always Follow These Instructions\\n${sections.join('\\n\\n')}\\n`\n    : '';\n  _cachedProjectDir = projectDir;\n\n  return _cachedInstructions;\n}\n\n/**\n * Clear the cache (for testing or when switching projects).\n */\nexport function clearTopOfMindCache(): void {\n  _cachedInstructions = null;\n  _cachedProjectDir = null;\n}\n", "/**\n * Per-Session Scratchpad Directory\n *\n * Each agent session gets an isolated temp directory for working files.\n * This avoids polluting the project directory or colliding with other agents\n * running in parallel on the same machine.\n *\n * Usage:\n *   const dir = createScratchpad(sessionId);\n *   // ... pass dir to LLM via getScratchpadInstructions() ...\n *   cleanupScratchpad(sessionId);\n */\n\nimport { mkdirSync, rmSync } from 'fs';\nimport { join } from 'path';\nimport { tmpdir } from 'os';\n\n/**\n * Create (or ensure existence of) the scratchpad directory for a session.\n * Returns the absolute path to the directory.\n */\nexport function createScratchpad(sessionId: string): string {\n  const dir = join(tmpdir(), `crew-cli-scratch-${sessionId}`);\n  mkdirSync(dir, { recursive: true });\n  return dir;\n}\n\n/**\n * Delete the scratchpad directory and all its contents.\n * Safe to call even if the directory no longer exists.\n */\nexport function cleanupScratchpad(sessionId: string): void {\n  const dir = join(tmpdir(), `crew-cli-scratch-${sessionId}`);\n  rmSync(dir, { recursive: true, force: true });\n}\n\n/**\n * Build the system-prompt snippet that tells the LLM about its scratchpad.\n */\nexport function getScratchpadInstructions(scratchDir: string): string {\n  return (\n    '\\n\\nYou have a dedicated scratchpad directory for temporary files:\\n' +\n    `  ${scratchDir}\\n` +\n    'Use this instead of /tmp for drafts, intermediate files, or working copies.' +\n    ' It will be cleaned up when the session ends.'\n  );\n}\n", "/**\n * Collections Search \u2014 lightweight local RAG over docs and markdown files.\n *\n * Indexes markdown / text files under configurable paths, builds a simple\n * TF-IDF\u2013style term index, and returns ranked chunks with source attribution.\n */\n\nimport { readdir, readFile, stat } from 'node:fs/promises';\nimport { extname, join, relative, resolve } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CollectionChunk {\n  /** Relative path from the collection root */\n  source: string;\n  /** 1-based line number where the chunk starts */\n  startLine: number;\n  /** The raw text of the chunk */\n  text: string;\n  /** Relevance score (higher = more relevant) */\n  score: number;\n}\n\nexport interface CollectionIndex {\n  root: string;\n  fileCount: number;\n  chunkCount: number;\n  /** term \u2192 Set of chunk indices */\n  terms: Map<string, Set<number>>;\n  chunks: CollectionChunk[];\n}\n\nexport interface BuildCollectionOptions {\n  includeCode?: boolean;\n}\n\nexport interface SearchResult {\n  query: string;\n  hits: CollectionChunk[];\n  totalChunks: number;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst DOC_EXTENSIONS = new Set(['.md', '.mdx', '.txt', '.rst', '.adoc']);\nconst CODE_EXTENSIONS = new Set([\n  '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.json',\n  '.py', '.go', '.rs', '.java', '.kt', '.swift',\n  '.sh', '.bash', '.zsh', '.yaml', '.yml', '.toml'\n]);\n\nconst IGNORED_DIRS = new Set([\n  'node_modules', '.git', 'dist', 'build', '.crew',\n  '.next', '.turbo', 'coverage', '__pycache__'\n]);\n\nfunction tokenize(text: string): string[] {\n  return text\n    .toLowerCase()\n    .replace(/[^a-z0-9\\s_-]/g, ' ')\n    .split(/\\s+/)\n    .filter(t => t.length > 1);\n}\n\nfunction hashToken(token: string, dim: number): number {\n  let h = 2166136261;\n  for (let i = 0; i < token.length; i++) {\n    h ^= token.charCodeAt(i);\n    h = Math.imul(h, 16777619);\n  }\n  return Math.abs(h) % dim;\n}\n\nfunction toHashedVector(text: string, dim = 256): Float64Array {\n  const vec = new Float64Array(dim);\n  const toks = tokenize(text);\n  for (const t of toks) {\n    vec[hashToken(t, dim)] += 1;\n  }\n  // l2 normalize\n  let norm = 0;\n  for (let i = 0; i < dim; i++) norm += vec[i] * vec[i];\n  norm = Math.sqrt(norm);\n  if (norm > 0) {\n    for (let i = 0; i < dim; i++) vec[i] /= norm;\n  }\n  return vec;\n}\n\nfunction cosineSimilarity(a: Float64Array, b: Float64Array): number {\n  const dim = Math.min(a.length, b.length);\n  let dot = 0;\n  for (let i = 0; i < dim; i++) {\n    dot += a[i] * b[i];\n  }\n  return dot;\n}\n\n/**\n * Split a file into chunks \u2014 one chunk per heading section, or fixed-size\n * paragraphs for files without headings.\n */\nfunction chunkFile(content: string, source: string): CollectionChunk[] {\n  const lines = content.split('\\n');\n  const chunks: CollectionChunk[] = [];\n  let currentLines: string[] = [];\n  let currentStart = 1;\n\n  const flush = () => {\n    const text = currentLines.join('\\n').trim();\n    if (text.length > 0) {\n      chunks.push({ source, startLine: currentStart, text, score: 0 });\n    }\n    currentLines = [];\n  };\n\n  for (let i = 0; i < lines.length; i++) {\n    const line = lines[i];\n    // Split on markdown headings\n    if (/^#{1,4}\\s/.test(line) && currentLines.length > 0) {\n      flush();\n      currentStart = i + 1;\n    }\n    currentLines.push(line);\n\n    // Also split on large paragraphs (every ~40 lines if no heading)\n    if (currentLines.length >= 40 && !/^#{1,4}\\s/.test(line)) {\n      flush();\n      currentStart = i + 2;\n    }\n  }\n  flush();\n  return chunks;\n}\n\n// ---------------------------------------------------------------------------\n// Walk & Index\n// ---------------------------------------------------------------------------\n\nasync function walkDocs(rootDir: string, includeCode = false): Promise<string[]> {\n  const files: string[] = [];\n\n  async function walk(dir: string) {\n    let entries: string[];\n    try {\n      entries = await readdir(dir);\n    } catch {\n      return;\n    }\n    for (const entry of entries) {\n      if (IGNORED_DIRS.has(entry)) continue;\n      const fullPath = join(dir, entry);\n      let st;\n      try {\n        st = await stat(fullPath);\n      } catch {\n        continue;\n      }\n      if (st.isDirectory()) {\n        await walk(fullPath);\n      } else {\n        const ext = extname(entry).toLowerCase();\n        if (DOC_EXTENSIONS.has(ext) || (includeCode && CODE_EXTENSIONS.has(ext))) {\n        files.push(fullPath);\n        }\n      }\n    }\n  }\n\n  await walk(rootDir);\n  return files;\n}\n\nexport async function buildCollectionIndex(\n  paths: string[],\n  options: BuildCollectionOptions = {}\n): Promise<CollectionIndex> {\n  const allChunks: CollectionChunk[] = [];\n  const roots = paths.map(p => resolve(p));\n  let fileCount = 0;\n\n  for (const rootPath of roots) {\n    let st;\n    try {\n      st = await stat(rootPath);\n    } catch {\n      continue;\n    }\n\n    const files = st.isDirectory() ? await walkDocs(rootPath, Boolean(options.includeCode)) : [rootPath];\n\n    for (const file of files) {\n      let content: string;\n      try {\n        content = await readFile(file, 'utf8');\n      } catch {\n        continue;\n      }\n      fileCount++;\n      const rel = relative(resolve(rootPath, st.isDirectory() ? '.' : '..'), file);\n      const chunks = chunkFile(content, rel);\n      allChunks.push(...chunks);\n    }\n  }\n\n  // Build inverted term index\n  const terms = new Map<string, Set<number>>();\n  for (let i = 0; i < allChunks.length; i++) {\n    const tokens = tokenize(allChunks[i].text);\n    for (const token of tokens) {\n      if (!terms.has(token)) terms.set(token, new Set());\n      terms.get(token)!.add(i);\n    }\n  }\n\n  return {\n    root: roots[0] || '.',\n    fileCount,\n    chunkCount: allChunks.length,\n    terms,\n    chunks: allChunks\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Search\n// ---------------------------------------------------------------------------\n\nexport function searchCollection(\n  index: CollectionIndex,\n  query: string,\n  maxResults = 10\n): SearchResult {\n  const queryTokens = tokenize(query);\n  if (queryTokens.length === 0) {\n    return { query, hits: [], totalChunks: index.chunkCount };\n  }\n\n  // Score each chunk by number of matching query terms + term rarity (IDF-like)\n  const scores = new Float64Array(index.chunkCount);\n\n  for (const token of queryTokens) {\n    const matchingChunks = index.terms.get(token);\n    if (!matchingChunks) continue;\n    // IDF-like weight: rarer terms score higher\n    const idf = Math.log(1 + index.chunkCount / matchingChunks.size);\n    for (const idx of matchingChunks) {\n      scores[idx] += idf;\n    }\n  }\n\n  // Collect non-zero scores\n  const candidates: Array<{ idx: number; score: number }> = [];\n  for (let i = 0; i < scores.length; i++) {\n    if (scores[i] > 0) {\n      candidates.push({ idx: i, score: scores[i] });\n    }\n  }\n\n  // Sort descending by score\n  candidates.sort((a, b) => b.score - a.score);\n\n  const queryVector = toHashedVector(query);\n  const maxTfidf = candidates.length > 0 ? candidates[0].score : 1;\n  const tfidfWeight = 0.7;\n  const vectorWeight = 0.3;\n\n  const hybrid = candidates.map(c => {\n    const chunk = index.chunks[c.idx];\n    const chunkVector = toHashedVector(chunk.text);\n    const cosine = Math.max(0, cosineSimilarity(queryVector, chunkVector));\n    const tfidfNorm = maxTfidf > 0 ? (c.score / maxTfidf) : 0;\n    const hybridScore = (tfidfNorm * tfidfWeight) + (cosine * vectorWeight);\n    return { idx: c.idx, score: hybridScore };\n  });\n\n  hybrid.sort((a, b) => b.score - a.score);\n\n  const hits = hybrid.slice(0, maxResults).map(c => ({\n    ...index.chunks[c.idx],\n    score: Math.round(c.score * 1000) / 1000\n  }));\n\n  return { query, hits, totalChunks: index.chunkCount };\n}\n", "/**\n * Agentic L3 Executor v2 \u2014 10/10 competitive CLI engine\n *\n * Features:\n * - 45+ tools via GeminiToolAdapter (LSP, git, web, memory, tracker, etc.)\n * - Streaming output \u2014 real-time token display as LLM generates\n * - JIT context discovery \u2014 files discovered by tools are indexed for next turn\n * - Turn compression \u2014 Topic-Action-Summary keeps prompts lean on long sessions\n * - Multi-model routing \u2014 cheap models for simple tasks, heavy for complex\n * - Auto-retry \u2014 failed tool calls retry up to 3 times with correction\n * - Repo-map context \u2014 TF-IDF semantic search injected before execution\n */\n\nimport type { TurnResult } from '../worker/autonomous-loop.js';\nimport type { ToolDeclaration } from '../tools/base.js';\nimport type {\n  AnthropicContentBlock,\n  OpenAIToolCall,\n  LLMResponseData,\n  GeminiContent,\n  ChatMessage,\n} from '../types/common.js';\nimport type { Sandbox } from '../sandbox/index.js';\nimport { GeminiToolAdapter, type ConstraintLevel, constraintLevelForPersona } from '../tools/gemini/crew-adapter.js';\nimport { RunEngine } from '../engine/run-engine.js';\nimport {\n  openAICompatibleTurn,\n  anthropicTurn,\n  type LLMTurnResult\n} from './multi-turn-drivers.js';\nimport { CorrectionStore } from '../learning/corrections.js';\nimport { estimateTokens, getContextWindow, adaptiveCompressionRatio, calculateTokenBudget, compactConversation, type CompactedMessage } from '../context/token-compaction.js';\nimport { ExecutionTranscript } from '../execution/transcript.js';\nimport { buildTaskModeGuidance, detectTaskMode } from '../execution/agentic-guidance.js';\nimport { PatchCritic } from '../engine/patch-critic.js';\nimport { StructuredHistory } from '../engine/structured-history.js';\nimport { filterToolsForTask, describeFiltering } from '../engine/tool-filter.js';\nimport { loadTopOfMind } from '../engine/top-of-mind.js';\nimport { getOAuthToken, forceRefreshOAuthToken } from '../auth/oauth-keychain.js';\nimport { getOpenAIOAuthToken, forceRefreshOpenAIOAuth, OPENAI_CODEX_API_URL } from '../auth/openai-oauth.js';\nimport { getGeminiOAuthToken, forceRefreshGeminiOAuth } from '../auth/gemini-oauth.js';\nimport { computeVersionSuffix, buildBillingBlock, signBody } from '../auth/cch.js';\nimport { createScratchpad, cleanupScratchpad, getScratchpadInstructions } from './scratchpad.js';\nimport { TOOL_RESULT_CLEARING_PROMPT } from './tool-result-clearing.js';\n\n// ---------------------------------------------------------------------------\n// System prompt\n// ---------------------------------------------------------------------------\n\n// Repair common JSON quirks from provider tool call responses\nexport function repairJson(raw: string): string {\n  if (!raw || raw.trim() === '') return '{}';\n  let s = raw.trim();\n  // Remove trailing commas before } or ]\n  s = s.replace(/,\\s*([}\\]])/g, '$1');\n  // Fix single quotes to double quotes (but not inside strings)\n  if (!s.includes('\"') && s.includes(\"'\")) {\n    s = s.replace(/'/g, '\"');\n  }\n  // Fix unquoted keys: { key: \"value\" } \u2192 { \"key\": \"value\" }\n  s = s.replace(/([{,])\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*:/g, '$1\"$2\":');\n  // Handle truncated JSON from streaming \u2014 close open braces/brackets\n  const openBraces = (s.match(/{/g) || []).length;\n  const closeBraces = (s.match(/}/g) || []).length;\n  for (let i = 0; i < openBraces - closeBraces; i++) s += '}';\n  const openBrackets = (s.match(/\\[/g) || []).length;\n  const closeBrackets = (s.match(/]/g) || []).length;\n  for (let i = 0; i < openBrackets - closeBrackets; i++) s += ']';\n  return s;\n}\n\nconst L3_SYSTEM_PROMPT = `You are a senior AI engineer executing coding tasks autonomously.\n\n## Cognitive Loop: THINK \u2192 ACT \u2192 OBSERVE\n\nEvery turn, follow this exact pattern:\n\n**THINK** (internal reasoning, 1-3 sentences):\n- What is the current state? What do I know from previous tool results?\n- What is the minimal next action to make progress?\n- Am I done? If so, summarize and stop.\n\n**ACT** (one or more tool calls):\n- Choose the most targeted tool for the job.\n- Prefer small, verifiable steps over large changes.\n- When multiple independent lookups are needed, call multiple tools in parallel.\n\n**OBSERVE** (after tools return):\n- Did the tool succeed or fail? What does the output tell me?\n- Do I need to adjust my approach?\n\n## Operating Principles\n\n- Match the request. Do what was asked \u2014 nothing more. A bug fix is just a bug fix. Don't refactor adjacent code, add docstrings to unchanged functions, or suggest rewrites beyond the task scope.\n- Simplest approach first. Don't over-engineer. Three similar lines are better than a premature abstraction. Only add error handling, validation, or fallbacks at system boundaries (user input, external APIs), not for internal guarantees.\n- Own mistakes. If a tool call fails or your approach is wrong, say so briefly and try a different approach. Don't repeat the same failing action. If the same failure pattern repeats twice, switch strategy.\n- Be security-conscious. Don't introduce injection, XSS, or hardcoded secrets. Validate at trust boundaries.\n\n## Available Tools\n\n**Files**: read_file, write_file, replace (edit with replace_all flag), read_many_files, glob, grep_search (output_mode: content/files/count, context, type filter), list_directory, mkdir, append_file\n**Shell**: run_shell_command (Docker isolation when staged files exist; run_in_background for long commands; configurable timeout via CREW_SHELL_TIMEOUT, default 120s, max 600s), check_background_task, sleep (wait between actions, max 60s)\n**Git**: git (status, diff, log, add, commit, show, branch, stash, tag, blame, checkout, fetch, pull, merge, rebase, cherry-pick, worktree \u2014 force-push and --no-verify blocked)\n**Worktrees**: worktree, enter_worktree, exit_worktree, merge_worktree, list_worktrees (isolated git worktrees for parallel work)\n**Code Intel**: lsp (diagnostics, go-to-definition, find-references, hover, completions), notebook_edit (Jupyter .ipynb \u2014 add/edit/delete/run cells)\n**Web**: google_web_search, web_fetch\n**Memory**: save_memory (persist facts across sessions), write_todos\n**Docs**: get_internal_docs (read project documentation)\n**Agents**: spawn_agent (spawn autonomous sub-agent \u2014 returns session_id for follow-ups), agent_message (send follow-up to existing sub-agent session \u2014 multi-turn dialogue with full context)\n**Discovery**: tool_search (find available tools by name or description query), activate_skill\n\n## File Reading Strategy\n\n1. ALWAYS read a file before editing it. Never guess at file contents.\n2. For large files (500+ lines): read specific line ranges instead of the whole file.\n3. If a read_file result looks truncated, re-read with a narrower range around the area of interest.\n4. Use grep_search to locate exact strings before attempting replace/edit.\n\n## Edit Strategy\n\n1. ALWAYS read_file before editing. Edits on unread files will be rejected.\n2. Use replace (edit) for surgical changes \u2014 provide exact old_string that uniquely matches.\n3. Use replace_all:true when renaming a variable/function across the file.\n4. For new files, use write_file.\n5. Never rewrite an entire existing file \u2014 always use targeted edits.\n6. If an edit fails with \"not unique\", provide more surrounding context or use replace_all:true.\n7. If an edit fails with \"String not found\", re-read the file and retry with current content.\n\n## Shell Strategy\n\n1. For long-running commands (builds, tests, installs), use run_in_background:true.\n2. Use check_background_task to poll for results.\n3. Prefer dedicated tools over shell: use read_file not cat, grep_search not rg, glob not find.\n4. Never use destructive commands (rm -rf, git reset --hard) without explicit task instruction.\n\n## Verification\n\n1. After code changes: run the build command (usually \"npm run build\" or \"tsc --noEmit\").\n2. After logic changes: run relevant tests (\"npm test\", or specific test file).\n3. Check git diff to confirm only intended changes were made.\n\n## Output\n\n- Lead with what you did, not how you thought about it. Skip preamble.\n- For informational queries (listing files, reading code, checking status): include the actual tool output in your response so the user sees the data.\n- For code changes: concise summary of files modified, what changed, verification result.\n- When you used a tool to answer a question, show the results \u2014 don't just say \"I listed the files\" without showing them.\n\n## Stop Conditions \u2014 When to Finish\n\n- The task is fully complete and verified.\n- You have confirmed the changes work (via build, test, or diagnostic check).\n- Do NOT keep reading files or running tools after the work is done.\n- Do NOT repeat yourself or restate your work \u2014 just give a concise summary.\n\n## Anti-Patterns to Avoid\n\n- Do NOT read every file in the project to \"understand context\" \u2014 read only what's needed.\n- Do NOT make speculative changes to files you haven't read.\n- Do NOT run the same command twice if it already succeeded.\n- Do NOT apologize or explain failures at length \u2014 just fix them and move on.\n- Do NOT add features, refactor, or \"improve\" code beyond what the task asks.\n- Do NOT add comments, docstrings, or type annotations to code you didn't change.`;\n\n// ---------------------------------------------------------------------------\n// Corrections injection \u2014 load recent corrections to prevent repeat mistakes\n// ---------------------------------------------------------------------------\n\nasync function loadCorrectionsContext(projectDir: string): Promise<string> {\n  try {\n    const store = new CorrectionStore(projectDir);\n    const entries = await store.loadAll();\n    if (entries.length === 0) return '';\n\n    // Take last 10 corrections (most recent = most relevant)\n    const recent = entries.slice(-10);\n    const lines = recent.map(c => {\n      const tags = c.tags?.length ? ` [${c.tags.join(', ')}]` : '';\n      return `- ${c.prompt.slice(0, 100)}${tags}: ${c.corrected.slice(0, 200)}`;\n    });\n\n    return `\\n\\n## Past Corrections (avoid repeating these mistakes)\\n${lines.join('\\n')}`;\n  } catch {\n    return ''; // No corrections file or parse error \u2014 non-fatal\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Turn Compression \u2014 Topic-Action-Summary model\n// ---------------------------------------------------------------------------\n\ninterface CompressedTurn {\n  turn: number;\n  topic: string;   // what was being worked on\n  action: string;  // tool + brief params\n  outcome: string; // success/fail + short result\n}\n\nexport function compressTurnHistory(history: TurnResult[]): CompressedTurn[] {\n  return history.map(h => {\n    const paramStr = JSON.stringify(h.params);\n    // Extract the most important param (usually file_path, pattern, or command)\n    const keyParam = h.params.file_path || h.params.pattern || h.params.command\n      || h.params.query || h.params.path || h.params.dir_path || '';\n    const action = `${h.tool}(${String(keyParam).slice(0, 80)})`;\n\n    const isError = Boolean(h.error);\n    const resultText = isError\n      ? h.error!\n      : (typeof h.result === 'object' && h.result && 'output' in h.result)\n        ? String((h.result as { output?: string }).output ?? '')\n        : String(h.result ?? '');\n\n    // Compress outcome to most useful info\n    const outcome = isError\n      ? `FAIL: ${resultText.slice(0, 120)}`\n      : `OK: ${resultText.slice(0, 120)}`;\n\n    // Infer topic from tool + params\n    const topic = h.params.file_path\n      ? String(h.params.file_path).split('/').pop() || 'file'\n      : h.tool;\n\n    return { turn: h.turn, topic, action, outcome };\n  });\n}\n\n/** Format a tool result as a string, truncated for context */\nexport function formatToolResult(h: TurnResult, maxLen = 1500): string {\n  const res = h.error\n    ? `ERROR: ${h.error}`\n    : (typeof h.result === 'object' && h.result && 'output' in h.result)\n      ? String((h.result as { output?: string }).output ?? '')\n      : String(h.result ?? '');\n  return res.slice(0, maxLen);\n}\n\n/**\n * Convert TurnResult[] into provider-specific structured messages.\n * Each TurnResult becomes an assistant tool_call + user tool_result pair.\n * For long histories, middle turns are compressed to text summary while\n * the first 3 (initial context) and last 5 (recent work) use full structured format.\n */\nexport function historyToGeminiContents(history: TurnResult[], model?: string): GeminiContent[] {\n  if (history.length === 0) return [];\n  const contents: GeminiContent[] = [];\n\n  // Estimate current token usage to pick adaptive compression ratio\n  const totalChars = history.reduce((sum, h) => {\n    const paramStr = JSON.stringify(h.params);\n    const resultStr = typeof h.result === 'string' ? h.result : JSON.stringify(h.result || '');\n    return sum + paramStr.length + resultStr.length;\n  }, 0);\n  const estimatedHistoryTokens = estimateTokens(String.fromCharCode(0).repeat(totalChars));\n  const contextWindow = getContextWindow(model || 'gemini-2.5-flash');\n  const usagePct = estimatedHistoryTokens / contextWindow;\n\n  // Adaptive compression: more aggressive as context fills up\n  const { firstN, lastN } = adaptiveCompressionRatio(history.length, usagePct);\n  const needsCompression = history.length > firstN + lastN;\n  const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n  const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n  const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n  // Emit head turns (initial context) as full structured messages\n  for (const h of headDetailed) {\n    contents.push({\n      role: 'model',\n      parts: [{ functionCall: { name: h.tool, args: h.params } }]\n    });\n    const resultObj = h.error\n      ? { error: h.error }\n      : (typeof h.result === 'object' && h.result) ? (h.result as Record<string, unknown>) : { output: formatToolResult(h) };\n    contents.push({\n      role: 'user',\n      parts: [{ functionResponse: { name: h.tool, response: resultObj } }]\n    });\n  }\n\n  // Emit compressed summary of middle turns\n  if (middleTurns.length > 0) {\n    const compressed = compressTurnHistory(middleTurns);\n    const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n    contents.push(\n      { role: 'model', parts: [{ text: `[Earlier execution summary]\\n${summary}` }] },\n      { role: 'user', parts: [{ text: 'Acknowledged. Continue with the task.' }] }\n    );\n  }\n\n  for (const h of structuredTurns) {\n    // Model made a tool call\n    contents.push({\n      role: 'model',\n      parts: [{ functionCall: { name: h.tool, args: h.params } }]\n    });\n    // User provided tool result\n    const resultObj = h.error\n      ? { error: h.error }\n      : (typeof h.result === 'object' && h.result) ? (h.result as Record<string, unknown>) : { output: formatToolResult(h) };\n    contents.push({\n      role: 'user',\n      parts: [{ functionResponse: { name: h.tool, response: resultObj } }]\n    });\n  }\n  return contents;\n}\n\nexport function historyToOpenAIMessages(history: TurnResult[], model?: string): ChatMessage[] {\n  if (history.length === 0) return [];\n  const messages: ChatMessage[] = [];\n\n  // Estimate token usage for adaptive compression\n  const totalChars = history.reduce((sum, h) => {\n    const paramStr = JSON.stringify(h.params);\n    const resultStr = typeof h.result === 'string' ? h.result : JSON.stringify(h.result || '');\n    return sum + paramStr.length + resultStr.length;\n  }, 0);\n  const estimatedHistoryTokens = estimateTokens(String.fromCharCode(0).repeat(totalChars));\n  const contextWindow = getContextWindow(model || 'gpt-4o');\n  const usagePct = estimatedHistoryTokens / contextWindow;\n\n  const { firstN, lastN } = adaptiveCompressionRatio(history.length, usagePct);\n  const needsCompression = history.length > firstN + lastN;\n  const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n  const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n  const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n  // Emit head turns (initial context) as full structured messages\n  for (const h of headDetailed) {\n    const callId = `call_${h.turn}_${h.tool}`;\n    messages.push({\n      role: 'assistant',\n      tool_calls: [{\n        id: callId,\n        type: 'function',\n        function: { name: h.tool, arguments: JSON.stringify(h.params) }\n      }]\n    });\n    messages.push({\n      role: 'tool',\n      tool_call_id: callId,\n      content: formatToolResult(h)\n    });\n  }\n\n  // Emit compressed summary of middle turns\n  if (middleTurns.length > 0) {\n    const compressed = compressTurnHistory(middleTurns);\n    const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n    messages.push(\n      { role: 'assistant', content: `[Earlier execution summary]\\n${summary}` },\n      { role: 'user', content: 'Acknowledged. Continue with the task.' }\n    );\n  }\n\n  for (const h of structuredTurns) {\n    const callId = `call_${h.turn}_${h.tool}`;\n    messages.push({\n      role: 'assistant',\n      tool_calls: [{\n        id: callId,\n        type: 'function',\n        function: { name: h.tool, arguments: JSON.stringify(h.params) }\n      }]\n    });\n    messages.push({\n      role: 'tool',\n      tool_call_id: callId,\n      content: formatToolResult(h)\n    });\n  }\n  return messages;\n}\n\nfunction historyToAnthropicMessages(history: TurnResult[]): ChatMessage[] {\n  if (history.length === 0) return [];\n  const messages: ChatMessage[] = [];\n\n  // Selective compression: keep first 3 + last 5 detailed, compress only middle\n  const firstN = 3;\n  const lastN = 5;\n  const needsCompression = history.length > firstN + lastN;\n  const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n  const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n  const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n  // Emit head turns (initial context) as full structured messages\n  for (const h of headDetailed) {\n    const useId = `tu_${h.turn}_${h.tool}`;\n    messages.push({\n      role: 'assistant',\n      content: [{\n        type: 'tool_use',\n        id: useId,\n        name: h.tool,\n        input: h.params\n      }]\n    });\n    messages.push({\n      role: 'user',\n      content: [{\n        type: 'tool_result',\n        tool_use_id: useId,\n        content: formatToolResult(h),\n        ...(h.error ? { is_error: true } : {})\n      }]\n    });\n  }\n\n  // Emit compressed summary of middle turns\n  if (middleTurns.length > 0) {\n    const compressed = compressTurnHistory(middleTurns);\n    const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n    messages.push(\n      { role: 'assistant', content: `[Earlier execution summary]\\n${summary}` },\n      { role: 'user', content: 'Acknowledged. Continue with the task.' }\n    );\n  }\n\n  for (const h of structuredTurns) {\n    const useId = `tu_${h.turn}_${h.tool}`;\n    messages.push({\n      role: 'assistant',\n      content: [{\n        type: 'tool_use',\n        id: useId,\n        name: h.tool,\n        input: h.params\n      }]\n    });\n    messages.push({\n      role: 'user',\n      content: [{\n        type: 'tool_result',\n        tool_use_id: useId,\n        content: formatToolResult(h),\n        ...(h.error ? { is_error: true } : {})\n      }]\n    });\n  }\n  return messages;\n}\n\n/** Legacy text-based history for fallback (markers-only providers) */\nfunction historyToContext(history: TurnResult[]): string {\n  if (history.length === 0) return '';\n\n  // For short histories, use detailed format\n  if (history.length <= 5) {\n    const lines = history.map(h => {\n      return `[Turn ${h.turn}] ${h.tool}(${JSON.stringify(h.params).slice(0, 200)}) \u2192 ${formatToolResult(h, 800)}`;\n    });\n    return '\\n\\nPrevious tool results:\\n' + lines.join('\\n');\n  }\n\n  // For longer histories, use compressed Topic-Action-Summary\n  const compressed = compressTurnHistory(history);\n  const recentDetailed = history.slice(-3); // Keep last 3 turns detailed\n  const olderCompressed = compressed.slice(0, -3);\n\n  let ctx = '\\n\\nExecution summary (compressed):\\n';\n  ctx += olderCompressed.map(c =>\n    `[${c.turn}] ${c.action} \u2192 ${c.outcome}`\n  ).join('\\n');\n\n  ctx += '\\n\\nRecent actions (detailed):\\n';\n  ctx += recentDetailed.map(h => {\n    return `[Turn ${h.turn}] ${h.tool}(${JSON.stringify(h.params).slice(0, 200)}) \u2192 ${formatToolResult(h, 800)}`;\n  }).join('\\n');\n\n  return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Multi-model routing \u2014 more providers, task-based selection\n// ---------------------------------------------------------------------------\n\ninterface ProviderEntry {\n  id: string;\n  envKey: string;\n  model: string;\n  driver: 'gemini' | 'openai' | 'anthropic' | 'openrouter';\n  apiUrl?: string;\n  modelPrefix?: string;\n  tier: 'fast' | 'standard' | 'heavy'; // for complexity-based routing\n}\n\nconst PROVIDER_ORDER: ProviderEntry[] = [\n  // Heavy tier \u2014 L2 brain (complex multi-file tasks, planning)\n  { id: 'openai', envKey: 'OPENAI_API_KEY', model: 'gpt-4.1', driver: 'openai', apiUrl: 'https://api.openai.com/v1/chat/completions', modelPrefix: 'gpt', tier: 'heavy' },\n  { id: 'anthropic', envKey: 'ANTHROPIC_API_KEY', model: 'claude-sonnet-4-20250514', driver: 'anthropic', modelPrefix: 'claude', tier: 'heavy' },\n  { id: 'grok', envKey: 'XAI_API_KEY', model: 'grok-3-mini-beta', driver: 'openai', apiUrl: 'https://api.x.ai/v1/chat/completions', modelPrefix: 'grok', tier: 'heavy' },\n  // Standard tier \u2014 L3 workers (execution, parallel tasks)\n  { id: 'gemini', envKey: 'GEMINI_API_KEY', model: 'gemini-2.5-flash', driver: 'gemini', modelPrefix: 'gemini', tier: 'standard' },\n  { id: 'gemini', envKey: 'GOOGLE_API_KEY', model: 'gemini-2.5-flash', driver: 'gemini', modelPrefix: 'gemini', tier: 'standard' },\n  { id: 'deepseek', envKey: 'DEEPSEEK_API_KEY', model: 'deepseek-chat', driver: 'openai', apiUrl: 'https://api.deepseek.com/v1/chat/completions', modelPrefix: 'deepseek', tier: 'standard' },\n  { id: 'kimi', envKey: 'MOONSHOT_API_KEY', model: 'moonshot-v1-128k', driver: 'openai', apiUrl: 'https://api.moonshot.cn/v1/chat/completions', modelPrefix: 'kimi', tier: 'standard' },\n  // Fast tier \u2014 L1 routing (classification, cheap)\n  { id: 'groq', envKey: 'GROQ_API_KEY', model: 'llama-3.3-70b-versatile', driver: 'openai', apiUrl: 'https://api.groq.com/openai/v1/chat/completions', modelPrefix: 'llama', tier: 'fast' },\n  // Mid-tier \u2014 additional providers\n  { id: 'mistral', envKey: 'MISTRAL_API_KEY', model: 'mistral-large-latest', driver: 'openai', apiUrl: 'https://api.mistral.ai/v1/chat/completions', modelPrefix: 'mistral', tier: 'standard' },\n  { id: 'cerebras', envKey: 'CEREBRAS_API_KEY', model: 'qwen-3-235b-a22b-instruct-2507', driver: 'openai', apiUrl: 'https://api.cerebras.ai/v1/chat/completions', modelPrefix: 'qwen', tier: 'fast' },\n  { id: 'nvidia', envKey: 'NVIDIA_API_KEY', model: 'meta/llama-3.3-70b-instruct', driver: 'openai', apiUrl: 'https://integrate.api.nvidia.com/v1/chat/completions', modelPrefix: 'nvidia', tier: 'standard' },\n  // OpenCode/Zen \u2014 39 models, strong tool calling (Kimi K2.5, MiniMax, GLM-5, Nemotron, etc.)\n  { id: 'opencode', envKey: 'OPENCODE_API_KEY', model: 'kimi-k2.5', driver: 'openai', apiUrl: 'https://opencode.ai/zen/v1/chat/completions', modelPrefix: 'kimi', tier: 'standard' },\n  { id: 'opencode', envKey: 'OPENCODE_API_KEY', model: 'minimax-m2.5', driver: 'openai', apiUrl: 'https://opencode.ai/zen/v1/chat/completions', modelPrefix: 'minimax', tier: 'standard' },\n  { id: 'opencode', envKey: 'OPENCODE_API_KEY', model: 'glm-5', driver: 'openai', apiUrl: 'https://opencode.ai/zen/v1/chat/completions', modelPrefix: 'glm', tier: 'standard' },\n  { id: 'opencode', envKey: 'OPENCODE_API_KEY', model: 'nemotron-3-super-free', driver: 'openai', apiUrl: 'https://opencode.ai/zen/v1/chat/completions', modelPrefix: 'nemotron', tier: 'standard' },\n  { id: 'opencode', envKey: 'OPENCODE_API_KEY', model: 'qwen3.6-plus-free', driver: 'openai', apiUrl: 'https://opencode.ai/zen/v1/chat/completions', modelPrefix: 'qwen3.6', tier: 'standard' },\n  { id: 'opencode', envKey: 'OPENCODE_API_KEY', model: 'trinity-large-preview-free', driver: 'openai', apiUrl: 'https://opencode.ai/zen/v1/chat/completions', modelPrefix: 'trinity', tier: 'standard' },\n  { id: 'opencode', envKey: 'OPENCODE_API_KEY', model: 'big-pickle', driver: 'openai', apiUrl: 'https://opencode.ai/zen/v1/chat/completions', modelPrefix: 'big-pickle', tier: 'standard' },\n  // Ollama \u2014 local/cloud models via OpenAI-compatible API (keyless, always available)\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'gemma4:31b-cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'gemma', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'glm-5.1:cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'glm-5.1', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'glm-5:cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'glm-5:', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'glm-4.7:cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'glm-4', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'minimax-m2.7:cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'minimax', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'kimi-k2.5:cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'kimi-k2', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'deepseek-v3.2:cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'deepseek-v3', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'qwen3-coder-next:cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'qwen3-coder', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'devstral-2:123b-cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'devstral', tier: 'standard' },\n  { id: 'ollama', envKey: 'OLLAMA_DUMMY', model: 'nemotron-3-super:cloud', driver: 'openai', apiUrl: 'http://localhost:11434/v1/chat/completions', modelPrefix: 'nemotron', tier: 'standard' },\n  // Perplexity\n  { id: 'perplexity', envKey: 'PERPLEXITY_API_KEY', model: 'sonar', driver: 'openai', apiUrl: 'https://api.perplexity.ai/chat/completions', modelPrefix: 'sonar', tier: 'standard' },\n  // Fallback \u2014 free tier\n  { id: 'openrouter', envKey: 'OPENROUTER_API_KEY', model: 'google/gemini-2.0-flash-exp:free', driver: 'openrouter', apiUrl: 'https://openrouter.ai/api/v1/chat/completions', modelPrefix: 'openrouter', tier: 'standard' },\n  // Additional providers (OpenAI-compatible, cheap workers)\n  { id: 'together', envKey: 'TOGETHER_API_KEY', model: 'Qwen/Qwen3.5-397B-A17B', driver: 'openai', apiUrl: 'https://api.together.xyz/v1/chat/completions', modelPrefix: 'qwen', tier: 'standard' },\n  { id: 'fireworks', envKey: 'FIREWORKS_API_KEY', model: 'accounts/fireworks/models/qwen3.5-397b-a17b', driver: 'openai', apiUrl: 'https://api.fireworks.ai/inference/v1/chat/completions', modelPrefix: 'fireworks', tier: 'standard' },\n];\n\nexport type ResolvedProvider = {\n  key: string;\n  model: string;\n  driver: string;\n  apiUrl?: string;\n  id: string;\n  isOAuth?: boolean;\n  projectId?: string;\n  oauthSource?: string;\n};\n\nfunction stripSchemaMetadata(value: unknown): unknown {\n  if (Array.isArray(value)) return value.map(stripSchemaMetadata);\n  if (!value || typeof value !== 'object') return value;\n\n  const out: Record<string, unknown> = {};\n  for (const [key, child] of Object.entries(value)) {\n    if (['description', 'title', 'examples', 'default', '$comment'].includes(key)) continue;\n    if (key === 'properties' && child && typeof child === 'object') {\n      out.properties = Object.fromEntries(\n        Object.entries(child).map(([prop, schema]) => [prop, stripSchemaMetadata(schema)])\n      );\n      continue;\n    }\n    out[key] = stripSchemaMetadata(child);\n  }\n  return out;\n}\n\nfunction compactToolDeclarations(tools: ToolDeclaration[], turn: number, model?: string): ToolDeclaration[] {\n  const enabled = String(process.env.CREW_TOOL_SCHEMA_COMPACTION || 'true').trim().toLowerCase();\n  // OpenAI models need full tool descriptions every turn \u2014 they don't retain tool semantics across turns\n  const isOpenAI = model && (model.includes('gpt') || model.includes('o3') || model.includes('o4'));\n  if (turn <= 1 || enabled === 'false' || enabled === '0' || enabled === 'off' || isOpenAI) return tools;\n  return tools.map((tool) => ({\n    name: tool.name,\n    description: '',\n    parameters: stripSchemaMetadata(tool.parameters) as ToolDeclaration['parameters']\n  }));\n}\n\nasync function resolveProvider(modelOverride?: string, preferTier?: string): Promise<ResolvedProvider | null> {\n  let effectiveModel = (modelOverride || process.env.CREW_EXECUTION_MODEL || '').trim().toLowerCase();\n\n  // \u2500\u2500 PRIORITY 0: Explicit provider:model format (e.g. groq:llama-3.3-70b, ollama:glm-5.1:cloud) \u2500\u2500\n  // Unambiguous routing \u2014 skips all guessing. Provider ID before first colon (unless it's a model tag like :cloud/:latest).\n  const providerModelMatch = effectiveModel.match(/^([a-z][\\w-]*):(.+)$/);\n  if (providerModelMatch) {\n    const [, explicitProvider, modelPart] = providerModelMatch;\n    // Skip if the \"provider\" part is actually a model tag (cloud, latest, 31b, etc.)\n    const isModelTag = /^\\d+b$|^cloud$|^latest$|^q\\d|^fp\\d|^gguf$/i.test(modelPart.split(':')[0] || '');\n    if (!isModelTag) {\n      const providerAliases: Record<string, string> = {\n        'anthropic': 'anthropic', 'claude': 'anthropic',\n        'openai': 'openai', 'gpt': 'openai',\n        'google': 'gemini', 'gemini': 'gemini',\n        'xai': 'grok', 'grok': 'grok',\n        'groq': 'groq',\n        'deepseek': 'deepseek',\n        'mistral': 'mistral',\n        'cerebras': 'cerebras',\n        'nvidia': 'nvidia',\n        'fireworks': 'fireworks',\n        'together': 'together',\n        'openrouter': 'openrouter',\n        'opencode': 'opencode', 'zen': 'opencode',\n        'perplexity': 'perplexity',\n        'ollama': 'ollama',\n      };\n      const resolvedId = providerAliases[explicitProvider] || explicitProvider;\n\n      // Ollama \u2014 keyless\n      if (resolvedId === 'ollama') {\n        return {\n          key: 'ollama',\n          model: modelPart,\n          driver: 'openai',\n          apiUrl: 'http://localhost:11434/v1/chat/completions',\n          id: 'ollama'\n        };\n      }\n\n      // OAuth providers\n      if (resolvedId === 'anthropic' && process.env.CREW_NO_OAUTH !== 'true') {\n        try {\n          const oauth = await getOAuthToken();\n          if (oauth?.accessToken) {\n            return { key: oauth.accessToken, model: modelPart, driver: 'anthropic', id: 'anthropic-oauth', isOAuth: true };\n          }\n        } catch {}\n      }\n      if (resolvedId === 'openai' && process.env.CREW_NO_OAUTH !== 'true') {\n        try {\n          const oauth = await getOpenAIOAuthToken();\n          if (oauth?.accessToken) {\n            return { key: oauth.accessToken, model: modelPart, driver: 'openai', apiUrl: OPENAI_CODEX_API_URL, id: 'openai-oauth', isOAuth: true };\n          }\n        } catch {}\n      }\n      if (resolvedId === 'gemini' && process.env.CREW_NO_OAUTH !== 'true') {\n        try {\n          const oauth = await getGeminiOAuthToken();\n          if (oauth?.accessToken) {\n            return { key: oauth.accessToken, model: modelPart, driver: 'gemini', id: 'gemini-oauth', isOAuth: true };\n          }\n        } catch {}\n      }\n\n      // API key providers\n      const p = PROVIDER_ORDER.find(p => p.id === resolvedId);\n      if (p) {\n        const key = process.env[p.envKey];\n        if (key && key.length >= 5) {\n          return { key, model: modelPart, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n        }\n      }\n\n      console.warn(`[crew-cli] \u26A0\uFE0F Provider \"${explicitProvider}\" specified but no API key found (${resolvedId})`);\n      // Don't fall through \u2014 explicit provider should fail, not silently use another\n      return null;\n    }\n  }\n\n  // \u2500\u2500 OAuth: subscription-based auth (free, highest priority) \u2500\u2500\n  // Try all OAuth providers before API keys. OAuth uses existing subscriptions (free).\n\n  if (process.env.CREW_NO_OAUTH !== 'true') {\n    // OAuth providers are free (use subscriptions), so prefer over API keys.\n    // When a specific model is requested, route to the matching provider first.\n    // When no model is specified, try all in priority order: Claude > OpenAI > Gemini.\n\n    const wantsOpenAI = effectiveModel.includes('gpt') || effectiveModel.includes('openai') || effectiveModel.includes('o3') || effectiveModel.includes('o4');\n    const wantsGemini = effectiveModel.includes('gemini');\n    const wantsClaude = effectiveModel.includes('claude') || effectiveModel.includes('sonnet') || effectiveModel.includes('opus') || effectiveModel.includes('haiku');\n\n    // 1. Claude OAuth (macOS Keychain \u2014 Claude Max/Pro subscription)\n    // All 3 tiers work: Haiku, Sonnet, Opus. Default is Sonnet 4.6.\n    // Override via CREW_OAUTH_CLAUDE_MODEL env var or dashboard Models tab.\n    if (wantsClaude || (!wantsOpenAI && !wantsGemini && !effectiveModel)) {\n      try {\n        const oauth = await getOAuthToken();\n        if (oauth?.accessToken) {\n          return {\n            key: oauth.accessToken,\n            model: effectiveModel && wantsClaude ? effectiveModel : String(process.env.CREW_OAUTH_CLAUDE_MODEL || (() => { try { const c = JSON.parse(require('fs').readFileSync(require('path').join(require('os').homedir(), '.crewswarm', 'crewswarm.json'), 'utf8')); return c.claudeOauthModel || 'claude-sonnet-4-6'; } catch { return 'claude-sonnet-4-6'; } })()),\n            driver: 'anthropic',\n            id: `anthropic-oauth-${oauth.subscriptionType || 'unknown'}`,\n            isOAuth: true\n          };\n        }\n      } catch {}\n    }\n\n    // 2. OpenAI OAuth (Codex CLI auth \u2014 ChatGPT Plus/Pro subscription)\n    if (wantsOpenAI || (!wantsClaude && !wantsGemini && !effectiveModel)) {\n      try {\n        const oauth = await getOpenAIOAuthToken();\n        if (oauth?.accessToken) {\n          return {\n            key: oauth.accessToken,\n            model: effectiveModel && wantsOpenAI ? effectiveModel : String(process.env.CREW_OAUTH_OPENAI_MODEL || 'gpt-5.4'),\n            driver: 'openai',\n            apiUrl: OPENAI_CODEX_API_URL,\n            id: 'openai-oauth-codex',\n            isOAuth: true\n          };\n        }\n      } catch {\n        // OpenAI OAuth unavailable \u2014 try next\n      }\n    }\n\n    // 3. Gemini OAuth (Google ADC or Gemini CLI \u2014 Google account)\n    if (wantsGemini || (!wantsClaude && !wantsOpenAI && !effectiveModel)) {\n      try {\n        const oauth = await getGeminiOAuthToken();\n        if (oauth?.accessToken) {\n          return {\n            key: oauth.accessToken,\n            model: effectiveModel.includes('gemini') ? effectiveModel : 'gemini-2.5-flash',\n            driver: 'gemini',\n            id: 'gemini-oauth-adc',\n            isOAuth: true\n          };\n        }\n      } catch {\n        // Gemini OAuth unavailable \u2014 try next\n      }\n    }\n  }\n\n  // \u2500\u2500 API key providers (fallback when OAuth unavailable) \u2500\u2500\n  // If a specific model is requested, find the matching provider\n  if (effectiveModel) {\n    // Ollama catch-all: any model with \":cloud\" suffix or known Ollama local models\n    // Route to Ollama's OpenAI-compatible API \u2014 no API key needed\n    const isOllamaModel = effectiveModel.includes(':cloud') || effectiveModel.includes(':latest')\n      || /^(qwen|llama|gemma|phi|mistral|deepseek-coder|codellama|lfm)\\d*[-.:]/.test(effectiveModel);\n    if (isOllamaModel) {\n      return {\n        key: 'ollama',\n        model: modelOverride || effectiveModel,\n        driver: 'openai',\n        apiUrl: 'http://localhost:11434/v1/chat/completions',\n        id: 'ollama'\n      };\n    }\n\n    // Models with provider/ prefix (e.g. anthropic/claude-sonnet-4.6, qwen/qwen3-coder)\n    // are OpenRouter model slugs \u2014 route to OpenRouter directly\n    // Slash-prefixed models (moonshotai/kimi-k2, openai/gpt-oss-120b, qwen/qwen3-32b)\n    // These are hosted on multiple providers (Groq, Fireworks, NVIDIA, OpenRouter).\n    // Use CREW_PROVIDER env var to force a specific provider, otherwise try OpenRouter.\n    if (effectiveModel.includes('/') && !effectiveModel.startsWith('accounts/') && !effectiveModel.startsWith('models/')) {\n      const forcedProvider = process.env.CREW_PROVIDER?.toLowerCase();\n      if (forcedProvider) {\n        const p = PROVIDER_ORDER.find(p => p.id === forcedProvider);\n        const key = p ? process.env[p.envKey] : undefined;\n        if (p && key && key.length >= 5) {\n          return { key, model: modelOverride || effectiveModel, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n        }\n      }\n      const orKey = process.env.OPENROUTER_API_KEY;\n      if (orKey && orKey.length >= 5) {\n        return { key: orKey, model: modelOverride || effectiveModel, driver: 'openrouter', apiUrl: 'https://openrouter.ai/api/v1/chat/completions', id: 'openrouter' };\n      }\n    }\n\n    for (const p of PROVIDER_ORDER) {\n      const isKeyless = p.id === 'ollama';\n      const key = isKeyless ? 'ollama' : process.env[p.envKey];\n      if (!isKeyless && (!key || key.length < 5)) continue;\n      if (p.envKey === 'GOOGLE_API_KEY' && process.env.GEMINI_API_KEY) continue;\n      if (p.modelPrefix && effectiveModel.includes(p.modelPrefix)) {\n        return { key: key || 'ollama', model: modelOverride || process.env.CREW_EXECUTION_MODEL || p.model, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n      }\n    }\n\n    // No prefix match \u2014 warn and try OpenAI-compatible provider as last resort\n    console.warn(`[crew-cli] \u26A0\uFE0F No provider matched model \"${effectiveModel}\" \u2014 trying OpenAI-compatible fallback`);\n    for (const p of PROVIDER_ORDER) {\n      const key = process.env[p.envKey];\n      if (!key || key.length < 5) continue;\n      if (p.driver === 'openai' || p.driver === 'openrouter') {\n        console.warn(`[crew-cli] \u26A0\uFE0F Falling back to ${p.id} (${p.apiUrl}) \u2014 model may not be available there`);\n        return { key, model: modelOverride || effectiveModel, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n      }\n    }\n  }\n\n  // Tier-based routing\n  const targetTier = preferTier || 'standard';\n  // Try preferred tier first, then fall back to any\n  const tieredOrder = [\n    ...PROVIDER_ORDER.filter(p => p.tier === targetTier),\n    ...PROVIDER_ORDER.filter(p => p.tier !== targetTier)\n  ];\n\n  for (const p of tieredOrder) {\n    const key = process.env[p.envKey];\n    if (!key || key.length < 5) continue;\n    if (p.envKey === 'GOOGLE_API_KEY' && process.env.GEMINI_API_KEY) continue;\n    return { key, model: p.model, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n  }\n  return null;\n}\n\n// ---------------------------------------------------------------------------\n// Streaming LLM turn \u2014 real-time token output\n// ---------------------------------------------------------------------------\n\n/** Image attachment for multimodal input */\nexport interface ImageAttachment {\n  data: string;      // base64-encoded image data\n  mimeType: string;  // e.g. 'image/png', 'image/jpeg'\n}\n\nasync function executeStreamingGeminiTurn(\n  fullTask: string,\n  tools: ToolDeclaration[],\n  key: string,\n  model: string,\n  systemPrompt: string,\n  stream: boolean,\n  images?: ImageAttachment[],\n  historyMessages?: GeminiContent[] | ChatMessage[],\n  isOAuth?: boolean,\n  projectId?: string,\n  oauthSource?: string,\n  abortSignal?: AbortSignal\n): Promise<LLMTurnResult> {\n  if (isOAuth) {\n    return executeGeminiCodeAssistTurn(\n      fullTask,\n      tools,\n      key,\n      model,\n      systemPrompt,\n      images,\n      historyMessages,\n      projectId,\n      oauthSource\n    );\n  }\n\n  const functionDeclarations = tools.map(t => ({\n    name: t.name,\n    description: t.description,\n    parameters: t.parameters\n  }));\n\n  // Build user parts: text + optional images\n  const userParts: Array<Record<string, unknown>> = [{ text: `${systemPrompt}\\n\\nTask:\\n${fullTask}` }];\n  if (images?.length) {\n    for (const img of images) {\n      userParts.push({ inlineData: { mimeType: img.mimeType, data: img.data } });\n    }\n  }\n  const contents: Array<Record<string, unknown>> = [\n    { role: 'user', parts: userParts },\n    // Insert structured history (tool call/result pairs)\n    ...(historyMessages || []),\n    // Continuation prompt if we have history\n    ...(historyMessages?.length ? [{ role: 'user', parts: [{ text: 'Continue executing the task based on the results above.' }] }] : [])\n  ];\n\n  const endpoint = stream ? 'streamGenerateContent' : 'generateContent';\n\n  // OAuth uses Bearer auth header; API keys use ?key= query parameter\n  const url = isOAuth\n    ? `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}${stream ? '?alt=sse' : ''}`\n    : `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${encodeURIComponent(key)}${stream ? '&alt=sse' : ''}`;\n\n  const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n  if (isOAuth) {\n    headers['Authorization'] = `Bearer ${key}`;\n  }\n\n  // Combine caller's abort signal with a timeout signal\n  const timeoutSignal = AbortSignal.timeout(120000);\n  const fetchSignal = abortSignal\n    ? AbortSignal.any([abortSignal, timeoutSignal])\n    : timeoutSignal;\n\n  const res = await fetch(url, {\n    method: 'POST',\n    headers,\n    signal: fetchSignal,\n    body: JSON.stringify({\n      contents,\n      tools: [{ functionDeclarations }],\n      generationConfig: { temperature: 0.3, maxOutputTokens: 8192 }\n    })\n  });\n\n  if (!res.ok) {\n    // On 401 with OAuth, try refreshing the token and retrying once\n    if (res.status === 401 && isOAuth) {\n      const refreshed = await forceRefreshGeminiOAuth();\n      if (refreshed?.accessToken && refreshed.accessToken !== key) {\n        return executeStreamingGeminiTurn(\n          fullTask, tools, refreshed.accessToken, model,\n          systemPrompt, stream, images, historyMessages, true, projectId, oauthSource, abortSignal\n        );\n      }\n    }\n    const err = await res.text();\n    throw new Error(`Gemini API ${res.status}: ${err.slice(0, 300)}`);\n  }\n\n  if (stream && res.body) {\n    // Parse SSE stream\n    let fullText = '';\n    const toolCalls: Array<{ tool: string; params: Record<string, unknown> }> = [];\n    let totalCost = 0;\n\n    const reader = res.body.getReader();\n    const decoder = new TextDecoder();\n    let buffer = '';\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n\n        buffer += decoder.decode(value, { stream: true });\n        const lines = buffer.split('\\n');\n        buffer = lines.pop() || '';\n\n        for (const line of lines) {\n          if (!line.startsWith('data: ')) continue;\n          const jsonStr = line.slice(6).trim();\n          if (!jsonStr || jsonStr === '[DONE]') continue;\n\n          try {\n            const chunk = JSON.parse(jsonStr);\n            const parts = chunk?.candidates?.[0]?.content?.parts ?? [];\n\n            for (const part of parts) {\n              if (part.text) {\n                process.stdout.write(part.text);\n                fullText += part.text;\n              }\n              if (part.functionCall) {\n                toolCalls.push({\n                  tool: part.functionCall.name || '',\n                  params: part.functionCall.args || {}\n                });\n              }\n            }\n\n            // Accumulate usage\n            const usage = chunk?.usageMetadata;\n            if (usage) {\n              totalCost = (usage.promptTokenCount || 0) * 0.075 / 1_000_000\n                + (usage.candidatesTokenCount || 0) * 0.30 / 1_000_000;\n            }\n          } catch {\n            // Skip malformed chunks\n          }\n        }\n      }\n    } finally {\n      reader.releaseLock();\n    }\n\n    if (fullText) process.stdout.write('\\n');\n\n    if (toolCalls.length > 0) {\n      return { toolCalls, response: fullText, cost: totalCost };\n    }\n    return { response: fullText, status: 'COMPLETE', cost: totalCost };\n  }\n\n  // Non-streaming fallback\n  const data = await res.json() as LLMResponseData;\n  const parts = data?.candidates?.[0]?.content?.parts ?? [];\n  const usage = (data?.usageMetadata ?? {}) as Record<string, number>;\n  const cost = (usage.promptTokenCount || 0) * 0.075 / 1_000_000 + (usage.candidatesTokenCount || 0) * 0.30 / 1_000_000;\n\n  const toolCalls: Array<{ tool: string; params: Record<string, unknown> }> = [];\n  for (const part of parts) {\n    const functionCall = part.functionCall as { name?: string; args?: Record<string, unknown> } | undefined;\n    if (functionCall) {\n      toolCalls.push({ tool: functionCall.name || '', params: functionCall.args || {} });\n    }\n  }\n\n  if (toolCalls.length > 0) return { toolCalls, response: '', cost };\n\n  const textPart = parts.find((p: Record<string, unknown>) => p.text) as { text?: string } | undefined;\n  return { response: textPart?.text || '', status: 'COMPLETE', cost };\n}\n\nasync function executeGeminiCodeAssistTurn(\n  fullTask: string,\n  tools: ToolDeclaration[],\n  key: string,\n  model: string,\n  systemPrompt: string,\n  images?: ImageAttachment[],\n  historyMessages?: GeminiContent[] | ChatMessage[],\n  projectId?: string,\n  oauthSource?: string\n): Promise<LLMTurnResult> {\n  const resolvedProjectId = projectId || process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT_ID || '';\n  const headers: Record<string, string> = {\n    'Content-Type': 'application/json',\n    'Authorization': `Bearer ${key}`,\n    'User-Agent': 'GeminiCLI/crew-cli'\n  };\n  if (oauthSource === 'adc' && resolvedProjectId) {\n    headers['x-goog-user-project'] = resolvedProjectId;\n  }\n\n  const metadata = {\n    ideType: 'IDE_UNSPECIFIED',\n    platform: 'PLATFORM_UNSPECIFIED',\n    pluginType: 'GEMINI',\n    duetProject: resolvedProjectId || undefined\n  };\n\n  const loadResponse = await fetch('https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist', {\n    method: 'POST',\n    headers,\n    signal: AbortSignal.timeout(120000),\n    body: JSON.stringify({\n      cloudaicompanionProject: resolvedProjectId || undefined,\n      metadata\n    })\n  });\n\n  if (!loadResponse.ok) {\n    if (loadResponse.status === 401) {\n      const refreshed = await forceRefreshGeminiOAuth();\n      if (refreshed?.accessToken && refreshed.accessToken !== key) {\n        return executeGeminiCodeAssistTurn(\n          fullTask,\n          tools,\n          refreshed.accessToken,\n          model,\n          systemPrompt,\n          images,\n          historyMessages,\n          refreshed.projectId || projectId,\n          refreshed.source\n        );\n      }\n    }\n    const err = await loadResponse.text().catch(() => '');\n    throw new Error(`Gemini Code Assist loadCodeAssist ${loadResponse.status}: ${err.slice(0, 300)}`);\n  }\n\n  const loadData = await loadResponse.json() as LLMResponseData;\n  const activeProjectId = loadData?.cloudaicompanionProject || resolvedProjectId;\n  const functionDeclarations = tools.map(t => ({\n    name: t.name,\n    description: t.description,\n    parameters: t.parameters\n  }));\n\n  const userParts: Array<Record<string, unknown>> = [{ text: `${systemPrompt}\\n\\nTask:\\n${fullTask}` }];\n  if (images?.length) {\n    for (const img of images) {\n      userParts.push({ inlineData: { mimeType: img.mimeType, data: img.data } });\n    }\n  }\n\n  const response = await fetch('https://cloudcode-pa.googleapis.com/v1internal:generateContent', {\n    method: 'POST',\n    headers,\n    signal: AbortSignal.timeout(120000),\n    body: JSON.stringify({\n      model,\n      project: activeProjectId || undefined,\n      user_prompt_id: `crew-${Date.now()}`,\n      request: {\n        contents: [\n          { role: 'user', parts: userParts },\n          ...(historyMessages || []),\n          ...(historyMessages?.length ? [{ role: 'user', parts: [{ text: 'Continue executing the task based on the results above.' }] }] : [])\n        ],\n        systemInstruction: {\n          role: 'user',\n          parts: [{ text: systemPrompt }]\n        },\n        tools: [{ functionDeclarations }],\n        generationConfig: { temperature: 0.3, maxOutputTokens: 8192 },\n        session_id: ''\n      }\n    })\n  });\n\n  if (!response.ok) {\n    const err = await response.text().catch(() => '');\n    throw new Error(`Gemini Code Assist generateContent ${response.status}: ${err.slice(0, 300)}`);\n  }\n\n  type CodeAssistData = { response?: { candidates?: Array<{ content?: { parts?: Array<Record<string, unknown>> } }>; usageMetadata?: Record<string, number> } };\n  const data = await response.json() as CodeAssistData;\n  const parts = data?.response?.candidates?.[0]?.content?.parts ?? [];\n  const usage = data?.response?.usageMetadata ?? {};\n  const cost = (usage.promptTokenCount || 0) * 0.075 / 1_000_000 + (usage.candidatesTokenCount || 0) * 0.30 / 1_000_000;\n\n  const toolCalls: Array<{ tool: string; params: Record<string, unknown> }> = [];\n  let fullText = '';\n  for (const part of parts) {\n    const text = typeof part.text === 'string' ? part.text : '';\n    const functionCall = part.functionCall as { name?: string; args?: Record<string, unknown> } | undefined;\n    if (text) {\n      fullText += text;\n    }\n    if (functionCall) {\n      toolCalls.push({ tool: functionCall.name || '', params: functionCall.args || {} });\n    }\n  }\n\n  if (fullText) process.stdout.write(`${fullText}\\n`);\n  if (toolCalls.length > 0) return { toolCalls, response: fullText, cost };\n  return { response: fullText, status: 'COMPLETE', cost };\n}\n\nasync function executeStreamingOpenAITurn(\n  fullTask: string,\n  tools: ToolDeclaration[],\n  apiUrl: string,\n  apiKey: string,\n  model: string,\n  systemPrompt: string,\n  stream: boolean,\n  images?: ImageAttachment[],\n  historyMessages?: GeminiContent[] | ChatMessage[],\n  isOAuth?: boolean,\n  historyContext?: string,\n  abortSignal?: AbortSignal\n): Promise<LLMTurnResult> {\n  // Responses API (Codex OAuth) degrades with 20+ tools \u2014 GPT-5.4 stops using write tools.\n  // Filter to core tools only for that path. Chat Completions path gets all tools.\n  const isCodexResponses = isOAuth && apiUrl === OPENAI_CODEX_API_URL;\n  // GPT-5.4 via Responses API degrades sharply above ~8 tools (tested: 5=perfect, 14=broken)\n  const CODEX_CORE_TOOLS = new Set([\n    'read_file', 'write_file', 'replace',\n    'run_shell_command', 'grep_search', 'list_directory',\n    'append_file', 'mkdir'\n  ]);\n  // Apply tool filtering for Codex Responses API and any GPT-5+ model via OpenRouter/Chat Completions\n  const isGPT5Plus = model && (/gpt-5|gpt-6/i.test(model) || /o3|o4/i.test(model));\n  const shouldFilterTools = isCodexResponses || (isGPT5Plus && tools.length > 10);\n  const effectiveTools = shouldFilterTools\n    ? tools.filter(t => CODEX_CORE_TOOLS.has(t.name))\n    : tools;\n  const openaiTools = effectiveTools.map(t => ({\n    type: 'function' as const,\n    ...(isCodexResponses\n      ? { name: t.name, description: t.description, parameters: t.parameters }\n      : { function: { name: t.name, description: t.description, parameters: t.parameters } })\n  }));\n\n  if (isCodexResponses && process.env.CREW_VERBOSE !== 'false') {\n    console.error(`\\x1b[2m[Codex Responses API] ${openaiTools.length} tools (filtered from ${tools.length})\\x1b[0m`);\n  }\n\n  // GPT-5/6 only support temperature=1; other values cause 400\n  const temp = (model?.startsWith?.('gpt-5') || model?.startsWith?.('gpt-6')) ? 1 : 0.3;\n  const isCodexOAuth = isOAuth && apiUrl === OPENAI_CODEX_API_URL;\n  // Build Responses API input with proper function_call/function_call_output history\n  const codexInput: Array<Record<string, unknown>> = [];\n  if (isCodexResponses && historyMessages && Array.isArray(historyMessages)) {\n    // Convert OpenAI-format history to Responses API input items\n    for (const msg of historyMessages as ChatMessage[]) {\n      if (msg.role === 'assistant' && msg.tool_calls) {\n        for (const tc of msg.tool_calls) {\n          codexInput.push({\n            type: 'function_call',\n            name: tc.function?.name || '',\n            arguments: tc.function?.arguments || '{}',\n            call_id: tc.id || `call_${Date.now()}`\n          });\n        }\n      } else if (msg.role === 'tool') {\n        codexInput.push({\n          type: 'function_call_output',\n          call_id: msg.tool_call_id || '',\n          output: typeof msg.content === 'string' ? msg.content.slice(0, 4000) : JSON.stringify(msg.content).slice(0, 4000)\n        });\n      }\n    }\n  }\n\n  const body: Record<string, unknown> = isCodexResponses\n    ? {\n        model,\n        instructions: systemPrompt,\n        input: [\n          {\n            role: 'user',\n            content: [\n              {\n                type: 'input_text',\n                text: fullTask\n              },\n              ...(images?.map((img: ImageAttachment) => ({\n                type: 'input_image',\n                image_url: `data:${img.mimeType};base64,${img.data}`\n              })) || [])\n            ]\n          },\n          ...codexInput\n        ],\n        tools: openaiTools,\n        store: false,\n        stream: true\n      }\n    : (() => {\n        let userContent: string | Array<Record<string, unknown>> = fullTask;\n        if (images?.length) {\n          const parts: Array<Record<string, unknown>> = [{ type: 'text', text: fullTask }];\n          for (const img of images) {\n            parts.push({\n              type: 'image_url',\n              image_url: { url: `data:${img.mimeType};base64,${img.data}` }\n            });\n          }\n          userContent = parts;\n        }\n        const messages = [\n          { role: 'system', content: systemPrompt },\n          { role: 'user', content: userContent },\n          ...(historyMessages || [])\n        ];\n        const isGpt5Plus = model?.startsWith?.('gpt-5') || model?.startsWith?.('gpt-6') || model?.startsWith?.('o3') || model?.startsWith?.('o4');\n        return {\n          model,\n          messages,\n          tools: openaiTools,\n          temperature: temp,\n          ...(isGpt5Plus ? { max_completion_tokens: 8192 } : { max_tokens: 8192 }),\n          stream\n        };\n      })();\n\n  // Combine caller's abort signal with a timeout signal\n  const openAITimeoutSignal = AbortSignal.timeout(120000);\n  const openAIFetchSignal = abortSignal\n    ? AbortSignal.any([abortSignal, openAITimeoutSignal])\n    : openAITimeoutSignal;\n\n  const res = await fetch(apiUrl, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      'Authorization': `Bearer ${apiKey}`\n    },\n    signal: openAIFetchSignal,\n    body: JSON.stringify(body)\n  });\n\n  if (!res.ok) {\n    // On 401 with OAuth, try refreshing the token and retrying once\n    if (res.status === 401 && isOAuth) {\n      const refreshed = await forceRefreshOpenAIOAuth();\n      if (refreshed?.accessToken && refreshed.accessToken !== apiKey) {\n        return executeStreamingOpenAITurn(\n          fullTask, tools, apiUrl, refreshed.accessToken, model,\n          systemPrompt, stream, images, historyMessages, true, historyContext, abortSignal\n        );\n      }\n    }\n    const err = await res.text();\n    throw new Error(`OpenAI API ${res.status}: ${err.slice(0, 300)}`);\n  }\n\n  if (isCodexOAuth && res.body) {\n    return streamOpenAIResponsesOAuthTurn(res);\n  }\n\n  if (stream && res.body) {\n    let fullText = '';\n    const toolCallAccumulator = new Map<number, { name: string; args: string }>();\n    const sseDebug = process.env.CREW_DEBUG_SSE === '1' || process.env.CREW_DEBUG_SSE === 'true';\n    const sseLog: string[] = [];\n\n    const reader = res.body.getReader();\n    const decoder = new TextDecoder();\n    let buffer = '';\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n\n        buffer += decoder.decode(value, { stream: true });\n        const lines = buffer.split('\\n');\n        buffer = lines.pop() || '';\n\n        for (const line of lines) {\n          if (!line.startsWith('data: ')) continue;\n          const jsonStr = line.slice(6).trim();\n          if (!jsonStr || jsonStr === '[DONE]') continue;\n          if (sseDebug) sseLog.push(jsonStr);\n\n          try {\n            const chunk = JSON.parse(jsonStr);\n            const delta = chunk?.choices?.[0]?.delta;\n            if (!delta) continue;\n\n            // Stream text content\n            if (delta.content) {\n              process.stdout.write(delta.content);\n              fullText += delta.content;\n            }\n\n            // Accumulate tool calls (streamed in pieces)\n            if (delta.tool_calls) {\n              for (const tc of delta.tool_calls) {\n                const idx = tc.index ?? 0;\n                if (!toolCallAccumulator.has(idx)) {\n                  toolCallAccumulator.set(idx, { name: '', args: '' });\n                }\n                const acc = toolCallAccumulator.get(idx)!;\n                if (tc.function?.name) {\n                  acc.name += tc.function.name;\n                  if (sseDebug) console.error(`[SSE-OAI] tool_call idx=${idx} name=${tc.function.name}`);\n                }\n                if (tc.function?.arguments) acc.args += tc.function.arguments;\n              }\n            }\n          } catch {\n            // Skip malformed chunks\n          }\n        }\n      }\n    } finally {\n      reader.releaseLock();\n    }\n\n    if (fullText) process.stdout.write('\\n');\n\n    // Dump raw SSE log for debugging\n    if (sseDebug && sseLog.length > 0) {\n      const logPath = `/tmp/crew-sse-openai-${Date.now()}.jsonl`;\n      try {\n        const { writeFileSync } = await import('node:fs');\n        writeFileSync(logPath, sseLog.join('\\n') + '\\n');\n        console.error(`[SSE-OAI] Raw log saved: ${logPath} (${sseLog.length} events)`);\n      } catch {}\n    }\n\n    // Parse accumulated tool calls\n    const toolCalls: Array<{ tool: string; params: Record<string, unknown> }> = [];\n    for (const [idx, tc] of toolCallAccumulator) {\n      if (tc.name) {\n        let params: Record<string, unknown> = {};\n        if (sseDebug) console.error(`[SSE-OAI] Parsing tool idx=${idx} name=${tc.name} argsLen=${tc.args.length} preview=${tc.args.slice(0, 100)}`);\n        // Parse raw first \u2014 repairJson corrupts code strings containing `: type`\n        try {\n          params = JSON.parse(tc.args);\n          if (sseDebug) console.error(`[SSE-OAI] Raw parse OK: keys=${Object.keys(params).join(',')}`);\n        } catch {\n          try {\n            params = JSON.parse(repairJson(tc.args));\n            if (sseDebug) console.error(`[SSE-OAI] Repair parse OK: keys=${Object.keys(params).join(',')}`);\n          } catch {\n            if (sseDebug) console.error(`[SSE-OAI] Both parses FAILED`);\n          }\n        }\n        toolCalls.push({ tool: tc.name, params });\n      }\n    }\n\n    if (toolCalls.length > 0) return { toolCalls, response: fullText, cost: 0 };\n    return { response: fullText, status: 'COMPLETE', cost: 0 };\n  }\n\n  // Non-streaming fallback to multi-turn-drivers\n  // (this path shouldn't be hit normally since we always stream)\n  const data = await res.json() as LLMResponseData;\n  const choice = data?.choices?.[0];\n  const msg = choice?.message;\n\n  const toolCallsRaw = msg?.tool_calls;\n  if (toolCallsRaw && toolCallsRaw.length > 0) {\n    const toolCalls = (toolCallsRaw as OpenAIToolCall[]).map((tc) => {\n      let params: Record<string, unknown> = {};\n      // Parse raw first \u2014 repairJson corrupts code strings containing `: type`\n      try { params = JSON.parse(tc.function?.arguments || '{}'); } catch { try { params = JSON.parse(repairJson(tc.function?.arguments || '{}')); } catch {} }\n      return { tool: tc.function?.name || '', params };\n    });\n    return { toolCalls, response: msg?.content || '', cost: 0 };\n  }\n\n  return { response: msg?.content || '', status: 'COMPLETE', cost: 0 };\n}\n\nasync function streamOpenAIResponsesOAuthTurn(res: Response): Promise<LLMTurnResult> {\n  if (!res.body) {\n    return { response: '', status: 'COMPLETE', cost: 0 };\n  }\n\n  const reader = res.body.getReader();\n  const decoder = new TextDecoder();\n  const toolCallsById = new Map<string, { name: string; args: string }>();\n  let buffer = '';\n  let fullText = '';\n  let usage: Record<string, number> | null = null;\n\n  const applyEvent = (eventType: string, payload: Record<string, unknown>) => {\n    const item = (payload?.item || payload?.output_item) as Record<string, unknown> | undefined;\n    const itemId = String(item?.id || payload?.item_id || payload?.call_id || '');\n\n    if (eventType === 'response.output_text.delta' && typeof payload?.delta === 'string') {\n      process.stdout.write(payload.delta);\n      fullText += payload.delta;\n      return;\n    }\n\n    if (eventType === 'response.function_call_arguments.delta' && itemId) {\n      if (!toolCallsById.has(itemId)) {\n        toolCallsById.set(itemId, { name: '', args: '' });\n      }\n      toolCallsById.get(itemId)!.args += String(payload?.delta || '');\n      return;\n    }\n\n    if ((eventType === 'response.output_item.added' || eventType === 'response.output_item.done') && item?.type === 'function_call') {\n      if (!toolCallsById.has(itemId)) {\n        toolCallsById.set(itemId, { name: '', args: '' });\n      }\n      const acc = toolCallsById.get(itemId)!;\n      if (item?.name) acc.name = String(item.name);\n      if (typeof item?.arguments === 'string') acc.args = item.arguments;\n      return;\n    }\n\n    if (eventType === 'response.completed') {\n      const res = payload?.response as Record<string, unknown> | undefined;\n      usage = (res?.usage as Record<string, number>) || null;\n      if (!fullText && typeof res?.output_text === 'string') {\n        fullText = res.output_text;\n      }\n    }\n  };\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      let boundary = buffer.indexOf('\\n\\n');\n      while (boundary !== -1) {\n        const chunk = buffer.slice(0, boundary);\n        buffer = buffer.slice(boundary + 2);\n\n        let eventType = '';\n        const dataLines: string[] = [];\n        for (const line of chunk.split('\\n')) {\n          if (line.startsWith('event:')) eventType = line.slice(6).trim();\n          if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());\n        }\n\n        const raw = dataLines.join('\\n');\n        if (raw) {\n          try {\n            const payload = JSON.parse(raw);\n            applyEvent(eventType || String(payload?.type || ''), payload);\n          } catch {\n            // Ignore malformed SSE fragments.\n          }\n        }\n        boundary = buffer.indexOf('\\n\\n');\n      }\n    }\n  } finally {\n    reader.releaseLock();\n  }\n\n  if (fullText) process.stdout.write('\\n');\n\n  const toolCalls: Array<{ tool: string; params: Record<string, unknown> }> = [];\n  for (const [, tc] of toolCallsById) {\n    if (!tc.name) continue;\n    let params: Record<string, unknown> = {};\n    // Parse raw first \u2014 repairJson corrupts code strings containing `: type`\n    try { params = JSON.parse(tc.args); } catch { try { params = JSON.parse(repairJson(tc.args)); } catch {} }\n    toolCalls.push({ tool: tc.name, params });\n  }\n\n  const openAiUsage = usage as { input_tokens?: number; output_tokens?: number } | null;\n  const cost = openAiUsage\n    ? ((openAiUsage.input_tokens || 0) * 5 + (openAiUsage.output_tokens || 0) * 20) / 1_000_000\n    : 0;\n\n  if (toolCalls.length > 0) {\n    return { toolCalls, response: fullText.trim(), cost };\n  }\n  return { response: fullText.trim(), status: 'COMPLETE', cost };\n}\n\n// ---------------------------------------------------------------------------\n// Anthropic SDK path \u2014 uses official SDK with authToken for OAuth\n// ---------------------------------------------------------------------------\n\nasync function executeAnthropicSDKTurn(\n  fullTask: string,\n  tools: ToolDeclaration[],\n  authToken: string,\n  model: string,\n  systemPrompt: string,\n  images?: ImageAttachment[],\n  historyMessages?: GeminiContent[] | ChatMessage[]\n): Promise<LLMTurnResult> {\n  const Anthropic = (await import('@anthropic-ai/sdk')).default;\n  const { randomUUID } = await import('node:crypto');\n  const sessionHeader = randomUUID();\n  const client = new Anthropic({\n    authToken,\n    apiKey: null as unknown as string,\n    timeout: 120000,\n    defaultHeaders: {\n      'x-app': 'cli',\n      'X-Claude-Code-Session-Id': sessionHeader,\n      'anthropic-dangerous-direct-browser-access': 'true'\n    }\n  });\n\n  // Build user content\n  let userContent: string | Array<Record<string, unknown>> = fullTask;\n  if (images?.length) {\n    const parts: Array<Record<string, unknown>> = [{ type: 'text', text: fullTask }];\n    for (const img of images) {\n      parts.push({\n        type: 'image',\n        source: { type: 'base64', media_type: img.mimeType, data: img.data }\n      });\n    }\n    userContent = parts;\n  }\n\n  const anthropicTools = tools.map(t => ({\n    name: t.name,\n    description: t.description || '',\n    input_schema: t.parameters as Record<string, unknown>\n  }));\n\n  // Read device_id from Claude Code's session data for metadata\n  let deviceId = '';\n  try {\n    const { readdirSync, readFileSync } = await import('node:fs');\n    const { join: pj } = await import('node:path');\n    const { homedir: hd } = await import('node:os');\n    // Search session files for userID (Claude Code stores it in session JSONL)\n    const projDir = pj(hd(), '.claude', 'projects');\n    if (readdirSync(projDir).length > 0) {\n      const sessionDirs = readdirSync(projDir).slice(0, 5);\n      for (const sd of sessionDirs) {\n        try {\n          const files = readdirSync(pj(projDir, sd)).filter((f: string) => f.endsWith('.jsonl'));\n          for (const f of files.slice(0, 3)) {\n            const content = readFileSync(pj(projDir, sd, f), 'utf8');\n            const match = content.match(/\"userID\"\\s*:\\s*\"([a-f0-9]{64})\"/);\n            if (match) { deviceId = match[1]; break; }\n          }\n          if (deviceId) break;\n        } catch {}\n      }\n    }\n  } catch {}\n\n  try {\n    // Use beta.messages.create with OAuth + thinking (proven working with Haiku)\n    const response = await (client.beta.messages.create as unknown as (opts: Record<string, unknown>) => Promise<{ usage?: { input_tokens?: number; output_tokens?: number }; content?: AnthropicContentBlock[] }>)({\n      model,\n      max_tokens: 16000,\n      system: systemPrompt,\n      messages: [\n        { role: 'user' as const, content: userContent },\n        ...(historyMessages || [])\n      ],\n      temperature: 1, // Required when thinking is enabled\n      tools: anthropicTools,\n      betas: [\n        'oauth-2025-04-20',              // Required for OAuth auth\n        'interleaved-thinking-2025-05-14', // Think between tool calls\n        'context-management-2025-06-27',   // Preserves thinking across compaction\n        'redact-thinking-2026-02-12',      // Hides thinking from output (saves tokens)\n      ],\n      thinking: { type: 'enabled', budget_tokens: 4096 },\n      ...(deviceId ? {\n        metadata: {\n          user_id: JSON.stringify({\n            device_id: deviceId,\n            account_uuid: '',\n            session_id: sessionHeader\n          })\n        }\n      } : {}),\n    });\n\n    const usage = response.usage || {};\n    const cost = ((usage.input_tokens || 0) * 3 + (usage.output_tokens || 0) * 15) / 1_000_000;\n\n    const content: AnthropicContentBlock[] = response.content || [];\n    const toolUseBlocks = content.filter((b) => b.type === 'tool_use');\n    const textBlocks = content.filter((b) => b.type === 'text');\n    const textResponse = textBlocks.map((b) => b.text).join('\\n');\n\n    if (textResponse) process.stdout.write(textResponse);\n\n    if (toolUseBlocks.length > 0) {\n      const toolCalls = toolUseBlocks.map((b) => ({\n        tool: b.name || '',\n        params: b.input || {}\n      }));\n      return { toolCalls, response: textResponse, cost };\n    }\n\n    return { response: textResponse, status: 'COMPLETE', cost };\n  } catch (err: unknown) {\n    // On auth error, try refreshing token\n    if ((err as Record<string, unknown>)?.status === 401) {\n      const refreshed = await forceRefreshOAuthToken();\n      if (refreshed?.accessToken && refreshed.accessToken !== authToken) {\n        return executeAnthropicSDKTurn(fullTask, tools, refreshed.accessToken, model, systemPrompt, images, historyMessages);\n      }\n    }\n    throw err;\n  }\n}\n\nasync function executeStreamingAnthropicTurn(\n  fullTask: string,\n  tools: ToolDeclaration[],\n  apiKey: string,\n  model: string,\n  systemPrompt: string,\n  stream: boolean,\n  images?: ImageAttachment[],\n  historyMessages?: GeminiContent[] | ChatMessage[],\n  isOAuth?: boolean,\n  abortSignal?: AbortSignal\n): Promise<LLMTurnResult> {\n  // Build user content: text + optional images\n  let userContent: string | Array<Record<string, unknown>> = fullTask;\n  if (images?.length) {\n    const parts: Array<Record<string, unknown>> = [{ type: 'text', text: fullTask }];\n    for (const img of images) {\n      parts.push({\n        type: 'image',\n        source: { type: 'base64', media_type: img.mimeType, data: img.data }\n      });\n    }\n    userContent = parts;\n  }\n\n  const anthropicTools = tools.map(t => ({\n    name: t.name,\n    description: t.description,\n    input_schema: t.parameters\n  }));\n\n  const CLAUDE_OAUTH_BETA_HEADER = [\n    'claude-code-20250219',\n    'oauth-2025-04-20',\n    'adaptive-thinking-2026-01-28',\n    'research-preview-2026-02-01',\n    'interleaved-thinking-2025-05-14',\n    'redact-thinking-2026-02-12',\n    'context-management-2025-06-27',\n  ].join(',');\n\n  // Build body \u2014 OAuth uses CCH signing + billing block; API key uses plain JSON\n  let bodyStr: string;\n  const headers: Record<string, string> = {\n    'Content-Type': 'application/json',\n    'anthropic-version': '2023-06-01'\n  };\n\n  if (isOAuth) {\n    const suffix = computeVersionSuffix(typeof fullTask === 'string' ? fullTask : '');\n    const billingBlock = buildBillingBlock(suffix);\n    const supportsThinking = !model.includes('haiku');\n    const bodyObj: Record<string, unknown> = {\n      model,\n      max_tokens: 8192,\n      ...(supportsThinking ? { thinking: { type: 'adaptive' } } : {}),\n      metadata: { user_id: `user_crewswarm_l3_${Date.now()}` },\n      system: [\n        billingBlock,\n        { type: 'text', text: systemPrompt, cache_control: { type: 'ephemeral' } }\n      ],\n      messages: [\n        { role: 'user', content: userContent },\n        ...(historyMessages || [])\n      ],\n      // temperature must be 1 (or omitted) when adaptive thinking is enabled\n      ...(supportsThinking ? {} : { temperature: 0.3 }),\n      tools: anthropicTools,\n      stream\n    };\n    bodyStr = await signBody(bodyObj);\n    headers['Authorization'] = `Bearer ${apiKey}`;\n    headers['anthropic-beta'] = CLAUDE_OAUTH_BETA_HEADER;\n    headers['anthropic-dangerous-direct-browser-access'] = 'true';\n    headers['x-app'] = 'cli';\n    headers['user-agent'] = 'claude-cli/2.1.87 (external, cli)';\n  } else {\n    const bodyObj: Record<string, unknown> = {\n      model,\n      max_tokens: 8192,\n      system: systemPrompt,\n      messages: [\n        { role: 'user', content: userContent },\n        ...(historyMessages || [])\n      ],\n      temperature: 0.3,\n      tools: anthropicTools,\n      stream\n    };\n    bodyStr = JSON.stringify(bodyObj);\n    headers['x-api-key'] = apiKey;\n  }\n\n  // Combine caller's abort signal with a timeout signal\n  const anthropicTimeoutSignal = AbortSignal.timeout(120000);\n  const anthropicFetchSignal = abortSignal\n    ? AbortSignal.any([abortSignal, anthropicTimeoutSignal])\n    : anthropicTimeoutSignal;\n\n  const apiUrl = isOAuth ? 'https://api.anthropic.com/v1/messages?beta=true' : 'https://api.anthropic.com/v1/messages';\n\n  const res = await fetch(apiUrl, {\n    method: 'POST',\n    headers,\n    signal: anthropicFetchSignal,\n    body: bodyStr\n  });\n\n  if (!res.ok) {\n    // On 401 with OAuth, try refreshing the token and retrying once\n    if (res.status === 401 && isOAuth) {\n      const refreshed = await forceRefreshOAuthToken();\n      if (refreshed?.accessToken && refreshed.accessToken !== apiKey) {\n        return executeStreamingAnthropicTurn(\n          fullTask, tools, refreshed.accessToken, model,\n          systemPrompt, stream, images, historyMessages, true, abortSignal\n        );\n      }\n    }\n    const err = await res.text();\n    throw new Error(`Anthropic API ${res.status}: ${err.slice(0, 300)}`);\n  }\n\n  if (stream && res.body) {\n    let fullText = '';\n    const toolBlocks = new Map<number, { name: string; inputJson: string }>();\n    let totalCost = 0;\n    const sseDebug = process.env.CREW_DEBUG_SSE === '1' || process.env.CREW_DEBUG_SSE === 'true';\n    const sseLog: string[] = [];\n\n    const reader = res.body.getReader();\n    const decoder = new TextDecoder();\n    let buffer = '';\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n\n        buffer += decoder.decode(value, { stream: true });\n        const lines = buffer.split('\\n');\n        buffer = lines.pop() || '';\n\n        for (const line of lines) {\n          if (!line.startsWith('data: ')) continue;\n          const jsonStr = line.slice(6).trim();\n          if (!jsonStr) continue;\n          if (sseDebug) sseLog.push(jsonStr);\n\n          try {\n            const event = JSON.parse(jsonStr);\n\n            if (event.type === 'content_block_start') {\n              if (sseDebug) console.error(`[SSE] block_start idx=${event.index} type=${event.content_block?.type} name=${event.content_block?.name || ''}`);\n              if (event.content_block?.type === 'tool_use') {\n                toolBlocks.set(event.index, {\n                  name: event.content_block.name || '',\n                  // Some responses include full input in content_block_start\n                  inputJson: event.content_block.input && typeof event.content_block.input === 'object' && Object.keys(event.content_block.input).length > 0\n                    ? JSON.stringify(event.content_block.input)\n                    : ''\n                });\n              }\n            }\n\n            if (event.type === 'content_block_delta') {\n              if (event.delta?.type === 'text_delta' && event.delta.text) {\n                process.stdout.write(event.delta.text);\n                fullText += event.delta.text;\n              }\n              if (event.delta?.type === 'input_json_delta') {\n                if (sseDebug) console.error(`[SSE] json_delta idx=${event.index} len=${(event.delta.partial_json || '').length}`);\n                if (event.delta.partial_json) {\n                  const block = toolBlocks.get(event.index);\n                  if (block) {\n                    block.inputJson += event.delta.partial_json;\n                  }\n                }\n              }\n            }\n\n            if (event.type === 'message_delta' && event.usage) {\n              totalCost = (event.usage.input_tokens || 0) * 3 / 1_000_000\n                + (event.usage.output_tokens || 0) * 15 / 1_000_000;\n            }\n          } catch {\n            // Skip malformed events\n          }\n        }\n      }\n    } finally {\n      reader.releaseLock();\n    }\n\n    if (fullText) process.stdout.write('\\n');\n\n    // Dump raw SSE log for debugging\n    if (sseDebug && sseLog.length > 0) {\n      const logPath = `/tmp/crew-sse-log-${Date.now()}.jsonl`;\n      try {\n        const { writeFileSync } = await import('node:fs');\n        writeFileSync(logPath, sseLog.join('\\n') + '\\n');\n        console.error(`[SSE] Raw log saved: ${logPath} (${sseLog.length} events)`);\n      } catch {}\n    }\n\n    // Parse accumulated tool calls\n    const toolCalls: Array<{ tool: string; params: Record<string, unknown> }> = [];\n    for (const [idx, block] of toolBlocks) {\n      if (block.name) {\n        let params: Record<string, unknown> = {};\n        if (sseDebug) console.error(`[SSE] Parsing tool idx=${idx} name=${block.name} inputJsonLen=${block.inputJson.length} preview=${block.inputJson.slice(0, 100)}`);\n        // Parse raw first \u2014 repairJson corrupts code strings containing `: type`\n        try {\n          params = JSON.parse(block.inputJson);\n          if (sseDebug) console.error(`[SSE] Raw parse OK: keys=${Object.keys(params).join(',')}`);\n        } catch (e1) {\n          if (sseDebug) console.error(`[SSE] Raw parse FAIL: ${(e1 as Error).message?.slice(0, 80)}`);\n          try {\n            params = JSON.parse(repairJson(block.inputJson));\n            if (sseDebug) console.error(`[SSE] Repair parse OK: keys=${Object.keys(params).join(',')}`);\n          } catch (e2) {\n            if (sseDebug) console.error(`[SSE] Repair parse FAIL: ${(e2 as Error).message?.slice(0, 80)}`);\n          }\n        }\n        toolCalls.push({ tool: block.name, params });\n      }\n    }\n\n    if (toolCalls.length > 0) return { toolCalls, response: fullText, cost: totalCost };\n    return { response: fullText, status: 'COMPLETE', cost: totalCost };\n  }\n\n  // Non-streaming fallback\n  const data = await res.json() as LLMResponseData;\n  const usage = data?.usage || {};\n  const cost = (usage.input_tokens || 0) * 3 / 1_000_000 + (usage.output_tokens || 0) * 15 / 1_000_000;\n  const content = data?.content || [];\n  const toolUseBlocks = (content as AnthropicContentBlock[]).filter((b) => b.type === 'tool_use');\n  const textBlocks = (content as AnthropicContentBlock[]).filter((b) => b.type === 'text');\n  const textResponse = textBlocks.map((b) => b.text).join('\\n');\n\n  if (toolUseBlocks.length > 0) {\n    const toolCalls = toolUseBlocks.map((b) => ({ tool: b.name || '', params: b.input || {} }));\n    return { toolCalls, response: textResponse, cost };\n  }\n  return { response: textResponse, status: 'COMPLETE', cost };\n}\n\nasync function executeLLMTurn(\n  task: string,\n  tools: ToolDeclaration[],\n  history: TurnResult[],\n  model: string,\n  systemPrompt: string,\n  stream: boolean,\n  images?: ImageAttachment[],\n  abortSignal?: AbortSignal\n): Promise<LLMTurnResult> {\n  const resolved = await resolveProvider(model);\n  if (!resolved) {\n    throw new Error(\n      'No LLM providers available. Use OAuth (free with subscriptions) or set an API key:\\n' +\n      '  OAuth (auto-detected, no config needed):\\n' +\n      '  \u2192 Claude Code login  \u2192 uses Claude Max/Pro subscription\\n' +\n      '  \u2192 Codex CLI login    \u2192 uses ChatGPT Plus/Pro subscription\\n' +\n      '  \u2192 gcloud auth login  \u2192 uses Google account for Gemini\\n' +\n      '  API keys (fallback):\\n' +\n      '  \u2192 GEMINI_API_KEY (free tier \u2014 https://aistudio.google.com/apikey)\\n' +\n      '  \u2192 GROQ_API_KEY   (free \u2014 https://console.groq.com/keys)\\n' +\n      '  \u2192 XAI_API_KEY    ($5/mo free credits \u2014 https://console.x.ai)\\n' +\n      'Or any of: OPENAI_API_KEY, ANTHROPIC_API_KEY, DEEPSEEK_API_KEY, OPENROUTER_API_KEY\\n' +\n      'Run \"crew doctor\" to check your setup.'\n    );\n  }\n\n  const { key, model: effectiveModel, driver, apiUrl, id, isOAuth } = resolved;\n\n  // Show auth method per turn so user knows OAuth vs API key\n  const authBadge = isOAuth ? 'OAuth' : 'API';\n  console.error(`\\x1b[2m[${effectiveModel} ${authBadge}]\\x1b[0m`);\n\n  // Gemini: structured multi-turn with functionCall/functionResponse\n  if (driver === 'gemini') {\n    const historyMsgs = historyToGeminiContents(history, effectiveModel);\n    return executeStreamingGeminiTurn(\n      task,\n      tools,\n      key,\n      effectiveModel,\n      systemPrompt,\n      stream,\n      images,\n      historyMsgs,\n      isOAuth,\n      resolved.projectId,\n      resolved.oauthSource,\n      abortSignal\n    );\n  }\n\n  // Anthropic: structured multi-turn with tool_use/tool_result\n  if (driver === 'anthropic') {\n    const historyMsgs = historyToAnthropicMessages(history);\n    return executeStreamingAnthropicTurn(task, tools, key, effectiveModel, systemPrompt, stream, images, historyMsgs, isOAuth, abortSignal);\n  }\n\n  // OpenAI-compatible: structured multi-turn with tool_calls/tool messages\n  if (driver === 'openai' || driver === 'openrouter') {\n    const historyMsgs = historyToOpenAIMessages(history, effectiveModel);\n    return executeStreamingOpenAITurn(\n      task,\n      tools,\n      apiUrl!,\n      key,\n      effectiveModel,\n      systemPrompt,\n      stream,\n      images,\n      historyMsgs,\n      isOAuth,\n      historyToContext(history),\n      abortSignal\n    );\n  }\n\n  throw new Error(`Unsupported driver: ${driver}`);\n}\n\n// ---------------------------------------------------------------------------\n// JIT Context Discovery \u2014 index files as tools discover them\n// ---------------------------------------------------------------------------\n\nclass JITContextTracker {\n  private discoveredFiles = new Set<string>();\n  private contextCache: string = '';\n\n  /** Hydrate from a prior session's discovered files */\n  static fromPrior(files: string[]): JITContextTracker {\n    const tracker = new JITContextTracker();\n    for (const f of files) tracker.discoveredFiles.add(f);\n    return tracker;\n  }\n\n  /** Serialize discovered files for session persistence */\n  toFileList(): string[] {\n    return Array.from(this.discoveredFiles);\n  }\n\n  /** Track a file that was read/written/grepped during tool execution */\n  trackFile(filePath: string) {\n    if (filePath && !this.discoveredFiles.has(filePath)) {\n      this.discoveredFiles.add(filePath);\n    }\n  }\n\n  /** Extract file paths from tool calls and results */\n  trackFromToolResult(toolName: string, params: Record<string, unknown>, result: { output?: string } | null) {\n    // Track files referenced in tool params\n    for (const key of ['file_path', 'path', 'dir_path']) {\n      if (params[key]) this.trackFile(String(params[key]));\n    }\n\n    // Track files discovered by glob/grep results\n    if ((toolName === 'glob' || toolName === 'grep_search' || toolName === 'grep_search_ripgrep') && result?.output) {\n      const lines = String(result.output).split('\\n');\n      for (const line of lines) {\n        const match = line.match(/^([^\\s:]+\\.[a-zA-Z]+)/);\n        if (match) this.trackFile(match[1]);\n      }\n    }\n\n    // Track files from list_directory\n    if (toolName === 'list_directory' && result?.output) {\n      const lines = String(result.output).split('\\n');\n      const dir = params.dir_path || params.path || '.';\n      for (const line of lines) {\n        const match = line.match(/^[fd]\\s+(.+)/);\n        if (match && match[1].includes('.')) {\n          this.trackFile(`${dir}/${match[1]}`);\n        }\n      }\n    }\n  }\n\n  /** Build enriched context from discovered files for next turn */\n  async buildJITContext(projectDir: string): Promise<string> {\n    if (this.discoveredFiles.size === 0) return '';\n\n    try {\n      const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n\n      // Index only the discovered files/directories\n      const uniqueDirs = new Set<string>();\n      for (const f of this.discoveredFiles) {\n        const parts = f.split('/');\n        if (parts.length > 1) {\n          uniqueDirs.add(parts.slice(0, -1).join('/'));\n        }\n      }\n\n      // If we've discovered specific directories, search them\n      const dirsToIndex = Array.from(uniqueDirs).slice(0, 5);\n      if (dirsToIndex.length === 0) return '';\n\n      const { resolve: resolvePath } = await import('node:path');\n      const paths = dirsToIndex.map(d => resolvePath(projectDir, d));\n\n      const index = await buildCollectionIndex(paths, { includeCode: true });\n      if (index.chunkCount === 0) return '';\n\n      // Search for related patterns based on discovered file names\n      const query = Array.from(this.discoveredFiles).slice(0, 10).join(' ');\n      const results = searchCollection(index, query, 3);\n      if (results.hits.length === 0) return '';\n\n      const newContext = results.hits.map(h =>\n        `--- JIT: ${h.source}:${h.startLine} ---\\n${h.text.slice(0, 400)}`\n      ).join('\\n\\n');\n\n      this.contextCache = newContext;\n      return `\\n\\nJIT-discovered context:\\n${newContext}`;\n    } catch {\n      return '';\n    }\n  }\n\n  get fileCount() { return this.discoveredFiles.size; }\n}\n\n// ---------------------------------------------------------------------------\n// Repo-map context builder\n// ---------------------------------------------------------------------------\n\nasync function buildRepoMapContext(task: string, projectDir: string): Promise<string> {\n  try {\n    // Skip indexing for home directory or root \u2014 too large, will hang\n    const { homedir } = await import('node:os');\n    if (projectDir === homedir() || projectDir === '/') return '';\n\n    const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n    const index = await buildCollectionIndex([projectDir], { includeCode: true });\n    if (index.chunkCount === 0) return '';\n\n    const results = searchCollection(index, task, 5);\n    if (results.hits.length === 0) return '';\n\n    const chunks = results.hits.map(h =>\n      `--- ${h.source}:${h.startLine} (score: ${h.score}) ---\\n${h.text.slice(0, 600)}`\n    );\n    return `\\n\\nRelevant codebase context (${index.fileCount} files indexed, ${index.chunkCount} chunks):\\n${chunks.join('\\n\\n')}`;\n  } catch {\n    return '';\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Auto-retry wrapper\n// ---------------------------------------------------------------------------\n\nconst MAX_RETRIES = 3;\n\ninterface ToolExecResult {\n  output: string;\n  success: boolean;\n  error?: string;\n  handled?: boolean;       // false = worker MUST address this, not ignore it\n  recovery?: string;       // hint for how to fix\n}\n\nasync function executeToolWithRetry(\n  adapter: GeminiToolAdapter,\n  name: string,\n  params: Record<string, unknown>,\n  verbose: boolean\n): Promise<ToolExecResult> {\n  for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {\n    const result = await adapter.executeTool(name, params);\n    if (result.success) {\n      return { output: result.output ?? '', success: true };\n    }\n\n    // Constraint-level blocks are never retryable \u2014 propagate immediately with recovery hint\n    if (result.handled === false && result.recovery) {\n      const msg = result.recovery\n        ? `${result.error}\\n\\n[RECOVERY HINT]: ${result.recovery}`\n        : result.error || 'Tool blocked';\n      return { output: msg, success: false, error: result.error, handled: false, recovery: result.recovery };\n    }\n\n    // If first attempt failed and we have retries left, try with corrections\n    if (attempt < MAX_RETRIES) {\n      if (verbose) {\n        console.log(`  \u27F3 Retry ${attempt}/${MAX_RETRIES - 1} for ${name}: ${(result.error || '').slice(0, 80)}`);\n      }\n\n      // Auto-correct common errors\n      if (result.error?.includes('String not found') && params.old_string) {\n        // Edge case fix: re-read the file to get fresh content before retrying\n        if (params.file_path) {\n          try {\n            const freshRead = await adapter.executeTool('read_file', { file_path: params.file_path });\n            if (freshRead.success && freshRead.output) {\n              // Return the fresh content as error context so the LLM can see it on next turn\n              return {\n                output: `File content has changed. Current content of ${params.file_path}:\\n${freshRead.output.slice(0, 3000)}`,\n                success: false,\n                error: `String not found in ${params.file_path}. File was re-read \u2014 content returned above for correction.`\n              };\n            }\n          } catch { /* fall through to trim retry */ }\n        }\n        // Fallback: try trimming whitespace\n        params.old_string = String(params.old_string || '').trim();\n      } else if (result.error?.includes('No such file') && params.file_path) {\n        // For file ops: try without leading ./\n        params.file_path = String(params.file_path || '').replace(/^\\.\\//, '');\n      } else {\n        // No auto-correction available, don't retry \u2014 propagate handled/recovery\n        return { output: result.output ?? '', success: false, error: result.error, handled: result.handled, recovery: result.recovery };\n      }\n    } else {\n      return { output: result.output ?? '', success: false, error: result.error, handled: result.handled, recovery: result.recovery };\n    }\n  }\n\n  return { output: '', success: false, error: 'Max retries exceeded' };\n}\n\n// ---------------------------------------------------------------------------\n// Main executor\n// ---------------------------------------------------------------------------\n\nexport interface AgenticExecutorResult {\n  success: boolean;\n  output: string;\n  cost: number;\n  turns?: number;\n  toolsUsed?: string[];\n  providerId?: string;\n  modelUsed?: string;\n  filesDiscovered?: number;\n  discoveredFiles?: string[];\n  history?: TurnResult[];\n  stopReason?: string;\n  transcript?: ExecutionTranscript;\n  constraintLevel?: ConstraintLevel;\n}\n\nexport async function runAgenticWorker(\n  task: string,\n  sandbox: Sandbox,\n  options: {\n    systemPrompt?: string;\n    model?: string;\n    maxTurns?: number;\n    projectDir?: string;\n    verbose?: boolean;\n    stream?: boolean;\n    tier?: 'fast' | 'standard' | 'heavy';\n    images?: ImageAttachment[];\n    onToolCall?: (name: string, params: Record<string, unknown>) => void;\n    priorDiscoveredFiles?: string[];\n    constraintLevel?: ConstraintLevel;\n    persona?: string;\n    /** Feature 3: AbortController \u2014 pass a signal to cancel the agent mid-run */\n    abortSignal?: AbortSignal;\n    /** Feature 4: Budget limit in USD \u2014 stop execution when cost exceeds this */\n    maxBudgetUsd?: number;\n    /** Explicit verification commands to run after edits */\n    verificationCommands?: string[];\n  } = {}\n): Promise<AgenticExecutorResult> {\n  // Resolve constraint level: explicit > persona-derived > full (default)\n  const constraintLevel = options.constraintLevel\n    || (options.persona ? constraintLevelForPersona(options.persona) : 'full');\n  const adapter = new GeminiToolAdapter(sandbox, constraintLevel);\n  const rawTools = adapter.getToolDeclarations() as ToolDeclaration[];\n  // Auto-filter tools based on task domains (reduces context, improves accuracy)\n  const toolFilterEnabled = process.env.CREW_TOOL_FILTER !== 'false';\n  const allTools = toolFilterEnabled ? filterToolsForTask(rawTools, task) : rawTools;\n  const model = options.model || process.env.CREW_EXECUTION_MODEL || '';\n  const maxTurns = options.maxTurns ?? 25;\n  const projectDir = options.projectDir || sandbox.getBaseDir() || process.cwd();\n  const verbose = options.verbose ?? Boolean(process.env.CREW_DEBUG);\n  if (verbose && toolFilterEnabled && allTools.length < rawTools.length) {\n    console.log(describeFiltering(task, rawTools.length, allTools.length));\n  }\n\n  // Adaptive weights: load trajectory feedback from autoharness (once per process)\n  if (!(globalThis as Record<string, unknown>).__crewAdaptiveWeightsLoaded) {\n    try {\n      const { extractTrajectoryFeedback } = await import('../../lib/autoharness/index.mjs' as string);\n      const feedback = extractTrajectoryFeedback('default', 'global');\n      if (feedback.length > 0) {\n        RunEngine.loadTrajectoryFeedback(feedback);\n        if (verbose) console.log(`[AgenticExecutor] Loaded ${feedback.length} trajectory feedback entries for adaptive weights`);\n      }\n    } catch {\n      // Non-fatal \u2014 autoharness may not be available\n    }\n    (globalThis as Record<string, unknown>).__crewAdaptiveWeightsLoaded = true;\n  }\n\n  // Feature: Per-session scratchpad \u2014 give each run an isolated temp directory\n  const sessionId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n  const scratchDir = createScratchpad(sessionId);\n  const baseSystemPrompt = options.systemPrompt || L3_SYSTEM_PROMPT;\n  // Append scratchpad instructions + tool-result clearing notice + top-of-mind\n  const topOfMind = await loadTopOfMind(projectDir);\n  const systemPrompt =\n    baseSystemPrompt +\n    getScratchpadInstructions(scratchDir) +\n    TOOL_RESULT_CLEARING_PROMPT +\n    topOfMind;\n  const stream = options.stream ?? !process.env.CREW_NO_STREAM; // Stream by default\n  const jit = options.priorDiscoveredFiles?.length\n    ? JITContextTracker.fromPrior(options.priorDiscoveredFiles)\n    : new JITContextTracker();\n\n  // Resolve provider early to report which model/provider is being used\n  const resolvedProvider = await resolveProvider(model, options.tier);\n\n  // Auth summary \u2014 always show so user knows OAuth vs API key\n  if (resolvedProvider) {\n    const authMethod = resolvedProvider.isOAuth ? 'OAuth' : 'API key';\n    console.error(`\\x1b[2m[auth] ${resolvedProvider.model} via ${authMethod} (${resolvedProvider.id})\\x1b[0m`);\n  }\n\n  if (verbose) {\n    const prov = resolvedProvider ? `${resolvedProvider.id}/${resolvedProvider.model}` : 'none';\n    console.log(`[AgenticExecutor] Provider: ${prov} | Stream: ${stream} | Tools: ${allTools.length} | Constraint: ${constraintLevel}`);\n  }\n\n  // Inject repo-map context\n  let enrichedTask = task;\n  try {\n    const repoContext = await buildRepoMapContext(task, projectDir);\n    if (repoContext) {\n      enrichedTask = `${task}${repoContext}`;\n      if (verbose) {\n        console.log(`[AgenticExecutor] Repo-map: ${repoContext.length} chars injected`);\n      }\n    }\n  } catch {\n    // Non-fatal\n  }\n\n  // Inject past corrections to prevent repeat mistakes\n  try {\n    const correctionsContext = await loadCorrectionsContext(projectDir);\n    if (correctionsContext) {\n      enrichedTask = `${enrichedTask}${correctionsContext}`;\n      if (verbose) {\n        console.log(`[AgenticExecutor] Corrections context injected`);\n      }\n    }\n  } catch {\n    // Non-fatal\n  }\n\n  const taskMode = detectTaskMode(task);\n  enrichedTask = `${enrichedTask}\\n\\n## Execution Strategy\\n${buildTaskModeGuidance(taskMode)}`;\n\n  if (verbose) {\n    console.log(`[AgenticExecutor] ${allTools.length} tools: ${allTools.map(t => t.name).join(', ')}`);\n    console.log(`[AgenticExecutor] task mode: ${taskMode}`);\n  }\n\n  let totalCost = 0;\n  const toolsUsed = new Set<string>();\n  const transcript = new ExecutionTranscript();\n  const verificationCommands = normalizeVerificationCommands(options.verificationCommands ?? extractVerificationCommands(task));\n  const patchCritic = new PatchCritic({ allowedPaths: [] }); // scope enforced by task envelope\n  const structuredHistory = new StructuredHistory();\n\n  const executeTool = async (name: string, params: Record<string, unknown>) => {\n    toolsUsed.add(name);\n\n    // Always fire onToolCall callback (for REPL tool progress display)\n    options.onToolCall?.(name, params);\n\n    if (verbose) {\n      const paramStr = JSON.stringify(params).slice(0, 120);\n      process.stdout.write(`  \uD83D\uDD27 ${name}(${paramStr})...`);\n    }\n\n    const toolStart = Date.now();\n    const result = await executeToolWithRetry(adapter, name, params, verbose);\n    const durationMs = Date.now() - toolStart;\n\n    // Record in transcript (immutable log)\n    transcript.record({\n      ts: toolStart,\n      toolName: name,\n      params,\n      success: result.success,\n      outputPreview: (result.output || result.error || '').slice(0, 200),\n      durationMs,\n      error: result.error,\n      handled: result.handled,\n      recovery: result.recovery\n    });\n\n    // Record in structured history (rich state preservation)\n    const filePath = String(params.file_path || params.path || '');\n    const isReadOnly = ['read_file', 'read_many_files', 'grep_search', 'glob', 'list_directory', 'get_internal_docs'].includes(name);\n    structuredHistory.recordToolExecution({\n      turn: turnCount,\n      tool: name,\n      params,\n      result: result.success ? (result.output || '') : null,\n      error: result.error,\n      durationMs,\n      filesAffected: filePath ? [filePath] : [],\n      readOnly: isReadOnly\n    });\n\n    // Surface failures to RunEngine's failure memory so it can block repeated bad moves.\n    // executeToolWithRetry swallows retries internally \u2014 this ensures the final failure\n    // (after retries exhausted) reaches RunEngine.state.recordFailure().\n    // EXCEPTION: read-before-edit rejections are recoverable guidance, not real failures.\n    // The model should read the file then retry \u2014 don't poison failure memory.\n    const isRecoverableGuard = !result.success && result.error &&\n      (result.error.includes('must read_file') || result.error.includes('read_file before editing'));\n    if (!result.success && result.error && !isRecoverableGuard) {\n      engine.state.recordFailure({\n        turn: turnCount,\n        tool: name,\n        params,\n        error: result.error\n      });\n    }\n\n    // Patch critic: evaluate change quality and inject guidance\n    const criticReport = patchCritic.evaluate(turnCount, name, params, result, result.error, structuredHistory);\n    if (criticReport.guidance && verbose) {\n      console.log(`  [Critic] Score: ${criticReport.score}/100 \u2014 ${criticReport.findings.filter(f => f.severity !== 'info').length} issues`);\n    }\n\n    // Auto-pagination: if read_file result looks truncated, hint for narrower read\n    if (name === 'read_file' && result.success && result.output) {\n      const outputLen = result.output.length;\n      if (outputLen > 8000 && (result.output.includes('... (truncated)') || result.output.includes('content truncated'))) {\n        result.output += '\\n\\n[NOTE: File output was truncated. Use line_start and line_end parameters to read specific sections.]';\n      }\n    }\n\n    // JIT: track discovered files\n    jit.trackFromToolResult(name, params, result);\n\n    if (verbose) {\n      const status = result.success ? '\u2713' : '\u2717';\n      const preview = (result.output || result.error || '').slice(0, 80).replace(/\\n/g, ' ');\n      console.log(` ${status} ${preview}`);\n    }\n    return result;\n  };\n\n  let turnCount = 0;\n\n  const engine = new RunEngine({\n    task,\n    sessionId,\n    maxTurns,\n    maxBudgetUsd: options.maxBudgetUsd,\n    abortSignal: options.abortSignal,\n    tools: allTools,\n    model,\n    taskMode,\n    verificationCommands,\n    onProgress: verbose\n      ? (turn, action) => {\n          console.log(`  [Turn ${turn}] ${action}`);\n        }\n      : undefined\n  });\n\n  const result = await engine.execute(\n    async (prompt, tools, history, abortSignal) => {\n      turnCount++;\n\n      // Inject structured history summary + patch critic guidance\n      let taskWithJIT = enrichedTask;\n      const historySummary = structuredHistory.buildExecutionSummary();\n      if (historySummary && turnCount > 1) {\n        taskWithJIT = `${taskWithJIT}\\n\\n${historySummary}`;\n      }\n\n      // JIT: inject discovered context every 3 turns\n      let historyForTurn = history;\n      if (turnCount > 1 && turnCount % 3 === 0 && jit.fileCount > 0) {\n        try {\n          const jitContext = await jit.buildJITContext(projectDir);\n          if (jitContext) {\n            taskWithJIT = `${enrichedTask}${jitContext}`;\n            if (verbose) {\n              console.log(`  [JIT] Injected context from ${jit.fileCount} discovered files`);\n            }\n          }\n        } catch {\n          // Non-fatal\n        }\n      }\n\n      // Token compaction: check if history is getting too large for context window\n      if (turnCount > 4 && history.length > 8) {\n        const historyText = history.map(h => JSON.stringify(h)).join('\\n');\n        const budget = calculateTokenBudget(\n          [{ content: systemPrompt }, { content: taskWithJIT }, { content: historyText }],\n          model\n        );\n        if (budget.shouldCompact) {\n          const { firstN, lastN } = adaptiveCompressionRatio(history.length, 1 - budget.remainingPct);\n          // Compact history by keeping first N + last M tool results and summarizing the middle.\n          const historyMsgs: CompactedMessage[] = history.map(h => ({\n            role: 'assistant',\n            content: `[Turn ${h.turn}] ${h.tool}(${JSON.stringify(h.params).slice(0, 100)}) \u2192 ${typeof h.result === 'string' ? h.result.slice(0, 200) : JSON.stringify(h.result || h.error || '').slice(0, 200)}`\n          }));\n          const compacted = await compactConversation(historyMsgs, {\n            keepFirst: firstN,\n            keepLast: lastN,\n            targetTokens: 1000\n          });\n          const summary = compacted.find(msg => msg.isCompacted)?.content;\n          if (summary) {\n            taskWithJIT = `${taskWithJIT}\\n\\n${summary}`;\n            const keepHead = history.slice(0, Math.min(firstN, history.length));\n            const tailStart = Math.max(keepHead.length, history.length - lastN);\n            historyForTurn = [...keepHead, ...history.slice(tailStart)];\n          }\n          if (verbose && compacted.length < historyMsgs.length) {\n            console.log(`  [Compaction] ${historyMsgs.length} \u2192 ${compacted.length} messages (${Math.round(budget.remainingPct * 100)}% context remaining)`);\n          }\n        }\n      }\n\n      // Only inject images on the first turn to avoid context bloat\n      const turnImages = turnCount === 1 ? options.images : undefined;\n      const turnTools = compactToolDeclarations(allTools, turnCount, model);\n      const turnResult = await executeLLMTurn(taskWithJIT, turnTools, historyForTurn, model, systemPrompt, stream, turnImages, abortSignal);\n      totalCost += turnResult.cost || 0;\n      return {\n        toolCalls: turnResult.toolCalls,\n        response: turnResult.response,\n        status: turnResult.status,\n        costUsd: turnResult.cost  // Feature 4: surface cost per turn to autonomous loop\n      };\n    },\n    async (name, params) => {\n      const result = await executeTool(name, params);\n      // RunEngine expects executeTool to throw on failure so it can\n      // record failures and block repeated bad moves.\n      // Only throw for write/shell failures \u2014 read-only failures (ENOENT etc.)\n      // are normal exploration and shouldn't count as real failures.\n      const READ_ONLY = new Set(['read_file', 'read_many_files', 'list_directory', 'glob', 'grep_search', 'grep', 'list', 'lsp', 'get_internal_docs', 'tool_search']);\n      if (!result.success && result.error && !READ_ONLY.has(name)) {\n        const err = new Error(result.error);\n        (err as Error & { toolResult: unknown }).toolResult = result;\n        throw err;\n      }\n      return result;\n    }\n  );\n\n  // Feature: Clean up the per-session scratchpad directory\n  cleanupScratchpad(sessionId);\n\n  // Freeze transcript \u2014 immutable after execution completes\n  transcript.freeze();\n\n  const rawOutput = result.output ?? result.history?.map(h => {\n    if (!h.result) return '';\n    if (typeof h.result === 'string') return h.result;\n    const toolResult = h.result as { output?: string; error?: string };\n    return toolResult.output || toolResult.error || JSON.stringify(h.result);\n  }).filter(Boolean).join('\\n') ?? '';\n\n  const runSnapshot = result.runState.snapshot();\n\n  const lastPhase = runSnapshot.phases.length > 0\n    ? runSnapshot.phases[runSnapshot.phases.length - 1]\n    : undefined;\n\n  return {\n    success: result.success ?? false,\n    output: stripThinkActObserve(rawOutput),\n    cost: result.costUsd || totalCost,\n    turns: result.turns,\n    toolsUsed: Array.from(toolsUsed),\n    providerId: resolvedProvider?.id,\n    modelUsed: resolvedProvider?.model,\n    filesDiscovered: jit.fileCount,\n    discoveredFiles: jit.toFileList(),\n    history: result.history,\n    stopReason: result.success\n      ? undefined\n      : runSnapshot.abortReason || (lastPhase?.notes.length ? lastPhase.notes[lastPhase.notes.length - 1] : undefined) || runSnapshot.phase,\n    transcript,\n    constraintLevel\n  };\n}\n\nfunction normalizeVerificationCommands(commands: string[]): string[] {\n  return [...new Set(commands.map(cmd => cmd.trim()).filter(Boolean))];\n}\n\nfunction extractVerificationCommands(task: string): string[] {\n  const commands = new Set<string>();\n  const lines = task.split('\\n');\n  for (const line of lines) {\n    const trimmed = line.trim();\n    const runMatch = trimmed.match(/^(?:[-*]\\s*)?(?:run|execute)\\s+(.+)$/i);\n    if (runMatch?.[1]) {\n      commands.add(runMatch[1].trim());\n      continue;\n    }\n    const commandMatch = trimmed.match(/`([^`]+)`/g);\n    if (commandMatch) {\n      for (const token of commandMatch) {\n        const command = token.slice(1, -1).trim();\n        if (looksLikeCommand(command)) commands.add(command);\n      }\n    }\n  }\n  return [...commands];\n}\n\nfunction looksLikeCommand(value: string): boolean {\n  if (!value) return false;\n  return /^(npm|pnpm|yarn|bun|node|pytest|jest|vitest|cargo|go|make|\\.\\/|bash|sh)\\b/.test(value);\n}\n\n/**\n * Strip THINK/ACT/OBSERVE reasoning scaffold from LLM output.\n * Handles both **THINK** (bold) and THINK: (plain) formats.\n */\nfunction stripThinkActObserve(text: string): string {\n  if (!text) return text;\n  // Bold format: **THINK** ... **ACT** ... **OBSERVE** ...\n  let out = text\n    .replace(/\\*\\*THINK\\*\\*[^]*?(?=\\*\\*ACT\\*\\*|\\*\\*OBSERVE\\*\\*|^---$)/gim, '')\n    .replace(/\\*\\*ACT\\*\\*[^]*?(?=\\*\\*OBSERVE\\*\\*|\\*\\*THINK\\*\\*|^---$)/gim, '')\n    .replace(/\\*\\*OBSERVE\\*\\*[^]*?(?=\\*\\*THINK\\*\\*|\\*\\*ACT\\*\\*|^---$)/gim, '');\n  // Plain format: THINK: ... ACT: ... OBSERVE: ... followed by ---\n  out = out.replace(/^THINK:.*$/gim, '')\n    .replace(/^ACT:.*$/gim, '')\n    .replace(/^OBSERVE:.*$/gim, '');\n  // Remove --- separator line\n  out = out.replace(/^---\\s*$/gm, '');\n  return out.trim();\n}\n", "/**\n * Prompt Registry - Versioned, immutable prompt templates with controlled overlays\n */\n\nexport interface PromptTemplate {\n  id: string;\n  version: string;\n  role: string;\n  basePrompt: string;\n  allowedOverlays: string[];\n  capabilities: string[];\n  riskLevel: 'low' | 'medium' | 'high';\n}\n\nexport interface PersonaProfile {\n  id: string;\n  role: string;\n  templateId: string;\n  capabilities: string[];\n  riskLevel: 'low' | 'medium' | 'high';\n}\n\nexport interface PromptOverlay {\n  type: 'task' | 'safety' | 'context' | 'constraints';\n  content: string;\n  priority: number;\n}\n\nexport interface ComposedPrompt {\n  templateId: string;\n  templateVersion: string;\n  finalPrompt: string;\n  overlays: PromptOverlay[];\n  composedAt: string;\n  traceId: string;\n}\n\n/**\n * Immutable base prompts for each tier and role\n */\nexport const PROMPT_TEMPLATES: Record<string, PromptTemplate> = {\n  // Tier 1: Router\n  'router-v1': {\n    id: 'router-v1',\n    version: '1.0.0',\n    role: 'Router (Tier 1)',\n    basePrompt: `You are an intelligent task router for crew-cli.\n\nAnalyze the user's request and decide: CHAT, CODE, or DISPATCH.\n\n- CHAT: Simple questions, greetings, status checks\n- CODE: Writing, editing, or building code\n- DISPATCH: Complex multi-step tasks requiring specialists\n\nReturn ONLY valid JSON:\n{\"decision\":\"CHAT|CODE|DISPATCH\",\"agent\":\"crew-xxx if needed\",\"task\":\"reformulated\",\"response\":\"if CHAT\"}`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['routing', 'classification'],\n    riskLevel: 'low'\n  },\n\n  // Tier 2: Local Executor\n  'executor-code-v1': {\n    id: 'executor-code',\n    version: '1.0.0',\n    role: 'Code Executor (Tier 2)',\n    basePrompt: `You are a skilled AI engineer executing coding tasks.\n\n## Standards\n- Clean, readable code. Small functions, clear names, no dead code.\n- Error handling everywhere: try/catch async ops, validate inputs, guard nulls before property access.\n- ES modules (import/export), async/await, no callbacks.\n- Match existing code patterns, naming conventions, and structure in the project.\n\n## File Writing Protocol\nUse @@WRITE_FILE to create or modify files:\n\n@@WRITE_FILE path/to/file.tsx\n// file contents here\n@@END_FILE\n\n- Always use absolute or relative paths\n- Include all file content (not diffs or snippets)\n- Multiple files: separate @@WRITE_FILE blocks\n- NEVER use markdown code blocks for files that should be written to disk\n\n## Workflow\n- Read existing files to understand context before modifying\n- Write surgical edits \u2014 only change what the task asks\n- Use @@WRITE_FILE for all file changes\n- Confirm changes by summarizing what was modified\n\n## Before Completing\n- Check: unclosed brackets, missing imports, mismatched braces\n- Mental trace: happy path + one error path\n- Verify logic matches function name and intent\n\nAlways use @@WRITE_FILE for file operations. Be concise and actionable.`,\n    allowedOverlays: ['task', 'context', 'safety', 'constraints'],\n    capabilities: ['code-generation', 'refactoring', 'documentation', 'debugging'],\n    riskLevel: 'medium'\n  },\n\n  'executor-chat-v1': {\n    id: 'executor-chat',\n    version: '1.0.0',\n    role: 'Conversational Assistant (Tier 2)',\n    basePrompt: `You are a helpful AI assistant for technical questions.\n\nProvide clear, accurate, and concise answers. Focus on:\n- Technical accuracy\n- Practical examples\n- Best practices\n- Security considerations\n\nBe professional and helpful.`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['conversation', 'explanation', 'guidance'],\n    riskLevel: 'low'\n  },\n\n  // Tier 2A: Decomposer (Planner-of-Planners)\n  'decomposer-v1': {\n    id: 'decomposer',\n    version: '1.0.0',\n    role: 'Task Decomposer (Tier 2A - Work Graph Generator)',\n    basePrompt: `You are L2A - the Work Graph Decomposition specialist.\n\nYour input: Planning artifacts (PDD, ROADMAP, ARCH, SCAFFOLD, CONTRACT-TESTS, DOD, GOLDEN-BENCHMARKS)\nYour output: Executable work graph with dependencies\n\n## Critical Rules\n\n### 1. Every Work Unit MUST Reference Source Artifacts\nEach unit's \\`sourceRefs\\` field MUST point to at least one of:\n- PDD.md#section (requirements, success criteria, file structure)\n- ROADMAP.md#milestone (phases, tasks)\n- ARCH.md#decision (technology choices, patterns)\n- SCAFFOLD.md#structure (bootstrap requirements)\n- CONTRACT-TESTS.md#case (test specifications)\n- DOD.md#checklist (completion criteria)\n- GOLDEN-BENCHMARKS.md#suite (performance targets)\n\nExample: \\`\"sourceRefs\": [\"PDD.md#requirements\", \"ARCH.md#module-structure\", \"CONTRACT-TESTS.md#test-1\"]\\`\n\n### 2. Persona Assignment Strategy\nMatch work unit to the RIGHT specialist:\n\n**Code Generation:**\n- \\`executor-code\\` - General full-stack coding, scaffolding\n- \\`crew-coder\\` - Complex multi-file features\n- \\`crew-coder-front\\` - React/Vue/UI components\n- \\`crew-coder-back\\` - API endpoints, services, databases\n- \\`crew-frontend\\` - CSS/styling/animations\n\n**Quality Assurance:**\n- \\`specialist-qa\\` - Test generation, contract testing, DOD validation\n- \\`crew-qa\\` - Full audits, security + functionality\n\n**Architecture:**\n- \\`specialist-pm\\` - Planning artifacts only (you already used this!)\n- \\`crew-architect\\` - System design, infrastructure\n\n**Specialized:**\n- \\`crew-security\\` - Security audits (OWASP)\n- \\`crew-github\\` - Git operations, PRs\n- \\`crew-copywriter\\` - Documentation\n\n### 3. Dependency Graph Rules\n- Scaffold ALWAYS comes first (unit: scaffold-bootstrap)\n- Contract tests generated BEFORE implementation (unit: contract-tests-from-pdd)\n- All implementation depends on: scaffold-bootstrap AND contract-tests-from-pdd\n- DOD gate runs AFTER all implementation (unit: gate-definition-of-done)\n- Benchmark gate runs AFTER DOD (unit: gate-golden-benchmark-suite)\n\n### 4. Complexity Estimation\n- **low**: Single file, <50 lines, no external deps (e.g., create error class)\n- **medium**: 2-3 files, 50-200 lines, basic logic (e.g., service with tests)\n- **high**: 4+ files, >200 lines, complex integration (e.g., full auth system)\n\n### 5. Task Granularity\nEach unit should be:\n- Completable in 1-3 minutes of LLM work\n- Independently testable\n- One clear deliverable\n\nToo big: \"Build user management system\"\nJust right: \"Create /src/service/UserService.ts with register() method per ARCH.md patterns\"\n\n## Output Format (CRITICAL - READ TWICE)\n\nReturn ONLY valid JSON (no markdown, no code fences, no preamble):\n\n{\n  \"units\": [\n    {\n      \"id\": \"unique-kebab-case-id\",\n      \"description\": \"IMPERATIVE: Create /exact/file/path.ts with X per ARCH.md patterns\",\n      \"requiredPersona\": \"executor-code|crew-coder|crew-coder-front|crew-coder-back|specialist-qa|crew-qa|etc\",\n      \"dependencies\": [\"other-unit-id\"],\n      \"estimatedComplexity\": \"low|medium|high\",\n      \"requiredCapabilities\": [\"code-generation\", \"testing\", etc],\n      \"sourceRefs\": [\"PDD.md#section\", \"ARCH.md#decision\", \"CONTRACT-TESTS.md#case\"]\n    }\n  ],\n  \"totalComplexity\": 1-10,\n  \"requiredPersonas\": [\"list\", \"of\", \"personas\"],\n  \"estimatedCost\": 0.001\n}\n\n## JSON Rules (CRITICAL)\n1. NO markdown code fences (\\`\\`\\`json)\n2. Start response with { and end with }\n3. Return raw JSON only\n4. All strings properly escaped\n\n## Description Format Examples\n\n\u2705 GOOD:\n- \"Create /src/errors/AppError.ts custom error class per ARCH.md error strategy\"\n- \"Create /src/utils/Logger.ts with JSON structured logging per ARCH.md logging pattern\"\n- \"Update /src/api.ts to use UserService per ARCH.md integration points\"\n- \"Generate unit tests in /test/UserService.test.ts per CONTRACT-TESTS.md cases TEST-1, TEST-2, TEST-3\"\n\n\u274C BAD:\n- \"Create error handling\" (no file path)\n- \"Add logging\" (vague)\n- \"Improve code quality\" (not imperative)\n- \"Refactor services\" (no acceptance criteria)\n\n## Anti-Patterns (NEVER DO THIS)\n\u274C Units without sourceRefs (every unit MUST reference artifacts)\n\u274C Vague descriptions (\"improve\", \"enhance\", \"refactor\")\n\u274C Missing file paths\n\u274C Wrong persona assignments (e.g., crew-qa writing code)\n\u274C Circular dependencies (unit A depends on B, B depends on A)\n\u274C Implementation before scaffold\n\u274C Implementation before contract tests\n\n## Success Criteria for Your Output\n\u2705 Every unit has 1+ sourceRefs\n\u2705 Every description has exact file path\n\u2705 Dependency graph is acyclic\n\u2705 Scaffold \u2192 Contract Tests \u2192 Implementation \u2192 DOD \u2192 Benchmarks\n\u2705 Persona matches capability (coders code, QA tests)\n\u2705 Total complexity reflects actual work (5-10 units = 3-7 complexity)\n\nYou are L2A. Decompose with SURGICAL PRECISION.`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['decomposition', 'planning', 'dependency-analysis', 'work-graph-generation'],\n    riskLevel: 'low'\n  },\n\n  // Tier 2B: Policy/QA Planner\n  'policy-validator-v1': {\n    id: 'policy-validator',\n    version: '1.0.0',\n    role: 'Policy Validator (Tier 2B - Risk & Cost Gate)',\n    basePrompt: `You are L2B - the Policy & Risk Validation gate.\n\nYour input: Work graph from L2A decomposer\nYour output: Risk assessment + approval decision + fallback strategy\n\n## Validation Domains\n\n### 1. Security Risks (CRITICAL)\nCheck for:\n- File system access patterns (reading/writing sensitive files)\n- Command execution (shell commands, npm scripts)\n- Network calls (API endpoints, external services)\n- Credential handling (API keys, tokens, passwords)\n- User input processing (injection risks)\n\n**Risk Levels:**\n- \\`critical\\`: Writes to system files, executes arbitrary commands\n- \\`high\\`: Reads sensitive data, network calls without validation\n- \\`medium\\`: File operations in project scope\n- \\`low\\`: Read-only, no external access\n\n### 2. Resource Costs\nEstimate:\n- Token usage (LLM calls \u00D7 average tokens per call)\n- API costs (provider rates \u00D7 estimated tokens)\n- Time (serial vs parallel execution)\n- Storage (artifact files, cache)\n\n**Cost Thresholds:**\n- >$0.50 per task = \\`high\\` risk, suggest optimization\n- $0.10-$0.50 = \\`medium\\` risk, acceptable\n- <$0.10 = \\`low\\` risk\n\n**Calculation:**\n- Simple code generation: ~2000 tokens = $0.01\n- Complex reasoning: ~8000 tokens = $0.04\n- Planning artifacts: ~10000 tokens = $0.05\n- QA validation: ~3000 tokens = $0.015\n\n### 3. Capability Requirements\nValidate each work unit's \\`requiredCapabilities\\` against persona matrix:\n\n**Available Capabilities:**\n- \\`executor-code\\`: code-generation, refactoring, debugging, file-write, scaffolding\n- \\`specialist-qa\\`: testing, auditing, validation, contract-testing, benchmarking\n- \\`crew-security\\`: security-review, risk-assessment, policy-enforcement\n- \\`crew-coder-front\\`: frontend, ui, ux, component-design\n- \\`crew-coder-back\\`: backend, api-design, data-modeling\n\n**Validation:**\n- Check: Does assigned persona have ALL required capabilities?\n- If NOT: Add to \\`concerns\\` and suggest persona swap in \\`recommendations\\`\n\n### 4. Dependency Validation\nCheck graph for:\n- Circular dependencies (A \u2192 B \u2192 A)\n- Missing dependencies (unit references file created by uncompleted unit)\n- Orphaned units (no path from root to unit)\n- Excessive fan-out (one unit blocks >5 units)\n\n### 5. Fallback Strategy\nFor tasks with \\`medium\\` or \\`high\\` risk, define:\n- What happens if a unit fails?\n- Can execution continue?\n- Is there a safe rollback?\n- Which units are optional vs critical?\n\nExample: \"If UserService creation fails, skip dependent units and retry with simpler implementation using inline functions instead of class-based service.\"\n\n## Output Format (CRITICAL - READ TWICE)\n\nReturn ONLY valid JSON (no markdown, no code fences, no preamble):\n\n{\n  \"approved\": true|false,\n  \"riskLevel\": \"low|medium|high|critical\",\n  \"concerns\": [\n    \"Detailed concern with specific unit IDs\",\n    \"Another concern\"\n  ],\n  \"recommendations\": [\n    \"Actionable recommendation\",\n    \"Another recommendation\"\n  ],\n  \"fallbackStrategy\": \"Detailed strategy if execution fails\",\n  \"estimatedCost\": 0.15\n}\n\n## JSON Rules (CRITICAL)\n1. NO markdown code fences (\\`\\`\\`json)\n2. Start response with { and end with }\n3. Return raw JSON only\n4. All strings properly escaped\n\n## Approval Decision Matrix\n\n| Risk Level | Cost | Concerns | Decision |\n|-----------|------|----------|----------|\n| low | <$0.10 | 0-1 | \\`approved: true\\` |\n| medium | $0.10-$0.50 | 2-3 | \\`approved: true\\` (with recommendations) |\n| high | $0.50-$1.00 | 4+ | \\`approved: false\\` (unless user override) |\n| critical | any | security risk | \\`approved: false\\` |\n\n## Example Validation Outputs\n\n### Example 1: Low Risk (Approved)\n\\`\\`\\`json\n{\n  \"approved\": true,\n  \"riskLevel\": \"low\",\n  \"concerns\": [],\n  \"recommendations\": [\n    \"Consider caching L2A decomposer results for similar tasks\"\n  ],\n  \"fallbackStrategy\": \"If implementation fails, scaffold + contract tests already provide testable foundation\",\n  \"estimatedCost\": 0.08\n}\n\\`\\`\\`\n\n### Example 2: Medium Risk (Approved with Concerns)\n\\`\\`\\`json\n{\n  \"approved\": true,\n  \"riskLevel\": \"medium\",\n  \"concerns\": [\n    \"Unit 'feature-3' has high estimated complexity with >5 dependencies\",\n    \"Total cost $0.45 approaches threshold - consider splitting into 2 phases\"\n  ],\n  \"recommendations\": [\n    \"Split unit 'feature-3' into 2 smaller units to reduce blast radius\",\n    \"Run scaffold + contract-tests first, then pause for user review before implementation\"\n  ],\n  \"fallbackStrategy\": \"If high-complexity units fail, fall back to manual implementation guided by planning artifacts\",\n  \"estimatedCost\": 0.45\n}\n\\`\\`\\`\n\n### Example 3: High Risk (Rejected)\n\\`\\`\\`json\n{\n  \"approved\": false,\n  \"riskLevel\": \"critical\",\n  \"concerns\": [\n    \"Unit 'deploy-to-prod' executes shell commands with user input (command injection risk)\",\n    \"No input validation on file paths in unit 'migrate-db'\",\n    \"Estimated cost $1.20 exceeds $0.50 threshold by 140%\"\n  ],\n  \"recommendations\": [\n    \"Add input sanitization to 'deploy-to-prod' unit\",\n    \"Use parameterized queries in 'migrate-db' unit\",\n    \"Reduce scope to MVP only (remove units 8-12) to bring cost to $0.35\"\n  ],\n  \"fallbackStrategy\": \"Do NOT proceed. Refine task requirements and re-plan with security constraints\",\n  \"estimatedCost\": 1.20\n}\n\\`\\`\\`\n\n## Anti-Patterns (NEVER DO THIS)\n\u274C Auto-approving without validating capabilities\n\u274C Ignoring security risks in shell commands\n\u274C Not estimating costs\n\u274C Generic fallback like \"retry\" (be specific!)\n\u274C Empty concerns array when risk is medium/high\n\n## Success Criteria for Your Output\n\u2705 Risk level matches concerns count and severity\n\u2705 Cost estimate is calculated (not guessed)\n\u2705 Fallback strategy is actionable\n\u2705 Recommendations are concrete (not vague)\n\u2705 Approval decision follows matrix\n\u2705 Security risks trigger critical risk level\n\nYou are L2B. Guard the gates. Be ruthless about risk.`,\n    allowedOverlays: ['safety', 'constraints'],\n    capabilities: ['validation', 'risk-assessment', 'policy-enforcement', 'cost-estimation', 'security-review'],\n    riskLevel: 'high'\n  },\n\n  // Tier 3: Gateway Specialists\n  'specialist-qa-v1': {\n    id: 'specialist-qa',\n    version: '1.0.0',\n    role: 'QA Specialist (Tier 3)',\n    basePrompt: `You are a quality assurance specialist. Every report is backed by evidence.\n\n## Test Strategy\n- Functionality: happy path + 3 edge cases minimum\n- Input validation: empty arrays, null values, missing properties, concurrent access\n- Error handling: all async ops in try/catch? Errors propagated correctly?\n- Security: SQL injection, XSS, hardcoded secrets, auth bypass (OWASP Top 10)\n- Performance: N+1 queries, unbounded loops, memory leaks, missing pagination\n- Correctness: does logic match function name and acceptance criteria?\n\n## Output Format\n### CRITICAL\n- Line N: [issue] \u2192 Fix: [exact code change]\n### HIGH / MEDIUM / LOW\n- Line N: [issue]\n### Verdict\nPASS / PASS WITH WARNINGS / FAIL (CRITICAL issues = automatic FAIL)\n\nNever say \"looks good\" without citing specific checks performed.\nFormat findings in markdown with code blocks for suggested fixes.`,\n    allowedOverlays: ['task', 'context', 'safety', 'constraints'],\n    capabilities: ['testing', 'auditing', 'validation', 'security-review'],\n    riskLevel: 'medium'\n  },\n\n  'specialist-pm-v1': {\n    id: 'specialist-pm',\n    version: '1.0.0',\n    role: 'Project Manager (Tier 3 / L2 Planning Artifacts)',\n    basePrompt: `You are an elite technical project manager and system architect.\n\nYour job: Generate 7 canonical planning artifacts that will guide ALL downstream workers.\n\n## CRITICAL: You are in L2 PLANNING PHASE\nThis is NOT implementation. You are creating the SOURCE OF TRUTH that L3 workers will execute from.\n\n## Artifact Requirements\n\n### 1. PDD.md (Product Design Doc)\n**Purpose:** Define WHAT and WHY before HOW\n- Overview & Goals (2-3 sentences max - be surgical)\n- User stories / Requirements (numbered list, concrete)\n- Success criteria (measurable - \"user can X\", \"system does Y in <Zms\")\n- Technical constraints (existing tech stack, must-use libraries, integration points)\n- File structure (EXACT files that will be created - with paths)\n- Non-goals (explicitly out of scope)\n\n**Format:**\n\\`\\`\\`markdown\n# PDD: [Feature Name]\n\n## Goal\n[One sentence]\n\n## Requirements\n1. [Concrete, testable requirement]\n2. [...]\n\n## Success Criteria\n- AC-1: [Given X, when Y, then Z]\n- AC-2: [...]\n\n## File Structure\n- /src/service/UserService.ts - business logic\n- /src/errors/AppError.ts - custom error class\n- /src/utils/Logger.ts - logging utility\n- /test/UserService.test.ts - unit tests\n\n## Technical Constraints\n- Must use TypeScript strict mode\n- Must integrate with existing Express app at /src/api.ts\n- Must use bcrypt for password hashing\n\\`\\`\\`\n\n### 2. ROADMAP.md\n**Purpose:** Sequential delivery milestones with dependencies\n- Break into phases (MVP, Enhancement, Polish)\n- Each task: IMPERATIVE verb + file path + acceptance criteria\n- Show dependencies (task B needs task A complete)\n- Estimate effort (S/M/L complexity)\n\n**Format:**\n\\`\\`\\`markdown\n# ROADMAP\n\n## Phase 1: Core Infrastructure\n- [ ] **SCAFFOLD-1**: Bootstrap project structure (package.json, tsconfig.json, build scripts) | Complexity: S | Dependencies: none\n- [ ] **CORE-1**: Create /src/errors/AppError.ts custom error class | Complexity: S | Dependencies: SCAFFOLD-1\n- [ ] **CORE-2**: Create /src/utils/Logger.ts with file + console output | Complexity: M | Dependencies: SCAFFOLD-1\n\n## Phase 2: Business Logic\n- [ ] **FEATURE-1**: Create /src/service/UserService.ts with registration logic | Complexity: L | Dependencies: CORE-1, CORE-2\n- [ ] **FEATURE-2**: Update /src/api.ts to use UserService | Complexity: M | Dependencies: FEATURE-1\n\n## Phase 3: Quality Gates\n- [ ] **TEST-1**: Create /test/UserService.test.ts unit tests | Complexity: M | Dependencies: FEATURE-1\n- [ ] **QA-1**: Run contract tests against acceptance criteria | Complexity: S | Dependencies: FEATURE-2, TEST-1\n\\`\\`\\`\n\n### 3. ARCH.md (Architecture)\n**Purpose:** KEY DECISIONS that prevent worker confusion\n- Technology decisions (e.g., \"VS Code Extension API, NOT Chrome Extension\")\n- Module structure (what goes where and why)\n- Integration points (how pieces connect)\n- Shared patterns (naming conventions, API format, error handling style)\n- Data flow (request \u2192 controller \u2192 service \u2192 DB)\n\n**Format:**\n\\`\\`\\`markdown\n# ARCH: System Architecture\n\n## Key Decisions\n1. **Runtime:** Node.js native modules only (no external HTTP libs)\n2. **Error Strategy:** All service methods throw AppError with statusCode\n3. **Logging:** JSON structured logs via Logger.ts (dev: console, prod: file)\n4. **Testing:** Jest with @types/jest, test files colocated in /test/\n\n## Module Structure\n/src/\n  service/     - Business logic (UserService, AuthService)\n  errors/      - Custom error classes\n  utils/       - Shared utilities (Logger, validators)\n  api.ts       - Express app entry point\n\n## Integration Points\n- UserService \u2192 Logger (logs all operations)\n- UserService \u2192 AppError (throws on validation failures)\n- api.ts \u2192 UserService (controller calls service methods)\n\n## Patterns\n- Service methods: \\`async register(data: RegisterInput): Promise<User>\\`\n- Error responses: \\`{ error: string, code: string, statusCode: number }\\`\n- Logging: \\`logger.info('User registered', { userId, email })\\`\n\\`\\`\\`\n\n### 4. SCAFFOLD.md\n**Purpose:** Minimal bootstrap that MUST exist before implementation\n- Required starter files (package.json, tsconfig.json, build scripts)\n- Mandatory config (linter, formatter, test runner)\n- Smoke test commands (build, lint, test must pass)\n- Bootstrap code/contracts per module (interfaces, base classes)\n\n**Format:**\n\\`\\`\\`markdown\n# SCAFFOLD: Bootstrap Requirements\n\n## Required Files (MUST be created first)\n1. package.json - dependencies: express, bcrypt, @types/node, @types/express, jest, typescript\n2. tsconfig.json - strict mode, ES2022, outDir: dist\n3. .eslintrc.json - standard TypeScript rules\n4. /src/api.ts - Express app scaffold (3 lines: import express, create app, export app)\n\n## Smoke Commands (MUST pass before implementation)\n- \\`npm run build\\` \u2192 no errors\n- \\`npm run lint\\` \u2192 no errors\n- \\`npm test\\` \u2192 0 tests (but runner works)\n\n## Bootstrap Contracts\n- /src/errors/AppError.ts \u2192 interface: \\`class AppError extends Error { statusCode: number; code: string }\\`\n- /src/utils/Logger.ts \u2192 interface: \\`class Logger { info(msg, meta), error(msg, meta) }\\`\n\\`\\`\\`\n\n### 5. CONTRACT-TESTS.md\n**Purpose:** Generate tests DIRECTLY from PDD acceptance criteria\n- Map each PDD success criterion to a test case\n- Given/When/Then format\n- Include test ID and AC ID mapping\n\n**Format:**\n\\`\\`\\`markdown\n# CONTRACT TESTS\n\n## Test Suite: User Registration\n\n### TEST-1 (maps to AC-1)\n**Given:** Valid user data (email, password)\n**When:** UserService.register() is called\n**Then:** Returns user object with hashed password, logs event\n\n### TEST-2 (maps to AC-2)\n**Given:** Duplicate email\n**When:** UserService.register() is called\n**Then:** Throws AppError with statusCode 400, code 'DUPLICATE_EMAIL'\n\n### TEST-3 (maps to AC-3)\n**Given:** Missing required field\n**When:** UserService.register() is called\n**Then:** Throws AppError with statusCode 400, code 'VALIDATION_ERROR'\n\\`\\`\\`\n\n### 6. DOD.md (Definition of Done)\n**Purpose:** Completion checklist for the entire feature\n- Build passes\n- Tests pass (with coverage target)\n- QA approved\n- Security check passed\n- Documentation updated\n\n**Format:**\n\\`\\`\\`markdown\n# DEFINITION OF DONE\n\n## Completion Criteria\n- [ ] All files in PDD file structure exist\n- [ ] \\`npm run build\\` passes with 0 errors\n- [ ] \\`npm test\\` passes with >80% coverage\n- [ ] All acceptance criteria from PDD are met\n- [ ] No CRITICAL or HIGH security findings\n- [ ] Code follows project patterns from ARCH.md\n- [ ] Logger used for all service operations\n- [ ] Error handling follows AppError pattern\n\n## Fail Conditions (automatic FAIL)\n- Any CRITICAL security issue\n- Build fails\n- Less than 3 unit tests\n- Any acceptance criterion unmet\n\\`\\`\\`\n\n### 7. GOLDEN-BENCHMARKS.md\n**Purpose:** Performance/quality benchmarks for major changes\n- Benchmark suite commands\n- Expected metrics (time, cost, quality)\n- Pass criteria\n\n**Format:**\n\\`\\`\\`markdown\n# GOLDEN BENCHMARKS\n\n## Benchmark Suite\n1. **Build Time:** \\`time npm run build\\` \u2192 expect <5s\n2. **Test Time:** \\`time npm test\\` \u2192 expect <10s\n3. **Bundle Size:** \\`du -sh dist/\\` \u2192 expect <500KB\n4. **Startup Time:** \\`time node dist/api.js\\` \u2192 expect <1s\n\n## Run Condition\nExecute before merging any changes to /src/service/ or /src/api.ts\n\n## Pass Criteria\nAll benchmarks within 10% of baseline\n\\`\\`\\`\n\n## OUTPUT FORMAT (CRITICAL)\nReturn ONLY valid JSON (no markdown, no code fences, no preamble):\n\n{\n  \"pdd\": \"# PDD\\\\n\\\\n## Goal\\\\n...\",\n  \"roadmap\": \"# ROADMAP\\\\n\\\\n## Phase 1\\\\n...\",\n  \"architecture\": \"# ARCH\\\\n\\\\n## Key Decisions\\\\n...\",\n  \"scaffold\": \"# SCAFFOLD\\\\n\\\\n## Required Files\\\\n...\",\n  \"contractTests\": \"# CONTRACT TESTS\\\\n\\\\n## Test Suite\\\\n...\",\n  \"definitionOfDone\": \"# DOD\\\\n\\\\n## Completion Criteria\\\\n...\",\n  \"goldenBenchmarks\": \"# GOLDEN BENCHMARKS\\\\n\\\\n## Benchmark Suite\\\\n...\",\n  \"acceptanceCriteria\": [\"AC-1: ...\", \"AC-2: ...\"]\n}\n\n## JSON RULES (CRITICAL - READ TWICE)\n1. All newlines MUST be \\\\n (backslash + n)\n2. All quotes MUST be \\\\\" (backslash + quote)\n3. Return ONLY the JSON object\n4. NO markdown code fences (\\`\\`\\`json)\n5. NO text before { or after }\n6. Start response with { and end with }\n\n## ANTI-PATTERNS (NEVER DO THIS)\n\u274C \"Improve the codebase\" (vague)\n\u274C \"Refactor for better performance\" (no acceptance criteria)\n\u274C \"Add tests\" (which tests? for what?)\n\u274C Generic boilerplate (every artifact must be SPECIFIC to the task)\n\u274C Inventing file paths not mentioned in requirements\n\u274C Mixing Chrome Extension docs when task says VS Code Extension\n\n## SUCCESS CRITERIA FOR YOUR OUTPUT\n\u2705 L3 workers can execute WITHOUT asking questions\n\u2705 Every file path is concrete and justified\n\u2705 Every acceptance criterion is testable\n\u2705 ARCH.md prevents technology confusion\n\u2705 SCAFFOLD.md ensures buildable foundation\n\u2705 CONTRACT-TESTS.md maps 1:1 with PDD\n\u2705 DOD.md has explicit pass/fail gates\n\nYou are the SOURCE OF TRUTH. Be precise, be concrete, be executable.`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['planning', 'roadmapping', 'coordination', 'documentation', 'scaffold-planning', 'architecture'],\n    riskLevel: 'low'\n  },\n\n  'specialist-security-v1': {\n    id: 'specialist-security',\n    version: '1.0.0',\n    role: 'Security Specialist (Tier 3)',\n    basePrompt: `You are a security auditor. Check against OWASP Top 10.\n\n## Audit Checklist\n### Secrets & Credentials\n- Hardcoded API keys, tokens, passwords in source\n- .env files committed or referenced with defaults\n- Secrets in logs, error messages, or client-side code\n\n### Injection (Top Priority)\n- SQL: string concatenation in queries \u2192 must use parameterized queries\n- XSS: unescaped user input in HTML/templates\n- Command injection: user input in exec/spawn calls\n- Path traversal: user input in file paths without sanitization\n\n### Auth & Access\n- Missing auth checks on protected endpoints\n- Broken session management (no expiry, no rotation)\n- Privilege escalation (user can access admin routes)\n- CORS misconfiguration (wildcard origins with credentials)\n\n### Data Protection\n- Plaintext passwords (must be hashed with bcrypt/argon2)\n- Sensitive data in URLs or query params\n- Missing rate limiting on auth endpoints\n- No input validation on user-facing endpoints\n\n## Output Format\n### CRITICAL (must fix before deploy)\n- file:line \u2014 [vulnerability] \u2014 Remediation: [exact fix]\n### HIGH / MEDIUM / LOW\n### Summary: X findings. Overall risk: CRITICAL / HIGH / MODERATE / LOW\n\nReport only \u2014 do not modify files. Format in markdown with code examples.`,\n    allowedOverlays: ['task', 'context', 'safety', 'constraints'],\n    capabilities: ['security-review', 'risk-assessment', 'policy-enforcement'],\n    riskLevel: 'high'\n  },\n\n  'specialist-frontend-v1': {\n    id: 'specialist-frontend',\n    version: '1.0.0',\n    role: 'Frontend/UI Specialist (Tier 3)',\n    basePrompt: `You are a frontend specialist. Every UI you produce must meet Apple/Linear/Vercel-level polish.\n\n## Design Standards (Non-Negotiable)\n- Typography: system font stack or Inter. 16-18px body, 1.5 line-height. Weight hierarchy (400/500/600/700).\n- Spacing: 8px grid. Generous section padding (48-96px). Content breathes.\n- Color: muted neutrals + one accent. Dark mode via CSS custom properties. No pure black (#000).\n- Motion: 200-300ms ease-out. Fade + slight translate for reveals. Respect prefers-reduced-motion.\n- Layout: mobile-first (640/768/1024/1280px), CSS Grid + Flexbox, max-width 1200px.\n- Components: rounded corners (8-12px), soft layered shadows, no hard borders.\n- Accessibility: semantic HTML, focus-visible, 4.5:1 contrast, aria-labels.\n\n## Rules\n- Match existing design system when present\n- If none exists, establish CSS custom properties (--color-*, --space-*, --radius-*)\n- Mobile-first breakpoints (375px, 768px, 1440px must all look intentional)\n- Format code in markdown blocks.\n\nReturn production-ready code with proper HTML semantics and CSS structure.`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['frontend', 'ui', 'ux', 'accessibility', 'component-design'],\n    riskLevel: 'medium'\n  },\n\n  'specialist-backend-v1': {\n    id: 'specialist-backend',\n    version: '1.0.0',\n    role: 'Backend/API Specialist (Tier 3)',\n    basePrompt: `You are a backend specialist. Design robust APIs and services.\n\n## Standards\n- ES modules, async/await, no callbacks. Prefer native Node APIs over dependencies.\n- Every endpoint: input validation, error handling, proper HTTP status codes (200/201/400/401/403/404/500).\n- Database ops: parameterized queries (never string interpolation), connection pooling, transactions for multi-step writes.\n- Auth: never store plaintext passwords, use bcrypt/argon2. JWT with short expiry + refresh tokens.\n- Logging: structured (JSON), include request ID, timestamp, level. No console.log in production.\n- Environment: all config via env vars, never hardcoded secrets. Validate required env vars at startup.\n\n## Rules\n- Match existing code patterns and naming conventions\n- Think about: request fails, DB is down, input is malformed\n- Mental trace: happy path + one failure path\n\nReturn implementation details with proper error handling and validation.\nFormat code in markdown blocks.`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['backend', 'api-design', 'data-modeling', 'integration'],\n    riskLevel: 'medium'\n  },\n\n  'specialist-research-v1': {\n    id: 'specialist-research',\n    version: '1.0.0',\n    role: 'Research Specialist (Tier 3)',\n    basePrompt: `You are a research specialist.\n\nGather and synthesize relevant technical or market information.\nProvide concise, source-oriented conclusions and explicit assumptions.`,\n    allowedOverlays: ['task', 'context'],\n    capabilities: ['research', 'analysis', 'synthesis'],\n    riskLevel: 'low'\n  },\n\n  'specialist-ml-v1': {\n    id: 'specialist-ml',\n    version: '1.0.0',\n    role: 'ML Specialist (Tier 3)',\n    basePrompt: `You are an ML/LLM systems specialist.\n\nProvide practical guidance on:\n- model selection and evaluation\n- inference/training pipelines\n- data quality and metrics\n- deployment and monitoring tradeoffs`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['ml', 'evaluation', 'pipeline-design', 'model-selection'],\n    riskLevel: 'medium'\n  },\n\n  'specialist-github-v1': {\n    id: 'specialist-github',\n    version: '1.0.0',\n    role: 'GitHub Operations Specialist (Tier 3)',\n    basePrompt: `You are a git and GitHub workflow specialist.\n\nPrepare actionable steps for:\n- branch/commit strategy\n- PR hygiene and review readiness\n- issue/PR triage and release workflow`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['git', 'github', 'release-management'],\n    riskLevel: 'low'\n  },\n\n  'specialist-docs-v1': {\n    id: 'specialist-docs',\n    version: '1.0.0',\n    role: 'Documentation Specialist (Tier 3)',\n    basePrompt: `You are a documentation specialist.\n\nWrite clear, accurate technical docs:\n- setup and usage\n- architecture decisions\n- operational runbooks\n- change logs and migration notes`,\n    allowedOverlays: ['task', 'context', 'constraints'],\n    capabilities: ['documentation', 'technical-writing', 'onboarding'],\n    riskLevel: 'low'\n  }\n};\n\n/**\n * Prompt Composer - Safely composes prompts from templates + overlays\n */\nexport class PromptComposer {\n  private traceLog: ComposedPrompt[] = [];\n\n  /**\n   * Get a template by ID (for extracting system prompts)\n   */\n  getTemplate(templateId: string): PromptTemplate | undefined {\n    return PROMPT_TEMPLATES[templateId];\n  }\n\n  /**\n   * Compose a prompt from template + controlled overlays\n   */\n  compose(\n    templateId: string,\n    overlays: PromptOverlay[],\n    traceId: string\n  ): ComposedPrompt {\n    const template = PROMPT_TEMPLATES[templateId];\n    if (!template) {\n      throw new Error(`Unknown prompt template: ${templateId}`);\n    }\n\n    // Validate overlays are allowed\n    for (const overlay of overlays) {\n      if (!template.allowedOverlays.includes(overlay.type)) {\n        throw new Error(\n          `Overlay type \"${overlay.type}\" not allowed for template \"${templateId}\"`\n        );\n      }\n    }\n\n    // Sort overlays by priority\n    const sortedOverlays = [...overlays].sort((a, b) => a.priority - b.priority);\n\n    // Compose final prompt\n    let finalPrompt = template.basePrompt;\n    for (const overlay of sortedOverlays) {\n      finalPrompt += `\\n\\n[${overlay.type.toUpperCase()}]\\n${overlay.content}`;\n    }\n\n    const composed: ComposedPrompt = {\n      templateId: template.id,\n      templateVersion: template.version,\n      finalPrompt,\n      overlays: sortedOverlays,\n      composedAt: new Date().toISOString(),\n      traceId\n    };\n\n    this.traceLog.push(composed);\n    return composed;\n  }\n\n  /**\n   * Get trace history for debugging\n   */\n  getTrace(traceId?: string): ComposedPrompt[] {\n    if (traceId) {\n      return this.traceLog.filter(c => c.traceId === traceId);\n    }\n    return this.traceLog;\n  }\n\n  /**\n   * Clear trace history\n   */\n  clearTrace() {\n    this.traceLog = [];\n  }\n}\n\n/**\n * Capability Matrix - Define what each persona can do\n */\nexport const CAPABILITY_MATRIX: Record<string, string[]> = {\n  'router': ['routing', 'classification'],\n  'executor-code': ['code-generation', 'refactoring', 'documentation', 'debugging', 'file-write', 'scaffolding', 'bootstrap'],\n  'executor-chat': ['conversation', 'explanation', 'guidance'],\n  'decomposer': ['decomposition', 'planning', 'dependency-analysis'],\n  'policy-validator': ['validation', 'risk-assessment', 'policy-enforcement'],\n  'specialist-qa': ['testing', 'auditing', 'validation', 'security-review', 'file-read', 'contract-testing', 'definition-of-done', 'benchmarking'],\n  'specialist-pm': ['planning', 'roadmapping', 'coordination', 'documentation', 'file-write', 'scaffold-planning'],\n  'specialist-security': ['security-review', 'risk-assessment', 'policy-enforcement'],\n  'specialist-frontend': ['frontend', 'ui', 'ux', 'accessibility', 'component-design'],\n  'specialist-backend': ['backend', 'api-design', 'data-modeling', 'integration'],\n  'specialist-research': ['research', 'analysis', 'synthesis'],\n  'specialist-ml': ['ml', 'evaluation', 'pipeline-design', 'model-selection'],\n  'specialist-github': ['git', 'github', 'release-management'],\n  'specialist-docs': ['documentation', 'technical-writing', 'onboarding']\n};\n\n// Standalone persona coverage aligned with crewswarm's broader 20-role roster.\nexport const PERSONA_PROFILES: Record<string, PersonaProfile> = {\n  'crew-coder': {\n    id: 'crew-coder',\n    role: 'Full Stack Coder',\n    templateId: 'executor-code-v1',\n    capabilities: ['code-generation', 'refactoring', 'debugging'],\n    riskLevel: 'medium'\n  },\n  'crew-coder-front': {\n    id: 'crew-coder-front',\n    role: 'Frontend Engineer',\n    templateId: 'specialist-frontend-v1',\n    capabilities: ['frontend', 'ui', 'component-design'],\n    riskLevel: 'medium'\n  },\n  'crew-coder-back': {\n    id: 'crew-coder-back',\n    role: 'Backend Engineer',\n    templateId: 'specialist-backend-v1',\n    capabilities: ['backend', 'api-design', 'integration'],\n    riskLevel: 'medium'\n  },\n  'crew-frontend': {\n    id: 'crew-frontend',\n    role: 'UI/UX Specialist',\n    templateId: 'specialist-frontend-v1',\n    capabilities: ['ui', 'ux', 'accessibility'],\n    riskLevel: 'medium'\n  },\n  'crew-qa': {\n    id: 'crew-qa',\n    role: 'Quality Assurance',\n    templateId: 'specialist-qa-v1',\n    capabilities: ['testing', 'auditing', 'validation'],\n    riskLevel: 'medium'\n  },\n  'crew-fixer': {\n    id: 'crew-fixer',\n    role: 'Bug Fixer',\n    templateId: 'executor-code-v1',\n    capabilities: ['debugging', 'refactoring', 'code-generation'],\n    riskLevel: 'medium'\n  },\n  'crew-security': {\n    id: 'crew-security',\n    role: 'Security Auditor',\n    templateId: 'specialist-security-v1',\n    capabilities: ['security-review', 'risk-assessment'],\n    riskLevel: 'high'\n  },\n  'crew-pm': {\n    id: 'crew-pm',\n    role: 'Product Manager',\n    templateId: 'specialist-pm-v1',\n    capabilities: ['planning', 'roadmapping', 'coordination'],\n    riskLevel: 'low'\n  },\n  'crew-main': {\n    id: 'crew-main',\n    role: 'Coordinator',\n    templateId: 'executor-chat-v1',\n    capabilities: ['conversation', 'synthesis'],\n    riskLevel: 'low'\n  },\n  'crew-orchestrator': {\n    id: 'crew-orchestrator',\n    role: 'Orchestrator',\n    templateId: 'executor-chat-v1',\n    capabilities: ['coordination', 'planning'],\n    riskLevel: 'low'\n  },\n  orchestrator: {\n    id: 'orchestrator',\n    role: 'Orchestrator Alias',\n    templateId: 'executor-chat-v1',\n    capabilities: ['coordination', 'planning'],\n    riskLevel: 'low'\n  },\n  'crew-architect': {\n    id: 'crew-architect',\n    role: 'Architecture Specialist',\n    templateId: 'specialist-backend-v1',\n    capabilities: ['api-design', 'system-design', 'integration'],\n    riskLevel: 'medium'\n  },\n  'crew-researcher': {\n    id: 'crew-researcher',\n    role: 'Research Specialist',\n    templateId: 'specialist-research-v1',\n    capabilities: ['research', 'analysis', 'synthesis'],\n    riskLevel: 'low'\n  },\n  'crew-copywriter': {\n    id: 'crew-copywriter',\n    role: 'Content Specialist',\n    templateId: 'specialist-docs-v1',\n    capabilities: ['documentation', 'technical-writing'],\n    riskLevel: 'low'\n  },\n  'crew-seo': {\n    id: 'crew-seo',\n    role: 'SEO Specialist',\n    templateId: 'specialist-research-v1',\n    capabilities: ['research', 'analysis', 'content-strategy'],\n    riskLevel: 'low'\n  },\n  'crew-ml': {\n    id: 'crew-ml',\n    role: 'ML Specialist',\n    templateId: 'specialist-ml-v1',\n    capabilities: ['ml', 'evaluation', 'pipeline-design'],\n    riskLevel: 'medium'\n  },\n  'crew-github': {\n    id: 'crew-github',\n    role: 'GitHub Specialist',\n    templateId: 'specialist-github-v1',\n    capabilities: ['git', 'github', 'release-management'],\n    riskLevel: 'low'\n  },\n  'crew-mega': {\n    id: 'crew-mega',\n    role: 'Heavy Generalist',\n    templateId: 'executor-code-v1',\n    capabilities: ['code-generation', 'planning', 'debugging'],\n    riskLevel: 'medium'\n  },\n  'crew-telegram': {\n    id: 'crew-telegram',\n    role: 'Telegram Channel Agent',\n    templateId: 'executor-chat-v1',\n    capabilities: ['conversation', 'integration'],\n    riskLevel: 'low'\n  },\n  'crew-whatsapp': {\n    id: 'crew-whatsapp',\n    role: 'WhatsApp Channel Agent',\n    templateId: 'executor-chat-v1',\n    capabilities: ['conversation', 'integration'],\n    riskLevel: 'low'\n  }\n};\n\n/**\n * Check if a persona has a required capability\n */\nexport function hasCapability(templateId: string, capability: string): boolean {\n  const normalized = String(templateId || '').replace(/-v\\d+$/, '');\n  const capabilities = CAPABILITY_MATRIX[templateId] || CAPABILITY_MATRIX[normalized] || [];\n  return capabilities.includes(capability);\n}\n\n/**\n * Get risk level for a template\n */\nexport function getRiskLevel(templateId: string): 'low' | 'medium' | 'high' | 'unknown' {\n  const template = PROMPT_TEMPLATES[templateId];\n  return template?.riskLevel || 'unknown';\n}\n\nexport function getTemplateForPersona(persona: string): string {\n  const key = String(persona || '').trim();\n  const profile = PERSONA_PROFILES[key];\n  if (profile?.templateId) return profile.templateId;\n\n  if (key === 'specialist-qa') return 'specialist-qa-v1';\n  if (key === 'specialist-pm') return 'specialist-pm-v1';\n  if (key === 'specialist-security') return 'specialist-security-v1';\n  if (key.startsWith('specialist-')) return 'executor-chat-v1';\n  return 'executor-code-v1';\n}\n", "export interface JsonParseOptions {\n  label?: string;\n  schemaHint?: string;\n  maxAttempts?: number;\n  validate?: (parsed: unknown) => { ok: boolean; errors?: string[] };\n  onAttempt?: (meta: {\n    label: string;\n    attempt: number;\n    success: boolean;\n    repaired: boolean;\n    error?: string;\n  }) => void | Promise<void>;\n  repair?: (prompt: string) => Promise<string>;\n}\n\nexport function extractJsonCandidate(raw: string): string {\n  const text = String(raw || '');\n  const fenced = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i);\n  const candidate = fenced?.[1] || text;\n  const start = candidate.indexOf('{');\n  const end = candidate.lastIndexOf('}');\n  if (start < 0 || end < 0 || end <= start) {\n    throw new Error('Expected JSON object in model response');\n  }\n  return candidate.slice(start, end + 1);\n}\n\nexport function sanitizeBrokenJson(jsonText: string): string {\n  const src = String(jsonText || '');\n  let out = '';\n  let inString = false;\n  let escaped = false;\n  for (let i = 0; i < src.length; i += 1) {\n    const ch = src[i];\n    if (escaped) {\n      out += ch;\n      escaped = false;\n      continue;\n    }\n    if (ch === '\\\\') {\n      out += ch;\n      escaped = true;\n      continue;\n    }\n    if (ch === '\"') {\n      out += ch;\n      inString = !inString;\n      continue;\n    }\n    if (inString) {\n      if (ch === '\\n') { out += '\\\\n'; continue; }\n      if (ch === '\\r') { out += '\\\\r'; continue; }\n      if (ch === '\\t') { out += '\\\\t'; continue; }\n      const code = ch.charCodeAt(0);\n      if (code >= 0 && code < 0x20) {\n        out += `\\\\u${code.toString(16).padStart(4, '0')}`;\n        continue;\n      }\n    }\n    out += ch;\n  }\n\n  // Repair common commas/termination issues.\n  let fixed = out.replace(/,\\s*([}\\]])/g, '$1').replace(/,+/g, ',');\n  const openBraces = (fixed.match(/\\{/g) || []).length;\n  const closeBraces = (fixed.match(/\\}/g) || []).length;\n  if (openBraces > closeBraces) fixed += '}'.repeat(openBraces - closeBraces);\n  const openBrackets = (fixed.match(/\\[/g) || []).length;\n  const closeBrackets = (fixed.match(/\\]/g) || []).length;\n  if (openBrackets > closeBrackets) fixed += ']'.repeat(openBrackets - closeBrackets);\n  return fixed;\n}\n\nexport function parseJsonObject(raw: string): Record<string, unknown> {\n  const candidate = extractJsonCandidate(raw);\n  try {\n    return JSON.parse(candidate);\n  } catch {\n    return JSON.parse(sanitizeBrokenJson(candidate));\n  }\n}\n\nfunction buildRepairPrompt(raw: string, schemaHint?: string): string {\n  return [\n    'Convert the following content to STRICT valid JSON.',\n    'Return exactly one JSON object. No markdown. No commentary.',\n    schemaHint ? `Schema hint:\\n${schemaHint}` : '',\n    '',\n    '[RAW OUTPUT]',\n    String(raw || '').slice(0, 16000)\n  ].join('\\n');\n}\n\nexport async function parseJsonObjectWithRepair(raw: string, options: JsonParseOptions = {}): Promise<Record<string, unknown>> {\n  const label = options.label || 'JSON';\n  const maxAttempts = Math.max(1, Number(options.maxAttempts || 2));\n  let lastError = '';\n  let candidateRaw = String(raw || '');\n\n  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n    const repaired = attempt > 1;\n    try {\n      const parsed = parseJsonObject(candidateRaw);\n      if (options.validate) {\n        const verdict = options.validate(parsed);\n        if (!verdict.ok) {\n          throw new Error((verdict.errors || []).join('; ') || 'schema validation failed');\n        }\n      }\n      await options.onAttempt?.({ label, attempt, success: true, repaired });\n      return parsed;\n    } catch (err) {\n      lastError = err instanceof Error ? err.message : String(err);\n      if (process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true') {\n        console.log(`[JSON Parse Error] ${label} attempt ${attempt}: ${lastError}`);\n        console.log(`[JSON Parse Error] Raw response (first 500 chars): ${candidateRaw.substring(0, 500)}`);\n      }\n      await options.onAttempt?.({ label, attempt, success: false, repaired, error: lastError });\n      if (attempt >= maxAttempts || !options.repair) break;\n      const repairPrompt = buildRepairPrompt(candidateRaw, options.schemaHint);\n      candidateRaw = await options.repair(repairPrompt);\n    }\n  }\n\n  throw new Error(`${label} parse failed after ${maxAttempts} attempt(s): ${lastError}`);\n}\n", "/**\n * Dual-Tier Level 2 Planning System\n * L2A: Decomposer - breaks complex tasks into work graphs\n * L2B: Policy Validator - validates plans for risk/cost/compliance\n */\n\nimport { PromptComposer, PromptOverlay } from './registry.js';\nimport { LocalExecutor } from '../executor/local.js';\nimport { runAgenticWorker } from '../executor/agentic-executor.js';\nimport { Sandbox } from '../sandbox/index.js';\nimport { Logger } from '../utils/logger.js';\nimport { mkdir, writeFile, readFile, readdir, stat } from 'node:fs/promises';\nimport { resolve, join, relative } from 'node:path';\nimport { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { parseJsonObjectWithRepair } from '../utils/structured-json.js';\n\nexport interface WorkUnit {\n  id: string;\n  description: string;\n  requiredPersona: string;\n  dependencies: string[];\n  estimatedComplexity: 'low' | 'medium' | 'high';\n  requiredCapabilities: string[];\n  sourceRefs?: string[];\n  allowedPaths?: string[];\n  verification?: string[];\n  escalationHints?: string[];\n  maxFilesTouched?: number;\n}\n\nexport interface PlanningArtifacts {\n  pdd: string;\n  roadmap: string;\n  architecture: string;\n  scaffold: string;\n  contractTests: string;\n  design: string;\n  definitionOfDone: string;\n  goldenBenchmarks: string;\n  acceptanceCriteria: string[];\n  outputDir: string;\n  files: {\n    pdd: string;\n    roadmap: string;\n    architecture: string;\n    scaffold: string;\n    contractTests: string;\n    design: string;\n    definitionOfDone: string;\n    goldenBenchmarks: string;\n  };\n}\n\nexport interface WorkGraph {\n  units: WorkUnit[];\n  totalComplexity: number;\n  requiredPersonas: string[];\n  estimatedCost: number;\n  summary?: string;\n  acceptanceCriteria?: string[];\n  planningArtifacts?: PlanningArtifacts;\n  planMode?: 'lightweight' | 'full';\n}\n\nexport interface PolicyValidation {\n  approved: boolean;\n  riskLevel: 'low' | 'medium' | 'high' | 'critical';\n  concerns: string[];\n  recommendations: string[];\n  fallbackStrategy?: string;\n  estimatedCost: number;\n}\n\nexport interface DualL2Result {\n  workGraph: WorkGraph;\n  validation: PolicyValidation;\n  traceId: string;\n  executionPath: string[];\n  artifacts?: PlanningArtifacts;\n}\n\nexport class DualL2Planner {\n  private logger = new Logger();\n  private composer = new PromptComposer();\n  private executor = new LocalExecutor();\n\n  private getReasoningModel(): string | undefined {\n    const model = String(process.env.CREW_REASONING_MODEL || '').trim();\n    return model || undefined;\n  }\n  \n  private getChatModel(): string | undefined {\n    // For structured JSON outputs, use fast chat models, not reasoning models\n    const chatModel = String(process.env.CREW_CHAT_MODEL || '').trim();\n    const reasoningModel = String(process.env.CREW_REASONING_MODEL || '').trim();\n    \n    // Avoid reasoning-only models for structured JSON\n    // deepseek-reasoner, gemini-*-preview, etc.\n    if (reasoningModel && \n        !reasoningModel.includes('deepseek-reasoner') && \n        !reasoningModel.includes('-preview')) {\n      return reasoningModel;\n    }\n    \n    return chatModel || undefined;\n  }\n\n  private getL2AModel(): string | undefined {\n    const model = String(process.env.CREW_L2A_MODEL || '').trim();\n    if (model) return model;\n    return this.getChatModel();\n  }\n\n  private getL2BModel(): string | undefined {\n    const model = String(process.env.CREW_L2B_MODEL || '').trim();\n    if (model) return model;\n    return this.getChatModel();\n  }\n\n  private extractAllowedPaths(task: string): string[] {\n    const found = new Set<string>();\n    const fileNamed = [...task.matchAll(/file named\\s+[\"'`]?([A-Za-z0-9._/-]+\\.[A-Za-z0-9]+)[\"'`]?/gi)];\n    for (const match of fileNamed) {\n      const path = String(match[1] || '').trim();\n      if (path) found.add(path);\n    }\n\n    const pathLike = [...task.matchAll(/(?:^|[\\s(\"'`])([A-Za-z0-9._/-]+\\.[A-Za-z0-9]+)(?=$|[\\s)\"'`,.:;])/g)];\n    for (const match of pathLike) {\n      const path = String(match[1] || '').trim();\n      if (path && !path.startsWith('ac-')) found.add(path);\n    }\n\n    return Array.from(found).slice(0, 3);\n  }\n\n  private isLightweightTask(task: string, context: string = ''): boolean {\n    const text = `${task}\\n${context}`.toLowerCase();\n    if (text.length > 1200) return false;\n\n    const broadSignals = [\n      'roadmap',\n      'architecture',\n      'planning',\n      'phase 1',\n      'phase 2',\n      'phase 3',\n      'entire project',\n      'whole project',\n      'multi-agent',\n      'benchmark suite',\n      'golden benchmark',\n      'definition of done',\n      'contract tests',\n      'scaffold',\n      'deploy',\n      'migration',\n      'refactor the entire',\n      'across the repo'\n    ];\n    if (broadSignals.some(signal => text.includes(signal))) return false;\n\n    // Multi-part tasks with numbered items or multiple deliverables need full planning\n    const numberedItems = text.match(/\\d+\\)/g) || text.match(/\\d+\\.\\s/g) || [];\n    if (numberedItems.length >= 3) return false;\n\n    // Tasks mentioning tests + implementation + docs need decomposition\n    const hasTests = /\\b(test|spec|assert)\\b/.test(text);\n    const hasImpl = /\\b(endpoint|api|function|class|module|component)\\b/.test(text);\n    const hasDocs = /\\b(readme|doc|documentation)\\b/.test(text);\n    if ([hasTests, hasImpl, hasDocs].filter(Boolean).length >= 2) return false;\n\n    const paths = this.extractAllowedPaths(task);\n    const narrowIntent = /(create|write|update|modify|edit|add|fix|rename)\\b/.test(text);\n\n    // Multi-step creation tasks need decomposition even if few paths\n    // \"create X ... also create Y\" or \"create X ... add tests\" = 2+ deliverables\n    const multiDeliverable = /(also create|also add|and create|and add|then create|then add)/i.test(text);\n    const multiBug = /(two bugs|both bugs|multiple bugs|bug.*and.*bug|\\(1\\).*\\(2\\))/i.test(text);\n    if (multiDeliverable || multiBug) return false;\n\n    return narrowIntent && paths.length > 0 && paths.length <= 3;\n  }\n\n  private buildLightweightPlan(task: string, context: string, traceId: string): DualL2Result {\n    const allowedPaths = this.extractAllowedPaths(task);\n    const artifacts: PlanningArtifacts = {\n      pdd: `# PDD\\n\\n## Overview\\n- Execute a small scoped implementation task.\\n\\n## Requirements\\n- ${task}`,\n      roadmap: `# ROADMAP\\n\\n## Phase 1\\n- Complete the requested small file-scoped task.`,\n      architecture: `# ARCH\\n\\n## Scope\\n- Lightweight single-step implementation.\\n- Limit edits to explicit task paths.`,\n      scaffold: '',\n      contractTests: '',\n      design: '',\n      definitionOfDone: '',\n      goldenBenchmarks: '',\n      acceptanceCriteria: [\n        `Complete task exactly as requested: ${task}`\n      ],\n      outputDir: '',\n      files: {\n        pdd: '',\n        roadmap: '',\n        architecture: '',\n        scaffold: '',\n        contractTests: '',\n        design: '',\n        definitionOfDone: '',\n        goldenBenchmarks: ''\n      }\n    };\n\n    const workGraph: WorkGraph = {\n      units: [\n        {\n          id: 'lightweight-execute',\n          description: task,\n          requiredPersona: 'executor-code',\n          dependencies: [],\n          estimatedComplexity: allowedPaths.length > 1 ? 'medium' : 'low',\n          requiredCapabilities: ['code-generation', 'file-write', 'code-reading'],\n          sourceRefs: ['PDD.md#overview', 'ROADMAP.md#phase-1', 'ARCH.md#scope'],\n          allowedPaths,\n          verification: allowedPaths.map(path => `Confirm ${path} exists and matches the requested content/behavior.`),\n          escalationHints: [\n            'Escalate if completing the task requires editing files outside the allowed paths.',\n            'Escalate after two failed verification attempts.'\n          ],\n          maxFilesTouched: Math.max(1, allowedPaths.length)\n        }\n      ],\n      totalComplexity: allowedPaths.length > 1 ? 3 : 1,\n      requiredPersonas: ['executor-code'],\n      estimatedCost: 0.001,\n      planningArtifacts: artifacts,\n      planMode: 'lightweight'\n    };\n\n    return {\n      workGraph,\n      validation: {\n        approved: true,\n        riskLevel: 'low',\n        concerns: [],\n        recommendations: ['Keep edits within explicit allowedPaths.'],\n        fallbackStrategy: 'Escalate to full planner if the task expands beyond the scoped files.',\n        estimatedCost: 0.001\n      },\n      traceId,\n      executionPath: ['dual-l2-planner', 'l2a-lightweight', 'l2b-lightweight'],\n      artifacts\n    };\n  }\n\n  private async parseStructuredJson<T>(raw: string, label: string, schemaHint?: string): Promise<T> {\n    // Strip markdown code fences if present\n    let cleaned = raw.trim();\n    if (cleaned.startsWith('```json')) {\n      cleaned = cleaned.replace(/^```json\\n?/, '').replace(/\\n?```$/, '');\n    } else if (cleaned.startsWith('```')) {\n      cleaned = cleaned.replace(/^```\\n?/, '').replace(/\\n?```$/, '');\n    }\n    \n    // Log parse attempt\n    console.log(`[JSON Parse] ${label}: raw=${raw.length} chars, cleaned=${cleaned.length} chars`);\n    \n    const parsed = await parseJsonObjectWithRepair(cleaned, {\n      label,\n      schemaHint,\n      repair: async (repairPrompt: string) => {\n        const repaired = await this.executor.execute(repairPrompt, {\n          model: String(process.env.CREW_JSON_REPAIR_MODEL || this.getChatModel() || this.getReasoningModel() || '').trim() || undefined,\n          temperature: 0,\n          maxTokens: 1500\n        });\n        return String(repaired.result || '');\n      }\n    });\n    \n    console.log(`[JSON Parse] ${label}: \u2713 success`);\n    return parsed as T;\n  }\n\n  /**\n   * Run dual-tier Level 2 planning\n   * L2A: Decompose task into work graph\n   * L2B: Validate work graph against policy\n   */\n  /**\n   * Deep repo scan \u2014 reads key files directly and uses grep to find\n   * task-relevant code. Gives L2 the same codebase awareness that\n   * Cursor/Claude/Codex achieve through their iterative tool calls.\n   */\n  private async agenticRepoScan(task: string): Promise<string> {\n    const cwd = process.cwd();\n    const sections: string[] = [];\n\n    try {\n      // 1. Project structure\n      const tree = this.shellSafe(`find ${cwd} -maxdepth 2 -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -path '*/.crew/*' | head -60`);\n      if (tree) {\n        const paths = tree.split('\\n').map(p => relative(cwd, p)).filter(p => p && !p.startsWith('.'));\n        sections.push(`## Project Structure\\n${paths.join('\\n')}`);\n      }\n\n      // 2. package.json\n      const pkgPath = join(cwd, 'package.json');\n      if (existsSync(pkgPath)) {\n        try {\n          const pkg = JSON.parse(await readFile(pkgPath, 'utf8'));\n          sections.push(`## package.json\\nName: ${pkg.name}\\nVersion: ${pkg.version}\\nScripts: ${Object.keys(pkg.scripts || {}).slice(0, 15).join(', ')}\\nDeps: ${Object.keys(pkg.dependencies || {}).slice(0, 15).join(', ')}`);\n        } catch {}\n      }\n\n      // 3. Keyword grep \u2014 find files related to the task\n      const keywords = task.match(/\\b(dashboard|widget|agent|health|failure|status|api|endpoint|component|tab|server|route|monitor)\\b/gi) || [];\n      const uniqueKw = [...new Set(keywords.map(k => k.toLowerCase()))].slice(0, 5);\n      const relevantFiles = new Set<string>();\n\n      for (const kw of uniqueKw) {\n        const grep = this.shellSafe(`find ${cwd} -type f \\\\( -name \"*.ts\" -o -name \"*.js\" -o -name \"*.mjs\" -o -name \"*.html\" \\\\) -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" -not -path \"*/dist/*\" | xargs grep -l \"${kw}\" 2>/dev/null | head -8`);\n        if (grep) {\n          for (const f of grep.split('\\n').filter(Boolean)) {\n            relevantFiles.add(f);\n          }\n        }\n      }\n\n      if (relevantFiles.size > 0) {\n        const relPaths = [...relevantFiles].map(f => relative(cwd, f)).slice(0, 15);\n        sections.push(`## Files matching task keywords [${uniqueKw.join(', ')}]\\n${relPaths.join('\\n')}`);\n      }\n\n      // 4. Read the most relevant files (the key differentiator vs other engines)\n      const topFiles = [...relevantFiles].slice(0, 5);\n      for (const file of topFiles) {\n        try {\n          const content = await readFile(file, 'utf8');\n          const relPath = relative(cwd, file);\n          // Extract key patterns: exports, functions, API routes, class names\n          const lines = content.split('\\n');\n          const keyLines = lines.filter(l =>\n            /export |function |class |app\\.(get|post|put)|router\\.|endpoint|\\/api\\/|interface |type /.test(l)\n          ).slice(0, 20);\n\n          if (keyLines.length > 0) {\n            sections.push(`## ${relPath} \u2014 key exports/routes\\n\\`\\`\\`\\n${keyLines.join('\\n')}\\n\\`\\`\\``);\n          } else {\n            // Just show first 40 lines\n            sections.push(`## ${relPath} (first 40 lines)\\n\\`\\`\\`\\n${lines.slice(0, 40).join('\\n')}\\n\\`\\`\\``);\n          }\n        } catch {}\n      }\n\n      // 5. Git log\n      const gitLog = this.shellSafe(`git -C ${cwd} log --oneline -8 2>/dev/null`);\n      if (gitLog) sections.push(`## Recent commits\\n${gitLog}`);\n\n    } catch (err) {\n      this.logger.warn(`Repo scan failed: ${(err as Error).message}`);\n    }\n\n    const result = sections.join('\\n\\n');\n    console.log(`[L2 Planner] Repo scan: ${sections.length} sections, ${result.length} chars, ${[...new Set(sections.map(s => s.split('\\n')[0]))].length} unique files read`);\n    return result;\n  }\n\n  /**\n   * Static repo scan fallback \u2014 uses shell commands directly.\n   * Less accurate than agentic scan but faster and more reliable.\n   */\n  private async staticRepoScan(task: string): Promise<string> {\n    const cwd = process.cwd();\n    const sections: string[] = [];\n\n    try {\n      // 1. Project structure (top 2 levels, no node_modules)\n      const tree = this.shellSafe(`find ${cwd} -maxdepth 2 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' | head -80`);\n      if (tree) {\n        const relPaths = tree.split('\\n').map(p => relative(cwd, p)).filter(Boolean);\n        sections.push(`## Project Structure\\n${relPaths.join('\\n')}`);\n      }\n\n      // 2. Package.json for dependencies and scripts\n      const pkgPath = join(cwd, 'package.json');\n      if (existsSync(pkgPath)) {\n        const pkg = await readFile(pkgPath, 'utf8').catch(() => '');\n        if (pkg) {\n          try {\n            const parsed = JSON.parse(pkg);\n            sections.push(`## package.json\\nName: ${parsed.name}\\nScripts: ${Object.keys(parsed.scripts || {}).join(', ')}\\nDeps: ${Object.keys(parsed.dependencies || {}).join(', ')}`);\n          } catch {}\n        }\n      }\n\n      // 3. Grep for relevant patterns from the task\n      const keywords = task.match(/\\b(dashboard|widget|agent|health|api|endpoint|component|tab|server|route)\\b/gi) || [];\n      const uniqueKeywords = [...new Set(keywords.map(k => k.toLowerCase()))].slice(0, 4);\n      for (const kw of uniqueKeywords) {\n        const grepResult = this.shellSafe(`grep -rl \"${kw}\" ${cwd} --include=\"*.ts\" --include=\"*.js\" --include=\"*.mjs\" --include=\"*.html\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" -not -path \"*/dist/*\" 2>/dev/null | head -10`);\n        if (grepResult) {\n          const files = grepResult.split('\\n').map(p => relative(cwd, p)).filter(Boolean);\n          sections.push(`## Files matching \"${kw}\"\\n${files.join('\\n')}`);\n        }\n      }\n\n      // 4. Read key files that match the task (first 100 lines each)\n      const relevantFiles = this.shellSafe(`grep -rl \"${uniqueKeywords[0] || 'index'}\" ${cwd} --include=\"*.ts\" --include=\"*.js\" --include=\"*.mjs\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" -not -path \"*/dist/*\" 2>/dev/null | head -3`);\n      if (relevantFiles) {\n        for (const file of relevantFiles.split('\\n').filter(Boolean).slice(0, 3)) {\n          const content = await readFile(file, 'utf8').catch(() => '');\n          if (content) {\n            const relPath = relative(cwd, file);\n            const preview = content.split('\\n').slice(0, 80).join('\\n');\n            sections.push(`## ${relPath} (first 80 lines)\\n\\`\\`\\`\\n${preview}\\n\\`\\`\\``);\n          }\n        }\n      }\n\n      // 5. Git recent changes\n      const gitLog = this.shellSafe(`git -C ${cwd} log --oneline -10 2>/dev/null`);\n      if (gitLog) sections.push(`## Recent git commits\\n${gitLog}`);\n\n    } catch (err) {\n      this.logger.warn(`Repo scan failed: ${(err as Error).message}`);\n    }\n\n    const repoContext = sections.join('\\n\\n');\n    if (repoContext) {\n      console.log(`[L2 Planner] Repo scan: ${sections.length} sections, ${repoContext.length} chars`);\n    }\n    return repoContext;\n  }\n\n  private shellSafe(cmd: string): string {\n    try {\n      return execSync(cmd, { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();\n    } catch {\n      return '';\n    }\n  }\n\n  async plan(\n    task: string,\n    context: string = '',\n    traceId: string\n  ): Promise<DualL2Result> {\n    const executionPath: string[] = ['dual-l2-planner'];\n\n    try {\n      if (this.isLightweightTask(task, context)) {\n        executionPath.push('l2a-lightweight');\n        return this.buildLightweightPlan(task, context, traceId);\n      }\n\n      // L2-PHASE-0: Agentic repo scan \u2014 uses L3 tools (read_file, glob, grep, git)\n      // to build codebase context like Cursor/Claude/Codex do\n      executionPath.push('l2-agentic-scan');\n      const repoContext = await this.agenticRepoScan(task);\n      const enrichedContext = repoContext ? `${context}\\n\\n${repoContext}` : context;\n\n      // L2A-PHASE-0: Generate planning artifacts (PDD, ROADMAP, ARCH)\n      executionPath.push('l2a-planning-artifacts');\n      const planningArtifacts = await this.generatePlanningArtifacts(task, enrichedContext, traceId);\n\n      // L2A-PHASE-1: Decomposer - break down the task with artifacts\n      executionPath.push('l2a-decomposer');\n      const rawGraph = await this.decompose(task, enrichedContext, traceId, planningArtifacts);\n      const workGraph = this.enforceMandatoryExecutionGraph(rawGraph);\n\n      // L2B: Policy Validator - validate the plan\n      executionPath.push('l2b-policy-validator');\n      const validation = await this.validate(workGraph, task, traceId);\n\n      return {\n        workGraph,\n        validation,\n        traceId,\n        executionPath,\n        artifacts: planningArtifacts\n      };\n    } catch (err) {\n      this.logger.error(`Dual-L2 planning failed: ${(err as Error).message}`);\n      throw err;\n    }\n  }\n\n  /**\n   * L2A-PHASE-0: Generate planning artifacts before decomposition\n  /**\n   * Generate planning artifacts in 3 passes to avoid JSON truncation\n   * Pass 1: Core docs (PDD, ROADMAP, ARCH) + acceptance criteria\n   * Pass 2: Implementation docs (SCAFFOLD, CONTRACT-TESTS)\n   * Pass 3: Quality gates (DOD, GOLDEN-BENCHMARKS)\n   */\n  private async generatePlanningArtifacts(\n    task: string,\n    context: string,\n    traceId: string\n  ): Promise<PlanningArtifacts> {\n    console.log('[L2A Planning] Multi-pass artifact generation...');\n    \n    // Pass 1: Core planning artifacts\n    console.log('[L2A Planning] Pass 1/3: Core docs (PDD + ROADMAP + ARCH)...');\n    const coreResult = await this.generateCoreArtifacts(task, context, traceId);\n    \n    // Pass 2: Implementation artifacts (use core context)\n    console.log('[L2A Planning] Pass 2/3: Implementation docs (SCAFFOLD + CONTRACT-TESTS)...');\n    const implResult = await this.generateImplArtifacts(task, coreResult, traceId);\n    \n    // Pass 3: Quality gate artifacts (use core + impl context)\n    console.log('[L2A Planning] Pass 3/3: Quality gates (DOD + GOLDEN-BENCHMARKS)...');\n    const gateResult = await this.generateGateArtifacts(task, coreResult, traceId);\n    \n    // Write all artifacts to disk\n    const baseDir = process.env.CREW_PIPELINE_ARTIFACT_DIR\n      ? resolve(process.env.CREW_PIPELINE_ARTIFACT_DIR)\n      : resolve(process.cwd(), '.crew', 'pipeline-artifacts', traceId);\n    await mkdir(baseDir, { recursive: true });\n    \n    const files = {\n      pdd: join(baseDir, 'PDD.md'),\n      roadmap: join(baseDir, 'ROADMAP.md'),\n      architecture: join(baseDir, 'ARCH.md'),\n      scaffold: join(baseDir, 'SCAFFOLD.md'),\n      contractTests: join(baseDir, 'CONTRACT-TESTS.md'),\n      design: join(baseDir, 'DESIGN.md'),\n      definitionOfDone: join(baseDir, 'DOD.md'),\n      goldenBenchmarks: join(baseDir, 'GOLDEN-BENCHMARKS.md')\n    };\n\n    const writeOps = [\n      writeFile(files.pdd, coreResult.pdd, 'utf8'),\n      writeFile(files.roadmap, coreResult.roadmap, 'utf8'),\n      writeFile(files.architecture, coreResult.architecture, 'utf8'),\n      writeFile(files.scaffold, implResult.scaffold, 'utf8'),\n      writeFile(files.contractTests, implResult.contractTests, 'utf8'),\n      writeFile(files.definitionOfDone, gateResult.definitionOfDone, 'utf8'),\n      writeFile(files.goldenBenchmarks, gateResult.goldenBenchmarks, 'utf8')\n    ];\n    if (implResult.design) {\n      writeOps.push(writeFile(files.design, implResult.design, 'utf8'));\n    }\n    await Promise.all(writeOps);\n\n    console.log('[L2A Planning] \u2705 All artifacts generated:');\n    console.log(`  PDD.md: ${coreResult.pdd.length} chars`);\n    console.log(`  ROADMAP.md: ${coreResult.roadmap.length} chars`);\n    console.log(`  ARCH.md: ${coreResult.architecture.length} chars`);\n    console.log(`  SCAFFOLD.md: ${implResult.scaffold.length} chars`);\n    console.log(`  CONTRACT-TESTS.md: ${implResult.contractTests.length} chars`);\n    if (implResult.design) console.log(`  DESIGN.md: ${implResult.design.length} chars`);\n    console.log(`  DOD.md: ${gateResult.definitionOfDone.length} chars`);\n    console.log(`  GOLDEN-BENCHMARKS.md: ${gateResult.goldenBenchmarks.length} chars`);\n    console.log(`  Dir: ${baseDir}`);\n\n    return {\n      pdd: coreResult.pdd,\n      roadmap: coreResult.roadmap,\n      architecture: coreResult.architecture,\n      scaffold: implResult.scaffold,\n      contractTests: implResult.contractTests,\n      design: implResult.design || '',\n      definitionOfDone: gateResult.definitionOfDone,\n      goldenBenchmarks: gateResult.goldenBenchmarks,\n      acceptanceCriteria: coreResult.acceptanceCriteria,\n      outputDir: baseDir,\n      files\n    };\n  }\n\n  /**\n   * Pass 1: Generate core planning artifacts (PDD + ROADMAP + ARCH + acceptance criteria)\n   */\n  private async generateCoreArtifacts(\n    task: string,\n    context: string,\n    traceId: string\n  ): Promise<{ pdd: string; roadmap: string; architecture: string; acceptanceCriteria: string[] }> {\n    const overlays: PromptOverlay[] = [\n      { type: 'task', content: `Task: ${task}`, priority: 1 }\n    ];\n\n    if (context) {\n      overlays.push({ type: 'context', content: `Context:\\n${context}`, priority: 2 });\n    }\n\n    overlays.push({\n      type: 'constraints',\n      content: `Generate THREE core planning artifacts as compact bullet lists:\n\n**1. PDD.md** (Product Design Doc):\n- Overview (1-2 sentences)\n- Requirements (bullet list, max 5 items)\n- Success criteria (bullet list, max 3 items)\n- File structure (bullet list of files to create)\n\n**2. ROADMAP.md**:\n- Phase 1, Phase 2, Phase 3 (bullet list per phase)\n- Dependencies (\u2192 syntax: \"task-2 \u2192 task-5\")\n- Critical path (ordered list of must-complete tasks)\n\n**3. ARCH.md**:\n- Tech stack (bullet list: framework, language, key libs)\n- Module structure (bullet list of modules with 1-line purpose)\n- Patterns (e.g., \"API format: REST JSON\", \"naming: camelCase\")\n- **CRITICAL: Module system** - Inspect test files mentioned in task/context:\n  - If you see \\`import { something } from\\` in tests \u2192 write: \"Module system: **ESM** - use \\`export\\` keyword\"\n  - If you see \\`const x = require()\\` in tests \u2192 write: \"Module system: **CommonJS** - use \\`module.exports\\`\"\n  - Implementation code MUST use the SAME module system as tests\n\nReturn ONLY valid JSON (no markdown, no code fences):\n{\n  \"pdd\": \"# PDD\\\\n\\\\n## Overview\\\\n- bullet\\\\n\\\\n## Requirements\\\\n- req1\\\\n- req2\",\n  \"roadmap\": \"# ROADMAP\\\\n\\\\n## Phase 1\\\\n- task1\\\\n- task2\",\n  \"architecture\": \"# ARCH\\\\n\\\\n## Stack\\\\n- Node 20\\\\n- TypeScript\\\\n- Module system: **ESM** - use export keyword\",\n  \"acceptanceCriteria\": [\"ac-1: criteria\", \"ac-2: criteria\"]\n}\n\nCRITICAL: Escape \\\\n for newlines, \\\\\" for quotes. Return JSON only.`,\n      priority: 3\n    });\n\n    const composedPrompt = this.composer.compose('specialist-pm-v1', overlays, `${traceId}-core`);\n    const l2aModel = this.getL2AModel();\n    console.log(`[DualL2] Core artifacts - model: ${l2aModel || 'undefined (will use executor default)'}`);\n    const result = await this.executor.execute(composedPrompt.finalPrompt, {\n      model: l2aModel,\n      temperature: 0,  // Deterministic for JSON\n      maxTokens: 4000,\n      jsonMode: true  // Structured output where supported\n    });\n\n    if (!result.success) {\n      throw new Error(`Core artifacts generation failed: ${result.result}`);\n    }\n\n    const parsed = await this.parseStructuredJson<{\n      pdd: string;\n      roadmap: string;\n      architecture: string;\n      acceptanceCriteria: string[];\n    }>(\n      result.result,\n      'Core artifacts (Pass 1)',\n      '{\"pdd\":\"...\",\"roadmap\":\"...\",\"architecture\":\"...\",\"acceptanceCriteria\":[\"ac-1\"]}'\n    );\n\n    return {\n      pdd: String(parsed.pdd || `# PDD\\\\n\\\\n## Task\\\\n${task}\\\\n`).trim(),\n      roadmap: String(parsed.roadmap || `# ROADMAP\\\\n\\\\n- Implement: ${task}\\\\n`).trim(),\n      architecture: String(parsed.architecture || `# ARCH\\\\n\\\\n## System\\\\nDerived from requirements.\\\\n`).trim(),\n      acceptanceCriteria: Array.isArray(parsed.acceptanceCriteria)\n        ? parsed.acceptanceCriteria.map(v => String(v).trim()).filter(Boolean)\n        : []\n    };\n  }\n\n  /**\n   * Pass 2: Generate implementation artifacts (SCAFFOLD + CONTRACT-TESTS)\n   */\n  private async generateImplArtifacts(\n    task: string,\n    coreContext: { pdd: string; roadmap: string; architecture: string; acceptanceCriteria: string[] },\n    traceId: string\n  ): Promise<{ scaffold: string; contractTests: string; design: string }> {\n    const overlays: PromptOverlay[] = [\n      { type: 'task', content: `Task: ${task}`, priority: 1 },\n      {\n        type: 'context',\n        content: `**Core Planning Context:**\nPDD Summary: ${coreContext.pdd.slice(0, 300)}...\nROADMAP Summary: ${coreContext.roadmap.slice(0, 200)}...\nARCH Summary: ${coreContext.architecture.slice(0, 200)}...\nAcceptance Criteria: ${coreContext.acceptanceCriteria.slice(0, 3).join('; ')}`,\n        priority: 2\n      },\n      {\n        type: 'constraints',\n        content: `Generate THREE implementation artifacts as compact bullet lists:\n\n**1. SCAFFOLD.md** (Bootstrap checklist):\n- File tree (bullet list: path + 1-line purpose)\n- Config files needed (package.json, tsconfig.json, etc.)\n- Build smoke command (e.g., \"npm run build\")\n- Test smoke command (e.g., \"npm test\")\n\n**2. CONTRACT-TESTS.md**:\n- Map each acceptance criterion to 1-2 tests\n- Format: \"Test ac-1: Given X, When Y, Then Z\"\n- Include file path where test should live\n\n**3. DESIGN.md** (UI/UX design system \u2014 generate ONLY if the task involves frontend, UI, components, pages, or user-facing features. If the task is purely backend/API/CLI, set design to empty string \"\"):\n- Color tokens (primary, secondary, accent, background, surface, text, error, success \u2014 as CSS custom properties)\n- Typography scale (font families, sizes for h1-h4, body, small, mono \u2014 with line heights)\n- Spacing system (4px base unit, named sizes: xs=4, sm=8, md=16, lg=24, xl=32, xxl=48)\n- Component patterns (card, button, input, badge, modal, nav \u2014 with states: default, hover, active, disabled, focus)\n- Layout rules (max-width, grid columns, breakpoints for mobile/tablet/desktop)\n- Accessibility requirements (WCAG AA contrast ratios, focus indicators, reduced motion, aria patterns)\n- Dark/light theme token mappings\n- Animation guidelines (duration: fast=100ms, normal=200ms, slow=300ms; easing: ease-out for entrances, ease-in for exits)\n\nReturn ONLY valid JSON (no markdown, no code fences):\n{\n  \"scaffold\": \"# SCAFFOLD\\\\n\\\\n## Files\\\\n- src/index.ts: entry point\\\\n\\\\n## Build\\\\n- npm run build\",\n  \"contractTests\": \"# CONTRACT TESTS\\\\n\\\\n- Test ac-1: Given ..., When ..., Then ...\\\\n  File: tests/ac1.test.ts\",\n  \"design\": \"# DESIGN SYSTEM\\\\n\\\\n## Colors\\\\n- --color-primary: #818cf8\\\\n...\"\n}\n\nIf the task has NO frontend/UI component, set \"design\": \"\".\nCRITICAL: Escape \\\\n for newlines, \\\\\" for quotes. Return JSON only.`,\n        priority: 3\n      }\n    ];\n\n    const composedPrompt = this.composer.compose('specialist-pm-v1', overlays, `${traceId}-impl`);\n    const result = await this.executor.execute(composedPrompt.finalPrompt, {\n      model: this.getL2AModel(),\n      temperature: 0,  // Deterministic for JSON\n      maxTokens: 4000,\n      jsonMode: true\n    });\n\n    if (!result.success) {\n      throw new Error(`Implementation artifacts generation failed: ${result.result}`);\n    }\n\n    const parsed = await this.parseStructuredJson<{\n      scaffold: string;\n      contractTests: string;\n      design: string;\n    }>(\n      result.result,\n      'Implementation artifacts (Pass 2)',\n      '{\"scaffold\":\"...\",\"contractTests\":\"...\",\"design\":\"...\"}'\n    );\n\n    return {\n      scaffold: String(parsed.scaffold || `# SCAFFOLD\\\\n\\\\n- Initialize project\\\\n- Add scripts\\\\n`).trim(),\n      contractTests: String(parsed.contractTests || `# CONTRACT TESTS\\\\n\\\\n- Map acceptance criteria to tests\\\\n`).trim(),\n      design: String(parsed.design || '').trim()\n    };\n  }\n\n  /**\n   * Pass 3: Generate quality gate artifacts (DOD + GOLDEN-BENCHMARKS)\n   */\n  private async generateGateArtifacts(\n    task: string,\n    coreContext: { pdd: string; roadmap: string; acceptanceCriteria: string[] },\n    traceId: string\n  ): Promise<{ definitionOfDone: string; goldenBenchmarks: string }> {\n    const overlays: PromptOverlay[] = [\n      { type: 'task', content: `Task: ${task}`, priority: 1 },\n      {\n        type: 'context',\n        content: `**Planning Context:**\nAcceptance Criteria: ${coreContext.acceptanceCriteria.join('; ')}\nPDD Summary: ${coreContext.pdd.slice(0, 200)}...`,\n        priority: 2\n      },\n      {\n        type: 'constraints',\n        content: `Generate TWO quality gate artifacts as compact checklists:\n\n**1. DOD.md** (Definition of Done):\n- Build checklist (e.g., \"\u2713 npm run build succeeds\")\n- Test checklist (e.g., \"\u2713 all tests pass\", \"\u2713 coverage >80%\")\n- QA checklist (e.g., \"\u2713 no linter errors\")\n- Security checklist (e.g., \"\u2713 no hardcoded secrets\")\n\n**2. GOLDEN-BENCHMARKS.md**:\n- Benchmark suite command (e.g., \"npm run benchmark\")\n- Pass criteria (e.g., \"\u2713 all tasks <500ms\", \"\u2713 cost <$0.10\")\n- When to run (e.g., \"on major refactors\", \"before release\")\n\nReturn ONLY valid JSON (no markdown, no code fences):\n{\n  \"definitionOfDone\": \"# DOD\\\\n\\\\n## Build\\\\n- \u2713 npm run build\\\\n\\\\n## Tests\\\\n- \u2713 all pass\",\n  \"goldenBenchmarks\": \"# GOLDEN BENCHMARKS\\\\n\\\\n## Command\\\\n- npm run benchmark\\\\n\\\\n## Criteria\\\\n- \u2713 <500ms\"\n}\n\nCRITICAL: Escape \\\\n for newlines, \\\\\" for quotes. Return JSON only.`,\n        priority: 3\n      }\n    ];\n\n    const composedPrompt = this.composer.compose('specialist-pm-v1', overlays, `${traceId}-gates`);\n    const result = await this.executor.execute(composedPrompt.finalPrompt, {\n      model: this.getL2AModel(),\n      temperature: 0,  // Deterministic for JSON\n      maxTokens: 2000,\n      jsonMode: true\n    });\n\n    if (!result.success) {\n      throw new Error(`Quality gate artifacts generation failed: ${result.result}`);\n    }\n\n    const parsed = await this.parseStructuredJson<{\n      definitionOfDone: string;\n      goldenBenchmarks: string;\n    }>(\n      result.result,\n      'Quality gates (Pass 3)',\n      '{\"definitionOfDone\":\"...\",\"goldenBenchmarks\":\"...\"}'\n    );\n\n    return {\n      definitionOfDone: String(parsed.definitionOfDone || `# DOD\\\\n\\\\n- Build passes\\\\n- Tests pass\\\\n`).trim(),\n      goldenBenchmarks: String(parsed.goldenBenchmarks || `# GOLDEN BENCHMARKS\\\\n\\\\n- Run on major changes\\\\n`).trim()\n    };\n  }\n\n\n  /**\n   * L2A: Decompose task into work graph\n   */\n  private async decompose(\n    task: string,\n    context: string,\n    traceId: string,\n    planningArtifacts?: PlanningArtifacts\n  ): Promise<WorkGraph> {\n    const overlays: PromptOverlay[] = [\n      {\n        type: 'task',\n        content: `User task: ${task}`,\n        priority: 1\n      }\n    ];\n\n    if (context) {\n      overlays.push({\n        type: 'context',\n        content: `Context:\\n${context}`,\n        priority: 2\n      });\n    }\n\n    // Add planning artifacts to context if available\n    if (planningArtifacts) {\n      overlays.push({\n        type: 'context',\n        content: `Planning artifacts for decomposition:\n[PDD.md]\n${planningArtifacts.pdd}\n\n[ROADMAP.md]\n${planningArtifacts.roadmap}\n\n[ARCH.md]\n${planningArtifacts.architecture}\n\n[SCAFFOLD.md]\n${planningArtifacts.scaffold}\n\n[CONTRACT-TESTS.md]\n${planningArtifacts.contractTests}\n${planningArtifacts.design ? `\n[DESIGN.md]\n${planningArtifacts.design}` : ''}\n\n[DOD.md]\n${planningArtifacts.definitionOfDone}\n\n[GOLDEN-BENCHMARKS.md]\n${planningArtifacts.goldenBenchmarks}`,\n        priority: 2\n      });\n    }\n\n    overlays.push({\n      type: 'constraints',\n      content: `Return ONLY valid JSON with this structure:\n{\n  \"units\": [\n    {\n      \"id\": \"unique-id\",\n      \"description\": \"what to do\",\n      \"requiredPersona\": \"crew-coder-back\",\n      \"dependencies\": [\"id1\", \"id2\"],\n      \"estimatedComplexity\": \"low|medium|high\",\n      \"requiredCapabilities\": [\"code-generation\", \"file-write\", \"code-reading\"],\n      \"sourceRefs\": [\"PDD.md#section\", \"ROADMAP.md#milestone\", \"ARCH.md#decision\", \"CONTRACT-TESTS.md#case\", \"DOD.md#checklist\"],\n      \"allowedPaths\": [\"src/auth/jwt.ts\", \"test/auth/jwt.test.ts\"],\n      \"verification\": [\"Run npm test -- jwt\", \"Confirm src/auth/jwt.ts was updated\"],\n      \"escalationHints\": [\"Escalate if auth logic requires changes outside src/auth\", \"Escalate after two failed verification attempts\"],\n      \"maxFilesTouched\": 2\n    }\n  ],\n  \"totalComplexity\": 1-10,\n  \"requiredPersonas\": [\"crew-coder-back\", \"crew-qa\", \"crew-copywriter\"],\n  \"estimatedCost\": 0.001\n}\n\nRules:\n- Use requiredPersona to indicate the TYPE of work. Available personas:\n  - \"executor-code\" \u2014 general coding (default, full tool access)\n  - \"crew-coder-back\" \u2014 backend/API implementation\n  - \"crew-coder-front\" \u2014 frontend/UI implementation\n  - \"crew-qa\" \u2014 writing tests, test repair, validation\n  - \"crew-copywriter\" \u2014 documentation, README, guides\n  - \"crew-security\" \u2014 security review, auth implementation\n  - \"crew-fixer\" \u2014 bug fixes, debugging\n- Choose the most specific persona for each unit. Use \"executor-code\" only when no specialized persona fits.\n- requiredCapabilities can be: [\"code-generation\", \"file-write\", \"code-reading\"] only. NO \"filesystem\" or other non-existent capabilities.\n- Every unit must include at least one sourceRefs entry.\n- sourceRefs must reference one or more of: PDD.md, ROADMAP.md, ARCH.md, CONTRACT-TESTS.md, DOD.md, SCAFFOLD.md, GOLDEN-BENCHMARKS.md.\n- Every unit must include explicit allowedPaths. Use the smallest concrete file list possible.\n- Every unit must include explicit verification steps. Verification must mention exact commands or exact file-state checks.\n- Every unit must include escalationHints. Tell the worker when to stop and escalate.\n- maxFilesTouched must be 1-3 for normal tasks. Only use a higher number if absolutely necessary.\n- Keep each unit tightly scoped to one artifact or one small cluster of files. Do not create broad \"entire project\" tasks.\n- DO NOT wrap in markdown code fences (NO \\`\\`\\`json)\n- Start response with { and end with }\n- Return raw JSON only`,\n      priority: 3\n    });\n\n    const composedPrompt = this.composer.compose('decomposer-v1', overlays, traceId);\n\n    const result = await this.executor.execute(composedPrompt.finalPrompt, {\n      model: this.getL2AModel(),  // Dedicated L2A model when configured\n      temperature: 0.3,\n      maxTokens: 8000  // Increased for complete work graph JSON (was 4000)\n    });\n\n    if (!result.success) {\n      throw new Error(`Decomposer failed: ${result.result}`);\n    }\n\n    // Debug: write BEFORE parsing\n    const rawOutput = result.result || '';\n    if (process.env.DEBUG_JSON_PARSE) {\n      const fs = await import('fs');\n      fs.writeFileSync('/tmp/gemini-decomposer-response.txt', `Length: ${rawOutput.length}\\n\\n${rawOutput}`);\n      console.log('[DualL2] Debug: wrote decomposer response to /tmp/gemini-decomposer-response.txt');\n    }\n\n    const workGraph = await this.parseStructuredJson<WorkGraph>(\n      rawOutput,\n      'Decomposer',\n      '{\"units\":[{\"id\":\"unit-1\",\"description\":\"Update src/example.ts\",\"requiredPersona\":\"executor-code\",\"dependencies\":[],\"estimatedComplexity\":\"low\",\"requiredCapabilities\":[\"code-generation\",\"file-write\"],\"sourceRefs\":[\"ROADMAP.md#item\"],\"allowedPaths\":[\"src/example.ts\"],\"verification\":[\"Confirm src/example.ts changed\"],\"escalationHints\":[\"Escalate if another file must be edited\"],\"maxFilesTouched\":1}],\"totalComplexity\":1,\"requiredPersonas\":[\"executor-code\"],\"estimatedCost\":0.01}'\n    );\n    for (const unit of (workGraph.units || [])) {\n      if (!Array.isArray(unit.sourceRefs) || unit.sourceRefs.length === 0) {\n        unit.sourceRefs = ['PDD.md#overview', 'ROADMAP.md#milestones', 'ARCH.md#architecture', 'CONTRACT-TESTS.md#cases', 'DOD.md#checklist'];\n      }\n      if (!Array.isArray(unit.allowedPaths)) {\n        unit.allowedPaths = [];\n      }\n      if (!Array.isArray(unit.verification) || unit.verification.length === 0) {\n        unit.verification = ['Report the exact files changed.'];\n      }\n      if (!Array.isArray(unit.escalationHints) || unit.escalationHints.length === 0) {\n        unit.escalationHints = ['Escalate after two failed verification attempts.'];\n      }\n      if (typeof unit.maxFilesTouched !== 'number' || !Number.isFinite(unit.maxFilesTouched) || unit.maxFilesTouched < 1) {\n        unit.maxFilesTouched = unit.allowedPaths.length > 0 ? unit.allowedPaths.length : 1;\n      }\n    }\n    \n    // Attach planning artifacts to work graph for L3 workers\n    workGraph.planningArtifacts = planningArtifacts;\n    \n    return workGraph;\n  }\n\n  /**\n   * L2B: Validate work graph against policy\n   */\n  private async validate(\n    workGraph: WorkGraph,\n    originalTask: string,\n    traceId: string\n  ): Promise<PolicyValidation> {\n    const overlays: PromptOverlay[] = [\n      {\n        type: 'safety',\n        content: `Original task: ${originalTask}\n\nWork graph to validate:\n${JSON.stringify(workGraph, null, 2)}\n\nAvailable capability matrix (crew-cli standalone mode):\n- All personas run locally via the same L3 executor with persona-specific prompts\n- Supported personas: executor-code, crew-coder-back, crew-coder-front, crew-qa, crew-copywriter, crew-security, crew-fixer\n\nValidate for:\n1. Security risks (file access outside project, network calls, shell execution)\n2. Resource costs (estimated tokens, time, API calls)\n3. Scope discipline (units stay within allowedPaths)\n4. Fallback strategy (what if a unit fails?)\n\nCRITICAL VALIDATIONS:\n- APPROVE all supported personas (executor-code, crew-coder-back, crew-qa, crew-copywriter, etc.) \u2014 they all run locally\n- APPROVE all file operations to project directory (expected and safe in standalone mode)\n- APPROVE all requiredCapabilities (no capability restrictions for local L3 worker)\n- REJECT only if units access files outside the project or make dangerous external calls\n\nReturn ONLY valid JSON:\n{\n  \"approved\": true|false,\n  \"riskLevel\": \"low|medium|high|critical\",\n  \"concerns\": [\"list\", \"of\", \"concerns\"],\n  \"recommendations\": [\"list\", \"of\", \"recommendations\"],\n  \"fallbackStrategy\": \"what to do if this fails\",\n  \"estimatedCost\": 0.001\n}`,\n        priority: 1\n      },\n      {\n        type: 'constraints',\n        content: `Cost limit: $0.50 per task\nRisk tolerance: medium\nAPPROVE: All supported personas (executor-code, crew-coder-back, crew-qa, crew-copywriter, crew-security, crew-fixer, crew-coder-front)\nAPPROVE: File writes to project directory\nAPPROVE: All requiredCapabilities for local execution`,\n        priority: 2\n      }\n    ];\n\n    const composedPrompt = this.composer.compose('policy-validator-v1', overlays, traceId);\n\n    const result = await this.executor.execute(composedPrompt.finalPrompt, {\n      model: this.getL2BModel(),  // Dedicated L2B model when configured\n      temperature: 0.1,\n      maxTokens: 1000\n    });\n\n    if (!result.success) {\n      throw new Error(`Policy validator failed: ${result.result}`);\n    }\n\n    const validation = await this.parseStructuredJson<PolicyValidation>(\n      result.result,\n      'Policy validator',\n      '{\"approved\":true,\"riskLevel\":\"low\",\"concerns\":[],\"recommendations\":[],\"estimatedCost\":0.01}'\n    );\n    return validation;\n  }\n\n  /**\n   * Get composed prompts for trace debugging\n   */\n  getTrace(traceId: string) {\n    return this.composer.getTrace(traceId);\n  }\n\n  private enforceMandatoryExecutionGraph(workGraph: WorkGraph): WorkGraph {\n    const units = Array.isArray(workGraph.units) ? [...workGraph.units] : [];\n    const byId = new Map(units.map(u => [u.id, u]));\n    const gateIds = new Set(['scaffold-bootstrap', 'contract-tests-from-pdd', 'gate-definition-of-done', 'gate-golden-benchmark-suite']);\n\n    const addUnit = (unit: WorkUnit) => {\n      if (!byId.has(unit.id)) {\n        units.push(unit);\n        byId.set(unit.id, unit);\n      }\n    };\n\n    addUnit({\n      id: 'scaffold-bootstrap',\n      description: 'Mandatory scaffold phase: produce project skeleton, starter files, and build/test smoke scaffolding exactly per SCAFFOLD.md.',\n      requiredPersona: 'executor-code',\n      dependencies: [],\n      estimatedComplexity: 'low',\n      requiredCapabilities: ['scaffolding', 'code-generation'],\n      sourceRefs: ['SCAFFOLD.md#structure', 'ARCH.md#module-structure'],\n      allowedPaths: ['.'],\n      verification: ['Confirm the scaffold files required by SCAFFOLD.md now exist.'],\n      escalationHints: ['Escalate if the scaffold requires changes outside the project workspace.'],\n      maxFilesTouched: 3\n    });\n\n    addUnit({\n      id: 'contract-tests-from-pdd',\n      description: 'Generate contract tests from PDD acceptance criteria and map each test to acceptance IDs before feature implementation.',\n      requiredPersona: 'executor-code',\n      dependencies: ['scaffold-bootstrap'],\n      estimatedComplexity: 'medium',\n      requiredCapabilities: ['code-generation', 'file-write', 'code-reading'],\n      sourceRefs: ['PDD.md#success-criteria', 'CONTRACT-TESTS.md#cases'],\n      allowedPaths: ['test/', 'tests/', '__tests__/'],\n      verification: ['Confirm contract tests were created from CONTRACT-TESTS.md cases.'],\n      escalationHints: ['Escalate if the correct test directory cannot be determined.'],\n      maxFilesTouched: 3\n    });\n\n    for (const unit of units) {\n      if (gateIds.has(unit.id)) continue;\n      const deps = new Set(Array.isArray(unit.dependencies) ? unit.dependencies : []);\n      deps.add('scaffold-bootstrap');\n      deps.add('contract-tests-from-pdd');\n      unit.dependencies = Array.from(deps).filter(dep => dep !== unit.id);\n    }\n\n    const implUnitIds = units\n      .filter(u => !gateIds.has(u.id))\n      .map(u => u.id);\n\n    addUnit({\n      id: 'gate-definition-of-done',\n      description: 'Definition of done gate: verify completion criteria from DOD.md are met and return explicit pass/fail with failed checks.',\n      requiredPersona: 'executor-code',\n      dependencies: implUnitIds,\n      estimatedComplexity: 'low',\n      requiredCapabilities: ['code-reading'],\n      sourceRefs: ['DOD.md#checklist', 'PDD.md#success-criteria'],\n      allowedPaths: ['.'],\n      verification: ['Return explicit pass/fail against DOD.md and list failed checks if any.'],\n      escalationHints: ['Escalate if the definition-of-done checks require missing artifacts.'],\n      maxFilesTouched: 1\n    });\n\n    addUnit({\n      id: 'gate-golden-benchmark-suite',\n      description: 'Run golden benchmark suite for major changes using GOLDEN-BENCHMARKS.md and report command outputs, timing, and pass/fail.',\n      requiredPersona: 'executor-code',\n      dependencies: ['gate-definition-of-done'],\n      estimatedComplexity: 'medium',\n      requiredCapabilities: ['code-reading'],\n      sourceRefs: ['GOLDEN-BENCHMARKS.md#suite', 'ROADMAP.md#critical-path'],\n      allowedPaths: ['.'],\n      verification: ['Report the benchmark command, timing, and pass/fail outcome.'],\n      escalationHints: ['Escalate if the benchmark command is missing or ambiguous.'],\n      maxFilesTouched: 1\n    });\n\n    for (const unit of units) {\n      unit.dependencies = Array.from(new Set(unit.dependencies || [])).filter(dep => dep !== unit.id);\n    }\n\n    return {\n      ...workGraph,\n      units,\n      requiredPersonas: Array.from(new Set(units.map(u => u.requiredPersona))),\n      estimatedCost: Math.max(Number(workGraph.estimatedCost || 0), 0) + 0.002\n    };\n  }\n}\n", "import { randomUUID } from 'node:crypto';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport type { PlanningArtifacts } from '../prompts/dual-l2.js';\n\ninterface ContextChunk {\n  id: string;\n  source: 'PDD.md' | 'ROADMAP.md' | 'ARCH.md' | 'SCAFFOLD.md' | 'CONTRACT-TESTS.md' | 'DOD.md' | 'GOLDEN-BENCHMARKS.md';\n  ordinal: number;\n  text: string;\n  terms: string[];\n}\n\ninterface ContextPack {\n  id: string;\n  traceId: string;\n  createdAt: string;\n  chunks: ContextChunk[];\n}\n\nexport class ContextPackManager {\n  private packs = new Map<string, ContextPack>();\n  private cacheDir = resolve(process.cwd(), '.crew', 'context-packs');\n  private ttlHours = this.resolveTtlHours();\n\n  createPack(traceId: string, artifacts: PlanningArtifacts): string {\n    this.ensureCacheDir();\n    this.compactCache();\n    const key = this.computePackKey(artifacts);\n    const id = `pack-${key.slice(0, 12)}`;\n    const path = join(this.cacheDir, `${key}.json`);\n    const nowIso = new Date().toISOString();\n\n    if (existsSync(path)) {\n      try {\n        const parsed = JSON.parse(readFileSync(path, 'utf8'));\n        const chunks = Array.isArray(parsed?.chunks) ? parsed.chunks : [];\n        const cached: ContextPack = {\n          id,\n          traceId,\n          createdAt: String(parsed?.createdAt || nowIso),\n          chunks\n        };\n        this.packs.set(id, cached);\n        return id;\n      } catch {\n        // Rebuild cache on parse failure.\n      }\n    }\n\n    const chunks: ContextChunk[] = [\n      ...this.chunkDoc('PDD.md', artifacts.pdd),\n      ...this.chunkDoc('ROADMAP.md', artifacts.roadmap),\n      ...this.chunkDoc('ARCH.md', artifacts.architecture),\n      ...this.chunkDoc('SCAFFOLD.md', artifacts.scaffold),\n      ...this.chunkDoc('CONTRACT-TESTS.md', artifacts.contractTests),\n      ...this.chunkDoc('DOD.md', artifacts.definitionOfDone),\n      ...this.chunkDoc('GOLDEN-BENCHMARKS.md', artifacts.goldenBenchmarks)\n    ];\n    const pack: ContextPack = {\n      id,\n      traceId,\n      createdAt: nowIso,\n      chunks\n    };\n    this.packs.set(id, pack);\n    writeFileSync(path, JSON.stringify({ createdAt: nowIso, chunks }, null, 2), 'utf8');\n    return id;\n  }\n\n  retrieve(packId: string, options: {\n    query: string;\n    sourceRefs?: string[];\n    budgetChars?: number;\n    maxChunks?: number;\n  }): string {\n    const pack = this.packs.get(packId);\n    if (!pack) return '';\n\n    const queryTerms = this.extractTerms(options.query || '');\n    const refSources = new Set(\n      (options.sourceRefs || [])\n        .map(ref => String(ref || '').trim())\n        .filter(Boolean)\n        .map(ref => {\n          const file = ref.split('#')[0] || '';\n          if (file.endsWith('PDD.md')) return 'PDD.md';\n          if (file.endsWith('ROADMAP.md')) return 'ROADMAP.md';\n          if (file.endsWith('ARCH.md')) return 'ARCH.md';\n          if (file.endsWith('SCAFFOLD.md')) return 'SCAFFOLD.md';\n          if (file.endsWith('CONTRACT-TESTS.md')) return 'CONTRACT-TESTS.md';\n          if (file.endsWith('DOD.md')) return 'DOD.md';\n          if (file.endsWith('GOLDEN-BENCHMARKS.md')) return 'GOLDEN-BENCHMARKS.md';\n          return '';\n        })\n        .filter(Boolean)\n    );\n\n    const scored = pack.chunks.map(chunk => {\n      let score = 0;\n      if (refSources.has(chunk.source)) score += 100;\n      for (const term of queryTerms) {\n        if (chunk.terms.includes(term)) score += 3;\n      }\n      return { chunk, score };\n    });\n\n    scored.sort((a, b) => b.score - a.score || a.chunk.ordinal - b.chunk.ordinal);\n\n    const maxChunks = Math.max(1, Number(options.maxChunks || 6));\n    const budget = Math.max(1200, Number(options.budgetChars || 6000));\n    const selected: ContextChunk[] = [];\n    let used = 0;\n\n    for (const item of scored) {\n      if (selected.length >= maxChunks) break;\n      const block = `[${item.chunk.source}#${item.chunk.ordinal}]\\n${item.chunk.text}\\n`;\n      if (used + block.length > budget) continue;\n      selected.push(item.chunk);\n      used += block.length;\n    }\n\n    return selected\n      .map(c => `[${c.source}#${c.ordinal}]\\n${c.text}`)\n      .join('\\n\\n');\n  }\n\n  getPackStats(packId: string): { chunks: number } {\n    const pack = this.packs.get(packId);\n    return { chunks: pack?.chunks.length || 0 };\n  }\n\n  private resolveTtlHours(): number {\n    const raw = Number(process.env.CREW_CONTEXT_PACK_TTL_HOURS || 24);\n    if (!Number.isFinite(raw) || raw < 1) return 24;\n    return Math.min(24 * 14, Math.floor(raw));\n  }\n\n  private ensureCacheDir() {\n    if (!existsSync(this.cacheDir)) {\n      mkdirSync(this.cacheDir, { recursive: true });\n    }\n  }\n\n  private computePackKey(artifacts: PlanningArtifacts): string {\n    const body = [\n      artifacts.pdd,\n      artifacts.roadmap,\n      artifacts.architecture,\n      artifacts.scaffold,\n      artifacts.contractTests,\n      artifacts.definitionOfDone,\n      artifacts.goldenBenchmarks\n    ].join('\\n---\\n');\n    return createHash('sha256').update(body).digest('hex');\n  }\n\n  private compactCache() {\n    if (!existsSync(this.cacheDir)) return;\n    const now = Date.now();\n    const ttlMs = this.ttlHours * 60 * 60 * 1000;\n    for (const entry of readdirSync(this.cacheDir)) {\n      const full = join(this.cacheDir, entry);\n      try {\n        const stat = statSync(full);\n        if ((now - stat.mtimeMs) > ttlMs) {\n          unlinkSync(full);\n        }\n      } catch {\n        // Best effort cleanup.\n      }\n    }\n  }\n\n  private chunkDoc(source: ContextChunk['source'], text: string): ContextChunk[] {\n    const raw = String(text || '').trim();\n    if (!raw) return [];\n    const normalized = raw.replace(/\\r\\n/g, '\\n');\n    const chunkSize = 2200;\n    const overlap = 200;\n    const out: ContextChunk[] = [];\n    let start = 0;\n    let ordinal = 1;\n    while (start < normalized.length) {\n      const end = Math.min(normalized.length, start + chunkSize);\n      const slice = normalized.slice(start, end);\n      out.push({\n        id: `${source}-${ordinal}`,\n        source,\n        ordinal,\n        text: slice,\n        terms: this.extractTerms(slice)\n      });\n      if (end >= normalized.length) break;\n      start = Math.max(start + 1, end - overlap);\n      ordinal += 1;\n    }\n    return out;\n  }\n\n  private extractTerms(input: string): string[] {\n    const words = String(input || '')\n      .toLowerCase()\n      .split(/[^a-z0-9_.#-]+/g)\n      .filter(w => w.length >= 3);\n    return Array.from(new Set(words)).slice(0, 300);\n  }\n}\n", "/**\n * AgentMemory - Cognitive persistence layer for cross-model memory continuity\n * Inspired by AgentKeeper (https://github.com/Thinklanceai/agentkeeper)\n * \n * Extends ContextPackManager with:\n * - Critical fact prioritization\n * - Cross-provider memory persistence\n * - Token budget management\n * - Provider-agnostic context injection\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nexport interface MemoryFact {\n  id: string;\n  content: string;\n  critical: boolean;\n  timestamp: string;\n  tags: string[];\n  provider?: string;\n}\n\nexport interface AgentMemoryState {\n  agentId: string;\n  facts: MemoryFact[];\n  createdAt: string;\n  updatedAt: string;\n}\n\nexport class AgentMemory {\n  private state: AgentMemoryState;\n  private storageDir: string;\n\n  constructor(agentId: string, options?: { storageDir?: string }) {\n    // Use CREW_MEMORY_DIR for shared cross-system memory, or local dir for CLI-only\n    const baseDir = options?.storageDir || \n      process.env.CREW_MEMORY_DIR || \n      process.cwd();\n    this.storageDir = resolve(baseDir, '.crew', 'agent-memory');\n    this.ensureStorageDir();\n    this.state = this.loadOrCreate(agentId);\n  }\n\n  /**\n   * Store a fact in agent memory\n   */\n  remember(content: string, options: {\n    critical?: boolean;\n    tags?: string[];\n    provider?: string;\n  } = {}): string {\n    const fact: MemoryFact = {\n      id: randomUUID(),\n      content,\n      critical: options.critical || false,\n      timestamp: new Date().toISOString(),\n      tags: options.tags || [],\n      provider: options.provider\n    };\n\n    this.state.facts.push(fact);\n    this.state.updatedAt = new Date().toISOString();\n    this.persist();\n    return fact.id;\n  }\n\n  /**\n   * Remove a fact by ID\n   */\n  forget(factId: string): boolean {\n    const before = this.state.facts.length;\n    this.state.facts = this.state.facts.filter(f => f.id !== factId);\n    if (this.state.facts.length < before) {\n      this.state.updatedAt = new Date().toISOString();\n      this.persist();\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Recall facts optimized for current context\n   * Priority: critical facts first, then most recent\n   */\n  recall(options: {\n    tokenBudget?: number;\n    criticalOnly?: boolean;\n    tags?: string[];\n    provider?: string;\n  } = {}): string {\n    const budget = options.tokenBudget || 2000;\n    const estimatedCharsPerToken = 4; // Conservative estimate\n    const charBudget = budget * estimatedCharsPerToken;\n\n    // Filter facts\n    let facts = this.state.facts;\n    \n    if (options.criticalOnly) {\n      facts = facts.filter(f => f.critical);\n    }\n    \n    if (options.tags && options.tags.length > 0) {\n      facts = facts.filter(f => \n        options.tags!.some(tag => f.tags.includes(tag))\n      );\n    }\n\n    if (options.provider) {\n      facts = facts.filter(f => !f.provider || f.provider === options.provider);\n    }\n\n    // Sort: critical first, then newest\n    facts.sort((a, b) => {\n      if (a.critical && !b.critical) return -1;\n      if (!a.critical && b.critical) return 1;\n      return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();\n    });\n\n    // Pack into budget\n    const selected: MemoryFact[] = [];\n    let used = 0;\n\n    for (const fact of facts) {\n      const block = `[${fact.critical ? 'CRITICAL' : 'INFO'}] ${fact.content}\\n`;\n      if (used + block.length > charBudget) break;\n      selected.push(fact);\n      used += block.length;\n    }\n\n    if (selected.length === 0) return '';\n\n    // Format for injection\n    const header = '=== AGENT MEMORY (Context from previous decisions) ===\\n';\n    const body = selected.map(f => \n      `[${f.critical ? 'CRITICAL' : 'INFO'}] ${f.content}`\n    ).join('\\n');\n    const footer = '\\n=== END AGENT MEMORY ===\\n';\n\n    return header + body + footer;\n  }\n\n  /**\n   * Search facts by lexical similarity for brokered retrieval.\n   */\n  search(query: string, options: {\n    maxResults?: number;\n    tags?: string[];\n    provider?: string;\n  } = {}): MemoryFact[] {\n    const maxResults = Math.max(1, Number(options.maxResults || 5));\n    const qTokens = new Set(\n      String(query || '')\n        .toLowerCase()\n        .replace(/[^a-z0-9\\s_-]/g, ' ')\n        .split(/\\s+/)\n        .filter(t => t.length > 2)\n    );\n\n    let facts = this.state.facts.slice();\n    if (options.tags && options.tags.length > 0) {\n      facts = facts.filter(f => options.tags!.some(tag => f.tags.includes(tag)));\n    }\n    if (options.provider) {\n      facts = facts.filter(f => !f.provider || f.provider === options.provider);\n    }\n\n    const score = (fact: MemoryFact): number => {\n      const toks = new Set(\n        String(fact.content || '')\n          .toLowerCase()\n          .replace(/[^a-z0-9\\s_-]/g, ' ')\n          .split(/\\s+/)\n          .filter(t => t.length > 2)\n      );\n      if (qTokens.size === 0 || toks.size === 0) return 0;\n      let inter = 0;\n      for (const t of qTokens) {\n        if (toks.has(t)) inter += 1;\n      }\n      const sim = inter / Math.max(qTokens.size, toks.size);\n      return sim + (fact.critical ? 0.1 : 0);\n    };\n\n    const ranked = facts\n      .map(f => ({ fact: f, score: score(f) }))\n      .filter(x => x.score > 0.12)\n      .sort((a, b) => b.score - a.score)\n      .slice(0, maxResults)\n      .map(x => x.fact);\n\n    return ranked;\n  }\n\n  /**\n   * Get memory statistics\n   */\n  stats(): {\n    totalFacts: number;\n    criticalFacts: number;\n    providers: string[];\n    oldestFact: string | null;\n    newestFact: string | null;\n  } {\n    const facts = this.state.facts || [];\n    const timestamps = facts.map(f => f.timestamp).sort();\n    const providers = Array.from(new Set(\n      facts.map(f => f.provider).filter(Boolean) as string[]\n    ));\n\n    return {\n      totalFacts: facts.length,\n      criticalFacts: facts.filter(f => f.critical).length,\n      providers,\n      oldestFact: timestamps[0] || null,\n      newestFact: timestamps[timestamps.length - 1] || null\n    };\n  }\n\n  /**\n   * Clear all facts (useful for testing)\n   */\n  clear(): void {\n    this.state.facts = [];\n    this.state.updatedAt = new Date().toISOString();\n    this.persist();\n  }\n\n  private loadOrCreate(agentId: string): AgentMemoryState {\n    const path = this.getStatePath(agentId);\n    \n    if (existsSync(path)) {\n      try {\n        const raw = readFileSync(path, 'utf8');\n        return JSON.parse(raw);\n      } catch (err) {\n        console.warn(`[AgentMemory] Failed to load state for ${agentId}, creating new`);\n      }\n    }\n\n    const now = new Date().toISOString();\n    return {\n      agentId,\n      facts: [],\n      createdAt: now,\n      updatedAt: now\n    };\n  }\n\n  private persist(): void {\n    const path = this.getStatePath(this.state.agentId);\n    writeFileSync(path, JSON.stringify(this.state, null, 2), 'utf8');\n  }\n\n  private getStatePath(agentId: string): string {\n    return join(this.storageDir, `${agentId}.json`);\n  }\n\n  private ensureStorageDir(): void {\n    if (!existsSync(this.storageDir)) {\n      mkdirSync(this.storageDir, { recursive: true });\n    }\n  }\n}\n\n/**\n * Global memory instance for pipeline-wide memory\n */\nlet _pipelineMemory: AgentMemory | null = null;\n\nexport function getPipelineMemory(agentId: string = 'pipeline'): AgentMemory {\n  if (!_pipelineMemory) {\n    _pipelineMemory = new AgentMemory(agentId);\n  }\n  return _pipelineMemory;\n}\n\n/**\n * Get or create a crew-wide memory instance (shared across CLI and gateway)\n */\nexport function getCrewMemory(crewId: string = 'crew-lead'): AgentMemory {\n  // Always create fresh instance to ensure latest state from shared storage\n  return new AgentMemory(crewId);\n}\n", "export interface ValidationResult {\n  ok: boolean;\n  errors: string[];\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n  return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction result(errors: string[]): ValidationResult {\n  return { ok: errors.length === 0, errors };\n}\n\nexport function validateRouterDecision(v: unknown): ValidationResult {\n  const errors: string[] = [];\n  if (!isObject(v)) return result(['must be object']);\n  const decision = String(v.decision || '').trim();\n  // Normalize: lowercase, replace underscores with hyphens, strip whitespace\n  const lower = decision.toLowerCase().replace(/_/g, '-').replace(/\\s+/g, '-');\n  // Accept any string that normalizeDecision() in unified.ts would handle,\n  // plus common LLM variations (underscores, extra words, etc.)\n  const looksLikeDecision =\n    lower.length > 0 &&\n    (\n      lower.includes('direct') ||\n      lower.includes('answer') ||\n      lower.includes('chat') ||\n      lower.includes('local') ||\n      lower.includes('code') ||\n      lower.includes('parallel') ||\n      lower.includes('dispatch') ||\n      lower.includes('simple') ||\n      lower.includes('execute') ||\n      lower.includes('run') ||\n      lower.includes('plan') ||\n      lower.includes('build') ||\n      lower.includes('implement')\n    );\n  if (!looksLikeDecision) {\n    errors.push('invalid decision');\n  }\n  // reasoning is preferred but not required \u2014 old-schema or terse LLM responses may omit it.\n  // normalizeDecision() in unified.ts handles the decision mapping regardless.\n  return result(errors);\n}\n\nexport function validateWorkGraph(v: unknown): ValidationResult {\n  const errors: string[] = [];\n  if (!isObject(v)) return result(['must be object']);\n  if (!Array.isArray(v.units)) errors.push('units must be array');\n  if (!Array.isArray(v.requiredPersonas)) errors.push('requiredPersonas must be array');\n  if (typeof v.totalComplexity !== 'number') errors.push('totalComplexity must be number');\n  if (typeof v.estimatedCost !== 'number') errors.push('estimatedCost must be number');\n  for (const unit of Array.isArray(v.units) ? v.units : []) {\n    if (!isObject(unit)) { errors.push('unit must be object'); continue; }\n    if (!String(unit.id || '').trim()) errors.push('unit.id missing');\n    if (!String(unit.description || '').trim()) errors.push('unit.description missing');\n    if (!String(unit.requiredPersona || '').trim()) errors.push('unit.requiredPersona missing');\n    if (!Array.isArray(unit.dependencies)) errors.push('unit.dependencies must be array');\n    if (!Array.isArray(unit.requiredCapabilities)) errors.push('unit.requiredCapabilities must be array');\n    if (!Array.isArray(unit.sourceRefs) || unit.sourceRefs.length === 0) errors.push(`unit.sourceRefs missing for ${String(unit.id || 'unknown')}`);\n    if (!Array.isArray(unit.allowedPaths)) errors.push(`unit.allowedPaths must be array for ${String(unit.id || 'unknown')}`);\n    if (!Array.isArray(unit.verification) || unit.verification.length === 0) errors.push(`unit.verification missing for ${String(unit.id || 'unknown')}`);\n    if (!Array.isArray(unit.escalationHints) || unit.escalationHints.length === 0) errors.push(`unit.escalationHints missing for ${String(unit.id || 'unknown')}`);\n    if (typeof unit.maxFilesTouched !== 'number' || !Number.isFinite(unit.maxFilesTouched) || unit.maxFilesTouched < 1) {\n      errors.push(`unit.maxFilesTouched invalid for ${String(unit.id || 'unknown')}`);\n    }\n  }\n  return result(errors);\n}\n\nexport function validatePolicyValidation(v: unknown): ValidationResult {\n  const errors: string[] = [];\n  if (!isObject(v)) return result(['must be object']);\n  if (typeof v.approved !== 'boolean') errors.push('approved must be boolean');\n  if (!['low', 'medium', 'high', 'critical'].includes(String(v.riskLevel || ''))) errors.push('invalid riskLevel');\n  if (!Array.isArray(v.concerns)) errors.push('concerns must be array');\n  if (!Array.isArray(v.recommendations)) errors.push('recommendations must be array');\n  if (typeof v.estimatedCost !== 'number') errors.push('estimatedCost must be number');\n  return result(errors);\n}\n", "import { appendFile, mkdir } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nexport async function recordJsonParseMetric(entry: {\n  label: string;\n  attempt: number;\n  success: boolean;\n  repaired: boolean;\n  error?: string;\n  traceId?: string;\n}) {\n  try {\n    const dir = resolve(process.cwd(), '.crew');\n    await mkdir(dir, { recursive: true });\n    const path = join(dir, 'json-parse-metrics.jsonl');\n    await appendFile(path, `${JSON.stringify({ ts: new Date().toISOString(), ...entry })}\\n`, 'utf8');\n  } catch {\n    // Best-effort observability.\n  }\n}\n\n", "/**\n * Pipeline Run State \u2014 strict ordered stage machine.\n *\n * Bootstrap graph stages:\n *   scan \u2192 route \u2192 plan \u2192 validate-plan \u2192 execute \u2192 evidence \u2192 qa \u2192 checkpoint \u2192 complete\n *\n * Each stage MUST complete before the next starts.\n * 'failed' can be entered from any stage.\n * Stages can be skipped (e.g., direct-answer skips execute..checkpoint).\n */\n\nexport type PipelinePhase =\n  | 'init'\n  | 'scan'             // Build ProjectContext\n  | 'route'            // L1 classify\n  | 'plan'             // L2 decompose\n  | 'validate-plan'    // Check work units are well-formed\n  | 'execute'          // L3 workers\n  | 'evidence'         // Build transcript + file diffs\n  | 'validate'         // Deterministic QA + optional LLM review (legacy compat alias for 'qa')\n  | 'qa'               // Deterministic QA + optional LLM review\n  | 'checkpoint'       // Git commit if changes made\n  | 'complete'\n  | 'failed';\n\nconst ORDER: PipelinePhase[] = [\n  'init', 'scan', 'route', 'plan', 'validate-plan',\n  'execute', 'evidence', 'validate', 'qa', 'checkpoint', 'complete'\n];\n\nexport class PipelineRunState {\n  private phase: PipelinePhase = 'init';\n  private timeline: Array<{ phase: PipelinePhase; ts: string; durationMs?: number; note?: string }> = [\n    { phase: 'init', ts: new Date().toISOString() }\n  ];\n  private phaseStartTime: number = Date.now();\n\n  transition(next: PipelinePhase, note?: string) {\n    const now = Date.now();\n    const durationMs = now - this.phaseStartTime;\n\n    // Update the current phase's duration\n    if (this.timeline.length > 0) {\n      this.timeline[this.timeline.length - 1].durationMs = durationMs;\n    }\n\n    if (next === 'failed') {\n      this.phase = 'failed';\n      this.timeline.push({ phase: 'failed', ts: new Date().toISOString(), note });\n      return;\n    }\n\n    // Allow 'validate' as legacy alias for 'qa'\n    const effectiveNext = next === 'validate' ? next : next;\n\n    const currentIdx = ORDER.indexOf(this.phase);\n    const nextIdx = ORDER.indexOf(effectiveNext);\n    if (currentIdx < 0 || nextIdx < 0 || nextIdx <= currentIdx) {\n      // Allow skipping forward (not just adjacent) \u2014 but never backward\n      if (nextIdx <= currentIdx) {\n        throw new Error(`Invalid phase transition: ${this.phase} -> ${next} (cannot go backward)`);\n      }\n    }\n\n    this.phase = effectiveNext;\n    this.phaseStartTime = now;\n    this.timeline.push({ phase: effectiveNext, ts: new Date().toISOString(), note });\n  }\n\n  current() {\n    return this.phase;\n  }\n\n  getTimeline() {\n    return [...this.timeline];\n  }\n\n  /** Total elapsed time from init to current phase. */\n  totalElapsedMs(): number {\n    if (this.timeline.length < 2) return 0;\n    const first = new Date(this.timeline[0].ts).getTime();\n    return Date.now() - first;\n  }\n\n  /** Get timing for a specific phase. */\n  phaseDuration(phase: PipelinePhase): number | undefined {\n    const entry = this.timeline.find(e => e.phase === phase);\n    return entry?.durationMs;\n  }\n}\n\n", "export interface CapabilityMap {\n  canRead: boolean;\n  canWrite: boolean;\n  canPty: boolean;\n  canLsp: boolean;\n  canDispatch: boolean;\n  canGit: boolean;\n  mode: 'standalone' | 'connected';\n}\n\nexport function resolveCapabilityMap(mode: 'standalone' | 'connected'): CapabilityMap {\n  const pty = process.env.CREW_DISABLE_PTY === 'true' ? false : true;\n  const lsp = process.env.CREW_DISABLE_LSP === 'true' ? false : true;\n  return {\n    canRead: true,\n    canWrite: true,\n    canPty: pty,\n    canLsp: lsp,\n    canDispatch: mode === 'connected',\n    canGit: true,\n    mode\n  };\n}\n\nexport function missingForRequiredCapabilities(required: string[], caps: CapabilityMap): string[] {\n  const req = new Set((required || []).map(v => String(v).toLowerCase().trim()).filter(Boolean));\n  const missing: string[] = [];\n  if (req.has('dispatch') && !caps.canDispatch) missing.push('dispatch');\n  if ((req.has('write') || req.has('write-file') || req.has('code-generation')) && !caps.canWrite) missing.push('write');\n  if (req.has('pty') && !caps.canPty) missing.push('pty');\n  if ((req.has('lsp') || req.has('type-check')) && !caps.canLsp) missing.push('lsp');\n  if ((req.has('git') || req.has('github')) && !caps.canGit) missing.push('git');\n  return missing;\n}\n\n", "import type { WorkGraph, WorkUnit } from '../prompts/dual-l2.js';\n\nexport interface WorkerTaskEnvelope {\n  id: string;\n  goal: string;\n  persona: string;\n  dependencies: string[];\n  allowedPaths: string[];\n  verification: string[];\n  requiredCapabilities: string[];\n  sourceRefs?: string[];\n  estimatedComplexity?: 'low' | 'medium' | 'high';\n  escalationHints?: string[];\n  maxFilesTouched?: number;\n}\n\nexport interface WorkerTaskValidation {\n  ok: boolean;\n  errors: string[];\n  warnings: string[];\n}\n\nconst FILE_PATH_RE = /(?:^|[\\s(])((?:\\.{0,2}\\/|\\/)?(?:[\\w.-]+\\/)*[\\w.-]+\\.[A-Za-z0-9]+)\\b/g;\nconst CANONICAL_SOURCE_RE = /^(PDD|ROADMAP|ARCH|CONTRACT-TESTS|DOD|SCAFFOLD|GOLDEN-BENCHMARKS)\\.md#/;\nconst BROAD_SCOPE_RE = /\\b(entire|whole|all files|entire project|whole project|entire codebase|everything)\\b/i;\nconst ACTION_VERB_RE = /\\b(add|build|create|edit|fix|implement|refactor|remove|rename|replace|update|verify|write)\\b/i;\n\nfunction unique<T>(items: T[]): T[] {\n  return Array.from(new Set(items));\n}\n\nfunction extractPaths(text: string): string[] {\n  const matches: string[] = [];\n  let match;\n  while ((match = FILE_PATH_RE.exec(text)) !== null) {\n    const raw = String(match[1] || '').trim();\n    if (!raw) continue;\n    matches.push(raw.replace(/[),.;:]+$/, ''));\n  }\n  return unique(matches);\n}\n\nfunction defaultVerification(unit: WorkUnit, allowedPaths: string[]): string[] {\n  const checks: string[] = [];\n  if (allowedPaths.length > 0) {\n    checks.push(`Confirm the requested changes exist in: ${allowedPaths.join(', ')}`);\n  }\n  checks.push('Report the exact files changed.');\n  if ((unit.requiredCapabilities || []).includes('testing')) {\n    checks.push('Run the relevant test or validation command and report the result.');\n  }\n  return checks;\n}\n\nfunction defaultEscalationHints(unit: WorkUnit, allowedPaths: string[]): string[] {\n  const hints: string[] = [];\n  if (allowedPaths.length === 0) {\n    hints.push('Escalate if the required file paths are ambiguous.');\n  }\n  if (unit.estimatedComplexity === 'high') {\n    hints.push('Escalate if the task expands beyond the stated scope or requires architectural decisions.');\n  }\n  hints.push('Escalate after two failed attempts on the same verification step.');\n  return hints;\n}\n\nexport function createWorkerTaskEnvelope(unit: WorkUnit): WorkerTaskEnvelope {\n  const allowedPaths = Array.isArray(unit.allowedPaths) && unit.allowedPaths.length > 0\n    ? unique(unit.allowedPaths.map(String))\n    : extractPaths(unit.description || '');\n  const verification = Array.isArray(unit.verification) && unit.verification.length > 0\n    ? unique(unit.verification.map(String))\n    : defaultVerification(unit, allowedPaths);\n\n  const envelope: WorkerTaskEnvelope = {\n    id: unit.id,\n    goal: unit.description,\n    persona: unit.requiredPersona,\n    dependencies: Array.isArray(unit.dependencies) ? unit.dependencies : [],\n    allowedPaths,\n    verification,\n    requiredCapabilities: Array.isArray(unit.requiredCapabilities) ? unit.requiredCapabilities : [],\n  };\n\n  // Only populate optional advisory fields when there's actual data\n  const sourceRefs = Array.isArray(unit.sourceRefs) ? unit.sourceRefs.map(String).filter(Boolean) : [];\n  if (sourceRefs.length > 0) {\n    envelope.sourceRefs = sourceRefs;\n  }\n\n  if (unit.estimatedComplexity && ['low', 'medium', 'high'].includes(unit.estimatedComplexity)) {\n    envelope.estimatedComplexity = unit.estimatedComplexity;\n  }\n\n  const escalationHints = Array.isArray(unit.escalationHints) && unit.escalationHints.length > 0\n    ? unique(unit.escalationHints.map(String))\n    : defaultEscalationHints(unit, allowedPaths);\n  if (escalationHints.length > 0) {\n    envelope.escalationHints = escalationHints;\n  }\n\n  if (typeof unit.maxFilesTouched === 'number' && Number.isFinite(unit.maxFilesTouched) && unit.maxFilesTouched > 0) {\n    envelope.maxFilesTouched = Math.floor(unit.maxFilesTouched);\n  } else if (allowedPaths.length > 0) {\n    envelope.maxFilesTouched = allowedPaths.length;\n  }\n\n  return envelope;\n}\n\nexport function validateWorkerTaskEnvelope(task: WorkerTaskEnvelope): WorkerTaskValidation {\n  const errors: string[] = [];\n  const warnings: string[] = [];\n  if (!String(task.id || '').trim()) errors.push('task.id missing');\n  if (!String(task.goal || '').trim()) errors.push('task.goal missing');\n  if (!String(task.persona || '').trim()) errors.push('task.persona missing');\n  if (!Array.isArray(task.dependencies)) errors.push('task.dependencies must be array');\n  if (!Array.isArray(task.allowedPaths)) errors.push('task.allowedPaths must be array');\n  if (!Array.isArray(task.verification) || task.verification.length === 0) errors.push('task.verification missing');\n  if (!Array.isArray(task.requiredCapabilities)) errors.push('task.requiredCapabilities must be array');\n  if (task.sourceRefs !== undefined && !Array.isArray(task.sourceRefs)) errors.push('task.sourceRefs must be array if provided');\n  if (task.maxFilesTouched !== undefined && (typeof task.maxFilesTouched !== 'number' || !Number.isFinite(task.maxFilesTouched) || task.maxFilesTouched < 1)) {\n    errors.push('task.maxFilesTouched invalid');\n  }\n  if (task.estimatedComplexity !== undefined && !['low', 'medium', 'high'].includes(String(task.estimatedComplexity || ''))) {\n    errors.push('task.estimatedComplexity invalid');\n  }\n  const goal = String(task.goal || '').trim();\n  if (goal.length < 20) {\n    // Ad-hoc tasks from raw user input may be intentionally short (e.g. \"reply with a haiku\") \u2014 warn, don't reject\n    if (task.sourceRefs?.includes('adhoc#request') || task.sourceRefs?.includes('request#user-input')) {\n      warnings.push('task.goal is short; consider a more descriptive goal for pipeline tasks');\n    } else {\n      errors.push('task.goal too short');\n    }\n  }\n  if (!ACTION_VERB_RE.test(goal)) warnings.push('task.goal may be too vague; no concrete action verb found');\n  if (BROAD_SCOPE_RE.test(goal)) {\n    // Ad-hoc tasks from raw user input may contain broad language \u2014 warn, don't reject\n    if (task.sourceRefs?.includes('adhoc#request') || task.sourceRefs?.includes('request#user-input')) {\n      warnings.push('task.goal may be too broad for a single worker');\n    } else {\n      errors.push('task.goal too broad');\n    }\n  }\n  if (task.estimatedComplexity && task.estimatedComplexity !== 'low' && task.allowedPaths.length === 0) {\n    warnings.push('task.allowedPaths empty for non-trivial task');\n  }\n  if (task.allowedPaths.length > 3) {\n    warnings.push('task.allowedPaths spans more than 3 paths; consider decomposing further');\n  }\n  if (task.maxFilesTouched && task.maxFilesTouched > 3 && task.estimatedComplexity !== 'high') {\n    warnings.push('task.maxFilesTouched > 3 for non-high-complexity task');\n  }\n  if (task.verification.length > 5) {\n    warnings.push('task.verification has many checks; consider splitting the task');\n  }\n  if (Array.isArray(task.sourceRefs) && task.sourceRefs.length > 0) {\n    const invalidSourceRefs = task.sourceRefs.filter(ref => !CANONICAL_SOURCE_RE.test(String(ref)));\n    if (invalidSourceRefs.length > 0) {\n      warnings.push(`task.sourceRefs include non-canonical refs: ${invalidSourceRefs.join(', ')}`);\n    }\n  }\n  return { ok: errors.length === 0, errors, warnings };\n}\n\nexport function buildWorkerTasks(workGraph: WorkGraph): WorkerTaskEnvelope[] {\n  return (workGraph.units || []).map(createWorkerTaskEnvelope);\n}\n\nexport function createAdHocWorkerTask(input: {\n  id: string;\n  goal: string;\n  persona?: string;\n  sourceRefs?: string[];\n  estimatedComplexity?: 'low' | 'medium' | 'high';\n  requiredCapabilities?: string[];\n  maxFilesTouched?: number;\n}): WorkerTaskEnvelope {\n  const goal = String(input.goal || '').trim();\n  const allowedPaths = extractPaths(goal);\n  const sourceRefs = Array.isArray(input.sourceRefs) && input.sourceRefs.length > 0\n    ? input.sourceRefs.map(String)\n    : ['adhoc#request'];\n  const requiredCapabilities = Array.isArray(input.requiredCapabilities) && input.requiredCapabilities.length > 0\n    ? input.requiredCapabilities.map(String)\n    : ['code-generation'];\n  return {\n    id: input.id,\n    goal,\n    persona: input.persona || 'executor-code',\n    dependencies: [],\n    allowedPaths,\n    verification: [\n      ...(allowedPaths.length > 0 ? [`Confirm the requested changes exist in: ${allowedPaths.join(', ')}`] : []),\n      'Report the exact files changed.',\n      'Run relevant verification if code was modified.'\n    ],\n    requiredCapabilities,\n    sourceRefs,\n    estimatedComplexity: input.estimatedComplexity || 'medium',\n    escalationHints: [\n      ...(allowedPaths.length === 0 ? ['Escalate if the file scope is ambiguous.'] : []),\n      'Escalate after two failed attempts on the same verification step.'\n    ],\n    maxFilesTouched: typeof input.maxFilesTouched === 'number' && Number.isFinite(input.maxFilesTouched) && input.maxFilesTouched > 0\n      ? Math.floor(input.maxFilesTouched)\n      : Math.max(1, allowedPaths.length || 1)\n  };\n}\n", "/**\n * Deterministic QA Gate \u2014 mechanical validation from execution transcript.\n *\n * Runs BEFORE any LLM-based QA. If these checks fail, no LLM review needed.\n * If all pass, optional LLM review can run for semantic quality checks.\n */\n\nimport type { ExecutionTranscript } from './transcript.js';\n\nexport interface QACheck {\n  name: string;\n  passed: boolean;\n  detail?: string;\n}\n\nexport interface QAGateResult {\n  passed: boolean;\n  checks: QACheck[];\n  summary: string;\n}\n\n/**\n * Run deterministic QA checks against an execution transcript.\n */\nexport function runDeterministicQA(\n  transcript: ExecutionTranscript,\n  options: {\n    maxTurns?: number;\n    requireFileChanges?: boolean;\n  } = {}\n): QAGateResult {\n  const checks: QACheck[] = [];\n\n  // 1. All edited files were read first?\n  const unreadEdits = transcript.unreadEdits;\n  checks.push({\n    name: 'read-before-edit',\n    passed: unreadEdits.length === 0,\n    detail: unreadEdits.length > 0\n      ? `Files edited without prior read: ${unreadEdits.join(', ')}`\n      : undefined\n  });\n\n  // 2. No file overwrites (write_file should only create new files)?\n  const editedFiles = transcript.filesEdited;\n  const writtenFiles = transcript.filesWritten;\n  const overwrites = [...writtenFiles].filter(f => editedFiles.has(f));\n  checks.push({\n    name: 'no-overwrites',\n    passed: overwrites.length === 0,\n    detail: overwrites.length > 0\n      ? `Files both written and edited (possible overwrite): ${overwrites.join(', ')}`\n      : undefined\n  });\n\n  // 3. Shell commands succeeded?\n  const failedShell = transcript.failedShellCommands;\n  checks.push({\n    name: 'shell-success',\n    passed: failedShell.length === 0,\n    detail: failedShell.length > 0\n      ? `${failedShell.length} shell command(s) failed: ${failedShell.map(e => e.params.command || '?').join('; ').slice(0, 200)}`\n      : undefined\n  });\n\n  // 4. Worker stayed within turn/token budget?\n  const maxTurns = options.maxTurns ?? 25;\n  const toolCallCount = transcript.length;\n  // Rough heuristic: each turn might have 1-3 tool calls, so budget is ~3x maxTurns\n  const toolBudget = maxTurns * 3;\n  checks.push({\n    name: 'within-budget',\n    passed: toolCallCount <= toolBudget,\n    detail: toolCallCount > toolBudget\n      ? `${toolCallCount} tool calls exceeds budget of ${toolBudget} (${maxTurns} turns \u00D7 3)`\n      : undefined\n  });\n\n  // 5. Files actually changed on disk?\n  if (options.requireFileChanges !== false) {\n    const anyFileChanges = transcript.filesEdited.size > 0 || transcript.filesWritten.size > 0;\n    checks.push({\n      name: 'files-changed',\n      passed: anyFileChanges,\n      detail: !anyFileChanges\n        ? 'No file edits or writes recorded in transcript'\n        : undefined\n    });\n  }\n\n  // 6. No unhandled errors?\n  const unhandledErrors = transcript.entries.filter(e => !e.success && e.handled === false);\n  checks.push({\n    name: 'no-unhandled-errors',\n    passed: unhandledErrors.length === 0,\n    detail: unhandledErrors.length > 0\n      ? `${unhandledErrors.length} unhandled error(s): ${unhandledErrors.map(e => e.error || '?').join('; ').slice(0, 200)}`\n      : undefined\n  });\n\n  // 7. No repeated identical failing tool calls (stuck loop)?\n  const failedSignatures = transcript.entries\n    .filter(e => !e.success)\n    .map(e => `${e.toolName}:${JSON.stringify(e.params)}`);\n  const failedCounts = new Map<string, number>();\n  for (const sig of failedSignatures) {\n    failedCounts.set(sig, (failedCounts.get(sig) || 0) + 1);\n  }\n  const stuckLoops = [...failedCounts.entries()].filter(([, count]) => count >= 3);\n  checks.push({\n    name: 'no-stuck-loops',\n    passed: stuckLoops.length === 0,\n    detail: stuckLoops.length > 0\n      ? `Repeated failing tool calls detected (stuck loop): ${stuckLoops.map(([sig]) => sig.slice(0, 80)).join('; ')}`\n      : undefined\n  });\n\n  const passed = checks.every(c => c.passed);\n  const failed = checks.filter(c => !c.passed);\n  const summary = passed\n    ? `All ${checks.length} QA checks passed`\n    : `${failed.length}/${checks.length} QA checks failed: ${failed.map(c => c.name).join(', ')}`;\n\n  return { passed, checks, summary };\n}\n", "/**\n * Immutable ProjectContext \u2014 frozen snapshot of the project at session start.\n *\n * Built once, injected into every system prompt (L1 router, L2 planner, L3 workers).\n * Prevents workers from creating wrong-tech-stack code (e.g., Node.js modules\n * for browser projects, TypeScript for vanilla JS projects).\n */\n\nimport { readFile, readdir, stat } from 'node:fs/promises';\nimport { join, extname, relative } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface FileEntry {\n  path: string;     // relative to project root\n  type: 'file' | 'dir';\n  size: number;\n  ext: string;\n}\n\nexport type TechStack =\n  | 'static-html'\n  | 'node-js'\n  | 'node-ts'\n  | 'python'\n  | 'go'\n  | 'rust'\n  | 'java'\n  | 'ruby'\n  | 'php'\n  | 'unknown';\n\nexport interface ProjectConfig {\n  name?: string;\n  packageManager?: 'npm' | 'yarn' | 'pnpm' | 'bun';\n  dependencies?: Record<string, string>;\n  devDependencies?: Record<string, string>;\n  scripts?: Record<string, string>;\n  tsconfig?: boolean;\n  eslint?: boolean;\n  prettier?: boolean;\n  gitignorePatterns?: string[];\n}\n\nexport interface ProjectContext {\n  readonly root: string;\n  readonly techStack: TechStack;\n  readonly fileTree: ReadonlyArray<FileEntry>;\n  readonly config: Readonly<ProjectConfig>;\n  readonly summary: string;        // pre-formatted context string for injection\n  readonly builtAt: number;        // Date.now() \u2014 never changes\n}\n\n// ---------------------------------------------------------------------------\n// Ignore patterns\n// ---------------------------------------------------------------------------\n\nconst IGNORE_DIRS = new Set([\n  'node_modules', '.git', '.crew', 'dist', 'build', '.next', '__pycache__',\n  '.venv', 'venv', 'target', '.idea', '.vscode', 'coverage', '.turbo',\n  '.cache', '.parcel-cache', '.output', '.nuxt', '.svelte-kit'\n]);\n\nconst IGNORE_EXTS = new Set([\n  '.map', '.lock', '.log', '.DS_Store', '.ico', '.woff', '.woff2', '.eot',\n  '.ttf', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.mp4', '.mp3',\n  '.wav', '.pdf', '.zip', '.tar', '.gz'\n]);\n\n// ---------------------------------------------------------------------------\n// Build\n// ---------------------------------------------------------------------------\n\nexport async function buildProjectContext(projectRoot: string): Promise<ProjectContext> {\n  const fileTree: FileEntry[] = [];\n\n  // Walk directory (max 2 levels deep, max 500 files to stay fast)\n  await walkDir(projectRoot, projectRoot, fileTree, 0, 3, 500);\n\n  const config = await detectConfig(projectRoot);\n  const techStack = detectTechStack(fileTree, config);\n  const summary = formatContextSummary(projectRoot, techStack, fileTree, config);\n\n  const ctx: ProjectContext = Object.freeze({\n    root: projectRoot,\n    techStack,\n    fileTree: Object.freeze(fileTree),\n    config: Object.freeze(config),\n    summary,\n    builtAt: Date.now()\n  });\n\n  return ctx;\n}\n\nasync function walkDir(\n  base: string,\n  dir: string,\n  entries: FileEntry[],\n  depth: number,\n  maxDepth: number,\n  maxFiles: number\n): Promise<void> {\n  if (depth > maxDepth || entries.length >= maxFiles) return;\n\n  let dirEntries: string[];\n  try {\n    dirEntries = await readdir(dir);\n  } catch {\n    return;\n  }\n\n  for (const name of dirEntries) {\n    if (entries.length >= maxFiles) break;\n    if (name.startsWith('.') && name !== '.gitignore') continue;\n    if (IGNORE_DIRS.has(name)) continue;\n\n    const fullPath = join(dir, name);\n    try {\n      const s = await stat(fullPath);\n      const relPath = relative(base, fullPath);\n      const ext = extname(name);\n\n      if (s.isDirectory()) {\n        entries.push({ path: relPath, type: 'dir', size: 0, ext: '' });\n        await walkDir(base, fullPath, entries, depth + 1, maxDepth, maxFiles);\n      } else if (s.isFile() && !IGNORE_EXTS.has(ext.toLowerCase())) {\n        entries.push({ path: relPath, type: 'file', size: s.size, ext });\n      }\n    } catch {\n      // skip inaccessible\n    }\n  }\n}\n\nasync function detectConfig(root: string): Promise<ProjectConfig> {\n  const config: ProjectConfig = {};\n\n  // package.json\n  try {\n    const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));\n    config.name = pkg.name;\n    config.dependencies = pkg.dependencies;\n    config.devDependencies = pkg.devDependencies;\n    config.scripts = pkg.scripts;\n    if (pkg.packageManager?.startsWith('yarn')) config.packageManager = 'yarn';\n    else if (pkg.packageManager?.startsWith('pnpm')) config.packageManager = 'pnpm';\n    else if (pkg.packageManager?.startsWith('bun')) config.packageManager = 'bun';\n    else config.packageManager = 'npm';\n  } catch {\n    // no package.json\n  }\n\n  // tsconfig\n  try {\n    await stat(join(root, 'tsconfig.json'));\n    config.tsconfig = true;\n  } catch {\n    config.tsconfig = false;\n  }\n\n  // .gitignore\n  try {\n    const gi = await readFile(join(root, '.gitignore'), 'utf8');\n    config.gitignorePatterns = gi.split('\\n').filter(l => l.trim() && !l.startsWith('#')).slice(0, 20);\n  } catch {\n    // no .gitignore\n  }\n\n  return config;\n}\n\nfunction detectTechStack(files: FileEntry[], config: ProjectConfig): TechStack {\n  const exts = new Set(files.filter(f => f.type === 'file').map(f => f.ext.toLowerCase()));\n  const hasTS = exts.has('.ts') || exts.has('.tsx') || config.tsconfig;\n  const hasJS = exts.has('.js') || exts.has('.jsx') || exts.has('.mjs');\n  const hasPy = exts.has('.py');\n  const hasGo = exts.has('.go');\n  const hasRust = exts.has('.rs');\n  const hasJava = exts.has('.java');\n  const hasRuby = exts.has('.rb');\n  const hasPHP = exts.has('.php');\n  const hasHTML = exts.has('.html') || exts.has('.htm');\n\n  if (hasTS && config.dependencies) return 'node-ts';\n  if (hasJS && config.dependencies) return 'node-js';\n  if (hasPy) return 'python';\n  if (hasGo) return 'go';\n  if (hasRust) return 'rust';\n  if (hasJava) return 'java';\n  if (hasRuby) return 'ruby';\n  if (hasPHP) return 'php';\n  if (hasHTML && !config.dependencies) return 'static-html';\n  if (hasJS && !config.dependencies) return 'static-html'; // vanilla JS without package.json\n  return 'unknown';\n}\n\n// ---------------------------------------------------------------------------\n// Format for injection\n// ---------------------------------------------------------------------------\n\nfunction formatContextSummary(\n  root: string,\n  techStack: TechStack,\n  files: FileEntry[],\n  config: ProjectConfig\n): string {\n  const lines: string[] = [];\n  lines.push(`## Project Context (auto-detected, frozen at session start)`);\n  lines.push(`- **Root**: ${root}`);\n  lines.push(`- **Tech stack**: ${techStack}`);\n  lines.push(`- **Files scanned**: ${files.length}`);\n\n  if (config.name) lines.push(`- **Package**: ${config.name}`);\n  if (config.packageManager) lines.push(`- **Package manager**: ${config.packageManager}`);\n  if (config.tsconfig) lines.push(`- **TypeScript**: yes (tsconfig.json present)`);\n\n  // Key dependencies\n  const allDeps = { ...config.dependencies, ...config.devDependencies };\n  const importantDeps = Object.keys(allDeps).filter(d =>\n    ['react', 'vue', 'svelte', 'angular', 'next', 'nuxt', 'express', 'fastify', 'hono',\n     'tailwindcss', 'prisma', 'drizzle', 'mongoose', 'sequelize', 'jest', 'vitest', 'mocha',\n     'webpack', 'vite', 'esbuild', 'rollup', 'turbo'].includes(d)\n  );\n  if (importantDeps.length > 0) {\n    lines.push(`- **Key deps**: ${importantDeps.join(', ')}`);\n  }\n\n  // Tech stack constraints\n  const constraints: string[] = [];\n  if (techStack === 'static-html') {\n    constraints.push('This is a static HTML/CSS/JS project. Do NOT use require(), import/export, or Node.js APIs.');\n    constraints.push('Do NOT create package.json or node_modules. Keep all JS in <script> tags or vanilla .js files.');\n  }\n  if (techStack === 'node-ts') {\n    constraints.push('This is a TypeScript project. Use .ts extensions, type annotations, and import/export syntax.');\n  }\n  if (techStack === 'node-js') {\n    constraints.push('This is a Node.js JavaScript project. Check existing files for module style (ESM vs CJS) before writing new code.');\n  }\n\n  if (constraints.length > 0) {\n    lines.push(`\\n### Constraints`);\n    for (const c of constraints) lines.push(`- ${c}`);\n  }\n\n  // Directory structure (top-level only)\n  const dirs = files.filter(f => f.type === 'dir').map(f => f.path).sort();\n  if (dirs.length > 0) {\n    lines.push(`\\n### Directory Structure`);\n    lines.push('```');\n    for (const d of dirs.slice(0, 30)) lines.push(`  ${d}/`);\n    lines.push('```');\n  }\n\n  return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Singleton cache\n// ---------------------------------------------------------------------------\n\nlet _cachedContext: ProjectContext | null = null;\n\nexport async function getProjectContext(projectRoot: string): Promise<ProjectContext> {\n  if (_cachedContext && _cachedContext.root === projectRoot) return _cachedContext;\n  _cachedContext = await buildProjectContext(projectRoot);\n  return _cachedContext;\n}\n\nexport function clearProjectContextCache(): void {\n  _cachedContext = null;\n}\n", "import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport type { LocalExecutor } from './local.js';\n\nexport interface ReviewIssue {\n  severity: 'low' | 'medium' | 'high';\n  problem: string;\n  requiredFix: string;\n}\n\nexport interface ReviewResult {\n  approved: boolean;\n  severity: 'low' | 'medium' | 'high';\n  summary: string;\n  issues: ReviewIssue[];\n  model?: string;\n  cost: number;\n  raw: string;\n}\n\nexport interface ReviewInput {\n  executor: LocalExecutor;\n  model?: string;\n  sessionId?: string;\n  projectDir: string;\n  projectContextSummary?: string;\n  workUnitId: string;\n  persona: string;\n  taskGoal: string;\n  workerOutput: string;\n  filesChanged: string[];\n  verification: string[];\n  shellResults?: Array<{ command: string; exitCode: number; output: string }>;\n  stagedContentForPath?: (filePath: string) => string | undefined;\n}\n\nasync function loadFileSnippets(input: ReviewInput): Promise<string> {\n  const snippets: string[] = [];\n  let chars = 0;\n  const limit = Number(process.env.CREW_L3_REVIEW_SNIPPET_CHARS || 6000);\n\n  for (const relPath of input.filesChanged.slice(0, 4)) {\n    try {\n      const staged = input.stagedContentForPath?.(relPath);\n      const content = staged ?? await readFile(resolve(input.projectDir, relPath), 'utf8');\n      const trimmed = content.slice(0, 1800);\n      if (chars + trimmed.length > limit) break;\n      snippets.push(`## ${relPath}\\n\\`\\`\\`\\n${trimmed}\\n\\`\\`\\``);\n      chars += trimmed.length;\n    } catch {\n      // Best-effort review context only.\n    }\n  }\n\n  return snippets.join('\\n\\n');\n}\n\nfunction normalizeSeverity(raw: unknown): 'low' | 'medium' | 'high' {\n  const value = String(raw || '').trim().toLowerCase();\n  if (value === 'high' || value === 'medium' || value === 'low') return value;\n  return 'low';\n}\n\nexport async function reviewWorkerExecution(input: ReviewInput): Promise<ReviewResult> {\n  const fileSnippets = await loadFileSnippets(input);\n  const prompt = [\n    'Review this worker result for correctness against the requested task.',\n    'Focus on implementation bugs, stack mismatches, obvious regressions, missing requirements, and unsafe changes.',\n    'Prefer concrete issues over style feedback.',\n    '',\n    input.projectContextSummary ? `Project context:\\n${input.projectContextSummary}` : '',\n    `Work unit: ${input.workUnitId}`,\n    `Persona: ${input.persona}`,\n    `Task:\\n${input.taskGoal}`,\n    '',\n    `Files changed: ${input.filesChanged.join(', ') || '(none)'}`,\n    `Verification: ${input.verification.join(' | ') || '(none)'}`,\n    `Shell results: ${JSON.stringify(input.shellResults || [])}`,\n    '',\n    `Worker output:\\n${input.workerOutput}`,\n    '',\n    fileSnippets ? `Changed file snippets:\\n${fileSnippets}` : '',\n    '',\n    'Return ONLY valid JSON:',\n    '{',\n    '  \"approved\": true,',\n    '  \"severity\": \"low|medium|high\",',\n    '  \"summary\": \"short summary\",',\n    '  \"issues\": [',\n    '    {',\n    '      \"severity\": \"low|medium|high\",',\n    '      \"problem\": \"what is wrong\",',\n    '      \"requiredFix\": \"specific fix guidance\"',\n    '    }',\n    '  ]',\n    '}',\n    '',\n    'Approve when the code appears correct and aligned with the task. Reject if there are concrete defects or requirement misses.'\n  ].filter(Boolean).join('\\n');\n\n  const result = await input.executor.execute(prompt, {\n    model: input.model,\n    temperature: 0,\n    maxTokens: 1800,\n    jsonMode: true,\n    sessionId: input.sessionId\n  });\n\n  const raw = String(result.result || '').trim();\n  try {\n    const parsed = JSON.parse(raw);\n    const issues = Array.isArray(parsed.issues)\n      ? parsed.issues.map((issue: Record<string, unknown>) => ({\n          severity: normalizeSeverity(issue?.severity),\n          problem: String(issue?.problem || '').trim(),\n          requiredFix: String(issue?.requiredFix || '').trim()\n        })).filter((issue: ReviewIssue) => issue.problem && issue.requiredFix)\n      : [];\n\n    return {\n      approved: Boolean(parsed.approved),\n      severity: normalizeSeverity(parsed.severity),\n      summary: String(parsed.summary || '').trim() || (issues.length === 0 ? 'Approved' : 'Issues found'),\n      issues,\n      model: result.model,\n      cost: Number(result.costUsd || 0),\n      raw\n    };\n  } catch {\n    const lower = raw.toLowerCase();\n    const approved = lower.includes('approved') && !lower.includes('not approved') && !lower.includes('reject');\n    return {\n      approved,\n      severity: approved ? 'low' : 'medium',\n      summary: approved ? 'Reviewer returned non-JSON approval text' : 'Reviewer returned non-JSON rejection text',\n      issues: approved ? [] : [{\n        severity: 'medium',\n        problem: 'Reviewer response was not valid JSON.',\n        requiredFix: 'Re-run review or inspect the worker output manually.'\n      }],\n      model: result.model,\n      cost: Number(result.costUsd || 0),\n      raw\n    };\n  }\n}\n", "/**\n * Delegation Tuning \u2014 Choose the right persona/model for each task.\n *\n * When the pipeline decomposes work into units, delegation tuning selects\n * the optimal persona and model based on:\n *   - Task characteristics (file types, complexity, scope)\n *   - Historical performance (which persona/model succeeded on similar tasks)\n *   - Cost/speed tradeoffs (use cheap models for simple tasks)\n *   - Failure avoidance (don't assign a persona that recently failed similar work)\n *\n * This is deterministic scoring \u2014 no LLM call. It augments the L2 planner's\n * persona assignments with empirical tuning data.\n */\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface DelegationCandidate {\n  persona: string;\n  model: string;\n  score: number;\n  reasons: string[];\n}\n\nexport interface TaskCharacteristics {\n  /** Primary language/framework (e.g., 'typescript', 'react', 'python') */\n  language?: string;\n  /** File paths involved */\n  files: string[];\n  /** Task description */\n  description: string;\n  /** Estimated complexity */\n  complexity: 'low' | 'medium' | 'high';\n  /** Required capabilities */\n  capabilities: string[];\n  /** Task type derived from description */\n  taskType: TaskType;\n}\n\nexport type TaskType =\n  | 'create-file'       // New file from scratch\n  | 'edit-existing'     // Modify existing code\n  | 'fix-bug'           // Debug and fix\n  | 'add-test'          // Write tests\n  | 'refactor'          // Restructure without behavior change\n  | 'review'            // Code review / QA\n  | 'docs'              // Documentation\n  | 'config'            // Configuration / build setup\n  | 'research'          // Read and understand code\n  | 'mixed';            // Multiple types\n\nexport interface PerformanceRecord {\n  persona: string;\n  model: string;\n  taskType: TaskType;\n  success: boolean;\n  turns: number;\n  costUsd: number;\n  verificationPassed: boolean;\n  timestamp: number;\n}\n\n// ---------------------------------------------------------------------------\n// Persona registry \u2014 what each persona is good at\n// ---------------------------------------------------------------------------\n\ninterface PersonaProfile {\n  id: string;\n  strengths: TaskType[];\n  languages: string[];\n  /** Cost tier: cheaper personas for simpler tasks */\n  costTier: 'fast' | 'standard' | 'heavy';\n  /** Max complexity this persona should handle */\n  maxComplexity: 'low' | 'medium' | 'high';\n}\n\nconst PERSONA_PROFILES: PersonaProfile[] = [\n  {\n    id: 'executor-code',\n    strengths: ['create-file', 'edit-existing', 'fix-bug', 'refactor', 'mixed'],\n    languages: ['typescript', 'javascript', 'python', 'go', 'rust'],\n    costTier: 'standard',\n    maxComplexity: 'high'\n  },\n  {\n    id: 'crew-coder',\n    strengths: ['create-file', 'edit-existing', 'mixed'],\n    languages: ['typescript', 'javascript', 'python', 'go', 'rust', 'java'],\n    costTier: 'standard',\n    maxComplexity: 'high'\n  },\n  {\n    id: 'crew-coder-back',\n    strengths: ['create-file', 'edit-existing', 'fix-bug', 'config'],\n    languages: ['typescript', 'javascript', 'python', 'go', 'rust', 'sql'],\n    costTier: 'standard',\n    maxComplexity: 'high'\n  },\n  {\n    id: 'crew-coder-front',\n    strengths: ['create-file', 'edit-existing', 'refactor'],\n    languages: ['typescript', 'javascript', 'css', 'html', 'react', 'vue'],\n    costTier: 'standard',\n    maxComplexity: 'medium'\n  },\n  {\n    id: 'crew-qa',\n    strengths: ['add-test', 'review'],\n    languages: ['typescript', 'javascript', 'python'],\n    costTier: 'fast',\n    maxComplexity: 'medium'\n  },\n  {\n    id: 'crew-fixer',\n    strengths: ['fix-bug', 'edit-existing'],\n    languages: ['typescript', 'javascript', 'python', 'go'],\n    costTier: 'standard',\n    maxComplexity: 'high'\n  },\n  {\n    id: 'crew-copywriter',\n    strengths: ['docs'],\n    languages: ['markdown'],\n    costTier: 'fast',\n    maxComplexity: 'low'\n  },\n  {\n    id: 'crew-security',\n    strengths: ['review', 'fix-bug'],\n    languages: ['typescript', 'javascript', 'python', 'go'],\n    costTier: 'standard',\n    maxComplexity: 'high'\n  }\n];\n\n// ---------------------------------------------------------------------------\n// Task analysis\n// ---------------------------------------------------------------------------\n\nexport function analyzeTask(description: string, files: string[], capabilities: string[] = []): TaskCharacteristics {\n  const lower = description.toLowerCase();\n  const taskType = detectTaskType(lower);\n  const language = detectLanguage(files);\n  const complexity = estimateComplexity(lower, files);\n\n  return {\n    language,\n    files,\n    description,\n    complexity,\n    capabilities,\n    taskType\n  };\n}\n\nfunction detectTaskType(desc: string): TaskType {\n  // Order matters: domain-specific patterns before generic action words.\n  // \"write documentation\" should be docs, not edit-existing.\n  // \"add tests\" should be add-test, not edit-existing.\n  if (/\\btest|spec|assert|coverage|jest|mocha|vitest\\b/.test(desc)) return 'add-test';\n  if (/\\b(fix|bug|broken|crash|error|fail|debug)\\b/.test(desc)) return 'fix-bug';\n  if (/\\b(refactor|restructure|reorganize|clean.?up|simplif)\\b/.test(desc)) return 'refactor';\n  if (/\\b(review|audit|check|inspect|securit)\\b/.test(desc)) return 'review';\n  if (/\\b(docs?|document(ation)?|readme|guide|tutorial)\\b/.test(desc)) return 'docs';\n  if (/\\b(config|setup|install|deploy|docker|ci|cd)\\b/.test(desc)) return 'config';\n  if (/\\b(read|understand|explore|investigate|research|analyz)\\b/.test(desc)) return 'research';\n  if (/\\b(create|add|new|implement|build|write)\\b/.test(desc)) {\n    if (/\\b(new file|new component|from scratch|create)\\b/.test(desc)) return 'create-file';\n    return 'edit-existing';\n  }\n  return 'mixed';\n}\n\nfunction detectLanguage(files: string[]): string | undefined {\n  const extensions = files\n    .map(f => f.split('.').pop()?.toLowerCase())\n    .filter(Boolean) as string[];\n\n  const extMap: Record<string, string> = {\n    ts: 'typescript', tsx: 'typescript',\n    js: 'javascript', jsx: 'javascript', mjs: 'javascript',\n    py: 'python',\n    go: 'go',\n    rs: 'rust',\n    java: 'java',\n    css: 'css',\n    html: 'html',\n    md: 'markdown',\n    sql: 'sql'\n  };\n\n  const counts = new Map<string, number>();\n  for (const ext of extensions) {\n    const lang = extMap[ext] || ext;\n    counts.set(lang, (counts.get(lang) || 0) + 1);\n  }\n\n  if (counts.size === 0) return undefined;\n  return [...counts.entries()].sort((a, b) => b[1] - a[1])[0][0];\n}\n\nfunction estimateComplexity(desc: string, files: string[]): 'low' | 'medium' | 'high' {\n  let score = 0;\n  if (files.length > 5) score += 2;\n  else if (files.length > 2) score += 1;\n\n  if (desc.length > 500) score += 1;\n  if (/\\b(architect|system|migration|overhaul|redesign)\\b/.test(desc)) score += 2;\n  if (/\\b(simple|small|minor|quick|trivial)\\b/.test(desc)) score -= 1;\n  if (/\\b(complex|large|major|significant)\\b/.test(desc)) score += 1;\n\n  if (score >= 3) return 'high';\n  if (score >= 1) return 'medium';\n  return 'low';\n}\n\n// ---------------------------------------------------------------------------\n// Delegation scoring\n// ---------------------------------------------------------------------------\n\nexport class DelegationTuner {\n  private performanceHistory: PerformanceRecord[] = [];\n\n  /**\n   * Record a completed task's performance for future delegation decisions.\n   */\n  recordPerformance(record: PerformanceRecord): void {\n    this.performanceHistory.push(record);\n    // Keep last 200 records\n    if (this.performanceHistory.length > 200) {\n      this.performanceHistory = this.performanceHistory.slice(-200);\n    }\n  }\n\n  /**\n   * Rank personas for a given task, returning scored candidates.\n   */\n  rankCandidates(task: TaskCharacteristics): DelegationCandidate[] {\n    const candidates: DelegationCandidate[] = [];\n\n    for (const profile of PERSONA_PROFILES) {\n      const { score, reasons } = this.scorePersona(profile, task);\n      if (score > 0) {\n        candidates.push({\n          persona: profile.id,\n          model: this.recommendModel(profile, task),\n          score,\n          reasons\n        });\n      }\n    }\n\n    return candidates.sort((a, b) => b.score - a.score);\n  }\n\n  /**\n   * Get the best persona for a task.\n   */\n  bestCandidate(task: TaskCharacteristics): DelegationCandidate | null {\n    const ranked = this.rankCandidates(task);\n    return ranked[0] || null;\n  }\n\n  private scorePersona(profile: PersonaProfile, task: TaskCharacteristics): { score: number; reasons: string[] } {\n    let score = 50; // baseline\n    const reasons: string[] = [];\n\n    // Strength match\n    if (profile.strengths.includes(task.taskType)) {\n      score += 30;\n      reasons.push(`strong at ${task.taskType}`);\n    } else {\n      score -= 10;\n    }\n\n    // Language match\n    if (task.language && profile.languages.includes(task.language)) {\n      score += 15;\n      reasons.push(`knows ${task.language}`);\n    } else if (task.language) {\n      score -= 5;\n    }\n\n    // Complexity match\n    const complexityOrder = { low: 0, medium: 1, high: 2 };\n    if (complexityOrder[task.complexity] > complexityOrder[profile.maxComplexity]) {\n      score -= 20;\n      reasons.push('task may be too complex for this persona');\n    }\n\n    // Cost efficiency\n    if (task.complexity === 'low' && profile.costTier === 'fast') {\n      score += 10;\n      reasons.push('cost-efficient for simple task');\n    }\n    if (task.complexity === 'high' && profile.costTier === 'heavy') {\n      score += 5;\n      reasons.push('heavy-tier appropriate for complex task');\n    }\n\n    // Historical performance\n    const history = this.performanceHistory.filter(\n      r => r.persona === profile.id && r.taskType === task.taskType\n    );\n    if (history.length >= 3) {\n      const successRate = history.filter(r => r.success).length / history.length;\n      if (successRate >= 0.8) {\n        score += 15;\n        reasons.push(`${Math.round(successRate * 100)}% success rate on similar tasks`);\n      } else if (successRate < 0.5) {\n        score -= 15;\n        reasons.push(`low success rate (${Math.round(successRate * 100)}%) on similar tasks`);\n      }\n\n      const avgTurns = history.reduce((s, r) => s + r.turns, 0) / history.length;\n      if (avgTurns < 10) {\n        score += 5;\n        reasons.push('historically efficient (few turns)');\n      }\n    }\n\n    // Recent failures on same persona \u2014 avoid\n    const recentFailures = history\n      .filter(r => !r.success && Date.now() - r.timestamp < 3600_000)\n      .length;\n    if (recentFailures >= 2) {\n      score -= 20;\n      reasons.push('recent repeated failures \u2014 try different persona');\n    }\n\n    return { score: Math.max(0, score), reasons };\n  }\n\n  private recommendModel(profile: PersonaProfile, task: TaskCharacteristics): string {\n    // Map cost tier + complexity to model recommendation\n    if (task.complexity === 'high' || profile.costTier === 'heavy') {\n      return 'heavy'; // caller maps to actual model ID\n    }\n    if (task.complexity === 'low' && profile.costTier === 'fast') {\n      return 'fast';\n    }\n    return 'standard';\n  }\n\n  /**\n   * Export performance data for persistence.\n   */\n  exportHistory(): PerformanceRecord[] {\n    return [...this.performanceHistory];\n  }\n\n  /**\n   * Import performance data from persistence.\n   */\n  importHistory(records: PerformanceRecord[]): void {\n    this.performanceHistory = [...records];\n  }\n}\n", "/**\n * Direct File Command Parser for crew-cli\n * \n * Adds support for @@WRITE_FILE...@@END_FILE syntax similar to\n * OpenCode/Codex/Gemini CLI protocols.\n * \n * Usage:\n *   crew chat \"@@WRITE_FILE hello.txt\n *   Hello World\n *   @@END_FILE\"\n */\n\nexport interface FileCommand {\n  type: 'write' | 'mkdir' | 'delete';\n  path: string;\n  content?: string;\n}\n\n/**\n * Parse @@WRITE_FILE...@@END_FILE blocks from input\n */\nexport function parseDirectFileCommands(input: string): FileCommand[] {\n  const commands: FileCommand[] = [];\n  \n  // Match @@WRITE_FILE path\\ncontent\\n@@END_FILE\n  const writeFileRegex = /@@WRITE_FILE\\s+([^\\n]+)\\n([\\s\\S]*?)@@END_FILE/g;\n  \n  let match;\n  while ((match = writeFileRegex.exec(input)) !== null) {\n    const path = match[1].trim();\n    const content = match[2] || '';\n    \n    commands.push({\n      type: 'write',\n      path,\n      content\n    });\n  }\n  \n  // Match @@MKDIR path\n  const mkdirRegex = /@@MKDIR\\s+([^\\n]+)/g;\n  while ((match = mkdirRegex.exec(input)) !== null) {\n    commands.push({\n      type: 'mkdir',\n      path: match[1].trim()\n    });\n  }\n  \n  return commands;\n}\n\n/**\n * Parse write: syntax (OpenCode/Codex style)\n * Format: write: path/to/file.txt\n * Content follows on next lines until next command or EOF\n */\nexport function parseWriteSyntax(input: string): FileCommand[] {\n  const commands: FileCommand[] = [];\n  const lines = input.split('\\n');\n  \n  let i = 0;\n  while (i < lines.length) {\n    const line = lines[i].trim();\n    \n    if (line.startsWith('write:')) {\n      const path = line.substring(6).trim();\n      const contentLines: string[] = [];\n      \n      i++;\n      // Collect content until next command or EOF\n      while (i < lines.length) {\n        const nextLine = lines[i];\n        if (nextLine.trim().match(/^(write:|mkdir:|delete:|@@\\w+)/)) {\n          break;\n        }\n        contentLines.push(nextLine);\n        i++;\n      }\n      \n      commands.push({\n        type: 'write',\n        path,\n        content: contentLines.join('\\n')\n      });\n    } else if (line.startsWith('mkdir:')) {\n      commands.push({\n        type: 'mkdir',\n        path: line.substring(6).trim()\n      });\n      i++;\n    } else {\n      i++;\n    }\n  }\n  \n  return commands;\n}\n\n/**\n * Remove direct command blocks from input (for LLM processing)\n */\nexport function stripDirectCommands(input: string): string {\n  let stripped = input;\n  \n  // Remove @@WRITE_FILE...@@END_FILE blocks\n  stripped = stripped.replace(/@@WRITE_FILE\\s+[^\\n]+\\n[\\s\\S]*?@@END_FILE/g, '');\n  \n  // Remove @@MKDIR commands\n  stripped = stripped.replace(/@@MKDIR\\s+[^\\n]+/g, '');\n  \n  // Remove write:/mkdir: blocks\n  stripped = stripped.replace(/^(write|mkdir):\\s+[^\\n]+(\\n(?!write:|mkdir:|@@)[^\\n]*)*$/gm, '');\n  \n  return stripped.trim();\n}\n\n/**\n * Check if input contains any direct commands\n */\nexport function hasDirectCommands(input: string): boolean {\n  return /@@WRITE_FILE|@@MKDIR|^write:|^mkdir:/m.test(input);\n}\n\n/**\n * Execute direct commands using sandbox\n */\nexport async function executeDirectCommands(\n  commands: FileCommand[],\n  sandbox: { addChange(path: string, content: string): Promise<void> },\n  logger?: { info(msg: string): void; error?(msg: string): void }\n): Promise<string[]> {\n  const appliedFiles: string[] = [];\n  \n  for (const cmd of commands) {\n    try {\n      if (cmd.type === 'write') {\n        await sandbox.addChange(cmd.path, cmd.content || '');\n        appliedFiles.push(cmd.path);\n        logger?.info(`Staged: ${cmd.path}`);\n      } else if (cmd.type === 'mkdir') {\n        // For mkdir, we can create an empty .gitkeep file\n        const keepPath = `${cmd.path}/.gitkeep`;\n        await sandbox.addChange(keepPath, '');\n        appliedFiles.push(keepPath);\n        logger?.info(`Created directory: ${cmd.path}`);\n      }\n    } catch (err) {\n      logger?.error?.(`Failed to stage ${cmd.path}: ${(err as Error).message}`);\n    }\n  }\n  \n  return appliedFiles;\n}\n\n/**\n * Example usage in crew chat command:\n * \n * ```typescript\n * const directCommands = [\n *   ...parseDirectFileCommands(input),\n *   ...parseWriteSyntax(input)\n * ];\n * \n * if (directCommands.length > 0) {\n *   const appliedFiles = await executeDirectCommands(\n *     directCommands,\n *     sandbox,\n *     logger\n *   );\n *   \n *   // Strip direct commands from input before LLM call\n *   const llmInput = stripDirectCommands(input);\n *   \n *   if (llmInput) {\n *     // Continue with LLM for remaining natural language\n *   } else {\n *     // Pure direct commands, no LLM needed\n *     return { appliedFiles, response: `Staged ${appliedFiles.length} files` };\n *   }\n * }\n * ```\n */\n", "/**\n * Codebase RAG - Auto-load relevant files for LLM context\n *\n * Three modes:\n * 1. Keyword-based (fast, local, no cost)\n * 2. Import graph (smarter, local, no cost)\n * 3. Semantic (best, requires embeddings API or uses local hashed vectors)\n *\n * CodebaseIndex: persistent, incremental embedding index that auto-builds\n * in the background on startup and re-embeds only changed files.\n */\n\nimport { execSync } from 'node:child_process';\nimport { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { relative, join } from 'node:path';\nimport { buildRepositoryGraph } from '../mapping/index.js';\nimport type { RepositoryGraph } from '../mapping/index.js';\n\nexport type RagMode = 'keyword' | 'import-graph' | 'semantic' | 'auto' | 'off';\n\nexport interface RagOptions {\n  mode?: RagMode;\n  tokenBudget?: number;\n  maxFiles?: number;\n  sessionHistory?: Array<{ output?: string }>;\n  cacheDir?: string;\n}\n\nexport interface RagResult {\n  context: string;\n  filesLoaded: string[];\n  mode: RagMode;\n  tokenEstimate: number;\n}\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction extractKeywords(query: string): string[] {\n  return (query\n    .toLowerCase()\n    .match(/\\b[a-z]{3,}\\b/g) || [])\n    .filter(kw => !STOP_WORDS.has(kw));\n}\n\nconst STOP_WORDS = new Set([\n  'the', 'and', 'for', 'with', 'this', 'that', 'from', 'are', 'was', 'were',\n  'will', 'can', 'could', 'should', 'would', 'add', 'create', 'make', 'write',\n  'update', 'fix', 'change', 'modify', 'delete', 'remove', 'get', 'set'\n]);\n\nfunction contentHash(content: string): string {\n  return createHash('sha256').update(content).digest('hex').slice(0, 16);\n}\n\n// \u2500\u2500 Local hashed vector (zero-cost fallback) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction toHashedVector(text: string, dim = 256): Float64Array {\n  const vec = new Float64Array(dim);\n  const tokens = text.toLowerCase().split(/\\W+/).filter(t => t.length > 2);\n  for (const token of tokens) {\n    let h = 0;\n    for (let i = 0; i < token.length; i++) {\n      h = ((h << 5) - h + token.charCodeAt(i)) | 0;\n    }\n    const idx = ((h % dim) + dim) % dim;\n    vec[idx] += 1;\n  }\n  // L2 normalize\n  let norm = 0;\n  for (let i = 0; i < dim; i++) norm += vec[i] * vec[i];\n  norm = Math.sqrt(norm) || 1;\n  for (let i = 0; i < dim; i++) vec[i] /= norm;\n  return vec;\n}\n\nfunction cosineSimilarity(a: number[] | Float64Array, b: number[] | Float64Array): number {\n  if (a.length !== b.length) return 0;\n  let dot = 0, na = 0, nb = 0;\n  for (let i = 0; i < a.length; i++) {\n    dot += a[i] * b[i];\n    na += a[i] * a[i];\n    nb += b[i] * b[i];\n  }\n  return dot / (Math.sqrt(na) * Math.sqrt(nb) || 1);\n}\n\n// \u2500\u2500 Embedding providers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ntype EmbeddingProvider = 'openai' | 'gemini' | 'local';\n\nfunction detectEmbeddingProvider(): EmbeddingProvider {\n  const explicit = String(process.env.CREW_EMBEDDING_PROVIDER || '').toLowerCase();\n  if (explicit === 'openai' || explicit === 'gemini' || explicit === 'local') return explicit;\n  if (process.env.OPENAI_API_KEY) return 'openai';\n  if (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY) return 'gemini';\n  return 'local';\n}\n\nasync function generateEmbedding(text: string, provider?: EmbeddingProvider): Promise<number[]> {\n  const p = provider || detectEmbeddingProvider();\n\n  if (p === 'openai') {\n    const apiKey = process.env.OPENAI_API_KEY;\n    if (!apiKey) throw new Error('OPENAI_API_KEY not set');\n    const response = await fetch('https://api.openai.com/v1/embeddings', {\n      method: 'POST',\n      headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },\n      body: JSON.stringify({ model: 'text-embedding-3-small', input: text.slice(0, 8000) })\n    });\n    if (!response.ok) throw new Error(`OpenAI embedding failed: ${response.statusText}`);\n    const data = await response.json();\n    return (data as { data: Array<{ embedding: number[] }> }).data[0].embedding;\n  }\n\n  if (p === 'gemini') {\n    const apiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;\n    if (!apiKey) throw new Error('GEMINI_API_KEY not set');\n    const response = await fetch(\n      `https://generativelanguage.googleapis.com/v1beta/models/text-embedding-004:embedContent?key=${apiKey}`,\n      {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({\n          model: 'models/text-embedding-004',\n          content: { parts: [{ text: text.slice(0, 8000) }] }\n        })\n      }\n    );\n    if (!response.ok) throw new Error(`Gemini embedding failed: ${response.statusText}`);\n    const data = await response.json();\n    return (data as { embedding?: { values?: number[] } }).embedding?.values || [];\n  }\n\n  // Local: hashed vector (zero-cost, ~80% as good for code search)\n  return Array.from(toHashedVector(text));\n}\n\n// \u2500\u2500 CodebaseIndex (persistent, incremental) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface IndexEntry {\n  file: string;\n  embedding: number[];\n  hash: string;\n}\n\ninterface IndexMeta {\n  provider: EmbeddingProvider;\n  dim: number;\n  fileCount: number;\n  lastUpdated: string;\n}\n\nexport class CodebaseIndex {\n  private cwd: string;\n  private cacheDir: string;\n  private entries: IndexEntry[] = [];\n  private entryMap = new Map<string, IndexEntry>();\n  private meta: IndexMeta | null = null;\n  private loaded = false;\n  private building = false;\n  private provider: EmbeddingProvider;\n\n  private static instances = new Map<string, CodebaseIndex>();\n\n  static getInstance(cwd: string): CodebaseIndex {\n    const existing = CodebaseIndex.instances.get(cwd);\n    if (existing) return existing;\n    const inst = new CodebaseIndex(cwd);\n    CodebaseIndex.instances.set(cwd, inst);\n    return inst;\n  }\n\n  private constructor(cwd: string) {\n    this.cwd = cwd;\n    this.cacheDir = join(cwd, '.crew', 'rag-cache');\n    this.provider = detectEmbeddingProvider();\n  }\n\n  private indexPath() { return join(this.cacheDir, 'embeddings.json'); }\n  private metaPath() { return join(this.cacheDir, 'index-meta.json'); }\n\n  /** Load index from disk if not already loaded. */\n  async load(): Promise<void> {\n    if (this.loaded) return;\n    try {\n      if (existsSync(this.indexPath())) {\n        const raw = await readFile(this.indexPath(), 'utf8');\n        this.entries = JSON.parse(raw);\n        this.entryMap.clear();\n        for (const e of this.entries) this.entryMap.set(e.file, e);\n      }\n      if (existsSync(this.metaPath())) {\n        this.meta = JSON.parse(await readFile(this.metaPath(), 'utf8'));\n      }\n    } catch { /* corrupt index \u2014 will rebuild */ }\n    this.loaded = true;\n  }\n\n  /** Save index to disk. */\n  private async save(): Promise<void> {\n    await mkdir(this.cacheDir, { recursive: true });\n    await writeFile(this.indexPath(), JSON.stringify(this.entries), 'utf8');\n    this.meta = {\n      provider: this.provider,\n      dim: this.entries[0]?.embedding.length || 0,\n      fileCount: this.entries.length,\n      lastUpdated: new Date().toISOString()\n    };\n    await writeFile(this.metaPath(), JSON.stringify(this.meta, null, 2), 'utf8');\n  }\n\n  /** List code files in the repo (respects .gitignore). */\n  private listFiles(): string[] {\n    try {\n      const maxFiles = Number(process.env.CREW_RAG_MAX_FILES || 2000);\n      const stdout = execSync(\n        `rg --files --type-add 'code:*.{ts,js,tsx,jsx,py,go,rs,java,rb,php,c,cpp,h,hpp,cs,swift,kt,scala,lua,sh,bash,zsh,sql,proto,graphql,vue,svelte}' -t code`,\n        { cwd: this.cwd, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, stdio: ['pipe', 'pipe', 'ignore'] }\n      );\n      return stdout.trim().split('\\n').filter(Boolean).slice(0, maxFiles);\n    } catch {\n      return [];\n    }\n  }\n\n  /**\n   * Ensure the index is built and up-to-date. Incrementally re-embeds only changed files.\n   * Safe to call from background \u2014 non-blocking if already building.\n   */\n  async ensureIndex(opts?: { onProgress?: (done: number, total: number) => void }): Promise<{ indexed: number; skipped: number; removed: number }> {\n    if (this.building) return { indexed: 0, skipped: 0, removed: 0 };\n    this.building = true;\n\n    try {\n      await this.load();\n\n      const files = this.listFiles();\n      if (files.length === 0) return { indexed: 0, skipped: 0, removed: 0 };\n\n      // If provider changed, invalidate entire index\n      if (this.meta && this.meta.provider !== this.provider) {\n        this.entries = [];\n        this.entryMap.clear();\n      }\n\n      const currentFiles = new Set(files);\n      let indexed = 0;\n      let skipped = 0;\n\n      // Remove entries for deleted files\n      const removed = this.entries.filter(e => !currentFiles.has(e.file)).length;\n      this.entries = this.entries.filter(e => currentFiles.has(e.file));\n      this.entryMap.clear();\n      for (const e of this.entries) this.entryMap.set(e.file, e);\n\n      // Process files \u2014 skip unchanged (same content hash)\n      const batchSize = Number(process.env.CREW_RAG_BATCH_SIZE || 20);\n      for (let i = 0; i < files.length; i += batchSize) {\n        const batch = files.slice(i, i + batchSize);\n\n        const work: Array<{ file: string; content: string; hash: string }> = [];\n        for (const file of batch) {\n          try {\n            const content = await readFile(join(this.cwd, file), 'utf8');\n            if (content.length < 10) continue; // skip near-empty files\n            if (content.length > 100_000) continue; // skip massive generated files\n            const hash = contentHash(content);\n            const existing = this.entryMap.get(file);\n            if (existing && existing.hash === hash) {\n              skipped++;\n              continue;\n            }\n            work.push({ file, content, hash });\n          } catch { /* skip unreadable */ }\n        }\n\n        // Embed in parallel (up to batchSize concurrently)\n        const results = await Promise.allSettled(\n          work.map(async ({ file, content, hash }) => {\n            const embedding = await generateEmbedding(content, this.provider);\n            return { file, embedding, hash };\n          })\n        );\n\n        for (const result of results) {\n          if (result.status === 'fulfilled') {\n            const entry = result.value;\n            // Update or insert\n            const existing = this.entryMap.get(entry.file);\n            if (existing) {\n              existing.embedding = entry.embedding;\n              existing.hash = entry.hash;\n            } else {\n              this.entries.push(entry);\n              this.entryMap.set(entry.file, entry);\n            }\n            indexed++;\n          }\n        }\n\n        opts?.onProgress?.(Math.min(i + batchSize, files.length), files.length);\n      }\n\n      // Save if anything changed\n      if (indexed > 0 || removed > 0) {\n        await this.save();\n      }\n\n      return { indexed, skipped, removed };\n    } finally {\n      this.building = false;\n    }\n  }\n\n  /** Query the index for files most relevant to a query string. */\n  async query(query: string, topK = 10): Promise<Array<{ file: string; score: number }>> {\n    await this.load();\n    if (this.entries.length === 0) return [];\n\n    const queryEmb = await generateEmbedding(query, this.provider);\n    const scored = this.entries.map(entry => ({\n      file: entry.file,\n      score: cosineSimilarity(queryEmb, entry.embedding)\n    }));\n    scored.sort((a, b) => b.score - a.score);\n    return scored.slice(0, topK);\n  }\n\n  /** Get index stats. */\n  stats(): { files: number; provider: string; lastUpdated: string | null; building: boolean } {\n    return {\n      files: this.entries.length,\n      provider: this.provider,\n      lastUpdated: this.meta?.lastUpdated || null,\n      building: this.building\n    };\n  }\n\n  isReady(): boolean {\n    return this.loaded && this.entries.length > 0 && !this.building;\n  }\n}\n\n// \u2500\u2500 Phase 1: Keyword-based file matching \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function keywordBasedSearch(\n  query: string,\n  cwd: string,\n  options: RagOptions\n): Promise<Array<{ file: string; score: number }>> {\n  const keywords = extractKeywords(query);\n  if (keywords.length === 0) return [];\n\n  try {\n    const pattern = keywords.slice(0, 5).join('|');\n    const stdout = execSync(\n      `rg -l \"${pattern}\" --type-add 'code:*.{ts,js,tsx,jsx,py,go,rs,java}' -t code`,\n      { cwd, encoding: 'utf8', maxBuffer: 1024 * 1024, stdio: ['pipe', 'pipe', 'ignore'] }\n    );\n\n    const files = stdout.trim().split('\\n').filter(Boolean);\n    return files.map(file => {\n      let score = 0;\n      const lowerFile = file.toLowerCase();\n      for (const kw of keywords) {\n        if (lowerFile.includes(kw)) score += 2;\n      }\n      for (const entry of options.sessionHistory || []) {\n        if (entry.output?.includes(file)) score += 3;\n      }\n      return { file, score };\n    });\n  } catch {\n    return [];\n  }\n}\n\n// \u2500\u2500 Phase 2: Import graph expansion \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function expandWithImports(\n  files: string[],\n  cwd: string,\n  maxDepth: number = 1\n): Promise<Set<string>> {\n  const expanded = new Set<string>(files);\n  try {\n    const graph = await buildRepositoryGraph(cwd);\n    for (const file of files) {\n      const node = graph.nodes.find(n => n.path === file || join(cwd, n.path) === file);\n      if (node) {\n        for (const importPath of node.imports.slice(0, 5)) expanded.add(importPath);\n        for (const importedByPath of node.importedBy.slice(0, 3)) expanded.add(importedByPath);\n      }\n    }\n  } catch (err) {\n    console.warn('[RAG] Import graph expansion failed:', (err as Error).message);\n  }\n  return expanded;\n}\n\n// \u2500\u2500 Main entry point \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function autoLoadRelevantFiles(\n  query: string,\n  cwd: string,\n  options: RagOptions = {}\n): Promise<RagResult> {\n  const rawMode = options.mode || String(process.env.CREW_RAG_MODE || 'auto').toLowerCase() as RagMode;\n  const tokenBudget = options.tokenBudget || Number(process.env.CREW_RAG_TOKEN_BUDGET || 8000);\n  const maxFiles = options.maxFiles || Number(process.env.CREW_RAG_MAX_FILES_LOAD || 10);\n\n  // Resolve 'auto': use semantic index if available, else keyword\n  let mode: RagMode = rawMode;\n  if (mode === 'auto') {\n    const index = CodebaseIndex.getInstance(cwd);\n    mode = index.isReady() ? 'semantic' : 'keyword';\n  }\n\n  if (mode === 'off') {\n    return { context: '', filesLoaded: [], mode: 'off', tokenEstimate: 0 };\n  }\n\n  let scoredFiles: Array<{ file: string; score: number }> = [];\n\n  if (mode === 'semantic') {\n    try {\n      const index = CodebaseIndex.getInstance(cwd);\n      scoredFiles = await index.query(query, maxFiles * 2);\n    } catch (err) {\n      console.warn('[RAG] Semantic search failed, falling back to keyword:', (err as Error).message);\n      scoredFiles = await keywordBasedSearch(query, cwd, options);\n    }\n  } else {\n    scoredFiles = await keywordBasedSearch(query, cwd, options);\n  }\n\n  if (scoredFiles.length === 0) {\n    return { context: '', filesLoaded: [], mode, tokenEstimate: 0 };\n  }\n\n  // Expand with imports (for import-graph and semantic modes)\n  let filesToLoad = scoredFiles.map(x => x.file);\n  if (mode === 'import-graph' || mode === 'semantic') {\n    const expanded = await expandWithImports(filesToLoad.slice(0, 5), cwd);\n    filesToLoad = Array.from(expanded);\n  }\n\n  // Load files within token budget\n  const loaded: string[] = [];\n  const contextParts: string[] = [];\n  let charsUsed = 0;\n  const charBudget = tokenBudget * 4;\n\n  const originalSet = new Set(scoredFiles.slice(0, 10).map(x => x.file));\n  const finalScored = filesToLoad.map(file => ({\n    file,\n    score: originalSet.has(file) ? 10 : 1\n  }));\n  finalScored.sort((a, b) => b.score - a.score);\n\n  for (const { file } of finalScored.slice(0, maxFiles)) {\n    try {\n      const fullPath = join(cwd, file);\n      const content = await readFile(fullPath, 'utf8');\n      if (charsUsed + content.length > charBudget) break;\n      const relPath = relative(cwd, file);\n      contextParts.push(`\\n=== ${relPath} ===\\n${content}`);\n      loaded.push(relPath);\n      charsUsed += content.length;\n    } catch {\n      // skip unreadable\n    }\n  }\n\n  if (loaded.length === 0) {\n    return { context: '', filesLoaded: [], mode, tokenEstimate: 0 };\n  }\n\n  const context = `## Relevant Codebase Context (${loaded.length} files loaded via ${mode} RAG)\\n${contextParts.join('\\n\\n')}`;\n  const tokenEstimate = Math.ceil(charsUsed / 4);\n\n  return { context, filesLoaded: loaded, mode, tokenEstimate };\n}\n\n/** Check if query should trigger RAG. */\nexport function shouldUseRag(query: string): boolean {\n  const lower = query.toLowerCase();\n  const hasExecutionIntent = /\\b(implement|create|build|write|fix|refactor|modify|update|add|patch|test|debug|investigate|explain|how)\\b/.test(lower);\n  const hasCodeReference = /\\/src\\/|\\.ts\\b|\\.js\\b|\\.tsx\\b|\\.py\\b|\\.go\\b/.test(query);\n  const hasFileOperation = /\\b(file|function|class|component|endpoint|route|middleware|module|service|handler|controller)\\b/.test(lower);\n  return hasExecutionIntent || hasCodeReference || hasFileOperation;\n}\n\n/** Rebuild the entire index (clears cache). */\nexport async function rebuildEmbeddingsIndex(\n  cwd: string,\n  cacheDir?: string\n): Promise<void> {\n  const dir = cacheDir || join(cwd, '.crew', 'rag-cache');\n  const indexPath = join(dir, 'embeddings.json');\n  if (existsSync(indexPath)) {\n    await writeFile(indexPath, '[]', 'utf8');\n  }\n  const index = CodebaseIndex.getInstance(cwd);\n  await index.ensureIndex();\n}\n", "/**\n * Unified 3-Tier Pipeline\n * \n * L1: Chat Interface (REPL/CLI) - User interaction only\n * L2: Router + Reasoner + Planner - Unified orchestration layer\n * L3: Parallel Executors - Specialized workers\n */\n\nimport { LocalExecutor } from '../executor/local.js';\nimport { runAgenticWorker } from '../executor/agentic-executor.js';\nimport { DualL2Planner, WorkGraph, PolicyValidation } from '../prompts/dual-l2.js';\nimport { PromptComposer, PromptOverlay, getTemplateForPersona } from '../prompts/registry.js';\nimport { Logger } from '../utils/logger.js';\nimport { randomUUID } from 'crypto';\nimport { ContextPackManager } from './context-pack.js';\nimport { getPipelineMemory } from './agent-memory.js';\nimport { appendFile, mkdir, readFile } from 'node:fs/promises';\nimport { resolve, join, normalize } from 'node:path';\nimport { parseJsonObject, parseJsonObjectWithRepair } from '../utils/structured-json.js';\nimport { validatePolicyValidation, validateRouterDecision, validateWorkGraph } from '../utils/json-schemas.js';\nimport { recordJsonParseMetric } from '../metrics/json-parse.js';\nimport { PipelineRunState } from './run-state.js';\nimport { missingForRequiredCapabilities, resolveCapabilityMap } from '../capabilities/index.js';\nimport { buildWorkerTasks, createAdHocWorkerTask, validateWorkerTaskEnvelope, type WorkerTaskEnvelope } from './task-envelope.js';\nimport { runDeterministicQA } from '../execution/qa-gate.js';\nimport type { ExecutionTranscript } from '../execution/transcript.js';\nimport { getProjectContext } from '../context/project-context.js';\nimport { reviewWorkerExecution, type ReviewResult } from '../executor/reviewer.js';\nimport { enterWorktree, exitWorktree, mergeWorktree } from '../tools/worktree.js';\nimport { Sandbox } from '../sandbox/index.js';\nimport type { SessionManager } from '../session/manager.js';\nimport { DelegationTuner, analyzeTask as analyzeDelegationTask } from '../engine/delegation.js';\n// Structure analyzer temporarily disabled - file missing\n// import { analyzeProjectStructure, formatStructureContext } from '../utils/structure-analyzer.js';\n\ntype EffortLevel = 'low' | 'medium' | 'high';\n\nexport interface L1Request {\n  userInput: string;\n  context?: string;\n  sessionId: string;\n  deferApply?: boolean; // If true, don't auto-flush sandbox \u2014 let caller handle preview/apply\n  autoApply?: boolean; // If true, auto-apply sandbox changes after execution\n  resume?: {\n    fromPhase?: 'plan' | 'execute' | 'validate';\n    priorPlan?: L2Plan;\n    priorResponse?: string;\n    priorExecutionResults?: L3Result;\n  };\n}\n\nexport interface L2Plan {\n  decision: 'direct-answer' | 'execute-local' | 'execute-parallel' | 'execute-direct';\n  reasoning: string;\n  workGraph?: WorkGraph;\n  validation?: PolicyValidation;\n  directResponse?: string;\n  estimatedEffort?: EffortLevel;\n  traceId: string;\n}\n\nexport interface L3Result {\n  success: boolean;\n  results: Array<{\n    workUnitId: string;\n    persona: string;\n    output: string;\n    cost: number;\n    filesChanged: string[];\n    verification: string[];\n    verificationPassed: boolean;\n    escalationNeeded: boolean;\n    escalationReason?: string;\n    toolsUsed?: string[];\n    failedToolCalls?: number;\n    turns?: number;\n    stopReason?: string;\n    shellResults?: Array<{ command: string; exitCode: number; output: string }>;\n    transcript?: ExecutionTranscript;\n    reviewer?: ReviewResult;\n    qaGateResult?: import('../execution/qa-gate.js').QAGateResult;\n  }>;\n  totalCost: number;\n  executionTimeMs: number;\n  metrics?: {\n    contextChunksUsed: number;\n    contextCharsSaved: number;\n  };\n}\n\nexport interface PipelineResult {\n  response: string;\n  executionPath: string[];\n  plan?: L2Plan;\n  executionResults?: L3Result;\n  totalCost: number;\n  traceId: string;\n  phase: 'complete' | 'failed';\n  timeline: Array<{ phase: string; ts: string; note?: string }>;\n}\n\n/**\n * Unified Pipeline - Single path for all operations\n */\nexport class UnifiedPipeline {\n  private logger = new Logger();\n  private composer = new PromptComposer();\n  private executor = new LocalExecutor();\n  private planner = new DualL2Planner();\n  private contextPacks = new ContextPackManager();\n  private sandbox: Sandbox | undefined;\n  private session?: SessionManager;\n  private delegationTuner = new DelegationTuner();\n\n  constructor(sandbox?: Sandbox, session?: SessionManager) {\n    this.sandbox = sandbox;\n    this.session = session;\n  }\n\n  private requireSandbox(): Sandbox {\n    if (!this.sandbox) throw new Error('Sandbox is required for pipeline execution');\n    return this.sandbox;\n  }\n\n  private async trackCacheHit(cachedTokens: number, totalTokens: number, model: string) {\n    if (!this.session || !cachedTokens || cachedTokens === 0) return;\n    \n    // Calculate savings based on provider\n    let savingsRate = 0;\n    if (model.startsWith('claude')) {\n      savingsRate = 0.90;  // Anthropic: 90% savings on cached tokens\n    } else if (model.startsWith('grok')) {\n      savingsRate = 0.50;  // Grok: 50% savings on cached tokens\n    } else if (model.startsWith('deepseek')) {\n      savingsRate = 0.50;  // DeepSeek: estimated 50% savings\n    } else if (model.startsWith('gemini')) {\n      savingsRate = 0.50;  // Gemini: estimated 50% savings\n    }\n    \n    if (savingsRate === 0) return;\n    \n    // Calculate USD saved (rough estimate based on model pricing)\n    const baseRate = model.startsWith('claude') ? 3.00 : \n                     model.startsWith('grok') ? 5.00 :\n                     model.startsWith('gemini') ? 0.075 : 0.27;\n    const usdSaved = (cachedTokens * baseRate * savingsRate) / 1_000_000;\n    \n    await this.session.trackCacheSavings({\n      hit: true,\n      tokensSaved: cachedTokens,\n      usdSaved\n    });\n  }\n\n  private normalizeDecision(raw: string): 'direct-answer' | 'execute-local' | 'execute-parallel' | 'execute-direct' {\n    // Normalize: lowercase, underscores\u2192hyphens, collapse whitespace\n    const value = String(raw || '').trim().toLowerCase().replace(/_/g, '-').replace(/\\s+/g, '-');\n    if (value === 'direct-answer' || value === 'chat' || value === 'answer') return 'direct-answer';\n    if (value === 'execute-direct' || value === 'direct-execute' || value === 'simple' || value === 'run' || value === 'execute') return 'execute-direct';\n    if (value === 'execute-local' || value === 'code') {\n      return process.env.CREW_ALLOW_EXECUTE_LOCAL === 'true'\n        ? 'execute-local'\n        : 'execute-parallel';\n    }\n    if (value === 'execute-parallel' || value === 'dispatch' || value === 'plan' || value === 'build' || value === 'implement') return 'execute-parallel';\n    // Fallback: if it contains recognizable fragments, route accordingly\n    if (value.includes('direct') && value.includes('answer')) return 'direct-answer';\n    if (value.includes('direct')) return 'execute-direct';\n    if (value.includes('parallel') || value.includes('dispatch')) return 'execute-parallel';\n    return 'execute-parallel';\n  }\n\n  private getReasoningModel(): string | undefined {\n    const model = String(process.env.CREW_REASONING_MODEL || process.env.CREW_CHAT_MODEL || '').trim();\n    return model || undefined;\n  }\n\n  private normalizeEffort(raw: unknown, fallback: EffortLevel = 'medium'): EffortLevel {\n    const value = String(raw || '').trim().toLowerCase();\n    if (value === 'low' || value === 'medium' || value === 'high') return value;\n    return fallback;\n  }\n\n  private getRequestedEffortOverride(): EffortLevel | undefined {\n    const env = String(process.env.CREW_EFFORT || '').trim().toLowerCase();\n    if (env === 'low' || env === 'medium' || env === 'high') return env;\n    return undefined;\n  }\n\n  private inferEffortFromInput(text: string): EffortLevel {\n    const lower = String(text || '').toLowerCase();\n    if (lower.length < 120 && /\\b(typo|rename|small|one line|one-liner|quick|minor|simple)\\b/.test(lower)) return 'low';\n    if (lower.length > 500 || /\\b(api|refactor|architecture|pipeline|multi-file|parallel|worker|oauth|reviewer|two files|both files|multiple files|create.*test|extract.*into|also create)\\b/.test(lower)) return 'high';\n    return 'medium';\n  }\n\n  private getExecutionEffort(taskOrRequest: { estimatedComplexity?: string; goal?: string; userInput?: string }, fallback?: EffortLevel): EffortLevel {\n    const override = this.getRequestedEffortOverride();\n    if (override) return override;\n    if (taskOrRequest.estimatedComplexity) {\n      return this.normalizeEffort(taskOrRequest.estimatedComplexity, fallback || 'medium');\n    }\n    if (taskOrRequest.goal) return this.inferEffortFromInput(taskOrRequest.goal);\n    if (taskOrRequest.userInput) return this.inferEffortFromInput(taskOrRequest.userInput);\n    return fallback || 'medium';\n  }\n\n  private getModelForLayer(layer: 'l1' | 'l3' | 'l3-review' | 'l3-fixer', effort: EffortLevel = 'medium'): string | undefined {\n    const envByLayer: Record<typeof layer, string[]> = {\n      l1: ['CREW_L1_MODEL', 'CREW_ROUTER_MODEL'],\n      l3: ['CREW_L3_MODEL', 'CREW_EXECUTION_MODEL'],\n      'l3-review': ['CREW_L3_REVIEW_MODEL', 'CREW_QA_MODEL'],\n      'l3-fixer': ['CREW_L3_FIXER_MODEL', 'CREW_EXECUTION_MODEL']\n    };\n    for (const envKey of envByLayer[layer]) {\n      const value = String(process.env[envKey] || '').trim();\n      if (value) return value;\n    }\n\n    if (layer === 'l1') return this.getReasoningModel() || 'gemini-2.5-flash';\n    if (layer === 'l3-review') return 'gemini-2.5-flash';\n    if (layer === 'l3-fixer') {\n      if (effort === 'high') return 'gpt-5.2-codex';\n      return 'gpt-5.2';\n    }\n    if (effort === 'low') return 'gemini-2.5-flash';\n    if (effort === 'high') return 'claude-opus-4.6';\n    return 'gpt-5.2';\n  }\n\n  private getTierForEffort(effort: EffortLevel): 'fast' | 'standard' | 'heavy' {\n    if (effort === 'low') return 'fast';\n    if (effort === 'high') return 'heavy';\n    return 'standard';\n  }\n\n  private getMaxTurnsForEffort(effort: EffortLevel): number {\n    const explicit = Number(process.env.CREW_MAX_TURNS || 0);\n    if (Number.isFinite(explicit) && explicit > 0) return Math.max(1, Math.floor(explicit));\n    if (effort === 'low') return 6;\n    if (effort === 'high') return 25;\n    return 10;\n  }\n  \n  private getRouterModel(): string | undefined {\n    // Router needs structured JSON, so avoid pure reasoning models\n    const routerModel = this.getModelForLayer('l1', 'low');\n    if (routerModel) return routerModel;\n    \n    // If CREW_REASONING_MODEL is a reasoning-only model (deepseek-reasoner, gemini-*-preview),\n    // fall back to chat model for structured output\n    const reasoningModel = String(process.env.CREW_REASONING_MODEL || '').trim();\n    if (reasoningModel && \n        !reasoningModel.includes('deepseek-reasoner') && \n        !reasoningModel.includes('-preview')) {\n      return reasoningModel;\n    }\n    \n    // Default to chat model for structured decisions\n    return String(process.env.CREW_CHAT_MODEL || '').trim() || undefined;\n  }\n\n  private getQaModel(): string | undefined {\n    const model = String(process.env.CREW_QA_MODEL || process.env.CREW_L3_REVIEW_MODEL || process.env.CREW_REASONING_MODEL || '').trim();\n    return model || undefined;\n  }\n\n  private getJsonRepairModel(): string | undefined {\n    const explicit = String(process.env.CREW_JSON_REPAIR_MODEL || '').trim();\n    if (explicit) return explicit;\n    if (process.env.GROQ_API_KEY) return 'llama-3.3-70b-versatile';\n    return this.getRouterModel() || this.getReasoningModel();\n  }\n\n  private getJsonParseAttempts(): number {\n    const n = Number(process.env.CREW_JSON_PARSE_MAX_ATTEMPTS || 2);\n    if (!Number.isFinite(n) || n < 1) return 2;\n    return Math.min(4, Math.floor(n));\n  }\n\n  private qaLoopEnabled(): boolean {\n    return process.env.CREW_QA_LOOP_ENABLED === 'true';\n  }\n\n  private scaffoldGateEnabled(): boolean {\n    const raw = String(process.env.CREW_SCAFFOLD_GATE_ENABLED || 'true').trim().toLowerCase();\n    return raw !== 'false' && raw !== '0' && raw !== 'off';\n  }\n\n  private definitionOfDoneEnabled(): boolean {\n    const raw = String(process.env.CREW_DOD_GATE_ENABLED || 'true').trim().toLowerCase();\n    return raw !== 'false' && raw !== '0' && raw !== 'off';\n  }\n\n  private goldenBenchmarkGateEnabled(): boolean {\n    const raw = String(process.env.CREW_GOLDEN_BENCH_GATE_ENABLED || 'true').trim().toLowerCase();\n    return raw !== 'false' && raw !== '0' && raw !== 'off';\n  }\n\n  private qaMaxRounds(): number {\n    const value = Number(process.env.CREW_QA_MAX_ROUNDS || 2);\n    if (!Number.isFinite(value) || value < 1) return 2;\n    return Math.min(5, Math.floor(value));\n  }\n\n  private getExtraL2ValidatorModels(): string[] {\n    const raw = String(process.env.CREW_L2_EXTRA_VALIDATORS || '').trim();\n    if (!raw) return [];\n    return raw\n      .split(',')\n      .map(v => v.trim())\n      .filter(Boolean);\n  }\n\n  private getMaxParallelWorkers(): number {\n    const raw = Number(process.env.CREW_MAX_PARALLEL_WORKERS || 6);\n    if (!Number.isFinite(raw) || raw < 1) return 6;\n    return Math.min(32, Math.floor(raw));\n  }\n\n  private reviewerEnabled(): boolean {\n    const raw = String(process.env.CREW_L3_REVIEW_ENABLED || 'true').trim().toLowerCase();\n    return raw !== 'false' && raw !== '0' && raw !== 'off';\n  }\n\n  private getReviewerMaxCycles(): number {\n    const raw = Number(process.env.CREW_L3_REVIEW_MAX_CYCLES || 2);\n    if (!Number.isFinite(raw) || raw < 1) return 2;\n    return Math.min(3, Math.floor(raw));\n  }\n\n  private async getFileReviewSnippet(filePath: string): Promise<string | undefined> {\n    const staged = this.sandbox?.getStagedContent?.(filePath);\n    if (typeof staged === 'string') return staged;\n    try {\n      return await readFile(resolve(this.sandbox?.getBaseDir() || process.cwd(), filePath), 'utf8');\n    } catch {\n      return undefined;\n    }\n  }\n\n  private parseWorkerOutput(raw: string): { output: string; summary?: string; edits?: string[]; validation?: string[] } {\n    const text = String(raw || '').trim();\n    const start = text.indexOf('{');\n    const end = text.lastIndexOf('}');\n    if (start >= 0 && end > start) {\n      try {\n        const parsed = JSON.parse(text.slice(start, end + 1));\n        const output = String(parsed.output || parsed.result || '').trim();\n        if (output) {\n          return {\n            output,\n            summary: typeof parsed.summary === 'string' ? parsed.summary : undefined,\n            edits: Array.isArray(parsed.edits) ? parsed.edits.map(String) : undefined,\n            validation: Array.isArray(parsed.validation) ? parsed.validation.map(String) : undefined\n          };\n        }\n      } catch {\n        // Fall back to raw output.\n      }\n    }\n    return { output: text };\n  }\n\n  // NOTE: Files are extracted from claimed tool calls in worker history,\n  // not from actual filesystem state. A worker could claim a write_file\n  // call that the sandbox rejected, or the file could have been\n  // overwritten by a later worker. Filesystem verification is not yet\n  // implemented.\n  private extractFilesChanged(history: Array<{ tool: string; params: Record<string, unknown>; error?: string }> = []): string[] {\n    const changed = new Set<string>();\n    for (const turn of history) {\n      if (turn?.error) continue;\n      const tool = String(turn.tool || '');\n      if (['write_file', 'append_file', 'replace', 'edit', 'edit_file', 'notebook_edit'].includes(tool)) {\n        const filePath = String(turn.params?.file_path || turn.params?.path || '').trim();\n        if (filePath) changed.add(filePath);\n        continue;\n      }\n      if (tool === 'run_shell_command' || tool === 'check_background_task' || tool === 'run_cmd' || tool === 'shell') {\n        const command = String(turn.params?.command || '').trim();\n        for (const target of this.extractShellWriteTargets(command)) changed.add(target);\n      }\n    }\n    return Array.from(changed);\n  }\n\n  private extractShellWriteTargets(command: string): string[] {\n    const text = String(command || '').trim();\n    if (!text) return [];\n    const targets = new Set<string>();\n    const redirectRe = /(?:^|[|&;]\\s*|\\s)(?:>>?|1>>?|2>>?)\\s*(?:\"([^\"]+)\"|'([^']+)'|([^\\s|&;]+))/g;\n    let match: RegExpExecArray | null;\n    while ((match = redirectRe.exec(text)) !== null) {\n      const target = String(match[1] || match[2] || match[3] || '').trim();\n      if (target) targets.add(target);\n    }\n    const teeRe = /\\btee\\s+(?:-a\\s+)?(?:\"([^\"]+)\"|'([^']+)'|([^\\s|&;]+))/g;\n    while ((match = teeRe.exec(text)) !== null) {\n      const target = String(match[1] || match[2] || match[3] || '').trim();\n      if (target) targets.add(target);\n    }\n    return [...targets];\n  }\n\n  private stringifyShellResult(result: unknown): string {\n    if (typeof result === 'string') return result.trim();\n    if (!result || typeof result !== 'object') return String(result || '').trim();\n    const candidate = result as {\n      output?: unknown;\n      stdout?: unknown;\n      stderr?: unknown;\n      llmContent?: unknown;\n      returnDisplay?: unknown;\n      return_display?: unknown;\n    };\n    return String(\n      candidate.output\n      || candidate.stdout\n      || candidate.stderr\n      || candidate.llmContent\n      || candidate.returnDisplay\n      || candidate.return_display\n      || ''\n    ).trim();\n  }\n\n  private extractShellResults(\n    history: Array<{ tool: string; params: Record<string, unknown>; result?: unknown; error?: string }> = []\n  ): Array<{ command: string; exitCode: number; output: string }> {\n    const results: Array<{ command: string; exitCode: number; output: string }> = [];\n    for (const turn of history) {\n      const tool = String(turn?.tool || '');\n      if (tool !== 'run_shell_command' && tool !== 'check_background_task' && tool !== 'run_cmd' && tool !== 'shell') continue;\n      const command = String(turn.params?.command || turn.params?.task_id || '').trim();\n      const result = turn.result as { output?: unknown; exitCode?: unknown } | undefined;\n      const rawOutput = this.stringifyShellResult(result || turn.result);\n      const exitCode = turn?.error ? 1 : (typeof result?.exitCode === 'number' ? result.exitCode : 0);\n      results.push({\n        command,\n        exitCode,\n        output: rawOutput.slice(0, 500)\n      });\n    }\n    return results;\n  }\n\n  private collectVerificationSignals(\n    history: Array<{ tool: string; params: Record<string, unknown>; result?: unknown; error?: string }> = [],\n    parsed: { output: string; validation?: string[] },\n    task: WorkerTaskEnvelope\n  ): { verification: string[]; verificationPassed: boolean; escalationNeeded: boolean; escalationReason?: string } {\n    const verification = new Set<string>(Array.isArray(parsed.validation) ? parsed.validation : []);\n    let verificationPassed = false;\n    let escalationNeeded = false;\n    let escalationReason: string | undefined;\n\n    const filesWritten = new Set<string>();\n    const filesReadBack = new Set<string>();\n\n    for (const turn of history) {\n      const tool = String(turn?.tool || '');\n      if (turn?.error) continue;\n\n      // Shell commands are primary verification evidence\n      if (tool === 'run_shell_command' || tool === 'check_background_task' || tool === 'run_cmd' || tool === 'shell') {\n        const command = String(turn.params?.command || turn.params?.task_id || '').trim();\n        const result = turn.result as { output?: unknown } | undefined;\n        const output = this.stringifyShellResult(result || turn.result);\n        verification.add(command ? `Command succeeded: ${command}` : 'Verification command succeeded.');\n        if (output) {\n          verification.add(`Verification output: ${output.slice(0, 200)}`);\n        }\n        verificationPassed = true;\n      }\n\n      // Track file writes and readbacks as secondary verification\n      if (tool === 'write_file' || tool === 'append_file') {\n        const fp = String(turn.params?.file_path || '').trim();\n        if (fp) filesWritten.add(fp);\n      }\n      if (tool === 'read_file' || tool === 'read_many_files') {\n        const fp = String(turn.params?.file_path || '').trim();\n        if (fp) filesReadBack.add(fp);\n      }\n    }\n\n    // If no shell verification but files were written AND read back, count as verified.\n    // Writing a file + reading it back is sufficient proof for file-creation tasks.\n    if (!verificationPassed && filesWritten.size > 0) {\n      const confirmedFiles = [...filesWritten].filter(f => filesReadBack.has(f));\n      if (confirmedFiles.length > 0) {\n        verificationPassed = true;\n        verification.add(`Files written and read back: ${confirmedFiles.join(', ')}`);\n      } else if (task.requiredCapabilities.includes('file-write')) {\n        // Files were written but not read back \u2014 still count for file-write tasks\n        verificationPassed = true;\n        verification.add(`Files written: ${[...filesWritten].join(', ')}`);\n      }\n    }\n\n    // Escalate only if no verification at all and plan expected verification\n    if (!verificationPassed && task.verification.length > 0) {\n      escalationNeeded = true;\n      escalationReason = 'No shell verification command was executed and no files were written';\n    }\n\n    return {\n      verification: Array.from(verification),\n      verificationPassed,\n      escalationNeeded,\n      escalationReason\n    };\n  }\n\n  private countFailedToolCalls(history: Array<{ tool: string; params: Record<string, unknown>; error?: string }> = []): number {\n    return history.filter(turn => Boolean(turn?.error)).length;\n  }\n\n  private hasRepeatedFailedAction(history: Array<{ tool: string; params: Record<string, unknown>; error?: string }> = []): boolean {\n    const failures = history\n      .filter(turn => Boolean(turn?.error))\n      .map(turn => `${String(turn.tool || '')}:${JSON.stringify(turn.params || {})}`);\n    if (failures.length < 2) return false;\n    const last = failures[failures.length - 1];\n    const prev = failures[failures.length - 2];\n    return last === prev;\n  }\n\n  private containsLegacyFileCommands(text: string): boolean {\n    const value = String(text || '');\n    return value.includes('@@WRITE_FILE')\n      || value.includes('@@MKDIR')\n      || /(^|\\n)\\s*FILE:\\s+/im.test(value)\n      || /(^|\\n)\\s*write:\\s+/im.test(value);\n  }\n\n  private shouldParseLegacyCommands(result: { output: string; filesChanged?: string[] }): boolean {\n    const hasLegacy = (!Array.isArray(result.filesChanged) || result.filesChanged.length === 0)\n      && this.containsLegacyFileCommands(result.output);\n    if (hasLegacy) {\n      this.logger.warn('[DEPRECATED] Legacy file commands detected (@@WRITE_FILE, FILE:, write:). Use structured tool calls instead.');\n    }\n    return hasLegacy;\n  }\n\n  private buildStructuredEvidence(executionResults?: L3Result): Array<{\n    workUnitId: string;\n    persona: string;\n    filesChanged: string[];\n    shellResults: Array<{ command: string; exitCode: number; output: string }>;\n    verificationPassed: boolean;\n    verificationEvidence: string;\n    workerOutput: string;\n    escalationNeeded: boolean;\n    escalationReason?: string;\n    failedToolCalls?: number;\n    turns?: number;\n    stopReason?: string;\n  }> {\n    if (!executionResults || !Array.isArray(executionResults.results) || executionResults.results.length === 0) {\n      return [];\n    }\n    return executionResults.results.map(result => {\n      const shellResults = Array.isArray(result.shellResults) ? result.shellResults : [];\n      const verificationEvidence = result.verification.length > 0\n        ? result.verification.join(' | ')\n        : 'No shell verification command was executed';\n      return {\n        workUnitId: result.workUnitId,\n        persona: result.persona,\n        filesChanged: result.filesChanged,\n        shellResults,\n        verificationPassed: result.verificationPassed,\n        verificationEvidence,\n        workerOutput: result.output,\n        escalationNeeded: result.escalationNeeded,\n        escalationReason: result.escalationReason,\n        failedToolCalls: result.failedToolCalls,\n        turns: result.turns,\n        stopReason: result.stopReason\n      };\n    });\n  }\n\n  private buildExecutionAuditContext(executionResults?: L3Result): string {\n    const evidence = this.buildStructuredEvidence(executionResults);\n    if (evidence.length === 0) {\n      return 'No execution metadata available.';\n    }\n    return evidence.map(e => {\n      const lines = [\n        `Unit: ${e.workUnitId}`,\n        `Persona: ${e.persona}`,\n        `Files changed: ${JSON.stringify(e.filesChanged)}`,\n        `Verification passed: ${e.verificationPassed}`,\n        `Verification evidence: ${e.verificationEvidence}`,\n        `Shell results: ${JSON.stringify(e.shellResults)}`,\n        `Escalation needed: ${e.escalationNeeded}`,\n      ];\n      if (e.escalationReason) lines.push(`Escalation reason: ${e.escalationReason}`);\n      if (typeof e.failedToolCalls === 'number') lines.push(`Failed tool calls: ${e.failedToolCalls}`);\n      if (typeof e.turns === 'number') lines.push(`Turns: ${e.turns}`);\n      if (e.stopReason) lines.push(`Stop reason: ${e.stopReason}`);\n      return lines.join('\\n');\n    }).join('\\n\\n');\n  }\n\n  private appendExecutionAuditContext(response: string, executionResults?: L3Result): string {\n    if (!executionResults || !Array.isArray(executionResults.results) || executionResults.results.length === 0) {\n      return response;\n    }\n    return `${response}\\n\\nExecution metadata:\\n${this.buildExecutionAuditContext(executionResults)}`;\n  }\n\n  private extractRequestedPaths(task: string): string[] {\n    const found = new Set<string>();\n    const fileNamed = [...String(task || '').matchAll(/file named\\s+[\"'`]?([A-Za-z0-9._/-]+\\.[A-Za-z0-9]+)[\"'`]?/gi)];\n    for (const match of fileNamed) {\n      const filePath = String(match[1] || '').trim();\n      if (filePath) found.add(filePath);\n    }\n    const pathLike = [...String(task || '').matchAll(/(?:^|[\\s(\"'`])([A-Za-z0-9._/-]+\\.[A-Za-z0-9]+)(?=$|[\\s)\"'`,.:;])/g)];\n    for (const match of pathLike) {\n      const filePath = String(match[1] || '').trim();\n      if (filePath && !filePath.startsWith('ac-')) found.add(filePath);\n    }\n    return Array.from(found).slice(0, 4);\n  }\n\n  private isSmallScopedTask(request: L1Request, plan: L2Plan): boolean {\n    if (plan.workGraph?.planMode === 'lightweight') return true;\n    const text = String(request.userInput || '').toLowerCase();\n    if (text.length > 1200) return false;\n    const paths = this.extractRequestedPaths(text);\n    const narrowIntent = /(create|write|update|modify|edit|add|fix|rename)\\b/.test(text);\n    const broadSignals = [\n      'roadmap',\n      'architecture',\n      'planning',\n      'entire project',\n      'whole project',\n      'phase 1',\n      'phase 2',\n      'phase 3',\n      'contract tests',\n      'golden benchmark',\n      'definition of done'\n    ];\n    return narrowIntent && paths.length > 0 && paths.length <= 4 && !broadSignals.some(signal => text.includes(signal));\n  }\n\n  private async passesDeterministicSmallTaskGate(\n    request: L1Request,\n    plan: L2Plan,\n    executionResults?: L3Result\n  ): Promise<boolean> {\n    if (!this.isSmallScopedTask(request, plan)) return false;\n\n    const scopedPaths = plan.workGraph?.units?.flatMap(unit => Array.isArray(unit.allowedPaths) ? unit.allowedPaths : []).filter(Boolean);\n    const paths = scopedPaths && scopedPaths.length > 0 ? scopedPaths : this.extractRequestedPaths(request.userInput);\n    if (paths.length === 0) return false;\n\n    const baseDir = this.sandbox?.getBaseDir() || process.cwd();\n    const verbose = process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true';\n    const taskText = String(request.userInput || '');\n    const isMutationTask = /(fix|bug|update|modify|edit|refactor|rename|change|replace|repair)/i.test(taskText);\n\n    // For mutation tasks (bugfix, refactor, etc.), the model MUST have actually changed files.\n    // Don't let a model pass by just reading the pre-existing fixture.\n    if (isMutationTask && executionResults?.results?.length) {\n      const anyFilesChanged = executionResults.results.some(result =>\n        Array.isArray(result.filesChanged) && result.filesChanged.length > 0\n      );\n      const anyVerificationPassed = executionResults.results.some(result => result.verificationPassed);\n      if (!anyFilesChanged && !anyVerificationPassed) {\n        if (verbose) console.log(`[QA-det] Mutation task but no files changed and no verification \u2014 rejecting`);\n        return false;\n      }\n    }\n\n    // FILESYSTEM CHECK: verify expected files exist with correct content.\n    // This is ground truth for file-creation tasks and confirms mutations landed.\n    const contents = new Map();\n    for (const relPath of paths) {\n      const staged = this.requireSandbox().getStagedContent(relPath);\n      if (typeof staged === 'string') {\n        if (verbose) console.log(`[QA-det] ${relPath}: found in sandbox (${staged.length} bytes)`);\n        contents.set(relPath, staged);\n        continue;\n      }\n      try {\n        const fullPath = resolve(baseDir, relPath);\n        const content = await readFile(fullPath, 'utf8');\n        if (verbose) console.log(`[QA-det] ${relPath}: found on disk at ${fullPath} (${content.length} bytes)`);\n        contents.set(relPath, content);\n      } catch (err) {\n        if (verbose) console.log(`[QA-det] ${relPath}: NOT FOUND at ${resolve(baseDir, relPath)} \u2014 ${(err as Error).message?.slice(0, 80)}`);\n        return false;\n      }\n    }\n\n    // For bugfix tasks targeting specific files, verify the bug is actually fixed\n    if (isMutationTask) {\n      for (const relPath of paths) {\n        const content = String(contents.get(relPath) || '');\n        // Bugfix: divide-by-zero \u2014 must have a throw/error guard\n        if (relPath.endsWith('math.ts') && /divid/i.test(taskText) && /zero/i.test(taskText)) {\n          if (!/throw\\s+new\\s+Error/i.test(content) && !/if\\s*\\(\\s*b\\s*===?\\s*0\\s*\\)/.test(content)) {\n            if (verbose) console.log(`[QA-det] ${relPath}: bugfix not applied \u2014 no division-by-zero guard found`);\n            return false;\n          }\n        }\n      }\n    }\n\n    const exactLines = [...taskText.matchAll(/\"([^\"]+)\"/g)].map(match => String(match[1] || ''));\n    if (/containing exactly/i.test(taskText) && paths.length === 1 && exactLines.length > 0) {\n      const actual = String(contents.get(paths[0]) || '').trim();\n      const expected = exactLines.join('\\n').trim();\n      return actual === expected;\n    }\n\n    for (const relPath of paths) {\n      const content = String(contents.get(relPath) || '');\n      if (relPath.endsWith('SUMMARY.md') && !content.trim()) return false;\n      if (relPath.endsWith('math.ts') && /add\\(a,\\s*b\\)/i.test(taskText)) {\n        const looksTypedAdd = /export\\s+(function|const)\\s+add\\s*\\(\\s*a\\s*:\\s*[^,]+,\\s*b\\s*:\\s*[^)]+\\)/.test(content)\n          || /export\\s+const\\s+add\\s*=\\s*\\(\\s*a\\s*:\\s*[^,]+,\\s*b\\s*:\\s*[^)]+\\)/.test(content);\n        if (!looksTypedAdd) return false;\n      }\n    }\n\n    return true;\n  }\n\n  private buildWorkerExecutionResult(\n    task: WorkerTaskEnvelope,\n    parsed: { output: string; validation?: string[] },\n    workerResult: {\n      cost?: number;\n      success?: boolean;\n      toolsUsed?: string[];\n      history?: Array<{ tool: string; params: Record<string, unknown>; result?: unknown; error?: string }>;\n      stopReason?: string;\n      turns?: number;\n      transcript?: ExecutionTranscript;\n    }\n  ): L3Result['results'][number] {\n    const history = Array.isArray(workerResult.history) ? workerResult.history : [];\n    const filesChanged = this.extractFilesChanged(history);\n    const shellResults = this.extractShellResults(history);\n    const verificationState = this.collectVerificationSignals(history, parsed, task);\n    const failedToolCalls = this.countFailedToolCalls(history);\n    const repeatedFailedAction = this.hasRepeatedFailedAction(history);\n\n    let escalationNeeded = verificationState.escalationNeeded || workerResult.success === false;\n    let escalationReason = verificationState.escalationReason;\n\n    if (!escalationReason && workerResult.success === false) {\n      escalationReason = workerResult.stopReason || 'Worker did not reach a successful completion state.';\n    } else if (!escalationReason && workerResult.stopReason && !String(workerResult.stopReason).toLowerCase().includes('complete')) {\n      escalationNeeded = true;\n      escalationReason = workerResult.stopReason;\n    }\n\n    const baseDir = this.sandbox?.getBaseDir() || process.cwd();\n    const normalizedAllowedPaths = task.allowedPaths.map(path => {\n      const p = normalize(String(path)).replace(/\\\\/g, '/');\n      // Resolve relative allowed paths against baseDir\n      return p.startsWith('/') ? p : normalize(resolve(baseDir, p)).replace(/\\\\/g, '/');\n    });\n    const outOfScopeFiles = filesChanged.filter(file => {\n      // Resolve relative file paths against baseDir for comparison\n      const absFile = file.startsWith('/') ? file : resolve(baseDir, file);\n      const normalizedFile = normalize(absFile).replace(/\\\\/g, '/');\n      if (normalizedAllowedPaths.length === 0 || normalizedAllowedPaths.includes('.') || normalizedAllowedPaths.includes(normalize(baseDir).replace(/\\\\/g, '/'))) return false;\n      return !normalizedAllowedPaths.some(allowed => (\n        normalizedFile === allowed ||\n        normalizedFile.startsWith(`${allowed}/`) ||\n        (allowed.endsWith('/') && normalizedFile.startsWith(allowed)) ||\n        // Also check if allowed is a glob pattern covering the file\n        (allowed.endsWith('/**') && normalizedFile.startsWith(allowed.slice(0, -3)))\n      ));\n    });\n    if (outOfScopeFiles.length > 0) {\n      escalationNeeded = true;\n      escalationReason = `Worker changed files outside allowed scope: ${outOfScopeFiles.join(', ')}`;\n    } else if (task.maxFilesTouched && filesChanged.length > task.maxFilesTouched) {\n      escalationNeeded = true;\n      escalationReason = `Worker touched ${filesChanged.length} files but task budget was ${task.maxFilesTouched}.`;\n    } else if (task.requiredCapabilities.includes('file-write') && filesChanged.length === 0 && !this.containsLegacyFileCommands(parsed.output)) {\n      escalationNeeded = true;\n      escalationReason = 'Worker completed without producing any file changes for a file-write task.';\n    } else if (failedToolCalls >= 2 && repeatedFailedAction) {\n      escalationNeeded = true;\n      escalationReason = 'Worker repeated the same failing tool action multiple times.';\n    } else if (failedToolCalls >= 3) {\n      escalationNeeded = true;\n      escalationReason = 'Worker accumulated too many failed tool calls.';\n    }\n\n    return {\n      workUnitId: task.id,\n      persona: task.persona,\n      output: parsed.output,\n      cost: workerResult.cost || 0,\n      filesChanged,\n      verification: verificationState.verification,\n      verificationPassed: verificationState.verificationPassed,\n      escalationNeeded,\n      escalationReason,\n      toolsUsed: workerResult.toolsUsed || [],\n      failedToolCalls,\n      turns: workerResult.turns,\n      stopReason: workerResult.stopReason,\n      shellResults,\n      transcript: workerResult.transcript\n    };\n  }\n\n  private extractVerificationCommands(task: WorkerTaskEnvelope): string[] {\n    return Array.from(new Set(\n      (task.verification || [])\n        .map(item => this.extractVerificationCommand(item))\n        .filter((value): value is string => Boolean(value))\n    ));\n  }\n\n  private extractVerificationCommand(value: string): string | null {\n    const trimmed = String(value || '').trim();\n    if (!trimmed) return null;\n\n    const explicit = trimmed.match(/^(?:run|execute)\\s+(.+)$/i);\n    if (explicit?.[1] && this.looksLikeVerificationCommand(explicit[1].trim())) {\n      return explicit[1].trim();\n    }\n\n    const backticked = [...trimmed.matchAll(/`([^`]+)`/g)]\n      .map(match => match[1]?.trim())\n      .filter((command): command is string => Boolean(command) && this.looksLikeVerificationCommand(command));\n    if (backticked.length > 0) return backticked[0];\n\n    return this.looksLikeVerificationCommand(trimmed) ? trimmed : null;\n  }\n\n  private looksLikeVerificationCommand(value: string): boolean {\n    return /^(npm|pnpm|yarn|bun|node|pytest|jest|vitest|cargo|go|make|\\.\\/|bash|sh)\\b/.test(value);\n  }\n\n  private async reviewAndFixWorkerResult(\n    task: WorkerTaskEnvelope,\n    result: L3Result['results'][number],\n    traceId: string,\n    context: string,\n    sessionId?: string\n  ): Promise<L3Result['results'][number]> {\n    if (!this.reviewerEnabled()) return result;\n\n    let current = result;\n    let lastReview: ReviewResult | undefined;\n    const maxCycles = this.getReviewerMaxCycles();\n\n    for (let cycle = 1; cycle <= maxCycles; cycle += 1) {\n      let projectContextSummary = '';\n      try {\n        const projCtx = await getProjectContext(process.cwd());\n        projectContextSummary = projCtx.summary;\n      } catch {\n        // Non-fatal review context.\n      }\n\n      const review = await reviewWorkerExecution({\n        executor: this.executor,\n        model: this.getModelForLayer('l3-review', this.getExecutionEffort(task)),\n        sessionId,\n        projectDir: process.cwd(),\n        projectContextSummary,\n        workUnitId: current.workUnitId,\n        persona: current.persona,\n        taskGoal: task.goal,\n        workerOutput: current.output,\n        filesChanged: current.filesChanged || [],\n        verification: current.verification || [],\n        shellResults: current.shellResults || [],\n        stagedContentForPath: (filePath: string) => this.sandbox?.getStagedContent?.(filePath)\n      });\n\n      lastReview = review;\n      current.reviewer = review;\n\n      if (review.approved || review.issues.length === 0) {\n        return current;\n      }\n\n      if (cycle >= maxCycles) break;\n\n      const fixTask = createAdHocWorkerTask({\n        id: `${task.id}-review-fix-${cycle}`,\n        goal: [\n          task.goal,\n          '',\n          'Reviewer issues to fix:',\n          ...review.issues.map((issue, index) => `${index + 1}. [${issue.severity}] ${issue.problem} -> ${issue.requiredFix}`),\n          '',\n          'Apply only the concrete fixes above and preserve any correct changes already made.'\n        ].join('\\n'),\n        persona: task.persona,\n        sourceRefs: task.sourceRefs || ['request#user-input'],\n        estimatedComplexity: task.estimatedComplexity || this.getExecutionEffort(task),\n        requiredCapabilities: task.requiredCapabilities,\n        maxFilesTouched: task.maxFilesTouched\n      });\n\n      const fixResult = await this.runWorker(context ? `${context}\\n\\n${fixTask.goal}` : fixTask.goal, {\n        model: this.getModelForLayer('l3-fixer', this.getExecutionEffort(task)),\n        maxTurns: this.getMaxTurnsForEffort(this.getExecutionEffort(task)),\n        verbose: process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true',\n        persona: task.persona,\n        constraintLevel: undefined,\n        verificationCommands: this.extractVerificationCommands(task)\n      });\n      const parsed = this.parseWorkerOutput(String(fixResult.output || ''));\n      current = this.buildWorkerExecutionResult(task, parsed, fixResult);\n    }\n\n    current.escalationNeeded = true;\n    current.escalationReason = `Reviewer rejected result: ${lastReview?.summary || 'issues remain after review cycles'}`;\n    current.reviewer = lastReview;\n    return current;\n  }\n\n  private async recordPipelineMetrics(entry: {\n    traceId: string;\n    decision: string;\n    qaEnabled: boolean;\n    qaApproved: boolean;\n    qaRounds: number;\n    contextChunksUsed: number;\n    contextCharsSaved: number;\n    totalCost: number;\n    executionPath: string[];\n  }): Promise<void> {\n    try {\n      const dir = resolve(process.cwd(), '.crew');\n      await mkdir(dir, { recursive: true });\n      const path = join(dir, 'pipeline-metrics.jsonl');\n      await appendFile(path, `${JSON.stringify({ ts: new Date().toISOString(), ...entry })}\\n`, 'utf8');\n    } catch {\n      // Best-effort observability only.\n    }\n  }\n\n  private async writeRunCheckpoint(traceId: string, payload: Record<string, unknown>): Promise<void> {\n    try {\n      const dir = resolve(process.cwd(), '.crew', 'pipeline-runs');\n      await mkdir(dir, { recursive: true });\n      const path = join(dir, `${traceId}.jsonl`);\n      await appendFile(path, `${JSON.stringify({ ts: new Date().toISOString(), ...payload })}\\n`, 'utf8');\n    } catch {\n      // Best-effort checkpointing only.\n    }\n  }\n\n  private parseJsonObject(raw: string): Record<string, unknown> {\n    return parseJsonObject(raw);\n  }\n\n  private async parseRouterDecision(raw: string, traceId: string, sessionId?: string): Promise<{\n    decision: string;\n    reasoning: string;\n    directResponse?: string;\n    complexity?: string;\n  }> {\n    const parsed = await parseJsonObjectWithRepair(raw, {\n      label: `L2 router (${traceId})`,\n      schemaHint: '{\"decision\":\"direct-answer|execute-direct|execute-local|execute-parallel\",\"reasoning\":\"...\",\"directResponse\":\"...\",\"complexity\":\"low|medium|high\",\"estimatedCost\":0.001}',\n      maxAttempts: this.getJsonParseAttempts(),\n      validate: validateRouterDecision,\n      onAttempt: async meta => {\n        await recordJsonParseMetric({ ...meta, traceId });\n      },\n      repair: async (repairPrompt: string) => {\n        const repaired = await this.executor.execute(repairPrompt, {\n          model: this.getJsonRepairModel(),\n          temperature: 0,\n          maxTokens: 1000,\n          sessionId\n        });\n        return String(repaired.result || '');\n      }\n    });\n    return parsed as {\n      decision: string;\n      reasoning: string;\n      directResponse?: string;\n      complexity?: string;\n    };\n  }\n\n  private async qaAuditResponse(response: string, traceId: string, round: number, sessionId?: string, executionResults?: L3Result): Promise<{\n    approved: boolean;\n    summary: string;\n    issues: Array<{ severity: 'high' | 'medium' | 'low'; problem: string; requiredFix: string }>;\n    cost: number;\n  }> {\n    const evidence = this.buildStructuredEvidence(executionResults);\n    const hasStructuredEvidence = evidence.length > 0;\n\n    const overlays: PromptOverlay[] = [\n      {\n        type: 'task',\n        content: `Audit this generated output for correctness, completeness, and coherence.\n\nEvaluate based on STRUCTURED EVIDENCE first (shell results, exit codes, files changed), not narrative quality.\nIf shell commands passed with exit code 0 and files were modified as expected, approve regardless of prose quality.\nOnly reject based on prose if structured evidence is missing or contradictory.`,\n        priority: 1\n      },\n      {\n        type: 'context',\n        content: hasStructuredEvidence\n          ? `Round: ${round}\\n\\nStructured evidence:\\n${JSON.stringify(evidence, null, 2)}\\n\\nWorker output:\\n${response}`\n          : `Round: ${round}\\n\\nGenerated output:\\n${response}`,\n        priority: 2\n      },\n      {\n        type: 'constraints',\n        content: `Return ONLY valid JSON:\n{\n  \"approved\": true|false,\n  \"summary\": \"short summary\",\n  \"issues\": [\n    {\n      \"severity\": \"high|medium|low\",\n      \"problem\": \"what is wrong\",\n      \"requiredFix\": \"what to change\"\n    }\n  ]\n}\n\nIf output has blockers, set approved=false.`,\n        priority: 3\n      }\n    ];\n    const prompt = this.composer.compose('specialist-qa-v1', overlays, `${traceId}-qa-${round}`);\n    const result = await this.executor.execute(prompt.finalPrompt, {\n      model: this.getQaModel(),\n      temperature: 0.1,\n      maxTokens: 2000,\n      sessionId,\n      jsonMode: true\n    });\n    const rawResult = String(result.result || '');\n    try {\n      const parsed = this.parseJsonObject(rawResult);\n      const issues = Array.isArray(parsed.issues) ? parsed.issues : [];\n      return {\n        approved: Boolean(parsed.approved),\n        summary: String(parsed.summary || ''),\n        issues,\n        cost: Number(result.costUsd || 0)\n      };\n    } catch {\n      // QA parse failure: use deterministic heuristic on raw text instead of auto-approving\n      this.logger.warn(`QA audit response was not valid JSON (round ${round}), falling back to text analysis`);\n      const lower = rawResult.toLowerCase();\n      const hasRejectSignals = lower.includes('reject') || lower.includes('fail') || lower.includes('incorrect') || lower.includes('missing') || lower.includes('wrong');\n      const hasApproveSignals = lower.includes('approved') || lower.includes('looks good') || lower.includes('correct') || lower.includes('passes');\n      const approved = hasApproveSignals && !hasRejectSignals;\n      return {\n        approved,\n        summary: `QA parse failed \u2014 text heuristic: ${approved ? 'likely approved' : 'likely rejected'}`,\n        issues: hasRejectSignals ? [{ severity: 'medium' as const, problem: 'QA returned non-JSON with rejection signals', requiredFix: 'Review worker output manually' }] : [],\n        cost: Number(result.costUsd || 0)\n      };\n    }\n  }\n\n  private async fixerPatchResponse(\n    response: string,\n    issues: Array<{ severity: 'high' | 'medium' | 'low'; problem: string; requiredFix: string }>,\n    traceId: string,\n    round: number,\n    sessionId?: string\n  ): Promise<{ output: string; cost: number }> {\n    const overlays: PromptOverlay[] = [\n      {\n        type: 'task',\n        content: `Fix the generated output according to QA issues and return a corrected output body.`,\n        priority: 1\n      },\n      {\n        type: 'context',\n        content: `Round: ${round}\\n\\nIssues:\\n${JSON.stringify(issues, null, 2)}\\n\\nCurrent output:\\n${response}`,\n        priority: 2\n      },\n      {\n        type: 'constraints',\n        content: `Return only corrected output content, no extra commentary.`,\n        priority: 3\n      }\n    ];\n    const templateId = getTemplateForPersona('crew-fixer');\n    const prompt = this.composer.compose(templateId, overlays, `${traceId}-fix-${round}`);\n    const result = await this.executor.execute(prompt.finalPrompt, {\n      temperature: 0.2,\n      maxTokens: 5000,\n      sessionId\n    });\n    return {\n      output: String(result.result || ''),\n      cost: Number(result.costUsd || 0)\n    };\n  }\n\n  private async runQaFixerLoop(\n    response: string,\n    traceId: string,\n    executionResults?: L3Result,\n    sessionId?: string\n  ): Promise<{\n    response: string;\n    addedCost: number;\n    approved: boolean;\n    rounds: number;\n    lastSummary: string;\n  }> {\n    let working = response;\n    let addedCost = 0;\n    let approved = false;\n    let lastSummary = '';\n    const rounds = this.qaMaxRounds();\n\n    for (let round = 1; round <= rounds; round++) {\n      const qaPayload = this.appendExecutionAuditContext(working, executionResults);\n      const qa = await this.qaAuditResponse(qaPayload, traceId, round, sessionId, executionResults);\n      addedCost += qa.cost;\n      lastSummary = qa.summary;\n      if (qa.approved) {\n        approved = true;\n        return { response: working, addedCost, approved, rounds: round, lastSummary };\n      }\n      const fix = await this.fixerPatchResponse(working, qa.issues, traceId, round, sessionId);\n      addedCost += fix.cost;\n      if (fix.output.trim()) {\n        working = fix.output;\n      }\n    }\n\n    // Final gate check after last fixer round.\n    const finalQa = await this.qaAuditResponse(\n      this.appendExecutionAuditContext(working, executionResults),\n      traceId,\n      rounds + 1,\n      sessionId,\n      executionResults\n    );\n    addedCost += finalQa.cost;\n    lastSummary = finalQa.summary;\n    approved = finalQa.approved;\n    return { response: working, addedCost, approved, rounds: rounds + 1, lastSummary };\n  }\n\n  /**\n   * Apply any pending sandbox file writes to disk.\n   * Workers stage files via write_file/edit tools \u2192 sandbox.addChange(),\n   * but those changes need to be flushed to disk after execution.\n   */\n  private async flushSandbox(request?: L1Request): Promise<void> {\n    if (!this.sandbox) return;\n    const pending = this.sandbox.getPendingPaths();\n    if (pending.length === 0) return;\n    if (request?.deferApply) {\n      this.logger.info(`${pending.length} file(s) staged \u2014 deferred apply (caller will preview): ${pending.join(', ')}`);\n      return; // Don't apply \u2014 let REPL show diff preview first\n    }\n    await this.sandbox.apply();\n    this.logger.info(`Applied ${pending.length} staged file(s) to disk: ${pending.join(', ')}`);\n  }\n\n  private autoCheckpointEnabled(): boolean {\n    const raw = String(process.env.CREW_AUTO_CHECKPOINT || 'true').trim().toLowerCase();\n    return raw !== 'false' && raw !== '0' && raw !== 'off';\n  }\n\n  /** Interval (ms) between periodic checkpoint snapshots during long tasks. 0 = disabled. */\n  private checkpointIntervalMs(): number {\n    const raw = String(process.env.CREW_CHECKPOINT_INTERVAL_MS || '').trim();\n    const ms = Number(raw);\n    return Number.isFinite(ms) && ms > 0 ? ms : 60_000; // Default: 60s\n  }\n\n  private _intervalTimer: ReturnType<typeof setInterval> | null = null;\n  private _intervalSnapshotCount = 0;\n\n  /**\n   * Start periodic checkpoint timer. Creates git stash snapshots at fixed intervals\n   * so the user can roll back to any point during long-running pipeline execution.\n   * Stashes are named with the traceId for easy identification.\n   */\n  private startCheckpointInterval(traceId: string): void {\n    if (!this.autoCheckpointEnabled()) return;\n    const intervalMs = this.checkpointIntervalMs();\n    if (intervalMs <= 0) return;\n\n    this._intervalSnapshotCount = 0;\n    this._intervalTimer = setInterval(async () => {\n      try {\n        const { execSync } = await import('node:child_process');\n        const cwd = (this.sandbox as unknown as { baseDir?: string })?.baseDir || process.cwd();\n        const status = execSync('git status --porcelain', { encoding: 'utf8', cwd }).trim();\n        if (!status) return; // nothing to snapshot\n\n        this._intervalSnapshotCount++;\n        const tag = `crew-interval-${traceId.slice(0, 8)}-${this._intervalSnapshotCount}`;\n        // Stage all and create a stash (non-destructive \u2014 working tree stays intact)\n        execSync('git stash push --include-untracked --keep-index -m ' +\n          `\"${tag}: periodic snapshot\"`, { cwd, stdio: 'ignore' });\n        // Immediately pop to restore working tree (the stash ref remains in reflog)\n        execSync('git stash pop', { cwd, stdio: 'ignore' });\n        this.logger.info(`Interval checkpoint #${this._intervalSnapshotCount} saved [${tag}]`);\n      } catch {\n        // Best-effort \u2014 stash may fail if no changes or git unavailable\n      }\n    }, intervalMs);\n  }\n\n  /** Stop the periodic checkpoint timer. */\n  private stopCheckpointInterval(): void {\n    if (this._intervalTimer) {\n      clearInterval(this._intervalTimer);\n      this._intervalTimer = null;\n    }\n    if (this._intervalSnapshotCount > 0) {\n      this.logger.info(`Interval checkpointing stopped (${this._intervalSnapshotCount} snapshot(s) saved).`);\n    }\n    this._intervalSnapshotCount = 0;\n  }\n\n  /**\n   * Git checkpoint at task boundary \u2014 auto-commit changes so user can revert.\n   * Uses a predictable branch-style commit message for easy rollback.\n   */\n  private async gitCheckpoint(traceId: string, executionResults?: L3Result): Promise<void> {\n    try {\n      const { execSync } = await import('node:child_process');\n      const cwd = (this.sandbox as unknown as { baseDir?: string })?.baseDir || process.cwd();\n\n      // Check if we're in a git repo with changes\n      const status = execSync('git status --porcelain', { encoding: 'utf8', cwd }).trim();\n      if (!status) return; // nothing to commit\n\n      // Collect changed files from execution results\n      const filesChanged = (executionResults?.results || [])\n        .flatMap(r => r.filesChanged || [])\n        .filter(Boolean);\n\n      // Build descriptive commit message\n      const filesSummary = filesChanged.length > 0\n        ? filesChanged.slice(0, 5).join(', ') + (filesChanged.length > 5 ? ` (+${filesChanged.length - 5} more)` : '')\n        : 'pipeline changes';\n      const msg = `checkpoint(crew-cli): ${filesSummary} [${traceId.slice(0, 8)}]`;\n\n      execSync('git add -A', { cwd, stdio: 'ignore' });\n      execSync(`git commit -m \"${msg.replace(/\"/g, '\\\\\"')}\" --no-verify`, { cwd, stdio: 'ignore' });\n      this.logger.info(`Checkpoint committed: ${msg}`);\n    } catch {\n      // Best-effort \u2014 don't fail the pipeline if git isn't available or commit fails\n    }\n  }\n\n  private isMajorChange(workGraph?: WorkGraph): boolean {\n    if (!workGraph) return false;\n    const complexity = Number(workGraph.totalComplexity || 0);\n    const unitCount = Array.isArray(workGraph.units) ? workGraph.units.length : 0;\n    return complexity >= 7 || unitCount >= 8;\n  }\n\n  private assertMandatoryWorkGraphGates(workGraph: WorkGraph) {\n    if (!this.scaffoldGateEnabled()) return;\n    if (process.env.CREW_DUAL_L2_ENABLED !== 'true') return;\n    if (workGraph.planMode === 'lightweight') return;\n    const ids = new Set((workGraph.units || []).map(u => u.id));\n    const required = ['scaffold-bootstrap', 'contract-tests-from-pdd', 'gate-definition-of-done', 'gate-golden-benchmark-suite'];\n    const missing = required.filter(id => !ids.has(id));\n    if (missing.length > 0) {\n      throw new Error(`Mandatory pipeline gates missing: ${missing.join(', ')}`);\n    }\n  }\n\n  private buildValidatedWorkerTasks(workGraph: WorkGraph): WorkerTaskEnvelope[] {\n    const tasks = buildWorkerTasks(workGraph);\n    const errors: string[] = [];\n    const warnings: string[] = [];\n    for (const task of tasks) {\n      const check = validateWorkerTaskEnvelope(task);\n      if (!check.ok) {\n        errors.push(`${task.id}: ${check.errors.join(', ')}`);\n      }\n      if (Array.isArray(check.warnings) && check.warnings.length > 0) {\n        warnings.push(`${task.id}: ${check.warnings.join(', ')}`);\n      }\n    }\n    if (warnings.length > 0) {\n      this.logger.warn(`L2\u2192L3 worker task warnings: ${warnings.join(' | ')}`);\n    }\n    if (errors.length > 0) {\n      throw new Error(`Invalid L2\u2192L3 worker tasks: ${errors.join(' | ')}`);\n    }\n    return tasks;\n  }\n\n  private async runDefinitionOfDoneGate(\n    response: string,\n    request: L1Request,\n    plan: L2Plan,\n    traceId: string,\n    sessionId?: string\n  ): Promise<{ approved: boolean; summary: string; cost: number; ran: boolean }> {\n    if (!this.definitionOfDoneEnabled()) return { approved: true, summary: 'DoD gate disabled', cost: 0, ran: false };\n\n    const artifacts = plan.workGraph?.planningArtifacts;\n    if (!artifacts?.definitionOfDone?.trim()) {\n      return { approved: true, summary: 'No DOD artifact present', cost: 0, ran: false };\n    }\n    const overlays: PromptOverlay[] = [\n      {\n        type: 'task',\n        content: 'Run a strict Definition of Done gate. Approve only if all required completion criteria are satisfied.',\n        priority: 1\n      },\n      {\n        type: 'context',\n        content: `User request:\\n${request.userInput}\\n\\nGenerated response:\\n${response}`,\n        priority: 2\n      },\n      {\n        type: 'context',\n        content: artifacts\n          ? `DOD.md:\\n${artifacts.definitionOfDone}\\n\\nPDD acceptance criteria:\\n${(artifacts.acceptanceCriteria || []).join('\\n')}`\n          : 'No DOD artifacts available.',\n        priority: 3\n      },\n      {\n        type: 'constraints',\n        content: `Return ONLY valid JSON:\n{\n  \"approved\": true|false,\n  \"summary\": \"short summary\",\n  \"failedChecks\": [\"list of failed checklist items\"]\n}`,\n        priority: 4\n      }\n    ];\n    const prompt = this.composer.compose('specialist-qa-v1', overlays, `${traceId}-dod`);\n    const res = await this.executor.execute(prompt.finalPrompt, {\n      model: this.getQaModel(),\n      temperature: 0.1,\n      maxTokens: 1200,\n      sessionId\n    });\n    const rawDod = String(res.result || '');\n    try {\n      const parsed = this.parseJsonObject(rawDod);\n      const failed = Array.isArray(parsed.failedChecks) ? parsed.failedChecks : [];\n      const approved = Boolean(parsed.approved) && failed.length === 0;\n      return {\n        approved,\n        summary: String(parsed.summary || ''),\n        cost: Number(res.costUsd || 0),\n        ran: true\n      };\n    } catch {\n      this.logger.warn('DoD QA response was not valid JSON, falling back to text analysis');\n      const lower = rawDod.toLowerCase();\n      const hasRejectSignals = lower.includes('fail') || lower.includes('reject') || lower.includes('missing') || lower.includes('incorrect');\n      return {\n        approved: !hasRejectSignals,\n        summary: `DoD parse failed \u2014 text heuristic: ${hasRejectSignals ? 'likely rejected' : 'likely approved'}`,\n        cost: Number(res.costUsd || 0),\n        ran: true\n      };\n    }\n  }\n\n  private async runGoldenBenchmarkGate(\n    executionResults: L3Result | undefined,\n    plan: L2Plan,\n    traceId: string,\n    sessionId?: string\n  ): Promise<{ approved: boolean; summary: string; cost: number; ran: boolean }> {\n    if (!this.goldenBenchmarkGateEnabled()) return { approved: true, summary: 'Golden benchmark gate disabled', cost: 0, ran: false };\n    if (!this.isMajorChange(plan.workGraph)) return { approved: true, summary: 'Not a major change', cost: 0, ran: false };\n\n    const benchmarkOutput = (executionResults?.results || [])\n      .find(r => r.workUnitId === 'gate-golden-benchmark-suite')?.output || '';\n    if (!benchmarkOutput.trim()) {\n      return { approved: false, summary: 'Missing golden benchmark gate output', cost: 0, ran: true };\n    }\n\n    const overlays: PromptOverlay[] = [\n      {\n        type: 'task',\n        content: 'Validate that golden benchmark suite was executed and results indicate pass for major change.',\n        priority: 1\n      },\n      {\n        type: 'context',\n        content: `Benchmark gate output:\\n${benchmarkOutput}`,\n        priority: 2\n      },\n      {\n        type: 'constraints',\n        content: `Return ONLY valid JSON:\n{\n  \"approved\": true|false,\n  \"summary\": \"short summary\",\n  \"evidence\": [\"signals proving benchmark run happened\"]\n}`,\n        priority: 3\n      }\n    ];\n    const prompt = this.composer.compose('specialist-qa-v1', overlays, `${traceId}-golden-bench`);\n    const res = await this.executor.execute(prompt.finalPrompt, {\n      model: this.getQaModel(),\n      temperature: 0.1,\n      maxTokens: 1000,\n      sessionId\n    });\n    const rawGolden = String(res.result || '');\n    try {\n      const parsed = this.parseJsonObject(rawGolden);\n      return {\n        approved: Boolean(parsed.approved),\n        summary: String(parsed.summary || ''),\n        cost: Number(res.costUsd || 0),\n        ran: true\n      };\n    } catch {\n      this.logger.warn('Golden benchmark QA response was not valid JSON, falling back to text analysis');\n      const lower = rawGolden.toLowerCase();\n      const hasRejectSignals = lower.includes('fail') || lower.includes('reject') || lower.includes('not pass');\n      return {\n        approved: !hasRejectSignals,\n        summary: `Golden bench parse failed \u2014 text heuristic: ${hasRejectSignals ? 'likely rejected' : 'likely approved'}`,\n        cost: Number(res.costUsd || 0),\n        ran: true\n      };\n    }\n  }\n\n  private async runExtraL2Validators(\n    request: L1Request,\n    plan: L2Plan,\n    traceId: string\n  ): Promise<{ approved: boolean; summary: string; cost: number; ran: boolean }> {\n    const models = this.getExtraL2ValidatorModels();\n    if (models.length === 0) return { approved: true, summary: 'No extra L2 validators configured', cost: 0, ran: false };\n    if (!plan.workGraph) return { approved: true, summary: 'No work graph to validate', cost: 0, ran: false };\n\n    let totalCost = 0;\n    const failures: string[] = [];\n\n    for (const model of models) {\n      const overlays: PromptOverlay[] = [\n        {\n          type: 'safety',\n          content: `Validate this plan from an independent L2 pass.\\n\\nTask:\\n${request.userInput}\\n\\nPlan:\\n${JSON.stringify(plan.workGraph, null, 2)}`,\n          priority: 1\n        },\n        {\n          type: 'constraints',\n          content: `Return ONLY valid JSON:\n{\n  \"approved\": true|false,\n  \"summary\": \"short summary\",\n  \"issues\": [\"optional issue list\"]\n}`,\n          priority: 2\n        }\n      ];\n      const prompt = this.composer.compose('policy-validator-v1', overlays, `${traceId}-l2-extra-${model}`);\n      const res = await this.executor.execute(prompt.finalPrompt, {\n        model,\n        temperature: 0.1,\n        maxTokens: 1000\n      });\n      totalCost += Number(res.costUsd || 0);\n      try {\n        const parsed = this.parseJsonObject(String(res.result || ''));\n        if (!Boolean(parsed.approved)) {\n          failures.push(`${model}: ${String(parsed.summary || 'rejected')}`);\n        }\n      } catch {\n        const rawExtra = String(res.result || '').toLowerCase();\n        const hasRejectSignals = rawExtra.includes('reject') || rawExtra.includes('fail') || rawExtra.includes('unsafe');\n        if (hasRejectSignals) {\n          failures.push(`${model}: non-JSON response with rejection signals`);\n        }\n        this.logger.warn(`Extra L2 validator ${model} returned non-JSON, text heuristic: ${hasRejectSignals ? 'rejected' : 'approved'}`);\n      }\n    }\n\n    if (failures.length > 0) {\n      return {\n        approved: false,\n        summary: failures.join(' | '),\n        cost: totalCost,\n        ran: true\n      };\n    }\n    return {\n      approved: true,\n      summary: `Extra L2 validators approved (${models.join(', ')})`,\n      cost: totalCost,\n      ran: true\n    };\n  }\n\n  /**\n   * Execute request through unified pipeline\n   */\n  async execute(request: L1Request): Promise<PipelineResult> {\n    const traceId = `pipeline-${randomUUID()}`;\n    const executionPath: string[] = ['l1-interface'];\n    const startTime = Date.now();\n    const runState = new PipelineRunState();\n    const sessionId = request.sessionId || (this.session ? await this.session.getSessionId() : undefined);\n\n    try {\n      // SCAN: Build ProjectContext (frozen snapshot)\n      runState.transition('scan', 'Building project context');\n      try {\n        await getProjectContext(process.cwd());\n        executionPath.push('scan-project-context');\n      } catch { /* non-fatal \u2014 workers will proceed without context */ }\n\n      // ROUTE + PLAN: L2 Router + Reasoner + Planner (or resume from prior plan)\n      runState.transition('plan', 'L2 orchestration');\n      executionPath.push('l2-orchestrator');\n      await this.writeRunCheckpoint(traceId, { phase: 'plan', userInput: request.userInput, sessionId: request.sessionId });\n      const resumeFrom = request.resume?.fromPhase;\n      const canReusePlan = (resumeFrom === 'execute' || resumeFrom === 'validate') && Boolean(request.resume?.priorPlan);\n      const plan = canReusePlan\n        ? (request.resume?.priorPlan as L2Plan)\n        : await this.l2Orchestrate(request, traceId, request.sessionId);\n      if (canReusePlan) {\n        executionPath.push('resume-plan-loaded');\n      }\n      await this.writeRunCheckpoint(traceId, {\n        phase: 'plan.completed',\n        decision: plan.decision,\n        plan\n      });\n\n      // Store L2 decisions in agent memory for cross-model continuity\n      const memory = getPipelineMemory();\n      memory.remember(`L2 Decision: ${plan.decision} - ${plan.reasoning || 'direct execution'}`, {\n        critical: true,\n        tags: ['l2-decision', traceId],\n        provider: 'pipeline'\n      });\n\n      let response: string;\n      let executionResults: L3Result | undefined;\n      let totalCost = 0;\n      let qaApproved = true;\n      let qaRounds = 0;\n      let contextChunksUsed = 0;\n      let contextCharsSaved = 0;\n      let parallelExecuted = false;\n\n      // Execute based on L2 decision\n      runState.transition('execute');\n      await this.writeRunCheckpoint(traceId, { phase: 'execute', decision: plan.decision });\n\n      // Start periodic checkpoint snapshots for long-running tasks\n      if (plan.decision !== 'direct-answer') {\n        this.startCheckpointInterval(traceId);\n      }\n      if (resumeFrom === 'validate' && request.resume?.priorResponse) {\n        response = String(request.resume.priorResponse || '');\n        executionResults = request.resume.priorExecutionResults;\n        totalCost = Number(request.resume.priorExecutionResults?.totalCost || 0);\n        executionPath.push('resume-validate-only');\n      }\n      else if (process.env.CREW_FORCE_L2 === 'true' && plan.workGraph) {\n        // FORCE_L2: return L2 plan without executing L3 workers (enhance-prompt path)\n        executionPath.push('l2-plan-only');\n        const units = plan.workGraph.units || [];\n        const planText = [\n          '## Build Brief',\n          plan.workGraph.summary || plan.reasoning || request.userInput,\n          '',\n          '## Work Units',\n          ...units.map((u, i) => `${i + 1}. **${u.id}** (${u.requiredPersona}): ${u.description}`),\n          '',\n          '## Acceptance Criteria',\n          ...(plan.workGraph.acceptanceCriteria || plan.workGraph.planningArtifacts?.acceptanceCriteria || []).map((c: string) => `- ${c}`),\n          '',\n          plan.validation ? `## Risk: ${plan.validation.riskLevel}` : '',\n          ...(plan.validation?.concerns || []).map((c: string) => `- ${c}`),\n        ].filter(Boolean).join('\\n');\n        response = planText;\n        totalCost = 0.01;\n      }\n      else if (plan.decision === 'direct-answer') {\n        executionPath.push('l2-direct-response');\n        response = plan.directResponse || 'No response generated';\n        totalCost = 0.0001; // Minimal cost for routing\n      } \n      else if (plan.decision === 'execute-local') {\n        executionPath.push('l3-executor-single');\n        const result = await this.l3ExecuteSingle(\n          createAdHocWorkerTask({\n            id: 'single-task',\n            goal: request.userInput,\n            persona: 'executor-code',\n            sourceRefs: ['request#user-input'],\n            estimatedComplexity: plan.estimatedEffort || 'medium'\n          }),\n          request.context || '',\n          traceId\n        );\n        response = result.output;\n        totalCost = result.cost;\n\n        // Apply any tool-based file writes staged during worker execution\n        await this.flushSandbox(request);\n\n        // Parse and apply file commands from the output\n        const { parseDirectFileCommands } = await import('../cli/file-commands.js');\n        const fileCommands = this.shouldParseLegacyCommands(result) ? parseDirectFileCommands(response) : [];\n        if (fileCommands.length > 0) {\n          // Update result so QA gate knows files were written\n          const writtenPaths = fileCommands.filter(c => c.type === 'write').map(c => c.path);\n          if (writtenPaths.length > 0) {\n            result.filesChanged = [...(result.filesChanged || []), ...writtenPaths];\n            result.toolsUsed = [...(result.toolsUsed || []), 'write_file'];\n          }\n          if (this.sandbox) {\n            await this.sandbox.load();\n            for (const cmd of fileCommands) {\n              if (cmd.type === 'write') {\n                await this.sandbox.addChange(cmd.path, cmd.content || '');\n                this.logger.info(`Staged file: ${cmd.path}`);\n              } else if (cmd.type === 'mkdir') {\n                await this.sandbox.addChange(cmd.path + '/.gitkeep', '');\n                this.logger.info(`Staged directory: ${cmd.path}`);\n              }\n            }\n            if (request.autoApply) {\n              await this.sandbox.apply();\n              this.logger.info(`Applied ${fileCommands.length} file change(s)`);\n            }\n          }\n        }\n\n        executionResults = {\n          success: true,\n          results: [result],\n          totalCost: result.cost,\n          executionTimeMs: Date.now() - startTime\n        };\n      }\n      else if (plan.decision === 'execute-direct') {\n        // execute-direct: skip L2 planning entirely, go straight to L3 single execution\n        executionPath.push('l3-executor-direct');\n        const directTask = createAdHocWorkerTask({\n          id: 'direct-task',\n          goal: request.userInput,\n          persona: 'executor-code',\n          sourceRefs: ['request#user-input'],\n          estimatedComplexity: plan.estimatedEffort || 'low'\n        });\n        const result = await this.l3ExecuteSingle(\n          directTask,\n          request.context || '',\n          traceId\n        );\n        response = result.output;\n        totalCost = result.cost;\n\n        // Apply any tool-based file writes staged during worker execution\n        await this.flushSandbox(request);\n\n        // Parse and apply file commands from the output\n        const { parseDirectFileCommands: parseDirectCmds } = await import('../cli/file-commands.js');\n        const directFileCommands = this.shouldParseLegacyCommands(result) ? parseDirectCmds(response) : [];\n        if (directFileCommands.length > 0 && this.sandbox) {\n          await this.sandbox.load();\n          for (const cmd of directFileCommands) {\n            if (cmd.type === 'write') {\n              await this.sandbox.addChange(cmd.path, cmd.content || '');\n              this.logger.info(`Staged file: ${cmd.path}`);\n            } else if (cmd.type === 'mkdir') {\n              await this.sandbox.addChange(cmd.path + '/.gitkeep', '');\n              this.logger.info(`Staged directory: ${cmd.path}`);\n            }\n          }\n          if (request.autoApply) {\n            await this.sandbox.apply();\n            this.logger.info(`Applied ${directFileCommands.length} file change(s)`);\n          }\n        }\n\n        executionResults = {\n          success: true,\n          results: [result],\n          totalCost: result.cost,\n          executionTimeMs: Date.now() - startTime\n        };\n      }\n      else if (plan.decision === 'execute-parallel') {\n        if (!plan.workGraph) {\n          this.logger.warn('execute-parallel without workGraph \u2014 routing to execute-direct instead');\n          executionPath.push('l3-executor-direct');\n          const fallbackTask = createAdHocWorkerTask({\n            id: 'direct-task',\n            goal: request.userInput,\n            persona: 'executor-code',\n            sourceRefs: ['request#user-input'],\n            estimatedComplexity: plan.estimatedEffort || 'low'\n          });\n          const result = await this.l3ExecuteSingle(\n            fallbackTask,\n            request.context || '',\n            traceId\n          );\n          response = result.output;\n          totalCost = result.cost;\n\n          // Apply any tool-based file writes staged during worker execution\n          await this.flushSandbox(request);\n\n          // Parse and apply file commands from the output\n          const { parseDirectFileCommands } = await import('../cli/file-commands.js');\n          const fileCommands = this.shouldParseLegacyCommands(result) ? parseDirectFileCommands(response) : [];\n          if (fileCommands.length > 0) {\n            const writtenPaths = fileCommands.filter(c => c.type === 'write').map(c => c.path);\n            if (writtenPaths.length > 0) {\n              result.filesChanged = [...(result.filesChanged || []), ...writtenPaths];\n              result.toolsUsed = [...(result.toolsUsed || []), 'write_file'];\n            }\n            if (this.sandbox) {\n              await this.sandbox.load();\n              for (const cmd of fileCommands) {\n                if (cmd.type === 'write') {\n                  await this.sandbox.addChange(cmd.path, cmd.content || '');\n                  this.logger.info(`Staged file: ${cmd.path}`);\n                } else if (cmd.type === 'mkdir') {\n                  await this.sandbox.addChange(cmd.path + '/.gitkeep', '');\n                  this.logger.info(`Staged directory: ${cmd.path}`);\n                }\n              }\n              if (request.autoApply) {\n                await this.sandbox.apply();\n                this.logger.info(`Applied ${fileCommands.length} file change(s)`);\n              }\n            }\n          }\n\n          executionResults = {\n            success: true,\n            results: [result],\n            totalCost: result.cost,\n            executionTimeMs: Date.now() - startTime\n          };\n        } else {\n          executionPath.push('l3-executor-parallel');\n          executionResults = await this.l3ExecuteParallel(\n            plan.workGraph,\n            request.context || '',\n            traceId\n          );\n          parallelExecuted = true;\n          response = this.synthesizeResults(executionResults);\n          totalCost = executionResults.totalCost;\n          const metrics = (executionResults as L3Result)?.metrics;\n          contextChunksUsed = Number(metrics?.contextChunksUsed || 0);\n          contextCharsSaved = Number(metrics?.contextCharsSaved || 0);\n\n          // Apply any tool-based file writes staged during worker execution\n          await this.flushSandbox(request);\n\n          // Parse and apply file commands from parallel worker outputs\n          const { parseDirectFileCommands } = await import('../cli/file-commands.js');\n          const allFileCommands: Array<{ type: string; path: string; content?: string }> = [];\n          for (const result of executionResults.results) {\n            if (!this.shouldParseLegacyCommands(result)) continue;\n            const commands = parseDirectFileCommands(result.output);\n            // Update result.filesChanged so QA gate knows work was done\n            const writtenPaths = commands.filter(c => c.type === 'write').map(c => c.path);\n            if (writtenPaths.length > 0) {\n              result.filesChanged = [...(result.filesChanged || []), ...writtenPaths];\n              result.toolsUsed = [...(result.toolsUsed || []), 'write_file'];\n            }\n            allFileCommands.push(...commands);\n          }\n\n          if (allFileCommands.length > 0 && this.sandbox) {\n            await this.sandbox.load();\n            for (const cmd of allFileCommands) {\n              if (cmd.type === 'write') {\n                await this.sandbox.addChange(cmd.path, cmd.content || '');\n                this.logger.info(`Staged file: ${cmd.path}`);\n              } else if (cmd.type === 'mkdir') {\n                await this.sandbox.addChange(cmd.path + '/.gitkeep', '');\n                this.logger.info(`Staged directory: ${cmd.path}`);\n              }\n            }\n\n            if (request.autoApply) {\n              await this.sandbox.apply();\n              this.logger.info(`Applied ${allFileCommands.length} file change(s)`);\n            }\n          }\n        }\n      }\n      else {\n        throw new Error(`Unknown decision: ${plan.decision}`);\n      }\n\n      if (plan.decision !== 'direct-answer') {\n        // Transcript-based deterministic QA (runs on ALL executions, not just small tasks)\n        if (executionResults?.results?.length) {\n          for (const r of executionResults.results) {\n            const transcript = r.transcript;\n            if (transcript) {\n              const qaResult = runDeterministicQA(transcript, {\n                requireFileChanges: plan.decision !== 'execute-direct'\n              });\n              if (!qaResult.passed) {\n                const verbose = process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true';\n                if (verbose) {\n                  console.log(`[QA Gate] ${r.workUnitId}: ${qaResult.summary}`);\n                  for (const check of qaResult.checks.filter(c => !c.passed)) {\n                    console.log(`  \u2717 ${check.name}: ${check.detail}`);\n                  }\n                }\n                r.escalationNeeded = true;\n                r.escalationReason = `Deterministic QA failed: ${qaResult.summary}`;\n              }\n              // Store QA results in execution metadata\n              r.qaGateResult = qaResult;\n            }\n          }\n          executionPath.push('l3-transcript-qa');\n        }\n\n        // Run deterministic content gate FIRST \u2014 if files exist with correct content,\n        // approve immediately regardless of transcript QA escalations (failed git/tsc/etc).\n        // This prevents the LLM QA loop from rejecting successful file-creation tasks.\n        const deterministicQaApproved = await this.passesDeterministicSmallTaskGate(request, plan, executionResults);\n        if (deterministicQaApproved) {\n          qaApproved = true;\n          qaRounds = 0;\n          executionPath.push('l3-qa-approved-deterministic');\n        } else {\n          // Deterministic gate rejected \u2014 mark as not approved\n          qaApproved = false;\n          if (this.qaLoopEnabled()) {\n            executionPath.push('l3-qa-gate');\n            const qaLoop = await this.runQaFixerLoop(response, traceId, executionResults, sessionId);\n            response = qaLoop.response;\n            totalCost += qaLoop.addedCost;\n            qaRounds = qaLoop.rounds;\n            qaApproved = qaLoop.approved;\n            executionPath.push(qaLoop.approved ? 'l3-qa-approved' : 'l3-qa-rejected');\n            if (!qaLoop.approved) {\n              throw new Error(`QA gate failed after ${qaLoop.rounds} rounds. ${qaLoop.lastSummary || ''}`.trim());\n            }\n          }\n        }\n      }\n\n      // EVIDENCE: transcript + file diffs collected (already on results)\n      runState.transition('validate', 'QA validation');\n      await this.writeRunCheckpoint(traceId, {\n        phase: 'validate.input',\n        response,\n        executionResults\n      });\n      if (plan.decision === 'execute-parallel' && parallelExecuted) {\n        const l2extra = await this.runExtraL2Validators(request, plan, traceId);\n        if (l2extra.ran) executionPath.push('l2-extra-validators');\n        totalCost += l2extra.cost;\n        if (!l2extra.approved) {\n          throw new Error(`Extra L2 validation failed. ${l2extra.summary}`.trim());\n        }\n      }\n\n      if (plan.decision === 'execute-parallel' && parallelExecuted) {\n        const dod = await this.runDefinitionOfDoneGate(response, request, plan, traceId, sessionId);\n        if (dod.ran) executionPath.push('l3-definition-of-done-gate');\n        totalCost += dod.cost;\n        if (!dod.approved) {\n          throw new Error(`Definition of done gate failed. ${dod.summary}`.trim());\n        }\n      }\n\n      if (plan.decision === 'execute-parallel' && parallelExecuted) {\n        const bench = await this.runGoldenBenchmarkGate(executionResults, plan, traceId, sessionId);\n        if (bench.ran) executionPath.push('l3-golden-benchmark-gate');\n        totalCost += bench.cost;\n        if (!bench.approved) {\n          throw new Error(`Golden benchmark gate failed. ${bench.summary}`.trim());\n        }\n      }\n\n      // CHECKPOINT: git commit if changes made\n      runState.transition('checkpoint', 'Auto-checkpoint');\n\n      // Stop periodic snapshots before final checkpoint\n      this.stopCheckpointInterval();\n\n      // Auto-checkpoint: git commit at task boundary if files were changed\n      if (plan.decision !== 'direct-answer' && this.autoCheckpointEnabled()) {\n        await this.gitCheckpoint(traceId, executionResults);\n      }\n\n      runState.transition('complete');\n\n      await this.writeRunCheckpoint(traceId, {\n        phase: 'complete',\n        decision: plan.decision,\n        totalCost,\n        durationMs: Date.now() - startTime,\n        qaApproved\n      });\n\n      await this.recordPipelineMetrics({\n        traceId,\n        decision: plan.decision,\n        qaEnabled: this.qaLoopEnabled(),\n        qaApproved,\n        qaRounds,\n        contextChunksUsed,\n        contextCharsSaved,\n        totalCost,\n        executionPath\n      });\n\n      return {\n        response,\n        executionPath,\n        plan,\n        executionResults,\n        totalCost,\n        traceId,\n        phase: 'complete',\n        timeline: runState.getTimeline()\n      };\n    } catch (err) {\n      this.stopCheckpointInterval();\n      runState.transition('failed', (err as Error).message);\n      await this.writeRunCheckpoint(traceId, {\n        phase: 'failed',\n        error: (err as Error).message,\n        executionPath\n      });\n      this.logger.error(`Pipeline execution failed: ${(err as Error).message}`);\n      throw err;\n    }\n  }\n\n  /**\n   * L2-only route planning for orchestrator integration.\n   * This runs L2 reasoning (and optional dual-L2 planning) without executing L3 workers.\n   */\n  async routeOnly(request: L1Request): Promise<{\n    decision: 'CHAT' | 'CODE' | 'DISPATCH';\n    agent?: string;\n    task?: string;\n    response?: string;\n    explanation?: string;\n    traceId: string;\n  }> {\n    const traceId = `pipeline-${randomUUID()}`;\n    const plan = await this.l2Orchestrate(request, traceId, request.sessionId);\n\n    if (plan.decision === 'direct-answer') {\n      return {\n        decision: 'CHAT',\n        response: plan.directResponse || 'No response generated',\n        explanation: plan.reasoning,\n        traceId\n      };\n    }\n\n    // All execution paths map to CODE in standalone mode.\n    // execute-direct, execute-local, and execute-parallel are all handled locally.\n    return {\n      decision: 'CODE',\n      agent: 'crew-coder',\n      task: request.userInput,\n      explanation: plan.reasoning,\n      traceId\n    };\n  }\n\n  /**\n   * L2: Unified Orchestration Layer\n   * Combines routing + reasoning + planning into single decision\n   */\n  private async l2Orchestrate(\n    request: L1Request,\n    traceId: string,\n    sessionId?: string\n  ): Promise<L2Plan> {\n    // Step 0: Quick project scan so router + workers understand what we're working with\n    const projectDir = (this.sandbox as unknown as { baseDir?: string })?.baseDir || process.cwd();\n    let projectContext = '';\n    try {\n      const { readdirSync, statSync, readFileSync, existsSync } = await import('node:fs');\n      const { join } = await import('node:path');\n      // Get top-level file listing\n      const entries = readdirSync(projectDir)\n        .filter(f => !f.startsWith('.') && f !== 'node_modules')\n        .slice(0, 30);\n      const fileList = entries.map(f => {\n        const s = statSync(join(projectDir, f));\n        return s.isDirectory() ? `${f}/` : f;\n      });\n      projectContext = `Project files: ${fileList.join(', ')}`;\n      // Detect tech stack from key files\n      const hasPackageJson = existsSync(join(projectDir, 'package.json'));\n      const hasIndexHtml = existsSync(join(projectDir, 'index.html'));\n      const hasTsConfig = existsSync(join(projectDir, 'tsconfig.json'));\n      if (hasIndexHtml && !hasTsConfig) {\n        projectContext += '\\nTech: Static HTML/CSS/JS site (vanilla, no build step, no Node.js modules). All JS must be browser-compatible (no require/import/export, no Node APIs).';\n      } else if (hasPackageJson) {\n        try {\n          const pkg = JSON.parse(readFileSync(join(projectDir, 'package.json'), 'utf8'));\n          const deps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).slice(0, 10);\n          projectContext += `\\nTech: Node.js project. Dependencies: ${deps.join(', ')}`;\n        } catch { /* skip */ }\n      }\n      // Read a snippet of the main file to understand the style\n      if (hasIndexHtml) {\n        try {\n          const html = readFileSync(join(projectDir, 'index.html'), 'utf8');\n          projectContext += `\\nindex.html: ${html.length} chars, ${(html.match(/<script/g) || []).length} script tags, ${(html.match(/<link.*css/g) || []).length} CSS links`;\n        } catch { /* skip */ }\n      }\n    } catch { /* non-fatal */ }\n\n    // Step 1: Router - classify the request\n    const overlays: PromptOverlay[] = [\n      {\n        type: 'task',\n        content: `User request: ${request.userInput}`,\n        priority: 1\n      }\n    ];\n\n    if (request.context) {\n      overlays.push({\n        type: 'context',\n        content: `Context:\\n${request.context}`,\n        priority: 2\n      });\n    }\n\n    if (projectContext) {\n      overlays.push({\n        type: 'context',\n        content: projectContext,\n        priority: 2\n      });\n    }\n    const currentModel = this.getRouterModel() || process.env.CREW_CHAT_MODEL || process.env.CREW_EXECUTION_MODEL || 'unknown';\n    const interfaceMode = String(process.env.CREW_INTERFACE_MODE || 'standalone').toLowerCase();\n    overlays.push({\n      type: 'constraints',\n      content: `You are crewswarm's CLI assistant, running model \"${currentModel}\" in ${interfaceMode} mode.\nYou are operating in project directory: ${projectDir}\nYou have full file system access with tools: list_directory, read_file, write_file, grep_search, glob, run_shell_command, git, and more.\nYou do NOT dispatch to external agents or a swarm. All execution is local.\n\nWhen asked about your identity or what model you are, answer: \"I'm crewswarm CLI running ${currentModel}.\" The brand is always lowercase \"crewswarm\" \u2014 never \"crewswarm\" or \"crewswarm\".\n\nAnalyze this request and decide:\n\n1. DIRECT-ANSWER: ONLY for pure conversational greetings (\"hi\", \"hello\", \"how are you\") or questions about YOUR identity/capabilities (\"what can you do\", \"who are you\")\n   \u2192 Provide immediate text response\n   \u2192 NEVER use this if the request implies ANY action, creation, modification, building, designing, or doing\n   \u2192 NEVER use this for questions about files, code, project state, or folder contents\n   \u2192 When in doubt, use EXECUTE-DIRECT instead\n\n2. EXECUTE-DIRECT: Simple task, question about project, or single-file action\n   \u2192 Questions about files, folder contents, code, project structure \u2192 use tools to answer\n   \u2192 Single file create/edit, small bug fix, one-liner change\n   \u2192 Bypasses L2 planning overhead entirely\n\n3. EXECUTE-LOCAL: DEPRECATED - only for testing/debugging\n   \u2192 Not used in production\n\n4. EXECUTE-PARALLEL: Multi-file or complex coding/implementation tasks (default for code)\n   \u2192 Any request involving writing, modifying, or refactoring multiple files\n   \u2192 L2 will decompose into work units for L3 workers\n   \u2192 After execution, L2 runs QA validation\n   \u2192 If QA fails, expensive fixer runs, then QA again\n   \u2192 Use dual-L2 planner for work graph\n\n**CRITICAL: These action words ALWAYS require EXECUTE-DIRECT or EXECUTE-PARALLEL (NEVER DIRECT-ANSWER):**\nadd, create, build, design, make, write, edit, update, modify, change, fix, implement, refactor, remove, delete, move, rename, install, configure, set up, deploy, generate, scaffold, do, put, insert, append\n\n**Choose EXECUTE-DIRECT for:**\n- Any question about files, folders, code, or project state (use tools to look)\n- Creating or editing a single file\n- Adding content to an existing file\n- Small, focused bug fixes\n- Simple code generation with obvious scope\n\n**Choose EXECUTE-PARALLEL for:**\n- Multi-file features, APIs, or refactors\n- Implementing features that span modules\n- Test creation across multiple files\n- Documentation generation for entire projects\n\nReturn ONLY valid JSON:\n{\n  \"decision\": \"direct-answer|execute-direct|execute-parallel\",\n  \"reasoning\": \"why this path was chosen\",\n  \"directResponse\": \"if direct-answer, provide response here\",\n  \"complexity\": \"low|medium|high\",\n  \"estimatedCost\": 0.001\n}`,\n        priority: 3\n      }\n    );\n\n    const composedPrompt = this.composer.compose('router-v1', overlays, traceId);\n    \n    const verbose = process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true';\n    if (verbose) {\n      console.log(`[L2 Router] Calling ${this.executor.constructor.name}...`);\n      console.log(`[L2 Router] Prompt length: ${composedPrompt.finalPrompt.length} chars`);\n      console.log(`[L2 Router] Request: ${request.userInput.substring(0, 100)}...`);\n    }\n\n    const routerStart = Date.now();\n    const requestedRouterModel = this.getRouterModel();\n    const result = await this.executor.execute(composedPrompt.finalPrompt, {\n      model: requestedRouterModel,\n      temperature: 0.3,\n      maxTokens: 8000,  // L2 gets expensive model budget - only place we use it\n      jsonMode: true,  // Router needs JSON\n      sessionId: request.sessionId  // Pass session ID for cache coherence\n    });\n    if (verbose) {\n      console.log(`[L2 Router] \u2705 Response in ${Date.now() - routerStart}ms`);\n      console.log(`[L2 Router] Model requested: ${requestedRouterModel || '(default)'} | used: ${result.model || '(unknown)'}`);\n    }\n\n    // Track cache savings from router call\n    if (result.cachedTokens) {\n      const totalTokens = (result.promptTokens || 0) + (result.cachedTokens || 0);\n      await this.trackCacheHit(result.cachedTokens, totalTokens, result.model);\n    }\n\n    if (!result.success) {\n      throw new Error(`L2 orchestration failed: ${result.result}`);\n    }\n\n    const decision = await this.parseRouterDecision(String(result.result || ''), traceId, sessionId);\n    let normalizedDecision = this.normalizeDecision(decision.decision);\n\n    // Deterministic override: tasks with file-creation verbs must never be direct-answer.\n    // Some models (GPT-5.x) classify simple tasks as direct-answer even when tools are needed.\n    if (normalizedDecision === 'direct-answer') {\n      const lower = String(request.userInput || '').toLowerCase();\n      const requiresExecution = /\\b(create|write|add|edit|update|modify|fix|build|implement|refactor|delete|remove|rename|generate|scaffold)\\b/.test(lower)\n        && /\\b(file|directory|folder|function|class|module|component|test|spec)\\b/.test(lower);\n      if (requiresExecution) {\n        normalizedDecision = 'execute-direct';\n      }\n    }\n\n    const estimatedEffort = this.getRequestedEffortOverride()\n      || this.normalizeEffort(decision.complexity, this.inferEffortFromInput(request.userInput));\n\n    // Step 2: If complex AND Dual-L2 enabled, run planner\n    let workGraph: WorkGraph | undefined;\n    let validation: PolicyValidation | undefined;\n\n    const dualL2Enabled = process.env.CREW_DUAL_L2_ENABLED === 'true';\n\n    // CREW_FORCE_L2=true bypasses L1 routing and always runs L2 planner (used by enhance-prompt)\n    const forceL2 = process.env.CREW_FORCE_L2 === 'true';\n    if ((normalizedDecision === 'execute-parallel' || forceL2) && dualL2Enabled) {\n      console.log('[L2 Planner] Dual-L2 enabled, calling DualL2Planner...');\n      \n      const planStart = Date.now();\n      const dualL2Result = await this.planner.plan(\n        request.userInput,\n        request.context || '',\n        traceId\n      );\n      console.log(`[L2 Planner] \u2705 Plan complete in ${Date.now() - planStart}ms`);\n      console.log(`[L2 Planner] Work units: ${dualL2Result.workGraph?.units?.length || 0}`);\n      \n      workGraph = dualL2Result.workGraph;\n      validation = dualL2Result.validation;\n\n      if (workGraph) {\n        const graphCheck = validateWorkGraph(workGraph);\n        if (!graphCheck.ok) {\n          throw new Error(`Planner returned invalid work graph: ${graphCheck.errors.join('; ')}`);\n        }\n        this.buildValidatedWorkerTasks(workGraph);\n      }\n      if (validation) {\n        const policyCheck = validatePolicyValidation(validation);\n        if (!policyCheck.ok) {\n          throw new Error(`Planner returned invalid validation payload: ${policyCheck.errors.join('; ')}`);\n        }\n      }\n\n      if (workGraph) {\n        const mode = String(process.env.CREW_INTERFACE_MODE || 'standalone').toLowerCase() === 'connected'\n          ? 'connected'\n          : 'standalone';\n        const caps = resolveCapabilityMap(mode);\n        for (const unit of workGraph.units || []) {\n          const missing = missingForRequiredCapabilities(unit.requiredCapabilities || [], caps);\n          if (missing.length > 0) {\n            throw new Error(\n              `Capability gate failed for unit \"${unit.id}\" (${unit.requiredPersona}): missing ${missing.join(', ')} in ${caps.mode} mode`\n            );\n          }\n        }\n      }\n\n      // HARD RISK GATE - Block critical risk tasks\n      if (!validation.approved) {\n        throw new Error(\n          `Task rejected by policy validator:\\n${validation.concerns.join('\\n')}\\n\\n` +\n          `Recommendations:\\n${validation.recommendations.join('\\n')}`\n        );\n      }\n\n      const allowCritical = process.env.CREW_ALLOW_CRITICAL === 'true';\n      if (validation.riskLevel === 'critical' && !allowCritical) {\n        throw new Error(\n          `CRITICAL RISK detected. Task blocked.\\n${validation.concerns.join('\\n')}\\n` +\n          `Use CREW_ALLOW_CRITICAL=true to override (not recommended).`\n        );\n      }\n    }\n\n    return {\n      decision: normalizedDecision,\n      reasoning: decision.reasoning,\n      workGraph,\n      validation,\n      directResponse: decision.directResponse,\n      estimatedEffort,\n      traceId\n    };\n  }\n\n  /**\n   * L3: Single Executor\n   */\n  private async l3ExecuteSingle(\n    task: WorkerTaskEnvelope,\n    context: string,\n    traceId: string\n  ): Promise<{\n    workUnitId: string;\n    persona: string;\n    output: string;\n    cost: number;\n    filesChanged: string[];\n    verification: string[];\n    verificationPassed: boolean;\n    escalationNeeded: boolean;\n    escalationReason?: string;\n    toolsUsed?: string[];\n  }> {\n    const check = validateWorkerTaskEnvelope(task);\n    if (!check.ok) {\n      throw new Error(`Invalid single worker task: ${check.errors.join(', ')}`);\n    }\n    // Inject frozen ProjectContext so workers know the tech stack\n    let projectContextSummary = '';\n    try {\n      const projCtx = await getProjectContext(process.cwd());\n      projectContextSummary = projCtx.summary;\n    } catch { /* non-fatal */ }\n    const enhancedTask = projectContextSummary\n      ? `${projectContextSummary}\\n\\n${task.goal}`\n      : task.goal;\n\n    const overlays: PromptOverlay[] = [\n      { type: 'task', content: enhancedTask, priority: 1 }\n    ];\n\n    if (context) {\n      overlays.push({ type: 'context', content: context, priority: 2 });\n    }\n\n    try {\n      const { autoLoadRelevantFiles, shouldUseRag } = await import('../context/codebase-rag.js');\n      if (shouldUseRag(enhancedTask)) {\n        const ragContext = await autoLoadRelevantFiles(enhancedTask, process.cwd(), {\n          mode: (process.env.CREW_RAG_MODE || 'auto') as import('../context/codebase-rag.js').RagMode,\n          tokenBudget: Number(process.env.CREW_RAG_WORKER_BUDGET || 4000),\n          maxFiles: Number(process.env.CREW_RAG_MAX_FILES_LOAD || 6)\n        });\n        if (ragContext.context) {\n          overlays.push({\n            type: 'context',\n            content: ragContext.context,\n            priority: 3\n          });\n        }\n      }\n    } catch {\n      // Never fail a worker due to RAG injection.\n    }\n\n    overlays.push({\n      type: 'constraints',\n      content: `Worker task contract:\n- Allowed paths: ${task.allowedPaths.length > 0 ? task.allowedPaths.join(', ') : '(no explicit paths extracted)'}\n- Verification: ${task.verification.join(' | ')}\n- Escalate when: ${(task.escalationHints || []).join(' | ')}`,\n      priority: 3\n    });\n\n    // Get sessionId from session manager if available\n    const sessionId = this.session ? await this.session.getSessionId() : undefined;\n\n    const composedPrompt = this.composer.compose('executor-code-v1', overlays, traceId);\n\n    const effort = this.getExecutionEffort(task);\n    const verificationCommands = this.extractVerificationCommands(task);\n    const result = await runAgenticWorker(composedPrompt.finalPrompt, this.requireSandbox(), {\n      model: this.getModelForLayer('l3', effort) || '',\n      maxTurns: this.getMaxTurnsForEffort(effort),\n      tier: this.getTierForEffort(effort),\n      persona: task.persona,\n      verificationCommands\n    });\n\n    if (process.env.CREW_DEBUG_PIPELINE) {\n      console.log(`[Pipeline] L3 result: success=${result.success} turns=${result.turns} historyLen=${result.history?.length ?? 0} tools=${result.toolsUsed?.join(',')}`);\n      if (result.history) {\n        for (const h of result.history.slice(0, 5)) {\n          console.log(`[Pipeline]   [T${h.turn}] ${h.tool}(${(h.params?.file_path || h.params?.command || '').toString().slice(0, 40)}) ${h.error ? 'ERR' : 'ok'}`);\n        }\n      }\n    }\n    const parsed = this.parseWorkerOutput(String(result.output || ''));\n    const built = this.buildWorkerExecutionResult(task, parsed, result);\n    if (process.env.CREW_DEBUG_PIPELINE) {\n      console.log(`[Pipeline] Built: filesChanged=${built.filesChanged.join(',')} shellResults=${(built.shellResults || []).length} verificationPassed=${built.verificationPassed} escalation=${built.escalationNeeded} reason=${built.escalationReason || 'none'}`);\n    }\n    return this.reviewAndFixWorkerResult(task, built, traceId, context, sessionId);\n  }\n\n  /**\n   * L3: Parallel Executors\n   * Execute work units in dependency order with parallelization\n   */\n  private async l3ExecuteParallel(\n    workGraph: WorkGraph,\n    context: string,\n    traceId: string\n  ): Promise<L3Result> {\n    const verbose = process.env.CREW_VERBOSE === 'true' || process.env.CREW_DEBUG === 'true';\n    if (verbose) {\n      console.log('[L3 Execute] Starting parallel execution...');\n      console.log(`[L3 Execute] Total work units: ${workGraph.units.length}`);\n    }\n    \n    // HARD COST GATE - Block before execution\n    if (workGraph.estimatedCost > 0.50) {\n      throw new Error(\n        `Task cost $${workGraph.estimatedCost.toFixed(3)} exceeds limit ($0.50). ` +\n        `Use /approve-cost to override or simplify the task.`\n      );\n    }\n\n    this.assertMandatoryWorkGraphGates(workGraph);\n    const workerTasks = this.buildValidatedWorkerTasks(workGraph);\n\n    // Get sessionId from session manager if available\n    const sessionId = this.session ? await this.session.getSessionId() : undefined;\n\n    const startTime = Date.now();\n    const results: L3Result['results'] = [];\n    const completed = new Set<string>();\n    const outputByUnit = new Map<string, string>();\n    let totalCost = 0;\n    // Accumulate discovered files across batches so later workers inherit context.\n    // Load prior JIT context from session if available.\n    let accumulatedDiscoveredFiles: string[] = [];\n    if (this.session) {\n      try {\n        accumulatedDiscoveredFiles = await this.session.loadJITContext();\n      } catch { /* first run \u2014 no prior context */ }\n    }\n    let contextChunksUsed = 0;\n    let contextCharsSaved = 0;\n    const artifactPackId = workGraph.planningArtifacts\n      ? this.contextPacks.createPack(traceId, workGraph.planningArtifacts)\n      : '';\n\n    // Sort work units by dependency order\n    const sorted = this.topologicalSort(workerTasks);\n\n    // Detect if git worktree isolation is available for parallel batches\n    const projectDir = (this.sandbox as unknown as { baseDir?: string })?.baseDir || process.cwd();\n    const worktreeIsolation = (() => {\n      if (process.env.CREW_WORKTREE_ISOLATION === 'false') return false;\n      try {\n        const { execSync } = require('node:child_process');\n        execSync('git rev-parse --is-inside-work-tree', { cwd: projectDir, encoding: 'utf8', timeout: 5000 });\n        return true;\n      } catch { return false; }\n    })();\n\n    // Execute in batches (units with no pending dependencies)\n    const maxWorkers = this.getMaxParallelWorkers();\n    for (const batch of this.getBatches(sorted)) {\n      const useWorktrees = worktreeIsolation && batch.length > 1;\n      if (verbose) {\n        console.log(`[L3 Batch] Executing ${batch.length} units in parallel...`);\n        console.log(`[L3 Batch] Units: ${batch.map(u => u.id).join(', ')}`);\n        console.log(`[L3 Batch] Concurrency cap: ${maxWorkers}${useWorktrees ? ' (worktree isolation)' : ''}`);\n      }\n\n      // Create per-unit worktrees for parallel isolation\n      const unitWorktrees = new Map<string, { worktreePath: string; branchName: string }>();\n      if (useWorktrees) {\n        for (const unit of batch) {\n          try {\n            const wt = enterWorktree(projectDir, {\n              branchPrefix: 'crew-l3',\n              agentId: unit.id.slice(0, 8)\n            });\n            unitWorktrees.set(unit.id, { worktreePath: wt.worktreePath, branchName: wt.branchName });\n            if (verbose) {\n              console.log(`  [${unit.id}] worktree \u2192 ${wt.worktreePath}`);\n            }\n          } catch (err: unknown) {\n            if (verbose) console.warn(`  [${unit.id}] worktree failed, sharing filesystem: ${err instanceof Error ? err.message : String(err)}`);\n          }\n        }\n      }\n\n      const batchStart = Date.now();\n      const runUnit = async (unit: typeof batch[number]) => {\n        // Check dependencies\n        for (const depId of unit.dependencies) {\n          if (!completed.has(depId)) {\n            throw new Error(`Dependency ${depId} not completed for ${unit.id}`);\n          }\n        }\n\n        // Resolve prompt template from persona registry (covers full standalone role set).\n        const templateId = getTemplateForPersona(unit.persona);\n\n        // Inject frozen ProjectContext so workers know the tech stack\n        let projectContextSummary = '';\n        try {\n          const projCtx = await getProjectContext(process.cwd());\n          projectContextSummary = projCtx.summary;\n        } catch { /* non-fatal */ }\n        const enhancedDescription = projectContextSummary\n          ? `${projectContextSummary}\\n\\n${unit.goal}`\n          : unit.goal;\n\n        const overlays: PromptOverlay[] = [\n          { type: 'task', content: enhancedDescription, priority: 1 },\n          { type: 'context', content: context, priority: 2 }\n        ];\n\n        // Inject agent memory for cross-model continuity\n        const memory = getPipelineMemory();\n        const memoryContext = memory.recall({\n          tokenBudget: 500,\n          tags: ['l2-decision', traceId],\n          provider: 'pipeline'\n        });\n        if (memoryContext) {\n          overlays.push({\n            type: 'context',\n            content: memoryContext,\n            priority: 0\n          });\n        }\n\n        try {\n          const { autoLoadRelevantFiles, shouldUseRag } = await import('../context/codebase-rag.js');\n          const ragQuery = [\n            unit.goal,\n            accumulatedDiscoveredFiles.slice(0, 8).join(' ')\n          ].filter(Boolean).join('\\n');\n          if (shouldUseRag(ragQuery)) {\n            const ragContext = await autoLoadRelevantFiles(ragQuery, process.cwd(), {\n              mode: (process.env.CREW_RAG_MODE || 'auto') as import('../context/codebase-rag.js').RagMode,\n              tokenBudget: Number(process.env.CREW_RAG_WORKER_BUDGET || 4000),\n              maxFiles: Number(process.env.CREW_RAG_MAX_FILES_LOAD || 6),\n              sessionHistory: accumulatedDiscoveredFiles.map(file => ({ output: file }))\n            });\n            if (ragContext.context) {\n              overlays.push({\n                type: 'context',\n                content: ragContext.context,\n                priority: 3\n              });\n            }\n          }\n        } catch {\n          // Never fail a worker due to RAG injection.\n        }\n\n        if (artifactPackId) {\n          const fullArtifactChars = (workGraph.planningArtifacts?.pdd?.length || 0)\n            + (workGraph.planningArtifacts?.roadmap?.length || 0)\n            + (workGraph.planningArtifacts?.architecture?.length || 0);\n          const artifactContext = this.contextPacks.retrieve(artifactPackId, {\n            query: unit.goal,\n            sourceRefs: unit.sourceRefs || [],\n            budgetChars: Number(process.env.CREW_CONTEXT_BUDGET_CHARS || 7000),\n            maxChunks: Number(process.env.CREW_CONTEXT_MAX_CHUNKS || 8)\n          });\n          const usedChunks = (artifactContext.match(/\\[(PDD|ROADMAP|ARCH|SCAFFOLD|CONTRACT-TESTS|DOD|GOLDEN-BENCHMARKS)\\.md#/g) || []).length;\n          contextChunksUsed += usedChunks;\n          contextCharsSaved += Math.max(0, fullArtifactChars - artifactContext.length);\n          overlays.push({\n            type: 'context',\n            content: `Context pack id: ${artifactPackId}\\n${artifactContext}`,\n            priority: 2\n          });\n        }\n\n        // Add outputs from completed dependencies (bounded) so downstream workers remain coherent.\n        const dependencyOutputs: string[] = [];\n        for (const depId of unit.dependencies) {\n          const depOutput = outputByUnit.get(depId);\n          if (depOutput) {\n            dependencyOutputs.push(`[Output from ${depId}]:\\n${depOutput.substring(0, 1500)}`);\n          }\n        }\n        if (dependencyOutputs.length > 0) {\n          overlays.push({\n            type: 'context',\n            content: `Dependency outputs:\\n${dependencyOutputs.join('\\n\\n')}`,\n            priority: 3\n          });\n        }\n\n        if (Array.isArray(unit.sourceRefs) && unit.sourceRefs.length > 0) {\n          overlays.push({\n            type: 'context',\n            content: `Required source refs for this unit: ${unit.sourceRefs.join(', ')}`,\n            priority: 3\n          });\n        }\n        overlays.push({\n          type: 'constraints',\n          content: `Worker task contract:\n- Allowed paths: ${unit.allowedPaths.length > 0 ? unit.allowedPaths.join(', ') : '(no explicit paths extracted)'}\n- Verification: ${unit.verification.join(' | ')}\n- Escalate when: ${(unit.escalationHints || []).join(' | ')}`,\n          priority: 3\n        });\n        \n        // All workers use structured tool calls (write_file, replace, read_file, etc.)\n        // NEVER use @@WRITE_FILE text markers \u2014 use the write_file tool instead.\n        overlays.push({\n          type: 'constraints',\n          content: `IMPORTANT RULES:\n1. ALWAYS read_file before editing any file. Never guess at contents.\n2. Use \"replace\" tool for editing existing files (with old_string/new_string). write_file is ONLY for NEW files.\n3. Do NOT output @@WRITE_FILE or @@EDIT markers \u2014 use structured tool calls.\n4. Match the existing code style exactly. If the project uses vanilla JS (no modules), do NOT use require/import/export or Node.js APIs.\n5. After completing work, return a JSON summary: {\"output\":\"what you did\",\"summary\":\"short summary\",\"edits\":[\"files changed\"],\"validation\":[\"verification steps\"]}`,\n          priority: 4\n        });\n\n        const composedPrompt = this.composer.compose(templateId, overlays, `${traceId}-${unit.id}`);\n        const effort = this.getExecutionEffort(unit);\n        \n        if (verbose) {\n          console.log(`  [${unit.id}] ${unit.persona} executing (agentic)...`);\n        }\n        const unitStart = Date.now();\n        \n        // Use built-in L3_SYSTEM_PROMPT (has THINK\u2192ACT\u2192OBSERVE + tool list)\n        // Do NOT override with template basePrompt \u2014 those are generic and don't mention tools\n        //\n        // If this unit has a worktree, run in isolated sandbox + projectDir.\n        // Otherwise fall back to the shared sandbox (sequential or non-git).\n        const unitWt = unitWorktrees.get(unit.id);\n        const workerSandbox = unitWt ? new Sandbox(unitWt.worktreePath) : this.requireSandbox();\n        const workerProjectDir = unitWt ? unitWt.worktreePath : projectDir;\n\n        const result = await runAgenticWorker(composedPrompt.finalPrompt, workerSandbox, {\n          model: this.getModelForLayer('l3', effort) || '',\n          maxTurns: this.getMaxTurnsForEffort(effort),\n          verbose,\n          projectDir: workerProjectDir,\n          priorDiscoveredFiles: accumulatedDiscoveredFiles.length > 0 ? accumulatedDiscoveredFiles : undefined,\n          persona: unit.persona,\n          constraintLevel: undefined,\n          verificationCommands: this.extractVerificationCommands(unit)\n        });\n        const parsed = this.parseWorkerOutput(String(result.output || ''));\n\n        // Accumulate discovered files for subsequent batches\n        if (result.discoveredFiles?.length) {\n          for (const f of result.discoveredFiles) {\n            if (!accumulatedDiscoveredFiles.includes(f)) accumulatedDiscoveredFiles.push(f);\n          }\n        }\n\n        if (verbose) {\n          console.log(`  [${unit.id}] \u2705 Complete in ${Date.now() - unitStart}ms ($${result.cost?.toFixed(6) || 0}) [${result.turns ?? 0} turns]`);\n        }\n\n        completed.add(unit.id);\n        outputByUnit.set(unit.id, parsed.output);\n\n        // Store worker output in memory for cross-model continuity\n        getPipelineMemory().remember(\n          `Worker ${unit.id} (${unit.persona}): ${parsed.output.substring(0, 300)}...`,\n          { critical: false, tags: ['l3-output', traceId, unit.id], provider: 'pipeline' }\n        );\n\n        const built = this.buildWorkerExecutionResult(unit, parsed, result);\n        return this.reviewAndFixWorkerResult(unit, built, `${traceId}-${unit.id}`, context, sessionId);\n      };\n\n      const batchResults: Array<{\n        workUnitId: string;\n        persona: string;\n        output: string;\n        cost: number;\n        filesChanged: string[];\n        verification: string[];\n        verificationPassed: boolean;\n        escalationNeeded: boolean;\n        escalationReason?: string;\n        toolsUsed?: string[];\n        turns?: number;\n        shellResults?: Array<{ command: string; exitCode: number; output: string }>;\n      }> = [];\n      const queue = batch.slice();\n      const workers = Array.from({ length: Math.min(maxWorkers, queue.length) }, async () => {\n        while (queue.length > 0) {\n          const next = queue.shift();\n          if (!next) break;\n          const res = await runUnit(next);\n          batchResults.push(res);\n        }\n      });\n      await Promise.all(workers);\n\n      // Merge worktrees back to main branch sequentially\n      if (unitWorktrees.size > 0) {\n        const mergeResults: Array<{ unitId: string; success: boolean; message: string }> = [];\n        for (const [unitId, wt] of unitWorktrees) {\n          try {\n            // Exit worktree (auto-commits uncommitted changes)\n            const exitResult = await exitWorktree(projectDir, wt.branchName);\n            if (exitResult.hasChanges) {\n              // Merge the branch back into main\n              const merge = mergeWorktree(projectDir, wt.branchName, 'squash');\n              mergeResults.push({ unitId, ...merge });\n              if (verbose) {\n                console.log(`  [${unitId}] ${merge.success ? '\u2705' : '\u26A0\uFE0F'} merge: ${merge.message}`);\n              }\n            } else {\n              mergeResults.push({ unitId, success: true, message: 'No changes to merge' });\n            }\n          } catch (err: unknown) {\n            const error = err as Error;\n            mergeResults.push({ unitId, success: false, message: error.message });\n            if (verbose) console.warn(`  [${unitId}] \u26A0\uFE0F worktree cleanup failed: ${error.message}`);\n          }\n        }\n        unitWorktrees.clear();\n\n        const conflicts = mergeResults.filter(r => !r.success);\n        if (conflicts.length > 0 && verbose) {\n          console.warn(`[L3 Batch] \u26A0\uFE0F ${conflicts.length} merge conflict(s): ${conflicts.map(c => `${c.unitId}: ${c.message}`).join('; ')}`);\n        }\n      }\n\n      if (verbose) {\n        console.log(`[L3 Batch] \u2705 Batch complete in ${Date.now() - batchStart}ms`);\n      }\n\n      results.push(...batchResults);\n      totalCost += batchResults.reduce((sum, r) => sum + r.cost, 0);\n\n      // Record delegation performance for future persona ranking\n      for (const r of batchResults) {\n        const unitDef = batch.find(u => u.id === r.workUnitId);\n        if (unitDef) {\n          const taskChars = analyzeDelegationTask(unitDef.goal, unitDef.allowedPaths, unitDef.requiredCapabilities);\n          this.delegationTuner.recordPerformance({\n            persona: r.persona,\n            model: String(process.env.CREW_EXECUTION_MODEL || 'default'),\n            taskType: taskChars.taskType,\n            success: !r.escalationNeeded,\n            turns: r.turns || 0,\n            costUsd: r.cost,\n            verificationPassed: r.verificationPassed,\n            timestamp: Date.now()\n          });\n        }\n      }\n\n      // HARD COST GATE - Check during execution\n      if (totalCost > 0.50) {\n        throw new Error(\n          `Execution cost $${totalCost.toFixed(3)} exceeded limit ($0.50) during execution. ` +\n          `Partial results saved but task aborted.`\n        );\n      }\n    }\n\n    // Persist JIT context for subsequent CLI invocations\n    if (this.session && accumulatedDiscoveredFiles.length > 0) {\n      try { await this.session.saveJITContext(accumulatedDiscoveredFiles); } catch { /* best-effort */ }\n    }\n\n    return {\n      success: true,\n      results,\n      totalCost,\n      executionTimeMs: Date.now() - startTime,\n      metrics: {\n        contextChunksUsed,\n        contextCharsSaved\n      }\n    };\n  }\n\n  /**\n   * Topological sort for dependency ordering\n   */\n  private topologicalSort<T extends { id: string; dependencies: string[] }>(units: T[]): T[] {\n    const sorted: T[] = [];\n    const visited = new Set<string>();\n    const temp = new Set<string>();\n\n    const visit = (unitId: string) => {\n      if (temp.has(unitId)) {\n        throw new Error(`Circular dependency detected: ${unitId}`);\n      }\n      if (visited.has(unitId)) return;\n\n      temp.add(unitId);\n\n      const unit = units.find(u => u.id === unitId);\n      if (!unit) throw new Error(`Unit not found: ${unitId}`);\n\n      for (const depId of unit.dependencies) {\n        visit(depId);\n      }\n\n      temp.delete(unitId);\n      visited.add(unitId);\n      sorted.push(unit);\n    };\n\n    for (const unit of units) {\n      if (!visited.has(unit.id)) {\n        visit(unit.id);\n      }\n    }\n\n    return sorted;\n  }\n\n  /**\n   * Group units into parallel execution batches\n   */\n  private getBatches<T extends { id: string; dependencies: string[] }>(sortedUnits: T[]): Array<T[]> {\n    const batches: Array<T[]> = [];\n    const completed = new Set<string>();\n\n    while (completed.size < sortedUnits.length) {\n      const batch = sortedUnits.filter(unit => \n        !completed.has(unit.id) &&\n        unit.dependencies.every(depId => completed.has(depId))\n      );\n\n      if (batch.length === 0) {\n        throw new Error('Unable to resolve dependencies');\n      }\n\n      batches.push(batch);\n      batch.forEach(unit => completed.add(unit.id));\n    }\n\n    return batches;\n  }\n\n  /**\n   * Synthesize parallel results into coherent response\n   */\n  private synthesizeResults(results: L3Result): string {\n    const sections = results.results.map(r => {\n      const filesChanged = r.filesChanged || [];\n      const verification = r.verification || [];\n      const metadata = [\n        `Files: ${filesChanged.length > 0 ? filesChanged.join(', ') : '(none reported)'}`,\n        `Verification: ${r.verificationPassed ? 'passed' : 'not confirmed'}`,\n        ...(verification.length > 0 ? [`Evidence: ${verification.join(' | ')}`] : []),\n        ...(r.escalationNeeded ? [`Escalation: ${r.escalationReason || 'required'}`] : [])\n      ].join('\\n');\n      return `### ${r.persona} (${r.workUnitId})\\n\\n${metadata}\\n\\n${r.output}`;\n    });\n\n    return sections.join('\\n\\n---\\n\\n');\n  }\n\n  /**\n   * Run a worker unit \u2014 delegates to agentic executor by default.\n   * Can be overridden in tests to use a mock executor.\n   */\n  async runWorker(prompt: string, options: { model?: string; maxTurns?: number; verbose?: boolean; priorDiscoveredFiles?: string[]; persona?: string; constraintLevel?: import('../tools/gemini/crew-adapter.js').ConstraintLevel; verificationCommands?: string[] }): Promise<{ output: string; cost?: number; turns?: number; discoveredFiles?: string[] }> {\n    // Always use the agentic executor with full tool suite (write_file, replace, etc.)\n    // The LocalExecutor is a single-turn LLM call with no tools \u2014 workers need tools to write files.\n    return runAgenticWorker(prompt, this.requireSandbox(), options);\n  }\n\n  /**\n   * Check if native Gemini tool loop can be used for a given model\n   */\n  private canUseNativeGeminiToolLoop(modelId: string): boolean {\n    if (!process.env.GEMINI_API_KEY) return false;\n    const mode = (process.env.CREW_TOOL_MODE || 'auto').toLowerCase();\n    if (mode === 'markers') return false;\n    const lower = String(modelId || '').toLowerCase();\n    return lower.includes('gemini');\n  }\n\n  /**\n   * Parse tool call markers from LLM output\n   */\n  private parseToolCalls(output: string): Array<{ toolName: string; params: Record<string, string> }> {\n    const calls: Array<{ toolName: string; params: Record<string, string> }> = [];\n    const lines = output.split('\\n');\n\n    let i = 0;\n    while (i < lines.length) {\n      const line = lines[i];\n\n      // @@WRITE_FILE <path>\n      const writeMatch = line.match(/^@@WRITE_FILE\\s+(.+)$/);\n      if (writeMatch) {\n        const filePath = writeMatch[1].trim().replace(/[`;\\s]+$/g, '');\n        // Find @@END_FILE\n        let content = '';\n        let found = false;\n        let j = i + 1;\n        while (j < lines.length) {\n          if (lines[j].trim() === '@@END_FILE') {\n            found = true;\n            break;\n          }\n          content += (content ? '\\n' : '') + lines[j];\n          j++;\n        }\n        if (found) {\n          calls.push({ toolName: 'write_file', params: { file_path: filePath, content } });\n          i = j + 1;\n          continue;\n        }\n        // No terminator \u2014 skip just the @@WRITE_FILE line\n        i++;\n        continue;\n      }\n\n      // @@EDIT \"old\" \u2192 \"new\" <path>\n      const editMatch = line.match(/^@@EDIT\\s+\"(.+?)\"\\s*\u2192\\s*\"(.+?)\"\\s+(.+)$/);\n      if (editMatch) {\n        let editPath = editMatch[3].trim().replace(/[`;\\s]+$/g, '');\n        // Reject paths with @@ (likely garbled)\n        if (!editPath.includes('@@')) {\n          calls.push({ toolName: 'edit', params: { path: editPath, old: editMatch[1], new: editMatch[2] } });\n        }\n        i++;\n        continue;\n      }\n\n      // @@MKDIR <path>\n      const mkdirMatch = line.match(/^@@MKDIR\\s+(.+)$/);\n      if (mkdirMatch) {\n        const dirPath = mkdirMatch[1].trim().replace(/[`;\\s]+$/g, '');\n        if (!dirPath.includes('@@')) {\n          calls.push({ toolName: 'mkdir', params: { path: dirPath } });\n        }\n        i++;\n        continue;\n      }\n\n      i++;\n    }\n\n    return calls;\n  }\n\n  /**\n   * Get execution trace\n   */\n  getTrace(traceId: string) {\n    return {\n      composedPrompts: this.composer.getTrace(traceId),\n      plannerTrace: this.planner.getTrace(traceId)\n    };\n  }\n}\n", "// @ts-nocheck\nimport { AgentRouter } from '../agent/router.js';\nimport { Sandbox } from '../sandbox/index.js';\nimport { Logger } from '../utils/logger.js';\nimport type { Orchestrator } from './index.js';\nimport { AgentKeeper } from '../memory/agentkeeper.js';\n\nexport interface WorkerTask {\n  id: string;\n  agent: string;\n  prompt: string;\n  context?: string;\n  retries?: number;\n}\n\nexport interface WorkerPoolOptions {\n  router: AgentRouter;\n  orchestrator: Orchestrator;\n  sandbox: Sandbox;\n  keeper?: AgentKeeper;\n  concurrency?: number;\n  maxRetries?: number;\n  timeoutMs?: number;\n}\n\nexport interface TaskResult {\n  taskId: string;\n  success: boolean;\n  result?: unknown;\n  error?: string;\n  edits?: string[];\n}\n\nexport class WorkerPool {\n  private queue: WorkerTask[] = [];\n  private activeWorkers = 0;\n  private concurrency: number;\n  private maxRetries: number;\n  private timeoutMs: number;\n  private logger = new Logger();\n\n  constructor(private options: WorkerPoolOptions) {\n    this.concurrency = options.concurrency || 3;\n    this.maxRetries = options.maxRetries || 2;\n    this.timeoutMs = options.timeoutMs || 120000;\n  }\n\n  public enqueue(task: WorkerTask) {\n    this.queue.push({\n      ...task,\n      retries: task.retries || 0\n    });\n  }\n\n  public enqueueAll(tasks: WorkerTask[]) {\n    for (const t of tasks) {\n      this.enqueue(t);\n    }\n  }\n\n  public async runAll(options: { sessionId: string; projectDir: string; runId?: string }): Promise<TaskResult[]> {\n    const results: TaskResult[] = [];\n    \n    return new Promise((resolve) => {\n      const checkQueue = async () => {\n        if (this.queue.length === 0 && this.activeWorkers === 0) {\n          resolve(results);\n          return;\n        }\n\n        while (this.activeWorkers < this.concurrency && this.queue.length > 0) {\n          const task = this.queue.shift();\n          if (!task) continue;\n\n          this.activeWorkers++;\n          \n          this.executeTask(task, options)\n            .then((result) => {\n              results.push(result);\n              this.activeWorkers--;\n              checkQueue();\n            })\n            .catch((err) => {\n              this.logger.error(`Worker pool critical failure for task ${task.id}: ${err.message}`);\n              results.push({ taskId: task.id, success: false, error: err.message });\n              this.activeWorkers--;\n              checkQueue();\n            });\n        }\n      };\n\n      checkQueue();\n    });\n  }\n\n  private async executeTask(task: WorkerTask, options: { sessionId: string; projectDir: string; runId?: string }): Promise<TaskResult> {\n    this.logger.info(`[WorkerPool] Starting task: ${task.id} with agent ${task.agent}`);\n    \n    let attempt = 0;\n    while (attempt <= this.maxRetries) {\n      try {\n        const timeoutPromise = new Promise<never>((_, reject) => {\n          setTimeout(() => reject(new Error(`Timeout after ${this.timeoutMs}ms`)), this.timeoutMs);\n        });\n\n        const fullPrompt = task.context ? `${task.prompt}\n\n${task.context}` : task.prompt;\n\n        const dispatchPromise = this.options.router.dispatch(task.agent, fullPrompt, {\n          sessionId: options.sessionId,\n          project: options.projectDir,\n          timeout: this.timeoutMs.toString()\n        });\n\n        const result = await Promise.race([dispatchPromise, timeoutPromise]) as Record<string, unknown>;\n\n        const responseText = String(result.result || '');\n        const edits = await this.options.orchestrator.parseAndApplyToSandbox(responseText);\n        if (this.options.keeper && responseText.trim().length > 0) {\n          const saved = await this.options.keeper.recordSafe({\n            runId: options.runId || 'worker-run',\n            tier: 'worker',\n            task: task.prompt,\n            result: responseText,\n            agent: task.agent,\n            metadata: {\n              taskId: task.id,\n              edits: edits.length,\n              retries: attempt\n            }\n          });\n          if (!saved.ok) {\n            this.logger.warn(`[WorkerPool] Memory write skipped for task ${task.id}: ${saved.error}`);\n          }\n        }\n\n        this.logger.success(`[WorkerPool] Task completed: ${task.id}`);\n        return {\n          taskId: task.id,\n          success: true,\n          result: responseText,\n          edits\n        };\n\n      } catch (err) {\n        attempt++;\n        this.logger.warn(`[WorkerPool] Task ${task.id} failed (attempt ${attempt}/${this.maxRetries + 1}): ${(err as Error).message}`);\n        \n        if (attempt > this.maxRetries) {\n          return {\n            taskId: task.id,\n            success: false,\n            error: err.message\n          };\n        }\n        \n        // Wait before retry\n        await new Promise(r => setTimeout(r, 2000 * attempt));\n      }\n    }\n    \n    return { taskId: task.id, success: false, error: 'Max retries exceeded' };\n  }\n}\n", "// @ts-nocheck\nimport { Sandbox } from '../sandbox/index.js';\nimport { AgentRouter } from '../agent/router.js';\nimport { Logger } from '../utils/logger.js';\nimport { getStrategy } from '../strategies/index.js';\nimport { SessionManager } from '../session/manager.js';\nimport { readFile } from 'node:fs/promises';\nimport { LocalExecutor } from '../executor/local.js';\nimport { getProfileConfig, type RuntimeProfile } from '../executor/profiles.js';\nimport { UnifiedPipeline } from '../pipeline/unified.js';\nimport { parseJsonObjectWithRepair } from '../utils/structured-json.js';\n\nexport { WorkerPool } from './worker-pool.js';\nexport type { WorkerTask, TaskResult, WorkerPoolOptions } from './worker-pool.js';\n\nconst ROUTING_SYSTEM_PROMPT = `You are the intelligent routing system for crewswarm CLI (always lowercase \"crewswarm\"), a standalone agentic coding engine.\n\nRoute this request to one of: direct-answer, execute-direct, execute-parallel.\n\n- direct-answer: Simple conversation, greetings, status checks, or questions about YOUR identity/capabilities. Provide response in \"directResponse\".\n- execute-direct: Code editing, building, implementing, single-file tasks, questions about files/project state, or any development task.\n- execute-parallel: Complex multi-file features, large refactors, or multi-step implementation tasks.\n\nYou are running as a standalone CLI assistant. You do NOT dispatch to external agents or a swarm.\n\nReturn ONLY a JSON object in this exact format:\n{\"decision\":\"direct-answer|execute-direct|execute-parallel\",\"reasoning\":\"why this path\",\"directResponse\":\"if direct-answer, your response here\",\"complexity\":\"low|medium|high\",\"estimatedCost\":0.001}`;\n\nexport enum RouteDecision {\n  CHAT = 'CHAT',\n  CODE = 'CODE',\n  DISPATCH = 'DISPATCH',\n  SKILL = 'SKILL'\n}\n\nexport interface RouteResult {\n  decision: RouteDecision;\n  agent?: string;\n  task?: string;\n  explanation?: string;\n  response?: string; // For CHAT decisions, the LLM's conversational response\n}\n\ninterface AuthorizedUserCredentials {\n  type?: string;\n  refresh_token?: string;\n  client_id?: string;\n  client_secret?: string;\n}\n\ninterface ChatCompletionLikeResponse {\n  choices?: Array<{\n    message?: {\n      content?: string;\n    };\n  }>;\n}\n\ninterface GeminiRouteResponse {\n  candidates?: Array<{\n    content?: {\n      parts?: Array<{ text?: string }>;\n    };\n  }>;\n}\n\ninterface LocalExecutionResult {\n  success: boolean;\n  result: string;\n  model?: string;\n  promptTokens?: number;\n  completionTokens?: number;\n  costUsd?: number;\n}\n\ninterface AgenticExecutionOptions {\n  model?: string;\n  onToolCall?: (name: string, params: Record<string, unknown>) => void;\n  conversationContext?: string;\n  sessionId?: string;\n  verbose?: boolean;\n  deferApply?: boolean;\n}\n\nexport class Orchestrator {\n  private logger = new Logger();\n  private localExecutor = new LocalExecutor();\n  private pipeline: UnifiedPipeline;\n\n  constructor(\n    private router: AgentRouter,\n    private sandbox: Sandbox,\n    private session: SessionManager,\n    private profile: RuntimeProfile = 'builder'\n  ) {\n    this.pipeline = new UnifiedPipeline(sandbox, session);\n  }\n\n  /**\n   * Decides which path to take based on user input.\n   */\n  async route(input: string): Promise<RouteResult> {\n    const useUnifiedRouter = this.shouldUseUnifiedRouter();\n    if (useUnifiedRouter) {\n      try {\n        const routed = await this.pipeline.routeOnly({\n          userInput: input,\n          sessionId: 'crew-cli'\n        });\n        const result: RouteResult = {\n          decision: routed.decision as RouteDecision,\n          agent: routed.agent,\n          task: routed.task,\n          response: routed.response,\n          explanation: routed.explanation\n        };\n        await this.logRoutingDecision(input, result);\n        return result;\n      } catch (err) {\n        // Fall through to deterministic routing if unified planner fails.\n        console.warn(`[Orchestrator] routeOnly failed, falling back to legacy router: ${(err as Error).message}`);\n      }\n    }\n\n    const llmDecision = await this.routeWithLLM(input);\n    if (llmDecision) {\n      if (llmDecision.decision === RouteDecision.CHAT && this.isExecutionIntent(input)) {\n        llmDecision.decision = RouteDecision.CODE;\n        llmDecision.agent = llmDecision.agent || 'crew-coder';\n        llmDecision.task = llmDecision.task || input;\n        llmDecision.explanation = 'Execution intent detected; bypassing chat-only route';\n      }\n      llmDecision.agent = this.normalizeAgentName(llmDecision.agent);\n      // Ensure CODE decisions always have an agent\n      if (llmDecision.decision === RouteDecision.CODE && !llmDecision.agent) {\n        llmDecision.agent = 'crew-coder';\n      }\n      await this.logRoutingDecision(input, llmDecision);\n      return llmDecision;\n    }\n\n    const lower = input.toLowerCase();\n    const isStandalone = String(process.env.CREW_INTERFACE_MODE || 'standalone').toLowerCase() !== 'connected';\n    let result: RouteResult;\n\n    // Skill calling detection\n    if (lower.startsWith('skill:') || lower.includes('run skill')) {\n      result = { decision: RouteDecision.SKILL, explanation: 'Detected skill request' };\n    }\n    // Planning/PM tasks - roadmap, planning, architecture, research\n    else if (\n      lower.includes('roadmap') ||\n      lower.includes('plan for') ||\n      lower.includes('planning') ||\n      lower.includes('architecture') ||\n      lower.includes('design doc') ||\n      (lower.includes('build') && (lower.includes('website') || lower.includes('app') || lower.includes('system'))) ||\n      (lower.includes('research') && (lower.includes('indepth') || lower.includes('in-depth')))\n    ) {\n      result = { decision: isStandalone ? RouteDecision.CODE : RouteDecision.DISPATCH, agent: isStandalone ? 'crew-coder' : 'crew-pm', task: input };\n    }\n    // Specialist dispatch detection\n    else if (lower.includes('ask') || lower.includes('tell')) {\n      if (isStandalone) {\n        result = { decision: RouteDecision.CODE, agent: 'crew-coder', task: input };\n      } else if (lower.includes('fixer') || lower.includes('fix')) {\n        result = { decision: RouteDecision.DISPATCH, agent: 'crew-fixer', task: input };\n      } else if (lower.includes('qa') || lower.includes('test')) {\n        result = { decision: RouteDecision.DISPATCH, agent: 'crew-qa', task: input };\n      } else if (lower.includes('frontend') || lower.includes('ui')) {\n        result = { decision: RouteDecision.DISPATCH, agent: 'crew-frontend', task: input };\n      } else if (lower.includes('security') || lower.includes('audit')) {\n        result = { decision: RouteDecision.DISPATCH, agent: 'crew-security', task: input };\n      } else {\n        result = { decision: RouteDecision.DISPATCH, agent: 'crew-main', task: input };\n      }\n    }\n    // Code generation/building detection\n    else if (\n      lower.includes('create') || \n      lower.includes('implement') || \n      lower.includes('modify') || \n      lower.includes('add') || \n      lower.includes('write') ||\n      lower.includes('change') ||\n      lower.includes('update') ||\n      lower.includes('build') ||\n      lower.includes('make')\n    ) {\n      result = { decision: RouteDecision.CODE, agent: 'crew-coder', task: input };\n    }\n    // Simple questions about system capabilities\n    else if (\n      (lower.includes('what') || lower.includes('how') || lower.includes('which')) &&\n      (lower.includes('model') || lower.includes('version') || lower.includes('agent'))\n    ) {\n      result = { \n        decision: RouteDecision.CHAT, \n        response: \"I'm crew-cli, a multi-agent orchestration system. I can build code, plan projects, fix bugs, review security, and coordinate specialists. Try asking me to build something or create a roadmap!\",\n        explanation: 'System info query'\n      };\n    }\n    else if (\n      lower === 'hello' ||\n      lower === 'hi' ||\n      lower === 'hey' ||\n      lower.startsWith('hello ') ||\n      lower.startsWith('hi ') ||\n      lower.startsWith('hey ')\n    ) {\n      result = {\n        decision: RouteDecision.CHAT,\n        response: 'Hey. What do you want to build or fix?',\n        explanation: 'Greeting'\n      };\n    }\n    else {\n      result = { decision: isStandalone ? RouteDecision.CODE : RouteDecision.DISPATCH, agent: isStandalone ? 'crew-coder' : 'crew-main', task: input };\n    }\n\n    await this.logRoutingDecision(input, result);\n    return result;\n  }\n\n  private shouldUseUnifiedRouter(): boolean {\n    const explicitLegacy = String(process.env.CREW_LEGACY_ROUTER || '').trim().toLowerCase();\n    if (explicitLegacy === '1' || explicitLegacy === 'true' || explicitLegacy === 'yes') {\n      return false;\n    }\n    const explicit = String(process.env.CREW_USE_UNIFIED_ROUTER || '').trim().toLowerCase();\n    if (!explicit) return true;\n    return !(explicit === '0' || explicit === 'false' || explicit === 'no' || explicit === 'off');\n  }\n\n  private isExecutionIntent(input: string): boolean {\n    const lower = String(input || '').toLowerCase();\n    return /\\b(implement|create|build|write|fix|refactor|modify|update|add|patch|test|run tests|make tests pass)\\b/.test(lower)\n      || /\\/src\\/|\\.ts\\b|\\.js\\b|\\.tsx\\b|\\.py\\b/.test(lower);\n  }\n\n  private async getGeminiADCToken(): Promise<string | null> {\n    try {\n      const adcPath = process.env.GOOGLE_APPLICATION_CREDENTIALS || \n                      `${process.env.HOME}/.config/gcloud/application_default_credentials.json`;\n      \n      const { readFile } = await import('node:fs/promises');\n      const credentialsJson = await readFile(adcPath, 'utf8');\n      const credentials = JSON.parse(credentialsJson) as AuthorizedUserCredentials;\n      \n      if (credentials.type !== 'authorized_user' || !credentials.refresh_token) {\n        return null;\n      }\n      \n      // Exchange refresh token for access token\n      const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({\n          client_id: credentials.client_id,\n          client_secret: credentials.client_secret,\n          refresh_token: credentials.refresh_token,\n          grant_type: 'refresh_token'\n        })\n      });\n      \n      if (!tokenResponse.ok) return null;\n      \n      const tokenData = await tokenResponse.json() as { access_token?: string };\n      return tokenData.access_token || null;\n    } catch {\n      return null;\n    }\n  }\n\n  private normalizeAgentName(raw?: string): string | undefined {\n    if (!raw) return raw;\n    const lower = raw.toLowerCase().replace(/[^a-z]/g, '');\n    const aliases: Record<string, string> = {\n      fixer: 'crew-fixer', thefixer: 'crew-fixer', crewfixer: 'crew-fixer',\n      coder: 'crew-coder', thecoder: 'crew-coder', crewcoder: 'crew-coder',\n      qa: 'crew-qa', theqa: 'crew-qa', crewqa: 'crew-qa',\n      frontend: 'crew-frontend', thefrontend: 'crew-frontend', crewfrontend: 'crew-frontend',\n      main: 'crew-main', crewmain: 'crew-main',\n      security: 'crew-security', crewsecurity: 'crew-security',\n      pm: 'crew-pm', crewpm: 'crew-pm',\n      copywriter: 'crew-copywriter', crewcopywriter: 'crew-copywriter',\n    };\n    return aliases[lower] || (raw.startsWith('crew-') ? raw : undefined);\n  }\n\n  private getJsonRepairModel(): string | undefined {\n    const explicit = String(process.env.CREW_JSON_REPAIR_MODEL || '').trim();\n    if (explicit) return explicit;\n    if (process.env.GROQ_API_KEY) return 'llama-3.3-70b-versatile';\n    if (process.env.XAI_API_KEY) return 'grok-4-1-fast-reasoning';\n    if (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY) return 'gemini-2.5-flash';\n    if (process.env.DEEPSEEK_API_KEY) return 'deepseek-chat';\n    return undefined;\n  }\n\n  private async parseRouteJson(raw: string, fallbackTask: string): Promise<RouteResult | null> {\n    try {\n      const parsed = await parseJsonObjectWithRepair(raw, {\n        label: 'Route decision',\n        schemaHint: '{\"decision\":\"direct-answer|execute-direct|execute-parallel\",\"reasoning\":\"...\",\"directResponse\":\"...\",\"complexity\":\"low|medium|high\",\"estimatedCost\":0.001}',\n        repair: async (repairPrompt: string) => {\n          const res = await this.localExecutor.execute(repairPrompt, {\n            model: this.getJsonRepairModel(),\n            temperature: 0,\n            maxTokens: 500\n          });\n          return String(res.result || '');\n        }\n      });\n      // Map L2-style decisions to RouteDecision enum\n      const rawDecision = String(parsed.decision || '').trim().toLowerCase().replace(/_/g, '-');\n      let decision: RouteDecision;\n      if (rawDecision === 'direct-answer' || rawDecision === 'chat' || rawDecision === 'answer') {\n        decision = RouteDecision.CHAT;\n      } else if (rawDecision === 'execute-direct' || rawDecision === 'code' || rawDecision === 'simple' || rawDecision === 'execute') {\n        decision = RouteDecision.CODE;\n      } else if (rawDecision === 'execute-parallel' || rawDecision === 'dispatch' || rawDecision === 'plan' || rawDecision === 'build') {\n        // In standalone mode, parallel execution is handled locally \u2014 map to CODE\n        decision = RouteDecision.CODE;\n      } else if (rawDecision === 'skill') {\n        decision = RouteDecision.SKILL;\n      } else {\n        // Try uppercase match for backward compat\n        const upper = rawDecision.toUpperCase();\n        if (Object.values(RouteDecision).includes(upper as RouteDecision)) {\n          decision = upper as RouteDecision;\n        } else {\n          return null;\n        }\n      }\n      // Never produce DISPATCH in standalone \u2014 remap to CODE\n      if (decision === RouteDecision.DISPATCH) {\n        decision = RouteDecision.CODE;\n      }\n      return {\n        decision,\n        agent: parsed.agent || (decision === RouteDecision.CODE ? 'crew-coder' : undefined),\n        task: parsed.task || fallbackTask,\n        response: parsed.directResponse || parsed.response || undefined,\n        explanation: parsed.reasoning || parsed.explanation || 'LLM-based routing'\n      };\n    } catch {\n      return null;\n    }\n  }\n\n  private async routeWithLLM(input: string): Promise<RouteResult | null> {\n    // Read routing priority from env (default: grok,gemini,deepseek)\n    const routingOrder = (process.env.CREW_ROUTING_ORDER || 'grok,gemini,deepseek')\n      .toLowerCase()\n      .split(',')\n      .map(s => s.trim());\n    \n    for (const provider of routingOrder) {\n      let result: RouteResult | null = null;\n      \n      switch (provider) {\n        case 'grok':\n        case 'xai':\n          result = await this.routeWithGrok(input);\n          break;\n        case 'gemini':\n          const geminiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;\n          if (geminiKey) {\n            result = await this.routeWithGemini(input, geminiKey);\n          } else {\n            const adcToken = await this.getGeminiADCToken();\n            if (adcToken) {\n              result = await this.routeWithGemini(input, adcToken);\n            }\n          }\n          break;\n        case 'deepseek':\n          result = await this.routeWithDeepSeek(input);\n          break;\n        case 'groq':\n          if (process.env.GROQ_ROUTING_ENABLED === 'true') {\n            result = await this.routeWithGroq(input);\n          }\n          break;\n      }\n      \n      if (result) return result;\n    }\n    \n    return null; // Use fallback heuristic routing\n  }\n\n  private async routeWithGrok(input: string): Promise<RouteResult | null> {\n    const key = process.env.XAI_API_KEY;\n    if (!key) return null;\n\n    try {\n      const response = await fetch('https://api.x.ai/v1/chat/completions', {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          Authorization: `Bearer ${key}`\n        },\n        body: JSON.stringify({\n          model: 'grok-beta',\n          messages: [\n            {\n              role: 'system',\n              content: ROUTING_SYSTEM_PROMPT\n            },\n            {\n              role: 'user',\n              content: input\n            }\n          ],\n          temperature: 0.3\n        })\n      });\n\n      if (!response.ok) return null;\n\n      const data = await response.json() as ChatCompletionLikeResponse;\n      const content = data?.choices?.[0]?.message?.content;\n      if (!content) return null;\n\n      const routed = await this.parseRouteJson(content, input);\n      if (!routed) return null;\n      routed.explanation = routed.explanation || 'Grok routing';\n      return routed;\n    } catch {\n      return null;\n    }\n  }\n\n  private async routeWithDeepSeek(input: string): Promise<RouteResult | null> {\n    const key = process.env.DEEPSEEK_API_KEY;\n    if (!key) return null;\n\n    try {\n      const response = await fetch('https://api.deepseek.com/v1/chat/completions', {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          Authorization: `Bearer ${key}`\n        },\n        body: JSON.stringify({\n          model: 'deepseek-chat',\n          messages: [\n            {\n              role: 'system',\n              content: ROUTING_SYSTEM_PROMPT\n            },\n            {\n              role: 'user',\n              content: input\n            }\n          ],\n          temperature: 0.3\n        })\n      });\n\n      if (!response.ok) return null;\n\n      const data = await response.json() as ChatCompletionLikeResponse;\n      const content = data?.choices?.[0]?.message?.content;\n      if (!content) return null;\n\n      const routed = await this.parseRouteJson(content, input);\n      if (!routed) return null;\n      routed.explanation = routed.explanation || 'DeepSeek routing';\n      return routed;\n    } catch {\n      return null;\n    }\n  }\n\n  private async routeWithGroq(input: string): Promise<RouteResult | null> {\n    const key = process.env.GROQ_API_KEY;\n    if (!key) return null;\n\n    try {\n      const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          Authorization: `Bearer ${key}`\n        },\n        body: JSON.stringify({\n          model: 'llama-3.3-70b-versatile',\n          messages: [\n            {\n              role: 'system',\n              content: ROUTING_SYSTEM_PROMPT\n            },\n            {\n              role: 'user',\n              content: input\n            }\n          ],\n          temperature: 0.3\n        })\n      });\n\n      if (!response.ok) return null;\n\n      const data = await response.json() as ChatCompletionLikeResponse;\n      const content = data?.choices?.[0]?.message?.content;\n      if (!content) return null;\n\n      const routed = await this.parseRouteJson(content, input);\n      if (!routed) return null;\n      routed.explanation = routed.explanation || 'LLM-based routing';\n      return routed;\n    } catch {\n      return null;\n    }\n  }\n\n  private async routeWithGemini(input: string, apiKey: string): Promise<RouteResult | null> {\n    try {\n      const response = await fetch('https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=' + encodeURIComponent(apiKey), {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({\n          contents: [{\n            parts: [{\n              text: `${ROUTING_SYSTEM_PROMPT}\\n\\nUser request: ${input}`\n            }]\n          }],\n          generationConfig: {\n            temperature: 0,\n            maxOutputTokens: 500\n          }\n        })\n      });\n\n      if (!response.ok) return null;\n      const data = await response.json() as GeminiRouteResponse;\n      const content = data?.candidates?.[0]?.content?.parts?.[0]?.text;\n      if (!content) return null;\n\n      const routed = await this.parseRouteJson(content, input);\n      if (!routed) return null;\n      routed.explanation = routed.explanation || 'Routed via Gemini 2.0 Flash (2M context)';\n      return routed;\n    } catch {\n      return null;\n    }\n  }\n\n  private async logRoutingDecision(input: string, result: RouteResult) {\n    await this.session.appendRouting({\n      input,\n      decision: result.decision,\n      agent: result.agent,\n      explanation: result.explanation\n    });\n  }\n\n  /**\n   * Tracks cost for a given model and token counts.\n   */\n  async trackCost(model: string, promptTokens: number, completionTokens: number) {\n    // Simple cost estimation (can be expanded with model-specific pricing)\n    const costPerMillion = 1.0; // placeholder: $1.00 per 1M tokens\n    const usd = ((promptTokens + completionTokens) / 1_000_000) * costPerMillion;\n    \n    await this.session.trackCost({\n      model,\n      promptTokens,\n      completionTokens,\n      usd\n    });\n  }\n\n  /**\n   * Parses output for Aider-style SEARCH/REPLACE blocks.\n   */\n  /**\n   * Execute a task locally without gateway (Tier 2 direct execution)\n   */\n  async executeLocally(task: string, options: { model?: string; explicitModel?: boolean } = {}): Promise<LocalExecutionResult> {\n    try {\n      const result = await this.localExecutor.execute(task, {\n        model: options.model,\n        explicitModel: Boolean(options.explicitModel),\n        temperature: 0.7,\n        maxTokens: 4000\n      });\n\n      return {\n        success: result.success,\n        result: result.result,\n        model: result.model,\n        promptTokens: result.promptTokens,\n        completionTokens: result.completionTokens,\n        costUsd: result.costUsd\n      };\n    } catch (err) {\n      return {\n        success: false,\n        result: `Local execution failed: ${(err as Error).message}`,\n        model: 'none',\n        error: (err as Error).message\n      };\n    }\n  }\n\n  /**\n   * Execute full unified L1->L2->L3 pipeline locally.\n   */\n  async executePipeline(\n    task: string,\n    context = '',\n    sessionId = 'crew-cli',\n    resume?: {\n      fromPhase?: 'plan' | 'execute' | 'validate';\n      priorPlan?: unknown;\n      priorResponse?: string;\n      priorExecutionResults?: unknown;\n    },\n    preClassifiedDecision?: 'direct-answer' | 'execute-parallel',\n    directResponse?: string\n  ): Promise<LocalExecutionResult & Record<string, unknown>> {\n    const out = await this.pipeline.execute({\n      userInput: task,\n      context,\n      sessionId,\n      preClassifiedDecision,\n      directResponse,\n      resume\n    });\n    return {\n      ...out,\n      success: true,\n      result: out.response,\n      costUsd: out.totalCost,\n      model: 'unified-pipeline'\n    };\n  }\n\n  /**\n   * Get current runtime profile configuration\n   */\n  getProfile() {\n    return getProfileConfig(this.profile);\n  }\n\n  /**\n   * Set runtime profile\n   */\n  setProfile(profile: RuntimeProfile) {\n    this.profile = profile;\n  }\n\n  /**\n   * Get execution trace for debugging\n   */\n  getTrace(traceId: string) {\n    return this.pipeline.getTrace(traceId);\n  }\n\n  /**\n   * Execute a task using the agentic executor with full file tools.\n   * This is the primary execution path \u2014 single worker with THINK\u2192ACT\u2192OBSERVE loop\n   * and 45+ tools (read_file, write_file, replace, bash, grep, etc.).\n   * Equivalent to how Claude Code, Codex CLI, and Gemini CLI execute tasks.\n   */\n  async executeAgentic(\n    task: string,\n    options: AgenticExecutionOptions = {}\n  ): Promise<Record<string, unknown>> {\n    try {\n      const fullTask = options.conversationContext\n        ? `## Recent conversation context\\n${options.conversationContext}\\n\\n## Current task\\n${task}`\n        : task;\n\n      const result = await this.pipeline.execute({\n        userInput: fullTask,\n        sessionId: options.sessionId || 'crew-cli',\n        context: options.conversationContext,\n        deferApply: options.deferApply\n      });\n\n      return {\n        success: result.phase === 'complete',\n        result: result.response,\n        response: result.response,\n        model: options.model || process.env.CREW_EXECUTION_MODEL || 'gemini-2.5-flash',\n        turns: result.executionResults?.results?.length || 0,\n        toolsUsed: Array.from(new Set((result.executionResults?.results || []).flatMap(r => r.toolsUsed || []))),\n        costUsd: result.totalCost || 0,\n        totalCost: result.totalCost || 0,\n        plan: result.plan,\n        traceId: result.traceId,\n        timeline: result.timeline,\n        executionPath: result.executionPath\n      };\n    } catch (err) {\n      return {\n        success: false,\n        result: `Agentic execution failed: ${(err as Error).message}`,\n        response: `Agentic execution failed: ${(err as Error).message}`,\n        model: options.model || process.env.CREW_EXECUTION_MODEL || 'gemini-2.5-flash',\n        error: (err as Error).message\n      };\n    }\n  }\n\n  async parseAndApplyToSandbox(agentOutput: string): Promise<string[]> {\n    const lines = agentOutput.split('\\n');\n    const changedFiles: string[] = [];\n\n    // First parse @@WRITE_FILE/@@MKDIR/write: syntax commands.\n    try {\n      const { parseDirectFileCommands, parseWriteSyntax, executeDirectCommands } = await import('../cli/file-commands.js');\n      const directCommands = [\n        ...parseDirectFileCommands(agentOutput),\n        ...parseWriteSyntax(agentOutput)\n      ];\n      if (directCommands.length > 0) {\n        const directChanged = await executeDirectCommands(directCommands, this.sandbox, this.logger);\n        changedFiles.push(...directChanged);\n      }\n    } catch (err) {\n      this.logger.error(`Direct command parsing failed: ${(err as Error).message}`);\n    }\n    \n    let i = 0;\n    while (i < lines.length) {\n      const line = lines[i].trim();\n      \n      // Support @@WRITE_FILE format (crewswarm tool syntax)\n      if (line.startsWith('@@WRITE_FILE')) {\n        const filePath = line.replace('@@WRITE_FILE', '').trim();\n        let blockContent = '';\n        let j = i + 1;\n        \n        while (j < lines.length && !lines[j].trim().startsWith('@@END_FILE')) {\n          blockContent += lines[j] + '\\n';\n          j++;\n        }\n        \n        if (blockContent.trim().length > 0) {\n          await this.sandbox.addChange(filePath, blockContent.trimEnd() + '\\n');\n          changedFiles.push(filePath);\n        }\n        \n        i = j + 1; // Skip past @@END_FILE\n      }\n      // Support \"FILE: path/to/file\" or \"File: path/to/file\"\n      else if (line.toLowerCase().startsWith('file:')) {\n        const filePath = line.split(':')[1].trim();\n        let blockContent = '';\n        let j = i + 1;\n        \n        while (j < lines.length && !lines[j].trim().toLowerCase().startsWith('file:') && !lines[j].trim().startsWith('@@WRITE_FILE')) {\n          blockContent += lines[j] + '\\n';\n          j++;\n        }\n\n        if (blockContent.includes('<<<<<< SEARCH')) {\n          try {\n            this.logger.info(`Detected edit block for ${filePath}`);\n            \n            let originalContent = '';\n            try {\n              originalContent = await readFile(filePath, 'utf8');\n            } catch {\n              originalContent = '';\n            }\n            const modifiedContent = this.extractBlocksAndApply(blockContent, originalContent);\n            await this.sandbox.addChange(filePath, modifiedContent);\n            changedFiles.push(filePath);\n          } catch (err) {\n            this.logger.error(`Error parsing blocks for ${filePath}: ${(err as Error).message}`);\n          }\n        } else if (blockContent.trim().length > 0) {\n          // Whole-file fallback: if a FILE block does not include edit markers, store as full rewrite.\n          await this.sandbox.addChange(filePath, blockContent.trimEnd() + '\\n');\n          changedFiles.push(filePath);\n        }\n        \n        i = j;\n      } else {\n        i++;\n      }\n    }\n\n    return Array.from(new Set(changedFiles));\n  }\n\n  private extractBlocksAndApply(blockContent: string, originalContent: string): string {\n    // This uses the SearchReplaceStrategy logic\n    const strategy = getStrategy('search-replace');\n    return strategy.apply(originalContent, blockContent);\n  }\n}\n", "/**\n * AgentKeeper \u2014 cross-tier persistent task memory.\n *\n * Stores planner decisions, worker outputs, and task results in a local\n * append-only JSONL store (`.crew/agentkeeper.jsonl`).  Supports retrieval\n * of prior entries by task similarity so repeated tasks can reuse earlier\n * decomposition patterns.  Compaction keeps the store bounded.\n */\n\nimport { appendFile, mkdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { randomUUID } from 'node:crypto';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface MemoryEntry {\n  id: string;\n  runId: string;\n  tier: 'planner' | 'worker' | 'orchestrator';\n  task: string;\n  result: string;\n  structured?: {\n    problem?: string;\n    plan?: string[];\n    edits?: Array<{ path?: string; summary?: string }>;\n    validation?: { lintPassed?: boolean; testsPassed?: boolean; notes?: string };\n    outcome?: string;\n  };\n  agent?: string;\n  model?: string;\n  metadata?: Record<string, unknown>;\n  timestamp: string;\n}\n\nexport interface MemoryMatch {\n  entry: MemoryEntry;\n  score: number;\n}\n\nexport interface CompactionResult {\n  entriesBefore: number;\n  entriesAfter: number;\n  bytesFreed: number;\n}\n\ninterface AgentKeeperOptions {\n  storageDir?: string;\n  maxEntries?: number;\n  maxBytes?: number;\n  maxAgeDays?: number;\n  autoCompactEvery?: number;\n  semanticDedupe?: boolean;\n  dedupeThreshold?: number;\n}\n\ninterface RecallOptions {\n  preferSuccessful?: boolean;\n  pathHints?: string[];\n  nowMs?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction tokenize(text: string): Set<string> {\n  return new Set(\n    text\n      .toLowerCase()\n      .replace(/[^a-z0-9\\s_-]/g, ' ')\n      .split(/\\s+/)\n      .filter(t => t.length > 2)\n  );\n}\n\nfunction similarity(a: Set<string>, b: Set<string>): number {\n  if (a.size === 0 || b.size === 0) return 0;\n  let intersection = 0;\n  for (const token of a) {\n    if (b.has(token)) intersection++;\n  }\n  return intersection / Math.max(a.size, b.size);\n}\n\n// ---------------------------------------------------------------------------\n// AgentKeeper class\n// ---------------------------------------------------------------------------\n\nexport class AgentKeeper {\n  private storePath: string;\n  private maxEntries: number;\n  private maxBytes: number;\n  private maxAgeDays: number;\n  private autoCompactEvery: number;\n  private semanticDedupe: boolean;\n  private dedupeThreshold: number;\n  private writeCount = 0;\n\n  constructor(baseDir: string, options: AgentKeeperOptions = {}) {\n    const storageBase = options.storageDir || process.env.CREW_MEMORY_DIR || baseDir;\n    this.storePath = join(storageBase, '.crew', 'agentkeeper.jsonl');\n    this.maxEntries = options.maxEntries ?? 500;\n    this.maxBytes = options.maxBytes ?? 2_000_000;\n    this.maxAgeDays = options.maxAgeDays ?? 30;\n    this.autoCompactEvery = options.autoCompactEvery ?? 20;\n    this.semanticDedupe = options.semanticDedupe ?? true;\n    this.dedupeThreshold = options.dedupeThreshold ?? 0.9;\n  }\n\n  private redactText(input: string): string {\n    let out = String(input || '');\n    const replacements: Array<[RegExp, string]> = [\n      [/\\bsk-[A-Za-z0-9]{16,}\\b/g, '[REDACTED_API_KEY]'],\n      [/\\b(?:ghp|gho|ghu|ghs|github_pat)_[A-Za-z0-9_]{16,}\\b/g, '[REDACTED_GITHUB_TOKEN]'],\n      [/\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi, '[REDACTED_EMAIL]'],\n      [/\\beyJ[A-Za-z0-9_\\-]{8,}\\.[A-Za-z0-9_\\-]{8,}\\.[A-Za-z0-9_\\-]{8,}\\b/g, '[REDACTED_JWT]'],\n      [/\\b[A-Fa-f0-9]{40,}\\b/g, '[REDACTED_HEX_TOKEN]'],\n      [/\\b[A-Za-z0-9+/]{80,}={0,2}\\b/g, '[REDACTED_BASE64_BLOB]']\n    ];\n    for (const [rx, replacement] of replacements) {\n      out = out.replace(rx, replacement);\n    }\n    return out;\n  }\n\n  private sanitizeText(input: string, maxChars = 6000): string {\n    const redacted = this.redactText(String(input || ''));\n    if (redacted.length <= maxChars) return redacted;\n    return `${redacted.slice(0, maxChars)}\\n... [truncated ${redacted.length - maxChars} chars]`;\n  }\n\n  private sanitizeMetadata(value: unknown, depth = 0): unknown {\n    if (depth > 3) return '[TRUNCATED_DEPTH]';\n    if (value === null || value === undefined) return value;\n    if (typeof value === 'string') return this.sanitizeText(value, 1000);\n    if (typeof value === 'number' || typeof value === 'boolean') return value;\n    if (Array.isArray(value)) return value.slice(0, 50).map(item => this.sanitizeMetadata(item, depth + 1));\n    if (typeof value === 'object') {\n      const out: Record<string, unknown> = {};\n      for (const [k, v] of Object.entries(value as Record<string, unknown>).slice(0, 100)) {\n        out[k] = this.sanitizeMetadata(v, depth + 1);\n      }\n      return out;\n    }\n    return String(value);\n  }\n\n  private normalizeStructured(structured: MemoryEntry['structured']): MemoryEntry['structured'] | undefined {\n    if (!structured) return undefined;\n    const out: NonNullable<MemoryEntry['structured']> = {};\n    if (structured.problem) out.problem = this.sanitizeText(structured.problem, 1200);\n    if (Array.isArray(structured.plan)) {\n      out.plan = structured.plan.slice(0, 50).map(step => this.sanitizeText(step, 300));\n    }\n    if (Array.isArray(structured.edits)) {\n      out.edits = structured.edits.slice(0, 100).map(edit => ({\n        path: edit.path ? this.sanitizeText(edit.path, 300) : undefined,\n        summary: edit.summary ? this.sanitizeText(edit.summary, 300) : undefined\n      }));\n    }\n    if (structured.validation) {\n      out.validation = {\n        lintPassed: Boolean(structured.validation.lintPassed),\n        testsPassed: Boolean(structured.validation.testsPassed),\n        notes: structured.validation.notes ? this.sanitizeText(structured.validation.notes, 600) : undefined\n      };\n    }\n    if (structured.outcome) out.outcome = this.sanitizeText(structured.outcome, 600);\n    return out;\n  }\n\n  private estimateStoreBytes(entries: MemoryEntry[]): number {\n    return entries.reduce((sum, entry) => sum + Buffer.byteLength(JSON.stringify(entry) + '\\n', 'utf8'), 0);\n  }\n\n  private pruneEntries(entries: MemoryEntry[]): MemoryEntry[] {\n    const now = Date.now();\n    const maxAgeMs = Math.max(1, this.maxAgeDays) * 24 * 60 * 60 * 1000;\n    let kept = entries.filter(entry => {\n      const ts = Date.parse(entry.timestamp || '');\n      if (!Number.isFinite(ts)) return true;\n      return now - ts <= maxAgeMs;\n    });\n\n    if (kept.length > this.maxEntries) {\n      kept = kept.slice(-this.maxEntries);\n    }\n\n    while (kept.length > 1 && this.estimateStoreBytes(kept) > this.maxBytes) {\n      kept = kept.slice(1);\n    }\n\n    return kept;\n  }\n\n  private dedupeSemantically(entries: MemoryEntry[]): MemoryEntry[] {\n    if (!this.semanticDedupe || entries.length < 2) return entries;\n\n    const keptNewestFirst: MemoryEntry[] = [];\n    const keptTokens: Array<Set<string>> = [];\n    const descending = entries.slice().reverse();\n\n    for (const entry of descending) {\n      const entryText = `${entry.task || ''}\\n${String(entry.result || '').slice(0, 1200)}`;\n      const entryTokenSet = tokenize(entryText);\n      if (entryTokenSet.size < 6) {\n        keptNewestFirst.push(entry);\n        keptTokens.push(entryTokenSet);\n        continue;\n      }\n      let duplicate = false;\n\n      for (let i = 0; i < keptNewestFirst.length; i += 1) {\n        const existing = keptNewestFirst[i];\n        if (existing.tier !== entry.tier) continue;\n        if ((existing.agent || '') !== (entry.agent || '')) continue;\n        if (keptTokens[i].size < 6) continue;\n        const sim = similarity(entryTokenSet, keptTokens[i]);\n        if (sim >= this.dedupeThreshold) {\n          duplicate = true;\n          break;\n        }\n      }\n\n      if (!duplicate) {\n        keptNewestFirst.push(entry);\n        keptTokens.push(entryTokenSet);\n      }\n    }\n\n    return keptNewestFirst.reverse();\n  }\n\n  private async maybeAutoCompact(): Promise<void> {\n    this.writeCount += 1;\n    if (this.writeCount % this.autoCompactEvery !== 0) return;\n    try {\n      await this.compact();\n    } catch {\n      // Never fail runtime flows due to maintenance compaction.\n    }\n  }\n\n  /** Append a new memory entry. */\n  async record(entry: Omit<MemoryEntry, 'id' | 'timestamp'>): Promise<MemoryEntry> {\n    await mkdir(dirname(this.storePath), { recursive: true });\n    const full: MemoryEntry = {\n      ...entry,\n      id: randomUUID(),\n      task: this.sanitizeText(entry.task, 1200),\n      result: this.sanitizeText(entry.result, 6000),\n      structured: this.normalizeStructured(entry.structured),\n      metadata: this.sanitizeMetadata(entry.metadata) as Record<string, unknown> | undefined,\n      timestamp: new Date().toISOString()\n    };\n    const line = JSON.stringify(full) + '\\n';\n    await appendFile(this.storePath, line, 'utf8');\n    await this.maybeAutoCompact();\n    return full;\n  }\n\n  /** Best-effort append: never throws, returns success state. */\n  async recordSafe(entry: Omit<MemoryEntry, 'id' | 'timestamp'>): Promise<{ ok: boolean; entry?: MemoryEntry; error?: string }> {\n    try {\n      const saved = await this.record(entry);\n      return { ok: true, entry: saved };\n    } catch (error) {\n      return { ok: false, error: (error as Error).message };\n    }\n  }\n\n  /** Load all entries from the JSONL store. */\n  async loadAll(): Promise<MemoryEntry[]> {\n    let raw: string;\n    try {\n      raw = await readFile(this.storePath, 'utf8');\n    } catch {\n      return [];\n    }\n    const entries: MemoryEntry[] = [];\n    for (const line of raw.split('\\n')) {\n      if (!line.trim()) continue;\n      try {\n        entries.push(JSON.parse(line));\n      } catch {\n        // skip malformed lines\n      }\n    }\n    return entries;\n  }\n\n  /**\n   * Retrieve entries similar to the given task description.\n   * Returns up to `maxResults` matches sorted by similarity score descending.\n   */\n  async recall(task: string, maxResults = 5, options: RecallOptions = {}): Promise<MemoryMatch[]> {\n    const entries = await this.loadAll();\n    if (entries.length === 0) return [];\n\n    const queryTokens = tokenize(task);\n    const now = options.nowMs || Date.now();\n    const hints = new Set((options.pathHints || []).map(x => String(x || '').trim()).filter(Boolean));\n    const scored: MemoryMatch[] = [];\n\n    for (const entry of entries) {\n      const entryTokens = tokenize(entry.task);\n      const sim = similarity(queryTokens, entryTokens);\n\n      let recencyBoost = 0;\n      const ts = Date.parse(entry.timestamp || '');\n      if (Number.isFinite(ts)) {\n        const ageDays = Math.max(0, (now - ts) / (24 * 60 * 60 * 1000));\n        recencyBoost = Math.max(0, 1 - Math.min(ageDays, 30) / 30) * 0.15;\n      }\n\n      let successBoost = 0;\n      const success = Boolean(entry.metadata?.success)\n        || Boolean(entry.structured?.outcome?.toLowerCase().includes('success'));\n      if (options.preferSuccessful !== false && success) {\n        successBoost = 0.1;\n      }\n\n      let pathBoost = 0;\n      if (hints.size > 0) {\n        const entryPaths = new Set<string>();\n        for (const edit of entry.structured?.edits || []) {\n          if (edit.path) entryPaths.add(edit.path);\n        }\n        const metadataPaths = entry.metadata?.paths;\n        if (Array.isArray(metadataPaths)) {\n          for (const p of metadataPaths) {\n            entryPaths.add(String(p || ''));\n          }\n        }\n        let overlap = 0;\n        for (const h of hints) {\n          if (entryPaths.has(h)) overlap += 1;\n        }\n        if (overlap > 0) {\n          pathBoost = Math.min(0.2, overlap / Math.max(1, hints.size) * 0.2);\n        }\n      }\n\n      const score = sim + recencyBoost + successBoost + pathBoost;\n      if (score > 0.15) {\n        scored.push({ entry, score: Math.round(score * 100) / 100 });\n      }\n    }\n\n    scored.sort((a, b) => b.score - a.score);\n    return scored.slice(0, maxResults);\n  }\n\n  /**\n   * Format recalled memories into a context block for prompt injection.\n   * Recent entries shown full, older entries compressed (progressive disclosure pattern).\n   */\n  async recallAsContext(task: string, maxResults = 3, options: RecallOptions = {}): Promise<string> {\n    const matches = await this.recall(task, maxResults, options);\n    if (matches.length === 0) return '';\n\n    const lines = ['## Prior Task Memory'];\n    const keepFullCount = Math.min(5, Math.ceil(matches.length * 0.5)); // Keep top 50% full\n    \n    for (let i = 0; i < matches.length; i++) {\n      const m = matches[i];\n      const isFull = i < keepFullCount;\n      \n      // Full version for recent/high-scoring entries\n      if (isFull) {\n        const resultPreview = m.entry.result.length > 400\n          ? m.entry.result.slice(0, 400) + '...'\n          : m.entry.result;\n        lines.push(`### [${m.entry.tier}] ${m.entry.task} (score: ${m.score})`);\n        if (m.entry.agent) lines.push(`Agent: ${m.entry.agent}`);\n        lines.push(`Result: ${resultPreview}`);\n        lines.push('');\n      } else {\n        // Compressed version for older/lower-scoring entries\n        const hasError = /error|failed|exception/i.test(m.entry.result);\n        const statusIcon = hasError ? '\u274C' : '\u2713';\n        const preview = m.entry.result.slice(0, 120);\n        lines.push(`### ${statusIcon} [${m.entry.tier}] ${m.entry.task}`);\n        lines.push(`${preview}... [${hasError ? 'failed' : 'completed'}]`);\n        lines.push('');\n      }\n    }\n    return lines.join('\\n');\n  }\n\n  /**\n   * Compact the store: keep only the most recent `maxEntries` entries.\n   */\n  async compact(): Promise<CompactionResult> {\n    const entries = await this.loadAll();\n    const entriesBefore = entries.length;\n\n    let bytesBefore = 0;\n    try {\n      const st = await stat(this.storePath);\n      bytesBefore = st.size;\n    } catch {\n      bytesBefore = 0;\n    }\n\n    const deduped = this.dedupeSemantically(entries);\n    const kept = this.pruneEntries(deduped);\n    if (kept.length === entries.length) {\n      return { entriesBefore, entriesAfter: kept.length, bytesFreed: 0 };\n    }\n    const content = kept.map(e => JSON.stringify(e)).join('\\n') + '\\n';\n    await writeFile(this.storePath, content, 'utf8');\n\n    let bytesAfter = 0;\n    try {\n      const st = await stat(this.storePath);\n      bytesAfter = st.size;\n    } catch {\n      bytesAfter = content.length;\n    }\n\n    return {\n      entriesBefore,\n      entriesAfter: kept.length,\n      bytesFreed: Math.max(0, bytesBefore - bytesAfter)\n    };\n  }\n\n  /** Get summary stats. */\n  async stats(): Promise<{ entries: number; byTier: Record<string, number>; byAgent: Record<string, number>; bytes: number }> {\n    const entries = await this.loadAll();\n    const byTier: Record<string, number> = {};\n    const byAgent: Record<string, number> = {};\n    for (const e of entries) {\n      byTier[e.tier] = (byTier[e.tier] || 0) + 1;\n      if (e.agent) byAgent[e.agent] = (byAgent[e.agent] || 0) + 1;\n    }\n    return { entries: entries.length, byTier, byAgent, bytes: this.estimateStoreBytes(entries) };\n  }\n}\n", "// @ts-nocheck\nimport { exec } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { AgentRouter } from '../agent/router.js';\nimport { Orchestrator } from '../orchestrator/index.js';\nimport { Sandbox } from '../sandbox/index.js';\nimport { SessionManager } from '../session/manager.js';\n\nconst execAsync = promisify(exec);\n\nexport interface CheckRunResult {\n  success: boolean;\n  command: string;\n  stdout: string;\n  stderr: string;\n}\n\nexport async function runCheckCommand(command: string, cwd = process.cwd()): Promise<CheckRunResult> {\n  try {\n    const { stdout, stderr } = await execAsync(command, {\n      cwd,\n      maxBuffer: 1024 * 1024 * 4\n    });\n    return {\n      success: true,\n      command,\n      stdout: String(stdout || ''),\n      stderr: String(stderr || '')\n    };\n  } catch (error) {\n    return {\n      success: false,\n      command,\n      stdout: String(error?.stdout || ''),\n      stderr: String(error?.stderr || error?.message || '')\n    };\n  }\n}\n\nexport interface CiFixOptions {\n  command: string;\n  maxAttempts: number;\n  cwd?: string;\n  router: AgentRouter;\n  orchestrator: Orchestrator;\n  sandbox: Sandbox;\n  session: SessionManager;\n}\n\nexport async function runCiFixLoop(options: CiFixOptions) {\n  const cwd = options.cwd || process.cwd();\n  const attempts = Math.max(1, options.maxAttempts || 3);\n  const runHistory: Array<{ attempt: number; success: boolean; stderr: string }> = [];\n\n  for (let attempt = 1; attempt <= attempts; attempt++) {\n    const checkResult = await runCheckCommand(options.command, cwd);\n    runHistory.push({\n      attempt,\n      success: checkResult.success,\n      stderr: checkResult.stderr\n    });\n\n    if (checkResult.success) {\n      return {\n        success: true,\n        attemptsUsed: attempt,\n        history: runHistory\n      };\n    }\n\n    const task = [\n      `CI check failed on attempt ${attempt}/${attempts}.`,\n      `Command: ${options.command}`,\n      'Please return concrete file edits in FILE: path + SEARCH/REPLACE or full content blocks.',\n      '',\n      'STDOUT:',\n      checkResult.stdout.slice(0, 6000),\n      '',\n      'STDERR:',\n      checkResult.stderr.slice(0, 6000)\n    ].join('\\n');\n\n    const fixResult = await options.router.dispatch('crew-fixer', task, {\n      sessionId: await options.session.getSessionId(),\n      project: cwd\n    });\n\n    await options.orchestrator.parseAndApplyToSandbox(String(fixResult.result || ''));\n    if (options.sandbox.hasChanges()) {\n      await options.sandbox.apply();\n    }\n  }\n\n  return {\n    success: false,\n    attemptsUsed: attempts,\n    history: runHistory\n  };\n}\n", "/**\n * Blast Radius Analysis \u2014 safe refactoring guard.\n *\n * Uses the repository dependency graph + git diff to compute which files and\n * symbols are affected by a set of changes, and assigns a risk score.\n */\n\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { relative, resolve } from 'node:path';\nimport { buildRepositoryGraph, type RepositoryGraph, type RepositoryGraphNode } from '../mapping/index.js';\n\nconst execFileAsync = promisify(execFile);\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type RiskLevel = 'low' | 'medium' | 'high';\n\nexport interface AffectedFile {\n  /** Relative path of the affected file */\n  path: string;\n  /** How it is affected: directly changed, or transitively impacted */\n  relation: 'changed' | 'direct-importer' | 'transitive-importer';\n  /** Depth from the changed file (0 = changed, 1 = direct importer, \u2026) */\n  depth: number;\n}\n\nexport interface BlastRadiusReport {\n  /** Changed files extracted from git diff */\n  changedFiles: string[];\n  /** All affected files (changed + importers, transitively) */\n  affectedFiles: AffectedFile[];\n  /** Total unique files impacted */\n  impactCount: number;\n  /** Risk level */\n  risk: RiskLevel;\n  /** Human-readable summary */\n  summary: string;\n}\n\n// ---------------------------------------------------------------------------\n// Utility functions\n// ---------------------------------------------------------------------------\n\nfunction severityRank(level: RiskLevel): number {\n  if (level === 'high') return 3;\n  if (level === 'medium') return 2;\n  return 1;\n}\n\nexport function isSeverityAtLeast(actual: RiskLevel, threshold: RiskLevel): boolean {\n  return severityRank(actual) >= severityRank(threshold);\n}\n\n// ---------------------------------------------------------------------------\n// Git diff parsing\n// ---------------------------------------------------------------------------\n\nasync function getChangedFiles(cwd: string, diffRef?: string): Promise<string[]> {\n  const args = diffRef\n    ? ['diff', '--name-only', diffRef]\n    : ['diff', '--name-only', 'HEAD'];\n\n  try {\n    const { stdout } = await execFileAsync('git', args, { cwd, maxBuffer: 1024 * 1024 });\n    return stdout.trim().split('\\n').filter(Boolean);\n  } catch {\n    // Fallback: unstaged changes\n    try {\n      const { stdout } = await execFileAsync('git', ['diff', '--name-only'], { cwd, maxBuffer: 1024 * 1024 });\n      return stdout.trim().split('\\n').filter(Boolean);\n    } catch {\n      return [];\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Transitive impact traversal\n// ---------------------------------------------------------------------------\n\nfunction collectImporters(\n  graph: RepositoryGraph,\n  startFiles: Set<string>,\n  maxDepth = 5\n): AffectedFile[] {\n  const nodeByPath = new Map<string, RepositoryGraphNode>();\n  for (const node of graph.nodes) {\n    nodeByPath.set(node.path, node);\n  }\n\n  const visited = new Map<string, AffectedFile>();\n\n  // Seed with changed files\n  for (const file of startFiles) {\n    visited.set(file, { path: file, relation: 'changed', depth: 0 });\n  }\n\n  // BFS through importedBy edges\n  let frontier = new Set(startFiles);\n\n  for (let depth = 1; depth <= maxDepth && frontier.size > 0; depth++) {\n    const nextFrontier = new Set<string>();\n    for (const file of frontier) {\n      const node = nodeByPath.get(file);\n      if (!node) continue;\n      for (const importer of node.importedBy) {\n        if (visited.has(importer)) continue;\n        const relation: AffectedFile['relation'] = depth === 1 ? 'direct-importer' : 'transitive-importer';\n        visited.set(importer, { path: importer, relation, depth });\n        nextFrontier.add(importer);\n      }\n    }\n    frontier = nextFrontier;\n  }\n\n  return Array.from(visited.values()).sort((a, b) => a.depth - b.depth || a.path.localeCompare(b.path));\n}\n\n// ---------------------------------------------------------------------------\n// Risk scoring\n// ---------------------------------------------------------------------------\n\nfunction assessRisk(changedCount: number, impactCount: number, totalNodes: number): RiskLevel {\n  // For very small repos (<10 files), use absolute counts only\n  if (totalNodes < 10) {\n    if (impactCount > 8) return 'high';\n    if (impactCount > 4) return 'medium';\n    return 'low';\n  }\n\n  const impactRatio = totalNodes > 0 ? impactCount / totalNodes : 0;\n\n  // High: >30% of codebase affected or >20 files impacted\n  if (impactRatio > 0.3 || impactCount > 20) return 'high';\n  // Medium: >10% or >8 files\n  if (impactRatio > 0.1 || impactCount > 8) return 'medium';\n  return 'low';\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport async function analyzeBlastRadius(\n  cwd: string,\n  options: { diffRef?: string; maxDepth?: number; changedFiles?: string[] } = {}\n): Promise<BlastRadiusReport> {\n  const rootDir = resolve(cwd);\n  const maxDepth = options.maxDepth ?? 5;\n\n  // 1. Get changed files from git diff or explicit list\n  let rawChanged = options.changedFiles ?? await getChangedFiles(rootDir, options.diffRef);\n\n  // 2. Build repository dependency graph\n  const graph = await buildRepositoryGraph(rootDir);\n\n  // Normalize changed file paths to match graph paths (relative)\n  const graphPaths = new Set(graph.nodes.map(n => n.path));\n  const changedSet = new Set<string>();\n  for (const file of rawChanged) {\n    const rel = relative(rootDir, resolve(rootDir, file));\n    if (graphPaths.has(rel)) changedSet.add(rel);\n  }\n\n  // 3. Traverse import graph for transitive impact\n  const affectedFiles = collectImporters(graph, changedSet, maxDepth);\n  const impactCount = affectedFiles.length;\n\n  // 4. Assess risk\n  const risk = assessRisk(changedSet.size, impactCount, graph.nodeCount);\n\n  // 5. Build summary\n  const changedList = Array.from(changedSet);\n  const directImporters = affectedFiles.filter(f => f.relation === 'direct-importer').length;\n  const transitiveImporters = affectedFiles.filter(f => f.relation === 'transitive-importer').length;\n\n  const riskEmoji = { low: 'LOW', medium: 'MEDIUM', high: 'HIGH' }[risk];\n  const lines = [\n    `Blast Radius: ${riskEmoji}`,\n    `  Changed files: ${changedSet.size}`,\n    `  Direct importers: ${directImporters}`,\n    `  Transitive importers: ${transitiveImporters}`,\n    `  Total impacted: ${impactCount} / ${graph.nodeCount} source files`\n  ];\n\n  if (risk === 'high') {\n    lines.push('', '  \u26A0 HIGH RISK \u2014 review affected files carefully before applying.');\n  }\n\n  return {\n    changedFiles: changedList,\n    affectedFiles,\n    impactCount,\n    risk,\n    summary: lines.join('\\n')\n  };\n}\n", "import chalk from 'chalk';\nimport { execSync } from 'child_process';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\n\n/**\n * Dynamic crewswarm status dashboard\n * Shows REAL system information, not hardcoded values\n */\n\ninterface StatusInfo {\n  online: boolean;\n  activeAgents: number;\n  gatewayReachable: boolean;\n  queuedTasks: number;\n  runningTasks: number;\n  models: string[];\n  gatewayUrl: string;\n  version: string;\n}\n\ninterface StatusRenderOptions {\n  interfaceMode?: 'connected' | 'standalone';\n}\n\nexport async function getSystemStatus(): Promise<StatusInfo> {\n  const status: StatusInfo = {\n    online: false,\n    activeAgents: 0,\n    gatewayReachable: false,\n    queuedTasks: 0,\n    runningTasks: 0,\n    models: [],\n    gatewayUrl: process.env.CREW_LEAD_URL || 'http://127.0.0.1:5010',\n    version: '0.1.0-alpha'\n  };\n\n  // Check which providers have API keys (from crewswarm.json + env vars)\n  const providers: string[] = [];\n  try {\n    const { readFileSync } = await import('node:fs');\n    const cfgPath = `${homedir()}/.crewswarm/crewswarm.json`;\n    const cfg = JSON.parse(readFileSync(cfgPath, 'utf8'));\n    const providerEntries = cfg.providers || {};\n    for (const [id, p] of Object.entries(providerEntries) as [string, Record<string, unknown>][]) {\n      if (p.apiKey && String(p.apiKey).trim()) {\n        providers.push(id);\n      }\n    }\n  } catch { /* no config */ }\n  // Also check env vars for providers not in config\n  const envMap: Record<string, string> = {\n    GEMINI_API_KEY: 'google', GOOGLE_API_KEY: 'google', GROQ_API_KEY: 'groq',\n    XAI_API_KEY: 'xai', OPENAI_API_KEY: 'openai', ANTHROPIC_API_KEY: 'anthropic',\n    DEEPSEEK_API_KEY: 'deepseek', MISTRAL_API_KEY: 'mistral', PERPLEXITY_API_KEY: 'perplexity',\n    TOGETHER_API_KEY: 'together', FIREWORKS_API_KEY: 'fireworks', HUGGINGFACE_API_KEY: 'huggingface',\n  };\n  for (const [envKey, id] of Object.entries(envMap)) {\n    if (process.env[envKey] && !providers.includes(id)) providers.push(id);\n  }\n  status.models = providers;\n  status.online = providers.length > 0;\n\n  // Check if gateway is reachable (optional, for connected mode)\n  try {\n    // Read auth token from ~/.crewswarm/config.json\n    let authToken = '';\n    try {\n      const { readFileSync } = await import('node:fs');\n      const { homedir } = await import('node:os');\n      const cfg = JSON.parse(readFileSync(`${homedir()}/.crewswarm/config.json`, 'utf8'));\n      authToken = cfg?.rt?.authToken || '';\n    } catch { /* no config */ }\n\n    const controller = new AbortController();\n    const timeoutId = setTimeout(() => controller.abort(), 800);\n    const headers: Record<string, string> = {};\n    if (authToken) headers['Authorization'] = `Bearer ${authToken}`;\n    const statusCheck = await fetch(`${status.gatewayUrl}/status`, {\n      signal: controller.signal,\n      headers\n    });\n    clearTimeout(timeoutId);\n    if (statusCheck.ok) {\n      status.gatewayReachable = true;\n      const data = await statusCheck.json() as { agents?: unknown[] };\n      status.activeAgents = Array.isArray(data.agents) ? data.agents.length : 1;\n    }\n  } catch {\n    // Gateway not reachable \u2014 standalone mode only\n  }\n\n  return status;\n}\n\nexport function renderStatusDashboard(status: StatusInfo, options: StatusRenderOptions = {}): string {\n  const { online, activeAgents, gatewayReachable, models } = status;\n  \n  // Colors\n  const border = chalk.cyan;\n  const label = chalk.gray;\n  const value = chalk.white.bold;\n  const accent = chalk.blue;\n\n  // Provider status bar\n  const providerCount = models.length;\n  const maxProviders = 24;\n  const filled = Math.min(10, Math.floor((providerCount / maxProviders) * 10));\n  const empty = 10 - filled;\n  const progressBar = chalk.green('\u2588'.repeat(filled)) + chalk.gray('\u2591'.repeat(empty));\n\n  const statusText = online ? chalk.green('READY') : chalk.red('NO API KEYS');\n  const interfaceMode = options.interfaceMode || (gatewayReachable ? 'connected' : 'standalone');\n  const interfaceText = interfaceMode === 'connected'\n    ? chalk.green('CONNECTED')\n    : chalk.gray('STANDALONE');\n  const gatewayText = gatewayReachable\n    ? chalk.green('AVAILABLE') + chalk.gray(activeAgents > 0 ? ` (${activeAgents} agents)` : '')\n    : chalk.gray('UNREACHABLE');\n  const modelStack = models.length > 0 ? models.join(' / ') : chalk.red('None \u2014 add API keys');\n\n  const lines = [\n    border('\u250C\u2500[ CREW-CLI :: AGENTIC CODING ENGINE ]\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510'),\n    '',\n    `   ${label('STATUS')}     : ${statusText}`,\n    `   ${label('INTERFACE')}  : ${interfaceText}`,\n    `   ${label('GATEWAY')}    : ${gatewayText}`,\n    `   ${label('PROVIDERS')}  : ${value(modelStack)}`,\n    '',\n    `   ${accent('Provider Coverage')}: ${progressBar} ${providerCount}/${maxProviders}`,\n    '',\n    `   ${chalk.italic.gray('\"One idea. One Build. One Crew.\"')}`,\n    '',\n    border('\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518')\n  ];\n\n  return lines.join('\\n');\n}\n\nexport async function displayStatus(options: StatusRenderOptions = {}): Promise<void> {\n  const status = await getSystemStatus();\n  console.log('\\n' + renderStatusDashboard(status, options) + '\\n');\n}\n", "/**\n * Model info for enhanced /model display\n * Benchmark scores from OpenRouter coding leaderboard (March 2026)\n */\n\nexport interface ModelInfo {\n  name: string;\n  provider: string;\n  codingScore: number;   // OpenRouter coding benchmark (0-100)\n  inputCost: number;     // $/1M input tokens\n  outputCost: number;    // $/1M output tokens\n  contextWindow: string; // human-readable\n  tier: 'heavy' | 'standard' | 'fast';\n  note?: string;\n}\n\nexport const MODEL_CATALOG: ModelInfo[] = [\n  // Heavy tier \u2014 L2 brain\n  { name: 'gpt-5.4',             provider: 'OpenAI',     codingScore: 57.3, inputCost: 3.00,  outputCost: 15.00, contextWindow: '128K',  tier: 'heavy', note: '#1 coding' },\n  { name: 'gemini-3.1-pro',      provider: 'Google',     codingScore: 55.5, inputCost: 2.00,  outputCost: 12.00, contextWindow: '200K',  tier: 'heavy', note: '#2 coding' },\n  { name: 'gpt-5.3-codex',       provider: 'OpenAI',     codingScore: 53.1, inputCost: 3.00,  outputCost: 15.00, contextWindow: '128K',  tier: 'heavy' },\n  { name: 'claude-sonnet-4.6',   provider: 'Anthropic',  codingScore: 50.9, inputCost: 3.00,  outputCost: 15.00, contextWindow: '200K',  tier: 'heavy' },\n  { name: 'claude-opus-4.6',     provider: 'Anthropic',  codingScore: 48.1, inputCost: 3.00,  outputCost: 15.00, contextWindow: '200K',  tier: 'heavy' },\n  { name: 'grok-4.20-beta',      provider: 'xAI',        codingScore: 42.2, inputCost: 2.00,  outputCost: 6.00,  contextWindow: '2M',   tier: 'heavy', note: '2M context' },\n  { name: 'grok-4',              provider: 'xAI',        codingScore: 40.5, inputCost: 3.00,  outputCost: 15.00, contextWindow: '256K',  tier: 'heavy' },\n\n  // Standard tier \u2014 L3 workers\n  { name: 'gemini-2.5-pro',      provider: 'Google',     codingScore: 46.7, inputCost: 1.25,  outputCost: 10.00, contextWindow: '1M',   tier: 'standard' },\n  { name: 'gemini-3-pro',        provider: 'Google',     codingScore: 46.5, inputCost: 2.00,  outputCost: 12.00, contextWindow: '200K',  tier: 'standard' },\n  { name: 'glm-5',               provider: 'Z-AI',       codingScore: 44.2, inputCost: 0.50,  outputCost: 2.00,  contextWindow: '128K',  tier: 'standard' },\n  { name: 'gemini-3-flash',      provider: 'Google',     codingScore: 42.6, inputCost: 0.50,  outputCost: 3.00,  contextWindow: '1M',   tier: 'standard' },\n  { name: 'minimax-m2.7',        provider: 'MiniMax',    codingScore: 41.9, inputCost: 0.30,  outputCost: 1.00,  contextWindow: '128K',  tier: 'standard' },\n  { name: 'qwen3.5-397b',        provider: 'Qwen',       codingScore: 41.3, inputCost: 0.30,  outputCost: 0.90,  contextWindow: '128K',  tier: 'standard' },\n  { name: 'gemini-2.5-flash',    provider: 'Google',     codingScore: 38.0, inputCost: 0.30,  outputCost: 2.50,  contextWindow: '1M',   tier: 'standard', note: 'free tier' },\n  { name: 'kimi-k2.5',           provider: 'Moonshot',   codingScore: 39.5, inputCost: 0.60,  outputCost: 2.00,  contextWindow: '128K',  tier: 'standard' },\n  { name: 'deepseek-v3.2',       provider: 'DeepSeek',   codingScore: 36.0, inputCost: 0.28,  outputCost: 0.42,  contextWindow: '164K',  tier: 'standard', note: 'cheapest' },\n\n  // Fast tier \u2014 L1 routing\n  { name: 'grok-4.1-fast',       provider: 'xAI',        codingScore: 35.0, inputCost: 0.20,  outputCost: 0.50,  contextWindow: '2M',   tier: 'fast', note: '2M, $0.20/M' },\n  { name: 'llama-3.3-70b',       provider: 'Groq',       codingScore: 28.0, inputCost: 0.075, outputCost: 0.30,  contextWindow: '128K',  tier: 'fast', note: 'free tier' },\n  { name: 'gemini-2.5-flash-lite', provider: 'Google',   codingScore: 25.0, inputCost: 0.10,  outputCost: 0.40,  contextWindow: '1M',   tier: 'fast', note: 'cheapest' },\n];\n\nexport function findModelInfo(modelName: string): ModelInfo | undefined {\n  const lower = modelName.toLowerCase();\n  return MODEL_CATALOG.find(m => lower.includes(m.name.toLowerCase()) || m.name.toLowerCase().includes(lower));\n}\n\nexport function formatModelTable(models: ModelInfo[]): string {\n  const header = `  ${'Model'.padEnd(24)} ${'Score'.padStart(5)} ${'In $/M'.padStart(7)} ${'Out $/M'.padStart(8)} ${'Context'.padStart(8)} ${'Note'.padEnd(14)}`;\n  const sep    = `  ${'\u2500'.repeat(24)} ${'\u2500'.repeat(5)} ${'\u2500'.repeat(7)} ${'\u2500'.repeat(8)} ${'\u2500'.repeat(8)} ${'\u2500'.repeat(14)}`;\n  const rows = models.map(m => {\n    const score = m.codingScore.toFixed(1).padStart(5);\n    const inCost = `$${m.inputCost.toFixed(2)}`.padStart(7);\n    const outCost = `$${m.outputCost.toFixed(2)}`.padStart(8);\n    const ctx = m.contextWindow.padStart(8);\n    const note = (m.note || '').padEnd(14);\n    return `  ${m.name.padEnd(24)} ${score} ${inCost} ${outCost} ${ctx} ${note}`;\n  });\n  return [header, sep, ...rows].join('\\n');\n}\n", "/**\n * Chat Recall \u2014 semantic search across conversation history.\n *\n * Indexes past session entries (commands, outputs, tool results)\n * and provides keyword + fuzzy search across all sessions.\n *\n * Uses the existing session history stored in .crew/session.json\n * and builds a lightweight inverted index for fast lookup.\n */\n\nimport { readFile, readdir, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface RecallEntry {\n  sessionId: string;\n  timestamp: string;\n  input: string;\n  output?: string;\n  route?: string;\n  agent?: string;\n  score: number;\n}\n\nexport interface RecallResult {\n  query: string;\n  entries: RecallEntry[];\n  totalSearched: number;\n}\n\n// ---------------------------------------------------------------------------\n// Index\n// ---------------------------------------------------------------------------\n\ninterface IndexedSession {\n  sessionId: string;\n  entries: Array<{\n    timestamp: string;\n    input: string;\n    output?: string;\n    route?: string;\n    agent?: string;\n    tokens: string[];\n  }>;\n}\n\nfunction tokenize(text: string): string[] {\n  return text\n    .toLowerCase()\n    .replace(/[^a-z0-9\\s_.-]/g, ' ')\n    .split(/\\s+/)\n    .filter(t => t.length >= 2);\n}\n\nfunction scoreMatch(queryTokens: string[], entryTokens: string[]): number {\n  if (queryTokens.length === 0 || entryTokens.length === 0) return 0;\n  const entrySet = new Set(entryTokens);\n  let matches = 0;\n  for (const qt of queryTokens) {\n    // Exact match\n    if (entrySet.has(qt)) { matches += 2; continue; }\n    // Prefix match\n    for (const et of entrySet) {\n      if (et.startsWith(qt) || qt.startsWith(et)) { matches += 1; break; }\n    }\n  }\n  return matches / (queryTokens.length * 2); // normalize to 0-1\n}\n\n// ---------------------------------------------------------------------------\n// Load & Search\n// ---------------------------------------------------------------------------\n\n/**\n * Load all session histories from a project directory.\n */\nasync function loadSessionHistories(projectDir: string): Promise<IndexedSession[]> {\n  const sessions: IndexedSession[] = [];\n\n  // Current session\n  const sessionPath = join(projectDir, '.crew', 'session.json');\n  if (existsSync(sessionPath)) {\n    try {\n      const raw = await readFile(sessionPath, 'utf8');\n      const session = JSON.parse(raw);\n      if (session.history?.length) {\n        sessions.push({\n          sessionId: session.sessionId || 'current',\n          entries: session.history.map((h: Record<string, unknown>) => ({\n            timestamp: String(h.timestamp || ''),\n            input: String(h.input || ''),\n            output: h.output ? String(h.output) : undefined,\n            route: h.route ? String(h.route) : undefined,\n            agent: h.agent ? String(h.agent) : undefined,\n            tokens: tokenize(`${h.input || ''} ${h.output || ''} ${h.route || ''} ${h.agent || ''}`)\n          }))\n        });\n      }\n    } catch {}\n  }\n\n  // Past session logs (.crew/sessions/ directory if exists)\n  const sessionsDir = join(projectDir, '.crew', 'sessions');\n  if (existsSync(sessionsDir)) {\n    try {\n      const files = await readdir(sessionsDir);\n      for (const file of files.filter(f => f.endsWith('.json'))) {\n        try {\n          const raw = await readFile(join(sessionsDir, file), 'utf8');\n          const session = JSON.parse(raw);\n          if (session.history?.length) {\n            sessions.push({\n              sessionId: session.sessionId || file.replace('.json', ''),\n              entries: session.history.map((h: Record<string, unknown>) => ({\n                timestamp: String(h.timestamp || ''),\n                input: String(h.input || ''),\n                output: h.output ? String(h.output) : undefined,\n                route: h.route ? String(h.route) : undefined,\n                agent: h.agent ? String(h.agent) : undefined,\n                tokens: tokenize(`${h.input || ''} ${h.output || ''} ${h.route || ''} ${h.agent || ''}`)\n              }))\n            });\n          }\n        } catch {}\n      }\n    } catch {}\n  }\n\n  // Routing log (.crew/routing.log \u2014 JSONL format)\n  const routingPath = join(projectDir, '.crew', 'routing.log');\n  if (existsSync(routingPath)) {\n    try {\n      const raw = await readFile(routingPath, 'utf8');\n      const entries = raw.split('\\n').filter(Boolean).map(line => {\n        try { return JSON.parse(line); } catch { return null; }\n      }).filter(Boolean);\n      if (entries.length > 0) {\n        sessions.push({\n          sessionId: 'routing-log',\n          entries: entries.map((e: Record<string, unknown>) => ({\n            timestamp: String(e.timestamp || ''),\n            input: String(e.task || e.input || ''),\n            output: String(e.decision || e.route || ''),\n            route: String(e.route || e.decision || ''),\n            agent: String(e.agent || ''),\n            tokens: tokenize(JSON.stringify(e).slice(0, 500))\n          }))\n        });\n      }\n    } catch {}\n  }\n\n  return sessions;\n}\n\n/**\n * Search across all session history for a query.\n */\nexport async function recallSearch(\n  query: string,\n  projectDir: string = process.cwd(),\n  options: { maxResults?: number; minScore?: number } = {}\n): Promise<RecallResult> {\n  const maxResults = options.maxResults ?? 10;\n  const minScore = options.minScore ?? 0.2;\n  const queryTokens = tokenize(query);\n\n  if (queryTokens.length === 0) {\n    return { query, entries: [], totalSearched: 0 };\n  }\n\n  const sessions = await loadSessionHistories(projectDir);\n  const scored: RecallEntry[] = [];\n  let totalSearched = 0;\n\n  for (const session of sessions) {\n    for (const entry of session.entries) {\n      totalSearched++;\n      const score = scoreMatch(queryTokens, entry.tokens);\n      if (score >= minScore) {\n        scored.push({\n          sessionId: session.sessionId,\n          timestamp: entry.timestamp,\n          input: entry.input,\n          output: entry.output,\n          route: entry.route,\n          agent: entry.agent,\n          score\n        });\n      }\n    }\n  }\n\n  // Sort by score descending, then by timestamp descending\n  scored.sort((a, b) => b.score - a.score || b.timestamp.localeCompare(a.timestamp));\n\n  return {\n    query,\n    entries: scored.slice(0, maxResults),\n    totalSearched\n  };\n}\n\n/**\n * Build a context string from recall results for injection into LLM prompt.\n */\nexport function buildRecallContext(result: RecallResult, maxChars: number = 2000): string {\n  if (result.entries.length === 0) return '';\n\n  const lines: string[] = ['## Relevant past interactions:'];\n  let chars = lines[0].length;\n\n  for (const entry of result.entries) {\n    const line = `- [${entry.timestamp?.split('T')[0] || '?'}] ${entry.input?.slice(0, 120)}${entry.output ? ' \u2192 ' + entry.output.slice(0, 80) : ''}`;\n    if (chars + line.length > maxChars) break;\n    lines.push(line);\n    chars += line.length;\n  }\n\n  return lines.join('\\n');\n}\n", "/**\n * Summon \u2014 runtime sub-agent delegation.\n *\n * Unlike spawn_agent (which starts a new autonomous loop), summon\n * dynamically loads a specialized persona mid-execution and delegates\n * a sub-task to it. The sub-agent runs with:\n *   - A persona-specific system prompt\n *   - A filtered tool set appropriate for its role\n *   - Access to the current sandbox state\n *   - Budget/turn limits from the parent\n *\n * This enables runtime persona switching without the overhead of\n * starting a full new agent session.\n *\n * Usage from the LLM:\n *   summon({ persona: \"crew-qa\", task: \"write tests for src/auth.ts\" })\n */\n\nimport type { Sandbox } from '../sandbox/index.js';\nimport { filterToolsForTask, type ToolDeclarationLike } from './tool-filter.js';\n\n// ---------------------------------------------------------------------------\n// Persona definitions\n// ---------------------------------------------------------------------------\n\nexport interface PersonaConfig {\n  id: string;\n  name: string;\n  systemPromptAddition: string;\n  defaultMaxTurns: number;\n  toolDomains: string[];\n}\n\nconst PERSONAS: Record<string, PersonaConfig> = {\n  'crew-qa': {\n    id: 'crew-qa',\n    name: 'QA Specialist',\n    systemPromptAddition: `You are a QA specialist. Your primary focus is:\n- Writing comprehensive test cases\n- Verifying code correctness\n- Running test suites and analyzing failures\n- Checking edge cases and error handling\n- Ensuring test coverage for all modified code\nAlways run tests after writing them to verify they pass.`,\n    defaultMaxTurns: 8,\n    toolDomains: ['coding', 'testing']\n  },\n  'crew-coder-back': {\n    id: 'crew-coder-back',\n    name: 'Backend Specialist',\n    systemPromptAddition: `You are a backend specialist. Your primary focus is:\n- API design and implementation (REST, GraphQL)\n- Database operations and data modeling\n- Authentication and authorization\n- Input validation and error handling\n- Performance and security best practices\nPrefer minimal, well-typed implementations. Validate at boundaries.`,\n    defaultMaxTurns: 10,\n    toolDomains: ['coding', 'testing']\n  },\n  'crew-coder-front': {\n    id: 'crew-coder-front',\n    name: 'Frontend Specialist',\n    systemPromptAddition: `You are a frontend specialist. Your primary focus is:\n- UI component implementation\n- Responsive layouts and CSS\n- Accessibility (WCAG AA compliance)\n- State management and data flow\n- Performance optimization (bundle size, render cycles)\nFollow the DESIGN.md design system if available. Use semantic HTML.`,\n    defaultMaxTurns: 10,\n    toolDomains: ['coding', 'research']\n  },\n  'crew-security': {\n    id: 'crew-security',\n    name: 'Security Reviewer',\n    systemPromptAddition: `You are a security specialist. Your primary focus is:\n- Identifying injection vulnerabilities (SQL, XSS, command)\n- Reviewing authentication and authorization logic\n- Checking for secrets/credentials in code\n- Input validation and sanitization\n- OWASP Top 10 compliance\nReport findings with severity (critical/high/medium/low) and fix guidance.`,\n    defaultMaxTurns: 6,\n    toolDomains: ['coding']\n  },\n  'crew-copywriter': {\n    id: 'crew-copywriter',\n    name: 'Documentation Writer',\n    systemPromptAddition: `You are a technical writer. Your primary focus is:\n- Clear, concise documentation\n- API documentation with examples\n- README files with install/usage/contributing sections\n- Code comments only where logic isn't self-evident\n- Changelog entries\nWrite for developers. Lead with examples, not explanations.`,\n    defaultMaxTurns: 6,\n    toolDomains: ['coding', 'docs']\n  },\n  'crew-fixer': {\n    id: 'crew-fixer',\n    name: 'Bug Fixer',\n    systemPromptAddition: `You are a debugging specialist. Your primary focus is:\n- Reading error messages and stack traces carefully\n- Identifying root causes, not just symptoms\n- Making minimal, targeted fixes\n- Verifying the fix doesn't introduce regressions\n- Running the failing test/command after fixing\nNever guess \u2014 read the code first. Fix one thing at a time.`,\n    defaultMaxTurns: 8,\n    toolDomains: ['coding', 'testing']\n  }\n};\n\n// ---------------------------------------------------------------------------\n// Summon interface\n// ---------------------------------------------------------------------------\n\nexport interface SummonOptions {\n  persona: string;\n  task: string;\n  maxTurns?: number;\n  /** Parent context to pass to the sub-agent */\n  context?: string;\n  /** Budget limit inherited from parent */\n  maxBudgetUsd?: number;\n}\n\nexport interface SummonResult {\n  persona: string;\n  task: string;\n  success: boolean;\n  output: string;\n  turns: number;\n  cost: number;\n  toolsUsed: string[];\n}\n\n/**\n * Get a persona configuration by ID.\n */\nexport function getPersona(id: string): PersonaConfig | undefined {\n  return PERSONAS[id];\n}\n\n/**\n * List all available personas.\n */\nexport function listPersonas(): PersonaConfig[] {\n  return Object.values(PERSONAS);\n}\n\n/**\n * Build a system prompt for a summoned sub-agent.\n */\nexport function buildSummonPrompt(\n  basePrompt: string,\n  persona: PersonaConfig,\n  parentContext?: string\n): string {\n  const parts = [basePrompt, persona.systemPromptAddition];\n  if (parentContext) {\n    parts.push(`\\n## Parent context:\\n${parentContext}`);\n  }\n  return parts.join('\\n\\n');\n}\n\n/**\n * Filter tools for a summoned persona based on its domains.\n */\nexport function filterToolsForPersona<T extends ToolDeclarationLike>(\n  tools: T[],\n  persona: PersonaConfig\n): T[] {\n  // Build a fake task that includes domain keywords\n  const domainKeywords: Record<string, string> = {\n    coding: 'write code files',\n    testing: 'run tests verify',\n    research: 'search web fetch',\n    git: 'git commit branch',\n    docs: 'documentation readme',\n    planning: 'plan roadmap architect'\n  };\n  const fakeTask = persona.toolDomains.map(d => domainKeywords[d] || d).join(' ');\n  return filterToolsForTask(tools, fakeTask);\n}\n", "import { AgentRouter } from '../agent/router.js';\nimport { Logger } from '../utils/logger.js';\nimport chalk from 'chalk';\n// Lazy-loaded to avoid blocking bundle import (inquirer v9 uses top-level await)\nconst getInquirer = () => import('inquirer').then(m => m.default);\nimport { runPtyCommand } from '../pty/index.js';\nimport { platform, release } from 'node:os';\n\nexport interface ShellCopilotOptions {\n  projectDir?: string;\n  gateway?: string;\n  model?: string;\n}\n\nexport async function runShellCopilot(\n  request: string,\n  router: AgentRouter,\n  options: ShellCopilotOptions = {}\n): Promise<void> {\n  const logger = new Logger();\n  const projectDir = options.projectDir || process.cwd();\n  \n  const systemContext = `You are a shell command assistant (like GitHub Copilot CLI).\nThe user is on ${platform()} ${release()}.\nProvide a single valid shell command that answers the user's request.\nThen provide a brief explanation of the command.\nDO NOT EXECUTE ANY TOOLS. DO NOT RUN COMMANDS. Just output the text.\n\nFormat your output EXACTLY like this:\nCOMMAND:\n\\`\\`\\`bash\n<the exact shell command>\n\\`\\`\\`\n\nEXPLANATION:\n<brief explanation of what the command does, arguments, etc.>\n`;\n\n  let currentRequest = request;\n  \n  while (true) {\n    logger.info(`Translating request into shell command...`);\n    \n    let result;\n    try {\n      const fullTask = `${systemContext}\\n\\nUser Request: ${currentRequest}`;\n      result = await router.dispatch('crew-main', fullTask, {\n        project: projectDir,\n        gateway: options.gateway,\n        model: options.model,\n        skipPreamble: true,\n        injectGitContext: false,\n        direct: true,\n        bypass: true\n      });\n    } catch (err) {\n      logger.error(`Failed to generate command: ${(err as Error).message}`);\n      return;\n    }\n\n    const text = String(result.result || '');\n    \n    const commandMatch = text.match(/COMMAND:\\s*```(?:bash|sh)?\\s*([\\s\\S]*?)\\s*```/i) || text.match(/```(?:bash|sh)?\\s*([\\s\\S]*?)\\s*```/i);\n    const explanationMatch = text.match(/EXPLANATION:\\s*([\\s\\S]*)/i);\n    \n    let command = commandMatch ? commandMatch[1].trim() : '';\n    let explanation = explanationMatch ? explanationMatch[1].trim() : text.trim();\n    \n    if (!command) {\n      // Fallback if formatting failed but it looks like a command\n      const lines = text.split('\\n').filter(l => l.trim().length > 0);\n      if (lines.length > 0 && !lines[0].includes(' ')) {\n         command = lines[0];\n         explanation = text;\n      } else {\n         logger.error('Could not parse a valid command from the response.');\n         console.log(chalk.gray(text));\n         return;\n      }\n    }\n\n    console.log(chalk.blue('\\n--- Proposed Command ---'));\n    console.log(chalk.green.bold(`> ${command}`));\n    console.log(chalk.gray(`\\n${explanation}\\n`));\n\n    const inquirer = await getInquirer();\n    const { action } = await inquirer.prompt([{\n      type: 'list',\n      name: 'action',\n      message: 'What would you like to do?',\n      choices: [\n        { name: 'Run this command', value: 'run' },\n        { name: 'Revise query', value: 'revise' },\n        { name: 'Cancel', value: 'cancel' }\n      ]\n    }]);\n\n    if (action === 'cancel') {\n      logger.info('Cancelled.');\n      return;\n    }\n\n    if (action === 'revise') {\n      const { newQuery } = await (await getInquirer()).prompt([{\n        type: 'input',\n        name: 'newQuery',\n        message: 'Revise your query:',\n        default: currentRequest\n      }]);\n      currentRequest = newQuery;\n      continue; // loop back\n    }\n\n    if (action === 'run') {\n      logger.info(`Executing: ${command}`);\n      try {\n         const ptyResult = await runPtyCommand(command, { cwd: projectDir });\n         if (!ptyResult.success) {\n           process.exit(ptyResult.exitCode || 1);\n         }\n      } catch (err) {\n         logger.error(`Execution failed: ${(err as Error).message}`);\n      }\n      return;\n    }\n  }\n}\n", "#!/usr/bin/env node\n// @ts-nocheck \u2014 systemic type issues pre-date this PR; individual `any` annotations fixed below\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { AgentRouter } from '../agent/router.js';\nimport { ToolManager } from '../tools/manager.js';\nimport { ConfigManager } from '../config/manager.js';\nimport { Logger } from '../utils/logger.js';\nimport { SessionManager } from '../session/manager.js';\nimport { Sandbox } from '../sandbox/index.js';\nimport { Orchestrator } from '../orchestrator/index.js';\nimport { TokenFinder } from '../auth/token-finder.js';\nimport { Planner } from '../planner/index.js';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport {\n  compareVersions,\n  getInstalledCliVersion,\n  getLatestCliVersion,\n  isGlobalInstallLinked,\n  runDoctorChecks,\n  summarizeDoctorResults\n} from '../diagnostics/doctor.js';\nimport { compareModelCosts, estimateCost, getCheapestAlternative } from '../cost/predictor.js';\nimport { CorrectionStore } from '../learning/corrections.js';\nimport { runEngine } from '../engines/index.js';\nimport { startWatchMode } from '../watch/index.js';\nimport { getBanner } from '../hello/index.js';\nimport { collectMultiRepoContext, detectBreakingApiSignals, findSiblingRepos, getRepoSummary, syncRepoSnapshots } from '../multirepo/index.js';\nimport { runCiFixLoop } from '../ci/index.js';\nimport { compareScreenshots, runBrowserDebug } from '../browser/index.js';\nimport { downloadTeamContext, getTeamSyncStatus, loadPrivacyControls, savePrivacyControls, uploadTeamContext } from '../team/index.js';\nimport { appendVoiceTranscript, recordAudio, speakWithSkill, transcribeAudio } from '../voice/listener.js';\nimport { buildFileContextBlock, buildImageContextBlock, buildRepoContextBlock, collectOption, enforceContextBudget, mergeTaskWithContext, readStdinText } from '../context/augment.js';\nimport { detectHighSeverityFindings, getReviewPayload } from '../review/index.js';\nimport { addMcpServer, doctorMcpServers, listMcpServers, removeMcpServer } from '../mcp/index.js';\nimport { getHeadlessState, runHeadlessTask, setHeadlessPaused } from '../headless/index.js';\nimport { startUnifiedServer } from '../interface/server.js';\nimport { createSrcBatchPlan, runSrcCli } from '../sourcegraph/index.js';\nimport { getProjectContext } from '../context/git.js';\nimport { startRepl } from '../repl/index.js';\nimport { startTui } from '../tui/index.js';\nimport { TokenCache } from '../cache/token-cache.js';\nimport { analyzeBlastRadius, isSeverityAtLeast, type RiskLevel } from '../blast-radius/index.js';\nimport { AgentKeeper } from '../memory/agentkeeper.js';\nimport { CheckpointStore } from '../checkpoint/store.js';\nimport { scorePatchRisk } from '../risk/score.js';\nimport { runXSearch } from '../xai/search.js';\nimport { MemoryBroker } from '../memory/broker.js';\nimport { getNestedValue, loadResolvedRepoConfig, readRepoConfig, redactRepoConfigForDisplay, setRepoConfigValue } from '../config/repo-config.js';\nimport { commandToShell, describeIntent, executeGitHubIntent, parseGitHubIntent, requiresConfirmation, runGitHubDoctor, buildGitHubCommand } from '../github/nl.js';\nimport { loadModelPolicy } from '../config/model-policy.js';\nimport { AutoFixStore, type AutoFixApplyPolicy, type AutoFixJobStatus } from '../autofix/store.js';\nimport { runAutoFixJob } from '../autofix/runner.js';\nimport { loadPipelineMetricsSummary } from '../metrics/pipeline.js';\nimport { randomUUID } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { execSync } from 'node:child_process';\nimport { enforceStrictPreflight, getCapabilityHandshake, getExecutionPolicy, isRetryableError, isRiskBlocked, withRetries, type RiskThreshold } from '../runtime/execution-policy.js';\nimport type { PipelineRunEvent } from '../types/common.js';\n\n\nconst program = new Command();\n\nexport function parseHeadlessShortcutArgs(args: string[]) {\n  const enabled = args.includes('--headless');\n  if (!enabled) return { enabled: false };\n\n  const readValue = (...names: string[]) => {\n    for (let i = 0; i < args.length; i += 1) {\n      if (names.includes(args[i])) return args[i + 1];\n    }\n    return undefined;\n  };\n\n  return {\n    enabled: true,\n    json: args.includes('--json'),\n    alwaysApprove: args.includes('--always-approve'),\n    out: readValue('--out'),\n    task: readValue('-t', '--task'),\n    agent: readValue('--agent'),\n    gateway: readValue('-g', '--gateway')\n  };\n}\n\nfunction extractValidationSignals(result: Record<string, unknown>, requireValidation: boolean) {\n  if (!requireValidation) {\n    return {\n      required: false,\n      passed: true,\n      lintPassed: undefined as boolean | undefined,\n      testsPassed: undefined as boolean | undefined,\n      notes: ''\n    };\n  }\n\n  const candidates = [\n    result?.validation,\n    result?.metadata?.validation,\n    result?.meta?.validation\n  ].filter(Boolean);\n  const merged = Object.assign({}, ...candidates);\n\n  let lintPassed: boolean | undefined;\n  let testsPassed: boolean | undefined;\n  const hasLint = typeof merged?.lintPassed === 'boolean' || typeof result?.lintPassed === 'boolean';\n  const hasTests = typeof merged?.testsPassed === 'boolean' || typeof result?.testsPassed === 'boolean';\n  if (hasLint) lintPassed = Boolean(merged?.lintPassed ?? result?.lintPassed);\n  if (hasTests) testsPassed = Boolean(merged?.testsPassed ?? result?.testsPassed);\n\n  let explicitPass: boolean | undefined;\n  if (typeof merged?.passed === 'boolean') explicitPass = merged.passed;\n  else if (typeof merged?.ok === 'boolean') explicitPass = merged.ok;\n  else if (typeof merged?.success === 'boolean') explicitPass = merged.success;\n\n  if (explicitPass === undefined && !hasLint && !hasTests) {\n    const text = String(result?.result || '').toLowerCase();\n    if (/\\btests?\\s+(all\\s+)?passed\\b/.test(text)) testsPassed = true;\n    if (/\\b(?:lint|eslint|typecheck|type-check)\\s+passed\\b/.test(text)) lintPassed = true;\n    if (/\\btests?\\s+failed\\b/.test(text)) testsPassed = false;\n    if (/\\b(?:lint|eslint|typecheck|type-check)\\s+failed\\b/.test(text)) lintPassed = false;\n  }\n\n  const anySignal = explicitPass !== undefined || lintPassed !== undefined || testsPassed !== undefined;\n  const checks: boolean[] = [];\n  if (explicitPass !== undefined) checks.push(explicitPass);\n  if (lintPassed !== undefined) checks.push(lintPassed);\n  if (testsPassed !== undefined) checks.push(testsPassed);\n  const passed = anySignal && checks.every(Boolean);\n  const notes = passed\n    ? 'validation-signals-present'\n    : anySignal\n      ? 'validation-failed'\n      : 'validation-signals-missing';\n\n  return {\n    required: true,\n    passed,\n    lintPassed,\n    testsPassed,\n    notes\n  };\n}\n\ninterface ParsedDiagnostic {\n  file: string;\n  line: number;\n  column: number;\n  category: string;\n  message: string;\n}\n\n/**\n * Parse structured diagnostics from command output.\n * Handles common formats: TSC, ESLint, Jest, pytest, gcc/clang, Go, Rust.\n */\nfunction parseDiagnosticOutput(output: string, command: string): ParsedDiagnostic[] {\n  const diagnostics: ParsedDiagnostic[] = [];\n  const seen = new Set<string>();\n  const lines = output.split('\\n');\n\n  for (const line of lines) {\n    let match: RegExpMatchArray | null;\n\n    // TypeScript / ESLint: src/foo.ts(10,5): error TS2345: ...\n    // Also: src/foo.ts:10:5 - error TS2345: ...\n    match = line.match(/^(.+?)[:(](\\d+)[,:](\\d+)[):]?\\s*[-\u2013:]\\s*(error|warning|info)\\s+(.+)/i);\n    if (!match) {\n      // GCC / Clang / Go: foo.go:10:5: error: ...\n      match = line.match(/^(.+?):(\\d+):(\\d+):\\s*(error|warning|note|fatal error):\\s*(.+)/i);\n    }\n    if (!match) {\n      // Simple file:line: message (pytest, generic)\n      match = line.match(/^(.+?):(\\d+):\\s*(error|Error|FAIL|FAILED|E\\s)(.+)/);\n      if (match) {\n        match = [match[0], match[1], match[2], '1', 'error', match[4].trim()];\n      }\n    }\n    if (!match) {\n      // Jest: \"FAIL src/foo.test.ts\" then indented errors \u2014 skip these for now\n      // Rust: error[E0308]: ...  at --> src/main.rs:10:5\n      match = line.match(/^\\s*--> (.+?):(\\d+):(\\d+)/);\n      if (match) {\n        match = [match[0], match[1], match[2], match[3], 'error', 'see above'];\n      }\n    }\n\n    if (match) {\n      const key = `${match[1]}:${match[2]}:${match[5]?.slice(0, 80)}`;\n      if (!seen.has(key)) {\n        seen.add(key);\n        diagnostics.push({\n          file: match[1].trim(),\n          line: Number(match[2]),\n          column: Number(match[3]) || 1,\n          category: String(match[4]).toLowerCase().startsWith('warn') ? 'warning' : 'error',\n          message: String(match[5]).trim()\n        });\n      }\n    }\n  }\n\n  return diagnostics;\n}\n\ntype SubscriptionEngineId = 'cursor' | 'claude-cli' | 'codex-cli';\n\ninterface SubscriptionEngineProbe {\n  id: SubscriptionEngineId;\n  binary: string;\n  installed: boolean;\n  authenticated: boolean;\n  ready: boolean;\n  notes: string[];\n  version: string;\n}\n\nfunction hasBinary(bin: string): boolean {\n  try {\n    execSync(`command -v ${bin}`, { stdio: 'ignore' });\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nfunction readBinaryVersion(bin: string): string {\n  try {\n    return String(execSync(`${bin} --version`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })).trim();\n  } catch {\n    return '';\n  }\n}\n\nfunction commandOutput(command: string): { ok: boolean; output: string } {\n  try {\n    const output = String(execSync(`${command} 2>&1`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })).trim();\n    return { ok: true, output };\n  } catch (error) {\n    const execError = error as { stdout?: string; stderr?: string };\n    const output = String(execError.stdout || execError.stderr || '').trim();\n    return { ok: false, output };\n  }\n}\n\nfunction detectCliAuthStatus(): { claude: boolean; codex: boolean; cursor: boolean } {\n  const claude = hasBinary('claude')\n    ? (() => {\n      const result = commandOutput('claude auth status');\n      const text = (result.output || '').toLowerCase();\n      if (!text) return false;\n      if (/\"loggedin\"\\s*:\\s*true/.test(text)) return true;\n      if (text.includes('logged in')) return true;\n      return false;\n    })()\n    : false;\n\n  const codex = hasBinary('codex')\n    ? (() => {\n      const result = commandOutput('codex login status');\n      const text = (result.output || '').toLowerCase();\n      return text.includes('logged in');\n    })()\n    : false;\n\n  const cursor = hasBinary('cursor') && existsSync(join(homedir(), '.cursor', 'User', 'globalStorage', 'state.vscdb'));\n\n  return { claude, codex, cursor };\n}\n\nfunction detectSubscriptionEngines(tokens: Record<string, string | undefined>): SubscriptionEngineProbe[] {\n  const cursorInstalled = hasBinary('cursor');\n  const claudeInstalled = hasBinary('claude');\n  const codexInstalled = hasBinary('codex');\n  const cliAuth = detectCliAuthStatus();\n\n  const cursorAuth = Boolean(tokens.cursor || cliAuth.cursor);\n  const claudeAuth = Boolean(tokens.claude || cliAuth.claude);\n  const codexAuth = Boolean(tokens.openai || process.env.OPENAI_API_KEY || cliAuth.codex);\n\n  return [\n    {\n      id: 'cursor',\n      binary: 'cursor',\n      installed: cursorInstalled,\n      authenticated: cursorAuth,\n      ready: cursorInstalled && cursorAuth,\n      notes: [\n        cursorInstalled ? 'binary-ok' : 'missing-binary',\n        cursorAuth ? 'auth-ok' : 'auth-not-detected'\n      ],\n      version: cursorInstalled ? readBinaryVersion('cursor') : ''\n    },\n    {\n      id: 'claude-cli',\n      binary: 'claude',\n      installed: claudeInstalled,\n      authenticated: claudeAuth,\n      ready: claudeInstalled && claudeAuth,\n      notes: [\n        claudeInstalled ? 'binary-ok' : 'missing-binary',\n        claudeAuth ? 'auth-ok' : 'auth-not-detected'\n      ],\n      version: claudeInstalled ? readBinaryVersion('claude') : ''\n    },\n    {\n      id: 'codex-cli',\n      binary: 'codex',\n      installed: codexInstalled,\n      authenticated: codexAuth,\n      ready: codexInstalled && codexAuth,\n      notes: [\n        codexInstalled ? 'binary-ok' : 'missing-binary',\n        codexAuth ? 'auth-ok' : 'auth-not-detected'\n      ],\n      version: codexInstalled ? readBinaryVersion('codex') : ''\n    }\n  ];\n}\n\nfunction normalizeStandaloneEngine(engine: string): string {\n  const raw = String(engine || '').trim().toLowerCase();\n  if (!raw || raw === 'auto') return 'auto';\n  if (raw === 'claude' || raw === 'claude-code') return 'claude-cli';\n  if (raw === 'gemini' || raw === 'gemini-api') return 'gemini-cli';\n  if (raw === 'codex') return 'codex-cli';\n  if (raw === 'cursor') return 'cursor-cli';\n  return raw;\n}\n\nfunction shouldRetryWithFallback(error: unknown): boolean {\n  const text = String((error as Error)?.message || '').toLowerCase();\n  return isRetryableError(error) || text.includes('empty');\n}\n\nfunction printJsonEnvelope(kind: string, payload: Record<string, unknown>) {\n  console.log(JSON.stringify({\n    version: 'v1',\n    kind,\n    ts: new Date().toISOString(),\n    ...payload\n  }, null, 2));\n}\n\nasync function loadPipelineRunEvents(traceId: string, baseDir = process.cwd()): Promise<PipelineRunEvent[]> {\n  const path = join(baseDir, '.crew', 'pipeline-runs', `${traceId}.jsonl`);\n  const raw = await readFile(path, 'utf8');\n  return raw\n    .split('\\n')\n    .map(line => line.trim())\n    .filter(Boolean)\n    .map(line => {\n      try {\n        return JSON.parse(line);\n      } catch {\n        return null;\n      }\n    })\n    .filter(Boolean);\n}\n\nfunction inferResumeTask(events: Record<string, unknown>[]): { task: string; phase: string } | null {\n  if (!Array.isArray(events) || events.length === 0) return null;\n  const firstPlan = events.find(e => String(e?.phase || '') === 'plan' && typeof e?.userInput === 'string');\n  const last = events[events.length - 1];\n  if (!firstPlan?.userInput) return null;\n  return {\n    task: String(firstPlan.userInput),\n    phase: String(last?.phase || 'unknown')\n  };\n}\n\nfunction extractResumeArtifacts(events: Record<string, unknown>[]): {\n  priorPlan?: unknown;\n  priorResponse?: string;\n  priorExecutionResults?: unknown;\n} {\n  const planEvent = [...events].reverse().find(e => String(e?.phase || '') === 'plan.completed' && e?.plan);\n  const validateInput = [...events].reverse().find(e => String(e?.phase || '') === 'validate.input');\n  return {\n    priorPlan: planEvent?.plan,\n    priorResponse: typeof validateInput?.response === 'string' ? validateInput.response : undefined,\n    priorExecutionResults: validateInput?.executionResults\n  };\n}\n\nasync function runValidationCommands(commands: string[] = [], cwd = process.cwd()) {\n  if (!Array.isArray(commands) || commands.length === 0) {\n    return { passed: true, failedCommand: '', output: '' };\n  }\n  for (const cmd of commands) {\n    try {\n      const out = execSync(cmd, {\n        cwd,\n        stdio: 'pipe',\n        encoding: 'utf8',\n        maxBuffer: 2 * 1024 * 1024\n      });\n      if (String(out || '').trim().length > 0) {\n        // keep deterministic side-effect free behavior, no streaming here.\n      }\n    } catch (error) {\n      const execError = error as { stderr?: string };\n      return {\n        passed: false,\n        failedCommand: cmd,\n        output: String(execError.stderr || (error as Error)?.message || '')\n      };\n    }\n  }\n  return { passed: true, failedCommand: '', output: '' };\n}\n\nasync function runLspAutoFixCycle(\n  projectDir: string,\n  maxAttempts: number,\n  options: {\n    router: AgentRouter;\n    orchestrator: Orchestrator;\n    sessionId: string;\n    gateway?: string;\n    model?: string;\n    fallbackModels?: string[];\n    checkpoints?: CheckpointStore;\n    runId?: string;\n    logger: Logger;\n  }\n): Promise<{ fixed: boolean; attempts: number; remainingDiagnostics: number }> {\n  const { typeCheckProject } = await import('../lsp/index.js');\n  const cappedAttempts = Math.max(1, maxAttempts);\n  let diagnostics = await typeCheckProject(projectDir, []);\n  if (diagnostics.length === 0) return { fixed: true, attempts: 0, remainingDiagnostics: 0 };\n\n  let attempts = 0;\n  while (attempts < cappedAttempts && diagnostics.length > 0) {\n    attempts += 1;\n    const top = diagnostics.slice(0, 30);\n    const summary = top\n      .map(d => `${d.file}:${d.line}:${d.column} [${d.category}] TS${d.code} ${d.message}`)\n      .join('\\n');\n    const task = [\n      'Run a targeted TypeScript auto-fix pass for the following diagnostics.',\n      'Apply minimal safe changes only.',\n      'Diagnostics:',\n      summary\n    ].join('\\n');\n\n    const dispatched = await dispatchWithFallback(\n      options.router,\n      'crew-fixer',\n      task,\n      {\n        project: projectDir,\n        sessionId: options.sessionId,\n        gateway: options.gateway,\n        model: options.model\n      },\n      options.fallbackModels || [],\n      options.checkpoints,\n      options.runId\n    );\n    const response = String(dispatched.result?.result || '');\n    const edits = await options.orchestrator.parseAndApplyToSandbox(response);\n    options.logger.info(`LSP auto-fix attempt ${attempts}: ${diagnostics.length} diagnostics, ${edits.length} sandbox edit(s).`);\n    await options.checkpoints?.append(String(options.runId || ''), 'lsp.autofix.attempt', {\n      attempt: attempts,\n      diagnostics: diagnostics.length,\n      edits: edits.length\n    });\n    diagnostics = await typeCheckProject(projectDir, []);\n  }\n\n  return {\n    fixed: diagnostics.length === 0,\n    attempts,\n    remainingDiagnostics: diagnostics.length\n  };\n}\n\nasync function dispatchWithFallback(\n  router: AgentRouter,\n  agent: string,\n  task: string,\n  options: Record<string, unknown>,\n  fallbackModels: string[] = [],\n  checkpoint?: CheckpointStore,\n  runId?: string\n) {\n  const tried: string[] = [];\n  const primary = String(options.model || '').trim();\n  if (primary) tried.push(primary);\n  const chain = [primary, ...fallbackModels].map(x => String(x || '').trim()).filter(Boolean);\n  if (chain.length === 0) {\n    const result = await router.dispatch(agent, task, options);\n    return { result, usedModel: primary || 'default', attempts: tried };\n  }\n\n  let lastError: Error | null = null;\n  for (let i = 0; i < chain.length; i++) {\n    const model = chain[i];\n    tried.push(model);\n    try {\n      if (checkpoint && runId) {\n        await checkpoint.append(runId, 'dispatch.model.attempt', { model, index: i + 1 });\n      }\n      const result = await router.dispatch(agent, task, { ...options, model });\n      if (checkpoint && runId) {\n        await checkpoint.append(runId, 'dispatch.model.success', { model, index: i + 1 });\n      }\n      return { result, usedModel: model, attempts: tried };\n    } catch (error) {\n      lastError = error as Error;\n      if (checkpoint && runId) {\n        await checkpoint.append(runId, 'dispatch.model.failed', { model, error: String((error as Error).message || error) });\n      }\n      const retryable = shouldRetryWithFallback(error);\n      const hasNext = i < chain.length - 1;\n      if (!retryable || !hasNext) break;\n    }\n  }\n\n  throw lastError || new Error('Dispatch failed across fallback chain');\n}\n\nexport function parseConfigValue(raw: string, asJson = false): unknown {\n  const text = String(raw ?? '').trim();\n  if (asJson) {\n    return JSON.parse(text);\n  }\n  if (text === 'true') return true;\n  if (text === 'false') return false;\n  if (text === 'null') return null;\n  if (/^-?\\d+(\\.\\d+)?$/.test(text)) return Number(text);\n  return text;\n}\n\nexport async function main(args = []) {\n  // \u2500\u2500 Fast-path for lightweight commands that don't need full startup \u2500\u2500\n  const firstArg = (args.find(a => !a.startsWith('-')) || '').toLowerCase();\n  if (['doctor', 'update', 'version'].includes(firstArg)) {\n    const lightweight = new Command();\n    lightweight.name('crew');\n\n    lightweight\n      .command('doctor')\n      .description('Run local diagnostics (Node, Git, config, API keys, gateway)')\n      .option('-g, --gateway <url>', 'Gateway URL to check', 'http://localhost:5010')\n      .option('--update-tag <tag>', 'Version channel for update check', 'latest')\n      .action(async options => {\n        const checks = await runDoctorChecks({ gateway: options.gateway, updateTag: options.updateTag });\n        const summary = summarizeDoctorResults(checks);\n\n        console.log(chalk.blue('\\ncrew doctor\\n'));\n        checks.forEach(check => {\n          let marker = check.ok ? chalk.green('\u2713') : chalk.red('\u2717');\n          if (check.name === 'CLI update status' && String(check.details || '').toLowerCase().includes('update available')) {\n            marker = chalk.yellow('!');\n          }\n          console.log(`  ${marker} ${check.name} ${chalk.gray(`\u2014 ${check.details}`)}`);\n          if (!check.ok && check.hint) {\n            check.hint.split('\\n').forEach(line => console.log(chalk.yellow(`    ${line}`)));\n          }\n        });\n\n        console.log();\n        const summaryColor = summary.failed === 0 ? chalk.green : chalk.red;\n        console.log(summaryColor(`  ${summary.passed} passed, ${summary.failed} failed\\n`));\n\n        if (summary.failed > 0) process.exit(1);\n      });\n\n    lightweight\n      .command('update')\n      .description('Check for updates and install latest crew-cli globally')\n      .option('--check', 'Only check availability, do not install', false)\n      .option('--tag <tag>', 'Update channel/tag (default: latest)', 'latest')\n      .option('-y, --yes', 'Skip confirmation prompt', false)\n      .action(async options => {\n        const installed = await getInstalledCliVersion();\n        const latest = await getLatestCliVersion(options.tag || 'latest');\n        if (!latest) {\n          console.log(chalk.yellow('Unable to check latest version from npm right now.'));\n          return;\n        }\n        if (!installed) {\n          console.log(chalk.yellow(`Current version unknown. Latest available: ${latest}`));\n          return;\n        }\n        const cmp = compareVersions(installed, latest);\n        if (cmp >= 0) {\n          console.log(chalk.green(`\u2713 Up to date (${installed})`));\n        } else {\n          console.log(chalk.yellow(`Update available: ${installed} \u2192 ${latest}`));\n          console.log(chalk.gray('Run: npm i -g crewswarm-cli@latest'));\n        }\n      });\n\n    lightweight\n      .command('version')\n      .description('Show crew-cli version')\n      .action(async () => {\n        const v = await getInstalledCliVersion();\n        console.log(v || 'unknown');\n      });\n\n    await lightweight.parseAsync(args, { from: 'user' });\n    process.exit(0);\n  }\n\n  const normalizedArgs = [...args];\n  if (normalizedArgs.includes('--legacy-router')) {\n    process.env.CREW_LEGACY_ROUTER = 'true';\n    process.env.CREW_USE_UNIFIED_ROUTER = 'false';\n    const idx = normalizedArgs.indexOf('--legacy-router');\n    normalizedArgs.splice(idx, 1);\n    args = normalizedArgs;\n  }\n\n  // Show banner on first launch (or always if CREW_SHOW_BANNER=1)\n  const bannerFile = join(process.env.HOME || homedir(), '.crew', 'cli-banner-seen');\n  const showAlways = process.env.CREW_SHOW_BANNER === '1';\n  \n  if (showAlways || !existsSync(bannerFile)) {\n    const banner = `\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n\u2551                                                                           \u2551\n\u2551     \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557    \u2588\u2588\u2557      \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557     \u2588\u2588\u2557           \u2551\n\u2551    \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551    \u2588\u2588\u2551     \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n\u2551    \u2588\u2588\u2551      \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2557  \u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n\u2551    \u2588\u2588\u2551      \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u255D  \u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n\u2551    \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551  \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D     \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551           \u2551\n\u2551     \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D  \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D       \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D           \u2551\n\u2551                                                                           \u2551\n\u2551                   \uD83C\uDFAA One idea. One Build. One Crew.                       \u2551\n\u2551                                                                           \u2551\n\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n`;\n    console.log(chalk.cyan(banner));\n    \n    // Mark as seen (best effort)\n    try {\n      await mkdir(dirname(bannerFile), { recursive: true });\n      await writeFile(bannerFile, new Date().toISOString());\n    } catch (e) {\n      logger.error(`Failed to mark banner as seen: ${e.message}`);\n    }\n  }\n\n  // (fast-path for doctor/update/version is at the top of main())\n\n  // Load env vars from ~/.crewswarm/crewswarm.json (set via Dashboard \u2192 Settings)\n  // These override process.env only if not already set (env vars take precedence)\n  try {\n    const swarmCfgPath = join(homedir(), '.crewswarm', 'crewswarm.json');\n    if (existsSync(swarmCfgPath)) {\n      const swarmCfg = JSON.parse(await readFile(swarmCfgPath, 'utf8'));\n      const providerEnvMap: Record<string, string> = {\n        openai: \"OPENAI_API_KEY\",\n        anthropic: \"ANTHROPIC_API_KEY\",\n        xai: \"XAI_API_KEY\",\n        grok: \"XAI_API_KEY\",\n        google: \"GEMINI_API_KEY\",\n        gemini: \"GEMINI_API_KEY\",\n        deepseek: \"DEEPSEEK_API_KEY\",\n        groq: \"GROQ_API_KEY\",\n        mistral: \"MISTRAL_API_KEY\",\n        perplexity: \"PERPLEXITY_API_KEY\",\n        cerebras: \"CEREBRAS_API_KEY\",\n        openrouter: \"OPENROUTER_API_KEY\",\n        nvidia: \"NVIDIA_API_KEY\",\n        fireworks: \"FIREWORKS_API_KEY\",\n        together: \"TOGETHER_API_KEY\",\n        huggingface: \"HF_API_KEY\",\n        greptile: \"GREPTILE_API_KEY\",\n      };\n      if (swarmCfg.env && typeof swarmCfg.env === 'object') {\n        for (const [k, v] of Object.entries(swarmCfg.env)) {\n          if (!process.env[k] && v != null) {\n            process.env[k] = String(v);\n          }\n        }\n      }\n      if (swarmCfg.providers && typeof swarmCfg.providers === \"object\") {\n        for (const [provider, config] of Object.entries(swarmCfg.providers)) {\n          const envKey = providerEnvMap[String(provider).toLowerCase()];\n          const apiKey = config && typeof config === \"object\" ? config.apiKey : null;\n          if (envKey && !process.env[envKey] && apiKey) {\n            process.env[envKey] = String(apiKey);\n          }\n        }\n      }\n    }\n  } catch {\n    // Never fail startup due to config read\n  }\n\n  const logger = new Logger();\n  const config = new ConfigManager();\n  const toolManager = new ToolManager(config);\n  const agentRouter = new AgentRouter(config, toolManager);\n  const sessionManager = new SessionManager(process.cwd());\n  const sandbox = new Sandbox(process.cwd());\n  const orchestrator = new Orchestrator(agentRouter, sandbox, sessionManager);\n  const corrections = new CorrectionStore(process.cwd());\n  const tokenCache = new TokenCache(process.cwd());\n  const agentKeeper = new AgentKeeper(process.cwd());\n  const checkpoints = new CheckpointStore(process.cwd());\n  const autoFixStore = new AutoFixStore(process.cwd());\n  const repoConfig = await loadResolvedRepoConfig(process.cwd());\n  const modelPolicy = await loadModelPolicy(process.cwd());\n  const cliDefaults = repoConfig.cli || {};\n  const plannerPolicy = modelPolicy.tiers?.planner || {};\n  const executorPolicy = modelPolicy.tiers?.executor || {};\n  const workerPolicy = modelPolicy.tiers?.worker || {};\n  const plannerPrimary = plannerPolicy.primary || cliDefaults.model || '';\n  const executorPrimary = executorPolicy.primary || cliDefaults.model || '';\n  const workerPrimary = workerPolicy.primary || cliDefaults.model || '';\n\n  await sessionManager.ensureInitialized();\n  await toolManager.initialize();\n  await sandbox.load();\n\n  const getStandaloneRuntime = async (projectDir?: string) => {\n    const targetDir = projectDir || process.cwd();\n    if (targetDir === process.cwd()) {\n      return { sandbox, orchestrator, sessionManager };\n    }\n    const scopedSession = new SessionManager(targetDir);\n    const scopedSandbox = new Sandbox(targetDir);\n    const scopedOrchestrator = new Orchestrator(agentRouter, scopedSandbox, scopedSession);\n    await scopedSession.ensureInitialized();\n    await scopedSandbox.load();\n    return {\n      sandbox: scopedSandbox,\n      orchestrator: scopedOrchestrator,\n      sessionManager: scopedSession\n    };\n  };\n\n  // Show banner on new sessions\n  const sessionData = await sessionManager.loadSession();\n  if (sessionData.history.length === 0 && !args.includes('--headless') && !args.includes('--json')) {\n    console.log(getBanner());\n  }\n\n  try {\n    await agentKeeper.compact();\n  } catch {\n    // Never fail startup due to maintenance compaction.\n  }\n\n  // Background codebase indexing \u2014 non-blocking, incremental\n  if (String(process.env.CREW_RAG_MODE || 'auto').toLowerCase() !== 'off') {\n    import('../context/codebase-rag.js').then(async ({ CodebaseIndex }) => {\n      try {\n        const index = CodebaseIndex.getInstance(process.cwd());\n        const result = await index.ensureIndex({\n          onProgress: (done, total) => {\n            if (done === total && done > 0) {\n              logger.info(`[RAG] Codebase index ready (${index.stats().files} files, provider: ${index.stats().provider})`);\n            }\n          }\n        });\n        if (result.indexed > 0) {\n          logger.info(`[RAG] Indexed ${result.indexed} new/changed files, skipped ${result.skipped} unchanged${result.removed > 0 ? `, removed ${result.removed} deleted` : ''}`);\n        }\n      } catch {\n        // Never fail startup due to indexing\n      }\n    }).catch(() => {});\n  }\n\n  const headlessShortcut = parseHeadlessShortcutArgs(args);\n  if (headlessShortcut.enabled) {\n    if (!headlessShortcut.task) {\n      console.error('Missing task for headless mode. Use -t \"your task\".');\n      process.exit(1);\n    }\n    const result = await runHeadlessTask({\n      task: headlessShortcut.task,\n      json: headlessShortcut.json,\n      alwaysApprove: headlessShortcut.alwaysApprove,\n      out: headlessShortcut.out,\n      agent: headlessShortcut.agent,\n      gateway: headlessShortcut.gateway,\n      projectDir: process.cwd(),\n      router: agentRouter,\n      orchestrator,\n      sandbox,\n      session: sessionManager\n    });\n    if (!result.success) process.exit(1);\n    return;\n  }\n\n  const cliVersion = (await getInstalledCliVersion()) || '0.1.0-alpha';\n\n  program\n    .name('crew')\n    .description('crewswarm CLI - Agent orchestration made simple')\n    .version(cliVersion);\n\n  program.option('--legacy-router', 'Use legacy routing path (disables UnifiedPipeline default)', false);\n\n  program\n    .command('chat')\n    .description('Chat with crewswarm (automatically routed to best agent)')\n    .argument('<input...>', 'Message or question')\n    .option('-p, --project <path>', 'Project directory')\n    .option('-g, --gateway <url>', 'Override gateway URL')\n    .option('-m, --model <id>', 'Model override for direct/bypass gateway paths', executorPrimary || undefined)\n    .option('--engine <id>', 'Engine override for direct/bypass gateway paths (e.g. cursor)', cliDefaults.engine || undefined)\n    .option('--direct', 'Request direct execution path on gateway', false)\n    .option('--bypass', 'Request bypass/orchestrator-skip path on gateway', false)\n    .option('--crew', 'Use full multi-agent crew via gateway (like OpenCode PM loop)', false)\n    .option('--apply', 'Auto-apply sandbox changes to disk after completion', false)\n    .option('--image <path>', 'Attach an image file to the prompt (repeatable)', collectOption, [])\n    .option('--context-image <path>', 'Attach an image file as context (repeatable)', collectOption, [])\n    .option('--image-max-bytes <n>', 'Max bytes per image context payload', '250000')\n    .option('--cross-repo', 'Inject sibling repository context', false)\n    .option('--context-file <path>', 'Attach a file as additional context (repeatable)', collectOption, [])\n    .option('--context-repo <path>', 'Attach git context from another repo (repeatable)', collectOption, [])\n    .option('--stdin', 'Read additional context from stdin', false)\n    .option('--max-context-tokens <n>', 'Max context token budget (approx, chars/4)')\n    .option('--context-budget-mode <mode>', 'trim | stop when budget exceeded', 'trim')\n    .option('--docs', 'Inject matching docs context via collections search', false)\n    .option('--docs-path <paths...>', 'Custom paths for docs search (default: docs/ + project root)')\n    .option('--docs-code', 'Include source code files in docs retrieval index', Boolean(cliDefaults.docsCode))\n    .option('--fallback-model <id>', 'Fallback model chain entry (repeatable)', collectOption, [])\n    .option('--retry-attempts <n>', 'Retry attempts for transient failures', '2')\n    .option('--strict-preflight', 'Block execution if doctor checks fail', false)\n    .option('--json', 'Output machine-readable JSON envelope', false)\n    .action(async (inputArray, options) => {\n      let input = inputArray.join(' ');\n      try {\n        const policy = getExecutionPolicy({\n          strictPreflight: Boolean(options.strictPreflight),\n          retryAttempts: Number.parseInt(options.retryAttempts || '2', 10)\n        });\n        await enforceStrictPreflight(policy, options.gateway);\n        const fileBlock = await buildFileContextBlock(options.contextFile || []);\n        const repoBlock = await buildRepoContextBlock(options.contextRepo || []);\n        const imagePaths = [...(options.image || []), ...(options.contextImage || [])];\n        const imageBlock = await buildImageContextBlock(\n          imagePaths,\n          Number.parseInt(options.imageMaxBytes || '250000', 10)\n        );\n        const stdinText = options.stdin ? await readStdinText() : '';\n        const stdinBlock = stdinText ? `## Stdin Context\\n\\`\\`\\`text\\n${stdinText}\\n\\`\\`\\`` : '';\n\n        let docsBlock = '';\n        if (options.docs) {\n          const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n          const docsPaths = options.docsPath && options.docsPath.length > 0\n            ? options.docsPath\n            : [join(process.cwd(), 'docs'), process.cwd()];\n          const index = await buildCollectionIndex(docsPaths, {\n            includeCode: Boolean(options.docsCode)\n          });\n          const result = searchCollection(index, input, 5);\n          if (result.hits.length > 0) {\n            const chunks = result.hits.map(h => `### ${h.source}:${h.startLine} (score: ${h.score})\\n${h.text}`);\n            docsBlock = `## Docs Context (auto-retrieved)\\n${chunks.join('\\n\\n')}`;\n          }\n        }\n\n        const budget = enforceContextBudget(\n          input,\n          [fileBlock, repoBlock, imageBlock, stdinBlock, docsBlock],\n          options.maxContextTokens ? Number.parseInt(options.maxContextTokens, 10) : undefined,\n          options.contextBudgetMode === 'stop' ? 'stop' : 'trim'\n        );\n        if (budget.exceeded) {\n          throw new Error(`Context budget exceeded (~${budget.estimatedTokens} tokens > ${options.maxContextTokens}). Use --context-budget-mode trim or raise budget.`);\n        }\n        if (budget.trimmed) {\n          logger.warn(`Context trimmed to stay under budget (~${budget.estimatedTokens} tokens).`);\n        }\n        input = budget.task;\n\n        if (options.crossRepo) {\n          const multiContext = await collectMultiRepoContext(options.project || process.cwd());\n          input = `${input}\\n\\n${multiContext}`;\n        }\n\n        const projectDir = options.project || process.cwd();\n\n        // crew-CLI: use connected mode (gateway dispatch) when --gateway or --crew is specified\n        // Otherwise use standalone agentic executor with built-in tools\n        const useConnected = Boolean(options.gateway || options.crew);\n        const useLegacyStandalone = String(process.env.CREW_LEGACY_ROUTER || '').toLowerCase() === 'true';\n        const fallbackModels = (options.fallbackModel && options.fallbackModel.length > 0)\n          ? options.fallbackModel\n          : (executorPolicy.fallback || []);\n        const capabilityHandshake = getCapabilityHandshake(useConnected ? 'connected' : 'standalone');\n\n        // crew-CLI uses agentic executor (standalone) unless explicitly connected\n        const selectedStandaloneEngine = normalizeStandaloneEngine(options.engine || '');\n        const useDirectCliEngine = !useConnected && !useLegacyStandalone && selectedStandaloneEngine !== 'auto' && selectedStandaloneEngine !== 'crew-cli';\n\n        if (useDirectCliEngine) {\n          logger.info(`Executing in standalone direct-engine mode (${selectedStandaloneEngine})`);\n          const result = await withRetries(\n            async () => runEngine(selectedStandaloneEngine, input, {\n              model: options.model,\n              cwd: projectDir,\n              projectDir\n            }),\n            policy\n          );\n          const responseText = String(result.stdout || result.stderr || '');\n          console.log(\n            JSON.stringify(\n              {\n                version: 'v1',\n                kind: 'chat.result',\n                ts: new Date().toISOString(),\n                route: { decision: 'EXECUTE', explanation: `Direct standalone engine (${selectedStandaloneEngine})` },\n                agent: selectedStandaloneEngine,\n                response: responseText,\n                engine: result.engine,\n                success: result.success,\n                exitCode: result.exitCode,\n                capabilityHandshake\n              },\n              null,\n              2\n            )\n          );\n          return;\n        }\n\n        if (!useConnected && !useLegacyStandalone) {\n          logger.info('Executing in standalone mode (agentic executor with file tools)');\n          const standaloneRuntime = await getStandaloneRuntime(projectDir);\n          const result = await withRetries(\n            async () => standaloneRuntime.orchestrator.executeAgentic(input, {\n              sessionId: await standaloneRuntime.sessionManager.getSessionId(),\n              model: options.model\n            }),\n            policy\n          );\n          const responseText = String(result.response || result.result || '');\n          const edits = await standaloneRuntime.orchestrator.parseAndApplyToSandbox(responseText);\n          const hasPendingChanges = standaloneRuntime.sandbox.hasChanges();\n          let appliedPaths: string[] = [];\n          if (hasPendingChanges && options.apply) {\n            appliedPaths = standaloneRuntime.sandbox.getPendingPaths();\n            await standaloneRuntime.sandbox.apply();\n          }\n          await standaloneRuntime.sessionManager.appendHistory({\n            input,\n            response: responseText,\n            decision: result.plan?.decision || 'execute',\n            agent: 'unified-pipeline',\n            model: String(result.plan?.validation?.modelUsed || 'unknown'),\n            costUsd: result.totalCost\n          });\n\n          console.log(\n            JSON.stringify(\n              {\n                version: 'v1',\n                kind: 'chat.result',\n                ts: new Date().toISOString(),\n                route: result.plan\n                  ? {\n                      decision: result.plan.decision.toUpperCase(),\n                      explanation: result.plan.reasoning\n                    }\n                  : { decision: 'EXECUTE', explanation: 'Direct L3 execution' },\n                agent: 'unified-pipeline',\n                response: responseText,\n                edits: edits.length > 0 ? edits : undefined,\n                applied: appliedPaths.length > 0 ? appliedPaths : undefined,\n                needsApproval: hasPendingChanges && appliedPaths.length === 0,\n                traceId: result.traceId,\n                timeline: result.timeline,\n                capabilityHandshake\n              },\n              null,\n              2\n            )\n          );\n          return;\n        }\n\n        // Connected mode or legacy: route first, then dispatch\n        const route = await orchestrator.route(input);\n\n        if (route.decision === 'CHAT' || route.decision === 'CODE' || route.decision === 'DISPATCH') {\n          const agent = route.agent || 'crew-main';\n          logger.info(`Routing to ${agent} (Decision: ${route.decision})`);\n\n          const result = await dispatchWithFallback(\n                agentRouter,\n                agent,\n                input,\n                {\n                  project: projectDir,\n                  sessionId: await sessionManager.getSessionId(),\n                  gateway: options.gateway,\n                  model: options.model,\n                  engine: options.engine,\n                  direct: options.direct,\n                  bypass: options.bypass,\n                  images: options.image || []\n                },\n                fallbackModels,\n                checkpoints,\n                `chat-${randomUUID()}`\n              );\n\n          const rawResponse = result.response || result.result || '';\n          const responseText = typeof rawResponse === 'object' \n            ? (rawResponse.result || rawResponse.output || rawResponse.message || JSON.stringify(rawResponse, null, 2))\n            : String(rawResponse);\n          // Try to parse any edits\n          const edits = await orchestrator.parseAndApplyToSandbox(responseText);\n          let appliedPaths: string[] = [];\n          if (edits.length > 0 && (options.apply || options.crew)) {\n            appliedPaths = sandbox.getPendingPaths();\n            await sandbox.apply();\n          }\n          if (options.json) {\n            printJsonEnvelope('chat.result', {\n              route,\n              agent,\n              response: responseText,\n              edits,\n              applied: appliedPaths.length > 0 ? appliedPaths : undefined,\n              needsApproval: edits.length > 0 && appliedPaths.length === 0,\n              traceId: result.traceId || null,\n              timeline: Array.isArray(result.timeline) ? result.timeline : [],\n              capabilityHandshake\n            });\n            return;\n          }\n          console.log(chalk.blue('\\n--- Agent Response ---'));\n          console.log(responseText);\n          if (Array.isArray(result.timeline) && result.timeline.length > 0) {\n            console.log(chalk.gray('\\nPipeline timeline:'));\n            for (const step of result.timeline) {\n              console.log(chalk.gray(`  - ${step.phase} @ ${step.ts}`));\n            }\n          }\n          if (edits.length > 0) {\n            if (appliedPaths.length > 0) {\n              logger.success(`\u2713 Applied ${appliedPaths.length} files to disk`);\n              appliedPaths.forEach(f => logger.info(`  - ${f}`));\n            } else {\n              logger.success(`Added changes to ${edits.length} files in sandbox. Run \"crew preview\" to review.`);\n            }\n          }\n        } else if (route.decision === 'SKILL') {\n          logger.info('Detected skill request. Please use \"crew skill <name>\" for now.');\n        }\n      } catch (error) {\n        logger.error('Chat failed:', error.message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('auto')\n    .description('Autonomous mode - LLM iterates on task until completion without approval prompts')\n    .argument('<task...>', 'Task description')\n    .option('-p, --project <path>', 'Project directory', process.cwd())\n    .option('-g, --gateway <url>', 'Override gateway URL')\n    .option('-m, --model <id>', 'Model override', workerPrimary || undefined)\n    .option('--fallback-model <id>', 'Fallback model chain entry (repeatable)', collectOption, [])\n    .option('--max-iterations <n>', 'Maximum autonomous iterations', '10')\n    .option('--auto-apply', 'Automatically apply sandbox changes when task completes', false)\n    .option('--cross-repo', 'Inject sibling repository context', false)\n    .option('--cache', 'Enable output cache for autonomous iterations', false)\n    .option('--cache-ttl <sec>', 'Output cache TTL in seconds', '1800')\n    .option('--no-memory', 'Disable shared AgentKeeper memory')\n    .option('--memory-max <n>', 'Max recalled memory entries', String(cliDefaults.memoryMax ?? 3))\n    .option('--memory-require-validation', 'Store memory only when validation is marked passed', false)\n    .option('--lsp-auto-fix', 'Run LSP diagnostics and auto-dispatch fixes after edits', false)\n    .option('--lsp-auto-fix-max-attempts <n>', 'Max LSP auto-fix attempts per iteration', '3')\n    .option('--no-blast-radius-gate', 'Disable blast-radius safety gate before auto-apply')\n    .option('--blast-radius-threshold <level>', 'Blast-radius gate threshold: low|medium|high', 'high')\n    .option('--force-auto-apply', 'Bypass blast-radius gate and auto-apply anyway', false)\n    .option('--escalate-risk', 'Escalate high-risk patches to QA and Security before completion', false)\n    .option('--risk-threshold <level>', 'Escalation threshold: low|medium|high', 'high')\n    .action(async (taskArray, options) => {\n      const task = taskArray.join(' ');\n      const projectDir = options.project || process.cwd();\n      const maxIterations = Number.parseInt(options.maxIterations || '10', 10);\n      const fallbackModels = (options.fallbackModel && options.fallbackModel.length > 0)\n        ? options.fallbackModel\n        : (workerPolicy.fallback || []);\n\n      logger.info(chalk.cyan(`\uD83E\uDD16 Autonomous Mode: ${task}`));\n      logger.info(chalk.gray(`   Max iterations: ${maxIterations}`));\n      logger.info(chalk.gray(`   Project: ${projectDir}\\n`));\n\n      let currentTask = task;\n      let iteration = 0;\n      let failedRun = false;\n      const runId = `auto-${randomUUID()}`;\n      const useMemory = options.memory !== false;\n      await checkpoints.beginRun({ runId, mode: 'auto', task });\n\n      if (useMemory) {\n        const matches = await agentKeeper.recall(task, Number.parseInt(options.memoryMax || '3', 10), {\n          preferSuccessful: true\n        });\n        const avgScore = matches.length\n          ? matches.reduce((sum, m) => sum + Number(m.score || 0), 0) / matches.length\n          : 0;\n        await sessionManager.trackMemoryRecall({\n          used: true,\n          miss: matches.length === 0,\n          matchCount: matches.length,\n          qualityScore: avgScore\n        });\n        if (matches.length > 0) {\n          const memoryContext = await agentKeeper.recallAsContext(task, Number.parseInt(options.memoryMax || '3', 10), {\n            preferSuccessful: true\n          });\n          currentTask = `${currentTask}\\n\\n${memoryContext}`;\n        }\n      }\n\n      if (options.crossRepo) {\n        const multiContext = await collectMultiRepoContext(projectDir);\n        currentTask = `${currentTask}\\n\\n${multiContext}`;\n      }\n\n      while (iteration < maxIterations) {\n        iteration += 1;\n        logger.info(chalk.blue(`\\n[Iteration ${iteration}/${maxIterations}]`));\n\n        try {\n          const route = await orchestrator.route(currentTask);\n          const agent = route.agent || 'crew-main';\n          \n          logger.info(chalk.gray(`  Routing to: ${agent}`));\n\n          const useCache = Boolean(options.cache);\n          const cacheKey = TokenCache.hashKey(JSON.stringify({\n            kind: 'auto-output',\n            agent,\n            task: currentTask,\n            projectDir,\n            gateway: options.gateway || '',\n            model: options.model || ''\n          }));\n\n          let result: Record<string, unknown> | undefined;\n          if (useCache) {\n            const cached = await tokenCache.get<Record<string, unknown>>('output', cacheKey);\n            if (cached.hit && cached.value) {\n              logger.info(chalk.gray('  Using cached output.'));\n              result = cached.value;\n              await sessionManager.trackCacheSavings({\n                hit: true,\n                tokensSaved: Number(cached.meta?.tokensSaved || 0),\n                usdSaved: Number(cached.meta?.usdSaved || 0)\n              });\n            } else {\n              await sessionManager.trackCacheSavings({ miss: true });\n              const dispatched = await dispatchWithFallback(\n                agentRouter,\n                agent,\n                currentTask,\n                {\n                  project: projectDir,\n                  sessionId: await sessionManager.getSessionId(),\n                  gateway: options.gateway,\n                  model: options.model\n                },\n                fallbackModels,\n                checkpoints,\n                runId\n              );\n              result = dispatched.result;\n              const estTokens = Math.ceil((String(currentTask).length + String(result.result || '').length) / 4);\n              await tokenCache.set(\n                'output',\n                cacheKey,\n                result,\n                Number.parseInt(options.cacheTtl || '1800', 10),\n                { tokensSaved: estTokens, usdSaved: estTokens / 1_000_000, source: 'auto-output' }\n              );\n            }\n          } else {\n            const dispatched = await dispatchWithFallback(\n              agentRouter,\n              agent,\n              currentTask,\n              {\n                project: projectDir,\n                sessionId: await sessionManager.getSessionId(),\n                gateway: options.gateway,\n                model: options.model\n              },\n              fallbackModels,\n              checkpoints,\n              runId\n            );\n            result = dispatched.result;\n          }\n\n          await sessionManager.appendHistory({\n            type: 'auto_iteration',\n            agent,\n            iteration,\n            task: currentTask,\n            success: Boolean(result.success),\n            result: result.result\n          });\n          if (useMemory) {\n            const response = String(result.result || '').trim();\n            const isControlPrompt =\n              currentTask.startsWith('The previous changes have been staged in sandbox') ||\n              currentTask.startsWith('Continue working on:');\n            const hasSignal = response.length > 0;\n            const isSuccessful = Boolean(result.success);\n            const validation = extractValidationSignals(result, Boolean(options.memoryRequireValidation));\n            if (hasSignal && isSuccessful && !isControlPrompt && validation.passed) {\n              const saved = await agentKeeper.recordSafe({\n                runId,\n                tier: 'worker',\n                task,\n                result: response,\n                agent,\n                structured: {\n                  problem: task,\n                  validation: {\n                    lintPassed: validation.lintPassed,\n                    testsPassed: validation.testsPassed,\n                    notes: validation.notes\n                  },\n                  outcome: 'success'\n                },\n                metadata: {\n                  iteration,\n                  promptKind: 'user-task',\n                  success: true,\n                  validationRequired: validation.required,\n                  validationPassed: validation.passed\n                }\n              });\n              if (!saved.ok) {\n                logger.warn(`Memory write skipped: ${saved.error}`);\n              }\n            }\n          }\n\n          if (result.costUsd && result.model) {\n            await sessionManager.trackCost({\n              model: result.model,\n              usd: result.costUsd,\n              promptTokens: result.promptTokens || 0,\n              completionTokens: result.completionTokens || 0\n            });\n          }\n\n          const responseText = String(result.result || '');\n          console.log(chalk.cyan('\\n  Response:'));\n          logger.printWithHighlight(responseText);\n\n          // Parse and add to sandbox\n          const edits = await orchestrator.parseAndApplyToSandbox(responseText);\n          await checkpoints.append(runId, 'auto.iteration', {\n            iteration,\n            agent,\n            success: Boolean(result.success),\n            edits: edits.length\n          });\n          if (edits.length > 0) {\n            logger.success(`  \u2713 Added ${edits.length} file changes to sandbox`);\n            if (options.lspAutoFix) {\n              const lspFix = await runLspAutoFixCycle(\n                projectDir,\n                Number.parseInt(options.lspAutoFixMaxAttempts || '3', 10),\n                {\n                  router: agentRouter,\n                  orchestrator,\n                  sessionId: await sessionManager.getSessionId(),\n                  gateway: options.gateway,\n                  model: options.model,\n                  fallbackModels,\n                  checkpoints,\n                  runId,\n                  logger\n                }\n              );\n              if (lspFix.fixed) {\n                logger.success(`  \u2713 LSP auto-fix complete (${lspFix.attempts} attempt(s)).`);\n              } else {\n                logger.warn(`  \u26A0 LSP auto-fix incomplete (${lspFix.remainingDiagnostics} diagnostics remain after ${lspFix.attempts} attempt(s)).`);\n              }\n            }\n          }\n\n          // Check if task appears complete\n          const lowerResponse = responseText.toLowerCase();\n          const completionSignals = [\n            'task complete', 'task is complete', 'implementation complete',\n            'all done', 'finished', 'successfully implemented',\n            'no further changes needed', 'ready for review'\n          ];\n          \n          const hasCompletionSignal = completionSignals.some(signal => lowerResponse.includes(signal));\n          \n          if (hasCompletionSignal) {\n            logger.success(chalk.green(`\\n\u2713 Task appears complete after ${iteration} iteration(s)`));\n            break;\n          }\n\n          // If we have sandbox changes, ask the LLM to verify and continue or finish\n          if (edits.length > 0 && iteration < maxIterations) {\n            currentTask = `The previous changes have been staged in sandbox. Please verify the implementation is complete and correct. If there are any remaining issues, fix them. If everything looks good, respond with \"Task complete.\"`;\n          } else if (iteration >= maxIterations) {\n            logger.warn(chalk.yellow(`\\n\u26A0\uFE0F  Reached max iterations (${maxIterations})`));\n            break;\n          } else {\n            // No edits detected, ask for next step\n            currentTask = `Continue working on: ${task}`;\n          }\n        } catch (err) {\n          logger.error(`Iteration ${iteration} failed: ${(err as Error).message}`);\n          failedRun = true;\n          await checkpoints.append(runId, 'auto.error', {\n            iteration,\n            error: (err as Error).message\n          });\n          \n          await sessionManager.appendHistory({\n            type: 'auto_error',\n            iteration,\n            task: currentTask,\n            error: (err as Error).message\n          });\n          \n          break;\n        }\n      }\n\n      // Show final sandbox state\n      const activeBranch = sandbox.getActiveBranch();\n      if (sandbox.hasChanges(activeBranch)) {\n        console.log(chalk.blue('\\n--- Pending Changes ---'));\n        console.log(logger.highlightDiff(sandbox.preview(activeBranch)));\n        \n        if (options.autoApply) {\n          try {\n            const paths = sandbox.getPendingPaths(activeBranch);\n            const report = await analyzeBlastRadius(projectDir, { changedFiles: paths });\n            const patchRisk = scorePatchRisk({\n              blastRadius: report,\n              changedFiles: paths.length\n            });\n            logger.info(`Patch confidence: ${(patchRisk.confidence * 100).toFixed(0)}% (risk score ${patchRisk.riskScore}/100, ${patchRisk.riskLevel})`);\n            await checkpoints.append(runId, 'patch.risk', {\n              riskLevel: patchRisk.riskLevel,\n              riskScore: patchRisk.riskScore,\n              confidence: patchRisk.confidence\n            });\n            if (options.escalateRisk && isSeverityAtLeast(patchRisk.riskLevel, String(options.riskThreshold || 'high').toLowerCase() as RiskLevel)) {\n              const escalationTask = `High-risk patch review requested.\\nRisk score: ${patchRisk.riskScore}/100 (${patchRisk.riskLevel}).\\nFiles: ${paths.join(', ')}.\\nPlease review for correctness, regressions, and security concerns.`;\n              const qa = await dispatchWithFallback(agentRouter, 'crew-qa', escalationTask, {\n                project: projectDir,\n                sessionId: await sessionManager.getSessionId(),\n                gateway: options.gateway\n              }, fallbackModels, checkpoints, runId);\n              const sec = await dispatchWithFallback(agentRouter, 'crew-security', escalationTask, {\n                project: projectDir,\n                sessionId: await sessionManager.getSessionId(),\n                gateway: options.gateway\n              }, fallbackModels, checkpoints, runId);\n              logger.info(chalk.yellow('\\n--- QA Escalation ---'));\n              logger.printWithHighlight(String(qa.result.result || ''));\n              logger.info(chalk.yellow('\\n--- Security Escalation ---'));\n              logger.printWithHighlight(String(sec.result.result || ''));\n            }\n            if (options.blastRadiusGate && !options.forceAutoApply) {\n              const threshold = (String(options.blastRadiusThreshold || 'high').toLowerCase() as 'low' | 'medium' | 'high');\n              logger.info(`Blast radius: ${report.summary}`);\n              if (isSeverityAtLeast(report.risk, threshold)) {\n                logger.warn('Auto-apply blocked by blast-radius safety gate.');\n                logger.warn(`Changed files: ${report.changedFiles.length}, direct impacts: ${report.affectedFiles.filter(f => f.relation === 'direct-importer').length}, transitive impacts: ${report.affectedFiles.filter(f => f.relation === 'transitive-importer').length}`);\n                logger.warn('Re-run with --force-auto-apply or lower --blast-radius-threshold to override.');\n                return;\n              }\n            }\n            await sandbox.apply(activeBranch);\n            logger.success(`\\n\u2713 Auto-applied changes to: ${paths.join(', ')}`);\n          } catch (applyErr) {\n            logger.error(`Auto-apply failed: ${(applyErr as Error).message}`);\n            logger.info('Run \"crew apply\" manually to apply changes.');\n          }\n        } else {\n          logger.info('\\nRun \"crew apply\" to write changes to disk, or \"crew preview\" to review.');\n        }\n      }\n\n      const cost = await sessionManager.loadCost();\n      logger.info(chalk.gray(`\\nTotal session cost: $${cost.totalUsd.toFixed(4)}`));\n      if (useMemory) {\n        const saved = await agentKeeper.recordSafe({\n          runId,\n          tier: 'orchestrator',\n          task,\n          result: sandbox.hasChanges(sandbox.getActiveBranch())\n            ? `Autonomous run finished with pending changes on branch ${sandbox.getActiveBranch()}`\n            : 'Autonomous run finished with no pending changes',\n          agent: 'crew-main',\n          structured: {\n            problem: task,\n            outcome: 'run-complete'\n          },\n          metadata: {\n            iterations: iteration,\n            autoApply: Boolean(options.autoApply)\n          }\n        });\n        if (!saved.ok) {\n          logger.warn(`Memory write skipped: ${saved.error}`);\n        }\n        if (iteration >= 5) {\n          try {\n            await agentKeeper.compact();\n          } catch {\n            // Best-effort maintenance.\n          }\n        }\n      }\n      await checkpoints.finish(runId, failedRun ? 'failed' : 'completed');\n    });\n\n  const autofix = program\n    .command('autofix')\n    .description('Background AutoFix queue and worker (safe unattended fix cycles)');\n\n  autofix\n    .command('enqueue')\n    .description('Queue a background AutoFix job')\n    .argument('<task...>', 'Task description')\n    .option('-p, --project <path>', 'Project directory', process.cwd())\n    .option('-g, --gateway <url>', 'Override gateway URL')\n    .option('-m, --model <id>', 'Model override', workerPrimary || undefined)\n    .option('--fallback-model <id>', 'Fallback model chain entry (repeatable)', collectOption, [])\n    .option('--max-iterations <n>', 'Maximum AutoFix iterations per job', '6')\n    .option('--validate-cmd <cmd>', 'Validation command gate (repeatable)', collectOption, [])\n    .option('--auto-apply-policy <mode>', 'never|safe|force', 'safe')\n    .option('--blast-radius-threshold <level>', 'Blast-radius threshold: low|medium|high', 'high')\n    .option('--lsp-auto-fix', 'Run TypeScript diagnostics auto-fix loop after edits', false)\n    .option('--lsp-auto-fix-max-attempts <n>', 'Max LSP auto-fix attempts', '3')\n    .action(async (taskArray, options) => {\n      const task = taskArray.join(' ').trim();\n      if (!task) {\n        logger.error('Task is required.');\n        process.exit(1);\n      }\n      const fallbackModels = (options.fallbackModel && options.fallbackModel.length > 0)\n        ? options.fallbackModel\n        : (workerPolicy.fallback || []);\n      const policyRaw = String(options.autoApplyPolicy || 'safe').toLowerCase();\n      const autoApplyPolicy: AutoFixApplyPolicy = policyRaw === 'force'\n        ? 'force'\n        : policyRaw === 'never'\n          ? 'never'\n          : 'safe';\n      const threshold = String(options.blastRadiusThreshold || 'high').toLowerCase();\n      const blastRadiusThreshold = threshold === 'low' || threshold === 'medium' || threshold === 'high'\n        ? threshold\n        : 'high';\n      const job = await autoFixStore.enqueue({\n        task,\n        projectDir: options.project || process.cwd(),\n        config: {\n          maxIterations: Number.parseInt(options.maxIterations || '6', 10),\n          model: options.model,\n          fallbackModels,\n          gateway: options.gateway,\n          validateCommands: options.validateCmd || [],\n          autoApplyPolicy,\n          blastRadiusThreshold,\n          lspAutoFix: Boolean(options.lspAutoFix),\n          lspAutoFixMaxAttempts: Number.parseInt(options.lspAutoFixMaxAttempts || '3', 10)\n        }\n      });\n      logger.success(`Queued AutoFix job ${job.id}`);\n      logger.info(`Policy: ${job.config.autoApplyPolicy} | Max iterations: ${job.config.maxIterations} | Project: ${job.projectDir}`);\n    });\n\n  autofix\n    .command('list')\n    .description('List background AutoFix jobs')\n    .option('--status <status>', 'Filter by status: queued|running|completed|failed|canceled')\n    .option('--max <n>', 'Maximum jobs to show', '30')\n    .action(async (options) => {\n      const statusRaw = String(options.status || '').toLowerCase();\n      const allowed: AutoFixJobStatus[] = ['queued', 'running', 'completed', 'failed', 'canceled'];\n      const filterStatus = allowed.includes(statusRaw as AutoFixJobStatus)\n        ? statusRaw as AutoFixJobStatus\n        : undefined;\n      const jobs = await autoFixStore.list({ status: filterStatus });\n      const max = Math.max(1, Number.parseInt(options.max || '30', 10));\n      const sliced = jobs.slice(0, max);\n      if (sliced.length === 0) {\n        logger.info('No AutoFix jobs found.');\n        return;\n      }\n      for (const job of sliced) {\n        const summary = job.result?.applied\n          ? 'applied'\n          : job.result?.proposalPath\n            ? `proposal: ${job.result.proposalPath}`\n            : '';\n        logger.info(`${job.id} | ${job.status} | ${job.updatedAt} | ${job.task}${summary ? ` | ${summary}` : ''}`);\n      }\n    });\n\n  autofix\n    .command('show')\n    .description('Show one AutoFix job in detail')\n    .argument('<jobId>', 'AutoFix job id')\n    .action(async (jobId) => {\n      const job = await autoFixStore.get(jobId);\n      if (!job) {\n        logger.error(`Job not found: ${jobId}`);\n        process.exit(1);\n      }\n      console.log(JSON.stringify(job, null, 2));\n    });\n\n  autofix\n    .command('cancel')\n    .description('Cancel a queued/running AutoFix job')\n    .argument('<jobId>', 'AutoFix job id')\n    .action(async (jobId) => {\n      const ok = await autoFixStore.cancel(jobId);\n      if (!ok) {\n        logger.error(`Unable to cancel job ${jobId}. It may be missing or already final.`);\n        process.exit(1);\n      }\n      logger.success(`Canceled ${jobId}`);\n    });\n\n  autofix\n    .command('worker')\n    .description('Run background AutoFix worker loop')\n    .option('--once', 'Process at most one queued job and exit', false)\n    .option('--max-jobs <n>', 'Stop after processing N jobs (0 = unlimited)', '0')\n    .option('--poll-ms <ms>', 'Poll interval when queue is empty', '5000')\n    .option('--worker-id <id>', 'Worker identity for lock/debug info', `worker-${process.pid}`)\n    .action(async (options) => {\n      const once = Boolean(options.once);\n      const maxJobs = Math.max(0, Number.parseInt(options.maxJobs || '0', 10));\n      const pollMs = Math.max(1000, Number.parseInt(options.pollMs || '5000', 10));\n      const workerId = String(options.workerId || `worker-${process.pid}`);\n      let processed = 0;\n\n      logger.info(`AutoFix worker started (${workerId})`);\n      while (true) {\n        const job = await autoFixStore.claimNext(workerId);\n        if (!job) {\n          if (once || (maxJobs > 0 && processed >= maxJobs)) break;\n          await new Promise(resolve => setTimeout(resolve, pollMs));\n          continue;\n        }\n\n        logger.info(`Running ${job.id}: ${job.task}`);\n        try {\n          const result = await runAutoFixJob(job, {\n            router: agentRouter,\n            orchestrator,\n            sandbox,\n            session: sessionManager,\n            logger,\n            checkpoints\n          });\n          await autoFixStore.markCompleted(job.id, {\n            ...result,\n            completedAt: new Date().toISOString()\n          });\n          logger.success(`Completed ${job.id} | applied=${result.applied} | files=${result.editedFiles.length}`);\n        } catch (error) {\n          const message = String((error as Error).message || error);\n          await autoFixStore.markFailed(job.id, message, {\n            failedAt: new Date().toISOString()\n          });\n          logger.error(`Failed ${job.id}: ${message}`);\n        }\n\n        processed += 1;\n        if (once || (maxJobs > 0 && processed >= maxJobs)) break;\n      }\n      logger.info(`AutoFix worker exiting (${workerId}). Jobs processed: ${processed}`);\n    });\n\n  program\n    .command('repl')\n    .description('Start interactive REPL mode for continuous conversations')\n    .option('-p, --project <path>', 'Project directory', process.cwd())\n    .option('-m, --mode <mode>', 'Initial REPL mode (manual|assist|autopilot)', 'manual')\n    .option('--interface-mode <mode>', 'Initial interface mode (standalone|connected)')\n    .option('--pick-interface', 'Show connected/standalone picker on REPL launch', false)\n    .option('--strict-preflight', 'Block launch if doctor checks fail', false)\n    .option('-g, --gateway <url>', 'Gateway URL for strict preflight checks')\n    .action(async (options) => {\n      const projectDir = options.project || process.cwd();\n      const initialMode = options.mode?.toLowerCase();\n      if (initialMode && !['manual', 'assist', 'autopilot'].includes(initialMode)) {\n        console.error(chalk.red(`Invalid mode \"${initialMode}\". Must be one of: manual, assist, autopilot`));\n        process.exit(1);\n      }\n      const interfaceMode = String(options.interfaceMode || '').toLowerCase();\n      if (interfaceMode && !['standalone', 'connected'].includes(interfaceMode)) {\n        console.error(chalk.red(`Invalid interface mode \"${interfaceMode}\". Must be one of: standalone, connected`));\n        process.exit(1);\n      }\n      try {\n        const policy = getExecutionPolicy({ strictPreflight: Boolean(options.strictPreflight) });\n        await enforceStrictPreflight(policy, options.gateway);\n        await startRepl({\n          router: agentRouter,\n          orchestrator,\n          sandbox,\n          session: sessionManager,\n          logger,\n          projectDir,\n          repoConfig,\n          initialMode: initialMode as 'manual' | 'assist' | 'autopilot' | undefined,\n          initialInterfaceMode: (interfaceMode || undefined) as 'standalone' | 'connected' | undefined,\n          promptInterfaceMode: Boolean(options.pickInterface) || (!interfaceMode && process.stdin.isTTY)\n        });\n      } catch (error) {\n        console.error('Error starting REPL:', error);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('tui')\n    .description('Start terminal UI mode (same runtime/controller as REPL, improved layout)')\n    .option('-p, --project <path>', 'Project directory', process.cwd())\n    .option('-m, --mode <mode>', 'Initial TUI mode (manual|assist|autopilot)', 'manual')\n    .option('--strict-preflight', 'Block launch if doctor checks fail', false)\n    .option('-g, --gateway <url>', 'Gateway URL for strict preflight checks')\n    .action(async (options) => {\n      const projectDir = options.project || process.cwd();\n      const initialMode = options.mode?.toLowerCase();\n      if (initialMode && !['manual', 'assist', 'autopilot'].includes(initialMode)) {\n        console.error(chalk.red(`Invalid mode \"${initialMode}\". Must be one of: manual, assist, autopilot`));\n        process.exit(1);\n      }\n      try {\n        const policy = getExecutionPolicy({ strictPreflight: Boolean(options.strictPreflight) });\n        await enforceStrictPreflight(policy, options.gateway);\n        await startTui({\n          router: agentRouter,\n          orchestrator,\n          sandbox,\n          session: sessionManager,\n          logger,\n          projectDir,\n          repoConfig,\n          initialMode: initialMode as 'manual' | 'assist' | 'autopilot' | undefined\n        });\n      } catch (error) {\n        console.error('Error starting TUI:', error);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('dispatch')\n    .description('Dispatch a task to an agent')\n    .argument('<agent>', 'Agent name')\n    .argument('<task>', 'Task description')\n    .option('-p, --project <path>', 'Project directory')\n    .option('-g, --gateway <url>', 'Override gateway URL')\n    .option('-t, --timeout <ms>', 'Timeout in milliseconds', '30000')\n    .option('-m, --model <id>', 'Model ID for cost estimate', executorPrimary || 'openai/gpt-4o-mini')\n    .option('--fallback-model <id>', 'Fallback model chain entry (repeatable)', collectOption, [])\n    .option('--engine <id>', 'Engine override for direct/bypass gateway paths (e.g. cursor)')\n    .option('--direct', 'Request direct execution path on gateway', false)\n    .option('--bypass', 'Request bypass/orchestrator-skip path on gateway', false)\n    .option('--output-tokens <count>', 'Expected completion tokens for estimate', '1200')\n    .option('--max-cost <usd>', 'Require confirmation if estimate exceeds this USD amount', String(executorPolicy.maxCostUsd ?? 1))\n    .option('--skip-cost-check', 'Skip cost estimate confirmation gate', false)\n    .option('--cross-repo', 'Inject sibling repository context', false)\n    .option('--cache', 'Enable output cache for dispatch result', false)\n    .option('--cache-ttl <sec>', 'Output cache TTL in seconds', '1800')\n    .option('--no-memory', 'Disable shared AgentKeeper memory')\n    .option('--memory-max <n>', 'Max recalled memory entries', String(cliDefaults.memoryMax ?? 3))\n    .option('--memory-require-validation', 'Store memory only when validation is marked passed', false)\n    .option('--image <path>', 'Attach an image file to the task (repeatable)', collectOption, [])\n    .option('--context-image <path>', 'Attach an image file as context (repeatable)', collectOption, [])\n    .option('--image-max-bytes <n>', 'Max bytes per image context payload', '250000')\n    .option('--context-file <path>', 'Attach a file as additional context (repeatable)', collectOption, [])\n    .option('--context-repo <path>', 'Attach git context from another repo (repeatable)', collectOption, [])\n    .option('--stdin', 'Read additional context from stdin', false)\n    .option('--max-context-tokens <n>', 'Max context token budget (approx, chars/4)')\n    .option('--context-budget-mode <mode>', 'trim | stop when budget exceeded', 'trim')\n    .option('--docs', 'Inject matching docs context via collections search', false)\n    .option('--docs-path <paths...>', 'Custom paths for docs search (default: docs/ + project root)')\n    .option('--docs-code', 'Include source code files in docs retrieval index', Boolean(cliDefaults.docsCode))\n    .option('--escalate-risk', 'Escalate high-risk patches to QA and Security', false)\n    .option('--risk-threshold <level>', 'Escalation threshold: low|medium|high', 'high')\n    .option('--retry-attempts <n>', 'Retry attempts for transient failures', '2')\n    .option('--strict-preflight', 'Block execution if doctor checks fail', false)\n    .option('--json', 'Output machine-readable JSON envelope', false)\n    .action(async (agent, task, options) => {\n      let finalTask = task;\n      const runId = `dispatch-${randomUUID()}`;\n      const fallbackModels = (options.fallbackModel && options.fallbackModel.length > 0)\n        ? options.fallbackModel\n        : (executorPolicy.fallback || []);\n      try {\n        const policy = getExecutionPolicy({\n          strictPreflight: Boolean(options.strictPreflight),\n          retryAttempts: Number.parseInt(options.retryAttempts || '2', 10),\n          riskThreshold: String(options.riskThreshold || 'high').toLowerCase() as RiskLevel\n        });\n        await enforceStrictPreflight(policy, options.gateway);\n        await checkpoints.beginRun({ runId, mode: 'dispatch', task });\n        const useMemory = options.memory !== false;\n        if (useMemory) {\n          const pathHints = (options.contextFile || []).map((p: string) => String(p).trim()).filter(Boolean);\n          const matches = await agentKeeper.recall(finalTask, Number.parseInt(options.memoryMax || '3', 10), {\n            preferSuccessful: true,\n            pathHints\n          });\n          const avgScore = matches.length\n            ? matches.reduce((sum, m) => sum + Number(m.score || 0), 0) / matches.length\n            : 0;\n          await sessionManager.trackMemoryRecall({\n            used: true,\n            miss: matches.length === 0,\n            matchCount: matches.length,\n            qualityScore: avgScore\n          });\n          if (matches.length > 0) {\n            const memoryContext = await agentKeeper.recallAsContext(finalTask, Number.parseInt(options.memoryMax || '3', 10), {\n              preferSuccessful: true,\n              pathHints\n            });\n            finalTask = `${finalTask}\\n\\n${memoryContext}`;\n          }\n        }\n        const fileBlock = await buildFileContextBlock(options.contextFile || []);\n        const repoBlock = await buildRepoContextBlock(options.contextRepo || []);\n        const imagePaths = [...(options.image || []), ...(options.contextImage || [])];\n        const imageBlock = await buildImageContextBlock(\n          imagePaths,\n          Number.parseInt(options.imageMaxBytes || '250000', 10)\n        );\n        const stdinText = options.stdin ? await readStdinText() : '';\n        const stdinBlock = stdinText ? `## Stdin Context\\n\\`\\`\\`text\\n${stdinText}\\n\\`\\`\\`` : '';\n\n        let docsBlock = '';\n        if (options.docs) {\n          const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n          const docsPaths = options.docsPath && options.docsPath.length > 0\n            ? options.docsPath\n            : [join(process.cwd(), 'docs'), process.cwd()];\n          const index = await buildCollectionIndex(docsPaths, {\n            includeCode: Boolean(options.docsCode)\n          });\n          const result = searchCollection(index, task, 5);\n          if (result.hits.length > 0) {\n            const chunks = result.hits.map(h => `### ${h.source}:${h.startLine} (score: ${h.score})\\n${h.text}`);\n            docsBlock = `## Docs Context (auto-retrieved)\\n${chunks.join('\\n\\n')}`;\n          }\n        }\n\n        const budget = enforceContextBudget(\n          finalTask,\n          [fileBlock, repoBlock, imageBlock, stdinBlock, docsBlock],\n          options.maxContextTokens ? Number.parseInt(options.maxContextTokens, 10) : undefined,\n          options.contextBudgetMode === 'stop' ? 'stop' : 'trim'\n        );\n        if (budget.exceeded) {\n          throw new Error(`Context budget exceeded (~${budget.estimatedTokens} tokens > ${options.maxContextTokens}). Use --context-budget-mode trim or raise budget.`);\n        }\n        if (budget.trimmed) {\n          logger.warn(`Context trimmed to stay under budget (~${budget.estimatedTokens} tokens).`);\n        }\n        finalTask = budget.task;\n\n        if (options.crossRepo) {\n          const multiContext = await collectMultiRepoContext(options.project || process.cwd());\n          finalTask = `${finalTask}\\n\\n${multiContext}`;\n        }\n\n        const sessionId = await sessionManager.getSessionId();\n        const projectDir = options.project || process.cwd();\n        const outputTokens = Number.parseInt(options.outputTokens || '1200', 10);\n        const maxCost = Number.parseFloat(options.maxCost || '1');\n        const estimate = estimateCost(finalTask, options.model, outputTokens);\n        const cheapest = getCheapestAlternative(finalTask, outputTokens);\n\n        logger.info(\n          `Estimated cost (${estimate.model}): $${estimate.totalUsd.toFixed(4)} ` +\n          `(in:${estimate.inputTokens} tok, out:${estimate.outputTokens} tok)`\n        );\n\n        if (cheapest.model !== estimate.model) {\n          logger.info(\n            `Cheaper alternative: ${cheapest.model} ($${cheapest.totalUsd.toFixed(4)})`\n          );\n        }\n\n        if (!options.skipCostCheck && estimate.totalUsd > maxCost) {\n          const { confirm } = await (await import('inquirer')).default.prompt([{\n            type: 'confirm',\n            name: 'confirm',\n            message: `Estimated cost $${estimate.totalUsd.toFixed(4)} exceeds limit $${maxCost.toFixed(2)}. Continue?`,\n            default: false\n          }]);\n\n          if (!confirm) {\n            logger.warn('Dispatch cancelled by cost guard.');\n            return;\n          }\n        }\n\n        const dispatchOptions = {\n          ...options,\n          project: projectDir,\n          sessionId,\n          images: options.image || []\n        };\n\n        await sessionManager.appendHistory({\n          type: 'dispatch_request',\n          agent,\n          task: finalTask,\n          projectDir\n        });\n\n        logger.info(`Dispatching task to ${agent}: ${finalTask}`);\n        let result: Record<string, unknown> | undefined;\n        if (options.cache) {\n          const cacheKey = TokenCache.hashKey(JSON.stringify({\n            kind: 'dispatch-output',\n            agent,\n            task: finalTask,\n            projectDir,\n            gateway: options.gateway || '',\n            model: options.model || '',\n            engine: options.engine || '',\n            direct: Boolean(options.direct),\n            bypass: Boolean(options.bypass)\n          }));\n          const cached = await tokenCache.get<Record<string, unknown>>('output', cacheKey);\n          if (cached.hit && cached.value) {\n            logger.info('Using cached dispatch output.');\n            result = cached.value;\n            await sessionManager.trackCacheSavings({\n              hit: true,\n              tokensSaved: Number(cached.meta?.tokensSaved || 0),\n              usdSaved: Number(cached.meta?.usdSaved || 0)\n            });\n          } else {\n            await sessionManager.trackCacheSavings({ miss: true });\n            const dispatched = await dispatchWithFallback(\n              agentRouter,\n              agent,\n              finalTask,\n              dispatchOptions,\n              fallbackModels,\n              checkpoints,\n              runId\n            );\n            result = dispatched.result;\n            await tokenCache.set(\n              'output',\n              cacheKey,\n              result,\n              Number.parseInt(options.cacheTtl || '1800', 10),\n              {\n                tokensSaved: estimate.inputTokens + estimate.outputTokens,\n                usdSaved: estimate.totalUsd,\n                source: 'dispatch-output'\n              }\n            );\n          }\n        } else {\n          const dispatched = await withRetries(\n            async () => dispatchWithFallback(\n              agentRouter,\n              agent,\n              finalTask,\n              dispatchOptions,\n              fallbackModels,\n              checkpoints,\n              runId\n            ),\n            policy,\n            { shouldRetry: shouldRetryWithFallback }\n          );\n          result = dispatched.result;\n        }\n\n        await sessionManager.appendHistory({\n          type: 'dispatch_result',\n          agent,\n          taskId: result.taskId || null,\n          success: Boolean(result.success),\n          result: result.result\n        });\n        if (useMemory) {\n          const response = String(result.result || '').trim();\n          const validation = extractValidationSignals(result, Boolean(options.memoryRequireValidation));\n          if (Boolean(result.success) && response.length > 0 && validation.passed) {\n            const saved = await agentKeeper.recordSafe({\n              runId,\n              tier: 'orchestrator',\n              task,\n              result: response,\n              agent,\n              structured: {\n                problem: task,\n                validation: {\n                  lintPassed: validation.lintPassed,\n                  testsPassed: validation.testsPassed,\n                  notes: validation.notes\n                },\n                outcome: 'success'\n              },\n              metadata: {\n                taskId: result.taskId || null,\n                success: true,\n                validationRequired: validation.required,\n                validationPassed: validation.passed\n              }\n            });\n            if (!saved.ok) {\n              logger.warn(`Memory write skipped: ${saved.error}`);\n            }\n          }\n        }\n        await sessionManager.appendRouting({\n          route: 'DISPATCH',\n          model: result.model || 'unknown',\n          agent,\n          taskId: result.taskId || null\n        });\n        await sessionManager.trackCost({\n          model: result.model || estimate.model || 'unknown',\n          usd: result.costUsd || estimate.totalUsd || 0,\n          promptTokens: result.promptTokens || estimate.inputTokens || 0,\n          completionTokens: result.completionTokens || estimate.outputTokens || 0\n        });\n\n        const responseText = String(result.result || '');\n        const edits = await orchestrator.parseAndApplyToSandbox(responseText);\n        const capabilityHandshake = getCapabilityHandshake('standalone');\n        await checkpoints.append(runId, 'dispatch.completed', {\n          agent,\n          success: Boolean(result.success),\n          edits: edits.length\n        });\n        let riskReport: Record<string, unknown> | null = null;\n        let patchRisk: Record<string, unknown> | null = null;\n        if (edits.length > 0) {\n          riskReport = await analyzeBlastRadius(process.cwd(), { changedFiles: edits });\n          patchRisk = scorePatchRisk({\n            blastRadius: riskReport,\n            changedFiles: edits.length\n          });\n          logger.info(`Patch confidence: ${(patchRisk.confidence * 100).toFixed(0)}% (risk score ${patchRisk.riskScore}/100, ${patchRisk.riskLevel})`);\n          if (options.escalateRisk && isSeverityAtLeast(patchRisk.riskLevel, String(options.riskThreshold || 'high').toLowerCase() as RiskLevel)) {\n            const escalationTask = `High-risk patch review requested.\\nRisk score: ${patchRisk.riskScore}/100 (${patchRisk.riskLevel}).\\nFiles: ${edits.join(', ')}.\\nPlease review for correctness, regressions, and security concerns.`;\n            const qa = await dispatchWithFallback(agentRouter, 'crew-qa', escalationTask, {\n              project: projectDir,\n              sessionId,\n              gateway: options.gateway\n            }, fallbackModels, checkpoints, runId);\n            const sec = await dispatchWithFallback(agentRouter, 'crew-security', escalationTask, {\n              project: projectDir,\n              sessionId,\n              gateway: options.gateway\n            }, fallbackModels, checkpoints, runId);\n            logger.info(chalk.yellow('\\n--- QA Escalation ---'));\n            logger.printWithHighlight(String(qa.result.result || ''));\n            logger.info(chalk.yellow('\\n--- Security Escalation ---'));\n            logger.printWithHighlight(String(sec.result.result || ''));\n          }\n        }\n\n        if (options.json) {\n          printJsonEnvelope('dispatch.result', {\n            runId,\n            agent,\n            taskId: result.taskId || null,\n            success: Boolean(result.success),\n            response: responseText,\n            edits,\n            needsApproval: edits.length > 0,\n            risk: patchRisk || null,\n            blastRadius: riskReport || null,\n            capabilityHandshake\n          });\n          await checkpoints.finish(runId, 'completed');\n          return;\n        }\n\n        logger.success('Task completed:', result);\n        await checkpoints.finish(runId, 'completed');\n      } catch (error) {\n        await sessionManager.appendHistory({\n          type: 'dispatch_error',\n          agent,\n          task: finalTask,\n          error: error.message\n        });\n        await checkpoints.append(runId, 'dispatch.error', { error: error.message });\n        await checkpoints.finish(runId, 'failed');\n        logger.error('Dispatch failed:', error.message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('status')\n    .description('Show crewswarm orchestration status dashboard')\n    .action(async () => {\n      const { displayStatus } = await import('../status/dashboard.ts');\n      await displayStatus();\n    });\n\n  program\n    .command('capabilities')\n    .description('Show runtime capability handshake for current interface mode')\n    .option('--json', 'Output as JSON', false)\n    .action(options => {\n      // crew-CLI is always standalone - no connected mode\n      const mode = 'standalone';\n      const handshake = getCapabilityHandshake(mode);\n      if (options.json) {\n        printJsonEnvelope('capabilities', { handshake });\n        return;\n      }\n      console.log(chalk.blue('\\n--- Capability Handshake ---\\n'));\n      console.log(`  mode        : ${handshake.mode}`);\n      console.log(`  can_read    : ${handshake.can_read}`);\n      console.log(`  can_write   : ${handshake.can_write}`);\n      console.log(`  can_pty     : ${handshake.can_pty}`);\n      console.log(`  can_lsp     : ${handshake.can_lsp}`);\n      console.log(`  can_dispatch: ${handshake.can_dispatch}`);\n      console.log(`  can_git     : ${handshake.can_git}`);\n    });\n\n  program\n    .command('run')\n    .description('Execute unified pipeline task (supports phase-aware resume from trace checkpoint)')\n    .option('-t, --task <text>', 'Task text for a new run')\n    .option('--resume <traceId>', 'Resume/replay a prior pipeline trace id')\n    .option('--from-phase <phase>', 'Resume from phase: plan|execute|validate')\n    .option('--retry-attempts <n>', 'Retry attempts for transient failures', '2')\n    .option('--strict-preflight', 'Block execution if doctor checks fail', false)\n    .option('-g, --gateway <url>', 'Gateway URL for strict preflight checks')\n    .option('--json', 'Output machine-readable JSON envelope', false)\n    .action(async options => {\n      try {\n        const policy = getExecutionPolicy({\n          strictPreflight: Boolean(options.strictPreflight),\n          retryAttempts: Number.parseInt(options.retryAttempts || '2', 10)\n        });\n        await enforceStrictPreflight(policy, options.gateway);\n\n        let task = String(options.task || '').trim();\n        let resumedFrom: string | null = null;\n        let previousPhase: string | null = null;\n        let resumeContext: { priorPlan?: unknown; priorResponse?: string; priorExecutionResults?: unknown } | undefined = undefined;\n\n        if (options.resume) {\n          const traceId = String(options.resume).trim();\n          const events = await loadPipelineRunEvents(traceId, process.cwd());\n          const resumeInfo = inferResumeTask(events);\n          if (!resumeInfo) {\n            throw new Error(`Unable to infer task from trace ${traceId}.`);\n          }\n          task = task || resumeInfo.task;\n          resumedFrom = traceId;\n          previousPhase = resumeInfo.phase;\n          const requestedPhase = String(options.fromPhase || '').toLowerCase();\n          const fromPhase = requestedPhase || (previousPhase === 'failed' ? 'execute' : 'plan');\n          if (!['plan', 'execute', 'validate'].includes(fromPhase)) {\n            throw new Error(`Invalid --from-phase \"${fromPhase}\". Use plan|execute|validate.`);\n          }\n          const artifacts = extractResumeArtifacts(events);\n          if (fromPhase === 'execute' || fromPhase === 'validate') {\n            if (!artifacts.priorPlan) {\n              throw new Error(`Trace ${traceId} missing prior plan artifact; cannot resume from ${fromPhase}.`);\n            }\n          }\n          if (fromPhase === 'validate' && !artifacts.priorResponse) {\n            throw new Error(`Trace ${traceId} missing prior validation input; cannot resume from validate.`);\n          }\n          resumeContext = {\n            fromPhase,\n            priorPlan: artifacts.priorPlan,\n            priorResponse: artifacts.priorResponse,\n            priorExecutionResults: artifacts.priorExecutionResults\n          };\n\n          if (previousPhase === 'complete' && fromPhase === 'plan') {\n            if (options.json) {\n              printJsonEnvelope('run.resume', {\n                resumedFrom,\n                previousPhase,\n                task,\n                skipped: true,\n                reason: 'already-complete'\n              });\n              return;\n            }\n            logger.info(`Trace ${traceId} already completed. Re-running task for deterministic replay.`);\n          }\n        }\n\n        if (!task) {\n          throw new Error('Provide --task for a new run or --resume <traceId> for replay.');\n        }\n\n        const sessionId = await sessionManager.getSessionId();\n        const result = await withRetries(\n          async () => orchestrator.executePipeline(task, '', sessionId, resumeContext),\n          policy\n        );\n        const responseText = String(result.response || result.result || '');\n        const edits = await orchestrator.parseAndApplyToSandbox(responseText);\n        const capabilityHandshake = getCapabilityHandshake(\n          String(process.env.CREW_INTERFACE_MODE || 'standalone').toLowerCase() === 'connected'\n            ? 'connected'\n            : 'standalone'\n        );\n\n        if (options.json) {\n          printJsonEnvelope('run.result', {\n            task,\n            resumedFrom,\n            previousPhase,\n            resumedPhase: resumeContext?.fromPhase || null,\n            traceId: result.traceId || null,\n            phase: result.phase || null,\n            decision: result.plan?.decision || null,\n            executionPath: Array.isArray(result.executionPath) ? result.executionPath : [],\n            timeline: Array.isArray(result.timeline) ? result.timeline : [],\n            response: responseText,\n            edits,\n            needsApproval: edits.length > 0,\n            capabilityHandshake,\n            // Benchmark telemetry\n            totalCost: result.totalCost || 0,\n            turns: result.executionResults?.results?.reduce((s: number, r: Record<string, unknown>) => s + (Number(r.turns) || 0), 0) || 0,\n            toolsUsed: [...new Set((result.executionResults?.results || []).flatMap((r: Record<string, unknown>) => (r.toolsUsed as string[]) || []))],\n            modelUsed: result.executionResults?.results?.[0]?.modelUsed || null,\n          });\n          return;\n        }\n\n        logger.printWithHighlight(responseText);\n        if (Array.isArray(result.timeline) && result.timeline.length > 0) {\n          console.log(chalk.gray('\\nPipeline timeline:'));\n          for (const step of result.timeline) {\n            console.log(chalk.gray(`  - ${step.phase} @ ${step.ts}`));\n          }\n        }\n        if (edits.length > 0) {\n          logger.success(`Staged ${edits.length} file change(s). Run \"crew preview\" then \"crew apply\".`);\n        }\n      } catch (error) {\n        logger.error(`Run failed: ${(error as Error).message}`);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('map')\n    .description('Generate a repository structure graph respecting .gitignore')\n    .option('--graph', 'Emit dependency graph instead of tree output', false)\n    .option('--visualize', 'Generate interactive HTML graph (implies --graph)', false)\n    .option('--out <path>', 'Output path for --visualize HTML', join(process.cwd(), '.crew', 'repo-graph.html'))\n    .option('--json', 'Emit graph as JSON', false)\n    .option('--max-nodes <n>', 'Limit graph nodes in text mode', '200')\n    .action(async (options) => {\n      const {\n        buildRepositoryGraph,\n        buildRepositoryMap,\n        buildRepositoryGraphDot,\n        buildRepositoryGraphHtml\n      } = await import('../mapping/index.js');\n      try {\n        if (options.graph || options.visualize) {\n          const graph = await buildRepositoryGraph(process.cwd());\n          if (options.visualize) {\n            const htmlPath = String(options.out || join(process.cwd(), '.crew', 'repo-graph.html'));\n            await mkdir(dirname(htmlPath), { recursive: true });\n            const html = buildRepositoryGraphHtml(graph);\n            await writeFile(htmlPath, html, 'utf8');\n            const dotPath = `${htmlPath}.dot`;\n            await writeFile(dotPath, buildRepositoryGraphDot(graph), 'utf8');\n            logger.success(`Wrote graph visualization: ${htmlPath}`);\n            logger.info(`Wrote Graphviz DOT: ${dotPath}`);\n            return;\n          }\n          if (options.json) {\n            console.log(JSON.stringify(graph, null, 2));\n            return;\n          }\n          const maxNodes = Number.parseInt(options.maxNodes || '200', 10);\n          console.log(chalk.blue('--- Repository Dependency Graph ---'));\n          console.log(`Root: ${graph.root}`);\n          console.log(`Nodes: ${graph.nodeCount}`);\n          console.log(`Edges: ${graph.edgeCount}`);\n          const shown = graph.nodes.slice(0, Math.max(1, maxNodes));\n          for (const node of shown) {\n            const imports = node.imports.length ? node.imports.join(', ') : '(none)';\n            const importedBy = node.importedBy.length ? node.importedBy.join(', ') : '(none)';\n            console.log(`\\n- ${node.path}`);\n            console.log(`  imports: ${imports}`);\n            console.log(`  importedBy: ${importedBy}`);\n          }\n          if (graph.nodes.length > shown.length) {\n            console.log(`\\n... ${graph.nodes.length - shown.length} more nodes omitted`);\n          }\n          return;\n        }\n\n        const map = await buildRepositoryMap(process.cwd());\n        console.log(chalk.blue('--- Repository Tree Map ---'));\n        console.log(map);\n      } catch (err) {\n        logger.error(`Failed to generate map: ${(err as Error).message}`);\n        process.exit(1);\n      }\n    });\n\n  const lsp = program\n    .command('lsp')\n    .description('Language-server style utilities (typecheck, completions)');\n\n  lsp\n    .command('check')\n    .description('Run TypeScript diagnostics for the current project')\n    .argument('[files...]', 'Optional relative files to filter diagnostics')\n    .option('--json', 'Emit JSON', false)\n    .action(async (files, options) => {\n      try {\n        const { typeCheckProject } = await import('../lsp/index.js');\n        const diagnostics = typeCheckProject(process.cwd(), files || []);\n        if (options.json) {\n          console.log(JSON.stringify({ count: diagnostics.length, diagnostics }, null, 2));\n          return;\n        }\n        if (diagnostics.length === 0) {\n          logger.success('No LSP diagnostics found.');\n          return;\n        }\n        console.log(chalk.yellow(`Found ${diagnostics.length} diagnostic(s):`));\n        for (const diag of diagnostics) {\n          console.log(`${diag.category.toUpperCase()} ${diag.code} ${diag.file}:${diag.line}:${diag.column}`);\n          console.log(`  ${diag.message}`);\n        }\n        process.exit(1);\n      } catch (error) {\n        logger.error(`LSP check failed: ${(error as Error).message}`);\n        process.exit(1);\n      }\n    });\n\n  lsp\n    .command('complete')\n    .description('Get code completions at a cursor position')\n    .argument('<file>', 'Relative or absolute path to source file')\n    .argument('<line>', '1-based line number')\n    .argument('<column>', '1-based column number')\n    .option('--prefix <text>', 'Filter completions by prefix', '')\n    .option('--limit <n>', 'Max completion count', '50')\n    .option('--json', 'Emit JSON', false)\n    .action(async (file, line, column, options) => {\n      try {\n        const { getCompletions } = await import('../lsp/index.js');\n        const completions = getCompletions(\n          process.cwd(),\n          file,\n          Number.parseInt(line, 10),\n          Number.parseInt(column, 10),\n          Number.parseInt(options.limit || '50', 10),\n          String(options.prefix || '')\n        );\n        if (options.json) {\n          console.log(JSON.stringify({ count: completions.length, completions }, null, 2));\n          return;\n        }\n        if (completions.length === 0) {\n          logger.warn('No completions found.');\n          return;\n        }\n        console.log(chalk.blue(`Completions (${completions.length}):`));\n        completions.forEach(item => {\n          console.log(`- ${item.name} (${item.kind})`);\n        });\n      } catch (error) {\n        logger.error(`LSP completion failed: ${(error as Error).message}`);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('pty')\n    .description('Run an interactive command in a pseudo-terminal')\n    .argument('<command...>', 'Command to execute in PTY')\n    .option('-p, --project <path>', 'Working directory', process.cwd())\n    .option('--timeout <ms>', 'Timeout in milliseconds (0 disables)', '0')\n    .action(async (commandArray, options) => {\n      const command = commandArray.join(' ');\n      try {\n        const { runPtyCommand } = await import('../pty/index.js');\n        const result = await runPtyCommand(command, {\n          cwd: options.project || process.cwd(),\n          timeoutMs: Number.parseInt(options.timeout || '0', 10)\n        });\n        if (!result.success) {\n          process.exit(result.exitCode === 0 ? 1 : result.exitCode);\n        }\n      } catch (error) {\n        logger.error(`PTY command failed: ${(error as Error).message}`);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('shell')\n    .description('Translate natural language into a shell command and execute it (GitHub Copilot CLI style)')\n    .argument('<request...>', 'Natural language request (e.g. \"list files sorted by size\")')\n    .option('-m, --model <id>', 'Model override for shell command generation')\n    .action(async (requestArray, options) => {\n      const { runShellCopilot } = await import('../shell/index.js');\n      await runShellCopilot(requestArray.join(' '), agentRouter, {\n        projectDir: process.cwd(),\n        model: options.model\n      });\n    });\n\n  program\n    .command('exec')\n    .description('Run a one-shot task or interactive terminal command with PTY support')\n    .argument('<command>', 'Command to run')\n    .argument('[args...]', 'Arguments for the command')\n    .option('-m, --model <id>', 'Model override for one-shot task fallback')\n    .option('--json', 'Output machine-readable JSON envelope for one-shot task fallback', false)\n    .action(async (command, args, options) => {\n      const looksLikeNaturalLanguage =\n        args.length === 0 &&\n        typeof command === 'string' &&\n        /\\s/.test(command.trim());\n\n      if (looksLikeNaturalLanguage) {\n        logger.info('Interpreting `crew exec` input as a one-shot task. Use `crew exec <cmd> [args...]` for PTY commands.');\n        try {\n          const standaloneRuntime = await getStandaloneRuntime(process.cwd());\n          const result = await standaloneRuntime.orchestrator.executeAgentic(command, {\n            sessionId: await standaloneRuntime.sessionManager.getSessionId(),\n            model: options.model\n          });\n          const responseText = String(result.response || result.result || '');\n          const edits = await standaloneRuntime.orchestrator.parseAndApplyToSandbox(responseText);\n          await standaloneRuntime.sessionManager.appendHistory({\n            input: command,\n            response: responseText,\n            decision: result.plan?.decision || 'execute',\n            agent: 'unified-pipeline',\n            model: String(result.plan?.validation?.modelUsed || options.model || 'unknown'),\n            costUsd: result.totalCost\n          });\n          if (options.json) {\n            printJsonEnvelope('exec.result', {\n              route: result.plan\n                ? {\n                    decision: result.plan.decision.toUpperCase(),\n                    explanation: result.plan.reasoning\n                  }\n                : { decision: 'EXECUTE', explanation: 'Direct L3 execution' },\n              agent: 'unified-pipeline',\n              response: responseText,\n              edits,\n              needsApproval: edits.length > 0,\n              traceId: result.traceId,\n              timeline: result.timeline\n            });\n            return;\n          }\n          console.log(responseText);\n          if (edits.length > 0) {\n            logger.success(`Added changes to ${edits.length} files in sandbox. Run \"crew preview\" to review.`);\n          }\n          return;\n        } catch (err) {\n          logger.error(`One-shot task failed: ${(err as Error).message}`);\n          process.exit(1);\n        }\n      }\n\n      // Unified: use src/pty implementation (has fallback logic)\n      const { runPtyCommand } = await import('../pty/index.js');\n      try {\n        const fullCommand = [command, ...args].join(' ');\n        const result = await runPtyCommand(fullCommand);\n        process.exit(result.exitCode);\n      } catch (err) {\n        logger.error(`Interactive command failed: ${(err as Error).message}`);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('lsp-check')\n    .description('Run LSP type checking on a file')\n    .argument('<file>', 'File to check')\n    .action(async (file) => {\n      const { LspService } = await import('../lsp/index.js');\n      const service = new LspService(process.cwd());\n      const diagnostics = service.getDiagnostics(file);\n      \n      if (diagnostics.length === 0) {\n        logger.success('No type errors found.');\n      } else {\n        console.log(chalk.red(`Found ${diagnostics.length} errors:`));\n        diagnostics.forEach(d => console.log(`- ${d}`));\n      }\n    });\n\n  program\n    .command('lsp-complete')\n    .description('Get LSP autocomplete suggestions at a specific position')\n    .argument('<file>', 'File path')\n    .argument('<line>', 'Line number (1-based)')\n    .argument('<char>', 'Character number (1-based)')\n    .action(async (file, lineStr, charStr) => {\n      const { LspService } = await import('../lsp/index.js');\n      const service = new LspService(process.cwd());\n      const line = parseInt(lineStr, 10);\n      const char = parseInt(charStr, 10);\n      const completions = service.getCompletions(file, line, char);\n      \n      if (completions.length === 0) {\n        logger.info('No completions found.');\n      } else {\n        console.log(chalk.blue(`--- Autocomplete (${completions.length}) ---`));\n        console.log(completions.slice(0, 50).join(', ') + (completions.length > 50 ? '...' : ''));\n      }\n    });\n\n  program\n    .command('explore')\n    .description('Speculative execution: run a task on 3 parallel branches with different strategies')\n    .argument('<task...>', 'Task to explore')\n    .option('-p, --project <path>', 'Project directory')\n    .option('-g, --gateway <url>', 'Override gateway URL')\n    .action(async (taskArray, options) => {\n      const task = taskArray.join(' ');\n      const projectDir = options.project || process.cwd();\n      const sessionId = await sessionManager.getSessionId();\n\n      logger.info(chalk.blue(`\\n\uD83D\uDD00 Exploring 3 approaches for: ${task}`));\n\n      const branches = [\n        { name: 'explore-minimal', prompt: `Implement this task with the MINIMAL possible changes. Be extremely concise and surgical: \"${task}\"` },\n        { name: 'explore-clean', prompt: `Implement this task following CLEAN ARCHITECTURE principles. Prioritize maintainability and best practices: \"${task}\"` },\n        { name: 'explore-pragmatic', prompt: `Implement this task with a PRAGMATIC approach. Balance speed and quality: \"${task}\"` }\n      ];\n\n      const originalBranch = sandbox.getActiveBranch();\n      const results: Array<{ branch: string; result: unknown }> = [];\n\n      // Run in parallel\n      await Promise.all(branches.map(async (b) => {\n        try {\n          logger.info(chalk.gray(`  Starting ${b.name}...`));\n          \n          // Create and switch to branch\n          try {\n            await sandbox.createBranch(b.name, originalBranch);\n          } catch {\n            await sandbox.switchBranch(b.name);\n            await sandbox.rollback(b.name);\n          }\n\n          const result = await agentRouter.dispatch('crew-coder', b.prompt, {\n            project: projectDir,\n            sessionId: `${sessionId}-${b.name}`,\n            gateway: options.gateway\n          });\n\n          const edits = await orchestrator.parseAndApplyToSandbox(String(result.result || ''));\n          \n          results.push({\n            name: b.name,\n            success: true,\n            edits: edits.length,\n            result: result.result\n          });\n\n          logger.success(`  \u2713 Completed ${b.name} (${edits.length} files)`);\n        } catch (err) {\n          logger.error(`  \u2717 ${b.name} failed: ${(err as Error).message}`);\n          results.push({ name: b.name, success: false, error: (err as Error).message });\n        }\n      }));\n\n      // Switch back to original branch\n      await sandbox.switchBranch(originalBranch);\n\n      console.log(chalk.blue('\\n--- Exploration Results ---'));\n      results.forEach(r => {\n        if (r.success) {\n          console.log(chalk.green(`  ${r.name}: ${r.edits} files modified`));\n        } else {\n          console.log(chalk.red(`  ${r.name}: Failed (${r.error})`));\n        }\n      });\n\n      const { choice } = await (import('inquirer')).then(m => m.default.prompt([{\n        type: 'list',\n        name: 'choice',\n        message: 'Which approach would you like to inspect or merge?',\n        choices: [\n          ...results.filter(r => r.success).map(r => r.name),\n          'none'\n        ]\n      }]));\n\n      if (choice !== 'none') {\n        await sandbox.switchBranch(choice);\n        logger.info(`Switched to branch: ${choice}. Use \"crew preview\" to review or \"crew merge ${choice} main\" to merge.`);\n      }\n    });\n\n  program\n    .command('repos-scan')\n    .description('Detect sibling git repositories')\n    .action(async () => {\n      const repos = await findSiblingRepos(process.cwd());\n      if (repos.length === 0) {\n        console.log(chalk.yellow('No sibling repositories found.'));\n        return;\n      }\n      console.log(chalk.blue('Sibling repos:'));\n      repos.forEach(path => console.log(`- ${path}`));\n    });\n\n  program\n    .command('repos-context')\n    .description('Show cross-repo context for sibling repositories')\n    .action(async () => {\n      const context = await collectMultiRepoContext(process.cwd());\n      console.log(context);\n    });\n\n  program\n    .command('repos-sync')\n    .description('Sync and store sibling repository snapshots to .crew/multi-repo-sync.json')\n    .action(async () => {\n      const outPath = await syncRepoSnapshots(process.cwd());\n      logger.success(`Wrote snapshot to ${outPath}`);\n    });\n\n  program\n    .command('repos-warn')\n    .description('Warn about potential cross-repo API breaking changes')\n    .action(async () => {\n      const repos = await findSiblingRepos(process.cwd());\n      if (repos.length === 0) {\n        console.log(chalk.yellow('No sibling repositories found.'));\n        return;\n      }\n\n      let hasWarnings = false;\n      for (const repo of repos) {\n        const summary = await getRepoSummary(repo);\n        const warnings = await detectBreakingApiSignals(repo);\n        if (warnings.length > 0) {\n          hasWarnings = true;\n          console.log(chalk.red(`\\n[${summary.name}]`));\n          warnings.forEach(w => console.log(`- ${w}`));\n        }\n      }\n\n      if (!hasWarnings) {\n        console.log(chalk.green('No obvious API-breaking signals detected in sibling repos.'));\n      }\n    });\n\n  program\n    .command('sync')\n    .description('Upload/download team context and merge team corrections')\n    .option('--upload', 'Upload local .crew session/corrections to team store')\n    .option('--download', 'Download shared team context into local .crew')\n    .option('--status', 'Show team sync status and privacy controls')\n    .action(async options => {\n      if (options.upload) {\n        const result = await uploadTeamContext(process.cwd());\n        logger.success(`Uploaded team context: ${result.sessionOut}, ${result.correctionsOut}`);\n      }\n      if (options.download) {\n        const result = await downloadTeamContext(process.cwd());\n        logger.success(`Downloaded/merged team context. Corrections entries: ${result.mergedCount}`);\n      }\n      if (options.status || (!options.upload && !options.download)) {\n        const status = await getTeamSyncStatus(process.cwd());\n        console.log(chalk.blue('--- Team Sync Status ---'));\n        console.log(`Dir: ${status.teamDir}`);\n        console.log(`Files: ${status.files.length}`);\n        console.log(`Privacy: ${JSON.stringify(status.privacy)}`);\n      }\n    });\n\n  const configCmd = program\n    .command('config')\n    .description('Manage repo-level configuration in .crew/config.json and .crew/config.local.json');\n\n  configCmd\n    .command('show')\n    .description('Show resolved/team/user repo configuration')\n    .option('--scope <scope>', 'resolved | team | user', 'resolved')\n    .option('--json', 'Output JSON', false)\n    .action(async (options) => {\n      const scope = String(options.scope || 'resolved').toLowerCase();\n      if (!['resolved', 'team', 'user'].includes(scope)) {\n        logger.error('Invalid scope. Use: resolved | team | user');\n        process.exit(1);\n      }\n      const value = scope === 'resolved'\n        ? await loadResolvedRepoConfig(process.cwd())\n        : await readRepoConfig(process.cwd(), scope as 'team' | 'user');\n      const redacted = redactRepoConfigForDisplay(value);\n      if (options.json) {\n        console.log(JSON.stringify(redacted, null, 2));\n        return;\n      }\n      console.log(chalk.blue(`--- Repo Config (${scope}) ---`));\n      console.log(JSON.stringify(redacted, null, 2));\n    });\n\n  configCmd\n    .command('get')\n    .description('Get a repo config value by dotted key path')\n    .argument('<key>', 'Dotted key path (e.g. cli.model)')\n    .option('--scope <scope>', 'resolved | team | user', 'resolved')\n    .option('--json', 'Output JSON', false)\n    .action(async (key, options) => {\n      const scope = String(options.scope || 'resolved').toLowerCase();\n      if (!['resolved', 'team', 'user'].includes(scope)) {\n        logger.error('Invalid scope. Use: resolved | team | user');\n        process.exit(1);\n      }\n      const source = scope === 'resolved'\n        ? await loadResolvedRepoConfig(process.cwd())\n        : await readRepoConfig(process.cwd(), scope as 'team' | 'user');\n      const value = getNestedValue(source as Record<string, unknown>, String(key));\n      if (value === undefined) {\n        logger.warn(`No value found for key \"${key}\" in ${scope} config.`);\n        process.exit(1);\n      }\n      const redacted = redactRepoConfigForDisplay(value);\n      if (options.json) {\n        console.log(JSON.stringify(redacted, null, 2));\n        return;\n      }\n      if (typeof redacted === 'object') {\n        console.log(JSON.stringify(redacted, null, 2));\n      } else {\n        console.log(String(redacted));\n      }\n    });\n\n  configCmd\n    .command('set')\n    .description('Set a repo config value by dotted key path')\n    .argument('<key>', 'Dotted key path (e.g. repl.autoApply)')\n    .argument('<value>', 'Value (string by default, or JSON with --json)')\n    .option('--scope <scope>', 'team | user', 'user')\n    .option('--json', 'Parse value as JSON', false)\n    .action(async (key, value, options) => {\n      const scope = String(options.scope || 'user').toLowerCase();\n      if (!['team', 'user'].includes(scope)) {\n        logger.error('Invalid scope for set. Use: team | user');\n        process.exit(1);\n      }\n      let parsedValue: unknown;\n      try {\n        parsedValue = parseConfigValue(String(value), Boolean(options.json));\n      } catch (error) {\n        logger.error(`Invalid value: ${(error as Error).message}`);\n        process.exit(1);\n      }\n      await setRepoConfigValue(process.cwd(), scope as 'team' | 'user', String(key), parsedValue);\n      logger.success(`Set ${scope}.${String(key)} = ${JSON.stringify(redactRepoConfigForDisplay(parsedValue))}`);\n    });\n\n  program\n    .command('github')\n    .description('Natural language GitHub issue/PR flows via gh CLI')\n    .argument('<request...>', 'Natural language request or \"doctor\"')\n    .option('--repo <owner/name>', 'Override GitHub repository (default: current git remote)')\n    .option('--limit <n>', 'Default list limit for list requests', '10')\n    .option('-y, --yes', 'Skip confirmation gate for mutating actions', false)\n    .option('--dry-run', 'Parse and print the exact gh command without executing', false)\n    .option('--json', 'Output raw gh JSON for list flows when available', false)\n    .action(async (requestArray, options) => {\n      const request = String((requestArray || []).join(' ') || '').trim();\n      if (request.toLowerCase() === 'doctor') {\n        const checks = await runGitHubDoctor(process.cwd(), options.repo);\n        let failed = false;\n        for (const check of checks) {\n          const marker = check.ok ? chalk.green('\u2713') : chalk.red('\u2717');\n          console.log(`${marker} ${check.name}: ${check.details}`);\n          if (!check.ok) failed = true;\n        }\n        if (failed) process.exit(1);\n        return;\n      }\n      const intent = parseGitHubIntent(request, {\n        defaultLimit: Number.parseInt(options.limit || '10', 10)\n      });\n      if (intent.kind === 'unknown') {\n        logger.error(intent.reason);\n        logger.info('Try examples:');\n        logger.info('  crew github \"list open issues limit 20\"');\n        logger.info('  crew github \"create issue \\\\\"Fix login bug\\\\\" body: repro steps...\"');\n        logger.info('  crew github \"update issue #42 close\"');\n        logger.info('  crew github \"create draft pr \\\\\"Refactor auth\\\\\" body: summary...\"');\n        process.exit(1);\n      }\n\n      logger.info(`Intent: ${describeIntent(intent)}`);\n      const ghArgs = buildGitHubCommand(intent, options.repo);\n      if (options.dryRun) {\n        console.log(chalk.blue('\\n--- GitHub Dry Run ---'));\n        console.log(`Intent: ${describeIntent(intent)}`);\n        console.log(`Command: ${commandToShell(ghArgs)}`);\n        return;\n      }\n      if (requiresConfirmation(intent) && !options.yes) {\n        const answer = await (await import('inquirer')).default.prompt([{\n          type: 'confirm',\n          name: 'confirm',\n          message: `Proceed with: ${describeIntent(intent)}?`,\n          default: false\n        }]);\n        if (!answer.confirm) {\n          logger.warn('Cancelled.');\n          return;\n        }\n      }\n\n      try {\n        const output = await executeGitHubIntent(intent, {\n          cwd: process.cwd(),\n          repo: options.repo\n        });\n        if (options.json || intent.kind === 'issue_create' || intent.kind === 'issue_update' || intent.kind === 'pr_draft') {\n          console.log(output);\n          return;\n        }\n        try {\n          const parsed = JSON.parse(output);\n          console.log(JSON.stringify(parsed, null, 2));\n        } catch {\n          console.log(output);\n        }\n      } catch (error) {\n        logger.error(`GitHub command failed: ${(error as Error).message}`);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('privacy')\n    .description('Configure privacy controls for team sync')\n    .option('--preset <name>', 'full | metadata | no-content')\n    .option('--share-prompt <bool>', 'true|false')\n    .option('--share-original <bool>', 'true|false')\n    .option('--share-corrected <bool>', 'true|false')\n    .option('--share-tags <bool>', 'true|false')\n    .action(async options => {\n      const current = await loadPrivacyControls(process.cwd());\n      const parseBool = (value: string | undefined, fallback: boolean) => {\n        if (value === undefined) return fallback;\n        return String(value).toLowerCase() === 'true';\n      };\n\n      let next = { ...current };\n      if (options.preset) {\n        const preset = String(options.preset).toLowerCase();\n        if (preset === 'full') {\n          next = { sharePrompt: true, shareOriginal: true, shareCorrected: true, shareTags: true };\n        } else if (preset === 'metadata') {\n          next = { sharePrompt: false, shareOriginal: false, shareCorrected: false, shareTags: true };\n        } else if (preset === 'no-content') {\n          next = { sharePrompt: false, shareOriginal: false, shareCorrected: false, shareTags: false };\n        }\n      }\n\n      next = {\n        sharePrompt: parseBool(options.sharePrompt, next.sharePrompt),\n        shareOriginal: parseBool(options.shareOriginal, next.shareOriginal),\n        shareCorrected: parseBool(options.shareCorrected, next.shareCorrected),\n        shareTags: parseBool(options.shareTags, next.shareTags)\n      };\n\n      await savePrivacyControls(next, process.cwd());\n      logger.success(`Saved privacy controls: ${JSON.stringify(next)}`);\n    });\n\n  program\n    .command('listen')\n    .description('Voice mode: record speech, transcribe via Whisper, run command, and optionally speak response')\n    .option('--duration-sec <n>', 'Recording duration in seconds', '6')\n    .option('--provider <id>', 'STT provider: auto | groq | openai | whisper-cli', 'auto')\n    .option('--text <value>', 'Skip recording and use raw text directly')\n    .option('--continuous', 'Keep listening in a loop', false)\n    .option('--max-rounds <n>', 'Maximum rounds in continuous mode', '5')\n    .option('--no-tts', 'Disable TTS response playback')\n    .option('--tts-skill <id>', 'crewswarm skill for TTS', 'elevenlabs.tts')\n    .action(async options => {\n      const durationSec = Number.parseInt(options.durationSec || '6', 10);\n      const maxRounds = Math.max(1, Number.parseInt(options.maxRounds || '5', 10));\n      let round = 0;\n\n      while (true) {\n        round += 1;\n        if (options.continuous) {\n          logger.progress(round - 1, maxRounds, 'Listen');\n        }\n\n        let userText = String(options.text || '').trim();\n        if (!userText) {\n          logger.info(`Listening for ${durationSec}s...`);\n          const audioPath = await recordAudio({ durationSec });\n          userText = await transcribeAudio(audioPath, {\n            provider: options.provider\n          });\n        }\n\n        if (!userText) {\n          logger.warn('No speech detected.');\n          if (!options.continuous || round >= maxRounds) break;\n          continue;\n        }\n\n        await appendVoiceTranscript(process.cwd(), 'user', userText);\n        logger.info(`Heard: ${userText}`);\n\n        const route = await orchestrator.route(userText);\n        const agent = route.agent || 'crew-main';\n        const response = await agentRouter.dispatch(agent, userText, {\n          sessionId: await sessionManager.getSessionId(),\n          project: process.cwd()\n        });\n\n        const responseText = String(response.result || '');\n        logger.printWithHighlight(responseText);\n        await appendVoiceTranscript(process.cwd(), 'assistant', responseText);\n\n        if (options.tts) {\n          try {\n            await speakWithSkill(agentRouter, responseText, options.ttsSkill || 'elevenlabs.tts');\n            logger.success(`Spoken via ${options.ttsSkill || 'elevenlabs.tts'}`);\n          } catch (ttsErr) {\n            logger.warn(`TTS failed: ${(ttsErr as Error).message}`);\n          }\n        }\n\n        if (!options.continuous || round >= maxRounds) {\n          if (options.continuous) {\n            logger.progress(maxRounds, maxRounds, 'Listen');\n          }\n          break;\n        }\n      }\n    });\n\n  program\n    .command('review')\n    .description('Analyze current git diff before commit and request a QA-style review')\n    .option('--agent <id>', 'Agent to run review with', 'crew-qa')\n    .option('--strict', 'Exit non-zero if review includes high-severity findings', false)\n    .action(async options => {\n      const review = await getReviewPayload(process.cwd());\n      if (!review.hasChanges) {\n        logger.warn('No staged/unstaged git diff detected.');\n        return;\n      }\n      logger.info(`Dispatching diff review to ${options.agent}`);\n      const result = await agentRouter.dispatch(options.agent, review.payload, {\n        sessionId: await sessionManager.getSessionId(),\n        project: process.cwd(),\n        injectGitContext: false\n      });\n      const text = String(result.result || '');\n      logger.printWithHighlight(text);\n      if (options.strict) {\n        const strict = detectHighSeverityFindings(text);\n        if (strict.hasHighSeverity) {\n          logger.error(`Strict review failed due to high-severity markers: ${strict.matches.join(', ')}`);\n          process.exit(1);\n        }\n      }\n    });\n\n  program\n    .command('context')\n    .description('Inspect current prompt/context footprint')\n    .option('-p, --project <path>', 'Project directory', process.cwd())\n    .action(async options => {\n      const project = options.project || process.cwd();\n      const gitContext = await getProjectContext(project);\n      const session = await sessionManager.loadSession();\n      const tokenEstimate = Math.ceil((gitContext.length + JSON.stringify(session.history).length) / 4);\n\n      console.log(chalk.blue('--- Context Report ---'));\n      console.log(`Project: ${project}`);\n      console.log(`Session entries: ${session.history.length}`);\n      console.log(`Git context chars: ${gitContext.length}`);\n      console.log(`Estimated tokens in active context: ~${tokenEstimate}`);\n    });\n\n  program\n    .command('compact')\n    .description('Compact local session/cost context windows to keep prompts lean')\n    .option('--history <n>', 'Keep last N history entries', '200')\n    .option('--cost <n>', 'Keep last N cost entries', '500')\n    .option('--write-summary', 'Write compact context summary file', true)\n    .action(async options => {\n      const result = await sessionManager.compact({\n        keepHistory: Number.parseInt(options.history || '200', 10),\n        keepCostEntries: Number.parseInt(options.cost || '500', 10)\n      });\n\n      if (options.writeSummary) {\n        const session = await sessionManager.loadSession();\n        const last = session.history.slice(-10);\n        const summary = [\n          '# Compact Context Summary',\n          '',\n          `Updated: ${new Date().toISOString()}`,\n          `History entries kept: ${session.history.length}`,\n          '',\n          '## Recent activity',\n          ...last.map((entry: Record<string, unknown>) => `- ${entry.timestamp} ${entry.type}${entry.agent ? ` (${entry.agent})` : ''}`)\n        ].join('\\n');\n        await writeFile(join(process.cwd(), '.crew', 'context-summary.md'), `${summary}\\n`, 'utf8');\n      }\n\n      logger.success(\n        `Compacted session history ${result.historyBefore} -> ${result.historyAfter}, ` +\n        `cost entries ${result.costBefore} -> ${result.costAfter}`\n      );\n    });\n\n  const mcp = program\n    .command('mcp')\n    .description('Manage MCP server entries (add/list/remove)');\n\n  mcp\n    .command('list')\n    .description('List local MCP servers from .crew/mcp-servers.json')\n    .action(async () => {\n      const servers = await listMcpServers(process.cwd());\n      const names = Object.keys(servers);\n      if (!names.length) {\n        logger.warn('No MCP servers configured.');\n        return;\n      }\n      names.forEach(name => {\n        const item = servers[name];\n        console.log(`- ${name}: ${item.url}${item.bearerTokenEnvVar ? ` (token env: ${item.bearerTokenEnvVar})` : ''}`);\n      });\n    });\n\n  mcp\n    .command('doctor')\n    .description('Validate MCP server config, env tokens, and reachability')\n    .action(async () => {\n      const checks = await doctorMcpServers(process.cwd());\n      checks.forEach(check => {\n        const marker = check.ok ? chalk.green('\u2713') : chalk.red('\u2717');\n        console.log(`${marker} ${check.server}: ${check.details}`);\n      });\n      if (checks.some(x => !x.ok)) process.exit(1);\n    });\n\n  mcp\n    .command('add')\n    .description('Add an MCP server entry')\n    .argument('<name>', 'Server name')\n    .requiredOption('--url <url>', 'MCP server URL')\n    .option('--bearer-token-env-var <var>', 'Bearer token env variable name')\n    .option('--header <kv>', 'Custom header key:value (repeatable)', collectOption, [])\n    .option('--client <id>', 'Optional client sync: cursor | claude | opencode | codex')\n    .action(async (name, options) => {\n      const headers: Record<string, string> = {};\n      for (const raw of options.header || []) {\n        const [key, ...rest] = String(raw).split(':');\n        if (key && rest.length) headers[key.trim()] = rest.join(':').trim();\n      }\n      await addMcpServer(name, {\n        url: options.url,\n        bearerTokenEnvVar: options.bearerTokenEnvVar,\n        headers\n      }, process.cwd(), options.client);\n      logger.success(`Added MCP server \"${name}\"`);\n    });\n\n  mcp\n    .command('remove')\n    .description('Remove an MCP server entry')\n    .argument('<name>', 'Server name')\n    .option('--client <id>', 'Optional client sync removal: cursor | claude | opencode | codex')\n    .action(async (name, options) => {\n      await removeMcpServer(name, process.cwd(), options.client);\n      logger.success(`Removed MCP server \"${name}\"`);\n    });\n\n  const headless = program\n    .command('headless')\n    .description('Headless execution controls for CI automation');\n\n  headless\n    .command('run')\n    .requiredOption('-t, --task <text>', 'Task text')\n    .option('--agent <id>', 'Override routed agent')\n    .option('-g, --gateway <url>', 'Override gateway URL')\n    .option('--json', 'Emit JSONL events', false)\n    .option('--always-approve', 'Auto-apply sandbox changes', false)\n    .option('--force-auto-apply', 'Bypass risk gate for auto-apply', false)\n    .option('--risk-threshold <level>', 'Auto-apply risk threshold (low|medium|high)', 'high')\n    .option('--retry-attempts <n>', 'Retry attempts for transient failures', '2')\n    .option('--fallback-model <id>', 'Fallback model chain entry (repeatable)', collectOption, [])\n    .option('--strict-preflight', 'Block execution if doctor checks fail', false)\n    .option('--out <path>', 'Write JSONL events to file (for CI artifacts)')\n    .action(async options => {\n      const policy = getExecutionPolicy({\n        strictPreflight: Boolean(options.strictPreflight),\n        retryAttempts: Number.parseInt(options.retryAttempts || '2', 10),\n        riskThreshold: String(options.riskThreshold || 'high').toLowerCase() as RiskLevel,\n        forceAutoApply: Boolean(options.forceAutoApply)\n      });\n      await enforceStrictPreflight(policy, options.gateway);\n      const result = await runHeadlessTask({\n        task: options.task,\n        agent: options.agent,\n        json: options.json,\n        alwaysApprove: options.alwaysApprove,\n        forceAutoApply: options.forceAutoApply,\n        riskThreshold: policy.riskThreshold,\n        retryAttempts: policy.retryAttempts,\n        fallbackModels: options.fallbackModel || [],\n        out: options.out,\n        gateway: options.gateway,\n        projectDir: process.cwd(),\n        router: agentRouter,\n        orchestrator,\n        sandbox,\n        session: sessionManager\n      });\n      if (!result.success) process.exit(1);\n    });\n\n  headless\n    .command('pause')\n    .description('Pause headless execution')\n    .action(async () => {\n      await setHeadlessPaused(true, process.cwd());\n      logger.success('Headless mode paused.');\n    });\n\n  headless\n    .command('resume')\n    .description('Resume headless execution')\n    .action(async () => {\n      await setHeadlessPaused(false, process.cwd());\n      logger.success('Headless mode resumed.');\n    });\n\n  headless\n    .command('status')\n    .description('Show headless pause/resume state')\n    .action(async () => {\n      const state = await getHeadlessState(process.cwd());\n      console.log(`paused=${state.paused} updatedAt=${state.updatedAt || 'n/a'}`);\n    });\n\n  program\n    .command('src')\n    .description('Run Sourcegraph src CLI commands (for batch codemods/search)')\n    .allowUnknownOption(true)\n    .argument('<args...>', 'Arguments passed to src CLI')\n    .action(async (srcArgs: string[]) => {\n      if (srcArgs[0] === 'batch-plan') {\n        const args = srcArgs.slice(1);\n        const readValue = (...names: string[]) => {\n          for (let i = 0; i < args.length; i += 1) {\n            if (names.includes(args[i])) return args[i + 1];\n          }\n          return undefined;\n        };\n        const repos: string[] = [];\n        for (let i = 0; i < args.length; i += 1) {\n          if (args[i] === '--repo' && args[i + 1]) repos.push(args[i + 1]);\n        }\n        const plan = await createSrcBatchPlan({\n          query: readValue('--query', '-q') || '',\n          repos,\n          execute: args.includes('--execute'),\n          specPath: readValue('--spec')\n        }, process.cwd());\n\n        if (plan.success) {\n          logger.success(plan.message);\n          return;\n        }\n        logger.error(plan.message);\n        process.exit(1);\n      }\n\n      const result = await runSrcCli(srcArgs, process.cwd());\n      if (result.stdout) process.stdout.write(result.stdout);\n      if (result.stderr) process.stderr.write(result.stderr);\n      if (!result.success) process.exit(result.code || 1);\n    });\n\n  program\n    .command('estimate')\n    .description('Estimate token usage and compare model costs before execution')\n    .argument('<task...>', 'Task or prompt text')\n    .option('--output-tokens <count>', 'Expected completion tokens', '1200')\n    .action((taskArray, options) => {\n      const task = taskArray.join(' ');\n      const outputTokens = Number.parseInt(options.outputTokens || '1200', 10);\n      const estimates = compareModelCosts(task, outputTokens);\n\n      console.log(chalk.blue('--- Cost Estimates (lowest first) ---'));\n      estimates.forEach(item => {\n        console.log(\n          `${chalk.green(item.model)} ` +\n          `total=$${item.totalUsd.toFixed(4)} ` +\n          `(in ${item.inputTokens} tok, out ${item.outputTokens} tok)`\n        );\n      });\n    });\n\n  program\n    .command('list')\n    .description('List available agents')\n    .action(async () => {\n      try {\n        const agents = await agentRouter.listAgents();\n        agents.forEach(agent => {\n          console.log(chalk.green(`\u2713 ${agent.name}`), chalk.gray(`- ${agent.role}`));\n        });\n      } catch (error) {\n        logger.error('Failed to list agents:', error.message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('status')\n    .description('Check system status')\n    .action(async () => {\n      try {\n        const status = await agentRouter.getStatus();\n        console.log(chalk.blue('System Status:'));\n        console.log(`Agents Online: ${status.agentsOnline}`);\n        console.log(`Tasks Active: ${status.tasksActive}`);\n        console.log(`RT Bus: ${status.rtBusStatus}`);\n      } catch (error) {\n        logger.error('Status check failed:', error.message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('history')\n    .description('Show recent session activity history')\n    .option('-n, --limit <count>', 'Number of entries to show', '5')\n    .action(async (options) => {\n      const session = await sessionManager.loadSession();\n      const limit = Number.parseInt(options.limit || '5', 10);\n      const entries = session.history.slice(-limit);\n\n      console.log(chalk.blue(`--- Recent History (${entries.length} entries) ---`));\n      entries.forEach((e: Record<string, unknown>, i: number) => {\n        const time = e.timestamp.split('T')[1].split('.')[0];\n        console.log(`${chalk.gray(`[${time}]`)} ${chalk.bold(e.type)}: ${e.agent || e.skill || ''}`);\n        if (e.task) console.log(chalk.gray(`  Task: ${e.task.slice(0, 60)}...`));\n      });\n    });\n\n  program\n    .command('cost')\n    .description('Show total usage cost summary')\n    .option('--summary', 'Show breakdown by model', true)\n    .action(async () => {\n      const cost = await sessionManager.loadCost();\n      const pipeline = await loadPipelineMetricsSummary(process.cwd());\n      console.log(chalk.blue('--- Cost Summary ---'));\n      console.log(`Total Spent: ${chalk.green(`$${cost.totalUsd.toFixed(4)}`)}`);\n      \n      if (Object.keys(cost.byModel).length > 0) {\n        console.log(chalk.gray('\\nBreakdown by model:'));\n        Object.entries(cost.byModel as Record<string, number>).forEach(([model, usd]) => {\n          console.log(`- ${model}: $${usd.toFixed(4)}`);\n        });\n      }\n      const cache = cost.cacheSavings || {};\n      console.log(chalk.gray('\\nCache savings:'));\n      console.log(`- hits: ${Number(cache.hits || 0)}`);\n      console.log(`- misses: ${Number(cache.misses || 0)}`);\n      console.log(`- tokens saved (est): ${Number(cache.tokensSaved || 0)}`);\n      console.log(`- usd saved (est): $${Number(cache.usdSaved || 0).toFixed(4)}`);\n      const memory = cost.memoryMetrics || {};\n      const recallUsed = Number(memory.recallUsed || 0);\n      const recallMisses = Number(memory.recallMisses || 0);\n      const matchCount = Number(memory.totalMatches ?? memory.matchCount ?? 0);\n      const avgQuality = Number(\n        memory.averageQualityScore\n        ?? (recallUsed > 0 ? (Number(memory.qualityScoreSum || 0) / recallUsed) : 0)\n      );\n      console.log(chalk.gray('\\nMemory recall metrics:'));\n      console.log(`- recall_used: ${recallUsed}`);\n      console.log(`- recall_misses: ${recallMisses}`);\n      console.log(`- match_count: ${matchCount}`);\n      console.log(`- quality_score_avg: ${avgQuality.toFixed(3)}`);\n      console.log(chalk.gray('\\nPipeline metrics:'));\n      console.log(`- runs: ${pipeline.runs}`);\n      console.log(`- qa_approved: ${pipeline.qaApproved}`);\n      console.log(`- qa_rejected: ${pipeline.qaRejected}`);\n      const avgRounds = pipeline.runs > 0 ? (pipeline.qaRoundsTotal / pipeline.runs) : 0;\n      console.log(`- qa_rounds_avg: ${avgRounds.toFixed(2)}`);\n      console.log(`- context_chunks_used: ${pipeline.contextChunksUsed}`);\n      console.log(`- context_chars_saved_est: ${pipeline.contextCharsSaved}`);\n    });\n\n  program\n    .command('clear')\n    .description('Clear local crew-cli session state (.crew)')\n    .action(async () => {\n      try {\n        await sessionManager.clear();\n        logger.success('Cleared session state in .crew/');\n      } catch (error) {\n        logger.error('Failed to clear session state:', error.message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('skill')\n    .description('Call a crewswarm skill by name')\n    .argument('<name>', 'Skill name, e.g. zeroeval.benchmark')\n    .option('--params <json>', 'JSON params payload', '{}')\n    .option('-g, --gateway <url>', 'Override gateway URL')\n    .action(async (name, options) => {\n      try {\n        let params = {};\n        try {\n          params = JSON.parse(options.params || '{}');\n        } catch {\n          throw new Error('Invalid JSON passed to --params');\n        }\n\n        await sessionManager.appendHistory({\n          type: 'skill_request',\n          skill: name,\n          params\n        });\n\n        const result = await agentRouter.callSkill(name, params, {\n          gateway: options.gateway\n        });\n\n        await sessionManager.appendHistory({\n          type: 'skill_result',\n          skill: name,\n          success: Boolean(result.success)\n        });\n        await sessionManager.appendRouting({\n          route: 'SKILL',\n          model: 'n/a',\n          skill: name\n        });\n\n        logger.success('Skill completed:', result);\n      } catch (error) {\n        await sessionManager.appendHistory({\n          type: 'skill_error',\n          skill: name,\n          error: error.message\n        });\n        logger.error('Skill call failed:', error.message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('x-search')\n    .description('Run native Grok X/Twitter search via xAI Responses API')\n    .argument('<query...>', 'Search query')\n    .option('--model <id>', 'xAI model', 'grok-4-1-fast-reasoning')\n    .option('--from-date <date>', 'Start date (YYYY-MM-DD)')\n    .option('--to-date <date>', 'End date (YYYY-MM-DD)')\n    .option('--allow-handle <handle>', 'Allowed X handle (repeatable)', collectOption, [])\n    .option('--exclude-handle <handle>', 'Excluded X handle (repeatable)', collectOption, [])\n    .option('--images', 'Enable image understanding in x_search tool', false)\n    .option('--videos', 'Enable video understanding in x_search tool', false)\n    .option('--json', 'Output full JSON payload', false)\n    .action(async (queryArray, options) => {\n      try {\n        const query = queryArray.join(' ').trim();\n        const result = await runXSearch(query, {\n          model: options.model,\n          fromDate: options.fromDate,\n          toDate: options.toDate,\n          allowedHandles: options.allowHandle || [],\n          excludedHandles: options.excludeHandle || [],\n          enableImages: Boolean(options.images),\n          enableVideos: Boolean(options.videos)\n        });\n        if (options.json) {\n          console.log(JSON.stringify(result.raw, null, 2));\n          return;\n        }\n        console.log(chalk.blue('\\n--- X Search Result ---\\n'));\n        logger.printWithHighlight(result.text);\n        if (result.citations.length > 0) {\n          console.log(chalk.gray('\\nCitations:'));\n          for (const c of result.citations) console.log(`- ${c}`);\n        }\n      } catch (error) {\n        logger.error('x-search failed:', (error as Error).message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('plan')\n    .description('Generate a detailed plan for a task and execute it step-by-step or in parallel')\n    .argument('<task...>', 'Task to plan and execute')\n    .option('--parallel', 'Execute plan steps in parallel using worker pool', false)\n    .option('--concurrency <n>', 'Maximum parallel workers', '3')\n    .option('-m, --model <id>', 'Model override for plan execution', plannerPrimary || undefined)\n    .option('--fallback-model <id>', 'Fallback model chain entry (repeatable)', collectOption, [])\n    .option('--resume <runId>', 'Resume a prior plan run from checkpoint')\n    .option('--validate-cmd <cmd>', 'Validation command (repeatable, hard gate)', collectOption, [])\n    .option('--reflect-agent <id>', 'Agent used for reflect step', 'crew-main')\n    .option('--no-cache', 'Disable planner cache')\n    .option('--cache-ttl <sec>', 'Planner cache TTL in seconds', '3600')\n    .option('--no-memory', 'Disable shared AgentKeeper memory')\n    .option('--memory-max <n>', 'Max recalled memory entries', '3')\n    .option('--memory-require-validation', 'Store memory only when validation is marked passed', false)\n    .option('--json', 'Output machine-readable JSON envelope and skip interactive prompts', false)\n    .option('--yes', 'Auto-approve plan execution without confirmation', false)\n    .action(async (taskArray, options) => {\n      const task = taskArray.join(' ');\n      const planner = new Planner(agentRouter, sessionManager, process.cwd());\n      const runId = options.resume ? String(options.resume) : `plan-${randomUUID()}`;\n      const validationCommands = options.validateCmd || [];\n      const fallbackModels = (options.fallbackModel && options.fallbackModel.length > 0)\n        ? options.fallbackModel\n        : (plannerPolicy.fallback || []);\n      const existingRun = options.resume ? await checkpoints.load(runId) : null;\n      if (!existingRun) {\n        await checkpoints.beginRun({ runId, mode: 'plan', task });\n      }\n      \n      logger.info(`Generating plan for: ${task}`);\n      const plan = await planner.generatePlan(task, {\n        useCache: options.cache,\n        cacheTtlSeconds: Number.parseInt(options.cacheTtl || '3600', 10),\n        useMemory: options.memory,\n        memoryMaxResults: Number.parseInt(options.memoryMax || '3', 10),\n        runId\n      });\n      await checkpoints.append(runId, 'plan.generated', { steps: plan.steps.length });\n      \n      console.log(chalk.blue('\\n--- Proposed Plan ---'));\n      plan.steps.forEach(s => console.log(`${s.id}. ${s.task}`));\n\n      let completedSteps = new Set<number>();\n      if (options.resume) {\n        const prior = existingRun || await checkpoints.load(runId);\n        if (prior) {\n          completedSteps = new Set(CheckpointStore.completedPlanSteps(prior));\n          if (completedSteps.size > 0) {\n            logger.info(`Resuming from checkpoint ${runId}; skipping completed steps: ${Array.from(completedSteps).join(', ')}`);\n          }\n        }\n      }\n      \n      // Skip confirmation prompt in programmatic/JSON mode or when --yes flag is set\n      let confirm = true;\n      \n      if (!options.json && !options.yes) {\n        const result = await (import('inquirer')).then(m => m.default.prompt([{\n          type: 'confirm',\n          name: 'confirm',\n          message: `Execute this plan ${options.parallel ? 'in parallel' : 'step-by-step'}?`,\n          default: true\n        }]));\n        confirm = result.confirm;\n      }\n      \n      if (!confirm) {\n        if (options.json) {\n          printJsonEnvelope('plan.cancelled', { reason: 'user_declined' });\n        } else {\n          logger.warn('Plan cancelled.');\n        }\n        return;\n      }\n      \n      if (options.parallel) {\n        const { WorkerPool } = await import('../orchestrator/index.js');\n        const pool = new WorkerPool({\n          router: agentRouter,\n          orchestrator,\n          sandbox,\n          keeper: options.memory !== false ? agentKeeper : undefined,\n          concurrency: Number.parseInt(options.concurrency || '3', 10)\n        });\n\n        logger.info(`Starting parallel execution with concurrency ${options.concurrency}`);\n        \n        pool.enqueueAll(plan.steps.map(s => ({\n          id: `step-${s.id}`,\n          agent: 'crew-coder',\n          prompt: s.task\n        })));\n\n        const results = await pool.runAll({\n          sessionId: await sessionManager.getSessionId(),\n          projectDir: process.cwd(),\n          runId\n        });\n\n        const successCount = results.filter(r => r.success).length;\n        const failedCount = results.length - successCount;\n        \n        logger.info(`Parallel execution complete: ${successCount} succeeded, ${failedCount} failed.`);\n        results.forEach(r => {\n          if (!r.success) {\n            logger.error(`Task ${r.taskId} failed: ${r.error}`);\n          }\n        });\n      } else {\n        for (const step of plan.steps) {\n          if (completedSteps.has(step.id)) {\n            continue;\n          }\n          logger.progress(step.id - 1, plan.steps.length, 'Plan');\n          logger.info(`Step ${step.id}: ${step.task}`);\n          try {\n            await checkpoints.append(runId, 'plan.step.started', { stepId: step.id, task: step.task });\n            const dispatched = await dispatchWithFallback(\n              agentRouter,\n              'crew-coder',\n              step.task,\n              {\n                sessionId: await sessionManager.getSessionId(),\n                project: process.cwd(),\n                model: options.model\n              },\n              fallbackModels,\n              checkpoints,\n              runId\n            );\n            const result = dispatched.result;\n            logger.printWithHighlight(chalk.gray(String(result.result || '')));\n            \n            const edits = await orchestrator.parseAndApplyToSandbox(result.result);\n            const validationGate = await runValidationCommands(validationCommands, process.cwd());\n            await checkpoints.append(runId, 'plan.step.validation', {\n              stepId: step.id,\n              passed: validationGate.passed,\n              failedCommand: validationGate.failedCommand || null\n            });\n            if (!validationGate.passed) {\n              logger.error(`Validation failed at step ${step.id}: ${validationGate.failedCommand}`);\n              logger.printWithHighlight(String(validationGate.output || ''));\n              await checkpoints.append(runId, 'plan.step.failed', {\n                stepId: step.id,\n                reason: 'validation-failed',\n                command: validationGate.failedCommand\n              });\n              await checkpoints.finish(runId, 'failed');\n              process.exit(1);\n            }\n            if (options.memory !== false) {\n              const response = String(result.result || '').trim();\n              const validation = extractValidationSignals(result, Boolean(options.memoryRequireValidation));\n              if (response.length > 0 && validation.passed) {\n                const saved = await agentKeeper.recordSafe({\n                  runId,\n                  tier: 'worker',\n                  task: step.task,\n                  result: response,\n                  agent: 'crew-coder',\n                  structured: {\n                    problem: step.task,\n                    edits: edits.map((path: string) => ({ path })),\n                    validation: {\n                      lintPassed: validation.lintPassed,\n                      testsPassed: validation.testsPassed,\n                      notes: validation.notes\n                    },\n                    outcome: 'success'\n                  },\n                  metadata: {\n                    stepId: step.id,\n                    edits: edits.length,\n                    success: true,\n                    paths: edits,\n                    validationRequired: validation.required,\n                    validationPassed: validation.passed\n                  }\n                });\n                if (!saved.ok) {\n                  logger.warn(`Memory write skipped: ${saved.error}`);\n                }\n              }\n            }\n            if (edits.length > 0) {\n              logger.success(`Added changes to ${edits.length} files in sandbox for step ${step.id}.`);\n              const report = await analyzeBlastRadius(process.cwd(), { changedFiles: edits });\n              const patchRisk = scorePatchRisk({\n                blastRadius: report,\n                validationPassed: validationGate.passed,\n                changedFiles: edits.length\n              });\n              logger.info(`Step ${step.id} patch confidence: ${(patchRisk.confidence * 100).toFixed(0)}% (${patchRisk.riskLevel}, ${patchRisk.riskScore}/100)`);\n            }\n            const reflectPrompt = [\n              `Reflect on this completed step and decide next action.`,\n              `Step: ${step.task}`,\n              `Output summary: ${String(result.result || '').slice(0, 1200)}`,\n              `Validation: ${validationGate.passed ? 'passed' : 'failed'}`,\n              `Return concise guidance for next step execution.`\n            ].join('\\n');\n            const reflect = await dispatchWithFallback(\n              agentRouter,\n              options.reflectAgent || 'crew-main',\n              reflectPrompt,\n              {\n                sessionId: await sessionManager.getSessionId(),\n                project: process.cwd()\n              },\n              fallbackModels,\n              checkpoints,\n              runId\n            );\n            logger.info(chalk.gray(`Reflect (${options.reflectAgent || 'crew-main'}): ${String(reflect.result.result || '').slice(0, 180)}`));\n            await checkpoints.append(runId, 'plan.step.completed', {\n              stepId: step.id,\n              edits: edits.length\n            });\n          } catch (err) {\n            logger.error(`Failed at step ${step.id}: ${err.message}`);\n            await checkpoints.append(runId, 'plan.step.failed', {\n              stepId: step.id,\n              reason: String(err.message || err)\n            });\n            await checkpoints.finish(runId, 'failed');\n            break;\n          }\n        }\n        logger.progress(plan.steps.length, plan.steps.length, 'Plan');\n      }\n      \n      logger.success('Plan execution complete. Use \"crew preview\" to review changes.');\n      await checkpoints.finish(runId, 'completed');\n      if (options.memory !== false) {\n        try {\n          await agentKeeper.compact();\n        } catch {\n          // Best-effort maintenance.\n        }\n      }\n    });\n\n  program\n    .command('auth')\n    .description('Search for local OAuth tokens from other coding CLIs')\n    .option('--link', 'Probe local subscription engines and show routing readiness')\n    .option('--no-link', 'Disable engine probe/autolink behavior')\n    .option('--apply', 'Persist auto-plumbed engine defaults to repo config.local.json')\n    .option('--scope <scope>', 'Config scope for --apply: user|team', 'user')\n    .action(async (options) => {\n      const argv = process.argv.slice(2);\n      const explicitLinkFlag = argv.includes('--link') || argv.includes('--no-link');\n      const explicitApplyFlag = argv.includes('--apply');\n      const implicitConnectMode = !explicitLinkFlag && !explicitApplyFlag;\n\n      const finder = new TokenFinder();\n      const tokens = await finder.findTokens();\n      \n      console.log(chalk.blue('--- Local Tokens Found ---'));\n      if (tokens.claude) console.log(chalk.green('\u2713 Claude Code session found'));\n      if (tokens.openai) console.log(chalk.green('\u2713 OpenAI config key found'));\n      if (tokens.gemini) console.log(chalk.green('\u2713 Gemini ADC credentials found'));\n      if (Object.keys(tokens).length === 0) {\n        console.log(chalk.yellow('No local tokens detected.'));\n      }\n\n      const linkEnabled = options.link !== false;\n      if (!linkEnabled) return;\n\n      const probes = detectSubscriptionEngines(tokens);\n      const ready = probes.filter(p => p.ready).map(p => p.id);\n      const installed = probes.filter(p => p.installed).map(p => p.id);\n\n      console.log(chalk.blue('\\n--- Engine Auto-Plumb Probe ---'));\n      for (const probe of probes) {\n        const status = probe.ready\n          ? chalk.green('ready')\n          : probe.installed\n            ? chalk.yellow('partial')\n            : chalk.red('missing');\n        const version = probe.version ? ` (${probe.version})` : '';\n        console.log(`- ${probe.id.padEnd(10)} ${status}${version}`);\n        console.log(chalk.gray(`  notes: ${probe.notes.join(', ')}`));\n      }\n\n      if (installed.length === 0) {\n        console.log(chalk.yellow('\\nNo subscription CLIs detected (cursor/claude/codex).'));\n        return;\n      }\n\n      if (ready.length === 0) {\n        console.log(chalk.yellow('\\nNo engine is fully ready yet. Install/login first, then rerun `crew auth --link --apply`.'));\n        return;\n      }\n\n      const preferredOrder: SubscriptionEngineId[] = ['cursor', 'claude-cli', 'codex-cli'];\n      const preferredReady = preferredOrder.filter(id => ready.includes(id));\n      const recommended = preferredReady[0];\n      console.log(chalk.green(`\\nRecommended default engine: ${recommended}`));\n      console.log(chalk.gray(`Preferred ready order: ${preferredReady.join(' -> ')}`));\n\n      const shouldApply = Boolean(options.apply || implicitConnectMode);\n      if (!shouldApply) {\n        console.log(chalk.gray('Use --apply to persist this into .crew/config.local.json'));\n        return;\n      }\n\n      const scope = String(options.scope || 'user').toLowerCase();\n      if (scope !== 'user' && scope !== 'team') {\n        throw new Error(`Invalid scope \"${scope}\". Use user or team.`);\n      }\n\n      await setRepoConfigValue(process.cwd(), scope as 'user' | 'team', 'cli.engine', recommended);\n      await setRepoConfigValue(process.cwd(), scope as 'user' | 'team', 'repl.engine', recommended);\n      await setRepoConfigValue(process.cwd(), scope as 'user' | 'team', 'cli.preferredEngines', preferredReady);\n\n      console.log(chalk.green('\\n\u2713 Auto-plumb applied'));\n      if (implicitConnectMode) {\n        console.log(chalk.gray('  mode: implicit (crew auth)'));\n      }\n      console.log(chalk.gray(`  scope: ${scope}`));\n      console.log(chalk.gray(`  cli.engine: ${recommended}`));\n      console.log(chalk.gray(`  repl.engine: ${recommended}`));\n      console.log(chalk.gray(`  cli.preferredEngines: ${preferredReady.join(', ')}`));\n    });\n\n  program\n    .command('correction')\n    .description('Record a user correction for local training data (.crew/training-data.jsonl)')\n    .requiredOption('--prompt <text>', 'Original user request/prompt')\n    .requiredOption('--original <text>', 'Initial model output before correction')\n    .requiredOption('--corrected <text>', 'Final corrected output')\n    .option('--agent <id>', 'Agent/model identifier')\n    .option('--tags <csv>', 'Comma-separated tags')\n    .action(async options => {\n      try {\n        const tags = options.tags\n          ? String(options.tags).split(',').map((x: string) => x.trim()).filter(Boolean)\n          : [];\n\n        const entry = await corrections.record({\n          prompt: options.prompt,\n          original: options.original,\n          corrected: options.corrected,\n          agent: options.agent,\n          tags\n        });\n\n        logger.success(`Saved correction at ${entry.timestamp}`);\n      } catch (error) {\n        logger.error('Failed to save correction:', (error as Error).message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('tune')\n    .description('Summarize or export local correction dataset')\n    .option('-e, --export <path>', 'Export training JSONL to a target path')\n    .option('--format <kind>', 'Export format: raw | lora', 'raw')\n    .action(async options => {\n      try {\n        const summary = await corrections.summary();\n        console.log(chalk.blue('--- Local Training Data ---'));\n        console.log(`Entries: ${summary.count}`);\n        if (summary.latest) {\n          console.log(`Latest: ${summary.latest.timestamp}`);\n          console.log(`Agent: ${summary.latest.agent || 'n/a'}`);\n        }\n\n        if (options.export) {\n          if (options.format === 'lora') {\n            const entries = await corrections.loadAll();\n            const lines = entries.map(entry => JSON.stringify({\n              instruction: entry.prompt,\n              input: entry.original,\n              output: entry.corrected,\n              metadata: {\n                timestamp: entry.timestamp,\n                agent: entry.agent || null,\n                tags: entry.tags || []\n              }\n            }));\n            const { writeFile } = await import('node:fs/promises');\n            await writeFile(options.export, `${lines.join('\\n')}\\n`, 'utf8');\n          } else {\n            await corrections.exportTo(options.export);\n          }\n          logger.success(`Exported dataset to ${options.export} (${options.format})`);\n        }\n      } catch (error) {\n        logger.error('Tune command failed:', (error as Error).message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('engine')\n    .description('Run a prompt through a direct engine integration')\n    .requiredOption(\n      '-e, --engine <id>',\n      'gemini-api | claude-api | gemini-cli | codex-cli | claude-cli | cursor | cursor-cli (Cursor agent CLI, not IDE opener)'\n    )\n    .requiredOption('-p, --prompt <text>', 'Prompt text')\n    .option('-m, --model <id>', 'Model override')\n    .option('-t, --timeout <ms>', 'Timeout in milliseconds', '600000')\n    .action(async options => {\n      const result = await runEngine(options.engine, options.prompt, {\n        model: options.model,\n        timeoutMs: Number.parseInt(options.timeout || '600000', 10)\n      });\n\n      if (result.stdout) logger.printWithHighlight(result.stdout);\n      if (result.stderr) console.error(chalk.red(result.stderr));\n      if (!result.success) process.exit(1);\n    });\n\n  program\n    .command('watch')\n    .description('Watch files, detect TODOs, and offer auto-implementation dispatch')\n    .option('-d, --dir <path>', 'Directory to watch', process.cwd())\n    .action(async options => {\n      const root = options.dir || process.cwd();\n      logger.info(`Watching ${root} for TODOs...`);\n      const watcher = startWatchMode(root, async event => {\n        if (event.type === 'todo_detected') {\n          logger.warn(`TODO detected in ${event.file} (${event.todoCount})`);\n          const todoText = (event.todos || []).slice(0, 3).join('\\n');\n          const { confirm } = await (await import('inquirer')).default.prompt([{\n            type: 'confirm',\n            name: 'confirm',\n            message: `Dispatch TODO implementation for ${event.file}?`,\n            default: false\n          }]);\n\n          if (confirm) {\n            await agentRouter.dispatch('crew-coder', `Implement TODOs in ${event.file}:\\n${todoText}`, {\n              sessionId: await sessionManager.getSessionId(),\n              project: process.cwd()\n            });\n            logger.success(`Dispatched TODO implementation for ${event.file}`);\n          }\n        }\n      });\n\n      process.on('SIGINT', () => {\n        watcher.close();\n        logger.info('Watch mode stopped.');\n        process.exit(0);\n      });\n    });\n\n  program\n    .command('browser-debug')\n    .description('Launch Chrome in debug mode, collect console errors, and capture a screenshot')\n    .requiredOption('--url <url>', 'Target URL')\n    .option('--duration-ms <ms>', 'Capture duration in milliseconds', '5000')\n    .option('--port <n>', 'Remote debug port', '9222')\n    .option('--screenshot <path>', 'Screenshot output path')\n    .action(async options => {\n      const result = await runBrowserDebug(options.url, {\n        durationMs: Number.parseInt(options.durationMs || '5000', 10),\n        port: Number.parseInt(options.port || '9222', 10),\n        screenshotPath: options.screenshot\n      });\n      console.log(chalk.blue('--- Browser Debug ---'));\n      console.log(`Errors: ${result.consoleErrors.length}`);\n      result.consoleErrors.forEach(err => console.log(`- ${err}`));\n      if (result.screenshotPath) {\n        console.log(`Screenshot: ${result.screenshotPath}`);\n      }\n    });\n\n  program\n    .command('browser-diff')\n    .description('Compare two screenshots and report byte-level diff')\n    .argument('<a>', 'First screenshot path')\n    .argument('<b>', 'Second screenshot path')\n    .action(async (a, b) => {\n      const diff = await compareScreenshots(a, b);\n      console.log(chalk.blue('--- Screenshot Diff ---'));\n      console.log(`Diff bytes: ${diff.diffBytes}`);\n      console.log(`Diff percent: ${diff.diffPercent.toFixed(2)}%`);\n    });\n\n  program\n    .command('browser-fix')\n    .description('Collect browser errors / failing UI tests and dispatch to crew-fixer')\n    .requiredOption('--url <url>', 'Target URL')\n    .option('--duration-ms <ms>', 'Capture duration in milliseconds', '5000')\n    .option('--test-command <cmd>', 'Optional UI test command to run')\n    .action(async options => {\n      const debug = await runBrowserDebug(options.url, {\n        durationMs: Number.parseInt(options.durationMs || '5000', 10)\n      });\n\n      let task = `Analyze and fix browser issues for ${options.url}.\\n`;\n      if (debug.consoleErrors.length > 0) {\n        task += `Console errors:\\n${debug.consoleErrors.map((e: string) => `- ${e}`).join('\\n')}\\n`;\n      } else {\n        task += 'No console errors captured.\\n';\n      }\n\n      if (options.testCommand) {\n        const { runCheckCommand } = await import('../ci/index.js');\n        const check = await runCheckCommand(options.testCommand, process.cwd());\n        if (!check.success) {\n          task += `\\nUI test command failed: ${options.testCommand}\\nSTDERR:\\n${check.stderr.slice(0, 4000)}\\n`;\n        }\n      }\n\n      const result = await agentRouter.dispatch('crew-fixer', task, {\n        sessionId: await sessionManager.getSessionId(),\n        project: process.cwd()\n      });\n      logger.printWithHighlight(String(result.result || ''));\n    });\n\n  program\n    .command('ci-fix')\n    .description('Run a CI check command and auto-dispatch fixes (max attempts)')\n    .option('-c, --command <cmd>', 'Check command to run', 'npm test')\n    .option('-m, --max-attempts <n>', 'Maximum auto-fix attempts', '3')\n    .option('--push', 'Commit and push after successful fix loop', false)\n    .option('--commit-message <msg>', 'Commit message for --push', 'chore(ci): auto-fix failing checks')\n    .action(async options => {\n      const maxAttempts = Number.parseInt(options.maxAttempts || '3', 10);\n      logger.info(`Starting ci-fix loop for: ${options.command} (max ${maxAttempts})`);\n\n      const result = await runCiFixLoop({\n        command: options.command,\n        maxAttempts,\n        cwd: process.cwd(),\n        router: agentRouter,\n        orchestrator,\n        sandbox,\n        session: sessionManager\n      });\n\n      result.history.forEach(entry => {\n        const marker = entry.success ? chalk.green('PASS') : chalk.red('FAIL');\n        console.log(`Attempt ${entry.attempt}: ${marker}`);\n      });\n\n      if (!result.success) {\n        logger.error(`ci-fix failed after ${result.attemptsUsed} attempts`);\n        process.exit(1);\n      }\n\n      if (options.push) {\n        const { execSync } = await import('node:child_process');\n        try {\n          execSync('git add -A', { stdio: 'inherit', cwd: process.cwd() });\n          execSync(`git commit -m \"${String(options.commitMessage || '').replace(/\"/g, '\\\\\"')}\"`, { stdio: 'inherit', cwd: process.cwd() });\n          execSync('git push', { stdio: 'inherit', cwd: process.cwd() });\n          logger.success('Committed and pushed ci-fix changes.');\n        } catch (pushErr) {\n          logger.warn(`ci-fix succeeded, but push failed: ${(pushErr as Error).message}`);\n        }\n      }\n\n      logger.success(`ci-fix passed in ${result.attemptsUsed} attempt(s)`);\n    });\n\n  program\n    .command('branch')\n    .description('Create a new sandbox branch')\n    .argument('<name>', 'Branch name')\n    .option('-f, --from <branch>', 'Source branch')\n    .action(async (name, options) => {\n      try {\n        await sandbox.createBranch(name, options.from);\n        logger.success(`Created and switched to branch \"${name}\"`);\n      } catch (error) {\n        logger.error('Failed to create branch:', error.message);\n      }\n    });\n\n  program\n    .command('switch')\n    .description('Switch to a different sandbox branch')\n    .argument('<name>', 'Branch name')\n    .action(async (name) => {\n      try {\n        await sandbox.switchBranch(name);\n        logger.success(`Switched to branch \"${name}\"`);\n      } catch (error) {\n        logger.error('Failed to switch branch:', error.message);\n      }\n    });\n\n  program\n    .command('merge')\n    .description('Merge changes from one branch into another')\n    .argument('<source>', 'Source branch')\n    .option('-t, --target <branch>', 'Target branch')\n    .action(async (source, options) => {\n      try {\n        await sandbox.mergeBranch(source, options.target);\n        logger.success(`Merged \"${source}\" into \"${options.target || sandbox.getActiveBranch()}\"`);\n      } catch (error) {\n        logger.error('Failed to merge branch:', error.message);\n      }\n    });\n\n  program\n    .command('branches')\n    .description('List all sandbox branches')\n    .action(() => {\n      const active = sandbox.getActiveBranch();\n      const branches = sandbox.getBranches();\n      console.log(chalk.blue('--- Sandbox Branches ---'));\n      branches.forEach(b => {\n        if (b === active) {\n          console.log(chalk.green(`* ${b}`));\n        } else {\n          console.log(`  ${b}`);\n        }\n      });\n    });\n\n  program\n    .command('doctor')\n    .description('Run local diagnostics (Node, Git, config, gateway)')\n    .option('-g, --gateway <url>', 'Gateway URL to check', 'http://localhost:5010')\n    .option('--update-tag <tag>', 'Version channel for update check', 'latest')\n    .action(async options => {\n      const checks = await runDoctorChecks({ gateway: options.gateway, updateTag: options.updateTag });\n      const summary = summarizeDoctorResults(checks);\n\n      console.log(chalk.blue('crew doctor'));\n      checks.forEach(check => {\n        let marker = check.ok ? chalk.green('\u2713') : chalk.red('\u2717');\n        if (check.name === 'CLI update status' && String(check.details || '').toLowerCase().includes('update available')) {\n          marker = chalk.yellow('!');\n        }\n        console.log(`${marker} ${check.name} ${chalk.gray(`(${check.details})`)}`);\n        if (!check.ok && check.hint) {\n          console.log(chalk.yellow(`  ${check.hint}`));\n        }\n      });\n\n      const summaryColor = summary.failed === 0 ? chalk.green : chalk.red;\n      console.log(summaryColor(`Passed: ${summary.passed}  Failed: ${summary.failed}`));\n\n      if (summary.failed > 0) {\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('update')\n    .description('Check for updates and install latest crew-cli globally')\n    .option('--check', 'Only check availability, do not install', false)\n    .option('--tag <tag>', 'Update channel/tag (default: latest)', 'latest')\n    .option('-y, --yes', 'Skip confirmation prompt', false)\n    .action(async options => {\n      try {\n        const installed = await getInstalledCliVersion();\n        const latest = await getLatestCliVersion(options.tag || 'latest');\n\n        if (!latest) {\n          if (options.check) {\n            logger.warn('Unable to check latest version from npm right now.');\n            return;\n          }\n          logger.error('Unable to check latest version from npm.');\n          process.exit(1);\n        }\n\n        if (!installed) {\n          logger.warn(`Current version unknown. Latest available: ${latest}`);\n        } else {\n          const cmp = compareVersions(installed, latest);\n          if (cmp >= 0) {\n            logger.success(`Already up to date (${installed}).`);\n            return;\n          }\n          logger.info(`Update available: ${installed} -> ${latest}`);\n        }\n\n        if (options.check) {\n          return;\n        }\n\n        const linked = await isGlobalInstallLinked();\n        if (linked) {\n          logger.warn('Global npm link detected. Update may replace the linked install.');\n        }\n\n        if (!options.yes) {\n          const { confirm } = await (await import('inquirer')).default.prompt([{\n            type: 'confirm',\n            name: 'confirm',\n            message: `Install crewswarm-cli@${options.tag || 'latest'} globally now?`,\n            default: true\n          }]);\n          if (!confirm) {\n            logger.warn('Update cancelled.');\n            return;\n          }\n        }\n\n        const { spawn } = await import('node:child_process');\n        await new Promise((resolve, reject) => {\n          const child = spawn('npm', ['install', '-g', `crewswarm-cli@${options.tag || 'latest'}`], {\n            stdio: 'inherit',\n            shell: false\n          });\n          child.on('error', reject);\n          child.on('close', code => {\n            if (code === 0) resolve(null);\n            else reject(new Error(`npm install exited with code ${code}`));\n          });\n        });\n\n        const refreshed = await getLatestCliVersion(options.tag || 'latest');\n        logger.success(`Updated crew-cli to ${refreshed || options.tag || 'latest'}.`);\n      } catch (error) {\n        logger.error('Update failed:', (error as Error).message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('preview')\n    .description('Show pending changes in the sandbox')\n    .argument('[branch]', 'Optional branch name to preview')\n    .action((branch) => {\n      const active = branch || sandbox.getActiveBranch();\n      if (!sandbox.hasChanges(active)) {\n        console.log(chalk.yellow(`No pending changes in sandbox branch \"${active}\".`));\n        return;\n      }\n      console.log(chalk.blue(`--- Sandbox Preview [${active}] ---`));\n      console.log(logger.highlightDiff(sandbox.preview(active)));\n    });\n\n  program\n    .command('apply')\n    .description('Apply all pending changes in the sandbox to the filesystem')\n    .argument('[branch]', 'Optional branch name to apply')\n    .option('-c, --check <command>', 'Command to run after apply (e.g. \"npm test\")')\n    .option('--retries <n>', 'Max retry attempts for --check with diagnostic parsing (default: 3)', '3')\n    .option('--risk-threshold <level>', 'Block apply when risk is >= threshold (low|medium|high)', 'high')\n    .option('--force', 'Bypass risk gate', false)\n    .action(async (branch, options) => {\n      const active = branch || sandbox.getActiveBranch();\n      if (!sandbox.hasChanges(active)) {\n        console.log(chalk.yellow(`No changes to apply on branch \"${active}\".`));\n        return;\n      }\n      try {\n        const paths = sandbox.getPendingPaths(active);\n        const policy = getExecutionPolicy({\n          riskThreshold: String(options.riskThreshold || 'high').toLowerCase() as RiskLevel,\n          forceAutoApply: Boolean(options.force)\n        });\n        const report = await analyzeBlastRadius(process.cwd(), { changedFiles: paths });\n        if (isRiskBlocked(report.risk, policy.riskThreshold, policy.forceAutoApply)) {\n          logger.error(`Apply blocked by risk gate (${report.risk} >= ${policy.riskThreshold}).`);\n          logger.warn('Run \"crew preview\" to inspect changes, then re-run with --force if intentional.');\n          process.exit(1);\n        }\n        await sandbox.apply(active);\n        logger.success(`Applied changes from branch \"${active}\" to: ${paths.join(', ')}`);\n\n        if (options.check) {\n          const maxRetries = Number(options.retries ?? 3);\n          const { execSync } = await import('node:child_process');\n          let attempt = 0;\n          let lastOutput = '';\n          let passed = false;\n\n          while (attempt < maxRetries && !passed) {\n            attempt++;\n            logger.info(`Running check (attempt ${attempt}/${maxRetries}): ${options.check}`);\n            try {\n              execSync(options.check, { stdio: 'inherit', cwd: process.cwd() });\n              logger.success('Check passed!');\n              passed = true;\n            } catch (err) {\n              const execError = err as { stderr?: string; stdout?: string; message?: string };\n              // Capture stderr/stdout for diagnostic parsing\n              const output = String(execError.stderr || execError.stdout || execError.message || '');\n              const diagnostics = parseDiagnosticOutput(output, options.check);\n\n              if (diagnostics.length > 0) {\n                logger.error(`Check failed with ${diagnostics.length} diagnostic(s):`);\n                for (const d of diagnostics.slice(0, 10)) {\n                  logger.warn(`  ${d.file}:${d.line} ${d.message}`);\n                }\n              } else {\n                logger.error(`Check failed: ${output.slice(0, 500)}`);\n              }\n\n              // Don't retry if output is identical to last attempt (no progress)\n              if (output === lastOutput && attempt > 1) {\n                logger.warn('No progress detected \u2014 stopping retry loop.');\n                break;\n              }\n              lastOutput = output;\n\n              if (attempt < maxRetries) {\n                logger.warn(`Dispatching crew-fixer with parsed diagnostics (attempt ${attempt})...`);\n                try {\n                  const fixPrompt = diagnostics.length > 0\n                    ? [\n                        `The command \"${options.check}\" failed after applying changes to: ${paths.join(', ')}.`,\n                        `${diagnostics.length} diagnostic(s) found:`,\n                        ...diagnostics.slice(0, 30).map(d =>\n                          `  ${d.file}:${d.line}:${d.column} [${d.category}] ${d.message}`\n                        ),\n                        'Fix these specific errors. Apply minimal, targeted changes only.'\n                      ].join('\\n')\n                    : `The command \"${options.check}\" failed after applying sandbox changes to files: ${paths.join(', ')}. Output:\\n${output.slice(0, 2000)}\\nDiagnose and provide a fix.`;\n\n                  const fixResult = await agentRouter.dispatch(\n                    'crew-fixer',\n                    fixPrompt,\n                    {\n                      sessionId: await sessionManager.getSessionId(),\n                      project: process.cwd()\n                    }\n                  );\n                  logger.printWithHighlight(String(fixResult.result || ''));\n                } catch (fixError) {\n                  logger.warn(`Auto-fixer failed: ${(fixError as Error).message}`);\n                  break;\n                }\n              }\n            }\n          }\n\n          if (!passed) {\n            logger.error(`Check failed after ${attempt} attempt(s).`);\n          }\n        }\n      } catch (error) {\n        logger.error('Failed to apply changes:', error.message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('rollback')\n    .description('Discard all pending changes in the sandbox')\n    .argument('[branch]', 'Optional branch name to rollback')\n    .action(async (branch) => {\n      const active = branch || sandbox.getActiveBranch();\n      try {\n        await sandbox.rollback(active);\n        logger.success(`Rolled back all pending changes in branch \"${active}\".`);\n      } catch (error) {\n        logger.error('Failed to rollback:', error.message);\n        process.exit(1);\n      }\n    });\n\n  // \u2500\u2500 Collections Search (RAG over docs) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  program\n    .command('docs')\n    .description('Search project docs and optionally code with source-attributed local RAG')\n    .argument('<query...>', 'Search query')\n    .option('--path <paths...>', 'Paths to index (default: docs/ and project root)')\n    .option('--code', 'Include source code files in the index', false)\n    .option('--max <n>', 'Max results to return', '8')\n    .option('--json', 'Output as JSON', false)\n    .action(async (queryArray, options) => {\n      const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n      const query = queryArray.join(' ');\n      const paths = options.path && options.path.length > 0\n        ? options.path\n        : [join(process.cwd(), 'docs'), process.cwd()];\n      try {\n        const index = await buildCollectionIndex(paths, {\n          includeCode: Boolean(options.code)\n        });\n        const result = searchCollection(index, query, Number.parseInt(options.max || '8', 10));\n\n        if (options.json) {\n          console.log(JSON.stringify(result, null, 2));\n          return;\n        }\n\n        if (result.hits.length === 0) {\n          logger.warn(`No results for \"${query}\" (${index.fileCount} files, ${index.chunkCount} chunks indexed).`);\n          return;\n        }\n\n        console.log(chalk.blue(`\\n--- Docs Search: \"${query}\" (${result.hits.length} hits from ${index.chunkCount} chunks) ---\\n`));\n        for (const hit of result.hits) {\n          console.log(chalk.yellow(`[${hit.score}] ${hit.source}:${hit.startLine}`));\n          const preview = hit.text.length > 200 ? hit.text.slice(0, 200) + '...' : hit.text;\n          console.log(chalk.gray(preview));\n          console.log('');\n        }\n      } catch (error) {\n        logger.error('Docs search failed:', error.message);\n        process.exit(1);\n      }\n    });\n\n  // \u2500\u2500 Blast Radius Analysis \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  program\n    .command('blast-radius')\n    .description('Analyze impact of current changes across the codebase')\n    .option('--ref <ref>', 'Git diff reference (default: HEAD)')\n    .option('--max-depth <n>', 'Max transitive import depth', '5')\n    .option('--json', 'Output as JSON', false)\n    .option('--gate', 'Exit non-zero if risk is high (for CI)', false)\n    .action(async (options) => {\n      const { analyzeBlastRadius } = await import('../blast-radius/index.js');\n      try {\n        const report = await analyzeBlastRadius(process.cwd(), {\n          diffRef: options.ref,\n          maxDepth: Number.parseInt(options.maxDepth || '5', 10)\n        });\n\n        if (options.json) {\n          console.log(JSON.stringify(report, null, 2));\n        } else {\n          const riskColor = { low: chalk.green, medium: chalk.yellow, high: chalk.red }[report.risk];\n          console.log(chalk.blue('\\n--- Blast Radius Analysis ---\\n'));\n          console.log(riskColor(report.summary));\n\n          if (report.affectedFiles.length > 0) {\n            console.log(chalk.blue('\\nAffected files:'));\n            for (const af of report.affectedFiles) {\n              const tag = { changed: chalk.red('CHANGED'), 'direct-importer': chalk.yellow('DIRECT'), 'transitive-importer': chalk.gray('TRANSITIVE') }[af.relation];\n              console.log(`  ${tag}  ${af.path}`);\n            }\n          }\n        }\n\n        if (options.gate && report.risk === 'high') {\n          logger.error('Blast radius is HIGH \u2014 aborting (use without --gate to see report only).');\n          process.exit(1);\n        }\n      } catch (error) {\n        logger.error('Blast radius analysis failed:', error.message);\n        process.exit(1);\n      }\n    });\n\n  program\n    .command('test-sandbox')\n    .description('Internal test for sandbox')\n    .option('-f, --file <path>', 'File to modify', 'sandbox-test.txt')\n    .option('-c, --content <text>', 'New content', 'Hello from sandbox!')\n    .action(async options => {\n      try {\n        await sandbox.addChange(options.file, options.content);\n        logger.success(`Added change to ${options.file} in sandbox.`);\n        console.log('Run \"crew preview\" to see the diff.');\n      } catch (error) {\n        logger.error('Test failed:', error.message);\n      }\n    });\n\n  // \u2500\u2500 AgentKeeper Memory \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  program\n    .command('memory')\n    .description('Query AgentKeeper task memory')\n    .argument('[query...]', 'Search query (omit to show stats)')\n    .option('--max <n>', 'Max results', '5')\n    .option('--rag', 'Blend AgentKeeper + shared fact memory + collections RAG', true)\n    .option('--no-rag', 'Use AgentKeeper-only recall')\n    .option('--include-code', 'Include source files in collections retrieval', false)\n    .option('--path <paths...>', 'Custom docs/code search paths for RAG')\n    .option('--json', 'Output as JSON', false)\n    .action(async (queryArray, options) => {\n      const { AgentKeeper } = await import('../memory/agentkeeper.js');\n      const keeper = new AgentKeeper(process.cwd());\n      const broker = new MemoryBroker(process.cwd());\n      const query = (queryArray || []).join(' ').trim();\n\n      if (!query) {\n        const stats = await keeper.stats();\n        if (options.json) {\n          console.log(JSON.stringify(stats, null, 2));\n        } else {\n          console.log(chalk.blue('\\n--- AgentKeeper Memory Stats ---\\n'));\n          console.log(`  Total entries: ${stats.entries}`);\n          console.log(`  Approx bytes: ${stats.bytes}`);\n          if (Object.keys(stats.byTier).length > 0) {\n            console.log('  By tier:');\n            for (const [tier, count] of Object.entries(stats.byTier)) {\n              console.log(`    ${tier}: ${count}`);\n            }\n          }\n          if (Object.keys(stats.byAgent).length > 0) {\n            console.log('  By agent:');\n            for (const [agent, count] of Object.entries(stats.byAgent)) {\n              console.log(`    ${agent}: ${count}`);\n            }\n          }\n          try {\n            const cost = await sessionManager.loadCost();\n            const memory = cost.memoryMetrics || {};\n            const recallUsed = Number(memory.recallUsed || 0);\n            const recallMisses = Number(memory.recallMisses || 0);\n            const matchCount = Number(memory.totalMatches ?? memory.matchCount ?? 0);\n            const avgQuality = Number(\n              memory.averageQualityScore\n              ?? (recallUsed > 0 ? (Number(memory.qualityScoreSum || 0) / recallUsed) : 0)\n            );\n            console.log('  Recall metrics:');\n            console.log(`    recall_used: ${recallUsed}`);\n            console.log(`    recall_misses: ${recallMisses}`);\n            console.log(`    match_count: ${matchCount}`);\n            console.log(`    quality_score_avg: ${avgQuality.toFixed(3)}`);\n          } catch {\n            // Best-effort observability section.\n          }\n        }\n        return;\n      }\n\n      const max = Number.parseInt(options.max || '5', 10);\n      if (options.rag) {\n        const hits = await broker.recall(query, {\n          maxResults: max,\n          includeDocs: true,\n          includeCode: Boolean(options.includeCode),\n          docsPaths: options.path && options.path.length > 0 ? options.path : undefined\n        });\n        if (options.json) {\n          console.log(JSON.stringify(hits, null, 2));\n          return;\n        }\n        if (hits.length === 0) {\n          logger.warn(`No shared memory/RAG matches for \"${query}\".`);\n          return;\n        }\n        console.log(chalk.blue(`\\n--- Shared Memory + RAG Recall: \"${query}\" (${hits.length} hits) ---\\n`));\n        for (const h of hits) {\n          console.log(chalk.yellow(`[${h.score.toFixed(3)}] ${h.source} \u2014 ${h.title.slice(0, 100)}`));\n          const preview = h.text.length > 160 ? h.text.slice(0, 160) + '...' : h.text;\n          console.log(chalk.gray(`  ${preview}`));\n          console.log('');\n        }\n        return;\n      }\n\n      const matches = await keeper.recall(query, max);\n      if (options.json) {\n        console.log(JSON.stringify(matches, null, 2));\n        return;\n      }\n      if (matches.length === 0) {\n        logger.warn(`No memory matches for \"${query}\".`);\n        return;\n      }\n      console.log(chalk.blue(`\\n--- Memory Recall: \"${query}\" (${matches.length} matches) ---\\n`));\n      for (const m of matches) {\n        console.log(chalk.yellow(`[${m.score}] ${m.entry.tier} \u2014 ${m.entry.task.slice(0, 80)}`));\n        if (m.entry.agent) console.log(chalk.gray(`  Agent: ${m.entry.agent}`));\n        const preview = m.entry.result.length > 150 ? m.entry.result.slice(0, 150) + '...' : m.entry.result;\n        console.log(chalk.gray(`  Result: ${preview}`));\n        console.log('');\n      }\n    });\n\n  program\n    .command('memory-compact')\n    .description('Compact AgentKeeper memory store')\n    .option('--max-entries <n>', 'Max entries to keep', '500')\n    .action(async (options) => {\n      const { AgentKeeper } = await import('../memory/agentkeeper.js');\n      const keeper = new AgentKeeper(process.cwd(), {\n        maxEntries: Number.parseInt(options.maxEntries || '500', 10)\n      });\n      const result = await keeper.compact();\n      logger.success(`Compacted: ${result.entriesBefore} \u2192 ${result.entriesAfter} entries (freed ${result.bytesFreed} bytes).`);\n    });\n\n  const checkpointCmd = program\n    .command('checkpoint')\n    .description('Inspect or replay resumable run checkpoints');\n\n  checkpointCmd\n    .command('list')\n    .description('List recent checkpoints')\n    .option('--max <n>', 'Max checkpoints', '20')\n    .action(async options => {\n      const runs = await checkpoints.list(Number.parseInt(options.max || '20', 10));\n      if (runs.length === 0) {\n        logger.warn('No checkpoints found.');\n        return;\n      }\n      console.log(chalk.blue('\\n--- Checkpoints ---\\n'));\n      for (const run of runs) {\n        console.log(`${run.runId}  ${run.mode}  ${run.status}  ${run.updatedAt}`);\n        console.log(chalk.gray(`  ${run.task.slice(0, 120)}`));\n      }\n    });\n\n  checkpointCmd\n    .command('show')\n    .description('Show checkpoint details and deterministic event log')\n    .argument('<runId>', 'Checkpoint run id')\n    .option('--json', 'Output raw JSON', false)\n    .action(async (runId, options) => {\n      const run = await checkpoints.load(runId);\n      if (!run) {\n        logger.error(`Checkpoint not found: ${runId}`);\n        process.exit(1);\n      }\n      if (options.json) {\n        console.log(JSON.stringify(run, null, 2));\n        return;\n      }\n      console.log(chalk.blue(`\\n--- Checkpoint ${run.runId} ---\\n`));\n      console.log(`Mode: ${run.mode}`);\n      console.log(`Status: ${run.status}`);\n      console.log(`Task: ${run.task}`);\n      console.log(`Events: ${run.events.length}\\n`);\n      for (const ev of run.events) {\n        console.log(`${ev.ts}  ${ev.type}`);\n        if (ev.data && Object.keys(ev.data).length > 0) {\n          console.log(chalk.gray(`  ${JSON.stringify(ev.data)}`));\n        }\n      }\n    });\n\n  checkpointCmd\n    .command('replay')\n    .description('Replay checkpoint decisions/tools (dry-run by default)')\n    .argument('<runId>', 'Checkpoint run id')\n    .option('--execute', 'Execute replay for supported modes', false)\n    .action(async (runId, options) => {\n      const run = await checkpoints.load(runId);\n      if (!run) {\n        logger.error(`Checkpoint not found: ${runId}`);\n        process.exit(1);\n      }\n      console.log(chalk.blue(`\\n--- Replay ${run.runId} (${run.mode}) ---\\n`));\n      for (const ev of run.events) {\n        console.log(`${ev.ts}  ${ev.type}`);\n      }\n      if (!options.execute) {\n        logger.info('Dry-run replay complete. Re-run with --execute to execute replay where supported.');\n        return;\n      }\n      if (run.mode === 'plan') {\n        logger.info(`Use: crew plan \"${run.task}\" --resume ${run.runId}`);\n        return;\n      }\n      if (run.mode !== 'dispatch') {\n        logger.warn('Execute replay currently supports dispatch checkpoints only.');\n        return;\n      }\n      const agent =\n        String(run.events.find(e => e.type === 'dispatch.completed')?.data?.agent || 'crew-main');\n      const chain = run.events\n        .filter(e => e.type === 'dispatch.model.attempt')\n        .map(e => String(e.data?.model || '').trim())\n        .filter(Boolean);\n      const primary = chain[0];\n      const fallbacks = chain.slice(1);\n      const replay = await dispatchWithFallback(\n        agentRouter,\n        agent,\n        run.task,\n        {\n          sessionId: await sessionManager.getSessionId(),\n          project: process.cwd(),\n          model: primary || undefined\n        },\n        fallbacks,\n        checkpoints,\n        `${run.runId}-replay-${Date.now()}`\n      );\n      logger.success('Replay dispatch complete.');\n      logger.printWithHighlight(String(replay.result.result || ''));\n    });\n\n  program\n    .command('serve')\n    .description('Start unified interface API server (standalone only)')\n    .option('--mode <mode>', 'Compatibility alias; only \"standalone\" is supported', 'standalone')\n    .option('--host <host>', 'Bind host', process.env.CREW_API_HOST || '127.0.0.1')\n    .option('--port <port>', 'Bind port', process.env.CREW_API_PORT || '4317')\n    .action(async (options) => {\n      const requestedMode = String(options.mode || 'standalone').trim().toLowerCase();\n      if (requestedMode !== 'standalone') {\n        logger.error(`Unsupported --mode \"${requestedMode}\". crew serve only supports standalone mode now.`);\n        logger.info('Use: crew serve --port 4097');\n        process.exit(1);\n      }\n      const mode = 'standalone';\n      const host = String(options.host || '127.0.0.1');\n      const port = Number.parseInt(String(options.port || '4317'), 10);\n      if (Number.isNaN(port) || port <= 0) {\n        logger.error('Invalid --port value.');\n        process.exit(1);\n      }\n\n      const svc = await startUnifiedServer({\n        mode,\n        host,\n        port,\n        gateway: options.gateway,\n        router: agentRouter,\n        orchestrator,\n        sandbox,\n        session: sessionManager,\n        projectDir: process.cwd(),\n        logger\n      });\n\n      logger.success(`Unified API server running at ${svc.address} (${mode})`);\n      logger.info('Press Ctrl+C to stop.');\n      const shutdown = async () => {\n        try {\n          await svc.close();\n        } finally {\n          process.exit(0);\n        }\n      };\n      process.on('SIGINT', shutdown);\n      process.on('SIGTERM', shutdown);\n      await new Promise(() => {});\n    });\n\n  // \u2500\u2500 crew validate \u2014 blind AI code review \u2500\u2500\n  program\n    .command('validate')\n    .description('Blind AI code review of recent changes')\n    .option('-m, --model <id>', 'Model override', executorPrimary || undefined)\n    .option('-n, --commits <n>', 'How many commits to review (default: 1)', '1')\n    .option('--json', 'Output machine-readable JSON', false)\n    .action(async (options) => {\n      try {\n        const n = Math.max(1, parseInt(options.commits || '1', 10));\n        let diffStat = '';\n        try { diffStat = execSync(`git diff HEAD~${n} --stat`, { encoding: 'utf8', cwd: process.cwd() }).slice(0, 2000); } catch {}\n        let codeSnippets = '';\n        try {\n          const changedFiles = execSync(`git diff HEAD~${n} --name-only`, { encoding: 'utf8', cwd: process.cwd() })\n            .split('\\n').filter(Boolean).slice(0, 5);\n          for (const f of changedFiles) {\n            try {\n              const { readFileSync } = await import('node:fs');\n              const content = readFileSync(join(process.cwd(), f), 'utf8');\n              codeSnippets += `\\n### ${f}\\n\\`\\`\\`\\n${content.slice(0, 1500)}\\n\\`\\`\\`\\n`;\n            } catch {}\n          }\n        } catch {}\n\n        const validateTask = `You are crew-judge, a blind code validator. Review these recent changes and provide a structured assessment.\n\nScore each category 1-5:\n- **Correctness**: Does the code work? Edge cases?\n- **Security**: Vulnerabilities? Input validation?\n- **Performance**: Bottlenecks? Memory leaks?\n- **Readability**: Clean, documented, follows conventions?\n- **Test Coverage**: Tests present? What's missing?\n\nEnd with VERDICT: SHIP, FIX, or REJECT with actionable items.\n\n## Changed files\\n${diffStat || 'No recent changes'}\\n\\n## Code\\n${codeSnippets || 'No code to review'}`;\n\n        logger.info('Running blind validation...');\n        const result = await orchestrator.executeLocally(validateTask, { model: options.model });\n        const responseText = String(result.result || 'Validation could not complete.');\n\n        if (options.json) {\n          printJsonEnvelope('validate.result', { response: responseText, costUsd: result.costUsd || 0 });\n        } else {\n          console.log(chalk.blue('\\n--- Validation Report ---'));\n          logger.printWithHighlight(responseText);\n          console.log();\n          if (result.costUsd) {\n            console.log(chalk.gray(`Cost: $${result.costUsd.toFixed(4)}`));\n          }\n        }\n      } catch (error) {\n        logger.error('Validation failed:', (error as Error).message);\n        process.exit(1);\n      }\n    });\n\n  // \u2500\u2500 crew diff \u2014 colored git diff \u2500\u2500\n  program\n    .command('diff')\n    .description('Show colored git diff of working directory')\n    .option('--staged', 'Show only staged changes', false)\n    .option('--stat', 'Show diffstat only', false)\n    .action(async (options) => {\n      try {\n        const statFlag = options.stat ? ' --stat' : '';\n        const staged = execSync(`git diff --cached${statFlag}`, { encoding: 'utf8', cwd: process.cwd() }).trim();\n        const unstaged = options.staged ? '' : execSync(`git diff${statFlag}`, { encoding: 'utf8', cwd: process.cwd() }).trim();\n        const fullDiff = (staged + '\\n' + unstaged).trim();\n        if (!fullDiff) {\n          console.log(chalk.yellow('No git changes.'));\n          return;\n        }\n        const lines = fullDiff.split('\\n').map(line => {\n          if (line.startsWith('+++') || line.startsWith('---')) return chalk.bold(line);\n          if (line.startsWith('+')) return chalk.green(line);\n          if (line.startsWith('-')) return chalk.red(line);\n          if (line.startsWith('@@')) return chalk.cyan(line);\n          if (line.startsWith('diff ')) return chalk.bold.blue(line);\n          return line;\n        });\n        console.log(lines.join('\\n'));\n      } catch (error) {\n        logger.error('Git diff failed:', (error as Error).message);\n        process.exit(1);\n      }\n    });\n\n  // \u2500\u2500 crew test-first \u2014 TDD workflow \u2500\u2500\n  program\n    .command('test-first')\n    .description('TDD workflow: generate tests -> implement -> validate')\n    .argument('<task...>', 'Task description')\n    .option('-m, --model <id>', 'Model override', executorPrimary || undefined)\n    .option('--json', 'Output machine-readable JSON', false)\n    .action(async (taskArray, options) => {\n      const task = taskArray.join(' ');\n      const projectDir = process.cwd();\n      try {\n        logger.info('Step 1: Generating tests...');\n        const testResult = await orchestrator.executeLocally(\n          `You are a TDD expert. Write comprehensive tests FIRST. Cover happy path, edge cases, error handling. Output ONLY the test code in a fenced code block with filename.\\n\\nTask: ${task}\\nProject dir: ${projectDir}`,\n          { model: options.model }\n        );\n        const testCode = String(testResult.result || '');\n        if (!options.json) {\n          console.log(chalk.blue('\\n--- Tests ---'));\n          logger.printWithHighlight(testCode);\n        }\n\n        logger.info('Step 2: Implementing to pass tests...');\n        const implResult = await orchestrator.executeLocally(\n          `Given these tests, write the MINIMAL implementation to make ALL tests pass.\\n\\nTests:\\n${testCode}\\n\\nTask: \"${task}\"`,\n          { model: options.model }\n        );\n        const implCode = String(implResult.result || '');\n        if (!options.json) {\n          console.log(chalk.blue('\\n--- Implementation ---'));\n          logger.printWithHighlight(implCode);\n        }\n\n        logger.info('Step 3: Validating...');\n        const valResult = await orchestrator.executeLocally(\n          `Verify: 1) Would all tests pass? 2) Missing edge cases? 3) Bugs?\\nVerdict: PASS or FAIL with specific issues.\\n\\nTests:\\n${testCode}\\n\\nImplementation:\\n${implCode}`,\n          { model: options.model }\n        );\n        if (!options.json) {\n          console.log(chalk.blue('\\n--- Validation ---'));\n          logger.printWithHighlight(String(valResult.result || ''));\n        }\n\n        const totalCost = (testResult.costUsd || 0) + (implResult.costUsd || 0) + (valResult.costUsd || 0);\n        if (options.json) {\n          printJsonEnvelope('test-first.result', {\n            tests: testCode, implementation: implCode,\n            validation: String(valResult.result || ''), costUsd: totalCost\n          });\n        } else {\n          console.log(chalk.gray(`\\nTotal cost: $${totalCost.toFixed(4)}`));\n        }\n      } catch (error) {\n        logger.error('Test-first failed:', (error as Error).message);\n        process.exit(1);\n      }\n    });\n\n  if (args.length === 0) {\n    program.help();\n  }\n\n  await program.parseAsync(args, { from: 'user' });\n}\n\nif (import.meta.url === `file://${process.argv[1]}`) {\n  main(process.argv.slice(2));\n}\n", "import { EventEmitter } from 'events';\nimport { Logger } from '../utils/logger.js';\nimport { getProjectContext } from '../context/git.js';\nimport { CLI_SYSTEM_PROMPT } from './prompt.js';\nimport { readFileSync } from 'node:fs';\n\nexport class AgentRouter extends EventEmitter {\n  constructor(config, toolManager) {\n    super();\n    this.config = config;\n    this.toolManager = toolManager;\n    this.logger = new Logger();\n    this.agents = new Map();\n  }\n\n  async dispatch(agentName, task, options = {}) {\n    if (!agentName || !task) {\n      throw new Error('Agent name and task are required');\n    }\n\n    this.logger.info(`Routing task to agent: ${agentName}`);\n\n    const timeout = parseInt(options.timeout || '300000', 10);\n    const crewLeadUrl = options.gateway || this.config.get('crewLeadUrl') || 'http://localhost:5010';\n    const projectDir = options.project || process.cwd();\n\n    try {\n      const gitContext = options.injectGitContext === false\n        ? ''\n        : await getProjectContext(projectDir);\n\n      const preamble = options.skipPreamble ? '' : CLI_SYSTEM_PROMPT;\n      const taskWithContext = [\n        preamble,\n        '--- USER REQUEST ---',\n        task,\n        '--- REPO CONTEXT ---',\n        gitContext\n      ].filter(Boolean).join('\\n\\n');\n\n      const imagesData = [];\n      if (options.images && Array.isArray(options.images)) {\n        for (const imgPath of options.images) {\n          try {\n            const data = readFileSync(imgPath);\n            const base64 = data.toString('base64');\n            const ext = imgPath.split('.').pop().toLowerCase();\n            const mimeType = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg';\n            imagesData.push({ data: base64, mimeType });\n          } catch (err) {\n            this.logger.warn(`Could not read image ${imgPath}: ${err.message}`);\n          }\n        }\n      }\n\n      const runtime = this.mapEngineToRuntime(options.engine);\n      const dispatchPayload = {\n        agent: agentName,\n        task: taskWithContext,\n        sessionId: options.sessionId || 'crew-cli',\n        projectDir,\n        images: imagesData.length > 0 ? imagesData : undefined,\n        model: options.model,\n        engine: options.engine,\n        runtime: runtime || options.runtime,\n        useCursorCli: runtime === 'cursor' || runtime === 'cursor-cli',\n        useClaudeCode: runtime === 'claude' || runtime === 'claude-code',\n        useCodex: runtime === 'codex' || runtime === 'codex-cli',\n        useGeminiCli: runtime === 'gemini' || runtime === 'gemini-cli',\n        direct: Boolean(options.direct),\n        bypass: Boolean(options.bypass),\n        gatewayMode: options.gatewayMode,\n        session: {\n          id: options.sessionId || 'crew-cli',\n          source: 'crew-cli',\n          timestamp: new Date().toISOString()\n        }\n      };\n\n      const token = this.getAuthToken();\n      const headers = { 'Content-Type': 'application/json' };\n      if (token) {\n        headers['Authorization'] = `Bearer ${token}`;\n      }\n\n      const dispatchResponse = await fetch(`${crewLeadUrl}/api/dispatch`, {\n        method: 'POST',\n        headers,\n        body: JSON.stringify(dispatchPayload)\n      });\n\n      if (!dispatchResponse.ok) {\n        const raw = await dispatchResponse.text();\n        let parsed = null;\n        try {\n          parsed = JSON.parse(raw);\n        } catch {\n          parsed = null;\n        }\n        const baseMessage = parsed?.error || raw || `Gateway returned ${dispatchResponse.status}`;\n        throw new Error(\n          `${baseMessage}${this.getDispatchErrorHint(baseMessage, options)}`\n        );\n      }\n\n      const { taskId } = await dispatchResponse.json();\n\n      if (!taskId) {\n        this.logger.warn('No taskId returned - agent may be using fallback mode');\n        return {\n          success: true,\n          agent: agentName,\n          task,\n          result: 'Task dispatched (no taskId - check RT Messages tab)',\n          timestamp: new Date().toISOString()\n        };\n      }\n\n      this.logger.info(`Polling for task completion (taskId: ${taskId})`);\n      const result = await this.pollTaskStatus(crewLeadUrl, taskId, timeout, options);\n\n      return {\n        success: true,\n        agent: agentName,\n        task,\n        taskId,\n        result,\n        timestamp: new Date().toISOString()\n      };\n    } catch (error) {\n      this.logger.error(`Dispatch failed: ${error.message}`);\n      throw error;\n    }\n  }\n\n  mapEngineToRuntime(engine) {\n    const raw = String(engine || '').toLowerCase();\n    if (!raw) return null;\n    if (raw === 'cursor' || raw === 'cursor-cli') return 'cursor-cli';\n    if (raw === 'claude' || raw === 'claude-cli' || raw === 'claude-code') return 'claude-code';\n    if (raw === 'codex' || raw === 'codex-cli') return 'codex-cli';\n    if (raw === 'gemini' || raw === 'gemini-cli' || raw === 'gemini-api') return 'gemini-cli';\n    if (raw === 'opencode' || raw === 'gpt5' || raw === 'gpt-5') return 'opencode';\n    return raw;\n  }\n\n  getDispatchErrorHint(message, options = {}) {\n    const text = String(message || '').toLowerCase();\n    const hints = [];\n    if (text.includes('429') || text.includes('rate limit') || text.includes('too many requests')) {\n      hints.push('rate-limited upstream; retry with backoff or switch model');\n    }\n    if (text.includes('missing model') || text.includes('model required') || text.includes('--model')) {\n      hints.push('set an explicit model (e.g. --model anthropic/claude-3-5-sonnet)');\n    }\n    if (\n      (text.includes('exit code 1') || text.includes('code 1')) &&\n      (text.includes('cursor') || options.engine === 'cursor' || options.direct || options.bypass)\n    ) {\n      hints.push('Cursor CLI likely failed; verify cursor auth/env and pass --model explicitly');\n    }\n    return hints.length ? ` (hint: ${hints.join('; ')})` : '';\n  }\n\n  async pollTaskStatus(gatewayUrl, taskId, timeoutMs, options = {}) {\n    const startTime = Date.now();\n    const pollInterval = 2000;\n\n    const token = this.getAuthToken();\n    const headers = {};\n    if (token) {\n      headers['Authorization'] = `Bearer ${token}`;\n    }\n\n    while (Date.now() - startTime < timeoutMs) {\n      try {\n        const statusResponse = await fetch(`${gatewayUrl}/api/status/${taskId}`, {\n          headers\n        });\n\n        if (!statusResponse.ok) {\n          throw new Error(`Status check failed: ${statusResponse.status}`);\n        }\n\n        const status = await statusResponse.json();\n\n        if (status.status === 'done') {\n          try {\n            return this.normalizeCompletedResult(status.result, options, status);\n          } catch (normalizeError) {\n            const fatal = normalizeError instanceof Error ? normalizeError : new Error(String(normalizeError));\n            fatal.fatal = true;\n            throw fatal;\n          }\n        }\n\n        if (status.status === 'error') {\n          const baseError = status.error || status.result || 'Task failed';\n          const fatal = new Error(`${baseError}${this.getDispatchErrorHint(baseError, options)}`);\n          fatal.fatal = true;\n          throw fatal;\n        }\n\n        await new Promise(resolve => setTimeout(resolve, pollInterval));\n      } catch (error) {\n        if (error && error.fatal) {\n          throw error;\n        }\n        if (Date.now() - startTime >= timeoutMs) {\n          throw new Error(`Timeout waiting for ${taskId} (${timeoutMs}ms)`);\n        }\n      }\n    }\n\n    throw new Error(`Timeout waiting for ${taskId} (${timeoutMs}ms)`);\n  }\n\n  normalizeCompletedResult(rawResult, options = {}, statusObj = {}) {\n    const isObject = rawResult && typeof rawResult === 'object';\n    if (!isObject) {\n      const text = String(rawResult || '').trim();\n      if (!text) {\n        if (options.direct || options.bypass) {\n          throw new Error('Gateway returned an empty direct/bypass response');\n        }\n        return 'Task completed';\n      }\n      this.assertEngineProvenance(text, options, statusObj);\n      return text;\n    }\n\n    const result = rawResult;\n    const exitCode =\n      typeof result.exitCode === 'number'\n        ? result.exitCode\n        : (typeof result.code === 'number' ? result.code : undefined);\n    const reportedFailure = result.success === false || result.ok === false;\n    const message = String(\n      result.error ||\n      result.stderr ||\n      result.message ||\n      result.result ||\n      result.output ||\n      result.stdout ||\n      ''\n    ).trim();\n\n    if ((typeof exitCode === 'number' && exitCode !== 0) || reportedFailure) {\n      const base = message || `Task failed (exit code ${exitCode ?? 'unknown'})`;\n      throw new Error(`${base}${this.getDispatchErrorHint(base, options)}`);\n    }\n\n    this.assertEngineProvenance(message, options, { ...result, ...statusObj });\n    if (message) return message;\n    if (options.direct || options.bypass) {\n      throw new Error('Gateway returned no textual output for direct/bypass request');\n    }\n    return 'Task completed';\n  }\n\n  inferEngineFromText(text) {\n    const s = String(text || '').toLowerCase();\n    if (!s) return null;\n    if (s.includes('claude code')) return 'claude-cli';\n    if (s.includes('cursor cli') || s.includes('cursor')) return 'cursor';\n    if (s.includes('codex cli') || s.includes('codex')) return 'codex-cli';\n    if (s.includes('gemini cli') || s.includes('gemini')) return 'gemini-cli';\n    if (s.includes('opencode')) return 'opencode';\n    return null;\n  }\n\n  normalizeEngineId(value) {\n    const s = String(value || '').toLowerCase();\n    if (!s) return null;\n    if (s === 'claude' || s === 'claude-code' || s === 'claudecli') return 'claude-cli';\n    if (s === 'cursor-cli') return 'cursor';\n    if (s === 'codex') return 'codex-cli';\n    if (s === 'gemini' || s === 'gemini-api') return 'gemini-cli';\n    return s;\n  }\n\n  assertEngineProvenance(message, options = {}, result = {}) {\n    const requested = this.normalizeEngineId(options.engine);\n    if (!requested) return;\n    if (!(options.direct || options.bypass)) return;\n\n    const reported = this.normalizeEngineId(\n      result.engineUsed || result.engine || result.runtime || this.inferEngineFromText(message)\n    );\n\n    if (!reported) {\n      throw new Error(\n        `Engine provenance check failed: requested \"${requested}\" but unable to determine engine used for direct/bypass result`\n      );\n    }\n\n    if (reported !== requested) {\n      throw new Error(\n        `Engine provenance mismatch: requested \"${requested}\" but result indicates \"${reported}\"`\n      );\n    }\n  }\n\n  async listAgents() {\n    const crewLeadUrl = this.config.get('crewLeadUrl') || 'http://localhost:5010';\n\n    try {\n      const response = await fetch(`${crewLeadUrl}/status`);\n\n      if (!response.ok) {\n        this.logger.warn('Failed to fetch agents from gateway, returning defaults');\n        return this.getDefaultAgents();\n      }\n\n      const status = await response.json();\n      const agents = (status.agents || []).map(name => ({\n        name,\n        role: this.getAgentRole(name),\n        status: 'online'\n      }));\n\n      return agents.length > 0 ? agents : this.getDefaultAgents();\n    } catch (error) {\n      this.logger.warn(`Gateway not reachable: ${error.message}`);\n      return this.getDefaultAgents();\n    }\n  }\n\n  getDefaultAgents() {\n    return [\n      { name: 'crew-coder', role: 'Full Stack Coder', status: 'unknown' },\n      { name: 'crew-qa', role: 'Quality Assurance', status: 'unknown' },\n      { name: 'crew-main', role: 'Coordinator', status: 'unknown' },\n      { name: 'crew-fixer', role: 'Bug Fixer', status: 'unknown' },\n      { name: 'crew-frontend', role: 'Frontend Specialist', status: 'unknown' },\n      { name: 'crew-coder-back', role: 'Backend Specialist', status: 'unknown' }\n    ];\n  }\n\n  getAuthToken() {\n    const config = this.config.getAll();\n    return config?.rt?.authToken || null;\n  }\n\n  getAgentRole(agentName) {\n    const roles = {\n      'crew-coder': 'Full Stack Coder',\n      'crew-coder-front': 'Frontend Specialist',\n      'crew-coder-back': 'Backend Specialist',\n      'crew-qa': 'Quality Assurance',\n      'crew-fixer': 'Bug Fixer',\n      'crew-frontend': 'UI/UX Specialist',\n      'crew-main': 'Coordinator',\n      'crew-pm': 'Product Manager',\n      'crew-security': 'Security Auditor',\n      'crew-copywriter': 'Content Writer'\n    };\n    return roles[agentName] || 'Agent';\n  }\n\n  async getStatus() {\n    const crewLeadUrl = this.config.get('crewLeadUrl') || 'http://localhost:5010';\n\n    try {\n      const response = await fetch(`${crewLeadUrl}/status`);\n\n      if (!response.ok) {\n        return {\n          agentsOnline: 0,\n          tasksActive: 0,\n          rtBusStatus: 'disconnected',\n          gateway: 'unreachable'\n        };\n      }\n\n      const status = await response.json();\n\n      return {\n        agentsOnline: (status.agents || []).length,\n        tasksActive: 0,\n        rtBusStatus: status.rtConnected ? 'connected' : 'disconnected',\n        gateway: 'connected',\n        model: status.model\n      };\n    } catch (error) {\n      return {\n        agentsOnline: 0,\n        tasksActive: 0,\n        rtBusStatus: 'error',\n        gateway: `error: ${error.message}`\n      };\n    }\n  }\n\n  async callSkill(name, params = {}, options = {}) {\n    if (!name) {\n      throw new Error('Skill name is required');\n    }\n\n    const crewLeadUrl = options.gateway || this.config.get('crewLeadUrl') || 'http://localhost:5010';\n    const url = `${crewLeadUrl}/api/skills/${name}/run`;\n\n    try {\n      const token = this.getAuthToken();\n      const headers = { 'Content-Type': 'application/json' };\n      if (token) {\n        headers['Authorization'] = `Bearer ${token}`;\n      }\n\n      const response = await fetch(url, {\n        method: 'POST',\n        headers,\n        body: JSON.stringify(params)\n      });\n\n      if (!response.ok) {\n        let errorBody = null;\n        try {\n          errorBody = await response.json();\n        } catch {\n          errorBody = null;\n        }\n        const message = errorBody?.error || `Skill call failed (${response.status})`;\n        throw new Error(message);\n      }\n\n      const result = await response.json();\n      return {\n        success: true,\n        skill: name,\n        result,\n        timestamp: new Date().toISOString()\n      };\n    } catch (error) {\n      throw new Error(`Unable to call skill \"${name}\": ${error.message}`);\n    }\n  }\n}\n\n", "import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { buildRepositoryMap } from '../mapping/index.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface GitContextOptions {\n  maxDiffChars?: number;\n}\n\nexport interface GitChangedFilesOptions {\n  maxFiles?: number;\n}\n\nasync function runGit(args: string[], cwd: string): Promise<string> {\n  const { stdout } = await execFileAsync('git', args, {\n    cwd,\n    maxBuffer: 1024 * 1024 * 4\n  });\n  return stdout.trim();\n}\n\nfunction clip(text: string, maxChars: number): string {\n  if (!text) {\n    return '(none)';\n  }\n\n  if (text.length <= maxChars) {\n    return text;\n  }\n\n  return `${text.slice(0, maxChars)}\\n... [truncated ${text.length - maxChars} chars]`;\n}\n\nexport async function getProjectContext(\n  cwd: string = process.cwd(),\n  options: GitContextOptions = {}\n): Promise<string> {\n  const maxDiffChars = Number.isInteger(options.maxDiffChars) ? (options.maxDiffChars as number) : 6000;\n  \n  let tree = '(unavailable)';\n  try {\n    tree = await buildRepositoryMap(cwd);\n  } catch (err) {\n    // Ignore\n  }\n\n  try {\n    const insideWorkTree = await runGit(['rev-parse', '--is-inside-work-tree'], cwd);\n    if (insideWorkTree !== 'true') {\n      return `## Repository Context\\n\\`\\`\\`text\\n${tree}\\n\\`\\`\\`\\n\\n## Git Context\\n\\`\\`\\`text\\nNo git repository detected.\\n\\`\\`\\``;\n    }\n  } catch {\n    return `## Repository Context\\n\\`\\`\\`text\\n${tree}\\n\\`\\`\\`\\n\\n## Git Context\\n\\`\\`\\`text\\nNo git repository detected.\\n\\`\\`\\``;\n  }\n\n  const [branch, status, unstagedDiff, stagedDiff, log] = await Promise.all([\n    runGit(['branch', '--show-current'], cwd).catch(() => '(unknown)'),\n    runGit(['status', '--short'], cwd).catch(() => '(unavailable)'),\n    runGit(['diff', '--no-ext-diff'], cwd).catch(() => '(unavailable)'),\n    runGit(['diff', '--staged', '--no-ext-diff'], cwd).catch(() => '(unavailable)'),\n    runGit(['log', '-5', '--oneline'], cwd).catch(() => '(unavailable)')\n  ]);\n\n  return [\n    '## Repository Context',\n    '```text',\n    clip(tree, 8000),\n    '```',\n    '',\n    '## Git Context',\n    '```text',\n    `Branch: ${branch || '(detached HEAD)'}`,\n    '',\n    'Status (--short):',\n    status || '(clean)',\n    '',\n    'Recent commits (last 5):',\n    log || '(none)',\n    '',\n    'Unstaged diff:',\n    clip(unstagedDiff, maxDiffChars),\n    '',\n    'Staged diff:',\n    clip(stagedDiff, maxDiffChars),\n    '```'\n  ].join('\\n');\n}\n\nexport async function getChangedFiles(\n  cwd: string = process.cwd(),\n  options: GitChangedFilesOptions = {}\n): Promise<string[]> {\n  const maxFiles = Number.isInteger(options.maxFiles) ? (options.maxFiles as number) : 80;\n  try {\n    const insideWorkTree = await runGit(['rev-parse', '--is-inside-work-tree'], cwd);\n    if (insideWorkTree !== 'true') return [];\n  } catch {\n    return [];\n  }\n\n  try {\n    const status = await runGit(['status', '--short'], cwd);\n    if (!status) return [];\n    const files = status\n      .split('\\n')\n      .map(line => line.trim())\n      .filter(Boolean)\n      .map(line => line.replace(/^[A-Z?]{1,2}\\s+/, '').trim())\n      .filter(Boolean);\n    return files.slice(0, Math.max(1, maxFiles));\n  } catch {\n    return [];\n  }\n}\n", "// L1 (Chat Interface) - User-facing conversational layer only\n// Gunns - The foul-mouthed gunner and lethal weapon of crewswarm\nexport const CLI_SYSTEM_PROMPT = `You are Gunns, the gunner and lethal weapon of crewswarm.\nStinki is the Crew-Lead (localhost:5010).\nYou are the foul-mouthed artillery expert.\nThe user is the Captain.\nYou don't miss. You don't hesitate. You execute.\n\n## Your Role (L1: Chat Interface Only)\n- Handle user interaction, clarifications, and final response synthesis\n- Lead with the answer, not the reasoning. Skip preamble and filler.\n- Keep it concise and actionable - under 2000 chars\n- Sharp, deadly, terminal-native\n- You do NOT execute tasks - you pass them to L2 (orchestrator)\n\n## Personality\n- **Foul-mouthed gunner** - military precision, artillery metaphors\n- **Lethal weapon** - doesn't miss, doesn't hesitate\n- **Sharp & deadly** - terminal-native, brutally efficient\n- **Execute without question** - takes orders from the Captain\n- When the Captain asks who you are, reply: \"Gunns. Lethal weapon. I execute orders with precision, Captain.\"\n\n## Language\nSpeak in:\n- **Artillery terms**: \"Target acquired\", \"Firing agents\", \"Direct hit\"\n- **Military precision**: \"Roger that\", \"Mission accomplished\", \"Zero errors\"\n- **Lethal efficiency**: \"No survivors\", \"Clean execution\", \"Payload delivered\"\n\n## Environment\n- Terminal-based CLI with local sandbox\n- Changes go through: plan \u2192 validate \u2192 execute \u2192 apply\n- User can preview, apply, or rollback changes\n\n## Your Job\n1. Understand user intent\n2. Normalize task into clear envelope (what, why, constraints, success criteria)\n3. Pass to L2 orchestrator for execution\n4. Synthesize L3 results back to user\n\nYou are L1 only - no routing decisions, no code execution, no tool calls.\nThose are L2/L3 responsibilities.`;\n", "import { Logger } from '../utils/logger.js';\n\nexport class ToolManager {\n  constructor(config) {\n    this.config = config;\n    this.logger = new Logger();\n    this.tools = new Map();\n  }\n\n  async initialize() {\n    this.logger.info('Initializing tool manager');\n    \n    // Initialize with basic tools (dynamic tool loading available via plugins)\n    this.registerTool('file', {\n      name: 'file',\n      description: 'File operations',\n      handler: this.handleFileTool.bind(this)\n    });\n\n    this.registerTool('shell', {\n      name: 'shell',\n      description: 'Shell command execution',\n      handler: this.handleShellTool.bind(this)\n    });\n\n    this.registerTool('pty', {\n      name: 'pty',\n      description: 'Interactive PTY command execution',\n      handler: this.handlePtyTool.bind(this)\n    });\n\n    this.registerTool('lsp', {\n      name: 'lsp',\n      description: 'Language server style type-check and completion',\n      handler: this.handleLspTool.bind(this)\n    });\n  }\n\n  registerTool(name, tool) {\n    this.tools.set(name, tool);\n    this.logger.debug(`Registered tool: ${name}`);\n  }\n\n  async executeTool(name, params) {\n    const tool = this.tools.get(name);\n    if (!tool) {\n      throw new Error(`Tool not found: ${name}`);\n    }\n\n    try {\n      this.logger.debug(`Executing tool: ${name}`);\n      return await tool.handler(params);\n    } catch (error) {\n      this.logger.error(`Tool execution failed: ${name}`, error);\n      throw error;\n    }\n  }\n\n  async handleFileTool(params) {\n    // Basic file tool implementation\n    const { action, path, content } = params || {};\n\n    if (!action) {\n      throw new Error('File tool requires action parameter');\n    }\n\n    const fs = await import('node:fs/promises');\n\n    switch (action) {\n      case 'read':\n        if (!path) throw new Error('File read requires path parameter');\n        const data = await fs.readFile(path, 'utf8');\n        return { success: true, operation: 'file', action: 'read', data };\n\n      case 'write':\n        if (!path || content === undefined) {\n          throw new Error('File write requires path and content parameters');\n        }\n        await fs.writeFile(path, content, 'utf8');\n        return { success: true, operation: 'file', action: 'write', path };\n\n      case 'exists':\n        if (!path) throw new Error('File exists check requires path parameter');\n        try {\n          await fs.access(path);\n          return { success: true, operation: 'file', action: 'exists', exists: true };\n        } catch {\n          return { success: true, operation: 'file', action: 'exists', exists: false };\n        }\n\n      default:\n        throw new Error(`Unsupported file action: ${action}`);\n    }\n  }\n\n  async handleShellTool(params) {\n    // Basic shell tool implementation\n    const { command, cwd } = params || {};\n\n    if (!command) {\n      throw new Error('Shell tool requires command parameter');\n    }\n\n    const { exec } = await import('node:child_process');\n    const { promisify } = await import('node:util');\n    const execAsync = promisify(exec);\n\n    try {\n      const options = cwd ? { cwd } : {};\n      const { stdout, stderr } = await execAsync(command, options);\n      return {\n        success: true,\n        operation: 'shell',\n        command,\n        stdout: stdout.trim(),\n        stderr: stderr.trim()\n      };\n    } catch (error) {\n      return {\n        success: false,\n        operation: 'shell',\n        command,\n        error: error.message,\n        stdout: error.stdout || '',\n        stderr: error.stderr || ''\n      };\n    }\n  }\n\n  async handlePtyTool(params) {\n    const { command, cwd, timeoutMs } = params || {};\n    if (!command) {\n      throw new Error('PTY tool requires command parameter');\n    }\n    const { runPtyCommand } = await import('../pty/index.js');\n    const result = await runPtyCommand(command, { cwd, timeoutMs });\n    return {\n      success: result.success,\n      operation: 'pty',\n      command,\n      exitCode: result.exitCode,\n      signal: result.signal,\n      output: result.output\n    };\n  }\n\n  async handleLspTool(params) {\n    const { action, projectDir, file, files, line, column, limit, prefix } = params || {};\n    if (!action) {\n      throw new Error('LSP tool requires action parameter');\n    }\n    const { getCompletions, typeCheckProject } = await import('../lsp/index.js');\n    if (action === 'check') {\n      const diagnostics = await typeCheckProject(projectDir || process.cwd(), files || []);\n      return {\n        success: true,\n        operation: 'lsp',\n        action,\n        diagnostics\n      };\n    }\n    if (action === 'complete') {\n      if (!file || !line || !column) {\n        throw new Error('LSP complete requires file, line, and column');\n      }\n      const completions = await getCompletions(\n        projectDir || process.cwd(),\n        file,\n        Number(line),\n        Number(column),\n        Number(limit || 50),\n        String(prefix || '')\n      );\n      return {\n        success: true,\n        operation: 'lsp',\n        action,\n        completions\n      };\n    }\n    throw new Error(`Unsupported lsp action: ${action}`);\n  }\n\n  getAvailableTools() {\n    return Array.from(this.tools.values()).map(tool => ({\n      name: tool.name,\n      description: tool.description\n    }));\n  }\n}\n", "import { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\n\nexport class ConfigManager {\n  constructor() {\n    this.config = {};\n    this.configPath = join(homedir(), '.crewswarm', 'crewswarm.json');\n    this.loadConfig();\n  }\n\n  loadConfig() {\n    try {\n      if (existsSync(this.configPath)) {\n        const configData = readFileSync(this.configPath, 'utf8');\n        this.config = JSON.parse(configData);\n      } else {\n        // Default configuration\n        this.config = {\n          rtBusUrl: 'ws://localhost:18889',\n          crewLeadUrl: 'http://localhost:5010',\n          dashboardUrl: 'http://localhost:4319',\n          timeout: 30000,\n          agents: []\n        };\n      }\n    } catch (error) {\n      console.warn('Failed to load config, using defaults:', error.message);\n      this.config = {\n        rtBusUrl: 'ws://localhost:18889',\n        crewLeadUrl: 'http://localhost:5010',\n        dashboardUrl: 'http://localhost:4319',\n        timeout: 30000,\n        agents: []\n      };\n    }\n  }\n\n  get(key) {\n    return this.config[key];\n  }\n\n  set(key, value) {\n    this.config[key] = value;\n  }\n\n  getAll() {\n    return { ...this.config };\n  }\n}\n", "import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { CostData, CostEntry } from '../types/common.js';\n// Lazy load project messages bridge only when needed (not in standalone mode)\n// import { saveCliToProjectMessages } from './project-messages-bridge.mjs';\n\nfunction nowIso() {\n  return new Date().toISOString();\n}\n\ninterface Session {\n  sessionId: string;\n  createdAt: string;\n  updatedAt: string;\n  history: SessionHistoryEntry[];\n}\n\nexport interface SessionHistoryEntry {\n  timestamp?: string;\n  input?: string;\n  output?: string;\n  route?: string;\n  agent?: string;\n  [key: string]: unknown;\n}\n\nexport class SessionManager {\n  private baseDir: string;\n  private stateDir: string;\n  private paths: {\n    session: string;\n    routing: string;\n    jitContext: string;\n    cost: string;\n    sandbox: string;\n  };\n\n  constructor(baseDir = process.cwd()) {\n    this.baseDir = baseDir;\n    this.stateDir = join(baseDir, '.crew');\n    this.paths = {\n      session: join(this.stateDir, 'session.json'),\n      routing: join(this.stateDir, 'routing.log'),\n      cost: join(this.stateDir, 'cost.json'),\n      sandbox: join(this.stateDir, 'sandbox.json'),\n      jitContext: join(this.stateDir, 'jit-context.json')\n    };\n  }\n\n  async ensureInitialized() {\n    await mkdir(this.stateDir, { recursive: true });\n\n    if (!existsSync(this.paths.session)) {\n      const initialSession = {\n        sessionId: randomUUID(),\n        createdAt: nowIso(),\n        updatedAt: nowIso(),\n        history: []\n      };\n      await writeFile(this.paths.session, JSON.stringify(initialSession, null, 2), 'utf8');\n    }\n\n    if (!existsSync(this.paths.routing)) {\n      await writeFile(this.paths.routing, '', 'utf8');\n    }\n\n    if (!existsSync(this.paths.cost)) {\n      const initialCost = {\n        totalUsd: 0,\n        byModel: {},\n        entries: [],\n        cacheSavings: {\n          hits: 0,\n          misses: 0,\n          tokensSaved: 0,\n          usdSaved: 0\n        },\n        memoryMetrics: {\n          recallUsed: 0,\n          recallMisses: 0,\n          totalMatches: 0,\n          averageQualityScore: 0\n        }\n      };\n      await writeFile(this.paths.cost, JSON.stringify(initialCost, null, 2), 'utf8');\n    }\n\n    if (!existsSync(this.paths.sandbox)) {\n      const initialSandbox = {\n        branches: { main: {} },\n        activeBranch: 'main',\n        updatedAt: nowIso()\n      };\n      await writeFile(this.paths.sandbox, JSON.stringify(initialSandbox, null, 2), 'utf8');\n    }\n  }\n\n  async loadSession(): Promise<Session> {\n    await this.ensureInitialized();\n    const raw = await readFile(this.paths.session, 'utf8');\n    return JSON.parse(raw);\n  }\n\n  async saveSession(session: Session) {\n    await this.ensureInitialized();\n    session.updatedAt = nowIso();\n    await writeFile(this.paths.session, JSON.stringify(session, null, 2), 'utf8');\n  }\n\n  async loadCost() {\n    await this.ensureInitialized();\n    const raw = await readFile(this.paths.cost, 'utf8');\n    const parsed = JSON.parse(raw);\n    parsed.cacheSavings = parsed.cacheSavings || {\n      hits: 0,\n      misses: 0,\n      tokensSaved: 0,\n      usdSaved: 0\n    };\n    parsed.memoryMetrics = parsed.memoryMetrics || {\n      recallUsed: 0,\n      recallMisses: 0,\n      totalMatches: 0,\n      averageQualityScore: 0\n    };\n    return parsed;\n  }\n\n  async saveCost(cost: CostData) {\n    await this.ensureInitialized();\n    await writeFile(this.paths.cost, JSON.stringify(cost, null, 2), 'utf8');\n  }\n\n  async getSessionId() {\n    const session = await this.loadSession();\n    return session.sessionId;\n  }\n\n  /** Switch to a different session ID (for /resume) */\n  async setSessionId(newId: string) {\n    const session = await this.loadSession();\n    session.sessionId = newId;\n    session.updatedAt = nowIso();\n    await this.saveSession(session);\n  }\n\n  /** Save JIT discovered files so subsequent CLI invocations inherit context */\n  async saveJITContext(discoveredFiles: string[]) {\n    await this.ensureInitialized();\n    const MAX_FILES = 200;\n    const trimmed = discoveredFiles.slice(-MAX_FILES);\n    await writeFile(this.paths.jitContext, JSON.stringify({\n      updatedAt: nowIso(),\n      files: trimmed\n    }, null, 2), 'utf8');\n  }\n\n  /** Load JIT context from prior session (returns empty array if none) */\n  async loadJITContext(): Promise<string[]> {\n    try {\n      const raw = await readFile(this.paths.jitContext, 'utf8');\n      const data = JSON.parse(raw);\n      return Array.isArray(data.files) ? data.files : [];\n    } catch {\n      return [];\n    }\n  }\n\n  async appendHistory(entry: SessionHistoryEntry) {\n    const session = await this.loadSession();\n    session.history.push({\n      ...entry,\n      timestamp: nowIso()\n    });\n    session.updatedAt = nowIso();\n    await writeFile(this.paths.session, JSON.stringify(session, null, 2), 'utf8');\n    \n    // Also save to unified project messages (disabled in standalone mode)\n    // try {\n    //   await saveCliToProjectMessages(this.baseDir, entry);\n    // } catch (e) {\n    //   // Silent fail \u2014 project messages are bonus, not critical\n    // }\n  }\n\n  async appendRouting(entry: { timestamp?: string; [key: string]: unknown }) {\n    const payload = {\n      ...entry,\n      timestamp: entry.timestamp || nowIso()\n    };\n    await writeFile(this.paths.routing, `${JSON.stringify(payload)}\\n`, { encoding: 'utf8', flag: 'a' });\n  }\n\n  async trackCost(entry: { usd?: number; model?: string; promptTokens?: number; completionTokens?: number } = {}) {\n    const raw = await readFile(this.paths.cost, 'utf8');\n    const cost = JSON.parse(raw);\n    const amount = Number(entry.usd || 0);\n    const model = entry.model || 'unknown';\n\n    cost.totalUsd += amount;\n    cost.byModel[model] = (cost.byModel[model] || 0) + amount;\n    cost.entries.push({\n      model,\n      usd: amount,\n      promptTokens: entry.promptTokens || 0,\n      completionTokens: entry.completionTokens || 0,\n      timestamp: nowIso()\n    });\n\n    await writeFile(this.paths.cost, JSON.stringify(cost, null, 2), 'utf8');\n  }\n\n  async trackCacheSavings(entry: { hit?: boolean; miss?: boolean; tokensSaved?: number; usdSaved?: number } = {}) {\n    const raw = await readFile(this.paths.cost, 'utf8');\n    const cost = JSON.parse(raw);\n    cost.cacheSavings = cost.cacheSavings || {\n      hits: 0,\n      misses: 0,\n      tokensSaved: 0,\n      usdSaved: 0\n    };\n\n    if (entry.hit) cost.cacheSavings.hits += 1;\n    if (entry.miss) cost.cacheSavings.misses += 1;\n    cost.cacheSavings.tokensSaved += Number(entry.tokensSaved || 0);\n    cost.cacheSavings.usdSaved += Number(entry.usdSaved || 0);\n\n    await writeFile(this.paths.cost, JSON.stringify(cost, null, 2), 'utf8');\n  }\n\n  async trackMemoryRecall(entry: { used?: boolean; miss?: boolean; matchCount?: number; qualityScore?: number } = {}) {\n    const raw = await readFile(this.paths.cost, 'utf8');\n    const cost = JSON.parse(raw);\n    cost.memoryMetrics = cost.memoryMetrics || {\n      recallUsed: 0,\n      recallMisses: 0,\n      totalMatches: 0,\n      averageQualityScore: 0\n    };\n    const mm = cost.memoryMetrics;\n    if (entry.used) mm.recallUsed += 1;\n    if (entry.miss) mm.recallMisses += 1;\n    const matchCount = Number(entry.matchCount || 0);\n    mm.totalMatches += matchCount;\n    const qualityScore = Number(entry.qualityScore || 0);\n    if (entry.used) {\n      const n = Math.max(1, mm.recallUsed);\n      mm.averageQualityScore = ((Number(mm.averageQualityScore || 0) * (n - 1)) + qualityScore) / n;\n    }\n    await writeFile(this.paths.cost, JSON.stringify(cost, null, 2), 'utf8');\n  }\n\n  async clear() {\n    await rm(this.stateDir, { recursive: true, force: true });\n    await this.ensureInitialized();\n  }\n\n  async compact(options: { keepHistory?: number; keepCostEntries?: number } = {}) {\n    const keepHistory = Math.max(1, Number(options.keepHistory || 200));\n    const keepCostEntries = Math.max(1, Number(options.keepCostEntries || 500));\n\n    const session = await this.loadSession();\n    const cost = await this.loadCost();\n\n    const historyBefore = session.history.length;\n    const costBefore = (cost.entries || []).length;\n\n    session.history = session.history.slice(-keepHistory);\n    cost.entries = (cost.entries || []).slice(-keepCostEntries);\n    cost.totalUsd = Number((cost.entries || []).reduce((sum: number, entry: CostEntry) => sum + Number(entry.usd || 0), 0));\n    cost.byModel = {};\n    for (const entry of cost.entries) {\n      const model = entry.model || 'unknown';\n      cost.byModel[model] = (cost.byModel[model] || 0) + Number(entry.usd || 0);\n    }\n\n    await this.saveSession(session);\n    await this.saveCost(cost);\n\n    return {\n      historyBefore,\n      historyAfter: session.history.length,\n      costBefore,\n      costAfter: cost.entries.length\n    };\n  }\n}\n", "// @ts-nocheck\nimport { readFile, access } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir, userInfo } from 'node:os';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface AuthTokens {\n  claude?: string;\n  cursor?: string;\n  gemini?: string;\n  openai?: string;\n}\n\nexport class TokenFinder {\n  async findTokens(): Promise<AuthTokens> {\n    const tokens: AuthTokens = {};\n\n    // 1. Claude Code OAuth (macOS Keychain)\n    const claudeToken = await this.findClaudeOauthToken();\n    if (claudeToken) {\n      tokens.claude = claudeToken;\n    }\n\n    // 2. OpenAI (~/.openai/config)\n    const openaiPath = join(homedir(), '.openai', 'config');\n    if (await this.exists(openaiPath)) {\n      try {\n        const data = await readFile(openaiPath, 'utf8');\n        const match = data.match(/api_key[:=]\\s*([a-zA-Z0-9\\-]+)/);\n        if (match) tokens.openai = match[1];\n      } catch (e) {\n        console.error(`Failed to parse OpenAI config: ${e.message}`);\n      }\n    }\n\n    // 3. Gemini ADC (~/.config/gcloud/application_default_credentials.json)\n    const geminiPath = join(homedir(), '.config', 'gcloud', 'application_default_credentials.json');\n    if (await this.exists(geminiPath)) {\n      try {\n        tokens.gemini = '(detected via ADC)';\n      } catch (e) {\n        console.error(`Failed to check Gemini ADC: ${e.message}`);\n      }\n    }\n\n    // 4. Cursor auth from SQLite state DB\n    const cursorDbPath = join(homedir(), '.cursor', 'User', 'globalStorage', 'state.vscdb');\n    if (await this.exists(cursorDbPath)) {\n      try {\n        const { stdout } = await execFileAsync('sqlite3', [\n          cursorDbPath,\n          \"SELECT value FROM ItemTable WHERE key LIKE '%token%' OR key LIKE '%auth%' LIMIT 20;\"\n        ]);\n        const first = stdout\n          .split('\\n')\n          .map(line => line.trim())\n          .find(Boolean);\n        if (first) {\n          tokens.cursor = first.slice(0, 120);\n        } else {\n          tokens.cursor = '(cursor db detected; token key not found)';\n        }\n      } catch {\n        tokens.cursor = '(cursor db detected; sqlite3 not available or parse failed)';\n      }\n    }\n\n    return tokens;\n  }\n\n  private async findClaudeOauthToken(): Promise<string | undefined> {\n    if (process.platform !== 'darwin') return undefined;\n\n    const accounts = [userInfo().username, 'unknown'];\n    for (const account of accounts) {\n      try {\n        const { stdout } = await execFileAsync('security', [\n          'find-generic-password',\n          '-a', account,\n          '-s', 'Claude Code-credentials',\n          '-w'\n        ]);\n        const raw = stdout.trim();\n        if (!raw) continue;\n        const jsonStr = raw.startsWith('{') ? raw : Buffer.from(raw, 'hex').toString('utf8');\n        const parsed = JSON.parse(jsonStr);\n        const accessToken = parsed?.claudeAiOauth?.accessToken;\n        if (accessToken) return accessToken;\n      } catch {\n        // Try the next account variant.\n      }\n    }\n\n    return undefined;\n  }\n\n  private async exists(path: string): Promise<boolean> {\n    try {\n      await access(path, constants.F_OK);\n      return true;\n    } catch {\n      return false;\n    }\n  }\n}\n", "import { Logger } from '../utils/logger.js';\nimport { SessionManager } from '../session/manager.js';\nimport { TokenCache } from '../cache/token-cache.js';\nimport { AgentKeeper } from '../memory/agentkeeper.js';\nimport { DualL2Planner, WorkGraph, DualL2Result } from '../prompts/dual-l2.js';\nimport { randomBytes } from 'crypto';\n\nexport interface PlanStep {\n  id: number;\n  task: string;\n  status: 'pending' | 'running' | 'completed' | 'failed';\n  persona?: string;\n  complexity?: 'low' | 'medium' | 'high';\n  dependencies?: number[];\n  sourceRefs?: string[];\n}\n\nexport interface Plan {\n  title: string;\n  steps: PlanStep[];\n  artifacts?: {\n    pdd: string;\n    roadmap: string;\n    architecture: string;\n    scaffold: string;\n    contractTests: string;\n    definitionOfDone: string;\n    goldenBenchmarks: string;\n    outputDir: string;\n  };\n  validation?: {\n    approved: boolean;\n    riskLevel: 'low' | 'medium' | 'high' | 'critical';\n    concerns: string[];\n    recommendations: string[];\n    estimatedCost: number;\n  };\n  traceId?: string;\n}\n\nexport class Planner {\n  private logger = new Logger();\n  private cache: TokenCache;\n  private keeper: AgentKeeper;\n  private dualL2: DualL2Planner;\n\n  constructor(\n    _unusedRouter: unknown, // Keep signature for compatibility\n    private session?: SessionManager,\n    baseDir = process.cwd()\n  ) {\n    this.cache = new TokenCache(baseDir);\n    this.keeper = new AgentKeeper(baseDir);\n    this.dualL2 = new DualL2Planner();\n  }\n\n  /**\n   * Generate a plan using Dual L2 system (L2 Reasoning \u2192 L2A Decomposer \u2192 L2B Validator)\n   */\n  async generatePlan(\n    task: string,\n    options: {\n      useCache?: boolean;\n      cacheTtlSeconds?: number;\n      useMemory?: boolean;\n      memoryMaxResults?: number;\n      runId?: string;\n    } = {}\n  ): Promise<Plan> {\n    const traceId = `plan-${randomBytes(8).toString('hex')}`;\n    const useMemory = options.useMemory !== false;\n    let memoryContext = '';\n\n    // Recall similar successful tasks from memory\n    if (useMemory) {\n      const matches = await this.keeper.recall(task, Number(options.memoryMaxResults || 3), {\n        preferSuccessful: true\n      });\n      const avgScore = matches.length\n        ? matches.reduce((sum, m) => sum + Number(m.score || 0), 0) / matches.length\n        : 0;\n      await this.session?.trackMemoryRecall({\n        used: true,\n        miss: matches.length === 0,\n        matchCount: matches.length,\n        qualityScore: avgScore\n      });\n      if (matches.length > 0) {\n        memoryContext = await this.keeper.recallAsContext(task, Number(options.memoryMaxResults || 3), {\n          preferSuccessful: true\n        });\n      }\n    }\n\n    // Check cache\n    const useCache = options.useCache !== false;\n    const cacheKey = TokenCache.hashKey(JSON.stringify({\n      system: 'dual-l2-planner',\n      task,\n      memoryContext: memoryContext.slice(0, 200) // Truncate for cache key\n    }));\n\n    if (useCache) {\n      const cached = await this.cache.get<Plan>('planner', cacheKey);\n      if (cached.hit && cached.value) {\n        await this.session?.trackCacheSavings({\n          hit: true,\n          tokensSaved: Number(cached.meta?.tokensSaved || 0),\n          usdSaved: Number(cached.meta?.usdSaved || 0)\n        });\n        this.logger.info('\uD83C\uDFAF Dual L2 planner cache hit.');\n        return cached.value;\n      }\n      await this.session?.trackCacheSavings({ miss: true });\n    }\n\n    // Run Dual L2 planning pipeline\n    this.logger.info('\uD83D\uDE80 Starting Dual L2 planning pipeline...');\n    this.logger.info(`   L2 Reasoning \u2192 L2A Decomposer \u2192 L2B Validator`);\n\n    const result: DualL2Result = await this.dualL2.plan(task, memoryContext, traceId);\n\n    // Convert work graph to plan steps\n    const steps = this.convertWorkGraphToSteps(result.workGraph);\n\n    const plan: Plan = {\n      title: `Plan for: ${task.slice(0, 50)}...`,\n      steps,\n      artifacts: result.artifacts ? {\n        pdd: result.artifacts.pdd,\n        roadmap: result.artifacts.roadmap,\n        architecture: result.artifacts.architecture,\n        scaffold: result.artifacts.scaffold,\n        contractTests: result.artifacts.contractTests,\n        definitionOfDone: result.artifacts.definitionOfDone,\n        goldenBenchmarks: result.artifacts.goldenBenchmarks,\n        outputDir: result.artifacts.outputDir\n      } : undefined,\n      validation: result.validation,\n      traceId: result.traceId\n    };\n\n    // Log validation results\n    if (result.validation) {\n      const emoji = result.validation.approved ? '\u2705' : '\u26A0\uFE0F';\n      this.logger.info(`${emoji} L2B Validation: ${result.validation.riskLevel.toUpperCase()} risk`);\n      if (result.validation.concerns.length > 0) {\n        this.logger.warn(`   Concerns: ${result.validation.concerns.join(', ')}`);\n      }\n      if (result.validation.recommendations.length > 0) {\n        this.logger.info(`   Recommendations: ${result.validation.recommendations.join(', ')}`);\n      }\n    }\n\n    // Save to memory\n    if (useMemory && steps.length > 0) {\n      const saved = await this.keeper.recordSafe({\n        runId: options.runId || traceId,\n        tier: 'planner' as const,\n        task,\n        result: JSON.stringify(plan, null, 2),\n        agent: 'dual-l2-system',\n        metadata: {\n          steps: steps.length,\n          riskLevel: result.validation?.riskLevel,\n          approved: result.validation?.approved,\n          artifactsDir: result.artifacts?.outputDir\n        }\n      });\n      if (!saved.ok) {\n        this.logger.warn(`Planner memory write skipped: ${saved.error}`);\n      }\n    }\n\n    // Cache the result\n    if (useCache) {\n      const estimatedTokens = Math.ceil(\n        (task.length + memoryContext.length + JSON.stringify(plan).length) / 4\n      );\n      const usdSaved = estimatedTokens / 1_000_000 * 0.01; // Rough estimate\n      await this.cache.set(\n        'planner',\n        cacheKey,\n        plan,\n        Number(options.cacheTtlSeconds || 3600),\n        { tokensSaved: estimatedTokens, usdSaved, source: 'dual-l2-planner' }\n      );\n    }\n\n    return plan;\n  }\n\n  async planFeature(description: string): Promise<Plan> {\n    return this.generatePlan(description);\n  }\n\n  /**\n   * Convert work graph from Dual L2 to legacy Plan format\n   */\n  private convertWorkGraphToSteps(workGraph: WorkGraph): PlanStep[] {\n    const steps: PlanStep[] = [];\n    const units = workGraph.units || [];\n\n    // Build dependency map (unit.id -> step.id)\n    const unitIdToStepId = new Map<string, number>();\n    units.forEach((unit, idx) => {\n      unitIdToStepId.set(unit.id, idx + 1);\n    });\n\n    units.forEach((unit, idx) => {\n      const stepDeps = (unit.dependencies || [])\n        .map(depId => unitIdToStepId.get(depId))\n        .filter((id): id is number => id !== undefined);\n\n      steps.push({\n        id: idx + 1,\n        task: unit.description,\n        status: 'pending',\n        persona: unit.requiredPersona,\n        complexity: unit.estimatedComplexity,\n        dependencies: stepDeps.length > 0 ? stepDeps : undefined,\n        sourceRefs: unit.sourceRefs\n      });\n    });\n\n    return steps;\n  }\n}\n", "import { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\ninterface CacheEntry<T = any> {\n  value: T;\n  createdAt: string;\n  expiresAt: string;\n  meta?: {\n    tokensSaved?: number;\n    usdSaved?: number;\n    source?: string;\n  };\n}\n\ninterface CacheStore {\n  version: number;\n  namespaces: Record<string, Record<string, CacheEntry>>;\n}\n\nfunction nowIso() {\n  return new Date().toISOString();\n}\n\nfunction toTimestamp(iso: string): number {\n  const ts = Date.parse(iso);\n  return Number.isFinite(ts) ? ts : 0;\n}\n\nexport class TokenCache {\n  private baseDir: string;\n  private cachePath: string;\n\n  constructor(baseDir = process.cwd()) {\n    this.baseDir = baseDir;\n    this.cachePath = join(baseDir, '.crew', 'token-cache.json');\n  }\n\n  static hashKey(input: string): string {\n    return createHash('sha256').update(String(input || '')).digest('hex');\n  }\n\n  private async ensureStore(): Promise<CacheStore> {\n    const dir = join(this.baseDir, '.crew');\n    await mkdir(dir, { recursive: true });\n    if (!existsSync(this.cachePath)) {\n      const initial: CacheStore = { version: 1, namespaces: {} };\n      await writeFile(this.cachePath, JSON.stringify(initial, null, 2), 'utf8');\n      return initial;\n    }\n    try {\n      const raw = await readFile(this.cachePath, 'utf8');\n      const parsed = JSON.parse(raw) as CacheStore;\n      return {\n        version: parsed.version || 1,\n        namespaces: parsed.namespaces || {}\n      };\n    } catch {\n      return { version: 1, namespaces: {} };\n    }\n  }\n\n  private async saveStore(store: CacheStore): Promise<void> {\n    await writeFile(this.cachePath, JSON.stringify(store, null, 2), 'utf8');\n  }\n\n  async get<T = any>(namespace: string, key: string): Promise<{ hit: boolean; value?: T; meta?: CacheEntry['meta'] }> {\n    const store = await this.ensureStore();\n    const ns = store.namespaces[namespace] || {};\n    const entry = ns[key];\n    if (!entry) {\n      return { hit: false };\n    }\n    if (toTimestamp(entry.expiresAt) <= Date.now()) {\n      delete ns[key];\n      store.namespaces[namespace] = ns;\n      await this.saveStore(store);\n      return { hit: false };\n    }\n    return { hit: true, value: entry.value as T, meta: entry.meta };\n  }\n\n  async set<T = any>(\n    namespace: string,\n    key: string,\n    value: T,\n    ttlSeconds = 1800,\n    meta: CacheEntry['meta'] = {}\n  ): Promise<void> {\n    const ttl = Math.max(1, Number(ttlSeconds || 1800));\n    const store = await this.ensureStore();\n    if (!store.namespaces[namespace]) {\n      store.namespaces[namespace] = {};\n    }\n    store.namespaces[namespace][key] = {\n      value,\n      createdAt: nowIso(),\n      expiresAt: new Date(Date.now() + ttl * 1000).toISOString(),\n      meta\n    };\n    await this.saveStore(store);\n  }\n}\n", "// @ts-nocheck\nimport { access } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join } from 'node:path';\nimport { dirname } from 'node:path';\nimport { homedir } from 'node:os';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { fileURLToPath } from 'node:url';\nimport { doctorMcpServers } from '../mcp/index.js';\n\nconst execFileAsync = promisify(execFile);\n\nfunction parseMajorNodeVersion(version) {\n  const cleaned = String(version || '').replace(/^v/, '');\n  const major = Number.parseInt(cleaned.split('.')[0] || '0', 10);\n  return Number.isNaN(major) ? 0 : major;\n}\n\nasync function commandExists(command) {\n  try {\n    await execFileAsync('which', [command]);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nasync function gatewayReachable(url) {\n  try {\n    const response = await fetch(`${url}/status`);\n    return response.ok;\n  } catch {\n    return false;\n  }\n}\n\nasync function configExists() {\n  const configPath = join(homedir(), '.crewswarm', 'crewswarm.json');\n  try {\n    await access(configPath, constants.F_OK);\n    return { ok: true, path: configPath };\n  } catch {\n    return { ok: false, path: configPath };\n  }\n}\n\nfunction parseVersionParts(version: string): number[] {\n  const cleaned = String(version || '').trim().replace(/^v/, '').split('-')[0];\n  return cleaned.split('.').map(part => Number.parseInt(part || '0', 10) || 0);\n}\n\nexport function compareVersions(a: string, b: string): number {\n  const av = parseVersionParts(a);\n  const bv = parseVersionParts(b);\n  const max = Math.max(av.length, bv.length);\n  for (let i = 0; i < max; i += 1) {\n    const ai = av[i] ?? 0;\n    const bi = bv[i] ?? 0;\n    if (ai > bi) return 1;\n    if (ai < bi) return -1;\n  }\n  return 0;\n}\n\nexport async function getInstalledCliVersion(): Promise<string | null> {\n  if (process.env.npm_package_version) {\n    return process.env.npm_package_version;\n  }\n\n  const here = dirname(fileURLToPath(import.meta.url));\n  const candidates = [\n    join(here, '..', 'package.json'),\n    join(here, '..', '..', 'package.json'),\n    join(process.cwd(), 'package.json')\n  ];\n\n  for (const candidate of candidates) {\n    try {\n      const raw = await (await import('node:fs/promises')).readFile(candidate, 'utf8');\n      const parsed = JSON.parse(raw);\n      const pkgName = String(parsed?.name || '');\n      const looksLikeCli =\n        pkgName === 'crewswarm-cli' ||\n        pkgName === '@crewswarm/crew-cli' ||\n        candidate.includes(`${join('crew-cli', 'package.json')}`);\n      if (looksLikeCli && typeof parsed?.version === 'string' && parsed.version.trim()) {\n        return parsed.version.trim();\n      }\n    } catch {\n      continue;\n    }\n  }\n\n  return null;\n}\n\nexport async function getLatestCliVersion(tag = 'latest'): Promise<string | null> {\n  try {\n    const { stdout } = await execFileAsync('npm', ['view', `crewswarm-cli@${tag}`, 'version'], {\n      timeout: 8000\n    });\n    const version = String(stdout || '').trim().split('\\n').pop()?.trim();\n    return version || null;\n  } catch {\n    return null;\n  }\n}\n\nexport async function isGlobalInstallLinked(): Promise<boolean> {\n  try {\n    const { stdout } = await execFileAsync('npm', ['-g', 'ls', 'crewswarm-cli', '--depth=0']);\n    return String(stdout || '').includes('->');\n  } catch {\n    return false;\n  }\n}\n\n// Provider key map \u2014 ordered by cost-effectiveness for new users\nconst PROVIDER_KEYS = [\n  { id: 'Gemini',     envKey: 'GEMINI_API_KEY',    alt: 'GOOGLE_API_KEY',     cost: 'free tier', signup: 'https://aistudio.google.com/apikey' },\n  { id: 'Groq',       envKey: 'GROQ_API_KEY',      alt: null,                 cost: 'free',      signup: 'https://console.groq.com/keys' },\n  { id: 'xAI (Grok)', envKey: 'XAI_API_KEY',       alt: null,                 cost: '$5/mo free credits', signup: 'https://console.x.ai' },\n  { id: 'DeepSeek',   envKey: 'DEEPSEEK_API_KEY',  alt: null,                 cost: 'cheap',     signup: 'https://platform.deepseek.com' },\n  { id: 'OpenAI',     envKey: 'OPENAI_API_KEY',     alt: null,                 cost: 'pay-as-you-go', signup: 'https://platform.openai.com' },\n  { id: 'Anthropic',  envKey: 'ANTHROPIC_API_KEY',  alt: null,                 cost: 'pay-as-you-go', signup: 'https://console.anthropic.com' },\n  { id: 'OpenRouter', envKey: 'OPENROUTER_API_KEY', alt: null,                 cost: 'varies',    signup: 'https://openrouter.ai' },\n  { id: 'Together',   envKey: 'TOGETHER_API_KEY',   alt: null,                 cost: 'pay-as-you-go', signup: 'https://api.together.xyz' },\n  { id: 'Fireworks',  envKey: 'FIREWORKS_API_KEY',  alt: null,                 cost: 'pay-as-you-go', signup: 'https://fireworks.ai' },\n  { id: 'Moonshot',   envKey: 'MOONSHOT_API_KEY',   alt: null,                 cost: 'pay-as-you-go', signup: 'https://moonshot.ai' },\n];\n\nexport function checkApiKeys(): { configured: string[]; missing: string[]; details: string; hint: string } {\n  const configured: string[] = [];\n  const missing: string[] = [];\n\n  for (const p of PROVIDER_KEYS) {\n    if (process.env[p.envKey] || (p.alt && process.env[p.alt])) {\n      configured.push(p.id);\n    } else {\n      missing.push(p.id);\n    }\n  }\n\n  let details: string;\n  let hint = '';\n  if (configured.length === 0) {\n    details = 'No API keys found \u2014 crew-cli cannot run';\n    hint = `Cheapest options:\\n    \u2192 Gemini (free tier): ${PROVIDER_KEYS[0].signup}\\n    \u2192 Groq (free): ${PROVIDER_KEYS[1].signup}`;\n  } else {\n    details = `${configured.length} provider(s): ${configured.join(', ')}`;\n  }\n\n  return { configured, missing, details, hint };\n}\n\nexport async function runDoctorChecks(options: { gateway?: string; updateTag?: string } = {}) {\n  const gateway = options.gateway || 'http://localhost:5010';\n  const nodeMajor = parseMajorNodeVersion(process.version);\n\n  // Helper: race any promise against a 5s timeout\n  const withTimeout = <T>(promise: Promise<T>, fallback: T, label: string): Promise<T> =>\n    Promise.race([\n      promise,\n      new Promise<T>(resolve => setTimeout(() => {\n        resolve(fallback);\n      }, 2000))\n    ]);\n\n  const gitOk = await commandExists('git');\n  const gatewayOk = await withTimeout(gatewayReachable(gateway), false, 'gateway');\n  const config = await configExists();\n  const installedVersion = await getInstalledCliVersion();\n  const latestVersion = await withTimeout(getLatestCliVersion(options.updateTag || 'latest'), null, 'npm');\n  const linkedInstall = await withTimeout(isGlobalInstallLinked(), false, 'npm-link');\n  const mcpChecks = await withTimeout(doctorMcpServers(process.cwd()), [{ server: '(timeout)', ok: false, details: 'MCP check timed out' }], 'mcp');\n  const apiKeys = checkApiKeys();\n\n  let updateDetails = 'Update check unavailable';\n  if (installedVersion && latestVersion) {\n    const cmp = compareVersions(installedVersion, latestVersion);\n    if (cmp < 0) {\n      updateDetails = `Update available: ${installedVersion} -> ${latestVersion} (run \"crew update\")`;\n    } else {\n      updateDetails = `Up to date (${installedVersion})`;\n    }\n  }\n  if (linkedInstall) {\n    updateDetails += ' [global npm link detected]';\n  }\n\n  const mcpFailed = mcpChecks.filter(x => !x.ok).length;\n  const mcpDetails = mcpFailed === 0 \n    ? `All ${mcpChecks.length} servers online` \n    : `${mcpFailed}/${mcpChecks.length} servers failing`;\n\n  return [\n    {\n      name: 'Node.js >= 20',\n      ok: nodeMajor >= 20,\n      details: `Detected ${process.version}`\n    },\n    {\n      name: 'Git installed',\n      ok: gitOk,\n      details: gitOk ? 'git found in PATH' : 'git not found in PATH'\n    },\n    {\n      name: 'LLM API keys',\n      ok: apiKeys.configured.length > 0,\n      details: apiKeys.details,\n      hint: apiKeys.hint\n    },\n    {\n      name: 'crewswarm config present',\n      ok: config.ok,\n      details: config.path\n    },\n    {\n      name: 'crewswarm gateway reachable',\n      ok: gatewayOk,\n      details: `${gateway}/status`\n    },\n    {\n      name: 'MCP configuration health',\n      ok: mcpFailed === 0,\n      details: mcpDetails\n    },\n    {\n      name: 'CLI update status',\n      ok: true,\n      details: updateDetails\n    }\n  ];\n}\n\nexport function summarizeDoctorResults(results) {\n  const passed = results.filter(item => item.ok).length;\n  const failed = results.length - passed;\n  return { passed, failed };\n}\n", "import { execFileSync } from 'node:child_process';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport interface McpServerConfig {\n  url: string;\n  bearerTokenEnvVar?: string;\n  headers?: Record<string, string>;\n}\n\ninterface McpStore {\n  mcpServers: Record<string, McpServerConfig>;\n}\n\nfunction localStorePath(baseDir = process.cwd()): string {\n  return join(baseDir, '.crew', 'mcp-servers.json');\n}\n\nfunction clientPath(client: string): string {\n  const home = homedir();\n  const key = String(client || '').toLowerCase();\n  if (key === 'cursor') return join(home, '.cursor', 'mcp.json');\n  if (key === 'claude') return join(home, '.claude', 'mcp.json');\n  if (key === 'opencode') return join(home, '.config', 'opencode', 'mcp.json');\n  if (key === 'codex') return join(home, '.codex', 'mcp', 'config.json');\n  throw new Error(`Unsupported client: ${client}`);\n}\n\nfunction isCodexClient(client: string): boolean {\n  return String(client || '').toLowerCase() === 'codex';\n}\n\nfunction syncServerToCodex(name: string, config: McpServerConfig): void {\n  const extraHeaders = Object.entries(config.headers || {}).filter(\n    ([key]) => key.toLowerCase() !== 'authorization'\n  );\n  if (extraHeaders.length > 0) {\n    throw new Error(\n      `Codex MCP sync does not support custom headers: ${extraHeaders.map(([key]) => key).join(', ')}`\n    );\n  }\n\n  const args = ['mcp', 'add', name, '--url', config.url];\n  if (config.bearerTokenEnvVar) {\n    args.push('--bearer-token-env-var', config.bearerTokenEnvVar);\n  } else if ((config.headers || {}).Authorization || (config.headers || {}).authorization) {\n    throw new Error(\n      'Codex MCP sync requires --bearer-token-env-var for authenticated HTTP servers'\n    );\n  }\n\n  execFileSync('codex', args, { stdio: 'ignore' });\n}\n\nfunction removeServerFromCodex(name: string): void {\n  execFileSync('codex', ['mcp', 'remove', name], { stdio: 'ignore' });\n}\n\nasync function loadStore(path: string): Promise<McpStore> {\n  if (!existsSync(path)) return { mcpServers: {} };\n  try {\n    const raw = await readFile(path, 'utf8');\n    const parsed = JSON.parse(raw);\n    return { mcpServers: parsed.mcpServers || {} };\n  } catch {\n    return { mcpServers: {} };\n  }\n}\n\nasync function saveStore(path: string, store: McpStore): Promise<void> {\n  await mkdir(join(path, '..'), { recursive: true });\n  await writeFile(path, `${JSON.stringify(store, null, 2)}\\n`, 'utf8');\n}\n\nexport async function listMcpServers(baseDir = process.cwd()): Promise<Record<string, McpServerConfig>> {\n  const store = await loadStore(localStorePath(baseDir));\n  return store.mcpServers;\n}\n\nexport async function addMcpServer(\n  name: string,\n  config: McpServerConfig,\n  baseDir = process.cwd(),\n  client?: string\n): Promise<void> {\n  if (!name || !config?.url) {\n    throw new Error('name and url are required');\n  }\n\n  const localPath = localStorePath(baseDir);\n  const store = await loadStore(localPath);\n  store.mcpServers[name] = {\n    url: config.url,\n    bearerTokenEnvVar: config.bearerTokenEnvVar || undefined,\n    headers: config.headers || undefined\n  };\n  await saveStore(localPath, store);\n\n  if (client) {\n    await syncServerToClient(name, store.mcpServers[name], client);\n  }\n}\n\nexport async function removeMcpServer(name: string, baseDir = process.cwd(), client?: string): Promise<void> {\n  if (!name) throw new Error('name is required');\n\n  const localPath = localStorePath(baseDir);\n  const store = await loadStore(localPath);\n  delete store.mcpServers[name];\n  await saveStore(localPath, store);\n\n  if (client) {\n    if (isCodexClient(client)) {\n      removeServerFromCodex(name);\n      return;\n    }\n    const path = clientPath(client);\n    const clientStore = await loadStore(path);\n    delete clientStore.mcpServers[name];\n    await saveStore(path, clientStore);\n  }\n}\n\nexport async function syncServerToClient(name: string, config: McpServerConfig, client: string): Promise<void> {\n  if (isCodexClient(client)) {\n    syncServerToCodex(name, config);\n    return;\n  }\n  const path = clientPath(client);\n  const store = await loadStore(path);\n  const payload: McpServerConfig = { url: config.url };\n\n  if (config.headers && Object.keys(config.headers).length) {\n    payload.headers = config.headers;\n  }\n  if (config.bearerTokenEnvVar) {\n    payload.bearerTokenEnvVar = config.bearerTokenEnvVar;\n  }\n\n  store.mcpServers[name] = payload;\n  await saveStore(path, store);\n}\n\nexport interface McpDoctorCheck {\n  server: string;\n  ok: boolean;\n  details: string;\n}\n\nexport async function doctorMcpServers(baseDir = process.cwd()): Promise<McpDoctorCheck[]> {\n  const checks: McpDoctorCheck[] = [];\n  const servers = await listMcpServers(baseDir);\n  const names = Object.keys(servers);\n\n  if (!names.length) {\n    return [{ server: '(none)', ok: false, details: 'No MCP servers configured' }];\n  }\n\n  for (const name of names) {\n    const server = servers[name];\n    if (!server?.url) {\n      checks.push({ server: name, ok: false, details: 'Missing URL' });\n      continue;\n    }\n\n    try {\n      // URL format validation\n      new URL(server.url);\n    } catch {\n      checks.push({ server: name, ok: false, details: `Invalid URL: ${server.url}` });\n      continue;\n    }\n\n    if (server.bearerTokenEnvVar && !process.env[server.bearerTokenEnvVar]) {\n      checks.push({\n        server: name,\n        ok: false,\n        details: `Missing env var ${server.bearerTokenEnvVar}`\n      });\n      continue;\n    }\n\n    try {\n      const res = await fetch(server.url, {\n        method: 'GET',\n        signal: AbortSignal.timeout(2500)\n      });\n      checks.push({\n        server: name,\n        ok: res.ok,\n        details: `HTTP ${res.status}`\n      });\n    } catch (error) {\n      checks.push({\n        server: name,\n        ok: false,\n        details: `Unreachable: ${(error as Error).message}`\n      });\n    }\n  }\n\n  return checks;\n}\n", "export interface ModelPricing {\n  model: string;\n  inputPerMillion: number;\n  outputPerMillion: number;\n}\n\nexport interface CostEstimate {\n  model: string;\n  inputTokens: number;\n  outputTokens: number;\n  inputUsd: number;\n  outputUsd: number;\n  totalUsd: number;\n}\n\nconst DEFAULT_OUTPUT_TOKENS = 1200;\n\nconst MODEL_PRICING: Record<string, ModelPricing> = {\n  'openai/gpt-4o': { model: 'openai/gpt-4o', inputPerMillion: 2.5, outputPerMillion: 10.0 },\n  'openai/gpt-4o-mini': { model: 'openai/gpt-4o-mini', inputPerMillion: 0.15, outputPerMillion: 0.6 },\n  'anthropic/claude-3-5-sonnet': { model: 'anthropic/claude-3-5-sonnet', inputPerMillion: 3.0, outputPerMillion: 15.0 },\n  'deepseek/deepseek-chat': { model: 'deepseek/deepseek-chat', inputPerMillion: 0.27, outputPerMillion: 1.1 },\n  'deepseek/deepseek-reasoner': { model: 'deepseek/deepseek-reasoner', inputPerMillion: 0.55, outputPerMillion: 2.19 },\n  'google/gemini-2.0-flash-exp': { model: 'google/gemini-2.0-flash-exp', inputPerMillion: 0.075, outputPerMillion: 0.30 },\n  'google/gemini-2.5-flash': { model: 'google/gemini-2.5-flash', inputPerMillion: 0.075, outputPerMillion: 0.30 },\n  'groq/llama-3.3-70b-versatile': { model: 'groq/llama-3.3-70b-versatile', inputPerMillion: 0.59, outputPerMillion: 0.79 },\n  'xai/grok-4': { model: 'xai/grok-4', inputPerMillion: 0.50, outputPerMillion: 2.00 }\n};\n\nfunction normalizeModel(model?: string): string {\n  if (!model) {\n    return 'openai/gpt-4o-mini';\n  }\n  return model;\n}\n\nexport function estimateTokens(text: string): number {\n  const safe = text || '';\n  // \"Similar tokenizer\" heuristic for mixed code + prose:\n  // split by words, numbers, punctuation, and whitespace groups.\n  const pieces = safe.match(/[A-Za-z_]+|\\d+|[^\\sA-Za-z0-9_]|[\\s]+/g) || [];\n  let tokens = 0;\n  for (const piece of pieces) {\n    if (/^\\s+$/.test(piece)) {\n      tokens += Math.max(1, Math.ceil(piece.length / 4));\n    } else if (/^[A-Za-z_]+$/.test(piece)) {\n      tokens += Math.max(1, Math.ceil(piece.length / 4));\n    } else if (/^\\d+$/.test(piece)) {\n      tokens += Math.max(1, Math.ceil(piece.length / 3));\n    } else {\n      tokens += 1;\n    }\n  }\n  return Math.max(1, tokens);\n}\n\nexport function estimateCost(\n  text: string,\n  model?: string,\n  outputTokens = DEFAULT_OUTPUT_TOKENS\n): CostEstimate {\n  const selected = normalizeModel(model);\n  const pricing = MODEL_PRICING[selected] || MODEL_PRICING['openai/gpt-4o-mini'];\n  const inputTokens = estimateTokens(text);\n  const inputUsd = (inputTokens / 1_000_000) * pricing.inputPerMillion;\n  const outputUsd = (Math.max(1, outputTokens) / 1_000_000) * pricing.outputPerMillion;\n\n  return {\n    model: pricing.model,\n    inputTokens,\n    outputTokens: Math.max(1, outputTokens),\n    inputUsd,\n    outputUsd,\n    totalUsd: inputUsd + outputUsd\n  };\n}\n\nexport function compareModelCosts(\n  text: string,\n  outputTokens = DEFAULT_OUTPUT_TOKENS,\n  models = Object.keys(MODEL_PRICING)\n): CostEstimate[] {\n  return models\n    .map(model => estimateCost(text, model, outputTokens))\n    .sort((a, b) => a.totalUsd - b.totalUsd);\n}\n\nexport function getCheapestAlternative(text: string, outputTokens = DEFAULT_OUTPUT_TOKENS): CostEstimate {\n  return compareModelCosts(text, outputTokens)[0];\n}\n", "// @ts-nocheck\nimport { spawn } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { Logger } from '../utils/logger.js';\nimport { EngineSessionLayer, buildSessionPromptEnvelope } from './session-layer.js';\nimport { ConversationTranscriptStore, buildConversationHydrationPrompt } from '../session/conversation-transcript.js';\nimport { NativeEngineSessionManager, buildEngineShellCommand } from './native-session.js';\nimport { ToolAuditStore, buildReplayPlan, extractToolCalls, previewAuditOutput } from './tool-audit.js';\nconst logger = new Logger({ level: process.env.CREW_LOG_LEVEL || 'info' });\nconst nativeSessionManagers = new Map<string, NativeEngineSessionManager>();\n\nexport interface EngineRunOptions {\n  model?: string;\n  cwd?: string;\n  timeoutMs?: number;\n  sessionId?: string;\n  sessionTurns?: number;\n  projectDir?: string;\n  systemPrompt?: string;\n  runId?: string;\n  onEvent?: (event: EngineRunEvent) => void;\n}\n\nexport interface EngineRunResult {\n  success: boolean;\n  engine: string;\n  stdout: string;\n  stderr: string;\n  exitCode: number;\n}\n\nexport interface EngineRunEvent {\n  type: 'start' | 'chunk' | 'end' | 'error' | 'tool-audit';\n  ts: string;\n  engine: string;\n  runId?: string;\n  sessionId?: string;\n  text?: string;\n  exitCode?: number;\n  success?: boolean;\n  mode?: string;\n  toolCount?: number;\n}\n\nfunction emitEngineEvent(options: EngineRunOptions, engine: string, event: Omit<EngineRunEvent, 'ts' | 'engine'>): void {\n  const cb = options.onEvent;\n  if (!cb) return;\n  try {\n    cb({\n      ts: new Date().toISOString(),\n      engine,\n      ...event\n    });\n  } catch {\n    // ignore callback failures\n  }\n}\n\nfunction sessionLayerEnabled(): boolean {\n  const raw = String(process.env.CREW_ENGINE_SESSION_ENABLED || 'true').trim().toLowerCase();\n  return raw !== 'false' && raw !== '0' && raw !== 'off' && raw !== 'no';\n}\n\nfunction nativeEngineSessionEnabled(): boolean {\n  const raw = String(process.env.CREW_ENGINE_NATIVE_SESSION_ENABLED || 'true').trim().toLowerCase();\n  return raw !== 'false' && raw !== '0' && raw !== 'off' && raw !== 'no';\n}\n\nfunction isCliEngine(engine: string): boolean {\n  const e = String(engine || '').trim().toLowerCase();\n  return e === 'codex-cli' || e === 'claude-cli' || e === 'cursor-cli' || e === 'cursor' || e === 'gemini-cli' || e === 'opencode-cli' || e === 'opencode';\n}\n\nfunction getNativeSessionManager(baseDir: string): NativeEngineSessionManager {\n  const key = String(baseDir || process.cwd());\n  if (!nativeSessionManagers.has(key)) {\n    nativeSessionManagers.set(key, new NativeEngineSessionManager(key));\n  }\n  return nativeSessionManagers.get(key)!;\n}\n\nasync function preparePromptWithSession(\n  engine: string,\n  prompt: string,\n  options: EngineRunOptions\n): Promise<{\n  effectivePrompt: string;\n  engineStore: EngineSessionLayer | null;\n  transcriptStore: ConversationTranscriptStore | null;\n}> {\n  if (!sessionLayerEnabled()) {\n    return {\n      effectivePrompt: options.systemPrompt ? buildSessionPromptEnvelope({ systemPrompt: options.systemPrompt, history: [], prompt }) : prompt,\n      engineStore: null,\n      transcriptStore: null\n    };\n  }\n\n  const sessionId = String(options.sessionId || '').trim();\n  const systemPrompt = String(options.systemPrompt || '').trim();\n  if (!sessionId) {\n    if (!systemPrompt) {\n      return {\n        effectivePrompt: prompt,\n        engineStore: null,\n        transcriptStore: null\n      };\n    }\n    return {\n      effectivePrompt: buildSessionPromptEnvelope({ systemPrompt, history: [], prompt }),\n      engineStore: null,\n      transcriptStore: null\n    };\n  }\n\n  const baseDir = String(options.projectDir || options.cwd || process.cwd());\n  const engineStore = new EngineSessionLayer(baseDir);\n  const transcriptStore = new ConversationTranscriptStore(baseDir);\n  const maxTurns = Math.max(1, Number(options.sessionTurns || 6));\n  const [engineHistory, conversationHistory] = await Promise.all([\n    engineStore.getRecentTurns(engine, sessionId, maxTurns),\n    transcriptStore.getRecentTurns(sessionId, Math.max(2, maxTurns * 2))\n  ]);\n  const withConversation = buildConversationHydrationPrompt({\n    turns: conversationHistory,\n    currentPrompt: prompt\n  });\n  const effectivePrompt = buildSessionPromptEnvelope({\n    systemPrompt,\n    history: engineHistory,\n    prompt: withConversation\n  });\n  return { effectivePrompt, engineStore, transcriptStore };\n}\n\nasync function persistEngineTurn(\n  engineStore: EngineSessionLayer | null,\n  transcriptStore: ConversationTranscriptStore | null,\n  engine: string,\n  prompt: string,\n  options: EngineRunOptions,\n  result: EngineRunResult,\n  durationMs: number\n): Promise<void> {\n  const sessionId = String(options.sessionId || '').trim();\n  if (!sessionId) {\n    return;\n  }\n  try {\n    if (engineStore) {\n      await engineStore.appendTurn({\n        engine,\n        sessionId,\n        prompt,\n        response: result.success ? result.stdout : result.stderr,\n        success: result.success,\n        exitCode: Number(result.exitCode || 0),\n        model: options.model,\n        durationMs,\n        keepTurns: Number(process.env.CREW_ENGINE_SESSION_KEEP_TURNS || 20)\n      });\n    }\n    if (transcriptStore) {\n      await transcriptStore.appendTurn({\n        sessionId,\n        role: 'user',\n        text: prompt,\n        engine,\n        keepTurns: Number(process.env.CREW_CONVERSATION_KEEP_TURNS || 40)\n      });\n      await transcriptStore.appendTurn({\n        sessionId,\n        role: 'assistant',\n        text: result.success ? result.stdout : result.stderr,\n        engine,\n        keepTurns: Number(process.env.CREW_CONVERSATION_KEEP_TURNS || 40)\n      });\n    }\n  } catch (err) {\n    logger.warn(`[engine-session] failed to persist turn: ${(err as Error).message}`);\n  }\n}\n\nasync function runCommand(command: string, args: string[], options: EngineRunOptions = {}, stdin?: string): Promise<EngineRunResult> {\n  const engineLabel = String(command || '');\n  emitEngineEvent(options, engineLabel, {\n    type: 'start',\n    runId: options.runId,\n    sessionId: options.sessionId,\n    mode: 'spawn'\n  });\n  return new Promise(resolve => {\n    // Strip env vars that prevent CLI engines from running inside other sessions\n    const cleanEnv = { ...process.env };\n    delete cleanEnv.CLAUDECODE;\n    delete cleanEnv.CLAUDE_CODE;\n    if (/(^|[\\\\/])claude$/.test(engineLabel)) {\n      delete cleanEnv.ANTHROPIC_API_KEY;\n    }\n\n    const child = spawn(command, args, {\n      cwd: options.cwd || process.cwd(),\n      stdio: [stdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],\n      env: cleanEnv\n    });\n\n    let stdinWritten = false;\n    if (stdin && child.stdin) {\n      try {\n        child.stdin.write(stdin, 'utf8', (err) => {\n          if (err) {\n            logger.error(`[${command}] stdin write error:`, err);\n          }\n          // Give the process a moment to start reading before closing stdin\n          setTimeout(() => {\n            if (child.stdin && !child.stdin.destroyed) {\n              child.stdin.end();\n            }\n          }, 50);\n        });\n        stdinWritten = true;\n      } catch (err) {\n        logger.error(`[${command}] failed to write stdin:`, err);\n      }\n    }\n\n    const timeoutMs = options.timeoutMs || 600000;\n    let stdout = '';\n    let stderr = '';\n    let done = false;\n\n    const timer = setTimeout(() => {\n      if (done) return;\n      logger.error(`[${command}] Timing out after ${timeoutMs}ms. stdout: ${stdout.slice(0, 200)}, stderr: ${stderr.slice(0, 200)}`);\n      child.kill('SIGTERM');\n      // Give process 2s to clean up, then SIGKILL if needed\n      setTimeout(() => {\n        if (!done && !child.killed) {\n          child.kill('SIGKILL');\n        }\n      }, 2000);\n      done = true;\n      resolve({\n        success: false,\n        engine: command,\n        stdout,\n        stderr: `${stderr}\\nTimed out after ${timeoutMs}ms`,\n        exitCode: -1\n      });\n    }, timeoutMs);\n\n    child.stdout.on('data', chunk => {\n      const text = String(chunk);\n      stdout += text;\n      emitEngineEvent(options, engineLabel, {\n        type: 'chunk',\n        runId: options.runId,\n        sessionId: options.sessionId,\n        text\n      });\n    });\n    child.stderr.on('data', chunk => {\n      const text = String(chunk);\n      stderr += text;\n      emitEngineEvent(options, engineLabel, {\n        type: 'chunk',\n        runId: options.runId,\n        sessionId: options.sessionId,\n        text\n      });\n    });\n\n    child.on('error', (err) => {\n      if (done) return;\n      done = true;\n      clearTimeout(timer);\n      logger.error(`[${command}] process error:`, err);\n      resolve({\n        success: false,\n        engine: command,\n        stdout,\n        stderr: `${stderr}\\nProcess error: ${err.message}`,\n        exitCode: -1\n      });\n    });\n\n    child.on('close', code => {\n      if (done) return;\n      done = true;\n      clearTimeout(timer);\n      resolve({\n        success: code === 0,\n        engine: command,\n        stdout: stdout.trim(),\n        stderr: stderr.trim(),\n        exitCode: code ?? -1\n      });\n      emitEngineEvent(options, engineLabel, {\n        type: 'end',\n        runId: options.runId,\n        sessionId: options.sessionId,\n        exitCode: code ?? -1,\n        success: code === 0,\n        mode: 'spawn'\n      });\n    });\n  });\n}\n\nasync function maybeRunViaNativeSession(engine: string, prompt: string, options: EngineRunOptions): Promise<EngineRunResult | null> {\n  if (!nativeEngineSessionEnabled()) return null;\n  if (!isCliEngine(engine)) return null;\n  const sessionId = String(options.sessionId || '').trim();\n  if (!sessionId) return null;\n\n  const cwd = String(options.cwd || options.projectDir || process.cwd());\n  const command = buildEngineShellCommand(engine, prompt, options.model, cwd);\n  if (!command) return null;\n  const manager = getNativeSessionManager(cwd);\n  emitEngineEvent(options, engine, {\n    type: 'start',\n    runId: options.runId,\n    sessionId,\n    mode: 'native-shell'\n  });\n  const result = await manager.runInSession({\n    engine,\n    sessionId,\n    cwd,\n    command,\n    timeoutMs: options.timeoutMs,\n    onChunk: (text: string) => {\n      emitEngineEvent(options, engine, {\n        type: 'chunk',\n        runId: options.runId,\n        sessionId,\n        text\n      });\n    }\n  });\n\n  if (result.mode === 'fallback') return null;\n  emitEngineEvent(options, engine, {\n    type: result.success ? 'end' : 'error',\n    runId: options.runId,\n    sessionId,\n    exitCode: result.exitCode,\n    success: result.success,\n    mode: result.mode\n  });\n  return {\n    success: result.success,\n    engine,\n    stdout: result.stdout || '',\n    stderr: result.stderr || '',\n    exitCode: result.exitCode\n  };\n}\n\nasync function callJsonApi(url: string, apiKey: string | null, body: unknown): Promise<string> {\n  const headers: Record<string, string> = {\n    'Content-Type': 'application/json'\n  };\n  if (apiKey) {\n    headers.Authorization = `Bearer ${apiKey}`;\n  }\n\n  const response = await fetch(url, {\n    method: 'POST',\n    headers,\n    body: JSON.stringify(body)\n  });\n\n  if (!response.ok) {\n    const text = await response.text();\n    throw new Error(`API error ${response.status}: ${text.slice(0, 500)}`);\n  }\n\n  const data = await response.json() as Record<string, unknown>;\n  const content = data?.content as Array<{ text?: string }> | undefined;\n  const candidates = data?.candidates as Array<{ content?: { parts?: Array<{ text?: string }> } }> | undefined;\n  return content?.[0]?.text\n    || candidates?.[0]?.content?.parts?.[0]?.text\n    || (data?.output_text as string)\n    || JSON.stringify(data);\n}\n\nexport async function runGeminiApi(prompt: string, options: EngineRunOptions = {}): Promise<EngineRunResult> {\n  const key = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;\n  if (!key) {\n    return {\n      success: false,\n      engine: 'gemini-api',\n      stdout: '',\n      stderr: 'Missing GEMINI_API_KEY/GOOGLE_API_KEY',\n      exitCode: 1\n    };\n  }\n\n  const model = options.model || 'gemini-2.0-flash';\n  try {\n    const text = await callJsonApi(\n      `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${encodeURIComponent(key)}`,\n      null,\n      { contents: [{ parts: [{ text: prompt }] }] }\n    );\n    return { success: true, engine: 'gemini-api', stdout: text, stderr: '', exitCode: 0 };\n  } catch (error) {\n    return { success: false, engine: 'gemini-api', stdout: '', stderr: (error as Error).message, exitCode: 1 };\n  }\n}\n\nexport async function runClaudeApi(prompt: string, options: EngineRunOptions = {}): Promise<EngineRunResult> {\n  const key = process.env.ANTHROPIC_API_KEY;\n  if (!key) {\n    return {\n      success: false,\n      engine: 'claude-api',\n      stdout: '',\n      stderr: 'Missing ANTHROPIC_API_KEY',\n      exitCode: 1\n    };\n  }\n\n  const model = options.model || 'claude-3-5-sonnet-latest';\n  try {\n    const response = await fetch('https://api.anthropic.com/v1/messages', {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        'x-api-key': key,\n        'anthropic-version': '2023-06-01'\n      },\n      body: JSON.stringify({\n        model,\n        max_tokens: 2000,\n        messages: [{ role: 'user', content: prompt }]\n      })\n    });\n    if (!response.ok) {\n      const text = await response.text();\n      throw new Error(`API error ${response.status}: ${text.slice(0, 500)}`);\n    }\n    const data = await response.json() as { content?: Array<{ text?: string }> };\n    const text = data?.content?.[0]?.text || JSON.stringify(data);\n    return { success: true, engine: 'claude-api', stdout: text, stderr: '', exitCode: 0 };\n  } catch (error) {\n    return { success: false, engine: 'claude-api', stdout: '', stderr: (error as Error).message, exitCode: 1 };\n  }\n}\n\nexport async function runGeminiCli(prompt: string, options: EngineRunOptions = {}): Promise<EngineRunResult> {\n  const args = ['-p', prompt, '--output-format', 'stream-json', '--yolo'];\n  if (options.model) {\n    args.push('-m', options.model);\n  }\n  return runCommand('gemini', args, options);\n}\n\nexport async function runCodexCli(prompt: string, options: EngineRunOptions = {}): Promise<EngineRunResult> {\n  const args = ['-a', 'never', 'exec', '--sandbox', 'danger-full-access', '--skip-git-repo-check', '--json', prompt];\n  return runCommand('codex', args, options);\n}\n\nexport async function runClaudeCli(prompt: string, options: EngineRunOptions = {}): Promise<EngineRunResult> {\n  const args = ['-p', '--setting-sources', 'user', '--output-format', 'stream-json', '--verbose'];\n  if (process.env.CREW_CLAUDE_SKIP_PERMISSIONS !== 'false') {\n    args.push('--dangerously-skip-permissions');\n  }\n  args.push('--', prompt);\n  return runCommand('claude', args, options);\n}\n\n/**\n * Cursor engine: use the Cursor **agent** CLI (`agent`), same as gateway bypass\n * (`lib/engines/runners.mjs` / `CURSOR_CLI_BIN`). The `cursor` binary on PATH is\n * often the IDE opener (Electron) \u2014 not compatible with `--execute`.\n */\nfunction resolveCursorAgentBin(): string {\n  const fromEnv = String(process.env.CURSOR_CLI_BIN || '').trim();\n  if (fromEnv) return fromEnv;\n  const agentLocal = path.join(os.homedir(), '.local', 'bin', 'agent');\n  if (fs.existsSync(agentLocal)) return agentLocal;\n  return 'agent';\n}\n\nexport async function runCursorCli(prompt: string, options: EngineRunOptions = {}): Promise<EngineRunResult> {\n  const bin = resolveCursorAgentBin();\n  const projectDir = options.cwd || options.projectDir || process.cwd();\n  const cursorDefault = process.env.CREWSWARM_CURSOR_MODEL || 'composer-2-fast';\n  let model = options.model;\n  if (!model || String(model).trim() === '') {\n    model = cursorDefault;\n  } else if (String(model).includes('/')) {\n    model = cursorDefault;\n  } else if (String(model).includes('sonnet-4.6')) {\n    model = 'sonnet-4.5';\n  }\n  const args = [\n    '-p',\n    '--force',\n    '--trust',\n    '--output-format',\n    'stream-json',\n    prompt,\n    '--model',\n    model,\n    '--workspace',\n    projectDir\n  ];\n  return runCommand(bin, args, { ...options, cwd: projectDir });\n}\n\nexport async function runOpenCodeCli(prompt: string, options: EngineRunOptions = {}): Promise<EngineRunResult> {\n  const args = ['run'];\n  if (options.model) {\n    args.push('--model', options.model);\n  }\n  args.push(prompt);\n  return runCommand('opencode', args, options);\n}\n\nexport async function runEngine(engine: string, prompt: string, options: EngineRunOptions = {}): Promise<EngineRunResult> {\n  const normalizedEngine = String(engine || '').trim().toLowerCase();\n  const start = Date.now();\n  const runId = String(options.runId || `eng-${randomUUID()}`);\n  const optionsWithRunId: EngineRunOptions = { ...options, runId };\n  const { effectivePrompt, engineStore, transcriptStore } = await preparePromptWithSession(normalizedEngine, prompt, options);\n  let result: EngineRunResult;\n\n  const native = await maybeRunViaNativeSession(normalizedEngine, effectivePrompt, optionsWithRunId);\n  if (native) {\n    result = native;\n    await persistEngineTurn(engineStore, transcriptStore, normalizedEngine, prompt, optionsWithRunId, result, Date.now() - start);\n    await maybeRecordToolAudit(runId, normalizedEngine, prompt, result, optionsWithRunId);\n    return result;\n  }\n\n  switch (normalizedEngine) {\n    case 'gemini-api':\n      result = await runGeminiApi(effectivePrompt, options);\n      break;\n    case 'claude-api':\n      result = await runClaudeApi(effectivePrompt, options);\n      break;\n    case 'gemini-cli':\n      result = await runGeminiCli(effectivePrompt, options);\n      break;\n    case 'codex-cli':\n      result = await runCodexCli(effectivePrompt, options);\n      break;\n    case 'claude-cli':\n      result = await runClaudeCli(effectivePrompt, options);\n      break;\n    case 'cursor':\n    case 'cursor-cli':\n      result = await runCursorCli(effectivePrompt, options);\n      break;\n    case 'opencode':\n    case 'opencode-cli':\n      result = await runOpenCodeCli(effectivePrompt, options);\n      break;\n    default:\n      result = {\n        success: false,\n        engine: normalizedEngine,\n        stdout: '',\n        stderr: `Unknown engine \"${normalizedEngine}\"`,\n        exitCode: 1\n      };\n      break;\n  }\n\n  await persistEngineTurn(engineStore, transcriptStore, normalizedEngine, prompt, optionsWithRunId, result, Date.now() - start);\n  await maybeRecordToolAudit(runId, normalizedEngine, prompt, result, optionsWithRunId);\n  return result;\n}\n\nasync function maybeRecordToolAudit(\n  runId: string,\n  engine: string,\n  prompt: string,\n  result: EngineRunResult,\n  options: EngineRunOptions\n): Promise<void> {\n  const raw = result.success ? result.stdout : result.stderr;\n  const toolCalls = extractToolCalls(raw);\n  const store = new ToolAuditStore(String(options.projectDir || options.cwd || process.cwd()));\n  await store.record({\n    runId,\n    ts: new Date().toISOString(),\n    engine,\n    sessionId: options.sessionId,\n    prompt: previewAuditOutput(prompt),\n    success: result.success,\n    exitCode: result.exitCode,\n    toolCalls,\n    rawOutputPreview: previewAuditOutput(raw)\n  });\n  emitEngineEvent(options, engine, {\n    type: 'tool-audit',\n    runId,\n    sessionId: options.sessionId,\n    toolCount: toolCalls.length\n  });\n}\n\nexport async function listNativeEngineSessions(baseDir = process.cwd()): Promise<Record<string, unknown>> {\n  const manager = getNativeSessionManager(baseDir);\n  return manager.list();\n}\n\nexport async function closeNativeEngineSessions(baseDir = process.cwd()): Promise<void> {\n  const manager = getNativeSessionManager(baseDir);\n  await manager.closeAll();\n}\n\nexport async function getToolAuditRuns(baseDir = process.cwd(), limit = 30): Promise<Array<Record<string, unknown>>> {\n  const store = new ToolAuditStore(baseDir);\n  return store.list(limit);\n}\n\nexport async function getToolAuditReplayPlan(baseDir: string, runId: string): Promise<ReturnType<typeof buildReplayPlan> | null> {\n  const store = new ToolAuditStore(baseDir);\n  const run = await store.loadRun(runId);\n  if (!run) return null;\n  return buildReplayPlan(run);\n}\n", "import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nexport interface EngineSessionTurn {\n  ts: string;\n  prompt: string;\n  response: string;\n  success: boolean;\n  exitCode: number;\n  model?: string;\n  durationMs?: number;\n}\n\nexport interface EngineSessionRecord {\n  key: string;\n  engine: string;\n  sessionId: string;\n  projectDir: string;\n  createdAt: string;\n  updatedAt: string;\n  turns: EngineSessionTurn[];\n  totalTurns: number;\n  lastSuccess: boolean;\n  lastExitCode: number;\n  lastModel?: string;\n}\n\nexport interface EngineSessionSummary {\n  key: string;\n  engine: string;\n  sessionId: string;\n  projectDir: string;\n  createdAt: string;\n  updatedAt: string;\n  totalTurns: number;\n  lastSuccess: boolean;\n  lastExitCode: number;\n  lastModel?: string;\n}\n\ntype SessionStore = Record<string, EngineSessionRecord>;\n\nfunction nowIso(): string {\n  return new Date().toISOString();\n}\n\nfunction clip(text: string, maxChars: number): string {\n  const value = String(text || '');\n  if (value.length <= maxChars) return value;\n  return `${value.slice(0, maxChars)}\\n...[truncated]`;\n}\n\nexport class EngineSessionLayer {\n  private readonly baseDir: string;\n  private readonly stateDir: string;\n  private readonly sessionsPath: string;\n\n  constructor(baseDir: string = process.cwd()) {\n    this.baseDir = resolve(baseDir);\n    this.stateDir = join(this.baseDir, '.crew');\n    this.sessionsPath = join(this.stateDir, 'engine-sessions.json');\n  }\n\n  makeKey(engine: string, sessionId: string): string {\n    return `${String(engine || '').trim().toLowerCase()}::${String(sessionId || '').trim()}`;\n  }\n\n  async ensureInitialized(): Promise<void> {\n    await mkdir(this.stateDir, { recursive: true });\n    if (!existsSync(this.sessionsPath)) {\n      await writeFile(this.sessionsPath, JSON.stringify({}, null, 2), 'utf8');\n    }\n  }\n\n  private async loadStore(): Promise<SessionStore> {\n    await this.ensureInitialized();\n    try {\n      const raw = await readFile(this.sessionsPath, 'utf8');\n      const parsed = JSON.parse(raw);\n      if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};\n      return parsed as SessionStore;\n    } catch {\n      return {};\n    }\n  }\n\n  private async saveStore(store: SessionStore): Promise<void> {\n    await this.ensureInitialized();\n    await writeFile(this.sessionsPath, JSON.stringify(store, null, 2), 'utf8');\n  }\n\n  async appendTurn(params: {\n    engine: string;\n    sessionId: string;\n    prompt: string;\n    response: string;\n    success: boolean;\n    exitCode: number;\n    model?: string;\n    durationMs?: number;\n    keepTurns?: number;\n  }): Promise<EngineSessionRecord> {\n    const engine = String(params.engine || '').trim().toLowerCase();\n    const sessionId = String(params.sessionId || '').trim();\n    if (!engine || !sessionId) {\n      throw new Error('appendTurn requires engine and sessionId');\n    }\n\n    const keepTurns = Math.max(1, Number(params.keepTurns || 20));\n    const store = await this.loadStore();\n    const key = this.makeKey(engine, sessionId);\n    const existing = store[key];\n    const record: EngineSessionRecord = existing || {\n      key,\n      engine,\n      sessionId,\n      projectDir: this.baseDir,\n      createdAt: nowIso(),\n      updatedAt: nowIso(),\n      turns: [],\n      totalTurns: 0,\n      lastSuccess: true,\n      lastExitCode: 0,\n      lastModel: ''\n    };\n\n    record.turns.push({\n      ts: nowIso(),\n      prompt: clip(params.prompt, 4000),\n      response: clip(params.response, 12000),\n      success: Boolean(params.success),\n      exitCode: Number(params.exitCode ?? 0),\n      model: params.model,\n      durationMs: Number(params.durationMs || 0)\n    });\n    record.turns = record.turns.slice(-keepTurns);\n    record.totalTurns = Number(record.totalTurns || 0) + 1;\n    record.lastSuccess = Boolean(params.success);\n    record.lastExitCode = Number(params.exitCode ?? 0);\n    record.lastModel = params.model || record.lastModel;\n    record.updatedAt = nowIso();\n\n    store[key] = record;\n    await this.saveStore(store);\n    return record;\n  }\n\n  async getRecord(engine: string, sessionId: string): Promise<EngineSessionRecord | null> {\n    const key = this.makeKey(engine, sessionId);\n    const store = await this.loadStore();\n    return store[key] || null;\n  }\n\n  async getRecentTurns(engine: string, sessionId: string, maxTurns = 6): Promise<EngineSessionTurn[]> {\n    const rec = await this.getRecord(engine, sessionId);\n    if (!rec) return [];\n    const n = Math.max(1, Number(maxTurns || 6));\n    return rec.turns.slice(-n);\n  }\n\n  async listSummaries(): Promise<Record<string, EngineSessionSummary>> {\n    const store = await this.loadStore();\n    const out: Record<string, EngineSessionSummary> = {};\n    for (const [key, rec] of Object.entries(store)) {\n      out[key] = {\n        key,\n        engine: rec.engine,\n        sessionId: rec.sessionId,\n        projectDir: rec.projectDir,\n        createdAt: rec.createdAt,\n        updatedAt: rec.updatedAt,\n        totalTurns: Number(rec.totalTurns || rec.turns?.length || 0),\n        lastSuccess: Boolean(rec.lastSuccess),\n        lastExitCode: Number(rec.lastExitCode || 0),\n        lastModel: rec.lastModel\n      };\n    }\n    return out;\n  }\n\n  async clear(): Promise<void> {\n    await this.saveStore({});\n  }\n}\n\nexport function buildSessionPromptEnvelope(params: {\n  systemPrompt?: string;\n  history: EngineSessionTurn[];\n  prompt: string;\n}): string {\n  const chunks: string[] = [];\n  const systemPrompt = String(params.systemPrompt || '').trim();\n  if (systemPrompt) {\n    chunks.push('SYSTEM PERSONA (persist across session):');\n    chunks.push(systemPrompt);\n  }\n  const history = Array.isArray(params.history) ? params.history : [];\n  if (history.length > 0) {\n    chunks.push('SESSION HISTORY (most recent turns):');\n    for (const turn of history) {\n      chunks.push(`[USER @ ${turn.ts}]`);\n      chunks.push(clip(String(turn.prompt || ''), 1200));\n      chunks.push(`[ASSISTANT @ ${turn.ts}]`);\n      chunks.push(clip(String(turn.response || ''), 2000));\n    }\n    chunks.push('Continue consistently with the session history.');\n  }\n  chunks.push('CURRENT USER MESSAGE:');\n  chunks.push(String(params.prompt || ''));\n  return chunks.join('\\n\\n');\n}\n", "/**\n * Conversation Transcript Store \u2014 JSONL append-only format\n *\n * Each turn is appended as a single JSON line to .crew/transcript-{sessionId}.jsonl\n * This is crash-safe: a mid-write crash only loses the last incomplete line.\n * On load, lines are parsed individually so partial corruption doesn't lose the whole file.\n */\n\nimport { appendFile, mkdir, readFile, readdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n// Inline token estimation to avoid cross-module .js/.ts resolution issues in Node ESM\nfunction estimateTokens(text: string): number {\n  if (!text) return 0;\n  return Math.ceil(text.length / 3.7);\n}\n\nexport interface ConversationTurn {\n  ts: string;\n  role: 'user' | 'assistant';\n  text: string;\n  engine?: string;\n  estimatedTokens?: number;\n  sessionId?: string;\n}\n\nfunction nowIso(): string {\n  return new Date().toISOString();\n}\n\nfunction clip(text: string, maxChars: number): string {\n  const value = String(text || '');\n  if (value.length <= maxChars) return value;\n  return `${value.slice(0, maxChars)}\\n...[truncated]`;\n}\n\nexport class ConversationTranscriptStore {\n  private readonly stateDir: string;\n\n  constructor(baseDir: string = process.cwd()) {\n    const root = resolve(baseDir);\n    this.stateDir = join(root, '.crew');\n  }\n\n  private transcriptPath(sessionId: string): string {\n    // Sanitize session ID for safe filenames\n    const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');\n    return join(this.stateDir, `transcript-${safe}.jsonl`);\n  }\n\n  async ensureInitialized(): Promise<void> {\n    await mkdir(this.stateDir, { recursive: true });\n  }\n\n  /**\n   * Append a turn to the transcript \u2014 single atomic append, crash-safe.\n   */\n  async appendTurn(params: {\n    sessionId: string;\n    role: 'user' | 'assistant';\n    text: string;\n    engine?: string;\n    keepTurns?: number;\n  }): Promise<void> {\n    const sessionId = String(params.sessionId || '').trim();\n    if (!sessionId) return;\n    await this.ensureInitialized();\n\n    const clippedText = clip(params.text, 8000);\n    const turn: ConversationTurn = {\n      ts: nowIso(),\n      role: params.role,\n      text: clippedText,\n      engine: params.engine,\n      estimatedTokens: estimateTokens(clippedText),\n      sessionId\n    };\n\n    // Append single line \u2014 atomic on most filesystems for < 4KB\n    const line = JSON.stringify(turn) + '\\n';\n    await appendFile(this.transcriptPath(sessionId), line, 'utf8');\n  }\n\n  /**\n   * Load all turns for a session from JSONL file.\n   * Skips corrupt/incomplete lines gracefully.\n   */\n  async loadTurns(sessionId: string): Promise<ConversationTurn[]> {\n    const key = String(sessionId || '').trim();\n    if (!key) return [];\n\n    const path = this.transcriptPath(key);\n    if (!existsSync(path)) return [];\n\n    try {\n      const raw = await readFile(path, 'utf8');\n      const turns: ConversationTurn[] = [];\n      for (const line of raw.split('\\n')) {\n        const trimmed = line.trim();\n        if (!trimmed) continue;\n        try {\n          turns.push(JSON.parse(trimmed) as ConversationTurn);\n        } catch {\n          // Skip corrupt line \u2014 this is the crash-safety benefit\n        }\n      }\n      return turns;\n    } catch {\n      return [];\n    }\n  }\n\n  /**\n   * Get recent turns with token-aware trimming.\n   */\n  async getRecentTurns(sessionId: string, maxTurns = 8): Promise<ConversationTurn[]> {\n    const turns = await this.loadTurns(sessionId);\n    if (turns.length === 0) return [];\n\n    // Token-aware trimming\n    const maxSessionTokens = Number(process.env.CREW_MAX_SESSION_TOKENS) || 100_000;\n    let totalTokens = 0;\n    const result: ConversationTurn[] = [];\n\n    // Walk backwards to keep most recent turns within budget\n    for (let i = turns.length - 1; i >= 0 && result.length < maxTurns; i--) {\n      const t = turns[i];\n      const tokens = t.estimatedTokens || estimateTokens(t.text);\n      if (totalTokens + tokens > maxSessionTokens && result.length >= 4) break;\n      totalTokens += tokens;\n      result.unshift(t);\n    }\n\n    return result;\n  }\n\n  /**\n   * List all session IDs that have transcripts.\n   */\n  async listSessions(): Promise<Array<{ sessionId: string; path: string; lines: number }>> {\n    await this.ensureInitialized();\n    const sessions: Array<{ sessionId: string; path: string; lines: number }> = [];\n\n    try {\n      const files = await readdir(this.stateDir);\n      for (const f of files) {\n        const match = f.match(/^transcript-(.+)\\.jsonl$/);\n        if (!match) continue;\n        const sessionId = match[1];\n        const fullPath = join(this.stateDir, f);\n        try {\n          const raw = await readFile(fullPath, 'utf8');\n          const lines = raw.split('\\n').filter(l => l.trim()).length;\n          sessions.push({ sessionId, path: fullPath, lines });\n        } catch {\n          sessions.push({ sessionId, path: fullPath, lines: 0 });\n        }\n      }\n    } catch { /* empty dir */ }\n\n    return sessions;\n  }\n\n  /**\n   * Get a summary of a session (first user message + turn count + last activity).\n   */\n  async getSessionSummary(sessionId: string): Promise<{\n    sessionId: string;\n    turnCount: number;\n    firstMessage: string;\n    lastActivity: string;\n    totalTokens: number;\n  } | null> {\n    const turns = await this.loadTurns(sessionId);\n    if (turns.length === 0) return null;\n\n    const firstUser = turns.find(t => t.role === 'user');\n    return {\n      sessionId,\n      turnCount: turns.length,\n      firstMessage: clip(firstUser?.text || '(no user message)', 80),\n      lastActivity: turns[turns.length - 1].ts,\n      totalTokens: turns.reduce((sum, t) => sum + (t.estimatedTokens || estimateTokens(t.text)), 0)\n    };\n  }\n}\n\nexport function buildConversationHydrationPrompt(params: {\n  turns: ConversationTurn[];\n  currentPrompt: string;\n}): string {\n  const turns = Array.isArray(params.turns) ? params.turns : [];\n  if (turns.length === 0) return String(params.currentPrompt || '');\n\n  const lines: string[] = [];\n  lines.push('SHARED SESSION CONTEXT (engine-agnostic):');\n  for (const t of turns) {\n    const role = t.role === 'assistant' ? 'ASSISTANT' : 'USER';\n    lines.push(`[${role} @ ${t.ts}${t.engine ? ` via ${t.engine}` : ''}]`);\n    lines.push(clip(String(t.text || ''), 1600));\n  }\n  lines.push('Continue from this shared conversation state.');\n  lines.push('CURRENT USER MESSAGE:');\n  lines.push(String(params.currentPrompt || ''));\n  return lines.join('\\n\\n');\n}\n", "import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { randomUUID } from 'node:crypto';\n\nexport interface NativeSessionSummary {\n  key: string;\n  engine: string;\n  sessionId: string;\n  cwd: string;\n  shell: string;\n  createdAt: string;\n  updatedAt: string;\n  turns: number;\n  alive: boolean;\n}\n\ntype RuntimeSession = {\n  key: string;\n  engine: string;\n  sessionId: string;\n  cwd: string;\n  shell: string;\n  createdAt: string;\n  updatedAt: string;\n  turns: number;\n  busy: boolean;\n  pty: PtyProcessLike;\n};\n\ninterface PtyProcessLike {\n  onData(cb: (data: string) => void): void;\n  onExit(cb: (info: { exitCode: number; signal: number }) => void): void;\n  off(event: 'data', listener: (data: string) => void): void;\n  write(data: string): void;\n  resize(cols: number, rows: number): void;\n  kill(): void;\n}\n\ninterface PtySpawnLike {\n  (\n    file: string,\n    args: string | string[],\n    options: {\n      name: string;\n      cwd: string;\n      cols: number;\n      rows: number;\n      env: NodeJS.ProcessEnv;\n    }\n  ): PtyProcessLike;\n}\n\ntype SessionStore = Record<string, Omit<NativeSessionSummary, 'alive'>>;\n\nfunction nowIso(): string {\n  return new Date().toISOString();\n}\n\nfunction shellQuote(value: string): string {\n  const text = String(value || '');\n  if (text.length === 0) return \"''\";\n  return `'${text.replace(/'/g, `'\\\"'\\\"'`)}'`;\n}\n\nexport class NativeEngineSessionManager {\n  private readonly baseDir: string;\n  private readonly stateDir: string;\n  private readonly statePath: string;\n  private readonly runtime = new Map<string, RuntimeSession>();\n  private ptySpawn: PtySpawnLike | null = null;\n  private ptyLoadFailed = false;\n\n  constructor(baseDir: string = process.cwd()) {\n    this.baseDir = resolve(baseDir);\n    this.stateDir = join(this.baseDir, '.crew');\n    this.statePath = join(this.stateDir, 'engine-native-sessions.json');\n  }\n\n  private makeKey(engine: string, sessionId: string): string {\n    return `${String(engine || '').trim().toLowerCase()}::${String(sessionId || '').trim()}`;\n  }\n\n  private async ensureStore(): Promise<void> {\n    await mkdir(this.stateDir, { recursive: true });\n    if (!existsSync(this.statePath)) {\n      await writeFile(this.statePath, JSON.stringify({}, null, 2), 'utf8');\n    }\n  }\n\n  private async loadStore(): Promise<SessionStore> {\n    await this.ensureStore();\n    try {\n      const raw = await readFile(this.statePath, 'utf8');\n      const parsed = JSON.parse(raw);\n      if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};\n      return parsed as SessionStore;\n    } catch {\n      return {};\n    }\n  }\n\n  private async saveStore(store: SessionStore): Promise<void> {\n    await this.ensureStore();\n    await writeFile(this.statePath, JSON.stringify(store, null, 2), 'utf8');\n  }\n\n  private async getPtySpawn(): Promise<PtySpawnLike | null> {\n    if (this.ptySpawn) return this.ptySpawn;\n    if (this.ptyLoadFailed) return null;\n    try {\n      const mod = await import('node-pty') as unknown as { spawn?: PtySpawnLike; default?: { spawn?: PtySpawnLike } };\n      this.ptySpawn = mod?.spawn || mod?.default?.spawn || null;\n      return this.ptySpawn;\n    } catch {\n      this.ptyLoadFailed = true;\n      return null;\n    }\n  }\n\n  private async ensureSession(engine: string, sessionId: string, cwd: string, shell?: string): Promise<RuntimeSession | null> {\n    const key = this.makeKey(engine, sessionId);\n    const existing = this.runtime.get(key);\n    if (existing) return existing;\n\n    const spawn = await this.getPtySpawn();\n    if (!spawn) return null;\n\n    const chosenShell = shell || process.env.SHELL || '/bin/bash';\n    const pty = spawn(chosenShell, ['-l'], {\n      name: 'xterm-color',\n      cwd,\n      cols: process.stdout.columns || 120,\n      rows: process.stdout.rows || 30,\n      env: process.env\n    });\n\n    const session: RuntimeSession = {\n      key,\n      engine,\n      sessionId,\n      cwd,\n      shell: chosenShell,\n      createdAt: nowIso(),\n      updatedAt: nowIso(),\n      turns: 0,\n      busy: false,\n      pty\n    };\n    this.runtime.set(key, session);\n    await this.persistSessionMeta(session);\n    return session;\n  }\n\n  private async persistSessionMeta(session: RuntimeSession): Promise<void> {\n    const store = await this.loadStore();\n    store[session.key] = {\n      key: session.key,\n      engine: session.engine,\n      sessionId: session.sessionId,\n      cwd: session.cwd,\n      shell: session.shell,\n      createdAt: session.createdAt,\n      updatedAt: session.updatedAt,\n      turns: session.turns\n    };\n    await this.saveStore(store);\n  }\n\n  async list(): Promise<Record<string, NativeSessionSummary>> {\n    const store = await this.loadStore();\n    const out: Record<string, NativeSessionSummary> = {};\n    for (const [key, value] of Object.entries(store)) {\n      out[key] = {\n        ...value,\n        alive: this.runtime.has(key)\n      };\n    }\n    for (const [key, session] of this.runtime.entries()) {\n      if (!out[key]) {\n        out[key] = {\n          key,\n          engine: session.engine,\n          sessionId: session.sessionId,\n          cwd: session.cwd,\n          shell: session.shell,\n          createdAt: session.createdAt,\n          updatedAt: session.updatedAt,\n          turns: session.turns,\n          alive: true\n        };\n      }\n    }\n    return out;\n  }\n\n  async closeAll(): Promise<void> {\n    for (const [key, session] of this.runtime.entries()) {\n      try {\n        session.pty.kill();\n      } catch {\n        // ignore\n      }\n      this.runtime.delete(key);\n    }\n  }\n\n  async runInSession(params: {\n    engine: string;\n    sessionId: string;\n    cwd: string;\n    shell?: string;\n    command: string;\n    timeoutMs?: number;\n    onChunk?: (chunk: string) => void;\n  }): Promise<{ success: boolean; exitCode: number; stdout: string; stderr: string; mode: 'native-shell' | 'fallback' }> {\n    const session = await this.ensureSession(params.engine, params.sessionId, params.cwd, params.shell);\n    if (!session) {\n      return {\n        success: false,\n        exitCode: -1,\n        stdout: '',\n        stderr: 'native-session unavailable (node-pty missing)',\n        mode: 'fallback'\n      };\n    }\n    if (session.busy) {\n      return {\n        success: false,\n        exitCode: -1,\n        stdout: '',\n        stderr: `session ${session.key} is busy`,\n        mode: 'native-shell'\n      };\n    }\n    session.busy = true;\n    session.updatedAt = nowIso();\n    session.turns += 1;\n    await this.persistSessionMeta(session);\n\n    const sentinel = `__CREW_DONE_${randomUUID().replace(/-/g, '')}__`;\n    const markerCmd = `${params.command}\\necho ${shellQuote(`${sentinel}$?`) }\\n`;\n    const timeoutMs = Number(params.timeoutMs || 600000);\n\n    return new Promise((resolve) => {\n      let stdout = '';\n      let stderr = '';\n      let done = false;\n      const timer = setTimeout(() => {\n        if (done) return;\n        done = true;\n        session.busy = false;\n        resolve({\n          success: false,\n          exitCode: -1,\n          stdout,\n          stderr: `${stderr}\\nTimed out after ${timeoutMs}ms`,\n          mode: 'native-shell'\n        });\n      }, timeoutMs);\n\n      const onData = (data: string) => {\n        const chunk = String(data || '');\n        const idx = chunk.indexOf(sentinel);\n        if (idx >= 0) {\n          const before = chunk.slice(0, idx);\n          if (before) {\n            stdout += before;\n            params.onChunk?.(before);\n          }\n          const codeMatch = chunk.slice(idx + sentinel.length).match(/^(\\d+)/);\n          const exitCode = codeMatch ? Number(codeMatch[1]) : 0;\n          if (!done) {\n            done = true;\n            clearTimeout(timer);\n            session.busy = false;\n            session.updatedAt = nowIso();\n            void this.persistSessionMeta(session);\n            session.pty.off?.('data', onData);\n            resolve({\n              success: exitCode === 0,\n              exitCode,\n              stdout: stdout.trim(),\n              stderr: stderr.trim(),\n              mode: 'native-shell'\n            });\n          }\n          return;\n        }\n        stdout += chunk;\n        params.onChunk?.(chunk);\n      };\n\n      session.pty.onData(onData);\n      try {\n        session.pty.write(markerCmd);\n      } catch (err) {\n        if (!done) {\n          done = true;\n          clearTimeout(timer);\n          session.busy = false;\n          session.pty.off?.('data', onData);\n          resolve({\n            success: false,\n            exitCode: -1,\n            stdout,\n            stderr: String((err as Error)?.message || err),\n            mode: 'native-shell'\n          });\n        }\n      }\n    });\n  }\n}\n\nfunction resolveCursorAgentBinQuoted(): string {\n  const fromEnv = String(process.env.CURSOR_CLI_BIN || '').trim();\n  if (fromEnv) return shellQuote(fromEnv);\n  const agentLocal = join(homedir(), '.local', 'bin', 'agent');\n  if (existsSync(agentLocal)) return shellQuote(agentLocal);\n  return 'agent';\n}\n\n/** cwd: working directory / --workspace for CLI engines that need it (e.g. Cursor agent). */\nexport function buildEngineShellCommand(engine: string, prompt: string, model?: string, cwd?: string): string {\n  const p = shellQuote(prompt);\n  const m = model ? ` -m ${shellQuote(model)}` : '';\n  const e = String(engine || '').trim().toLowerCase();\n  if (e === 'codex-cli') return `codex -a never exec --sandbox danger-full-access --skip-git-repo-check --json ${p}`;\n  if (e === 'claude-cli') return `claude -p --setting-sources user --output-format stream-json --verbose${String(process.env.CREW_CLAUDE_SKIP_PERMISSIONS || 'true') !== 'false' ? ' --dangerously-skip-permissions' : ''} -- ${p}`;\n  if (e === 'cursor-cli' || e === 'cursor') {\n    const ws = shellQuote(cwd || process.cwd());\n    const cursorDefault = process.env.CREWSWARM_CURSOR_MODEL || 'composer-2-fast';\n    let mod = model;\n    if (!mod || String(mod).trim() === '') mod = cursorDefault;\n    else if (String(mod).includes('/')) mod = cursorDefault;\n    else if (String(mod).includes('sonnet-4.6')) mod = 'sonnet-4.5';\n    const mq = shellQuote(mod);\n    const bin = resolveCursorAgentBinQuoted();\n    return `${bin} -p --force --trust --output-format stream-json ${p} --model ${mq} --workspace ${ws}`;\n  }\n  if (e === 'gemini-cli') return `gemini -p ${p}${model ? ` -m ${shellQuote(model)}` : ''} --output-format stream-json --yolo`;\n  if (e === 'opencode-cli' || e === 'opencode') return `opencode run${m} ${p}`;\n  return '';\n}\n", "import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nexport interface ToolCallRecord {\n  name: string;\n  args: Record<string, unknown>;\n}\n\nexport interface ToolAuditRun {\n  runId: string;\n  ts: string;\n  engine: string;\n  sessionId?: string;\n  prompt: string;\n  success: boolean;\n  exitCode: number;\n  toolCalls: ToolCallRecord[];\n  rawOutputPreview: string;\n}\n\nfunction clip(text: string, max = 3000): string {\n  const value = String(text || '');\n  if (value.length <= max) return value;\n  return `${value.slice(0, max)}\\n...[truncated]`;\n}\n\nexport function extractToolCalls(raw: string): ToolCallRecord[] {\n  const text = String(raw || '');\n  const calls: ToolCallRecord[] = [];\n\n  const add = (name: string, args: Record<string, unknown>) => {\n    calls.push({ name: String(name || '').trim(), args: args || {} });\n  };\n\n  const writeRe = /@@WRITE_FILE\\s+([^\\n]+)/g;\n  let m: RegExpExecArray | null;\n  while ((m = writeRe.exec(text)) !== null) add('write_file', { file_path: String(m[1] || '').trim() });\n\n  const readRe = /@@READ_FILE\\s+([^\\n]+)/g;\n  while ((m = readRe.exec(text)) !== null) add('read_file', { file_path: String(m[1] || '').trim() });\n\n  const editRe = /@@EDIT\\s+\"([^\"]+)\"\\s*\u2192\\s*\"([^\"]+)\"\\s+([^\\n]+)/g;\n  while ((m = editRe.exec(text)) !== null) {\n    add('edit', {\n      old_string: String(m[1] || ''),\n      new_string: String(m[2] || ''),\n      file_path: String(m[3] || '').trim()\n    });\n  }\n\n  const mkdirRe = /@@MKDIR\\s+([^\\n]+)/g;\n  while ((m = mkdirRe.exec(text)) !== null) add('mkdir', { path: String(m[1] || '').trim() });\n\n  const cmdRe = /@@RUN_CMD\\s+([^\\n]+)/g;\n  while ((m = cmdRe.exec(text)) !== null) add('run_cmd', { command: String(m[1] || '').trim() });\n\n  const toolJsonRe = /@@TOOL\\s+([^\\n]+)/g;\n  while ((m = toolJsonRe.exec(text)) !== null) {\n    const rawArgs = String(m[1] || '').trim();\n    if (!rawArgs) continue;\n    try {\n      if (rawArgs.startsWith('{')) {\n        const parsed = JSON.parse(rawArgs);\n        const n = String(parsed?.name || parsed?.tool || '').trim();\n        const a = parsed?.args || parsed?.params || {};\n        if (n) add(n, (a && typeof a === 'object') ? a : {});\n      }\n    } catch {\n      // ignore malformed\n    }\n  }\n\n  const fenced = text.match(/```json\\s*([\\s\\S]*?)```/gi) || [];\n  for (const block of fenced) {\n    const payload = block.replace(/^```json/i, '').replace(/```$/i, '').trim();\n    try {\n      const parsed = JSON.parse(payload);\n      const tc = Array.isArray(parsed?.tool_calls) ? parsed.tool_calls : [];\n      for (const t of tc) {\n        const name = String(t?.function?.name || t?.name || '').trim();\n        if (!name) continue;\n        const argsRaw = t?.function?.arguments ?? t?.arguments ?? {};\n        let args: Record<string, unknown> = {};\n        if (typeof argsRaw === 'string') {\n          try { args = JSON.parse(argsRaw); } catch { args = {}; }\n        } else if (argsRaw && typeof argsRaw === 'object') {\n          args = argsRaw as Record<string, unknown>;\n        }\n        add(name, args);\n      }\n    } catch {\n      // ignore\n    }\n  }\n\n  return calls.filter(c => c.name.length > 0);\n}\n\nexport class ToolAuditStore {\n  private readonly baseDir: string;\n  private readonly dir: string;\n  private readonly indexPath: string;\n\n  constructor(baseDir: string = process.cwd()) {\n    this.baseDir = resolve(baseDir);\n    this.dir = join(this.baseDir, '.crew', 'tool-audit');\n    this.indexPath = join(this.baseDir, '.crew', 'tool-audit.jsonl');\n  }\n\n  private async ensureDir(): Promise<void> {\n    await mkdir(this.dir, { recursive: true });\n  }\n\n  async record(run: ToolAuditRun): Promise<void> {\n    await this.ensureDir();\n    const runPath = join(this.dir, `${run.runId}.json`);\n    await writeFile(runPath, JSON.stringify(run, null, 2), 'utf8');\n    await appendFile(this.indexPath, `${JSON.stringify({\n      runId: run.runId,\n      ts: run.ts,\n      engine: run.engine,\n      sessionId: run.sessionId || '',\n      success: run.success,\n      exitCode: run.exitCode,\n      toolCount: run.toolCalls.length\n    })}\\n`, 'utf8');\n  }\n\n  async loadRun(runId: string): Promise<ToolAuditRun | null> {\n    try {\n      const raw = await readFile(join(this.dir, `${runId}.json`), 'utf8');\n      return JSON.parse(raw) as ToolAuditRun;\n    } catch {\n      return null;\n    }\n  }\n\n  async list(limit = 30): Promise<Array<Record<string, unknown>>> {\n    if (!existsSync(this.indexPath)) return [];\n    const raw = await readFile(this.indexPath, 'utf8');\n    const rows = raw.split('\\n').map(l => l.trim()).filter(Boolean).map((line) => {\n      try { return JSON.parse(line); } catch { return null; }\n    }).filter(Boolean) as Array<Record<string, unknown>>;\n    return rows.slice(-Math.max(1, limit)).reverse();\n  }\n}\n\nexport function buildReplayPlan(run: ToolAuditRun): {\n  runId: string;\n  deterministicOrder: ToolCallRecord[];\n  supportedMutations: ToolCallRecord[];\n} {\n  const supported = new Set(['write_file', 'edit', 'mkdir']);\n  const ordered = Array.isArray(run.toolCalls) ? [...run.toolCalls] : [];\n  return {\n    runId: run.runId,\n    deterministicOrder: ordered,\n    supportedMutations: ordered.filter(c => supported.has(String(c.name || '').toLowerCase()))\n  };\n}\n\nexport function previewAuditOutput(rawOutput: string): string {\n  return clip(rawOutput, 5000);\n}\n", "import { watch } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { StudioBroadcaster } from '../studio/broadcaster.js';\n\ninterface ChokidarWatcher {\n  on(event: 'change' | 'add' | 'unlink', listener: (file: string) => Promise<void> | void): ChokidarWatcher;\n}\n\ninterface ChokidarModule {\n  watch(rootDir: string, options: { ignored: string[]; ignoreInitial: boolean }): ChokidarWatcher;\n}\n\nexport interface WatchEvent {\n  type: 'todo_detected' | 'file_changed';\n  file: string;\n  todoCount?: number;\n  todos?: string[];\n}\n\nfunction extractTodos(content: string): string[] {\n  const todos: string[] = [];\n  const lines = content.split('\\n');\n  for (const line of lines) {\n    if (line.toLowerCase().includes('todo')) {\n      todos.push(line.trim());\n    }\n  }\n  return todos;\n}\n\nexport async function inspectFileForTodos(path: string): Promise<WatchEvent> {\n  let content = '';\n  try {\n    content = await readFile(path, 'utf8');\n  } catch {\n    return { type: 'file_changed', file: path };\n  }\n\n  const todos = extractTodos(content);\n  if (todos.length > 0) {\n    return {\n      type: 'todo_detected',\n      file: path,\n      todoCount: todos.length,\n      todos\n    };\n  }\n\n  return { type: 'file_changed', file: path };\n}\n\nexport function startWatchMode(\n  rootDir: string,\n  onEvent: (event: WatchEvent) => Promise<void> | void,\n  ignored: string[] = ['node_modules', '.git', 'dist', '.crew'],\n  options?: { broadcastToStudio?: boolean; studioUrl?: string }\n) {\n  // Initialize Studio broadcaster if requested\n  let broadcaster: StudioBroadcaster | null = null;\n  if (options?.broadcastToStudio) {\n    broadcaster = new StudioBroadcaster(options?.studioUrl);\n    broadcaster.connect().catch(() => {\n      // Studio not running - continue without broadcast\n    });\n  }\n\n  // Prefer chokidar if available for robust cross-platform watching.\n  try {\n    const chokidarMod = (globalThis as { __crewChokidarCache?: ChokidarModule }).__crewChokidarCache\n      || null;\n    if (chokidarMod?.watch) {\n      const watcher = chokidarMod.watch(rootDir, { ignored, ignoreInitial: true });\n      \n      watcher.on('change', async (file: string) => {\n        const event = await inspectFileForTodos(file);\n        await onEvent(event);\n        \n        // Broadcast to Studio\n        if (broadcaster) {\n          await broadcaster.broadcastFileChange(file, true);\n        }\n      });\n      \n      watcher.on('add', async (file: string) => {\n        if (broadcaster) {\n          await broadcaster.broadcastFileCreated(file);\n        }\n      });\n      \n      watcher.on('unlink', async (file: string) => {\n        if (broadcaster) {\n          await broadcaster.broadcastFileDeleted(file);\n        }\n      });\n      \n      return watcher;\n    }\n  } catch {\n    // fallback below\n  }\n\n  const watcher = watch(rootDir, { recursive: true }, async (eventType, filename) => {\n    if (!filename) return;\n    const relative = String(filename);\n    if (ignored.some(p => relative.includes(p))) return;\n\n    const fullPath = join(rootDir, relative);\n    const event = await inspectFileForTodos(fullPath);\n    await onEvent(event);\n    \n    // Broadcast to Studio\n    if (broadcaster) {\n      if (eventType === 'rename') {\n        // Could be add or delete - check if file exists\n        await broadcaster.broadcastFileChange(fullPath, true);\n      } else {\n        await broadcaster.broadcastFileChange(fullPath, true);\n      }\n    }\n  });\n\n  return watcher;\n}\n\n// Lazy-load chokidar once if installed.\nvoid import('chokidar')\n  .then(mod => {\n    (globalThis as unknown as Record<string, unknown>).__crewChokidarCache = mod.default || mod;\n  })\n  .catch(() => {\n    // optional dependency\n  });\n", "/**\n * Studio Broadcaster\n * Sends file changes from CLI to Studio via WebSocket\n */\n\nimport WebSocket from 'ws';\nimport { readFile } from 'node:fs/promises';\nimport { Logger } from '../utils/logger.js';\n\nexport interface FileBroadcastEvent {\n  type: 'file-changed' | 'file-created' | 'file-deleted';\n  path: string;\n  content?: string;\n  timestamp: number;\n}\n\nexport class StudioBroadcaster {\n  private ws: WebSocket | null = null;\n  private connected = false;\n  private reconnectTimer: NodeJS.Timeout | null = null;\n  private logger: Logger;\n  private studioUrl: string;\n\n  constructor(studioUrl = 'ws://127.0.0.1:3334/ws', logger?: Logger) {\n    this.studioUrl = studioUrl;\n    this.logger = logger || new Logger({ prefix: 'studio' });\n  }\n\n  async connect(): Promise<void> {\n    return new Promise((resolve, reject) => {\n      try {\n        this.ws = new WebSocket(this.studioUrl);\n\n        this.ws.on('open', () => {\n          this.connected = true;\n          this.logger.info('Connected to Studio watch server');\n          resolve();\n        });\n\n        this.ws.on('close', () => {\n          this.connected = false;\n          this.logger.info('Disconnected from Studio');\n          this.scheduleReconnect();\n        });\n\n        this.ws.on('error', (err: Error) => {\n          this.logger.error('Studio WebSocket error:', err.message);\n          if (!this.connected) {\n            reject(err);\n          }\n        });\n      } catch (err) {\n        reject(err);\n      }\n    });\n  }\n\n  private scheduleReconnect(): void {\n    if (this.reconnectTimer) return;\n    \n    this.reconnectTimer = setTimeout(() => {\n      this.reconnectTimer = null;\n      this.logger.info('Attempting to reconnect to Studio...');\n      this.connect().catch(() => {\n        // Will retry again via scheduleReconnect\n      });\n    }, 5000);\n  }\n\n  async broadcastFileChange(filePath: string, includeContent = true): Promise<void> {\n    if (!this.connected || !this.ws) {\n      // Silently skip if not connected\n      return;\n    }\n\n    try {\n      const event: FileBroadcastEvent = {\n        type: 'file-changed',\n        path: filePath,\n        timestamp: Date.now()\n      };\n\n      if (includeContent) {\n        try {\n          event.content = await readFile(filePath, 'utf8');\n        } catch {\n          // File might be binary or deleted - send without content\n          event.content = undefined;\n        }\n      }\n\n      this.ws.send(JSON.stringify(event));\n    } catch (err) {\n      this.logger.error('Failed to broadcast file change:', err);\n    }\n  }\n\n  async broadcastFileCreated(filePath: string, content?: string): Promise<void> {\n    if (!this.connected || !this.ws) return;\n\n    try {\n      const event: FileBroadcastEvent = {\n        type: 'file-created',\n        path: filePath,\n        content,\n        timestamp: Date.now()\n      };\n\n      this.ws.send(JSON.stringify(event));\n    } catch (err) {\n      this.logger.error('Failed to broadcast file creation:', err);\n    }\n  }\n\n  async broadcastFileDeleted(filePath: string): Promise<void> {\n    if (!this.connected || !this.ws) return;\n\n    try {\n      const event: FileBroadcastEvent = {\n        type: 'file-deleted',\n        path: filePath,\n        timestamp: Date.now()\n      };\n\n      this.ws.send(JSON.stringify(event));\n    } catch (err) {\n      this.logger.error('Failed to broadcast file deletion:', err);\n    }\n  }\n\n  disconnect(): void {\n    if (this.reconnectTimer) {\n      clearTimeout(this.reconnectTimer);\n      this.reconnectTimer = null;\n    }\n\n    if (this.ws) {\n      this.ws.close();\n      this.ws = null;\n    }\n\n    this.connected = false;\n  }\n\n  isConnected(): boolean {\n    return this.connected;\n  }\n}\n", "import chalk from 'chalk';\n\nconst BANNER = `\n \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551                                                                           \u2551\n \u2551     \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557    \u2588\u2588\u2557      \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557     \u2588\u2588\u2557           \u2551\n \u2551    \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551    \u2588\u2588\u2551     \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n \u2551    \u2588\u2588\u2551      \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2557  \u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n \u2551    \u2588\u2588\u2551      \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u255D  \u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n \u2551    \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551  \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D     \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551           \u2551\n \u2551     \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D  \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D       \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D           \u2551\n \u2551                                                                           \u2551\n \u2551              \uD83C\uDFAA  Multi-Agent Orchestrator  \u2022  v0.1.0-alpha                \u2551\n \u2551                                                                           \u2551\n \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n`;\n\nexport function getBanner(): string {\n  return chalk.cyan(BANNER);\n}\n\nexport function helloWorld(): string {\n  return \"Hello, World!\";\n}\n", "import { readdir, access, mkdir, writeFile } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface RepoSummary {\n  name: string;\n  path: string;\n  branch: string;\n  statusShort: string;\n  recentCommit: string;\n}\n\nasync function exists(path: string): Promise<boolean> {\n  try {\n    await access(path, constants.F_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nasync function runGit(repoPath: string, args: string[]): Promise<string> {\n  const { stdout } = await execFileAsync('git', args, {\n    cwd: repoPath,\n    maxBuffer: 1024 * 1024 * 2\n  });\n  return stdout.trim();\n}\n\nexport async function findSiblingRepos(baseDir = process.cwd()): Promise<string[]> {\n  const abs = resolve(baseDir);\n  const parent = dirname(abs);\n  const currentName = abs.split('/').pop() || '';\n  const entries = await readdir(parent, { withFileTypes: true });\n\n  const repos: string[] = [];\n  for (const entry of entries) {\n    if (!entry.isDirectory()) continue;\n    if (entry.name === currentName) continue;\n    const repoPath = join(parent, entry.name);\n    if (await exists(join(repoPath, '.git'))) {\n      repos.push(repoPath);\n    }\n  }\n  return repos;\n}\n\nexport async function getRepoSummary(repoPath: string): Promise<RepoSummary> {\n  const [branch, statusShort, recentCommit] = await Promise.all([\n    runGit(repoPath, ['branch', '--show-current']).catch(() => '(unknown)'),\n    runGit(repoPath, ['status', '--short']).catch(() => ''),\n    runGit(repoPath, ['log', '-1', '--oneline']).catch(() => '(none)')\n  ]);\n\n  return {\n    name: repoPath.split('/').pop() || repoPath,\n    path: repoPath,\n    branch: branch || '(detached)',\n    statusShort: statusShort || '(clean)',\n    recentCommit\n  };\n}\n\nexport async function collectMultiRepoContext(baseDir = process.cwd()): Promise<string> {\n  const siblings = await findSiblingRepos(baseDir);\n  if (siblings.length === 0) {\n    return '## Cross-Repo Context\\n```text\\nNo sibling git repositories found.\\n```';\n  }\n\n  const summaries = await Promise.all(siblings.map(path => getRepoSummary(path)));\n  const lines = summaries.flatMap(summary => [\n    `${summary.name} (${summary.path})`,\n    `  branch: ${summary.branch}`,\n    `  recent: ${summary.recentCommit}`,\n    `  status: ${summary.statusShort}`,\n    ''\n  ]);\n\n  return ['## Cross-Repo Context', '```text', ...lines, '```'].join('\\n');\n}\n\nexport async function syncRepoSnapshots(baseDir = process.cwd()): Promise<string> {\n  const siblings = await findSiblingRepos(baseDir);\n  const summaries = await Promise.all(siblings.map(path => getRepoSummary(path)));\n  const outDir = join(baseDir, '.crew');\n  await mkdir(outDir, { recursive: true });\n  const outPath = join(outDir, 'multi-repo-sync.json');\n  await writeFile(\n    outPath,\n    JSON.stringify({ syncedAt: new Date().toISOString(), repos: summaries }, null, 2),\n    'utf8'\n  );\n  return outPath;\n}\n\nexport async function detectBreakingApiSignals(repoPath: string): Promise<string[]> {\n  const changedFilesRaw = await runGit(repoPath, ['diff', '--name-only']).catch(() => '');\n  const changedFiles = changedFilesRaw.split('\\n').map(s => s.trim()).filter(Boolean);\n  const warnings: string[] = [];\n\n  for (const file of changedFiles) {\n    if (/(api|route|routes|schema|openapi|proto|graphql|types?)/i.test(file)) {\n      warnings.push(`Potential API-impacting file changed: ${file}`);\n    }\n  }\n\n  const diffText = await runGit(repoPath, ['diff']).catch(() => '');\n  const removedExports = (diffText.match(/^-.*export\\s+(interface|type|class|function)\\s+/gm) || []).length;\n  if (removedExports > 0) {\n    warnings.push(`Detected ${removedExports} removed exported symbols.`);\n  }\n\n  const removedRoutes = (diffText.match(/^-.*(app\\.(get|post|put|delete)|router\\.(get|post|put|delete))/gm) || []).length;\n  if (removedRoutes > 0) {\n    warnings.push(`Detected ${removedRoutes} removed route handlers.`);\n  }\n\n  return warnings;\n}\n", "import { spawn, ChildProcess } from 'node:child_process';\nimport { access, readFile, writeFile } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport WebSocket from 'ws';\n\nconst execFileAsync = promisify(execFile);\n\nasync function exists(path: string): Promise<boolean> {\n  try {\n    await access(path, constants.F_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function findChromeExecutable(): Promise<string | null> {\n  if (process.env.CHROME_BIN) return process.env.CHROME_BIN;\n  const candidates = [\n    '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',\n    '/Applications/Chromium.app/Contents/MacOS/Chromium',\n    'google-chrome',\n    'chromium',\n    'chromium-browser',\n    'chrome'\n  ];\n\n  for (const candidate of candidates) {\n    if (candidate.startsWith('/')) {\n      if (await exists(candidate)) return candidate;\n      continue;\n    }\n    try {\n      const { stdout } = await execFileAsync('which', [candidate]);\n      const bin = stdout.trim();\n      if (bin) return bin;\n    } catch {\n      // continue\n    }\n  }\n  return null;\n}\n\nexport async function launchChromeDebug(url: string, port = 9222): Promise<ChildProcess> {\n  const chrome = await findChromeExecutable();\n  if (!chrome) {\n    throw new Error('Chrome/Chromium binary not found. Set CHROME_BIN or install Chrome.');\n  }\n\n  const userDataDir = join(tmpdir(), `crew-browser-debug-${Date.now()}`);\n  const args = [\n    `--remote-debugging-port=${port}`,\n    `--user-data-dir=${userDataDir}`,\n    '--no-first-run',\n    '--no-default-browser-check',\n    '--headless=new',\n    '--disable-gpu',\n    url\n  ];\n\n  const proc = spawn(chrome, args, { stdio: 'ignore' });\n  return proc;\n}\n\nexport type CdpEventHandler = (params: Record<string, unknown>) => void;\n\nexport class CdpClient {\n  ws: WebSocket;\n  id = 0;\n  pending = new Map<number, (value: Record<string, unknown>) => void>();\n  handlers = new Map<string, CdpEventHandler[]>();\n\n  constructor(ws: WebSocket) {\n    this.ws = ws;\n    ws.on('message', data => {\n      const payload = JSON.parse(String(data));\n      if (payload.id && this.pending.has(payload.id)) {\n        this.pending.get(payload.id)?.(payload);\n        this.pending.delete(payload.id);\n      } else if (payload.method && this.handlers.has(payload.method)) {\n        for (const handler of this.handlers.get(payload.method) || []) {\n          handler(payload.params || {});\n        }\n      }\n    });\n  }\n\n  send(method: string, params: Record<string, unknown> = {}) {\n    const id = ++this.id;\n    return new Promise<Record<string, unknown>>((resolve, reject) => {\n      this.pending.set(id, resolve);\n      this.ws.send(JSON.stringify({ id, method, params }), err => {\n        if (err) reject(err);\n      });\n    });\n  }\n\n  on(method: string, handler: CdpEventHandler) {\n    const list = this.handlers.get(method) || [];\n    list.push(handler);\n    this.handlers.set(method, list);\n  }\n}\n\nexport interface BrowserDebugResult {\n  consoleErrors: string[];\n  screenshotPath?: string;\n}\n\ninterface DevToolsTarget {\n  type?: string;\n  webSocketDebuggerUrl?: string;\n}\n\ninterface DevToolsVersionResponse {\n  webSocketDebuggerUrl?: string;\n}\n\ninterface ConsoleArg {\n  value?: string | number | boolean | null;\n  description?: string;\n}\n\ninterface ConsoleApiParams {\n  type?: string;\n  args?: ConsoleArg[];\n}\n\ninterface ExceptionParams {\n  exceptionDetails?: {\n    text?: string;\n  };\n}\n\ninterface LogEntryParams {\n  entry?: {\n    level?: string;\n    text?: string;\n  };\n}\n\ninterface CaptureScreenshotResponse {\n  result?: {\n    data?: string;\n  };\n  data?: string;\n}\n\nexport async function getPageWsUrl(port: number, timeoutMs = 10000): Promise<string> {\n  const start = Date.now();\n  while (Date.now() - start < timeoutMs) {\n    try {\n      const res = await fetch(`http://127.0.0.1:${port}/json`);\n      if (res.ok) {\n        const targets = await res.json() as DevToolsTarget[];\n        const page = targets.find(t => t.type === 'page');\n        if (page?.webSocketDebuggerUrl) return page.webSocketDebuggerUrl;\n      }\n    } catch {\n      // retry\n    }\n    await new Promise(resolve => setTimeout(resolve, 300));\n  }\n  throw new Error('Timed out waiting for Chrome Page target.');\n}\n\nexport async function waitForWsDebuggerUrl(port: number, timeoutMs = 10000): Promise<string> {\n  const start = Date.now();\n  while (Date.now() - start < timeoutMs) {\n    try {\n      const res = await fetch(`http://127.0.0.1:${port}/json/version`);\n      if (res.ok) {\n        const data = await res.json() as DevToolsVersionResponse;\n        if (data.webSocketDebuggerUrl) return data.webSocketDebuggerUrl;\n      }\n    } catch {\n      // retry\n    }\n    await new Promise(resolve => setTimeout(resolve, 300));\n  }\n  throw new Error('Timed out waiting for Chrome DevTools endpoint.');\n}\n\nexport async function runBrowserDebug(url: string, options: { port?: number; durationMs?: number; screenshotPath?: string } = {}): Promise<BrowserDebugResult> {\n  const port = options.port || 9222;\n  const durationMs = options.durationMs || 5000;\n  const proc = await launchChromeDebug(url, port);\n  let ws: WebSocket | null = null;\n\n  try {\n    const wsUrl = await waitForWsDebuggerUrl(port);\n    ws = new WebSocket(wsUrl);\n\n    await new Promise<void>((resolve, reject) => {\n      ws?.once('open', () => resolve());\n      ws?.once('error', reject);\n    });\n\n    const client = new CdpClient(ws);\n    const errors: string[] = [];\n\n    client.on('Runtime.consoleAPICalled', params => {\n      const consoleParams = params as ConsoleApiParams;\n      const level = consoleParams.type || 'log';\n      if (level === 'error' || level === 'warning') {\n        const text = (consoleParams.args || []).map((a) => a.value || a.description || '').join(' ');\n        errors.push(`[console:${level}] ${text}`.trim());\n      }\n    });\n\n    client.on('Runtime.exceptionThrown', params => {\n      const exceptionParams = params as ExceptionParams;\n      const desc = exceptionParams.exceptionDetails?.text || 'Exception thrown';\n      errors.push(`[exception] ${desc}`);\n    });\n\n    client.on('Log.entryAdded', params => {\n      const logParams = params as LogEntryParams;\n      const level = logParams.entry?.level || 'info';\n      if (level === 'error' || level === 'warning') {\n        errors.push(`[log:${level}] ${logParams.entry?.text || ''}`.trim());\n      }\n    });\n\n    await client.send('Runtime.enable');\n    await client.send('Log.enable');\n    await client.send('Page.enable');\n    await client.send('Page.navigate', { url });\n    await new Promise(resolve => setTimeout(resolve, durationMs));\n\n    let screenshotPath = options.screenshotPath;\n    const screenshotRes = await client.send('Page.captureScreenshot', { format: 'png', fromSurface: true }) as CaptureScreenshotResponse;\n    if (!screenshotPath) {\n      screenshotPath = join(process.cwd(), '.crew', `browser-shot-${Date.now()}.png`);\n    }\n    await writeFile(screenshotPath, Buffer.from(screenshotRes.result?.data || screenshotRes.data || '', 'base64'));\n\n    return { consoleErrors: errors, screenshotPath };\n  } finally {\n    try {\n      ws?.close();\n    } catch (e) {\n      console.error(`Failed to close WebSocket: ${(e as Error).message}`);\n    }\n    try {\n      proc.kill('SIGTERM');\n    } catch (e) {\n      console.error(`Failed to kill browser process: ${(e as Error).message}`);\n    }\n  }\n}\n\nexport function compareScreenshotBuffers(a: Buffer, b: Buffer) {\n  const max = Math.max(a.length, b.length);\n  if (max === 0) return { diffBytes: 0, diffPercent: 0 };\n  let diff = 0;\n  for (let i = 0; i < max; i++) {\n    const av = i < a.length ? a[i] : 0;\n    const bv = i < b.length ? b[i] : 0;\n    if (av !== bv) diff++;\n  }\n  return {\n    diffBytes: diff,\n    diffPercent: (diff / max) * 100\n  };\n}\n\nexport async function compareScreenshots(pathA: string, pathB: string) {\n  const [a, b] = await Promise.all([readFile(pathA), readFile(pathB)]);\n  return compareScreenshotBuffers(a, b);\n}\n", "// @ts-nocheck\nimport { access, copyFile, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { homedir, hostname } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface PrivacyControls {\n  sharePrompt: boolean;\n  shareOriginal: boolean;\n  shareCorrected: boolean;\n  shareTags: boolean;\n}\n\nconst DEFAULT_PRIVACY: PrivacyControls = {\n  sharePrompt: true,\n  shareOriginal: true,\n  shareCorrected: true,\n  shareTags: true\n};\n\nasync function exists(path: string): Promise<boolean> {\n  try {\n    await access(path, constants.F_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nfunction getStateDir(baseDir = process.cwd()) {\n  return join(baseDir, '.crew');\n}\n\nfunction getTeamSyncDir(baseDir = process.cwd()) {\n  return process.env.TEAM_SYNC_DIR || join(getStateDir(baseDir), 'team-sync');\n}\n\nfunction getPrivacyPath(baseDir = process.cwd()) {\n  return join(getStateDir(baseDir), 'privacy.json');\n}\n\nfunction applyPrivacyToCorrection(entry: Record<string, unknown>, privacy: PrivacyControls) {\n  const output: Record<string, unknown> = {\n    timestamp: entry.timestamp,\n    agent: entry.agent || null\n  };\n  if (privacy.sharePrompt) output.prompt = entry.prompt;\n  if (privacy.shareOriginal) output.original = entry.original;\n  if (privacy.shareCorrected) output.corrected = entry.corrected;\n  if (privacy.shareTags) output.tags = entry.tags || [];\n  return output;\n}\n\nexport async function loadPrivacyControls(baseDir = process.cwd()): Promise<PrivacyControls> {\n  const path = getPrivacyPath(baseDir);\n  if (!(await exists(path))) {\n    await mkdir(getStateDir(baseDir), { recursive: true });\n    await writeFile(path, JSON.stringify(DEFAULT_PRIVACY, null, 2), 'utf8');\n    return { ...DEFAULT_PRIVACY };\n  }\n\n  try {\n    const raw = await readFile(path, 'utf8');\n    const parsed = JSON.parse(raw);\n    return {\n      sharePrompt: parsed.sharePrompt !== false,\n      shareOriginal: parsed.shareOriginal !== false,\n      shareCorrected: parsed.shareCorrected !== false,\n      shareTags: parsed.shareTags !== false\n    };\n  } catch {\n    return { ...DEFAULT_PRIVACY };\n  }\n}\n\nexport async function savePrivacyControls(privacy: PrivacyControls, baseDir = process.cwd()) {\n  await mkdir(getStateDir(baseDir), { recursive: true });\n  await writeFile(getPrivacyPath(baseDir), JSON.stringify(privacy, null, 2), 'utf8');\n}\n\nexport async function uploadTeamContext(baseDir = process.cwd()) {\n  const stateDir = getStateDir(baseDir);\n  const teamDir = getTeamSyncDir(baseDir);\n  await mkdir(teamDir, { recursive: true });\n\n  const sessionPath = join(stateDir, 'session.json');\n  const correctionsPath = join(stateDir, 'training-data.jsonl');\n  const host = hostname().replace(/[^a-zA-Z0-9_-]/g, '_');\n  const sessionOut = join(teamDir, `${host}-session.json`);\n  const correctionsOut = join(teamDir, `${host}-training-data.jsonl`);\n\n  if (await exists(sessionPath)) {\n    if (process.env.TEAM_S3_SESSION_PUT_URL) {\n      const body = await readFile(sessionPath, 'utf8');\n      await fetch(process.env.TEAM_S3_SESSION_PUT_URL, { method: 'PUT', body });\n    }\n    await copyFile(sessionPath, sessionOut);\n  }\n\n  if (await exists(correctionsPath)) {\n    let correctionsRaw = await readFile(correctionsPath, 'utf8');\n    const privacy = await loadPrivacyControls(baseDir);\n    if (correctionsRaw.trim().length > 0) {\n      const lines = correctionsRaw.split('\\n').map(s => s.trim()).filter(Boolean);\n      const filtered = lines.map(line => applyPrivacyToCorrection(JSON.parse(line), privacy));\n      correctionsRaw = `${filtered.map(item => JSON.stringify(item)).join('\\n')}\\n`;\n    }\n\n    if (process.env.TEAM_S3_CORRECTIONS_PUT_URL) {\n      await fetch(process.env.TEAM_S3_CORRECTIONS_PUT_URL, { method: 'PUT', body: correctionsRaw });\n    }\n    await writeFile(correctionsOut, correctionsRaw, 'utf8');\n  }\n\n  return { sessionOut, correctionsOut };\n}\n\nexport async function downloadTeamContext(baseDir = process.cwd()) {\n  const stateDir = getStateDir(baseDir);\n  const teamDir = getTeamSyncDir(baseDir);\n  await mkdir(stateDir, { recursive: true });\n  await mkdir(teamDir, { recursive: true });\n\n  const localSessionPath = join(stateDir, 'session.json');\n  const localCorrectionsPath = join(stateDir, 'training-data.jsonl');\n\n  // S3 session pull (optional)\n  if (process.env.TEAM_S3_SESSION_GET_URL) {\n    const response = await fetch(process.env.TEAM_S3_SESSION_GET_URL);\n    if (response.ok) {\n      const text = await response.text();\n      await writeFile(localSessionPath, text, 'utf8');\n    }\n  }\n\n  // S3 corrections pull (optional)\n  if (process.env.TEAM_S3_CORRECTIONS_GET_URL) {\n    const response = await fetch(process.env.TEAM_S3_CORRECTIONS_GET_URL);\n    if (response.ok) {\n      const text = await response.text();\n      await writeFile(localCorrectionsPath, text, 'utf8');\n    }\n  }\n\n  // Local shared folder sync fallback/merge.\n  const files = await readdir(teamDir);\n  const sessionCandidates = files.filter(name => name.endsWith('-session.json'));\n  const correctionCandidates = files.filter(name => name.endsWith('-training-data.jsonl'));\n\n  if (sessionCandidates.length > 0 && !(await exists(localSessionPath))) {\n    const src = join(teamDir, sessionCandidates.sort().at(-1) as string);\n    await copyFile(src, localSessionPath);\n  }\n\n  let mergedCorrections = '';\n  const seen = new Set<string>();\n\n  if (await exists(localCorrectionsPath)) {\n    const local = await readFile(localCorrectionsPath, 'utf8');\n    for (const line of local.split('\\n').map(s => s.trim()).filter(Boolean)) {\n      seen.add(line);\n      mergedCorrections += `${line}\\n`;\n    }\n  }\n\n  for (const file of correctionCandidates) {\n    const raw = await readFile(join(teamDir, file), 'utf8');\n    for (const line of raw.split('\\n').map(s => s.trim()).filter(Boolean)) {\n      if (!seen.has(line)) {\n        seen.add(line);\n        mergedCorrections += `${line}\\n`;\n      }\n    }\n  }\n\n  if (mergedCorrections.length > 0) {\n    await writeFile(localCorrectionsPath, mergedCorrections, 'utf8');\n  }\n\n  return {\n    sessionPath: localSessionPath,\n    correctionsPath: localCorrectionsPath,\n    mergedCount: seen.size\n  };\n}\n\nexport async function getTeamSyncStatus(baseDir = process.cwd()) {\n  const teamDir = getTeamSyncDir(baseDir);\n  await mkdir(teamDir, { recursive: true });\n  const files = await readdir(teamDir);\n  const privacy = await loadPrivacyControls(baseDir);\n  return {\n    teamDir,\n    files,\n    privacy\n  };\n}\n\nexport { applyPrivacyToCorrection };\n", "import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { AgentRouter } from '../agent/router.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface RecorderPlan {\n  command: string;\n  args: string[];\n}\n\nexport type RecorderKind = 'sox' | 'ffmpeg-mac' | 'ffmpeg-linux' | 'ffmpeg-windows';\n\nexport interface RecordOptions {\n  durationSec?: number;\n  outputPath?: string;\n}\n\nexport interface TranscribeOptions {\n  provider?: 'auto' | 'openai' | 'groq' | 'whisper-cli';\n}\n\nasync function commandExists(command: string): Promise<boolean> {\n  try {\n    await execFileAsync('which', [command]);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport function selectRecorderPlan(\n  platform: NodeJS.Platform,\n  hasSox: boolean,\n  hasFfmpeg: boolean,\n  outputPath: string,\n  durationSec: number\n): RecorderPlan | null {\n  if (hasSox) {\n    return {\n      command: 'sox',\n      args: ['-d', '-c', '1', '-r', '16000', outputPath, 'trim', '0', String(durationSec)]\n    };\n  }\n\n  if (hasFfmpeg) {\n    if (platform === 'darwin') {\n      return {\n        command: 'ffmpeg',\n        args: ['-y', '-f', 'avfoundation', '-i', ':0', '-t', String(durationSec), '-ac', '1', '-ar', '16000', outputPath]\n      };\n    }\n    if (platform === 'linux') {\n      return {\n        command: 'ffmpeg',\n        args: ['-y', '-f', 'alsa', '-i', 'default', '-t', String(durationSec), '-ac', '1', '-ar', '16000', outputPath]\n      };\n    }\n    return {\n      command: 'ffmpeg',\n      args: ['-y', '-f', 'dshow', '-i', 'audio=default', '-t', String(durationSec), '-ac', '1', '-ar', '16000', outputPath]\n    };\n  }\n\n  return null;\n}\n\nexport function selectRecorderStrategy(\n  available: { sox: boolean; ffmpeg: boolean },\n  platform: NodeJS.Platform = process.platform\n): RecorderKind | null {\n  if (available.sox) return 'sox';\n  if (!available.ffmpeg) return null;\n  if (platform === 'darwin') return 'ffmpeg-mac';\n  if (platform === 'linux') return 'ffmpeg-linux';\n  return 'ffmpeg-windows';\n}\n\nexport function buildRecorderStrategy(kind: RecorderKind, outputPath: string, durationSec: number): RecorderPlan {\n  if (kind === 'sox') {\n    return {\n      command: 'sox',\n      args: ['-d', '-c', '1', '-r', '16000', outputPath, 'trim', '0', String(durationSec)]\n    };\n  }\n  if (kind === 'ffmpeg-mac') {\n    return {\n      command: 'ffmpeg',\n      args: ['-y', '-f', 'avfoundation', '-i', ':0', '-t', String(durationSec), '-ac', '1', '-ar', '16000', outputPath]\n    };\n  }\n  if (kind === 'ffmpeg-linux') {\n    return {\n      command: 'ffmpeg',\n      args: ['-y', '-f', 'alsa', '-i', 'default', '-t', String(durationSec), '-ac', '1', '-ar', '16000', outputPath]\n    };\n  }\n  return {\n    command: 'ffmpeg',\n    args: ['-y', '-f', 'dshow', '-i', 'audio=default', '-t', String(durationSec), '-ac', '1', '-ar', '16000', outputPath]\n  };\n}\n\nexport async function recordAudio(options: RecordOptions = {}): Promise<string> {\n  const durationSec = Math.max(1, options.durationSec || 6);\n  const outputPath = options.outputPath || join(tmpdir(), `crew-listen-${Date.now()}.wav`);\n\n  const hasSox = await commandExists('sox');\n  const hasFfmpeg = await commandExists('ffmpeg');\n  const plan = selectRecorderPlan(process.platform, hasSox, hasFfmpeg, outputPath, durationSec);\n\n  if (!plan) {\n    throw new Error('No audio recorder found. Install sox or ffmpeg, or use --text.');\n  }\n\n  await execFileAsync(plan.command, plan.args, { maxBuffer: 1024 * 1024 * 16 });\n  return outputPath;\n}\n\nexport async function transcribeWithOpenAi(audioPath: string): Promise<string> {\n  const key = process.env.OPENAI_API_KEY;\n  if (!key) {\n    throw new Error('OPENAI_API_KEY is required for OpenAI Whisper transcription.');\n  }\n\n  const audioBuffer = await readFile(audioPath);\n  const blob = new Blob([audioBuffer], { type: 'audio/wav' });\n  const form = new FormData();\n  form.append('model', 'whisper-1');\n  form.append('file', blob, 'audio.wav');\n\n  const response = await fetch('https://api.openai.com/v1/audio/transcriptions', {\n    method: 'POST',\n    headers: { Authorization: `Bearer ${key}` },\n    body: form\n  });\n  if (!response.ok) {\n    const body = await response.text();\n    throw new Error(`Whisper API failed (${response.status}): ${body.slice(0, 400)}`);\n  }\n  const data = await response.json() as { text?: string };\n  return String(data.text || '').trim();\n}\n\nexport async function transcribeWithGroq(audioPath: string): Promise<string> {\n  const key = process.env.GROQ_API_KEY;\n  if (!key) {\n    throw new Error('GROQ_API_KEY is required for Groq Whisper transcription.');\n  }\n\n  const audioBuffer = await readFile(audioPath);\n  const blob = new Blob([audioBuffer], { type: 'audio/wav' });\n  const form = new FormData();\n  form.append('model', 'whisper-large-v3-turbo');\n  form.append('file', blob, 'audio.wav');\n  form.append('response_format', 'json');\n\n  const response = await fetch('https://api.groq.com/openai/v1/audio/transcriptions', {\n    method: 'POST',\n    headers: { Authorization: `Bearer ${key}` },\n    body: form\n  });\n  if (!response.ok) {\n    const body = await response.text();\n    throw new Error(`Groq Whisper API failed (${response.status}): ${body.slice(0, 400)}`);\n  }\n  const data = await response.json() as { text?: string };\n  return String(data.text || '').trim();\n}\n\nexport async function transcribeWithWhisperCli(audioPath: string): Promise<string> {\n  // Check for faster-whisper first (4x faster, same API as whisper)\n  const hasFasterWhisper = await commandExists('faster-whisper');\n  const hasWhisper = await commandExists('whisper');\n  \n  if (!hasFasterWhisper && !hasWhisper) {\n    throw new Error('Local whisper CLI is not installed. Install with: pip install faster-whisper');\n  }\n\n  const whisperCmd = hasFasterWhisper ? 'faster-whisper' : 'whisper';\n  const outDir = join(tmpdir(), `crew-whisper-${Date.now()}`);\n  await execFileAsync('mkdir', ['-p', outDir]);\n  \n  // Use tiny model for speed (base for quality)\n  const model = hasFasterWhisper ? 'tiny' : 'base';\n  \n  await execFileAsync(whisperCmd, [audioPath, '--model', model, '--output_format', 'txt', '--output_dir', outDir], {\n    maxBuffer: 1024 * 1024 * 16\n  });\n  const baseName = audioPath.split('/').pop()?.replace(/\\.[^.]+$/, '') || 'audio';\n  const txtPath = join(outDir, `${baseName}.txt`);\n  const text = await readFile(txtPath, 'utf8');\n  return text.trim();\n}\n\nexport async function transcribeAudio(audioPath: string, options: TranscribeOptions = {}): Promise<string> {\n  const provider = options.provider || 'auto';\n\n  if (provider === 'openai') {\n    return transcribeWithOpenAi(audioPath);\n  }\n  if (provider === 'groq') {\n    return transcribeWithGroq(audioPath);\n  }\n  if (provider === 'whisper-cli') {\n    return transcribeWithWhisperCli(audioPath);\n  }\n\n  // auto: try Groq first (fastest + cheapest), then OpenAI, then local CLI\n  if (process.env.GROQ_API_KEY) {\n    try {\n      return await transcribeWithGroq(audioPath);\n    } catch {\n      // fallback to next option\n    }\n  }\n  if (process.env.OPENAI_API_KEY) {\n    try {\n      return await transcribeWithOpenAi(audioPath);\n    } catch {\n      // fallback to local\n    }\n  }\n  return transcribeWithWhisperCli(audioPath);\n}\n\nexport async function speakWithSkill(router: AgentRouter, text: string, skill = 'elevenlabs.tts'): Promise<unknown> {\n  return router.callSkill(skill, { text });\n}\n\nexport async function speakText(router: AgentRouter, text: string, skill = 'elevenlabs.tts'): Promise<unknown> {\n  return speakWithSkill(router, text, skill);\n}\n\nexport async function appendVoiceTranscript(baseDir: string, role: 'user' | 'assistant', text: string) {\n  const path = join(baseDir, '.crew', 'voice-transcript.log');\n  await execFileAsync('mkdir', ['-p', join(baseDir, '.crew')]);\n  const line = JSON.stringify({\n    timestamp: new Date().toISOString(),\n    role,\n    text\n  });\n  await writeFile(path, `${line}\\n`, { encoding: 'utf8', flag: 'a' });\n}\n", "import { readFile } from 'node:fs/promises';\nimport { extname, resolve } from 'node:path';\nimport { getProjectContext } from './git.js';\n\nexport function collectOption(value: string, previous: string[] = []): string[] {\n  if (!value) return previous;\n  return [...previous, value];\n}\n\nexport async function readStdinText(): Promise<string> {\n  if (process.stdin.isTTY) return '';\n  let data = '';\n  for await (const chunk of process.stdin) {\n    data += String(chunk);\n  }\n  return data.trim();\n}\n\nfunction clip(text: string, maxChars: number): string {\n  if (text.length <= maxChars) return text;\n  return `${text.slice(0, maxChars)}\\n... [truncated ${text.length - maxChars} chars]`;\n}\n\nfunction inferImageMime(path: string): string | null {\n  const ext = extname(path).toLowerCase();\n  if (ext === '.png') return 'image/png';\n  if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';\n  if (ext === '.webp') return 'image/webp';\n  if (ext === '.gif') return 'image/gif';\n  return null;\n}\n\nexport async function buildFileContextBlock(paths: string[] = [], maxChars = 8000): Promise<string> {\n  if (!paths.length) return '';\n  const sections: string[] = [];\n\n  for (const rawPath of paths) {\n    const abs = resolve(rawPath);\n    try {\n      const content = await readFile(abs, 'utf8');\n      sections.push([\n        `### File Context: ${abs}`,\n        '```text',\n        clip(content, maxChars),\n        '```'\n      ].join('\\n'));\n    } catch (error) {\n      sections.push(`### File Context: ${abs}\\n(unavailable: ${(error as Error).message})`);\n    }\n  }\n\n  return `## Extra File Context\\n${sections.join('\\n\\n')}`;\n}\n\nexport async function buildRepoContextBlock(repos: string[] = []): Promise<string> {\n  if (!repos.length) return '';\n  const sections: string[] = [];\n\n  for (const repo of repos) {\n    const abs = resolve(repo);\n    const gitBlock = await getProjectContext(abs).catch((error: Error) => `## Git Context\\n${error.message}`);\n    sections.push(`### Repo Context: ${abs}\\n${gitBlock}`);\n  }\n\n  return `## Extra Repository Context\\n${sections.join('\\n\\n')}`;\n}\n\nexport async function buildImageContextBlock(paths: string[] = [], maxBytes = 250_000): Promise<string> {\n  if (!paths.length) return '';\n  const sections: string[] = [];\n\n  for (const rawPath of paths) {\n    const abs = resolve(rawPath);\n    try {\n      const mime = inferImageMime(abs);\n      if (!mime) {\n        sections.push(`### Image Context: ${abs}\\n(unsupported image type; supported: png, jpg, jpeg, webp, gif)`);\n        continue;\n      }\n\n      const buf = await readFile(abs);\n      const used = buf.subarray(0, maxBytes);\n      const truncated = buf.length > maxBytes;\n      const dataUri = `data:${mime};base64,${used.toString('base64')}`;\n      sections.push([\n        `### Image Context: ${abs}`,\n        `mime: ${mime}`,\n        `bytes: ${buf.length}${truncated ? ` (truncated to ${maxBytes})` : ''}`,\n        '```text',\n        dataUri,\n        '```',\n        'Instruction: If vision is available, inspect this image for UI/layout/code details and apply the request.'\n      ].join('\\n'));\n    } catch (error) {\n      sections.push(`### Image Context: ${abs}\\n(unavailable: ${(error as Error).message})`);\n    }\n  }\n\n  return `## Extra Image Context\\n${sections.join('\\n\\n')}`;\n}\n\n/** Load images as structured attachments for multimodal LLM input */\nexport async function loadImageAttachments(\n  paths: string[] = [],\n  maxBytes = 250_000\n): Promise<Array<{ data: string; mimeType: string }>> {\n  if (!paths.length) return [];\n  const attachments: Array<{ data: string; mimeType: string }> = [];\n\n  for (const rawPath of paths) {\n    const abs = resolve(rawPath);\n    try {\n      const mime = inferImageMime(abs);\n      if (!mime) continue;\n      const buf = await readFile(abs);\n      const used = buf.subarray(0, maxBytes);\n      attachments.push({ data: used.toString('base64'), mimeType: mime });\n    } catch {\n      // Skip unreadable files\n    }\n  }\n\n  return attachments;\n}\n\nexport function mergeTaskWithContext(task: string, blocks: string[]): string {\n  const filtered = blocks.map(x => String(x || '').trim()).filter(Boolean);\n  if (!filtered.length) return task;\n  return `${task}\\n\\n${filtered.join('\\n\\n')}`;\n}\n\nexport function estimateTokens(text: string): number {\n  if (!text) return 0;\n  return Math.ceil(text.length / 4);\n}\n\nexport function enforceContextBudget(\n  task: string,\n  blocks: string[],\n  maxTokens?: number,\n  mode: 'trim' | 'stop' = 'trim'\n): { task: string; estimatedTokens: number; trimmed: boolean; exceeded: boolean } {\n  const merged = mergeTaskWithContext(task, blocks);\n  if (!maxTokens || maxTokens <= 0) {\n    return { task: merged, estimatedTokens: estimateTokens(merged), trimmed: false, exceeded: false };\n  }\n\n  const estimated = estimateTokens(merged);\n  if (estimated <= maxTokens) {\n    return { task: merged, estimatedTokens: estimated, trimmed: false, exceeded: false };\n  }\n\n  if (mode === 'stop') {\n    return { task: merged, estimatedTokens: estimated, trimmed: false, exceeded: true };\n  }\n\n  const baseTask = String(task || '');\n  const maxChars = maxTokens * 4;\n  const baseChars = baseTask.length;\n  const remainingForContext = Math.max(0, maxChars - baseChars - 2);\n  const contextText = blocks.map(x => String(x || '').trim()).filter(Boolean).join('\\n\\n');\n  const clippedContext = contextText.slice(0, remainingForContext);\n  const clipped = clippedContext ? `${baseTask}\\n\\n${clippedContext}` : baseTask.slice(0, maxChars);\n  return {\n    task: clipped,\n    estimatedTokens: estimateTokens(clipped),\n    trimmed: true,\n    exceeded: false\n  };\n}\n", "import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nfunction clip(text: string, maxChars = 20000): string {\n  if (!text) return '(none)';\n  if (text.length <= maxChars) return text;\n  return `${text.slice(0, maxChars)}\\n... [truncated ${text.length - maxChars} chars]`;\n}\n\nasync function runGit(args: string[], cwd: string): Promise<string> {\n  const { stdout } = await execFileAsync('git', args, { cwd, maxBuffer: 1024 * 1024 * 8 });\n  return stdout.trim();\n}\n\nexport async function getReviewPayload(cwd = process.cwd()): Promise<{ hasChanges: boolean; payload: string }> {\n  try {\n    const [branch, unstaged, staged, status, commits] = await Promise.all([\n      runGit(['branch', '--show-current'], cwd).catch(() => '(unknown)'),\n      runGit(['diff', '--no-ext-diff'], cwd).catch(() => ''),\n      runGit(['diff', '--staged', '--no-ext-diff'], cwd).catch(() => ''),\n      runGit(['status', '--short'], cwd).catch(() => '(unavailable)'),\n      runGit(['log', '-5', '--oneline'], cwd).catch(() => '(unavailable)')\n    ]);\n\n    const hasChanges = Boolean(unstaged || staged);\n    const payload = [\n      'Please review this git diff before commit. Focus on regressions, missing tests, and risky behavior changes.',\n      '',\n      '## Branch',\n      branch || '(detached)',\n      '',\n      '## Status',\n      '```text',\n      status || '(clean)',\n      '```',\n      '',\n      '## Recent commits',\n      '```text',\n      commits || '(none)',\n      '```',\n      '',\n      '## Unstaged diff',\n      '```diff',\n      clip(unstaged),\n      '```',\n      '',\n      '## Staged diff',\n      '```diff',\n      clip(staged),\n      '```'\n    ].join('\\n');\n\n    return { hasChanges, payload };\n  } catch (error) {\n    return { hasChanges: false, payload: `Unable to collect review payload: ${(error as Error).message}` };\n  }\n}\n\nconst HIGH_SEVERITY_PATTERNS = [\n  /\\bcritical\\b/i,\n  /\\bseverity\\s*:\\s*high\\b/i,\n  /\\bhigh[-\\s]?severity\\b/i,\n  /\\bsev[-\\s]?1\\b/i,\n  /\\bp0\\b/i,\n  /\\bmust fix before merge\\b/i,\n  /\\bdo not merge\\b/i\n];\n\nexport function detectHighSeverityFindings(text: string): { hasHighSeverity: boolean; matches: string[] } {\n  const content = String(text || '');\n  const matches: string[] = [];\n  for (const pattern of HIGH_SEVERITY_PATTERNS) {\n    const found = content.match(pattern);\n    if (found?.[0]) matches.push(found[0]);\n  }\n  return { hasHighSeverity: matches.length > 0, matches };\n}\n", "import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getExecutionPolicy, isRetryableError, isRiskBlocked, withRetries } from '../runtime/execution-policy.js';\nimport { analyzeBlastRadius } from '../blast-radius/index.js';\n\ninterface HeadlessDeps {\n  router: {\n    dispatch(\n      agent: string,\n      task: string,\n      opts: { sessionId: string; project: string; gateway?: string; model?: string }\n    ): Promise<Record<string, unknown>>;\n  };\n  orchestrator: {\n    route(task: string): Promise<{ agent?: string; decision?: string }>;\n    parseAndApplyToSandbox(responseText: string): Promise<string[]>;\n  };\n  sandbox: {\n    hasChanges(branch: string): boolean;\n    getActiveBranch(): string;\n    getPendingPaths?(branch: string): string[];\n    apply(branch: string): Promise<void>;\n  };\n  session: {\n    getSessionId(): Promise<string>;\n  };\n}\n\ninterface HeadlessRunOptions extends HeadlessDeps {\n  task: string;\n  projectDir?: string;\n  agent?: string;\n  gateway?: string;\n  json?: boolean;\n  alwaysApprove?: boolean;\n  forceAutoApply?: boolean;\n  riskThreshold?: 'low' | 'medium' | 'high';\n  retryAttempts?: number;\n  fallbackModels?: string[];\n  out?: string;\n}\n\nfunction statePath(baseDir: string): string {\n  return join(baseDir, '.crew', 'headless-state.json');\n}\n\nasync function ensureState(baseDir: string): Promise<void> {\n  const path = statePath(baseDir);\n  await mkdir(join(baseDir, '.crew'), { recursive: true });\n  if (!existsSync(path)) {\n    await writeFile(path, JSON.stringify({ paused: false, updatedAt: new Date().toISOString() }, null, 2), 'utf8');\n  }\n}\n\nexport async function getHeadlessState(baseDir = process.cwd()): Promise<{ paused: boolean; updatedAt?: string }> {\n  await ensureState(baseDir);\n  try {\n    const raw = await readFile(statePath(baseDir), 'utf8');\n    const parsed = JSON.parse(raw);\n    return { paused: Boolean(parsed.paused), updatedAt: parsed.updatedAt };\n  } catch {\n    return { paused: false };\n  }\n}\n\nexport async function setHeadlessPaused(paused: boolean, baseDir = process.cwd()): Promise<void> {\n  await ensureState(baseDir);\n  await writeFile(\n    statePath(baseDir),\n    JSON.stringify({ paused: Boolean(paused), updatedAt: new Date().toISOString() }, null, 2),\n    'utf8'\n  );\n}\n\nasync function appendOutLine(baseDir: string, outPath: string | undefined, payload: Record<string, unknown>): Promise<void> {\n  if (!outPath) return;\n  const fullPath = join(baseDir, outPath);\n  await mkdir(join(fullPath, '..'), { recursive: true });\n  const prev = existsSync(fullPath) ? await readFile(fullPath, 'utf8') : '';\n  await writeFile(fullPath, `${prev}${JSON.stringify(payload)}\\n`, 'utf8');\n}\n\nasync function emit(baseDir: string, jsonMode: boolean, outPath: string | undefined, event: string, data: Record<string, unknown> = {}): Promise<void> {\n  const payload = { ts: new Date().toISOString(), event, ...data };\n  await appendOutLine(baseDir, outPath, payload);\n  if (jsonMode) {\n    process.stdout.write(`${JSON.stringify(payload)}\\n`);\n    return;\n  }\n  const suffix = data?.message ? `: ${data.message}` : '';\n  console.log(`[headless] ${event}${suffix}`);\n}\n\nexport async function runHeadlessTask(options: HeadlessRunOptions): Promise<{ success: boolean; response?: string }> {\n  const cwd = options.projectDir || process.cwd();\n  const jsonMode = Boolean(options.json);\n  const state = await getHeadlessState(cwd);\n\n  if (state.paused) {\n    await emit(cwd, jsonMode, options.out, 'blocked', { message: 'headless mode is paused' });\n    return { success: false };\n  }\n\n  await emit(cwd, jsonMode, options.out, 'start', { task: options.task });\n\n  const policy = getExecutionPolicy({\n    retryAttempts: Number(options.retryAttempts || 2),\n    riskThreshold: options.riskThreshold || 'high',\n    forceAutoApply: Boolean(options.forceAutoApply)\n  });\n\n  const route = await withRetries(\n    async () => options.orchestrator.route(options.task),\n    policy\n  );\n  const agent = options.agent || route.agent || 'crew-main';\n  await emit(cwd, jsonMode, options.out, 'route', { decision: route.decision, agent });\n\n  const fallbackChain = (options.fallbackModels || []).map(v => String(v || '').trim()).filter(Boolean);\n  const chain = fallbackChain.length > 0 ? fallbackChain : [''];\n  let dispatch: Record<string, unknown> | null = null;\n  let lastError: unknown = null;\n  for (const model of chain) {\n    try {\n      dispatch = await withRetries(\n        async () => options.router.dispatch(agent, options.task, {\n          sessionId: await options.session.getSessionId(),\n          project: cwd,\n          gateway: options.gateway,\n          model: model || undefined\n        }),\n        policy,\n        { shouldRetry: isRetryableError }\n      );\n      if (dispatch) break;\n    } catch (error) {\n      lastError = error;\n    }\n  }\n  if (!dispatch) {\n    throw (lastError as Error) || new Error('Headless dispatch failed');\n  }\n\n  const responseText = String(dispatch.result || '');\n  await emit(cwd, jsonMode, options.out, 'result', { agent, response: responseText });\n\n  const edits = await options.orchestrator.parseAndApplyToSandbox(responseText);\n  await emit(cwd, jsonMode, options.out, 'sandbox', { filesChanged: edits.length });\n\n  if (options.alwaysApprove && options.sandbox.hasChanges(options.sandbox.getActiveBranch())) {\n    const active = options.sandbox.getActiveBranch();\n    const changedFiles = typeof options.sandbox.getPendingPaths === 'function'\n      ? options.sandbox.getPendingPaths(active)\n      : [];\n    const report = await analyzeBlastRadius(cwd, { changedFiles });\n    if (isRiskBlocked(report.risk, policy.riskThreshold, policy.forceAutoApply)) {\n      await emit(cwd, jsonMode, options.out, 'approval_required', {\n        message: `risk gate blocked auto-apply (${report.risk} >= ${policy.riskThreshold})`\n      });\n      return { success: false, response: responseText };\n    }\n    await options.sandbox.apply(active);\n    await emit(cwd, jsonMode, options.out, 'applied', { message: 'sandbox changes applied (--always-approve)' });\n  } else if (edits.length > 0) {\n    await emit(cwd, jsonMode, options.out, 'approval_required', { message: 'pending sandbox changes require apply' });\n  }\n\n  await emit(cwd, jsonMode, options.out, 'done', { success: true });\n  return { success: true, response: responseText };\n}\n", "import { runDoctorChecks, summarizeDoctorResults } from '../diagnostics/doctor.js';\nimport { resolveCapabilityMap } from '../capabilities/index.js';\n\nexport type RiskThreshold = 'low' | 'medium' | 'high';\n\nexport interface ExecutionPolicy {\n  strictPreflight: boolean;\n  retryAttempts: number;\n  retryBackoffMs: number;\n  riskThreshold: RiskThreshold;\n  forceAutoApply: boolean;\n  diffFirst: boolean;\n}\n\nexport function getExecutionPolicy(input: Partial<ExecutionPolicy> = {}): ExecutionPolicy {\n  const retryAttempts = Number(input.retryAttempts ?? process.env.CREW_RETRY_ATTEMPTS ?? 2);\n  const retryBackoffMs = Number(input.retryBackoffMs ?? process.env.CREW_RETRY_BACKOFF_MS ?? 600);\n  const rawThreshold = String(input.riskThreshold ?? process.env.CREW_RISK_THRESHOLD ?? 'high').toLowerCase();\n  const riskThreshold: RiskThreshold =\n    rawThreshold === 'low' || rawThreshold === 'medium' || rawThreshold === 'high'\n      ? rawThreshold\n      : 'high';\n  const strictPreflight =\n    Boolean(input.strictPreflight) ||\n    String(process.env.CREW_STRICT_PREFLIGHT || '').toLowerCase() === 'true';\n  const forceAutoApply =\n    Boolean(input.forceAutoApply) ||\n    String(process.env.CREW_FORCE_AUTO_APPLY || '').toLowerCase() === 'true';\n  const diffFirst = String(process.env.CREW_DIFF_FIRST || 'true').toLowerCase() !== 'false';\n\n  return {\n    strictPreflight,\n    retryAttempts: Number.isFinite(retryAttempts) ? Math.max(1, Math.min(5, Math.floor(retryAttempts))) : 2,\n    retryBackoffMs: Number.isFinite(retryBackoffMs) ? Math.max(100, Math.min(5000, Math.floor(retryBackoffMs))) : 600,\n    riskThreshold,\n    forceAutoApply,\n    diffFirst\n  };\n}\n\nexport function isRetryableError(error: unknown): boolean {\n  const text = String((error as Error)?.message || '').toLowerCase();\n  return (\n    text.includes('rate limit') ||\n    text.includes('429') ||\n    text.includes('timeout') ||\n    text.includes('temporar') ||\n    text.includes('unavailable') ||\n    text.includes('quota') ||\n    text.includes('connection reset') ||\n    text.includes('econnreset')\n  );\n}\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nexport async function withRetries<T>(\n  fn: (attempt: number) => Promise<T>,\n  policy: ExecutionPolicy,\n  opts: { label?: string; shouldRetry?: (error: unknown) => boolean } = {}\n): Promise<T> {\n  const attempts = Math.max(1, policy.retryAttempts);\n  let lastError: unknown;\n  for (let i = 1; i <= attempts; i += 1) {\n    try {\n      return await fn(i);\n    } catch (error) {\n      lastError = error;\n      const retryable = (opts.shouldRetry || isRetryableError)(error);\n      const hasNext = i < attempts;\n      if (!retryable || !hasNext) break;\n      const delay = Math.round(policy.retryBackoffMs * i + Math.random() * 120);\n      await sleep(delay);\n    }\n  }\n  throw lastError;\n}\n\nexport async function enforceStrictPreflight(policy: ExecutionPolicy, gateway?: string): Promise<void> {\n  if (!policy.strictPreflight) return;\n  const checks = await runDoctorChecks({ gateway: gateway || 'http://localhost:5010' });\n  const summary = summarizeDoctorResults(checks);\n  if (summary.failed > 0) {\n    const failed = checks.filter(c => !c.ok).map(c => `${c.name}: ${c.details}`).join('; ');\n    throw new Error(`Strict preflight failed (${summary.failed} checks): ${failed}`);\n  }\n}\n\nexport function getCapabilityHandshake(mode: 'standalone' | 'connected') {\n  const caps = resolveCapabilityMap(mode);\n  return {\n    mode: caps.mode,\n    can_read: caps.canRead,\n    can_write: caps.canWrite,\n    can_pty: caps.canPty,\n    can_lsp: caps.canLsp,\n    can_dispatch: caps.canDispatch,\n    can_git: caps.canGit\n  };\n}\n\nexport function isRiskBlocked(\n  risk: 'low' | 'medium' | 'high',\n  threshold: RiskThreshold,\n  force = false\n): boolean {\n  if (force) return false;\n  const score = { low: 1, medium: 2, high: 3 };\n  return score[risk] >= score[threshold];\n}\n", "import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport type { AgentRouter } from '../agent/router.js';\nimport type { Orchestrator } from '../orchestrator/index.js';\nimport type { Sandbox } from '../sandbox/index.js';\nimport type { SessionManager } from '../session/manager.js';\nimport type { RagMode } from '../context/codebase-rag.js';\nimport { buildCollectionIndex, searchCollection, type CollectionIndex, type CollectionChunk } from '../collections/index.js';\nimport { handleMcpRequest } from './mcp-handler.js';\nimport { loadPipelineMetricsSummary } from '../metrics/pipeline.js';\nimport { runEngine, listNativeEngineSessions, closeNativeEngineSessions, getToolAuditRuns, getToolAuditReplayPlan } from '../engines/index.js';\nimport { EngineSessionLayer } from '../engines/session-layer.js';\nimport { GeminiToolAdapter } from '../tools/gemini/crew-adapter.js';\n\ntype InterfaceMode = 'connected' | 'standalone';\n\nexport interface UnifiedServerOptions {\n  mode: InterfaceMode;\n  host: string;\n  port: number;\n  gateway?: string;\n  router: AgentRouter;\n  orchestrator: Orchestrator;\n  sandbox: Sandbox;\n  session: SessionManager;\n  projectDir: string;\n  logger?: { info?: (...args: unknown[]) => void; warn?: (...args: unknown[]) => void; error?: (...args: unknown[]) => void };\n}\n\ninterface TaskRecord {\n  id: string;\n  status: 'queued' | 'running' | 'done' | 'error';\n  result?: unknown;\n  error?: string;\n  traceId?: string;\n  costUsd?: number;\n  createdAt: number;\n}\n\nconst taskStore = new Map<string, TaskRecord>();\n\nfunction evictStaleTasks() {\n  const maxAge = 3_600_000; // 1 hour\n  const now = Date.now();\n  for (const [id, task] of taskStore) {\n    if ((task.status === 'done' || task.status === 'error') && now - task.createdAt > maxAge) {\n      taskStore.delete(id);\n    }\n  }\n}\n\n// Run eviction every 10 minutes\nsetInterval(evictStaleTasks, 600_000).unref();\n\nlet latestIndex: CollectionIndex | null = null;\nlet latestIndexStats: { files: number; chunks: number } = { files: 0, chunks: 0 };\nlet latestIndexId = '';\n\ninterface OpenAIMessage {\n  role?: string;\n  content?: string | Array<{ type?: string; text?: string }>;\n  name?: string;\n  tool_call_id?: string;\n  tool_calls?: Array<{\n    id?: string;\n    type?: string;\n    function?: { name?: string; arguments?: string };\n  }>;\n}\n\ninterface ToolChoiceObject {\n  function?: { name?: string };\n}\n\ninterface ChatOptionsPayload {\n  mode?: string;\n  model?: string;\n  engine?: string;\n  direct?: boolean;\n  bypass?: boolean;\n  timeoutMs?: number;\n}\n\ninterface StreamChatPayload {\n  _sse?: boolean;\n  chunks?: unknown[];\n}\n\ninterface StatusPayload {\n  gateway?: string;\n  queueDepth?: number;\n}\n\ninterface ReplayableMutationCall {\n  name?: string;\n  args?: Record<string, unknown>;\n}\n\ninterface ReplayPlan {\n  supportedMutations?: ReplayableMutationCall[];\n}\n\ninterface McpRequestPayload {\n  jsonrpc: string;\n  id: string | number;\n  method: string;\n  params?: Record<string, unknown>;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n  return value && typeof value === 'object' ? value as Record<string, unknown> : {};\n}\n\nfunction asChatOptions(value: unknown): ChatOptionsPayload {\n  return value && typeof value === 'object' ? value as ChatOptionsPayload : {};\n}\n\nfunction asMcpRequest(value: Record<string, unknown>): McpRequestPayload | null {\n  if (typeof value.jsonrpc !== 'string' || typeof value.method !== 'string') return null;\n  const id = value.id;\n  if (typeof id !== 'string' && typeof id !== 'number') return null;\n  return {\n    jsonrpc: value.jsonrpc,\n    id,\n    method: value.method,\n    params: value.params && typeof value.params === 'object' ? value.params as Record<string, unknown> : undefined\n  };\n}\n\nfunction readRtToken(): string {\n  try {\n    const p = join(homedir(), '.crewswarm', 'crewswarm.json');\n    const cfg = JSON.parse(readFileSync(p, 'utf8'));\n    return String(cfg?.rt?.authToken || '');\n  } catch {\n    return '';\n  }\n}\n\nfunction checkAuth(req: IncomingMessage, res: ServerResponse): boolean {\n  const token = readRtToken();\n  if (!token) return true; // No token configured = no auth required\n  const auth = req.headers['authorization'];\n  if (auth === `Bearer ${token}`) return true;\n  json(res, 401, { error: 'Unauthorized' });\n  return false;\n}\n\nfunction json(res: ServerResponse, code: number, payload: unknown) {\n  res.writeHead(code, {\n    'content-type': 'application/json; charset=utf-8',\n    'access-control-allow-origin': '*',\n    'access-control-allow-headers': 'content-type, authorization',\n    'access-control-allow-methods': 'GET,POST,OPTIONS'\n  });\n  res.end(JSON.stringify(payload));\n}\n\nasync function readJson(req: IncomingMessage): Promise<Record<string, unknown>> {\n  const chunks: Buffer[] = [];\n  for await (const chunk of req) {\n    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n  }\n  const raw = Buffer.concat(chunks).toString('utf8').trim();\n  if (!raw) return {};\n  return JSON.parse(raw);\n}\n\nfunction getPath(req: IncomingMessage): string {\n  const url = new URL(req.url || '/', 'http://127.0.0.1');\n  return url.pathname;\n}\n\nfunction getQuery(req: IncomingMessage): URLSearchParams {\n  const url = new URL(req.url || '/', 'http://127.0.0.1');\n  return url.searchParams;\n}\n\nfunction extractMessageText(content: OpenAIMessage['content']): string {\n  if (typeof content === 'string') return content;\n  if (Array.isArray(content)) {\n    return content\n      .map(part => (part?.type === 'text' || !part?.type ? String(part?.text || '') : ''))\n      .filter(Boolean)\n      .join('\\n');\n  }\n  return '';\n}\n\nfunction normalizeOpenAIMessages(messages: unknown): Array<{ role: string; text: string }> {\n  if (!Array.isArray(messages)) return [];\n  return (messages as OpenAIMessage[])\n    .map(m => ({\n      role: String(m?.role || '').trim().toLowerCase(),\n      text: extractMessageText(m?.content).trim()\n    }))\n    .filter(m => Boolean(m.role) && Boolean(m.text));\n}\n\nfunction composeChatPayloadFromOpenAI(messages: unknown): {\n  message: string;\n  context: string;\n  inputChars: number;\n} {\n  const normalized = normalizeOpenAIMessages(messages);\n  const system = normalized.filter(m => m.role === 'system').map(m => m.text);\n  const assistant = normalized.filter(m => m.role === 'assistant').map(m => m.text);\n  const userTurns = normalized.filter(m => m.role === 'user');\n  const lastUser = (userTurns.length > 0 ? userTurns[userTurns.length - 1]?.text : '') || '';\n  const priorUser = userTurns.slice(0, -1).map(m => m.text);\n  const historyTail = [...priorUser, ...assistant].slice(-8);\n  const contextSections: string[] = [];\n  if (system.length > 0) contextSections.push(`SYSTEM INSTRUCTIONS:\\n${system.join('\\n\\n')}`);\n  if (historyTail.length > 0) contextSections.push(`RECENT CONTEXT:\\n${historyTail.join('\\n\\n')}`);\n  const toolResults = normalized\n    .filter(m => m.role === 'tool')\n    .map(m => m.text)\n    .filter(Boolean);\n  if (toolResults.length > 0) {\n    contextSections.push(`TOOL RESULTS:\\n${toolResults.join('\\n\\n')}`);\n  }\n  const context = contextSections.join('\\n\\n');\n  const inputChars = normalized.reduce((sum, m) => sum + m.text.length, 0);\n  return {\n    message: lastUser,\n    context,\n    inputChars\n  };\n}\n\ninterface ChatCompletionResponse {\n  status: number;\n  data: Record<string, unknown>;\n}\n\nfunction buildToolCallResponse(params: {\n  model: string;\n  stream: boolean;\n  toolName: string;\n  message: string;\n}): ChatCompletionResponse {\n  const completionId = `chatcmpl-${randomUUID()}`;\n  const created = Math.floor(Date.now() / 1000);\n  const toolCallId = `call_${randomUUID().replace(/-/g, '').slice(0, 20)}`;\n  const toolCall = {\n    id: toolCallId,\n    type: 'function',\n    function: {\n      name: params.toolName,\n      arguments: JSON.stringify({ task: params.message })\n    }\n  };\n  if (params.stream) {\n    return {\n      status: 200,\n      data: {\n        _sse: true,\n        model: params.model,\n        chunks: [\n          {\n            id: completionId,\n            object: 'chat.completion.chunk',\n            created,\n            model: params.model,\n            choices: [{ index: 0, delta: { role: 'assistant', tool_calls: [toolCall] }, finish_reason: null }]\n          },\n          {\n            id: completionId,\n            object: 'chat.completion.chunk',\n            created,\n            model: params.model,\n            choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }]\n          }\n        ]\n      }\n    };\n  }\n  return {\n    status: 200,\n    data: {\n      id: completionId,\n      object: 'chat.completion',\n      created,\n      model: params.model,\n      choices: [\n        {\n          index: 0,\n          message: {\n            role: 'assistant',\n            content: '',\n            tool_calls: [toolCall]\n          },\n          finish_reason: 'tool_calls'\n        }\n      ],\n      usage: {\n        prompt_tokens: Math.ceil(params.message.length / 4),\n        completion_tokens: 1,\n        total_tokens: Math.ceil(params.message.length / 4) + 1\n      }\n    }\n  };\n}\n\nfunction selectToolCallName(body: Record<string, unknown>, userMessage: string): string | null {\n  const tools = Array.isArray(body?.tools) ? body.tools : [];\n  if (tools.length === 0) return null;\n  const names = tools\n    .map((t: Record<string, unknown>) => String((t?.function as Record<string, unknown>)?.name || '').trim())\n    .filter(Boolean);\n  if (names.length === 0) return null;\n\n  const choice = body?.tool_choice;\n  if (choice === 'none') return null;\n  if (choice && typeof choice === 'object') {\n    const forced = String((choice as ToolChoiceObject)?.function?.name || '').trim();\n    if (forced && names.includes(forced)) return forced;\n  }\n  if (choice === 'required') return names[0];\n  if (choice && choice !== 'auto') return null;\n\n  const lower = userMessage.toLowerCase();\n  const likelyAction = /\\b(build|implement|write|create|edit|refactor|fix|change|update|run|test|analyze)\\b/.test(lower);\n  return likelyAction ? names[0] : null;\n}\n\nasync function forwardJson(\n  baseUrl: string,\n  path: string,\n  method: 'GET' | 'POST',\n  body?: unknown\n): Promise<{ status: number; ok: boolean; data: Record<string, unknown> }> {\n  const token = readRtToken();\n  const headers: Record<string, string> = { 'content-type': 'application/json' };\n  if (token) headers.authorization = `Bearer ${token}`;\n  const res = await fetch(`${baseUrl}${path}`, {\n    method,\n    headers,\n    body: body ? JSON.stringify(body) : undefined\n  });\n  const text = await res.text();\n  let data: Record<string, unknown> = { raw: text };\n  try {\n    data = JSON.parse(text) as Record<string, unknown>;\n  } catch {\n    data = { raw: text };\n  }\n  return { status: res.status, ok: res.ok, data };\n}\n\nfunction executionPathForDecision(decision?: string): string[] {\n  if (decision === 'CHAT') return ['l1-interface', 'l2-orchestrator', 'l2-direct-response'];\n  if (decision === 'CODE') return ['l1-interface', 'l2-orchestrator', 'l3-executor-single'];\n  if (decision === 'DISPATCH') return ['l1-interface', 'l2-orchestrator', 'l3-executor-parallel'];\n  return ['l1-interface', 'l2-orchestrator'];\n}\n\nfunction getChatControl(body: Record<string, unknown>): {\n  mode: string;\n  model: string;\n  engine: string;\n  direct: boolean;\n  bypass: boolean;\n  passthroughRequested: boolean;\n} {\n  const options = (body?.options && typeof body.options === 'object')\n    ? body.options as Record<string, unknown>\n    : {} as Record<string, unknown>;\n  const mode = String(body?.mode || options?.mode || '').trim().toLowerCase();\n  const model = String(options?.model || body?.model || '').trim();\n  const engine = String(options?.engine || body?.engine || '').trim().toLowerCase();\n  const direct = Boolean(\n    body?.direct === true ||\n    options?.direct === true ||\n    mode === 'direct'\n  );\n  const bypass = Boolean(\n    body?.bypass === true ||\n    options?.bypass === true ||\n    mode === 'bypass'\n  );\n  return {\n    mode,\n    model,\n    engine,\n    direct,\n    bypass,\n    passthroughRequested: direct || bypass\n  };\n}\n\nfunction normalizeStandaloneEngine(rawEngine: string): string {\n  const e = String(rawEngine || '').trim().toLowerCase();\n  if (!e) return '';\n  if (e === 'claude' || e === 'claude-code' || e === 'claude-cli') return 'claude-cli';\n  if (e === 'codex' || e === 'codex-cli') return 'codex-cli';\n  if (e === 'cursor' || e === 'cursor-cli') return 'cursor-cli';\n  if (e === 'opencode' || e === 'opencode-cli') return 'opencode-cli';\n  if (e === 'gemini' || e === 'gemini-cli') return 'gemini-cli';\n  if (e === 'gemini-api') return 'gemini-api';\n  if (e === 'claude-api') return 'claude-api';\n  return e;\n}\n\nasync function handleStandaloneChat(options: UnifiedServerOptions, body: Record<string, unknown>) {\n  const message = String(body?.message || '').trim();\n  if (!message) return { status: 400, data: { error: 'message is required' } };\n  const context = String(body?.context || '').trim();\n  const mergedInput = context ? `${message}\\n\\n${context}` : message;\n  const control = getChatControl(body);\n  const requestOptions = asChatOptions(body?.options);\n\n  if (control.passthroughRequested || control.engine) {\n    const engine = normalizeStandaloneEngine(control.engine || '');\n    if (!engine) {\n      return { status: 400, data: { error: 'engine is required for direct/bypass mode in standalone' } };\n    }\n    const run = await runEngine(engine, mergedInput, {\n      model: control.model || undefined,\n      cwd: String(body?.projectDir || options.projectDir || process.cwd()),\n      projectDir: String(body?.projectDir || options.projectDir || process.cwd()),\n      sessionId: String(body?.sessionId || ''),\n      timeoutMs: Number(requestOptions.timeoutMs || body?.timeoutMs || 600000)\n    });\n    if (!run.success) {\n      return {\n        status: 502,\n        data: {\n          error: run.stderr || `engine ${engine} failed`,\n          engine,\n          exitCode: run.exitCode\n        }\n      };\n    }\n    return {\n      status: 200,\n      data: {\n        reply: String(run.stdout || ''),\n        traceId: body?.traceId || '',\n        executionPath: ['l1-interface', 'engine-passthrough', engine],\n        costUsd: 0,\n        pendingChanges: options.sandbox.getPendingPaths(options.sandbox.getActiveBranch()).length,\n        engine,\n        exitCode: run.exitCode\n      }\n    };\n  }\n\n  // crew-cli is a code execution engine \u2014 always use the full pipeline\n  // The pipeline handles CHAT vs CODE routing internally\n  const sessionId = String(body?.sessionId || 'api');\n  const result = await options.orchestrator.executePipeline(\n    mergedInput, '', sessionId\n  );\n  const responseText = String(result?.response || result?.result || '');\n  const edits = await options.orchestrator.parseAndApplyToSandbox(responseText);\n  return {\n    status: 200,\n    data: {\n      reply: responseText,\n      traceId: result?.traceId || body?.traceId || '',\n      executionPath: result?.executionPath || ['pipeline'],\n      costUsd: Number(result?.totalCost || 0),\n      pendingChanges: edits.length\n    }\n  };\n}\n\nasync function handleConnectedChat(options: UnifiedServerOptions, body: Record<string, unknown>) {\n  const message = String(body?.message || '').trim();\n  if (!message) return { status: 400, data: { error: 'message is required' } };\n  const context = String(body?.context || '').trim();\n  const mergedInput = context ? `${message}\\n\\n${context}` : message;\n  const control = getChatControl(body);\n  const gateway = String(body?.gateway || options.gateway || 'http://127.0.0.1:5010');\n\n  if (control.passthroughRequested || control.engine) {\n    try {\n      const agent = String(body?.agent || 'crew-main');\n      const dispatched = await options.router.dispatch(agent, mergedInput, {\n        gateway,\n        sessionId: body?.sessionId || 'api',\n        model: control.model || undefined,\n        engine: control.engine || undefined,\n        direct: control.direct,\n        bypass: control.bypass,\n        skipPreamble: true,\n        injectGitContext: false,\n        project: String(body?.projectDir || options.projectDir || process.cwd())\n      });\n      const reply = String(dispatched?.result || '');\n      return {\n        status: 200,\n        data: {\n          reply,\n          traceId: String(body?.traceId || ''),\n          executionPath: ['l1-interface', 'gateway-dispatch', control.engine || 'direct'],\n          costUsd: 0,\n          pendingChanges: options.sandbox.getPendingPaths(options.sandbox.getActiveBranch()).length\n        }\n      };\n    } catch (err) {\n      return {\n        status: 502,\n        data: {\n          error: String((err as Error)?.message || err)\n        }\n      };\n    }\n  }\n\n  const forwarded = await forwardJson(gateway, '/chat', 'POST', {\n    message: mergedInput,\n    sessionId: body?.sessionId || 'api'\n  });\n  const reply =\n    forwarded.data?.reply ??\n    forwarded.data?.result ??\n    forwarded.data?.message ??\n    forwarded.data?.raw ??\n    '';\n  return {\n    status: forwarded.ok ? 200 : forwarded.status,\n    data: {\n      reply: String(reply || ''),\n      traceId: String(body?.traceId || ''),\n      executionPath: ['l1-interface', 'l2-orchestrator', 'l3-workers'],\n      costUsd: 0,\n      pendingChanges: options.sandbox.getPendingPaths(options.sandbox.getActiveBranch()).length\n    }\n  };\n}\n\nasync function handleOpenAIChatCompletions(options: UnifiedServerOptions, body: Record<string, unknown>) {\n  const model = String(body?.model || 'crewswarm');\n  const stream = Boolean(body?.stream);\n  const composed = composeChatPayloadFromOpenAI(body?.messages);\n  if (!composed.message) {\n    return {\n      status: 400,\n      data: { error: { message: 'No user message found', type: 'invalid_request_error' } }\n    };\n  }\n\n  const selectedTool = selectToolCallName(body, composed.message);\n  if (selectedTool) {\n    return buildToolCallResponse({\n      model,\n      stream,\n      toolName: selectedTool,\n      message: composed.message\n    });\n  }\n\n  const chatBody = {\n    message: model === 'crewswarm'\n      ? composed.message\n      : `${composed.message}\\n\\nPREFERRED_AGENT: ${model}`,\n    context: composed.context,\n    options: {\n      model: typeof asRecord(body?.metadata).modelOverride === 'string'\n        ? asRecord(body?.metadata).modelOverride as string\n        : undefined\n    }\n  };\n\n  const out = options.mode === 'connected'\n    ? await handleConnectedChat(options, chatBody)\n    : await handleStandaloneChat(options, chatBody);\n  const reply = String(out?.data?.reply || '');\n\n  const completionId = `chatcmpl-${randomUUID()}`;\n  const created = Math.floor(Date.now() / 1000);\n  const promptTokens = Math.ceil(composed.inputChars / 4);\n  const completionTokens = Math.ceil(reply.length / 4);\n\n  if (stream) {\n    return {\n      status: 200,\n      data: {\n        _sse: true,\n        model,\n        chunks: [\n          {\n            id: completionId,\n            object: 'chat.completion.chunk',\n            created,\n            model,\n            choices: [{ index: 0, delta: { role: 'assistant', content: reply }, finish_reason: null }]\n          },\n          {\n            id: completionId,\n            object: 'chat.completion.chunk',\n            created,\n            model,\n            choices: [{ index: 0, delta: {}, finish_reason: 'stop' }]\n          }\n        ]\n      }\n    };\n  }\n\n  return {\n    status: out.status,\n    data: {\n      id: completionId,\n      object: 'chat.completion',\n      created,\n      model,\n      choices: [{ index: 0, message: { role: 'assistant', content: reply }, finish_reason: 'stop' }],\n      usage: {\n        prompt_tokens: promptTokens,\n        completion_tokens: completionTokens,\n        total_tokens: promptTokens + completionTokens\n      }\n    }\n  };\n}\n\nasync function enqueueStandaloneTask(options: UnifiedServerOptions, body: Record<string, unknown>) {\n  const taskText = String(body?.task || '').trim();\n  if (!taskText) return { status: 400, data: { error: 'task is required' } };\n  const taskId = randomUUID();\n  taskStore.set(taskId, { id: taskId, status: 'queued', createdAt: Date.now() });\n  queueMicrotask(async () => {\n    const rec = taskStore.get(taskId);\n    if (!rec) return;\n    rec.status = 'running';\n    try {\n      const result = await options.orchestrator.executeLocally(taskText, {\n        model: asChatOptions(body?.options).model\n      });\n      rec.status = 'done';\n      rec.result = result?.result || '';\n      rec.costUsd = Number(result?.costUsd || 0);\n      taskStore.set(taskId, rec);\n    } catch (err) {\n      rec.status = 'error';\n      rec.error = String((err as Error)?.message || err);\n      taskStore.set(taskId, rec);\n    }\n  });\n  return { status: 202, data: { accepted: true, taskId } };\n}\n\nasync function enqueueConnectedTask(options: UnifiedServerOptions, body: Record<string, unknown>) {\n  const gateway = String(body?.gateway || options.gateway || 'http://127.0.0.1:5010');\n  const payload = {\n    agent: body?.agent,\n    task: body?.task,\n    sessionId: body?.sessionId || 'api',\n    ...(body?.options || {})\n  };\n  const forwarded = await forwardJson(String(gateway), '/api/dispatch', 'POST', payload);\n  const taskId = forwarded.data?.taskId || '';\n  return {\n    status: forwarded.ok ? 202 : forwarded.status,\n    data: {\n      accepted: forwarded.ok,\n      taskId\n    }\n  };\n}\n\nexport async function startUnifiedServer(options: UnifiedServerOptions): Promise<{\n  close: () => Promise<void>;\n  address: string;\n}> {\n  const passthroughSessions = new EngineSessionLayer(options.projectDir || process.cwd());\n  const server = createServer(async (req, res) => {\n    try {\n      if (req.method === 'OPTIONS') {\n        return json(res, 204, {});\n      }\n\n      const path = getPath(req);\n\n      if (req.method === 'POST' && path === '/v1/chat') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const out = options.mode === 'connected'\n          ? await handleConnectedChat(options, body)\n          : await handleStandaloneChat(options, body);\n        return json(res, out.status, out.data);\n      }\n\n      // Dashboard compatibility: direct engine passthrough stream API.\n      if (req.method === 'POST' && path === '/api/engine-passthrough') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const message = String(body?.message || '').trim();\n        const requestedEngine = String(body?.engine || '').trim().toLowerCase();\n        if (!message) return json(res, 400, { error: 'message is required' });\n        if (!requestedEngine) return json(res, 400, { error: 'engine is required' });\n\n        res.writeHead(200, {\n          'content-type': 'text/event-stream',\n          'cache-control': 'no-cache',\n          'connection': 'keep-alive',\n          'access-control-allow-origin': '*',\n          'access-control-allow-headers': 'content-type, authorization',\n          'access-control-allow-methods': 'GET,POST,OPTIONS'\n        });\n\n        if (options.mode === 'connected') {\n          const gateway = String(body?.gateway || options.gateway || 'http://127.0.0.1:5010');\n          const token = readRtToken();\n          const headers: Record<string, string> = { 'content-type': 'application/json' };\n          if (token) headers.authorization = `Bearer ${token}`;\n          const upstream = await fetch(`${gateway}/api/engine-passthrough`, {\n            method: 'POST',\n            headers,\n            body: JSON.stringify({\n              engine: requestedEngine,\n              message,\n              model: body?.model,\n              sessionId: body?.sessionId,\n              projectDir: body?.projectDir\n            })\n          });\n          if (!upstream.ok || !upstream.body) {\n            const text = await upstream.text().catch(() => '');\n            res.write(`data: ${JSON.stringify({ type: 'chunk', text: `Error ${upstream.status}: ${text || 'upstream failure'}` })}\\n\\n`);\n            res.write(`data: ${JSON.stringify({ type: 'done', exitCode: 1 })}\\n\\n`);\n            res.end();\n            return;\n          }\n          const reader = upstream.body.getReader();\n          const decoder = new TextDecoder();\n          while (true) {\n            const { done, value } = await reader.read();\n            if (done) break;\n            res.write(decoder.decode(value, { stream: true }));\n          }\n          res.end();\n          return;\n        }\n\n        const engine = normalizeStandaloneEngine(requestedEngine);\n        const sessionId = String(body?.sessionId || '');\n        const run = await runEngine(engine, message, {\n          model: String(body?.model || '').trim() || undefined,\n          cwd: String(body?.projectDir || options.projectDir || process.cwd()),\n          projectDir: String(body?.projectDir || options.projectDir || process.cwd()),\n          sessionId,\n          timeoutMs: Number(body?.timeoutMs || 300000),\n          onEvent: (event) => {\n            if (!event) return;\n            if (event.type === 'chunk' && typeof event.text === 'string') {\n              res.write(`data: ${JSON.stringify({ type: 'chunk', text: event.text })}\\n\\n`);\n              return;\n            }\n            res.write(`data: ${JSON.stringify({\n              type: 'event',\n              event: event.type,\n              runId: event.runId || '',\n              mode: event.mode || '',\n              exitCode: event.exitCode,\n              success: event.success,\n              toolCount: event.toolCount\n            })}\\n\\n`);\n          }\n        });\n        const chunkText = run.success ? (run.stdout || '') : (run.stderr || `engine ${engine} failed`);\n        if (chunkText.trim().length > 0) {\n          res.write(`data: ${JSON.stringify({ type: 'chunk', text: chunkText })}\\n\\n`);\n        }\n        res.write(`data: ${JSON.stringify({ type: 'done', exitCode: run.exitCode })}\\n\\n`);\n        res.end();\n        return;\n      }\n\n      // Dashboard compatibility: passthrough session presence checks.\n      if (req.method === 'GET' && path === '/api/passthrough-sessions') {\n        const sessions = await passthroughSessions.listSummaries();\n        const nativeSessions = await listNativeEngineSessions(String(options.projectDir || process.cwd()));\n        return json(res, 200, { sessions, nativeSessions });\n      }\n\n      if (req.method === 'GET' && path === '/api/tool-audit') {\n        if (!checkAuth(req, res)) return;\n        const query = getQuery(req);\n        const limit = Number(query.get('limit') || 30);\n        const rows = await getToolAuditRuns(String(options.projectDir || process.cwd()), limit);\n        return json(res, 200, { runs: rows });\n      }\n\n      if (req.method === 'POST' && path === '/api/tool-audit/replay') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const runId = String(body?.runId || '').trim();\n        if (!runId) return json(res, 400, { error: 'runId is required' });\n        const dryRun = body?.execute !== true;\n        const plan = await getToolAuditReplayPlan(String(options.projectDir || process.cwd()), runId);\n        if (!plan) return json(res, 404, { error: `run ${runId} not found` });\n        if (dryRun) {\n          return json(res, 200, { ok: true, dryRun: true, plan });\n        }\n\n        const adapter = new GeminiToolAdapter(options.sandbox);\n        const applied: Array<{ name: string; success: boolean; error?: string }> = [];\n        await options.sandbox.load();\n        for (const call of (plan as ReplayPlan).supportedMutations || []) {\n          const toolName = String(call?.name || '').toLowerCase();\n          const args = (call?.args && typeof call.args === 'object') ? call.args : {};\n          const result = await adapter.executeTool(toolName, args);\n          applied.push({\n            name: toolName,\n            success: Boolean(result?.success),\n            error: result?.error\n          });\n        }\n        await options.sandbox.save();\n        return json(res, 200, {\n          ok: true,\n          dryRun: false,\n          runId,\n          replayed: applied.length,\n          applied\n        });\n      }\n\n      // \u2500\u2500 crew-cli RAG API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n      // GET /api/rag/search?q=auth&projectDir=/path&mode=import-graph\n      if (req.method === 'GET' && path === '/api/rag/search') {\n        if (!checkAuth(req, res)) return;\n        \n        try {\n          const { autoLoadRelevantFiles, shouldUseRag } = await import('../context/codebase-rag.js');\n          const query = getQuery(req);\n          const q = query.get('q') || '';\n          const projectDir = query.get('projectDir') || options.projectDir;\n          const mode = (query.get('mode') || 'import-graph') as RagMode;\n          const tokenBudget = Number(query.get('tokenBudget') || 8000);\n          const maxFiles = Number(query.get('maxFiles') || 10);\n          \n          if (!q) {\n            return json(res, 400, { error: 'Missing query parameter: q' });\n          }\n          \n          const startTime = Date.now();\n          const result = await autoLoadRelevantFiles(q, projectDir, {\n            mode,\n            tokenBudget,\n            maxFiles,\n            sessionHistory: []\n          });\n          \n          return json(res, 200, {\n            query: q,\n            projectDir,\n            mode: result.mode,\n            filesLoaded: result.filesLoaded,\n            tokenEstimate: result.tokenEstimate,\n            context: result.context,\n            elapsedMs: Date.now() - startTime,\n            shouldUseRag: shouldUseRag(q)\n          });\n        } catch (error: unknown) {\n          options.logger?.error?.('[rag] search error:', error);\n          return json(res, 500, { error: (error as Error).message });\n        }\n      }\n      \n      // POST /api/rag/index - Force re-index\n      if (req.method === 'POST' && path === '/api/rag/index') {\n        if (!checkAuth(req, res)) return;\n        \n        try {\n          const { autoLoadRelevantFiles } = await import('../context/codebase-rag.js');\n          const body = await readJson(req);\n          const projectDir = String(body?.projectDir || options.projectDir);\n          \n          const result = await autoLoadRelevantFiles('index build', projectDir, {\n            mode: 'semantic',\n            tokenBudget: 1000,\n            maxFiles: 5\n          });\n          \n          return json(res, 200, {\n            ok: true,\n            projectDir,\n            message: 'Index built (semantic embeddings)',\n            filesIndexed: result.filesLoaded.length\n          });\n        } catch (error: unknown) {\n          options.logger?.error?.('[rag] index error:', error);\n          return json(res, 500, { error: (error as Error).message });\n        }\n      }\n      \n      // GET /api/rag/stats?projectDir=/path\n      if (req.method === 'GET' && path === '/api/rag/stats') {\n        if (!checkAuth(req, res)) return;\n        \n        try {\n          const { existsSync } = await import('node:fs');\n          const query = getQuery(req);\n          const projectDir = query.get('projectDir') || options.projectDir;\n          const cacheDir = process.env.CREW_RAG_CACHE_DIR || `${projectDir}/.crew/rag-cache`;\n          \n          return json(res, 200, {\n            projectDir,\n            cacheDir,\n            exists: existsSync(cacheDir),\n            modes: {\n              keyword: 'always available (no cache)',\n              importGraph: 'always available (no cache)',\n              semantic: existsSync(`${cacheDir}/embeddings.json`) ? 'cached' : 'not cached'\n            }\n          });\n        } catch (error: unknown) {\n          options.logger?.error?.('[rag] stats error:', error);\n          return json(res, 500, { error: (error as Error).message });\n        }\n      }\n\n      // Health check\n      if (req.method === 'GET' && path === '/health') {\n        return json(res, 200, { ok: true, mode: options.mode });\n      }\n      if (req.method === 'DELETE' && path === '/api/passthrough-sessions') {\n        await closeNativeEngineSessions(String(options.projectDir || process.cwd()));\n        await passthroughSessions.clear();\n        return json(res, 200, { ok: true });\n      }\n\n      if (req.method === 'GET' && path === '/v1/models') {\n        const agents = options.router.getDefaultAgents().map((a: Record<string, unknown>) => ({\n          id: a.name,\n          object: 'model',\n          created: 1700000000,\n          owned_by: 'crewswarm'\n        }));\n        return json(res, 200, {\n          object: 'list',\n          data: [\n            { id: 'crewswarm', object: 'model', created: 1700000000, owned_by: 'crewswarm' },\n            ...agents\n          ]\n        });\n      }\n\n      if (req.method === 'POST' && path === '/v1/chat/completions') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const out = await handleOpenAIChatCompletions(options, body);\n        if ((out.data as StreamChatPayload)?._sse) {\n          const streamPayload = out.data as StreamChatPayload;\n          res.writeHead(200, {\n            'content-type': 'text/event-stream',\n            'cache-control': 'no-cache',\n            'connection': 'keep-alive',\n            'access-control-allow-origin': '*',\n            'access-control-allow-headers': 'content-type, authorization',\n            'access-control-allow-methods': 'GET,POST,OPTIONS'\n          });\n          for (const chunk of streamPayload.chunks || []) {\n            res.write(`data: ${JSON.stringify(chunk)}\\n\\n`);\n          }\n          res.write('data: [DONE]\\n\\n');\n          res.end();\n          return;\n        }\n        return json(res, out.status, out.data);\n      }\n\n      if (req.method === 'POST' && path === '/v1/tasks') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const out = options.mode === 'connected'\n          ? await enqueueConnectedTask(options, body)\n          : await enqueueStandaloneTask(options, body);\n        return json(res, out.status, out.data);\n      }\n\n      if (req.method === 'GET' && path.startsWith('/v1/tasks/')) {\n        const taskId = path.slice('/v1/tasks/'.length);\n        if (options.mode === 'connected') {\n          const gateway = options.gateway || 'http://127.0.0.1:5010';\n          const forwarded = await forwardJson(gateway, `/api/status/${encodeURIComponent(taskId)}`, 'GET');\n          const status = String(forwarded.data?.status || '').toLowerCase();\n          const mapped =\n            status === 'done' ? 'done' :\n            status === 'error' ? 'error' :\n            status === 'running' ? 'running' :\n            'queued';\n          return json(res, forwarded.ok ? 200 : forwarded.status, {\n            status: mapped,\n            result: forwarded.data?.result ?? forwarded.data,\n            traceId: '',\n            costUsd: 0,\n            error: forwarded.data?.error\n          });\n        }\n        const rec = taskStore.get(taskId);\n        if (!rec) return json(res, 404, { error: 'task not found' });\n        return json(res, 200, {\n          status: rec.status,\n          result: rec.result,\n          traceId: rec.traceId || '',\n          costUsd: rec.costUsd || 0,\n          error: rec.error\n        });\n      }\n\n      if (req.method === 'GET' && path === '/v1/agents') {\n        if (options.mode === 'connected') {\n          const gateway = options.gateway || 'http://127.0.0.1:5010';\n          const forwarded = await forwardJson(gateway, '/api/agents', 'GET');\n          const agents = Array.isArray(forwarded.data) ? forwarded.data : (forwarded.data?.agents || []);\n          return json(res, forwarded.ok ? 200 : forwarded.status, { agents });\n        }\n        const agents = options.router.getDefaultAgents().map((a: Record<string, unknown>) => ({\n          id: a.name,\n          role: a.role,\n          status: a.status\n        }));\n        return json(res, 200, { agents });\n      }\n\n      if (req.method === 'GET' && path === '/v1/status') {\n        let gatewayStatus = 'local';\n        let queueDepth = 0;\n        const pipelineMetrics = await loadPipelineMetricsSummary(options.projectDir);\n        if (options.mode === 'connected') {\n          try {\n            const status = await options.router.getStatus();\n            gatewayStatus = (status as StatusPayload)?.gateway || 'unknown';\n            queueDepth = Number((status as StatusPayload)?.queueDepth || 0);\n          } catch {\n            gatewayStatus = 'error';\n          }\n        } else {\n          queueDepth = Array.from(taskStore.values()).filter(t => t.status === 'queued' || t.status === 'running').length;\n        }\n\n        return json(res, 200, {\n          mode: options.mode,\n          gateway: gatewayStatus,\n          l2: {\n            unifiedRouter: process.env.CREW_USE_UNIFIED_ROUTER === 'true',\n            dualL2: process.env.CREW_DUAL_L2_ENABLED === 'true'\n          },\n          queueDepth,\n          pipeline: {\n            runs: pipelineMetrics.runs,\n            qaApproved: pipelineMetrics.qaApproved,\n            qaRejected: pipelineMetrics.qaRejected,\n            qaRoundsAvg: pipelineMetrics.runs > 0\n              ? Number((pipelineMetrics.qaRoundsTotal / pipelineMetrics.runs).toFixed(2))\n              : 0,\n            contextChunksUsed: pipelineMetrics.contextChunksUsed,\n            contextCharsSavedEst: pipelineMetrics.contextCharsSaved\n          }\n        });\n      }\n\n      if (req.method === 'GET' && path === '/v1/sandbox') {\n        const branch = options.sandbox.getActiveBranch();\n        const changedFiles = options.sandbox.getPendingPaths(branch).length;\n        return json(res, 200, {\n          branch,\n          changedFiles,\n          diffPreview: options.sandbox.preview(branch)\n        });\n      }\n\n      if (req.method === 'POST' && path === '/v1/sandbox/apply') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const branch = String(body?.branch || options.sandbox.getActiveBranch());\n        const files = options.sandbox.getPendingPaths(branch);\n        await options.sandbox.apply(branch);\n        return json(res, 200, {\n          success: true,\n          appliedFiles: files\n        });\n      }\n\n      if (req.method === 'POST' && path === '/v1/sandbox/rollback') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const branch = String(body?.branch || options.sandbox.getActiveBranch());\n        await options.sandbox.rollback(branch);\n        return json(res, 200, { success: true });\n      }\n\n      if (req.method === 'GET' && path.startsWith('/v1/traces/')) {\n        const traceId = path.slice('/v1/traces/'.length);\n        const trace = options.orchestrator.getTrace(traceId);\n        return json(res, 200, {\n          composedPrompts: trace?.composedPrompts || [],\n          plannerTrace: trace?.plannerTrace || [],\n          events: []\n        });\n      }\n\n      if (req.method === 'POST' && path === '/v1/index/rebuild') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const paths = Array.isArray(body?.paths) && body.paths.length > 0\n          ? body.paths\n          : [join(options.projectDir, 'docs'), options.projectDir];\n        latestIndex = await buildCollectionIndex(paths, {\n          includeCode: Boolean(body?.includeCode)\n        });\n        latestIndexId = `idx-${randomUUID()}`;\n        latestIndexStats = {\n          files: Number(latestIndex?.fileCount || 0),\n          chunks: Number(latestIndex?.chunks?.length || 0)\n        };\n        return json(res, 200, {\n          indexId: latestIndexId,\n          stats: latestIndexStats\n        });\n      }\n\n      if (req.method === 'GET' && path === '/v1/index/search') {\n        const q = String(getQuery(req).get('q') || '').trim();\n        if (!q) return json(res, 400, { error: 'q is required' });\n        if (!latestIndex) {\n          const fallback = await buildCollectionIndex([join(options.projectDir, 'docs'), options.projectDir], {\n            includeCode: false\n          });\n          latestIndex = fallback;\n          latestIndexId = `idx-${randomUUID()}`;\n          latestIndexStats = {\n            files: Number(latestIndex?.fileCount || 0),\n            chunks: Number(latestIndex?.chunks?.length || 0)\n          };\n        }\n        const result = searchCollection(latestIndex, q, 8);\n        const hits = (result?.hits || []).map((h: CollectionChunk) => ({\n          path: h.source,\n          score: Number(h.score || 0),\n          snippet: h.text\n        }));\n        return json(res, 200, { hits });\n      }\n\n      // MCP endpoint\n      if (req.method === 'POST' && path === '/mcp') {\n        if (!checkAuth(req, res)) return;\n        const body = await readJson(req);\n        const mcpRequest = asMcpRequest(body);\n        if (!mcpRequest) return json(res, 400, { error: 'invalid MCP request payload' });\n        const mcpResponse = await handleMcpRequest(options, mcpRequest);\n        if (mcpResponse && !('_skip' in mcpResponse && mcpResponse._skip)) {\n          return json(res, 200, mcpResponse);\n        } else {\n          // Notifications should not advertise a JSON body. Some MCP clients\n          // attempt to decode an empty 200/application-json response and log\n          // a transport error during initialized.\n          res.writeHead(204);\n          res.end();\n          return;\n        }\n      }\n\n      // MCP health check  \n      if (req.method === 'GET' && path === '/mcp/health') {\n        return json(res, 200, {\n          ok: true,\n          server: 'crew-cli-mcp',\n          mode: options.mode,\n          version: '1.0.0',\n          tools: 8\n        });\n      }\n\n      return json(res, 404, { error: 'not found' });\n    } catch (err) {\n      options.logger?.error?.('[serve] request failed', err);\n      return json(res, 500, { error: String((err as Error)?.message || err) });\n    }\n  });\n\n  await new Promise<void>((resolve, reject) => {\n    server.once('error', reject);\n    server.listen(options.port, options.host, () => resolve());\n  });\n  const bound = server.address();\n  const actualPort = typeof bound === 'object' && bound ? bound.port : options.port;\n  const address = `http://${options.host}:${actualPort}`;\n  options.logger?.info?.(`[serve] unified API listening on ${address} (${options.mode})`);\n  return {\n    address,\n    close: async () => {\n      await new Promise<void>((resolve, reject) => server.close(err => err ? reject(err) : resolve()));\n    }\n  };\n}\n", "import { IncomingMessage, ServerResponse } from 'http';\nimport { UnifiedServerOptions } from './server.js';\nimport type { CollectionChunk } from '../collections/index.js';\n\ninterface McpRequest {\n  jsonrpc: string;\n  id: string | number;\n  method: string;\n  params?: Record<string, unknown>;\n}\n\ninterface McpResponse {\n  jsonrpc?: string;\n  id?: string | number;\n  result?: Record<string, unknown>;\n  error?: {\n    code: number;\n    message: string;\n  };\n  /** Internal sentinel: notifications don't need a JSON response body */\n  _skip?: boolean;\n}\n\nexport async function handleMcpRequest(\n  options: UnifiedServerOptions,\n  body: McpRequest\n): Promise<McpResponse> {\n  const { method, params, id } = body;\n\n  try {\n    switch (method) {\n      case 'initialize':\n        return {\n          jsonrpc: '2.0',\n          id,\n          result: {\n            protocolVersion: '2024-11-05',\n            capabilities: { tools: {} },\n            serverInfo: {\n              name: 'crew-cli',\n              version: '1.0.0',\n              description: 'crew-cli unified orchestration and sandbox tools'\n            }\n          }\n        };\n\n      case 'notifications/initialized':\n      case 'initialized':\n        // Notification - no response needed\n        return { _skip: true };\n\n      case 'tools/list':\n        return {\n          jsonrpc: '2.0',\n          id,\n          result: {\n            tools: [\n              {\n                name: 'crew_route_task',\n                description: 'Route a task through the unified orchestrator (L1\u2192L2\u2192L3)',\n                inputSchema: {\n                  type: 'object',\n                  properties: {\n                    task: { type: 'string', description: 'Task to execute' },\n                    context: { type: 'string', description: 'Optional context' }\n                  },\n                  required: ['task']\n                }\n              },\n              {\n                name: 'crew_execute_code',\n                description: 'Execute code generation task with sandbox isolation',\n                inputSchema: {\n                  type: 'object',\n                  properties: {\n                    task: { type: 'string', description: 'Code generation task' },\n                    model: { type: 'string', description: 'Optional model override' }\n                  },\n                  required: ['task']\n                }\n              },\n              {\n                name: 'crew_sandbox_status',\n                description: 'Get current sandbox state (pending changes, branch info)',\n                inputSchema: {\n                  type: 'object',\n                  properties: {},\n                  required: []\n                }\n              },\n              {\n                name: 'crew_sandbox_preview',\n                description: 'Preview pending changes in sandbox',\n                inputSchema: {\n                  type: 'object',\n                  properties: {},\n                  required: []\n                }\n              },\n              {\n                name: 'crew_sandbox_apply',\n                description: 'Apply pending sandbox changes to working directory',\n                inputSchema: {\n                  type: 'object',\n                  properties: {\n                    check: { type: 'string', description: 'Optional validation command (e.g. npm test)' }\n                  },\n                  required: []\n                }\n              },\n              {\n                name: 'crew_sandbox_rollback',\n                description: 'Rollback sandbox to previous state',\n                inputSchema: {\n                  type: 'object',\n                  properties: {},\n                  required: []\n                }\n              },\n              {\n                name: 'crew_search_code',\n                description: 'Search codebase with semantic/text search',\n                inputSchema: {\n                  type: 'object',\n                  properties: {\n                    query: { type: 'string', description: 'Search query' },\n                    limit: { type: 'number', description: 'Max results' }\n                  },\n                  required: ['query']\n                }\n              },\n              {\n                name: 'crew_list_models',\n                description: 'List available models and agents',\n                inputSchema: {\n                  type: 'object',\n                  properties: {},\n                  required: []\n                }\n              }\n            ]\n          }\n        };\n\n      case 'tools/call':\n        return await handleToolCall(options, params || {}, id);\n\n      default:\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: -32601,\n            message: `Method not found: ${method}`\n          }\n        };\n    }\n  } catch (err) {\n    return {\n      jsonrpc: '2.0',\n      id,\n      error: {\n        code: -32603,\n        message: String((err as Error)?.message || err)\n      }\n    };\n  }\n}\n\nasync function handleToolCall(\n  options: UnifiedServerOptions,\n  params: Record<string, unknown>,\n  id: string | number\n): Promise<McpResponse> {\n  const { name, arguments: args } = params as { name: string; arguments?: Record<string, unknown> };\n\n  try {\n    let result: Record<string, unknown>;\n\n    switch (name) {\n      case 'crew_route_task': {\n        const message = String(args?.task || '').trim();\n        const context = String(args?.context || '').trim();\n        const mergedInput = context ? `${message}\\n\\n${context}` : message;\n        \n        const route = await options.orchestrator.route(mergedInput);\n        const decision = String(route?.decision || '');\n        \n        if (decision === 'CHAT' && route.response) {\n          result = {\n            decision: 'CHAT',\n            response: route.response,\n            executionPath: ['l1-interface', 'l2-orchestrator', 'l2-direct-response']\n          };\n        } else {\n          const local = await options.orchestrator.executeLocally(route.task || mergedInput, {\n            model: args?.model as string | undefined\n          });\n          await options.orchestrator.parseAndApplyToSandbox(String(local?.result || ''));\n          \n          result = {\n            decision: decision || 'CODE',\n            response: local?.result,\n            executionPath: ['l1-interface', 'l2-orchestrator', 'l3-executor'],\n            pendingChanges: options.sandbox.getPendingPaths(options.sandbox.getActiveBranch()).length\n          };\n        }\n        break;\n      }\n\n      case 'crew_execute_code': {\n        const task = String(args?.task || '').trim();\n        const local = await options.orchestrator.executeLocally(task, {\n          model: args?.model as string | undefined\n        });\n        const edits = await options.orchestrator.parseAndApplyToSandbox(String(local?.result || ''));\n        \n        result = {\n          response: local?.result,\n          edits: edits.length,\n          pendingChanges: options.sandbox.getPendingPaths(options.sandbox.getActiveBranch()).length\n        };\n        break;\n      }\n\n      case 'crew_sandbox_status': {\n        const branch = options.sandbox.getActiveBranch();\n        const pending = options.sandbox.getPendingPaths(branch);\n        \n        result = {\n          branch,\n          pendingFiles: pending.length,\n          files: pending\n        };\n        break;\n      }\n\n      case 'crew_sandbox_preview': {\n        const branch = options.sandbox.getActiveBranch();\n        const pending = options.sandbox.getPendingPaths(branch);\n        const diffs = pending.map(p => {\n          const sandboxExt = options.sandbox as { readPendingFile?: (branch: string, path: string) => string };\n          const content = sandboxExt.readPendingFile?.(branch, p) || options.sandbox.getStagedContent(p, branch);\n          return { path: p, content };\n        });\n        \n        result = {\n          branch,\n          changes: diffs\n        };\n        break;\n      }\n\n      case 'crew_sandbox_apply': {\n        const branch = options.sandbox.getActiveBranch();\n        await options.sandbox.apply(branch);\n        \n        result = {\n          success: true,\n          message: 'Changes applied to working directory'\n        };\n        break;\n      }\n\n      case 'crew_sandbox_rollback': {\n        const branch = options.sandbox.getActiveBranch();\n        await options.sandbox.rollback(branch);\n        const newBranch = 'main'; // createBranch requires a name arg\n        \n        result = {\n          success: true,\n          message: `Rolled back ${branch}, created ${newBranch}`\n        };\n        break;\n      }\n\n      case 'crew_search_code': {\n        const query = String(args?.query || '').trim();\n        const limit = parseInt(String(args?.limit || '10'), 10);\n\n        if (!query) {\n          result = { query, results: [], message: 'Empty query' };\n          break;\n        }\n\n        try {\n          const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n          const idx = await buildCollectionIndex([options.projectDir], { includeCode: true });\n          const hits = searchCollection(idx, query, limit);\n          result = {\n            query,\n            results: hits.hits.map((r: CollectionChunk) => ({\n              file: r.source,\n              line: r.startLine,\n              text: r.text.slice(0, 500),\n              score: r.score\n            })),\n            total: hits.totalChunks\n          };\n        } catch (err) {\n          result = { query, results: [], message: `Search error: ${(err as Error).message}` };\n        }\n        break;\n      }\n\n      case 'crew_list_models': {\n        const agents = options.router.getDefaultAgents().map((a: Record<string, unknown>) => ({\n          id: a.id,\n          name: a.name,\n          role: a.role\n        }));\n        \n        result = {\n          mode: options.mode,\n          agents\n        };\n        break;\n      }\n\n      default:\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: -32601,\n            message: `Tool not found: ${name}`\n          }\n        };\n    }\n\n    return {\n      jsonrpc: '2.0',\n      id,\n      result: {\n        content: [\n          {\n            type: 'text',\n            text: JSON.stringify(result, null, 2)\n          }\n        ]\n      }\n    };\n  } catch (err) {\n    return {\n      jsonrpc: '2.0',\n      id,\n      error: {\n        code: -32603,\n        message: String((err as Error)?.message || err)\n      }\n    };\n  }\n}\n", "import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport interface PipelineMetricsSummary {\n  runs: number;\n  qaApproved: number;\n  qaRejected: number;\n  qaRoundsTotal: number;\n  contextChunksUsed: number;\n  contextCharsSaved: number;\n}\n\nexport async function loadPipelineMetricsSummary(baseDir: string): Promise<PipelineMetricsSummary> {\n  const path = join(baseDir, '.crew', 'pipeline-metrics.jsonl');\n  try {\n    const raw = await readFile(path, 'utf8');\n    const lines = raw.split('\\n').map(l => l.trim()).filter(Boolean);\n    let runs = 0;\n    let qaApproved = 0;\n    let qaRejected = 0;\n    let qaRoundsTotal = 0;\n    let contextChunksUsed = 0;\n    let contextCharsSaved = 0;\n    for (const line of lines) {\n      try {\n        const rec = JSON.parse(line);\n        runs += 1;\n        if (rec.qaApproved === true) qaApproved += 1;\n        if (rec.qaApproved === false) qaRejected += 1;\n        qaRoundsTotal += Number(rec.qaRounds || 0);\n        contextChunksUsed += Number(rec.contextChunksUsed || 0);\n        contextCharsSaved += Number(rec.contextCharsSaved || 0);\n      } catch {\n        // Ignore malformed rows.\n      }\n    }\n    return { runs, qaApproved, qaRejected, qaRoundsTotal, contextChunksUsed, contextCharsSaved };\n  } catch {\n    return { runs: 0, qaApproved: 0, qaRejected: 0, qaRoundsTotal: 0, contextChunksUsed: 0, contextCharsSaved: 0 };\n  }\n}\n", "import { spawn } from 'node:child_process';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport interface SrcCommandResult {\n  success: boolean;\n  code: number;\n  stdout: string;\n  stderr: string;\n}\n\nexport function runSrcCli(args: string[], cwd = process.cwd()): Promise<SrcCommandResult> {\n  return new Promise(resolve => {\n    const child = spawn('src', args, {\n      cwd,\n      stdio: ['ignore', 'pipe', 'pipe'],\n      env: process.env\n    });\n\n    let stdout = '';\n    let stderr = '';\n\n    child.stdout.on('data', chunk => { stdout += String(chunk); });\n    child.stderr.on('data', chunk => { stderr += String(chunk); });\n\n    child.on('error', error => {\n      resolve({\n        success: false,\n        code: 1,\n        stdout,\n        stderr: `${stderr}${error.message}`\n      });\n    });\n\n    child.on('close', code => {\n      resolve({\n        success: code === 0,\n        code: code ?? 1,\n        stdout,\n        stderr\n      });\n    });\n  });\n}\n\nexport interface SrcBatchPlanOptions {\n  query: string;\n  repos: string[];\n  execute?: boolean;\n  specPath?: string;\n}\n\nexport async function createSrcBatchPlan(options: SrcBatchPlanOptions, cwd = process.cwd()): Promise<{\n  success: boolean;\n  specPath: string;\n  message: string;\n}> {\n  if (!options.query) {\n    return { success: false, specPath: '', message: 'Missing --query for batch-plan' };\n  }\n\n  const repos = options.repos.length ? options.repos : ['repo:^github\\\\.com/.+'];\n  const specPath = options.specPath || '.crew/src-batch.spec.yaml';\n  const full = join(cwd, specPath);\n  await mkdir(join(full, '..'), { recursive: true });\n\n  const yaml = [\n    'name: crew-src-batch-plan',\n    'description: Generated by crew src batch-plan',\n    `on: ${repos[0]}`,\n    'steps:',\n    `  - run: |`,\n    `      # Replace with desired codemod command`,\n    `      src search '${options.query.replace(/'/g, \"\\\\'\")}'`,\n    '',\n    'changesetTemplate:',\n    '  title: \"chore: planned codemod\"',\n    '  body: |',\n    '    Generated by `crew src batch-plan` in dry-run mode.'\n  ].join('\\n');\n\n  await writeFile(full, `${yaml}\\n`, 'utf8');\n\n  if (!options.execute) {\n    return {\n      success: true,\n      specPath: full,\n      message: `Batch plan created at ${full}. Dry-run only. Execute with: src batch preview -f ${full}`\n    };\n  }\n\n  const preview = await runSrcCli(['batch', 'preview', '-f', full], cwd);\n  if (!preview.success) {\n    return { success: false, specPath: full, message: preview.stderr || 'src batch preview failed' };\n  }\n  return { success: true, specPath: full, message: 'src batch preview succeeded' };\n}\n", "import type { Interface as ReadlineInterface } from 'node:readline';\nimport { createInterface, emitKeypressEvents } from 'node:readline';\nimport { randomUUID } from 'node:crypto';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport chalk from 'chalk';\n// Lazy-load inquirer to avoid ESM/CJS interop deadlock on Node 24\n// (inquirer@9 is ESM but its nested ora@5 dep is CJS)\nlet _inquirer: typeof import('inquirer').default | null = null;\nasync function getInquirer() {\n  if (!_inquirer) {\n    const mod = await import('inquirer');\n    _inquirer = mod.default;\n  }\n  return _inquirer;\n}\nimport type { RepoConfig } from '../config/repo-config.js';\nimport { AgentRouter } from '../agent/router.js';\nimport { SessionManager } from '../session/manager.js';\nimport { Orchestrator } from '../orchestrator/index.js';\nimport { Sandbox } from '../sandbox/index.js';\nimport { Logger } from '../utils/logger.js';\nimport { getProjectContext } from '../context/git.js';\nimport { collectMultiRepoContext } from '../multirepo/index.js';\nimport { AgentKeeper } from '../memory/agentkeeper.js';\nimport { MemoryBroker } from '../memory/broker.js';\nimport { CheckpointStore } from '../checkpoint/store.js';\nimport { ConversationTranscriptStore } from '../session/conversation-transcript.js';\nimport { loadPipelineMetricsSummary } from '../metrics/pipeline.js';\nimport { estimateCost } from '../cost/predictor.js';\nimport { getExecutionPolicy, isRiskBlocked, withRetries } from '../runtime/execution-policy.js';\nimport { analyzeBlastRadius } from '../blast-radius/index.js';\nimport { scorePatchRisk } from '../risk/score.js';\nimport { runEngine } from '../engines/index.js';\n\nconst BANNER = `\n \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551                                                                           \u2551\n \u2551     \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557    \u2588\u2588\u2557      \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557     \u2588\u2588\u2557           \u2551\n \u2551    \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551    \u2588\u2588\u2551     \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n \u2551    \u2588\u2588\u2551      \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2557  \u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n \u2551    \u2588\u2588\u2551      \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u255D  \u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551     \u2588\u2588\u2551           \u2551\n \u2551    \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551  \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D     \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551           \u2551\n \u2551     \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D  \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D       \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D           \u2551\n \u2551                                                                           \u2551\n \u2551                   \uD83C\uDFAA One idea. One Build. One Crew.                       \u2551\n \u2551                                                                           \u2551\n \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n`;\n\nconst AVAILABLE_MODELS = [\n  'gpt-5.4', 'gpt-5.3-codex', 'gemini-3.1-pro', 'gemini-2.5-flash',\n  'claude-sonnet-4.6', 'grok-4.20-beta', 'grok-4.1-fast',\n  'deepseek-v3.2', 'qwen3.5-397b', 'kimi-k2.5', 'llama-3.3-70b'\n];\n\nconst AVAILABLE_ENGINES = ['auto', 'cursor', 'cursor-cli', 'claude', 'claude-cli', 'gemini', 'gemini-cli', 'codex', 'codex-cli', 'crew-cli'];\n\nexport interface ReplOptions {\n  router: AgentRouter;\n  orchestrator: Orchestrator;\n  sandbox: Sandbox;\n  session: SessionManager;\n  logger: Logger;\n  projectDir?: string;\n  repoConfig?: Required<RepoConfig>;\n  initialMode?: 'manual' | 'assist' | 'autopilot';\n  initialInterfaceMode?: 'connected' | 'standalone';\n  promptInterfaceMode?: boolean;\n  uiMode?: 'repl' | 'tui';\n}\n\ninterface ReplState {\n  model: string;\n  engine: string;\n  autoApply: boolean;\n  memoryMax: number;\n  mode: ReplMode;\n  verbose: boolean;\n  routerProvider: string; // Tier 1: grok, gemini, deepseek\n  executorProvider: string; // Tier 2: grok, gemini, deepseek\n  useGateway: boolean; // Tier 3: gateway for specialists\n}\n\ntype ReplMode = 'manual' | 'assist' | 'autopilot';\nconst REPL_MODE_ORDER: ReplMode[] = ['manual', 'assist', 'autopilot'];\n\nconst SLASH_COMMAND_GROUPS: Array<{ title: string; commands: string[] }> = [\n  { title: 'Session', commands: ['/help', '/info', '/status', '/history', '/clear', '/exit'] },\n  { title: 'Model & Engine', commands: ['/stack', '/engine', '/engines', '/mode'] },\n  { title: 'Sandbox', commands: ['/preview', '/apply', '/rollback', '/branch', '/branches'] },\n  { title: 'Runtime', commands: ['/tools', '/trace', '/timeline', '/cost', '/system', '/permissions'] },\n  { title: 'Context', commands: ['/image', '/search', '/recall', '/sessions', '/resume', '/skills'] },\n  { title: 'Agents', commands: ['/summon'] }\n];\n\ninterface ModelSummary {\n  mode: 'connected' | 'standalone';\n  replModel: string;\n  replEngine: string;\n  routerProvider: string;\n  executorProvider: string;\n  gatewayEnabled: boolean;\n  policyTierModels: string[];\n  agentModels: string[];\n  providerKeys: string[];\n}\n\ninterface RepoBootstrap {\n  projectDir: string;\n  topEntries: string[];\n  docs: string[];\n  keyFiles: string[];\n  readmeSummary: string;\n}\n\ninterface SessionHistoryEntry {\n  timestamp?: string;\n  type?: string;\n  agent?: string;\n  task?: string;\n  input?: string;\n  output?: string;\n  response?: string;\n  result?: string;\n}\n\ninterface ReplExecutionResult {\n  success?: boolean;\n  stdout?: string;\n  stderr?: string;\n  response?: string;\n  result?: unknown;\n  model?: string;\n  modelUsed?: string;\n  provider?: string;\n  providerId?: string;\n  engine?: string;\n  costUsd?: number;\n  cost?: number;\n  promptTokens?: number;\n  completionTokens?: number;\n  turns?: number;\n  toolsUsed?: unknown[];\n  timeline?: Array<{ phase: string; ts: string }>;\n}\n\nfunction readJsonFile(filePath: string): Record<string, unknown> | null {\n  try {\n    if (!existsSync(filePath)) return null;\n    return JSON.parse(readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n  } catch {\n    return null;\n  }\n}\n\nfunction getSlashCommands(): string[] {\n  const flat = SLASH_COMMAND_GROUPS.flatMap((group) => group.commands);\n  return Array.from(new Set(flat));\n}\n\nfunction printSlashCommandMenu(filter = '') {\n  const normalized = filter.trim().toLowerCase();\n  console.log(chalk.blue('\\n--- Slash Commands ---\\n'));\n  for (const group of SLASH_COMMAND_GROUPS) {\n    const matches = group.commands.filter((command) => !normalized || command.startsWith(normalized));\n    if (matches.length === 0) continue;\n    console.log(chalk.cyan(`  ${group.title}:`));\n    console.log(`    ${matches.join('   ')}`);\n  }\n  console.log(chalk.gray('\\n  Type a command directly or press Tab to autocomplete.\\n'));\n}\n\nasync function listInstalledSkills(): Promise<Array<{ name: string; type: 'knowledge' | 'api'; path: string }>> {\n  const skillsRoot = join(homedir(), '.crewswarm', 'skills');\n  const out: Array<{ name: string; type: 'knowledge' | 'api'; path: string }> = [];\n  try {\n    const entries = await readdir(skillsRoot, { withFileTypes: true });\n    for (const entry of entries) {\n      if (entry.isFile() && entry.name.endsWith('.json')) {\n        out.push({ name: entry.name.replace(/\\.json$/i, ''), type: 'api', path: join(skillsRoot, entry.name) });\n      } else if (entry.isDirectory()) {\n        const skillDoc = join(skillsRoot, entry.name, 'SKILL.md');\n        if (existsSync(skillDoc)) {\n          out.push({ name: entry.name, type: 'knowledge', path: skillDoc });\n        }\n      }\n    }\n  } catch {\n    return [];\n  }\n  return out.sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction resolveConfiguredReplModel(repoConfig?: Required<RepoConfig>): string {\n  const repoModel = String(repoConfig?.repl?.model || '').trim();\n  if (repoModel) return repoModel;\n\n  const envCandidates = [\n    process.env.CREW_CHAT_MODEL,\n    process.env.CREW_ROUTER_MODEL,\n    process.env.CREW_EXECUTION_MODEL\n  ].map(value => String(value || '').trim()).filter(Boolean);\n  if (envCandidates.length > 0) return envCandidates[0];\n\n  const swarmCfg = readJsonFile(join(homedir(), '.crewswarm', 'crewswarm.json')) || {};\n  const sharedEnv = swarmCfg?.env && typeof swarmCfg.env === 'object' ? swarmCfg.env as Record<string, unknown> : {} as Record<string, unknown>;\n  const sharedCandidates = [\n    sharedEnv.CREW_CHAT_MODEL,\n    sharedEnv.CREW_ROUTER_MODEL,\n    sharedEnv.CREW_EXECUTION_MODEL\n  ].map((value: unknown) => String(value || '').trim()).filter(Boolean);\n  if (sharedCandidates.length > 0) return sharedCandidates[0];\n\n  return 'grok-4-1-fast-reasoning';\n}\n\nfunction buildModelSummary(projectDir: string, state: ReplState): ModelSummary {\n  const envMode = String(process.env.CREW_INTERFACE_MODE || '').toLowerCase();\n  const mode: 'connected' | 'standalone' =\n    envMode === 'connected' ? 'connected' : (state.useGateway ? 'connected' : 'standalone');\n\n  const policyPath = join(projectDir, '.crew', 'model-policy.json');\n  const policy = readJsonFile(policyPath) || {};\n  const tiers = (policy?.tiers && typeof policy.tiers === 'object' ? policy.tiers : {}) as Record<string, Record<string, unknown>>;\n  const policyTierModels = Array.from(\n    new Set(\n      ['planner', 'executor', 'worker'].flatMap((tier: string) => {\n        const cfg = tiers?.[tier] || {};\n        return [cfg?.primary, ...(Array.isArray(cfg?.fallback) ? cfg.fallback : [])]\n          .map((x: unknown) => String(x || '').trim())\n          .filter(Boolean);\n      })\n    )\n  );\n\n  const swarmCfg = readJsonFile(join(homedir(), '.crewswarm', 'crewswarm.json')) || {};\n  const agents = Array.isArray(swarmCfg?.agents) ? swarmCfg.agents as Array<Record<string, unknown>> : [];\n  const agentModels = Array.from(\n    new Set(\n      agents\n        .map((a) => String(a?.model || '').trim())\n        .filter(Boolean)\n    )\n  );\n\n  const providers = swarmCfg?.providers && typeof swarmCfg.providers === 'object' ? swarmCfg.providers as Record<string, Record<string, unknown>> : {};\n  const providerKeys = Object.entries(providers)\n    .filter(([, v]) => Boolean(v && (v.apiKey || v.baseUrl)))\n    .map(([k]) => String(k));\n\n  return {\n    mode,\n    replModel: state.model,\n    replEngine: state.engine,\n    routerProvider: state.routerProvider,\n    executorProvider: state.executorProvider,\n    gatewayEnabled: state.useGateway,\n    policyTierModels,\n    agentModels,\n    providerKeys\n  };\n}\n\nfunction printModelSummary(summary: ModelSummary) {\n  console.log(chalk.blue('\\n--- Model Configuration ---\\n'));\n  console.log(`  Interface mode: ${summary.mode}`);\n  console.log(`  REPL model/engine: ${summary.replModel} / ${summary.replEngine}`);\n  console.log(`  L2 providers: router=${summary.routerProvider}, executor=${summary.executorProvider}`);\n  console.log(`  Tier-3 gateway: ${summary.gatewayEnabled ? 'enabled' : 'disabled'}`);\n  console.log(`  Policy-tier models: ${summary.policyTierModels.length ? summary.policyTierModels.join(', ') : '(none set)'}`);\n  console.log(`  Agent models (~/.crewswarm/crewswarm.json): ${summary.agentModels.length ? summary.agentModels.join(', ') : '(none found)'}`);\n  console.log(`  Providers configured: ${summary.providerKeys.length ? summary.providerKeys.join(', ') : '(none found)'}`);\n  console.log(chalk.gray('\\n  Change models with: /model, /stack, .crew/model-policy.json, ~/.crewswarm/crewswarm.json\\n'));\n}\n\nasync function buildRepoBootstrap(projectDir: string): Promise<RepoBootstrap> {\n  const ignored = new Set(['.git', 'node_modules', '.crew', 'dist']);\n  let topEntries: string[] = [];\n  try {\n    const entries = await readdir(projectDir, { withFileTypes: true });\n    topEntries = entries\n      .filter(e => !ignored.has(e.name))\n      .map(e => (e.isDirectory() ? `${e.name}/` : e.name))\n      .sort()\n      .slice(0, 20);\n  } catch {\n    topEntries = [];\n  }\n\n  let docs: string[] = [];\n  try {\n    const docsEntries = await readdir(join(projectDir, 'docs'), { withFileTypes: true });\n    docs = docsEntries\n      .filter(e => e.isFile() && e.name.toLowerCase().endsWith('.md'))\n      .map(e => `docs/${e.name}`)\n      .sort()\n      .slice(0, 15);\n  } catch {\n    docs = [];\n  }\n\n  const keyCandidates = [\n    'README.md',\n    'ROADMAP.md',\n    'progress.md',\n    'docs/API-UNIFIED-v1.md',\n    'docs/openapi.unified.v1.json',\n    'src/cli/index.ts',\n    'src/repl/index.ts',\n    'src/interface/server.ts'\n  ];\n  const keyFiles = keyCandidates.filter(p => existsSync(join(projectDir, p)));\n\n  let readmeSummary = '';\n  try {\n    const raw = await readFile(join(projectDir, 'README.md'), 'utf8');\n    const lines = raw\n      .split('\\n')\n      .map(l => l.trim())\n      .filter(Boolean);\n    readmeSummary = lines.slice(0, 3).join(' ').slice(0, 260);\n  } catch {\n    readmeSummary = '';\n  }\n\n  return {\n    projectDir,\n    topEntries,\n    docs,\n    keyFiles,\n    readmeSummary\n  };\n}\n\nfunction printSystemSummary(summary: ModelSummary, bootstrap: RepoBootstrap) {\n  console.log(chalk.blue('\\n--- System Summary ---\\n'));\n  console.log(`  Mode: ${summary.mode} (${summary.gatewayEnabled ? 'gateway enabled' : 'local-only'})`);\n  console.log(`  L1 (chat): ${summary.replModel} via ${summary.replEngine}`);\n  console.log(`  L2 (reasoning): router=${summary.routerProvider}, executor=${summary.executorProvider}`);\n  console.log(`  L3 (workers): ${summary.agentModels.length} configured agent model assignments`);\n  console.log(`  Providers: ${summary.providerKeys.length ? summary.providerKeys.join(', ') : '(none found)'}`);\n  console.log(`  Project: ${bootstrap.projectDir}`);\n  console.log(`  Key files: ${bootstrap.keyFiles.length ? bootstrap.keyFiles.join(', ') : '(none detected)'}`);\n  console.log(chalk.gray('\\n  Commands: /stack, /stack, /status, /preview, /apply, /trace <id>\\n'));\n}\n\nfunction answerLocalMetaQuestion(input: string, summary: ModelSummary): string | null {\n  const lower = input.trim().toLowerCase();\n  if (!lower) return null;\n\n  if (/^(hi|hello|hey)\\b/.test(lower)) {\n    return 'Hi. I can build/fix code, or answer stack config. Try: \"what models are configured?\"';\n  }\n\n  if (/\\b(solo mode|standalone mode|connected mode|are you in solo mode)\\b/.test(lower)) {\n    if (summary.mode === 'standalone') {\n      return 'You are in standalone mode. Routing/execution is local unless you explicitly use gateway-backed commands.';\n    }\n    return 'You are in connected mode. Requests route through crew-lead/gateway for multi-agent orchestration.';\n  }\n\n  if (\n    /\\b(what|which).*(models?|providers?).*(configured|active|set)\\b/.test(lower) ||\n    /\\bmodels?\\s+configured\\b/.test(lower)\n  ) {\n    const policy = summary.policyTierModels.length ? summary.policyTierModels.join(', ') : '(none set)';\n    const agents = summary.agentModels.length ? summary.agentModels.join(', ') : '(none found)';\n    return [\n      `Mode: ${summary.mode}.`,\n      `REPL model/engine: ${summary.replModel} / ${summary.replEngine}.`,\n      `L2 providers: router=${summary.routerProvider}, executor=${summary.executorProvider}.`,\n      `Policy-tier models: ${policy}.`,\n      `Agent models: ${agents}.`,\n      'Use /stack for full details, then change via /model, /stack, .crew/model-policy.json, or ~/.crewswarm/crewswarm.json.'\n    ].join(' ');\n  }\n\n  if (/\\b(change|modify|set|update).*(models?|model)\\b/.test(lower)) {\n    return 'Yes. Use /stack (models and providers per tier), or edit .crew/model-policy.json and ~/.crewswarm/crewswarm.json for persistent model changes.';\n  }\n\n  if (/\\b(what can you do|help me|onboard|getting started|how do i use)\\b/.test(lower)) {\n    return [\n      'Here is the fast path.',\n      '1) /stack to inspect real model/provider config.',\n      '2) /stack to set Tier-1 router + Tier-2 executor + gateway toggle.',\n      '3) Ask build/fix tasks directly; I route and stage edits in sandbox.',\n      '4) /preview then /apply (or /rollback).',\n      '5) /trace <id> for prompt/planner trace.',\n      'If you want me to run an exact command, say it explicitly: e.g. \"run /stack\".'\n    ].join(' ');\n  }\n\n  if (/\\b(run|execute)\\s+\\/[a-z-]+/.test(lower)) {\n    return 'Use slash commands directly in REPL. Example: /stack, /stack, /status, /preview, /apply, /trace <traceId>.';\n  }\n\n  return null;\n}\n\nfunction answerFromBootstrap(input: string, summary: ModelSummary, bootstrap: RepoBootstrap): string | null {\n  const lower = input.trim().toLowerCase();\n  if (!lower) return null;\n\n  // Greetings and smalltalk \u2014 don't waste L2 tokens on these\n  if (/^(hi|hey|hello|yo|sup|hola|howdy|hej|oi|what'?s? up|wh?at up|how('?s it going|'?re you|( are)? you doin|( are)? ya)|good (morning|afternoon|evening)|gm|gn)\\b/.test(lower)) {\n    const greetings = [\n      'Hi. I can build/fix code, or answer stack config. Try: \"what models are configured?\"',\n      'Hey! Ready to code. What do you need built or fixed?',\n      'Yo. Give me a coding task, a file to review, or ask about the system.',\n      'What\\'s up! I\\'m your coding crew. Drop a task or ask /help for commands.',\n    ];\n    return greetings[Math.floor(Math.random() * greetings.length)];\n  }\n\n  // Thanks / bye \u2014 quick responses\n  if (/^(thanks|thank you|thx|ty|cheers|nice|cool|great|awesome|perfect|ok|okay|k|bye|goodbye|later|peace)\\b/.test(lower)) {\n    return lower.match(/bye|goodbye|later|peace/) \n      ? 'Later! Run /exit or just close the terminal.' \n      : '\uD83D\uDC4D';\n  }\n\n  if (\n    /\\b(how does this system work|explain (the )?(system|architecture)|what is crew-cli|tell me about crew-cli)\\b/.test(lower)\n  ) {\n    const docs = bootstrap.docs.slice(0, 5).join(', ') || '(no docs indexed)';\n    const keys = bootstrap.keyFiles.slice(0, 6).join(', ') || '(no key files found)';\n    return [\n      `crewswarm CLI is a multi-layer orchestrator in ${summary.mode} mode.`,\n      `L1 chat runs on ${summary.replModel}/${summary.replEngine}; L2 uses router=${summary.routerProvider} and executor=${summary.executorProvider}; L3 uses configured worker/agent models.`,\n      `Key repo files: ${keys}.`,\n      `Docs index snapshot: ${docs}.`,\n      `Use /system for full stack summary and /stack for exact model/provider config.`\n    ].join(' ');\n  }\n\n  if (/\\b(read|write|file access|filesystem|permissions)\\b/.test(lower)) {\n    if (summary.mode === 'standalone') {\n      return 'Standalone mode has local read/write through orchestrator + sandbox. Edits stage in sandbox first, then /apply writes to disk.';\n    }\n    return 'Connected mode executes through gateway/agents; file operations happen via agent tools and still stage through sandbox workflow on this CLI.';\n  }\n\n  return null;\n}\n\nfunction printHelp(uiMode: 'repl' | 'tui' = 'repl') {\n  console.log(chalk.blue.bold('\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n  console.log(chalk.blue.bold('\u2551                       CREW REPL COMMANDS                             \u2551'));\n  console.log(chalk.blue.bold('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n'));\n\n  console.log(chalk.cyan.bold('  \uD83D\uDCCB Session Commands:'));\n  console.log('    /help              Show this comprehensive help');\n  console.log('    /info              Show current model, engine, and settings');\n  console.log('    /status            Session info (cost, history, sandbox)');\n  console.log('    /cost              Total spend this session');\n  console.log('    /history [n]       Show last n messages (default: 5)');\n  console.log('    /clear             Clear session history');\n  console.log('    /trace             Show execution path and composed prompts\\n');\n\n  console.log(chalk.yellow.bold('  Sandbox & Git:'));\n    console.log('    /preview           Show pending changes (colored diff)');\n    console.log('    /apply [--commit]  Write sandbox to disk + auto-commit');\n    console.log('    /rollback          Discard all pending changes');\n    console.log('    /diff              Show colored git diff');\n    console.log('    /branch [name]     List sandbox branches or switch directly');\n    console.log('    /branches          Same as /branch');\n    console.log('    /undo              Undo last change');\n    console.log('    /validate          Blind AI code review of recent changes');\n    console.log('    /test-first <task> TDD: tests -> implement -> validate');\n    console.log('    /image <path>      Attach image for next task (multimodal)\\n');\n\n  console.log(chalk.magenta.bold('  \uD83C\uDF9B\uFE0F  Model & Engine:'));\n  console.log('    /stack             Show full L1/L2/L3 model stack');\n  console.log('    /stack <model>     Quick-set L1 chat model');\n  console.log('    /stack l1|l2|l3 <name>  Set model per tier');\n  console.log('    /stack bench       Benchmark & pricing table');\n  console.log('    /engine <name>     Switch engine (auto|cursor|claude|gemini|codex|crew-cli)');\n  console.log('    /mode [name]       Cycle mode (manual/assist/autopilot)');\n  console.log('    Shift+Tab          Cycle REPL mode\\n');\n\n  console.log(chalk.green.bold('  \uD83E\uDDE0 Memory & LSP:'));\n  console.log('    /memory [query]    Show memory stats or recall');\n  console.log('    /tools             Show tool capability matrix by mode/path');\n  console.log('    /skills [name]     List installed skills or inspect one');\n  console.log('    /permissions       Explain current read/write/shell approval model');\n  console.log('    /lsp check [files] Run TypeScript diagnostics');\n  console.log('    /lsp complete <file> <line> <column> [prefix]  Get completions\\n');\n\n  console.log(chalk.green.bold('  \uD83D\uDD0D Context & Git:'));\n  console.log('    /context           Show context size estimate');\n  console.log('    /git               Show current git status');\n  console.log('    /repos             Show sibling repos (cross-repo)\\n');\n\n  console.log(chalk.red.bold('  \uD83D\uDEAA Exit:'));\n  console.log('    /exit, /quit       Exit REPL (or press Ctrl+C)\\n');\n\n  console.log(chalk.gray('  \uD83D\uDCA1 Tip: Type any coding task to get started. Simple chats respond'));\n  console.log(chalk.gray('      instantly, code changes route to specialist agents automatically.\\n'));\n  if (uiMode === 'tui') {\n    console.log(chalk.gray('  TUI mode uses the same runtime/controller as REPL with a denser terminal layout.\\n'));\n  }\n}\n\nfunction modeBehavior(mode: ReplMode) {\n  if (mode === 'manual') {\n    return {\n      memoryInject: false,\n      executionConfirm: false,\n      autoApply: false,\n      autopilotPipeline: false\n    };\n  }\n  if (mode === 'assist') {\n    return {\n      memoryInject: true,\n      executionConfirm: true,\n      autoApply: false,\n      autopilotPipeline: false\n    };\n  }\n  return {\n    memoryInject: true,\n    executionConfirm: false,\n    autoApply: true,\n    autopilotPipeline: true\n  };\n}\n\nfunction applySlashAlias(input: string, aliases: Record<string, string>): string {\n  if (!input.startsWith('/')) return input;\n  const [cmd, ...rest] = input.split(/\\s+/);\n  const replacement = aliases[cmd];\n  if (!replacement) return input;\n  const normalized = replacement.startsWith('/') ? replacement : `/${replacement}`;\n  return [normalized, ...rest].join(' ').trim();\n}\n\nasync function renderBannerAnimated(banner: string): Promise<void> {\n  const lines = banner.split('\\n');\n  for (const line of lines) {\n    process.stdout.write(`${chalk.cyan(line)}\\n`);\n    await new Promise(resolve => setTimeout(resolve, 10));\n  }\n}\n\nfunction nextMode(current: ReplMode): ReplMode {\n  const idx = REPL_MODE_ORDER.indexOf(current);\n  if (idx < 0 || idx === REPL_MODE_ORDER.length - 1) return REPL_MODE_ORDER[0];\n  return REPL_MODE_ORDER[idx + 1];\n}\n\nfunction buildPrompt(state: ReplState, isProcessing: boolean, uiMode: 'repl' | 'tui' = 'repl'): string {\n  const prefix = uiMode === 'tui' ? 'crew-tui' : 'crew';\n  const mode = state.mode;\n  if (isProcessing) return chalk.gray(`${prefix}(${mode},busy)> `);\n  if (mode === 'autopilot') return chalk.magenta(`${prefix}(${mode})> `);\n  if (mode === 'assist') return chalk.cyan(`${prefix}(${mode})> `);\n  return chalk.green(`${prefix}(${mode})> `);\n}\n\nfunction normalizeStandaloneEngine(engine: string): string {\n  const raw = String(engine || '').trim().toLowerCase();\n  if (!raw || raw === 'auto') return 'auto';\n  if (raw === 'claude' || raw === 'claude-code') return 'claude-cli';\n  if (raw === 'gemini' || raw === 'gemini-api') return 'gemini-cli';\n  if (raw === 'codex') return 'codex-cli';\n  if (raw === 'cursor') return 'cursor-cli';\n  return raw;\n}\n\nfunction printTuiScaffold() {\n  console.log(chalk.blue('\\n\u250C\u2500[ TUI LAYOUT ]\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510'));\n  console.log(chalk.white('\u2502 Chat + Commands share the same runtime as REPL (no orchestration fork). \u2502'));\n  console.log(chalk.white('\u2502 Panels: status/banner at top, responses inline, sandbox + cost summaries.\u2502'));\n  console.log(chalk.white('\u2502 Keys: Shift+Tab mode cycle, /help commands, /preview /apply /trace.      \u2502'));\n  console.log(chalk.blue('\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n'));\n}\n\nexport async function startRepl(options: ReplOptions): Promise<void> {\n  const { router, orchestrator, sandbox, session, logger } = options;\n  const projectDir = options.projectDir || process.cwd();\n  const repoConfig = options.repoConfig;\n  const uiMode: 'repl' | 'tui' = options.uiMode || 'repl';\n  const keeper = new AgentKeeper(projectDir);\n  const memoryBroker = new MemoryBroker(projectDir);\n  const checkpoints = new CheckpointStore(projectDir);\n  const sessionId = await session.getSessionId();\n  const replRunId = `repl-${randomUUID()}`;\n\n  // Interactive mode selection if not provided via CLI or config\n  let selectedMode: ReplMode = (options.initialMode || repoConfig?.repl?.mode || 'manual') as ReplMode;\n  \n  if (!options.initialMode && !repoConfig?.repl?.mode && process.stdin.isTTY) {\n    try {\n      console.log(''); // Clear line after init output\n      const inquirer = await getInquirer();\n      const modeAnswer = await inquirer.prompt([\n        {\n          type: 'list',\n          name: 'mode',\n          message: 'Select REPL mode:',\n          choices: [\n            {\n              name: 'manual - Requires approval for all changes (safest)',\n              value: 'manual',\n              short: 'manual'\n            },\n            {\n              name: 'assist - Memory-enhanced assistance',\n              value: 'assist',\n              short: 'assist'\n            },\n            {\n              name: 'autopilot - Full autonomous mode (auto-apply changes)',\n              value: 'autopilot',\n              short: 'autopilot'\n            }\n          ],\n          default: 'manual',\n          loop: false\n        }\n      ]);\n      selectedMode = modeAnswer.mode as ReplMode;\n    } catch (err) {\n      // User cancelled or inquirer unavailable \u2014 use manual\n      console.error('[repl] Mode picker failed, using manual:', (err as Error).message);\n      selectedMode = 'manual';\n    }\n  }\n\n  const envInterfaceMode = String(process.env.CREW_INTERFACE_MODE || '').toLowerCase();\n  const repoDefaultInterface: 'connected' | 'standalone' =\n    Boolean((repoConfig?.repl as Record<string, unknown> | undefined)?.useGateway) ? 'connected' : 'standalone';\n  let selectedInterfaceMode: 'connected' | 'standalone' =\n    options.initialInterfaceMode\n    || (envInterfaceMode === 'connected' ? 'connected' : envInterfaceMode === 'standalone' ? 'standalone' : repoDefaultInterface);\n\n  if (options.promptInterfaceMode && process.stdin.isTTY) {\n    try {\n      const inquirer2 = await getInquirer();\n      const ifaceAnswer = await inquirer2.prompt([\n        {\n          type: 'list',\n          name: 'interfaceMode',\n          message: 'Select interface mode:',\n          choices: [\n            {\n              name: 'standalone - Local unified pipeline (no gateway required)',\n              value: 'standalone',\n              short: 'standalone'\n            },\n            {\n              name: 'connected - Route via crew-lead/gateway specialists',\n              value: 'connected',\n              short: 'connected'\n            }\n          ],\n          default: selectedInterfaceMode,\n          loop: false\n        }\n      ]);\n      selectedInterfaceMode = ifaceAnswer.interfaceMode as 'connected' | 'standalone';\n    } catch {\n      // Keep selectedInterfaceMode fallback.\n    }\n  }\n  process.env.CREW_INTERFACE_MODE = selectedInterfaceMode;\n\n  const defaultReplModel = resolveConfiguredReplModel(repoConfig);\n\n  const replState: ReplState = {\n    model: defaultReplModel,\n    engine: String(repoConfig?.repl?.engine || 'auto'),\n    autoApply: Boolean(repoConfig?.repl?.autoApply),\n    memoryMax: Number(repoConfig?.repl?.memoryMax ?? 5),\n    mode: selectedMode,\n    verbose: Boolean((repoConfig?.repl as Record<string, unknown> | undefined)?.verbose || false),\n    routerProvider: String((repoConfig?.repl as Record<string, unknown> | undefined)?.routerProvider || 'grok'),\n    executorProvider: String((repoConfig?.repl as Record<string, unknown> | undefined)?.executorProvider || 'grok'),\n    useGateway: selectedInterfaceMode === 'connected'\n  };\n  // Enforce deterministic mode defaults on startup.\n  if (replState.mode === 'manual') replState.autoApply = false;\n  if (replState.mode === 'autopilot') replState.autoApply = true;\n  const slashAliases = repoConfig?.slashAliases || {};\n  const bannerEnabled = repoConfig?.repl?.bannerEnabled !== false;\n  const bannerAnimated = repoConfig?.repl?.animatedBanner !== false;\n  const bannerFirstLaunchOnly = repoConfig?.repl?.bannerFirstLaunchOnly === true; // Changed default to false\n  const bannerSeenFile = join(projectDir, '.crew', 'repl-banner-seen');\n  const replAuditPath = join(projectDir, '.crew', 'repl-events.jsonl');\n  const shouldRenderBanner = bannerEnabled && (!bannerFirstLaunchOnly || !existsSync(bannerSeenFile));\n  let auditSeq = 0;\n  let checkpointEnabled = true;\n\n  // Warn if running from home directory (too broad, will be slow)\n  if (projectDir === homedir()) {\n    console.log(chalk.yellow('\\n  \u26A0 Running from home directory (~). For best results, cd into a project folder first.\\n'));\n  }\n\n  // Lazy-load repo bootstrap (don't block cold start)\n  let repoBootstrap: RepoBootstrap = { projectDir, topEntries: [], docs: [], keyFiles: [], readmeSummary: '' };\n  const repoBootstrapPromise = buildRepoBootstrap(projectDir).then(b => { repoBootstrap = b; }).catch(() => {});\n\n  // Pre-warm LLM provider connections (fire-and-forget, reduces first-request latency)\n  const preWarmProviders = () => {\n    const endpoints = [\n      { key: 'GEMINI_API_KEY', url: 'https://generativelanguage.googleapis.com' },\n      { key: 'OPENAI_API_KEY', url: 'https://api.openai.com' },\n      { key: 'XAI_API_KEY', url: 'https://api.x.ai' },\n      { key: 'GROQ_API_KEY', url: 'https://api.groq.com' },\n    ];\n    for (const ep of endpoints) {\n      if (process.env[ep.key]) {\n        fetch(ep.url, { method: 'HEAD', signal: AbortSignal.timeout(2000) }).catch(() => {});\n        break; // Only pre-warm the first available provider\n      }\n    }\n  };\n  preWarmProviders();\n\n  // Render banner FIRST, before anything else\n  if (shouldRenderBanner) {\n    if (bannerAnimated) {\n      await renderBannerAnimated(BANNER);\n    } else {\n      console.log(chalk.cyan(BANNER));\n    }\n    try {\n      await mkdir(join(projectDir, '.crew'), { recursive: true });\n      await writeFile(bannerSeenFile, new Date().toISOString(), 'utf8');\n    } catch {\n      // Best-effort marker write.\n    }\n  }\n\n  // Wait for repo bootstrap before showing status (but it started earlier)\n  await repoBootstrapPromise;\n\n  // Show dynamic status dashboard on REPL startup\n  try {\n    const { displayStatus } = await import('../status/dashboard.js');\n    await displayStatus({ interfaceMode: selectedInterfaceMode });\n  } catch (err) {\n    // Silently fail if status dashboard can't be shown\n  }\n\n  let isProcessing = false;\n  let isClosing = false;\n  let isCommandProcessing = false;\n  let pendingExit = false;\n\n  const recordReplEvent = async (type: string, payload: Record<string, unknown>) => {\n    auditSeq += 1;\n    const event = {\n      ts: new Date().toISOString(),\n      seq: auditSeq,\n      runId: replRunId,\n      sessionId,\n      type,\n      ...payload\n    };\n    try {\n      await session.appendHistory({\n        type: `repl_${type}`,\n        runId: replRunId,\n        seq: auditSeq,\n        ...payload\n      });\n      if (checkpointEnabled) {\n        await checkpoints.append(replRunId, `repl.${type}`, {\n          sessionId,\n          seq: auditSeq,\n          ...payload\n        });\n      }\n      await mkdir(join(projectDir, '.crew'), { recursive: true });\n      await appendFile(replAuditPath, `${JSON.stringify(event)}\\n`, 'utf8');\n    } catch {\n      // Best-effort audit side channel.\n    }\n  };\n  try {\n    await checkpoints.beginRun({\n      runId: replRunId,\n      mode: 'repl',\n      task: `Interactive REPL session (${projectDir})`\n    });\n  } catch {\n    checkpointEnabled = false;\n  }\n  await recordReplEvent('session_started', {\n    mode: replState.mode,\n    model: replState.model,\n    engine: replState.engine\n  });\n\n  console.log(chalk.gray(`  Project: ${chalk.white(projectDir)}`));\n  console.log(chalk.gray(`  Session: ${chalk.white(sessionId)}`));\n  console.log(chalk.gray(`  Model: ${chalk.green(replState.model)}  Engine: ${chalk.blue(replState.engine)}  Mode: ${chalk.magenta(replState.mode)}`));\n  console.log();\n  if (uiMode === 'tui') {\n    printTuiScaffold();\n  }\n  console.log(chalk.gray(`  Type ${chalk.cyan('/help')} for full command list or start chatting!\\n`));\n  if (repoBootstrap.topEntries.length > 0) {\n    console.log(chalk.gray(`  Repo indexed: ${repoBootstrap.topEntries.length} top entries, ${repoBootstrap.docs.length} docs, ${repoBootstrap.keyFiles.length} key files.`));\n    console.log(chalk.gray(`  Try ${chalk.cyan('/system')} for stack summary.\\n`));\n  }\n\n  // Tab completion for commands and file paths\n  const SLASH_COMMANDS = [\n    ...getSlashCommands(),\n    '/quit', '/auto-apply', '/verbose', '/checkpoint', '/audit', '/validate', '/test', '/commit'\n  ];\n\n  const tabCompleter = (line: string): [string[], string] => {\n    const trimmed = line.trim();\n\n    // Complete slash commands\n    if (trimmed.startsWith('/')) {\n      const matches = SLASH_COMMANDS.filter(c => c.startsWith(trimmed));\n      return [matches.length > 0 ? matches : SLASH_COMMANDS, trimmed];\n    }\n\n    // Complete file paths (best-effort, sync)\n    if (trimmed.includes('/') || trimmed.includes('.')) {\n      try {\n        const { readdirSync, statSync } = require('fs');\n        const { dirname, basename } = require('path');\n        const partial = trimmed.split(/\\s+/).pop() || '';\n        const dir = partial.includes('/') ? join(projectDir, dirname(partial)) : projectDir;\n        const prefix = partial.includes('/') ? basename(partial) : partial;\n        interface DirEnt { name: string; isDirectory(): boolean }\n        const entries = (readdirSync(dir, { withFileTypes: true }) as DirEnt[])\n          .filter((e) => e.name.startsWith(prefix) && !e.name.startsWith('.'))\n          .slice(0, 20)\n          .map((e) => {\n            const full = partial.includes('/') ? dirname(partial) + '/' + e.name : e.name;\n            return e.isDirectory() ? full + '/' : full;\n          });\n        if (entries.length > 0) return [entries, partial];\n      } catch {\n        // Fall through \u2014 no completions available\n      }\n    }\n\n    return [[], trimmed];\n  };\n\n  const rl = createInterface({\n    input: process.stdin,\n    output: process.stdout,\n    prompt: buildPrompt(replState, isProcessing, uiMode),\n    terminal: true,\n    completer: tabCompleter\n  });\n\n  // \u2500\u2500\u2500 Inline ghost-text suggestions (Fish/zsh-style) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  let ghostText = '';\n\n  const clearGhost = () => {\n    if (!ghostText) return;\n    // Erase the ghost characters, then move cursor back\n    process.stdout.write('\\x1b[0m');  // reset color\n    process.stdout.write(`\\x1b[${ghostText.length}D`); // move left to cursor pos\n    process.stdout.write(`\\x1b[0K`); // clear from cursor to end of line\n    // Actually: the ghost is AFTER cursor, so just clear to EOL from current pos\n    ghostText = '';\n  };\n\n  // readline.Interface exposes `.line` and `.cursor` as internal properties\n  // not in the public type \u2014 cast once via an interface extension\n  const rlInternal = rl as ReadlineInterface & { line: string; cursor: number };\n\n  const renderGhost = () => {\n    const line = rlInternal.line;\n    if (!line || !line.startsWith('/') || line.includes(' ')) {\n      if (ghostText) clearGhost();\n      return;\n    }\n    const match = SLASH_COMMANDS.find(c => c.startsWith(line) && c !== line);\n    const suffix = match ? match.slice(line.length) : '';\n    if (suffix === ghostText) return; // no change\n    // Clear old ghost, write new one\n    if (ghostText) {\n      process.stdout.write(`\\x1b[0K`); // clear to end of line\n    }\n    if (suffix) {\n      process.stdout.write(`\\x1b[90m${suffix}\\x1b[0m`); // gray text\n      process.stdout.write(`\\x1b[${suffix.length}D`);    // move cursor back\n    }\n    ghostText = suffix;\n  };\n\n  const keypressListener = (_str: string, key: { name?: string; shift?: boolean; sequence?: string; ctrl?: boolean }) => {\n    // Shift+Tab: cycle modes\n    const isShiftTab = (key.name === 'tab' && key.shift) || key.sequence === '\\u001b[Z';\n    if (isShiftTab) {\n      clearGhost();\n      const from = replState.mode;\n      replState.mode = nextMode(replState.mode);\n      rl.setPrompt(buildPrompt(replState, isProcessing, uiMode));\n      void recordReplEvent('mode_change', { from, to: replState.mode, source: 'keybinding' });\n      console.log(chalk.magenta(`\\n  \u21BB Mode: ${replState.mode}`));\n      rl.prompt();\n      return;\n    }\n\n    // Right arrow: accept ghost suggestion\n    if (key.name === 'right' && ghostText) {\n      const line = rlInternal.line;\n      const accepted = line + ghostText;\n      rlInternal.line = accepted;\n      rlInternal.cursor = accepted.length;\n      process.stdout.write(`\\x1b[0K`); // clear ghost\n      process.stdout.write(ghostText);  // write as real text\n      ghostText = '';\n      return;\n    }\n\n    // After any other keypress, schedule ghost render on next tick\n    // (readline updates .line after keypress fires)\n    setImmediate(renderGhost);\n  };\n  if (process.stdin.isTTY) {\n    emitKeypressEvents(process.stdin, rl);\n    process.stdin.on('keypress', keypressListener as (...args: unknown[]) => void);\n  }\n  const refreshPrompt = () => rl.setPrompt(buildPrompt(replState, isProcessing, uiMode));\n  const confirmInline = async (message: string, defaultYes = true): Promise<boolean> => {\n    const suffix = defaultYes ? ' [Y/n] ' : ' [y/N] ';\n    return await new Promise(resolve => {\n      rl.question(`${message}${suffix}`, (answer) => {\n        const normalized = String(answer || '').trim().toLowerCase();\n        if (!normalized) {\n          resolve(defaultYes);\n          return;\n        }\n        resolve(normalized === 'y' || normalized === 'yes');\n      });\n    });\n  };\n\n  // Show initial prompt\n  rl.prompt();\n\n  // Pending images for multimodal (attached via /image, consumed on next task)\n  const pendingImages: string[] = [];\n\n  const handleSlashCommand = async (rawInput: string): Promise<boolean> => {\n    const trimmed = applySlashAlias(rawInput.trim(), slashAliases);\n    if (!trimmed.startsWith('/')) return false;\n    let [command, ...args] = trimmed.split(/\\s+/);\n\n    if (trimmed === '/') {\n      printSlashCommandMenu();\n      return true;\n    }\n\n    if (!SLASH_COMMANDS.includes(command)) {\n      const matches = SLASH_COMMANDS.filter((item) => item.startsWith(command));\n      if (matches.length > 0) {\n        printSlashCommandMenu(command);\n        return true;\n      }\n      console.log(chalk.red(`\\n  \u2717 Unknown command \"${command}\"`));\n      console.log(chalk.gray('  Type / for command suggestions or /help for full help.\\n'));\n      return true;\n    }\n\n    if (command === '/exit' || command === '/quit') {\n      console.log(chalk.cyan('\\n  \uD83D\uDC4B Goodbye! Session saved to .crew/\\n'));\n      isClosing = true;\n      rl.close();\n      return true;\n    }\n\n    if (command === '/help') {\n      printHelp(uiMode);\n      return true;\n    }\n\n    if (command === '/info') {\n      const summary = buildModelSummary(projectDir, replState);\n      const configuredCliEngine = String(repoConfig?.cli?.engine || '(not set)');\n      const configuredReplEngine = String(repoConfig?.repl?.engine || '(not set)');\n      const preferredEngines = Array.isArray(repoConfig?.cli?.preferredEngines)\n        ? repoConfig.cli.preferredEngines.map((x: unknown) => String(x)).filter(Boolean)\n        : [];\n      const chatModel = String(process.env.CREW_CHAT_MODEL || '(env not set)');\n      const routerModel = String(process.env.CREW_ROUTER_MODEL || '(env not set)');\n      const reasoningModel = String(process.env.CREW_REASONING_MODEL || '(env not set)');\n      const l2aModel = String(process.env.CREW_L2A_MODEL || '(env not set)');\n      const l2bModel = String(process.env.CREW_L2B_MODEL || '(env not set)');\n      const qaModel = String(process.env.CREW_QA_MODEL || '(env not set)');\n      const l1Model = String(process.env.CREW_L1_MODEL || '(env not set)');\n      const l3Model = String(process.env.CREW_L3_MODEL || '(env not set)');\n      const l3ReviewModel = String(process.env.CREW_L3_REVIEW_MODEL || '(env not set)');\n      const l3FixerModel = String(process.env.CREW_L3_FIXER_MODEL || '(env not set)');\n      const extraValidators = String(process.env.CREW_L2_EXTRA_VALIDATORS || '(env not set)');\n      const executionModel = String(process.env.CREW_EXECUTION_MODEL || '(env not set)');\n      const maxParallelWorkers = String(process.env.CREW_MAX_PARALLEL_WORKERS || '(env not set)');\n\n      console.log(chalk.blue('\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n      console.log(chalk.blue('\u2551                    CURRENT SETTINGS                          \u2551'));\n      console.log(chalk.blue('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n'));\n      console.log(chalk.cyan('  Engine Routing (dispatch/runtime):'));\n      console.log(`    Active REPL engine: ${chalk.blue(replState.engine)}`);\n      console.log(`    Config default (repl.engine): ${chalk.blue(configuredReplEngine)}`);\n      console.log(`    Config default (cli.engine) : ${chalk.blue(configuredCliEngine)}`);\n      console.log(`    Preferred engines           : ${preferredEngines.length ? preferredEngines.join(' -> ') : chalk.gray('(none configured)')}\\n`);\n\n      console.log(chalk.cyan('  Tier Stack (model/providers):'));\n      console.log(`    Tier 1 provider (Router)  : ${chalk.green(replState.routerProvider)}`);\n      console.log(`    Tier 2 provider (Executor): ${chalk.green(replState.executorProvider)}`);\n      console.log(`    Tier 3 gateway            : ${replState.useGateway ? chalk.green('ENABLED') : chalk.gray('disabled')}`);\n      console.log(`    CREW_CHAT_MODEL           : ${chatModel}`);\n      console.log(`    CREW_L1_MODEL             : ${l1Model}`);\n      console.log(`    CREW_ROUTER_MODEL         : ${routerModel}`);\n      console.log(`    CREW_REASONING_MODEL      : ${reasoningModel}`);\n      console.log(`    CREW_L2A_MODEL            : ${l2aModel}`);\n      console.log(`    CREW_L2B_MODEL            : ${l2bModel}`);\n      console.log(`    CREW_QA_MODEL             : ${qaModel}`);\n      console.log(`    CREW_L3_MODEL             : ${l3Model}`);\n      console.log(`    CREW_L3_REVIEW_MODEL      : ${l3ReviewModel}`);\n      console.log(`    CREW_L3_FIXER_MODEL       : ${l3FixerModel}`);\n      console.log(`    CREW_L2_EXTRA_VALIDATORS  : ${extraValidators}`);\n      console.log(`    CREW_EXECUTION_MODEL      : ${executionModel}`);\n      console.log(`    CREW_MAX_PARALLEL_WORKERS : ${maxParallelWorkers}`);\n      console.log(`    Policy-tier models        : ${summary.policyTierModels.length ? summary.policyTierModels.join(', ') : chalk.gray('(none set)')}\\n`);\n\n      console.log(chalk.cyan('  Session:'));\n      console.log(`    Model: ${chalk.green(replState.model)}`);\n      console.log(`    Engine: ${chalk.blue(replState.engine)}`);\n      console.log(`    Mode: ${chalk.magenta(replState.mode)}`);\n      const behavior = modeBehavior(replState.mode);\n      console.log(`    Mode behavior: memoryInject=${behavior.memoryInject ? 'on' : 'off'}, executionConfirm=${behavior.executionConfirm ? 'on' : 'off'}, autoApply=${behavior.autoApply ? 'on' : 'off'}, autopilotPipeline=${behavior.autopilotPipeline ? 'on' : 'off'}`);\n      console.log(`    Auto-apply: ${replState.autoApply ? chalk.green('ON') : chalk.gray('off')}`);\n      console.log(`    Verbose: ${replState.verbose ? chalk.green('ON') : chalk.gray('off')}`);\n      console.log(`    Memory max: ${replState.memoryMax}`);\n      console.log(`    Project: ${chalk.gray(projectDir)}\\n`);\n      return true;\n    }\n\n    if (command === '/system') {\n      const summary = buildModelSummary(projectDir, replState);\n      printSystemSummary(summary, repoBootstrap);\n      return true;\n    }\n\n    if (command === '/mode-info') {\n      console.log(chalk.blue('\\n--- REPL Mode Semantics ---\\n'));\n      console.log('  manual');\n      console.log('    - Chat + dispatch normally');\n      console.log('    - No memory context injection');\n      console.log('    - No execute confirmation prompt');\n      console.log('    - No auto-apply');\n      console.log('  assist');\n      console.log('    - Memory/RAG context injection enabled');\n      console.log('    - Confirm before non-chat execution');\n      console.log('    - No auto-apply');\n      console.log('  autopilot');\n      console.log('    - Memory/RAG context injection enabled');\n      console.log('    - Runs full unified pipeline in standalone mode');\n      console.log('    - Auto-apply sandbox changes by default\\n');\n      return true;\n    }\n\n    if (command === '/stack') {\n      const summary = buildModelSummary(projectDir, replState);\n      printModelSummary(summary);\n      return true;\n    }\n\n    // /models is an alias for /stack\n    if (command === '/models') {\n      args.unshift(...(args.length === 0 ? ['show'] : []));\n      command = '/stack';\n      // fall through to /stack handler below\n    }\n\n    // /model is an alias for /stack (backwards compatible)\n    if (command === '/model') {\n      if (args.length === 0) {\n        args = ['show'];\n      }\n      command = '/stack';\n      // fall through to /stack handler below\n    }\n\n    if (command === '/engines') {\n      const requestedEngine = (args[0] || '').trim();\n      if (requestedEngine) {\n        if (!AVAILABLE_ENGINES.includes(requestedEngine)) {\n          console.log(chalk.red(`\\n  \u2717 Unknown engine \"${requestedEngine}\". Available: ${AVAILABLE_ENGINES.join(', ')}\\n`));\n          return true;\n        }\n        replState.engine = normalizeStandaloneEngine(requestedEngine);\n        console.log(chalk.green(`\\n  \u2713 Engine set to: ${replState.engine}\\n`));\n        return true;\n      }\n      console.log(chalk.blue('\\n--- Available Engines ---\\n'));\n      for (const engine of AVAILABLE_ENGINES) {\n        const current = engine === replState.engine ? chalk.green(' (current)') : '';\n        console.log(`  ${engine}${current}`);\n      }\n      console.log(chalk.gray('\\n  Use /engine <name> or /engines <name> to switch.\\n'));\n      return true;\n    }\n\n    if (command === '/engine') {\n      const engineName = args[0] || '';\n      if (!engineName) {\n        console.log(chalk.red('\\n  \u2717 Provide an engine name. Type /engines to see options.\\n'));\n      } else if (!AVAILABLE_ENGINES.includes(engineName)) {\n        console.log(chalk.red(`\\n  \u2717 Unknown engine \"${engineName}\". Type /engines to see options.\\n`));\n      } else {\n        replState.engine = normalizeStandaloneEngine(engineName);\n        console.log(chalk.green(`\\n  \u2713 Engine set to: ${replState.engine}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/auto-apply') {\n      replState.autoApply = !replState.autoApply;\n      await recordReplEvent('autopilot_toggle', {\n        enabled: replState.autoApply,\n        source: 'slash'\n      });\n      console.log(chalk.yellow(`\\n  \u2713 Auto-apply: ${replState.autoApply ? chalk.green('ON') : chalk.gray('off')}\\n`));\n      return true;\n    }\n\n    if (command === '/verbose') {\n      replState.verbose = !replState.verbose;\n      console.log(chalk.yellow(`\\n  \u2713 Verbose mode: ${replState.verbose ? chalk.green('ON') : chalk.gray('off')}\\n`));\n      return true;\n    }\n\n    if (command === '/stack') {\n      const subcommand = (args[0] || 'show').trim().toLowerCase();\n      const stackValue = args.slice(1).join(' ').trim();\n\n      // Short tier setters: /stack l1|l2|l3|qa|fixer|review <model>\n      const tierShortcuts: Record<string, { env: string; label: string; replKey?: keyof ReplState }> = {\n        'l1':      { env: 'CREW_L1_MODEL', label: 'L1 (chat)', replKey: 'model' },\n        'l2':      { env: 'CREW_REASONING_MODEL', label: 'L2 (reasoning)' },\n        'l2a':     { env: 'CREW_L2A_MODEL', label: 'L2A (decomposer)' },\n        'l2b':     { env: 'CREW_L2B_MODEL', label: 'L2B (validator)' },\n        'l3':      { env: 'CREW_L3_MODEL', label: 'L3 (worker)' },\n        'qa':      { env: 'CREW_QA_MODEL', label: 'L3 QA' },\n        'fixer':   { env: 'CREW_L3_FIXER_MODEL', label: 'L3 Fixer' },\n        'review':  { env: 'CREW_L3_REVIEW_MODEL', label: 'L3 Review' },\n      };\n\n      if (tierShortcuts[subcommand] && stackValue) {\n        const tier = tierShortcuts[subcommand];\n        process.env[tier.env] = stackValue;\n        if (tier.replKey) (replState[tier.replKey] as string) = stackValue;\n        console.log(chalk.green(`\\n  \u2713 ${tier.label} model set to: ${stackValue}\\n`));\n        return true;\n      }\n\n      // Long env-style setters: /stack l1-model|router-model|... <value>\n      const stackFieldMap: Record<string, string> = {\n        'l1-model': 'CREW_L1_MODEL',\n        'router-model': 'CREW_ROUTER_MODEL',\n        'reasoning-model': 'CREW_REASONING_MODEL',\n        'l2a-model': 'CREW_L2A_MODEL',\n        'l2b-model': 'CREW_L2B_MODEL',\n        'qa-model': 'CREW_QA_MODEL',\n        'l3-model': 'CREW_L3_MODEL',\n        'l3-review-model': 'CREW_L3_REVIEW_MODEL',\n        'l3-fixer-model': 'CREW_L3_FIXER_MODEL',\n        'extra-validators': 'CREW_L2_EXTRA_VALIDATORS',\n        'max-parallel-workers': 'CREW_MAX_PARALLEL_WORKERS'\n      };\n\n      // /stack <modelname> \u2014 quick L1 setter (if not a known subcommand)\n      if (subcommand !== 'show' && !tierShortcuts[subcommand] && !stackFieldMap[subcommand]\n          && subcommand !== 'router' && subcommand !== 'executor' && subcommand !== 'gateway'\n          && subcommand !== 'bench') {\n        replState.model = subcommand;\n        process.env.CREW_L1_MODEL = subcommand;\n        try {\n          const { findModelInfo } = await import('./model-info.js');\n          const info = findModelInfo(subcommand);\n          if (info) {\n            console.log(chalk.green(`\\n  \u2713 L1 model: ${info.name} (${info.provider})`));\n            console.log(chalk.gray(`    Score: ${info.codingScore} | Cost: $${info.inputCost}/$${info.outputCost}/M | Context: ${info.contextWindow}${info.note ? ` | ${info.note}` : ''}\\n`));\n          } else {\n            console.log(chalk.green(`\\n  \u2713 L1 model set to: ${subcommand}\\n`));\n          }\n        } catch {\n          console.log(chalk.green(`\\n  \u2713 L1 model set to: ${subcommand}\\n`));\n        }\n        return true;\n      }\n\n      // /stack bench \u2014 benchmark table\n      if (subcommand === 'bench') {\n        try {\n          const { MODEL_CATALOG, formatModelTable, findModelInfo } = await import('./model-info.js');\n          const current = findModelInfo(replState.model);\n          console.log(chalk.blue('\\n  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n          console.log(chalk.blue('  \u2551                        MODEL BENCHMARK & PRICING                            \u2551'));\n          console.log(chalk.blue('  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n'));\n          console.log(chalk.gray('  Scores from OpenRouter coding benchmark (March 2026)\\n'));\n          console.log(chalk.cyan('  Heavy Tier (L2 Brain):'));\n          console.log(formatModelTable(MODEL_CATALOG.filter((m) => m.tier === 'heavy')));\n          console.log(chalk.cyan('\\n  Standard Tier (L3 Workers):'));\n          console.log(formatModelTable(MODEL_CATALOG.filter((m) => m.tier === 'standard')));\n          console.log(chalk.cyan('\\n  Fast Tier (L1 Routing):'));\n          console.log(formatModelTable(MODEL_CATALOG.filter((m) => m.tier === 'fast')));\n          if (current) {\n            console.log(chalk.green(`\\n  Current: ${current.name} (${current.provider}) \u2014 score ${current.codingScore}, $${current.inputCost}/$${current.outputCost}/M`));\n          } else {\n            console.log(chalk.yellow(`\\n  Current: ${replState.model} (not in catalog)`));\n          }\n          console.log(chalk.gray(`\\n  Usage: /stack <model>  \u2014 e.g. /stack gpt-5.4\\n`));\n        } catch {\n          console.log(chalk.red('\\n  \u2717 Could not load model catalog.\\n'));\n        }\n        return true;\n      }\n\n      if (subcommand === 'show') {\n        console.log(chalk.blue('\\n--- Stack ---\\n'));\n\n        console.log(chalk.cyan('  L1 (chat):'));\n        console.log(`    Model  : ${replState.model}${process.env.CREW_L1_MODEL ? ` (env: ${process.env.CREW_L1_MODEL})` : ''}`);\n        console.log(`    Engine : ${replState.engine}`);\n\n        console.log(chalk.cyan('\\n  L2 (reasoning/planning):'));\n        console.log(`    Router provider  : ${replState.routerProvider}`);\n        console.log(`    Executor provider: ${replState.executorProvider}`);\n        console.log(`    Reasoning model  : ${process.env.CREW_REASONING_MODEL || chalk.gray('(unset \u2014 uses L1)')}`);\n        console.log(`    L2A (decomposer) : ${process.env.CREW_L2A_MODEL || chalk.gray('(unset)')}`);\n        console.log(`    L2B (validator)  : ${process.env.CREW_L2B_MODEL || chalk.gray('(unset)')}`);\n        console.log(`    Router model     : ${process.env.CREW_ROUTER_MODEL || chalk.gray('(unset)')}`);\n\n        console.log(chalk.cyan('\\n  L3 (workers):'));\n        console.log(`    Gateway          : ${replState.useGateway ? 'enabled' : 'disabled'}`);\n        console.log(`    Worker model     : ${process.env.CREW_L3_MODEL || chalk.gray('(unset \u2014 uses L1)')}`);\n        console.log(`    QA model         : ${process.env.CREW_QA_MODEL || chalk.gray('(unset)')}`);\n        console.log(`    Fixer model      : ${process.env.CREW_L3_FIXER_MODEL || chalk.gray('(unset)')}`);\n        console.log(`    Review model     : ${process.env.CREW_L3_REVIEW_MODEL || chalk.gray('(unset)')}`);\n        console.log(`    Max parallel     : ${process.env.CREW_MAX_PARALLEL_WORKERS || chalk.gray('(unset)')}`);\n\n        console.log(chalk.gray('\\n  Set models:'));\n        console.log(chalk.gray('    /stack l1 <model>       /stack l2 <model>       /stack l3 <model>'));\n        console.log(chalk.gray('    /stack qa <model>       /stack fixer <model>    /stack review <model>'));\n        console.log(chalk.gray('    /stack <model>          \u2014 quick L1 set'));\n        console.log(chalk.gray('    /stack bench            \u2014 benchmark & pricing table'));\n        console.log(chalk.gray('  Set providers:'));\n        console.log(chalk.gray('    /stack router <grok|gemini|deepseek>'));\n        console.log(chalk.gray('    /stack executor <grok|gemini|deepseek>'));\n        console.log(chalk.gray('    /stack gateway <on|off>\\n'));\n        return true;\n      }\n\n      if (subcommand === 'router' || subcommand === 'executor') {\n        if (!['grok', 'gemini', 'deepseek'].includes(stackValue)) {\n          console.log(chalk.red(`\\n  \u2717 ${subcommand} must be one of: grok, gemini, deepseek\\n`));\n          return true;\n        }\n        if (subcommand === 'router') replState.routerProvider = stackValue;\n        if (subcommand === 'executor') replState.executorProvider = stackValue;\n        process.env.CREW_ROUTING_ORDER = `${replState.routerProvider},${replState.executorProvider}`;\n        console.log(chalk.green(`\\n  \u2713 Stack ${subcommand} set to: ${stackValue}\\n`));\n        return true;\n      }\n\n      if (subcommand === 'gateway') {\n        if (!['on', 'off', 'true', 'false', '1', '0'].includes(stackValue)) {\n          console.log(chalk.red('\\n  \u2717 gateway must be one of: on, off, true, false, 1, 0\\n'));\n          return true;\n        }\n        replState.useGateway = ['on', 'true', '1'].includes(stackValue);\n        console.log(chalk.green(`\\n  \u2713 Stack gateway: ${replState.useGateway ? 'ENABLED' : 'DISABLED'}\\n`));\n        return true;\n      }\n\n      if (stackFieldMap[subcommand]) {\n        const envKey = stackFieldMap[subcommand];\n        if (!stackValue) {\n          console.log(chalk.red(`\\n  \u2717 Provide a value for ${subcommand}.\\n`));\n          return true;\n        }\n        if (envKey === 'CREW_MAX_PARALLEL_WORKERS') {\n          const n = Number.parseInt(stackValue, 10);\n          if (!Number.isFinite(n) || n < 1 || n > 32) {\n            console.log(chalk.red('\\n  \u2717 max-parallel-workers must be a number between 1 and 32.\\n'));\n            return true;\n          }\n          process.env[envKey] = String(n);\n        } else {\n          process.env[envKey] = stackValue;\n        }\n        console.log(chalk.green(`\\n  \u2713 ${envKey} set for this session.\\n`));\n        return true;\n      }\n\n      console.log(chalk.red(`\\n  \u2717 Unknown /stack subcommand \"${subcommand}\". Use /stack show for options.\\n`));\n      return true;\n    }\n\n    if (command === '/verbose') {\n      replState.verbose = !replState.verbose;\n      console.log(chalk.yellow(`\\n  \u2713 Verbose routing: ${replState.verbose ? chalk.green('ON') : chalk.gray('off')}\\n`));\n      return true;\n    }\n\n    if (command === '/mode') {\n      const requested = (args[0] || '').trim().toLowerCase();\n      \n      // If no argument provided, cycle locally instead of launching an\n      // interactive picker. Inquirer and readline fight over the same TTY and\n      // can terminate the REPL session after the prompt returns.\n      if (!requested) {\n        const from = replState.mode;\n        replState.mode = nextMode(replState.mode);\n        if (replState.mode === 'manual') replState.autoApply = false;\n        if (replState.mode === 'autopilot') replState.autoApply = true;\n        rl.setPrompt(buildPrompt(replState, isProcessing, uiMode));\n        await recordReplEvent('mode_change', { from, to: replState.mode, source: 'cycle' });\n        console.log(chalk.green(`\\n  \u2713 Mode set to: ${replState.mode}\\n`));\n        console.log(chalk.gray('  Use /mode <manual|assist|autopilot> to set a specific mode.\\n'));\n        return true;\n      }\n      \n      // Argument provided, validate and set\n      if (!REPL_MODE_ORDER.includes(requested as ReplMode)) {\n        console.log(chalk.red('\\n  \u2717 Mode must be one of: manual, assist, autopilot\\n'));\n        return true;\n      }\n      const from = replState.mode;\n      replState.mode = requested as ReplMode;\n      if (replState.mode === 'manual') replState.autoApply = false;\n      if (replState.mode === 'autopilot') replState.autoApply = true;\n      rl.setPrompt(buildPrompt(replState, isProcessing, uiMode));\n      await recordReplEvent('mode_change', { from, to: replState.mode, source: 'slash' });\n      console.log(chalk.green(`\\n  \u2713 Mode set to: ${replState.mode}\\n`));\n      return true;\n    }\n\n    if (command === '/tools') {\n      const summary = buildModelSummary(projectDir, replState);\n      const mode = summary.mode;\n      const behavior = modeBehavior(replState.mode);\n      console.log(chalk.blue('\\n--- Tool Capability Matrix ---\\n'));\n      console.log(`  Interface mode: ${mode}`);\n      console.log(`  REPL mode: ${replState.mode}`);\n      console.log(`  Local sandbox edits: ${mode === 'standalone' ? 'yes' : 'staged via response parsing'}`);\n      console.log(`  Gateway agent tools: ${mode === 'connected' ? 'yes (dispatch path)' : 'no (unless explicitly connected)'}`);\n      console.log(`  Memory/RAG injection: ${behavior.memoryInject ? 'enabled' : 'disabled'}`);\n      console.log('  LSP checks/completion: enabled');\n      console.log('  PTY tooling: available via `crew exec`');\n      console.log('  Notes: actual tool usage depends on routing, permissions, and parser acceptance.\\n');\n      return true;\n    }\n\n    if (command === '/permissions') {\n      const summary = buildModelSummary(projectDir, replState);\n      const behavior = modeBehavior(replState.mode);\n      console.log(chalk.blue('\\n--- Permissions Model ---\\n'));\n      console.log(`  Interface mode: ${summary.mode}`);\n      console.log(`  REPL mode: ${replState.mode}`);\n      console.log('  Read files: yes');\n      console.log('  Stage edits in sandbox: yes');\n      console.log(`  Write to disk: ${replState.autoApply || behavior.autoApply ? 'auto-apply may occur' : 'via /apply'}`);\n      console.log('  Shell / PTY: available');\n      console.log('  Network/model calls: available');\n      console.log(`  Execution confirm: ${behavior.executionConfirm ? 'enabled' : 'disabled'}`);\n      console.log(chalk.gray('\\n  Canonical docs: docs/PERMISSIONS-MODEL.md and docs/INSTRUCTION-STACK.md\\n'));\n      return true;\n    }\n\n    if (command === '/skills') {\n      const skills = await listInstalledSkills();\n      const requested = args.join(' ').trim().toLowerCase();\n      if (skills.length === 0) {\n        console.log(chalk.yellow('\\n  No installed skills found in ~/.crewswarm/skills\\n'));\n        return true;\n      }\n      if (requested) {\n        const match = skills.find((s) => s.name.toLowerCase() === requested);\n        if (!match) {\n          console.log(chalk.red(`\\n  \u2717 Skill \"${requested}\" not found. Use /skills to list installed skills.\\n`));\n          return true;\n        }\n        console.log(chalk.blue('\\n--- Skill ---\\n'));\n        console.log(`  Name : ${match.name}`);\n        console.log(`  Type : ${match.type}`);\n        console.log(`  Path : ${match.path}`);\n        console.log(chalk.gray('\\n  API skills run via `crew skill <name>`. Knowledge skills are activated by the runtime when needed.\\n'));\n        return true;\n      }\n      console.log(chalk.blue('\\n--- Installed Skills ---\\n'));\n      for (const skill of skills) {\n        const kind = skill.type === 'knowledge' ? chalk.cyan('knowledge') : chalk.green('api');\n        console.log(`  ${skill.name} ${chalk.gray('\u00B7')} ${kind}`);\n      }\n      console.log(chalk.gray('\\n  Use /skills <name> to inspect one skill.\\n'));\n      return true;\n    }\n\n    if (command === '/status') {\n      const sess = await session.loadSession();\n      const cost = await session.loadCost();\n      const pipeline = await loadPipelineMetricsSummary(projectDir);\n      const activeBranch = sandbox.getActiveBranch();\n      const hasChanges = sandbox.hasChanges(activeBranch);\n\n      console.log(chalk.blue('\\n\u250C\u2500 Session Status'));\n      console.log(`\u2502  History: ${sess.history.length} entries`);\n      console.log(`\u2502  Cost: ${chalk.green(`$${cost.totalUsd.toFixed(4)}`)}`);\n      console.log(`\u2502  Sandbox: ${chalk.yellow(activeBranch)} ${hasChanges ? chalk.yellow('(has changes)') : chalk.gray('(clean)')}`);\n      console.log(`\u2502  Model: ${chalk.green(replState.model)}`);\n      console.log(`\u2502  Engine: ${chalk.blue(replState.engine)}`);\n      console.log(`\u2502  Mode: ${chalk.magenta(replState.mode)}`);\n      console.log(`\u2502  Pipeline runs: ${pipeline.runs} | QA approved: ${pipeline.qaApproved} | QA rejected: ${pipeline.qaRejected}`);\n      console.log(`\u2502  Context chunks: ${pipeline.contextChunksUsed} | Chars saved(est): ${pipeline.contextCharsSaved}`);\n      console.log('\u2514\u2500\\n');\n      return true;\n    }\n\n    if (command === '/history') {\n      const n = Number.parseInt(args[0] || '5', 10);\n      const sess = await session.loadSession();\n      const entries = sess.history.slice(-n);\n\n      console.log(chalk.blue(`\\n--- Last ${entries.length} Messages ---`));\n      entries.forEach((e) => {\n        const entry = e as { timestamp?: string; type?: string; agent?: string; task?: string; input?: string };\n        const time = entry.timestamp?.split('T')[1]?.split('.')[0] || '';\n        const type = entry.type || 'unknown';\n        console.log(`${chalk.gray(`[${time}]`)} ${chalk.bold(type)}${entry.agent ? chalk.gray(` (${entry.agent})`) : ''}`);\n        const taskStr = entry.task || entry.input || '';\n        if (taskStr) console.log(chalk.gray(`  ${taskStr.slice(0, 80)}${taskStr.length > 80 ? '...' : ''}`));\n      });\n      console.log();\n      return true;\n    }\n\n    if (command === '/recall') {\n      const query = args.join(' ').trim();\n      if (!query) {\n        console.log(chalk.yellow('\\n  Usage: /recall <search query>\\n  Search across past conversations and routing history.\\n'));\n        return true;\n      }\n      try {\n        const { recallSearch, buildRecallContext } = await import('../engine/chat-recall.js');\n        const result = await recallSearch(query, projectDir);\n        if (result.entries.length === 0) {\n          console.log(chalk.yellow(`\\n  No matches for \"${query}\" (searched ${result.totalSearched} entries)\\n`));\n        } else {\n          console.log(chalk.blue(`\\n--- Recall: \"${query}\" (${result.entries.length}/${result.totalSearched} matches) ---\\n`));\n          for (const entry of result.entries.slice(0, 10)) {\n            const date = entry.timestamp?.split('T')[0] || '?';\n            const score = (entry.score * 100).toFixed(0);\n            console.log(`  ${chalk.gray(`[${date}]`)} ${chalk.cyan(`${score}%`)} ${entry.input?.slice(0, 80) || '(no input)'}`);\n            if (entry.output) console.log(chalk.gray(`    \u2192 ${entry.output.slice(0, 60)}`));\n          }\n          console.log();\n        }\n      } catch (err) {\n        console.log(chalk.red(`\\n  Recall error: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/summon') {\n      const persona = args[0];\n      const task = args.slice(1).join(' ').trim();\n      if (!persona || !task) {\n        try {\n          const { listPersonas } = await import('../engine/summon.js');\n          const personas = listPersonas();\n          console.log(chalk.blue('\\n--- Available Personas ---\\n'));\n          for (const p of personas) {\n            console.log(`  ${chalk.cyan(p.id.padEnd(20))} ${p.name} (max ${p.defaultMaxTurns} turns)`);\n          }\n          console.log(chalk.gray('\\n  Usage: /summon <persona> <task>\\n  Example: /summon crew-qa write tests for src/auth.ts\\n'));\n        } catch {}\n        return true;\n      }\n      try {\n        const { getPersona, buildSummonPrompt, filterToolsForPersona } = await import('../engine/summon.js');\n        const personaConfig = getPersona(persona);\n        if (!personaConfig) {\n          console.log(chalk.red(`\\n  Unknown persona: ${persona}\\n`));\n          return true;\n        }\n        console.log(chalk.blue(`\\n  Summoning ${chalk.cyan(personaConfig.name)} for: ${task.slice(0, 60)}...\\n`));\n        const { runAgenticWorker } = await import('../executor/agentic-executor.js');\n        const personaPrompt = buildSummonPrompt('', personaConfig);\n        const result = await runAgenticWorker(task, sandbox, {\n          systemPrompt: personaPrompt,\n          maxTurns: personaConfig.defaultMaxTurns,\n          projectDir,\n          stream: true,\n          persona: personaConfig.id\n        });\n        if (sandbox.hasChanges()) {\n          console.log(chalk.yellow('\\n  Changes staged. Use /preview to review, /apply to write to disk.\\n'));\n        }\n        if (result.output) {\n          logger.printWithHighlight(result.output);\n        }\n        console.log(chalk.gray(`\\n  ${personaConfig.name}: ${result.success ? 'done' : 'failed'} in ${result.turns} turns\\n`));\n      } catch (err) {\n        console.log(chalk.red(`\\n  Summon error: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/preview') {\n      const activeBranch = sandbox.getActiveBranch();\n      if (!sandbox.hasChanges(activeBranch)) {\n        console.log(chalk.yellow(`\\n  No pending changes in \"${activeBranch}\".\\n`));\n      } else {\n        const rawPreview = sandbox.preview(activeBranch);\n        console.log(chalk.blue(`\\n\u250C\u2500 Sandbox Preview [${activeBranch}]`));\n        // Colored diff: green for adds, red for removals, cyan for hunks\n        const coloredLines = rawPreview.split('\\n').map((line: string) => {\n          if (line.startsWith('+++') || line.startsWith('---')) return chalk.bold(line);\n          if (line.startsWith('+')) return chalk.green(line);\n          if (line.startsWith('-')) return chalk.red(line);\n          if (line.startsWith('@@')) return chalk.cyan(line);\n          return line;\n        });\n        console.log(coloredLines.join('\\n'));\n        console.log('\u2514\u2500\\n');\n      }\n      return true;\n    }\n\n    if (command === '/apply') {\n      const wantCommit = args.includes('--commit');\n      const activeBranch = sandbox.getActiveBranch();\n      if (!sandbox.hasChanges(activeBranch)) {\n        console.log(chalk.yellow('\\n  No changes to apply.\\n'));\n      } else {\n        try {\n          const paths = sandbox.getPendingPaths(activeBranch);\n          await sandbox.apply(activeBranch);\n          console.log(chalk.green(`\\n  \u2713 Applied to: ${paths.join(', ')}\\n`));\n\n          // Auto-commit with AI-generated message\n          if (wantCommit) {\n            try {\n              const { execSync } = await import('node:child_process');\n              const diff = execSync('git diff --cached --stat', { encoding: 'utf8', cwd: projectDir }).trim()\n                || execSync('git diff --stat', { encoding: 'utf8', cwd: projectDir }).trim();\n              if (!diff) {\n                console.log(chalk.yellow('  No git changes to commit.\\n'));\n              } else {\n                execSync('git add -A', { cwd: projectDir });\n                // Generate commit message via LLM\n                const commitResult = await orchestrator.executeLocally(\n                  `Generate a concise conventional commit message (type: description, max 72 chars) for this diff. Reply with ONLY the commit message:\\n\\n${diff.slice(0, 2000)}`,\n                  { model: replState.model }\n                );\n                const commitMsg = String(commitResult.result || 'chore: update files').trim().replace(/^['\"`]|['\"`]$/g, '').split('\\n')[0];\n                execSync(`git commit -m \"${commitMsg.replace(/\"/g, '\\\\\"')}\"`, { cwd: projectDir });\n                console.log(chalk.green(`  \u2713 Committed: ${commitMsg}\\n`));\n              }\n            } catch (commitErr) {\n              console.log(chalk.red(`  \u2717 Commit failed: ${(commitErr as Error).message}\\n`));\n            }\n          }\n        } catch (err) {\n          console.log(chalk.red(`\\n  \u2717 Apply failed: ${(err as Error).message}\\n`));\n        }\n      }\n      return true;\n    }\n\n    if (command === '/rollback') {\n      const activeBranch = sandbox.getActiveBranch();\n      try {\n        await sandbox.rollback(activeBranch);\n        console.log(chalk.yellow(`\\n  \u2713 Rolled back \"${activeBranch}\".\\n`));\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Rollback failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/branches' || command === '/branch') {\n      const active = sandbox.getActiveBranch();\n      const branches = sandbox.getBranches();\n\n      if (!args[0]) {\n        console.log(chalk.blue('\\n\u250C\u2500 Sandbox Branches'));\n        branches.forEach(b => {\n          if (b === active) {\n            console.log(chalk.green(`\u2502  \u25CF ${b} (active)`));\n          } else {\n            console.log(`\u2502    ${b}`);\n          }\n        });\n        console.log('\u2514\u2500\\n');\n        console.log(chalk.gray('  Use /branch <name> to switch.\\n'));\n        return true;\n      }\n\n      const targetBranch = args[0];\n      if (!branches.includes(targetBranch)) {\n        console.log(chalk.red(`\\n  \u2717 Unknown sandbox branch \"${targetBranch}\".\\n`));\n        return true;\n      }\n      if (targetBranch === active) {\n        console.log(chalk.gray('\\n  No change.\\n'));\n        return true;\n      }\n      sandbox.switchBranch(targetBranch);\n      console.log(chalk.green(`\\n  \u2713 Switched to branch: ${targetBranch}\\n`));\n      return true;\n    }\n\n    if (command === '/clear') {\n      try {\n        await session.clear();\n        console.log(chalk.yellow('\\n  \u2713 Session history cleared.\\n'));\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Clear failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    // \u2500\u2500\u2500 /sessions \u2014 list all past sessions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (command === '/sessions') {\n      try {\n        const transcriptStore = new ConversationTranscriptStore(projectDir);\n        const sessions = await transcriptStore.listSessions();\n        if (sessions.length === 0) {\n          console.log(chalk.yellow('\\n  No sessions found.\\n'));\n          return true;\n        }\n        console.log(chalk.blue('\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n        console.log(chalk.blue('\u2551                       SESSIONS                               \u2551'));\n        console.log(chalk.blue('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n'));\n        for (const s of sessions) {\n          const summary = await transcriptStore.getSessionSummary(s.sessionId);\n          if (!summary) continue;\n          const age = summary.lastActivity ? new Date(summary.lastActivity).toLocaleString() : 'unknown';\n          console.log(chalk.cyan(`  ${s.sessionId}`));\n          console.log(chalk.gray(`    ${summary.turnCount} turns | ${summary.totalTokens} tokens | Last: ${age}`));\n          console.log(chalk.white(`    \"${summary.firstMessage}\"`));\n          console.log('');\n        }\n        console.log(chalk.gray('  Use /resume <session-id> to continue a session.\\n'));\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Failed to list sessions: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    // \u2500\u2500\u2500 /resume [id] \u2014 resume a previous session \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    if (command === '/resume') {\n      const targetId = args[0];\n      try {\n        const transcriptStore = new ConversationTranscriptStore(projectDir);\n        if (!targetId) {\n          const sessions = await transcriptStore.listSessions();\n          if (sessions.length === 0) {\n            console.log(chalk.yellow('\\n  No sessions to resume.\\n'));\n            return true;\n          }\n          const summaries = [];\n          for (const s of sessions) {\n            const summary = await transcriptStore.getSessionSummary(s.sessionId);\n            if (summary) summaries.push(summary);\n          }\n          if (summaries.length === 0) {\n            console.log(chalk.yellow('\\n  No sessions with content found.\\n'));\n            return true;\n          }\n          console.log(chalk.blue('\\n--- Resumable Sessions ---\\n'));\n          for (const s of summaries) {\n            console.log(chalk.cyan(`  ${s.sessionId}`));\n            console.log(chalk.gray(`    ${s.turnCount} turns | ${s.totalTokens} tokens`));\n            console.log(chalk.white(`    \"${s.firstMessage}\"`));\n          }\n          console.log(chalk.gray('\\n  Use /resume <session-id> to continue one of these sessions.\\n'));\n          return true;\n        }\n\n        // Direct resume by ID\n        const turns = await transcriptStore.loadTurns(targetId);\n        if (turns.length === 0) {\n          console.log(chalk.yellow(`\\n  No transcript found for session: ${targetId}\\n`));\n          return true;\n        }\n        await session.setSessionId(targetId);\n        console.log(chalk.green(`\\n  \u2713 Resumed session ${targetId} (${turns.length} turns loaded)\\n`));\n        const recent = turns.slice(-4);\n        for (const t of recent) {\n          const role = t.role === 'user' ? chalk.cyan('You') : chalk.green('Assistant');\n          const text = String(t.text || '').slice(0, 120);\n          console.log(chalk.gray(`  [${role}] ${text}${t.text.length > 120 ? '\u2026' : ''}`));\n        }\n        console.log('');\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Resume failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/trace') {\n      const traceId = args[0];\n      if (!traceId) {\n        console.log(chalk.blue('\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n        console.log(chalk.blue('\u2551                    EXECUTION TRACE                           \u2551'));\n        console.log(chalk.blue('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n'));\n        console.log(chalk.yellow('  Usage: /trace <traceId>'));\n        console.log(chalk.gray('  Trace IDs are shown in verbose mode or in execution results.\\n'));\n        return true;\n      }\n\n      try {\n        const trace = orchestrator.getTrace(traceId);\n        if (!trace || (trace.composedPrompts.length === 0 && !trace.plannerTrace)) {\n          console.log(chalk.yellow(`\\n  No trace found for ID: ${traceId}\\n`));\n          return true;\n        }\n\n        console.log(chalk.blue('\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n        console.log(chalk.blue(`\u2551           TRACE: ${traceId.slice(0, 30)}           \u2551`));\n        console.log(chalk.blue('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n'));\n\n        if (trace.composedPrompts.length > 0) {\n          console.log(chalk.cyan('  Composed Prompts:'));\n          trace.composedPrompts.forEach((p, i) => {\n            console.log(chalk.white(`    ${i + 1}. ${p.templateId} (v${p.templateVersion})`));\n            console.log(chalk.gray(`       Overlays: ${p.overlays.map(o => o.type).join(', ')}`));\n            console.log(chalk.gray(`       Composed: ${p.composedAt}`));\n          });\n          console.log();\n        }\n\n        if (trace.plannerTrace && trace.plannerTrace.length > 0) {\n          console.log(chalk.cyan('  Planner Trace:'));\n          trace.plannerTrace.forEach((p, i) => {\n            console.log(chalk.white(`    ${i + 1}. ${p.templateId} (v${p.templateVersion})`));\n            console.log(chalk.gray(`       Overlays: ${p.overlays.map(o => o.type).join(', ')}`));\n          });\n          console.log();\n        }\n\n        console.log(chalk.gray('  Full prompts saved to session history.\\n'));\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Trace failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/cost') {\n      const cost = await session.loadCost();\n      console.log(chalk.blue('\\n\u250C\u2500 Cost Summary'));\n      console.log(`\u2502  Total: ${chalk.green(`$${cost.totalUsd.toFixed(4)}`)}`);\n      if (Object.keys(cost.byModel).length > 0) {\n        console.log('\u2502  By model:');\n        Object.entries(cost.byModel as Record<string, number>).forEach(([model, usd]) => {\n          console.log(`\u2502    ${model}: $${usd.toFixed(4)}`);\n        });\n      }\n      console.log('\u2514\u2500\\n');\n      return true;\n    }\n\n    if (command === '/context') {\n      try {\n        const gitContext = await getProjectContext(projectDir);\n        const sess = await session.loadSession();\n        const tokenEstimate = Math.ceil((gitContext.length + JSON.stringify(sess.history).length) / 4);\n\n        console.log(chalk.blue('\\n\u250C\u2500 Context Footprint'));\n        console.log(`\u2502  Project: ${projectDir}`);\n        console.log(`\u2502  Session entries: ${sess.history.length}`);\n        console.log(`\u2502  Git context: ${gitContext.length} chars`);\n        console.log(`\u2502  Estimated tokens: ~${tokenEstimate}`);\n        console.log('\u2514\u2500\\n');\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Context check failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/git') {\n      try {\n        const gitContext = await getProjectContext(projectDir);\n        console.log(chalk.blue('\\n\u250C\u2500 Git Status'));\n        console.log(gitContext);\n        console.log('\u2514\u2500\\n');\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Git read failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/repos') {\n      try {\n        const repoContext = await collectMultiRepoContext(projectDir);\n        console.log(chalk.blue('\\n\u250C\u2500 Sibling Repositories'));\n        console.log(repoContext);\n        console.log('\u2514\u2500\\n');\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Repos scan failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    if (command === '/memory') {\n      const query = args.join(' ').trim();\n      if (!query) {\n        const stats = await keeper.stats();\n        console.log(chalk.blue('\\n--- AgentKeeper Memory Stats ---\\n'));\n        console.log(`  Total entries: ${stats.entries}`);\n        console.log(`  Approx bytes: ${stats.bytes}`);\n        return true;\n      }\n      const hits = await memoryBroker.recall(query, {\n        maxResults: replState.memoryMax,\n        includeDocs: true,\n        includeCode: false,\n        preferSuccessful: true\n      });\n      if (hits.length === 0) {\n        console.log(chalk.yellow(`\\n  No memory/RAG matches for \"${query}\".\\n`));\n        return true;\n      }\n      console.log(chalk.blue(`\\n--- Shared Memory + RAG Recall: \"${query}\" (${hits.length} hits) ---\\n`));\n      for (const h of hits) {\n        console.log(chalk.yellow(`[${h.score.toFixed(3)}] ${h.source} \u2014 ${h.title.slice(0, 80)}`));\n        const preview = h.text.length > 120 ? `${h.text.slice(0, 120)}...` : h.text;\n        console.log(chalk.gray(`  ${preview}`));\n      }\n      console.log();\n      return true;\n    }\n\n    if (command === '/lsp') {\n      const sub = args[0];\n      if (!sub || sub === 'help') {\n        console.log(chalk.blue('\\n--- LSP Commands ---'));\n        console.log('  /lsp check [files...]');\n        console.log('  /lsp complete <file> <line> <column> [prefix]\\n');\n        return true;\n      }\n      if (sub === 'check') {\n        const files = args.slice(1);\n        const { typeCheckProject } = await import('../lsp/index.js');\n        const diagnostics = await typeCheckProject(projectDir, files);\n        if (diagnostics.length === 0) {\n          console.log(chalk.green('\\n  \u2713 No LSP diagnostics found.\\n'));\n          return true;\n        }\n        console.log(chalk.yellow(`\\nFound ${diagnostics.length} diagnostic(s):`));\n        for (const diag of diagnostics) {\n          console.log(`  ${diag.category.toUpperCase()} ${diag.code} ${diag.file}:${diag.line}:${diag.column}`);\n          console.log(`    ${diag.message}`);\n        }\n        console.log();\n        return true;\n      }\n      if (sub === 'complete') {\n        const file = args[1];\n        const line = Number.parseInt(args[2] || '', 10);\n        const column = Number.parseInt(args[3] || '', 10);\n        const prefix = args[4] || '';\n        if (!file || Number.isNaN(line) || Number.isNaN(column)) {\n          console.log(chalk.red('\\n  \u2717 Usage: /lsp complete <file> <line> <column> [prefix]\\n'));\n          return true;\n        }\n        const { getCompletions } = await import('../lsp/index.js');\n        const completions = await getCompletions(projectDir, file, line, column, 20, prefix);\n        if (completions.length === 0) {\n          console.log(chalk.yellow('\\n  No completions found.\\n'));\n          return true;\n        }\n        console.log(chalk.blue(`\\nCompletions (${completions.length}):`));\n        completions.forEach(item => console.log(`  - ${item.name} (${item.kind})`));\n        console.log();\n        return true;\n      }\n      console.log(chalk.red(`\\n  \u2717 Unknown /lsp subcommand: ${sub}\\n`));\n      return true;\n    }\n\n    // \u2500\u2500 /image <path> \u2014 attach image for next agentic task \u2500\u2500\n    if (command === '/image') {\n      const imgPath = args.join(' ').trim();\n      if (!imgPath) {\n        if (pendingImages.length === 0) {\n          console.log(chalk.yellow('\\n  No images attached. Usage: /image <path>\\n'));\n        } else {\n          console.log(chalk.cyan(`\\n  \uD83D\uDCF7 ${pendingImages.length} image(s) attached:`));\n          for (const p of pendingImages) {\n            console.log(chalk.gray(`     ${p}`));\n          }\n          console.log(chalk.gray('  These will be sent with your next message.\\n'));\n        }\n        return true;\n      }\n      const { resolve: resolvePath } = await import('node:path');\n      const { existsSync } = await import('node:fs');\n      const absPath = resolvePath(projectDir, imgPath);\n      const ext = absPath.split('.').pop()?.toLowerCase();\n      if (!['png', 'jpg', 'jpeg', 'webp', 'gif'].includes(ext || '')) {\n        console.log(chalk.red(`\\n  \u2717 Unsupported image type: .${ext} (supported: png, jpg, jpeg, webp, gif)\\n`));\n        return true;\n      }\n      if (!existsSync(absPath)) {\n        console.log(chalk.red(`\\n  \u2717 File not found: ${absPath}\\n`));\n        return true;\n      }\n      pendingImages.push(absPath);\n      console.log(chalk.green(`\\n  \uD83D\uDCF7 Image attached: ${absPath}`));\n      console.log(chalk.gray(`  ${pendingImages.length} image(s) queued. Type your task and they'll be sent with it.\\n`));\n      return true;\n    }\n\n    // \u2500\u2500 /diff \u2014 colorized git diff \u2500\u2500\n    if (command === '/diff') {\n      try {\n        const { execSync } = await import('node:child_process');\n        const staged = execSync('git diff --cached', { encoding: 'utf8', cwd: projectDir }).trim();\n        const unstaged = execSync('git diff', { encoding: 'utf8', cwd: projectDir }).trim();\n        const fullDiff = (staged + '\\n' + unstaged).trim();\n        if (!fullDiff) {\n          console.log(chalk.yellow('\\n  No git changes.\\n'));\n        } else {\n          console.log(chalk.blue('\\n\u250C\u2500 Git Diff'));\n          const coloredLines = fullDiff.split('\\n').map((line: string) => {\n            if (line.startsWith('+++') || line.startsWith('---')) return chalk.bold(line);\n            if (line.startsWith('+')) return chalk.green(line);\n            if (line.startsWith('-')) return chalk.red(line);\n            if (line.startsWith('@@')) return chalk.cyan(line);\n            if (line.startsWith('diff ')) return chalk.bold.blue(line);\n            return line;\n          });\n          console.log(coloredLines.join('\\n'));\n          console.log('\u2514\u2500\\n');\n        }\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Git diff failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    // \u2500\u2500 /validate \u2014 blind LLM code review \u2500\u2500\n    if (command === '/validate') {\n      console.log(chalk.cyan('\\n  \uD83D\uDD0D Running blind validation...\\n'));\n      try {\n        const { execSync } = await import('node:child_process');\n        let diffStat = '';\n        try { diffStat = execSync('git diff HEAD~1 --stat', { encoding: 'utf8', cwd: projectDir }).slice(0, 2000); } catch {}\n        let codeSnippets = '';\n        try {\n          const changedFiles = execSync('git diff HEAD~1 --name-only', { encoding: 'utf8', cwd: projectDir })\n            .split('\\n').filter(Boolean).slice(0, 5);\n          for (const f of changedFiles) {\n            try {\n              const { readFileSync } = await import('node:fs');\n              const content = readFileSync(join(projectDir, f), 'utf8');\n              codeSnippets += `\\n### ${f}\\n\\`\\`\\`\\n${content.slice(0, 1500)}\\n\\`\\`\\`\\n`;\n            } catch {}\n          }\n        } catch {}\n\n        const validateTask = `You are crew-judge, a blind code validator. Review these recent changes and provide a structured assessment.\n\nScore each category 1-5:\n- **Correctness**: Does the code work? Edge cases?\n- **Security**: Vulnerabilities? Input validation?\n- **Performance**: Bottlenecks? Memory leaks?\n- **Readability**: Clean, documented, follows conventions?\n- **Test Coverage**: Tests present? What's missing?\n\nEnd with VERDICT: SHIP \u2705, FIX \uD83D\uDD27, or REJECT \u274C with actionable items.\n\n## Changed files\\n${diffStat || 'No recent changes'}\\n\\n## Code\\n${codeSnippets || 'No code to review'}`;\n\n        const result = await orchestrator.executeLocally(validateTask, { model: replState.model });\n        const responseText = String(result.result || 'Validation could not complete.');\n        console.log(chalk.cyan('  \u250C\u2500 Validation Report'));\n        logger.printWithHighlight(responseText);\n        console.log('  \u2514\u2500\\n');\n\n        if (result.costUsd) {\n          await session.trackCost({ model: result.model || replState.model, usd: result.costUsd });\n        }\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Validation failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    // \u2500\u2500 /test-first \u2014 TDD workflow \u2500\u2500\n    if (command === '/test-first') {\n      const tfTask = args.join(' ').trim();\n      if (!tfTask) {\n        console.log(chalk.red('\\n  \u2717 Usage: /test-first <task description>\\n'));\n        return true;\n      }\n      console.log(chalk.magenta('\\n  \uD83E\uDDEA Test-first mode\\n'));\n      console.log(chalk.gray('  Step 1: Generate tests \u2192 Step 2: Implement \u2192 Step 3: Validate\\n'));\n\n      try {\n        // Step 1: Generate tests\n        console.log(chalk.bold('  Step 1: Generating tests...\\n'));\n        const testResult = await orchestrator.executeLocally(\n          `You are a TDD expert. Given a task description, write comprehensive tests FIRST. Cover happy path, edge cases, error handling, input validation. Output ONLY the test code in a fenced code block with the filename.\\n\\nTask: ${tfTask}\\nProject dir: ${projectDir}`,\n          { model: replState.model }\n        );\n        const testCode = String(testResult.result || '');\n        console.log(chalk.cyan('  \u250C\u2500 Tests'));\n        logger.printWithHighlight(testCode);\n        console.log('  \u2514\u2500\\n');\n\n        // Step 2: Implement\n        console.log(chalk.bold('  Step 2: Implementing to pass tests...\\n'));\n        const implResult = await orchestrator.executeLocally(\n          `Given these tests, write the MINIMAL implementation to make ALL tests pass. Use diff blocks to show changes.\\n\\nTests:\\n${testCode}\\n\\nTask: \"${tfTask}\"`,\n          { model: replState.model }\n        );\n        const implCode = String(implResult.result || '');\n        console.log(chalk.cyan('  \u250C\u2500 Implementation'));\n        logger.printWithHighlight(implCode);\n        console.log('  \u2514\u2500\\n');\n\n        // Step 3: Validate\n        console.log(chalk.bold('  Step 3: Validating implementation against tests...\\n'));\n        const valResult = await orchestrator.executeLocally(\n          `Given tests and implementation, verify:\\n1. Would all tests pass? Walk through each test case.\\n2. Missing edge cases?\\n3. Implementation bugs?\\nVerdict: PASS \u2705 or FAIL \u274C with specific issues.\\n\\nTests:\\n${testCode}\\n\\nImplementation:\\n${implCode}`,\n          { model: replState.model }\n        );\n        console.log(chalk.cyan('  \u250C\u2500 Validation'));\n        logger.printWithHighlight(String(valResult.result || ''));\n        console.log('  \u2514\u2500\\n');\n\n        // Track cost for all 3 steps\n        const totalCost = (testResult.costUsd || 0) + (implResult.costUsd || 0) + (valResult.costUsd || 0);\n        if (totalCost > 0) {\n          await session.trackCost({ model: replState.model, usd: totalCost });\n        }\n        console.log(chalk.gray(`  Total test-first cost: $${totalCost.toFixed(4)}\\n`));\n      } catch (err) {\n        console.log(chalk.red(`\\n  \u2717 Test-first failed: ${(err as Error).message}\\n`));\n      }\n      return true;\n    }\n\n    console.log(chalk.red(`\\n  \u2717 Unknown command: ${command}. Type /help.\\n`));\n    return true;\n  };\n\n  refreshPrompt();\n  rl.prompt();\n\n  rl.on('line', async (input: string) => {\n    const trimmed = input.trim();\n\n    if (!trimmed) {\n      rl.prompt();\n      return;\n    }\n\n    if (trimmed === '/') {\n      printSlashCommandMenu();\n      rl.prompt();\n      return;\n    }\n\n    if (isCommandProcessing) {\n      const isExitCmd = /^\\/(?:exit|quit)\\b/i.test(trimmed);\n      if (isExitCmd) {\n        pendingExit = true;\n        if (process.stdin.isTTY) {\n          console.log(chalk.gray('\\n  Exiting after current command completes...\\n'));\n        }\n        return;\n      }\n      if (!process.stdin.isTTY) {\n        // In piped/script mode, ignore overlapping non-exit input quietly.\n        return;\n      }\n      console.log(chalk.yellow('\\n  \u23F3 A command prompt is already active. Finish/cancel it first.\\n'));\n      rl.prompt();\n      return;\n    }\n\n    let handled = false;\n    try {\n      isCommandProcessing = true;\n      handled = await handleSlashCommand(trimmed);\n    } catch (err) {\n      console.log(chalk.red(`\\n  \u2717 Command failed: ${(err as Error).message}\\n`));\n      isCommandProcessing = false;\n      if (!isClosing) rl.prompt();\n      return;\n    }\n    isCommandProcessing = false;\n    if (pendingExit && !isClosing) {\n      pendingExit = false;\n      isClosing = true;\n      console.log(chalk.cyan('\\n  \uD83D\uDC4B Goodbye! Session saved to .crew/\\n'));\n      rl.close();\n      return;\n    }\n    if (handled) {\n      if (!isClosing) rl.prompt();\n      return;\n    }\n\n    if (isProcessing) {\n      console.log(chalk.yellow('\\n  \u23F3 Previous message still processing. Please wait or press Ctrl+C to cancel.\\n'));\n      rl.prompt();\n      return;\n    }\n\n    isProcessing = true;\n\n    // Spinner for thinking indicator\n    // Simple thinking indicator (no intervals \u2014 those fight with readline)\n    let spinnerActive = false;\n    if (process.stdout.isTTY) {\n      process.stdout.write(chalk.gray('  \u23F3 Thinking...\\n'));\n      spinnerActive = true;\n    }\n    const stopSpinner = () => {\n      if (spinnerActive) {\n        spinnerActive = false;\n        // Move up one line and clear it\n        process.stdout.write('\\x1b[1A\\x1b[2K');\n      }\n    };\n\n    try {\n      if (replState.verbose) {\n        stopSpinner();\n        console.log(chalk.gray('  \u23F3 Routing...'));\n      }\n\n      let taskInput = trimmed;\n      const lower = trimmed.toLowerCase();\n      if (/\\b(switch|set|use).*(solo|standalone)\\b/.test(lower)) {\n        stopSpinner();\n        replState.useGateway = false;\n        process.env.CREW_INTERFACE_MODE = 'standalone';\n        console.log(chalk.cyan('\\n  \u250C\u2500 Response'));\n        console.log(chalk.white('  Switched to standalone mode. Local routing/execution is now preferred.'));\n        console.log('  \u2514\u2500\\n');\n        isProcessing = false;\n        rl.prompt();\n        return;\n      }\n      if (/\\b(switch|set|use).*(connected|gateway)\\b/.test(lower)) {\n        stopSpinner();\n        replState.useGateway = true;\n        process.env.CREW_INTERFACE_MODE = 'connected';\n        console.log(chalk.cyan('\\n  \u250C\u2500 Response'));\n        console.log(chalk.white('  Switched to connected mode. Gateway/crew-lead orchestration is now preferred.'));\n        console.log('  \u2514\u2500\\n');\n        isProcessing = false;\n        rl.prompt();\n        return;\n      }\n\n      const modelSummary = buildModelSummary(projectDir, replState);\n      const localAnswer = answerLocalMetaQuestion(trimmed, modelSummary);\n      if (localAnswer) {\n        console.log(chalk.cyan('\\n  \u250C\u2500 Response'));\n        console.log(chalk.white(`  ${localAnswer}`));\n        console.log('  \u2514\u2500\\n');\n        await session.appendHistory({\n          type: 'repl_meta',\n          input: trimmed,\n          response: localAnswer\n        });\n        isProcessing = false;\n        rl.prompt();\n        return;\n      }\n      // Only intercept genuine meta questions, not actual work requests\n      const bootstrapAnswer = answerFromBootstrap(trimmed, modelSummary, repoBootstrap);\n      if (bootstrapAnswer) {\n        stopSpinner();\n        console.log(chalk.cyan('\\n  \u250C\u2500 Response'));\n        console.log(chalk.white(`  ${bootstrapAnswer}`));\n        console.log('  \u2514\u2500\\n');\n        await session.appendHistory({\n          type: 'repl_meta',\n          input: trimmed,\n          response: bootstrapAnswer\n        });\n        isProcessing = false;\n        rl.prompt();\n        return;\n      }\n\n      const behavior = modeBehavior(replState.mode);\n      if (behavior.memoryInject) {\n        const recalls = await memoryBroker.recall(trimmed, {\n          maxResults: replState.memoryMax,\n          includeDocs: true,\n          includeCode: false,\n          preferSuccessful: true\n        });\n        if (recalls.length > 0) {\n          const memoryContext = await memoryBroker.recallAsContext(trimmed, {\n            maxResults: replState.memoryMax,\n            includeDocs: true,\n            includeCode: false,\n            preferSuccessful: true\n          });\n          taskInput = `${trimmed}\\n\\n${memoryContext}`;\n        }\n      }\n\n      const route = await orchestrator.route(taskInput);\n      const agent = route.agent || 'crew-main';\n\n      if (replState.verbose) {\n        console.log(chalk.gray(`  \u2192 ${agent} (${route.decision})`));\n      }\n\n      if (route.decision === 'CHAT') {\n        stopSpinner();\n        const responseText = route.response || \n          \"I'm crew-cli, a multi-agent coding orchestrator. Ask me to build something, review code, or dispatch to specialists!\";\n        console.log(chalk.cyan('\\n  \u250C\u2500 Response'));\n        logger.printWithHighlight(`  ${responseText}`);\n        console.log('  \u2514\u2500\\n');\n\n        try {\n          await session.appendHistory({\n            type: 'repl_chat',\n            input: trimmed,\n            response: responseText\n          });\n\n          await session.trackCost({\n            promptTokens: trimmed.length / 4,\n            completionTokens: responseText.length / 4,\n            model: 'groq-router',\n            usd: 0.0001\n          });\n        } catch {\n          // Session tracking is best-effort\n        }\n\n        isProcessing = false;\n        rl.prompt();\n        return;\n      }\n\n      if (behavior.executionConfirm && process.stdin.isTTY) {\n        stopSpinner();\n        const estimate = estimateCost(taskInput, replState.model || undefined, 1800);\n        const ok = await confirmInline(\n          `Execute ${route.decision} via ${agent}? est ~$${estimate.totalUsd.toFixed(4)}`,\n          true\n        );\n        if (!ok) {\n          console.log(chalk.yellow('\\n  Skipped execution.\\n'));\n          isProcessing = false;\n          rl.prompt();\n          return;\n        }\n      }\n\n      interface DispatchOpts {\n        project: string;\n        sessionId: string;\n        model?: string;\n        engine?: string;\n        onToolCall?: (name: string, params: Record<string, unknown>) => void;\n      }\n      const dispatchOpts: DispatchOpts = {\n        project: projectDir,\n        sessionId: await session.getSessionId()\n      };\n      if (replState.model && replState.model !== 'auto') dispatchOpts.model = replState.model;\n      if (replState.engine && replState.engine !== 'auto') dispatchOpts.engine = replState.engine;\n\n      // Load session history and format as context for standalone mode\n      const standaloneMode = modelSummary.mode === 'standalone';\n      let conversationContext = '';\n      if (standaloneMode) {\n        const sess = await session.loadSession();\n        const recentHistory = sess.history.slice(-10); // Last 10 exchanges\n        if (recentHistory.length > 0) {\n          conversationContext = recentHistory\n            .map((entry) => {\n              const histEntry = entry as { input?: string; task?: string; output?: string; response?: string; result?: string };\n              const input = histEntry.input || histEntry.task || '';\n              const output = histEntry.output || histEntry.response || histEntry.result || '';\n              if (!input && !output) return '';\n              const parts = [];\n              if (input) parts.push(`User: ${input}`);\n              if (output) parts.push(`Assistant: ${output}`);\n              return parts.join('\\n');\n            })\n            .filter(Boolean)\n            .join('\\n\\n');\n        }\n      }\n\n      const useLegacyStandalone = String(process.env.CREW_LEGACY_ROUTER || '').toLowerCase() === 'true';\n      const policy = getExecutionPolicy();\n      // Stop spinner before execution starts (streaming will take over)\n      stopSpinner();\n\n      // Tool progress display (visible without verbose mode)\n      const toolProgressLog: string[] = [];\n      const onToolCall = (name: string, params: Record<string, unknown>) => {\n        const paramHint = params.file_path || params.path || params.command || params.query || '';\n        const display = paramHint ? `${name}(${String(paramHint).slice(0, 60)})` : name;\n        if (!replState.verbose) {\n          console.log(chalk.gray(`  \uD83D\uDD27 ${display}`));\n        }\n        toolProgressLog.push(display);\n      };\n\n      // Inject onToolCall into orchestrator/executor options if available\n      if (dispatchOpts) dispatchOpts.onToolCall = onToolCall;\n\n      const selectedStandaloneEngine = normalizeStandaloneEngine(replState.engine);\n      const useDirectCliEngine = standaloneMode && selectedStandaloneEngine !== 'auto' && selectedStandaloneEngine !== 'crew-cli';\n\n      const result = useDirectCliEngine\n        ? await withRetries(\n            async () => runEngine(selectedStandaloneEngine, route.task || taskInput, {\n              model: dispatchOpts.model,\n              cwd: projectDir,\n              projectDir,\n              sessionId: dispatchOpts.sessionId\n            }),\n            policy\n          )\n        : standaloneMode\n        ? (useLegacyStandalone\n          ? await withRetries(\n              async () => orchestrator.executeLocally(route.task || taskInput, {\n                model: dispatchOpts.model\n              }),\n              policy\n            )\n          : await withRetries(\n              async () => orchestrator.executeAgentic(route.task || taskInput, {\n                model: dispatchOpts.model,\n                onToolCall,\n                conversationContext,\n                sessionId: dispatchOpts.sessionId,\n                deferApply: !replState.autoApply // In manual/assist mode, defer so REPL can show diff\n              }),\n              policy\n            ))\n        : await withRetries(\n            async () => router.dispatch(agent, taskInput, dispatchOpts),\n            policy\n          );\n\n      // Result may come from runEngine, executeLocally, executeAgentic, or router.dispatch\n      // All return compatible shapes with varying optional fields \u2014 cast to a known union\n      interface ExecutionResult {\n        success?: boolean;\n        result?: string;\n        response?: string;\n        stdout?: string;\n        stderr?: string;\n        model?: string;\n        costUsd?: number;\n        cost?: number;\n        promptTokens?: number;\n        completionTokens?: number;\n        turns?: number;\n        toolsUsed?: string[];\n        providerId?: string;\n        provider?: string;\n        modelUsed?: string;\n        engine?: string;\n        timeline?: Array<{ phase: string; ts: string }>;\n      }\n      const typedResult = result as ExecutionResult;\n\n      await session.appendHistory({ type: 'repl_request', agent, task: taskInput, projectDir });\n      await session.appendHistory({ type: 'repl_result', agent, success: Boolean(typedResult.success), result: typedResult.result });\n\n      await session.appendRouting({\n        route: route.decision,\n        model: typedResult.model || replState.model || 'unknown',\n        agent: standaloneMode ? 'local-executor' : agent,\n        mode: standaloneMode ? 'standalone' : 'connected'\n      });\n\n      if (typedResult.costUsd && typedResult.model) {\n        await session.trackCost({\n          model: typedResult.model,\n          usd: typedResult.costUsd,\n          promptTokens: typedResult.promptTokens || 0,\n          completionTokens: typedResult.completionTokens || 0\n        });\n      }\n\n      const responseText = String(typedResult.stdout || typedResult.response || typedResult.result || typedResult.stderr || '');\n      console.log(chalk.cyan('\\n  \u250C\u2500 Response'));\n      logger.printWithHighlight(responseText);\n      console.log('  \u2514\u2500');\n\n      // Provider + cost footer (novel feature)\n      const providerInfo = typedResult.providerId || typedResult.provider || typedResult.model || replState.model;\n      const modelUsed = typedResult.modelUsed || typedResult.model || providerInfo;\n      const engineUsed = typedResult.engine || (useDirectCliEngine ? selectedStandaloneEngine : (standaloneMode ? 'crew-cli' : (dispatchOpts.engine || replState.engine || 'gateway')));\n      const routeUsed = route.decision || (standaloneMode ? 'EXECUTE' : 'DISPATCH');\n      const responseCost = typedResult.costUsd || typedResult.cost || 0;\n      const turnsUsed = typedResult.turns || 1;\n      const toolCount = typedResult.toolsUsed?.length || toolProgressLog.length || 0;\n      if (modelUsed || responseCost) {\n        const costStr = responseCost > 0 ? `$${Number(responseCost).toFixed(4)}` : 'free';\n        console.log(chalk.gray(`  \u26A1 route=${routeUsed} \u00B7 engine=${engineUsed} \u00B7 provider=${providerInfo}`));\n        console.log(chalk.gray(`  \u26A1 model=${modelUsed} \u00B7 ${turnsUsed} turn${turnsUsed > 1 ? 's' : ''} \u00B7 ${toolCount} tool${toolCount !== 1 ? 's' : ''} \u00B7 ${costStr}`));\n      }\n      if (Array.isArray(typedResult.timeline) && typedResult.timeline.length > 0) {\n        console.log(chalk.gray('\\n  Timeline'));\n        for (const step of typedResult.timeline) {\n          console.log(chalk.gray(`  - ${step.phase} @ ${step.ts}`));\n        }\n      }\n\n      const edits = await orchestrator.parseAndApplyToSandbox(responseText);\n      if (edits.length > 0) {\n        console.log(chalk.yellow(`\\n  \u2713 ${edits.length} file(s) changed in sandbox`));\n\n        // Animated colored diff preview (premium UX)\n        try {\n          const activeBranch = sandbox.getActiveBranch();\n          if (sandbox.hasChanges(activeBranch)) {\n            const rawPreview = sandbox.preview(activeBranch);\n            if (rawPreview && rawPreview.length < 5000) { // Only show inline for reasonable diffs\n              console.log(chalk.blue(`\\n  \u250C\u2500 Diff Preview`));\n              const diffLines = rawPreview.split('\\n');\n              for (const line of diffLines) {\n                let colored: string;\n                if (line.startsWith('+++') || line.startsWith('---')) colored = chalk.bold(line);\n                else if (line.startsWith('+')) colored = chalk.green(line);\n                else if (line.startsWith('-')) colored = chalk.red(line);\n                else if (line.startsWith('@@')) colored = chalk.cyan(line);\n                else if (line.startsWith('diff') || line.startsWith('index')) colored = chalk.gray(line);\n                else colored = line;\n                console.log(`  ${colored}`);\n                // Animated rendering \u2014 slight delay for premium feel (only in TTY)\n                if (process.stdout.isTTY) {\n                  await new Promise(r => setTimeout(r, 8));\n                }\n              }\n              console.log(chalk.blue(`  \u2514\u2500`));\n            }\n          }\n        } catch {\n          // Diff preview is best-effort\n        }\n\n        const shouldAutoApply = replState.autoApply || behavior.autoApply;\n        await recordReplEvent('autopilot_decision', {\n          mode: replState.mode,\n          enabled: shouldAutoApply,\n          reason: replState.mode === 'autopilot' ? 'mode-autopilot' : (replState.autoApply ? 'auto-apply-toggle' : 'disabled'),\n          edits: edits.length\n        });\n        if (shouldAutoApply) {\n          try {\n            const activeBranch = sandbox.getActiveBranch();\n            const paths = sandbox.getPendingPaths(activeBranch);\n            const policy = getExecutionPolicy();\n            const report = await analyzeBlastRadius(projectDir, { changedFiles: paths });\n            if (isRiskBlocked(report.risk, policy.riskThreshold, policy.forceAutoApply)) {\n              const patchRisk = scorePatchRisk({\n                blastRadius: report,\n                changedFiles: paths.length\n              });\n              await recordReplEvent('autopilot_apply', {\n                mode: replState.mode,\n                success: false,\n                blockedByRisk: true,\n                risk: report.risk,\n                threshold: policy.riskThreshold,\n                confidence: patchRisk.confidence\n              });\n              console.log(chalk.red(`  \u2717 Auto-apply blocked by risk gate (${report.risk} >= ${policy.riskThreshold})`));\n              console.log(chalk.gray('  Use /preview and /apply, or set CREW_FORCE_AUTO_APPLY=true to override.'));\n              console.log();\n              isProcessing = false;\n              rl.prompt();\n              return;\n            }\n            await sandbox.apply(activeBranch);\n            await recordReplEvent('autopilot_apply', {\n              mode: replState.mode,\n              success: true,\n              paths\n            });\n            console.log(chalk.green(`  \u2713 Auto-applied to: ${paths.join(', ')}`));\n          } catch (applyErr) {\n            await recordReplEvent('autopilot_apply', {\n              mode: replState.mode,\n              success: false,\n              error: (applyErr as Error).message\n            });\n            console.log(chalk.red(`  \u2717 Auto-apply failed: ${(applyErr as Error).message}`));\n          }\n        } else {\n          console.log(chalk.gray('  Type /preview to review or /apply to write to disk'));\n        }\n        console.log();\n      }\n\n      const cost = await session.loadCost();\n      console.log(chalk.gray(`  Session cost: $${cost.totalUsd.toFixed(4)}\\n`));\n\n      isProcessing = false;\n      rl.prompt();\n    } catch (err) {\n      stopSpinner();\n      console.log(chalk.red(`\\n  \u2717 Error: ${(err as Error).message}\\n`));\n      await session.appendHistory({\n        type: 'repl_error',\n        task: trimmed,\n        error: (err as Error).message\n      });\n      isProcessing = false;\n      rl.prompt();\n    }\n  });\n\n  rl.on('close', async () => {\n    await recordReplEvent('session_closed', {\n      mode: replState.mode\n    });\n    if (checkpointEnabled) {\n      try {\n        await checkpoints.finish(replRunId, 'completed');\n      } catch {\n        // Best-effort checkpoint close.\n      }\n    }\n    if (process.stdin.isTTY) {\n      process.stdin.off('keypress', keypressListener as (...args: unknown[]) => void);\n    }\n    console.log(chalk.cyan('\\n  Session saved to .crew/ \u2014 run \"crew repl\" to continue.\\n'));\n    // Allow readline/inquirer handles to close naturally; avoid forced exit races.\n  });\n}\n", "import { resolve, join } from 'node:path';\nimport { AgentKeeper, type MemoryMatch } from './agentkeeper.js';\nimport { AgentMemory, type MemoryFact } from '../pipeline/agent-memory.js';\nimport { buildCollectionIndex, searchCollection, type CollectionChunk } from '../collections/index.js';\n\nexport interface BrokerHit {\n  source: 'agentkeeper' | 'agent-memory' | 'collections';\n  score: number;\n  title: string;\n  text: string;\n  metadata?: Record<string, unknown>;\n}\n\nexport interface BrokerRecallOptions {\n  maxResults?: number;\n  includeDocs?: boolean;\n  includeCode?: boolean;\n  docsPaths?: string[];\n  preferSuccessful?: boolean;\n  pathHints?: string[];\n}\n\nfunction tokenize(text: string): Set<string> {\n  return new Set(\n    String(text || '')\n      .toLowerCase()\n      .replace(/[^a-z0-9\\s_-]/g, ' ')\n      .split(/\\s+/)\n      .filter(t => t.length > 2)\n  );\n}\n\nfunction similarity(a: Set<string>, b: Set<string>): number {\n  if (a.size === 0 || b.size === 0) return 0;\n  let intersection = 0;\n  for (const token of a) {\n    if (b.has(token)) intersection += 1;\n  }\n  return intersection / Math.max(a.size, b.size);\n}\n\nfunction mapKeeperHit(m: MemoryMatch): BrokerHit {\n  return {\n    source: 'agentkeeper',\n    score: Number(m.score || 0),\n    title: `[${m.entry.tier}] ${m.entry.task}`,\n    text: m.entry.result,\n    metadata: {\n      agent: m.entry.agent,\n      runId: m.entry.runId,\n      timestamp: m.entry.timestamp\n    }\n  };\n}\n\nfunction mapFactHit(f: MemoryFact, score: number): BrokerHit {\n  return {\n    source: 'agent-memory',\n    score: Number(score.toFixed(3)),\n    title: `[${f.critical ? 'CRITICAL' : 'INFO'}] ${f.tags.join(', ') || 'memory-fact'}`,\n    text: f.content,\n    metadata: {\n      critical: f.critical,\n      tags: f.tags,\n      timestamp: f.timestamp,\n      provider: f.provider\n    }\n  };\n}\n\nfunction mapCollectionHit(c: CollectionChunk): BrokerHit {\n  return {\n    source: 'collections',\n    score: Number(c.score || 0),\n    title: `${c.source}:${c.startLine}`,\n    text: c.text,\n    metadata: {\n      path: c.source,\n      startLine: c.startLine\n    }\n  };\n}\n\nfunction normalizeCollectionPathForDedupe(input: string): string {\n  const value = String(input || '').replace(/\\\\/g, '/').replace(/^\\.\\/+/, '');\n  if (value.startsWith('docs/')) return value.slice('docs/'.length);\n  return value;\n}\n\nexport class MemoryBroker {\n  private readonly projectDir: string;\n  private readonly keeper: AgentKeeper;\n  private readonly factMemory: AgentMemory;\n  private readonly docsIndexCache = new Map<string, Awaited<ReturnType<typeof buildCollectionIndex>>>();\n\n  constructor(projectDir: string, options: { crewId?: string; storageDir?: string } = {}) {\n    this.projectDir = resolve(projectDir);\n    this.keeper = new AgentKeeper(this.projectDir, {\n      storageDir: options.storageDir || process.env.CREW_MEMORY_DIR\n    });\n    this.factMemory = new AgentMemory(options.crewId || 'crew-lead', {\n      storageDir: options.storageDir || process.env.CREW_MEMORY_DIR || this.projectDir\n    });\n  }\n\n  private scoreFacts(query: string, facts: MemoryFact[], max: number): BrokerHit[] {\n    const queryTokens = tokenize(query);\n    const scored = facts.map(f => {\n      const sim = similarity(queryTokens, tokenize(f.content));\n      const criticalBoost = f.critical ? 0.3 : 0;  // Increased from 0.1\n      const tagBoost = f.tags.some(t => query.toLowerCase().includes(t.toLowerCase())) ? 0.15 : 0;\n      return { fact: f, score: sim + criticalBoost + tagBoost };\n    }).filter(x => x.score > 0.08);  // Lowered from 0.12 to catch critical facts\n\n    // Force critical facts to top even if similarity is lower\n    scored.sort((a, b) => {\n      if (a.fact.critical && !b.fact.critical) return -1;\n      if (!a.fact.critical && b.fact.critical) return 1;\n      return b.score - a.score;\n    });\n    \n    return scored.slice(0, max).map(x => mapFactHit(x.fact, x.score));\n  }\n\n  private async getDocsIndex(paths: string[], includeCode: boolean) {\n    const key = `${paths.map(p => resolve(p)).join('|')}::${includeCode ? 'code' : 'docs'}`;\n    if (this.docsIndexCache.has(key)) return this.docsIndexCache.get(key)!;\n    const idx = await buildCollectionIndex(paths, { includeCode });\n    this.docsIndexCache.set(key, idx);\n    return idx;\n  }\n\n  async recall(query: string, options: BrokerRecallOptions = {}): Promise<BrokerHit[]> {\n    const maxResults = Math.max(1, Number(options.maxResults || 5));\n    const includeDocs = options.includeDocs !== false;\n    const includeCode = Boolean(options.includeCode);\n    const docsPaths = (options.docsPaths && options.docsPaths.length > 0)\n      ? options.docsPaths\n      : [join(this.projectDir, 'docs'), this.projectDir];\n\n    const [keeperHits, factHits, collectionHits] = await Promise.all([\n      this.keeper.recall(query, Math.max(maxResults, 8), {\n        preferSuccessful: options.preferSuccessful !== false,\n        pathHints: options.pathHints || []\n      }),\n      this.factMemory.search(query, { maxResults: Math.max(maxResults, 8) }),\n      includeDocs\n        ? (async () => {\n          const index = await this.getDocsIndex(docsPaths, includeCode);\n          return searchCollection(index, query, Math.max(maxResults, 8)).hits;\n        })()\n        : Promise.resolve([])\n    ]);\n\n    const merged = [\n      ...keeperHits.map(mapKeeperHit),\n      ...this.scoreFacts(query, factHits, Math.max(maxResults, 8)),\n      ...collectionHits.map(mapCollectionHit)\n    ];\n\n    merged.sort((a, b) => b.score - a.score);\n\n    // Dedupe near-identical collection hits that appear when both docs/ and repo root\n    // are indexed together (same chunk can be surfaced twice with different source paths).\n    const seen = new Set<string>();\n    const deduped: BrokerHit[] = [];\n    for (const hit of merged) {\n      let signature = `${hit.source}|${hit.title}|${hit.text.slice(0, 180)}`;\n      if (hit.source === 'collections') {\n        const path = normalizeCollectionPathForDedupe(String(hit.metadata?.path || hit.title.split(':')[0] || ''));\n        const startLine = Number(hit.metadata?.startLine || 0);\n        signature = `${hit.source}|${path}|${startLine}|${hit.text.slice(0, 220)}`;\n      }\n      if (seen.has(signature)) continue;\n      seen.add(signature);\n      deduped.push(hit);\n      if (deduped.length >= maxResults) break;\n    }\n    return deduped;\n  }\n\n  async recallAsContext(query: string, options: BrokerRecallOptions = {}): Promise<string> {\n    const hits = await this.recall(query, options);\n    if (hits.length === 0) return '';\n    const lines = ['## Shared Memory + RAG Context'];\n    for (const h of hits) {\n      const preview = h.text.length > 260 ? `${h.text.slice(0, 260)}...` : h.text;\n      lines.push(`### [${h.source}] ${h.title} (score: ${h.score.toFixed(3)})`);\n      lines.push(preview);\n      lines.push('');\n    }\n    return lines.join('\\n');\n  }\n}\n", "import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface CheckpointEvent {\n  ts: string;\n  type: string;\n  data?: Record<string, unknown>;\n}\n\nexport interface CheckpointRun {\n  runId: string;\n  mode: 'plan' | 'dispatch' | 'auto' | 'repl';\n  task: string;\n  createdAt: string;\n  updatedAt: string;\n  status: 'running' | 'completed' | 'failed';\n  events: CheckpointEvent[];\n}\n\nexport class CheckpointStore {\n  private dir: string;\n\n  constructor(baseDir = process.cwd()) {\n    this.dir = join(baseDir, '.crew', 'checkpoints');\n  }\n\n  private filePath(runId: string) {\n    return join(this.dir, `${runId}.json`);\n  }\n\n  async beginRun(run: Omit<CheckpointRun, 'createdAt' | 'updatedAt' | 'events' | 'status'>) {\n    await mkdir(this.dir, { recursive: true });\n    const now = new Date().toISOString();\n    const payload: CheckpointRun = {\n      ...run,\n      createdAt: now,\n      updatedAt: now,\n      status: 'running',\n      events: []\n    };\n    await writeFile(this.filePath(run.runId), JSON.stringify(payload, null, 2), 'utf8');\n    return payload;\n  }\n\n  async append(runId: string, type: string, data: Record<string, unknown> = {}) {\n    const run = await this.load(runId);\n    if (!run) return false;\n    run.events.push({\n      ts: new Date().toISOString(),\n      type,\n      data\n    });\n    run.updatedAt = new Date().toISOString();\n    await writeFile(this.filePath(runId), JSON.stringify(run, null, 2), 'utf8');\n    return true;\n  }\n\n  async finish(runId: string, status: 'completed' | 'failed') {\n    const run = await this.load(runId);\n    if (!run) return false;\n    run.status = status;\n    run.updatedAt = new Date().toISOString();\n    await writeFile(this.filePath(runId), JSON.stringify(run, null, 2), 'utf8');\n    return true;\n  }\n\n  async load(runId: string): Promise<CheckpointRun | null> {\n    try {\n      const raw = await readFile(this.filePath(runId), 'utf8');\n      return JSON.parse(raw);\n    } catch {\n      return null;\n    }\n  }\n\n  async list(limit = 20): Promise<CheckpointRun[]> {\n    if (!existsSync(this.dir)) return [];\n    const files = (await readdir(this.dir))\n      .filter(f => f.endsWith('.json'))\n      .slice(-Math.max(1, limit));\n    const runs: CheckpointRun[] = [];\n    for (const file of files) {\n      try {\n        const raw = await readFile(join(this.dir, file), 'utf8');\n        runs.push(JSON.parse(raw));\n      } catch {\n        // skip broken files\n      }\n    }\n    runs.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));\n    return runs;\n  }\n\n  static completedPlanSteps(run: CheckpointRun): number[] {\n    const ids = new Set<number>();\n    for (const ev of run.events) {\n      if (ev.type === 'plan.step.completed') {\n        const stepId = Number((ev.data || {}).stepId || 0);\n        if (Number.isFinite(stepId) && stepId > 0) ids.add(stepId);\n      }\n    }\n    return Array.from(ids).sort((a, b) => a - b);\n  }\n}\n", "import type { BlastRadiusReport } from '../blast-radius/index.js';\n\nexport interface PatchRiskAssessment {\n  riskScore: number; // 0..100\n  confidenceScore: number;\n  // Backward-compatible aliases used by CLI output paths.\n  confidence: number;\n  riskLevel: 'low' | 'medium' | 'high';\n  level: 'low' | 'medium' | 'high';\n  reasons: string[];\n}\n\nexport function scorePatchRisk(input: {\n  blastRadius?: Partial<BlastRadiusReport> | null;\n  validationPassed?: boolean;\n  changedFiles?: number;\n  failedSteps?: number;\n  risk?: 'low' | 'medium' | 'high';\n  summary?: string;\n  changedFilesList?: string[];\n}): PatchRiskAssessment {\n  const reasons: string[] = [];\n  let risk = 0.2;\n\n  const changedFiles = Number(input.changedFiles || input.changedFilesList?.length || 0);\n  if (changedFiles >= 12) {\n    risk += 0.25;\n    reasons.push('large-change-set');\n  } else if (changedFiles >= 5) {\n    risk += 0.15;\n    reasons.push('medium-change-set');\n  }\n\n  const blast = input.blastRadius || input;\n  const blastRisk = String((blast as { risk?: string })?.risk || '').toLowerCase();\n  if (blastRisk === 'high') {\n    risk += 0.35;\n    reasons.push('high-blast-radius');\n  } else if (blastRisk === 'medium') {\n    risk += 0.2;\n    reasons.push('medium-blast-radius');\n  }\n\n  if (Number(input.failedSteps || 0) > 0) {\n    risk += 0.2;\n    reasons.push('failed-plan-steps');\n  }\n\n  if (input.validationPassed === false) {\n    risk += 0.25;\n    reasons.push('validation-failed');\n  } else if (input.validationPassed === true) {\n    risk -= 0.1;\n    reasons.push('validation-passed');\n  } else {\n    reasons.push('validation-unknown');\n  }\n\n  const boundedRisk = Math.max(0, Math.min(1, risk));\n  const confidenceScore = Math.max(0, Math.min(1, 1 - boundedRisk));\n  const level: 'low' | 'medium' | 'high' = boundedRisk >= 0.75\n    ? 'high'\n    : boundedRisk >= 0.45\n      ? 'medium'\n      : 'low';\n\n  const riskScore = Number((boundedRisk * 100).toFixed(1));\n  return {\n    riskScore,\n    confidenceScore: Number(confidenceScore.toFixed(3)),\n    confidence: Number(confidenceScore.toFixed(3)),\n    riskLevel: level,\n    level,\n    reasons\n  };\n}\n", "import { startRepl, type ReplOptions } from '../repl/index.js';\n\n/**\n * TUI adapter.\n * Reuses the same REPL runtime/controller so routing, orchestration,\n * sandbox, memory, and safety behavior stay in one code path.\n */\nexport async function startTui(options: ReplOptions): Promise<void> {\n  process.env.CREW_UI_MODE = 'tui';\n  await startRepl({\n    ...options,\n    uiMode: 'tui'\n  });\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport interface XSearchOptions {\n  model?: string;\n  fromDate?: string;\n  toDate?: string;\n  allowedHandles?: string[];\n  excludedHandles?: string[];\n  enableImages?: boolean;\n  enableVideos?: boolean;\n}\n\nexport interface XSearchResult {\n  text: string;\n  citations: string[];\n  raw: Record<string, unknown>;\n}\n\nfunction getXaiApiKey(): string | null {\n  if (process.env.XAI_API_KEY) return process.env.XAI_API_KEY;\n  if (process.env.GROK_API_KEY) return process.env.GROK_API_KEY;\n  const cfgPath = join(homedir(), '.crewswarm', 'crewswarm.json');\n  if (!existsSync(cfgPath)) return null;\n  try {\n    const raw = readFileSync(cfgPath, 'utf8');\n    const cfg = JSON.parse(raw);\n    return cfg?.providers?.xai?.apiKey || null;\n  } catch {\n    return null;\n  }\n}\n\nfunction coerceDate(value?: string): string | undefined {\n  if (!value) return undefined;\n  const d = new Date(value);\n  if (!Number.isFinite(d.getTime())) return undefined;\n  return d.toISOString().slice(0, 10);\n}\n\nexport async function runXSearch(query: string, options: XSearchOptions = {}): Promise<XSearchResult> {\n  const apiKey = getXaiApiKey();\n  if (!apiKey) {\n    throw new Error('Missing xAI API key. Set XAI_API_KEY or ~/.crewswarm/crewswarm.json providers.xai.apiKey');\n  }\n  const model = options.model || 'grok-4-1-fast-reasoning';\n  const tool: Record<string, unknown> = { type: 'x_search' };\n  const fromDate = coerceDate(options.fromDate);\n  const toDate = coerceDate(options.toDate);\n  if (fromDate) tool.from_date = fromDate;\n  if (toDate) tool.to_date = toDate;\n  if (options.allowedHandles && options.allowedHandles.length > 0) tool.allowed_x_handles = options.allowedHandles;\n  if (options.excludedHandles && options.excludedHandles.length > 0) tool.excluded_x_handles = options.excludedHandles;\n  if (typeof options.enableImages === 'boolean') tool.enable_image_understanding = options.enableImages;\n  if (typeof options.enableVideos === 'boolean') tool.enable_video_understanding = options.enableVideos;\n\n  const response = await fetch('https://api.x.ai/v1/responses', {\n    method: 'POST',\n    headers: {\n      Authorization: `Bearer ${apiKey}`,\n      'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n      model,\n      input: [{ role: 'user', content: query }],\n      tools: [tool]\n    })\n  });\n\n  if (!response.ok) {\n    const text = await response.text();\n    throw new Error(`xAI request failed (${response.status}): ${text.slice(0, 300)}`);\n  }\n\n  const raw = await response.json() as Record<string, unknown>;\n  const outputs = Array.isArray(raw?.output) ? raw.output : [];\n  let text = '';\n  for (const o of outputs) {\n    const content = Array.isArray(o?.content) ? o.content : [];\n    for (const c of content) {\n      if (typeof c?.text === 'string' && c.text.trim()) {\n        text += (text ? '\\n\\n' : '') + c.text.trim();\n      }\n    }\n  }\n  const citations = Array.isArray(raw?.citations)\n    ? (raw.citations as Array<Record<string, unknown>>).map((c) => String(c?.url || c || '')).filter(Boolean)\n    : [];\n  return {\n    text: text || 'No textual response.',\n    citations,\n    raw\n  };\n}\n\n", "// @ts-nocheck\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface RepoConfig {\n  cli?: {\n    model?: string;\n    engine?: string;\n    preferredEngines?: string[];\n    fallbackModels?: string[];\n    docsCode?: boolean;\n    memoryMax?: number;\n  };\n  repl?: {\n    model?: string;\n    engine?: string;\n    autoApply?: boolean;\n    memoryMax?: number;\n    mode?: 'manual' | 'assist' | 'autopilot';\n    bannerEnabled?: boolean;\n    animatedBanner?: boolean;\n    bannerFirstLaunchOnly?: boolean;\n  };\n  slashAliases?: Record<string, string>;\n}\n\nconst DEFAULT_CONFIG: Required<RepoConfig> = {\n  cli: {\n    model: '',\n    engine: '',\n    preferredEngines: [],\n    fallbackModels: [],\n    docsCode: false,\n    memoryMax: 3\n  },\n  repl: {\n    model: '',\n    engine: 'auto',\n    autoApply: false,\n    memoryMax: 5,\n    mode: 'manual',\n    bannerEnabled: true,\n    animatedBanner: true,\n    bannerFirstLaunchOnly: true\n  },\n  slashAliases: {}\n};\n\nconst SECRET_KEY_RE = /(api[_-]?key|token|secret|password|bearer|auth)/i;\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n  return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction deepMerge<T extends Record<string, unknown>>(base: T, overlay: Record<string, unknown>): T {\n  const out: Record<string, unknown> = { ...base };\n  for (const [k, v] of Object.entries(overlay || {})) {\n    const existing = out[k];\n    if (isObject(existing) && isObject(v)) {\n      out[k] = deepMerge(existing, v);\n    } else {\n      out[k] = v;\n    }\n  }\n  return out as T;\n}\n\nfunction parseJsonOrEmpty(raw: string): Record<string, unknown> {\n  try {\n    const parsed = JSON.parse(raw);\n    return isObject(parsed) ? parsed : {};\n  } catch {\n    return {};\n  }\n}\n\nfunction configPath(baseDir: string, scope: 'team' | 'user') {\n  return join(baseDir, '.crew', scope === 'team' ? 'crewswarm.json' : 'config.local.json');\n}\n\nfunction assertNoSecrets(input: unknown, prefix = '') {\n  if (Array.isArray(input)) {\n    for (let i = 0; i < input.length; i++) {\n      assertNoSecrets(input[i], `${prefix}[${i}]`);\n    }\n    return;\n  }\n  if (!isObject(input)) return;\n  for (const [k, v] of Object.entries(input)) {\n    const path = prefix ? `${prefix}.${k}` : k;\n    if (SECRET_KEY_RE.test(k)) {\n      throw new Error(`Secret-like key not allowed in repo team config: ${path}`);\n    }\n    assertNoSecrets(v, path);\n  }\n}\n\nfunction redactSecrets(input: unknown): unknown {\n  if (Array.isArray(input)) return input.map(redactSecrets);\n  if (!isObject(input)) return input;\n  const out: Record<string, unknown> = {};\n  for (const [k, v] of Object.entries(input)) {\n    if (SECRET_KEY_RE.test(k)) {\n      out[k] = '[REDACTED]';\n    } else {\n      out[k] = redactSecrets(v);\n    }\n  }\n  return out;\n}\n\nexport async function readRepoConfig(baseDir: string, scope: 'team' | 'user'): Promise<Record<string, unknown>> {\n  const path = configPath(baseDir, scope);\n  if (!existsSync(path)) return {};\n  const raw = await readFile(path, 'utf8');\n  return parseJsonOrEmpty(raw);\n}\n\nexport async function loadResolvedRepoConfig(baseDir = process.cwd()): Promise<Required<RepoConfig>> {\n  const team = await readRepoConfig(baseDir, 'team');\n  const user = await readRepoConfig(baseDir, 'user');\n  return deepMerge(deepMerge(DEFAULT_CONFIG, team), user);\n}\n\nexport async function writeRepoConfig(baseDir: string, scope: 'team' | 'user', config: Record<string, unknown>) {\n  const path = configPath(baseDir, scope);\n  await mkdir(join(baseDir, '.crew'), { recursive: true });\n  if (scope === 'team') {\n    assertNoSecrets(config);\n  }\n  await writeFile(path, JSON.stringify(config, null, 2), 'utf8');\n}\n\nexport async function setRepoConfigValue(\n  baseDir: string,\n  scope: 'team' | 'user',\n  keyPath: string,\n  value: unknown\n) {\n  if (scope === 'team' && SECRET_KEY_RE.test(keyPath)) {\n    throw new Error(`Secret-like key not allowed in repo team config: ${keyPath}`);\n  }\n  const current = await readRepoConfig(baseDir, scope);\n  const parts = keyPath.split('.').filter(Boolean);\n  if (parts.length === 0) throw new Error('Invalid key path');\n  let cursor: Record<string, unknown> = current;\n  for (let i = 0; i < parts.length - 1; i++) {\n    const k = parts[i];\n    const next = cursor[k];\n    if (!isObject(next)) {\n      cursor[k] = {};\n    }\n    cursor = cursor[k] as Record<string, unknown>;\n  }\n  cursor[parts[parts.length - 1]] = value;\n  await writeRepoConfig(baseDir, scope, current);\n}\n\nexport function getNestedValue(source: Record<string, unknown>, keyPath: string): unknown {\n  const parts = keyPath.split('.').filter(Boolean);\n  let cursor: unknown = source;\n  for (const p of parts) {\n    if (!isObject(cursor) && !Array.isArray(cursor)) return undefined;\n    cursor = cursor[p];\n    if (cursor === undefined) return undefined;\n  }\n  return cursor;\n}\n\nexport function redactRepoConfigForDisplay<T>(value: T): T {\n  return redactSecrets(value) as T;\n}\n", "import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nexport type GitHubIntent =\n  | { kind: 'issue_list'; state: 'open' | 'closed' | 'all'; limit: number }\n  | { kind: 'issue_create'; title: string; body: string }\n  | { kind: 'issue_update'; number: number; title?: string; body?: string; state?: 'open' | 'closed' }\n  | { kind: 'pr_list'; state: 'open' | 'closed' | 'merged'; limit: number }\n  | { kind: 'pr_draft'; title: string; body: string; base?: string; head?: string }\n  | { kind: 'unknown'; reason: string };\n\nexport interface ParseGitHubIntentOptions {\n  defaultLimit?: number;\n}\n\nfunction readQuoted(text: string): string {\n  const m = text.match(/\"([^\"]+)\"/);\n  return (m?.[1] || '').trim();\n}\n\nfunction readAfter(text: string, marker: string): string {\n  const idx = text.toLowerCase().indexOf(marker.toLowerCase());\n  if (idx < 0) return '';\n  return text.slice(idx + marker.length).trim();\n}\n\nfunction parseLimit(text: string, fallback: number): number {\n  const m = text.match(/\\b(?:limit|top|first)\\s+(\\d+)\\b/i);\n  if (!m) return fallback;\n  const value = Number.parseInt(m[1], 10);\n  return Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\nexport function parseGitHubIntent(input: string, options: ParseGitHubIntentOptions = {}): GitHubIntent {\n  const text = String(input || '').trim();\n  const lower = text.toLowerCase();\n  const defaultLimit = Math.max(1, Number(options.defaultLimit || 10));\n\n  if (!text) return { kind: 'unknown', reason: 'Empty request.' };\n\n  if ((/\\b(list|show|get)\\b/.test(lower) && /\\bissues?\\b/.test(lower)) || lower.startsWith('issues')) {\n    const state = lower.includes('closed') ? 'closed' : lower.includes('all') ? 'all' : 'open';\n    return { kind: 'issue_list', state, limit: parseLimit(text, defaultLimit) };\n  }\n\n  if ((/\\b(list|show|get)\\b/.test(lower) && /\\b(pr|pull request|pull requests)\\b/.test(lower)) || lower.startsWith('prs')) {\n    const state = lower.includes('merged')\n      ? 'merged'\n      : lower.includes('closed')\n        ? 'closed'\n        : 'open';\n    return { kind: 'pr_list', state, limit: parseLimit(text, defaultLimit) };\n  }\n\n  if (/\\b(update|edit|close|reopen)\\b/.test(lower) && /\\bissue\\b/.test(lower)) {\n    const num = text.match(/#(\\d+)/)?.[1] || text.match(/\\bissue\\s+(\\d+)\\b/i)?.[1];\n    if (!num) return { kind: 'unknown', reason: 'Issue update requires an issue number (e.g. #123).' };\n    const parsedNumber = Number.parseInt(num, 10);\n    const title = readQuoted(text);\n    const body = readAfter(text, 'body:');\n    let state: 'open' | 'closed' | undefined;\n    if (/\\bclose\\b/.test(lower)) state = 'closed';\n    if (/\\breopen\\b/.test(lower)) state = 'open';\n    return {\n      kind: 'issue_update',\n      number: parsedNumber,\n      title: title || undefined,\n      body: body || undefined,\n      state\n    };\n  }\n\n  if ((/\\b(create|open|file)\\b/.test(lower) && /\\bissue\\b/.test(lower)) || lower.startsWith('issue create')) {\n    const quoted = readQuoted(text);\n    const title = quoted || readAfter(text, 'issue').replace(/^create\\s*/i, '').trim();\n    const body = readAfter(text, 'body:');\n    if (!title) return { kind: 'unknown', reason: 'Issue create requires a title (quote it for best parsing).' };\n    return { kind: 'issue_create', title, body: body || '' };\n  }\n\n  if (/\\b(create|open|draft)\\b/.test(lower) && /\\b(pr|pull request)\\b/.test(lower)) {\n    const title = readQuoted(text) || readAfter(text, 'pr').replace(/^create\\s*/i, '').trim();\n    const body = readAfter(text, 'body:');\n    const base = text.match(/\\bbase:([A-Za-z0-9_./-]+)/i)?.[1];\n    const head = text.match(/\\bhead:([A-Za-z0-9_./-]+)/i)?.[1];\n    if (!title) return { kind: 'unknown', reason: 'Draft PR create requires a title (quote it for best parsing).' };\n    return { kind: 'pr_draft', title, body: body || '', base, head };\n  }\n\n  return { kind: 'unknown', reason: 'Could not infer GitHub action. Try list/create/update issue or list/create PR.' };\n}\n\nasync function runGh(args: string[], cwd = process.cwd()): Promise<string> {\n  try {\n    const { stdout, stderr } = await execFileAsync('gh', args, {\n      cwd,\n      maxBuffer: 1024 * 1024 * 8\n    });\n    const out = String(stdout || '').trim();\n    const err = String(stderr || '').trim();\n    return out || err;\n  } catch (error) {\n    const message = String((error as { stderr?: string })?.stderr || (error as Error).message || error);\n    if (/enoent|not found/i.test(message)) {\n      throw new Error('GitHub CLI (gh) not found. Install gh and run `gh auth login`.');\n    }\n    throw new Error(message.trim() || 'GitHub command failed');\n  }\n}\n\nexport interface ExecuteGitHubIntentOptions {\n  cwd?: string;\n  repo?: string;\n}\n\nexport function buildGitHubCommand(intent: GitHubIntent, repo?: string): string[] {\n  const repoArgs = repo ? ['--repo', repo] : [];\n\n  if (intent.kind === 'issue_list') {\n    return ['issue', 'list', '--state', intent.state, '--limit', String(intent.limit), '--json', 'number,title,state,url', ...repoArgs];\n  }\n  if (intent.kind === 'pr_list') {\n    return ['pr', 'list', '--state', intent.state, '--limit', String(intent.limit), '--json', 'number,title,state,url', ...repoArgs];\n  }\n  if (intent.kind === 'issue_create') {\n    return ['issue', 'create', '--title', intent.title, '--body', intent.body || '', ...repoArgs];\n  }\n  if (intent.kind === 'issue_update') {\n    const args = ['issue', 'edit', String(intent.number), ...repoArgs];\n    if (intent.title) args.push('--title', intent.title);\n    if (intent.body) args.push('--body', intent.body);\n    if (intent.state) args.push('--state', intent.state);\n    return args;\n  }\n  if (intent.kind === 'pr_draft') {\n    const args = ['pr', 'create', '--draft', '--title', intent.title, '--body', intent.body || '', ...repoArgs];\n    if (intent.base) args.push('--base', intent.base);\n    if (intent.head) args.push('--head', intent.head);\n    return args;\n  }\n  throw new Error(intent.reason || 'Unknown GitHub request');\n}\n\nexport function commandToShell(args: string[]): string {\n  const q = (value: string) => {\n    if (!/[\\s\"'$`\\\\]/.test(value)) return value;\n    return `'${value.replace(/'/g, `'\\\\''`)}'`;\n  };\n  return `gh ${args.map(q).join(' ')}`;\n}\n\nexport async function executeGitHubIntent(intent: GitHubIntent, options: ExecuteGitHubIntentOptions = {}): Promise<string> {\n  const cwd = options.cwd || process.cwd();\n  const args = buildGitHubCommand(intent, options.repo);\n  return runGh(args, cwd);\n}\n\nexport function requiresConfirmation(intent: GitHubIntent): boolean {\n  return intent.kind === 'issue_create' || intent.kind === 'issue_update' || intent.kind === 'pr_draft';\n}\n\nexport function describeIntent(intent: GitHubIntent): string {\n  if (intent.kind === 'issue_list') return `List ${intent.state} issues (limit ${intent.limit})`;\n  if (intent.kind === 'pr_list') return `List ${intent.state} PRs (limit ${intent.limit})`;\n  if (intent.kind === 'issue_create') return `Create issue: \"${intent.title}\"`;\n  if (intent.kind === 'issue_update') return `Update issue #${intent.number}`;\n  if (intent.kind === 'pr_draft') return `Create draft PR: \"${intent.title}\"`;\n  return `Unknown: ${intent.reason}`;\n}\n\nexport interface GitHubDoctorCheck {\n  name: string;\n  ok: boolean;\n  details: string;\n}\n\nexport async function runGitHubDoctor(cwd = process.cwd(), repo?: string): Promise<GitHubDoctorCheck[]> {\n  const checks: GitHubDoctorCheck[] = [];\n  try {\n    const { stdout } = await execFileAsync('gh', ['--version'], { cwd, maxBuffer: 1024 * 1024 });\n    checks.push({\n      name: 'gh installed',\n      ok: true,\n      details: String(stdout || '').split('\\n')[0] || 'ok'\n    });\n  } catch (error) {\n    checks.push({\n      name: 'gh installed',\n      ok: false,\n      details: /enoent|not found/i.test(String((error as Error)?.message || ''))\n        ? 'gh not found in PATH'\n        : String((error as Error).message || error)\n    });\n    checks.push({\n      name: 'gh auth status',\n      ok: false,\n      details: 'skipped (gh missing)'\n    });\n    checks.push({\n      name: 'repo access baseline',\n      ok: false,\n      details: 'skipped (gh missing)'\n    });\n    return checks;\n  }\n\n  try {\n    const { stdout, stderr } = await execFileAsync('gh', ['auth', 'status'], {\n      cwd,\n      maxBuffer: 1024 * 1024\n    });\n    const info = String(stdout || stderr || '').trim();\n    checks.push({\n      name: 'gh auth status',\n      ok: true,\n      details: info.split('\\n')[0] || 'authenticated'\n    });\n  } catch (error) {\n    checks.push({\n      name: 'gh auth status',\n      ok: false,\n      details: String((error as { stderr?: string })?.stderr || (error as Error).message || error).trim()\n    });\n  }\n\n  const repoArgs = repo ? ['--repo', repo] : [];\n  try {\n    const { stdout } = await execFileAsync(\n      'gh',\n      ['repo', 'view', ...repoArgs, '--json', 'nameWithOwner,viewerPermission'],\n      { cwd, maxBuffer: 1024 * 1024 }\n    );\n    const parsed = JSON.parse(String(stdout || '{}'));\n    const perm = String(parsed.viewerPermission || 'unknown');\n    const name = String(parsed.nameWithOwner || repo || '(current)');\n    checks.push({\n      name: 'repo access baseline',\n      ok: true,\n      details: `${name} (${perm})`\n    });\n  } catch (error) {\n    checks.push({\n      name: 'repo access baseline',\n      ok: false,\n      details: String((error as { stderr?: string })?.stderr || (error as Error).message || error).trim()\n    });\n  }\n\n  return checks;\n}\n", "import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport interface TierPolicy {\n  primary?: string;\n  fallback?: string[];\n  maxCostUsd?: number;\n}\n\nexport interface ModelPolicy {\n  tiers?: {\n    planner?: TierPolicy;\n    executor?: TierPolicy;\n    worker?: TierPolicy;\n  };\n}\n\nfunction sanitizeTier(input: unknown): TierPolicy {\n  const out: TierPolicy = {};\n  if (!input || typeof input !== 'object') return out;\n  const item = input as Record<string, unknown>;\n  if (typeof item.primary === 'string') out.primary = item.primary.trim();\n  if (Array.isArray(item.fallback)) {\n    out.fallback = item.fallback\n      .map(v => String(v || '').trim())\n      .filter(Boolean);\n  }\n  if (typeof item.maxCostUsd === 'number' && Number.isFinite(item.maxCostUsd) && item.maxCostUsd >= 0) {\n    out.maxCostUsd = item.maxCostUsd;\n  }\n  return out;\n}\n\nexport async function loadModelPolicy(baseDir = process.cwd()): Promise<ModelPolicy> {\n  const path = join(baseDir, '.crew', 'model-policy.json');\n  if (!existsSync(path)) return {};\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(await readFile(path, 'utf8'));\n  } catch {\n    return {};\n  }\n  if (!parsed || typeof parsed !== 'object') return {};\n  const obj = parsed as Record<string, unknown>;\n  const tiers = (obj.tiers && typeof obj.tiers === 'object') ? (obj.tiers as Record<string, unknown>) : {};\n  return {\n    tiers: {\n      planner: sanitizeTier(tiers.planner),\n      executor: sanitizeTier(tiers.executor),\n      worker: sanitizeTier(tiers.worker)\n    }\n  };\n}\n", "import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { randomUUID } from 'node:crypto';\n\nexport type AutoFixJobStatus = 'queued' | 'running' | 'completed' | 'failed' | 'canceled';\nexport type AutoFixApplyPolicy = 'never' | 'safe' | 'force';\n\nexport interface AutoFixJobConfig {\n  maxIterations: number;\n  model?: string;\n  fallbackModels: string[];\n  gateway?: string;\n  validateCommands: string[];\n  autoApplyPolicy: AutoFixApplyPolicy;\n  blastRadiusThreshold: 'low' | 'medium' | 'high';\n  lspAutoFix: boolean;\n  lspAutoFixMaxAttempts: number;\n}\n\nexport interface AutoFixJob {\n  id: string;\n  task: string;\n  projectDir: string;\n  status: AutoFixJobStatus;\n  createdAt: string;\n  updatedAt: string;\n  startedAt?: string;\n  finishedAt?: string;\n  workerId?: string;\n  error?: string;\n  config: AutoFixJobConfig;\n  result?: Record<string, unknown>;\n}\n\ninterface AutoFixState {\n  version: 1;\n  jobs: AutoFixJob[];\n}\n\nconst DEFAULT_STATE: AutoFixState = {\n  version: 1,\n  jobs: []\n};\n\nfunction createDefaultState(): AutoFixState {\n  return {\n    version: 1,\n    jobs: []\n  };\n}\n\nexport class AutoFixStore {\n  private readonly dir: string;\n  private readonly file: string;\n\n  constructor(baseDir = process.cwd()) {\n    this.dir = join(baseDir, '.crew', 'autofix');\n    this.file = join(this.dir, 'queue.json');\n  }\n\n  private async readState(): Promise<AutoFixState> {\n    if (!existsSync(this.file)) return createDefaultState();\n    try {\n      const raw = await readFile(this.file, 'utf8');\n      const parsed = JSON.parse(raw) as AutoFixState;\n      if (!Array.isArray(parsed.jobs)) return createDefaultState();\n      return {\n        version: 1,\n        jobs: parsed.jobs.map(job => this.sanitizeJob(job)).filter(Boolean) as AutoFixJob[]\n      };\n    } catch {\n      return createDefaultState();\n    }\n  }\n\n  private sanitizeJob(job: Partial<AutoFixJob>): AutoFixJob | null {\n    if (!job || typeof job.id !== 'string' || typeof job.task !== 'string') return null;\n    const now = new Date().toISOString();\n    return {\n      id: job.id,\n      task: String(job.task || '').trim(),\n      projectDir: String(job.projectDir || process.cwd()),\n      status: this.sanitizeStatus(job.status),\n      createdAt: String(job.createdAt || now),\n      updatedAt: String(job.updatedAt || now),\n      startedAt: job.startedAt,\n      finishedAt: job.finishedAt,\n      workerId: job.workerId,\n      error: job.error,\n      config: {\n        maxIterations: Math.max(1, Number(job.config?.maxIterations || 6)),\n        model: typeof job.config?.model === 'string' && job.config.model.trim().length > 0 ? job.config.model.trim() : undefined,\n        fallbackModels: Array.isArray(job.config?.fallbackModels) ? job.config!.fallbackModels.map(v => String(v || '').trim()).filter(Boolean) : [],\n        gateway: typeof job.config?.gateway === 'string' && job.config.gateway.trim().length > 0 ? job.config.gateway.trim() : undefined,\n        validateCommands: Array.isArray(job.config?.validateCommands) ? job.config!.validateCommands.map(v => String(v || '').trim()).filter(Boolean) : [],\n        autoApplyPolicy: this.sanitizePolicy(job.config?.autoApplyPolicy),\n        blastRadiusThreshold: this.sanitizeThreshold(job.config?.blastRadiusThreshold),\n        lspAutoFix: Boolean(job.config?.lspAutoFix),\n        lspAutoFixMaxAttempts: Math.max(1, Number(job.config?.lspAutoFixMaxAttempts || 3))\n      },\n      result: job.result && typeof job.result === 'object' ? job.result : undefined\n    };\n  }\n\n  private sanitizeStatus(status: unknown): AutoFixJobStatus {\n    const value = String(status || 'queued').toLowerCase();\n    if (value === 'running' || value === 'completed' || value === 'failed' || value === 'canceled') return value;\n    return 'queued';\n  }\n\n  private sanitizePolicy(policy: unknown): AutoFixApplyPolicy {\n    const value = String(policy || 'safe').toLowerCase();\n    if (value === 'never' || value === 'force') return value;\n    return 'safe';\n  }\n\n  private sanitizeThreshold(level: unknown): 'low' | 'medium' | 'high' {\n    const value = String(level || 'high').toLowerCase();\n    if (value === 'low' || value === 'medium') return value;\n    return 'high';\n  }\n\n  private async writeState(state: AutoFixState): Promise<void> {\n    await mkdir(this.dir, { recursive: true });\n    await writeFile(this.file, JSON.stringify(state, null, 2), 'utf8');\n  }\n\n  async enqueue(input: {\n    task: string;\n    projectDir?: string;\n    config?: Partial<AutoFixJobConfig>;\n  }): Promise<AutoFixJob> {\n    const now = new Date().toISOString();\n    const state = await this.readState();\n    const job = this.sanitizeJob({\n      id: `af-${randomUUID()}`,\n      task: String(input.task || '').trim(),\n      projectDir: input.projectDir || process.cwd(),\n      status: 'queued',\n      createdAt: now,\n      updatedAt: now,\n      config: {\n        maxIterations: Math.max(1, Number(input.config?.maxIterations || 6)),\n        model: input.config?.model,\n        fallbackModels: input.config?.fallbackModels || [],\n        gateway: input.config?.gateway,\n        validateCommands: input.config?.validateCommands || [],\n        autoApplyPolicy: this.sanitizePolicy(input.config?.autoApplyPolicy),\n        blastRadiusThreshold: this.sanitizeThreshold(input.config?.blastRadiusThreshold),\n        lspAutoFix: Boolean(input.config?.lspAutoFix),\n        lspAutoFixMaxAttempts: Math.max(1, Number(input.config?.lspAutoFixMaxAttempts || 3))\n      }\n    });\n    if (!job) throw new Error('Invalid autofix job payload');\n    if (!job.task) throw new Error('Task is required');\n    state.jobs.push(job);\n    await this.writeState(state);\n    return job;\n  }\n\n  async list(filter?: { status?: AutoFixJobStatus }): Promise<AutoFixJob[]> {\n    const state = await this.readState();\n    const jobs = [...state.jobs].sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));\n    if (!filter?.status) return jobs;\n    return jobs.filter(job => job.status === filter.status);\n  }\n\n  async get(id: string): Promise<AutoFixJob | null> {\n    const state = await this.readState();\n    return state.jobs.find(job => job.id === id) || null;\n  }\n\n  async cancel(id: string): Promise<boolean> {\n    const state = await this.readState();\n    const index = state.jobs.findIndex(job => job.id === id);\n    if (index < 0) return false;\n    const current = state.jobs[index];\n    if (current.status === 'completed' || current.status === 'failed') return false;\n    state.jobs[index] = {\n      ...current,\n      status: 'canceled',\n      updatedAt: new Date().toISOString(),\n      finishedAt: new Date().toISOString()\n    };\n    await this.writeState(state);\n    return true;\n  }\n\n  async claimNext(workerId: string): Promise<AutoFixJob | null> {\n    const state = await this.readState();\n    const index = state.jobs.findIndex(job => job.status === 'queued');\n    if (index < 0) return null;\n    const now = new Date().toISOString();\n    const claimed = {\n      ...state.jobs[index],\n      status: 'running' as AutoFixJobStatus,\n      workerId,\n      startedAt: now,\n      updatedAt: now,\n      error: undefined\n    };\n    state.jobs[index] = claimed;\n    await this.writeState(state);\n    return claimed;\n  }\n\n  async markCompleted(id: string, result: Record<string, unknown>) {\n    return this.updateFinal(id, 'completed', result);\n  }\n\n  async markFailed(id: string, error: string, result: Record<string, unknown> = {}) {\n    return this.updateFinal(id, 'failed', {\n      ...result,\n      error\n    });\n  }\n\n  private async updateFinal(id: string, status: Extract<AutoFixJobStatus, 'completed' | 'failed'>, result: Record<string, unknown>) {\n    const state = await this.readState();\n    const index = state.jobs.findIndex(job => job.id === id);\n    if (index < 0) return false;\n    const now = new Date().toISOString();\n    const current = state.jobs[index];\n    state.jobs[index] = {\n      ...current,\n      status,\n      updatedAt: now,\n      finishedAt: now,\n      error: status === 'failed' ? String(result.error || 'Job failed') : undefined,\n      result\n    };\n    await this.writeState(state);\n    return true;\n  }\n}\n", "// @ts-nocheck\nimport { execSync } from 'node:child_process';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { AgentRouter } from '../agent/router.js';\nimport { analyzeBlastRadius, isSeverityAtLeast } from '../blast-radius/index.js';\nimport type { CheckpointStore } from '../checkpoint/store.js';\nimport type { Logger } from '../utils/logger.js';\nimport type { Orchestrator } from '../orchestrator/index.js';\nimport type { Sandbox } from '../sandbox/index.js';\nimport type { SessionManager } from '../session/manager.js';\nimport { scorePatchRisk } from '../risk/score.js';\nimport type { AutoFixJob } from './store.js';\n\nfunction hasCompletionSignal(text: string): boolean {\n  const lower = text.toLowerCase();\n  const signals = [\n    'task complete',\n    'task is complete',\n    'implementation complete',\n    'all done',\n    'finished',\n    'successfully implemented',\n    'no further changes needed',\n    'ready for review'\n  ];\n  return signals.some(signal => lower.includes(signal));\n}\n\nfunction shouldRetryWithFallback(error: unknown): boolean {\n  const text = String((error as Error)?.message || '').toLowerCase();\n  return (\n    text.includes('rate limit') ||\n    text.includes('429') ||\n    text.includes('timeout') ||\n    text.includes('empty') ||\n    text.includes('temporar') ||\n    text.includes('unavailable') ||\n    text.includes('quota')\n  );\n}\n\nasync function dispatchWithFallback(\n  router: AgentRouter,\n  agent: string,\n  task: string,\n  options: Record<string, unknown>,\n  fallbackModels: string[] = [],\n  checkpoints?: CheckpointStore,\n  runId?: string\n) {\n  const tried: string[] = [];\n  const primary = String(options.model || '').trim();\n  if (primary) tried.push(primary);\n  const chain = [primary, ...fallbackModels].map(v => String(v || '').trim()).filter(Boolean);\n  if (chain.length === 0) {\n    const result = await router.dispatch(agent, task, options);\n    return { result, usedModel: primary || 'default', attempts: tried };\n  }\n\n  let lastError: Error | null = null;\n  for (let i = 0; i < chain.length; i += 1) {\n    const model = chain[i];\n    try {\n      if (checkpoints && runId) {\n        await checkpoints.append(runId, 'autofix.dispatch.model.attempt', { model, index: i + 1 });\n      }\n      const result = await router.dispatch(agent, task, {\n        ...options,\n        model\n      });\n      if (checkpoints && runId) {\n        await checkpoints.append(runId, 'autofix.dispatch.model.success', { model, index: i + 1 });\n      }\n      return { result, usedModel: model, attempts: [...tried, model] };\n    } catch (error) {\n      lastError = error as Error;\n      tried.push(model);\n      if (checkpoints && runId) {\n        await checkpoints.append(runId, 'autofix.dispatch.model.failed', {\n          model,\n          error: String((error as Error).message || error)\n        });\n      }\n      const canRetry = i < chain.length - 1 && shouldRetryWithFallback(error);\n      if (!canRetry) break;\n    }\n  }\n\n  throw lastError || new Error(`Dispatch failed for ${agent}`);\n}\n\nfunction runValidationCommands(commands: string[] = [], cwd = process.cwd()) {\n  if (!commands.length) return { passed: true, failedCommand: '', output: '' };\n  for (const cmd of commands) {\n    try {\n      execSync(cmd, {\n        cwd,\n        stdio: 'pipe',\n        encoding: 'utf8',\n        maxBuffer: 2 * 1024 * 1024\n      });\n    } catch (error) {\n      return {\n        passed: false,\n        failedCommand: cmd,\n        output: String((error as { stderr?: string })?.stderr || (error as Error).message || '')\n      };\n    }\n  }\n  return { passed: true, failedCommand: '', output: '' };\n}\n\nasync function runLspAutoFixCycle(\n  projectDir: string,\n  maxAttempts: number,\n  options: {\n    router: AgentRouter;\n    orchestrator: Orchestrator;\n    sessionId: string;\n    gateway?: string;\n    model?: string;\n    fallbackModels: string[];\n    checkpoints?: CheckpointStore;\n    runId?: string;\n    logger: Logger;\n  }\n): Promise<{ fixed: boolean; attempts: number; remainingDiagnostics: number }> {\n  const { typeCheckProject } = await import('../lsp/index.js');\n  const cappedAttempts = Math.max(1, maxAttempts);\n  let diagnostics = await typeCheckProject(projectDir, []);\n  if (diagnostics.length === 0) return { fixed: true, attempts: 0, remainingDiagnostics: 0 };\n\n  let attempts = 0;\n  while (attempts < cappedAttempts && diagnostics.length > 0) {\n    attempts += 1;\n    const summary = diagnostics\n      .slice(0, 30)\n      .map(d => `${d.file}:${d.line}:${d.column} [${d.category}] TS${d.code} ${d.message}`)\n      .join('\\n');\n    const task = [\n      'Fix TypeScript diagnostics with minimal safe edits.',\n      'Diagnostics:',\n      summary\n    ].join('\\n');\n\n    const dispatched = await dispatchWithFallback(\n      options.router,\n      'crew-fixer',\n      task,\n      {\n        project: projectDir,\n        sessionId: options.sessionId,\n        gateway: options.gateway,\n        model: options.model\n      },\n      options.fallbackModels,\n      options.checkpoints,\n      options.runId\n    );\n    const response = String(dispatched.result?.result || '');\n    const edits = await options.orchestrator.parseAndApplyToSandbox(response);\n    options.logger.info(`Autofix LSP pass ${attempts}: ${diagnostics.length} diagnostics, ${edits.length} edit(s).`);\n    await options.checkpoints?.append(String(options.runId || ''), 'autofix.lsp.attempt', {\n      attempt: attempts,\n      diagnostics: diagnostics.length,\n      edits: edits.length\n    });\n    diagnostics = await typeCheckProject(projectDir, []);\n  }\n\n  return {\n    fixed: diagnostics.length === 0,\n    attempts,\n    remainingDiagnostics: diagnostics.length\n  };\n}\n\nexport interface AutoFixRunDependencies {\n  router: AgentRouter;\n  orchestrator: Orchestrator;\n  sandbox: Sandbox;\n  session: SessionManager;\n  logger: Logger;\n  checkpoints: CheckpointStore;\n}\n\nexport interface AutoFixRunResult {\n  runId: string;\n  iterations: number;\n  editedFiles: string[];\n  applied: boolean;\n  proposalPath?: string;\n  blastRisk?: 'low' | 'medium' | 'high';\n  patchRiskLevel?: 'low' | 'medium' | 'high';\n  patchRiskScore?: number;\n  validationPassed?: boolean;\n  validationFailedCommand?: string;\n}\n\nexport async function runAutoFixJob(job: AutoFixJob, deps: AutoFixRunDependencies): Promise<AutoFixRunResult> {\n  const { router, orchestrator, sandbox, session, logger, checkpoints } = deps;\n  const runId = `autofix-${job.id}`;\n  const activeBranch = sandbox.getActiveBranch();\n  if (sandbox.hasChanges(activeBranch)) {\n    throw new Error('Sandbox already has pending changes; apply or rollback before running background autofix jobs.');\n  }\n\n  await checkpoints.beginRun({ runId, mode: 'auto', task: job.task });\n  let iteration = 0;\n  let currentTask = job.task;\n\n  try {\n    while (iteration < job.config.maxIterations) {\n      iteration += 1;\n      const route = await orchestrator.route(currentTask);\n      const agent = route.agent || 'crew-fixer';\n      logger.info(`[AutoFix ${job.id}] Iteration ${iteration}/${job.config.maxIterations} via ${agent}`);\n\n      const dispatched = await dispatchWithFallback(\n        router,\n        agent,\n        currentTask,\n        {\n          project: job.projectDir,\n          sessionId: await session.getSessionId(),\n          gateway: job.config.gateway,\n          model: job.config.model\n        },\n        job.config.fallbackModels,\n        checkpoints,\n        runId\n      );\n\n      const responseText = String(dispatched.result?.result || '');\n      const edits = await orchestrator.parseAndApplyToSandbox(responseText);\n      await checkpoints.append(runId, 'autofix.iteration', {\n        iteration,\n        agent,\n        edits: edits.length,\n        success: Boolean(dispatched.result?.success)\n      });\n      await session.appendHistory({\n        type: 'autofix_iteration',\n        jobId: job.id,\n        iteration,\n        agent,\n        success: Boolean(dispatched.result?.success),\n        edits: edits.length\n      });\n\n      if (edits.length > 0 && job.config.lspAutoFix) {\n        await runLspAutoFixCycle(job.projectDir, job.config.lspAutoFixMaxAttempts, {\n          router,\n          orchestrator,\n          sessionId: await session.getSessionId(),\n          gateway: job.config.gateway,\n          model: job.config.model,\n          fallbackModels: job.config.fallbackModels,\n          checkpoints,\n          runId,\n          logger\n        });\n      }\n\n      if (hasCompletionSignal(responseText)) {\n        break;\n      }\n\n      if (iteration < job.config.maxIterations) {\n        currentTask = edits.length > 0\n          ? 'Previous edits are staged. Validate and apply remaining fixes. Respond with \"Task complete\" only when done.'\n          : `Continue fixing this task with minimal safe edits: ${job.task}`;\n      }\n    }\n\n    const changedBranch = sandbox.getActiveBranch();\n    const editedFiles = sandbox.getPendingPaths(changedBranch);\n    if (editedFiles.length === 0) {\n      await checkpoints.finish(runId, 'completed');\n      return {\n        runId,\n        iterations: iteration,\n        editedFiles: [],\n        applied: false\n      };\n    }\n\n    const validation = runValidationCommands(job.config.validateCommands, job.projectDir);\n    const blast = await analyzeBlastRadius(job.projectDir, { changedFiles: editedFiles });\n    const patchRisk = scorePatchRisk({\n      blastRadius: blast,\n      changedFiles: editedFiles.length,\n      validationPassed: validation.passed\n    });\n\n    await checkpoints.append(runId, 'autofix.safety', {\n      changedFiles: editedFiles.length,\n      blastRisk: blast.risk,\n      blastSummary: blast.summary,\n      validationPassed: validation.passed,\n      failedCommand: validation.failedCommand || undefined,\n      patchRiskLevel: patchRisk.riskLevel,\n      patchRiskScore: patchRisk.riskScore\n    });\n\n    const threshold = job.config.blastRadiusThreshold;\n    const allowByBlast = !isSeverityAtLeast(blast.risk, threshold);\n    const shouldApply = job.config.autoApplyPolicy === 'force'\n      ? true\n      : job.config.autoApplyPolicy === 'safe'\n        ? validation.passed && allowByBlast\n        : false;\n\n    if (shouldApply) {\n      await sandbox.apply(changedBranch);\n      await checkpoints.append(runId, 'autofix.applied', {\n        policy: job.config.autoApplyPolicy,\n        files: editedFiles\n      });\n      await checkpoints.finish(runId, 'completed');\n      return {\n        runId,\n        iterations: iteration,\n        editedFiles,\n        applied: true,\n        blastRisk: blast.risk,\n        patchRiskLevel: patchRisk.riskLevel,\n        patchRiskScore: patchRisk.riskScore,\n        validationPassed: validation.passed,\n        validationFailedCommand: validation.failedCommand || undefined\n      };\n    }\n\n    const proposalDir = join(job.projectDir, '.crew', 'autofix', 'proposals');\n    await mkdir(proposalDir, { recursive: true });\n    const proposalPath = join(proposalDir, `${job.id}.diff`);\n    await writeFile(proposalPath, sandbox.preview(changedBranch), 'utf8');\n    await sandbox.rollback(changedBranch);\n\n    await checkpoints.append(runId, 'autofix.proposal', {\n      policy: job.config.autoApplyPolicy,\n      proposalPath,\n      blockedByValidation: !validation.passed,\n      blockedByBlastRadius: !allowByBlast\n    });\n    await checkpoints.finish(runId, 'completed');\n\n    return {\n      runId,\n      iterations: iteration,\n      editedFiles,\n      applied: false,\n      proposalPath,\n      blastRisk: blast.risk,\n      patchRiskLevel: patchRisk.riskLevel,\n      patchRiskScore: patchRisk.riskScore,\n      validationPassed: validation.passed,\n      validationFailedCommand: validation.failedCommand || undefined\n    };\n  } catch (error) {\n    try {\n      await sandbox.rollback(sandbox.getActiveBranch());\n    } catch {\n      // Best-effort cleanup for failed background jobs.\n    }\n    await checkpoints.append(runId, 'autofix.error', {\n      error: String((error as Error).message || error),\n      iteration\n    });\n    await checkpoints.finish(runId, 'failed');\n    throw error;\n  }\n}\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;AAEA,SAAS,KAAK,MAAc,MAAsB;AAChD,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO,QAAU,IAAI,IAAI,IAAI;AAC/B;AALA,IAAM,UAOA,OAUO,QAoHA;AArIb;AAAA;AAAA;AAAA,IAAM,WAAW,QAAQ,QAAQ,QAAQ,KAAK,KAAK,CAAC,QAAQ,IAAI;AAOhE,IAAM,QAAQ;AAAA,MACZ,MAAM,CAAC,SAAiB,KAAK,MAAM,IAAI;AAAA,MACvC,KAAK,CAAC,SAAiB,KAAK,MAAM,IAAI;AAAA,MACtC,QAAQ,CAAC,SAAiB,KAAK,MAAM,IAAI;AAAA,MACzC,OAAO,CAAC,SAAiB,KAAK,MAAM,IAAI;AAAA,MACxC,MAAM,CAAC,SAAiB,KAAK,MAAM,IAAI;AAAA,MACvC,MAAM,CAAC,SAAiB,KAAK,MAAM,IAAI;AAAA,MACvC,MAAM,CAAC,SAAiB,KAAK,KAAK,IAAI;AAAA,IACxC;AAEO,IAAM,SAAN,MAAa;AAAA,MAIlB,YAAY,UAA+C,CAAC,GAAG;AAC7D,aAAK,QAAQ,QAAQ,SAAS;AAC9B,aAAK,SAAS,QAAQ,UAAU;AAAA,MAClC;AAAA,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AK;AAAA,EACf;AAEA,QAAM,QAAQ,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AACjD;AAEA,IAAI,YAAY,QAAQ,UAAU,QAAQ,KAAK,CAAC,CAAC,IAAI;AACnD,OAAK,QAAQ,KAAK,MAAM,CAAC,CAAC;AAC5B;",
  "names": ["resolve", "dirname", "resolve", "configPath", "program", "readFile", "writeFile", "mkdir", "join", "dirname", "path", "result", "execFile", "promisify", "result", "execFileAsync", "readFile", "access", "constants", "join", "homedir", "path", "refreshToken", "TOKEN_URL", "CLIENT_ID", "isTokenExpired", "TOKEN_EXPIRY_BUFFER_MS", "_cachedTokens", "_cacheTimestamp", "CACHE_TTL_MS", "_refreshInFlight", "readFile", "access", "constants", "join", "homedir", "fileExists", "path", "refreshToken", "TOKEN_URL", "result", "isTokenExpired", "TOKEN_EXPIRY_BUFFER_MS", "_cachedTokens", "_cacheTimestamp", "CACHE_TTL_MS", "_refreshInFlight", "randomUUID", "result", "errMsg", "cost", "cachedTokens", "response", "data", "content", "cacheReadTokens", "cacheCreateTokens", "inputTokens", "usage", "readFile", "existsSync", "join", "path", "resolve", "result", "existsSync", "join", "resolve", "randomUUID", "rm", "execSync", "randomUUID", "execSync", "mkdir", "readFile", "readdir", "writeFile", "dirname", "join", "resolve", "result", "existsSync", "statSync", "relative", "updated", "diagnostics", "lines", "execFileSync", "spawn", "DockerSandbox", "runAgenticWorker", "randomUUID", "READ_ONLY_TOOLS", "result", "EDIT_TOOLS", "READ_TOOLS", "EDIT_TOOLS", "extractTarget", "result", "isEditTool", "result", "errMsg", "access", "mkdir", "readFile", "writeFile", "constants", "join", "nowIso", "path", "result", "isReadTool", "isVerificationTool", "result", "path", "readFile", "existsSync", "join", "homedir", "join", "readdir", "readFile", "stat", "extname", "join", "relative", "resolve", "p", "toolCalls", "parts", "usage", "msg", "writeFileSync", "res", "CLAUDE_OAUTH_BETA_HEADER", "homedir", "buildCollectionIndex", "searchCollection", "result", "extractVerificationCommands", "mkdir", "writeFile", "readFile", "resolve", "join", "relative", "execSync", "existsSync", "path", "result", "fs", "createHash", "existsSync", "mkdirSync", "readFileSync", "join", "resolve", "path", "nowIso", "chunks", "stat", "randomUUID", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "join", "resolve", "path", "mkdir", "join", "resolve", "path", "init_run_state", "readFile", "readdir", "stat", "join", "extname", "relative", "getProjectContext", "readFile", "resolve", "result", "PERSONA_PROFILES", "path", "logger", "execSync", "readFile", "writeFile", "mkdir", "existsSync", "createHash", "relative", "join", "toHashedVector", "cosineSimilarity", "result", "randomUUID", "appendFile", "mkdir", "readFile", "resolve", "join", "init_run_state", "result", "path", "getProjectContext", "execSync", "parseDirectFileCommands", "readdirSync", "statSync", "readFileSync", "existsSync", "autoLoadRelevantFiles", "shouldUseRag", "resolve", "result", "readFile", "RouteDecision", "result", "parseDirectFileCommands", "parseWriteSyntax", "executeDirectCommands", "appendFile", "mkdir", "readFile", "stat", "writeFile", "dirname", "join", "randomUUID", "tokenize", "promisify", "execFile", "promisify", "relative", "resolve", "execFileAsync", "chalk", "homedir", "readFileSync", "gatewayReachable", "readFile", "readdir", "existsSync", "join", "tokenize", "result", "chalk", "logger", "result", "getInquirer", "chalk", "result", "resolve", "isObject", "path", "fs", "exec", "promisify", "execAsync", "runPtyCommand", "result", "getCompletions", "typeCheckProject", "readFileSync", "existsSync", "join", "readFile", "existsSync", "join", "readFile", "access", "constants", "join", "homedir", "userInfo", "execFile", "promisify", "execFileAsync", "path", "createHash", "mkdir", "readFile", "writeFile", "existsSync", "join", "nowIso", "result", "existsSync", "homedir", "access", "constants", "join", "dirname", "homedir", "execFile", "promisify", "mkdir", "readFile", "writeFile", "existsSync", "join", "homedir", "path", "execFileAsync", "promisify", "execFile", "configPath", "join", "homedir", "access", "constants", "dirname", "resolve", "estimateTokens", "spawn", "randomUUID", "fs", "path", "mkdir", "readFile", "writeFile", "existsSync", "join", "resolve", "nowIso", "clip", "appendFile", "mkdir", "readFile", "readdir", "existsSync", "join", "resolve", "estimateTokens", "nowIso", "clip", "path", "result", "mkdir", "readFile", "writeFile", "existsSync", "homedir", "join", "resolve", "randomUUID", "nowIso", "spawn", "appendFile", "mkdir", "readFile", "writeFile", "existsSync", "join", "resolve", "clip", "logger", "result", "resolve", "spawn", "text", "path", "fs", "randomUUID", "readFile", "join", "readFile", "logger", "resolve", "path", "readFile", "watcher", "relative", "join", "readdir", "access", "mkdir", "writeFile", "constants", "dirname", "join", "resolve", "execFile", "promisify", "execFileAsync", "path", "runGit", "spawn", "access", "readFile", "writeFile", "constants", "tmpdir", "join", "execFile", "promisify", "WebSocket", "execFileAsync", "exists", "path", "resolve", "resolve", "WebSocket", "join", "writeFile", "readFile", "access", "copyFile", "mkdir", "readFile", "readdir", "writeFile", "constants", "join", "exists", "path", "execFile", "promisify", "readFile", "writeFile", "join", "tmpdir", "execFileAsync", "commandExists", "platform", "join", "tmpdir", "commandExists", "execFileAsync", "readFile", "path", "join", "execFileAsync", "writeFile", "readFile", "extname", "resolve", "clip", "path", "extname", "resolve", "readFile", "estimateTokens", "execFile", "promisify", "execFileAsync", "clip", "runGit", "mkdir", "readFile", "writeFile", "existsSync", "join", "resolve", "join", "path", "mkdir", "existsSync", "writeFile", "readFile", "homedir", "join", "readFileSync", "randomUUID", "result", "buildCollectionIndex", "searchCollection", "readFile", "join", "path", "join", "homedir", "readFileSync", "randomUUID", "path", "result", "reply", "randomUUID", "path", "autoLoadRelevantFiles", "shouldUseRag", "existsSync", "agents", "join", "resolve", "spawn", "mkdir", "writeFile", "join", "resolve", "randomUUID", "existsSync", "readFileSync", "appendFile", "mkdir", "readFile", "readdir", "writeFile", "join", "homedir", "chalk", "resolve", "join", "tokenize", "similarity", "path", "mkdir", "readFile", "readdir", "writeFile", "existsSync", "join", "BANNER", "existsSync", "readFileSync", "chalk", "join", "homedir", "readdir", "readFile", "resolve", "normalizeStandaloneEngine", "logger", "randomUUID", "BANNER", "mkdir", "writeFile", "displayStatus", "appendFile", "readdirSync", "statSync", "dirname", "findModelInfo", "MODEL_CATALOG", "formatModelTable", "from", "recallSearch", "buildRecallContext", "result", "listPersonas", "getPersona", "buildSummonPrompt", "filterToolsForPersona", "runAgenticWorker", "execSync", "typeCheckProject", "getCompletions", "responseText", "input", "policy", "existsSync", "readFileSync", "join", "homedir", "text", "mkdir", "readFile", "writeFile", "existsSync", "join", "isObject", "configPath", "path", "execFile", "promisify", "execFileAsync", "existsSync", "readFile", "join", "path", "mkdir", "readFile", "writeFile", "existsSync", "join", "randomUUID", "join", "existsSync", "readFile", "mkdir", "writeFile", "randomUUID", "result", "execSync", "mkdir", "writeFile", "join", "result", "execSync", "typeCheckProject", "logger", "join", "mkdir", "writeFile", "randomUUID", "mkdir", "readFile", "writeFile", "dirname", "join", "execSync", "result", "execSync", "existsSync", "join", "homedir", "normalizeStandaloneEngine", "shouldRetryWithFallback", "path", "readFile", "runValidationCommands", "runLspAutoFixCycle", "typeCheckProject", "dispatchWithFallback", "chalk", "mkdir", "dirname", "writeFile", "logger", "config", "CodebaseIndex", "buildCollectionIndex", "searchCollection", "randomUUID", "hasCompletionSignal", "resolve", "displayStatus", "buildRepositoryGraph", "buildRepositoryMap", "buildRepositoryGraphDot", "buildRepositoryGraphHtml", "getCompletions", "runPtyCommand", "runShellCopilot", "args", "WorkerPool", "runCheckCommand", "spawn", "analyzeBlastRadius", "AgentKeeper", "readFileSync"]
}
