{
  "version": 3,
  "sources": ["../src/hooks/index.ts", "../src/tools/worktree.ts", "../src/tools/gemini/definitions/base-declarations.ts", "../src/lsp/index.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/auth/oauth-keychain.ts", "../src/auth/openai-oauth.ts", "../src/auth/gemini-oauth.ts", "../src/auth/cch.ts", "../src/executor/scratchpad.ts", "../src/collections/index.ts", "../src/executor/agentic-executor.ts", "../src/engine-api.ts", "../src/sandbox/index.ts"],
  "sourcesContent": ["/**\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", "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", "/**\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 * 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", "/**\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 * Engine API \u2014 public exports for use by gateway-bridge.\n * This is the entry point that lib/engines/crew-cli.mjs imports.\n * Provides direct function access to the agentic executor without spawning subprocesses.\n */\nexport { runAgenticWorker } from './executor/agentic-executor.js';\nexport { Sandbox } from './sandbox/index.js';\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"],
  "mappings": ";;;;;;;;;;;;;;;;;AAuBA,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AAkCrB,SAAS,cAAc,UAAkB,QAAQ,IAAI,GAAW;AAC9D,SAAO,QAAQ,IAAI,mBAAmB,KAAK,SAAS,SAAS,YAAY;AAC3E;AAEA,eAAsB,eAAe,SAAuC;AAC1E,QAAMA,QAAO,cAAc,OAAO;AAClC,MAAI,gBAAgB,eAAeA,MAAM,QAAO;AAEhD,MAAI,CAAC,WAAWA,KAAI,GAAG;AACrB,mBAAe,EAAE,OAAO,CAAC,EAAE;AAC3B,iBAAaA;AACb,WAAO;AAAA,EACT;AAEA,MAAI;AACF,UAAM,MAAM,MAAM,SAASA,OAAM,MAAM;AACvC,mBAAe,KAAK,MAAM,GAAG;AAC7B,iBAAaA;AACb,WAAO;AAAA,EACT,QAAQ;AACN,mBAAe,EAAE,OAAO,CAAC,EAAE;AAC3B,iBAAaA;AACb,WAAO;AAAA,EACT;AACF;AAQA,SAAS,YAAY,UAAkB,MAA+B;AACpE,MAAI;AACF,WAAO,IAAI,OAAO,KAAK,OAAO,EAAE,KAAK,QAAQ;AAAA,EAC/C,QAAQ;AACN,WAAO;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a,KAAK,MAAM,cAAuB;AACxD,WAAO,OAAO,KAAK,KAAK,MAAM,SAAS,UAAU,KAAK,CAAC,CAAC,EAAE,SAAS;AAAA,EACrE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAiB,UAAkB,aAAa,KAAK,MAAM,cAAkC;AAC3F,UAAM,SAAS,KAAK,MAAM,SAAS,UAAU;AAC7C,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,SAAS,OAAO,QAAQ;AAC9B,QAAI,OAAQ,QAAO,OAAO;AAC1B,WAAO;AAAA,EACT;AACF;",
  "names": ["path", "resolve", "existsSync", "join", "existsSync", "resolve", "configPath", "execSync", "randomUUID", "execSync", "readFile", "dirname", "join", "resolve", "existsSync", "mkdir", "writeFile", "relative", "updated", "diagnostics", "lines", "spawn", "DockerSandbox", "runAgenticWorker", "randomUUID", "READ_ONLY_TOOLS", "EDIT_TOOLS", "READ_TOOLS", "EDIT_TOOLS", "extractTarget", "isEditTool", "errMsg", "mkdir", "readFile", "writeFile", "join", "path", "isReadTool", "isVerificationTool", "path", "readFile", "existsSync", "join", "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", "isTokenExpired", "TOKEN_EXPIRY_BUFFER_MS", "_cachedTokens", "_cacheTimestamp", "CACHE_TTL_MS", "_refreshInFlight", "join", "readdir", "readFile", "stat", "join", "resolve", "p", "toolCalls", "parts", "usage", "msg", "res", "homedir", "buildCollectionIndex", "searchCollection", "extractVerificationCommands", "result", "readFile", "writeFile", "mkdir", "access", "constants", "join", "dirname", "path"]
}
